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