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