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