yaffsfs.c: Fix NULL dereference in yaffs_unmount2_reldev()
[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                 yaffs_release_temp_buffer(dev, buf);
3024                 return;
3025         }
3026
3027         oh = (struct yaffs_obj_hdr *)buf;
3028
3029         yaffs_do_endian_oh(dev, oh);
3030
3031         in->lazy_loaded = 0;
3032         in->yst_mode = oh->yst_mode;
3033         yaffs_load_attribs(in, oh);
3034         yaffs_set_obj_name_from_oh(in, oh);
3035
3036         if (in->variant_type == YAFFS_OBJECT_TYPE_SYMLINK)
3037                 in->variant.symlink_variant.alias =
3038                     yaffs_clone_str(oh->alias);
3039         yaffs_release_temp_buffer(dev, buf);
3040 }
3041
3042 /* UpdateObjectHeader updates the header on NAND for an object.
3043  * If name is not NULL, then that new name is used.
3044  *
3045  * We're always creating the obj header from scratch (except reading
3046  * the old name) so first set up in cpu endianness then run it through
3047  * endian fixing at the end.
3048  *
3049  * However, a twist: If there are xattribs we leave them as they were.
3050  *
3051  * Careful! The buffer holds the whole chunk. Part of the chunk holds the
3052  * object header and the rest holds the xattribs, therefore we use a buffer
3053  * pointer and an oh pointer to point to the same memory.
3054  */
3055
3056 int yaffs_update_oh(struct yaffs_obj *in, const YCHAR *name, int force,
3057                     int is_shrink, int shadows, struct yaffs_xattr_mod *xmod)
3058 {
3059
3060         struct yaffs_block_info *bi;
3061         struct yaffs_dev *dev = in->my_dev;
3062         int prev_chunk_id;
3063         int ret_val = 0;
3064         int result = 0;
3065         int new_chunk_id;
3066         struct yaffs_ext_tags new_tags;
3067         struct yaffs_ext_tags old_tags;
3068         const YCHAR *alias = NULL;
3069         u8 *buffer = NULL;
3070         YCHAR old_name[YAFFS_MAX_NAME_LENGTH + 1];
3071         struct yaffs_obj_hdr *oh = NULL;
3072         loff_t file_size = 0;
3073
3074         strcpy(old_name, _Y("silly old name"));
3075
3076         if (in->fake && in != dev->root_dir && !force && !xmod)
3077                 return ret_val;
3078
3079         yaffs_check_gc(dev, 0);
3080         yaffs_check_obj_details_loaded(in);
3081
3082         buffer = yaffs_get_temp_buffer(in->my_dev);
3083         oh = (struct yaffs_obj_hdr *)buffer;
3084
3085         prev_chunk_id = in->hdr_chunk;
3086
3087         if (prev_chunk_id > 0) {
3088                 /* Access the old obj header just to read the name. */
3089                 result = yaffs_rd_chunk_tags_nand(dev, prev_chunk_id,
3090                                                   buffer, &old_tags);
3091                 if (result == YAFFS_OK) {
3092                         yaffs_verify_oh(in, oh, &old_tags, 0);
3093                         memcpy(old_name, oh->name, sizeof(oh->name));
3094
3095                         /*
3096                         * NB We only wipe the object header area because the rest of
3097                         * the buffer might contain xattribs.
3098                         */
3099                         memset(oh, 0xff, sizeof(*oh));
3100                 }
3101         } else {
3102                 memset(buffer, 0xff, dev->data_bytes_per_chunk);
3103         }
3104
3105         oh->type = in->variant_type;
3106         oh->yst_mode = in->yst_mode;
3107         oh->shadows_obj = oh->inband_shadowed_obj_id = shadows;
3108
3109         yaffs_load_attribs_oh(oh, in);
3110
3111         if (in->parent)
3112                 oh->parent_obj_id = in->parent->obj_id;
3113         else
3114                 oh->parent_obj_id = 0;
3115
3116         if (name && *name) {
3117                 memset(oh->name, 0, sizeof(oh->name));
3118                 yaffs_load_oh_from_name(dev, oh->name, name);
3119         } else if (prev_chunk_id > 0) {
3120                 memcpy(oh->name, old_name, sizeof(oh->name));
3121         } else {
3122                 memset(oh->name, 0, sizeof(oh->name));
3123         }
3124
3125         oh->is_shrink = is_shrink;
3126
3127         switch (in->variant_type) {
3128         case YAFFS_OBJECT_TYPE_UNKNOWN:
3129                 /* Should not happen */
3130                 break;
3131         case YAFFS_OBJECT_TYPE_FILE:
3132                 if (oh->parent_obj_id != YAFFS_OBJECTID_DELETED &&
3133                     oh->parent_obj_id != YAFFS_OBJECTID_UNLINKED)
3134                         file_size = in->variant.file_variant.stored_size;
3135                 yaffs_oh_size_load(dev, oh, file_size, 0);
3136                 break;
3137         case YAFFS_OBJECT_TYPE_HARDLINK:
3138                 oh->equiv_id = in->variant.hardlink_variant.equiv_id;
3139                 break;
3140         case YAFFS_OBJECT_TYPE_SPECIAL:
3141                 /* Do nothing */
3142                 break;
3143         case YAFFS_OBJECT_TYPE_DIRECTORY:
3144                 /* Do nothing */
3145                 break;
3146         case YAFFS_OBJECT_TYPE_SYMLINK:
3147                 alias = in->variant.symlink_variant.alias;
3148                 if (!alias)
3149                         alias = _Y("no alias");
3150                 strncpy(oh->alias, alias, YAFFS_MAX_ALIAS_LENGTH);
3151                 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3152                 break;
3153         }
3154
3155         /* process any xattrib modifications */
3156         if (xmod)
3157                 yaffs_apply_xattrib_mod(in, (char *)buffer, xmod);
3158
3159         /* Tags */
3160         memset(&new_tags, 0, sizeof(new_tags));
3161         in->serial++;
3162         new_tags.chunk_id = 0;
3163         new_tags.obj_id = in->obj_id;
3164         new_tags.serial_number = in->serial;
3165
3166         /* Add extra info for file header */
3167         new_tags.extra_available = 1;
3168         new_tags.extra_parent_id = oh->parent_obj_id;
3169         new_tags.extra_file_size = file_size;
3170         new_tags.extra_is_shrink = oh->is_shrink;
3171         new_tags.extra_equiv_id = oh->equiv_id;
3172         new_tags.extra_shadows = (oh->shadows_obj > 0) ? 1 : 0;
3173         new_tags.extra_obj_type = in->variant_type;
3174
3175         /* Now endian swizzle the oh if needed. */
3176         yaffs_do_endian_oh(dev, oh);
3177
3178         yaffs_verify_oh(in, oh, &new_tags, 1);
3179
3180         /* Create new chunk in NAND */
3181         new_chunk_id =
3182             yaffs_write_new_chunk(dev, buffer, &new_tags,
3183                                   (prev_chunk_id > 0) ? 1 : 0);
3184
3185         if (buffer)
3186                 yaffs_release_temp_buffer(dev, buffer);
3187
3188         if (new_chunk_id < 0)
3189                 return new_chunk_id;
3190
3191         in->hdr_chunk = new_chunk_id;
3192
3193         if (prev_chunk_id > 0)
3194                 yaffs_chunk_del(dev, prev_chunk_id, 1, __LINE__);
3195
3196         if (!yaffs_obj_cache_dirty(in))
3197                 in->dirty = 0;
3198
3199         /* If this was a shrink, then mark the block
3200          * that the chunk lives on */
3201         if (is_shrink) {
3202                 bi = yaffs_get_block_info(in->my_dev,
3203                                           new_chunk_id /
3204                                           in->my_dev->param.chunks_per_block);
3205                 bi->has_shrink_hdr = 1;
3206         }
3207
3208         return new_chunk_id;
3209 }
3210
3211 /*--------------------- File read/write ------------------------
3212  * Read and write have very similar structures.
3213  * In general the read/write has three parts to it
3214  * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3215  * Some complete chunks
3216  * An incomplete chunk to end off with
3217  *
3218  * Curve-balls: the first chunk might also be the last chunk.
3219  */
3220
3221 int yaffs_file_rd(struct yaffs_obj *in, u8 * buffer, loff_t offset, int n_bytes)
3222 {
3223         int chunk;
3224         u32 start;
3225         int n_copy;
3226         int n = n_bytes;
3227         int n_done = 0;
3228         struct yaffs_cache *cache;
3229         struct yaffs_dev *dev;
3230
3231         dev = in->my_dev;
3232
3233         while (n > 0) {
3234                 yaffs_addr_to_chunk(dev, offset, &chunk, &start);
3235                 chunk++;
3236
3237                 /* OK now check for the curveball where the start and end are in
3238                  * the same chunk.
3239                  */
3240                 if ((start + n) < dev->data_bytes_per_chunk)
3241                         n_copy = n;
3242                 else
3243                         n_copy = dev->data_bytes_per_chunk - start;
3244
3245                 cache = yaffs_find_chunk_cache(in, chunk);
3246
3247                 /* If the chunk is already in the cache or it is less than
3248                  * a whole chunk or we're using inband tags then use the cache
3249                  * (if there is caching) else bypass the cache.
3250                  */
3251                 if (cache || n_copy != (int)dev->data_bytes_per_chunk ||
3252                     dev->param.inband_tags) {
3253                         if (dev->param.n_caches > 0) {
3254
3255                                 /* If we can't find the data in the cache,
3256                                  * then load it up. */
3257
3258                                 if (!cache) {
3259                                         cache =
3260                                             yaffs_grab_chunk_cache(in->my_dev);
3261                                         cache->object = in;
3262                                         cache->chunk_id = chunk;
3263                                         cache->dirty = 0;
3264                                         cache->locked = 0;
3265                                         yaffs_rd_data_obj(in, chunk,
3266                                                           cache->data);
3267                                         cache->n_bytes = 0;
3268                                 }
3269
3270                                 yaffs_use_cache(dev, cache, 0);
3271
3272                                 cache->locked = 1;
3273
3274                                 memcpy(buffer, &cache->data[start], n_copy);
3275
3276                                 cache->locked = 0;
3277                         } else {
3278                                 /* Read into the local buffer then copy.. */
3279
3280                                 u8 *local_buffer =
3281                                     yaffs_get_temp_buffer(dev);
3282                                 yaffs_rd_data_obj(in, chunk, local_buffer);
3283
3284                                 memcpy(buffer, &local_buffer[start], n_copy);
3285
3286                                 yaffs_release_temp_buffer(dev, local_buffer);
3287                         }
3288                 } else {
3289                         /* A full chunk. Read directly into the buffer. */
3290                         yaffs_rd_data_obj(in, chunk, buffer);
3291                 }
3292                 n -= n_copy;
3293                 offset += n_copy;
3294                 buffer += n_copy;
3295                 n_done += n_copy;
3296         }
3297         return n_done;
3298 }
3299
3300 int yaffs_do_file_wr(struct yaffs_obj *in, const u8 *buffer, loff_t offset,
3301                      int n_bytes, int write_through)
3302 {
3303
3304         int chunk;
3305         u32 start;
3306         int n_copy;
3307         int n = n_bytes;
3308         int n_done = 0;
3309         int n_writeback;
3310         loff_t start_write = offset;
3311         int chunk_written = 0;
3312         u32 n_bytes_read;
3313         loff_t chunk_start;
3314         struct yaffs_dev *dev;
3315
3316         dev = in->my_dev;
3317
3318         while (n > 0 && chunk_written >= 0) {
3319                 yaffs_addr_to_chunk(dev, offset, &chunk, &start);
3320
3321                 if (((loff_t)chunk) *
3322                     dev->data_bytes_per_chunk + start != offset ||
3323                     start >= dev->data_bytes_per_chunk) {
3324                         yaffs_trace(YAFFS_TRACE_ERROR,
3325                                 "AddrToChunk of offset %lld gives chunk %d start %d",
3326                                 (long  long)offset, chunk, start);
3327                 }
3328                 chunk++;        /* File pos to chunk in file offset */
3329
3330                 /* OK now check for the curveball where the start and end are in
3331                  * the same chunk.
3332                  */
3333
3334                 if ((start + n) < dev->data_bytes_per_chunk) {
3335                         n_copy = n;
3336
3337                         /* Now calculate how many bytes to write back....
3338                          * If we're overwriting and not writing to then end of
3339                          * file then we need to write back as much as was there
3340                          * before.
3341                          */
3342
3343                         chunk_start = (((loff_t)(chunk - 1)) *
3344                                         dev->data_bytes_per_chunk);
3345
3346                         if (chunk_start > in->variant.file_variant.file_size)
3347                                 n_bytes_read = 0;       /* Past end of file */
3348                         else
3349                                 n_bytes_read =
3350                                     in->variant.file_variant.file_size -
3351                                     chunk_start;
3352
3353                         if (n_bytes_read > dev->data_bytes_per_chunk)
3354                                 n_bytes_read = dev->data_bytes_per_chunk;
3355
3356                         n_writeback =
3357                             (n_bytes_read >
3358                              (start + n)) ? n_bytes_read : (start + n);
3359
3360                         if (n_writeback < 0 ||
3361                             n_writeback > (int)dev->data_bytes_per_chunk)
3362                                 BUG();
3363
3364                 } else {
3365                         n_copy = dev->data_bytes_per_chunk - start;
3366                         n_writeback = dev->data_bytes_per_chunk;
3367                 }
3368
3369                 if (n_copy != (int)dev->data_bytes_per_chunk ||
3370                     !dev->param.cache_bypass_aligned ||
3371                     dev->param.inband_tags) {
3372                         /* An incomplete start or end chunk (or maybe both
3373                          * start and end chunk), or we're using inband tags,
3374                          * or we're forcing writes through the cache,
3375                          * so we want to use the cache buffers.
3376                          */
3377                         if (dev->param.n_caches > 0) {
3378                                 struct yaffs_cache *cache;
3379
3380                                 /* If we can't find the data in the cache, then
3381                                  * load the cache */
3382                                 cache = yaffs_find_chunk_cache(in, chunk);
3383
3384                                 if (!cache &&
3385                                     yaffs_check_alloc_available(dev, 1)) {
3386                                         cache = yaffs_grab_chunk_cache(dev);
3387                                         cache->object = in;
3388                                         cache->chunk_id = chunk;
3389                                         cache->dirty = 0;
3390                                         cache->locked = 0;
3391                                         yaffs_rd_data_obj(in, chunk,
3392                                                           cache->data);
3393                                 } else if (cache &&
3394                                            !cache->dirty &&
3395                                            !yaffs_check_alloc_available(dev,
3396                                                                         1)) {
3397                                         /* Drop the cache if it was a read cache
3398                                          * item and no space check has been made
3399                                          * for it.
3400                                          */
3401                                         cache = NULL;
3402                                 }
3403
3404                                 if (cache) {
3405                                         yaffs_use_cache(dev, cache, 1);
3406                                         cache->locked = 1;
3407
3408                                         memcpy(&cache->data[start], buffer,
3409                                                n_copy);
3410
3411                                         cache->locked = 0;
3412                                         cache->n_bytes = n_writeback;
3413
3414                                         if (write_through) {
3415                                                 chunk_written =
3416                                                     yaffs_wr_data_obj
3417                                                     (cache->object,
3418                                                      cache->chunk_id,
3419                                                      cache->data,
3420                                                      cache->n_bytes, 1);
3421                                                 cache->dirty = 0;
3422                                         }
3423                                 } else {
3424                                         chunk_written = -1;     /* fail write */
3425                                 }
3426                         } else {
3427                                 /* An incomplete start or end chunk (or maybe
3428                                  * both start and end chunk). Read into the
3429                                  * local buffer then copy over and write back.
3430                                  */
3431
3432                                 u8 *local_buffer = yaffs_get_temp_buffer(dev);
3433
3434                                 yaffs_rd_data_obj(in, chunk, local_buffer);
3435                                 memcpy(&local_buffer[start], buffer, n_copy);
3436
3437                                 chunk_written =
3438                                     yaffs_wr_data_obj(in, chunk,
3439                                                       local_buffer,
3440                                                       n_writeback, 0);
3441
3442                                 yaffs_release_temp_buffer(dev, local_buffer);
3443                         }
3444                 } else {
3445                         /* A full chunk. Write directly from the buffer. */
3446
3447                         chunk_written =
3448                             yaffs_wr_data_obj(in, chunk, buffer,
3449                                               dev->data_bytes_per_chunk, 0);
3450
3451                         /* Since we've overwritten the cached data,
3452                          * we better invalidate it. */
3453                         yaffs_invalidate_chunk_cache(in, chunk);
3454                 }
3455
3456                 if (chunk_written >= 0) {
3457                         n -= n_copy;
3458                         offset += n_copy;
3459                         buffer += n_copy;
3460                         n_done += n_copy;
3461                 }
3462         }
3463
3464         /* Update file object */
3465
3466         if ((start_write + n_done) > in->variant.file_variant.file_size)
3467                 in->variant.file_variant.file_size = (start_write + n_done);
3468
3469         in->dirty = 1;
3470         return n_done;
3471 }
3472
3473 int yaffs_wr_file(struct yaffs_obj *in, const u8 *buffer, loff_t offset,
3474                   int n_bytes, int write_through)
3475 {
3476         yaffs2_handle_hole(in, offset);
3477         return yaffs_do_file_wr(in, buffer, offset, n_bytes, write_through);
3478 }
3479
3480 /* ---------------------- File resizing stuff ------------------ */
3481
3482 static void yaffs_prune_chunks(struct yaffs_obj *in, loff_t new_size)
3483 {
3484
3485         struct yaffs_dev *dev = in->my_dev;
3486         loff_t old_size = in->variant.file_variant.file_size;
3487         int i;
3488         int chunk_id;
3489         u32 dummy;
3490         int last_del;
3491         int start_del;
3492
3493         if (old_size > 0)
3494                 yaffs_addr_to_chunk(dev, old_size - 1, &last_del, &dummy);
3495         else
3496                 last_del = 0;
3497
3498         yaffs_addr_to_chunk(dev, new_size + dev->data_bytes_per_chunk - 1,
3499                                 &start_del, &dummy);
3500         last_del++;
3501         start_del++;
3502
3503         /* Delete backwards so that we don't end up with holes if
3504          * power is lost part-way through the operation.
3505          */
3506         for (i = last_del; i >= start_del; i--) {
3507                 /* NB this could be optimised somewhat,
3508                  * eg. could retrieve the tags and write them without
3509                  * using yaffs_chunk_del
3510                  */
3511
3512                 chunk_id = yaffs_find_del_file_chunk(in, i, NULL);
3513
3514                 if (chunk_id < 1)
3515                         continue;
3516
3517                 if ((u32)chunk_id <
3518                     (dev->internal_start_block * dev->param.chunks_per_block) ||
3519                     (u32)chunk_id >=
3520                     ((dev->internal_end_block + 1) *
3521                       dev->param.chunks_per_block)) {
3522                         yaffs_trace(YAFFS_TRACE_ALWAYS,
3523                                 "Found daft chunk_id %d for %d",
3524                                 chunk_id, i);
3525                 } else {
3526                         in->n_data_chunks--;
3527                         yaffs_chunk_del(dev, chunk_id, 1, __LINE__);
3528                 }
3529         }
3530 }
3531
3532 void yaffs_resize_file_down(struct yaffs_obj *obj, loff_t new_size)
3533 {
3534         int new_full;
3535         u32 new_partial;
3536         struct yaffs_dev *dev = obj->my_dev;
3537
3538         yaffs_addr_to_chunk(dev, new_size, &new_full, &new_partial);
3539
3540         yaffs_prune_chunks(obj, new_size);
3541
3542         if (new_partial != 0) {
3543                 int last_chunk = 1 + new_full;
3544                 u8 *local_buffer = yaffs_get_temp_buffer(dev);
3545
3546                 /* Rewrite the last chunk with its new size and zero pad */
3547                 yaffs_rd_data_obj(obj, last_chunk, local_buffer);
3548                 memset(local_buffer + new_partial, 0,
3549                        dev->data_bytes_per_chunk - new_partial);
3550
3551                 yaffs_wr_data_obj(obj, last_chunk, local_buffer,
3552                                   new_partial, 1);
3553
3554                 yaffs_release_temp_buffer(dev, local_buffer);
3555         }
3556
3557         obj->variant.file_variant.file_size = new_size;
3558         obj->variant.file_variant.stored_size = new_size;
3559
3560         yaffs_prune_tree(dev, &obj->variant.file_variant);
3561 }
3562
3563 int yaffs_resize_file(struct yaffs_obj *in, loff_t new_size)
3564 {
3565         struct yaffs_dev *dev = in->my_dev;
3566         loff_t old_size = in->variant.file_variant.file_size;
3567
3568         yaffs_flush_file_cache(in, 1);
3569         yaffs_invalidate_file_cache(in);
3570
3571         yaffs_check_gc(dev, 0);
3572
3573         if (in->variant_type != YAFFS_OBJECT_TYPE_FILE)
3574                 return YAFFS_FAIL;
3575
3576         if (new_size == old_size)
3577                 return YAFFS_OK;
3578
3579         if (new_size > old_size) {
3580                 yaffs2_handle_hole(in, new_size);
3581                 in->variant.file_variant.file_size = new_size;
3582         } else {
3583                 /* new_size < old_size */
3584                 yaffs_resize_file_down(in, new_size);
3585         }
3586
3587         /* Write a new object header to reflect the resize.
3588          * show we've shrunk the file, if need be
3589          * Do this only if the file is not in the deleted directories
3590          * and is not shadowed.
3591          */
3592         if (in->parent &&
3593             !in->is_shadowed &&
3594             in->parent->obj_id != YAFFS_OBJECTID_UNLINKED &&
3595             in->parent->obj_id != YAFFS_OBJECTID_DELETED)
3596                 yaffs_update_oh(in, NULL, 0, 0, 0, NULL);
3597
3598         return YAFFS_OK;
3599 }
3600
3601 int yaffs_flush_file(struct yaffs_obj *in,
3602                      int update_time,
3603                      int data_sync,
3604                      int discard_cache)
3605 {
3606         if (!in->dirty)
3607                 return YAFFS_OK;
3608
3609         yaffs_flush_file_cache(in, discard_cache);
3610
3611         if (data_sync)
3612                 return YAFFS_OK;
3613
3614         if (update_time)
3615                 yaffs_load_current_time(in, 0, 0);
3616
3617         return (yaffs_update_oh(in, NULL, 0, 0, 0, NULL) >= 0) ?
3618                                 YAFFS_OK : YAFFS_FAIL;
3619 }
3620
3621
3622 /* yaffs_del_file deletes the whole file data
3623  * and the inode associated with the file.
3624  * It does not delete the links associated with the file.
3625  */
3626 static int yaffs_unlink_file_if_needed(struct yaffs_obj *in)
3627 {
3628         int ret_val;
3629         int del_now = 0;
3630         struct yaffs_dev *dev = in->my_dev;
3631
3632         if (!in->my_inode)
3633                 del_now = 1;
3634
3635         if (del_now) {
3636                 ret_val =
3637                     yaffs_change_obj_name(in, in->my_dev->del_dir,
3638                                           _Y("deleted"), 0, 0);
3639                 yaffs_trace(YAFFS_TRACE_TRACING,
3640                         "yaffs: immediate deletion of file %d",
3641                         in->obj_id);
3642                 in->deleted = 1;
3643                 in->my_dev->n_deleted_files++;
3644                 if (dev->param.disable_soft_del || dev->param.is_yaffs2)
3645                         yaffs_resize_file(in, 0);
3646                 yaffs_soft_del_file(in);
3647         } else {
3648                 ret_val =
3649                     yaffs_change_obj_name(in, in->my_dev->unlinked_dir,
3650                                           _Y("unlinked"), 0, 0);
3651         }
3652         return ret_val;
3653 }
3654
3655 static int yaffs_del_file(struct yaffs_obj *in)
3656 {
3657         int ret_val = YAFFS_OK;
3658         int deleted;    /* Need to cache value on stack if in is freed */
3659         struct yaffs_dev *dev = in->my_dev;
3660
3661         if (dev->param.disable_soft_del || dev->param.is_yaffs2)
3662                 yaffs_resize_file(in, 0);
3663
3664         if (in->n_data_chunks > 0) {
3665                 /* Use soft deletion if there is data in the file.
3666                  * That won't be the case if it has been resized to zero.
3667                  */
3668                 if (!in->unlinked)
3669                         ret_val = yaffs_unlink_file_if_needed(in);
3670
3671                 deleted = in->deleted;
3672
3673                 if (ret_val == YAFFS_OK && in->unlinked && !in->deleted) {
3674                         in->deleted = 1;
3675                         deleted = 1;
3676                         in->my_dev->n_deleted_files++;
3677                         yaffs_soft_del_file(in);
3678                 }
3679                 return deleted ? YAFFS_OK : YAFFS_FAIL;
3680         } else {
3681                 /* The file has no data chunks so we toss it immediately */
3682                 yaffs_free_tnode(in->my_dev, in->variant.file_variant.top);
3683                 in->variant.file_variant.top = NULL;
3684                 yaffs_generic_obj_del(in);
3685
3686                 return YAFFS_OK;
3687         }
3688 }
3689
3690 int yaffs_is_non_empty_dir(struct yaffs_obj *obj)
3691 {
3692         return (obj &&
3693                 obj->variant_type == YAFFS_OBJECT_TYPE_DIRECTORY) &&
3694                 !(list_empty(&obj->variant.dir_variant.children));
3695 }
3696
3697 static int yaffs_del_dir(struct yaffs_obj *obj)
3698 {
3699         /* First check that the directory is empty. */
3700         if (yaffs_is_non_empty_dir(obj))
3701                 return YAFFS_FAIL;
3702
3703         return yaffs_generic_obj_del(obj);
3704 }
3705
3706 static int yaffs_del_symlink(struct yaffs_obj *in)
3707 {
3708         kfree(in->variant.symlink_variant.alias);
3709         in->variant.symlink_variant.alias = NULL;
3710
3711         return yaffs_generic_obj_del(in);
3712 }
3713
3714 static int yaffs_del_link(struct yaffs_obj *in)
3715 {
3716         /* remove this hardlink from the list associated with the equivalent
3717          * object
3718          */
3719         list_del_init(&in->hard_links);
3720         return yaffs_generic_obj_del(in);
3721 }
3722
3723 int yaffs_del_obj(struct yaffs_obj *obj)
3724 {
3725         int ret_val = -1;
3726
3727         switch (obj->variant_type) {
3728         case YAFFS_OBJECT_TYPE_FILE:
3729                 ret_val = yaffs_del_file(obj);
3730                 break;
3731         case YAFFS_OBJECT_TYPE_DIRECTORY:
3732                 if (!list_empty(&obj->variant.dir_variant.dirty)) {
3733                         yaffs_trace(YAFFS_TRACE_BACKGROUND,
3734                                 "Remove object %d from dirty directories",
3735                                 obj->obj_id);
3736                         list_del_init(&obj->variant.dir_variant.dirty);
3737                 }
3738                 return yaffs_del_dir(obj);
3739                 break;
3740         case YAFFS_OBJECT_TYPE_SYMLINK:
3741                 ret_val = yaffs_del_symlink(obj);
3742                 break;
3743         case YAFFS_OBJECT_TYPE_HARDLINK:
3744                 ret_val = yaffs_del_link(obj);
3745                 break;
3746         case YAFFS_OBJECT_TYPE_SPECIAL:
3747                 ret_val = yaffs_generic_obj_del(obj);
3748                 break;
3749         case YAFFS_OBJECT_TYPE_UNKNOWN:
3750                 ret_val = 0;
3751                 break;          /* should not happen. */
3752         }
3753         return ret_val;
3754 }
3755
3756
3757 static void yaffs_empty_dir_to_dir(struct yaffs_obj *from_dir,
3758                                    struct yaffs_obj *to_dir)
3759 {
3760         struct yaffs_obj *obj;
3761         struct list_head *lh;
3762         struct list_head *n;
3763
3764         list_for_each_safe(lh, n, &from_dir->variant.dir_variant.children) {
3765                 obj = list_entry(lh, struct yaffs_obj, siblings);
3766                 yaffs_add_obj_to_dir(to_dir, obj);
3767         }
3768 }
3769
3770 struct yaffs_obj *yaffs_retype_obj(struct yaffs_obj *obj,
3771                                    enum yaffs_obj_type type)
3772 {
3773         /* Tear down the old variant */
3774         switch (obj->variant_type) {
3775         case YAFFS_OBJECT_TYPE_FILE:
3776                 /* Nuke file data */
3777                 yaffs_resize_file(obj, 0);
3778                 yaffs_free_tnode(obj->my_dev, obj->variant.file_variant.top);
3779                 obj->variant.file_variant.top = NULL;
3780                 break;
3781         case YAFFS_OBJECT_TYPE_DIRECTORY:
3782                 /* Put the children in lost and found. */
3783                 yaffs_empty_dir_to_dir(obj, obj->my_dev->lost_n_found);
3784                 if (!list_empty(&obj->variant.dir_variant.dirty))
3785                         list_del_init(&obj->variant.dir_variant.dirty);
3786                 break;
3787         case YAFFS_OBJECT_TYPE_SYMLINK:
3788                 /* Nuke symplink data */
3789                 kfree(obj->variant.symlink_variant.alias);
3790                 obj->variant.symlink_variant.alias = NULL;
3791                 break;
3792         case YAFFS_OBJECT_TYPE_HARDLINK:
3793                 list_del_init(&obj->hard_links);
3794                 break;
3795         default:
3796                 break;
3797         }
3798
3799         memset(&obj->variant, 0, sizeof(obj->variant));
3800
3801         /*Set up new variant if the memset is not enough. */
3802         switch (type) {
3803         case YAFFS_OBJECT_TYPE_DIRECTORY:
3804                 INIT_LIST_HEAD(&obj->variant.dir_variant.children);
3805                 INIT_LIST_HEAD(&obj->variant.dir_variant.dirty);
3806                 break;
3807         case YAFFS_OBJECT_TYPE_FILE:
3808         case YAFFS_OBJECT_TYPE_SYMLINK:
3809         case YAFFS_OBJECT_TYPE_HARDLINK:
3810         default:
3811                 break;
3812         }
3813
3814         obj->variant_type = type;
3815
3816         return obj;
3817
3818 }
3819
3820 static int yaffs_unlink_worker(struct yaffs_obj *obj)
3821 {
3822         int del_now = 0;
3823
3824         if (!obj)
3825                 return YAFFS_FAIL;
3826
3827         if (!obj->my_inode)
3828                 del_now = 1;
3829
3830         yaffs_update_parent(obj->parent);
3831
3832         if (obj->variant_type == YAFFS_OBJECT_TYPE_HARDLINK) {
3833                 return yaffs_del_link(obj);
3834         } else if (!list_empty(&obj->hard_links)) {
3835                 /* Curve ball: We're unlinking an object that has a hardlink.
3836                  *
3837                  * This problem arises because we are not strictly following
3838                  * The Linux link/inode model.
3839                  *
3840                  * We can't really delete the object.
3841                  * Instead, we do the following:
3842                  * - Select a hardlink.
3843                  * - Unhook it from the hard links
3844                  * - Move it from its parent directory so that the rename works.
3845                  * - Rename the object to the hardlink's name.
3846                  * - Delete the hardlink
3847                  */
3848
3849                 struct yaffs_obj *hl;
3850                 struct yaffs_obj *parent;
3851                 int ret_val;
3852                 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
3853
3854                 hl = list_entry(obj->hard_links.next, struct yaffs_obj,
3855                                 hard_links);
3856
3857                 yaffs_get_obj_name(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
3858                 parent = hl->parent;
3859
3860                 list_del_init(&hl->hard_links);
3861
3862                 yaffs_add_obj_to_dir(obj->my_dev->unlinked_dir, hl);
3863
3864                 ret_val = yaffs_change_obj_name(obj, parent, name, 0, 0);
3865
3866                 if (ret_val == YAFFS_OK)
3867                         ret_val = yaffs_generic_obj_del(hl);
3868
3869                 return ret_val;
3870
3871         } else if (del_now) {
3872                 switch (obj->variant_type) {
3873                 case YAFFS_OBJECT_TYPE_FILE:
3874                         return yaffs_del_file(obj);
3875                         break;
3876                 case YAFFS_OBJECT_TYPE_DIRECTORY:
3877                         list_del_init(&obj->variant.dir_variant.dirty);
3878                         return yaffs_del_dir(obj);
3879                         break;
3880                 case YAFFS_OBJECT_TYPE_SYMLINK:
3881                         return yaffs_del_symlink(obj);
3882                         break;
3883                 case YAFFS_OBJECT_TYPE_SPECIAL:
3884                         return yaffs_generic_obj_del(obj);
3885                         break;
3886                 case YAFFS_OBJECT_TYPE_HARDLINK:
3887                 case YAFFS_OBJECT_TYPE_UNKNOWN:
3888                 default:
3889                         return YAFFS_FAIL;
3890                 }
3891         } else if (yaffs_is_non_empty_dir(obj)) {
3892                 return YAFFS_FAIL;
3893         } else {
3894                 return yaffs_change_obj_name(obj, obj->my_dev->unlinked_dir,
3895                                                 _Y("unlinked"), 0, 0);
3896         }
3897 }
3898
3899 int yaffs_unlink_obj(struct yaffs_obj *obj)
3900 {
3901         if (obj && obj->unlink_allowed)
3902                 return yaffs_unlink_worker(obj);
3903
3904         return YAFFS_FAIL;
3905 }
3906
3907 int yaffs_unlinker(struct yaffs_obj *dir, const YCHAR *name)
3908 {
3909         struct yaffs_obj *obj;
3910
3911         obj = yaffs_find_by_name(dir, name);
3912         return yaffs_unlink_obj(obj);
3913 }
3914
3915 /* Note:
3916  * If old_name is NULL then we take old_dir as the object to be renamed.
3917  */
3918 int yaffs_rename_obj(struct yaffs_obj *old_dir, const YCHAR *old_name,
3919                      struct yaffs_obj *new_dir, const YCHAR *new_name)
3920 {
3921         struct yaffs_obj *obj = NULL;
3922         struct yaffs_obj *existing_target = NULL;
3923         int force = 0;
3924         int result;
3925         struct yaffs_dev *dev;
3926
3927         if (!old_dir || old_dir->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY) {
3928                 BUG();
3929                 return YAFFS_FAIL;
3930         }
3931         if (!new_dir || new_dir->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY) {
3932                 BUG();
3933                 return YAFFS_FAIL;
3934         }
3935
3936         dev = old_dir->my_dev;
3937
3938 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
3939         /* Special case for case insemsitive systems.
3940          * While look-up is case insensitive, the name isn't.
3941          * Therefore we might want to change x.txt to X.txt
3942          */
3943         if (old_dir == new_dir &&
3944                 old_name && new_name &&
3945                 strcmp(old_name, new_name) == 0)
3946                 force = 1;
3947 #endif
3948
3949         if (strnlen(new_name, YAFFS_MAX_NAME_LENGTH + 1) >
3950             YAFFS_MAX_NAME_LENGTH)
3951                 /* ENAMETOOLONG */
3952                 return YAFFS_FAIL;
3953
3954         if (old_name)
3955                 obj = yaffs_find_by_name(old_dir, old_name);
3956         else{
3957                 obj = old_dir;
3958                 old_dir = obj->parent;
3959         }
3960
3961         if (obj && obj->rename_allowed) {
3962                 /* Now handle an existing target, if there is one */
3963                 existing_target = yaffs_find_by_name(new_dir, new_name);
3964                 if (yaffs_is_non_empty_dir(existing_target)) {
3965                         return YAFFS_FAIL;      /* ENOTEMPTY */
3966                 } else if (existing_target && existing_target != obj) {
3967                         /* Nuke the target first, using shadowing,
3968                          * but only if it isn't the same object.
3969                          *
3970                          * Note we must disable gc here otherwise it can mess
3971                          * up the shadowing.
3972                          *
3973                          */
3974                         dev->gc_disable = 1;
3975                         yaffs_change_obj_name(obj, new_dir, new_name, force,
3976                                               existing_target->obj_id);
3977                         existing_target->is_shadowed = 1;
3978                         yaffs_unlink_obj(existing_target);
3979                         dev->gc_disable = 0;
3980                 }
3981
3982                 result = yaffs_change_obj_name(obj, new_dir, new_name, 1, 0);
3983
3984                 yaffs_update_parent(old_dir);
3985                 if (new_dir != old_dir)
3986                         yaffs_update_parent(new_dir);
3987
3988                 return result;
3989         }
3990         return YAFFS_FAIL;
3991 }
3992
3993 /*----------------------- Initialisation Scanning ---------------------- */
3994
3995 void yaffs_handle_shadowed_obj(struct yaffs_dev *dev, int obj_id,
3996                                int backward_scanning)
3997 {
3998         struct yaffs_obj *obj;
3999
4000         if (backward_scanning) {
4001                 /* Handle YAFFS2 case (backward scanning)
4002                  * If the shadowed object exists then ignore.
4003                  */
4004                 obj = yaffs_find_by_number(dev, obj_id);
4005                 if (obj)
4006                         return;
4007         }
4008
4009         /* Let's create it (if it does not exist) assuming it is a file so that
4010          * it can do shrinking etc.
4011          * We put it in unlinked dir to be cleaned up after the scanning
4012          */
4013         obj =
4014             yaffs_find_or_create_by_number(dev, obj_id, YAFFS_OBJECT_TYPE_FILE);
4015         if (!obj)
4016                 return;
4017         obj->is_shadowed = 1;
4018         yaffs_add_obj_to_dir(dev->unlinked_dir, obj);
4019         obj->variant.file_variant.shrink_size = 0;
4020         obj->valid = 1;         /* So that we don't read any other info. */
4021 }
4022
4023 void yaffs_link_fixup(struct yaffs_dev *dev, struct list_head *hard_list)
4024 {
4025         struct list_head *lh;
4026         struct list_head *save;
4027         struct yaffs_obj *hl;
4028         struct yaffs_obj *in;
4029
4030         list_for_each_safe(lh, save, hard_list) {
4031                 hl = list_entry(lh, struct yaffs_obj, hard_links);
4032                 in = yaffs_find_by_number(dev,
4033                                         hl->variant.hardlink_variant.equiv_id);
4034
4035                 if (in) {
4036                         /* Add the hardlink pointers */
4037                         hl->variant.hardlink_variant.equiv_obj = in;
4038                         list_add(&hl->hard_links, &in->hard_links);
4039                 } else {
4040                         /* Todo Need to report/handle this better.
4041                          * Got a problem... hardlink to a non-existant object
4042                          */
4043                         hl->variant.hardlink_variant.equiv_obj = NULL;
4044                         INIT_LIST_HEAD(&hl->hard_links);
4045                 }
4046         }
4047 }
4048
4049 static void yaffs_strip_deleted_objs(struct yaffs_dev *dev)
4050 {
4051         /*
4052          *  Sort out state of unlinked and deleted objects after scanning.
4053          */
4054         struct list_head *i;
4055         struct list_head *n;
4056         struct yaffs_obj *l;
4057
4058         if (dev->read_only)
4059                 return;
4060
4061         /* Soft delete all the unlinked files */
4062         list_for_each_safe(i, n,
4063                            &dev->unlinked_dir->variant.dir_variant.children) {
4064                 l = list_entry(i, struct yaffs_obj, siblings);
4065                 yaffs_del_obj(l);
4066         }
4067
4068         list_for_each_safe(i, n, &dev->del_dir->variant.dir_variant.children) {
4069                 l = list_entry(i, struct yaffs_obj, siblings);
4070                 yaffs_del_obj(l);
4071         }
4072 }
4073
4074 /*
4075  * This code iterates through all the objects making sure that they are rooted.
4076  * Any unrooted objects are re-rooted in lost+found.
4077  * An object needs to be in one of:
4078  * - Directly under deleted, unlinked
4079  * - Directly or indirectly under root.
4080  *
4081  * Note:
4082  *  This code assumes that we don't ever change the current relationships
4083  *  between directories:
4084  *   root_dir->parent == unlinked_dir->parent == del_dir->parent == NULL
4085  *   lost-n-found->parent == root_dir
4086  *
4087  * This fixes the problem where directories might have inadvertently been
4088  * deleted leaving the object "hanging" without being rooted in the
4089  * directory tree.
4090  */
4091
4092 static int yaffs_has_null_parent(struct yaffs_dev *dev, struct yaffs_obj *obj)
4093 {
4094         return (obj == dev->del_dir ||
4095                 obj == dev->unlinked_dir || obj == dev->root_dir);
4096 }
4097
4098 static void yaffs_fix_hanging_objs(struct yaffs_dev *dev)
4099 {
4100         struct yaffs_obj *obj;
4101         struct yaffs_obj *parent;
4102         int i;
4103         struct list_head *lh;
4104         struct list_head *n;
4105         int depth_limit;
4106         int hanging;
4107
4108         if (dev->read_only)
4109                 return;
4110
4111         /* Iterate through the objects in each hash entry,
4112          * looking at each object.
4113          * Make sure it is rooted.
4114          */
4115
4116         for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
4117                 list_for_each_safe(lh, n, &dev->obj_bucket[i].list) {
4118                         obj = list_entry(lh, struct yaffs_obj, hash_link);
4119                         parent = obj->parent;
4120
4121                         if (yaffs_has_null_parent(dev, obj)) {
4122                                 /* These directories are not hanging */
4123                                 hanging = 0;
4124                         } else if (!parent ||
4125                                    parent->variant_type !=
4126                                    YAFFS_OBJECT_TYPE_DIRECTORY) {
4127                                 hanging = 1;
4128                         } else if (yaffs_has_null_parent(dev, parent)) {
4129                                 hanging = 0;
4130                         } else {
4131                                 /*
4132                                  * Need to follow the parent chain to
4133                                  * see if it is hanging.
4134                                  */
4135                                 hanging = 0;
4136                                 depth_limit = 100;
4137
4138                                 while (parent != dev->root_dir &&
4139                                        parent->parent &&
4140                                        parent->parent->variant_type ==
4141                                        YAFFS_OBJECT_TYPE_DIRECTORY &&
4142                                        depth_limit > 0) {
4143                                         parent = parent->parent;
4144                                         depth_limit--;
4145                                 }
4146                                 if (parent != dev->root_dir)
4147                                         hanging = 1;
4148                         }
4149                         if (hanging) {
4150                                 yaffs_trace(YAFFS_TRACE_SCAN,
4151                                         "Hanging object %d moved to lost and found",
4152                                         obj->obj_id);
4153                                 yaffs_add_obj_to_dir(dev->lost_n_found, obj);
4154                         }
4155                 }
4156         }
4157 }
4158
4159 /*
4160  * Delete directory contents for cleaning up lost and found.
4161  */
4162 static void yaffs_del_dir_contents(struct yaffs_obj *dir)
4163 {
4164         struct yaffs_obj *obj;
4165         struct list_head *lh;
4166         struct list_head *n;
4167
4168         if (dir->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY)
4169                 BUG();
4170
4171         list_for_each_safe(lh, n, &dir->variant.dir_variant.children) {
4172                 obj = list_entry(lh, struct yaffs_obj, siblings);
4173                 if (obj->variant_type == YAFFS_OBJECT_TYPE_DIRECTORY)
4174                         yaffs_del_dir_contents(obj);
4175                 yaffs_trace(YAFFS_TRACE_SCAN,
4176                         "Deleting lost_found object %d",
4177                         obj->obj_id);
4178                 yaffs_unlink_obj(obj);
4179         }
4180 }
4181
4182 static void yaffs_empty_l_n_f(struct yaffs_dev *dev)
4183 {
4184         yaffs_del_dir_contents(dev->lost_n_found);
4185 }
4186
4187
4188 struct yaffs_obj *yaffs_find_by_name(struct yaffs_obj *directory,
4189                                      const YCHAR *name)
4190 {
4191         int sum;
4192         struct list_head *i;
4193         YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
4194         struct yaffs_obj *l;
4195
4196         if (!name)
4197                 return NULL;
4198
4199         if (!directory) {
4200                 yaffs_trace(YAFFS_TRACE_ALWAYS,
4201                         "tragedy: yaffs_find_by_name: null pointer directory"
4202                         );
4203                 BUG();
4204                 return NULL;
4205         }
4206         if (directory->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY) {
4207                 yaffs_trace(YAFFS_TRACE_ALWAYS,
4208                         "tragedy: yaffs_find_by_name: non-directory"
4209                         );
4210                 BUG();
4211         }
4212
4213         sum = yaffs_calc_name_sum(name);
4214
4215         list_for_each(i, &directory->variant.dir_variant.children) {
4216                 l = list_entry(i, struct yaffs_obj, siblings);
4217
4218                 if (l->parent != directory)
4219                         BUG();
4220
4221                 yaffs_check_obj_details_loaded(l);
4222
4223                 /* Special case for lost-n-found */
4224                 if (l->obj_id == YAFFS_OBJECTID_LOSTNFOUND) {
4225                         if (!strcmp(name, YAFFS_LOSTNFOUND_NAME))
4226                                 return l;
4227                 } else if (l->sum == sum || l->hdr_chunk <= 0) {
4228                         /* LostnFound chunk called Objxxx
4229                          * Do a real check
4230                          */
4231                         yaffs_get_obj_name(l, buffer,
4232                                 YAFFS_MAX_NAME_LENGTH + 1);
4233                         if (!strncmp(name, buffer, YAFFS_MAX_NAME_LENGTH))
4234                                 return l;
4235                 }
4236         }
4237         return NULL;
4238 }
4239
4240 /* GetEquivalentObject dereferences any hard links to get to the
4241  * actual object.
4242  */
4243
4244 struct yaffs_obj *yaffs_get_equivalent_obj(struct yaffs_obj *obj)
4245 {
4246         if (obj && obj->variant_type == YAFFS_OBJECT_TYPE_HARDLINK) {
4247                 obj = obj->variant.hardlink_variant.equiv_obj;
4248                 yaffs_check_obj_details_loaded(obj);
4249         }
4250         return obj;
4251 }
4252
4253 /*
4254  *  A note or two on object names.
4255  *  * If the object name is missing, we then make one up in the form objnnn
4256  *
4257  *  * ASCII names are stored in the object header's name field from byte zero
4258  *  * Unicode names are historically stored starting from byte zero.
4259  *
4260  * Then there are automatic Unicode names...
4261  * The purpose of these is to save names in a way that can be read as
4262  * ASCII or Unicode names as appropriate, thus allowing a Unicode and ASCII
4263  * system to share files.
4264  *
4265  * These automatic unicode are stored slightly differently...
4266  *  - If the name can fit in the ASCII character space then they are saved as
4267  *    ascii names as per above.
4268  *  - If the name needs Unicode then the name is saved in Unicode
4269  *    starting at oh->name[1].
4270
4271  */
4272 static void yaffs_fix_null_name(struct yaffs_obj *obj, YCHAR *name,
4273                                 int buffer_size)
4274 {
4275         /* Create an object name if we could not find one. */
4276         if (strnlen(name, YAFFS_MAX_NAME_LENGTH) == 0) {
4277                 YCHAR local_name[20];
4278                 YCHAR num_string[20];
4279                 YCHAR *x = &num_string[19];
4280                 unsigned v = obj->obj_id;
4281                 num_string[19] = 0;
4282                 while (v > 0) {
4283                         x--;
4284                         *x = '0' + (v % 10);
4285                         v /= 10;
4286                 }
4287                 /* make up a name */
4288                 strcpy(local_name, YAFFS_LOSTNFOUND_PREFIX);
4289                 strcat(local_name, x);
4290                 strncpy(name, local_name, buffer_size - 1);
4291         }
4292 }
4293
4294 int yaffs_get_obj_name(struct yaffs_obj *obj, YCHAR *name, int buffer_size)
4295 {
4296         memset(name, 0, buffer_size * sizeof(YCHAR));
4297         yaffs_check_obj_details_loaded(obj);
4298         if (obj->obj_id == YAFFS_OBJECTID_LOSTNFOUND) {
4299                 strncpy(name, YAFFS_LOSTNFOUND_NAME, buffer_size - 1);
4300         } else if (obj->short_name[0]) {
4301                 strcpy(name, obj->short_name);
4302         } else if (obj->hdr_chunk > 0) {
4303                 int result;
4304                 u8 *buffer = yaffs_get_temp_buffer(obj->my_dev);
4305
4306                 struct yaffs_obj_hdr *oh = (struct yaffs_obj_hdr *)buffer;
4307
4308                 memset(buffer, 0, obj->my_dev->data_bytes_per_chunk);
4309
4310                 if (obj->hdr_chunk > 0) {
4311                         result = yaffs_rd_chunk_tags_nand(obj->my_dev,
4312                                 obj->hdr_chunk, buffer, NULL);
4313                         if (result == YAFFS_OK)
4314                                 yaffs_load_name_from_oh(obj->my_dev, name,
4315                                         oh->name, buffer_size);
4316                 }
4317                 yaffs_release_temp_buffer(obj->my_dev, buffer);
4318         }
4319
4320         yaffs_fix_null_name(obj, name, buffer_size);
4321
4322         return strnlen(name, YAFFS_MAX_NAME_LENGTH);
4323 }
4324
4325 loff_t yaffs_get_obj_length(struct yaffs_obj *obj)
4326 {
4327         /* Dereference any hard linking */
4328         obj = yaffs_get_equivalent_obj(obj);
4329
4330         if (obj->variant_type == YAFFS_OBJECT_TYPE_FILE)
4331                 return obj->variant.file_variant.file_size;
4332         if (obj->variant_type == YAFFS_OBJECT_TYPE_SYMLINK) {
4333                 if (!obj->variant.symlink_variant.alias)
4334                         return 0;
4335                 return strnlen(obj->variant.symlink_variant.alias,
4336                                      YAFFS_MAX_ALIAS_LENGTH);
4337         } else {
4338                 /* Only a directory should drop through to here */
4339                 return obj->my_dev->data_bytes_per_chunk;
4340         }
4341 }
4342
4343 int yaffs_get_obj_link_count(struct yaffs_obj *obj)
4344 {
4345         int count = 0;
4346         struct list_head *i;
4347
4348         if (!obj->unlinked)
4349                 count++;        /* the object itself */
4350
4351         list_for_each(i, &obj->hard_links)
4352             count++;            /* add the hard links; */
4353
4354         return count;
4355 }
4356
4357 int yaffs_get_obj_inode(struct yaffs_obj *obj)
4358 {
4359         obj = yaffs_get_equivalent_obj(obj);
4360
4361         return obj->obj_id;
4362 }
4363
4364 unsigned yaffs_get_obj_type(struct yaffs_obj *obj)
4365 {
4366         obj = yaffs_get_equivalent_obj(obj);
4367
4368         switch (obj->variant_type) {
4369         case YAFFS_OBJECT_TYPE_FILE:
4370                 return DT_REG;
4371                 break;
4372         case YAFFS_OBJECT_TYPE_DIRECTORY:
4373                 return DT_DIR;
4374                 break;
4375         case YAFFS_OBJECT_TYPE_SYMLINK:
4376                 return DT_LNK;
4377                 break;
4378         case YAFFS_OBJECT_TYPE_HARDLINK:
4379                 return DT_REG;
4380                 break;
4381         case YAFFS_OBJECT_TYPE_SPECIAL:
4382                 if (S_ISFIFO(obj->yst_mode))
4383                         return DT_FIFO;
4384                 if (S_ISCHR(obj->yst_mode))
4385                         return DT_CHR;
4386                 if (S_ISBLK(obj->yst_mode))
4387                         return DT_BLK;
4388                 if (S_ISSOCK(obj->yst_mode))
4389                         return DT_SOCK;
4390                 return DT_REG;
4391                 break;
4392         default:
4393                 return DT_REG;
4394                 break;
4395         }
4396 }
4397
4398 YCHAR *yaffs_get_symlink_alias(struct yaffs_obj *obj)
4399 {
4400         obj = yaffs_get_equivalent_obj(obj);
4401         if (obj->variant_type == YAFFS_OBJECT_TYPE_SYMLINK)
4402                 return yaffs_clone_str(obj->variant.symlink_variant.alias);
4403         else
4404                 return yaffs_clone_str(_Y(""));
4405 }
4406
4407 /*--------------------------- Initialisation code -------------------------- */
4408
4409 static int yaffs_check_dev_fns(struct yaffs_dev *dev)
4410 {
4411         struct yaffs_driver *drv = &dev->drv;
4412         struct yaffs_tags_handler *tagger = &dev->tagger;
4413
4414         /* Common functions, gotta have */
4415         if (!drv->drv_read_chunk_fn ||
4416             !drv->drv_write_chunk_fn ||
4417             !drv->drv_erase_fn)
4418                 return 0;
4419
4420         if (dev->param.is_yaffs2 &&
4421              (!drv->drv_mark_bad_fn  || !drv->drv_check_bad_fn))
4422                 return 0;
4423
4424         /* Install the default tags marshalling functions if needed. */
4425         yaffs_tags_compat_install(dev);
4426         yaffs_tags_marshall_install(dev);
4427
4428         /* Check we now have the marshalling functions required. */
4429         if (!tagger->write_chunk_tags_fn ||
4430             !tagger->read_chunk_tags_fn ||
4431             !tagger->query_block_fn ||
4432             !tagger->mark_bad_fn)
4433                 return 0;
4434
4435         return 1;
4436 }
4437
4438 static int yaffs_create_initial_dir(struct yaffs_dev *dev)
4439 {
4440         /* Initialise the unlinked, deleted, root and lost+found directories */
4441         dev->lost_n_found = NULL;
4442         dev->root_dir = NULL;
4443         dev->unlinked_dir = NULL;
4444         dev->del_dir = NULL;
4445
4446         dev->unlinked_dir =
4447             yaffs_create_fake_dir(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
4448         dev->del_dir =
4449             yaffs_create_fake_dir(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
4450         dev->root_dir =
4451             yaffs_create_fake_dir(dev, YAFFS_OBJECTID_ROOT,
4452                                   YAFFS_ROOT_MODE | S_IFDIR);
4453         dev->lost_n_found =
4454             yaffs_create_fake_dir(dev, YAFFS_OBJECTID_LOSTNFOUND,
4455                                   YAFFS_LOSTNFOUND_MODE | S_IFDIR);
4456
4457         if (dev->lost_n_found &&
4458                 dev->root_dir &&
4459                 dev->unlinked_dir &&
4460                 dev->del_dir) {
4461                         /* If lost-n-found is hidden then yank it out of the directory tree. */
4462                         if (dev->param.hide_lost_n_found)
4463                                 list_del_init(&dev->lost_n_found->siblings);
4464                         else
4465                                 yaffs_add_obj_to_dir(dev->root_dir, dev->lost_n_found);
4466                 return YAFFS_OK;
4467         }
4468         return YAFFS_FAIL;
4469 }
4470
4471 /* Low level init.
4472  * Typically only used by yaffs_guts_initialise, but also used by the
4473  * Low level yaffs driver tests.
4474  */
4475
4476 int yaffs_guts_ll_init(struct yaffs_dev *dev)
4477 {
4478
4479
4480         yaffs_trace(YAFFS_TRACE_TRACING, "yaffs: yaffs_ll_init()");
4481
4482         if (!dev) {
4483                 yaffs_trace(YAFFS_TRACE_ALWAYS,
4484                         "yaffs: Need a device"
4485                         );
4486                 return YAFFS_FAIL;
4487         }
4488
4489         if (dev->ll_init)
4490                 return YAFFS_OK;
4491
4492         dev->internal_start_block = dev->param.start_block;
4493         dev->internal_end_block = dev->param.end_block;
4494         dev->block_offset = 0;
4495         dev->chunk_offset = 0;
4496         dev->n_free_chunks = 0;
4497
4498         dev->gc_block = 0;
4499
4500         if (dev->param.start_block == 0) {
4501                 dev->internal_start_block = dev->param.start_block + 1;
4502                 dev->internal_end_block = dev->param.end_block + 1;
4503                 dev->block_offset = 1;
4504                 dev->chunk_offset = dev->param.chunks_per_block;
4505         }
4506
4507         /* Check geometry parameters. */
4508
4509         if ((!dev->param.inband_tags && dev->param.is_yaffs2 &&
4510                 dev->param.total_bytes_per_chunk < 1024) ||
4511                 (!dev->param.is_yaffs2 &&
4512                         dev->param.total_bytes_per_chunk < 512) ||
4513                 (dev->param.inband_tags && !dev->param.is_yaffs2) ||
4514                  dev->param.chunks_per_block < 2 ||
4515                  dev->param.n_reserved_blocks < 2 ||
4516                 dev->internal_start_block <= 0 ||
4517                 dev->internal_end_block <= 0 ||
4518                 dev->internal_end_block <=
4519                 (dev->internal_start_block + dev->param.n_reserved_blocks + 2)
4520                 ) {
4521                 /* otherwise it is too small */
4522                 yaffs_trace(YAFFS_TRACE_ALWAYS,
4523                         "NAND geometry problems: chunk size %d, type is yaffs%s, inband_tags %d ",
4524                         dev->param.total_bytes_per_chunk,
4525                         dev->param.is_yaffs2 ? "2" : "",
4526                         dev->param.inband_tags);
4527                 return YAFFS_FAIL;
4528         }
4529
4530         /* Sort out space for inband tags, if required */
4531         if (dev->param.inband_tags)
4532                 dev->data_bytes_per_chunk =
4533                     dev->param.total_bytes_per_chunk -
4534                     sizeof(struct yaffs_packed_tags2_tags_only);
4535         else
4536                 dev->data_bytes_per_chunk = dev->param.total_bytes_per_chunk;
4537
4538         /* Got the right mix of functions? */
4539         if (!yaffs_check_dev_fns(dev)) {
4540                 /* Function missing */
4541                 yaffs_trace(YAFFS_TRACE_ALWAYS,
4542                         "device function(s) missing or wrong");
4543
4544                 return YAFFS_FAIL;
4545         }
4546
4547         if (!yaffs_init_tmp_buffers(dev))
4548                 return YAFFS_FAIL;
4549
4550         if (yaffs_init_nand(dev) != YAFFS_OK) {
4551                 yaffs_trace(YAFFS_TRACE_ALWAYS, "InitialiseNAND failed");
4552                 return YAFFS_FAIL;
4553         }
4554
4555         dev->ll_init = 1;
4556
4557         return YAFFS_OK;
4558 }
4559
4560
4561 int yaffs_guts_format_dev(struct yaffs_dev *dev)
4562 {
4563         u32 i;
4564         enum yaffs_block_state state;
4565         u32 dummy;
4566
4567         if(yaffs_guts_ll_init(dev) != YAFFS_OK)
4568                 return YAFFS_FAIL;
4569
4570         if(dev->is_mounted)
4571                 return YAFFS_FAIL;
4572
4573         for (i = dev->internal_start_block; i <= dev->internal_end_block; i++) {
4574                 yaffs_query_init_block_state(dev, i, &state, &dummy);
4575                 if (state != YAFFS_BLOCK_STATE_DEAD)
4576                         yaffs_erase_block(dev, i);
4577         }
4578
4579         return YAFFS_OK;
4580 }
4581
4582 /*
4583  * If the dev is mounted r/w then the cleanup will happen during
4584  * yaffs_guts_initialise. However if the dev is mounted ro then
4585  * the cleanup will be dfered until yaffs is remounted r/w.
4586  */
4587 void yaffs_guts_cleanup(struct yaffs_dev *dev)
4588 {
4589         yaffs_strip_deleted_objs(dev);
4590         yaffs_fix_hanging_objs(dev);
4591         if (dev->param.empty_lost_n_found)
4592                         yaffs_empty_l_n_f(dev);
4593 }
4594
4595 int yaffs_guts_initialise(struct yaffs_dev *dev)
4596 {
4597         int init_failed = 0;
4598         u32 x;
4599         u32 bits;
4600
4601         if(yaffs_guts_ll_init(dev) != YAFFS_OK)
4602                 return YAFFS_FAIL;
4603
4604         if (dev->is_mounted) {
4605                 yaffs_trace(YAFFS_TRACE_ALWAYS, "device already mounted");
4606                 return YAFFS_FAIL;
4607         }
4608
4609         dev->is_mounted = 1;
4610
4611         /* OK now calculate a few things for the device */
4612
4613         /*
4614          *  Calculate all the chunk size manipulation numbers:
4615          */
4616         x = dev->data_bytes_per_chunk;
4617         /* We always use dev->chunk_shift and dev->chunk_div */
4618         dev->chunk_shift = calc_shifts(x);
4619         x >>= dev->chunk_shift;
4620         dev->chunk_div = x;
4621         /* We only use chunk mask if chunk_div is 1 */
4622         dev->chunk_mask = (1 << dev->chunk_shift) - 1;
4623
4624         /*
4625          * Calculate chunk_grp_bits.
4626          * We need to find the next power of 2 > than internal_end_block
4627          */
4628
4629         x = dev->param.chunks_per_block * (dev->internal_end_block + 1);
4630
4631         bits = calc_shifts_ceiling(x);
4632
4633         /* Set up tnode width if wide tnodes are enabled. */
4634         if (!dev->param.wide_tnodes_disabled) {
4635                 /* bits must be even so that we end up with 32-bit words */
4636                 if (bits & 1)
4637                         bits++;
4638                 if (bits < 16)
4639                         dev->tnode_width = 16;
4640                 else
4641                         dev->tnode_width = bits;
4642         } else {
4643                 dev->tnode_width = 16;
4644         }
4645
4646         dev->tnode_mask = (1 << dev->tnode_width) - 1;
4647
4648         /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
4649          * so if the bitwidth of the
4650          * chunk range we're using is greater than 16 we need
4651          * to figure out chunk shift and chunk_grp_size
4652          */
4653
4654         if (bits <= dev->tnode_width)
4655                 dev->chunk_grp_bits = 0;
4656         else
4657                 dev->chunk_grp_bits = bits - dev->tnode_width;
4658
4659         dev->tnode_size = (dev->tnode_width * YAFFS_NTNODES_LEVEL0) / 8;
4660         if (dev->tnode_size < sizeof(struct yaffs_tnode))
4661                 dev->tnode_size = sizeof(struct yaffs_tnode);
4662
4663         dev->chunk_grp_size = 1 << dev->chunk_grp_bits;
4664
4665         if (dev->param.chunks_per_block < dev->chunk_grp_size) {
4666                 /* We have a problem because the soft delete won't work if
4667                  * the chunk group size > chunks per block.
4668                  * This can be remedied by using larger "virtual blocks".
4669                  */
4670                 yaffs_trace(YAFFS_TRACE_ALWAYS, "chunk group too large");
4671
4672                 return YAFFS_FAIL;
4673         }
4674
4675         /* Finished verifying the device, continue with initialisation */
4676
4677         /* More device initialisation */
4678         dev->all_gcs = 0;
4679         dev->passive_gc_count = 0;
4680         dev->oldest_dirty_gc_count = 0;
4681         dev->bg_gcs = 0;
4682         dev->gc_block_finder = 0;
4683         dev->buffered_block = -1;
4684         dev->doing_buffered_block_rewrite = 0;
4685         dev->n_deleted_files = 0;
4686         dev->n_bg_deletions = 0;
4687         dev->n_unlinked_files = 0;
4688         dev->n_ecc_fixed = 0;
4689         dev->n_ecc_unfixed = 0;
4690         dev->n_tags_ecc_fixed = 0;
4691         dev->n_tags_ecc_unfixed = 0;
4692         dev->n_erase_failures = 0;
4693         dev->n_erased_blocks = 0;
4694         dev->gc_disable = 0;
4695         dev->has_pending_prioritised_gc = 1; /* Assume the worst for now,
4696                                               * will get fixed on first GC */
4697         INIT_LIST_HEAD(&dev->dirty_dirs);
4698         dev->oldest_dirty_seq = 0;
4699         dev->oldest_dirty_block = 0;
4700
4701         yaffs_endian_config(dev);
4702
4703         /* Initialise temporary caches. */
4704         dev->gc_cleanup_list = NULL;
4705
4706         if (!init_failed)
4707                 init_failed = yaffs_cache_init(dev) < 0;
4708
4709         dev->cache_hits = 0;
4710
4711         if (!init_failed) {
4712                 dev->gc_cleanup_list =
4713                     kmalloc(dev->param.chunks_per_block * sizeof(u32),
4714                                         GFP_NOFS);
4715                 if (!dev->gc_cleanup_list)
4716                         init_failed = 1;
4717         }
4718
4719         if (dev->param.is_yaffs2)
4720                 dev->param.use_header_file_size = 1;
4721
4722         if (!init_failed && !yaffs_init_blocks(dev))
4723                 init_failed = 1;
4724
4725         yaffs_init_tnodes_and_objs(dev);
4726
4727         if (!init_failed && !yaffs_create_initial_dir(dev))
4728                 init_failed = 1;
4729
4730         if (!init_failed && dev->param.is_yaffs2 &&
4731                 !dev->param.disable_summary &&
4732                 !yaffs_summary_init(dev))
4733                 init_failed = 1;
4734
4735         if (!init_failed) {
4736                 /* Now scan the flash. */
4737                 if (dev->param.is_yaffs2) {
4738                         if (yaffs2_checkpt_restore(dev)) {
4739                                 yaffs_check_obj_details_loaded(dev->root_dir);
4740                                 yaffs_trace(YAFFS_TRACE_CHECKPOINT |
4741                                         YAFFS_TRACE_MOUNT,
4742                                         "yaffs: restored from checkpoint"
4743                                         );
4744                         } else {
4745
4746                                 /* Clean up the mess caused by an aborted
4747                                  * checkpoint load then scan backwards.
4748                                  */
4749                                 yaffs_deinit_blocks(dev);
4750
4751                                 yaffs_deinit_tnodes_and_objs(dev);
4752
4753                                 dev->n_erased_blocks = 0;
4754                                 dev->n_free_chunks = 0;
4755                                 dev->alloc_block = -1;
4756                                 dev->alloc_page = -1;
4757                                 dev->n_deleted_files = 0;
4758                                 dev->n_unlinked_files = 0;
4759                                 dev->n_bg_deletions = 0;
4760
4761                                 if (!init_failed && !yaffs_init_blocks(dev))
4762                                         init_failed = 1;
4763
4764                                 yaffs_init_tnodes_and_objs(dev);
4765
4766                                 if (!init_failed
4767                                     && !yaffs_create_initial_dir(dev))
4768                                         init_failed = 1;
4769
4770                                 if (!init_failed && !yaffs2_scan_backwards(dev))
4771                                         init_failed = 1;
4772                         }
4773                 } else if (!yaffs1_scan(dev)) {
4774                         init_failed = 1;
4775                 }
4776
4777                 yaffs_guts_cleanup(dev);
4778         }
4779
4780         if (init_failed) {
4781                 /* Clean up the mess */
4782                 yaffs_trace(YAFFS_TRACE_TRACING,
4783                   "yaffs: yaffs_guts_initialise() aborted.");
4784
4785                 yaffs_deinitialise(dev);
4786                 return YAFFS_FAIL;
4787         }
4788
4789         /* Zero out stats */
4790         dev->n_page_reads = 0;
4791         dev->n_page_writes = 0;
4792         dev->n_erasures = 0;
4793         dev->n_gc_copies = 0;
4794         dev->n_retried_writes = 0;
4795
4796         dev->n_retired_blocks = 0;
4797
4798         yaffs_verify_free_chunks(dev);
4799         yaffs_verify_blocks(dev);
4800
4801         /* Clean up any aborted checkpoint data */
4802         if (!dev->is_checkpointed && dev->blocks_in_checkpt > 0)
4803                 yaffs2_checkpt_invalidate(dev);
4804
4805         yaffs_trace(YAFFS_TRACE_TRACING,
4806           "yaffs: yaffs_guts_initialise() done.");
4807         return YAFFS_OK;
4808 }
4809
4810 void yaffs_deinitialise(struct yaffs_dev *dev)
4811 {
4812         if (dev->is_mounted) {
4813                 u32 i;
4814
4815                 yaffs_deinit_blocks(dev);
4816                 yaffs_deinit_tnodes_and_objs(dev);
4817                 yaffs_summary_deinit(dev);
4818                 yaffs_cache_deinit(dev);
4819
4820                 kfree(dev->gc_cleanup_list);
4821
4822                 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
4823                         kfree(dev->temp_buffer[i].buffer);
4824                         dev->temp_buffer[i].buffer = NULL;
4825                 }
4826
4827                 kfree(dev->checkpt_buffer);
4828                 dev->checkpt_buffer = NULL;
4829                 kfree(dev->checkpt_block_list);
4830                 dev->checkpt_block_list = NULL;
4831
4832                 dev->ll_init = 0;
4833                 dev->is_mounted = 0;
4834
4835                 yaffs_deinit_nand(dev);
4836         }
4837 }
4838
4839 int yaffs_count_free_chunks(struct yaffs_dev *dev)
4840 {
4841         int n_free = 0;
4842         u32 b;
4843         struct yaffs_block_info *blk;
4844
4845         blk = dev->block_info;
4846         for (b = dev->internal_start_block; b <= dev->internal_end_block; b++) {
4847                 switch (blk->block_state) {
4848                 case YAFFS_BLOCK_STATE_EMPTY:
4849                 case YAFFS_BLOCK_STATE_ALLOCATING:
4850                 case YAFFS_BLOCK_STATE_COLLECTING:
4851                 case YAFFS_BLOCK_STATE_FULL:
4852                         n_free +=
4853                             (dev->param.chunks_per_block - blk->pages_in_use +
4854                              blk->soft_del_pages);
4855                         break;
4856                 default:
4857                         break;
4858                 }
4859                 blk++;
4860         }
4861         return n_free;
4862 }
4863
4864 int yaffs_get_n_free_chunks(struct yaffs_dev *dev)
4865 {
4866         /* This is what we report to the outside world */
4867         int n_free;
4868         int n_dirty_caches;
4869         int blocks_for_checkpt;
4870
4871         n_free = dev->n_free_chunks;
4872         n_free += dev->n_deleted_files;
4873
4874         /* Now count and subtract the number of dirty chunks in the cache. */
4875         n_dirty_caches = yaffs_count_dirty_caches(dev);
4876         n_free -= n_dirty_caches;
4877
4878         n_free -=
4879             ((dev->param.n_reserved_blocks + 1) * dev->param.chunks_per_block);
4880
4881         /* Now figure checkpoint space and report that... */
4882         blocks_for_checkpt = yaffs_calc_checkpt_blocks_required(dev);
4883
4884         n_free -= (blocks_for_checkpt * dev->param.chunks_per_block);
4885
4886         if (n_free < 0)
4887                 n_free = 0;
4888
4889         return n_free;
4890 }
4891
4892 /*
4893  * Marshalling functions to get the appropriate time values saved
4894  * and restored to/from obj headers.
4895  *
4896  * Note that the WinCE time fields are used to store the 32-bit values.
4897  */
4898
4899 static void yaffs_oh_time_load(u32 *yst_time, u32 *win_time, YTIME_T timeval)
4900 {
4901         u32 upper;
4902         u32 lower;
4903
4904         lower = timeval & 0xffffffff;
4905         /* we have to use #defines here insted of an if statement
4906         otherwise the compiler throws an error saying that
4907         right shift count >= width of type when we are using 32 bit time.
4908         */
4909         #ifdef CONFIG_YAFFS_USE_32_BIT_TIME_T
4910                 upper = 0;
4911         #else
4912                 upper = (timeval >> 32) & 0xffffffff;
4913         #endif
4914
4915         *yst_time = lower;
4916         win_time[0] = lower;
4917         win_time[1] = upper;
4918 }
4919
4920 static YTIME_T yaffs_oh_time_fetch(const u32 *yst_time, const u32 *win_time)
4921 {
4922         u32 upper;
4923         u32 lower;
4924
4925         if (win_time[1] == 0xffffffff) {
4926                 upper = 0;
4927                 lower = *yst_time;
4928         } else {
4929                 upper = win_time[1];
4930                 lower = win_time[0];
4931         }
4932         if (sizeof(YTIME_T) > sizeof(u32)) {
4933                 u64 ret;
4934                 ret = (((u64)upper) << 32) | lower;
4935                 return (YTIME_T) ret;
4936
4937         } else
4938                 return (YTIME_T) lower;
4939 }
4940
4941 YTIME_T yaffs_oh_ctime_fetch(struct yaffs_obj_hdr *oh)
4942 {
4943         return yaffs_oh_time_fetch(&oh->yst_ctime, oh->win_ctime);
4944 }
4945
4946 YTIME_T yaffs_oh_mtime_fetch(struct yaffs_obj_hdr *oh)
4947 {
4948         return yaffs_oh_time_fetch(&oh->yst_mtime, oh->win_mtime);
4949 }
4950
4951 YTIME_T yaffs_oh_atime_fetch(struct yaffs_obj_hdr *oh)
4952 {
4953         return yaffs_oh_time_fetch(&oh->yst_atime, oh->win_atime);
4954 }
4955
4956 void yaffs_oh_ctime_load(struct yaffs_obj *obj, struct yaffs_obj_hdr *oh)
4957 {
4958         yaffs_oh_time_load(&oh->yst_ctime, oh->win_ctime, obj->yst_ctime);
4959 }
4960
4961 void yaffs_oh_mtime_load(struct yaffs_obj *obj, struct yaffs_obj_hdr *oh)
4962 {
4963         yaffs_oh_time_load(&oh->yst_mtime, oh->win_mtime, obj->yst_mtime);
4964 }
4965
4966 void yaffs_oh_atime_load(struct yaffs_obj *obj, struct yaffs_obj_hdr *oh)
4967 {
4968         yaffs_oh_time_load(&oh->yst_atime, oh->win_atime, obj->yst_atime);
4969 }
4970
4971
4972 /*
4973  * Marshalling functions to get loff_t file sizes into and out of
4974  * object headers.
4975  */
4976 void yaffs_oh_size_load(struct yaffs_dev *dev,
4977                         struct yaffs_obj_hdr *oh,
4978                         loff_t fsize,
4979                         int do_endian)
4980 {
4981         oh->file_size_low = FSIZE_LOW(fsize);
4982
4983         oh->file_size_high = FSIZE_HIGH(fsize);
4984
4985         if (do_endian) {
4986                 yaffs_do_endian_u32(dev, &oh->file_size_low);
4987                 yaffs_do_endian_u32(dev, &oh->file_size_high);
4988         }
4989 }
4990
4991 loff_t yaffs_oh_to_size(struct yaffs_dev *dev, struct yaffs_obj_hdr *oh,
4992                         int do_endian)
4993 {
4994         loff_t retval;
4995
4996
4997         if (sizeof(loff_t) >= 8 && ~(oh->file_size_high)) {
4998                 u32 low = oh->file_size_low;
4999                 u32 high = oh->file_size_high;
5000
5001                 if (do_endian) {
5002                         yaffs_do_endian_u32 (dev, &low);
5003                         yaffs_do_endian_u32 (dev, &high);
5004                 }
5005                 retval = FSIZE_COMBINE(high, low);
5006         } else {
5007                 u32 low = oh->file_size_low;
5008
5009                 if (do_endian)
5010                         yaffs_do_endian_u32(dev, &low);
5011                 retval = (loff_t)low;
5012         }
5013
5014         return retval;
5015 }
5016
5017
5018 void yaffs_count_blocks_by_state(struct yaffs_dev *dev, int bs[10])
5019 {
5020         u32 i;
5021         struct yaffs_block_info *bi;
5022         int s;
5023
5024         for(i = 0; i < 10; i++)
5025                 bs[i] = 0;
5026
5027         for(i = dev->internal_start_block; i <= dev->internal_end_block; i++) {
5028                 bi = yaffs_get_block_info(dev, i);
5029                 s = bi->block_state;
5030                 if(s > YAFFS_BLOCK_STATE_DEAD || s < YAFFS_BLOCK_STATE_UNKNOWN)
5031                         bs[0]++;
5032                 else
5033                         bs[s]++;
5034         }
5035 }