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