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