Merge branch 'master' of ssh://www.aleph1.co.uk/home/aleph1/git/yaffs2
[yaffs2.git] / yaffs_guts.c
1 /*
2  * YAFFS: Yet Another Flash File System. A NAND-flash specific file system.
3  *
4  * Copyright (C) 2002-2011 Aleph One Ltd.
5  *   for Toby Churchill Ltd and Brightstar Engineering
6  *
7  * Created by Charles Manning <charles@aleph1.co.uk>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License version 2 as
11  * published by the Free Software Foundation.
12  */
13
14 #include "yportenv.h"
15 #include "yaffs_trace.h"
16
17 #include "yaffs_guts.h"
18 #include "yaffs_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         unlink_op = (new_dir == obj->my_dev->unlinked_dir);
1348         del_op = (new_dir == obj->my_dev->del_dir);
1349
1350         existing_target = yaffs_find_by_name(new_dir, new_name);
1351
1352         /* If the object is a file going into the unlinked directory,
1353          *   then it is OK to just stuff it in since duplicate names are OK.
1354          *   else only proceed if the new name does not exist and we're putting
1355          *   it into a directory.
1356          */
1357         if (!(unlink_op || del_op || force ||
1358               shadows > 0 || !existing_target) ||
1359               new_dir->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY)
1360                 return YAFFS_FAIL;
1361
1362         yaffs_set_obj_name(obj, new_name);
1363         obj->dirty = 1;
1364         yaffs_add_obj_to_dir(new_dir, obj);
1365
1366         if (unlink_op)
1367                 obj->unlinked = 1;
1368
1369         /* If it is a deletion then we mark it as a shrink for gc  */
1370         if (yaffs_update_oh(obj, new_name, 0, del_op, shadows, NULL) >= 0)
1371                 return YAFFS_OK;
1372
1373         return YAFFS_FAIL;
1374 }
1375
1376 /*------------------------ Short Operations Cache ------------------------------
1377  *   In many situations where there is no high level buffering  a lot of
1378  *   reads might be short sequential reads, and a lot of writes may be short
1379  *   sequential writes. eg. scanning/writing a jpeg file.
1380  *   In these cases, a short read/write cache can provide a huge perfomance
1381  *   benefit with dumb-as-a-rock code.
1382  *   In Linux, the page cache provides read buffering and the short op cache
1383  *   provides write buffering.
1384  *
1385  *   There are a small number (~10) of cache chunks per device so that we don't
1386  *   need a very intelligent search.
1387  */
1388
1389 static int yaffs_obj_cache_dirty(struct yaffs_obj *obj)
1390 {
1391         struct yaffs_dev *dev = obj->my_dev;
1392         int i;
1393         struct yaffs_cache *cache;
1394         int n_caches = obj->my_dev->param.n_caches;
1395
1396         for (i = 0; i < n_caches; i++) {
1397                 cache = &dev->cache[i];
1398                 if (cache->object == obj && cache->dirty)
1399                         return 1;
1400         }
1401
1402         return 0;
1403 }
1404
1405 static void yaffs_flush_file_cache(struct yaffs_obj *obj)
1406 {
1407         struct yaffs_dev *dev = obj->my_dev;
1408         int lowest = -99;       /* Stop compiler whining. */
1409         int i;
1410         struct yaffs_cache *cache;
1411         int chunk_written = 0;
1412         int n_caches = obj->my_dev->param.n_caches;
1413
1414         if (n_caches < 1)
1415                 return;
1416         do {
1417                 cache = NULL;
1418
1419                 /* Find the lowest dirty chunk for this object */
1420                 for (i = 0; i < n_caches; i++) {
1421                         if (dev->cache[i].object == obj &&
1422                             dev->cache[i].dirty) {
1423                                 if (!cache ||
1424                                     dev->cache[i].chunk_id < lowest) {
1425                                         cache = &dev->cache[i];
1426                                         lowest = cache->chunk_id;
1427                                 }
1428                         }
1429                 }
1430
1431                 if (cache && !cache->locked) {
1432                         /* Write it out and free it up */
1433                         chunk_written =
1434                             yaffs_wr_data_obj(cache->object,
1435                                               cache->chunk_id,
1436                                               cache->data,
1437                                               cache->n_bytes, 1);
1438                         cache->dirty = 0;
1439                         cache->object = NULL;
1440                 }
1441         } while (cache && chunk_written > 0);
1442
1443         if (cache)
1444                 /* Hoosterman, disk full while writing cache out. */
1445                 yaffs_trace(YAFFS_TRACE_ERROR,
1446                         "yaffs tragedy: no space during cache write");
1447 }
1448
1449 /*yaffs_flush_whole_cache(dev)
1450  *
1451  *
1452  */
1453
1454 void yaffs_flush_whole_cache(struct yaffs_dev *dev)
1455 {
1456         struct yaffs_obj *obj;
1457         int n_caches = dev->param.n_caches;
1458         int i;
1459
1460         /* Find a dirty object in the cache and flush it...
1461          * until there are no further dirty objects.
1462          */
1463         do {
1464                 obj = NULL;
1465                 for (i = 0; i < n_caches && !obj; i++) {
1466                         if (dev->cache[i].object && dev->cache[i].dirty)
1467                                 obj = dev->cache[i].object;
1468                 }
1469                 if (obj)
1470                         yaffs_flush_file_cache(obj);
1471         } while (obj);
1472
1473 }
1474
1475 /* Grab us a cache chunk for use.
1476  * First look for an empty one.
1477  * Then look for the least recently used non-dirty one.
1478  * Then look for the least recently used dirty one...., flush and look again.
1479  */
1480 static struct yaffs_cache *yaffs_grab_chunk_worker(struct yaffs_dev *dev)
1481 {
1482         int i;
1483
1484         if (dev->param.n_caches > 0) {
1485                 for (i = 0; i < dev->param.n_caches; i++) {
1486                         if (!dev->cache[i].object)
1487                                 return &dev->cache[i];
1488                 }
1489         }
1490         return NULL;
1491 }
1492
1493 static struct yaffs_cache *yaffs_grab_chunk_cache(struct yaffs_dev *dev)
1494 {
1495         struct yaffs_cache *cache;
1496         struct yaffs_obj *the_obj;
1497         int usage;
1498         int i;
1499         int pushout;
1500
1501         if (dev->param.n_caches < 1)
1502                 return NULL;
1503
1504         /* Try find a non-dirty one... */
1505
1506         cache = yaffs_grab_chunk_worker(dev);
1507
1508         if (!cache) {
1509                 /* They were all dirty, find the LRU object and flush
1510                  * its cache, then  find again.
1511                  * NB what's here is not very accurate,
1512                  * we actually flush the object with the LRU chunk.
1513                  */
1514
1515                 /* With locking we can't assume we can use entry zero,
1516                  * Set the_obj to a valid pointer for Coverity. */
1517                 the_obj = dev->cache[0].object;
1518                 usage = -1;
1519                 cache = NULL;
1520                 pushout = -1;
1521
1522                 for (i = 0; i < dev->param.n_caches; i++) {
1523                         if (dev->cache[i].object &&
1524                             !dev->cache[i].locked &&
1525                             (dev->cache[i].last_use < usage ||
1526                             !cache)) {
1527                                 usage = dev->cache[i].last_use;
1528                                 the_obj = dev->cache[i].object;
1529                                 cache = &dev->cache[i];
1530                                 pushout = i;
1531                         }
1532                 }
1533
1534                 if (!cache || cache->dirty) {
1535                         /* Flush and try again */
1536                         yaffs_flush_file_cache(the_obj);
1537                         cache = yaffs_grab_chunk_worker(dev);
1538                 }
1539         }
1540         return cache;
1541 }
1542
1543 /* Find a cached chunk */
1544 static struct yaffs_cache *yaffs_find_chunk_cache(const struct yaffs_obj *obj,
1545                                                   int chunk_id)
1546 {
1547         struct yaffs_dev *dev = obj->my_dev;
1548         int i;
1549
1550         if (dev->param.n_caches < 1)
1551                 return NULL;
1552
1553         for (i = 0; i < dev->param.n_caches; i++) {
1554                 if (dev->cache[i].object == obj &&
1555                     dev->cache[i].chunk_id == chunk_id) {
1556                         dev->cache_hits++;
1557
1558                         return &dev->cache[i];
1559                 }
1560         }
1561         return NULL;
1562 }
1563
1564 /* Mark the chunk for the least recently used algorithym */
1565 static void yaffs_use_cache(struct yaffs_dev *dev, struct yaffs_cache *cache,
1566                             int is_write)
1567 {
1568         int i;
1569
1570         if (dev->param.n_caches < 1)
1571                 return;
1572
1573         if (dev->cache_last_use < 0 ||
1574                 dev->cache_last_use > 100000000) {
1575                 /* Reset the cache usages */
1576                 for (i = 1; i < dev->param.n_caches; i++)
1577                         dev->cache[i].last_use = 0;
1578
1579                 dev->cache_last_use = 0;
1580         }
1581         dev->cache_last_use++;
1582         cache->last_use = dev->cache_last_use;
1583
1584         if (is_write)
1585                 cache->dirty = 1;
1586 }
1587
1588 /* Invalidate a single cache page.
1589  * Do this when a whole page gets written,
1590  * ie the short cache for this page is no longer valid.
1591  */
1592 static void yaffs_invalidate_chunk_cache(struct yaffs_obj *object, int chunk_id)
1593 {
1594         struct yaffs_cache *cache;
1595
1596         if (object->my_dev->param.n_caches > 0) {
1597                 cache = yaffs_find_chunk_cache(object, chunk_id);
1598
1599                 if (cache)
1600                         cache->object = NULL;
1601         }
1602 }
1603
1604 /* Invalidate all the cache pages associated with this object
1605  * Do this whenever ther file is deleted or resized.
1606  */
1607 static void yaffs_invalidate_whole_cache(struct yaffs_obj *in)
1608 {
1609         int i;
1610         struct yaffs_dev *dev = in->my_dev;
1611
1612         if (dev->param.n_caches > 0) {
1613                 /* Invalidate it. */
1614                 for (i = 0; i < dev->param.n_caches; i++) {
1615                         if (dev->cache[i].object == in)
1616                                 dev->cache[i].object = NULL;
1617                 }
1618         }
1619 }
1620
1621 static void yaffs_unhash_obj(struct yaffs_obj *obj)
1622 {
1623         int bucket;
1624         struct yaffs_dev *dev = obj->my_dev;
1625
1626         /* If it is still linked into the bucket list, free from the list */
1627         if (!list_empty(&obj->hash_link)) {
1628                 list_del_init(&obj->hash_link);
1629                 bucket = yaffs_hash_fn(obj->obj_id);
1630                 dev->obj_bucket[bucket].count--;
1631         }
1632 }
1633
1634 /*  FreeObject frees up a Object and puts it back on the free list */
1635 static void yaffs_free_obj(struct yaffs_obj *obj)
1636 {
1637         struct yaffs_dev *dev;
1638
1639         if (!obj) {
1640                 BUG();
1641                 return;
1642         }
1643         dev = obj->my_dev;
1644         yaffs_trace(YAFFS_TRACE_OS, "FreeObject %p inode %p",
1645                 obj, obj->my_inode);
1646         if (obj->parent)
1647                 BUG();
1648         if (!list_empty(&obj->siblings))
1649                 BUG();
1650
1651         if (obj->my_inode) {
1652                 /* We're still hooked up to a cached inode.
1653                  * Don't delete now, but mark for later deletion
1654                  */
1655                 obj->defered_free = 1;
1656                 return;
1657         }
1658
1659         yaffs_unhash_obj(obj);
1660
1661         yaffs_free_raw_obj(dev, obj);
1662         dev->n_obj--;
1663         dev->checkpoint_blocks_required = 0;    /* force recalculation */
1664 }
1665
1666 void yaffs_handle_defered_free(struct yaffs_obj *obj)
1667 {
1668         if (obj->defered_free)
1669                 yaffs_free_obj(obj);
1670 }
1671
1672 static int yaffs_generic_obj_del(struct yaffs_obj *in)
1673 {
1674         /* Iinvalidate the file's data in the cache, without flushing. */
1675         yaffs_invalidate_whole_cache(in);
1676
1677         if (in->my_dev->param.is_yaffs2 && in->parent != in->my_dev->del_dir) {
1678                 /* Move to unlinked directory so we have a deletion record */
1679                 yaffs_change_obj_name(in, in->my_dev->del_dir, _Y("deleted"), 0,
1680                                       0);
1681         }
1682
1683         yaffs_remove_obj_from_dir(in);
1684         yaffs_chunk_del(in->my_dev, in->hdr_chunk, 1, __LINE__);
1685         in->hdr_chunk = 0;
1686
1687         yaffs_free_obj(in);
1688         return YAFFS_OK;
1689
1690 }
1691
1692 static void yaffs_soft_del_file(struct yaffs_obj *obj)
1693 {
1694         if (!obj->deleted ||
1695             obj->variant_type != YAFFS_OBJECT_TYPE_FILE ||
1696             obj->soft_del)
1697                 return;
1698
1699         if (obj->n_data_chunks <= 0) {
1700                 /* Empty file with no duplicate object headers,
1701                  * just delete it immediately */
1702                 yaffs_free_tnode(obj->my_dev, obj->variant.file_variant.top);
1703                 obj->variant.file_variant.top = NULL;
1704                 yaffs_trace(YAFFS_TRACE_TRACING,
1705                         "yaffs: Deleting empty file %d",
1706                         obj->obj_id);
1707                 yaffs_generic_obj_del(obj);
1708         } else {
1709                 yaffs_soft_del_worker(obj,
1710                                       obj->variant.file_variant.top,
1711                                       obj->variant.
1712                                       file_variant.top_level, 0);
1713                 obj->soft_del = 1;
1714         }
1715 }
1716
1717 /* Pruning removes any part of the file structure tree that is beyond the
1718  * bounds of the file (ie that does not point to chunks).
1719  *
1720  * A file should only get pruned when its size is reduced.
1721  *
1722  * Before pruning, the chunks must be pulled from the tree and the
1723  * level 0 tnode entries must be zeroed out.
1724  * Could also use this for file deletion, but that's probably better handled
1725  * by a special case.
1726  *
1727  * This function is recursive. For levels > 0 the function is called again on
1728  * any sub-tree. For level == 0 we just check if the sub-tree has data.
1729  * If there is no data in a subtree then it is pruned.
1730  */
1731
1732 static struct yaffs_tnode *yaffs_prune_worker(struct yaffs_dev *dev,
1733                                               struct yaffs_tnode *tn, u32 level,
1734                                               int del0)
1735 {
1736         int i;
1737         int has_data;
1738
1739         if (!tn)
1740                 return tn;
1741
1742         has_data = 0;
1743
1744         if (level > 0) {
1745                 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1746                         if (tn->internal[i]) {
1747                                 tn->internal[i] =
1748                                     yaffs_prune_worker(dev,
1749                                                 tn->internal[i],
1750                                                 level - 1,
1751                                                 (i == 0) ? del0 : 1);
1752                         }
1753
1754                         if (tn->internal[i])
1755                                 has_data++;
1756                 }
1757         } else {
1758                 int tnode_size_u32 = dev->tnode_size / sizeof(u32);
1759                 u32 *map = (u32 *) tn;
1760
1761                 for (i = 0; !has_data && i < tnode_size_u32; i++) {
1762                         if (map[i])
1763                                 has_data++;
1764                 }
1765         }
1766
1767         if (has_data == 0 && del0) {
1768                 /* Free and return NULL */
1769                 yaffs_free_tnode(dev, tn);
1770                 tn = NULL;
1771         }
1772         return tn;
1773 }
1774
1775 static int yaffs_prune_tree(struct yaffs_dev *dev,
1776                             struct yaffs_file_var *file_struct)
1777 {
1778         int i;
1779         int has_data;
1780         int done = 0;
1781         struct yaffs_tnode *tn;
1782
1783         if (file_struct->top_level < 1)
1784                 return YAFFS_OK;
1785
1786         file_struct->top =
1787            yaffs_prune_worker(dev, file_struct->top, file_struct->top_level, 0);
1788
1789         /* Now we have a tree with all the non-zero branches NULL but
1790          * the height is the same as it was.
1791          * Let's see if we can trim internal tnodes to shorten the tree.
1792          * We can do this if only the 0th element in the tnode is in use
1793          * (ie all the non-zero are NULL)
1794          */
1795
1796         while (file_struct->top_level && !done) {
1797                 tn = file_struct->top;
1798
1799                 has_data = 0;
1800                 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1801                         if (tn->internal[i])
1802                                 has_data++;
1803                 }
1804
1805                 if (!has_data) {
1806                         file_struct->top = tn->internal[0];
1807                         file_struct->top_level--;
1808                         yaffs_free_tnode(dev, tn);
1809                 } else {
1810                         done = 1;
1811                 }
1812         }
1813
1814         return YAFFS_OK;
1815 }
1816
1817 /*-------------------- End of File Structure functions.-------------------*/
1818
1819 /* alloc_empty_obj gets us a clean Object.*/
1820 static struct yaffs_obj *yaffs_alloc_empty_obj(struct yaffs_dev *dev)
1821 {
1822         struct yaffs_obj *obj = yaffs_alloc_raw_obj(dev);
1823
1824         if (!obj)
1825                 return obj;
1826
1827         dev->n_obj++;
1828
1829         /* Now sweeten it up... */
1830
1831         memset(obj, 0, sizeof(struct yaffs_obj));
1832         obj->being_created = 1;
1833
1834         obj->my_dev = dev;
1835         obj->hdr_chunk = 0;
1836         obj->variant_type = YAFFS_OBJECT_TYPE_UNKNOWN;
1837         INIT_LIST_HEAD(&(obj->hard_links));
1838         INIT_LIST_HEAD(&(obj->hash_link));
1839         INIT_LIST_HEAD(&obj->siblings);
1840
1841         /* Now make the directory sane */
1842         if (dev->root_dir) {
1843                 obj->parent = dev->root_dir;
1844                 list_add(&(obj->siblings),
1845                          &dev->root_dir->variant.dir_variant.children);
1846         }
1847
1848         /* Add it to the lost and found directory.
1849          * NB Can't put root or lost-n-found in lost-n-found so
1850          * check if lost-n-found exists first
1851          */
1852         if (dev->lost_n_found)
1853                 yaffs_add_obj_to_dir(dev->lost_n_found, obj);
1854
1855         obj->being_created = 0;
1856
1857         dev->checkpoint_blocks_required = 0;    /* force recalculation */
1858
1859         return obj;
1860 }
1861
1862 static int yaffs_find_nice_bucket(struct yaffs_dev *dev)
1863 {
1864         int i;
1865         int l = 999;
1866         int lowest = 999999;
1867
1868         /* Search for the shortest list or one that
1869          * isn't too long.
1870          */
1871
1872         for (i = 0; i < 10 && lowest > 4; i++) {
1873                 dev->bucket_finder++;
1874                 dev->bucket_finder %= YAFFS_NOBJECT_BUCKETS;
1875                 if (dev->obj_bucket[dev->bucket_finder].count < lowest) {
1876                         lowest = dev->obj_bucket[dev->bucket_finder].count;
1877                         l = dev->bucket_finder;
1878                 }
1879         }
1880
1881         return l;
1882 }
1883
1884 static int yaffs_new_obj_id(struct yaffs_dev *dev)
1885 {
1886         int bucket = yaffs_find_nice_bucket(dev);
1887         int found = 0;
1888         struct list_head *i;
1889         u32 n = (u32) bucket;
1890
1891         /* Now find an object value that has not already been taken
1892          * by scanning the list.
1893          */
1894
1895         while (!found) {
1896                 found = 1;
1897                 n += YAFFS_NOBJECT_BUCKETS;
1898                 if (1 || dev->obj_bucket[bucket].count > 0) {
1899                         list_for_each(i, &dev->obj_bucket[bucket].list) {
1900                                 /* If there is already one in the list */
1901                                 if (i && list_entry(i, struct yaffs_obj,
1902                                                     hash_link)->obj_id == n) {
1903                                         found = 0;
1904                                 }
1905                         }
1906                 }
1907         }
1908         return n;
1909 }
1910
1911 static void yaffs_hash_obj(struct yaffs_obj *in)
1912 {
1913         int bucket = yaffs_hash_fn(in->obj_id);
1914         struct yaffs_dev *dev = in->my_dev;
1915
1916         list_add(&in->hash_link, &dev->obj_bucket[bucket].list);
1917         dev->obj_bucket[bucket].count++;
1918 }
1919
1920 struct yaffs_obj *yaffs_find_by_number(struct yaffs_dev *dev, u32 number)
1921 {
1922         int bucket = yaffs_hash_fn(number);
1923         struct list_head *i;
1924         struct yaffs_obj *in;
1925
1926         list_for_each(i, &dev->obj_bucket[bucket].list) {
1927                 /* Look if it is in the list */
1928                 in = list_entry(i, struct yaffs_obj, hash_link);
1929                 if (in->obj_id == number) {
1930                         /* Don't show if it is defered free */
1931                         if (in->defered_free)
1932                                 return NULL;
1933                         return in;
1934                 }
1935         }
1936
1937         return NULL;
1938 }
1939
1940 struct yaffs_obj *yaffs_new_obj(struct yaffs_dev *dev, int number,
1941                                 enum yaffs_obj_type type)
1942 {
1943         struct yaffs_obj *the_obj = NULL;
1944         struct yaffs_tnode *tn = NULL;
1945
1946         if (number < 0)
1947                 number = yaffs_new_obj_id(dev);
1948
1949         if (type == YAFFS_OBJECT_TYPE_FILE) {
1950                 tn = yaffs_get_tnode(dev);
1951                 if (!tn)
1952                         return NULL;
1953         }
1954
1955         the_obj = yaffs_alloc_empty_obj(dev);
1956         if (!the_obj) {
1957                 if (tn)
1958                         yaffs_free_tnode(dev, tn);
1959                 return NULL;
1960         }
1961
1962         the_obj->fake = 0;
1963         the_obj->rename_allowed = 1;
1964         the_obj->unlink_allowed = 1;
1965         the_obj->obj_id = number;
1966         yaffs_hash_obj(the_obj);
1967         the_obj->variant_type = type;
1968         yaffs_load_current_time(the_obj, 1, 1);
1969
1970         switch (type) {
1971         case YAFFS_OBJECT_TYPE_FILE:
1972                 the_obj->variant.file_variant.file_size = 0;
1973                 the_obj->variant.file_variant.scanned_size = 0;
1974                 the_obj->variant.file_variant.shrink_size = ~0; /* max */
1975                 the_obj->variant.file_variant.top_level = 0;
1976                 the_obj->variant.file_variant.top = tn;
1977                 break;
1978         case YAFFS_OBJECT_TYPE_DIRECTORY:
1979                 INIT_LIST_HEAD(&the_obj->variant.dir_variant.children);
1980                 INIT_LIST_HEAD(&the_obj->variant.dir_variant.dirty);
1981                 break;
1982         case YAFFS_OBJECT_TYPE_SYMLINK:
1983         case YAFFS_OBJECT_TYPE_HARDLINK:
1984         case YAFFS_OBJECT_TYPE_SPECIAL:
1985                 /* No action required */
1986                 break;
1987         case YAFFS_OBJECT_TYPE_UNKNOWN:
1988                 /* todo this should not happen */
1989                 break;
1990         }
1991         return the_obj;
1992 }
1993
1994 static struct yaffs_obj *yaffs_create_fake_dir(struct yaffs_dev *dev,
1995                                                int number, u32 mode)
1996 {
1997
1998         struct yaffs_obj *obj =
1999             yaffs_new_obj(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
2000
2001         if (!obj)
2002                 return NULL;
2003
2004         obj->fake = 1;  /* it is fake so it might not use NAND */
2005         obj->rename_allowed = 0;
2006         obj->unlink_allowed = 0;
2007         obj->deleted = 0;
2008         obj->unlinked = 0;
2009         obj->yst_mode = mode;
2010         obj->my_dev = dev;
2011         obj->hdr_chunk = 0;     /* Not a valid chunk. */
2012         return obj;
2013
2014 }
2015
2016
2017 static void yaffs_init_tnodes_and_objs(struct yaffs_dev *dev)
2018 {
2019         int i;
2020
2021         dev->n_obj = 0;
2022         dev->n_tnodes = 0;
2023         yaffs_init_raw_tnodes_and_objs(dev);
2024
2025         for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2026                 INIT_LIST_HEAD(&dev->obj_bucket[i].list);
2027                 dev->obj_bucket[i].count = 0;
2028         }
2029 }
2030
2031 struct yaffs_obj *yaffs_find_or_create_by_number(struct yaffs_dev *dev,
2032                                                  int number,
2033                                                  enum yaffs_obj_type type)
2034 {
2035         struct yaffs_obj *the_obj = NULL;
2036
2037         if (number > 0)
2038                 the_obj = yaffs_find_by_number(dev, number);
2039
2040         if (!the_obj)
2041                 the_obj = yaffs_new_obj(dev, number, type);
2042
2043         return the_obj;
2044
2045 }
2046
2047 YCHAR *yaffs_clone_str(const YCHAR *str)
2048 {
2049         YCHAR *new_str = NULL;
2050         int len;
2051
2052         if (!str)
2053                 str = _Y("");
2054
2055         len = strnlen(str, YAFFS_MAX_ALIAS_LENGTH);
2056         new_str = kmalloc((len + 1) * sizeof(YCHAR), GFP_NOFS);
2057         if (new_str) {
2058                 strncpy(new_str, str, len);
2059                 new_str[len] = 0;
2060         }
2061         return new_str;
2062
2063 }
2064 /*
2065  *yaffs_update_parent() handles fixing a directories mtime and ctime when a new
2066  * link (ie. name) is created or deleted in the directory.
2067  *
2068  * ie.
2069  *   create dir/a : update dir's mtime/ctime
2070  *   rm dir/a:   update dir's mtime/ctime
2071  *   modify dir/a: don't update dir's mtimme/ctime
2072  *
2073  * This can be handled immediately or defered. Defering helps reduce the number
2074  * of updates when many files in a directory are changed within a brief period.
2075  *
2076  * If the directory updating is defered then yaffs_update_dirty_dirs must be
2077  * called periodically.
2078  */
2079
2080 static void yaffs_update_parent(struct yaffs_obj *obj)
2081 {
2082         struct yaffs_dev *dev;
2083
2084         if (!obj)
2085                 return;
2086         dev = obj->my_dev;
2087         obj->dirty = 1;
2088         yaffs_load_current_time(obj, 0, 1);
2089         if (dev->param.defered_dir_update) {
2090                 struct list_head *link = &obj->variant.dir_variant.dirty;
2091
2092                 if (list_empty(link)) {
2093                         list_add(link, &dev->dirty_dirs);
2094                         yaffs_trace(YAFFS_TRACE_BACKGROUND,
2095                           "Added object %d to dirty directories",
2096                            obj->obj_id);
2097                 }
2098
2099         } else {
2100                 yaffs_update_oh(obj, NULL, 0, 0, 0, NULL);
2101         }
2102 }
2103
2104 void yaffs_update_dirty_dirs(struct yaffs_dev *dev)
2105 {
2106         struct list_head *link;
2107         struct yaffs_obj *obj;
2108         struct yaffs_dir_var *d_s;
2109         union yaffs_obj_var *o_v;
2110
2111         yaffs_trace(YAFFS_TRACE_BACKGROUND, "Update dirty directories");
2112
2113         while (!list_empty(&dev->dirty_dirs)) {
2114                 link = dev->dirty_dirs.next;
2115                 list_del_init(link);
2116
2117                 d_s = list_entry(link, struct yaffs_dir_var, dirty);
2118                 o_v = list_entry(d_s, union yaffs_obj_var, dir_variant);
2119                 obj = list_entry(o_v, struct yaffs_obj, variant);
2120
2121                 yaffs_trace(YAFFS_TRACE_BACKGROUND, "Update directory %d",
2122                         obj->obj_id);
2123
2124                 if (obj->dirty)
2125                         yaffs_update_oh(obj, NULL, 0, 0, 0, NULL);
2126         }
2127 }
2128
2129 /*
2130  * Mknod (create) a new object.
2131  * equiv_obj only has meaning for a hard link;
2132  * alias_str only has meaning for a symlink.
2133  * rdev only has meaning for devices (a subset of special objects)
2134  */
2135
2136 static struct yaffs_obj *yaffs_create_obj(enum yaffs_obj_type type,
2137                                           struct yaffs_obj *parent,
2138                                           const YCHAR *name,
2139                                           u32 mode,
2140                                           u32 uid,
2141                                           u32 gid,
2142                                           struct yaffs_obj *equiv_obj,
2143                                           const YCHAR *alias_str, u32 rdev)
2144 {
2145         struct yaffs_obj *in;
2146         YCHAR *str = NULL;
2147         struct yaffs_dev *dev = parent->my_dev;
2148
2149         /* Check if the entry exists.
2150          * If it does then fail the call since we don't want a dup. */
2151         if (yaffs_find_by_name(parent, name))
2152                 return NULL;
2153
2154         if (type == YAFFS_OBJECT_TYPE_SYMLINK) {
2155                 str = yaffs_clone_str(alias_str);
2156                 if (!str)
2157                         return NULL;
2158         }
2159
2160         in = yaffs_new_obj(dev, -1, type);
2161
2162         if (!in) {
2163                 kfree(str);
2164                 return NULL;
2165         }
2166
2167         in->hdr_chunk = 0;
2168         in->valid = 1;
2169         in->variant_type = type;
2170
2171         in->yst_mode = mode;
2172
2173         yaffs_attribs_init(in, gid, uid, rdev);
2174
2175         in->n_data_chunks = 0;
2176
2177         yaffs_set_obj_name(in, name);
2178         in->dirty = 1;
2179
2180         yaffs_add_obj_to_dir(parent, in);
2181
2182         in->my_dev = parent->my_dev;
2183
2184         switch (type) {
2185         case YAFFS_OBJECT_TYPE_SYMLINK:
2186                 in->variant.symlink_variant.alias = str;
2187                 break;
2188         case YAFFS_OBJECT_TYPE_HARDLINK:
2189                 in->variant.hardlink_variant.equiv_obj = equiv_obj;
2190                 in->variant.hardlink_variant.equiv_id = equiv_obj->obj_id;
2191                 list_add(&in->hard_links, &equiv_obj->hard_links);
2192                 break;
2193         case YAFFS_OBJECT_TYPE_FILE:
2194         case YAFFS_OBJECT_TYPE_DIRECTORY:
2195         case YAFFS_OBJECT_TYPE_SPECIAL:
2196         case YAFFS_OBJECT_TYPE_UNKNOWN:
2197                 /* do nothing */
2198                 break;
2199         }
2200
2201         if (yaffs_update_oh(in, name, 0, 0, 0, NULL) < 0) {
2202                 /* Could not create the object header, fail */
2203                 yaffs_del_obj(in);
2204                 in = NULL;
2205         }
2206
2207         if (in)
2208                 yaffs_update_parent(parent);
2209
2210         return in;
2211 }
2212
2213 struct yaffs_obj *yaffs_create_file(struct yaffs_obj *parent,
2214                                     const YCHAR *name, u32 mode, u32 uid,
2215                                     u32 gid)
2216 {
2217         return yaffs_create_obj(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2218                                 uid, gid, NULL, NULL, 0);
2219 }
2220
2221 struct yaffs_obj *yaffs_create_dir(struct yaffs_obj *parent, const YCHAR *name,
2222                                    u32 mode, u32 uid, u32 gid)
2223 {
2224         return yaffs_create_obj(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2225                                 mode, uid, gid, NULL, NULL, 0);
2226 }
2227
2228 struct yaffs_obj *yaffs_create_special(struct yaffs_obj *parent,
2229                                        const YCHAR *name, u32 mode, u32 uid,
2230                                        u32 gid, u32 rdev)
2231 {
2232         return yaffs_create_obj(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2233                                 uid, gid, NULL, NULL, rdev);
2234 }
2235
2236 struct yaffs_obj *yaffs_create_symlink(struct yaffs_obj *parent,
2237                                        const YCHAR *name, u32 mode, u32 uid,
2238                                        u32 gid, const YCHAR *alias)
2239 {
2240         return yaffs_create_obj(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2241                                 uid, gid, NULL, alias, 0);
2242 }
2243
2244 /* yaffs_link_obj returns the object id of the equivalent object.*/
2245 struct yaffs_obj *yaffs_link_obj(struct yaffs_obj *parent, const YCHAR * name,
2246                                  struct yaffs_obj *equiv_obj)
2247 {
2248         /* Get the real object in case we were fed a hard link obj */
2249         equiv_obj = yaffs_get_equivalent_obj(equiv_obj);
2250
2251         if (yaffs_create_obj(YAFFS_OBJECT_TYPE_HARDLINK,
2252                         parent, name, 0, 0, 0,
2253                         equiv_obj, NULL, 0))
2254                 return equiv_obj;
2255
2256         return NULL;
2257
2258 }
2259
2260
2261
2262 /*---------------------- Block Management and Page Allocation -------------*/
2263
2264 static void yaffs_deinit_blocks(struct yaffs_dev *dev)
2265 {
2266         if (dev->block_info_alt && dev->block_info)
2267                 vfree(dev->block_info);
2268         else
2269                 kfree(dev->block_info);
2270
2271         dev->block_info_alt = 0;
2272
2273         dev->block_info = NULL;
2274
2275         if (dev->chunk_bits_alt && dev->chunk_bits)
2276                 vfree(dev->chunk_bits);
2277         else
2278                 kfree(dev->chunk_bits);
2279         dev->chunk_bits_alt = 0;
2280         dev->chunk_bits = NULL;
2281 }
2282
2283 static int yaffs_init_blocks(struct yaffs_dev *dev)
2284 {
2285         int n_blocks = dev->internal_end_block - dev->internal_start_block + 1;
2286
2287         dev->block_info = NULL;
2288         dev->chunk_bits = NULL;
2289         dev->alloc_block = -1;  /* force it to get a new one */
2290
2291         /* If the first allocation strategy fails, thry the alternate one */
2292         dev->block_info =
2293                 kmalloc(n_blocks * sizeof(struct yaffs_block_info), GFP_NOFS);
2294         if (!dev->block_info) {
2295                 dev->block_info =
2296                     vmalloc(n_blocks * sizeof(struct yaffs_block_info));
2297                 dev->block_info_alt = 1;
2298         } else {
2299                 dev->block_info_alt = 0;
2300         }
2301
2302         if (!dev->block_info)
2303                 goto alloc_error;
2304
2305         /* Set up dynamic blockinfo stuff. Round up bytes. */
2306         dev->chunk_bit_stride = (dev->param.chunks_per_block + 7) / 8;
2307         dev->chunk_bits =
2308                 kmalloc(dev->chunk_bit_stride * n_blocks, GFP_NOFS);
2309         if (!dev->chunk_bits) {
2310                 dev->chunk_bits =
2311                     vmalloc(dev->chunk_bit_stride * n_blocks);
2312                 dev->chunk_bits_alt = 1;
2313         } else {
2314                 dev->chunk_bits_alt = 0;
2315         }
2316         if (!dev->chunk_bits)
2317                 goto alloc_error;
2318
2319
2320         memset(dev->block_info, 0, n_blocks * sizeof(struct yaffs_block_info));
2321         memset(dev->chunk_bits, 0, dev->chunk_bit_stride * n_blocks);
2322         return YAFFS_OK;
2323
2324 alloc_error:
2325         yaffs_deinit_blocks(dev);
2326         return YAFFS_FAIL;
2327 }
2328
2329
2330 void yaffs_block_became_dirty(struct yaffs_dev *dev, int block_no)
2331 {
2332         struct yaffs_block_info *bi = yaffs_get_block_info(dev, block_no);
2333         int erased_ok = 0;
2334         int i;
2335
2336         /* If the block is still healthy erase it and mark as clean.
2337          * If the block has had a data failure, then retire it.
2338          */
2339
2340         yaffs_trace(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2341                 "yaffs_block_became_dirty block %d state %d %s",
2342                 block_no, bi->block_state,
2343                 (bi->needs_retiring) ? "needs retiring" : "");
2344
2345         yaffs2_clear_oldest_dirty_seq(dev, bi);
2346
2347         bi->block_state = YAFFS_BLOCK_STATE_DIRTY;
2348
2349         /* If this is the block being garbage collected then stop gc'ing */
2350         if (block_no == dev->gc_block)
2351                 dev->gc_block = 0;
2352
2353         /* If this block is currently the best candidate for gc
2354          * then drop as a candidate */
2355         if (block_no == dev->gc_dirtiest) {
2356                 dev->gc_dirtiest = 0;
2357                 dev->gc_pages_in_use = 0;
2358         }
2359
2360         if (!bi->needs_retiring) {
2361                 yaffs2_checkpt_invalidate(dev);
2362                 erased_ok = yaffs_erase_block(dev, block_no);
2363                 if (!erased_ok) {
2364                         dev->n_erase_failures++;
2365                         yaffs_trace(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2366                           "**>> Erasure failed %d", block_no);
2367                 }
2368         }
2369
2370         /* Verify erasure if needed */
2371         if (erased_ok &&
2372             ((yaffs_trace_mask & YAFFS_TRACE_ERASE) ||
2373              !yaffs_skip_verification(dev))) {
2374                 for (i = 0; i < dev->param.chunks_per_block; i++) {
2375                         if (!yaffs_check_chunk_erased(dev,
2376                                 block_no * dev->param.chunks_per_block + i)) {
2377                                 yaffs_trace(YAFFS_TRACE_ERROR,
2378                                         ">>Block %d erasure supposedly OK, but chunk %d not erased",
2379                                         block_no, i);
2380                         }
2381                 }
2382         }
2383
2384         if (!erased_ok) {
2385                 /* We lost a block of free space */
2386                 dev->n_free_chunks -= dev->param.chunks_per_block;
2387                 yaffs_retire_block(dev, block_no);
2388                 yaffs_trace(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2389                         "**>> Block %d retired", block_no);
2390                 return;
2391         }
2392
2393         /* Clean it up... */
2394         bi->block_state = YAFFS_BLOCK_STATE_EMPTY;
2395         bi->seq_number = 0;
2396         dev->n_erased_blocks++;
2397         bi->pages_in_use = 0;
2398         bi->soft_del_pages = 0;
2399         bi->has_shrink_hdr = 0;
2400         bi->skip_erased_check = 1;      /* Clean, so no need to check */
2401         bi->gc_prioritise = 0;
2402         yaffs_clear_chunk_bits(dev, block_no);
2403
2404         yaffs_trace(YAFFS_TRACE_ERASE, "Erased block %d", block_no);
2405 }
2406
2407 static inline int yaffs_gc_process_chunk(struct yaffs_dev *dev,
2408                                         struct yaffs_block_info *bi,
2409                                         int old_chunk, u8 *buffer)
2410 {
2411         int new_chunk;
2412         int mark_flash = 1;
2413         struct yaffs_ext_tags tags;
2414         struct yaffs_obj *object;
2415         int matching_chunk;
2416         int ret_val = YAFFS_OK;
2417
2418         yaffs_init_tags(&tags);
2419         yaffs_rd_chunk_tags_nand(dev, old_chunk,
2420                                  buffer, &tags);
2421         object = yaffs_find_by_number(dev, tags.obj_id);
2422
2423         yaffs_trace(YAFFS_TRACE_GC_DETAIL,
2424                 "Collecting chunk in block %d, %d %d %d ",
2425                 dev->gc_chunk, tags.obj_id,
2426                 tags.chunk_id, tags.n_bytes);
2427
2428         if (object && !yaffs_skip_verification(dev)) {
2429                 if (tags.chunk_id == 0)
2430                         matching_chunk =
2431                             object->hdr_chunk;
2432                 else if (object->soft_del)
2433                         /* Defeat the test */
2434                         matching_chunk = old_chunk;
2435                 else
2436                         matching_chunk =
2437                             yaffs_find_chunk_in_file
2438                             (object, tags.chunk_id,
2439                              NULL);
2440
2441                 if (old_chunk != matching_chunk)
2442                         yaffs_trace(YAFFS_TRACE_ERROR,
2443                                 "gc: page in gc mismatch: %d %d %d %d",
2444                                 old_chunk,
2445                                 matching_chunk,
2446                                 tags.obj_id,
2447                                 tags.chunk_id);
2448         }
2449
2450         if (!object) {
2451                 yaffs_trace(YAFFS_TRACE_ERROR,
2452                         "page %d in gc has no object: %d %d %d ",
2453                         old_chunk,
2454                         tags.obj_id, tags.chunk_id,
2455                         tags.n_bytes);
2456         }
2457
2458         if (object &&
2459             object->deleted &&
2460             object->soft_del && tags.chunk_id != 0) {
2461                 /* Data chunk in a soft deleted file,
2462                  * throw it away.
2463                  * It's a soft deleted data chunk,
2464                  * No need to copy this, just forget
2465                  * about it and fix up the object.
2466                  */
2467
2468                 /* Free chunks already includes
2469                  * softdeleted chunks, how ever this
2470                  * chunk is going to soon be really
2471                  * deleted which will increment free
2472                  * chunks. We have to decrement free
2473                  * chunks so this works out properly.
2474                  */
2475                 dev->n_free_chunks--;
2476                 bi->soft_del_pages--;
2477
2478                 object->n_data_chunks--;
2479                 if (object->n_data_chunks <= 0) {
2480                         /* remeber to clean up obj */
2481                         dev->gc_cleanup_list[dev->n_clean_ups] = tags.obj_id;
2482                         dev->n_clean_ups++;
2483                 }
2484                 mark_flash = 0;
2485         } else if (object) {
2486                 /* It's either a data chunk in a live
2487                  * file or an ObjectHeader, so we're
2488                  * interested in it.
2489                  * NB Need to keep the ObjectHeaders of
2490                  * deleted files until the whole file
2491                  * has been deleted off
2492                  */
2493                 tags.serial_number++;
2494                 dev->n_gc_copies++;
2495
2496                 if (tags.chunk_id == 0) {
2497                         /* It is an object Id,
2498                          * We need to nuke the
2499                          * shrinkheader flags since its
2500                          * work is done.
2501                          * Also need to clean up
2502                          * shadowing.
2503                          */
2504                         struct yaffs_obj_hdr *oh;
2505                         oh = (struct yaffs_obj_hdr *) buffer;
2506
2507                         oh->is_shrink = 0;
2508                         tags.extra_is_shrink = 0;
2509                         oh->shadows_obj = 0;
2510                         oh->inband_shadowed_obj_id = 0;
2511                         tags.extra_shadows = 0;
2512
2513                         /* Update file size */
2514                         if (object->variant_type == YAFFS_OBJECT_TYPE_FILE) {
2515                                 oh->file_size =
2516                                     object->variant.file_variant.file_size;
2517                                 tags.extra_length = oh->file_size;
2518                         }
2519
2520                         yaffs_verify_oh(object, oh, &tags, 1);
2521                         new_chunk =
2522                             yaffs_write_new_chunk(dev, (u8 *) oh, &tags, 1);
2523                 } else {
2524                         new_chunk =
2525                             yaffs_write_new_chunk(dev, buffer, &tags, 1);
2526                 }
2527
2528                 if (new_chunk < 0) {
2529                         ret_val = YAFFS_FAIL;
2530                 } else {
2531
2532                         /* Now fix up the Tnodes etc. */
2533
2534                         if (tags.chunk_id == 0) {
2535                                 /* It's a header */
2536                                 object->hdr_chunk = new_chunk;
2537                                 object->serial = tags.serial_number;
2538                         } else {
2539                                 /* It's a data chunk */
2540                                 yaffs_put_chunk_in_file(object, tags.chunk_id,
2541                                                         new_chunk, 0);
2542                         }
2543                 }
2544         }
2545         if (ret_val == YAFFS_OK)
2546                 yaffs_chunk_del(dev, old_chunk, mark_flash, __LINE__);
2547         return ret_val;
2548 }
2549
2550 static int yaffs_gc_block(struct yaffs_dev *dev, int block, int whole_block)
2551 {
2552         int old_chunk;
2553         int ret_val = YAFFS_OK;
2554         int i;
2555         int is_checkpt_block;
2556         int max_copies;
2557         int chunks_before = yaffs_get_erased_chunks(dev);
2558         int chunks_after;
2559         struct yaffs_block_info *bi = yaffs_get_block_info(dev, block);
2560
2561         is_checkpt_block = (bi->block_state == YAFFS_BLOCK_STATE_CHECKPOINT);
2562
2563         yaffs_trace(YAFFS_TRACE_TRACING,
2564                 "Collecting block %d, in use %d, shrink %d, whole_block %d",
2565                 block, bi->pages_in_use, bi->has_shrink_hdr,
2566                 whole_block);
2567
2568         /*yaffs_verify_free_chunks(dev); */
2569
2570         if (bi->block_state == YAFFS_BLOCK_STATE_FULL)
2571                 bi->block_state = YAFFS_BLOCK_STATE_COLLECTING;
2572
2573         bi->has_shrink_hdr = 0; /* clear the flag so that the block can erase */
2574
2575         dev->gc_disable = 1;
2576
2577         if (is_checkpt_block || !yaffs_still_some_chunks(dev, block)) {
2578                 yaffs_trace(YAFFS_TRACE_TRACING,
2579                         "Collecting block %d that has no chunks in use",
2580                         block);
2581                 yaffs_block_became_dirty(dev, block);
2582         } else {
2583
2584                 u8 *buffer = yaffs_get_temp_buffer(dev, __LINE__);
2585
2586                 yaffs_verify_blk(dev, bi, block);
2587
2588                 max_copies = (whole_block) ? dev->param.chunks_per_block : 5;
2589                 old_chunk = block * dev->param.chunks_per_block + dev->gc_chunk;
2590
2591                 for (/* init already done */ ;
2592                      ret_val == YAFFS_OK &&
2593                      dev->gc_chunk < dev->param.chunks_per_block &&
2594                      (bi->block_state == YAFFS_BLOCK_STATE_COLLECTING) &&
2595                      max_copies > 0;
2596                      dev->gc_chunk++, old_chunk++) {
2597                         if (yaffs_check_chunk_bit(dev, block, dev->gc_chunk)) {
2598                                 /* Page is in use and might need to be copied */
2599                                 max_copies--;
2600                                 ret_val = yaffs_gc_process_chunk(dev, bi,
2601                                                         old_chunk, buffer);
2602                         }
2603                 }
2604                 yaffs_release_temp_buffer(dev, buffer, __LINE__);
2605         }
2606
2607         yaffs_verify_collected_blk(dev, bi, block);
2608
2609         if (bi->block_state == YAFFS_BLOCK_STATE_COLLECTING) {
2610                 /*
2611                  * The gc did not complete. Set block state back to FULL
2612                  * because checkpointing does not restore gc.
2613                  */
2614                 bi->block_state = YAFFS_BLOCK_STATE_FULL;
2615         } else {
2616                 /* The gc completed. */
2617                 /* Do any required cleanups */
2618                 for (i = 0; i < dev->n_clean_ups; i++) {
2619                         /* Time to delete the file too */
2620                         struct yaffs_obj *object =
2621                             yaffs_find_by_number(dev, dev->gc_cleanup_list[i]);
2622                         if (object) {
2623                                 yaffs_free_tnode(dev,
2624                                           object->variant.file_variant.top);
2625                                 object->variant.file_variant.top = NULL;
2626                                 yaffs_trace(YAFFS_TRACE_GC,
2627                                         "yaffs: About to finally delete object %d",
2628                                         object->obj_id);
2629                                 yaffs_generic_obj_del(object);
2630                                 object->my_dev->n_deleted_files--;
2631                         }
2632
2633                 }
2634                 chunks_after = yaffs_get_erased_chunks(dev);
2635                 if (chunks_before >= chunks_after)
2636                         yaffs_trace(YAFFS_TRACE_GC,
2637                                 "gc did not increase free chunks before %d after %d",
2638                                 chunks_before, chunks_after);
2639                 dev->gc_block = 0;
2640                 dev->gc_chunk = 0;
2641                 dev->n_clean_ups = 0;
2642         }
2643
2644         dev->gc_disable = 0;
2645
2646         return ret_val;
2647 }
2648
2649 /*
2650  * find_gc_block() selects the dirtiest block (or close enough)
2651  * for garbage collection.
2652  */
2653
2654 static unsigned yaffs_find_gc_block(struct yaffs_dev *dev,
2655                                     int aggressive, int background)
2656 {
2657         int i;
2658         int iterations;
2659         unsigned selected = 0;
2660         int prioritised = 0;
2661         int prioritised_exist = 0;
2662         struct yaffs_block_info *bi;
2663         int threshold;
2664
2665         /* First let's see if we need to grab a prioritised block */
2666         if (dev->has_pending_prioritised_gc && !aggressive) {
2667                 dev->gc_dirtiest = 0;
2668                 bi = dev->block_info;
2669                 for (i = dev->internal_start_block;
2670                      i <= dev->internal_end_block && !selected; i++) {
2671
2672                         if (bi->gc_prioritise) {
2673                                 prioritised_exist = 1;
2674                                 if (bi->block_state == YAFFS_BLOCK_STATE_FULL &&
2675                                     yaffs_block_ok_for_gc(dev, bi)) {
2676                                         selected = i;
2677                                         prioritised = 1;
2678                                 }
2679                         }
2680                         bi++;
2681                 }
2682
2683                 /*
2684                  * If there is a prioritised block and none was selected then
2685                  * this happened because there is at least one old dirty block
2686                  * gumming up the works. Let's gc the oldest dirty block.
2687                  */
2688
2689                 if (prioritised_exist &&
2690                     !selected && dev->oldest_dirty_block > 0)
2691                         selected = dev->oldest_dirty_block;
2692
2693                 if (!prioritised_exist) /* None found, so we can clear this */
2694                         dev->has_pending_prioritised_gc = 0;
2695         }
2696
2697         /* If we're doing aggressive GC then we are happy to take a less-dirty
2698          * block, and search harder.
2699          * else (leasurely gc), then we only bother to do this if the
2700          * block has only a few pages in use.
2701          */
2702
2703         if (!selected) {
2704                 int pages_used;
2705                 int n_blocks =
2706                     dev->internal_end_block - dev->internal_start_block + 1;
2707                 if (aggressive) {
2708                         threshold = dev->param.chunks_per_block;
2709                         iterations = n_blocks;
2710                 } else {
2711                         int max_threshold;
2712
2713                         if (background)
2714                                 max_threshold = dev->param.chunks_per_block / 2;
2715                         else
2716                                 max_threshold = dev->param.chunks_per_block / 8;
2717
2718                         if (max_threshold < YAFFS_GC_PASSIVE_THRESHOLD)
2719                                 max_threshold = YAFFS_GC_PASSIVE_THRESHOLD;
2720
2721                         threshold = background ? (dev->gc_not_done + 2) * 2 : 0;
2722                         if (threshold < YAFFS_GC_PASSIVE_THRESHOLD)
2723                                 threshold = YAFFS_GC_PASSIVE_THRESHOLD;
2724                         if (threshold > max_threshold)
2725                                 threshold = max_threshold;
2726
2727                         iterations = n_blocks / 16 + 1;
2728                         if (iterations > 100)
2729                                 iterations = 100;
2730                 }
2731
2732                 for (i = 0;
2733                      i < iterations &&
2734                      (dev->gc_dirtiest < 1 ||
2735                       dev->gc_pages_in_use > YAFFS_GC_GOOD_ENOUGH);
2736                      i++) {
2737                         dev->gc_block_finder++;
2738                         if (dev->gc_block_finder < dev->internal_start_block ||
2739                             dev->gc_block_finder > dev->internal_end_block)
2740                                 dev->gc_block_finder =
2741                                     dev->internal_start_block;
2742
2743                         bi = yaffs_get_block_info(dev, dev->gc_block_finder);
2744
2745                         pages_used = bi->pages_in_use - bi->soft_del_pages;
2746
2747                         if (bi->block_state == YAFFS_BLOCK_STATE_FULL &&
2748                             pages_used < dev->param.chunks_per_block &&
2749                             (dev->gc_dirtiest < 1 ||
2750                              pages_used < dev->gc_pages_in_use) &&
2751                             yaffs_block_ok_for_gc(dev, bi)) {
2752                                 dev->gc_dirtiest = dev->gc_block_finder;
2753                                 dev->gc_pages_in_use = pages_used;
2754                         }
2755                 }
2756
2757                 if (dev->gc_dirtiest > 0 && dev->gc_pages_in_use <= threshold)
2758                         selected = dev->gc_dirtiest;
2759         }
2760
2761         /*
2762          * If nothing has been selected for a while, try the oldest dirty
2763          * because that's gumming up the works.
2764          */
2765
2766         if (!selected && dev->param.is_yaffs2 &&
2767             dev->gc_not_done >= (background ? 10 : 20)) {
2768                 yaffs2_find_oldest_dirty_seq(dev);
2769                 if (dev->oldest_dirty_block > 0) {
2770                         selected = dev->oldest_dirty_block;
2771                         dev->gc_dirtiest = selected;
2772                         dev->oldest_dirty_gc_count++;
2773                         bi = yaffs_get_block_info(dev, selected);
2774                         dev->gc_pages_in_use =
2775                             bi->pages_in_use - bi->soft_del_pages;
2776                 } else {
2777                         dev->gc_not_done = 0;
2778                 }
2779         }
2780
2781         if (selected) {
2782                 yaffs_trace(YAFFS_TRACE_GC,
2783                         "GC Selected block %d with %d free, prioritised:%d",
2784                         selected,
2785                         dev->param.chunks_per_block - dev->gc_pages_in_use,
2786                         prioritised);
2787
2788                 dev->n_gc_blocks++;
2789                 if (background)
2790                         dev->bg_gcs++;
2791
2792                 dev->gc_dirtiest = 0;
2793                 dev->gc_pages_in_use = 0;
2794                 dev->gc_not_done = 0;
2795                 if (dev->refresh_skip > 0)
2796                         dev->refresh_skip--;
2797         } else {
2798                 dev->gc_not_done++;
2799                 yaffs_trace(YAFFS_TRACE_GC,
2800                         "GC none: finder %d skip %d threshold %d dirtiest %d using %d oldest %d%s",
2801                         dev->gc_block_finder, dev->gc_not_done, threshold,
2802                         dev->gc_dirtiest, dev->gc_pages_in_use,
2803                         dev->oldest_dirty_block, background ? " bg" : "");
2804         }
2805
2806         return selected;
2807 }
2808
2809 /* New garbage collector
2810  * If we're very low on erased blocks then we do aggressive garbage collection
2811  * otherwise we do "leasurely" garbage collection.
2812  * Aggressive gc looks further (whole array) and will accept less dirty blocks.
2813  * Passive gc only inspects smaller areas and only accepts more dirty blocks.
2814  *
2815  * The idea is to help clear out space in a more spread-out manner.
2816  * Dunno if it really does anything useful.
2817  */
2818 static int yaffs_check_gc(struct yaffs_dev *dev, int background)
2819 {
2820         int aggressive = 0;
2821         int gc_ok = YAFFS_OK;
2822         int max_tries = 0;
2823         int min_erased;
2824         int erased_chunks;
2825         int checkpt_block_adjust;
2826
2827         if (dev->param.gc_control && (dev->param.gc_control(dev) & 1) == 0)
2828                 return YAFFS_OK;
2829
2830         if (dev->gc_disable)
2831                 /* Bail out so we don't get recursive gc */
2832                 return YAFFS_OK;
2833
2834         /* This loop should pass the first time.
2835          * Only loops here if the collection does not increase space.
2836          */
2837
2838         do {
2839                 max_tries++;
2840
2841                 checkpt_block_adjust = yaffs_calc_checkpt_blocks_required(dev);
2842
2843                 min_erased =
2844                     dev->param.n_reserved_blocks + checkpt_block_adjust + 1;
2845                 erased_chunks =
2846                     dev->n_erased_blocks * dev->param.chunks_per_block;
2847
2848                 /* If we need a block soon then do aggressive gc. */
2849                 if (dev->n_erased_blocks < min_erased)
2850                         aggressive = 1;
2851                 else {
2852                         if (!background
2853                             && erased_chunks > (dev->n_free_chunks / 4))
2854                                 break;
2855
2856                         if (dev->gc_skip > 20)
2857                                 dev->gc_skip = 20;
2858                         if (erased_chunks < dev->n_free_chunks / 2 ||
2859                             dev->gc_skip < 1 || background)
2860                                 aggressive = 0;
2861                         else {
2862                                 dev->gc_skip--;
2863                                 break;
2864                         }
2865                 }
2866
2867                 dev->gc_skip = 5;
2868
2869                 /* If we don't already have a block being gc'd then see if we
2870                  * should start another */
2871
2872                 if (dev->gc_block < 1 && !aggressive) {
2873                         dev->gc_block = yaffs2_find_refresh_block(dev);
2874                         dev->gc_chunk = 0;
2875                         dev->n_clean_ups = 0;
2876                 }
2877                 if (dev->gc_block < 1) {
2878                         dev->gc_block =
2879                             yaffs_find_gc_block(dev, aggressive, background);
2880                         dev->gc_chunk = 0;
2881                         dev->n_clean_ups = 0;
2882                 }
2883
2884                 if (dev->gc_block > 0) {
2885                         dev->all_gcs++;
2886                         if (!aggressive)
2887                                 dev->passive_gc_count++;
2888
2889                         yaffs_trace(YAFFS_TRACE_GC,
2890                                 "yaffs: GC n_erased_blocks %d aggressive %d",
2891                                 dev->n_erased_blocks, aggressive);
2892
2893                         gc_ok = yaffs_gc_block(dev, dev->gc_block, aggressive);
2894                 }
2895
2896                 if (dev->n_erased_blocks < (dev->param.n_reserved_blocks) &&
2897                     dev->gc_block > 0) {
2898                         yaffs_trace(YAFFS_TRACE_GC,
2899                                 "yaffs: GC !!!no reclaim!!! n_erased_blocks %d after try %d block %d",
2900                                 dev->n_erased_blocks, max_tries,
2901                                 dev->gc_block);
2902                 }
2903         } while ((dev->n_erased_blocks < dev->param.n_reserved_blocks) &&
2904                  (dev->gc_block > 0) && (max_tries < 2));
2905
2906         return aggressive ? gc_ok : YAFFS_OK;
2907 }
2908
2909 /*
2910  * yaffs_bg_gc()
2911  * Garbage collects. Intended to be called from a background thread.
2912  * Returns non-zero if at least half the free chunks are erased.
2913  */
2914 int yaffs_bg_gc(struct yaffs_dev *dev, unsigned urgency)
2915 {
2916         int erased_chunks = dev->n_erased_blocks * dev->param.chunks_per_block;
2917
2918         yaffs_trace(YAFFS_TRACE_BACKGROUND, "Background gc %u", urgency);
2919
2920         yaffs_check_gc(dev, 1);
2921         return erased_chunks > dev->n_free_chunks / 2;
2922 }
2923
2924 /*-------------------- Data file manipulation -----------------*/
2925
2926 static int yaffs_rd_data_obj(struct yaffs_obj *in, int inode_chunk, u8 * buffer)
2927 {
2928         int nand_chunk = yaffs_find_chunk_in_file(in, inode_chunk, NULL);
2929
2930         if (nand_chunk >= 0)
2931                 return yaffs_rd_chunk_tags_nand(in->my_dev, nand_chunk,
2932                                                 buffer, NULL);
2933         else {
2934                 yaffs_trace(YAFFS_TRACE_NANDACCESS,
2935                         "Chunk %d not found zero instead",
2936                         nand_chunk);
2937                 /* get sane (zero) data if you read a hole */
2938                 memset(buffer, 0, in->my_dev->data_bytes_per_chunk);
2939                 return 0;
2940         }
2941
2942 }
2943
2944 void yaffs_chunk_del(struct yaffs_dev *dev, int chunk_id, int mark_flash,
2945                      int lyn)
2946 {
2947         int block;
2948         int page;
2949         struct yaffs_ext_tags tags;
2950         struct yaffs_block_info *bi;
2951
2952         if (chunk_id <= 0)
2953                 return;
2954
2955         dev->n_deletions++;
2956         block = chunk_id / dev->param.chunks_per_block;
2957         page = chunk_id % dev->param.chunks_per_block;
2958
2959         if (!yaffs_check_chunk_bit(dev, block, page))
2960                 yaffs_trace(YAFFS_TRACE_VERIFY,
2961                         "Deleting invalid chunk %d", chunk_id);
2962
2963         bi = yaffs_get_block_info(dev, block);
2964
2965         yaffs2_update_oldest_dirty_seq(dev, block, bi);
2966
2967         yaffs_trace(YAFFS_TRACE_DELETION,
2968                 "line %d delete of chunk %d",
2969                 lyn, chunk_id);
2970
2971         if (!dev->param.is_yaffs2 && mark_flash &&
2972             bi->block_state != YAFFS_BLOCK_STATE_COLLECTING) {
2973
2974                 yaffs_init_tags(&tags);
2975                 tags.is_deleted = 1;
2976                 yaffs_wr_chunk_tags_nand(dev, chunk_id, NULL, &tags);
2977                 yaffs_handle_chunk_update(dev, chunk_id, &tags);
2978         } else {
2979                 dev->n_unmarked_deletions++;
2980         }
2981
2982         /* Pull out of the management area.
2983          * If the whole block became dirty, this will kick off an erasure.
2984          */
2985         if (bi->block_state == YAFFS_BLOCK_STATE_ALLOCATING ||
2986             bi->block_state == YAFFS_BLOCK_STATE_FULL ||
2987             bi->block_state == YAFFS_BLOCK_STATE_NEEDS_SCAN ||
2988             bi->block_state == YAFFS_BLOCK_STATE_COLLECTING) {
2989                 dev->n_free_chunks++;
2990                 yaffs_clear_chunk_bit(dev, block, page);
2991                 bi->pages_in_use--;
2992
2993                 if (bi->pages_in_use == 0 &&
2994                     !bi->has_shrink_hdr &&
2995                     bi->block_state != YAFFS_BLOCK_STATE_ALLOCATING &&
2996                     bi->block_state != YAFFS_BLOCK_STATE_NEEDS_SCAN) {
2997                         yaffs_block_became_dirty(dev, block);
2998                 }
2999         }
3000 }
3001
3002 static int yaffs_wr_data_obj(struct yaffs_obj *in, int inode_chunk,
3003                              const u8 *buffer, int n_bytes, int use_reserve)
3004 {
3005         /* Find old chunk Need to do this to get serial number
3006          * Write new one and patch into tree.
3007          * Invalidate old tags.
3008          */
3009
3010         int prev_chunk_id;
3011         struct yaffs_ext_tags prev_tags;
3012         int new_chunk_id;
3013         struct yaffs_ext_tags new_tags;
3014         struct yaffs_dev *dev = in->my_dev;
3015
3016         yaffs_check_gc(dev, 0);
3017
3018         /* Get the previous chunk at this location in the file if it exists.
3019          * If it does not exist then put a zero into the tree. This creates
3020          * the tnode now, rather than later when it is harder to clean up.
3021          */
3022         prev_chunk_id = yaffs_find_chunk_in_file(in, inode_chunk, &prev_tags);
3023         if (prev_chunk_id < 1 &&
3024             !yaffs_put_chunk_in_file(in, inode_chunk, 0, 0))
3025                 return 0;
3026
3027         /* Set up new tags */
3028         yaffs_init_tags(&new_tags);
3029
3030         new_tags.chunk_id = inode_chunk;
3031         new_tags.obj_id = in->obj_id;
3032         new_tags.serial_number =
3033             (prev_chunk_id > 0) ? prev_tags.serial_number + 1 : 1;
3034         new_tags.n_bytes = n_bytes;
3035
3036         if (n_bytes < 1 || n_bytes > dev->param.total_bytes_per_chunk) {
3037                 yaffs_trace(YAFFS_TRACE_ERROR,
3038                   "Writing %d bytes to chunk!!!!!!!!!",
3039                    n_bytes);
3040                 BUG();
3041         }
3042
3043         new_chunk_id =
3044             yaffs_write_new_chunk(dev, buffer, &new_tags, use_reserve);
3045
3046         if (new_chunk_id > 0) {
3047                 yaffs_put_chunk_in_file(in, inode_chunk, new_chunk_id, 0);
3048
3049                 if (prev_chunk_id > 0)
3050                         yaffs_chunk_del(dev, prev_chunk_id, 1, __LINE__);
3051
3052                 yaffs_verify_file_sane(in);
3053         }
3054         return new_chunk_id;
3055
3056 }
3057
3058
3059
3060 static int yaffs_do_xattrib_mod(struct yaffs_obj *obj, int set,
3061                                 const YCHAR *name, const void *value, int size,
3062                                 int flags)
3063 {
3064         struct yaffs_xattr_mod xmod;
3065         int result;
3066
3067         xmod.set = set;
3068         xmod.name = name;
3069         xmod.data = value;
3070         xmod.size = size;
3071         xmod.flags = flags;
3072         xmod.result = -ENOSPC;
3073
3074         result = yaffs_update_oh(obj, NULL, 0, 0, 0, &xmod);
3075
3076         if (result > 0)
3077                 return xmod.result;
3078         else
3079                 return -ENOSPC;
3080 }
3081
3082 static int yaffs_apply_xattrib_mod(struct yaffs_obj *obj, char *buffer,
3083                                    struct yaffs_xattr_mod *xmod)
3084 {
3085         int retval = 0;
3086         int x_offs = sizeof(struct yaffs_obj_hdr);
3087         struct yaffs_dev *dev = obj->my_dev;
3088         int x_size = dev->data_bytes_per_chunk - sizeof(struct yaffs_obj_hdr);
3089         char *x_buffer = buffer + x_offs;
3090
3091         if (xmod->set)
3092                 retval =
3093                     nval_set(x_buffer, x_size, xmod->name, xmod->data,
3094                              xmod->size, xmod->flags);
3095         else
3096                 retval = nval_del(x_buffer, x_size, xmod->name);
3097
3098         obj->has_xattr = nval_hasvalues(x_buffer, x_size);
3099         obj->xattr_known = 1;
3100         xmod->result = retval;
3101
3102         return retval;
3103 }
3104
3105 static int yaffs_do_xattrib_fetch(struct yaffs_obj *obj, const YCHAR *name,
3106                                   void *value, int size)
3107 {
3108         char *buffer = NULL;
3109         int result;
3110         struct yaffs_ext_tags tags;
3111         struct yaffs_dev *dev = obj->my_dev;
3112         int x_offs = sizeof(struct yaffs_obj_hdr);
3113         int x_size = dev->data_bytes_per_chunk - sizeof(struct yaffs_obj_hdr);
3114         char *x_buffer;
3115         int retval = 0;
3116
3117         if (obj->hdr_chunk < 1)
3118                 return -ENODATA;
3119
3120         /* If we know that the object has no xattribs then don't do all the
3121          * reading and parsing.
3122          */
3123         if (obj->xattr_known && !obj->has_xattr) {
3124                 if (name)
3125                         return -ENODATA;
3126                 else
3127                         return 0;
3128         }
3129
3130         buffer = (char *)yaffs_get_temp_buffer(dev, __LINE__);
3131         if (!buffer)
3132                 return -ENOMEM;
3133
3134         result =
3135             yaffs_rd_chunk_tags_nand(dev, obj->hdr_chunk, (u8 *) buffer, &tags);
3136
3137         if (result != YAFFS_OK)
3138                 retval = -ENOENT;
3139         else {
3140                 x_buffer = buffer + x_offs;
3141
3142                 if (!obj->xattr_known) {
3143                         obj->has_xattr = nval_hasvalues(x_buffer, x_size);
3144                         obj->xattr_known = 1;
3145                 }
3146
3147                 if (name)
3148                         retval = nval_get(x_buffer, x_size, name, value, size);
3149                 else
3150                         retval = nval_list(x_buffer, x_size, value, size);
3151         }
3152         yaffs_release_temp_buffer(dev, (u8 *) buffer, __LINE__);
3153         return retval;
3154 }
3155
3156 int yaffs_set_xattrib(struct yaffs_obj *obj, const YCHAR * name,
3157                       const void *value, int size, int flags)
3158 {
3159         return yaffs_do_xattrib_mod(obj, 1, name, value, size, flags);
3160 }
3161
3162 int yaffs_remove_xattrib(struct yaffs_obj *obj, const YCHAR * name)
3163 {
3164         return yaffs_do_xattrib_mod(obj, 0, name, NULL, 0, 0);
3165 }
3166
3167 int yaffs_get_xattrib(struct yaffs_obj *obj, const YCHAR * name, void *value,
3168                       int size)
3169 {
3170         return yaffs_do_xattrib_fetch(obj, name, value, size);
3171 }
3172
3173 int yaffs_list_xattrib(struct yaffs_obj *obj, char *buffer, int size)
3174 {
3175         return yaffs_do_xattrib_fetch(obj, NULL, buffer, size);
3176 }
3177
3178 static void yaffs_check_obj_details_loaded(struct yaffs_obj *in)
3179 {
3180         u8 *buf;
3181         struct yaffs_obj_hdr *oh;
3182         struct yaffs_dev *dev;
3183         struct yaffs_ext_tags tags;
3184         int result;
3185         int alloc_failed = 0;
3186
3187         if (!in || !in->lazy_loaded || in->hdr_chunk < 1)
3188                 return;
3189
3190         dev = in->my_dev;
3191         in->lazy_loaded = 0;
3192         buf = yaffs_get_temp_buffer(dev, __LINE__);
3193
3194         result = yaffs_rd_chunk_tags_nand(dev, in->hdr_chunk, buf, &tags);
3195         oh = (struct yaffs_obj_hdr *)buf;
3196
3197         in->yst_mode = oh->yst_mode;
3198         yaffs_load_attribs(in, oh);
3199         yaffs_set_obj_name_from_oh(in, oh);
3200
3201         if (in->variant_type == YAFFS_OBJECT_TYPE_SYMLINK) {
3202                 in->variant.symlink_variant.alias =
3203                     yaffs_clone_str(oh->alias);
3204                 if (!in->variant.symlink_variant.alias)
3205                         alloc_failed = 1;       /* Not returned */
3206         }
3207         yaffs_release_temp_buffer(dev, buf, __LINE__);
3208 }
3209
3210 static void yaffs_load_name_from_oh(struct yaffs_dev *dev, YCHAR *name,
3211                                     const YCHAR *oh_name, int buff_size)
3212 {
3213 #ifdef CONFIG_YAFFS_AUTO_UNICODE
3214         if (dev->param.auto_unicode) {
3215                 if (*oh_name) {
3216                         /* It is an ASCII name, do an ASCII to
3217                          * unicode conversion */
3218                         const char *ascii_oh_name = (const char *)oh_name;
3219                         int n = buff_size - 1;
3220                         while (n > 0 && *ascii_oh_name) {
3221                                 *name = *ascii_oh_name;
3222                                 name++;
3223                                 ascii_oh_name++;
3224                                 n--;
3225                         }
3226                 } else {
3227                         strncpy(name, oh_name + 1, buff_size - 1);
3228                 }
3229         } else {
3230 #else
3231         {
3232 #endif
3233                 strncpy(name, oh_name, buff_size - 1);
3234         }
3235 }
3236
3237 static void yaffs_load_oh_from_name(struct yaffs_dev *dev, YCHAR *oh_name,
3238                                     const YCHAR *name)
3239 {
3240 #ifdef CONFIG_YAFFS_AUTO_UNICODE
3241
3242         int is_ascii;
3243         YCHAR *w;
3244
3245         if (dev->param.auto_unicode) {
3246
3247                 is_ascii = 1;
3248                 w = name;
3249
3250                 /* Figure out if the name will fit in ascii character set */
3251                 while (is_ascii && *w) {
3252                         if ((*w) & 0xff00)
3253                                 is_ascii = 0;
3254                         w++;
3255                 }
3256
3257                 if (is_ascii) {
3258                         /* It is an ASCII name, so convert unicode to ascii */
3259                         char *ascii_oh_name = (char *)oh_name;
3260                         int n = YAFFS_MAX_NAME_LENGTH - 1;
3261                         while (n > 0 && *name) {
3262                                 *ascii_oh_name = *name;
3263                                 name++;
3264                                 ascii_oh_name++;
3265                                 n--;
3266                         }
3267                 } else {
3268                         /* Unicode name, so save starting at the second YCHAR */
3269                         *oh_name = 0;
3270                         strncpy(oh_name + 1, name, YAFFS_MAX_NAME_LENGTH - 2);
3271                 }
3272         } else {
3273 #else
3274         {
3275 #endif
3276                 strncpy(oh_name, name, YAFFS_MAX_NAME_LENGTH - 1);
3277         }
3278 }
3279
3280 /* UpdateObjectHeader updates the header on NAND for an object.
3281  * If name is not NULL, then that new name is used.
3282  */
3283 int yaffs_update_oh(struct yaffs_obj *in, const YCHAR *name, int force,
3284                     int is_shrink, int shadows, struct yaffs_xattr_mod *xmod)
3285 {
3286
3287         struct yaffs_block_info *bi;
3288         struct yaffs_dev *dev = in->my_dev;
3289         int prev_chunk_id;
3290         int ret_val = 0;
3291         int result = 0;
3292         int new_chunk_id;
3293         struct yaffs_ext_tags new_tags;
3294         struct yaffs_ext_tags old_tags;
3295         const YCHAR *alias = NULL;
3296         u8 *buffer = NULL;
3297         YCHAR old_name[YAFFS_MAX_NAME_LENGTH + 1];
3298         struct yaffs_obj_hdr *oh = NULL;
3299
3300         strcpy(old_name, _Y("silly old name"));
3301
3302         if (in->fake && in != dev->root_dir && !force && !xmod)
3303                 return ret_val;
3304
3305         yaffs_check_gc(dev, 0);
3306         yaffs_check_obj_details_loaded(in);
3307
3308         buffer = yaffs_get_temp_buffer(in->my_dev, __LINE__);
3309         oh = (struct yaffs_obj_hdr *)buffer;
3310
3311         prev_chunk_id = in->hdr_chunk;
3312
3313         if (prev_chunk_id > 0) {
3314                 result = yaffs_rd_chunk_tags_nand(dev, prev_chunk_id,
3315                                                   buffer, &old_tags);
3316
3317                 yaffs_verify_oh(in, oh, &old_tags, 0);
3318                 memcpy(old_name, oh->name, sizeof(oh->name));
3319                 memset(buffer, 0xff, sizeof(struct yaffs_obj_hdr));
3320         } else {
3321                 memset(buffer, 0xff, dev->data_bytes_per_chunk);
3322         }
3323
3324         oh->type = in->variant_type;
3325         oh->yst_mode = in->yst_mode;
3326         oh->shadows_obj = oh->inband_shadowed_obj_id = shadows;
3327
3328         yaffs_load_attribs_oh(oh, in);
3329
3330         if (in->parent)
3331                 oh->parent_obj_id = in->parent->obj_id;
3332         else
3333                 oh->parent_obj_id = 0;
3334
3335         if (name && *name) {
3336                 memset(oh->name, 0, sizeof(oh->name));
3337                 yaffs_load_oh_from_name(dev, oh->name, name);
3338         } else if (prev_chunk_id > 0) {
3339                 memcpy(oh->name, old_name, sizeof(oh->name));
3340         } else {
3341                 memset(oh->name, 0, sizeof(oh->name));
3342         }
3343
3344         oh->is_shrink = is_shrink;
3345
3346         switch (in->variant_type) {
3347         case YAFFS_OBJECT_TYPE_UNKNOWN:
3348                 /* Should not happen */
3349                 break;
3350         case YAFFS_OBJECT_TYPE_FILE:
3351                 oh->file_size =
3352                     (oh->parent_obj_id == YAFFS_OBJECTID_DELETED ||
3353                      oh->parent_obj_id == YAFFS_OBJECTID_UNLINKED) ?
3354                      0 : in->variant.file_variant.file_size;
3355                 break;
3356         case YAFFS_OBJECT_TYPE_HARDLINK:
3357                 oh->equiv_id = in->variant.hardlink_variant.equiv_id;
3358                 break;
3359         case YAFFS_OBJECT_TYPE_SPECIAL:
3360                 /* Do nothing */
3361                 break;
3362         case YAFFS_OBJECT_TYPE_DIRECTORY:
3363                 /* Do nothing */
3364                 break;
3365         case YAFFS_OBJECT_TYPE_SYMLINK:
3366                 alias = in->variant.symlink_variant.alias;
3367                 if (!alias)
3368                         alias = _Y("no alias");
3369                 strncpy(oh->alias, alias, YAFFS_MAX_ALIAS_LENGTH);
3370                 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3371                 break;
3372         }
3373
3374         /* process any xattrib modifications */
3375         if (xmod)
3376                 yaffs_apply_xattrib_mod(in, (char *)buffer, xmod);
3377
3378         /* Tags */
3379         yaffs_init_tags(&new_tags);
3380         in->serial++;
3381         new_tags.chunk_id = 0;
3382         new_tags.obj_id = in->obj_id;
3383         new_tags.serial_number = in->serial;
3384
3385         /* Add extra info for file header */
3386         new_tags.extra_available = 1;
3387         new_tags.extra_parent_id = oh->parent_obj_id;
3388         new_tags.extra_length = oh->file_size;
3389         new_tags.extra_is_shrink = oh->is_shrink;
3390         new_tags.extra_equiv_id = oh->equiv_id;
3391         new_tags.extra_shadows = (oh->shadows_obj > 0) ? 1 : 0;
3392         new_tags.extra_obj_type = in->variant_type;
3393         yaffs_verify_oh(in, oh, &new_tags, 1);
3394
3395         /* Create new chunk in NAND */
3396         new_chunk_id =
3397             yaffs_write_new_chunk(dev, buffer, &new_tags,
3398                                   (prev_chunk_id > 0) ? 1 : 0);
3399
3400         if (buffer)
3401                 yaffs_release_temp_buffer(dev, buffer, __LINE__);
3402
3403         if (new_chunk_id < 0)
3404                 return new_chunk_id;
3405
3406         in->hdr_chunk = new_chunk_id;
3407
3408         if (prev_chunk_id > 0)
3409                 yaffs_chunk_del(dev, prev_chunk_id, 1, __LINE__);
3410
3411         if (!yaffs_obj_cache_dirty(in))
3412                 in->dirty = 0;
3413
3414         /* If this was a shrink, then mark the block
3415          * that the chunk lives on */
3416         if (is_shrink) {
3417                 bi = yaffs_get_block_info(in->my_dev,
3418                                           new_chunk_id /
3419                                           in->my_dev->param.chunks_per_block);
3420                 bi->has_shrink_hdr = 1;
3421         }
3422
3423
3424         return new_chunk_id;
3425 }
3426
3427 /*--------------------- File read/write ------------------------
3428  * Read and write have very similar structures.
3429  * In general the read/write has three parts to it
3430  * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3431  * Some complete chunks
3432  * An incomplete chunk to end off with
3433  *
3434  * Curve-balls: the first chunk might also be the last chunk.
3435  */
3436
3437 int yaffs_file_rd(struct yaffs_obj *in, u8 * buffer, loff_t offset, int n_bytes)
3438 {
3439         int chunk;
3440         u32 start;
3441         int n_copy;
3442         int n = n_bytes;
3443         int n_done = 0;
3444         struct yaffs_cache *cache;
3445         struct yaffs_dev *dev;
3446
3447         dev = in->my_dev;
3448
3449         while (n > 0) {
3450                 yaffs_addr_to_chunk(dev, offset, &chunk, &start);
3451                 chunk++;
3452
3453                 /* OK now check for the curveball where the start and end are in
3454                  * the same chunk.
3455                  */
3456                 if ((start + n) < dev->data_bytes_per_chunk)
3457                         n_copy = n;
3458                 else
3459                         n_copy = dev->data_bytes_per_chunk - start;
3460
3461                 cache = yaffs_find_chunk_cache(in, chunk);
3462
3463                 /* If the chunk is already in the cache or it is less than
3464                  * a whole chunk or we're using inband tags then use the cache
3465                  * (if there is caching) else bypass the cache.
3466                  */
3467                 if (cache || n_copy != dev->data_bytes_per_chunk ||
3468                     dev->param.inband_tags) {
3469                         if (dev->param.n_caches > 0) {
3470
3471                                 /* If we can't find the data in the cache,
3472                                  * then load it up. */
3473
3474                                 if (!cache) {
3475                                         cache =
3476                                             yaffs_grab_chunk_cache(in->my_dev);
3477                                         cache->object = in;
3478                                         cache->chunk_id = chunk;
3479                                         cache->dirty = 0;
3480                                         cache->locked = 0;
3481                                         yaffs_rd_data_obj(in, chunk,
3482                                                           cache->data);
3483                                         cache->n_bytes = 0;
3484                                 }
3485
3486                                 yaffs_use_cache(dev, cache, 0);
3487
3488                                 cache->locked = 1;
3489
3490                                 memcpy(buffer, &cache->data[start], n_copy);
3491
3492                                 cache->locked = 0;
3493                         } else {
3494                                 /* Read into the local buffer then copy.. */
3495
3496                                 u8 *local_buffer =
3497                                     yaffs_get_temp_buffer(dev, __LINE__);
3498                                 yaffs_rd_data_obj(in, chunk, local_buffer);
3499
3500                                 memcpy(buffer, &local_buffer[start], n_copy);
3501
3502                                 yaffs_release_temp_buffer(dev, local_buffer,
3503                                                           __LINE__);
3504                         }
3505                 } else {
3506                         /* A full chunk. Read directly into the buffer. */
3507                         yaffs_rd_data_obj(in, chunk, buffer);
3508                 }
3509                 n -= n_copy;
3510                 offset += n_copy;
3511                 buffer += n_copy;
3512                 n_done += n_copy;
3513         }
3514         return n_done;
3515 }
3516
3517 int yaffs_do_file_wr(struct yaffs_obj *in, const u8 *buffer, loff_t offset,
3518                      int n_bytes, int write_trhrough)
3519 {
3520
3521         int chunk;
3522         u32 start;
3523         int n_copy;
3524         int n = n_bytes;
3525         int n_done = 0;
3526         int n_writeback;
3527         int start_write = offset;
3528         int chunk_written = 0;
3529         u32 n_bytes_read;
3530         u32 chunk_start;
3531         struct yaffs_dev *dev;
3532
3533         dev = in->my_dev;
3534
3535         while (n > 0 && chunk_written >= 0) {
3536                 yaffs_addr_to_chunk(dev, offset, &chunk, &start);
3537
3538                 if (chunk * dev->data_bytes_per_chunk + start != offset ||
3539                     start >= dev->data_bytes_per_chunk) {
3540                         yaffs_trace(YAFFS_TRACE_ERROR,
3541                                 "AddrToChunk of offset %d gives chunk %d start %d",
3542                                 (int)offset, chunk, start);
3543                 }
3544                 chunk++;        /* File pos to chunk in file offset */
3545
3546                 /* OK now check for the curveball where the start and end are in
3547                  * the same chunk.
3548                  */
3549
3550                 if ((start + n) < dev->data_bytes_per_chunk) {
3551                         n_copy = n;
3552
3553                         /* Now calculate how many bytes to write back....
3554                          * If we're overwriting and not writing to then end of
3555                          * file then we need to write back as much as was there
3556                          * before.
3557                          */
3558
3559                         chunk_start = ((chunk - 1) * dev->data_bytes_per_chunk);
3560
3561                         if (chunk_start > in->variant.file_variant.file_size)
3562                                 n_bytes_read = 0;       /* Past end of file */
3563                         else
3564                                 n_bytes_read =
3565                                     in->variant.file_variant.file_size -
3566                                     chunk_start;
3567
3568                         if (n_bytes_read > dev->data_bytes_per_chunk)
3569                                 n_bytes_read = dev->data_bytes_per_chunk;
3570
3571                         n_writeback =
3572                             (n_bytes_read >
3573                              (start + n)) ? n_bytes_read : (start + n);
3574
3575                         if (n_writeback < 0 ||
3576                             n_writeback > dev->data_bytes_per_chunk)
3577                                 BUG();
3578
3579                 } else {
3580                         n_copy = dev->data_bytes_per_chunk - start;
3581                         n_writeback = dev->data_bytes_per_chunk;
3582                 }
3583
3584                 if (n_copy != dev->data_bytes_per_chunk ||
3585                     dev->param.inband_tags) {
3586                         /* An incomplete start or end chunk (or maybe both
3587                          * start and end chunk), or we're using inband tags,
3588                          * so we want to use the cache buffers.
3589                          */
3590                         if (dev->param.n_caches > 0) {
3591                                 struct yaffs_cache *cache;
3592
3593                                 /* If we can't find the data in the cache, then
3594                                  * load the cache */
3595                                 cache = yaffs_find_chunk_cache(in, chunk);
3596
3597                                 if (!cache &&
3598                                     yaffs_check_alloc_available(dev, 1)) {
3599                                         cache = yaffs_grab_chunk_cache(dev);
3600                                         cache->object = in;
3601                                         cache->chunk_id = chunk;
3602                                         cache->dirty = 0;
3603                                         cache->locked = 0;
3604                                         yaffs_rd_data_obj(in, chunk,
3605                                                           cache->data);
3606                                 } else if (cache &&
3607                                            !cache->dirty &&
3608                                            !yaffs_check_alloc_available(dev,
3609                                                                         1)) {
3610                                         /* Drop the cache if it was a read cache
3611                                          * item and no space check has been made
3612                                          * for it.
3613                                          */
3614                                         cache = NULL;
3615                                 }
3616
3617                                 if (cache) {
3618                                         yaffs_use_cache(dev, cache, 1);
3619                                         cache->locked = 1;
3620
3621                                         memcpy(&cache->data[start], buffer,
3622                                                n_copy);
3623
3624                                         cache->locked = 0;
3625                                         cache->n_bytes = n_writeback;
3626
3627                                         if (write_trhrough) {
3628                                                 chunk_written =
3629                                                     yaffs_wr_data_obj
3630                                                     (cache->object,
3631                                                      cache->chunk_id,
3632                                                      cache->data,
3633                                                      cache->n_bytes, 1);
3634                                                 cache->dirty = 0;
3635                                         }
3636                                 } else {
3637                                         chunk_written = -1;     /* fail write */
3638                                 }
3639                         } else {
3640                                 /* An incomplete start or end chunk (or maybe
3641                                  * both start and end chunk). Read into the
3642                                  * local buffer then copy over and write back.
3643                                  */
3644
3645                                 u8 *local_buffer =
3646                                     yaffs_get_temp_buffer(dev, __LINE__);
3647
3648                                 yaffs_rd_data_obj(in, chunk, local_buffer);
3649                                 memcpy(&local_buffer[start], buffer, n_copy);
3650
3651                                 chunk_written =
3652                                     yaffs_wr_data_obj(in, chunk,
3653                                                       local_buffer,
3654                                                       n_writeback, 0);
3655
3656                                 yaffs_release_temp_buffer(dev, local_buffer,
3657                                                           __LINE__);
3658                         }
3659                 } else {
3660                         /* A full chunk. Write directly from the buffer. */
3661
3662                         chunk_written =
3663                             yaffs_wr_data_obj(in, chunk, buffer,
3664                                               dev->data_bytes_per_chunk, 0);
3665
3666                         /* Since we've overwritten the cached data,
3667                          * we better invalidate it. */
3668                         yaffs_invalidate_chunk_cache(in, chunk);
3669                 }
3670
3671                 if (chunk_written >= 0) {
3672                         n -= n_copy;
3673                         offset += n_copy;
3674                         buffer += n_copy;
3675                         n_done += n_copy;
3676                 }
3677         }
3678
3679         /* Update file object */
3680
3681         if ((start_write + n_done) > in->variant.file_variant.file_size)
3682                 in->variant.file_variant.file_size = (start_write + n_done);
3683
3684         in->dirty = 1;
3685         return n_done;
3686 }
3687
3688 int yaffs_wr_file(struct yaffs_obj *in, const u8 *buffer, loff_t offset,
3689                   int n_bytes, int write_trhrough)
3690 {
3691         yaffs2_handle_hole(in, offset);
3692         return yaffs_do_file_wr(in, buffer, offset, n_bytes, write_trhrough);
3693 }
3694
3695 /* ---------------------- File resizing stuff ------------------ */
3696
3697 static void yaffs_prune_chunks(struct yaffs_obj *in, int new_size)
3698 {
3699
3700         struct yaffs_dev *dev = in->my_dev;
3701         int old_size = in->variant.file_variant.file_size;
3702         int i;
3703         int chunk_id;
3704         int last_del = 1 + (old_size - 1) / dev->data_bytes_per_chunk;
3705         int start_del = 1 + (new_size + dev->data_bytes_per_chunk - 1) /
3706             dev->data_bytes_per_chunk;
3707
3708
3709         /* Delete backwards so that we don't end up with holes if
3710          * power is lost part-way through the operation.
3711          */
3712         for (i = last_del; i >= start_del; i--) {
3713                 /* NB this could be optimised somewhat,
3714                  * eg. could retrieve the tags and write them without
3715                  * using yaffs_chunk_del
3716                  */
3717
3718                 chunk_id = yaffs_find_del_file_chunk(in, i, NULL);
3719
3720                 if (chunk_id < 1)
3721                         continue;
3722
3723                 if (chunk_id <
3724                     (dev->internal_start_block * dev->param.chunks_per_block) ||
3725                     chunk_id >=
3726                     ((dev->internal_end_block + 1) *
3727                       dev->param.chunks_per_block)) {
3728                         yaffs_trace(YAFFS_TRACE_ALWAYS,
3729                                 "Found daft chunk_id %d for %d",
3730                                 chunk_id, i);
3731                 } else {
3732                         in->n_data_chunks--;
3733                         yaffs_chunk_del(dev, chunk_id, 1, __LINE__);
3734                 }
3735         }
3736 }
3737
3738 void yaffs_resize_file_down(struct yaffs_obj *obj, loff_t new_size)
3739 {
3740         int new_full;
3741         u32 new_partial;
3742         struct yaffs_dev *dev = obj->my_dev;
3743
3744         yaffs_addr_to_chunk(dev, new_size, &new_full, &new_partial);
3745
3746         yaffs_prune_chunks(obj, new_size);
3747
3748         if (new_partial != 0) {
3749                 int last_chunk = 1 + new_full;
3750                 u8 *local_buffer = yaffs_get_temp_buffer(dev, __LINE__);
3751
3752                 /* Rewrite the last chunk with its new size and zero pad */
3753                 yaffs_rd_data_obj(obj, last_chunk, local_buffer);
3754                 memset(local_buffer + new_partial, 0,
3755                        dev->data_bytes_per_chunk - new_partial);
3756
3757                 yaffs_wr_data_obj(obj, last_chunk, local_buffer,
3758                                   new_partial, 1);
3759
3760                 yaffs_release_temp_buffer(dev, local_buffer, __LINE__);
3761         }
3762
3763         obj->variant.file_variant.file_size = new_size;
3764
3765         yaffs_prune_tree(dev, &obj->variant.file_variant);
3766 }
3767
3768 int yaffs_resize_file(struct yaffs_obj *in, loff_t new_size)
3769 {
3770         struct yaffs_dev *dev = in->my_dev;
3771         int old_size = in->variant.file_variant.file_size;
3772
3773         yaffs_flush_file_cache(in);
3774         yaffs_invalidate_whole_cache(in);
3775
3776         yaffs_check_gc(dev, 0);
3777
3778         if (in->variant_type != YAFFS_OBJECT_TYPE_FILE)
3779                 return YAFFS_FAIL;
3780
3781         if (new_size == old_size)
3782                 return YAFFS_OK;
3783
3784         if (new_size > old_size) {
3785                 yaffs2_handle_hole(in, new_size);
3786                 in->variant.file_variant.file_size = new_size;
3787         } else {
3788                 /* new_size < old_size */
3789                 yaffs_resize_file_down(in, new_size);
3790         }
3791
3792         /* Write a new object header to reflect the resize.
3793          * show we've shrunk the file, if need be
3794          * Do this only if the file is not in the deleted directories
3795          * and is not shadowed.
3796          */
3797         if (in->parent &&
3798             !in->is_shadowed &&
3799             in->parent->obj_id != YAFFS_OBJECTID_UNLINKED &&
3800             in->parent->obj_id != YAFFS_OBJECTID_DELETED)
3801                 yaffs_update_oh(in, NULL, 0, 0, 0, NULL);
3802
3803         return YAFFS_OK;
3804 }
3805
3806 int yaffs_flush_file(struct yaffs_obj *in, int update_time, int data_sync)
3807 {
3808         if (!in->dirty)
3809                 return YAFFS_OK;
3810
3811         yaffs_flush_file_cache(in);
3812
3813         if (data_sync)
3814                 return YAFFS_OK;
3815
3816         if (update_time)
3817                 yaffs_load_current_time(in, 0, 0);
3818
3819         return (yaffs_update_oh(in, NULL, 0, 0, 0, NULL) >= 0) ?
3820                                 YAFFS_OK : YAFFS_FAIL;
3821 }
3822
3823
3824 /* yaffs_del_file deletes the whole file data
3825  * and the inode associated with the file.
3826  * It does not delete the links associated with the file.
3827  */
3828 static int yaffs_unlink_file_if_needed(struct yaffs_obj *in)
3829 {
3830         int ret_val;
3831         int del_now = 0;
3832         struct yaffs_dev *dev = in->my_dev;
3833
3834         if (!in->my_inode)
3835                 del_now = 1;
3836
3837         if (del_now) {
3838                 ret_val =
3839                     yaffs_change_obj_name(in, in->my_dev->del_dir,
3840                                           _Y("deleted"), 0, 0);
3841                 yaffs_trace(YAFFS_TRACE_TRACING,
3842                         "yaffs: immediate deletion of file %d",
3843                         in->obj_id);
3844                 in->deleted = 1;
3845                 in->my_dev->n_deleted_files++;
3846                 if (dev->param.disable_soft_del || dev->param.is_yaffs2)
3847                         yaffs_resize_file(in, 0);
3848                 yaffs_soft_del_file(in);
3849         } else {
3850                 ret_val =
3851                     yaffs_change_obj_name(in, in->my_dev->unlinked_dir,
3852                                           _Y("unlinked"), 0, 0);
3853         }
3854         return ret_val;
3855 }
3856
3857 int yaffs_del_file(struct yaffs_obj *in)
3858 {
3859         int ret_val = YAFFS_OK;
3860         int deleted;    /* Need to cache value on stack if in is freed */
3861         struct yaffs_dev *dev = in->my_dev;
3862
3863         if (dev->param.disable_soft_del || dev->param.is_yaffs2)
3864                 yaffs_resize_file(in, 0);
3865
3866         if (in->n_data_chunks > 0) {
3867                 /* Use soft deletion if there is data in the file.
3868                  * That won't be the case if it has been resized to zero.
3869                  */
3870                 if (!in->unlinked)
3871                         ret_val = yaffs_unlink_file_if_needed(in);
3872
3873                 deleted = in->deleted;
3874
3875                 if (ret_val == YAFFS_OK && in->unlinked && !in->deleted) {
3876                         in->deleted = 1;
3877                         deleted = 1;
3878                         in->my_dev->n_deleted_files++;
3879                         yaffs_soft_del_file(in);
3880                 }
3881                 return deleted ? YAFFS_OK : YAFFS_FAIL;
3882         } else {
3883                 /* The file has no data chunks so we toss it immediately */
3884                 yaffs_free_tnode(in->my_dev, in->variant.file_variant.top);
3885                 in->variant.file_variant.top = NULL;
3886                 yaffs_generic_obj_del(in);
3887
3888                 return YAFFS_OK;
3889         }
3890 }
3891
3892 int yaffs_is_non_empty_dir(struct yaffs_obj *obj)
3893 {
3894         return (obj &&
3895                 obj->variant_type == YAFFS_OBJECT_TYPE_DIRECTORY) &&
3896                 !(list_empty(&obj->variant.dir_variant.children));
3897 }
3898
3899 static int yaffs_del_dir(struct yaffs_obj *obj)
3900 {
3901         /* First check that the directory is empty. */
3902         if (yaffs_is_non_empty_dir(obj))
3903                 return YAFFS_FAIL;
3904
3905         return yaffs_generic_obj_del(obj);
3906 }
3907
3908 static int yaffs_del_symlink(struct yaffs_obj *in)
3909 {
3910         kfree(in->variant.symlink_variant.alias);
3911         in->variant.symlink_variant.alias = NULL;
3912
3913         return yaffs_generic_obj_del(in);
3914 }
3915
3916 static int yaffs_del_link(struct yaffs_obj *in)
3917 {
3918         /* remove this hardlink from the list associated with the equivalent
3919          * object
3920          */
3921         list_del_init(&in->hard_links);
3922         return yaffs_generic_obj_del(in);
3923 }
3924
3925 int yaffs_del_obj(struct yaffs_obj *obj)
3926 {
3927         int ret_val = -1;
3928
3929         switch (obj->variant_type) {
3930         case YAFFS_OBJECT_TYPE_FILE: