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