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