yaffs: More mainlining cleanup
[yaffs2.git] / yaffs_guts.c
1 /*
2  * YAFFS: Yet Another Flash File System. A NAND-flash specific file system.
3  *
4  * Copyright (C) 2002-2011 Aleph One Ltd.
5  *   for Toby Churchill Ltd and Brightstar Engineering
6  *
7  * Created by Charles Manning <charles@aleph1.co.uk>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License version 2 as
11  * published by the Free Software Foundation.
12  */
13
14 #include "yportenv.h"
15 #include "yaffs_trace.h"
16
17 #include "yaffs_guts.h"
18 #include "yaffs_getblockinfo.h"
19 #include "yaffs_tagscompat.h"
20 #include "yaffs_nand.h"
21 #include "yaffs_yaffs1.h"
22 #include "yaffs_yaffs2.h"
23 #include "yaffs_bitmap.h"
24 #include "yaffs_verify.h"
25 #include "yaffs_nand.h"
26 #include "yaffs_packedtags2.h"
27 #include "yaffs_nameval.h"
28 #include "yaffs_allocator.h"
29 #include "yaffs_attribs.h"
30
31 /* Note YAFFS_GC_GOOD_ENOUGH must be <= YAFFS_GC_PASSIVE_THRESHOLD */
32 #define YAFFS_GC_GOOD_ENOUGH 2
33 #define YAFFS_GC_PASSIVE_THRESHOLD 4
34
35 #include "yaffs_ecc.h"
36
37 /* Forward declarations */
38
39 static int yaffs_wr_data_obj(struct yaffs_obj *in, int inode_chunk,
40                              const u8 *buffer, int n_bytes, int use_reserve);
41
42
43
44 /* Function to calculate chunk and offset */
45
46 static inline void yaffs_addr_to_chunk(struct yaffs_dev *dev, loff_t addr,
47                                         int *chunk_out, u32 *offset_out)
48 {
49         int chunk;
50         u32 offset;
51
52         chunk = (u32) (addr >> dev->chunk_shift);
53
54         if (dev->chunk_div == 1) {
55                 /* easy power of 2 case */
56                 offset = (u32) (addr & dev->chunk_mask);
57         } else {
58                 /* Non power-of-2 case */
59
60                 loff_t chunk_base;
61
62                 chunk /= dev->chunk_div;
63
64                 chunk_base = ((loff_t) chunk) * dev->data_bytes_per_chunk;
65                 offset = (u32) (addr - chunk_base);
66         }
67
68         *chunk_out = chunk;
69         *offset_out = offset;
70 }
71
72 /* Function to return the number of shifts for a power of 2 greater than or
73  * equal to the given number
74  * Note we don't try to cater for all possible numbers and this does not have to
75  * be hellishly efficient.
76  */
77
78 static inline u32 calc_shifts_ceiling(u32 x)
79 {
80         int extra_bits;
81         int shifts;
82
83         shifts = extra_bits = 0;
84
85         while (x > 1) {
86                 if (x & 1)
87                         extra_bits++;
88                 x >>= 1;
89                 shifts++;
90         }
91
92         if (extra_bits)
93                 shifts++;
94
95         return shifts;
96 }
97
98 /* Function to return the number of shifts to get a 1 in bit 0
99  */
100
101 static inline u32 calc_shifts(u32 x)
102 {
103         u32 shifts;
104
105         shifts = 0;
106
107         if (!x)
108                 return 0;
109
110         while (!(x & 1)) {
111                 x >>= 1;
112                 shifts++;
113         }
114
115         return shifts;
116 }
117
118 /*
119  * Temporary buffer manipulations.
120  */
121
122 static int yaffs_init_tmp_buffers(struct yaffs_dev *dev)
123 {
124         int i;
125         u8 *buf = (u8 *) 1;
126
127         memset(dev->temp_buffer, 0, sizeof(dev->temp_buffer));
128
129         for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
130                 dev->temp_buffer[i].in_use = 0;
131                 buf = kmalloc(dev->param.total_bytes_per_chunk, GFP_NOFS);
132                 dev->temp_buffer[i].buffer = buf;
133         }
134
135         return buf ? YAFFS_OK : YAFFS_FAIL;
136 }
137
138 u8 *yaffs_get_temp_buffer(struct yaffs_dev * dev)
139 {
140         int i;
141
142         dev->temp_in_use++;
143         if (dev->temp_in_use > dev->max_temp)
144                 dev->max_temp = dev->temp_in_use;
145
146         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
147                 if (dev->temp_buffer[i].in_use == 0) {
148                         dev->temp_buffer[i].in_use = 1;
149                         return dev->temp_buffer[i].buffer;
150                 }
151         }
152
153         yaffs_trace(YAFFS_TRACE_BUFFERS, "Out of temp buffers");
154         /*
155          * If we got here then we have to allocate an unmanaged one
156          * This is not good.
157          */
158
159         dev->unmanaged_buffer_allocs++;
160         return kmalloc(dev->data_bytes_per_chunk, GFP_NOFS);
161
162 }
163
164 void yaffs_release_temp_buffer(struct yaffs_dev *dev, u8 *buffer)
165 {
166         int i;
167
168         dev->temp_in_use--;
169
170         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
171                 if (dev->temp_buffer[i].buffer == buffer) {
172                         dev->temp_buffer[i].in_use = 0;
173                         return;
174                 }
175         }
176
177         if (buffer) {
178                 /* assume it is an unmanaged one. */
179                 yaffs_trace(YAFFS_TRACE_BUFFERS, "Releasing unmanaged temp buffer");
180                 kfree(buffer);
181                 dev->unmanaged_buffer_deallocs++;
182         }
183
184 }
185
186 /*
187  * Determine if we have a managed buffer.
188  */
189 int yaffs_is_managed_tmp_buffer(struct yaffs_dev *dev, const u8 *buffer)
190 {
191         int i;
192
193         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
194                 if (dev->temp_buffer[i].buffer == buffer)
195                         return 1;
196         }
197
198         for (i = 0; i < dev->param.n_caches; i++) {
199                 if (dev->cache[i].data == buffer)
200                         return 1;
201         }
202
203         if (buffer == dev->checkpt_buffer)
204                 return 1;
205
206         yaffs_trace(YAFFS_TRACE_ALWAYS,
207           "yaffs: unmaged buffer detected.");
208         return 0;
209 }
210
211 /*
212  * Functions for robustisizing TODO
213  *
214  */
215
216 static void yaffs_handle_chunk_wr_ok(struct yaffs_dev *dev, int nand_chunk,
217                                      const u8 *data,
218                                      const struct yaffs_ext_tags *tags)
219 {
220         dev = dev;
221         nand_chunk = nand_chunk;
222         data = data;
223         tags = tags;
224 }
225
226 static void yaffs_handle_chunk_update(struct yaffs_dev *dev, int nand_chunk,
227                                       const struct yaffs_ext_tags *tags)
228 {
229         dev = dev;
230         nand_chunk = nand_chunk;
231         tags = tags;
232 }
233
234 void yaffs_handle_chunk_error(struct yaffs_dev *dev,
235                               struct yaffs_block_info *bi)
236 {
237         if (!bi->gc_prioritise) {
238                 bi->gc_prioritise = 1;
239                 dev->has_pending_prioritised_gc = 1;
240                 bi->chunk_error_strikes++;
241
242                 if (bi->chunk_error_strikes > 3) {
243                         bi->needs_retiring = 1; /* Too many stikes, so retire */
244                         yaffs_trace(YAFFS_TRACE_ALWAYS,
245                                 "yaffs: Block struck out");
246
247                 }
248         }
249 }
250
251 static void yaffs_handle_chunk_wr_error(struct yaffs_dev *dev, int nand_chunk,
252                                         int erased_ok)
253 {
254         int flash_block = nand_chunk / dev->param.chunks_per_block;
255         struct yaffs_block_info *bi = yaffs_get_block_info(dev, flash_block);
256
257         yaffs_handle_chunk_error(dev, bi);
258
259         if (erased_ok) {
260                 /* Was an actual write failure,
261                  * so mark the block for retirement.*/
262                 bi->needs_retiring = 1;
263                 yaffs_trace(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
264                   "**>> Block %d needs retiring", flash_block);
265         }
266
267         /* Delete the chunk */
268         yaffs_chunk_del(dev, nand_chunk, 1, __LINE__);
269         yaffs_skip_rest_of_block(dev);
270 }
271
272 /*
273  * Verification code
274  */
275
276 /*
277  *  Simple hash function. Needs to have a reasonable spread
278  */
279
280 static inline int yaffs_hash_fn(int n)
281 {
282         n = abs(n);
283         return n % YAFFS_NOBJECT_BUCKETS;
284 }
285
286 /*
287  * Access functions to useful fake objects.
288  * Note that root might have a presence in NAND if permissions are set.
289  */
290
291 struct yaffs_obj *yaffs_root(struct yaffs_dev *dev)
292 {
293         return dev->root_dir;
294 }
295
296 struct yaffs_obj *yaffs_lost_n_found(struct yaffs_dev *dev)
297 {
298         return dev->lost_n_found;
299 }
300
301 /*
302  *  Erased NAND checking functions
303  */
304
305 int yaffs_check_ff(u8 *buffer, int n_bytes)
306 {
307         /* Horrible, slow implementation */
308         while (n_bytes--) {
309                 if (*buffer != 0xff)
310                         return 0;
311                 buffer++;
312         }
313         return 1;
314 }
315
316 static int yaffs_check_chunk_erased(struct yaffs_dev *dev, int nand_chunk)
317 {
318         int retval = YAFFS_OK;
319         u8 *data = yaffs_get_temp_buffer(dev);
320         struct yaffs_ext_tags tags;
321         int result;
322
323         result = yaffs_rd_chunk_tags_nand(dev, nand_chunk, data, &tags);
324
325         if (tags.ecc_result > YAFFS_ECC_RESULT_NO_ERROR)
326                 retval = YAFFS_FAIL;
327
328         if (!yaffs_check_ff(data, dev->data_bytes_per_chunk) ||
329                 tags.chunk_used) {
330                 yaffs_trace(YAFFS_TRACE_NANDACCESS,
331                         "Chunk %d not erased", nand_chunk);
332                 retval = YAFFS_FAIL;
333         }
334
335         yaffs_release_temp_buffer(dev, data);
336
337         return retval;
338
339 }
340
341 static int yaffs_verify_chunk_written(struct yaffs_dev *dev,
342                                       int nand_chunk,
343                                       const u8 *data,
344                                       struct yaffs_ext_tags *tags)
345 {
346         int retval = YAFFS_OK;
347         struct yaffs_ext_tags temp_tags;
348         u8 *buffer = yaffs_get_temp_buffer(dev);
349         int result;
350
351         result = yaffs_rd_chunk_tags_nand(dev, nand_chunk, buffer, &temp_tags);
352         if (memcmp(buffer, data, dev->data_bytes_per_chunk) ||
353             temp_tags.obj_id != tags->obj_id ||
354             temp_tags.chunk_id != tags->chunk_id ||
355             temp_tags.n_bytes != tags->n_bytes)
356                 retval = YAFFS_FAIL;
357
358         yaffs_release_temp_buffer(dev, buffer);
359
360         return retval;
361 }
362
363
364 int yaffs_check_alloc_available(struct yaffs_dev *dev, int n_chunks)
365 {
366         int reserved_chunks;
367         int reserved_blocks = dev->param.n_reserved_blocks;
368         int checkpt_blocks;
369
370         checkpt_blocks = yaffs_calc_checkpt_blocks_required(dev);
371
372         reserved_chunks =
373             (reserved_blocks + checkpt_blocks) * dev->param.chunks_per_block;
374
375         return (dev->n_free_chunks > (reserved_chunks + n_chunks));
376 }
377
378 static int yaffs_find_alloc_block(struct yaffs_dev *dev)
379 {
380         int i;
381         struct yaffs_block_info *bi;
382
383         if (dev->n_erased_blocks < 1) {
384                 /* Hoosterman we've got a problem.
385                  * Can't get space to gc
386                  */
387                 yaffs_trace(YAFFS_TRACE_ERROR,
388                   "yaffs tragedy: no more erased blocks");
389
390                 return -1;
391         }
392
393         /* Find an empty block. */
394
395         for (i = dev->internal_start_block; i <= dev->internal_end_block; i++) {
396                 dev->alloc_block_finder++;
397                 if (dev->alloc_block_finder < dev->internal_start_block
398                     || dev->alloc_block_finder > dev->internal_end_block) {
399                         dev->alloc_block_finder = dev->internal_start_block;
400                 }
401
402                 bi = yaffs_get_block_info(dev, dev->alloc_block_finder);
403
404                 if (bi->block_state == YAFFS_BLOCK_STATE_EMPTY) {
405                         bi->block_state = YAFFS_BLOCK_STATE_ALLOCATING;
406                         dev->seq_number++;
407                         bi->seq_number = dev->seq_number;
408                         dev->n_erased_blocks--;
409                         yaffs_trace(YAFFS_TRACE_ALLOCATE,
410                           "Allocated block %d, seq  %d, %d left" ,
411                            dev->alloc_block_finder, dev->seq_number,
412                            dev->n_erased_blocks);
413                         return dev->alloc_block_finder;
414                 }
415         }
416
417         yaffs_trace(YAFFS_TRACE_ALWAYS,
418                 "yaffs tragedy: no more erased blocks, but there should have been %d",
419                 dev->n_erased_blocks);
420
421         return -1;
422 }
423
424 static int yaffs_alloc_chunk(struct yaffs_dev *dev, int use_reserver,
425                              struct yaffs_block_info **block_ptr)
426 {
427         int ret_val;
428         struct yaffs_block_info *bi;
429
430         if (dev->alloc_block < 0) {
431                 /* Get next block to allocate off */
432                 dev->alloc_block = yaffs_find_alloc_block(dev);
433                 dev->alloc_page = 0;
434         }
435
436         if (!use_reserver && !yaffs_check_alloc_available(dev, 1)) {
437                 /* No space unless we're allowed to use the reserve. */
438                 return -1;
439         }
440
441         if (dev->n_erased_blocks < dev->param.n_reserved_blocks
442             && dev->alloc_page == 0)
443                 yaffs_trace(YAFFS_TRACE_ALLOCATE, "Allocating reserve");
444
445         /* Next page please.... */
446         if (dev->alloc_block >= 0) {
447                 bi = yaffs_get_block_info(dev, dev->alloc_block);
448
449                 ret_val = (dev->alloc_block * dev->param.chunks_per_block) +
450                     dev->alloc_page;
451                 bi->pages_in_use++;
452                 yaffs_set_chunk_bit(dev, dev->alloc_block, dev->alloc_page);
453
454                 dev->alloc_page++;
455
456                 dev->n_free_chunks--;
457
458                 /* If the block is full set the state to full */
459                 if (dev->alloc_page >= dev->param.chunks_per_block) {
460                         bi->block_state = YAFFS_BLOCK_STATE_FULL;
461                         dev->alloc_block = -1;
462                 }
463
464                 if (block_ptr)
465                         *block_ptr = bi;
466
467                 return ret_val;
468         }
469
470         yaffs_trace(YAFFS_TRACE_ERROR,
471                 "!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!");
472
473         return -1;
474 }
475
476 static int yaffs_get_erased_chunks(struct yaffs_dev *dev)
477 {
478         int n;
479
480         n = dev->n_erased_blocks * dev->param.chunks_per_block;
481
482         if (dev->alloc_block > 0)
483                 n += (dev->param.chunks_per_block - dev->alloc_page);
484
485         return n;
486
487 }
488
489 /*
490  * yaffs_skip_rest_of_block() skips over the rest of the allocation block
491  * if we don't want to write to it.
492  */
493 void yaffs_skip_rest_of_block(struct yaffs_dev *dev)
494 {
495         struct yaffs_block_info *bi;
496
497         if (dev->alloc_block > 0) {
498                 bi = yaffs_get_block_info(dev, dev->alloc_block);
499                 if (bi->block_state == YAFFS_BLOCK_STATE_ALLOCATING) {
500                         bi->block_state = YAFFS_BLOCK_STATE_FULL;
501                         dev->alloc_block = -1;
502                 }
503         }
504 }
505
506 static int yaffs_write_new_chunk(struct yaffs_dev *dev,
507                                  const u8 *data,
508                                  struct yaffs_ext_tags *tags, int use_reserver)
509 {
510         int attempts = 0;
511         int write_ok = 0;
512         int chunk;
513
514         yaffs2_checkpt_invalidate(dev);
515
516         do {
517                 struct yaffs_block_info *bi = 0;
518                 int erased_ok = 0;
519
520                 chunk = yaffs_alloc_chunk(dev, use_reserver, &bi);
521                 if (chunk < 0) {
522                         /* no space */
523                         break;
524                 }
525
526                 /* First check this chunk is erased, if it needs
527                  * checking.  The checking policy (unless forced
528                  * always on) is as follows:
529                  *
530                  * Check the first page we try to write in a block.
531                  * If the check passes then we don't need to check any
532                  * more.        If the check fails, we check again...
533                  * If the block has been erased, we don't need to check.
534                  *
535                  * However, if the block has been prioritised for gc,
536                  * then we think there might be something odd about
537                  * this block and stop using it.
538                  *
539                  * Rationale: We should only ever see chunks that have
540                  * not been erased if there was a partially written
541                  * chunk due to power loss.  This checking policy should
542                  * catch that case with very few checks and thus save a
543                  * lot of checks that are most likely not needed.
544                  *
545                  * Mods to the above
546                  * If an erase check fails or the write fails we skip the
547                  * rest of the block.
548                  */
549
550                 /* let's give it a try */
551                 attempts++;
552
553                 if (dev->param.always_check_erased)
554                         bi->skip_erased_check = 0;
555
556                 if (!bi->skip_erased_check) {
557                         erased_ok = yaffs_check_chunk_erased(dev, chunk);
558                         if (erased_ok != YAFFS_OK) {
559                                 yaffs_trace(YAFFS_TRACE_ERROR,
560                                   "**>> yaffs chunk %d was not erased",
561                                   chunk);
562
563                                 /* If not erased, delete this one,
564                                  * skip rest of block and
565                                  * try another chunk */
566                                 yaffs_chunk_del(dev, chunk, 1, __LINE__);
567                                 yaffs_skip_rest_of_block(dev);
568                                 continue;
569                         }
570                 }
571
572                 write_ok = yaffs_wr_chunk_tags_nand(dev, chunk, data, tags);
573
574                 if (!bi->skip_erased_check)
575                         write_ok =
576                             yaffs_verify_chunk_written(dev, chunk, data, tags);
577
578                 if (write_ok != YAFFS_OK) {
579                         /* Clean up aborted write, skip to next block and
580                          * try another chunk */
581                         yaffs_handle_chunk_wr_error(dev, chunk, erased_ok);
582                         continue;
583                 }
584
585                 bi->skip_erased_check = 1;
586
587                 /* Copy the data into the robustification buffer */
588                 yaffs_handle_chunk_wr_ok(dev, chunk, data, tags);
589
590         } while (write_ok != YAFFS_OK &&
591                  (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
592
593         if (!write_ok)
594                 chunk = -1;
595
596         if (attempts > 1) {
597                 yaffs_trace(YAFFS_TRACE_ERROR,
598                         "**>> yaffs write required %d attempts",
599                         attempts);
600                 dev->n_retired_writes += (attempts - 1);
601         }
602
603         return chunk;
604 }
605
606 /*
607  * Block retiring for handling a broken block.
608  */
609
610 static void yaffs_retire_block(struct yaffs_dev *dev, int flash_block)
611 {
612         struct yaffs_block_info *bi = yaffs_get_block_info(dev, flash_block);
613
614         yaffs2_checkpt_invalidate(dev);
615
616         yaffs2_clear_oldest_dirty_seq(dev, bi);
617
618         if (yaffs_mark_bad(dev, flash_block) != YAFFS_OK) {
619                 if (yaffs_erase_block(dev, flash_block) != YAFFS_OK) {
620                         yaffs_trace(YAFFS_TRACE_ALWAYS,
621                                 "yaffs: Failed to mark bad and erase block %d",
622                                 flash_block);
623                 } else {
624                         struct yaffs_ext_tags tags;
625                         int chunk_id =
626                             flash_block * dev->param.chunks_per_block;
627
628                         u8 *buffer = yaffs_get_temp_buffer(dev);
629
630                         memset(buffer, 0xff, dev->data_bytes_per_chunk);
631                         memset(&tags, 0, sizeof(tags));
632                         tags.seq_number = YAFFS_SEQUENCE_BAD_BLOCK;
633                         if (dev->param.write_chunk_tags_fn(dev, chunk_id -
634                                                            dev->chunk_offset,
635                                                            buffer,
636                                                            &tags) != YAFFS_OK)
637                                 yaffs_trace(YAFFS_TRACE_ALWAYS,
638                                         "yaffs: Failed to write bad block marker to block %d",
639                                         flash_block);
640
641                         yaffs_release_temp_buffer(dev, buffer);
642                 }
643         }
644
645         bi->block_state = YAFFS_BLOCK_STATE_DEAD;
646         bi->gc_prioritise = 0;
647         bi->needs_retiring = 0;
648
649         dev->n_retired_blocks++;
650 }
651
652 /*---------------- Name handling functions ------------*/
653
654 static u16 yaffs_calc_name_sum(const YCHAR *name)
655 {
656         u16 sum = 0;
657         u16 i = 1;
658
659         if (!name)
660                 return 0;
661
662         while ((*name) && i < (YAFFS_MAX_NAME_LENGTH / 2)) {
663
664                 /* 0x1f mask is case insensitive */
665                 sum += ((*name) & 0x1f) * i;
666                 i++;
667                 name++;
668         }
669         return sum;
670 }
671
672 void yaffs_set_obj_name(struct yaffs_obj *obj, const YCHAR * name)
673 {
674         memset(obj->short_name, 0, sizeof(obj->short_name));
675         if (name &&
676                 strnlen(name, YAFFS_SHORT_NAME_LENGTH + 1) <=
677                 YAFFS_SHORT_NAME_LENGTH)
678                 strcpy(obj->short_name, name);
679         else
680                 obj->short_name[0] = _Y('\0');
681         obj->sum = yaffs_calc_name_sum(name);
682 }
683
684 void yaffs_set_obj_name_from_oh(struct yaffs_obj *obj,
685                                 const struct yaffs_obj_hdr *oh)
686 {
687 #ifdef CONFIG_YAFFS_AUTO_UNICODE
688         YCHAR tmp_name[YAFFS_MAX_NAME_LENGTH + 1];
689         memset(tmp_name, 0, sizeof(tmp_name));
690         yaffs_load_name_from_oh(obj->my_dev, tmp_name, oh->name,
691                                 YAFFS_MAX_NAME_LENGTH + 1);
692         yaffs_set_obj_name(obj, tmp_name);
693 #else
694         yaffs_set_obj_name(obj, oh->name);
695 #endif
696 }
697
698 /*-------------------- TNODES -------------------
699
700  * List of spare tnodes
701  * The list is hooked together using the first pointer
702  * in the tnode.
703  */
704
705 struct yaffs_tnode *yaffs_get_tnode(struct yaffs_dev *dev)
706 {
707         struct yaffs_tnode *tn = yaffs_alloc_raw_tnode(dev);
708
709         if (tn) {
710                 memset(tn, 0, dev->tnode_size);
711                 dev->n_tnodes++;
712         }
713
714         dev->checkpoint_blocks_required = 0;    /* force recalculation */
715
716         return tn;
717 }
718
719 /* FreeTnode frees up a tnode and puts it back on the free list */
720 static void yaffs_free_tnode(struct yaffs_dev *dev, struct yaffs_tnode *tn)
721 {
722         yaffs_free_raw_tnode(dev, tn);
723         dev->n_tnodes--;
724         dev->checkpoint_blocks_required = 0;    /* force recalculation */
725 }
726
727 static void yaffs_deinit_tnodes_and_objs(struct yaffs_dev *dev)
728 {
729         yaffs_deinit_raw_tnodes_and_objs(dev);
730         dev->n_obj = 0;
731         dev->n_tnodes = 0;
732 }
733
734 void yaffs_load_tnode_0(struct yaffs_dev *dev, struct yaffs_tnode *tn,
735                         unsigned pos, unsigned val)
736 {
737         u32 *map = (u32 *) tn;
738         u32 bit_in_map;
739         u32 bit_in_word;
740         u32 word_in_map;
741         u32 mask;
742
743         pos &= YAFFS_TNODES_LEVEL0_MASK;
744         val >>= dev->chunk_grp_bits;
745
746         bit_in_map = pos * dev->tnode_width;
747         word_in_map = bit_in_map / 32;
748         bit_in_word = bit_in_map & (32 - 1);
749
750         mask = dev->tnode_mask << bit_in_word;
751
752         map[word_in_map] &= ~mask;
753         map[word_in_map] |= (mask & (val << bit_in_word));
754
755         if (dev->tnode_width > (32 - bit_in_word)) {
756                 bit_in_word = (32 - bit_in_word);
757                 word_in_map++;
758                 mask =
759                     dev->tnode_mask >> bit_in_word;
760                 map[word_in_map] &= ~mask;
761                 map[word_in_map] |= (mask & (val >> bit_in_word));
762         }
763 }
764
765 u32 yaffs_get_group_base(struct yaffs_dev *dev, struct yaffs_tnode *tn,
766                          unsigned pos)
767 {
768         u32 *map = (u32 *) tn;
769         u32 bit_in_map;
770         u32 bit_in_word;
771         u32 word_in_map;
772         u32 val;
773
774         pos &= YAFFS_TNODES_LEVEL0_MASK;
775
776         bit_in_map = pos * dev->tnode_width;
777         word_in_map = bit_in_map / 32;
778         bit_in_word = bit_in_map & (32 - 1);
779
780         val = map[word_in_map] >> bit_in_word;
781
782         if (dev->tnode_width > (32 - bit_in_word)) {
783                 bit_in_word = (32 - bit_in_word);
784                 word_in_map++;
785                 val |= (map[word_in_map] << bit_in_word);
786         }
787
788         val &= dev->tnode_mask;
789         val <<= dev->chunk_grp_bits;
790
791         return val;
792 }
793
794 /* ------------------- End of individual tnode manipulation -----------------*/
795
796 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
797  * The look up tree is represented by the top tnode and the number of top_level
798  * in the tree. 0 means only the level 0 tnode is in the tree.
799  */
800
801 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
802 struct yaffs_tnode *yaffs_find_tnode_0(struct yaffs_dev *dev,
803                                        struct yaffs_file_var *file_struct,
804                                        u32 chunk_id)
805 {
806         struct yaffs_tnode *tn = file_struct->top;
807         u32 i;
808         int required_depth;
809         int level = file_struct->top_level;
810
811         dev = dev;
812
813         /* Check sane level and chunk Id */
814         if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
815                 return NULL;
816
817         if (chunk_id > YAFFS_MAX_CHUNK_ID)
818                 return NULL;
819
820         /* First check we're tall enough (ie enough top_level) */
821
822         i = chunk_id >> YAFFS_TNODES_LEVEL0_BITS;
823         required_depth = 0;
824         while (i) {
825                 i >>= YAFFS_TNODES_INTERNAL_BITS;
826                 required_depth++;
827         }
828
829         if (required_depth > file_struct->top_level)
830                 return NULL;    /* Not tall enough, so we can't find it */
831
832         /* Traverse down to level 0 */
833         while (level > 0 && tn) {
834                 tn = tn->internal[(chunk_id >>
835                                    (YAFFS_TNODES_LEVEL0_BITS +
836                                     (level - 1) *
837                                     YAFFS_TNODES_INTERNAL_BITS)) &
838                                   YAFFS_TNODES_INTERNAL_MASK];
839                 level--;
840         }
841
842         return tn;
843 }
844
845 /* add_find_tnode_0 finds the level 0 tnode if it exists,
846  * otherwise first expands the tree.
847  * This happens in two steps:
848  *  1. If the tree isn't tall enough, then make it taller.
849  *  2. Scan down the tree towards the level 0 tnode adding tnodes if required.
850  *
851  * Used when modifying the tree.
852  *
853  *  If the tn argument is NULL, then a fresh tnode will be added otherwise the
854  *  specified tn will be plugged into the ttree.
855  */
856
857 struct yaffs_tnode *yaffs_add_find_tnode_0(struct yaffs_dev *dev,
858                                            struct yaffs_file_var *file_struct,
859                                            u32 chunk_id,
860                                            struct yaffs_tnode *passed_tn)
861 {
862         int required_depth;
863         int i;
864         int l;
865         struct yaffs_tnode *tn;
866         u32 x;
867
868         /* Check sane level and page Id */
869         if (file_struct->top_level < 0 ||
870             file_struct->top_level > YAFFS_TNODES_MAX_LEVEL)
871                 return NULL;
872
873         if (chunk_id > YAFFS_MAX_CHUNK_ID)
874                 return NULL;
875
876         /* First check we're tall enough (ie enough top_level) */
877
878         x = chunk_id >> YAFFS_TNODES_LEVEL0_BITS;
879         required_depth = 0;
880         while (x) {
881                 x >>= YAFFS_TNODES_INTERNAL_BITS;
882                 required_depth++;
883         }
884
885         if (required_depth > file_struct->top_level) {
886                 /* Not tall enough, gotta make the tree taller */
887                 for (i = file_struct->top_level; i < required_depth; i++) {
888
889                         tn = yaffs_get_tnode(dev);
890
891                         if (tn) {
892                                 tn->internal[0] = file_struct->top;
893                                 file_struct->top = tn;
894                                 file_struct->top_level++;
895                         } else {
896                                 yaffs_trace(YAFFS_TRACE_ERROR,
897                                         "yaffs: no more tnodes");
898                                 return NULL;
899                         }
900                 }
901         }
902
903         /* Traverse down to level 0, adding anything we need */
904
905         l = file_struct->top_level;
906         tn = file_struct->top;
907
908         if (l > 0) {
909                 while (l > 0 && tn) {
910                         x = (chunk_id >>
911                              (YAFFS_TNODES_LEVEL0_BITS +
912                               (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
913                             YAFFS_TNODES_INTERNAL_MASK;
914
915                         if ((l > 1) && !tn->internal[x]) {
916                                 /* Add missing non-level-zero tnode */
917                                 tn->internal[x] = yaffs_get_tnode(dev);
918                                 if (!tn->internal[x])
919                                         return NULL;
920                         } else if (l == 1) {
921                                 /* Looking from level 1 at level 0 */
922                                 if (passed_tn) {
923                                         /* If we already have one, release it */
924                                         if (tn->internal[x])
925                                                 yaffs_free_tnode(dev,
926                                                         tn->internal[x]);
927                                         tn->internal[x] = passed_tn;
928
929                                 } else if (!tn->internal[x]) {
930                                         /* Don't have one, none passed in */
931                                         tn->internal[x] = yaffs_get_tnode(dev);
932                                         if (!tn->internal[x])
933                                                 return NULL;
934                                 }
935                         }
936
937                         tn = tn->internal[x];
938                         l--;
939                 }
940         } else {
941                 /* top is level 0 */
942                 if (passed_tn) {
943                         memcpy(tn, passed_tn,
944                                (dev->tnode_width * YAFFS_NTNODES_LEVEL0) / 8);
945                         yaffs_free_tnode(dev, passed_tn);
946                 }
947         }
948
949         return tn;
950 }
951
952 static int yaffs_tags_match(const struct yaffs_ext_tags *tags, int obj_id,
953                             int chunk_obj)
954 {
955         return (tags->chunk_id == chunk_obj &&
956                 tags->obj_id == obj_id &&
957                 !tags->is_deleted) ? 1 : 0;
958
959 }
960
961 static int yaffs_find_chunk_in_group(struct yaffs_dev *dev, int the_chunk,
962                                         struct yaffs_ext_tags *tags, int obj_id,
963                                         int inode_chunk)
964 {
965         int j;
966
967         for (j = 0; the_chunk && j < dev->chunk_grp_size; j++) {
968                 if (yaffs_check_chunk_bit
969                     (dev, the_chunk / dev->param.chunks_per_block,
970                      the_chunk % dev->param.chunks_per_block)) {
971
972                         if (dev->chunk_grp_size == 1)
973                                 return the_chunk;
974                         else {
975                                 yaffs_rd_chunk_tags_nand(dev, the_chunk, NULL,
976                                                          tags);
977                                 if (yaffs_tags_match(tags,
978                                                         obj_id, inode_chunk)) {
979                                         /* found it; */
980                                         return the_chunk;
981                                 }
982                         }
983                 }
984                 the_chunk++;
985         }
986         return -1;
987 }
988
989 static int yaffs_find_chunk_in_file(struct yaffs_obj *in, int inode_chunk,
990                                     struct yaffs_ext_tags *tags)
991 {
992         /*Get the Tnode, then get the level 0 offset chunk offset */
993         struct yaffs_tnode *tn;
994         int the_chunk = -1;
995         struct yaffs_ext_tags local_tags;
996         int ret_val = -1;
997         struct yaffs_dev *dev = in->my_dev;
998
999         if (!tags) {
1000                 /* Passed a NULL, so use our own tags space */
1001                 tags = &local_tags;
1002         }
1003
1004         tn = yaffs_find_tnode_0(dev, &in->variant.file_variant, inode_chunk);
1005
1006         if (!tn)
1007                 return ret_val;
1008
1009         the_chunk = yaffs_get_group_base(dev, tn, inode_chunk);
1010
1011         ret_val = yaffs_find_chunk_in_group(dev, the_chunk, tags, in->obj_id,
1012                                               inode_chunk);
1013         return ret_val;
1014 }
1015
1016 static int yaffs_find_del_file_chunk(struct yaffs_obj *in, int inode_chunk,
1017                                      struct yaffs_ext_tags *tags)
1018 {
1019         /* Get the Tnode, then get the level 0 offset chunk offset */
1020         struct yaffs_tnode *tn;
1021         int the_chunk = -1;
1022         struct yaffs_ext_tags local_tags;
1023         struct yaffs_dev *dev = in->my_dev;
1024         int ret_val = -1;
1025
1026         if (!tags) {
1027                 /* Passed a NULL, so use our own tags space */
1028                 tags = &local_tags;
1029         }
1030
1031         tn = yaffs_find_tnode_0(dev, &in->variant.file_variant, inode_chunk);
1032
1033         if (!tn)
1034                 return ret_val;
1035
1036         the_chunk = yaffs_get_group_base(dev, tn, inode_chunk);
1037
1038         ret_val = yaffs_find_chunk_in_group(dev, the_chunk, tags, in->obj_id,
1039                                               inode_chunk);
1040
1041         /* Delete the entry in the filestructure (if found) */
1042         if (ret_val != -1)
1043                 yaffs_load_tnode_0(dev, tn, inode_chunk, 0);
1044
1045         return ret_val;
1046 }
1047
1048 int yaffs_put_chunk_in_file(struct yaffs_obj *in, int inode_chunk,
1049                             int nand_chunk, int in_scan)
1050 {
1051         /* NB in_scan is zero unless scanning.
1052          * For forward scanning, in_scan is > 0;
1053          * for backward scanning in_scan is < 0
1054          *
1055          * nand_chunk = 0 is a dummy insert to make sure the tnodes are there.
1056          */
1057
1058         struct yaffs_tnode *tn;
1059         struct yaffs_dev *dev = in->my_dev;
1060         int existing_cunk;
1061         struct yaffs_ext_tags existing_tags;
1062         struct yaffs_ext_tags new_tags;
1063         unsigned existing_serial, new_serial;
1064
1065         if (in->variant_type != YAFFS_OBJECT_TYPE_FILE) {
1066                 /* Just ignore an attempt at putting a chunk into a non-file
1067                  * during scanning.
1068                  * If it is not during Scanning then something went wrong!
1069                  */
1070                 if (!in_scan) {
1071                         yaffs_trace(YAFFS_TRACE_ERROR,
1072                                 "yaffs tragedy:attempt to put data chunk into a non-file"
1073                                 );
1074                         BUG();
1075                 }
1076
1077                 yaffs_chunk_del(dev, nand_chunk, 1, __LINE__);
1078                 return YAFFS_OK;
1079         }
1080
1081         tn = yaffs_add_find_tnode_0(dev,
1082                                     &in->variant.file_variant,
1083                                     inode_chunk, NULL);
1084         if (!tn)
1085                 return YAFFS_FAIL;
1086
1087         if (!nand_chunk)
1088                 /* Dummy insert, bail now */
1089                 return YAFFS_OK;
1090
1091         existing_cunk = yaffs_get_group_base(dev, tn, inode_chunk);
1092
1093         if (in_scan != 0) {
1094                 /* If we're scanning then we need to test for duplicates
1095                  * NB This does not need to be efficient since it should only
1096                  * happen when the power fails during a write, then only one
1097                  * chunk should ever be affected.
1098                  *
1099                  * Correction for YAFFS2: This could happen quite a lot and we
1100                  * need to think about efficiency! TODO
1101                  * Update: For backward scanning we don't need to re-read tags
1102                  * so this is quite cheap.
1103                  */
1104
1105                 if (existing_cunk > 0) {
1106                         /* NB Right now existing chunk will not be real
1107                          * chunk_id if the chunk group size > 1
1108                          * thus we have to do a FindChunkInFile to get the
1109                          * real chunk id.
1110                          *
1111                          * We have a duplicate now we need to decide which
1112                          * one to use:
1113                          *
1114                          * Backwards scanning YAFFS2: The old one is what
1115                          * we use, dump the new one.
1116                          * YAFFS1: Get both sets of tags and compare serial
1117                          * numbers.
1118                          */
1119
1120                         if (in_scan > 0) {
1121                                 /* Only do this for forward scanning */
1122                                 yaffs_rd_chunk_tags_nand(dev,
1123                                                          nand_chunk,
1124                                                          NULL, &new_tags);
1125
1126                                 /* Do a proper find */
1127                                 existing_cunk =
1128                                     yaffs_find_chunk_in_file(in, inode_chunk,
1129                                                              &existing_tags);
1130                         }
1131
1132                         if (existing_cunk <= 0) {
1133                                 /*Hoosterman - how did this happen? */
1134
1135                                 yaffs_trace(YAFFS_TRACE_ERROR,
1136                                         "yaffs tragedy: existing chunk < 0 in scan"
1137                                         );
1138
1139                         }
1140
1141                         /* NB The deleted flags should be false, otherwise
1142                          * the chunks will not be loaded during a scan
1143                          */
1144
1145                         if (in_scan > 0) {
1146                                 new_serial = new_tags.serial_number;
1147                                 existing_serial = existing_tags.serial_number;
1148                         }
1149
1150                         if ((in_scan > 0) &&
1151                             (existing_cunk <= 0 ||
1152                              ((existing_serial + 1) & 3) == new_serial)) {
1153                                 /* Forward scanning.
1154                                  * Use new
1155                                  * Delete the old one and drop through to
1156                                  * update the tnode
1157                                  */
1158                                 yaffs_chunk_del(dev, existing_cunk, 1,
1159                                                 __LINE__);
1160                         } else {
1161                                 /* Backward scanning or we want to use the
1162                                  * existing one
1163                                  * Delete the new one and return early so that
1164                                  * the tnode isn't changed
1165                                  */
1166                                 yaffs_chunk_del(dev, nand_chunk, 1, __LINE__);
1167                                 return YAFFS_OK;
1168                         }
1169                 }
1170
1171         }
1172
1173         if (existing_cunk == 0)
1174                 in->n_data_chunks++;
1175
1176         yaffs_load_tnode_0(dev, tn, inode_chunk, nand_chunk);
1177
1178         return YAFFS_OK;
1179 }
1180
1181 static void yaffs_soft_del_chunk(struct yaffs_dev *dev, int chunk)
1182 {
1183         struct yaffs_block_info *the_block;
1184         unsigned block_no;
1185
1186         yaffs_trace(YAFFS_TRACE_DELETION, "soft delete chunk %d", chunk);
1187
1188         block_no = chunk / dev->param.chunks_per_block;
1189         the_block = yaffs_get_block_info(dev, block_no);
1190         if (the_block) {
1191                 the_block->soft_del_pages++;
1192                 dev->n_free_chunks++;
1193                 yaffs2_update_oldest_dirty_seq(dev, block_no, the_block);
1194         }
1195 }
1196
1197 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all
1198  * the chunks in the file.
1199  * All soft deleting does is increment the block's softdelete count and pulls
1200  * the chunk out of the tnode.
1201  * Thus, essentially this is the same as DeleteWorker except that the chunks
1202  * are soft deleted.
1203  */
1204
1205 static int yaffs_soft_del_worker(struct yaffs_obj *in, struct yaffs_tnode *tn,
1206                                  u32 level, int chunk_offset)
1207 {
1208         int i;
1209         int the_chunk;
1210         int all_done = 1;
1211         struct yaffs_dev *dev = in->my_dev;
1212
1213         if (!tn)
1214                 return 1;
1215
1216         if (level > 0) {
1217                 for (i = YAFFS_NTNODES_INTERNAL - 1;
1218                         all_done && i >= 0;
1219                         i--) {
1220                         if (tn->internal[i]) {
1221                                 all_done =
1222                                     yaffs_soft_del_worker(in,
1223                                         tn->internal[i],
1224                                         level - 1,
1225                                         (chunk_offset <<
1226                                         YAFFS_TNODES_INTERNAL_BITS)
1227                                         + i);
1228                                 if (all_done) {
1229                                         yaffs_free_tnode(dev,
1230                                                 tn->internal[i]);
1231                                         tn->internal[i] = NULL;
1232                                 } else {
1233                                         /* Can this happen? */
1234                                 }
1235                         }
1236                 }
1237                 return (all_done) ? 1 : 0;
1238         }
1239
1240         /* level 0 */
1241          for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1242                 the_chunk = yaffs_get_group_base(dev, tn, i);
1243                 if (the_chunk) {
1244                         yaffs_soft_del_chunk(dev, the_chunk);
1245                         yaffs_load_tnode_0(dev, tn, i, 0);
1246                 }
1247         }
1248         return 1;
1249 }
1250
1251 static void yaffs_remove_obj_from_dir(struct yaffs_obj *obj)
1252 {
1253         struct yaffs_dev *dev = obj->my_dev;
1254         struct yaffs_obj *parent;
1255
1256         yaffs_verify_obj_in_dir(obj);
1257         parent = obj->parent;
1258
1259         yaffs_verify_dir(parent);
1260
1261         if (dev && dev->param.remove_obj_fn)
1262                 dev->param.remove_obj_fn(obj);
1263
1264         list_del_init(&obj->siblings);
1265         obj->parent = NULL;
1266
1267         yaffs_verify_dir(parent);
1268 }
1269
1270 void yaffs_add_obj_to_dir(struct yaffs_obj *directory, struct yaffs_obj *obj)
1271 {
1272         if (!directory) {
1273                 yaffs_trace(YAFFS_TRACE_ALWAYS,
1274                         "tragedy: Trying to add an object to a null pointer directory"
1275                         );
1276                 BUG();
1277                 return;
1278         }
1279         if (directory->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY) {
1280                 yaffs_trace(YAFFS_TRACE_ALWAYS,
1281                         "tragedy: Trying to add an object to a non-directory"
1282                         );
1283                 BUG();
1284         }
1285
1286         if (obj->siblings.prev == NULL) {
1287                 /* Not initialised */
1288                 BUG();
1289         }
1290
1291         yaffs_verify_dir(directory);
1292
1293         yaffs_remove_obj_from_dir(obj);
1294
1295         /* Now add it */
1296         list_add(&obj->siblings, &directory->variant.dir_variant.children);
1297         obj->parent = directory;
1298
1299         if (directory == obj->my_dev->unlinked_dir
1300             || directory == obj->my_dev->del_dir) {
1301                 obj->unlinked = 1;
1302                 obj->my_dev->n_unlinked_files++;
1303                 obj->rename_allowed = 0;
1304         }
1305
1306         yaffs_verify_dir(directory);
1307         yaffs_verify_obj_in_dir(obj);
1308 }
1309
1310 static int yaffs_change_obj_name(struct yaffs_obj *obj,
1311                                  struct yaffs_obj *new_dir,
1312                                  const YCHAR *new_name, int force, int shadows)
1313 {
1314         int unlink_op;
1315         int del_op;
1316         struct yaffs_obj *existing_target;
1317
1318         if (new_dir == NULL)
1319                 new_dir = obj->parent;  /* use the old directory */
1320
1321         if (new_dir->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY) {
1322                 yaffs_trace(YAFFS_TRACE_ALWAYS,
1323                         "tragedy: yaffs_change_obj_name: new_dir is not a directory"
1324                         );
1325                 BUG();
1326         }
1327
1328         unlink_op = (new_dir == obj->my_dev->unlinked_dir);
1329         del_op = (new_dir == obj->my_dev->del_dir);
1330
1331         existing_target = yaffs_find_by_name(new_dir, new_name);
1332
1333         /* If the object is a file going into the unlinked directory,
1334          *   then it is OK to just stuff it in since duplicate names are OK.
1335          *   else only proceed if the new name does not exist and we're putting
1336          *   it into a directory.
1337          */
1338         if (!(unlink_op || del_op || force ||
1339               shadows > 0 || !existing_target) ||
1340               new_dir->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY)
1341                 return YAFFS_FAIL;
1342
1343         yaffs_set_obj_name(obj, new_name);
1344         obj->dirty = 1;
1345         yaffs_add_obj_to_dir(new_dir, obj);
1346
1347         if (unlink_op)
1348                 obj->unlinked = 1;
1349
1350         /* If it is a deletion then we mark it as a shrink for gc  */
1351         if (yaffs_update_oh(obj, new_name, 0, del_op, shadows, NULL) >= 0)
1352                 return YAFFS_OK;
1353
1354         return YAFFS_FAIL;
1355 }
1356
1357 /*------------------------ Short Operations Cache ------------------------------
1358  *   In many situations where there is no high level buffering  a lot of
1359  *   reads might be short sequential reads, and a lot of writes may be short
1360  *   sequential writes. eg. scanning/writing a jpeg file.
1361  *   In these cases, a short read/write cache can provide a huge perfomance
1362  *   benefit with dumb-as-a-rock code.
1363  *   In Linux, the page cache provides read buffering and the short op cache
1364  *   provides write buffering.
1365  *
1366  *   There are a small number (~10) of cache chunks per device so that we don't
1367  *   need a very intelligent search.
1368  */
1369
1370 static int yaffs_obj_cache_dirty(struct yaffs_obj *obj)
1371 {
1372         struct yaffs_dev *dev = obj->my_dev;
1373         int i;
1374         struct yaffs_cache *cache;
1375         int n_caches = obj->my_dev->param.n_caches;
1376
1377         for (i = 0; i < n_caches; i++) {
1378                 cache = &dev->cache[i];
1379                 if (cache->object == obj && cache->dirty)
1380                         return 1;
1381         }
1382
1383         return 0;
1384 }
1385
1386 static void yaffs_flush_file_cache(struct yaffs_obj *obj)
1387 {
1388         struct yaffs_dev *dev = obj->my_dev;
1389         int lowest = -99;       /* Stop compiler whining. */
1390         int i;
1391         struct yaffs_cache *cache;
1392         int chunk_written = 0;
1393         int n_caches = obj->my_dev->param.n_caches;
1394
1395         if (n_caches < 1)
1396                 return;
1397         do {
1398                 cache = NULL;
1399
1400                 /* Find the lowest dirty chunk for this object */
1401                 for (i = 0; i < n_caches; i++) {
1402                         if (dev->cache[i].object == obj &&
1403                             dev->cache[i].dirty) {
1404                                 if (!cache ||
1405                                     dev->cache[i].chunk_id < lowest) {
1406                                         cache = &dev->cache[i];
1407                                         lowest = cache->chunk_id;
1408                                 }
1409                         }
1410                 }
1411
1412                 if (cache && !cache->locked) {
1413                         /* Write it out and free it up */
1414                         chunk_written =
1415                             yaffs_wr_data_obj(cache->object,
1416                                               cache->chunk_id,
1417                                               cache->data,
1418                                               cache->n_bytes, 1);
1419                         cache->dirty = 0;
1420                         cache->object = NULL;
1421                 }
1422         } while (cache && chunk_written > 0);
1423
1424         if (cache)
1425                 /* Hoosterman, disk full while writing cache out. */
1426                 yaffs_trace(YAFFS_TRACE_ERROR,
1427                         "yaffs tragedy: no space during cache write");
1428 }
1429
1430 /*yaffs_flush_whole_cache(dev)
1431  *
1432  *
1433  */
1434
1435 void yaffs_flush_whole_cache(struct yaffs_dev *dev)
1436 {
1437         struct yaffs_obj *obj;
1438         int n_caches = dev->param.n_caches;
1439         int i;
1440
1441         /* Find a dirty object in the cache and flush it...
1442          * until there are no further dirty objects.
1443          */
1444         do {
1445                 obj = NULL;
1446                 for (i = 0; i < n_caches && !obj; i++) {
1447                         if (dev->cache[i].object && dev->cache[i].dirty)
1448                                 obj = dev->cache[i].object;
1449                 }
1450                 if (obj)
1451                         yaffs_flush_file_cache(obj);
1452         } while (obj);
1453
1454 }
1455
1456 /* Grab us a cache chunk for use.
1457  * First look for an empty one.
1458  * Then look for the least recently used non-dirty one.
1459  * Then look for the least recently used dirty one...., flush and look again.
1460  */
1461 static struct yaffs_cache *yaffs_grab_chunk_worker(struct yaffs_dev *dev)
1462 {
1463         int i;
1464
1465         if (dev->param.n_caches > 0) {
1466                 for (i = 0; i < dev->param.n_caches; i++) {
1467                         if (!dev->cache[i].object)
1468                                 return &dev->cache[i];
1469                 }
1470         }
1471         return NULL;
1472 }
1473
1474 static struct yaffs_cache *yaffs_grab_chunk_cache(struct yaffs_dev *dev)
1475 {
1476         struct yaffs_cache *cache;
1477         struct yaffs_obj *the_obj;
1478         int usage;
1479         int i;
1480         int pushout;
1481
1482         if (dev->param.n_caches < 1)
1483                 return NULL;
1484
1485         /* Try find a non-dirty one... */
1486
1487         cache = yaffs_grab_chunk_worker(dev);
1488
1489         if (!cache) {
1490                 /* They were all dirty, find the LRU object and flush
1491                  * its cache, then  find again.
1492                  * NB what's here is not very accurate,
1493                  * we actually flush the object with the LRU chunk.
1494                  */
1495
1496                 /* With locking we can't assume we can use entry zero,
1497                  * Set the_obj to a valid pointer for Coverity. */
1498                 the_obj = dev->cache[0].object;
1499                 usage = -1;
1500                 cache = NULL;
1501                 pushout = -1;
1502
1503                 for (i = 0; i < dev->param.n_caches; i++) {
1504                         if (dev->cache[i].object &&
1505                             !dev->cache[i].locked &&
1506                             (dev->cache[i].last_use < usage ||
1507                             !cache)) {
1508                                 usage = dev->cache[i].last_use;
1509                                 the_obj = dev->cache[i].object;
1510                                 cache = &dev->cache[i];
1511                                 pushout = i;
1512                         }
1513                 }
1514
1515                 if (!cache || cache->dirty) {
1516                         /* Flush and try again */
1517                         yaffs_flush_file_cache(the_obj);
1518                         cache = yaffs_grab_chunk_worker(dev);
1519                 }
1520         }
1521         return cache;
1522 }
1523
1524 /* Find a cached chunk */
1525 static struct yaffs_cache *yaffs_find_chunk_cache(const struct yaffs_obj *obj,
1526                                                   int chunk_id)
1527 {
1528         struct yaffs_dev *dev = obj->my_dev;
1529         int i;
1530
1531         if (dev->param.n_caches < 1)
1532                 return NULL;
1533
1534         for (i = 0; i < dev->param.n_caches; i++) {
1535                 if (dev->cache[i].object == obj &&
1536                     dev->cache[i].chunk_id == chunk_id) {
1537                         dev->cache_hits++;
1538
1539                         return &dev->cache[i];
1540                 }
1541         }
1542         return NULL;
1543 }
1544
1545 /* Mark the chunk for the least recently used algorithym */
1546 static void yaffs_use_cache(struct yaffs_dev *dev, struct yaffs_cache *cache,
1547                             int is_write)
1548 {
1549         int i;
1550
1551         if (dev->param.n_caches < 1)
1552                 return;
1553
1554         if (dev->cache_last_use < 0 ||
1555                 dev->cache_last_use > 100000000) {
1556                 /* Reset the cache usages */
1557                 for (i = 1; i < dev->param.n_caches; i++)
1558                         dev->cache[i].last_use = 0;
1559
1560                 dev->cache_last_use = 0;
1561         }
1562         dev->cache_last_use++;
1563         cache->last_use = dev->cache_last_use;
1564
1565         if (is_write)
1566                 cache->dirty = 1;
1567 }
1568
1569 /* Invalidate a single cache page.
1570  * Do this when a whole page gets written,
1571  * ie the short cache for this page is no longer valid.
1572  */
1573 static void yaffs_invalidate_chunk_cache(struct yaffs_obj *object, int chunk_id)
1574 {
1575         struct yaffs_cache *cache;
1576
1577         if (object->my_dev->param.n_caches > 0) {
1578                 cache = yaffs_find_chunk_cache(object, chunk_id);
1579
1580                 if (cache)
1581                         cache->object = NULL;
1582         }
1583 }
1584
1585 /* Invalidate all the cache pages associated with this object
1586  * Do this whenever ther file is deleted or resized.
1587  */
1588 static void yaffs_invalidate_whole_cache(struct yaffs_obj *in)
1589 {
1590         int i;
1591         struct yaffs_dev *dev = in->my_dev;
1592
1593         if (dev->param.n_caches > 0) {
1594                 /* Invalidate it. */
1595                 for (i = 0; i < dev->param.n_caches; i++) {
1596                         if (dev->cache[i].object == in)
1597                                 dev->cache[i].object = NULL;
1598                 }
1599         }
1600 }
1601
1602 static void yaffs_unhash_obj(struct yaffs_obj *obj)
1603 {
1604         int bucket;
1605         struct yaffs_dev *dev = obj->my_dev;
1606
1607         /* If it is still linked into the bucket list, free from the list */
1608         if (!list_empty(&obj->hash_link)) {
1609                 list_del_init(&obj->hash_link);
1610                 bucket = yaffs_hash_fn(obj->obj_id);
1611                 dev->obj_bucket[bucket].count--;
1612         }
1613 }
1614
1615 /*  FreeObject frees up a Object and puts it back on the free list */
1616 static void yaffs_free_obj(struct yaffs_obj *obj)
1617 {
1618         struct yaffs_dev *dev;
1619
1620         if (!obj) {
1621                 BUG();
1622                 return;
1623         }
1624         dev = obj->my_dev;
1625         yaffs_trace(YAFFS_TRACE_OS, "FreeObject %p inode %p",
1626                 obj, obj->my_inode);
1627         if (obj->parent)
1628                 BUG();
1629         if (!list_empty(&obj->siblings))
1630                 BUG();
1631
1632         if (obj->my_inode) {
1633                 /* We're still hooked up to a cached inode.
1634                  * Don't delete now, but mark for later deletion
1635                  */
1636                 obj->defered_free = 1;
1637                 return;
1638         }
1639
1640         yaffs_unhash_obj(obj);
1641
1642         yaffs_free_raw_obj(dev, obj);
1643         dev->n_obj--;
1644         dev->checkpoint_blocks_required = 0;    /* force recalculation */
1645 }
1646
1647 void yaffs_handle_defered_free(struct yaffs_obj *obj)
1648 {
1649         if (obj->defered_free)
1650                 yaffs_free_obj(obj);
1651 }
1652
1653 static int yaffs_generic_obj_del(struct yaffs_obj *in)
1654 {
1655         /* Iinvalidate the file's data in the cache, without flushing. */
1656         yaffs_invalidate_whole_cache(in);
1657
1658         if (in->my_dev->param.is_yaffs2 && in->parent != in->my_dev->del_dir) {
1659                 /* Move to unlinked directory so we have a deletion record */
1660                 yaffs_change_obj_name(in, in->my_dev->del_dir, _Y("deleted"), 0,
1661                                       0);
1662         }
1663
1664         yaffs_remove_obj_from_dir(in);
1665         yaffs_chunk_del(in->my_dev, in->hdr_chunk, 1, __LINE__);
1666         in->hdr_chunk = 0;
1667
1668         yaffs_free_obj(in);
1669         return YAFFS_OK;
1670
1671 }
1672
1673 static void yaffs_soft_del_file(struct yaffs_obj *obj)
1674 {
1675         if (!obj->deleted ||
1676             obj->variant_type != YAFFS_OBJECT_TYPE_FILE ||
1677             obj->soft_del)
1678                 return;
1679
1680         if (obj->n_data_chunks <= 0) {
1681                 /* Empty file with no duplicate object headers,
1682                  * just delete it immediately */
1683                 yaffs_free_tnode(obj->my_dev, obj->variant.file_variant.top);
1684                 obj->variant.file_variant.top = NULL;
1685                 yaffs_trace(YAFFS_TRACE_TRACING,
1686                         "yaffs: Deleting empty file %d",
1687                         obj->obj_id);
1688                 yaffs_generic_obj_del(obj);
1689         } else {
1690                 yaffs_soft_del_worker(obj,
1691                                       obj->variant.file_variant.top,
1692                                       obj->variant.
1693                                       file_variant.top_level, 0);
1694                 obj->soft_del = 1;
1695         }
1696 }
1697
1698 /* Pruning removes any part of the file structure tree that is beyond the
1699  * bounds of the file (ie that does not point to chunks).
1700  *
1701  * A file should only get pruned when its size is reduced.
1702  *
1703  * Before pruning, the chunks must be pulled from the tree and the
1704  * level 0 tnode entries must be zeroed out.
1705  * Could also use this for file deletion, but that's probably better handled
1706  * by a special case.
1707  *
1708  * This function is recursive. For levels > 0 the function is called again on
1709  * any sub-tree. For level == 0 we just check if the sub-tree has data.
1710  * If there is no data in a subtree then it is pruned.
1711  */
1712
1713 static struct yaffs_tnode *yaffs_prune_worker(struct yaffs_dev *dev,
1714                                               struct yaffs_tnode *tn, u32 level,
1715                                               int del0)
1716 {
1717         int i;
1718         int has_data;
1719
1720         if (!tn)
1721                 return tn;
1722
1723         has_data = 0;
1724
1725         if (level > 0) {
1726                 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1727                         if (tn->internal[i]) {
1728                                 tn->internal[i] =
1729                                     yaffs_prune_worker(dev,
1730                                                 tn->internal[i],
1731                                                 level - 1,
1732                                                 (i == 0) ? del0 : 1);
1733                         }
1734
1735                         if (tn->internal[i])
1736                                 has_data++;
1737                 }
1738         } else {
1739                 int tnode_size_u32 = dev->tnode_size / sizeof(u32);
1740                 u32 *map = (u32 *) tn;
1741
1742                 for (i = 0; !has_data && i < tnode_size_u32; i++) {
1743                         if (map[i])
1744                                 has_data++;
1745                 }
1746         }
1747
1748         if (has_data == 0 && del0) {
1749                 /* Free and return NULL */
1750                 yaffs_free_tnode(dev, tn);
1751                 tn = NULL;
1752         }
1753         return tn;
1754 }
1755
1756 static int yaffs_prune_tree(struct yaffs_dev *dev,
1757                             struct yaffs_file_var *file_struct)
1758 {
1759         int i;
1760         int has_data;
1761         int done = 0;
1762         struct yaffs_tnode *tn;
1763
1764         if (file_struct->top_level < 1)
1765                 return YAFFS_OK;
1766
1767         file_struct->top =
1768            yaffs_prune_worker(dev, file_struct->top, file_struct->top_level, 0);
1769
1770         /* Now we have a tree with all the non-zero branches NULL but
1771          * the height is the same as it was.
1772          * Let's see if we can trim internal tnodes to shorten the tree.
1773          * We can do this if only the 0th element in the tnode is in use
1774          * (ie all the non-zero are NULL)
1775          */
1776
1777         while (file_struct->top_level && !done) {
1778                 tn = file_struct->top;
1779
1780                 has_data = 0;
1781                 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1782                         if (tn->internal[i])
1783                                 has_data++;
1784                 }
1785
1786                 if (!has_data) {
1787                         file_struct->top = tn->internal[0];
1788                         file_struct->top_level--;
1789                         yaffs_free_tnode(dev, tn);
1790                 } else {
1791                         done = 1;
1792                 }
1793         }
1794
1795         return YAFFS_OK;
1796 }
1797
1798 /*-------------------- End of File Structure functions.-------------------*/
1799
1800 /* alloc_empty_obj gets us a clean Object.*/
1801 static struct yaffs_obj *yaffs_alloc_empty_obj(struct yaffs_dev *dev)
1802 {
1803         struct yaffs_obj *obj = yaffs_alloc_raw_obj(dev);
1804
1805         if (!obj)
1806                 return obj;
1807
1808         dev->n_obj++;
1809
1810         /* Now sweeten it up... */
1811
1812         memset(obj, 0, sizeof(struct yaffs_obj));
1813         obj->being_created = 1;
1814
1815         obj->my_dev = dev;
1816         obj->hdr_chunk = 0;
1817         obj->variant_type = YAFFS_OBJECT_TYPE_UNKNOWN;
1818         INIT_LIST_HEAD(&(obj->hard_links));
1819         INIT_LIST_HEAD(&(obj->hash_link));
1820         INIT_LIST_HEAD(&obj->siblings);
1821
1822         /* Now make the directory sane */
1823         if (dev->root_dir) {
1824                 obj->parent = dev->root_dir;
1825                 list_add(&(obj->siblings),
1826                          &dev->root_dir->variant.dir_variant.children);
1827         }
1828
1829         /* Add it to the lost and found directory.
1830          * NB Can't put root or lost-n-found in lost-n-found so
1831          * check if lost-n-found exists first
1832          */
1833         if (dev->lost_n_found)
1834                 yaffs_add_obj_to_dir(dev->lost_n_found, obj);
1835
1836         obj->being_created = 0;
1837
1838         dev->checkpoint_blocks_required = 0;    /* force recalculation */
1839
1840         return obj;
1841 }
1842
1843 static int yaffs_find_nice_bucket(struct yaffs_dev *dev)
1844 {
1845         int i;
1846         int l = 999;
1847         int lowest = 999999;
1848
1849         /* Search for the shortest list or one that
1850          * isn't too long.
1851          */
1852
1853         for (i = 0; i < 10 && lowest > 4; i++) {
1854                 dev->bucket_finder++;
1855                 dev->bucket_finder %= YAFFS_NOBJECT_BUCKETS;
1856                 if (dev->obj_bucket[dev->bucket_finder].count < lowest) {
1857                         lowest = dev->obj_bucket[dev->bucket_finder].count;
1858                         l = dev->bucket_finder;
1859                 }
1860         }
1861
1862         return l;
1863 }
1864
1865 static int yaffs_new_obj_id(struct yaffs_dev *dev)
1866 {
1867         int bucket = yaffs_find_nice_bucket(dev);
1868         int found = 0;
1869         struct list_head *i;
1870         u32 n = (u32) bucket;
1871
1872         /* Now find an object value that has not already been taken
1873          * by scanning the list.
1874          */
1875
1876         while (!found) {
1877                 found = 1;
1878                 n += YAFFS_NOBJECT_BUCKETS;
1879                 if (1 || dev->obj_bucket[bucket].count > 0) {
1880                         list_for_each(i, &dev->obj_bucket[bucket].list) {
1881                                 /* If there is already one in the list */
1882                                 if (i && list_entry(i, struct yaffs_obj,
1883                                                     hash_link)->obj_id == n) {
1884                                         found = 0;
1885                                 }
1886                         }
1887                 }
1888         }
1889         return n;
1890 }
1891
1892 static void yaffs_hash_obj(struct yaffs_obj *in)
1893 {
1894         int bucket = yaffs_hash_fn(in->obj_id);
1895         struct yaffs_dev *dev = in->my_dev;
1896
1897         list_add(&in->hash_link, &dev->obj_bucket[bucket].list);
1898         dev->obj_bucket[bucket].count++;
1899 }
1900
1901 struct yaffs_obj *yaffs_find_by_number(struct yaffs_dev *dev, u32 number)
1902 {
1903         int bucket = yaffs_hash_fn(number);
1904         struct list_head *i;
1905         struct yaffs_obj *in;
1906
1907         list_for_each(i, &dev->obj_bucket[bucket].list) {
1908                 /* Look if it is in the list */
1909                 in = list_entry(i, struct yaffs_obj, hash_link);
1910                 if (in->obj_id == number) {
1911                         /* Don't show if it is defered free */
1912                         if (in->defered_free)
1913                                 return NULL;
1914                         return in;
1915                 }
1916         }
1917
1918         return NULL;
1919 }
1920
1921 struct yaffs_obj *yaffs_new_obj(struct yaffs_dev *dev, int number,
1922                                 enum yaffs_obj_type type)
1923 {
1924         struct yaffs_obj *the_obj = NULL;
1925         struct yaffs_tnode *tn = NULL;
1926
1927         if (number < 0)
1928                 number = yaffs_new_obj_id(dev);
1929
1930         if (type == YAFFS_OBJECT_TYPE_FILE) {
1931                 tn = yaffs_get_tnode(dev);
1932                 if (!tn)
1933                         return NULL;
1934         }
1935
1936         the_obj = yaffs_alloc_empty_obj(dev);
1937         if (!the_obj) {
1938                 if (tn)
1939                         yaffs_free_tnode(dev, tn);
1940                 return NULL;
1941         }
1942
1943         the_obj->fake = 0;
1944         the_obj->rename_allowed = 1;
1945         the_obj->unlink_allowed = 1;
1946         the_obj->obj_id = number;
1947         yaffs_hash_obj(the_obj);
1948         the_obj->variant_type = type;
1949         yaffs_load_current_time(the_obj, 1, 1);
1950
1951         switch (type) {
1952         case YAFFS_OBJECT_TYPE_FILE:
1953                 the_obj->variant.file_variant.file_size = 0;
1954                 the_obj->variant.file_variant.scanned_size = 0;
1955                 the_obj->variant.file_variant.shrink_size = ~0; /* max */
1956                 the_obj->variant.file_variant.top_level = 0;
1957                 the_obj->variant.file_variant.top = tn;
1958                 break;
1959         case YAFFS_OBJECT_TYPE_DIRECTORY:
1960                 INIT_LIST_HEAD(&the_obj->variant.dir_variant.children);
1961                 INIT_LIST_HEAD(&the_obj->variant.dir_variant.dirty);
1962                 break;
1963         case YAFFS_OBJECT_TYPE_SYMLINK:
1964         case YAFFS_OBJECT_TYPE_HARDLINK:
1965         case YAFFS_OBJECT_TYPE_SPECIAL:
1966                 /* No action required */
1967                 break;
1968         case YAFFS_OBJECT_TYPE_UNKNOWN:
1969                 /* todo this should not happen */
1970                 break;
1971         }
1972         return the_obj;
1973 }
1974
1975 static struct yaffs_obj *yaffs_create_fake_dir(struct yaffs_dev *dev,
1976                                                int number, u32 mode)
1977 {
1978
1979         struct yaffs_obj *obj =
1980             yaffs_new_obj(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1981
1982         if (!obj)
1983                 return NULL;
1984
1985         obj->fake = 1;  /* it is fake so it might not use NAND */
1986         obj->rename_allowed = 0;
1987         obj->unlink_allowed = 0;
1988         obj->deleted = 0;
1989         obj->unlinked = 0;
1990         obj->yst_mode = mode;
1991         obj->my_dev = dev;
1992         obj->hdr_chunk = 0;     /* Not a valid chunk. */
1993         return obj;
1994
1995 }
1996
1997
1998 static void yaffs_init_tnodes_and_objs(struct yaffs_dev *dev)
1999 {
2000         int i;
2001
2002         dev->n_obj = 0;
2003         dev->n_tnodes = 0;
2004         yaffs_init_raw_tnodes_and_objs(dev);
2005
2006         for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2007                 INIT_LIST_HEAD(&dev->obj_bucket[i].list);
2008                 dev->obj_bucket[i].count = 0;
2009         }
2010 }
2011
2012 struct yaffs_obj *yaffs_find_or_create_by_number(struct yaffs_dev *dev,
2013                                                  int number,
2014                                                  enum yaffs_obj_type type)
2015 {
2016         struct yaffs_obj *the_obj = NULL;
2017
2018         if (number > 0)
2019                 the_obj = yaffs_find_by_number(dev, number);
2020
2021         if (!the_obj)
2022                 the_obj = yaffs_new_obj(dev, number, type);
2023
2024         return the_obj;
2025
2026 }
2027
2028 YCHAR *yaffs_clone_str(const YCHAR *str)
2029 {
2030         YCHAR *new_str = NULL;
2031         int len;
2032
2033         if (!str)
2034                 str = _Y("");
2035
2036         len = strnlen(str, YAFFS_MAX_ALIAS_LENGTH);
2037         new_str = kmalloc((len + 1) * sizeof(YCHAR), GFP_NOFS);
2038         if (new_str) {
2039                 strncpy(new_str, str, len);
2040                 new_str[len] = 0;
2041         }
2042         return new_str;
2043
2044 }
2045 /*
2046  *yaffs_update_parent() handles fixing a directories mtime and ctime when a new
2047  * link (ie. name) is created or deleted in the directory.
2048  *
2049  * ie.
2050  *   create dir/a : update dir's mtime/ctime
2051  *   rm dir/a:   update dir's mtime/ctime
2052  *   modify dir/a: don't update dir's mtimme/ctime
2053  *
2054  * This can be handled immediately or defered. Defering helps reduce the number
2055  * of updates when many files in a directory are changed within a brief period.
2056  *
2057  * If the directory updating is defered then yaffs_update_dirty_dirs must be
2058  * called periodically.
2059  */
2060
2061 static void yaffs_update_parent(struct yaffs_obj *obj)
2062 {
2063         struct yaffs_dev *dev;
2064
2065         if (!obj)
2066                 return;
2067         dev = obj->my_dev;
2068         obj->dirty = 1;
2069         yaffs_load_current_time(obj, 0, 1);
2070         if (dev->param.defered_dir_update) {
2071                 struct list_head *link = &obj->variant.dir_variant.dirty;
2072
2073                 if (list_empty(link)) {
2074                         list_add(link, &dev->dirty_dirs);
2075                         yaffs_trace(YAFFS_TRACE_BACKGROUND,
2076                           "Added object %d to dirty directories",
2077                            obj->obj_id);
2078                 }
2079
2080         } else {
2081                 yaffs_update_oh(obj, NULL, 0, 0, 0, NULL);
2082         }
2083 }
2084
2085 void yaffs_update_dirty_dirs(struct yaffs_dev *dev)
2086 {
2087         struct list_head *link;
2088         struct yaffs_obj *obj;
2089         struct yaffs_dir_var *d_s;
2090         union yaffs_obj_var *o_v;
2091
2092         yaffs_trace(YAFFS_TRACE_BACKGROUND, "Update dirty directories");
2093
2094         while (!list_empty(&dev->dirty_dirs)) {
2095                 link = dev->dirty_dirs.next;
2096                 list_del_init(link);
2097
2098                 d_s = list_entry(link, struct yaffs_dir_var, dirty);
2099                 o_v = list_entry(d_s, union yaffs_obj_var, dir_variant);
2100                 obj = list_entry(o_v, struct yaffs_obj, variant);
2101
2102                 yaffs_trace(YAFFS_TRACE_BACKGROUND, "Update directory %d",
2103                         obj->obj_id);
2104
2105                 if (obj->dirty)
2106                         yaffs_update_oh(obj, NULL, 0, 0, 0, NULL);
2107         }
2108 }
2109
2110 /*
2111  * Mknod (create) a new object.
2112  * equiv_obj only has meaning for a hard link;
2113  * alias_str only has meaning for a symlink.
2114  * rdev only has meaning for devices (a subset of special objects)
2115  */
2116
2117 static struct yaffs_obj *yaffs_create_obj(enum yaffs_obj_type type,
2118                                           struct yaffs_obj *parent,
2119                                           const YCHAR *name,
2120                                           u32 mode,
2121                                           u32 uid,
2122                                           u32 gid,
2123                                           struct yaffs_obj *equiv_obj,
2124                                           const YCHAR *alias_str, u32 rdev)
2125 {
2126         struct yaffs_obj *in;
2127         YCHAR *str = NULL;
2128         struct yaffs_dev *dev = parent->my_dev;
2129
2130         /* Check if the entry exists.
2131          * If it does then fail the call since we don't want a dup. */
2132         if (yaffs_find_by_name(parent, name))
2133                 return NULL;
2134
2135         if (type == YAFFS_OBJECT_TYPE_SYMLINK) {
2136                 str = yaffs_clone_str(alias_str);
2137                 if (!str)
2138                         return NULL;
2139         }
2140
2141         in = yaffs_new_obj(dev, -1, type);
2142
2143         if (!in) {
2144                 kfree(str);
2145                 return NULL;
2146         }
2147
2148         in->hdr_chunk = 0;
2149         in->valid = 1;
2150         in->variant_type = type;
2151
2152         in->yst_mode = mode;
2153
2154         yaffs_attribs_init(in, gid, uid, rdev);
2155
2156         in->n_data_chunks = 0;
2157
2158         yaffs_set_obj_name(in, name);
2159         in->dirty = 1;
2160
2161         yaffs_add_obj_to_dir(parent, in);
2162
2163         in->my_dev = parent->my_dev;
2164
2165         switch (type) {
2166         case YAFFS_OBJECT_TYPE_SYMLINK:
2167                 in->variant.symlink_variant.alias = str;
2168                 break;
2169         case YAFFS_OBJECT_TYPE_HARDLINK:
2170                 in->variant.hardlink_variant.equiv_obj = equiv_obj;
2171                 in->variant.hardlink_variant.equiv_id = equiv_obj->obj_id;
2172                 list_add(&in->hard_links, &equiv_obj->hard_links);
2173                 break;
2174         case YAFFS_OBJECT_TYPE_FILE:
2175         case YAFFS_OBJECT_TYPE_DIRECTORY:
2176         case YAFFS_OBJECT_TYPE_SPECIAL:
2177         case YAFFS_OBJECT_TYPE_UNKNOWN:
2178                 /* do nothing */
2179                 break;
2180         }
2181
2182         if (yaffs_update_oh(in, name, 0, 0, 0, NULL) < 0) {
2183                 /* Could not create the object header, fail */
2184                 yaffs_del_obj(in);
2185                 in = NULL;
2186         }
2187
2188         if (in)
2189                 yaffs_update_parent(parent);
2190
2191         return in;
2192 }
2193
2194 struct yaffs_obj *yaffs_create_file(struct yaffs_obj *parent,
2195                                     const YCHAR *name, u32 mode, u32 uid,
2196                                     u32 gid)
2197 {
2198         return yaffs_create_obj(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2199                                 uid, gid, NULL, NULL, 0);
2200 }
2201
2202 struct yaffs_obj *yaffs_create_dir(struct yaffs_obj *parent, const YCHAR *name,
2203                                    u32 mode, u32 uid, u32 gid)
2204 {
2205         return yaffs_create_obj(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2206                                 mode, uid, gid, NULL, NULL, 0);
2207 }
2208
2209 struct yaffs_obj *yaffs_create_special(struct yaffs_obj *parent,
2210                                        const YCHAR *name, u32 mode, u32 uid,
2211                                        u32 gid, u32 rdev)
2212 {
2213         return yaffs_create_obj(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2214                                 uid, gid, NULL, NULL, rdev);
2215 }
2216
2217 struct yaffs_obj *yaffs_create_symlink(struct yaffs_obj *parent,
2218                                        const YCHAR *name, u32 mode, u32 uid,
2219                                        u32 gid, const YCHAR *alias)
2220 {
2221         return yaffs_create_obj(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2222                                 uid, gid, NULL, alias, 0);
2223 }
2224
2225 /* yaffs_link_obj returns the object id of the equivalent object.*/
2226 struct yaffs_obj *yaffs_link_obj(struct yaffs_obj *parent, const YCHAR * name,
2227                                  struct yaffs_obj *equiv_obj)
2228 {
2229         /* Get the real object in case we were fed a hard link obj */
2230         equiv_obj = yaffs_get_equivalent_obj(equiv_obj);
2231
2232         if (yaffs_create_obj(YAFFS_OBJECT_TYPE_HARDLINK,
2233                         parent, name, 0, 0, 0,
2234                         equiv_obj, NULL, 0))
2235                 return equiv_obj;
2236
2237         return NULL;
2238
2239 }
2240
2241
2242
2243 /*---------------------- Block Management and Page Allocation -------------*/
2244
2245 static void yaffs_deinit_blocks(struct yaffs_dev *dev)
2246 {
2247         if (dev->block_info_alt && dev->block_info)
2248                 vfree(dev->block_info);
2249         else
2250                 kfree(dev->block_info);
2251
2252         dev->block_info_alt = 0;
2253
2254         dev->block_info = NULL;
2255
2256         if (dev->chunk_bits_alt && dev->chunk_bits)
2257                 vfree(dev->chunk_bits);
2258         else
2259                 kfree(dev->chunk_bits);
2260         dev->chunk_bits_alt = 0;
2261         dev->chunk_bits = NULL;
2262 }
2263
2264 static int yaffs_init_blocks(struct yaffs_dev *dev)
2265 {
2266         int n_blocks = dev->internal_end_block - dev->internal_start_block + 1;
2267
2268         dev->block_info = NULL;
2269         dev->chunk_bits = NULL;
2270         dev->alloc_block = -1;  /* force it to get a new one */
2271
2272         /* If the first allocation strategy fails, thry the alternate one */
2273         dev->block_info =
2274                 kmalloc(n_blocks * sizeof(struct yaffs_block_info), GFP_NOFS);
2275         if (!dev->block_info) {
2276                 dev->block_info =
2277                     vmalloc(n_blocks * sizeof(struct yaffs_block_info));
2278                 dev->block_info_alt = 1;
2279         } else {
2280                 dev->block_info_alt = 0;
2281         }
2282
2283         if (!dev->block_info)
2284                 goto alloc_error;
2285
2286         /* Set up dynamic blockinfo stuff. Round up bytes. */
2287         dev->chunk_bit_stride = (dev->param.chunks_per_block + 7) / 8;
2288         dev->chunk_bits =
2289                 kmalloc(dev->chunk_bit_stride * n_blocks, GFP_NOFS);
2290         if (!dev->chunk_bits) {
2291                 dev->chunk_bits =
2292                     vmalloc(dev->chunk_bit_stride * n_blocks);
2293                 dev->chunk_bits_alt = 1;
2294         } else {
2295                 dev->chunk_bits_alt = 0;
2296         }
2297         if (!dev->chunk_bits)
2298                 goto alloc_error;
2299
2300
2301         memset(dev->block_info, 0, n_blocks * sizeof(struct yaffs_block_info));
2302         memset(dev->chunk_bits, 0, dev->chunk_bit_stride * n_blocks);
2303         return YAFFS_OK;
2304
2305 alloc_error:
2306         yaffs_deinit_blocks(dev);
2307         return YAFFS_FAIL;
2308 }
2309
2310
2311 void yaffs_block_became_dirty(struct yaffs_dev *dev, int block_no)
2312 {
2313         struct yaffs_block_info *bi = yaffs_get_block_info(dev, block_no);
2314         int erased_ok = 0;
2315         int i;
2316
2317         /* If the block is still healthy erase it and mark as clean.
2318          * If the block has had a data failure, then retire it.
2319          */
2320
2321         yaffs_trace(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2322                 "yaffs_block_became_dirty block %d state %d %s",
2323                 block_no, bi->block_state,
2324                 (bi->needs_retiring) ? "needs retiring" : "");
2325
2326         yaffs2_clear_oldest_dirty_seq(dev, bi);
2327
2328         bi->block_state = YAFFS_BLOCK_STATE_DIRTY;
2329
2330         /* If this is the block being garbage collected then stop gc'ing */
2331         if (block_no == dev->gc_block)
2332                 dev->gc_block = 0;
2333
2334         /* If this block is currently the best candidate for gc
2335          * then drop as a candidate */
2336         if (block_no == dev->gc_dirtiest) {
2337                 dev->gc_dirtiest = 0;
2338                 dev->gc_pages_in_use = 0;
2339         }
2340
2341         if (!bi->needs_retiring) {
2342                 yaffs2_checkpt_invalidate(dev);
2343                 erased_ok = yaffs_erase_block(dev, block_no);
2344                 if (!erased_ok) {
2345                         dev->n_erase_failures++;
2346                         yaffs_trace(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2347                           "**>> Erasure failed %d", block_no);
2348                 }
2349         }
2350
2351         /* Verify erasure if needed */
2352         if (erased_ok &&
2353             ((yaffs_trace_mask & YAFFS_TRACE_ERASE) ||
2354              !yaffs_skip_verification(dev))) {
2355                 for (i = 0; i < dev->param.chunks_per_block; i++) {
2356                         if (!yaffs_check_chunk_erased(dev,
2357                                 block_no * dev->param.chunks_per_block + i)) {
2358                                 yaffs_trace(YAFFS_TRACE_ERROR,
2359                                         ">>Block %d erasure supposedly OK, but chunk %d not erased",
2360                                         block_no, i);
2361                         }
2362                 }
2363         }
2364
2365         if (!erased_ok) {
2366                 /* We lost a block of free space */
2367                 dev->n_free_chunks -= dev->param.chunks_per_block;
2368                 yaffs_retire_block(dev, block_no);
2369                 yaffs_trace(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2370                         "**>> Block %d retired", block_no);
2371                 return;
2372         }
2373
2374         /* Clean it up... */
2375         bi->block_state = YAFFS_BLOCK_STATE_EMPTY;
2376         bi->seq_number = 0;
2377         dev->n_erased_blocks++;
2378         bi->pages_in_use = 0;
2379         bi->soft_del_pages = 0;
2380         bi->has_shrink_hdr = 0;
2381         bi->skip_erased_check = 1;      /* Clean, so no need to check */
2382         bi->gc_prioritise = 0;
2383         yaffs_clear_chunk_bits(dev, block_no);
2384
2385         yaffs_trace(YAFFS_TRACE_ERASE, "Erased block %d", block_no);
2386 }
2387
2388 static inline int yaffs_gc_process_chunk(struct yaffs_dev *dev,
2389                                         struct yaffs_block_info *bi,
2390                                         int old_chunk, u8 *buffer)
2391 {
2392         int new_chunk;
2393         int mark_flash = 1;
2394         struct yaffs_ext_tags tags;
2395         struct yaffs_obj *object;
2396         int matching_chunk;
2397         int ret_val = YAFFS_OK;
2398
2399         memset(&tags, 0, sizeof(tags));
2400         yaffs_rd_chunk_tags_nand(dev, old_chunk,
2401                                  buffer, &tags);
2402         object = yaffs_find_by_number(dev, tags.obj_id);
2403
2404         yaffs_trace(YAFFS_TRACE_GC_DETAIL,
2405                 "Collecting chunk in block %d, %d %d %d ",
2406                 dev->gc_chunk, tags.obj_id,
2407                 tags.chunk_id, tags.n_bytes);
2408
2409         if (object && !yaffs_skip_verification(dev)) {
2410                 if (tags.chunk_id == 0)
2411                         matching_chunk =
2412                             object->hdr_chunk;
2413                 else if (object->soft_del)
2414                         /* Defeat the test */
2415                         matching_chunk = old_chunk;
2416                 else
2417                         matching_chunk =
2418                             yaffs_find_chunk_in_file
2419                             (object, tags.chunk_id,
2420                              NULL);
2421
2422                 if (old_chunk != matching_chunk)
2423                         yaffs_trace(YAFFS_TRACE_ERROR,
2424                                 "gc: page in gc mismatch: %d %d %d %d",
2425                                 old_chunk,
2426                                 matching_chunk,
2427                                 tags.obj_id,
2428                                 tags.chunk_id);
2429         }
2430
2431         if (!object) {
2432                 yaffs_trace(YAFFS_TRACE_ERROR,
2433                         "page %d in gc has no object: %d %d %d ",
2434                         old_chunk,
2435                         tags.obj_id, tags.chunk_id,
2436                         tags.n_bytes);
2437         }
2438
2439         if (object &&
2440             object->deleted &&
2441             object->soft_del && tags.chunk_id != 0) {
2442                 /* Data chunk in a soft deleted file,
2443                  * throw it away.
2444                  * It's a soft deleted data chunk,
2445                  * No need to copy this, just forget
2446                  * about it and fix up the object.
2447                  */
2448
2449                 /* Free chunks already includes
2450                  * softdeleted chunks, how ever this
2451                  * chunk is going to soon be really
2452                  * deleted which will increment free
2453                  * chunks. We have to decrement free
2454                  * chunks so this works out properly.
2455                  */
2456                 dev->n_free_chunks--;
2457                 bi->soft_del_pages--;
2458
2459                 object->n_data_chunks--;
2460                 if (object->n_data_chunks <= 0) {
2461                         /* remeber to clean up obj */
2462                         dev->gc_cleanup_list[dev->n_clean_ups] = tags.obj_id;
2463                         dev->n_clean_ups++;
2464                 }
2465                 mark_flash = 0;
2466         } else if (object) {
2467                 /* It's either a data chunk in a live
2468                  * file or an ObjectHeader, so we're
2469                  * interested in it.
2470                  * NB Need to keep the ObjectHeaders of
2471                  * deleted files until the whole file
2472                  * has been deleted off
2473                  */
2474                 tags.serial_number++;
2475                 dev->n_gc_copies++;
2476
2477                 if (tags.chunk_id == 0) {
2478                         /* It is an object Id,
2479                          * We need to nuke the
2480                          * shrinkheader flags since its
2481                          * work is done.
2482                          * Also need to clean up
2483                          * shadowing.
2484                          */
2485                         struct yaffs_obj_hdr *oh;
2486                         oh = (struct yaffs_obj_hdr *) buffer;
2487
2488                         oh->is_shrink = 0;
2489                         tags.extra_is_shrink = 0;
2490                         oh->shadows_obj = 0;
2491                         oh->inband_shadowed_obj_id = 0;
2492                         tags.extra_shadows = 0;
2493
2494                         /* Update file size */
2495                         if (object->variant_type == YAFFS_OBJECT_TYPE_FILE) {
2496                                 oh->file_size =
2497                                     object->variant.file_variant.file_size;
2498                                 tags.extra_length = oh->file_size;
2499                         }
2500
2501                         yaffs_verify_oh(object, oh, &tags, 1);
2502                         new_chunk =
2503                             yaffs_write_new_chunk(dev, (u8 *) oh, &tags, 1);
2504                 } else {
2505                         new_chunk =
2506                             yaffs_write_new_chunk(dev, buffer, &tags, 1);
2507                 }
2508
2509                 if (new_chunk < 0) {
2510                         ret_val = YAFFS_FAIL;
2511                 } else {
2512
2513                         /* Now fix up the Tnodes etc. */
2514
2515                         if (tags.chunk_id == 0) {
2516                                 /* It's a header */
2517                                 object->hdr_chunk = new_chunk;
2518                                 object->serial = tags.serial_number;
2519                         } else {
2520                                 /* It's a data chunk */
2521                                 yaffs_put_chunk_in_file(object, tags.chunk_id,
2522                                                         new_chunk, 0);
2523                         }
2524                 }
2525         }
2526         if (ret_val == YAFFS_OK)
2527                 yaffs_chunk_del(dev, old_chunk, mark_flash, __LINE__);
2528         return ret_val;
2529 }
2530
2531 static int yaffs_gc_block(struct yaffs_dev *dev, int block, int whole_block)
2532 {
2533         int old_chunk;
2534         int ret_val = YAFFS_OK;
2535         int i;
2536         int is_checkpt_block;
2537         int max_copies;
2538         int chunks_before = yaffs_get_erased_chunks(dev);
2539         int chunks_after;
2540         struct yaffs_block_info *bi = yaffs_get_block_info(dev, block);
2541
2542         is_checkpt_block = (bi->block_state == YAFFS_BLOCK_STATE_CHECKPOINT);
2543
2544         yaffs_trace(YAFFS_TRACE_TRACING,
2545                 "Collecting block %d, in use %d, shrink %d, whole_block %d",
2546                 block, bi->pages_in_use, bi->has_shrink_hdr,
2547                 whole_block);
2548
2549         /*yaffs_verify_free_chunks(dev); */
2550
2551         if (bi->block_state == YAFFS_BLOCK_STATE_FULL)
2552                 bi->block_state = YAFFS_BLOCK_STATE_COLLECTING;
2553
2554         bi->has_shrink_hdr = 0; /* clear the flag so that the block can erase */
2555
2556         dev->gc_disable = 1;
2557
2558         if (is_checkpt_block || !yaffs_still_some_chunks(dev, block)) {
2559                 yaffs_trace(YAFFS_TRACE_TRACING,
2560                         "Collecting block %d that has no chunks in use",
2561                         block);
2562                 yaffs_block_became_dirty(dev, block);
2563         } else {
2564
2565                 u8 *buffer = yaffs_get_temp_buffer(dev);
2566
2567                 yaffs_verify_blk(dev, bi, block);
2568
2569                 max_copies = (whole_block) ? dev->param.chunks_per_block : 5;
2570                 old_chunk = block * dev->param.chunks_per_block + dev->gc_chunk;
2571
2572                 for (/* init already done */ ;
2573                      ret_val == YAFFS_OK &&
2574                      dev->gc_chunk < dev->param.chunks_per_block &&
2575                      (bi->block_state == YAFFS_BLOCK_STATE_COLLECTING) &&
2576                      max_copies > 0;
2577                      dev->gc_chunk++, old_chunk++) {
2578                         if (yaffs_check_chunk_bit(dev, block, dev->gc_chunk)) {
2579                                 /* Page is in use and might need to be copied */
2580                                 max_copies--;
2581                                 ret_val = yaffs_gc_process_chunk(dev, bi,
2582                                                         old_chunk, buffer);
2583                         }
2584                 }
2585                 yaffs_release_temp_buffer(dev, buffer);
2586         }
2587
2588         yaffs_verify_collected_blk(dev, bi, block);
2589
2590         if (bi->block_state == YAFFS_BLOCK_STATE_COLLECTING) {
2591                 /*
2592                  * The gc did not complete. Set block state back to FULL
2593                  * because checkpointing does not restore gc.
2594                  */
2595                 bi->block_state = YAFFS_BLOCK_STATE_FULL;
2596         } else {
2597                 /* The gc completed. */
2598                 /* Do any required cleanups */
2599                 for (i = 0; i < dev->n_clean_ups; i++) {
2600                         /* Time to delete the file too */
2601                         struct yaffs_obj *object =
2602                             yaffs_find_by_number(dev, dev->gc_cleanup_list[i]);
2603                         if (object) {
2604                                 yaffs_free_tnode(dev,
2605                                           object->variant.file_variant.top);
2606                                 object->variant.file_variant.top = NULL;
2607                                 yaffs_trace(YAFFS_TRACE_GC,
2608                                         "yaffs: About to finally delete object %d",
2609                                         object->obj_id);
2610                                 yaffs_generic_obj_del(object);
2611                                 object->my_dev->n_deleted_files--;
2612                         }
2613
2614                 }
2615                 chunks_after = yaffs_get_erased_chunks(dev);
2616                 if (chunks_before >= chunks_after)
2617                         yaffs_trace(YAFFS_TRACE_GC,
2618                                 "gc did not increase free chunks before %d after %d",
2619                                 chunks_before, chunks_after);
2620                 dev->gc_block = 0;
2621                 dev->gc_chunk = 0;
2622                 dev->n_clean_ups = 0;
2623         }
2624
2625         dev->gc_disable = 0;
2626
2627         return ret_val;
2628 }
2629
2630 /*
2631  * find_gc_block() selects the dirtiest block (or close enough)
2632  * for garbage collection.
2633  */
2634
2635 static unsigned yaffs_find_gc_block(struct yaffs_dev *dev,
2636                                     int aggressive, int background)
2637 {
2638         int i;
2639         int iterations;
2640         unsigned selected = 0;
2641         int prioritised = 0;
2642         int prioritised_exist = 0;
2643         struct yaffs_block_info *bi;
2644         int threshold;
2645
2646         /* First let's see if we need to grab a prioritised block */
2647         if (dev->has_pending_prioritised_gc && !aggressive) {
2648                 dev->gc_dirtiest = 0;
2649                 bi = dev->block_info;
2650                 for (i = dev->internal_start_block;
2651                      i <= dev->internal_end_block && !selected; i++) {
2652
2653                         if (bi->gc_prioritise) {
2654                                 prioritised_exist = 1;
2655                                 if (bi->block_state == YAFFS_BLOCK_STATE_FULL &&
2656                                     yaffs_block_ok_for_gc(dev, bi)) {
2657                                         selected = i;
2658                                         prioritised = 1;
2659                                 }
2660                         }
2661                         bi++;
2662                 }
2663
2664                 /*
2665                  * If there is a prioritised block and none was selected then
2666                  * this happened because there is at least one old dirty block
2667                  * gumming up the works. Let's gc the oldest dirty block.
2668                  */
2669
2670                 if (prioritised_exist &&
2671                     !selected && dev->oldest_dirty_block > 0)
2672                         selected = dev->oldest_dirty_block;
2673
2674                 if (!prioritised_exist) /* None found, so we can clear this */
2675                         dev->has_pending_prioritised_gc = 0;
2676         }
2677
2678         /* If we're doing aggressive GC then we are happy to take a less-dirty
2679          * block, and search harder.
2680          * else (leasurely gc), then we only bother to do this if the
2681          * block has only a few pages in use.
2682          */
2683
2684         if (!selected) {
2685                 int pages_used;
2686                 int n_blocks =
2687                     dev->internal_end_block - dev->internal_start_block + 1;
2688                 if (aggressive) {
2689                         threshold = dev->param.chunks_per_block;
2690                         iterations = n_blocks;
2691                 } else {
2692                         int max_threshold;
2693
2694                         if (background)
2695                                 max_threshold = dev->param.chunks_per_block / 2;
2696                         else
2697                                 max_threshold = dev->param.chunks_per_block / 8;
2698
2699                         if (max_threshold < YAFFS_GC_PASSIVE_THRESHOLD)
2700                                 max_threshold = YAFFS_GC_PASSIVE_THRESHOLD;
2701
2702                         threshold = background ? (dev->gc_not_done + 2) * 2 : 0;
2703                         if (threshold < YAFFS_GC_PASSIVE_THRESHOLD)
2704                                 threshold = YAFFS_GC_PASSIVE_THRESHOLD;
2705                         if (threshold > max_threshold)
2706                                 threshold = max_threshold;
2707
2708                         iterations = n_blocks / 16 + 1;
2709                         if (iterations > 100)
2710                                 iterations = 100;
2711                 }
2712
2713                 for (i = 0;
2714                      i < iterations &&
2715                      (dev->gc_dirtiest < 1 ||
2716                       dev->gc_pages_in_use > YAFFS_GC_GOOD_ENOUGH);
2717                      i++) {
2718                         dev->gc_block_finder++;
2719                         if (dev->gc_block_finder < dev->internal_start_block ||
2720                             dev->gc_block_finder > dev->internal_end_block)
2721                                 dev->gc_block_finder =
2722                                     dev->internal_start_block;
2723
2724                         bi = yaffs_get_block_info(dev, dev->gc_block_finder);
2725
2726                         pages_used = bi->pages_in_use - bi->soft_del_pages;
2727
2728                         if (bi->block_state == YAFFS_BLOCK_STATE_FULL &&
2729                             pages_used < dev->param.chunks_per_block &&
2730                             (dev->gc_dirtiest < 1 ||
2731                              pages_used < dev->gc_pages_in_use) &&
2732                             yaffs_block_ok_for_gc(dev, bi)) {
2733                                 dev->gc_dirtiest = dev->gc_block_finder;
2734                                 dev->gc_pages_in_use = pages_used;
2735                         }
2736                 }
2737
2738                 if (dev->gc_dirtiest > 0 && dev->gc_pages_in_use <= threshold)
2739                         selected = dev->gc_dirtiest;
2740         }
2741
2742         /*
2743          * If nothing has been selected for a while, try the oldest dirty
2744          * because that's gumming up the works.
2745          */
2746
2747         if (!selected && dev->param.is_yaffs2 &&
2748             dev->gc_not_done >= (background ? 10 : 20)) {
2749                 yaffs2_find_oldest_dirty_seq(dev);
2750                 if (dev->oldest_dirty_block > 0) {
2751                         selected = dev->oldest_dirty_block;
2752                         dev->gc_dirtiest = selected;
2753                         dev->oldest_dirty_gc_count++;
2754                         bi = yaffs_get_block_info(dev, selected);
2755                         dev->gc_pages_in_use =
2756                             bi->pages_in_use - bi->soft_del_pages;
2757                 } else {
2758                         dev->gc_not_done = 0;
2759                 }
2760         }
2761
2762         if (selected) {
2763                 yaffs_trace(YAFFS_TRACE_GC,
2764                         "GC Selected block %d with %d free, prioritised:%d",
2765                         selected,
2766                         dev->param.chunks_per_block - dev->gc_pages_in_use,
2767                         prioritised);
2768
2769                 dev->n_gc_blocks++;
2770                 if (background)
2771                         dev->bg_gcs++;
2772
2773                 dev->gc_dirtiest = 0;
2774                 dev->gc_pages_in_use = 0;
2775                 dev->gc_not_done = 0;
2776                 if (dev->refresh_skip > 0)
2777                         dev->refresh_skip--;
2778         } else {
2779                 dev->gc_not_done++;
2780                 yaffs_trace(YAFFS_TRACE_GC,
2781                         "GC none: finder %d skip %d threshold %d dirtiest %d using %d oldest %d%s",
2782                         dev->gc_block_finder, dev->gc_not_done, threshold,
2783                         dev->gc_dirtiest, dev->gc_pages_in_use,
2784                         dev->oldest_dirty_block, background ? " bg" : "");
2785         }
2786
2787         return selected;
2788 }
2789
2790 /* New garbage collector
2791  * If we're very low on erased blocks then we do aggressive garbage collection
2792  * otherwise we do "leasurely" garbage collection.
2793  * Aggressive gc looks further (whole array) and will accept less dirty blocks.
2794  * Passive gc only inspects smaller areas and only accepts more dirty blocks.
2795  *
2796  * The idea is to help clear out space in a more spread-out manner.
2797  * Dunno if it really does anything useful.
2798  */
2799 static int yaffs_check_gc(struct yaffs_dev *dev, int background)
2800 {
2801         int aggressive = 0;
2802         int gc_ok = YAFFS_OK;
2803         int max_tries = 0;
2804         int min_erased;
2805         int erased_chunks;
2806         int checkpt_block_adjust;
2807
2808         if (dev->param.gc_control && (dev->param.gc_control(dev) & 1) == 0)
2809                 return YAFFS_OK;
2810
2811         if (dev->gc_disable)
2812                 /* Bail out so we don't get recursive gc */
2813                 return YAFFS_OK;
2814
2815         /* This loop should pass the first time.
2816          * Only loops here if the collection does not increase space.
2817          */
2818
2819         do {
2820                 max_tries++;
2821
2822                 checkpt_block_adjust = yaffs_calc_checkpt_blocks_required(dev);
2823
2824                 min_erased =
2825                     dev->param.n_reserved_blocks + checkpt_block_adjust + 1;
2826                 erased_chunks =
2827                     dev->n_erased_blocks * dev->param.chunks_per_block;
2828
2829                 /* If we need a block soon then do aggressive gc. */
2830                 if (dev->n_erased_blocks < min_erased)
2831                         aggressive = 1;
2832                 else {
2833                         if (!background
2834                             && erased_chunks > (dev->n_free_chunks / 4))
2835                                 break;
2836
2837                         if (dev->gc_skip > 20)
2838                                 dev->gc_skip = 20;
2839                         if (erased_chunks < dev->n_free_chunks / 2 ||
2840                             dev->gc_skip < 1 || background)
2841                                 aggressive = 0;
2842                         else {
2843                                 dev->gc_skip--;
2844                                 break;
2845                         }
2846                 }
2847
2848                 dev->gc_skip = 5;
2849
2850                 /* If we don't already have a block being gc'd then see if we
2851                  * should start another */
2852
2853                 if (dev->gc_block < 1 && !aggressive) {
2854                         dev->gc_block = yaffs2_find_refresh_block(dev);
2855                         dev->gc_chunk = 0;
2856                         dev->n_clean_ups = 0;
2857                 }
2858                 if (dev->gc_block < 1) {
2859                         dev->gc_block =
2860                             yaffs_find_gc_block(dev, aggressive, background);
2861                         dev->gc_chunk = 0;
2862                         dev->n_clean_ups = 0;
2863                 }
2864
2865                 if (dev->gc_block > 0) {
2866                         dev->all_gcs++;
2867                         if (!aggressive)
2868                                 dev->passive_gc_count++;
2869
2870                         yaffs_trace(YAFFS_TRACE_GC,
2871                                 "yaffs: GC n_erased_blocks %d aggressive %d",
2872                                 dev->n_erased_blocks, aggressive);
2873
2874                         gc_ok = yaffs_gc_block(dev, dev->gc_block, aggressive);
2875                 }
2876
2877                 if (dev->n_erased_blocks < (dev->param.n_reserved_blocks) &&
2878                     dev->gc_block > 0) {
2879                         yaffs_trace(YAFFS_TRACE_GC,
2880                                 "yaffs: GC !!!no reclaim!!! n_erased_blocks %d after try %d block %d",
2881                                 dev->n_erased_blocks, max_tries,
2882                                 dev->gc_block);
2883                 }
2884         } while ((dev->n_erased_blocks < dev->param.n_reserved_blocks) &&
2885                  (dev->gc_block > 0) && (max_tries < 2));
2886
2887         return aggressive ? gc_ok : YAFFS_OK;
2888 }
2889
2890 /*
2891  * yaffs_bg_gc()
2892  * Garbage collects. Intended to be called from a background thread.
2893  * Returns non-zero if at least half the free chunks are erased.
2894  */
2895 int yaffs_bg_gc(struct yaffs_dev *dev, unsigned urgency)
2896 {
2897         int erased_chunks = dev->n_erased_blocks * dev->param.chunks_per_block;
2898
2899         yaffs_trace(YAFFS_TRACE_BACKGROUND, "Background gc %u", urgency);
2900
2901         yaffs_check_gc(dev, 1);
2902         return erased_chunks > dev->n_free_chunks / 2;
2903 }
2904
2905 /*-------------------- Data file manipulation -----------------*/
2906
2907 static int yaffs_rd_data_obj(struct yaffs_obj *in, int inode_chunk, u8 * buffer)
2908 {
2909         int nand_chunk = yaffs_find_chunk_in_file(in, inode_chunk, NULL);
2910
2911         if (nand_chunk >= 0)
2912                 return yaffs_rd_chunk_tags_nand(in->my_dev, nand_chunk,
2913                                                 buffer, NULL);
2914         else {
2915                 yaffs_trace(YAFFS_TRACE_NANDACCESS,
2916                         "Chunk %d not found zero instead",
2917                         nand_chunk);
2918                 /* get sane (zero) data if you read a hole */
2919                 memset(buffer, 0, in->my_dev->data_bytes_per_chunk);
2920                 return 0;
2921         }
2922
2923 }
2924
2925 void yaffs_chunk_del(struct yaffs_dev *dev, int chunk_id, int mark_flash,
2926                      int lyn)
2927 {
2928         int block;
2929         int page;
2930         struct yaffs_ext_tags tags;
2931         struct yaffs_block_info *bi;
2932
2933         if (chunk_id <= 0)
2934                 return;
2935
2936         dev->n_deletions++;
2937         block = chunk_id / dev->param.chunks_per_block;
2938         page = chunk_id % dev->param.chunks_per_block;
2939
2940         if (!yaffs_check_chunk_bit(dev, block, page))
2941                 yaffs_trace(YAFFS_TRACE_VERIFY,
2942                         "Deleting invalid chunk %d", chunk_id);
2943
2944         bi = yaffs_get_block_info(dev, block);
2945
2946         yaffs2_update_oldest_dirty_seq(dev, block, bi);
2947
2948         yaffs_trace(YAFFS_TRACE_DELETION,
2949                 "line %d delete of chunk %d",
2950                 lyn, chunk_id);
2951
2952         if (!dev->param.is_yaffs2 && mark_flash &&
2953             bi->block_state != YAFFS_BLOCK_STATE_COLLECTING) {
2954
2955                 memset(&tags, 0, sizeof(tags));
2956                 tags.is_deleted = 1;
2957                 yaffs_wr_chunk_tags_nand(dev, chunk_id, NULL, &tags);
2958                 yaffs_handle_chunk_update(dev, chunk_id, &tags);
2959         } else {
2960                 dev->n_unmarked_deletions++;
2961         }
2962
2963         /* Pull out of the management area.
2964          * If the whole block became dirty, this will kick off an erasure.
2965          */
2966         if (bi->block_state == YAFFS_BLOCK_STATE_ALLOCATING ||
2967             bi->block_state == YAFFS_BLOCK_STATE_FULL ||
2968             bi->block_state == YAFFS_BLOCK_STATE_NEEDS_SCAN ||
2969             bi->block_state == YAFFS_BLOCK_STATE_COLLECTING) {
2970                 dev->n_free_chunks++;
2971                 yaffs_clear_chunk_bit(dev, block, page);
2972                 bi->pages_in_use--;
2973
2974                 if (bi->pages_in_use == 0 &&
2975                     !bi->has_shrink_hdr &&
2976                     bi->block_state != YAFFS_BLOCK_STATE_ALLOCATING &&
2977                     bi->block_state != YAFFS_BLOCK_STATE_NEEDS_SCAN) {
2978                         yaffs_block_became_dirty(dev, block);
2979                 }
2980         }
2981 }
2982
2983 static int yaffs_wr_data_obj(struct yaffs_obj *in, int inode_chunk,
2984                              const u8 *buffer, int n_bytes, int use_reserve)
2985 {
2986         /* Find old chunk Need to do this to get serial number
2987          * Write new one and patch into tree.
2988          * Invalidate old tags.
2989          */
2990
2991         int prev_chunk_id;
2992         struct yaffs_ext_tags prev_tags;
2993         int new_chunk_id;
2994         struct yaffs_ext_tags new_tags;
2995         struct yaffs_dev *dev = in->my_dev;
2996
2997         yaffs_check_gc(dev, 0);
2998
2999         /* Get the previous chunk at this location in the file if it exists.
3000          * If it does not exist then put a zero into the tree. This creates
3001          * the tnode now, rather than later when it is harder to clean up.
3002          */
3003         prev_chunk_id = yaffs_find_chunk_in_file(in, inode_chunk, &prev_tags);
3004         if (prev_chunk_id < 1 &&
3005             !yaffs_put_chunk_in_file(in, inode_chunk, 0, 0))
3006                 return 0;
3007
3008         /* Set up new tags */
3009         memset(&new_tags, 0, sizeof(new_tags));
3010
3011         new_tags.chunk_id = inode_chunk;
3012         new_tags.obj_id = in->obj_id;
3013         new_tags.serial_number =
3014             (prev_chunk_id > 0) ? prev_tags.serial_number + 1 : 1;
3015         new_tags.n_bytes = n_bytes;
3016
3017         if (n_bytes < 1 || n_bytes > dev->param.total_bytes_per_chunk) {
3018                 yaffs_trace(YAFFS_TRACE_ERROR,
3019                   "Writing %d bytes to chunk!!!!!!!!!",
3020                    n_bytes);
3021                 BUG();
3022         }
3023
3024         new_chunk_id =
3025             yaffs_write_new_chunk(dev, buffer, &new_tags, use_reserve);
3026
3027         if (new_chunk_id > 0) {
3028                 yaffs_put_chunk_in_file(in, inode_chunk, new_chunk_id, 0);
3029
3030                 if (prev_chunk_id > 0)
3031                         yaffs_chunk_del(dev, prev_chunk_id, 1, __LINE__);
3032
3033                 yaffs_verify_file_sane(in);
3034         }
3035         return new_chunk_id;
3036
3037 }
3038
3039
3040
3041 static int yaffs_do_xattrib_mod(struct yaffs_obj *obj, int set,
3042                                 const YCHAR *name, const void *value, int size,
3043                                 int flags)
3044 {
3045         struct yaffs_xattr_mod xmod;
3046         int result;
3047
3048         xmod.set = set;
3049         xmod.name = name;
3050         xmod.data = value;
3051         xmod.size = size;
3052         xmod.flags = flags;
3053         xmod.result = -ENOSPC;
3054
3055         result = yaffs_update_oh(obj, NULL, 0, 0, 0, &xmod);
3056
3057         if (result > 0)
3058                 return xmod.result;
3059         else
3060                 return -ENOSPC;
3061 }
3062
3063 static int yaffs_apply_xattrib_mod(struct yaffs_obj *obj, char *buffer,
3064                                    struct yaffs_xattr_mod *xmod)
3065 {
3066         int retval = 0;
3067         int x_offs = sizeof(struct yaffs_obj_hdr);
3068         struct yaffs_dev *dev = obj->my_dev;
3069         int x_size = dev->data_bytes_per_chunk - sizeof(struct yaffs_obj_hdr);
3070         char *x_buffer = buffer + x_offs;
3071
3072         if (xmod->set)
3073                 retval =
3074                     nval_set(x_buffer, x_size, xmod->name, xmod->data,
3075                              xmod->size, xmod->flags);
3076         else
3077                 retval = nval_del(x_buffer, x_size, xmod->name);
3078
3079         obj->has_xattr = nval_hasvalues(x_buffer, x_size);
3080         obj->xattr_known = 1;
3081         xmod->result = retval;
3082
3083         return retval;
3084 }
3085
3086 static int yaffs_do_xattrib_fetch(struct yaffs_obj *obj, const YCHAR *name,
3087                                   void *value, int size)
3088 {
3089         char *buffer = NULL;
3090         int result;
3091         struct yaffs_ext_tags tags;
3092         struct yaffs_dev *dev = obj->my_dev;
3093         int x_offs = sizeof(struct yaffs_obj_hdr);
3094         int x_size = dev->data_bytes_per_chunk - sizeof(struct yaffs_obj_hdr);
3095         char *x_buffer;
3096         int retval = 0;
3097
3098         if (obj->hdr_chunk < 1)
3099                 return -ENODATA;
3100
3101         /* If we know that the object has no xattribs then don't do all the
3102          * reading and parsing.
3103          */
3104         if (obj->xattr_known && !obj->has_xattr) {
3105                 if (name)
3106                         return -ENODATA;
3107                 else
3108                         return 0;
3109         }
3110
3111         buffer = (char *)yaffs_get_temp_buffer(dev);
3112         if (!buffer)
3113                 return -ENOMEM;
3114
3115         result =
3116             yaffs_rd_chunk_tags_nand(dev, obj->hdr_chunk, (u8 *) buffer, &tags);
3117
3118         if (result != YAFFS_OK)
3119                 retval = -ENOENT;
3120         else {
3121                 x_buffer = buffer + x_offs;
3122
3123                 if (!obj->xattr_known) {
3124                         obj->has_xattr = nval_hasvalues(x_buffer, x_size);
3125                         obj->xattr_known = 1;
3126                 }
3127
3128                 if (name)
3129                         retval = nval_get(x_buffer, x_size, name, value, size);
3130                 else
3131                         retval = nval_list(x_buffer, x_size, value, size);
3132         }
3133         yaffs_release_temp_buffer(dev, (u8 *) buffer);
3134         return retval;
3135 }
3136
3137 int yaffs_set_xattrib(struct yaffs_obj *obj, const YCHAR * name,
3138                       const void *value, int size, int flags)
3139 {
3140         return yaffs_do_xattrib_mod(obj, 1, name, value, size, flags);
3141 }
3142
3143 int yaffs_remove_xattrib(struct yaffs_obj *obj, const YCHAR * name)
3144 {
3145         return yaffs_do_xattrib_mod(obj, 0, name, NULL, 0, 0);
3146 }
3147
3148 int yaffs_get_xattrib(struct yaffs_obj *obj, const YCHAR * name, void *value,
3149                       int size)
3150 {
3151         return yaffs_do_xattrib_fetch(obj, name, value, size);
3152 }
3153
3154 int yaffs_list_xattrib(struct yaffs_obj *obj, char *buffer, int size)
3155 {
3156         return yaffs_do_xattrib_fetch(obj, NULL, buffer, size);
3157 }
3158
3159 static void yaffs_check_obj_details_loaded(struct yaffs_obj *in)
3160 {
3161         u8 *buf;
3162         struct yaffs_obj_hdr *oh;
3163         struct yaffs_dev *dev;
3164         struct yaffs_ext_tags tags;
3165         int result;
3166         int alloc_failed = 0;
3167
3168         if (!in || !in->lazy_loaded || in->hdr_chunk < 1)
3169                 return;
3170
3171         dev = in->my_dev;
3172         in->lazy_loaded = 0;
3173         buf = yaffs_get_temp_buffer(dev);
3174
3175         result = yaffs_rd_chunk_tags_nand(dev, in->hdr_chunk, buf, &tags);
3176         oh = (struct yaffs_obj_hdr *)buf;
3177
3178         in->yst_mode = oh->yst_mode;
3179         yaffs_load_attribs(in, oh);
3180         yaffs_set_obj_name_from_oh(in, oh);
3181
3182         if (in->variant_type == YAFFS_OBJECT_TYPE_SYMLINK) {
3183                 in->variant.symlink_variant.alias =
3184                     yaffs_clone_str(oh->alias);
3185                 if (!in->variant.symlink_variant.alias)
3186                         alloc_failed = 1;       /* Not returned */
3187         }
3188         yaffs_release_temp_buffer(dev, buf);
3189 }
3190
3191 static void yaffs_load_name_from_oh(struct yaffs_dev *dev, YCHAR *name,
3192                                     const YCHAR *oh_name, int buff_size)
3193 {
3194 #ifdef CONFIG_YAFFS_AUTO_UNICODE
3195         if (dev->param.auto_unicode) {
3196                 if (*oh_name) {
3197                         /* It is an ASCII name, do an ASCII to
3198                          * unicode conversion */
3199                         const char *ascii_oh_name = (const char *)oh_name;
3200                         int n = buff_size - 1;
3201                         while (n > 0 && *ascii_oh_name) {
3202                                 *name = *ascii_oh_name;
3203                                 name++;
3204                                 ascii_oh_name++;
3205                                 n--;
3206                         }
3207                 } else {
3208                         strncpy(name, oh_name + 1, buff_size - 1);
3209                 }
3210         } else {
3211 #else
3212         {
3213 #endif
3214                 strncpy(name, oh_name, buff_size - 1);
3215         }
3216 }
3217
3218 static void yaffs_load_oh_from_name(struct yaffs_dev *dev, YCHAR *oh_name,
3219                                     const YCHAR *name)
3220 {
3221 #ifdef CONFIG_YAFFS_AUTO_UNICODE
3222
3223         int is_ascii;
3224         YCHAR *w;
3225
3226         if (dev->param.auto_unicode) {
3227
3228                 is_ascii = 1;
3229                 w = name;
3230
3231                 /* Figure out if the name will fit in ascii character set */
3232                 while (is_ascii && *w) {
3233                         if ((*w) & 0xff00)
3234                                 is_ascii = 0;
3235                         w++;
3236                 }
3237
3238                 if (is_ascii) {
3239                         /* It is an ASCII name, so convert unicode to ascii */
3240                         char *ascii_oh_name = (char *)oh_name;
3241                         int n = YAFFS_MAX_NAME_LENGTH - 1;
3242                         while (n > 0 && *name) {
3243                                 *ascii_oh_name = *name;
3244                                 name++;
3245                                 ascii_oh_name++;
3246                                 n--;
3247                         }
3248                 } else {
3249                         /* Unicode name, so save starting at the second YCHAR */
3250                         *oh_name = 0;
3251                         strncpy(oh_name + 1, name, YAFFS_MAX_NAME_LENGTH - 2);
3252                 }
3253         } else {
3254 #else
3255         {
3256 #endif
3257                 strncpy(oh_name, name, YAFFS_MAX_NAME_LENGTH - 1);
3258         }
3259 }
3260
3261 /* UpdateObjectHeader updates the header on NAND for an object.
3262  * If name is not NULL, then that new name is used.
3263  */
3264 int yaffs_update_oh(struct yaffs_obj *in, const YCHAR *name, int force,
3265                     int is_shrink, int shadows, struct yaffs_xattr_mod *xmod)
3266 {
3267
3268         struct yaffs_block_info *bi;
3269         struct yaffs_dev *dev = in->my_dev;
3270         int prev_chunk_id;
3271         int ret_val = 0;
3272         int result = 0;
3273         int new_chunk_id;
3274         struct yaffs_ext_tags new_tags;
3275         struct yaffs_ext_tags old_tags;
3276         const YCHAR *alias = NULL;
3277         u8 *buffer = NULL;
3278         YCHAR old_name[YAFFS_MAX_NAME_LENGTH + 1];
3279         struct yaffs_obj_hdr *oh = NULL;
3280
3281         strcpy(old_name, _Y("silly old name"));
3282
3283         if (in->fake && in != dev->root_dir && !force && !xmod)
3284                 return ret_val;
3285
3286         yaffs_check_gc(dev, 0);
3287         yaffs_check_obj_details_loaded(in);
3288
3289         buffer = yaffs_get_temp_buffer(in->my_dev);
3290         oh = (struct yaffs_obj_hdr *)buffer;
3291
3292         prev_chunk_id = in->hdr_chunk;
3293
3294         if (prev_chunk_id > 0) {
3295                 result = yaffs_rd_chunk_tags_nand(dev, prev_chunk_id,
3296                                                   buffer, &old_tags);
3297
3298                 yaffs_verify_oh(in, oh, &old_tags, 0);
3299                 memcpy(old_name, oh->name, sizeof(oh->name));
3300                 memset(buffer, 0xff, sizeof(struct yaffs_obj_hdr));
3301         } else {
3302                 memset(buffer, 0xff, dev->data_bytes_per_chunk);
3303         }
3304
3305         oh->type = in->variant_type;
3306         oh->yst_mode = in->yst_mode;
3307         oh->shadows_obj = oh->inband_shadowed_obj_id = shadows;
3308
3309         yaffs_load_attribs_oh(oh, in);
3310
3311         if (in->parent)
3312                 oh->parent_obj_id = in->parent->obj_id;
3313         else
3314                 oh->parent_obj_id = 0;
3315
3316         if (name && *name) {
3317                 memset(oh->name, 0, sizeof(oh->name));
3318                 yaffs_load_oh_from_name(dev, oh->name, name);
3319         } else if (prev_chunk_id > 0) {
3320                 memcpy(oh->name, old_name, sizeof(oh->name));
3321         } else {
3322                 memset(oh->name, 0, sizeof(oh->name));
3323         }
3324
3325         oh->is_shrink = is_shrink;
3326
3327         switch (in->variant_type) {
3328         case YAFFS_OBJECT_TYPE_UNKNOWN:
3329                 /* Should not happen */
3330                 break;
3331         case YAFFS_OBJECT_TYPE_FILE:
3332                 oh->file_size =
3333                     (oh->parent_obj_id == YAFFS_OBJECTID_DELETED ||
3334                      oh->parent_obj_id == YAFFS_OBJECTID_UNLINKED) ?
3335                      0 : in->variant.file_variant.file_size;
3336                 break;
3337         case YAFFS_OBJECT_TYPE_HARDLINK:
3338                 oh->equiv_id = in->variant.hardlink_variant.equiv_id;
3339                 break;
3340         case YAFFS_OBJECT_TYPE_SPECIAL:
3341                 /* Do nothing */
3342                 break;
3343         case YAFFS_OBJECT_TYPE_DIRECTORY:
3344                 /* Do nothing */
3345                 break;
3346         case YAFFS_OBJECT_TYPE_SYMLINK:
3347                 alias = in->variant.symlink_variant.alias;
3348                 if (!alias)
3349                         alias = _Y("no alias");
3350                 strncpy(oh->alias, alias, YAFFS_MAX_ALIAS_LENGTH);
3351                 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3352                 break;
3353         }
3354
3355         /* process any xattrib modifications */
3356         if (xmod)
3357                 yaffs_apply_xattrib_mod(in, (char *)buffer, xmod);
3358
3359         /* Tags */
3360         memset(&new_tags, 0, sizeof(new_tags));
3361         in->serial++;
3362         new_tags.chunk_id = 0;
3363         new_tags.obj_id = in->obj_id;
3364         new_tags.serial_number = in->serial;
3365
3366         /* Add extra info for file header */
3367         new_tags.extra_available = 1;
3368         new_tags.extra_parent_id = oh->parent_obj_id;
3369         new_tags.extra_length = oh->file_size;
3370         new_tags.extra_is_shrink = oh->is_shrink;
3371         new_tags.extra_equiv_id = oh->equiv_id;
3372         new_tags.extra_shadows = (oh->shadows_obj > 0) ? 1 : 0;
3373         new_tags.extra_obj_type = in->variant_type;
3374         yaffs_verify_oh(in, oh, &new_tags, 1);
3375
3376         /* Create new chunk in NAND */
3377         new_chunk_id =
3378             yaffs_write_new_chunk(dev, buffer, &new_tags,
3379                                   (prev_chunk_id > 0) ? 1 : 0);
3380
3381         if (buffer)
3382                 yaffs_release_temp_buffer(dev, buffer);
3383
3384         if (new_chunk_id < 0)
3385                 return new_chunk_id;
3386
3387         in->hdr_chunk = new_chunk_id;
3388
3389         if (prev_chunk_id > 0)
3390                 yaffs_chunk_del(dev, prev_chunk_id, 1, __LINE__);
3391
3392         if (!yaffs_obj_cache_dirty(in))
3393                 in->dirty = 0;
3394
3395         /* If this was a shrink, then mark the block
3396          * that the chunk lives on */
3397         if (is_shrink) {
3398                 bi = yaffs_get_block_info(in->my_dev,
3399                                           new_chunk_id /
3400                                           in->my_dev->param.chunks_per_block);
3401                 bi->has_shrink_hdr = 1;
3402         }
3403
3404
3405         return new_chunk_id;
3406 }
3407
3408 /*--------------------- File read/write ------------------------
3409  * Read and write have very similar structures.
3410  * In general the read/write has three parts to it
3411  * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3412  * Some complete chunks
3413  * An incomplete chunk to end off with
3414  *
3415  * Curve-balls: the first chunk might also be the last chunk.
3416  */
3417
3418 int yaffs_file_rd(struct yaffs_obj *in, u8 * buffer, loff_t offset, int n_bytes)
3419 {
3420         int chunk;
3421         u32 start;
3422         int n_