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