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