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