109a0b7f39214c43c9e48e1e9c4261ea740b69a5
[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 #ifndef CONFIG_YAFFS_NO_SHORT_NAMES
675         memset(obj->short_name, 0, sizeof(obj->short_name));
676         if (name &&
677                 strnlen(name, YAFFS_SHORT_NAME_LENGTH + 1) <=
678                 YAFFS_SHORT_NAME_LENGTH)
679                 strcpy(obj->short_name, name);
680         else
681                 obj->short_name[0] = _Y('\0');
682 #endif
683         obj->sum = yaffs_calc_name_sum(name);
684 }
685
686 void yaffs_set_obj_name_from_oh(struct yaffs_obj *obj,
687                                 const struct yaffs_obj_hdr *oh)
688 {
689 #ifdef CONFIG_YAFFS_AUTO_UNICODE
690         YCHAR tmp_name[YAFFS_MAX_NAME_LENGTH + 1];
691         memset(tmp_name, 0, sizeof(tmp_name));
692         yaffs_load_name_from_oh(obj->my_dev, tmp_name, oh->name,
693                                 YAFFS_MAX_NAME_LENGTH + 1);
694         yaffs_set_obj_name(obj, tmp_name);
695 #else
696         yaffs_set_obj_name(obj, oh->name);
697 #endif
698 }
699
700 /*-------------------- TNODES -------------------
701
702  * List of spare tnodes
703  * The list is hooked together using the first pointer
704  * in the tnode.
705  */
706
707 struct yaffs_tnode *yaffs_get_tnode(struct yaffs_dev *dev)
708 {
709         struct yaffs_tnode *tn = yaffs_alloc_raw_tnode(dev);
710
711         if (tn) {
712                 memset(tn, 0, dev->tnode_size);
713                 dev->n_tnodes++;
714         }
715
716         dev->checkpoint_blocks_required = 0;    /* force recalculation */
717
718         return tn;
719 }
720
721 /* FreeTnode frees up a tnode and puts it back on the free list */
722 static void yaffs_free_tnode(struct yaffs_dev *dev, struct yaffs_tnode *tn)
723 {
724         yaffs_free_raw_tnode(dev, tn);
725         dev->n_tnodes--;
726         dev->checkpoint_blocks_required = 0;    /* force recalculation */
727 }
728
729 static void yaffs_deinit_tnodes_and_objs(struct yaffs_dev *dev)
730 {
731         yaffs_deinit_raw_tnodes_and_objs(dev);
732         dev->n_obj = 0;
733         dev->n_tnodes = 0;
734 }
735
736 void yaffs_load_tnode_0(struct yaffs_dev *dev, struct yaffs_tnode *tn,
737                         unsigned pos, unsigned val)
738 {
739         u32 *map = (u32 *) tn;
740         u32 bit_in_map;
741         u32 bit_in_word;
742         u32 word_in_map;
743         u32 mask;
744
745         pos &= YAFFS_TNODES_LEVEL0_MASK;
746         val >>= dev->chunk_grp_bits;
747
748         bit_in_map = pos * dev->tnode_width;
749         word_in_map = bit_in_map / 32;
750         bit_in_word = bit_in_map & (32 - 1);
751
752         mask = dev->tnode_mask << bit_in_word;
753
754         map[word_in_map] &= ~mask;
755         map[word_in_map] |= (mask & (val << bit_in_word));
756
757         if (dev->tnode_width > (32 - bit_in_word)) {
758                 bit_in_word = (32 - bit_in_word);
759                 word_in_map++;
760                 mask =
761                     dev->tnode_mask >> bit_in_word;
762                 map[word_in_map] &= ~mask;
763                 map[word_in_map] |= (mask & (val >> bit_in_word));
764         }
765 }
766
767 u32 yaffs_get_group_base(struct yaffs_dev *dev, struct yaffs_tnode *tn,
768                          unsigned pos)
769 {
770         u32 *map = (u32 *) tn;
771         u32 bit_in_map;
772         u32 bit_in_word;
773         u32 word_in_map;
774         u32 val;
775
776         pos &= YAFFS_TNODES_LEVEL0_MASK;
777
778         bit_in_map = pos * dev->tnode_width;
779         word_in_map = bit_in_map / 32;
780         bit_in_word = bit_in_map & (32 - 1);
781
782         val = map[word_in_map] >> bit_in_word;
783
784         if (dev->tnode_width > (32 - bit_in_word)) {
785                 bit_in_word = (32 - bit_in_word);
786                 word_in_map++;
787                 val |= (map[word_in_map] << bit_in_word);
788         }
789
790         val &= dev->tnode_mask;
791         val <<= dev->chunk_grp_bits;
792
793         return val;
794 }
795
796 /* ------------------- End of individual tnode manipulation -----------------*/
797
798 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
799  * The look up tree is represented by the top tnode and the number of top_level
800  * in the tree. 0 means only the level 0 tnode is in the tree.
801  */
802
803 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
804 struct yaffs_tnode *yaffs_find_tnode_0(struct yaffs_dev *dev,
805                                        struct yaffs_file_var *file_struct,
806                                        u32 chunk_id)
807 {
808         struct yaffs_tnode *tn = file_struct->top;
809         u32 i;
810         int required_depth;
811         int level = file_struct->top_level;
812
813         dev = dev;
814
815         /* Check sane level and chunk Id */
816         if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
817                 return NULL;
818
819         if (chunk_id > YAFFS_MAX_CHUNK_ID)
820                 return NULL;
821
822         /* First check we're tall enough (ie enough top_level) */
823
824         i = chunk_id >> YAFFS_TNODES_LEVEL0_BITS;
825         required_depth = 0;
826         while (i) {
827                 i >>= YAFFS_TNODES_INTERNAL_BITS;
828                 required_depth++;
829         }
830
831         if (required_depth > file_struct->top_level)
832                 return NULL;    /* Not tall enough, so we can't find it */
833
834         /* Traverse down to level 0 */
835         while (level > 0 && tn) {
836                 tn = tn->internal[(chunk_id >>
837                                    (YAFFS_TNODES_LEVEL0_BITS +
838                                     (level - 1) *
839                                     YAFFS_TNODES_INTERNAL_BITS)) &
840                                   YAFFS_TNODES_INTERNAL_MASK];
841                 level--;
842         }
843
844         return tn;
845 }
846
847 /* add_find_tnode_0 finds the level 0 tnode if it exists,
848  * otherwise first expands the tree.
849  * This happens in two steps:
850  *  1. If the tree isn't tall enough, then make it taller.
851  *  2. Scan down the tree towards the level 0 tnode adding tnodes if required.
852  *
853  * Used when modifying the tree.
854  *
855  *  If the tn argument is NULL, then a fresh tnode will be added otherwise the
856  *  specified tn will be plugged into the ttree.
857  */
858
859 struct yaffs_tnode *yaffs_add_find_tnode_0(struct yaffs_dev *dev,
860                                            struct yaffs_file_var *file_struct,
861                                            u32 chunk_id,
862                                            struct yaffs_tnode *passed_tn)
863 {
864         int required_depth;
865         int i;
866         int l;
867         struct yaffs_tnode *tn;
868         u32 x;
869
870         /* Check sane level and page Id */
871         if (file_struct->top_level < 0 ||
872             file_struct->top_level > YAFFS_TNODES_MAX_LEVEL)
873                 return NULL;
874
875         if (chunk_id > YAFFS_MAX_CHUNK_ID)
876                 return NULL;
877
878         /* First check we're tall enough (ie enough top_level) */
879
880         x = chunk_id >> YAFFS_TNODES_LEVEL0_BITS;
881         required_depth = 0;
882         while (x) {
883                 x >>= YAFFS_TNODES_INTERNAL_BITS;
884                 required_depth++;
885         }
886
887         if (required_depth > file_struct->top_level) {
888                 /* Not tall enough, gotta make the tree taller */
889                 for (i = file_struct->top_level; i < required_depth; i++) {
890
891                         tn = yaffs_get_tnode(dev);
892
893                         if (tn) {
894                                 tn->internal[0] = file_struct->top;
895                                 file_struct->top = tn;
896                                 file_struct->top_level++;
897                         } else {
898                                 yaffs_trace(YAFFS_TRACE_ERROR,
899                                         "yaffs: no more tnodes");
900                                 return NULL;
901                         }
902                 }
903         }
904
905         /* Traverse down to level 0, adding anything we need */
906
907         l = file_struct->top_level;
908         tn = file_struct->top;
909
910         if (l > 0) {
911                 while (l > 0 && tn) {
912                         x = (chunk_id >>
913                              (YAFFS_TNODES_LEVEL0_BITS +
914                               (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
915                             YAFFS_TNODES_INTERNAL_MASK;
916
917                         if ((l > 1) && !tn->internal[x]) {
918                                 /* Add missing non-level-zero tnode */
919                                 tn->internal[x] = yaffs_get_tnode(dev);
920                                 if (!tn->internal[x])
921                                         return NULL;
922                         } else if (l == 1) {
923                                 /* Looking from level 1 at level 0 */
924                                 if (passed_tn) {
925                                         /* If we already have one, release it */
926                                         if (tn->internal[x])
927                                                 yaffs_free_tnode(dev,
928                                                         tn->internal[x]);
929                                         tn->internal[x] = passed_tn;
930
931                                 } else if (!tn->internal[x]) {
932                                         /* Don't have one, none passed in */
933                                         tn->internal[x] = yaffs_get_tnode(dev);
934                                         if (!tn->internal[x])
935                                                 return NULL;
936                                 }
937                         }
938
939                         tn = tn->internal[x];
940                         l--;
941                 }
942         } else {
943                 /* top is level 0 */
944                 if (passed_tn) {
945                         memcpy(tn, passed_tn,
946                                (dev->tnode_width * YAFFS_NTNODES_LEVEL0) / 8);
947                         yaffs_free_tnode(dev, passed_tn);
948                 }
949         }
950
951         return tn;
952 }
953
954 static int yaffs_tags_match(const struct yaffs_ext_tags *tags, int obj_id,
955                             int chunk_obj)
956 {
957         return (tags->chunk_id == chunk_obj &&
958                 tags->obj_id == obj_id &&
959                 !tags->is_deleted) ? 1 : 0;
960
961 }
962
963 static int yaffs_find_chunk_in_group(struct yaffs_dev *dev, int the_chunk,
964                                         struct yaffs_ext_tags *tags, int obj_id,
965                                         int inode_chunk)
966 {
967         int j;
968
969         for (j = 0; the_chunk && j < dev->chunk_grp_size; j++) {
970                 if (yaffs_check_chunk_bit
971                     (dev, the_chunk / dev->param.chunks_per_block,
972                      the_chunk % dev->param.chunks_per_block)) {
973
974                         if (dev->chunk_grp_size == 1)
975                                 return the_chunk;
976                         else {
977                                 yaffs_rd_chunk_tags_nand(dev, the_chunk, NULL,
978                                                          tags);
979                                 if (yaffs_tags_match(tags,
980                                                         obj_id, inode_chunk)) {
981                                         /* found it; */
982                                         return the_chunk;
983                                 }
984                         }
985                 }
986                 the_chunk++;
987         }
988         return -1;
989 }
990
991 static int yaffs_find_chunk_in_file(struct yaffs_obj *in, int inode_chunk,
992                                     struct yaffs_ext_tags *tags)
993 {
994         /*Get the Tnode, then get the level 0 offset chunk offset */
995         struct yaffs_tnode *tn;
996         int the_chunk = -1;
997         struct yaffs_ext_tags local_tags;
998         int ret_val = -1;
999         struct yaffs_dev *dev = in->my_dev;
1000
1001         if (!tags) {
1002                 /* Passed a NULL, so use our own tags space */
1003                 tags = &local_tags;
1004         }
1005
1006         tn = yaffs_find_tnode_0(dev, &in->variant.file_variant, inode_chunk);
1007
1008         if (!tn)
1009                 return ret_val;
1010
1011         the_chunk = yaffs_get_group_base(dev, tn, inode_chunk);
1012
1013         ret_val = yaffs_find_chunk_in_group(dev, the_chunk, tags, in->obj_id,
1014                                               inode_chunk);
1015         return ret_val;
1016 }
1017
1018 static int yaffs_find_del_file_chunk(struct yaffs_obj *in, int inode_chunk,
1019                                      struct yaffs_ext_tags *tags)
1020 {
1021         /* Get the Tnode, then get the level 0 offset chunk offset */
1022         struct yaffs_tnode *tn;
1023         int the_chunk = -1;
1024         struct yaffs_ext_tags local_tags;
1025         struct yaffs_dev *dev = in->my_dev;
1026         int ret_val = -1;
1027
1028         if (!tags) {
1029                 /* Passed a NULL, so use our own tags space */
1030                 tags = &local_tags;
1031         }
1032
1033         tn = yaffs_find_tnode_0(dev, &in->variant.file_variant, inode_chunk);
1034
1035         if (!tn)
1036                 return ret_val;
1037
1038         the_chunk = yaffs_get_group_base(dev, tn, inode_chunk);
1039
1040         ret_val = yaffs_find_chunk_in_group(dev, the_chunk, tags, in->obj_id,
1041                                               inode_chunk);
1042
1043         /* Delete the entry in the filestructure (if found) */
1044         if (ret_val != -1)
1045                 yaffs_load_tnode_0(dev, tn, inode_chunk, 0);
1046
1047         return ret_val;
1048 }
1049
1050 int yaffs_put_chunk_in_file(struct yaffs_obj *in, int inode_chunk,
1051                             int nand_chunk, int in_scan)
1052 {
1053         /* NB in_scan is zero unless scanning.
1054          * For forward scanning, in_scan is > 0;
1055          * for backward scanning in_scan is < 0
1056          *
1057          * nand_chunk = 0 is a dummy insert to make sure the tnodes are there.
1058          */
1059
1060         struct yaffs_tnode *tn;
1061         struct yaffs_dev *dev = in->my_dev;
1062         int existing_cunk;
1063         struct yaffs_ext_tags existing_tags;
1064         struct yaffs_ext_tags new_tags;
1065         unsigned existing_serial, new_serial;
1066
1067         if (in->variant_type != YAFFS_OBJECT_TYPE_FILE) {
1068                 /* Just ignore an attempt at putting a chunk into a non-file
1069                  * during scanning.
1070                  * If it is not during Scanning then something went wrong!
1071                  */
1072                 if (!in_scan) {
1073                         yaffs_trace(YAFFS_TRACE_ERROR,
1074                                 "yaffs tragedy:attempt to put data chunk into a non-file"
1075                                 );
1076                         BUG();
1077                 }
1078
1079                 yaffs_chunk_del(dev, nand_chunk, 1, __LINE__);
1080                 return YAFFS_OK;
1081         }
1082
1083         tn = yaffs_add_find_tnode_0(dev,
1084                                     &in->variant.file_variant,
1085                                     inode_chunk, NULL);
1086         if (!tn)
1087                 return YAFFS_FAIL;
1088
1089         if (!nand_chunk)
1090                 /* Dummy insert, bail now */
1091                 return YAFFS_OK;
1092
1093         existing_cunk = yaffs_get_group_base(dev, tn, inode_chunk);
1094
1095         if (in_scan != 0) {
1096                 /* If we're scanning then we need to test for duplicates
1097                  * NB This does not need to be efficient since it should only
1098                  * happen when the power fails during a write, then only one
1099                  * chunk should ever be affected.
1100                  *
1101                  * Correction for YAFFS2: This could happen quite a lot and we
1102                  * need to think about efficiency! TODO
1103                  * Update: For backward scanning we don't need to re-read tags
1104                  * so this is quite cheap.
1105                  */
1106
1107                 if (existing_cunk > 0) {
1108                         /* NB Right now existing chunk will not be real
1109                          * chunk_id if the chunk group size > 1
1110                          * thus we have to do a FindChunkInFile to get the
1111                          * real chunk id.
1112                          *
1113                          * We have a duplicate now we need to decide which
1114                          * one to use:
1115                          *
1116                          * Backwards scanning YAFFS2: The old one is what
1117                          * we use, dump the new one.
1118                          * YAFFS1: Get both sets of tags and compare serial
1119                          * numbers.
1120                          */
1121
1122                         if (in_scan > 0) {
1123                                 /* Only do this for forward scanning */
1124                                 yaffs_rd_chunk_tags_nand(dev,
1125                                                          nand_chunk,
1126                                                          NULL, &new_tags);
1127
1128                                 /* Do a proper find */
1129                                 existing_cunk =
1130                                     yaffs_find_chunk_in_file(in, inode_chunk,
1131                                                              &existing_tags);
1132                         }
1133
1134                         if (existing_cunk <= 0) {
1135                                 /*Hoosterman - how did this happen? */
1136
1137                                 yaffs_trace(YAFFS_TRACE_ERROR,
1138                                         "yaffs tragedy: existing chunk < 0 in scan"
1139                                         );
1140
1141                         }
1142
1143                         /* NB The deleted flags should be false, otherwise
1144                          * the chunks will not be loaded during a scan
1145                          */
1146
1147                         if (in_scan > 0) {
1148                                 new_serial = new_tags.serial_number;
1149                                 existing_serial = existing_tags.serial_number;
1150                         }
1151
1152                         if ((in_scan > 0) &&
1153                             (existing_cunk <= 0 ||
1154                              ((existing_serial + 1) & 3) == new_serial)) {
1155                                 /* Forward scanning.
1156                                  * Use new
1157                                  * Delete the old one and drop through to
1158                                  * update the tnode
1159                                  */
1160                                 yaffs_chunk_del(dev, existing_cunk, 1,
1161                                                 __LINE__);
1162                         } else {
1163                                 /* Backward scanning or we want to use the
1164                                  * existing one
1165                                  * Delete the new one and return early so that
1166                                  * the tnode isn't changed
1167                                  */
1168                                 yaffs_chunk_del(dev, nand_chunk, 1, __LINE__);
1169                                 return YAFFS_OK;
1170                         }
1171                 }
1172
1173         }
1174
1175         if (existing_cunk == 0)
1176                 in->n_data_chunks++;
1177
1178         yaffs_load_tnode_0(dev, tn, inode_chunk, nand_chunk);
1179
1180         return YAFFS_OK;
1181 }
1182
1183 static void yaffs_soft_del_chunk(struct yaffs_dev *dev, int chunk)
1184 {
1185         struct yaffs_block_info *the_block;
1186         unsigned block_no;
1187
1188         yaffs_trace(YAFFS_TRACE_DELETION, "soft delete chunk %d", chunk);
1189
1190         block_no = chunk / dev->param.chunks_per_block;
1191         the_block = yaffs_get_block_info(dev, block_no);
1192         if (the_block) {
1193                 the_block->soft_del_pages++;
1194                 dev->n_free_chunks++;
1195                 yaffs2_update_oldest_dirty_seq(dev, block_no, the_block);
1196         }
1197 }
1198
1199 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all
1200  * the chunks in the file.
1201  * All soft deleting does is increment the block's softdelete count and pulls
1202  * the chunk out of the tnode.
1203  * Thus, essentially this is the same as DeleteWorker except that the chunks
1204  * are soft deleted.
1205  */
1206
1207 static int yaffs_soft_del_worker(struct yaffs_obj *in, struct yaffs_tnode *tn,
1208                                  u32 level, int chunk_offset)
1209 {
1210         int i;
1211         int the_chunk;
1212         int all_done = 1;
1213         struct yaffs_dev *dev = in->my_dev;
1214
1215         if (!tn)
1216                 return 1;
1217
1218         if (level > 0) {
1219                 for (i = YAFFS_NTNODES_INTERNAL - 1;
1220                         all_done && i >= 0;
1221                         i--) {
1222                         if (tn->internal[i]) {
1223                                 all_done =
1224                                     yaffs_soft_del_worker(in,
1225                                         tn->internal[i],
1226                                         level - 1,
1227                                         (chunk_offset <<
1228                                         YAFFS_TNODES_INTERNAL_BITS)
1229                                         + i);
1230                                 if (all_done) {
1231                                         yaffs_free_tnode(dev,
1232                                                 tn->internal[i]);
1233                                         tn->internal[i] = NULL;
1234                                 } else {
1235                                         /* Can this happen? */
1236                                 }
1237                         }
1238                 }
1239                 return (all_done) ? 1 : 0;
1240         }
1241
1242         /* level 0 */
1243          for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1244                 the_chunk = yaffs_get_group_base(dev, tn, i);
1245                 if (the_chunk) {
1246                         yaffs_soft_del_chunk(dev, the_chunk);
1247                         yaffs_load_tnode_0(dev, tn, i, 0);
1248                 }
1249         }
1250         return 1;
1251 }
1252
1253 static void yaffs_remove_obj_from_dir(struct yaffs_obj *obj)
1254 {
1255         struct yaffs_dev *dev = obj->my_dev;
1256         struct yaffs_obj *parent;
1257
1258         yaffs_verify_obj_in_dir(obj);
1259         parent = obj->parent;
1260
1261         yaffs_verify_dir(parent);
1262
1263         if (dev && dev->param.remove_obj_fn)
1264                 dev->param.remove_obj_fn(obj);
1265
1266         list_del_init(&obj->siblings);
1267         obj->parent = NULL;
1268
1269         yaffs_verify_dir(parent);
1270 }
1271
1272 void yaffs_add_obj_to_dir(struct yaffs_obj *directory, struct yaffs_obj *obj)
1273 {
1274         if (!directory) {
1275                 yaffs_trace(YAFFS_TRACE_ALWAYS,
1276                         "tragedy: Trying to add an object to a null pointer directory"
1277                         );
1278                 BUG();
1279                 return;
1280         }
1281         if (directory->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY) {
1282                 yaffs_trace(YAFFS_TRACE_ALWAYS,
1283                         "tragedy: Trying to add an object to a non-directory"
1284                         );
1285                 BUG();
1286         }
1287
1288         if (obj->siblings.prev == NULL) {
1289                 /* Not initialised */
1290                 BUG();
1291         }
1292
1293         yaffs_verify_dir(directory);
1294
1295         yaffs_remove_obj_from_dir(obj);
1296
1297         /* Now add it */
1298         list_add(&obj->siblings, &directory->variant.dir_variant.children);
1299         obj->parent = directory;
1300
1301         if (directory == obj->my_dev->unlinked_dir
1302             || directory == obj->my_dev->del_dir) {
1303                 obj->unlinked = 1;
1304                 obj->my_dev->n_unlinked_files++;
1305                 obj->rename_allowed = 0;
1306         }
1307
1308         yaffs_verify_dir(directory);
1309         yaffs_verify_obj_in_dir(obj);
1310 }
1311
1312 static int yaffs_change_obj_name(struct yaffs_obj *obj,
1313                                  struct yaffs_obj *new_dir,
1314                                  const YCHAR *new_name, int force, int shadows)
1315 {
1316         int unlink_op;
1317         int del_op;
1318         struct yaffs_obj *existing_target;
1319
1320         if (new_dir == NULL)
1321                 new_dir = obj->parent;  /* use the old directory */
1322
1323         if (new_dir->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY) {
1324                 yaffs_trace(YAFFS_TRACE_ALWAYS,
1325                         "tragedy: yaffs_change_obj_name: new_dir is not a directory"
1326                         );
1327                 BUG();
1328         }
1329
1330         unlink_op = (new_dir == obj->my_dev->unlinked_dir);
1331         del_op = (new_dir == obj->my_dev->del_dir);
1332
1333         existing_target = yaffs_find_by_name(new_dir, new_name);
1334
1335         /* If the object is a file going into the unlinked directory,
1336          *   then it is OK to just stuff it in since duplicate names are OK.
1337          *   else only proceed if the new name does not exist and we're putting
1338          *   it into a directory.
1339          */
1340         if (!(unlink_op || del_op || force ||
1341               shadows > 0 || !existing_target) ||
1342               new_dir->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY)
1343                 return YAFFS_FAIL;
1344
1345         yaffs_set_obj_name(obj, new_name);
1346         obj->dirty = 1;
1347         yaffs_add_obj_to_dir(new_dir, obj);
1348
1349         if (unlink_op)
1350                 obj->unlinked = 1;
1351
1352         /* If it is a deletion then we mark it as a shrink for gc  */
1353         if (yaffs_update_oh(obj, new_name, 0, del_op, shadows, NULL) >= 0)
1354                 return YAFFS_OK;
1355
1356         return YAFFS_FAIL;
1357 }
1358
1359 /*------------------------ Short Operations Cache ------------------------------
1360  *   In many situations where there is no high level buffering  a lot of
1361  *   reads might be short sequential reads, and a lot of writes may be short
1362  *   sequential writes. eg. scanning/writing a jpeg file.
1363  *   In these cases, a short read/write cache can provide a huge perfomance
1364  *   benefit with dumb-as-a-rock code.
1365  *   In Linux, the page cache provides read buffering and the short op cache
1366  *   provides write buffering.
1367  *
1368  *   There are a small number (~10) of cache chunks per device so that we don't
1369  *   need a very intelligent search.
1370  */
1371
1372 static int yaffs_obj_cache_dirty(struct yaffs_obj *obj)
1373 {
1374         struct yaffs_dev *dev = obj->my_dev;
1375         int i;
1376         struct yaffs_cache *cache;
1377         int n_caches = obj->my_dev->param.n_caches;
1378
1379         for (i = 0; i < n_caches; i++) {
1380                 cache = &dev->cache[i];
1381                 if (cache->object == obj && cache->dirty)
1382                         return 1;
1383         }
1384
1385         return 0;
1386 }
1387
1388 static void yaffs_flush_file_cache(struct yaffs_obj *obj)
1389 {
1390         struct yaffs_dev *dev = obj->my_dev;
1391         int lowest = -99;       /* Stop compiler whining. */
1392         int i;
1393         struct yaffs_cache *cache;
1394         int chunk_written = 0;
1395         int n_caches = obj->my_dev->param.n_caches;
1396
1397         if (n_caches < 1)
1398                 return;
1399         do {
1400                 cache = NULL;
1401
1402                 /* Find the lowest dirty chunk for this object */
1403                 for (i = 0; i < n_caches; i++) {
1404                         if (dev->cache[i].object == obj &&
1405                             dev->cache[i].dirty) {
1406                                 if (!cache ||
1407                                     dev->cache[i].chunk_id < lowest) {
1408                                         cache = &dev->cache[i];
1409                                         lowest = cache->chunk_id;
1410                                 }
1411                         }
1412                 }
1413
1414                 if (cache && !cache->locked) {
1415                         /* Write it out and free it up */
1416                         chunk_written =
1417                             yaffs_wr_data_obj(cache->object,
1418                                               cache->chunk_id,
1419                                               cache->data,
1420                                               cache->n_bytes, 1);
1421                         cache->dirty = 0;
1422                         cache->object = NULL;
1423                 }
1424         } while (cache && chunk_written > 0);
1425
1426         if (cache)
1427                 /* Hoosterman, disk full while writing cache out. */
1428                 yaffs_trace(YAFFS_TRACE_ERROR,
1429                         "yaffs tragedy: no space during cache write");
1430 }
1431
1432 /*yaffs_flush_whole_cache(dev)
1433  *
1434  *
1435  */
1436
1437 void yaffs_flush_whole_cache(struct yaffs_dev *dev)
1438 {
1439         struct yaffs_obj *obj;
1440         int n_caches = dev->param.n_caches;
1441         int i;
1442
1443         /* Find a dirty object in the cache and flush it...
1444          * until there are no further dirty objects.
1445          */
1446         do {
1447                 obj = NULL;
1448                 for (i = 0; i < n_caches && !obj; i++) {
1449                         if (dev->cache[i].object && dev->cache[i].dirty)
1450                                 obj = dev->cache[i].object;
1451                 }
1452                 if (obj)
1453                         yaffs_flush_file_cache(obj);
1454         } while (obj);
1455
1456 }
1457
1458 /* Grab us a cache chunk for use.
1459  * First look for an empty one.
1460  * Then look for the least recently used non-dirty one.
1461  * Then look for the least recently used dirty one...., flush and look again.
1462  */
1463 static struct yaffs_cache *yaffs_grab_chunk_worker(struct yaffs_dev *dev)
1464 {
1465         int i;
1466
1467         if (dev->param.n_caches > 0) {
1468                 for (i = 0; i < dev->param.n_caches; i++) {
1469                         if (!dev->cache[i].object)
1470                                 return &dev->cache[i];
1471                 }
1472         }
1473         return NULL;
1474 }
1475
1476 static struct yaffs_cache *yaffs_grab_chunk_cache(struct yaffs_dev *dev)
1477 {
1478         struct yaffs_cache *cache;
1479         struct yaffs_obj *the_obj;
1480         int usage;
1481         int i;
1482         int pushout;
1483
1484         if (dev->param.n_caches < 1)
1485                 return NULL;
1486
1487         /* Try find a non-dirty one... */
1488
1489         cache = yaffs_grab_chunk_worker(dev);
1490
1491         if (!cache) {
1492                 /* They were all dirty, find the LRU object and flush
1493                  * its cache, then  find again.
1494                  * NB what's here is not very accurate,
1495                  * we actually flush the object with the LRU chunk.
1496                  */
1497
1498                 /* With locking we can't assume we can use entry zero,
1499                  * Set the_obj to a valid pointer for Coverity. */
1500                 the_obj = dev->cache[0].object;
1501                 usage = -1;
1502                 cache = NULL;
1503                 pushout = -1;
1504
1505                 for (i = 0; i < dev->param.n_caches; i++) {
1506                         if (dev->cache[i].object &&
1507                             !dev->cache[i].locked &&
1508                             (dev->cache[i].last_use < usage ||
1509                             !cache)) {
1510                                 usage = dev->cache[i].last_use;
1511                                 the_obj = dev->cache[i].object;
1512                                 cache = &dev->cache[i];
1513                                 pushout = i;
1514                         }
1515                 }
1516
1517                 if (!cache || cache->dirty) {
1518                         /* Flush and try again */
1519                         yaffs_flush_file_cache(the_obj);
1520                         cache = yaffs_grab_chunk_worker(dev);
1521                 }
1522         }
1523         return cache;
1524 }
1525
1526 /* Find a cached chunk */
1527 static struct yaffs_cache *yaffs_find_chunk_cache(const struct yaffs_obj *obj,
1528                                                   int chunk_id)
1529 {
1530         struct yaffs_dev *dev = obj->my_dev;
1531         int i;
1532
1533         if (dev->param.n_caches < 1)
1534                 return NULL;
1535
1536         for (i = 0; i < dev->param.n_caches; i++) {
1537                 if (dev->cache[i].object == obj &&
1538                     dev->cache[i].chunk_id == chunk_id) {
1539                         dev->cache_hits++;
1540
1541                         return &dev->cache[i];
1542                 }
1543         }
1544         return NULL;
1545 }
1546
1547 /* Mark the chunk for the least recently used algorithym */
1548 static void yaffs_use_cache(struct yaffs_dev *dev, struct yaffs_cache *cache,
1549                             int is_write)
1550 {
1551         int i;
1552
1553         if (dev->param.n_caches < 1)
1554                 return;
1555
1556         if (dev->cache_last_use < 0 ||
1557                 dev->cache_last_use > 100000000) {
1558                 /* Reset the cache usages */
1559                 for (i = 1; i < dev->param.n_caches; i++)
1560                         dev->cache[i].last_use = 0;
1561
1562                 dev->cache_last_use = 0;
1563         }
1564         dev->cache_last_use++;
1565         cache->last_use = dev->cache_last_use;
1566
1567         if (is_write)
1568                 cache->dirty = 1;
1569 }
1570
1571 /* Invalidate a single cache page.
1572  * Do this when a whole page gets written,
1573  * ie the short cache for this page is no longer valid.
1574  */
1575 static void yaffs_invalidate_chunk_cache(struct yaffs_obj *object, int chunk_id)
1576 {
1577         struct yaffs_cache *cache;
1578
1579         if (object->my_dev->param.n_caches > 0) {
1580                 cache = yaffs_find_chunk_cache(object, chunk_id);
1581
1582                 if (cache)
1583                         cache->object = NULL;
1584         }
1585 }
1586
1587 /* Invalidate all the cache pages associated with this object
1588  * Do this whenever ther file is deleted or resized.
1589  */
1590 static void yaffs_invalidate_whole_cache(struct yaffs_obj *in)
1591 {
1592         int i;
1593         struct yaffs_dev *dev = in->my_dev;
1594
1595         if (dev->param.n_caches > 0) {
1596                 /* Invalidate it. */
1597                 for (i = 0; i < dev->param.n_caches; i++) {
1598                         if (dev->cache[i].object == in)
1599                                 dev->cache[i].object = NULL;
1600                 }
1601         }
1602 }
1603
1604 static void yaffs_unhash_obj(struct yaffs_obj *obj)
1605 {
1606         int bucket;
1607         struct yaffs_dev *dev = obj->my_dev;
1608
1609         /* If it is still linked into the bucket list, free from the list */
1610         if (!list_empty(&obj->hash_link)) {
1611                 list_del_init(&obj->hash_link);
1612                 bucket = yaffs_hash_fn(obj->obj_id);
1613                 dev->obj_bucket[bucket].count--;
1614         }
1615 }
1616
1617 /*  FreeObject frees up a Object and puts it back on the free list */
1618 static void yaffs_free_obj(struct yaffs_obj *obj)
1619 {
1620         struct yaffs_dev *dev;
1621
1622         if (!obj) {
1623                 BUG();
1624                 return;
1625         }
1626         dev = obj->my_dev;
1627         yaffs_trace(YAFFS_TRACE_OS, "FreeObject %p inode %p",
1628                 obj, obj->my_inode);
1629         if (obj->parent)
1630                 BUG();
1631         if (!list_empty(&obj->siblings))
1632                 BUG();
1633
1634         if (obj->my_inode) {
1635                 /* We're still hooked up to a cached inode.
1636                  * Don't delete now, but mark for later deletion
1637                  */
1638                 obj->defered_free = 1;
1639                 return;
1640         }
1641
1642         yaffs_unhash_obj(obj);
1643
1644         yaffs_free_raw_obj(dev, obj);
1645         dev->n_obj--;
1646         dev->checkpoint_blocks_required = 0;    /* force recalculation */
1647 }
1648
1649 void yaffs_handle_defered_free(struct yaffs_obj *obj)
1650 {
1651         if (obj->defered_free)
1652                 yaffs_free_obj(obj);
1653 }
1654
1655 static int yaffs_generic_obj_del(struct yaffs_obj *in)
1656 {
1657         /* Iinvalidate the file's data in the cache, without flushing. */
1658         yaffs_invalidate_whole_cache(in);
1659
1660         if (in->my_dev->param.is_yaffs2 && in->parent != in->my_dev->del_dir) {
1661                 /* Move to unlinked directory so we have a deletion record */
1662                 yaffs_change_obj_name(in, in->my_dev->del_dir, _Y("deleted"), 0,
1663                                       0);
1664         }
1665
1666         yaffs_remove_obj_from_dir(in);
1667         yaffs_chunk_del(in->my_dev, in->hdr_chunk, 1, __LINE__);
1668         in->hdr_chunk = 0;
1669
1670         yaffs_free_obj(in);
1671         return YAFFS_OK;
1672
1673 }
1674
1675 static void yaffs_soft_del_file(struct yaffs_obj *obj)
1676 {
1677         if (!obj->deleted ||
1678             obj->variant_type != YAFFS_OBJECT_TYPE_FILE ||
1679             obj->soft_del)
1680                 return;
1681
1682         if (obj->n_data_chunks <= 0) {
1683                 /* Empty file with no duplicate object headers,
1684                  * just delete it immediately */
1685                 yaffs_free_tnode(obj->my_dev, obj->variant.file_variant.top);
1686                 obj->variant.file_variant.top = NULL;
1687                 yaffs_trace(YAFFS_TRACE_TRACING,
1688                         "yaffs: Deleting empty file %d",
1689                         obj->obj_id);
1690                 yaffs_generic_obj_del(obj);
1691         } else {
1692                 yaffs_soft_del_worker(obj,
1693                                       obj->variant.file_variant.top,
1694                                       obj->variant.
1695                                       file_variant.top_level, 0);
1696                 obj->soft_del = 1;
1697         }
1698 }
1699
1700 /* Pruning removes any part of the file structure tree that is beyond the
1701  * bounds of the file (ie that does not point to chunks).
1702  *
1703  * A file should only get pruned when its size is reduced.
1704  *
1705  * Before pruning, the chunks must be pulled from the tree and the
1706  * level 0 tnode entries must be zeroed out.
1707  * Could also use this for file deletion, but that's probably better handled
1708  * by a special case.
1709  *
1710  * This function is recursive. For levels > 0 the function is called again on
1711  * any sub-tree. For level == 0 we just check if the sub-tree has data.
1712  * If there is no data in a subtree then it is pruned.
1713  */
1714
1715 static struct yaffs_tnode *yaffs_prune_worker(struct yaffs_dev *dev,
1716                                               struct yaffs_tnode *tn, u32 level,
1717                                               int del0)
1718 {
1719         int i;
1720         int has_data;
1721
1722         if (!tn)
1723                 return tn;
1724
1725         has_data = 0;
1726
1727         if (level > 0) {
1728                 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1729                         if (tn->internal[i]) {
1730                                 tn->internal[i] =
1731                                     yaffs_prune_worker(dev,
1732                                                 tn->internal[i],
1733                                                 level - 1,
1734                                                 (i == 0) ? del0 : 1);
1735                         }
1736
1737                         if (tn->internal[i])
1738                                 has_data++;
1739                 }
1740         } else {
1741                 int tnode_size_u32 = dev->tnode_size / sizeof(u32);
1742                 u32 *map = (u32 *) tn;
1743
1744                 for (i = 0; !has_data && i < tnode_size_u32; i++) {
1745                         if (map[i])
1746                                 has_data++;
1747                 }
1748         }
1749
1750         if (has_data == 0 && del0) {
1751                 /* Free and return NULL */
1752                 yaffs_free_tnode(dev, tn);
1753                 tn = NULL;
1754         }
1755         return tn;
1756 }
1757
1758 static int yaffs_prune_tree(struct yaffs_dev *dev,
1759                             struct yaffs_file_var *file_struct)
1760 {
1761         int i;
1762         int has_data;
1763         int done = 0;
1764         struct yaffs_tnode *tn;
1765
1766         if (file_struct->top_level < 1)
1767                 return YAFFS_OK;
1768
1769         file_struct->top =
1770            yaffs_prune_worker(dev, file_struct->top, file_struct->top_level, 0);
1771
1772         /* Now we have a tree with all the non-zero branches NULL but
1773          * the height is the same as it was.
1774          * Let's see if we can trim internal tnodes to shorten the tree.
1775          * We can do this if only the 0th element in the tnode is in use
1776          * (ie all the non-zero are NULL)
1777          */
1778
1779         while (file_struct->top_level && !done) {
1780                 tn = file_struct->top;
1781
1782                 has_data = 0;
1783                 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1784                         if (tn->internal[i])
1785                                 has_data++;
1786                 }
1787
1788                 if (!has_data) {
1789                         file_struct->top = tn->internal[0];
1790                         file_struct->top_level--;
1791                         yaffs_free_tnode(dev, tn);
1792                 } else {
1793                         done = 1;
1794                 }
1795         }
1796
1797         return YAFFS_OK;
1798 }
1799
1800 /*-------------------- End of File Structure functions.-------------------*/
1801
1802 /* alloc_empty_obj gets us a clean Object.*/
1803 static struct yaffs_obj *yaffs_alloc_empty_obj(struct yaffs_dev *dev)
1804 {
1805         struct yaffs_obj *obj = yaffs_alloc_raw_obj(dev);
1806
1807         if (!obj)
1808                 return obj;
1809
1810         dev->n_obj++;
1811
1812         /* Now sweeten it up... */
1813
1814         memset(obj, 0, sizeof(struct yaffs_obj));
1815         obj->being_created = 1;
1816
1817         obj->my_dev = dev;
1818         obj->hdr_chunk = 0;
1819         obj->variant_type = YAFFS_OBJECT_TYPE_UNKNOWN;
1820         INIT_LIST_HEAD(&(obj->hard_links));
1821         INIT_LIST_HEAD(&(obj->hash_link));
1822         INIT_LIST_HEAD(&obj->siblings);
1823
1824         /* Now make the directory sane */
1825         if (dev->root_dir) {
1826                 obj->parent = dev->root_dir;
1827                 list_add(&(obj->siblings),
1828                          &dev->root_dir->variant.dir_variant.children);
1829         }
1830
1831         /* Add it to the lost and found directory.
1832          * NB Can't put root or lost-n-found in lost-n-found so
1833          * check if lost-n-found exists first
1834          */
1835         if (dev->lost_n_found)
1836                 yaffs_add_obj_to_dir(dev->lost_n_found, obj);
1837
1838         obj->being_created = 0;
1839
1840         dev->checkpoint_blocks_required = 0;    /* force recalculation */
1841
1842         return obj;
1843 }
1844
1845 static int yaffs_find_nice_bucket(struct yaffs_dev *dev)
1846 {
1847         int i;
1848         int l = 999;
1849         int lowest = 999999;
1850
1851         /* Search for the shortest list or one that
1852          * isn't too long.
1853          */
1854
1855         for (i = 0; i < 10 && lowest > 4; i++) {
1856                 dev->bucket_finder++;
1857                 dev->bucket_finder %= YAFFS_NOBJECT_BUCKETS;
1858                 if (dev->obj_bucket[dev->bucket_finder].count < lowest) {
1859                         lowest = dev->obj_bucket[dev->bucket_finder].count;
1860                         l = dev->bucket_finder;
1861                 }
1862         }
1863
1864         return l;
1865 }
1866
1867 static int yaffs_new_obj_id(struct yaffs_dev *dev)
1868 {
1869         int bucket = yaffs_find_nice_bucket(dev);
1870         int found = 0;
1871         struct list_head *i;
1872         u32 n = (u32) bucket;
1873
1874         /* Now find an object value that has not already been taken
1875          * by scanning the list.
1876          */
1877
1878         while (!found) {
1879                 found = 1;
1880                 n += YAFFS_NOBJECT_BUCKETS;
1881                 if (1 || dev->obj_bucket[bucket].count > 0) {
1882                         list_for_each(i, &dev->obj_bucket[bucket].list) {
1883                                 /* If there is already one in the list */
1884                                 if (i && list_entry(i, struct yaffs_obj,
1885                                                     hash_link)->obj_id == n) {
1886                                         found = 0;
1887                                 }
1888                         }
1889                 }
1890         }
1891         return n;
1892 }
1893
1894 static void yaffs_hash_obj(struct yaffs_obj *in)
1895 {
1896         int bucket = yaffs_hash_fn(in->obj_id);
1897         struct yaffs_dev *dev = in->my_dev;
1898
1899         list_add(&in->hash_link, &dev->obj_bucket[bucket].list);
1900         dev->obj_bucket[bucket].count++;
1901 }
1902
1903 struct yaffs_obj *yaffs_find_by_number(struct yaffs_dev *dev, u32 number)
1904 {
1905         int bucket = yaffs_hash_fn(number);
1906         struct list_head *i;
1907         struct yaffs_obj *in;
1908
1909         list_for_each(i, &dev->obj_bucket[bucket].list) {
1910                 /* Look if it is in the list */
1911                 in = list_entry(i, struct yaffs_obj, hash_link);
1912                 if (in->obj_id == number) {
1913                         /* Don't show if it is defered free */
1914                         if (in->defered_free)
1915                                 return NULL;
1916                         return in;
1917                 }
1918         }
1919
1920         return NULL;
1921 }
1922
1923 struct yaffs_obj *yaffs_new_obj(struct yaffs_dev *dev, int number,
1924                                 enum yaffs_obj_type type)
1925 {
1926         struct yaffs_obj *the_obj = NULL;
1927         struct yaffs_tnode *tn = NULL;
1928
1929         if (number < 0)
1930                 number = yaffs_new_obj_id(dev);
1931
1932         if (type == YAFFS_OBJECT_TYPE_FILE) {
1933                 tn = yaffs_get_tnode(dev);
1934                 if (!tn)
1935                         return NULL;
1936         }
1937
1938         the_obj = yaffs_alloc_empty_obj(dev);
1939         if (!the_obj) {
1940                 if (tn)
1941                         yaffs_free_tnode(dev, tn);
1942                 return NULL;
1943         }
1944
1945         the_obj->fake = 0;
1946         the_obj->rename_allowed = 1;
1947         the_obj->unlink_allowed = 1;
1948         the_obj->obj_id = number;
1949         yaffs_hash_obj(the_obj);
1950         the_obj->variant_type = type;
1951         yaffs_load_current_time(the_obj, 1, 1);
1952
1953         switch (type) {
1954         case YAFFS_OBJECT_TYPE_FILE:
1955                 the_obj->variant.file_variant.file_size = 0;
1956                 the_obj->variant.file_variant.scanned_size = 0;
1957                 the_obj->variant.file_variant.shrink_size = ~0; /* max */
1958                 the_obj->variant.file_variant.top_level = 0;
1959                 the_obj->variant.file_variant.top = tn;
1960                 break;
1961         case YAFFS_OBJECT_TYPE_DIRECTORY:
1962                 INIT_LIST_HEAD(&the_obj->variant.dir_variant.children);
1963                 INIT_LIST_HEAD(&the_obj->variant.dir_variant.dirty);
1964                 break;
1965         case YAFFS_OBJECT_TYPE_SYMLINK:
1966         case YAFFS_OBJECT_TYPE_HARDLINK:
1967         case YAFFS_OBJECT_TYPE_SPECIAL:
1968                 /* No action required */
1969                 break;
1970         case YAFFS_OBJECT_TYPE_UNKNOWN:
1971                 /* todo this should not happen */
1972                 break;
1973         }
1974         return the_obj;
1975 }
1976
1977 static struct yaffs_obj *yaffs_create_fake_dir(struct yaffs_dev *dev,
1978                                                int number, u32 mode)
1979 {
1980
1981         struct yaffs_obj *obj =
1982             yaffs_new_obj(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1983
1984         if (!obj)
1985                 return NULL;
1986
1987         obj->fake = 1;  /* it is fake so it might not use NAND */
1988         obj->rename_allowed = 0;
1989         obj->unlink_allowed = 0;
1990         obj->deleted = 0;
1991         obj->unlinked = 0;
1992         obj->yst_mode = mode;
1993         obj->my_dev = dev;
1994         obj->hdr_chunk = 0;     /* Not a valid chunk. */
1995         return obj;
1996
1997 }
1998
1999
2000 static void yaffs_init_tnodes_and_objs(struct yaffs_dev *dev)
2001 {
2002         int i;
2003
2004         dev->n_obj = 0;
2005         dev->n_tnodes = 0;
2006         yaffs_init_raw_tnodes_and_objs(dev);
2007
2008         for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2009                 INIT_LIST_HEAD(&dev->obj_bucket[i].list);
2010                 dev->obj_bucket[i].count = 0;
2011         }
2012 }
2013
2014 struct yaffs_obj *yaffs_find_or_create_by_number(struct yaffs_dev *dev,
2015                                                  int number,
2016                                                  enum yaffs_obj_type type)
2017 {
2018         struct yaffs_obj *the_obj = NULL;
2019
2020         if (number > 0)
2021                 the_obj = yaffs_find_by_number(dev, number);
2022
2023         if (!the_obj)
2024                 the_obj = yaffs_new_obj(dev, number, type);
2025
2026         return the_obj;
2027
2028 }
2029
2030 YCHAR *yaffs_clone_str(const YCHAR *str)
2031 {
2032         YCHAR *new_str = NULL;
2033         int len;
2034
2035         if (!str)
2036                 str = _Y("");
2037
2038         len = strnlen(str, YAFFS_MAX_ALIAS_LENGTH);
2039         new_str = kmalloc((len + 1) * sizeof(YCHAR), GFP_NOFS);
2040         if (new_str) {
2041                 strncpy(new_str, str, len);
2042                 new_str[len] = 0;
2043         }
2044         return new_str;
2045
2046 }
2047 /*
2048  *yaffs_update_parent() handles fixing a directories mtime and ctime when a new
2049  * link (ie. name) is created or deleted in the directory.
2050  *
2051  * ie.
2052  *   create dir/a : update dir's mtime/ctime
2053  *   rm dir/a:   update dir's mtime/ctime
2054  *   modify dir/a: don't update dir's mtimme/ctime
2055  *
2056  * This can be handled immediately or defered. Defering helps reduce the number
2057  * of updates when many files in a directory are changed within a brief period.
2058  *
2059  * If the directory updating is defered then yaffs_update_dirty_dirs must be
2060  * called periodically.
2061  */
2062
2063 static void yaffs_update_parent(struct yaffs_obj *obj)
2064 {
2065         struct yaffs_dev *dev;
2066
2067         if (!obj)
2068                 return;
2069         dev = obj->my_dev;
2070         obj->dirty = 1;
2071         yaffs_load_current_time(obj, 0, 1);
2072         if (dev->param.defered_dir_update) {
2073                 struct list_head *link = &obj->variant.dir_variant.dirty;
2074
2075                 if (list_empty(link)) {
2076                         list_add(link, &dev->dirty_dirs);
2077                         yaffs_trace(YAFFS_TRACE_BACKGROUND,
2078                           "Added object %d to dirty directories",
2079                            obj->obj_id);
2080                 }
2081
2082         } else {
2083                 yaffs_update_oh(obj, NULL, 0, 0, 0, NULL);
2084         }
2085 }
2086
2087 void yaffs_update_dirty_dirs(struct yaffs_dev *dev)
2088 {
2089         struct list_head *link;
2090         struct yaffs_obj *obj;
2091         struct yaffs_dir_var *d_s;
2092         union yaffs_obj_var *o_v;
2093
2094         yaffs_trace(YAFFS_TRACE_BACKGROUND, "Update dirty directories");
2095
2096         while (!list_empty(&dev->dirty_dirs)) {
2097                 link = dev->dirty_dirs.next;
2098                 list_del_init(link);
2099
2100                 d_s = list_entry(link, struct yaffs_dir_var, dirty);
2101                 o_v = list_entry(d_s, union yaffs_obj_var, dir_variant);
2102                 obj = list_entry(o_v, struct yaffs_obj, variant);
2103
2104                 yaffs_trace(YAFFS_TRACE_BACKGROUND, "Update directory %d",
2105                         obj->obj_id);
2106
2107                 if (obj->dirty)
2108                         yaffs_update_oh(obj, NULL, 0, 0, 0, NULL);
2109         }
2110 }
2111
2112 /*
2113  * Mknod (create) a new object.
2114  * equiv_obj only has meaning for a hard link;
2115  * alias_str only has meaning for a symlink.
2116  * rdev only has meaning for devices (a subset of special objects)
2117  */
2118
2119 static struct yaffs_obj *yaffs_create_obj(enum yaffs_obj_type type,
2120                                           struct yaffs_obj *parent,
2121                                           const YCHAR *name,
2122                                           u32 mode,
2123                                           u32 uid,
2124                                           u32 gid,
2125                                           struct yaffs_obj *equiv_obj,
2126                                           const YCHAR *alias_str, u32 rdev)
2127 {
2128         struct yaffs_obj *in;
2129         YCHAR *str = NULL;
2130         struct yaffs_dev *dev = parent->my_dev;
2131
2132         /* Check if the entry exists.
2133          * If it does then fail the call since we don't want a dup. */
2134         if (yaffs_find_by_name(parent, name))
2135                 return NULL;
2136
2137         if (type == YAFFS_OBJECT_TYPE_SYMLINK) {
2138                 str = yaffs_clone_str(alias_str);
2139                 if (!str)
2140                         return NULL;
2141         }
2142
2143         in = yaffs_new_obj(dev, -1, type);
2144
2145         if (!in) {
2146                 kfree(str);
2147                 return NULL;
2148         }
2149
2150         in->hdr_chunk = 0;
2151         in->valid = 1;
2152         in->variant_type = type;
2153
2154         in->yst_mode = mode;
2155
2156         yaffs_attribs_init(in, gid, uid, rdev);
2157
2158         in->n_data_chunks = 0;
2159
2160         yaffs_set_obj_name(in, name);
2161         in->dirty = 1;
2162
2163         yaffs_add_obj_to_dir(parent, in);
2164
2165         in->my_dev = parent->my_dev;
2166
2167         switch (type) {
2168         case YAFFS_OBJECT_TYPE_SYMLINK:
2169                 in->variant.symlink_variant.alias = str;
2170                 break;
2171         case YAFFS_OBJECT_TYPE_HARDLINK:
2172                 in->variant.hardlink_variant.equiv_obj = equiv_obj;
2173                 in->variant.hardlink_variant.equiv_id = equiv_obj->obj_id;
2174                 list_add(&in->hard_links, &equiv_obj->hard_links);
2175                 break;
2176         case YAFFS_OBJECT_TYPE_FILE:
2177         case YAFFS_OBJECT_TYPE_DIRECTORY:
2178         case YAFFS_OBJECT_TYPE_SPECIAL:
2179         case YAFFS_OBJECT_TYPE_UNKNOWN:
2180                 /* do nothing */
2181                 break;
2182         }
2183
2184         if (yaffs_update_oh(in, name, 0, 0, 0, NULL) < 0) {
2185                 /* Could not create the object header, fail */
2186                 yaffs_del_obj(in);
2187                 in = NULL;
2188         }
2189
2190         if (in)
2191                 yaffs_update_parent(parent);
2192
2193         return in;
2194 }
2195
2196 struct yaffs_obj *yaffs_create_file(struct yaffs_obj *parent,
2197                                     const YCHAR *name, u32 mode, u32 uid,
2198                                     u32 gid)
2199 {
2200         return yaffs_create_obj(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2201                                 uid, gid, NULL, NULL, 0);
2202 }
2203
2204 struct yaffs_obj *yaffs_create_dir(struct yaffs_obj *parent, const YCHAR *name,
2205                                    u32 mode, u32 uid, u32 gid)
2206 {
2207         return yaffs_create_obj(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2208                                 mode, uid, gid, NULL, NULL, 0);
2209 }
2210
2211 struct yaffs_obj *yaffs_create_special(struct yaffs_obj *parent,
2212                                        const YCHAR *name, u32 mode, u32 uid,
2213                                        u32 gid, u32 rdev)
2214 {
2215         return yaffs_create_obj(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2216                                 uid, gid, NULL, NULL, rdev);
2217 }
2218
2219 struct yaffs_obj *yaffs_create_symlink(struct yaffs_obj *parent,
2220                                        const YCHAR *name, u32 mode, u32 uid,
2221                                        u32 gid, const YCHAR *alias)
2222 {
2223         return yaffs_create_obj(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2224                                 uid, gid, NULL, alias, 0);
2225 }
2226
2227 /* yaffs_link_obj returns the object id of the equivalent object.*/
2228 struct yaffs_obj *yaffs_link_obj(struct yaffs_obj *parent, const YCHAR * name,
2229                                  struct yaffs_obj *equiv_obj)
2230 {
2231         /* Get the real object in case we were fed a hard link obj */
2232         equiv_obj = yaffs_get_equivalent_obj(equiv_obj);
2233
2234         if (yaffs_create_obj(YAFFS_OBJECT_TYPE_HARDLINK,
2235                         parent, name, 0, 0, 0,
2236                         equiv_obj, NULL, 0))
2237                 return equiv_obj;
2238
2239         return NULL;
2240
2241 }
2242
2243
2244
2245 /*---------------------- Block Management and Page Allocation -------------*/
2246
2247 static void yaffs_deinit_blocks(struct yaffs_dev *dev)
2248 {
2249         if (dev->block_info_alt && dev->block_info)
2250                 vfree(dev->block_info);
2251         else
2252                 kfree(dev->block_info);
2253
2254         dev->block_info_alt = 0;
2255
2256         dev->block_info = NULL;
2257
2258         if (dev->chunk_bits_alt && dev->chunk_bits)
2259                 vfree(dev->chunk_bits);
2260         else
2261                 kfree(dev->chunk_bits);
2262         dev->chunk_bits_alt = 0;
2263         dev->chunk_bits = NULL;
2264 }
2265
2266 static int yaffs_init_blocks(struct yaffs_dev *dev)
2267 {
2268         int n_blocks = dev->internal_end_block - dev->internal_start_block + 1;
2269
2270         dev->block_info = NULL;
2271         dev->chunk_bits = NULL;
2272         dev->alloc_block = -1;  /* force it to get a new one */
2273
2274         /* If the first allocation strategy fails, thry the alternate one */
2275         dev->block_info =
2276                 kmalloc(n_blocks * sizeof(struct yaffs_block_info), GFP_NOFS);
2277         if (!dev->block_info) {
2278                 dev->block_info =
2279                     vmalloc(n_blocks * sizeof(struct yaffs_block_info));
2280                 dev->block_info_alt = 1;
2281         } else {
2282                 dev->block_info_alt = 0;
2283         }
2284
2285         if (!dev->block_info)
2286                 goto alloc_error;
2287
2288         /* Set up dynamic blockinfo stuff. Round up bytes. */
2289         dev->chunk_bit_stride = (dev->param.chunks_per_block + 7) / 8;
2290         dev->chunk_bits =
2291                 kmalloc(dev->chunk_bit_stride * n_blocks, GFP_NOFS);
2292         if (!dev->chunk_bits) {
2293                 dev->chunk_bits =
2294                     vmalloc(dev->chunk_bit_stride * n_blocks);
2295                 dev->chunk_bits_alt = 1;
2296         } else {
2297                 dev->chunk_bits_alt = 0;
2298         }
2299         if (!dev->chunk_bits)
2300                 goto alloc_error;
2301
2302
2303         memset(dev->block_info, 0, n_blocks * sizeof(struct yaffs_block_info));
2304         memset(dev->chunk_bits, 0, dev->chunk_bit_stride * n_blocks);
2305         return YAFFS_OK;
2306
2307 alloc_error:
2308         yaffs_deinit_blocks(dev);
2309         return YAFFS_FAIL;
2310 }
2311
2312
2313 void yaffs_block_became_dirty(struct yaffs_dev *dev, int block_no)
2314 {
2315         struct yaffs_block_info *bi = yaffs_get_block_info(dev, block_no);
2316         int erased_ok = 0;
2317         int i;
2318
2319         /* If the block is still healthy erase it and mark as clean.
2320          * If the block has had a data failure, then retire it.
2321          */
2322
2323         yaffs_trace(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2324                 "yaffs_block_became_dirty block %d state %d %s",
2325                 block_no, bi->block_state,
2326                 (bi->needs_retiring) ? "needs retiring" : "");
2327
2328         yaffs2_clear_oldest_dirty_seq(dev, bi);
2329
2330         bi->block_state = YAFFS_BLOCK_STATE_DIRTY;
2331
2332         /* If this is the block being garbage collected then stop gc'ing */
2333         if (block_no == dev->gc_block)
2334                 dev->gc_block = 0;
2335
2336         /* If this block is currently the best candidate for gc
2337          * then drop as a candidate */
2338         if (block_no == dev->gc_dirtiest) {
2339                 dev->gc_dirtiest = 0;
2340                 dev->gc_pages_in_use = 0;
2341         }
2342
2343         if (!bi->needs_retiring) {
2344                 yaffs2_checkpt_invalidate(dev);
2345                 erased_ok = yaffs_erase_block(dev, block_no);
2346                 if (!erased_ok) {
2347                         dev->n_erase_failures++;
2348                         yaffs_trace(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2349                           "**>> Erasure failed %d", block_no);
2350                 }
2351         }
2352
2353         /* Verify erasure if needed */
2354         if (erased_ok &&
2355             ((yaffs_trace_mask & YAFFS_TRACE_ERASE) ||
2356              !yaffs_skip_verification(dev))) {
2357                 for (i = 0; i < dev->param.chunks_per_block; i++) {
2358                         if (!yaffs_check_chunk_erased(dev,
2359                                 block_no * dev->param.chunks_per_block + i)) {
2360                                 yaffs_trace(YAFFS_TRACE_ERROR,
2361                                         ">>Block %d erasure supposedly OK, but chunk %d not erased",
2362                                         block_no, i);
2363                         }
2364                 }
2365         }
2366
2367         if (!erased_ok) {
2368                 /* We lost a block of free space */
2369                 dev->n_free_chunks -= dev->param.chunks_per_block;
2370                 yaffs_retire_block(dev, block_no);
2371                 yaffs_trace(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2372                         "**>> Block %d retired", block_no);
2373                 return;
2374         }
2375
2376         /* Clean it up... */
2377         bi->block_state = YAFFS_BLOCK_STATE_EMPTY;
2378         bi->seq_number = 0;
2379         dev->n_erased_blocks++;
2380         bi->pages_in_use = 0;
2381         bi->soft_del_pages = 0;
2382         bi->has_shrink_hdr = 0;
2383         bi->skip_erased_check = 1;      /* Clean, so no need to check */
2384         bi->gc_prioritise = 0;
2385         yaffs_clear_chunk_bits(dev, block_no);
2386
2387         yaffs_trace(YAFFS_TRACE_ERASE, "Erased block %d", block_no);
2388 }
2389
2390 static inline int yaffs_gc_process_chunk(struct yaffs_dev *dev,
2391                                         struct yaffs_block_info *bi,
2392                                         int old_chunk, u8 *buffer)
2393 {
2394         int new_chunk;
2395         int mark_flash = 1;
2396         struct yaffs_ext_tags tags;
2397         struct yaffs_obj *object;
2398         int matching_chunk;
2399         int ret_val = YAFFS_OK;
2400
2401         memset(&tags, 0, sizeof(tags));
2402         yaffs_rd_chunk_tags_nand(dev, old_chunk,
2403                                  buffer, &tags);
2404         object = yaffs_find_by_number(dev, tags.obj_id);
2405
2406         yaffs_trace(YAFFS_TRACE_GC_DETAIL,
2407                 "Collecting chunk in block %d, %d %d %d ",
2408                 dev->gc_chunk, tags.obj_id,
2409                 tags.chunk_id, tags.n_bytes);
2410
2411         if (object && !yaffs_skip_verification(dev)) {
2412                 if (tags.chunk_id == 0)
2413                         matching_chunk =
2414                             object->hdr_chunk;
2415                 else if (object->soft_del)
2416                         /* Defeat the test */
2417                         matching_chunk = old_chunk;
2418                 else
2419                         matching_chunk =
2420                             yaffs_find_chunk_in_file
2421                             (object, tags.chunk_id,
2422                              NULL);
2423
2424                 if (old_chunk != matching_chunk)
2425                         yaffs_trace(YAFFS_TRACE_ERROR,
2426                                 "gc: page in gc mismatch: %d %d %d %d",
2427                                 old_chunk,
2428                                 matching_chunk,
2429                                 tags.obj_id,
2430                                 tags.chunk_id);
2431         }
2432
2433         if (!object) {
2434                 yaffs_trace(YAFFS_TRACE_ERROR,
2435                         "page %d in gc has no object: %d %d %d ",
2436                         old_chunk,
2437                         tags.obj_id, tags.chunk_id,
2438                         tags.n_bytes);
2439         }
2440
2441         if (object &&
2442             object->deleted &&
2443             object->soft_del && tags.chunk_id != 0) {
2444                 /* Data chunk in a soft deleted file,
2445                  * throw it away.
2446                  * It's a soft deleted data chunk,
2447                  * No need to copy this, just forget
2448                  * about it and fix up the object.
2449                  */
2450
2451                 /* Free chunks already includes
2452                  * softdeleted chunks, how ever this
2453                  * chunk is going to soon be really
2454                  * deleted which will increment free
2455                  * chunks. We have to decrement free
2456                  * chunks so this works out properly.
2457                  */
2458                 dev->n_free_chunks--;
2459                 bi->soft_del_pages--;
2460
2461                 object->n_data_chunks--;
2462                 if (object->n_data_chunks <= 0) {
2463                         /* remeber to clean up obj */
2464                         dev->gc_cleanup_list[dev->n_clean_ups] = tags.obj_id;
2465                         dev->n_clean_ups++;
2466                 }
2467                 mark_flash = 0;
2468         } else if (object) {
2469                 /* It's either a data chunk in a live
2470                  * file or an ObjectHeader, so we're
2471                  * interested in it.
2472                  * NB Need to keep the ObjectHeaders of
2473                  * deleted files until the whole file
2474                  * has been deleted off
2475                  */
2476                 tags.serial_number++;
2477                 dev->n_gc_copies++;
2478
2479                 if (tags.chunk_id == 0) {
2480                         /* It is an object Id,
2481                          * We need to nuke the
2482                          * shrinkheader flags since its
2483                          * work is done.
2484                          * Also need to clean up
2485                          * shadowing.
2486                          */
2487                         struct yaffs_obj_hdr *oh;
2488                         oh = (struct yaffs_obj_hdr *) buffer;
2489
2490                         oh->is_shrink = 0;
2491                         tags.extra_is_shrink = 0;
2492                         oh->shadows_obj = 0;
2493                         oh->inband_shadowed_obj_id = 0;
2494                         tags.extra_shadows = 0;
2495
2496                         /* Update file size */
2497                         if (object->variant_type == YAFFS_OBJECT_TYPE_FILE) {
2498                                 oh->file_size =
2499                                     object->variant.file_variant.file_size;
2500                                 tags.extra_length = oh->file_size;
2501                         }
2502
2503                         yaffs_verify_oh(object, oh, &tags, 1);
2504                         new_chunk =
2505                             yaffs_write_new_chunk(dev, (u8 *) oh, &tags, 1);
2506                 } else {
2507                         new_chunk =
2508                             yaffs_write_new_chunk(dev, buffer, &tags, 1);
2509                 }
2510
2511                 if (new_chunk < 0) {
2512                         ret_val = YAFFS_FAIL;
2513                 } else {
2514
2515                         /* Now fix up the Tnodes etc. */
2516
2517                         if (tags.chunk_id == 0) {
2518                                 /* It's a header */
2519                                 object->hdr_chunk = new_chunk;
2520                                 object->serial = tags.serial_number;
2521                         } else {
2522                                 /* It's a data chunk */
2523                                 yaffs_put_chunk_in_file(object, tags.chunk_id,
2524                                                         new_chunk, 0);
2525                         }
2526                 }
2527         }
2528         if (ret_val == YAFFS_OK)
2529                 yaffs_chunk_del(dev, old_chunk, mark_flash, __LINE__);
2530         return ret_val;
2531 }
2532
2533 static int yaffs_gc_block(struct yaffs_dev *dev, int block, int whole_block)
2534 {
2535         int old_chunk;
2536         int ret_val = YAFFS_OK;
2537         int i;
2538         int is_checkpt_block;
2539         int max_copies;
2540         int chunks_before = yaffs_get_erased_chunks(dev);
2541         int chunks_after;
2542         struct yaffs_block_info *bi = yaffs_get_block_info(dev, block);
2543
2544         is_checkpt_block = (bi->block_state == YAFFS_BLOCK_STATE_CHECKPOINT);
2545
2546         yaffs_trace(YAFFS_TRACE_TRACING,
2547                 "Collecting block %d, in use %d, shrink %d, whole_block %d",
2548                 block, bi->pages_in_use, bi->has_shrink_hdr,
2549                 whole_block);
2550
2551         /*yaffs_verify_free_chunks(dev); */
2552
2553         if (bi->block_state == YAFFS_BLOCK_STATE_FULL)
2554                 bi->block_state = YAFFS_BLOCK_STATE_COLLECTING;
2555
2556         bi->has_shrink_hdr = 0; /* clear the flag so that the block can erase */
2557
2558         dev->gc_disable = 1;
2559
2560         if (is_checkpt_block || !yaffs_still_some_chunks(dev, block)) {
2561                 yaffs_trace(YAFFS_TRACE_TRACING,
2562                         "Collecting block %d that has no chunks in use",
2563                         block);
2564                 yaffs_block_became_dirty(dev, block);
2565         } else {
2566
2567                 u8 *buffer = yaffs_get_temp_buffer(dev);
2568
2569                 yaffs_verify_blk(dev, bi, block);
2570
2571                 max_copies = (whole_block) ? dev->param.chunks_per_block : 5;
2572                 old_chunk = block * dev->param.chunks_per_block + dev->gc_chunk;
2573
2574                 for (/* init already done */ ;
2575                      ret_val == YAFFS_OK &&
2576                      dev->gc_chunk < dev->param.chunks_per_block &&
2577                      (bi->block_state == YAFFS_BLOCK_STATE_COLLECTING) &&
2578                      max_copies > 0;
2579                      dev->gc_chunk++, old_chunk++) {
2580                         if (yaffs_check_chunk_bit(dev, block, dev->gc_chunk)) {
2581                                 /* Page is in use and might need to be copied */
2582                                 max_copies--;
2583                                 ret_val = yaffs_gc_process_chunk(dev, bi,
2584                                                         old_chunk, buffer);
2585                         }
2586                 }
2587                 yaffs_release_temp_buffer(dev, buffer);
2588         }
2589
2590         yaffs_verify_collected_blk(dev, bi, block);
2591
2592         if (bi->block_state == YAFFS_BLOCK_STATE_COLLECTING) {
2593                 /*
2594                  * The gc did not complete. Set block state back to FULL
2595                  * because checkpointing does not restore gc.
2596                  */
2597                 bi->block_state = YAFFS_BLOCK_STATE_FULL;
2598         } else {
2599                 /* The gc completed. */
2600                 /* Do any required cleanups */
2601                 for (i = 0; i < dev->n_clean_ups; i++) {
2602                         /* Time to delete the file too */
2603                         struct yaffs_obj *object =
2604                             yaffs_find_by_number(dev, dev->gc_cleanup_list[i]);
2605                         if (object) {
2606                                 yaffs_free_tnode(dev,
2607                                           object->variant.file_variant.top);
2608                                 object->variant.file_variant.top = NULL;
2609                                 yaffs_trace(YAFFS_TRACE_GC,
2610                                         "yaffs: About to finally delete object %d",
2611                                         object->obj_id);
2612                                 yaffs_generic_obj_del(object);
2613                                 object->my_dev->n_deleted_files--;
2614                         }
2615
2616                 }
2617                 chunks_after = yaffs_get_erased_chunks(dev);
2618                 if (chunks_before >= chunks_after)
2619                         yaffs_trace(YAFFS_TRACE_GC,
2620                                 "gc did not increase free chunks before %d after %d",
2621                                 chunks_before, chunks_after);
2622                 dev->gc_block = 0;
2623                 dev->gc_chunk = 0;
2624                 dev->n_clean_ups = 0;
2625         }
2626
2627         dev->gc_disable = 0;
2628
2629         return ret_val;
2630 }
2631
2632 /*
2633  * find_gc_block() selects the dirtiest block (or close enough)
2634  * for garbage collection.
2635  */
2636
2637 static unsigned yaffs_find_gc_block(struct yaffs_dev *dev,
2638                                     int aggressive, int background)
2639 {
2640         int i;
2641         int iterations;
2642         unsigned selected = 0;
2643         int prioritised = 0;
2644         int prioritised_exist = 0;
2645         struct yaffs_block_info *bi;
2646         int threshold;
2647
2648         /* First let's see if we need to grab a prioritised block */
2649         if (dev->has_pending_prioritised_gc && !aggressive) {
2650                 dev->gc_dirtiest = 0;
2651                 bi = dev->block_info;
2652                 for (i = dev->internal_start_block;
2653                      i <= dev->internal_end_block && !selected; i++) {
2654
2655                         if (bi->gc_prioritise) {
2656                                 prioritised_exist = 1;
2657                                 if (bi->block_state == YAFFS_BLOCK_STATE_FULL &&
2658                                     yaffs_block_ok_for_gc(dev, bi)) {
2659                                         selected = i;
2660                                         prioritised = 1;
2661                                 }
2662                         }
2663                         bi++;
2664                 }
2665
2666                 /*
2667                  * If there is a prioritised block and none was selected then
2668                  * this happened because there is at least one old dirty block
2669                  * gumming up the works. Let's gc the oldest dirty block.
2670                  */
2671
2672                 if (prioritised_exist &&
2673                     !selected && dev->oldest_dirty_block > 0)
2674                         selected = dev->oldest_dirty_block;
2675
2676                 if (!prioritised_exist) /* None found, so we can clear this */
2677                         dev->has_pending_prioritised_gc = 0;
2678         }
2679
2680         /* If we're doing aggressive GC then we are happy to take a less-dirty
2681          * block, and search harder.
2682          * else (leasurely gc), then we only bother to do this if the
2683          * block has only a few pages in use.
2684          */
2685
2686         if (!selected) {
2687                 int pages_used;
2688                 int n_blocks =
2689                     dev->internal_end_block - dev->internal_start_block + 1;
2690                 if (aggressive) {
2691                         threshold = dev->param.chunks_per_block;
2692                         iterations = n_blocks;
2693                 } else {
2694                         int max_threshold;
2695
2696                         if (background)
2697                                 max_threshold = dev->param.chunks_per_block / 2;
2698                         else
2699                                 max_threshold = dev->param.chunks_per_block / 8;
2700
2701                         if (max_threshold < YAFFS_GC_PASSIVE_THRESHOLD)
2702                                 max_threshold = YAFFS_GC_PASSIVE_THRESHOLD;
2703
2704                         threshold = background ? (dev->gc_not_done + 2) * 2 : 0;
2705                         if (threshold < YAFFS_GC_PASSIVE_THRESHOLD)
2706                                 threshold = YAFFS_GC_PASSIVE_THRESHOLD;
2707                         if (threshold > max_threshold)
2708                                 threshold = max_threshold;
2709
2710                         iterations = n_blocks / 16 + 1;
2711                         if (iterations > 100)
2712                                 iterations = 100;
2713                 }
2714
2715                 for (i = 0;
2716                      i < iterations &&
2717                      (dev->gc_dirtiest < 1 ||
2718                       dev->gc_pages_in_use > YAFFS_GC_GOOD_ENOUGH);
2719                      i++) {
2720                         dev->gc_block_finder++;
2721                         if (dev->gc_block_finder < dev->internal_start_block ||
2722                             dev->gc_block_finder > dev->internal_end_block)
2723                                 dev->gc_block_finder =
2724                                     dev->internal_start_block;
2725
2726                         bi = yaffs_get_block_info(dev, dev->gc_block_finder);
2727
2728                         pages_used = bi->pages_in_use - bi->soft_del_pages;
2729
2730                         if (bi->block_state == YAFFS_BLOCK_STATE_FULL &&
2731                             pages_used < dev->param.chunks_per_block &&
2732                             (dev->gc_dirtiest < 1 ||
2733                              pages_used < dev->gc_pages_in_use) &&
2734                             yaffs_block_ok_for_gc(dev, bi)) {
2735                                 dev->gc_dirtiest = dev->gc_block_finder;
2736                                 dev->gc_pages_in_use = pages_used;
2737                         }
2738                 }
2739
2740                 if (dev->gc_dirtiest > 0 && dev->gc_pages_in_use <= threshold)
2741                         selected = dev->gc_dirtiest;
2742         }
2743
2744         /*
2745          * If nothing has been selected for a while, try the oldest dirty
2746          * because that's gumming up the works.
2747          */
2748
2749         if (!selected && dev->param.is_yaffs2 &&
2750             dev->gc_not_done >= (background ? 10 : 20)) {
2751                 yaffs2_find_oldest_dirty_seq(dev);
2752                 if (dev->oldest_dirty_block > 0) {
2753                         selected = dev->oldest_dirty_block;
2754                         dev->gc_dirtiest = selected;
2755                         dev->oldest_dirty_gc_count++;
2756                         bi = yaffs_get_block_info(dev, selected);
2757                         dev->gc_pages_in_use =
2758                             bi->pages_in_use - bi->soft_del_pages;
2759                 } else {
2760                         dev->gc_not_done = 0;
2761                 }
2762         }
2763
2764         if (selected) {
2765                 yaffs_trace(YAFFS_TRACE_GC,
2766                         "GC Selected block %d with %d free, prioritised:%d",
2767                         selected,
2768                         dev->param.chunks_per_block - dev->gc_pages_in_use,
2769                         prioritised);
2770
2771                 dev->n_gc_blocks++;
2772                 if (background)
2773                         dev->bg_gcs++;
2774
2775                 dev->gc_dirtiest = 0;
2776                 dev->gc_pages_in_use = 0;
2777                 dev->gc_not_done = 0;
2778                 if (dev->refresh_skip > 0)
2779                         dev->refresh_skip--;
2780         } else {
2781                 dev->gc_not_done++;
2782                 yaffs_trace(YAFFS_TRACE_GC,
2783                         "GC none: finder %d skip %d threshold %d dirtiest %d using %d oldest %d%s",
2784                         dev->gc_block_finder, dev->gc_not_done, threshold,
2785                         dev->gc_dirtiest, dev->gc_pages_in_use,
2786                         dev->oldest_dirty_block, background ? " bg" : "");
2787         }
2788
2789         return selected;
2790 }
2791
2792 /* New garbage collector
2793  * If we're very low on erased blocks then we do aggressive garbage collection
2794  * otherwise we do "leasurely" garbage collection.
2795  * Aggressive gc looks further (whole array) and will accept less dirty blocks.
2796  * Passive gc only inspects smaller areas and only accepts more dirty blocks.
2797  *
2798  * The idea is to help clear out space in a more spread-out manner.
2799  * Dunno if it really does anything useful.
2800  */
2801 static int yaffs_check_gc(struct yaffs_dev *dev, int background)
2802 {
2803         int aggressive = 0;
2804         int gc_ok = YAFFS_OK;
2805         int max_tries = 0;
2806         int min_erased;
2807         int erased_chunks;
2808         int checkpt_block_adjust;
2809
2810         if (dev->param.gc_control && (dev->param.gc_control(dev) & 1) == 0)
2811                 return YAFFS_OK;
2812
2813         if (dev->gc_disable)
2814                 /* Bail out so we don't get recursive gc */
2815                 return YAFFS_OK;
2816
2817         /* This loop should pass the first time.
2818          * Only loops here if the collection does not increase space.
2819          */
2820
2821         do {
2822                 max_tries++;
2823
2824                 checkpt_block_adjust = yaffs_calc_checkpt_blocks_required(dev);
2825
2826                 min_erased =
2827                     dev->param.n_reserved_blocks + checkpt_block_adjust + 1;
2828                 erased_chunks =
2829                     dev->n_erased_blocks * dev->param.chunks_per_block;
2830
2831                 /* If we need a block soon then do aggressive gc. */
2832                 if (dev->n_erased_blocks < min_erased)
2833                         aggressive = 1;
2834                 else {
2835                         if (!background
2836                             && erased_chunks > (dev->n_free_chunks / 4))
2837                                 break;
2838
2839                         if (dev->gc_skip > 20)
2840                                 dev->gc_skip = 20;
2841                         if (erased_chunks < dev->n_free_chunks / 2 ||
2842                             dev->gc_skip < 1 || background)
2843                                 aggressive = 0;
2844                         else {
2845                                 dev->gc_skip--;
2846                                 break;
2847                         }
2848                 }
2849
2850                 dev->gc_skip = 5;
2851
2852                 /* If we don't already have a block being gc'd then see if we
2853                  * should start another */
2854
2855                 if (dev->gc_block < 1 && !aggressive) {
2856                         dev->gc_block = yaffs2_find_refresh_block(dev);
2857                         dev->gc_chunk = 0;
2858                         dev->n_clean_ups = 0;
2859                 }
2860                 if (dev->gc_block < 1) {
2861                         dev->gc_block =
2862                             yaffs_find_gc_block(dev, aggressive, background);
2863                         dev->gc_chunk = 0;
2864                         dev->n_clean_ups = 0;
2865                 }
2866
2867                 if (dev->gc_block > 0) {
2868                         dev->all_gcs++;
2869                         if (!aggressive)
2870                                 dev->passive_gc_count++;
2871
2872                         yaffs_trace(YAFFS_TRACE_GC,
2873                                 "yaffs: GC n_erased_blocks %d aggressive %d",
2874                                 dev->n_erased_blocks, aggressive);
2875
2876                         gc_ok = yaffs_gc_block(dev, dev->gc_block, aggressive);
2877                 }
2878
2879                 if (dev->n_erased_blocks < (dev->param.n_reserved_blocks) &&
2880                     dev->gc_block > 0) {
2881                         yaffs_trace(YAFFS_TRACE_GC,
2882                                 "yaffs: GC !!!no reclaim!!! n_erased_blocks %d after try %d block %d",
2883                                 dev->n_erased_blocks, max_tries,
2884                                 dev->gc_block);
2885                 }
2886         } while ((dev->n_erased_blocks < dev->param.n_reserved_blocks) &&
2887                  (dev->gc_block > 0) && (max_tries < 2));
2888
2889         return aggressive ? gc_ok : YAFFS_OK;
2890 }
2891
2892 /*
2893  * yaffs_bg_gc()
2894  * Garbage collects. Intended to be called from a background thread.
2895  * Returns non-zero if at least half the free chunks are erased.
2896  */
2897 int yaffs_bg_gc(struct yaffs_dev *dev, unsigned urgency)
2898 {
2899         int erased_chunks = dev->n_erased_blocks * dev->param.chunks_per_block;
2900
2901         yaffs_trace(YAFFS_TRACE_BACKGROUND, "Background gc %u", urgency);
2902
2903         yaffs_check_gc(dev, 1);
2904         return erased_chunks > dev->n_free_chunks / 2;
2905 }
2906
2907 /*-------------------- Data file manipulation -----------------*/
2908
2909 static int yaffs_rd_data_obj(struct yaffs_obj *in, int inode_chunk, u8 * buffer)
2910 {
2911         int nand_chunk = yaffs_find_chunk_in_file(in, inode_chunk, NULL);
2912
2913         if (nand_chunk >= 0)
2914                 return yaffs_rd_chunk_tags_nand(in->my_dev, nand_chunk,
2915                                                 buffer, NULL);
2916         else {
2917                 yaffs_trace(YAFFS_TRACE_NANDACCESS,
2918                         "Chunk %d not found zero instead",
2919                         nand_chunk);
2920                 /* get sane (zero) data if you read a hole */
2921                 memset(buffer, 0, in->my_dev->data_bytes_per_chunk);
2922                 return 0;
2923         }
2924
2925 }
2926
2927 void yaffs_chunk_del(struct yaffs_dev *dev, int chunk_id, int mark_flash,
2928                      int lyn)
2929 {
2930         int block;
2931         int page;
2932         struct yaffs_ext_tags tags;
2933         struct yaffs_block_info *bi;
2934
2935         if (chunk_id <= 0)
2936                 return;
2937
2938         dev->n_deletions++;
2939         block = chunk_id / dev->param.chunks_per_block;
2940         page = chunk_id % dev->param.chunks_per_block;
2941
2942         if (!yaffs_check_chunk_bit(dev, block, page))
2943                 yaffs_trace(YAFFS_TRACE_VERIFY,
2944                         "Deleting invalid chunk %d", chunk_id);
2945
2946         bi = yaffs_get_block_info(dev, block);
2947
2948         yaffs2_update_oldest_dirty_seq(dev, block, bi);
2949
2950         yaffs_trace(YAFFS_TRACE_DELETION,
2951                 "line %d delete of chunk %d",
2952                 lyn, chunk_id);
2953
2954         if (!dev->param.is_yaffs2 && mark_flash &&
2955             bi->block_state != YAFFS_BLOCK_STATE_COLLECTING) {
2956
2957                 memset(&tags, 0, sizeof(tags));
2958                 tags.is_deleted = 1;
2959                 yaffs_wr_chunk_tags_nand(dev, chunk_id, NULL, &tags);
2960                 yaffs_handle_chunk_update(dev, chunk_id, &tags);
2961         } else {
2962                 dev->n_unmarked_deletions++;
2963         }
2964
2965         /* Pull out of the management area.
2966          * If the whole block became dirty, this will kick off an erasure.
2967          */
2968         if (bi->block_state == YAFFS_BLOCK_STATE_ALLOCATING ||
2969             bi->block_state == YAFFS_BLOCK_STATE_FULL ||
2970             bi->block_state == YAFFS_BLOCK_STATE_NEEDS_SCAN ||
2971             bi->block_state == YAFFS_BLOCK_STATE_COLLECTING) {
2972                 dev->n_free_chunks++;
2973                 yaffs_clear_chunk_bit(dev, block, page);
2974                 bi->pages_in_use--;
2975
2976                 if (bi->pages_in_use == 0 &&
2977                     !bi->has_shrink_hdr &&
2978                     bi->block_state != YAFFS_BLOCK_STATE_ALLOCATING &&
2979                     bi->block_state != YAFFS_BLOCK_STATE_NEEDS_SCAN) {
2980                         yaffs_block_became_dirty(dev, block);
2981                 }
2982         }
2983 }
2984
2985 static int yaffs_wr_data_obj(struct yaffs_obj *in, int inode_chunk,
2986                              const u8 *buffer, int n_bytes, int use_reserve)
2987 {
2988         /* Find old chunk Need to do this to get serial number
2989          * Write new one and patch into tree.
2990          * Invalidate old tags.
2991          */
2992
2993         int prev_chunk_id;
2994         struct yaffs_ext_tags prev_tags;
2995         int new_chunk_id;
2996         struct yaffs_ext_tags new_tags;
2997         struct yaffs_dev *dev = in->my_dev;
2998
2999         yaffs_check_gc(dev, 0);
3000
3001         /* Get the previous chunk at this location in the file if it exists.
3002          * If it does not exist then put a zero into the tree. This creates
3003          * the tnode now, rather than later when it is harder to clean up.
3004          */
3005         prev_chunk_id = yaffs_find_chunk_in_file(in, inode_chunk, &prev_tags);
3006         if (prev_chunk_id < 1 &&
3007             !yaffs_put_chunk_in_file(in, inode_chunk, 0, 0))
3008                 return 0;
3009
3010         /* Set up new tags */
3011         memset(&new_tags, 0, sizeof(new_tags));
3012
3013         new_tags.chunk_id = inode_chunk;
3014         new_tags.obj_id = in->obj_id;
3015         new_tags.serial_number =
3016             (prev_chunk_id > 0) ? prev_tags.serial_number + 1 : 1;
3017         new_tags.n_bytes = n_bytes;
3018
3019         if (n_bytes < 1 || n_bytes > dev->param.total_bytes_per_chunk) {
3020                 yaffs_trace(YAFFS_TRACE_ERROR,
3021                   "Writing %d bytes to chunk!!!!!!!!!",
3022                    n_bytes);
3023                 BUG();
3024         }
3025
3026         new_chunk_id =
3027             yaffs_write_new_chunk(dev, buffer, &new_tags, use_reserve);
3028
3029         if (new_chunk_id > 0) {
3030                 yaffs_put_chunk_in_file(in, inode_chunk, new_chunk_id, 0);
3031
3032                 if (prev_chunk_id > 0)
3033                         yaffs_chunk_del(dev, prev_chunk_id, 1, __LINE__);
3034
3035                 yaffs_verify_file_sane(in);
3036         }
3037         return new_chunk_id;
3038
3039 }
3040
3041
3042
3043 static int yaffs_do_xattrib_mod(struct yaffs_obj *obj, int set,
3044                                 const YCHAR *name, const void *value, int size,
3045                                 int flags)
3046 {
3047         struct yaffs_xattr_mod xmod;
3048         int result;
3049
3050         xmod.set = set;
3051         xmod.name = name;
3052         xmod.data = value;
3053         xmod.size = size;
3054         xmod.flags = flags;
3055         xmod.result = -ENOSPC;
3056
3057         result = yaffs_update_oh(obj, NULL, 0, 0, 0, &xmod);
3058
3059         if (result > 0)
3060                 return xmod.result;
3061         else
3062                 return -ENOSPC;
3063 }
3064
3065 static int yaffs_apply_xattrib_mod(struct yaffs_obj *obj, char *buffer,
3066                                    struct yaffs_xattr_mod *xmod)
3067 {
3068         int retval = 0;
3069         int x_offs = sizeof(struct yaffs_obj_hdr);
3070         struct yaffs_dev *dev = obj->my_dev;
3071         int x_size = dev->data_bytes_per_chunk - sizeof(struct yaffs_obj_hdr);
3072         char *x_buffer = buffer + x_offs;
3073
3074         if (xmod->set)
3075                 retval =
3076                     nval_set(x_buffer, x_size, xmod->name, xmod->data,
3077                              xmod->size, xmod->flags);
3078         else
3079                 retval = nval_del(x_buffer, x_size, xmod->name);
3080
3081         obj->has_xattr = nval_hasvalues(x_buffer, x_size);
3082         obj->xattr_known = 1;
3083         xmod->result = retval;
3084
3085         return retval;
3086 }
3087
3088 static int yaffs_do_xattrib_fetch(struct yaffs_obj *obj, const YCHAR *name,
3089                                   void *value, int size)
3090 {
3091         char *buffer = NULL;
3092         int result;
3093         struct yaffs_ext_tags tags;
3094         struct yaffs_dev *dev = obj->my_dev;
3095         int x_offs = sizeof(struct yaffs_obj_hdr);
3096         int x_size = dev->data_bytes_per_chunk - sizeof(struct yaffs_obj_hdr);
3097         char *x_buffer;
3098         int retval = 0;
3099
3100         if (obj->hdr_chunk < 1)
3101                 return -ENODATA;
3102
3103         /* If we know that the object has no xattribs then don't do all the
3104          * reading and parsing.
3105          */
3106         if (obj->xattr_known && !obj->has_xattr) {
3107                 if (name)
3108                         return -ENODATA;
3109                 else
3110                         return 0;
3111         }
3112
3113         buffer = (char *)yaffs_get_temp_buffer(dev);
3114         if (!buffer)
3115                 return -ENOMEM;
3116
3117         result =
3118             yaffs_rd_chunk_tags_nand(dev, obj->hdr_chunk, (u8 *) buffer, &tags);
3119
3120         if (result != YAFFS_OK)
3121                 retval = -ENOENT;
3122         else {
3123                 x_buffer = buffer + x_offs;
3124
3125                 if (!obj->xattr_known) {
3126                         obj->has_xattr = nval_hasvalues(x_buffer, x_size);
3127                         obj->xattr_known = 1;
3128                 }
3129
3130                 if (name)
3131                         retval = nval_get(x_buffer, x_size, name, value, size);
3132                 else
3133                         retval = nval_list(x_buffer, x_size, value, size);
3134         }
3135         yaffs_release_temp_buffer(dev, (u8 *) buffer);
3136         return retval;
3137 }
3138
3139 int yaffs_set_xattrib(struct yaffs_obj *obj, const YCHAR * name,
3140                       const void *value, int size, int flags)
3141 {
3142         return yaffs_do_xattrib_mod(obj, 1, name, value, size, flags);
3143 }
3144
3145 int yaffs_remove_xattrib(struct yaffs_obj *obj, const YCHAR * name)
3146 {
3147         return yaffs_do_xattrib_mod(obj, 0, name, NULL, 0, 0);
3148 }
3149
3150 int yaffs_get_xattrib(struct yaffs_obj *obj, const YCHAR * name, void *value,
3151                       int size)
3152 {
3153         return yaffs_do_xattrib_fetch(obj, name, value, size);
3154 }
3155
3156 int yaffs_list_xattrib(struct yaffs_obj *obj, char *buffer, int size)
3157 {
3158         return yaffs_do_xattrib_fetch(obj, NULL, buffer, size);
3159 }
3160
3161 static void yaffs_check_obj_details_loaded(struct yaffs_obj *in)
3162 {
3163         u8 *buf;
3164         struct yaffs_obj_hdr *oh;
3165         struct yaffs_dev *dev;
3166         struct yaffs_ext_tags tags;
3167         int result;
3168         int alloc_failed = 0;
3169
3170         if (!in || !in->lazy_loaded || in->hdr_chunk < 1)
3171                 return;
3172
3173         dev = in->my_dev;
3174         in->lazy_loaded = 0;
3175         buf = yaffs_get_temp_buffer(dev);
3176
3177         result = yaffs_rd_chunk_tags_nand(dev, in->hdr_chunk, buf, &tags);
3178         oh = (struct yaffs_obj_hdr *)buf;
3179
3180         in->yst_mode = oh->yst_mode;
3181         yaffs_load_attribs(in, oh);
3182         yaffs_set_obj_name_from_oh(in, oh);
3183
3184         if (in->variant_type == YAFFS_OBJECT_TYPE_SYMLINK) {
3185                 in->variant.symlink_variant.alias =
3186                     yaffs_clone_str(oh->alias);
3187                 if (!in->variant.symlink_variant.alias)
3188                         alloc_failed = 1;       /* Not returned */
3189         }
3190         yaffs_release_temp_buffer(dev, buf);
3191 }
3192
3193 static void yaffs_load_name_from_oh(struct yaffs_dev *dev, YCHAR *name,
3194                                     const YCHAR *oh_name, int buff_size)
3195 {
3196 #ifdef CONFIG_YAFFS_AUTO_UNICODE
3197         if (dev->param.auto_unicode) {
3198                 if (*oh_name) {
3199                         /* It is an ASCII name, do an ASCII to
3200                          * unicode conversion */
3201                         const char *ascii_oh_name = (const char *)oh_name;
3202                         int n = buff_size - 1;
3203                         while (n > 0 && *ascii_oh_name) {
3204                                 *name = *ascii_oh_name;
3205                                 name++;
3206                                 ascii_oh_name++;
3207                                 n--;
3208                         }
3209                 } else {
3210                         strncpy(name, oh_name + 1, buff_size - 1);
3211                 }
3212         } else {
3213 #else
3214         {
3215 #endif
3216                 strncpy(name, oh_name, buff_size - 1);
3217         }
3218 }
3219
3220 static void yaffs_load_oh_from_name(struct yaffs_dev *dev, YCHAR *oh_name,
3221                                     const YCHAR *name)
3222 {
3223 #ifdef CONFIG_YAFFS_AUTO_UNICODE
3224
3225         int is_ascii;
3226         YCHAR *w;
3227
3228         if (dev->param.auto_unicode) {
3229
3230                 is_ascii = 1;
3231                 w = name;
3232
3233                 /* Figure out if the name will fit in ascii character set */
3234                 while (is_ascii && *w) {
3235                         if ((*w) & 0xff00)
3236                                 is_ascii = 0;
3237                         w++;
3238                 }
3239
3240                 if (is_ascii) {
3241                         /* It is an ASCII name, so convert unicode to ascii */
3242                         char *ascii_oh_name = (char *)oh_name;
3243                         int n = YAFFS_MAX_NAME_LENGTH - 1;
3244                         while (n > 0 && *name) {
3245                                 *ascii_oh_name = *name;
3246                                 name++;
3247                                 ascii_oh_name++;
3248                                 n--;
3249                         }
3250                 } else {
3251                         /* Unicode name, so save starting at the second YCHAR */
3252                         *oh_name = 0;
3253                         strncpy(oh_name + 1, name, YAFFS_MAX_NAME_LENGTH - 2);
3254                 }
3255         } else {
3256 #else
3257         {
3258 #endif
3259                 strncpy(oh_name, name, YAFFS_MAX_NAME_LENGTH - 1);
3260         }
3261 }
3262
3263 /* UpdateObjectHeader updates the header on NAND for an object.
3264  * If name is not NULL, then that new name is used.
3265  */
3266 int yaffs_update_oh(struct yaffs_obj *in, const YCHAR *name, int force,
3267                     int is_shrink, int shadows, struct yaffs_xattr_mod *xmod)
3268 {
3269
3270         struct yaffs_block_info *bi;
3271         struct yaffs_dev *dev = in->my_dev;
3272         int prev_chunk_id;
3273         int ret_val = 0;
3274         int result = 0;
3275         int new_chunk_id;
3276         struct yaffs_ext_tags new_tags;
3277         struct yaffs_ext_tags old_tags;
3278         const YCHAR *alias = NULL;
3279         u8 *buffer = NULL;
3280         YCHAR old_name[YAFFS_MAX_NAME_LENGTH + 1];
3281         struct yaffs_obj_hdr *oh = NULL;
3282
3283         strcpy(old_name, _Y("silly old name"));
3284
3285         if (in->fake && in != dev->root_dir && !force && !xmod)
3286                 return ret_val;
3287
3288         yaffs_check_gc(dev, 0);
3289         yaffs_check_obj_details_loaded(in);
3290
3291         buffer = yaffs_get_temp_buffer(in->my_dev);
3292         oh = (struct yaffs_obj_hdr *)buffer;
3293
3294         prev_chunk_id = in->hdr_chunk;
3295
3296         if (prev_chunk_id > 0) {
3297                 result = yaffs_rd_chunk_tags_nand(dev, prev_chunk_id,
3298                                                   buffer, &old_tags);
3299
3300                 yaffs_verify_oh(in, oh, &old_tags, 0);
3301                 memcpy(old_name, oh->name, sizeof(oh->name));
3302                 memset(buffer, 0xff, sizeof(struct yaffs_obj_hdr));
3303         } else {
3304                 memset(buffer, 0xff, dev->data_bytes_per_chunk);
3305         }
3306
3307         oh->type = in->variant_type;
3308         oh->yst_mode = in->yst_mode;
3309         oh->shadows_obj = oh->inband_shadowed_obj_id = shadows;
3310
3311         yaffs_load_attribs_oh(oh, in);
3312
3313         if (in->parent)
3314                 oh->parent_obj_id = in->parent->obj_id;
3315         else
3316                 oh->parent_obj_id = 0;
3317
3318         if (name && *name) {
3319                 memset(oh->name, 0, sizeof(oh->name));
3320                 yaffs_load_oh_from_name(dev, oh->name, name);
3321         } else if (prev_chunk_id > 0) {
3322                 memcpy(oh->name, old_name, sizeof(oh->name));
3323         } else {
3324                 memset(oh->name, 0, sizeof(oh->name));
3325         }
3326
3327         oh->is_shrink = is_shrink;
3328
3329         switch (in->variant_type) {
3330         case YAFFS_OBJECT_TYPE_UNKNOWN:
3331                 /* Should not happen */
3332                 break;
3333         case YAFFS_OBJECT_TYPE_FILE:
3334                 oh->file_size =
3335                     (oh->parent_obj_id == YAFFS_OBJECTID_DELETED ||
3336                      oh->parent_obj_id == YAFFS_OBJECTID_UNLINKED) ?
3337                      0 : in->variant.file_variant.file_size;
3338                 break;
3339         case YAFFS_OBJECT_TYPE_HARDLINK:
3340                 oh->equiv_id = in->variant.hardlink_variant.equiv_id;
3341                 break;
3342         case YAFFS_OBJECT_TYPE_SPECIAL:
3343                 /* Do nothing */
3344                 break;
3345         case YAFFS_OBJECT_TYPE_DIRECTORY:
3346                 /* Do nothing */
3347                 break;
3348         case YAFFS_OBJECT_TYPE_SYMLINK:
3349                 alias = in->variant.symlink_variant.alias;
3350                 if (!alias)
3351                         alias = _Y("no alias");
3352                 strncpy(oh->alias, alias, YAFFS_MAX_ALIAS_LENGTH);
3353                 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3354                 break;
3355         }
3356
3357         /* process any xattrib modifications */
3358         if (xmod)
3359                 yaffs_apply_xattrib_mod(in, (char *)buffer, xmod);
3360
3361         /* Tags */
3362         memset(&new_tags, 0, sizeof(new_tags));
3363         in->serial++;
3364         new_tags.chunk_id = 0;
3365         new_tags.obj_id = in->obj_id;
3366         new_tags.serial_number = in->serial;
3367
3368         /* Add extra info for file header */
3369         new_tags.extra_available = 1;
3370         new_tags.extra_parent_id = oh->parent_obj_id;
3371         new_tags.extra_length = oh->file_size;
3372         new_tags.extra_is_shrink = oh->is_shrink;
3373         new_tags.extra_equiv_id = oh->equiv_id;
3374         new_tags.extra_shadows = (oh->shadows_obj > 0) ? 1 : 0;
3375         new_tags.extra_obj_type = in->variant_type;
3376         yaffs_verify_oh(in, oh, &new_tags, 1);
3377
3378         /* Create new chunk in NAND */
3379         new_chunk_id =
3380             yaffs_write_new_chunk(dev, buffer, &new_tags,
3381                                   (prev_chunk_id > 0) ? 1 : 0);
3382
3383         if (buffer)
3384                 yaffs_release_temp_buffer(dev, buffer);
3385
3386         if (new_chunk_id < 0)
3387                 return new_chunk_id;
3388
3389         in->hdr_chunk = new_chunk_id;
3390
3391         if (prev_chunk_id > 0)
3392                 yaffs_chunk_del(dev, prev_chunk_id, 1, __LINE__);
3393
3394         if (!yaffs_obj_cache_dirty(in))
3395                 in->dirty = 0;
3396
3397         /* If this was a shrink, then mark the block
3398          * that the chunk lives on */
3399         if (is_shrink) {
3400                 bi = yaffs_get_block_info(in->my_dev,
3401                                           new_chunk_id /
3402                                           in->my_dev->param.chunks_per_block);
3403                 bi->has_shrink_hdr = 1;
3404         }
3405
3406
3407         return new_chunk_id;
3408 }
3409
3410 /*--------------------- File read/write ------------------------
3411  * Read and write have very similar structures.
3412  * In general the read/write has three parts to it
3413  * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3414  * Some complete chunks
3415  * An incomplete chunk to end off with
3416  *
3417  * Curve-balls: the first chunk might also be the last chunk.
3418  */
3419
3420 int yaffs_file_rd(struct yaffs_obj *in, u8 * buffer, loff_t offset, int n_bytes)
3421 {
3422         int chunk;
3423         u32 start;
3424         int n_copy;
3425         int n = n_bytes;
3426         int n_done = 0;
3427         struct yaffs_cache *cache;
3428         struct yaffs_dev *dev;
3429
3430         dev = in->my_dev;
3431
3432         while (n > 0) {
3433                 yaffs_addr_to_chunk(dev, offset, &chunk, &start);
3434                 chunk++;
3435
3436                 /* OK now check for the curveball where the start and end are in
3437                  * the same chunk.
3438                  */
3439                 if ((start + n) < dev->data_bytes_per_chunk)
3440                         n_copy = n;
3441                 else
3442                         n_copy = dev->data_bytes_per_chunk - start;
3443
3444                 cache = yaffs_find_chunk_cache(in, chunk);
3445
3446                 /* If the chunk is already in the cache or it is less than
3447                  * a whole chunk or we're using inband tags then use the cache
3448                  * (if there is caching) else bypass the cache.
3449                  */
3450                 if (cache || n_copy != dev->data_bytes_per_chunk ||
3451                     dev->param.inband_tags) {
3452                         if (dev->param.n_caches > 0) {
3453
3454                                 /* If we can't find the data in the cache,
3455                                  * then load it up. */
3456
3457                                 if (!cache) {
3458                                         cache =
3459                                             yaffs_grab_chunk_cache(in->my_dev);
3460                                         cache->object = in;
3461                                         cache->chunk_id = chunk;
3462                                         cache->dirty = 0;
3463                                         cache->locked = 0;
3464                                         yaffs_rd_data_obj(in, chunk,
3465                                                           cache->data);
3466                                         cache->n_bytes = 0;
3467                                 }
3468
3469                                 yaffs_use_cache(dev, cache, 0);
3470
3471                                 cache->locked = 1;
3472
3473                                 memcpy(buffer, &cache->data[start], n_copy);
3474
3475                                 cache->locked = 0;
3476                         } else {
3477                                 /* Read into the local buffer then copy.. */
3478
3479                                 u8 *local_buffer =
3480                                     yaffs_get_temp_buffer(dev);
3481                                 yaffs_rd_data_obj(in, chunk, local_buffer);
3482
3483                                 memcpy(buffer, &local_buffer[start], n_copy);
3484
3485                                 yaffs_release_temp_buffer(dev, local_buffer);
3486                         }
3487                 } else {
3488                         /* A full chunk. Read directly into the buffer. */
3489                         yaffs_rd_data_obj(in, chunk, buffer);
3490                 }
3491                 n -= n_copy;
3492                 offset += n_copy;
3493                 buffer += n_copy;
3494                 n_done += n_copy;
3495         }
3496         return n_done;
3497 }
3498
3499 int yaffs_do_file_wr(struct yaffs_obj *in, const u8 *buffer, loff_t offset,
3500                      int n_bytes, int write_trhrough)
3501 {
3502
3503         int chunk;
3504         u32 start;
3505         int n_copy;
3506         int n = n_bytes;
3507         int n_done = 0;
3508         int n_writeback;
3509         int start_write = offset;
3510         int chunk_written = 0;
3511         u32 n_bytes_read;
3512         u32 chunk_start;
3513         struct yaffs_dev *dev;
3514
3515         dev = in->my_dev;
3516
3517         while (n > 0 && chunk_written >= 0) {
3518                 yaffs_addr_to_chunk(dev, offset, &chunk, &start);
3519
3520                 if (chunk * dev->data_bytes_per_chunk + start != offset ||
3521                     start >= dev->data_bytes_per_chunk) {
3522                         yaffs_trace(YAFFS_TRACE_ERROR,
3523                                 "AddrToChunk of offset %d gives chunk %d start %d",
3524                                 (int)offset, chunk, start);
3525                 }
3526                 chunk++;        /* File pos to chunk in file offset */
3527
3528                 /* OK now check for the curveball where the start and end are in
3529                  * the same chunk.
3530                  */
3531
3532                 if ((start + n) < dev->data_bytes_per_chunk) {
3533                         n_copy = n;
3534
3535                         /* Now calculate how many bytes to write back....
3536                          * If we're overwriting and not writing to then end of
3537                          * file then we need to write back as much as was there
3538                          * before.
3539                          */
3540
3541                         chunk_start = ((chunk - 1) * dev->data_bytes_per_chunk);
3542
3543                         if (chunk_start > in->variant.file_variant.file_size)
3544                                 n_bytes_read = 0;       /* Past end of file */
3545                         else
3546                                 n_bytes_read =
3547                                     in->variant.file_variant.file_size -
3548                                     chunk_start;
3549
3550                         if (n_bytes_read > dev->data_bytes_per_chunk)
3551                                 n_bytes_read = dev->data_bytes_per_chunk;
3552
3553                         n_writeback =
3554                             (n_bytes_read >
3555                              (start + n)) ? n_bytes_read : (start + n);
3556
3557                         if (n_writeback < 0 ||
3558                             n_writeback > dev->data_bytes_per_chunk)
3559                                 BUG();
3560
3561                 } else {
3562                         n_copy = dev->data_bytes_per_chunk - start;
3563                         n_writeback = dev->data_bytes_per_chunk;
3564                 }
3565
3566                 if (n_copy != dev->data_bytes_per_chunk ||
3567                     dev->param.inband_tags) {
3568                         /* An incomplete start or end chunk (or maybe both
3569                          * start and end chunk), or we're using inband tags,
3570                          * so we want to use the cache buffers.
3571                          */
3572                         if (dev->param.n_caches > 0) {
3573                                 struct yaffs_cache *cache;
3574
3575                                 /* If we can't find the data in the cache, then
3576                                  * load the cache */
3577                                 cache = yaffs_find_chunk_cache(in, chunk);
3578
3579                                 if (!cache &&
3580                                     yaffs_check_alloc_available(dev, 1)) {
3581                                         cache = yaffs_grab_chunk_cache(dev);
3582                                         cache->object = in;
3583                                         cache->chunk_id = chunk;
3584                                         cache->dirty = 0;
3585                                         cache->locked = 0;
3586                                         yaffs_rd_data_obj(in, chunk,
3587                                                           cache->data);
3588                                 } else if (cache &&
3589                                            !cache->dirty &&
3590                                            !yaffs_check_alloc_available(dev,
3591                                                                         1)) {
3592                                         /* Drop the cache if it was a read cache
3593                                          * item and no space check has been made
3594                                          * for it.
3595                                          */
3596                                         cache = NULL;
3597                                 }
3598
3599                                 if (cache) {
3600                                         yaffs_use_cache(dev, cache, 1);
3601                                         cache->locked = 1;
3602
3603                                         memcpy(&cache->data[start], buffer,
3604                                                n_copy);
3605
3606                                         cache->locked = 0;
3607                                         cache->n_bytes = n_writeback;
3608
3609                                         if (write_trhrough) {
3610                                                 chunk_written =
3611                                                     yaffs_wr_data_obj
3612                                                     (cache->object,
3613                                                      cache->chunk_id,
3614                                                      cache->data,
3615                                                      cache->n_bytes, 1);
3616                                                 cache->dirty = 0;
3617                                         }
3618                                 } else {
3619                                         chunk_written = -1;     /* fail write */
3620                                 }
3621                         } else {
3622                                 /* An incomplete start or end chunk (or maybe
3623                                  * both start and end chunk). Read into the
3624                                  * local buffer then copy over and write back.
3625                                  */
3626
3627                                 u8 *local_buffer = yaffs_get_temp_buffer(dev);
3628
3629                                 yaffs_rd_data_obj(in, chunk, local_buffer);
3630                                 memcpy(&local_buffer[start], buffer, n_copy);
3631
3632                                 chunk_written =
3633                                     yaffs_wr_data_obj(in, chunk,
3634                                                       local_buffer,
3635                                                       n_writeback, 0);
3636
3637                                 yaffs_release_temp_buffer(dev, local_buffer);
3638                         }
3639                 } else {
3640                         /* A full chunk. Write directly from the buffer. */
3641
3642                         chunk_written =
3643                             yaffs_wr_data_obj(in, chunk, buffer,
3644                                               dev->data_bytes_per_chunk, 0);
3645
3646                         /* Since we've overwritten the cached data,
3647                          * we better invalidate it. */
3648                         yaffs_invalidate_chunk_cache(in, chunk);
3649                 }
3650
3651                 if (chunk_written >= 0) {
3652                         n -= n_copy;
3653                         offset += n_copy;
3654                         buffer += n_copy;
3655                         n_done += n_copy;
3656                 }
3657         }
3658
3659         /* Update file object */
3660
3661         if ((start_write + n_done) > in->variant.file_variant.file_size)
3662                 in->variant.file_variant.file_size = (start_write + n_done);
3663
3664         in->dirty = 1;
3665         return n_done;
3666 }
3667
3668 int yaffs_wr_file(struct yaffs_obj *in, const u8 *buffer, loff_t offset,
3669                   int n_bytes, int write_trhrough)
3670 {
3671         yaffs2_handle_hole(in, offset);
3672         return yaffs_do_file_wr(in, buffer, offset, n_bytes, write_trhrough);
3673 }
3674
3675 /* ---------------------- File resizing stuff ------------------ */
3676
3677 static void yaffs_prune_chunks(struct yaffs_obj *in, int new_size)
3678 {
3679
3680         struct yaffs_dev *dev = in->my_dev;
3681         int old_size = in->variant.file_variant.file_size;
3682         int i;
3683         int chunk_id;
3684         int last_del = 1 + (old_size - 1) / dev->data_bytes_per_chunk;
3685         int start_del = 1 + (new_size + dev->data_bytes_per_chunk - 1) /
3686             dev->data_bytes_per_chunk;
3687
3688
3689         /* Delete backwards so that we don't end up with holes if
3690          * power is lost part-way through the operation.
3691          */
3692         for (i = last_del; i >= start_del; i--) {
3693                 /* NB this could be optimised somewhat,
3694                  * eg. could retrieve the tags and write them without
3695                  * using yaffs_chunk_del
3696                  */
3697
3698                 chunk_id = yaffs_find_del_file_chunk(in, i, NULL);
3699
3700                 if (chunk_id < 1)
3701                         continue;
3702
3703                 if (chunk_id <
3704                     (dev->internal_start_block * dev->param.chunks_per_block) ||
3705                     chunk_id >=
3706                     ((dev->internal_end_block + 1) *
3707                       dev->param.chunks_per_block)) {
3708                         yaffs_trace(YAFFS_TRACE_ALWAYS,
3709                                 "Found daft chunk_id %d for %d",
3710                                 chunk_id, i);
3711                 } else {
3712                         in->n_data_chunks--;
3713                         yaffs_chunk_del(dev, chunk_id, 1, __LINE__);
3714                 }
3715         }
3716 }
3717
3718 void yaffs_resize_file_down(struct yaffs_obj *obj, loff_t new_size)
3719 {
3720         int new_full;
3721         u32 new_partial;
3722         struct yaffs_dev *dev = obj->my_dev;
3723
3724         yaffs_addr_to_chunk(dev, new_size, &new_full, &new_partial);
3725
3726         yaffs_prune_chunks(obj, new_size);
3727
3728         if (new_partial != 0) {
3729                 int last_chunk = 1 + new_full;
3730                 u8 *local_buffer = yaffs_get_temp_buffer(dev);
3731
3732                 /* Rewrite the last chunk with its new size and zero pad */
3733                 yaffs_rd_data_obj(obj, last_chunk, local_buffer);
3734                 memset(local_buffer + new_partial, 0,
3735                        dev->data_bytes_per_chunk - new_partial);
3736
3737                 yaffs_wr_data_obj(obj, last_chunk, local_buffer,
3738                                   new_partial, 1);
3739
3740                 yaffs_release_temp_buffer(dev, local_buffer);
3741         }
3742
3743         obj->variant.file_variant.file_size = new_size;
3744
3745         yaffs_prune_tree(dev, &obj->variant.file_variant);
3746 }
3747
3748 int yaffs_resize_file(struct yaffs_obj *in, loff_t new_size)
3749 {
3750         struct yaffs_dev *dev = in->my_dev;
3751         int old_size = in->variant.file_variant.file_size;
3752
3753         yaffs_flush_file_cache(in);
3754         yaffs_invalidate_whole_cache(in);
3755
3756         yaffs_check_gc(dev, 0);
3757
3758         if (in->variant_type != YAFFS_OBJECT_TYPE_FILE)
3759                 return YAFFS_FAIL;
3760
3761         if (new_size == old_size)
3762                 return YAFFS_OK;
3763
3764         if (new_size > old_size) {
3765                 yaffs2_handle_hole(in, new_size);
3766                 in->variant.file_variant.file_size = new_size;
3767         } else {
3768                 /* new_size < old_size */
3769                 yaffs_resize_file_down(in, new_size);
3770         }
3771
3772         /* Write a new object header to reflect the resize.
3773          * show we've shrunk the file, if need be
3774          * Do this only if the file is not in the deleted directories
3775          * and is not shadowed.
3776          */
3777         if (in->parent &&
3778             !in->is_shadowed &&
3779             in->parent->obj_id != YAFFS_OBJECTID_UNLINKED &&
3780             in->parent->obj_id != YAFFS_OBJECTID_DELETED)
3781                 yaffs_update_oh(in, NULL, 0, 0, 0, NULL);
3782
3783         return YAFFS_OK;
3784 }
3785
3786 int yaffs_flush_file(struct yaffs_obj *in, int update_time, int data_sync)
3787 {
3788         if (!in->dirty)
3789                 return YAFFS_OK;
3790
3791         yaffs_flush_file_cache(in);
3792
3793         if (data_sync)
3794                 return YAFFS_OK;
3795
3796         if (update_time)
3797                 yaffs_load_current_time(in, 0, 0);
3798
3799         return (yaffs_update_oh(in, NULL, 0, 0, 0, NULL) >= 0) ?
3800                                 YAFFS_OK : YAFFS_FAIL;
3801 }
3802
3803
3804 /* yaffs_del_file deletes the whole file data
3805  * and the inode associated with the file.
3806  * It does not delete the links associated with the file.
3807  */
3808 static int yaffs_unlink_file_if_needed(struct yaffs_obj *in)
3809 {
3810         int ret_val;
3811         int del_now = 0;
3812         struct yaffs_dev *dev = in->my_dev;
3813
3814         if (!in->my_inode)
3815                 del_now = 1;
3816
3817         if (del_now) {
3818                 ret_val =
3819                     yaffs_change_obj_name(in, in->my_dev->del_dir,
3820                                           _Y("deleted"), 0, 0);
3821                 yaffs_trace(YAFFS_TRACE_TRACING,
3822                         "yaffs: immediate deletion of file %d",
3823                         in->obj_id);
3824                 in->deleted = 1;
3825                 in->my_dev->n_deleted_files++;
3826                 if (dev->param.disable_soft_del || dev->param.is_yaffs2)
3827                         yaffs_resize_file(in, 0);
3828                 yaffs_soft_del_file(in);
3829         } else {
3830                 ret_val =
3831                     yaffs_change_obj_name(in, in->my_dev->unlinked_dir,
3832                                           _Y("unlinked"), 0, 0);
3833         }
3834         return ret_val;
3835 }
3836
3837 int yaffs_del_file(struct yaffs_obj *in)
3838 {
3839         int ret_val = YAFFS_OK;
3840         int deleted;    /* Need to cache value on stack if in is freed */
3841         struct yaffs_dev *dev = in->my_dev;
3842
3843         if (dev->param.disable_soft_del || dev->param.is_yaffs2)
3844                 yaffs_resize_file(in, 0);
3845
3846         if (in->n_data_chunks > 0) {
3847                 /* Use soft deletion if there is data in the file.
3848                  * That won't be the case if it has been resized to zero.
3849                  */
3850                 if (!in->unlinked)
3851                         ret_val = yaffs_unlink_file_if_needed(in);
3852
3853                 deleted = in->deleted;
3854
3855                 if (ret_val == YAFFS_OK && in->unlinked && !in->deleted) {
3856                         in->deleted = 1;
3857                         deleted = 1;
3858                         in->my_dev->n_deleted_files++;
3859                         yaffs_soft_del_file(in);
3860                 }
3861                 return deleted ? YAFFS_OK : YAFFS_FAIL;
3862         } else {
3863                 /* The file has no data chunks so we toss it immediately */
3864                 yaffs_free_tnode(in->my_dev, in->variant.file_variant.top);
3865                 in->variant.file_variant.top = NULL;
3866                 yaffs_generic_obj_del(in);
3867
3868                 return YAFFS_OK;
3869         }
3870 }
3871
3872 int yaffs_is_non_empty_dir(struct yaffs_obj *obj)
3873 {
3874         return (obj &&
3875                 obj->variant_type == YAFFS_OBJECT_TYPE_DIRECTORY) &&
3876                 !(list_empty(&obj->variant.dir_variant.children));
3877 }
3878
3879 static int yaffs_del_dir(struct yaffs_obj *obj)
3880 {
3881         /* First check that the directory is empty. */
3882         if (yaffs_is_non_empty_dir(obj))
3883                 return YAFFS_FAIL;
3884
3885         return yaffs_generic_obj_del(obj);
3886 }
3887
3888 static int yaffs_del_symlink(struct yaffs_obj *in)
3889 {
3890         kfree(in->variant.symlink_variant.alias);
3891         in->variant.symlink_variant.alias = NULL;
3892
3893         return yaffs_generic_obj_del(in);
3894 }
3895
3896 static int yaffs_del_link(struct yaffs_obj *in)
3897 {
3898         /* remove this hardlink from the list associated with the equivalent
3899          * object
3900          */
3901         list_del_init(&in->hard_links);
3902         return yaffs_generic_obj_del(in);
3903 }
3904
3905 int yaffs_del_obj(struct yaffs_obj *obj)
3906 {
3907         int ret_val = -1;
3908
3909         switch (obj->variant_type) {
3910         case YAFFS_OBJECT_TYPE_FILE:
3911                 ret_val = yaffs_del_file(obj);
3912                 break;
3913         case YAFFS_OBJECT_TYPE_DIRECTORY:
3914                 if (!list_empty(&obj->variant.dir_variant.dirty)) {
3915                         yaffs_trace(YAFFS_TRACE_BACKGROUND,
3916                                 "Remove object %d from dirty directories",
3917                                 obj->obj_id);
3918                         list_del_init(&obj->variant.dir_variant.dirty);
3919                 }
3920                 return yaffs_del_dir(obj);
3921                 break;
3922         case YAFFS_OBJECT_TYPE_SYMLINK:
3923                 ret_val = yaffs_del_symlink(obj);
3924                 break;
3925         case YAFFS_OBJECT_TYPE_HARDLINK:
3926                 ret_val = yaffs_del_link(obj);
3927                 break;
3928         case YAFFS_OBJECT_TYPE_SPECIAL:
3929                 ret_val = yaffs_generic_obj_del(obj);
3930                 break;
3931         case YAFFS_OBJECT_TYPE_UNKNOWN:
3932                 ret_val = 0;
3933                 break;          /* should not happen. */
3934         }
3935         return ret_val;
3936 }
3937
3938 static int yaffs_unlink_worker(struct yaffs_obj *obj)
3939 {
3940         int del_now = 0;
3941
3942         if (!obj)
3943                 return YAFFS_FAIL;
3944
3945         if (!obj->my_inode)
3946                 del_now = 1;
3947
3948         yaffs_update_parent(obj->parent);
3949
3950         if (obj->variant_type == YAFFS_OBJECT_TYPE_HARDLINK) {
3951                 return yaffs_del_link(obj);
3952         } else if (!list_empty(&obj->hard_links)) {
3953                 /* Curve ball: We're unlinking an object that has a hardlink.
3954                  *
3955                  * This problem arises because we are not strictly following