Add files to hook up yaffs direct to u-boot
[yaffs2.git] / yaffs_guts.c
1 /*
2  * YAFFS: Yet Another Flash File System. A NAND-flash specific file system.
3  *
4  * Copyright (C) 2002-2011 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 "yaffs_guts.h"
18 #include "yaffs_getblockinfo.h"
19 #include "yaffs_tagscompat.h"
20 #include "yaffs_nand.h"
21 #include "yaffs_yaffs1.h"
22 #include "yaffs_yaffs2.h"
23 #include "yaffs_bitmap.h"
24 #include "yaffs_verify.h"
25 #include "yaffs_nand.h"
26 #include "yaffs_packedtags2.h"
27 #include "yaffs_nameval.h"
28 #include "yaffs_allocator.h"
29 #include "yaffs_attribs.h"
30 #include "yaffs_summary.h"
31
32 /* Note YAFFS_GC_GOOD_ENOUGH must be <= YAFFS_GC_PASSIVE_THRESHOLD */
33 #define YAFFS_GC_GOOD_ENOUGH 2
34 #define YAFFS_GC_PASSIVE_THRESHOLD 4
35
36 #include "yaffs_ecc.h"
37
38 /* Forward declarations */
39
40 static int yaffs_wr_data_obj(struct yaffs_obj *in, int inode_chunk,
41                              const u8 *buffer, int n_bytes, int use_reserve);
42
43
44
45 /* Function to calculate chunk and offset */
46
47 void yaffs_addr_to_chunk(struct yaffs_dev *dev, loff_t addr,
48                                 int *chunk_out, u32 *offset_out)
49 {
50         int chunk;
51         u32 offset;
52
53         chunk = (u32) (addr >> dev->chunk_shift);
54
55         if (dev->chunk_div == 1) {
56                 /* easy power of 2 case */
57                 offset = (u32) (addr & dev->chunk_mask);
58         } else {
59                 /* Non power-of-2 case */
60
61                 loff_t chunk_base;
62
63                 chunk /= dev->chunk_div;
64
65                 chunk_base = ((loff_t) chunk) * dev->data_bytes_per_chunk;
66                 offset = (u32) (addr - chunk_base);
67         }
68
69         *chunk_out = chunk;
70         *offset_out = offset;
71 }
72
73 /* Function to return the number of shifts for a power of 2 greater than or
74  * equal to the given number
75  * Note we don't try to cater for all possible numbers and this does not have to
76  * be hellishly efficient.
77  */
78
79 static inline u32 calc_shifts_ceiling(u32 x)
80 {
81         int extra_bits;
82         int shifts;
83
84         shifts = extra_bits = 0;
85
86         while (x > 1) {
87                 if (x & 1)
88                         extra_bits++;
89                 x >>= 1;
90                 shifts++;
91         }
92
93         if (extra_bits)
94                 shifts++;
95
96         return shifts;
97 }
98
99 /* Function to return the number of shifts to get a 1 in bit 0
100  */
101
102 static inline u32 calc_shifts(u32 x)
103 {
104         u32 shifts;
105
106         shifts = 0;
107
108         if (!x)
109                 return 0;
110
111         while (!(x & 1)) {
112                 x >>= 1;
113                 shifts++;
114         }
115
116         return shifts;
117 }
118
119 /*
120  * Temporary buffer manipulations.
121  */
122
123 static int yaffs_init_tmp_buffers(struct yaffs_dev *dev)
124 {
125         int i;
126         u8 *buf = (u8 *) 1;
127
128         memset(dev->temp_buffer, 0, sizeof(dev->temp_buffer));
129
130         for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
131                 dev->temp_buffer[i].in_use = 0;
132                 buf = kmalloc(dev->param.total_bytes_per_chunk, GFP_NOFS);
133                 dev->temp_buffer[i].buffer = buf;
134         }
135
136         return buf ? YAFFS_OK : YAFFS_FAIL;
137 }
138
139 u8 *yaffs_get_temp_buffer(struct yaffs_dev * dev)
140 {
141         int i;
142
143         dev->temp_in_use++;
144         if (dev->temp_in_use > dev->max_temp)
145                 dev->max_temp = dev->temp_in_use;
146
147         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
148                 if (dev->temp_buffer[i].in_use == 0) {
149                         dev->temp_buffer[i].in_use = 1;
150                         return dev->temp_buffer[i].buffer;
151                 }
152         }
153
154         yaffs_trace(YAFFS_TRACE_BUFFERS, "Out of temp buffers");
155         /*
156          * If we got here then we have to allocate an unmanaged one
157          * This is not good.
158          */
159
160         dev->unmanaged_buffer_allocs++;
161         return kmalloc(dev->data_bytes_per_chunk, GFP_NOFS);
162
163 }
164
165 void yaffs_release_temp_buffer(struct yaffs_dev *dev, u8 *buffer)
166 {
167         int i;
168
169         dev->temp_in_use--;
170
171         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
172                 if (dev->temp_buffer[i].buffer == buffer) {
173                         dev->temp_buffer[i].in_use = 0;
174                         return;
175                 }
176         }
177
178         if (buffer) {
179                 /* assume it is an unmanaged one. */
180                 yaffs_trace(YAFFS_TRACE_BUFFERS, "Releasing unmanaged temp buffer");
181                 kfree(buffer);
182                 dev->unmanaged_buffer_deallocs++;
183         }
184
185 }
186
187 /*
188  * Determine if we have a managed buffer.
189  */
190 int yaffs_is_managed_tmp_buffer(struct yaffs_dev *dev, const u8 *buffer)
191 {
192         int i;
193
194         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
195                 if (dev->temp_buffer[i].buffer == buffer)
196                         return 1;
197         }
198
199         for (i = 0; i < dev->param.n_caches; i++) {
200                 if (dev->cache[i].data == buffer)
201                         return 1;
202         }
203
204         if (buffer == dev->checkpt_buffer)
205                 return 1;
206
207         yaffs_trace(YAFFS_TRACE_ALWAYS,
208           "yaffs: unmaged buffer detected.");
209         return 0;
210 }
211
212 /*
213  * Functions for robustisizing TODO
214  *
215  */
216
217 static void yaffs_handle_chunk_wr_ok(struct yaffs_dev *dev, int nand_chunk,
218                                      const u8 *data,
219                                      const struct yaffs_ext_tags *tags)
220 {
221         dev = dev;
222         nand_chunk = nand_chunk;
223         data = data;
224         tags = tags;
225 }
226
227 static void yaffs_handle_chunk_update(struct yaffs_dev *dev, int nand_chunk,
228                                       const struct yaffs_ext_tags *tags)
229 {
230         dev = dev;
231         nand_chunk = nand_chunk;
232         tags = tags;
233 }
234
235 void yaffs_handle_chunk_error(struct yaffs_dev *dev,
236                               struct yaffs_block_info *bi)
237 {
238         if (!bi->gc_prioritise) {
239                 bi->gc_prioritise = 1;
240                 dev->has_pending_prioritised_gc = 1;
241                 bi->chunk_error_strikes++;
242
243                 if (bi->chunk_error_strikes > 3) {
244                         bi->needs_retiring = 1; /* Too many stikes, so retire */
245                         yaffs_trace(YAFFS_TRACE_ALWAYS,
246                                 "yaffs: Block struck out");
247
248                 }
249         }
250 }
251
252 static void yaffs_handle_chunk_wr_error(struct yaffs_dev *dev, int nand_chunk,
253                                         int erased_ok)
254 {
255         int flash_block = nand_chunk / dev->param.chunks_per_block;
256         struct yaffs_block_info *bi = yaffs_get_block_info(dev, flash_block);
257
258         yaffs_handle_chunk_error(dev, bi);
259
260         if (erased_ok) {
261                 /* Was an actual write failure,
262                  * so mark the block for retirement.*/
263                 bi->needs_retiring = 1;
264                 yaffs_trace(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
265                   "**>> Block %d needs retiring", flash_block);
266         }
267
268         /* Delete the chunk */
269         yaffs_chunk_del(dev, nand_chunk, 1, __LINE__);
270         yaffs_skip_rest_of_block(dev);
271 }
272
273 /*
274  * Verification code
275  */
276
277 /*
278  *  Simple hash function. Needs to have a reasonable spread
279  */
280
281 static inline int yaffs_hash_fn(int n)
282 {
283         if(n < 0)
284                 n = -n;
285         return n % YAFFS_NOBJECT_BUCKETS;
286 }
287
288 /*
289  * Access functions to useful fake objects.
290  * Note that root might have a presence in NAND if permissions are set.
291  */
292
293 struct yaffs_obj *yaffs_root(struct yaffs_dev *dev)
294 {
295         return dev->root_dir;
296 }
297
298 struct yaffs_obj *yaffs_lost_n_found(struct yaffs_dev *dev)
299 {
300         return dev->lost_n_found;
301 }
302
303 /*
304  *  Erased NAND checking functions
305  */
306
307 int yaffs_check_ff(u8 *buffer, int n_bytes)
308 {
309         /* Horrible, slow implementation */
310         while (n_bytes--) {
311                 if (*buffer != 0xff)
312                         return 0;
313                 buffer++;
314         }
315         return 1;
316 }
317
318 static int yaffs_check_chunk_erased(struct yaffs_dev *dev, int nand_chunk)
319 {
320         int retval = YAFFS_OK;
321         u8 *data = yaffs_get_temp_buffer(dev);
322         struct yaffs_ext_tags tags;
323         int result;
324
325         result = yaffs_rd_chunk_tags_nand(dev, nand_chunk, data, &tags);
326
327         if (tags.ecc_result > YAFFS_ECC_RESULT_NO_ERROR)
328                 retval = YAFFS_FAIL;
329
330         if (!yaffs_check_ff(data, dev->data_bytes_per_chunk) ||
331                 tags.chunk_used) {
332                 yaffs_trace(YAFFS_TRACE_NANDACCESS,
333                         "Chunk %d not erased", nand_chunk);
334                 retval = YAFFS_FAIL;
335         }
336
337         yaffs_release_temp_buffer(dev, data);
338
339         return retval;
340
341 }
342
343 static int yaffs_verify_chunk_written(struct yaffs_dev *dev,
344                                       int nand_chunk,
345                                       const u8 *data,
346                                       struct yaffs_ext_tags *tags)
347 {
348         int retval = YAFFS_OK;
349         struct yaffs_ext_tags temp_tags;
350         u8 *buffer = yaffs_get_temp_buffer(dev);
351         int result;
352
353         result = yaffs_rd_chunk_tags_nand(dev, nand_chunk, buffer, &temp_tags);
354         if (memcmp(buffer, data, dev->data_bytes_per_chunk) ||
355             temp_tags.obj_id != tags->obj_id ||
356             temp_tags.chunk_id != tags->chunk_id ||
357             temp_tags.n_bytes != tags->n_bytes)
358                 retval = YAFFS_FAIL;
359
360         yaffs_release_temp_buffer(dev, buffer);
361
362         return retval;
363 }
364
365
366 int yaffs_check_alloc_available(struct yaffs_dev *dev, int n_chunks)
367 {
368         int reserved_chunks;
369         int reserved_blocks = dev->param.n_reserved_blocks;
370         int checkpt_blocks;
371
372         checkpt_blocks = yaffs_calc_checkpt_blocks_required(dev);
373
374         reserved_chunks =
375             (reserved_blocks + checkpt_blocks) * dev->param.chunks_per_block;
376
377         return (dev->n_free_chunks > (reserved_chunks + n_chunks));
378 }
379
380 static int yaffs_find_alloc_block(struct yaffs_dev *dev)
381 {
382         int i;
383         struct yaffs_block_info *bi;
384
385         if (dev->n_erased_blocks < 1) {
386                 /* Hoosterman we've got a problem.
387                  * Can't get space to gc
388                  */
389                 yaffs_trace(YAFFS_TRACE_ERROR,
390                   "yaffs tragedy: no more erased blocks");
391
392                 return -1;
393         }
394
395         /* Find an empty block. */
396
397         for (i = dev->internal_start_block; i <= dev->internal_end_block; i++) {
398                 dev->alloc_block_finder++;
399                 if (dev->alloc_block_finder < dev->internal_start_block
400                     || dev->alloc_block_finder > dev->internal_end_block) {
401                         dev->alloc_block_finder = dev->internal_start_block;
402                 }
403
404                 bi = yaffs_get_block_info(dev, dev->alloc_block_finder);
405
406                 if (bi->block_state == YAFFS_BLOCK_STATE_EMPTY) {
407                         bi->block_state = YAFFS_BLOCK_STATE_ALLOCATING;
408                         dev->seq_number++;
409                         bi->seq_number = dev->seq_number;
410                         dev->n_erased_blocks--;
411                         yaffs_trace(YAFFS_TRACE_ALLOCATE,
412                           "Allocated block %d, seq  %d, %d left" ,
413                            dev->alloc_block_finder, dev->seq_number,
414                            dev->n_erased_blocks);
415                         return dev->alloc_block_finder;
416                 }
417         }
418
419         yaffs_trace(YAFFS_TRACE_ALWAYS,
420                 "yaffs tragedy: no more erased blocks, but there should have been %d",
421                 dev->n_erased_blocks);
422
423         return -1;
424 }
425
426 static int yaffs_alloc_chunk(struct yaffs_dev *dev, int use_reserver,
427                              struct yaffs_block_info **block_ptr)
428 {
429         int ret_val;
430         struct yaffs_block_info *bi;
431
432         if (dev->alloc_block < 0) {
433                 /* Get next block to allocate off */
434                 dev->alloc_block = yaffs_find_alloc_block(dev);
435                 dev->alloc_page = 0;
436         }
437
438         if (!use_reserver && !yaffs_check_alloc_available(dev, 1)) {
439                 /* No space unless we're allowed to use the reserve. */
440                 return -1;
441         }
442
443         if (dev->n_erased_blocks < dev->param.n_reserved_blocks
444             && dev->alloc_page == 0)
445                 yaffs_trace(YAFFS_TRACE_ALLOCATE, "Allocating reserve");
446
447         /* Next page please.... */
448         if (dev->alloc_block >= 0) {
449                 bi = yaffs_get_block_info(dev, dev->alloc_block);
450
451                 ret_val = (dev->alloc_block * dev->param.chunks_per_block) +
452                     dev->alloc_page;
453                 bi->pages_in_use++;
454                 yaffs_set_chunk_bit(dev, dev->alloc_block, dev->alloc_page);
455
456                 dev->alloc_page++;
457
458                 dev->n_free_chunks--;
459
460                 /* If the block is full set the state to full */
461                 if (dev->alloc_page >= dev->param.chunks_per_block) {
462                         bi->block_state = YAFFS_BLOCK_STATE_FULL;
463                         dev->alloc_block = -1;
464                 }
465
466                 if (block_ptr)
467                         *block_ptr = bi;
468
469                 return ret_val;
470         }
471
472         yaffs_trace(YAFFS_TRACE_ERROR,
473                 "!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!");
474
475         return -1;
476 }
477
478 static int yaffs_get_erased_chunks(struct yaffs_dev *dev)
479 {
480         int n;
481
482         n = dev->n_erased_blocks * dev->param.chunks_per_block;
483
484         if (dev->alloc_block > 0)
485                 n += (dev->param.chunks_per_block - dev->alloc_page);
486
487         return n;
488
489 }
490
491 /*
492  * yaffs_skip_rest_of_block() skips over the rest of the allocation block
493  * if we don't want to write to it.
494  */
495 void yaffs_skip_rest_of_block(struct yaffs_dev *dev)
496 {
497         struct yaffs_block_info *bi;
498
499         if (dev->alloc_block > 0) {
500                 bi = yaffs_get_block_info(dev, dev->alloc_block);
501                 if (bi->block_state == YAFFS_BLOCK_STATE_ALLOCATING) {
502                         bi->block_state = YAFFS_BLOCK_STATE_FULL;
503                         dev->alloc_block = -1;
504                 }
505         }
506 }
507
508 static int yaffs_write_new_chunk(struct yaffs_dev *dev,
509                                  const u8 *data,
510                                  struct yaffs_ext_tags *tags, int use_reserver)
511 {
512         int attempts = 0;
513         int write_ok = 0;
514         int chunk;
515
516         yaffs2_checkpt_invalidate(dev);
517
518         do {
519                 struct yaffs_block_info *bi = 0;
520                 int erased_ok = 0;
521
522                 chunk = yaffs_alloc_chunk(dev, use_reserver, &bi);
523                 if (chunk < 0) {
524                         /* no space */
525                         break;
526                 }
527
528                 /* First check this chunk is erased, if it needs
529                  * checking.  The checking policy (unless forced
530                  * always on) is as follows:
531                  *
532                  * Check the first page we try to write in a block.
533                  * If the check passes then we don't need to check any
534                  * more.        If the check fails, we check again...
535                  * If the block has been erased, we don't need to check.
536                  *
537                  * However, if the block has been prioritised for gc,
538                  * then we think there might be something odd about
539                  * this block and stop using it.
540                  *
541                  * Rationale: We should only ever see chunks that have
542                  * not been erased if there was a partially written
543                  * chunk due to power loss.  This checking policy should
544                  * catch that case with very few checks and thus save a
545                  * lot of checks that are most likely not needed.
546                  *
547                  * Mods to the above
548                  * If an erase check fails or the write fails we skip the
549                  * rest of the block.
550                  */
551
552                 /* let's give it a try */
553                 attempts++;
554
555                 if (dev->param.always_check_erased)
556                         bi->skip_erased_check = 0;
557
558                 if (!bi->skip_erased_check) {
559                         erased_ok = yaffs_check_chunk_erased(dev, chunk);
560                         if (erased_ok != YAFFS_OK) {
561                                 yaffs_trace(YAFFS_TRACE_ERROR,
562                                   "**>> yaffs chunk %d was not erased",
563                                   chunk);
564
565                                 /* If not erased, delete this one,
566                                  * skip rest of block and
567                                  * try another chunk */
568                                 yaffs_chunk_del(dev, chunk, 1, __LINE__);
569                                 yaffs_skip_rest_of_block(dev);
570                                 continue;
571                         }
572                 }
573
574                 write_ok = yaffs_wr_chunk_tags_nand(dev, chunk, data, tags);
575
576                 if (!bi->skip_erased_check)
577                         write_ok =
578                             yaffs_verify_chunk_written(dev, chunk, data, tags);
579
580                 if (write_ok != YAFFS_OK) {
581                         /* Clean up aborted write, skip to next block and
582                          * try another chunk */
583                         yaffs_handle_chunk_wr_error(dev, chunk, erased_ok);
584                         continue;
585                 }
586
587                 bi->skip_erased_check = 1;
588
589                 /* Copy the data into the robustification buffer */
590                 yaffs_handle_chunk_wr_ok(dev, chunk, data, tags);
591
592         } while (write_ok != YAFFS_OK &&
593                  (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
594
595         if (!write_ok)
596                 chunk = -1;
597
598         if (attempts > 1) {
599                 yaffs_trace(YAFFS_TRACE_ERROR,
600                         "**>> yaffs write required %d attempts",
601                         attempts);
602                 dev->n_retried_writes += (attempts - 1);
603         }
604
605         return chunk;
606 }
607
608 /*
609  * Block retiring for handling a broken block.
610  */
611
612 static void yaffs_retire_block(struct yaffs_dev *dev, int flash_block)
613 {
614         struct yaffs_block_info *bi = yaffs_get_block_info(dev, flash_block);
615
616         yaffs2_checkpt_invalidate(dev);
617
618         yaffs2_clear_oldest_dirty_seq(dev, bi);
619
620         if (yaffs_mark_bad(dev, flash_block) != YAFFS_OK) {
621                 if (yaffs_erase_block(dev, flash_block) != YAFFS_OK) {
622                         yaffs_trace(YAFFS_TRACE_ALWAYS,
623                                 "yaffs: Failed to mark bad and erase block %d",
624                                 flash_block);
625                 } else {
626                         struct yaffs_ext_tags tags;
627                         int chunk_id =
628                             flash_block * dev->param.chunks_per_block;
629
630                         u8 *buffer = yaffs_get_temp_buffer(dev);
631
632                         memset(buffer, 0xff, dev->data_bytes_per_chunk);
633                         memset(&tags, 0, sizeof(tags));
634                         tags.seq_number = YAFFS_SEQUENCE_BAD_BLOCK;
635                         if (dev->param.write_chunk_tags_fn(dev, chunk_id -
636                                                            dev->chunk_offset,
637                                                            buffer,
638                                                            &tags) != YAFFS_OK)
639                                 yaffs_trace(YAFFS_TRACE_ALWAYS,
640                                         "yaffs: Failed to write bad block marker to block %d",
641                                         flash_block);
642
643                         yaffs_release_temp_buffer(dev, buffer);
644                 }
645         }
646
647         bi->block_state = YAFFS_BLOCK_STATE_DEAD;
648         bi->gc_prioritise = 0;
649         bi->needs_retiring = 0;
650
651         dev->n_retired_blocks++;
652 }
653
654 /*---------------- Name handling functions ------------*/
655
656 static u16 yaffs_calc_name_sum(const YCHAR *name)
657 {
658         u16 sum = 0;
659         u16 i = 1;
660
661         if (!name)
662                 return 0;
663
664         while ((*name) && i < (YAFFS_MAX_NAME_LENGTH / 2)) {
665
666                 /* 0x1f mask is case insensitive */
667                 sum += ((*name) & 0x1f) * i;
668                 i++;
669                 name++;
670         }
671         return sum;
672 }
673
674 void yaffs_set_obj_name(struct yaffs_obj *obj, const YCHAR * name)
675 {
676         memset(obj->short_name, 0, sizeof(obj->short_name));
677         if (name &&
678                 strnlen(name, YAFFS_SHORT_NAME_LENGTH + 1) <=
679                 YAFFS_SHORT_NAME_LENGTH)
680                 strcpy(obj->short_name, name);
681         else
682                 obj->short_name[0] = _Y('\0');
683         obj->sum = yaffs_calc_name_sum(name);
684 }
685
686 void yaffs_set_obj_name_from_oh(struct yaffs_obj *obj,
687                                 const struct yaffs_obj_hdr *oh)
688 {
689 #ifdef CONFIG_YAFFS_AUTO_UNICODE
690         YCHAR tmp_name[YAFFS_MAX_NAME_LENGTH + 1];
691         memset(tmp_name, 0, sizeof(tmp_name));
692         yaffs_load_name_from_oh(obj->my_dev, tmp_name, oh->name,
693                                 YAFFS_MAX_NAME_LENGTH + 1);
694         yaffs_set_obj_name(obj, tmp_name);
695 #else
696         yaffs_set_obj_name(obj, oh->name);
697 #endif
698 }
699
700 loff_t yaffs_max_file_size(struct yaffs_dev *dev)
701 {
702         return ((loff_t) YAFFS_MAX_CHUNK_ID) * dev->data_bytes_per_chunk;
703 }
704
705 /*-------------------- TNODES -------------------
706
707  * List of spare tnodes
708  * The list is hooked together using the first pointer
709  * in the tnode.
710  */
711
712 struct yaffs_tnode *yaffs_get_tnode(struct yaffs_dev *dev)
713 {
714         struct yaffs_tnode *tn = yaffs_alloc_raw_tnode(dev);
715
716         if (tn) {
717                 memset(tn, 0, dev->tnode_size);
718                 dev->n_tnodes++;
719         }
720
721         dev->checkpoint_blocks_required = 0;    /* force recalculation */
722
723         return tn;
724 }
725
726 /* FreeTnode frees up a tnode and puts it back on the free list */
727 static void yaffs_free_tnode(struct yaffs_dev *dev, struct yaffs_tnode *tn)
728 {
729         yaffs_free_raw_tnode(dev, tn);
730         dev->n_tnodes--;
731         dev->checkpoint_blocks_required = 0;    /* force recalculation */
732 }
733
734 static void yaffs_deinit_tnodes_and_objs(struct yaffs_dev *dev)
735 {
736         yaffs_deinit_raw_tnodes_and_objs(dev);
737         dev->n_obj = 0;
738         dev->n_tnodes = 0;
739 }
740
741 void yaffs_load_tnode_0(struct yaffs_dev *dev, struct yaffs_tnode *tn,
742                         unsigned pos, unsigned val)
743 {
744         u32 *map = (u32 *) tn;
745         u32 bit_in_map;
746         u32 bit_in_word;
747         u32 word_in_map;
748         u32 mask;
749
750         pos &= YAFFS_TNODES_LEVEL0_MASK;
751         val >>= dev->chunk_grp_bits;
752
753         bit_in_map = pos * dev->tnode_width;
754         word_in_map = bit_in_map / 32;
755         bit_in_word = bit_in_map & (32 - 1);
756
757         mask = dev->tnode_mask << bit_in_word;
758
759         map[word_in_map] &= ~mask;
760         map[word_in_map] |= (mask & (val << bit_in_word));
761
762         if (dev->tnode_width > (32 - bit_in_word)) {
763                 bit_in_word = (32 - bit_in_word);
764                 word_in_map++;
765                 mask =
766                     dev->tnode_mask >> bit_in_word;
767                 map[word_in_map] &= ~mask;
768                 map[word_in_map] |= (mask & (val >> bit_in_word));
769         }
770 }
771
772 u32 yaffs_get_group_base(struct yaffs_dev *dev, struct yaffs_tnode *tn,
773                          unsigned pos)
774 {
775         u32 *map = (u32 *) tn;
776         u32 bit_in_map;
777         u32 bit_in_word;
778         u32 word_in_map;
779         u32 val;
780
781         pos &= YAFFS_TNODES_LEVEL0_MASK;
782
783         bit_in_map = pos * dev->tnode_width;
784         word_in_map = bit_in_map / 32;
785         bit_in_word = bit_in_map & (32 - 1);
786
787         val = map[word_in_map] >> bit_in_word;
788
789         if (dev->tnode_width > (32 - bit_in_word)) {
790                 bit_in_word = (32 - bit_in_word);
791                 word_in_map++;
792                 val |= (map[word_in_map] << bit_in_word);
793         }
794
795         val &= dev->tnode_mask;
796         val <<= dev->chunk_grp_bits;
797
798         return val;
799 }
800
801 /* ------------------- End of individual tnode manipulation -----------------*/
802
803 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
804  * The look up tree is represented by the top tnode and the number of top_level
805  * in the tree. 0 means only the level 0 tnode is in the tree.
806  */
807
808 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
809 struct yaffs_tnode *yaffs_find_tnode_0(struct yaffs_dev *dev,
810                                        struct yaffs_file_var *file_struct,
811                                        u32 chunk_id)
812 {
813         struct yaffs_tnode *tn = file_struct->top;
814         u32 i;
815         int required_depth;
816         int level = file_struct->top_level;
817
818         dev = dev;
819
820         /* Check sane level and chunk Id */
821         if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
822                 return NULL;
823
824         if (chunk_id > YAFFS_MAX_CHUNK_ID)
825                 return NULL;
826
827         /* First check we're tall enough (ie enough top_level) */
828
829         i = chunk_id >> YAFFS_TNODES_LEVEL0_BITS;
830         required_depth = 0;
831         while (i) {
832                 i >>= YAFFS_TNODES_INTERNAL_BITS;
833                 required_depth++;
834         }
835
836         if (required_depth > file_struct->top_level)
837                 return NULL;    /* Not tall enough, so we can't find it */
838
839         /* Traverse down to level 0 */
840         while (level > 0 && tn) {
841                 tn = tn->internal[(chunk_id >>
842                                    (YAFFS_TNODES_LEVEL0_BITS +
843                                     (level - 1) *
844                                     YAFFS_TNODES_INTERNAL_BITS)) &
845                                   YAFFS_TNODES_INTERNAL_MASK];
846                 level--;
847         }
848
849         return tn;
850 }
851
852 /* add_find_tnode_0 finds the level 0 tnode if it exists,
853  * otherwise first expands the tree.
854  * This happens in two steps:
855  *  1. If the tree isn't tall enough, then make it taller.
856  *  2. Scan down the tree towards the level 0 tnode adding tnodes if required.
857  *
858  * Used when modifying the tree.
859  *
860  *  If the tn argument is NULL, then a fresh tnode will be added otherwise the
861  *  specified tn will be plugged into the ttree.
862  */
863
864 struct yaffs_tnode *yaffs_add_find_tnode_0(struct yaffs_dev *dev,
865                                            struct yaffs_file_var *file_struct,
866                                            u32 chunk_id,
867                                            struct yaffs_tnode *passed_tn)
868 {
869         int required_depth;
870         int i;
871         int l;
872         struct yaffs_tnode *tn;
873         u32 x;
874
875         /* Check sane level and page Id */
876         if (file_struct->top_level < 0 ||
877             file_struct->top_level > YAFFS_TNODES_MAX_LEVEL)
878                 return NULL;
879
880         if (chunk_id > YAFFS_MAX_CHUNK_ID)
881                 return NULL;
882
883         /* First check we're tall enough (ie enough top_level) */
884
885         x = chunk_id >> YAFFS_TNODES_LEVEL0_BITS;
886         required_depth = 0;
887         while (x) {
888                 x >>= YAFFS_TNODES_INTERNAL_BITS;
889                 required_depth++;
890         }
891
892         if (required_depth > file_struct->top_level) {
893                 /* Not tall enough, gotta make the tree taller */
894                 for (i = file_struct->top_level; i < required_depth; i++) {
895
896                         tn = yaffs_get_tnode(dev);
897
898                         if (tn) {
899                                 tn->internal[0] = file_struct->top;
900                                 file_struct->top = tn;
901                                 file_struct->top_level++;
902                         } else {
903                                 yaffs_trace(YAFFS_TRACE_ERROR,
904                                         "yaffs: no more tnodes");
905                                 return NULL;
906                         }
907                 }
908         }
909
910         /* Traverse down to level 0, adding anything we need */
911
912         l = file_struct->top_level;
913         tn = file_struct->top;
914
915         if (l > 0) {
916                 while (l > 0 && tn) {
917                         x = (chunk_id >>
918                              (YAFFS_TNODES_LEVEL0_BITS +
919                               (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
920                             YAFFS_TNODES_INTERNAL_MASK;
921
922                         if ((l > 1) && !tn->internal[x]) {
923                                 /* Add missing non-level-zero tnode */
924                                 tn->internal[x] = yaffs_get_tnode(dev);
925                                 if (!tn->internal[x])
926                                         return NULL;
927                         } else if (l == 1) {
928                                 /* Looking from level 1 at level 0 */
929                                 if (passed_tn) {
930                                         /* If we already have one, release it */
931                                         if (tn->internal[x])
932                                                 yaffs_free_tnode(dev,
933                                                         tn->internal[x]);
934                                         tn->internal[x] = passed_tn;
935
936                                 } else if (!tn->internal[x]) {
937                                         /* Don't have one, none passed in */
938                                         tn->internal[x] = yaffs_get_tnode(dev);
939                                         if (!tn->internal[x])
940                                                 return NULL;
941                                 }
942                         }
943
944                         tn = tn->internal[x];
945                         l--;
946                 }
947         } else {
948                 /* top is level 0 */
949                 if (passed_tn) {
950                         memcpy(tn, passed_tn,
951                                (dev->tnode_width * YAFFS_NTNODES_LEVEL0) / 8);
952                         yaffs_free_tnode(dev, passed_tn);
953                 }
954         }
955
956         return tn;
957 }
958
959 static int yaffs_tags_match(const struct yaffs_ext_tags *tags, int obj_id,
960                             int chunk_obj)
961 {
962         return (tags->chunk_id == chunk_obj &&
963                 tags->obj_id == obj_id &&
964                 !tags->is_deleted) ? 1 : 0;
965
966 }
967
968 static int yaffs_find_chunk_in_group(struct yaffs_dev *dev, int the_chunk,
969                                         struct yaffs_ext_tags *tags, int obj_id,
970                                         int inode_chunk)
971 {
972         int j;
973
974         for (j = 0; the_chunk && j < dev->chunk_grp_size; j++) {
975                 if (yaffs_check_chunk_bit
976                     (dev, the_chunk / dev->param.chunks_per_block,
977                      the_chunk % dev->param.chunks_per_block)) {
978
979                         if (dev->chunk_grp_size == 1)
980                                 return the_chunk;
981                         else {
982                                 yaffs_rd_chunk_tags_nand(dev, the_chunk, NULL,
983                                                          tags);
984                                 if (yaffs_tags_match(tags,
985                                                         obj_id, inode_chunk)) {
986                                         /* found it; */
987                                         return the_chunk;
988                                 }
989                         }
990                 }
991                 the_chunk++;
992         }
993         return -1;
994 }
995
996 static int yaffs_find_chunk_in_file(struct yaffs_obj *in, int inode_chunk,
997                                     struct yaffs_ext_tags *tags)
998 {
999         /*Get the Tnode, then get the level 0 offset chunk offset */
1000         struct yaffs_tnode *tn;
1001         int the_chunk = -1;
1002         struct yaffs_ext_tags local_tags;
1003         int ret_val = -1;
1004         struct yaffs_dev *dev = in->my_dev;
1005
1006         if (!tags) {
1007                 /* Passed a NULL, so use our own tags space */
1008                 tags = &local_tags;
1009         }
1010
1011         tn = yaffs_find_tnode_0(dev, &in->variant.file_variant, inode_chunk);
1012
1013         if (!tn)
1014                 return ret_val;
1015
1016         the_chunk = yaffs_get_group_base(dev, tn, inode_chunk);
1017
1018         ret_val = yaffs_find_chunk_in_group(dev, the_chunk, tags, in->obj_id,
1019                                               inode_chunk);
1020         return ret_val;
1021 }
1022
1023 static int yaffs_find_del_file_chunk(struct yaffs_obj *in, int inode_chunk,
1024                                      struct yaffs_ext_tags *tags)
1025 {
1026         /* Get the Tnode, then get the level 0 offset chunk offset */
1027         struct yaffs_tnode *tn;
1028         int the_chunk = -1;
1029         struct yaffs_ext_tags local_tags;
1030         struct yaffs_dev *dev = in->my_dev;
1031         int ret_val = -1;
1032
1033         if (!tags) {
1034                 /* Passed a NULL, so use our own tags space */
1035                 tags = &local_tags;
1036         }
1037
1038         tn = yaffs_find_tnode_0(dev, &in->variant.file_variant, inode_chunk);
1039
1040         if (!tn)
1041                 return ret_val;
1042
1043         the_chunk = yaffs_get_group_base(dev, tn, inode_chunk);
1044
1045         ret_val = yaffs_find_chunk_in_group(dev, the_chunk, tags, in->obj_id,
1046                                               inode_chunk);
1047
1048         /* Delete the entry in the filestructure (if found) */
1049         if (ret_val != -1)
1050                 yaffs_load_tnode_0(dev, tn, inode_chunk, 0);
1051
1052         return ret_val;
1053 }
1054
1055 int yaffs_put_chunk_in_file(struct yaffs_obj *in, int inode_chunk,
1056                             int nand_chunk, int in_scan)
1057 {
1058         /* NB in_scan is zero unless scanning.
1059          * For forward scanning, in_scan is > 0;
1060          * for backward scanning in_scan is < 0
1061          *
1062          * nand_chunk = 0 is a dummy insert to make sure the tnodes are there.
1063          */
1064
1065         struct yaffs_tnode *tn;
1066         struct yaffs_dev *dev = in->my_dev;
1067         int existing_cunk;
1068         struct yaffs_ext_tags existing_tags;
1069         struct yaffs_ext_tags new_tags;
1070         unsigned existing_serial, new_serial;
1071
1072         if (in->variant_type != YAFFS_OBJECT_TYPE_FILE) {
1073                 /* Just ignore an attempt at putting a chunk into a non-file
1074                  * during scanning.
1075                  * If it is not during Scanning then something went wrong!
1076                  */
1077                 if (!in_scan) {
1078                         yaffs_trace(YAFFS_TRACE_ERROR,
1079                                 "yaffs tragedy:attempt to put data chunk into a non-file"
1080                                 );
1081                         BUG();
1082                 }
1083
1084                 yaffs_chunk_del(dev, nand_chunk, 1, __LINE__);
1085                 return YAFFS_OK;
1086         }
1087
1088         tn = yaffs_add_find_tnode_0(dev,
1089                                     &in->variant.file_variant,
1090                                     inode_chunk, NULL);
1091         if (!tn)
1092                 return YAFFS_FAIL;
1093
1094         if (!nand_chunk)
1095                 /* Dummy insert, bail now */
1096                 return YAFFS_OK;
1097
1098         existing_cunk = yaffs_get_group_base(dev, tn, inode_chunk);
1099
1100         if (in_scan != 0) {
1101                 /* If we're scanning then we need to test for duplicates
1102                  * NB This does not need to be efficient since it should only
1103                  * happen when the power fails during a write, then only one
1104                  * chunk should ever be affected.
1105                  *
1106                  * Correction for YAFFS2: This could happen quite a lot and we
1107                  * need to think about efficiency! TODO
1108                  * Update: For backward scanning we don't need to re-read tags
1109                  * so this is quite cheap.
1110                  */
1111
1112                 if (existing_cunk > 0) {
1113                         /* NB Right now existing chunk will not be real
1114                          * chunk_id if the chunk group size > 1
1115                          * thus we have to do a FindChunkInFile to get the
1116                          * real chunk id.
1117                          *
1118                          * We have a duplicate now we need to decide which
1119                          * one to use:
1120                          *
1121                          * Backwards scanning YAFFS2: The old one is what
1122                          * we use, dump the new one.
1123                          * YAFFS1: Get both sets of tags and compare serial
1124                          * numbers.
1125                          */
1126
1127                         if (in_scan > 0) {
1128                                 /* Only do this for forward scanning */
1129                                 yaffs_rd_chunk_tags_nand(dev,
1130                                                          nand_chunk,
1131                                                          NULL, &new_tags);
1132
1133                                 /* Do a proper find */
1134                                 existing_cunk =
1135                                     yaffs_find_chunk_in_file(in, inode_chunk,
1136                                                              &existing_tags);
1137                         }
1138
1139                         if (existing_cunk <= 0) {
1140                                 /*Hoosterman - how did this happen? */
1141
1142                                 yaffs_trace(YAFFS_TRACE_ERROR,
1143                                         "yaffs tragedy: existing chunk < 0 in scan"
1144                                         );
1145
1146                         }
1147
1148                         /* NB The deleted flags should be false, otherwise
1149                          * the chunks will not be loaded during a scan
1150                          */
1151
1152                         if (in_scan > 0) {
1153                                 new_serial = new_tags.serial_number;
1154                                 existing_serial = existing_tags.serial_number;
1155                         }
1156
1157                         if ((in_scan > 0) &&
1158                             (existing_cunk <= 0 ||
1159                              ((existing_serial + 1) & 3) == new_serial)) {
1160                                 /* Forward scanning.
1161                                  * Use new
1162                                  * Delete the old one and drop through to
1163                                  * update the tnode
1164                                  */
1165                                 yaffs_chunk_del(dev, existing_cunk, 1,
1166                                                 __LINE__);
1167                         } else {
1168                                 /* Backward scanning or we want to use the
1169                                  * existing one
1170                                  * Delete the new one and return early so that
1171                                  * the tnode isn't changed
1172                                  */
1173                                 yaffs_chunk_del(dev, nand_chunk, 1, __LINE__);
1174                                 return YAFFS_OK;
1175                         }
1176                 }
1177
1178         }
1179
1180         if (existing_cunk == 0)
1181                 in->n_data_chunks++;
1182
1183         yaffs_load_tnode_0(dev, tn, inode_chunk, nand_chunk);
1184
1185         return YAFFS_OK;
1186 }
1187
1188 static void yaffs_soft_del_chunk(struct yaffs_dev *dev, int chunk)
1189 {
1190         struct yaffs_block_info *the_block;
1191         unsigned block_no;
1192
1193         yaffs_trace(YAFFS_TRACE_DELETION, "soft delete chunk %d", chunk);
1194
1195         block_no = chunk / dev->param.chunks_per_block;
1196         the_block = yaffs_get_block_info(dev, block_no);
1197         if (the_block) {
1198                 the_block->soft_del_pages++;
1199                 dev->n_free_chunks++;
1200                 yaffs2_update_oldest_dirty_seq(dev, block_no, the_block);
1201         }
1202 }
1203
1204 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all
1205  * the chunks in the file.
1206  * All soft deleting does is increment the block's softdelete count and pulls
1207  * the chunk out of the tnode.
1208  * Thus, essentially this is the same as DeleteWorker except that the chunks
1209  * are soft deleted.
1210  */
1211
1212 static int yaffs_soft_del_worker(struct yaffs_obj *in, struct yaffs_tnode *tn,
1213                                  u32 level, int chunk_offset)
1214 {
1215         int i;
1216         int the_chunk;
1217         int all_done = 1;
1218         struct yaffs_dev *dev = in->my_dev;
1219
1220         if (!tn)
1221                 return 1;
1222
1223         if (level > 0) {
1224                 for (i = YAFFS_NTNODES_INTERNAL - 1;
1225                         all_done && i >= 0;
1226                         i--) {
1227                         if (tn->internal[i]) {
1228                                 all_done =
1229                                     yaffs_soft_del_worker(in,
1230                                         tn->internal[i],
1231                                         level - 1,
1232                                         (chunk_offset <<
1233                                         YAFFS_TNODES_INTERNAL_BITS)
1234                                         + i);
1235                                 if (all_done) {
1236                                         yaffs_free_tnode(dev,
1237                                                 tn->internal[i]);
1238                                         tn->internal[i] = NULL;
1239                                 } else {
1240                                         /* Can this happen? */
1241                                 }
1242                         }
1243                 }
1244                 return (all_done) ? 1 : 0;
1245         }
1246
1247         /* level 0 */
1248          for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1249                 the_chunk = yaffs_get_group_base(dev, tn, i);
1250                 if (the_chunk) {
1251                         yaffs_soft_del_chunk(dev, the_chunk);
1252                         yaffs_load_tnode_0(dev, tn, i, 0);
1253                 }
1254         }
1255         return 1;
1256 }
1257
1258 static void yaffs_remove_obj_from_dir(struct yaffs_obj *obj)
1259 {
1260         struct yaffs_dev *dev = obj->my_dev;
1261         struct yaffs_obj *parent;
1262
1263         yaffs_verify_obj_in_dir(obj);
1264         parent = obj->parent;
1265
1266         yaffs_verify_dir(parent);
1267
1268         if (dev && dev->param.remove_obj_fn)
1269                 dev->param.remove_obj_fn(obj);
1270
1271         list_del_init(&obj->siblings);
1272         obj->parent = NULL;
1273
1274         yaffs_verify_dir(parent);
1275 }
1276
1277 void yaffs_add_obj_to_dir(struct yaffs_obj *directory, struct yaffs_obj *obj)
1278 {
1279         if (!directory) {
1280                 yaffs_trace(YAFFS_TRACE_ALWAYS,
1281                         "tragedy: Trying to add an object to a null pointer directory"
1282                         );
1283                 BUG();
1284                 return;
1285         }
1286         if (directory->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY) {
1287                 yaffs_trace(YAFFS_TRACE_ALWAYS,
1288                         "tragedy: Trying to add an object to a non-directory"
1289                         );
1290                 BUG();
1291         }
1292
1293         if (obj->siblings.prev == NULL) {
1294                 /* Not initialised */
1295                 BUG();
1296         }
1297
1298         yaffs_verify_dir(directory);
1299
1300         yaffs_remove_obj_from_dir(obj);
1301
1302         /* Now add it */
1303         list_add(&obj->siblings, &directory->variant.dir_variant.children);
1304         obj->parent = directory;
1305
1306         if (directory == obj->my_dev->unlinked_dir
1307             || directory == obj->my_dev->del_dir) {
1308                 obj->unlinked = 1;
1309                 obj->my_dev->n_unlinked_files++;
1310                 obj->rename_allowed = 0;
1311         }
1312
1313         yaffs_verify_dir(directory);
1314         yaffs_verify_obj_in_dir(obj);
1315 }
1316
1317 static int yaffs_change_obj_name(struct yaffs_obj *obj,
1318                                  struct yaffs_obj *new_dir,
1319                                  const YCHAR *new_name, int force, int shadows)
1320 {
1321         int unlink_op;
1322         int del_op;
1323         struct yaffs_obj *existing_target;
1324
1325         if (new_dir == NULL)
1326                 new_dir = obj->parent;  /* use the old directory */
1327
1328         if (new_dir->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY) {
1329                 yaffs_trace(YAFFS_TRACE_ALWAYS,
1330                         "tragedy: yaffs_change_obj_name: new_dir is not a directory"
1331                         );
1332                 BUG();
1333         }
1334
1335         unlink_op = (new_dir == obj->my_dev->unlinked_dir);
1336         del_op = (new_dir == obj->my_dev->del_dir);
1337
1338         existing_target = yaffs_find_by_name(new_dir, new_name);
1339
1340         /* If the object is a file going into the unlinked directory,
1341          *   then it is OK to just stuff it in since duplicate names are OK.
1342          *   else only proceed if the new name does not exist and we're putting
1343          *   it into a directory.
1344          */
1345         if (!(unlink_op || del_op || force ||
1346               shadows > 0 || !existing_target) ||
1347               new_dir->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY)
1348                 return YAFFS_FAIL;
1349
1350         yaffs_set_obj_name(obj, new_name);
1351         obj->dirty = 1;
1352         yaffs_add_obj_to_dir(new_dir, obj);
1353
1354         if (unlink_op)
1355                 obj->unlinked = 1;
1356
1357         /* If it is a deletion then we mark it as a shrink for gc  */
1358         if (yaffs_update_oh(obj, new_name, 0, del_op, shadows, NULL) >= 0)
1359                 return YAFFS_OK;
1360
1361         return YAFFS_FAIL;
1362 }
1363
1364 /*------------------------ Short Operations Cache ------------------------------
1365  *   In many situations where there is no high level buffering  a lot of
1366  *   reads might be short sequential reads, and a lot of writes may be short
1367  *   sequential writes. eg. scanning/writing a jpeg file.
1368  *   In these cases, a short read/write cache can provide a huge perfomance
1369  *   benefit with dumb-as-a-rock code.
1370  *   In Linux, the page cache provides read buffering and the short op cache
1371  *   provides write buffering.
1372  *
1373  *   There are a small number (~10) of cache chunks per device so that we don't
1374  *   need a very intelligent search.
1375  */
1376
1377 static int yaffs_obj_cache_dirty(struct yaffs_obj *obj)
1378 {
1379         struct yaffs_dev *dev = obj->my_dev;
1380         int i;
1381         struct yaffs_cache *cache;
1382         int n_caches = obj->my_dev->param.n_caches;
1383
1384         for (i = 0; i < n_caches; i++) {
1385                 cache = &dev->cache[i];
1386                 if (cache->object == obj && cache->dirty)
1387                         return 1;
1388         }
1389
1390         return 0;
1391 }
1392
1393 static void yaffs_flush_file_cache(struct yaffs_obj *obj)
1394 {
1395         struct yaffs_dev *dev = obj->my_dev;
1396         int lowest = -99;       /* Stop compiler whining. */
1397         int i;
1398         struct yaffs_cache *cache;
1399         int chunk_written = 0;
1400         int n_caches = obj->my_dev->param.n_caches;
1401
1402         if (n_caches < 1)
1403                 return;
1404         do {
1405                 cache = NULL;
1406
1407                 /* Find the lowest dirty chunk for this object */
1408                 for (i = 0; i < n_caches; i++) {
1409                         if (dev->cache[i].object == obj &&
1410                             dev->cache[i].dirty) {
1411                                 if (!cache ||
1412                                     dev->cache[i].chunk_id < lowest) {
1413                                         cache = &dev->cache[i];
1414                                         lowest = cache->chunk_id;
1415                                 }
1416                         }
1417                 }
1418
1419                 if (cache && !cache->locked) {
1420                         /* Write it out and free it up */
1421                         chunk_written =
1422                             yaffs_wr_data_obj(cache->object,
1423                                               cache->chunk_id,
1424                                               cache->data,
1425                                               cache->n_bytes, 1);
1426                         cache->dirty = 0;
1427                         cache->object = NULL;
1428                 }
1429         } while (cache && chunk_written > 0);
1430
1431         if (cache)
1432                 /* Hoosterman, disk full while writing cache out. */
1433                 yaffs_trace(YAFFS_TRACE_ERROR,
1434                         "yaffs tragedy: no space during cache write");
1435 }
1436
1437 /*yaffs_flush_whole_cache(dev)
1438  *
1439  *
1440  */
1441
1442 void yaffs_flush_whole_cache(struct yaffs_dev *dev)
1443 {
1444         struct yaffs_obj *obj;
1445         int n_caches = dev->param.n_caches;
1446         int i;
1447
1448         /* Find a dirty object in the cache and flush it...
1449          * until there are no further dirty objects.
1450          */
1451         do {
1452                 obj = NULL;
1453                 for (i = 0; i < n_caches && !obj; i++) {
1454                         if (dev->cache[i].object && dev->cache[i].dirty)
1455                                 obj = dev->cache[i].object;
1456                 }
1457                 if (obj)
1458                         yaffs_flush_file_cache(obj);
1459         } while (obj);
1460
1461 }
1462
1463 /* Grab us a cache chunk for use.
1464  * First look for an empty one.
1465  * Then look for the least recently used non-dirty one.
1466  * Then look for the least recently used dirty one...., flush and look again.
1467  */
1468 static struct yaffs_cache *yaffs_grab_chunk_worker(struct yaffs_dev *dev)
1469 {
1470         int i;
1471
1472         if (dev->param.n_caches > 0) {
1473                 for (i = 0; i < dev->param.n_caches; i++) {
1474                         if (!dev->cache[i].object)
1475                                 return &dev->cache[i];
1476                 }
1477         }
1478         return NULL;
1479 }
1480
1481 static struct yaffs_cache *yaffs_grab_chunk_cache(struct yaffs_dev *dev)
1482 {
1483         struct yaffs_cache *cache;
1484         struct yaffs_obj *the_obj;
1485         int usage;
1486         int i;
1487         int pushout;
1488
1489         if (dev->param.n_caches < 1)
1490                 return NULL;
1491
1492         /* Try find a non-dirty one... */
1493
1494         cache = yaffs_grab_chunk_worker(dev);
1495
1496         if (!cache) {
1497                 /* They were all dirty, find the LRU object and flush
1498                  * its cache, then  find again.
1499                  * NB what's here is not very accurate,
1500                  * we actually flush the object with the LRU chunk.
1501                  */
1502
1503                 /* With locking we can't assume we can use entry zero,
1504                  * Set the_obj to a valid pointer for Coverity. */
1505                 the_obj = dev->cache[0].object;
1506                 usage = -1;
1507                 cache = NULL;
1508                 pushout = -1;
1509
1510                 for (i = 0; i < dev->param.n_caches; i++) {
1511                         if (dev->cache[i].object &&
1512                             !dev->cache[i].locked &&
1513                             (dev->cache[i].last_use < usage ||
1514                             !cache)) {
1515                                 usage = dev->cache[i].last_use;
1516                                 the_obj = dev->cache[i].object;
1517                                 cache = &dev->cache[i];
1518                                 pushout = i;
1519                         }
1520                 }
1521
1522                 if (!cache || cache->dirty) {
1523                         /* Flush and try again */
1524                         yaffs_flush_file_cache(the_obj);
1525                         cache = yaffs_grab_chunk_worker(dev);
1526                 }
1527         }
1528         return cache;
1529 }
1530
1531 /* Find a cached chunk */
1532 static struct yaffs_cache *yaffs_find_chunk_cache(const struct yaffs_obj *obj,
1533                                                   int chunk_id)
1534 {
1535         struct yaffs_dev *dev = obj->my_dev;
1536         int i;
1537
1538         if (dev->param.n_caches < 1)
1539                 return NULL;
1540
1541         for (i = 0; i < dev->param.n_caches; i++) {
1542                 if (dev->cache[i].object == obj &&
1543                     dev->cache[i].chunk_id == chunk_id) {
1544                         dev->cache_hits++;
1545
1546                         return &dev->cache[i];
1547                 }
1548         }
1549         return NULL;
1550 }
1551
1552 /* Mark the chunk for the least recently used algorithym */
1553 static void yaffs_use_cache(struct yaffs_dev *dev, struct yaffs_cache *cache,
1554                             int is_write)
1555 {
1556         int i;
1557
1558         if (dev->param.n_caches < 1)
1559                 return;
1560
1561         if (dev->cache_last_use < 0 ||
1562                 dev->cache_last_use > 100000000) {
1563                 /* Reset the cache usages */
1564                 for (i = 1; i < dev->param.n_caches; i++)
1565                         dev->cache[i].last_use = 0;
1566
1567                 dev->cache_last_use = 0;
1568         }
1569         dev->cache_last_use++;
1570         cache->last_use = dev->cache_last_use;
1571
1572         if (is_write)
1573                 cache->dirty = 1;
1574 }
1575
1576 /* Invalidate a single cache page.
1577  * Do this when a whole page gets written,
1578  * ie the short cache for this page is no longer valid.
1579  */
1580 static void yaffs_invalidate_chunk_cache(struct yaffs_obj *object, int chunk_id)
1581 {
1582         struct yaffs_cache *cache;
1583
1584         if (object->my_dev->param.n_caches > 0) {
1585                 cache = yaffs_find_chunk_cache(object, chunk_id);
1586
1587                 if (cache)
1588                         cache->object = NULL;
1589         }
1590 }
1591
1592 /* Invalidate all the cache pages associated with this object
1593  * Do this whenever ther file is deleted or resized.
1594  */
1595 static void yaffs_invalidate_whole_cache(struct yaffs_obj *in)
1596 {
1597         int i;
1598         struct yaffs_dev *dev = in->my_dev;
1599
1600         if (dev->param.n_caches > 0) {
1601                 /* Invalidate it. */
1602                 for (i = 0; i < dev->param.n_caches; i++) {
1603                         if (dev->cache[i].object == in)
1604                                 dev->cache[i].object = NULL;
1605                 }
1606         }
1607 }
1608
1609 static void yaffs_unhash_obj(struct yaffs_obj *obj)
1610 {
1611         int bucket;
1612         struct yaffs_dev *dev = obj->my_dev;
1613
1614         /* If it is still linked into the bucket list, free from the list */
1615         if (!list_empty(&obj->hash_link)) {
1616                 list_del_init(&obj->hash_link);
1617                 bucket = yaffs_hash_fn(obj->obj_id);
1618                 dev->obj_bucket[bucket].count--;
1619         }
1620 }
1621
1622 /*  FreeObject frees up a Object and puts it back on the free list */
1623 static void yaffs_free_obj(struct yaffs_obj *obj)
1624 {
1625         struct yaffs_dev *dev;
1626
1627         if (!obj) {
1628                 BUG();
1629                 return;
1630         }
1631         dev = obj->my_dev;
1632         yaffs_trace(YAFFS_TRACE_OS, "FreeObject %p inode %p",
1633                 obj, obj->my_inode);
1634         if (obj->parent)
1635                 BUG();
1636         if (!list_empty(&obj->siblings))
1637                 BUG();
1638
1639         if (obj->my_inode) {
1640                 /* We're still hooked up to a cached inode.
1641                  * Don't delete now, but mark for later deletion
1642                  */
1643                 obj->defered_free = 1;
1644                 return;
1645         }
1646
1647         yaffs_unhash_obj(obj);
1648
1649         yaffs_free_raw_obj(dev, obj);
1650         dev->n_obj--;
1651         dev->checkpoint_blocks_required = 0;    /* force recalculation */
1652 }
1653
1654 void yaffs_handle_defered_free(struct yaffs_obj *obj)
1655 {
1656         if (obj->defered_free)
1657                 yaffs_free_obj(obj);
1658 }
1659
1660 static int yaffs_generic_obj_del(struct yaffs_obj *in)
1661 {
1662         /* Iinvalidate the file's data in the cache, without flushing. */
1663         yaffs_invalidate_whole_cache(in);
1664
1665         if (in->my_dev->param.is_yaffs2 && in->parent != in->my_dev->del_dir) {
1666                 /* Move to unlinked directory so we have a deletion record */
1667                 yaffs_change_obj_name(in, in->my_dev->del_dir, _Y("deleted"), 0,
1668                                       0);
1669         }
1670
1671         yaffs_remove_obj_from_dir(in);
1672         yaffs_chunk_del(in->my_dev, in->hdr_chunk, 1, __LINE__);
1673         in->hdr_chunk = 0;
1674
1675         yaffs_free_obj(in);
1676         return YAFFS_OK;
1677
1678 }
1679
1680 static void yaffs_soft_del_file(struct yaffs_obj *obj)
1681 {
1682         if (!obj->deleted ||
1683             obj->variant_type != YAFFS_OBJECT_TYPE_FILE ||
1684             obj->soft_del)
1685                 return;
1686
1687         if (obj->n_data_chunks <= 0) {
1688                 /* Empty file with no duplicate object headers,
1689                  * just delete it immediately */
1690                 yaffs_free_tnode(obj->my_dev, obj->variant.file_variant.top);
1691                 obj->variant.file_variant.top = NULL;
1692                 yaffs_trace(YAFFS_TRACE_TRACING,
1693                         "yaffs: Deleting empty file %d",
1694                         obj->obj_id);
1695                 yaffs_generic_obj_del(obj);
1696         } else {
1697                 yaffs_soft_del_worker(obj,
1698                                       obj->variant.file_variant.top,
1699                                       obj->variant.
1700                                       file_variant.top_level, 0);
1701                 obj->soft_del = 1;
1702         }
1703 }
1704
1705 /* Pruning removes any part of the file structure tree that is beyond the
1706  * bounds of the file (ie that does not point to chunks).
1707  *
1708  * A file should only get pruned when its size is reduced.
1709  *
1710  * Before pruning, the chunks must be pulled from the tree and the
1711  * level 0 tnode entries must be zeroed out.
1712  * Could also use this for file deletion, but that's probably better handled
1713  * by a special case.
1714  *
1715  * This function is recursive. For levels > 0 the function is called again on
1716  * any sub-tree. For level == 0 we just check if the sub-tree has data.
1717  * If there is no data in a subtree then it is pruned.
1718  */
1719
1720 static struct yaffs_tnode *yaffs_prune_worker(struct yaffs_dev *dev,
1721                                               struct yaffs_tnode *tn, u32 level,
1722                                               int del0)
1723 {
1724         int i;
1725         int has_data;
1726
1727         if (!tn)
1728                 return tn;
1729
1730         has_data = 0;
1731
1732         if (level > 0) {
1733                 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1734                         if (tn->internal[i]) {
1735                                 tn->internal[i] =
1736                                     yaffs_prune_worker(dev,
1737                                                 tn->internal[i],
1738                                                 level - 1,
1739                                                 (i == 0) ? del0 : 1);
1740                         }
1741
1742                         if (tn->internal[i])
1743                                 has_data++;
1744                 }
1745         } else {
1746                 int tnode_size_u32 = dev->tnode_size / sizeof(u32);
1747                 u32 *map = (u32 *) tn;
1748
1749                 for (i = 0; !has_data && i < tnode_size_u32; i++) {
1750                         if (map[i])
1751                                 has_data++;
1752                 }
1753         }
1754
1755         if (has_data == 0 && del0) {
1756                 /* Free and return NULL */
1757                 yaffs_free_tnode(dev, tn);
1758                 tn = NULL;
1759         }
1760         return tn;
1761 }
1762
1763 static int yaffs_prune_tree(struct yaffs_dev *dev,
1764                             struct yaffs_file_var *file_struct)
1765 {
1766         int i;
1767         int has_data;
1768         int done = 0;
1769         struct yaffs_tnode *tn;
1770
1771         if (file_struct->top_level < 1)
1772                 return YAFFS_OK;
1773
1774         file_struct->top =
1775            yaffs_prune_worker(dev, file_struct->top, file_struct->top_level, 0);
1776
1777         /* Now we have a tree with all the non-zero branches NULL but
1778          * the height is the same as it was.
1779          * Let's see if we can trim internal tnodes to shorten the tree.
1780          * We can do this if only the 0th element in the tnode is in use
1781          * (ie all the non-zero are NULL)
1782          */
1783
1784         while (file_struct->top_level && !done) {
1785                 tn = file_struct->top;
1786
1787                 has_data = 0;
1788                 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1789                         if (tn->internal[i])
1790                                 has_data++;
1791                 }
1792
1793                 if (!has_data) {
1794                         file_struct->top = tn->internal[0];
1795                         file_struct->top_level--;
1796                         yaffs_free_tnode(dev, tn);
1797                 } else {
1798                         done = 1;
1799                 }
1800         }
1801
1802         return YAFFS_OK;
1803 }
1804
1805 /*-------------------- End of File Structure functions.-------------------*/
1806
1807 /* alloc_empty_obj gets us a clean Object.*/
1808 static struct yaffs_obj *yaffs_alloc_empty_obj(struct yaffs_dev *dev)
1809 {
1810         struct yaffs_obj *obj = yaffs_alloc_raw_obj(dev);
1811
1812         if (!obj)
1813                 return obj;
1814
1815         dev->n_obj++;
1816
1817         /* Now sweeten it up... */
1818
1819         memset(obj, 0, sizeof(struct yaffs_obj));
1820         obj->being_created = 1;
1821
1822         obj->my_dev = dev;
1823         obj->hdr_chunk = 0;
1824         obj->variant_type = YAFFS_OBJECT_TYPE_UNKNOWN;
1825         INIT_LIST_HEAD(&(obj->hard_links));
1826         INIT_LIST_HEAD(&(obj->hash_link));
1827         INIT_LIST_HEAD(&obj->siblings);
1828
1829         /* Now make the directory sane */
1830         if (dev->root_dir) {
1831                 obj->parent = dev->root_dir;
1832                 list_add(&(obj->siblings),
1833                          &dev->root_dir->variant.dir_variant.children);
1834         }
1835
1836         /* Add it to the lost and found directory.
1837          * NB Can't put root or lost-n-found in lost-n-found so
1838          * check if lost-n-found exists first
1839          */
1840         if (dev->lost_n_found)
1841                 yaffs_add_obj_to_dir(dev->lost_n_found, obj);
1842
1843         obj->being_created = 0;
1844
1845         dev->checkpoint_blocks_required = 0;    /* force recalculation */
1846
1847         return obj;
1848 }
1849
1850 static int yaffs_find_nice_bucket(struct yaffs_dev *dev)
1851 {
1852         int i;
1853         int l = 999;
1854         int lowest = 999999;
1855
1856         /* Search for the shortest list or one that
1857          * isn't too long.
1858          */
1859
1860         for (i = 0; i < 10 && lowest > 4; i++) {
1861                 dev->bucket_finder++;
1862                 dev->bucket_finder %= YAFFS_NOBJECT_BUCKETS;
1863                 if (dev->obj_bucket[dev->bucket_finder].count < lowest) {
1864                         lowest = dev->obj_bucket[dev->bucket_finder].count;
1865                         l = dev->bucket_finder;
1866                 }
1867         }
1868
1869         return l;
1870 }
1871
1872 static int yaffs_new_obj_id(struct yaffs_dev *dev)
1873 {
1874         int bucket = yaffs_find_nice_bucket(dev);
1875         int found = 0;
1876         struct list_head *i;
1877         u32 n = (u32) bucket;
1878
1879         /* Now find an object value that has not already been taken
1880          * by scanning the list.
1881          */
1882
1883         while (!found) {
1884                 found = 1;
1885                 n += YAFFS_NOBJECT_BUCKETS;
1886                 if (1 || dev->obj_bucket[bucket].count > 0) {
1887                         list_for_each(i, &dev->obj_bucket[bucket].list) {
1888                                 /* If there is already one in the list */
1889                                 if (i && list_entry(i, struct yaffs_obj,
1890                                                     hash_link)->obj_id == n) {
1891                                         found = 0;
1892                                 }
1893                         }
1894                 }
1895         }
1896         return n;
1897 }
1898
1899 static void yaffs_hash_obj(struct yaffs_obj *in)
1900 {
1901         int bucket = yaffs_hash_fn(in->obj_id);
1902         struct yaffs_dev *dev = in->my_dev;
1903
1904         list_add(&in->hash_link, &dev->obj_bucket[bucket].list);
1905         dev->obj_bucket[bucket].count++;
1906 }
1907
1908 struct yaffs_obj *yaffs_find_by_number(struct yaffs_dev *dev, u32 number)
1909 {
1910         int bucket = yaffs_hash_fn(number);
1911         struct list_head *i;
1912         struct yaffs_obj *in;
1913
1914         list_for_each(i, &dev->obj_bucket[bucket].list) {
1915                 /* Look if it is in the list */
1916                 in = list_entry(i, struct yaffs_obj, hash_link);
1917                 if (in->obj_id == number) {
1918                         /* Don't show if it is defered free */
1919                         if (in->defered_free)
1920                                 return NULL;
1921                         return in;
1922                 }
1923         }
1924
1925         return NULL;
1926 }
1927
1928 struct yaffs_obj *yaffs_new_obj(struct yaffs_dev *dev, int number,
1929                                 enum yaffs_obj_type type)
1930 {
1931         struct yaffs_obj *the_obj = NULL;
1932         struct yaffs_tnode *tn = NULL;
1933
1934         if (number < 0)
1935                 number = yaffs_new_obj_id(dev);
1936
1937         if (type == YAFFS_OBJECT_TYPE_FILE) {
1938                 tn = yaffs_get_tnode(dev);
1939                 if (!tn)
1940                         return NULL;
1941         }
1942
1943         the_obj = yaffs_alloc_empty_obj(dev);
1944         if (!the_obj) {
1945                 if (tn)
1946                         yaffs_free_tnode(dev, tn);
1947                 return NULL;
1948         }
1949
1950         the_obj->fake = 0;
1951         the_obj->rename_allowed = 1;
1952         the_obj->unlink_allowed = 1;
1953         the_obj->obj_id = number;
1954         yaffs_hash_obj(the_obj);
1955         the_obj->variant_type = type;
1956         yaffs_load_current_time(the_obj, 1, 1);
1957
1958         switch (type) {
1959         case YAFFS_OBJECT_TYPE_FILE:
1960                 the_obj->variant.file_variant.file_size = 0;
1961                 the_obj->variant.file_variant.scanned_size = 0;
1962                 the_obj->variant.file_variant.shrink_size =
1963                                                 yaffs_max_file_size(dev);
1964                 the_obj->variant.file_variant.top_level = 0;
1965                 the_obj->variant.file_variant.top = tn;
1966                 break;
1967         case YAFFS_OBJECT_TYPE_DIRECTORY:
1968                 INIT_LIST_HEAD(&the_obj->variant.dir_variant.children);
1969                 INIT_LIST_HEAD(&the_obj->variant.dir_variant.dirty);
1970                 break;
1971         case YAFFS_OBJECT_TYPE_SYMLINK:
1972         case YAFFS_OBJECT_TYPE_HARDLINK:
1973         case YAFFS_OBJECT_TYPE_SPECIAL:
1974                 /* No action required */
1975                 break;
1976         case YAFFS_OBJECT_TYPE_UNKNOWN:
1977                 /* todo this should not happen */
1978                 break;
1979         }
1980         return the_obj;
1981 }
1982
1983 static struct yaffs_obj *yaffs_create_fake_dir(struct yaffs_dev *dev,
1984                                                int number, u32 mode)
1985 {
1986
1987         struct yaffs_obj *obj =
1988             yaffs_new_obj(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1989
1990         if (!obj)
1991                 return NULL;
1992
1993         obj->fake = 1;  /* it is fake so it might not use NAND */
1994         obj->rename_allowed = 0;
1995         obj->unlink_allowed = 0;
1996         obj->deleted = 0;
1997         obj->unlinked = 0;
1998         obj->yst_mode = mode;
1999         obj->my_dev = dev;
2000         obj->hdr_chunk = 0;     /* Not a valid chunk. */
2001         return obj;
2002
2003 }
2004
2005
2006 static void yaffs_init_tnodes_and_objs(struct yaffs_dev *dev)
2007 {
2008         int i;
2009
2010         dev->n_obj = 0;
2011         dev->n_tnodes = 0;
2012         yaffs_init_raw_tnodes_and_objs(dev);
2013
2014         for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2015                 INIT_LIST_HEAD(&dev->obj_bucket[i].list);
2016                 dev->obj_bucket[i].count = 0;
2017         }
2018 }
2019
2020 struct yaffs_obj *yaffs_find_or_create_by_number(struct yaffs_dev *dev,
2021                                                  int number,
2022                                                  enum yaffs_obj_type type)
2023 {
2024         struct yaffs_obj *the_obj = NULL;
2025
2026         if (number > 0)
2027                 the_obj = yaffs_find_by_number(dev, number);
2028
2029         if (!the_obj)
2030                 the_obj = yaffs_new_obj(dev, number, type);
2031
2032         return the_obj;
2033
2034 }
2035
2036 YCHAR *yaffs_clone_str(const YCHAR *str)
2037 {
2038         YCHAR *new_str = NULL;
2039         int len;
2040
2041         if (!str)
2042                 str = _Y("");
2043
2044         len = strnlen(str, YAFFS_MAX_ALIAS_LENGTH);
2045         new_str = kmalloc((len + 1) * sizeof(YCHAR), GFP_NOFS);
2046         if (new_str) {
2047                 strncpy(new_str, str, len);
2048                 new_str[len] = 0;
2049         }
2050         return new_str;
2051
2052 }
2053 /*
2054  *yaffs_update_parent() handles fixing a directories mtime and ctime when a new
2055  * link (ie. name) is created or deleted in the directory.
2056  *
2057  * ie.
2058  *   create dir/a : update dir's mtime/ctime
2059  *   rm dir/a:   update dir's mtime/ctime
2060  *   modify dir/a: don't update dir's mtimme/ctime
2061  *
2062  * This can be handled immediately or defered. Defering helps reduce the number
2063  * of updates when many files in a directory are changed within a brief period.
2064  *
2065  * If the directory updating is defered then yaffs_update_dirty_dirs must be
2066  * called periodically.
2067  */
2068
2069 static void yaffs_update_parent(struct yaffs_obj *obj)
2070 {
2071         struct yaffs_dev *dev;
2072
2073         if (!obj)
2074                 return;
2075         dev = obj->my_dev;
2076         obj->dirty = 1;
2077         yaffs_load_current_time(obj, 0, 1);
2078         if (dev->param.defered_dir_update) {
2079                 struct list_head *link = &obj->variant.dir_variant.dirty;
2080
2081                 if (list_empty(link)) {
2082                         list_add(link, &dev->dirty_dirs);
2083                         yaffs_trace(YAFFS_TRACE_BACKGROUND,
2084                           "Added object %d to dirty directories",
2085                            obj->obj_id);
2086                 }
2087
2088         } else {
2089                 yaffs_update_oh(obj, NULL, 0, 0, 0, NULL);
2090         }
2091 }
2092
2093 void yaffs_update_dirty_dirs(struct yaffs_dev *dev)
2094 {
2095         struct list_head *link;
2096         struct yaffs_obj *obj;
2097         struct yaffs_dir_var *d_s;
2098         union yaffs_obj_var *o_v;
2099
2100         yaffs_trace(YAFFS_TRACE_BACKGROUND, "Update dirty directories");
2101
2102         while (!list_empty(&dev->dirty_dirs)) {
2103                 link = dev->dirty_dirs.next;
2104                 list_del_init(link);
2105
2106                 d_s = list_entry(link, struct yaffs_dir_var, dirty);
2107                 o_v = list_entry(d_s, union yaffs_obj_var, dir_variant);
2108                 obj = list_entry(o_v, struct yaffs_obj, variant);
2109
2110                 yaffs_trace(YAFFS_TRACE_BACKGROUND, "Update directory %d",
2111                         obj->obj_id);
2112
2113                 if (obj->dirty)
2114                         yaffs_update_oh(obj, NULL, 0, 0, 0, NULL);
2115         }
2116 }
2117
2118 /*
2119  * Mknod (create) a new object.
2120  * equiv_obj only has meaning for a hard link;
2121  * alias_str only has meaning for a symlink.
2122  * rdev only has meaning for devices (a subset of special objects)
2123  */
2124
2125 static struct yaffs_obj *yaffs_create_obj(enum yaffs_obj_type type,
2126                                           struct yaffs_obj *parent,
2127                                           const YCHAR *name,
2128                                           u32 mode,
2129                                           u32 uid,
2130                                           u32 gid,
2131                                           struct yaffs_obj *equiv_obj,
2132                                           const YCHAR *alias_str, u32 rdev)
2133 {
2134         struct yaffs_obj *in;
2135         YCHAR *str = NULL;
2136         struct yaffs_dev *dev = parent->my_dev;
2137
2138         /* Check if the entry exists.
2139          * If it does then fail the call since we don't want a dup. */
2140         if (yaffs_find_by_name(parent, name))
2141                 return NULL;
2142
2143         if (type == YAFFS_OBJECT_TYPE_SYMLINK) {
2144                 str = yaffs_clone_str(alias_str);
2145                 if (!str)
2146                         return NULL;
2147         }
2148
2149         in = yaffs_new_obj(dev, -1, type);
2150
2151         if (!in) {
2152                 kfree(str);
2153                 return NULL;
2154         }
2155
2156         in->hdr_chunk = 0;
2157         in->valid = 1;
2158         in->variant_type = type;
2159
2160         in->yst_mode = mode;
2161
2162         yaffs_attribs_init(in, gid, uid, rdev);
2163
2164         in->n_data_chunks = 0;
2165
2166         yaffs_set_obj_name(in, name);
2167         in->dirty = 1;
2168
2169         yaffs_add_obj_to_dir(parent, in);
2170
2171         in->my_dev = parent->my_dev;
2172
2173         switch (type) {
2174         case YAFFS_OBJECT_TYPE_SYMLINK:
2175                 in->variant.symlink_variant.alias = str;
2176                 break;
2177         case YAFFS_OBJECT_TYPE_HARDLINK:
2178                 in->variant.hardlink_variant.equiv_obj = equiv_obj;
2179                 in->variant.hardlink_variant.equiv_id = equiv_obj->obj_id;
2180                 list_add(&in->hard_links, &equiv_obj->hard_links);
2181                 break;
2182         case YAFFS_OBJECT_TYPE_FILE:
2183         case YAFFS_OBJECT_TYPE_DIRECTORY:
2184         case YAFFS_OBJECT_TYPE_SPECIAL:
2185         case YAFFS_OBJECT_TYPE_UNKNOWN:
2186                 /* do nothing */
2187                 break;
2188         }
2189
2190         if (yaffs_update_oh(in, name, 0, 0, 0, NULL) < 0) {
2191                 /* Could not create the object header, fail */
2192                 yaffs_del_obj(in);
2193                 in = NULL;
2194         }
2195
2196         if (in)
2197                 yaffs_update_parent(parent);
2198
2199         return in;
2200 }
2201
2202 struct yaffs_obj *yaffs_create_file(struct yaffs_obj *parent,
2203                                     const YCHAR *name, u32 mode, u32 uid,
2204                                     u32 gid)
2205 {
2206         return yaffs_create_obj(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2207                                 uid, gid, NULL, NULL, 0);
2208 }
2209
2210 struct yaffs_obj *yaffs_create_dir(struct yaffs_obj *parent, const YCHAR *name,
2211                                    u32 mode, u32 uid, u32 gid)
2212 {
2213         return yaffs_create_obj(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2214                                 mode, uid, gid, NULL, NULL, 0);
2215 }
2216
2217 struct yaffs_obj *yaffs_create_special(struct yaffs_obj *parent,
2218                                        const YCHAR *name, u32 mode, u32 uid,
2219                                        u32 gid, u32 rdev)
2220 {
2221         return yaffs_create_obj(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2222                                 uid, gid, NULL, NULL, rdev);
2223 }
2224
2225 struct yaffs_obj *yaffs_create_symlink(struct yaffs_obj *parent,
2226                                        const YCHAR *name, u32 mode, u32 uid,
2227                                        u32 gid, const YCHAR *alias)
2228 {
2229         return yaffs_create_obj(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2230                                 uid, gid, NULL, alias, 0);
2231 }
2232
2233 /* yaffs_link_obj returns the object id of the equivalent object.*/
2234 struct yaffs_obj *yaffs_link_obj(struct yaffs_obj *parent, const YCHAR * name,
2235                                  struct yaffs_obj *equiv_obj)
2236 {
2237         /* Get the real object in case we were fed a hard link obj */
2238         equiv_obj = yaffs_get_equivalent_obj(equiv_obj);
2239
2240         if (yaffs_create_obj(YAFFS_OBJECT_TYPE_HARDLINK,
2241                         parent, name, 0, 0, 0,
2242                         equiv_obj, NULL, 0))
2243                 return equiv_obj;
2244
2245         return NULL;
2246
2247 }
2248
2249
2250
2251 /*---------------------- Block Management and Page Allocation -------------*/
2252
2253 static void yaffs_deinit_blocks(struct yaffs_dev *dev)
2254 {
2255         if (dev->block_info_alt && dev->block_info)
2256                 vfree(dev->block_info);
2257         else
2258                 kfree(dev->block_info);
2259
2260         dev->block_info_alt = 0;
2261
2262         dev->block_info = NULL;
2263
2264         if (dev->chunk_bits_alt && dev->chunk_bits)
2265                 vfree(dev->chunk_bits);
2266         else
2267                 kfree(dev->chunk_bits);
2268         dev->chunk_bits_alt = 0;
2269         dev->chunk_bits = NULL;
2270 }
2271
2272 static int yaffs_init_blocks(struct yaffs_dev *dev)
2273 {
2274         int n_blocks = dev->internal_end_block - dev->internal_start_block + 1;
2275
2276         dev->block_info = NULL;
2277         dev->chunk_bits = NULL;
2278         dev->alloc_block = -1;  /* force it to get a new one */
2279
2280         /* If the first allocation strategy fails, thry the alternate one */
2281         dev->block_info =
2282                 kmalloc(n_blocks * sizeof(struct yaffs_block_info), GFP_NOFS);
2283         if (!dev->block_info) {
2284                 dev->block_info =
2285                     vmalloc(n_blocks * sizeof(struct yaffs_block_info));
2286                 dev->block_info_alt = 1;
2287         } else {
2288                 dev->block_info_alt = 0;
2289         }
2290
2291         if (!dev->block_info)
2292                 goto alloc_error;
2293
2294         /* Set up dynamic blockinfo stuff. Round up bytes. */
2295         dev->chunk_bit_stride = (dev->param.chunks_per_block + 7) / 8;
2296         dev->chunk_bits =
2297                 kmalloc(dev->chunk_bit_stride * n_blocks, GFP_NOFS);
2298         if (!dev->chunk_bits) {
2299                 dev->chunk_bits =
2300                     vmalloc(dev->chunk_bit_stride * n_blocks);
2301                 dev->chunk_bits_alt = 1;
2302         } else {
2303                 dev->chunk_bits_alt = 0;
2304         }
2305         if (!dev->chunk_bits)
2306                 goto alloc_error;
2307
2308
2309         memset(dev->block_info, 0, n_blocks * sizeof(struct yaffs_block_info));
2310         memset(dev->chunk_bits, 0, dev->chunk_bit_stride * n_blocks);
2311         return YAFFS_OK;
2312
2313 alloc_error:
2314         yaffs_deinit_blocks(dev);
2315         return YAFFS_FAIL;
2316 }
2317
2318
2319 void yaffs_block_became_dirty(struct yaffs_dev *dev, int block_no)
2320 {
2321         struct yaffs_block_info *bi = yaffs_get_block_info(dev, block_no);
2322         int erased_ok = 0;
2323         int i;
2324
2325         /* If the block is still healthy erase it and mark as clean.
2326          * If the block has had a data failure, then retire it.
2327          */
2328
2329         yaffs_trace(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2330                 "yaffs_block_became_dirty block %d state %d %s",
2331                 block_no, bi->block_state,
2332                 (bi->needs_retiring) ? "needs retiring" : "");
2333
2334         yaffs2_clear_oldest_dirty_seq(dev, bi);
2335
2336         bi->block_state = YAFFS_BLOCK_STATE_DIRTY;
2337
2338         /* If this is the block being garbage collected then stop gc'ing */
2339         if (block_no == dev->gc_block)
2340                 dev->gc_block = 0;
2341
2342         /* If this block is currently the best candidate for gc
2343          * then drop as a candidate */
2344         if (block_no == dev->gc_dirtiest) {
2345                 dev->gc_dirtiest = 0;
2346                 dev->gc_pages_in_use = 0;
2347         }
2348
2349         if (!bi->needs_retiring) {
2350                 yaffs2_checkpt_invalidate(dev);
2351                 erased_ok = yaffs_erase_block(dev, block_no);
2352                 if (!erased_ok) {
2353                         dev->n_erase_failures++;
2354                         yaffs_trace(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2355                           "**>> Erasure failed %d", block_no);
2356                 }
2357         }
2358
2359         /* Verify erasure if needed */
2360         if (erased_ok &&
2361             ((yaffs_trace_mask & YAFFS_TRACE_ERASE) ||
2362              !yaffs_skip_verification(dev))) {
2363                 for (i = 0; i < dev->param.chunks_per_block; i++) {
2364                         if (!yaffs_check_chunk_erased(dev,
2365                                 block_no * dev->param.chunks_per_block + i)) {
2366                                 yaffs_trace(YAFFS_TRACE_ERROR,
2367                                         ">>Block %d erasure supposedly OK, but chunk %d not erased",
2368                                         block_no, i);
2369                         }
2370                 }
2371         }
2372
2373         if (!erased_ok) {
2374                 /* We lost a block of free space */
2375                 dev->n_free_chunks -= dev->param.chunks_per_block;
2376                 yaffs_retire_block(dev, block_no);
2377                 yaffs_trace(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2378                         "**>> Block %d retired", block_no);
2379                 return;
2380         }
2381
2382         /* Clean it up... */
2383         bi->block_state = YAFFS_BLOCK_STATE_EMPTY;
2384         bi->seq_number = 0;
2385         dev->n_erased_blocks++;
2386         bi->pages_in_use = 0;
2387         bi->soft_del_pages = 0;
2388         bi->has_shrink_hdr = 0;
2389         bi->skip_erased_check = 1;      /* Clean, so no need to check */
2390         bi->gc_prioritise = 0;
2391         bi->has_summary=0;
2392
2393         yaffs_clear_chunk_bits(dev, block_no);
2394
2395         yaffs_trace(YAFFS_TRACE_ERASE, "Erased block %d", block_no);
2396 }
2397
2398 static inline int yaffs_gc_process_chunk(struct yaffs_dev *dev,
2399                                         struct yaffs_block_info *bi,
2400                                         int old_chunk, u8 *buffer)
2401 {
2402         int new_chunk;
2403         int mark_flash = 1;
2404         struct yaffs_ext_tags tags;
2405         struct yaffs_obj *object;
2406         int matching_chunk;
2407         int ret_val = YAFFS_OK;
2408
2409         memset(&tags, 0, sizeof(tags));
2410         yaffs_rd_chunk_tags_nand(dev, old_chunk,
2411                                  buffer, &tags);
2412         object = yaffs_find_by_number(dev, tags.obj_id);
2413
2414         yaffs_trace(YAFFS_TRACE_GC_DETAIL,
2415                 "Collecting chunk in block %d, %d %d %d ",
2416                 dev->gc_chunk, tags.obj_id,
2417                 tags.chunk_id, tags.n_bytes);
2418
2419         if (object && !yaffs_skip_verification(dev)) {
2420                 if (tags.chunk_id == 0)
2421                         matching_chunk =
2422                             object->hdr_chunk;
2423                 else if (object->soft_del)
2424                         /* Defeat the test */
2425                         matching_chunk = old_chunk;
2426                 else
2427                         matching_chunk =
2428                             yaffs_find_chunk_in_file
2429                             (object, tags.chunk_id,
2430                              NULL);
2431
2432                 if (old_chunk != matching_chunk)
2433                         yaffs_trace(YAFFS_TRACE_ERROR,
2434                                 "gc: page in gc mismatch: %d %d %d %d",
2435                                 old_chunk,
2436                                 matching_chunk,
2437                                 tags.obj_id,
2438                                 tags.chunk_id);
2439         }
2440
2441         if (!object) {
2442                 yaffs_trace(YAFFS_TRACE_ERROR,
2443                         "page %d in gc has no object: %d %d %d ",
2444                         old_chunk,
2445                         tags.obj_id, tags.chunk_id,
2446                         tags.n_bytes);
2447         }
2448
2449         if (object &&
2450             object->deleted &&
2451             object->soft_del && tags.chunk_id != 0) {
2452                 /* Data chunk in a soft deleted file,
2453                  * throw it away.
2454                  * It's a soft deleted data chunk,
2455                  * No need to copy this, just forget
2456                  * about it and fix up the object.
2457                  */
2458
2459                 /* Free chunks already includes
2460                  * softdeleted chunks, how ever this
2461                  * chunk is going to soon be really
2462                  * deleted which will increment free
2463                  * chunks. We have to decrement free
2464                  * chunks so this works out properly.
2465                  */
2466                 dev->n_free_chunks--;
2467                 bi->soft_del_pages--;
2468
2469                 object->n_data_chunks--;
2470                 if (object->n_data_chunks <= 0) {
2471                         /* remeber to clean up obj */
2472                         dev->gc_cleanup_list[dev->n_clean_ups] = tags.obj_id;
2473                         dev->n_clean_ups++;
2474                 }
2475                 mark_flash = 0;
2476         } else if (object) {
2477                 /* It's either a data chunk in a live
2478                  * file or an ObjectHeader, so we're
2479                  * interested in it.
2480                  * NB Need to keep the ObjectHeaders of
2481                  * deleted files until the whole file
2482                  * has been deleted off
2483                  */
2484                 tags.serial_number++;
2485                 dev->n_gc_copies++;
2486
2487                 if (tags.chunk_id == 0) {
2488                         /* It is an object Id,
2489                          * We need to nuke the
2490                          * shrinkheader flags since its
2491                          * work is done.
2492                          * Also need to clean up
2493                          * shadowing.
2494                          */
2495                         struct yaffs_obj_hdr *oh;
2496                         oh = (struct yaffs_obj_hdr *) buffer;
2497
2498                         oh->is_shrink = 0;
2499                         tags.extra_is_shrink = 0;
2500                         oh->shadows_obj = 0;
2501                         oh->inband_shadowed_obj_id = 0;
2502                         tags.extra_shadows = 0;
2503
2504                         /* Update file size */
2505                         if (object->variant_type == YAFFS_OBJECT_TYPE_FILE) {
2506                                 yaffs_oh_size_load( oh,
2507                                     object->variant.file_variant.file_size);
2508                                 tags.extra_file_size =
2509                                     object->variant.file_variant.file_size;
2510                         }
2511
2512                         yaffs_verify_oh(object, oh, &tags, 1);
2513                         new_chunk =
2514                             yaffs_write_new_chunk(dev, (u8 *) oh, &tags, 1);
2515                 } else {
2516                         new_chunk =
2517                             yaffs_write_new_chunk(dev, buffer, &tags, 1);
2518                 }
2519
2520                 if (new_chunk < 0) {
2521                         ret_val = YAFFS_FAIL;
2522                 } else {
2523
2524                         /* Now fix up the Tnodes etc. */
2525
2526                         if (tags.chunk_id == 0) {
2527                                 /* It's a header */
2528                                 object->hdr_chunk = new_chunk;
2529                                 object->serial = tags.serial_number;
2530                         } else {
2531                                 /* It's a data chunk */
2532                                 yaffs_put_chunk_in_file(object, tags.chunk_id,
2533                                                         new_chunk, 0);
2534                         }
2535                 }
2536         }
2537         if (ret_val == YAFFS_OK)
2538                 yaffs_chunk_del(dev, old_chunk, mark_flash, __LINE__);
2539         return ret_val;
2540 }
2541
2542 static int yaffs_gc_block(struct yaffs_dev *dev, int block, int whole_block)
2543 {
2544         int old_chunk;
2545         int ret_val = YAFFS_OK;
2546         int i;
2547         int is_checkpt_block;
2548         int max_copies;
2549         int chunks_before = yaffs_get_erased_chunks(dev);
2550         int chunks_after;
2551         struct yaffs_block_info *bi = yaffs_get_block_info(dev, block);
2552
2553         is_checkpt_block = (bi->block_state == YAFFS_BLOCK_STATE_CHECKPOINT);
2554
2555         yaffs_trace(YAFFS_TRACE_TRACING,
2556                 "Collecting block %d, in use %d, shrink %d, whole_block %d",
2557                 block, bi->pages_in_use, bi->has_shrink_hdr,
2558                 whole_block);
2559
2560         /*yaffs_verify_free_chunks(dev); */
2561
2562         if (bi->block_state == YAFFS_BLOCK_STATE_FULL)
2563                 bi->block_state = YAFFS_BLOCK_STATE_COLLECTING;
2564
2565         bi->has_shrink_hdr = 0; /* clear the flag so that the block can erase */
2566
2567         dev->gc_disable = 1;
2568
2569         yaffs_summary_gc(dev, block);
2570
2571         if (is_checkpt_block || !yaffs_still_some_chunks(dev, block)) {
2572                 yaffs_trace(YAFFS_TRACE_TRACING,
2573                         "Collecting block %d that has no chunks in use",
2574                         block);
2575                 yaffs_block_became_dirty(dev, block);
2576         } else {
2577
2578                 u8 *buffer = yaffs_get_temp_buffer(dev);
2579
2580                 yaffs_verify_blk(dev, bi, block);
2581
2582                 max_copies = (whole_block) ? dev->param.chunks_per_block : 5;
2583                 old_chunk = block * dev->param.chunks_per_block + dev->gc_chunk;
2584
2585                 for (/* init already done */ ;
2586                      ret_val == YAFFS_OK &&
2587                      dev->gc_chunk < dev->param.chunks_per_block &&
2588                      (bi->block_state == YAFFS_BLOCK_STATE_COLLECTING) &&
2589                      max_copies > 0;
2590                      dev->gc_chunk++, old_chunk++) {
2591                         if (yaffs_check_chunk_bit(dev, block, dev->gc_chunk)) {
2592                                 /* Page is in use and might need to be copied */
2593                                 max_copies--;
2594                                 ret_val = yaffs_gc_process_chunk(dev, bi,
2595                                                         old_chunk, buffer);
2596                         }
2597                 }
2598                 yaffs_release_temp_buffer(dev, buffer);
2599         }
2600
2601         yaffs_verify_collected_blk(dev, bi, block);
2602
2603         if (bi->block_state == YAFFS_BLOCK_STATE_COLLECTING) {
2604                 /*
2605                  * The gc did not complete. Set block state back to FULL
2606                  * because checkpointing does not restore gc.
2607                  */
2608                 bi->block_state = YAFFS_BLOCK_STATE_FULL;
2609         } else {
2610                 /* The gc completed. */
2611                 /* Do any required cleanups */
2612                 for (i = 0; i < dev->n_clean_ups; i++) {
2613                         /* Time to delete the file too */
2614                         struct yaffs_obj *object =
2615                             yaffs_find_by_number(dev, dev->gc_cleanup_list[i]);
2616                         if (object) {
2617                                 yaffs_free_tnode(dev,
2618                                           object->variant.file_variant.top);
2619                                 object->variant.file_variant.top = NULL;
2620                                 yaffs_trace(YAFFS_TRACE_GC,
2621                                         "yaffs: About to finally delete object %d",
2622                                         object->obj_id);
2623                                 yaffs_generic_obj_del(object);
2624                                 object->my_dev->n_deleted_files--;
2625                         }
2626
2627                 }
2628                 chunks_after = yaffs_get_erased_chunks(dev);
2629                 if (chunks_before >= chunks_after)
2630                         yaffs_trace(YAFFS_TRACE_GC,
2631                                 "gc did not increase free chunks before %d after %d",
2632                                 chunks_before, chunks_after);
2633                 dev->gc_block = 0;
2634                 dev->gc_chunk = 0;
2635                 dev->n_clean_ups = 0;
2636         }
2637
2638         dev->gc_disable = 0;
2639
2640         return ret_val;
2641 }
2642
2643 /*
2644  * find_gc_block() selects the dirtiest block (or close enough)
2645  * for garbage collection.
2646  */
2647
2648 static unsigned yaffs_find_gc_block(struct yaffs_dev *dev,
2649                                     int aggressive, int background)
2650 {
2651         int i;
2652         int iterations;
2653         unsigned selected = 0;
2654         int prioritised = 0;
2655         int prioritised_exist = 0;
2656         struct yaffs_block_info *bi;
2657         int threshold;
2658
2659         /* First let's see if we need to grab a prioritised block */
2660         if (dev->has_pending_prioritised_gc && !aggressive) {
2661                 dev->gc_dirtiest = 0;
2662                 bi = dev->block_info;
2663                 for (i = dev->internal_start_block;
2664                      i <= dev->internal_end_block && !selected; i++) {
2665
2666                         if (bi->gc_prioritise) {
2667                                 prioritised_exist = 1;
2668                                 if (bi->block_state == YAFFS_BLOCK_STATE_FULL &&
2669                                     yaffs_block_ok_for_gc(dev, bi)) {
2670                                         selected = i;
2671                                         prioritised = 1;
2672                                 }
2673                         }
2674                         bi++;
2675                 }
2676
2677                 /*
2678                  * If there is a prioritised block and none was selected then
2679                  * this happened because there is at least one old dirty block
2680                  * gumming up the works. Let's gc the oldest dirty block.
2681                  */
2682
2683                 if (prioritised_exist &&
2684                     !selected && dev->oldest_dirty_block > 0)
2685                         selected = dev->oldest_dirty_block;
2686
2687                 if (!prioritised_exist) /* None found, so we can clear this */
2688                         dev->has_pending_prioritised_gc = 0;
2689         }
2690
2691         /* If we're doing aggressive GC then we are happy to take a less-dirty
2692          * block, and search harder.
2693          * else (leasurely gc), then we only bother to do this if the
2694          * block has only a few pages in use.
2695          */
2696
2697         if (!selected) {
2698                 int pages_used;
2699                 int n_blocks =
2700                     dev->internal_end_block - dev->internal_start_block + 1;
2701                 if (aggressive) {
2702                         threshold = dev->param.chunks_per_block;
2703                         iterations = n_blocks;
2704                 } else {
2705                         int max_threshold;
2706
2707                         if (background)
2708                                 max_threshold = dev->param.chunks_per_block / 2;
2709                         else
2710                                 max_threshold = dev->param.chunks_per_block / 8;
2711
2712                         if (max_threshold < YAFFS_GC_PASSIVE_THRESHOLD)
2713                                 max_threshold = YAFFS_GC_PASSIVE_THRESHOLD;
2714
2715                         threshold = background ? (dev->gc_not_done + 2) * 2 : 0;
2716                         if (threshold < YAFFS_GC_PASSIVE_THRESHOLD)
2717                                 threshold = YAFFS_GC_PASSIVE_THRESHOLD;
2718                         if (threshold > max_threshold)
2719                                 threshold = max_threshold;
2720
2721                         iterations = n_blocks / 16 + 1;
2722                         if (iterations > 100)
2723                                 iterations = 100;
2724                 }
2725
2726                 for (i = 0;
2727                      i < iterations &&
2728                      (dev->gc_dirtiest < 1 ||
2729                       dev->gc_pages_in_use > YAFFS_GC_GOOD_ENOUGH);
2730                      i++) {
2731                         dev->gc_block_finder++;
2732                         if (dev->gc_block_finder < dev->internal_start_block ||
2733                             dev->gc_block_finder > dev->internal_end_block)
2734                                 dev->gc_block_finder =
2735                                     dev->internal_start_block;
2736
2737                         bi = yaffs_get_block_info(dev, dev->gc_block_finder);
2738
2739                         pages_used = bi->pages_in_use - bi->soft_del_pages;
2740
2741                         if (bi->block_state == YAFFS_BLOCK_STATE_FULL &&
2742                             pages_used < dev->param.chunks_per_block &&
2743                             (dev->gc_dirtiest < 1 ||
2744                              pages_used < dev->gc_pages_in_use) &&
2745                             yaffs_block_ok_for_gc(dev, bi)) {
2746                                 dev->gc_dirtiest = dev->gc_block_finder;
2747                                 dev->gc_pages_in_use = pages_used;
2748                         }
2749                 }
2750
2751                 if (dev->gc_dirtiest > 0 && dev->gc_pages_in_use <= threshold)
2752                         selected = dev->gc_dirtiest;
2753         }
2754
2755         /*
2756          * If nothing has been selected for a while, try the oldest dirty
2757          * because that's gumming up the works.
2758          */
2759
2760         if (!selected && dev->param.is_yaffs2 &&
2761             dev->gc_not_done >= (background ? 10 : 20)) {
2762                 yaffs2_find_oldest_dirty_seq(dev);
2763                 if (dev->oldest_dirty_block > 0) {
2764                         selected = dev->oldest_dirty_block;
2765                         dev->gc_dirtiest = selected;
2766                         dev->oldest_dirty_gc_count++;
2767                         bi = yaffs_get_block_info(dev, selected);
2768                         dev->gc_pages_in_use =
2769                             bi->pages_in_use - bi->soft_del_pages;
2770                 } else {
2771                         dev->gc_not_done = 0;
2772                 }
2773         }
2774
2775         if (selected) {
2776                 yaffs_trace(YAFFS_TRACE_GC,
2777                         "GC Selected block %d with %d free, prioritised:%d",
2778                         selected,
2779                         dev->param.chunks_per_block - dev->gc_pages_in_use,
2780                         prioritised);
2781
2782                 dev->n_gc_blocks++;
2783                 if (background)
2784                         dev->bg_gcs++;
2785
2786                 dev->gc_dirtiest = 0;
2787                 dev->gc_pages_in_use = 0;
2788                 dev->gc_not_done = 0;
2789                 if (dev->refresh_skip > 0)
2790                         dev->refresh_skip--;
2791         } else {
2792                 dev->gc_not_done++;
2793                 yaffs_trace(YAFFS_TRACE_GC,
2794                         "GC none: finder %d skip %d threshold %d dirtiest %d using %d oldest %d%s",
2795                         dev->gc_block_finder, dev->gc_not_done, threshold,
2796                         dev->gc_dirtiest, dev->gc_pages_in_use,
2797                         dev->oldest_dirty_block, background ? " bg" : "");
2798         }
2799
2800         return selected;
2801 }
2802
2803 /* New garbage collector
2804  * If we're very low on erased blocks then we do aggressive garbage collection
2805  * otherwise we do "leasurely" garbage collection.
2806  * Aggressive gc looks further (whole array) and will accept less dirty blocks.
2807  * Passive gc only inspects smaller areas and only accepts more dirty blocks.
2808  *
2809  * The idea is to help clear out space in a more spread-out manner.
2810  * Dunno if it really does anything useful.
2811  */
2812 static int yaffs_check_gc(struct yaffs_dev *dev, int background)
2813 {
2814         int aggressive = 0;
2815         int gc_ok = YAFFS_OK;
2816         int max_tries = 0;
2817         int min_erased;
2818         int erased_chunks;
2819         int checkpt_block_adjust;
2820
2821         if (dev->param.gc_control && (dev->param.gc_control(dev) & 1) == 0)
2822                 return YAFFS_OK;
2823
2824         if (dev->gc_disable)
2825                 /* Bail out so we don't get recursive gc */
2826                 return YAFFS_OK;
2827
2828         /* This loop should pass the first time.
2829          * Only loops here if the collection does not increase space.
2830          */
2831
2832         do {
2833                 max_tries++;
2834
2835                 checkpt_block_adjust = yaffs_calc_checkpt_blocks_required(dev);
2836
2837                 min_erased =
2838                     dev->param.n_reserved_blocks + checkpt_block_adjust + 1;
2839                 erased_chunks =
2840                     dev->n_erased_blocks * dev->param.chunks_per_block;
2841
2842                 /* If we need a block soon then do aggressive gc. */
2843                 if (dev->n_erased_blocks < min_erased)
2844                         aggressive = 1;
2845                 else {
2846                         if (!background
2847                             && erased_chunks > (dev->n_free_chunks / 4))
2848                                 break;
2849
2850                         if (dev->gc_skip > 20)
2851                                 dev->gc_skip = 20;
2852                         if (erased_chunks < dev->n_free_chunks / 2 ||
2853                             dev->gc_skip < 1 || background)
2854                                 aggressive = 0;
2855                         else {
2856                                 dev->gc_skip--;
2857                                 break;
2858                         }
2859                 }
2860
2861                 dev->gc_skip = 5;
2862
2863                 /* If we don't already have a block being gc'd then see if we
2864                  * should start another */
2865
2866                 if (dev->gc_block < 1 && !aggressive) {
2867                         dev->gc_block = yaffs2_find_refresh_block(dev);
2868                         dev->gc_chunk = 0;
2869                         dev->n_clean_ups = 0;
2870                 }
2871                 if (dev->gc_block < 1) {
2872                         dev->gc_block =
2873                             yaffs_find_gc_block(dev, aggressive, background);
2874                         dev->gc_chunk = 0;
2875                         dev->n_clean_ups = 0;
2876                 }
2877
2878                 if (dev->gc_block > 0) {
2879                         dev->all_gcs++;
2880                         if (!aggressive)
2881                                 dev->passive_gc_count++;
2882
2883                         yaffs_trace(YAFFS_TRACE_GC,
2884                                 "yaffs: GC n_erased_blocks %d aggressive %d",
2885                                 dev->n_erased_blocks, aggressive);
2886
2887                         gc_ok = yaffs_gc_block(dev, dev->gc_block, aggressive);
2888                 }
2889
2890                 if (dev->n_erased_blocks < (dev->param.n_reserved_blocks) &&
2891                     dev->gc_block > 0) {
2892                         yaffs_trace(YAFFS_TRACE_GC,
2893                                 "yaffs: GC !!!no reclaim!!! n_erased_blocks %d after try %d block %d",
2894                                 dev->n_erased_blocks, max_tries,
2895                                 dev->gc_block);
2896                 }
2897         } while ((dev->n_erased_blocks < dev->param.n_reserved_blocks) &&
2898                  (dev->gc_block > 0) && (max_tries < 2));
2899
2900         return aggressive ? gc_ok : YAFFS_OK;
2901 }
2902
2903 /*
2904  * yaffs_bg_gc()
2905  * Garbage collects. Intended to be called from a background thread.
2906  * Returns non-zero if at least half the free chunks are erased.
2907  */
2908 int yaffs_bg_gc(struct yaffs_dev *dev, unsigned urgency)
2909 {
2910         int erased_chunks = dev->n_erased_blocks * dev->param.chunks_per_block;
2911
2912         yaffs_trace(YAFFS_TRACE_BACKGROUND, "Background gc %u", urgency);
2913
2914         yaffs_check_gc(dev, 1);
2915         return erased_chunks > dev->n_free_chunks / 2;
2916 }
2917
2918 /*-------------------- Data file manipulation -----------------*/
2919
2920 static int yaffs_rd_data_obj(struct yaffs_obj *in, int inode_chunk, u8 * buffer)
2921 {
2922         int nand_chunk = yaffs_find_chunk_in_file(in, inode_chunk, NULL);
2923
2924         if (nand_chunk >= 0)
2925                 return yaffs_rd_chunk_tags_nand(in->my_dev, nand_chunk,
2926                                                 buffer, NULL);
2927         else {
2928                 yaffs_trace(YAFFS_TRACE_NANDACCESS,
2929                         "Chunk %d not found zero instead",
2930                         nand_chunk);
2931                 /* get sane (zero) data if you read a hole */
2932                 memset(buffer, 0, in->my_dev->data_bytes_per_chunk);
2933                 return 0;
2934         }
2935
2936 }
2937
2938 void yaffs_chunk_del(struct yaffs_dev *dev, int chunk_id, int mark_flash,
2939                      int lyn)
2940 {
2941         int block;
2942         int page;
2943         struct yaffs_ext_tags tags;
2944         struct yaffs_block_info *bi;
2945
2946         if (chunk_id <= 0)
2947                 return;
2948
2949         dev->n_deletions++;
2950         block = chunk_id / dev->param.chunks_per_block;
2951         page = chunk_id % dev->param.chunks_per_block;
2952
2953         if (!yaffs_check_chunk_bit(dev, block, page))
2954                 yaffs_trace(YAFFS_TRACE_VERIFY,
2955                         "Deleting invalid chunk %d", chunk_id);
2956
2957         bi = yaffs_get_block_info(dev, block);
2958
2959         yaffs2_update_oldest_dirty_seq(dev, block, bi);
2960
2961         yaffs_trace(YAFFS_TRACE_DELETION,
2962                 "line %d delete of chunk %d",
2963                 lyn, chunk_id);
2964
2965         if (!dev->param.is_yaffs2 && mark_flash &&
2966             bi->block_state != YAFFS_BLOCK_STATE_COLLECTING) {
2967
2968                 memset(&tags, 0, sizeof(tags));
2969                 tags.is_deleted = 1;
2970                 yaffs_wr_chunk_tags_nand(dev, chunk_id, NULL, &tags);
2971                 yaffs_handle_chunk_update(dev, chunk_id, &tags);
2972         } else {
2973                 dev->n_unmarked_deletions++;
2974         }
2975
2976         /* Pull out of the management area.
2977          * If the whole block became dirty, this will kick off an erasure.
2978          */
2979         if (bi->block_state == YAFFS_BLOCK_STATE_ALLOCATING ||
2980             bi->block_state == YAFFS_BLOCK_STATE_FULL ||
2981             bi->block_state == YAFFS_BLOCK_STATE_NEEDS_SCAN ||
2982             bi->block_state == YAFFS_BLOCK_STATE_COLLECTING) {
2983                 dev->n_free_chunks++;
2984                 yaffs_clear_chunk_bit(dev, block, page);
2985                 bi->pages_in_use--;
2986
2987                 if (bi->pages_in_use == 0 &&
2988                     !bi->has_shrink_hdr &&
2989                     bi->block_state != YAFFS_BLOCK_STATE_ALLOCATING &&
2990                     bi->block_state != YAFFS_BLOCK_STATE_NEEDS_SCAN) {
2991                         yaffs_block_became_dirty(dev, block);
2992                 }
2993         }
2994 }
2995
2996 static int yaffs_wr_data_obj(struct yaffs_obj *in, int inode_chunk,
2997                              const u8 *buffer, int n_bytes, int use_reserve)
2998 {
2999         /* Find old chunk Need to do this to get serial number
3000          * Write new one and patch into tree.
3001          * Invalidate old tags.
3002          */
3003
3004         int prev_chunk_id;
3005         struct yaffs_ext_tags prev_tags;
3006         int new_chunk_id;
3007         struct yaffs_ext_tags new_tags;
3008         struct yaffs_dev *dev = in->my_dev;
3009
3010         yaffs_check_gc(dev, 0);
3011
3012         /* Get the previous chunk at this location in the file if it exists.
3013          * If it does not exist then put a zero into the tree. This creates
3014          * the tnode now, rather than later when it is harder to clean up.
3015          */
3016         prev_chunk_id = yaffs_find_chunk_in_file(in, inode_chunk, &prev_tags);
3017         if (prev_chunk_id < 1 &&
3018             !yaffs_put_chunk_in_file(in, inode_chunk, 0, 0))
3019                 return 0;
3020
3021         /* Set up new tags */
3022         memset(&new_tags, 0, sizeof(new_tags));
3023
3024         new_tags.chunk_id = inode_chunk;
3025         new_tags.obj_id = in->obj_id;
3026         new_tags.serial_number =
3027             (prev_chunk_id > 0) ? prev_tags.serial_number + 1 : 1;
3028         new_tags.n_bytes = n_bytes;
3029
3030         if (n_bytes < 1 || n_bytes > dev->param.total_bytes_per_chunk) {
3031                 yaffs_trace(YAFFS_TRACE_ERROR,
3032                   "Writing %d bytes to chunk!!!!!!!!!",
3033                    n_bytes);
3034                 BUG();
3035         }
3036
3037         new_chunk_id =
3038             yaffs_write_new_chunk(dev, buffer, &new_tags, use_reserve);
3039
3040         if (new_chunk_id > 0) {
3041                 yaffs_put_chunk_in_file(in, inode_chunk, new_chunk_id, 0);
3042
3043                 if (prev_chunk_id > 0)
3044                         yaffs_chunk_del(dev, prev_chunk_id, 1, __LINE__);
3045
3046                 yaffs_verify_file_sane(in);
3047         }
3048         return new_chunk_id;
3049
3050 }
3051
3052
3053
3054 static int yaffs_do_xattrib_mod(struct yaffs_obj *obj, int set,
3055                                 const YCHAR *name, const void *value, int size,
3056                                 int flags)
3057 {
3058         struct yaffs_xattr_mod xmod;
3059         int result;
3060
3061         xmod.set = set;
3062         xmod.name = name;
3063         xmod.data = value;
3064         xmod.size = size;
3065         xmod.flags = flags;
3066         xmod.result = -ENOSPC;
3067
3068         result = yaffs_update_oh(obj, NULL, 0, 0, 0, &xmod);
3069
3070         if (result > 0)
3071                 return xmod.result;
3072         else
3073                 return -ENOSPC;
3074 }
3075
3076 static int yaffs_apply_xattrib_mod(struct yaffs_obj *obj, char *buffer,
3077                                    struct yaffs_xattr_mod *xmod)
3078 {
3079         int retval = 0;
3080         int x_offs = sizeof(struct yaffs_obj_hdr);
3081         struct yaffs_dev *dev = obj->my_dev;
3082         int x_size = dev->data_bytes_per_chunk - sizeof(struct yaffs_obj_hdr);
3083         char *x_buffer = buffer + x_offs;
3084
3085         if (xmod->set)
3086                 retval =
3087                     nval_set(x_buffer, x_size, xmod->name, xmod->data,
3088                              xmod->size, xmod->flags);
3089         else
3090                 retval = nval_del(x_buffer, x_size, xmod->name);
3091
3092         obj->has_xattr = nval_hasvalues(x_buffer, x_size);
3093         obj->xattr_known = 1;
3094         xmod->result = retval;
3095
3096         return retval;
3097 }
3098
3099 static int yaffs_do_xattrib_fetch(struct yaffs_obj *obj, const YCHAR *name,
3100                                   void *value, int size)
3101 {
3102         char *buffer = NULL;
3103         int result;
3104         struct yaffs_ext_tags tags;
3105         struct yaffs_dev *dev = obj->my_dev;
3106         int x_offs = sizeof(struct yaffs_obj_hdr);
3107         int x_size = dev->data_bytes_per_chunk - sizeof(struct yaffs_obj_hdr);
3108         char *x_buffer;
3109         int retval = 0;
3110
3111         if (obj->hdr_chunk < 1)
3112                 return -ENODATA;
3113
3114         /* If we know that the object has no xattribs then don't do all the
3115          * reading and parsing.
3116          */
3117         if (obj->xattr_known && !obj->has_xattr) {
3118                 if (name)
3119                         return -ENODATA;
3120                 else
3121                         return 0;
3122         }
3123
3124         buffer = (char *)yaffs_get_temp_buffer(dev);
3125         if (!buffer)
3126                 return -ENOMEM;
3127
3128         result =
3129             yaffs_rd_chunk_tags_nand(dev, obj->hdr_chunk, (u8 *) buffer, &tags);
3130
3131         if (result != YAFFS_OK)
3132                 retval = -ENOENT;
3133         else {
3134                 x_buffer = buffer + x_offs;
3135
3136                 if (!obj->xattr_known) {
3137                         obj->has_xattr = nval_hasvalues(x_buffer, x_size);
3138                         obj->xattr_known = 1;
3139                 }
3140
3141                 if (name)
3142                         retval = nval_get(x_buffer, x_size, name, value, size);
3143                 else
3144                         retval = nval_list(x_buffer, x_size, value, size);
3145         }
3146         yaffs_release_temp_buffer(dev, (u8 *) buffer);
3147         return retval;
3148 }
3149
3150 int yaffs_set_xattrib(struct yaffs_obj *obj, const YCHAR * name,
3151                       const void *value, int size, int flags)
3152 {
3153         return yaffs_do_xattrib_mod(obj, 1, name, value, size, flags);
3154 }
3155
3156 int yaffs_remove_xattrib(struct yaffs_obj *obj, const YCHAR * name)
3157 {
3158         return yaffs_do_xattrib_mod(obj, 0, name, NULL, 0, 0);
3159 }
3160
3161 int yaffs_get_xattrib(struct yaffs_obj *obj, const YCHAR * name, void *value,
3162                       int size)
3163 {
3164         return yaffs_do_xattrib_fetch(obj, name, value, size);
3165 }
3166
3167 int yaffs_list_xattrib(struct yaffs_obj *obj, char *buffer, int size)
3168 {
3169         return yaffs_do_xattrib_fetch(obj, NULL, buffer, size);
3170 }
3171
3172 static void yaffs_check_obj_details_loaded(struct yaffs_obj *in)
3173 {
3174         u8 *buf;
3175         struct yaffs_obj_hdr *oh;
3176         struct yaffs_dev *dev;
3177         struct yaffs_ext_tags tags;
3178         int result;
3179         int alloc_failed = 0;
3180
3181         if (!in || !in->lazy_loaded || in->hdr_chunk < 1)
3182                 return;
3183
3184         dev = in->my_dev;
3185         in->lazy_loaded = 0;
3186         buf = yaffs_get_temp_buffer(dev);
3187
3188         result = yaffs_rd_chunk_tags_nand(dev, in->hdr_chunk, buf, &tags);
3189         oh = (struct yaffs_obj_hdr *)buf;
3190
3191         in->yst_mode = oh->yst_mode;
3192         yaffs_load_attribs(in, oh);
3193         yaffs_set_obj_name_from_oh(in, oh);
3194
3195         if (in->variant_type == YAFFS_OBJECT_TYPE_SYMLINK) {
3196                 in->variant.symlink_variant.alias =
3197                     yaffs_clone_str(oh->alias);
3198                 if (!in->variant.symlink_variant.alias)
3199                         alloc_failed = 1;       /* Not returned */
3200         }
3201         yaffs_release_temp_buffer(dev, buf);
3202 }
3203
3204 static void yaffs_load_name_from_oh(struct yaffs_dev *dev, YCHAR *name,
3205                                     const YCHAR *oh_name, int buff_size)
3206 {
3207 #ifdef CONFIG_YAFFS_AUTO_UNICODE
3208         if (dev->param.auto_unicode) {
3209                 if (*oh_name) {
3210                         /* It is an ASCII name, do an ASCII to
3211                          * unicode conversion */
3212                         const char *ascii_oh_name = (const char *)oh_name;
3213                         int n = buff_size - 1;
3214                         while (n > 0 && *ascii_oh_name) {
3215                                 *name = *ascii_oh_name;
3216                                 name++;
3217                                 ascii_oh_name++;
3218                                 n--;
3219                         }
3220                 } else {
3221                         strncpy(name, oh_name + 1, buff_size - 1);
3222                 }
3223         } else {
3224 #else
3225         dev = dev;
3226         {
3227 #endif
3228                 strncpy(name, oh_name, buff_size - 1);
3229         }
3230 }
3231
3232 static void yaffs_load_oh_from_name(struct yaffs_dev *dev, YCHAR *oh_name,
3233                                     const YCHAR *name)
3234 {
3235 #ifdef CONFIG_YAFFS_AUTO_UNICODE
3236
3237         int is_ascii;
3238         YCHAR *w;
3239
3240         if (dev->param.auto_unicode) {
3241
3242                 is_ascii = 1;
3243                 w = name;
3244
3245                 /* Figure out if the name will fit in ascii character set */
3246                 while (is_ascii && *w) {
3247                         if ((*w) & 0xff00)
3248                                 is_ascii = 0;
3249                         w++;
3250                 }
3251
3252                 if (is_ascii) {
3253                         /* It is an ASCII name, so convert unicode to ascii */
3254                         char *ascii_oh_name = (char *)oh_name;
3255                         int n = YAFFS_MAX_NAME_LENGTH - 1;
3256                         while (n > 0 && *name) {
3257                                 *ascii_oh_name = *name;
3258                                 name++;
3259                                 ascii_oh_name++;
3260                                 n--;
3261                         }
3262                 } else {
3263                         /* Unicode name, so save starting at the second YCHAR */
3264                         *oh_name = 0;
3265                         strncpy(oh_name + 1, name, YAFFS_MAX_NAME_LENGTH - 2);
3266                 }
3267         } else {
3268 #else
3269         dev = dev;
3270         {
3271 #endif
3272                 strncpy(oh_name, name, YAFFS_MAX_NAME_LENGTH - 1);
3273         }
3274 }
3275
3276 /* UpdateObjectHeader updates the header on NAND for an object.
3277  * If name is not NULL, then that new name is used.
3278  */
3279 int yaffs_update_oh(struct yaffs_obj *in, const YCHAR *name, int force,
3280                     int is_shrink, int shadows, struct yaffs_xattr_mod *xmod)
3281 {
3282
3283         struct yaffs_block_info *bi;
3284         struct yaffs_dev *dev = in->my_dev;
3285         int prev_chunk_id;
3286         int ret_val = 0;
3287         int result = 0;
3288         int new_chunk_id;
3289         struct yaffs_ext_tags new_tags;
3290         struct yaffs_ext_tags old_tags;
3291         const YCHAR *alias = NULL;
3292         u8 *buffer = NULL;
3293         YCHAR old_name[YAFFS_MAX_NAME_LENGTH + 1];
3294         struct yaffs_obj_hdr *oh = NULL;
3295         loff_t file_size = 0;
3296
3297         strcpy(old_name, _Y("silly old name"));
3298
3299         if (in->fake && in != dev->root_dir && !force && !xmod)
3300                 return ret_val;
3301
3302         yaffs_check_gc(dev, 0);
3303         yaffs_check_obj_details_loaded(in);
3304
3305         buffer = yaffs_get_temp_buffer(in->my_dev);
3306         oh = (struct yaffs_obj_hdr *)buffer;
3307
3308         prev_chunk_id = in->hdr_chunk;
3309
3310         if (prev_chunk_id > 0) {
3311                 result = yaffs_rd_chunk_tags_nand(dev, prev_chunk_id,
3312                                                   buffer, &old_tags);
3313
3314                 yaffs_verify_oh(in, oh, &old_tags, 0);
3315                 memcpy(old_name, oh->name, sizeof(oh->name));
3316                 memset(buffer, 0xff, sizeof(struct yaffs_obj_hdr));
3317         } else {
3318                 memset(buffer, 0xff, dev->data_bytes_per_chunk);
3319         }
3320
3321         oh->type = in->variant_type;
3322         oh->yst_mode = in->yst_mode;
3323         oh->shadows_obj = oh->inband_shadowed_obj_id = shadows;
3324
3325         yaffs_load_attribs_oh(oh, in);
3326
3327         if (in->parent)
3328                 oh->parent_obj_id = in->parent->obj_id;
3329         else
3330                 oh->parent_obj_id = 0;
3331
3332         if (name && *name) {
3333                 memset(oh->name, 0, sizeof(oh->name));
3334                 yaffs_load_oh_from_name(dev, oh->name, name);
3335         } else if (prev_chunk_id > 0) {
3336                 memcpy(oh->name, old_name, sizeof(oh->name));
3337         } else {
3338                 memset(oh->name, 0, sizeof(oh->name));
3339         }
3340
3341         oh->is_shrink = is_shrink;
3342
3343         switch (in->variant_type) {
3344         case YAFFS_OBJECT_TYPE_UNKNOWN:
3345                 /* Should not happen */
3346                 break;
3347         case YAFFS_OBJECT_TYPE_FILE:
3348                 if (oh->parent_obj_id != YAFFS_OBJECTID_DELETED &&
3349                      oh->parent_obj_id != YAFFS_OBJECTID_UNLINKED)
3350                      file_size = in->variant.file_variant.file_size;
3351                 yaffs_oh_size_load(oh, file_size);
3352                 break;
3353         case YAFFS_OBJECT_TYPE_HARDLINK:
3354                 oh->equiv_id = in->variant.hardlink_variant.equiv_id;
3355                 break;
3356         case YAFFS_OBJECT_TYPE_SPECIAL:
3357                 /* Do nothing */
3358                 break;
3359         case YAFFS_OBJECT_TYPE_DIRECTORY:
3360                 /* Do nothing */
3361                 break;
3362         case YAFFS_OBJECT_TYPE_SYMLINK:
3363                 alias = in->variant.symlink_variant.alias;
3364                 if (!alias)
3365                         alias = _Y("no alias");
3366                 strncpy(oh->alias, alias, YAFFS_MAX_ALIAS_LENGTH);
3367                 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3368                 break;
3369         }
3370
3371         /* process any xattrib modifications */
3372         if (xmod)
3373                 yaffs_apply_xattrib_mod(in, (char *)buffer, xmod);
3374
3375         /* Tags */
3376         memset(&new_tags, 0, sizeof(new_tags));
3377         in->serial++;
3378         new_tags.chunk_id = 0;
3379         new_tags.obj_id = in->obj_id;
3380         new_tags.serial_number = in->serial;
3381
3382         /* Add extra info for file header */
3383         new_tags.extra_available = 1;
3384         new_tags.extra_parent_id = oh->parent_obj_id;
3385         new_tags.extra_file_size = file_size;
3386         new_tags.extra_is_shrink = oh->is_shrink;
3387         new_tags.extra_equiv_id = oh->equiv_id;
3388         new_tags.extra_shadows = (oh->shadows_obj > 0) ? 1 : 0;
3389         new_tags.extra_obj_type = in->variant_type;
3390         yaffs_verify_oh(in, oh, &new_tags, 1);
3391
3392         /* Create new chunk in NAND */
3393         new_chunk_id =
3394             yaffs_write_new_chunk(dev, buffer, &new_tags,
3395                                   (prev_chunk_id > 0) ? 1 : 0);
3396
3397         if (buffer)
3398                 yaffs_release_temp_buffer(dev, buffer);
3399
3400         if (new_chunk_id < 0)
3401                 return new_chunk_id;
3402
3403         in->hdr_chunk = new_chunk_id;
3404
3405         if (prev_chunk_id > 0)
3406                 yaffs_chunk_del(dev, prev_chunk_id, 1, __LINE__);
3407
3408         if (!yaffs_obj_cache_dirty(in))
3409                 in->dirty = 0;
3410
3411         /* If this was a shrink, then mark the block
3412          * that the chunk lives on */
3413         if (is_shrink) {
3414                 bi = yaffs_get_block_info(in->my_dev,
3415                                           new_chunk_id /
3416                                           in->my_dev->param.chunks_per_block);
3417                 bi->has_shrink_hdr = 1;
3418         }
3419
3420
3421         return