yaffs: Clean up some tracing.
[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 #ifndef CONFIG_YAFFS_NO_SHORT_NAMES
608         memset(obj->short_name, 0, sizeof(obj->short_name));
609         if (name && 
610                 yaffs_strnlen(name, YAFFS_SHORT_NAME_LENGTH + 1) <=
611             YAFFS_SHORT_NAME_LENGTH)
612                 yaffs_strcpy(obj->short_name, name);
613         else
614                 obj->short_name[0] = _Y('\0');
615 #endif
616         obj->sum = yaffs_calc_name_sum(name);
617 }
618
619 void yaffs_set_obj_name_from_oh(struct yaffs_obj *obj,
620                                 const struct yaffs_obj_hdr *oh)
621 {
622 #ifdef CONFIG_YAFFS_AUTO_UNICODE
623         YCHAR tmp_name[YAFFS_MAX_NAME_LENGTH + 1];
624         memset(tmp_name, 0, sizeof(tmp_name));
625         yaffs_load_name_from_oh(obj->my_dev, tmp_name, oh->name,
626                                 YAFFS_MAX_NAME_LENGTH + 1);
627         yaffs_set_obj_name(obj, tmp_name);
628 #else
629         yaffs_set_obj_name(obj, oh->name);
630 #endif
631 }
632
633 /*-------------------- TNODES -------------------
634
635  * List of spare tnodes
636  * The list is hooked together using the first pointer
637  * in the tnode.
638  */
639
640 struct yaffs_tnode *yaffs_get_tnode(struct yaffs_dev *dev)
641 {
642         struct yaffs_tnode *tn = yaffs_alloc_raw_tnode(dev);
643         if (tn) {
644                 memset(tn, 0, dev->tnode_size);
645                 dev->n_tnodes++;
646         }
647
648         dev->checkpoint_blocks_required = 0;    /* force recalculation */
649
650         return tn;
651 }
652
653 /* FreeTnode frees up a tnode and puts it back on the free list */
654 static void yaffs_free_tnode(struct yaffs_dev *dev, struct yaffs_tnode *tn)
655 {
656         yaffs_free_raw_tnode(dev, tn);
657         dev->n_tnodes--;
658         dev->checkpoint_blocks_required = 0;    /* force recalculation */
659 }
660
661 static void yaffs_deinit_tnodes_and_objs(struct yaffs_dev *dev)
662 {
663         yaffs_deinit_raw_tnodes_and_objs(dev);
664         dev->n_obj = 0;
665         dev->n_tnodes = 0;
666 }
667
668 void yaffs_load_tnode_0(struct yaffs_dev *dev, struct yaffs_tnode *tn,
669                         unsigned pos, unsigned val)
670 {
671         u32 *map = (u32 *) tn;
672         u32 bit_in_map;
673         u32 bit_in_word;
674         u32 word_in_map;
675         u32 mask;
676
677         pos &= YAFFS_TNODES_LEVEL0_MASK;
678         val >>= dev->chunk_grp_bits;
679
680         bit_in_map = pos * dev->tnode_width;
681         word_in_map = bit_in_map / 32;
682         bit_in_word = bit_in_map & (32 - 1);
683
684         mask = dev->tnode_mask << bit_in_word;
685
686         map[word_in_map] &= ~mask;
687         map[word_in_map] |= (mask & (val << bit_in_word));
688
689         if (dev->tnode_width > (32 - bit_in_word)) {
690                 bit_in_word = (32 - bit_in_word);
691                 word_in_map++;;
692                 mask =
693                     dev->tnode_mask >> ( /*dev->tnode_width - */ bit_in_word);
694                 map[word_in_map] &= ~mask;
695                 map[word_in_map] |= (mask & (val >> bit_in_word));
696         }
697 }
698
699 u32 yaffs_get_group_base(struct yaffs_dev *dev, struct yaffs_tnode *tn,
700                          unsigned pos)
701 {
702         u32 *map = (u32 *) tn;
703         u32 bit_in_map;
704         u32 bit_in_word;
705         u32 word_in_map;
706         u32 val;
707
708         pos &= YAFFS_TNODES_LEVEL0_MASK;
709
710         bit_in_map = pos * dev->tnode_width;
711         word_in_map = bit_in_map / 32;
712         bit_in_word = bit_in_map & (32 - 1);
713
714         val = map[word_in_map] >> bit_in_word;
715
716         if (dev->tnode_width > (32 - bit_in_word)) {
717                 bit_in_word = (32 - bit_in_word);
718                 word_in_map++;;
719                 val |= (map[word_in_map] << bit_in_word);
720         }
721
722         val &= dev->tnode_mask;
723         val <<= dev->chunk_grp_bits;
724
725         return val;
726 }
727
728 /* ------------------- End of individual tnode manipulation -----------------*/
729
730 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
731  * The look up tree is represented by the top tnode and the number of top_level
732  * in the tree. 0 means only the level 0 tnode is in the tree.
733  */
734
735 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
736 struct yaffs_tnode *yaffs_find_tnode_0(struct yaffs_dev *dev,
737                                        struct yaffs_file_var *file_struct,
738                                        u32 chunk_id)
739 {
740         struct yaffs_tnode *tn = file_struct->top;
741         u32 i;
742         int required_depth;
743         int level = file_struct->top_level;
744
745         dev = dev;
746
747         /* Check sane level and chunk Id */
748         if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
749                 return NULL;
750
751         if (chunk_id > YAFFS_MAX_CHUNK_ID)
752                 return NULL;
753
754         /* First check we're tall enough (ie enough top_level) */
755
756         i = chunk_id >> YAFFS_TNODES_LEVEL0_BITS;
757         required_depth = 0;
758         while (i) {
759                 i >>= YAFFS_TNODES_INTERNAL_BITS;
760                 required_depth++;
761         }
762
763         if (required_depth > file_struct->top_level)
764                 return NULL;    /* Not tall enough, so we can't find it */
765
766         /* Traverse down to level 0 */
767         while (level > 0 && tn) {
768                 tn = tn->internal[(chunk_id >>
769                                    (YAFFS_TNODES_LEVEL0_BITS +
770                                     (level - 1) *
771                                     YAFFS_TNODES_INTERNAL_BITS)) &
772                                   YAFFS_TNODES_INTERNAL_MASK];
773                 level--;
774         }
775
776         return tn;
777 }
778
779 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
780  * This happens in two steps:
781  *  1. If the tree isn't tall enough, then make it taller.
782  *  2. Scan down the tree towards the level 0 tnode adding tnodes if required.
783  *
784  * Used when modifying the tree.
785  *
786  *  If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
787  *  be plugged into the ttree.
788  */
789
790 struct yaffs_tnode *yaffs_add_find_tnode_0(struct yaffs_dev *dev,
791                                            struct yaffs_file_var *file_struct,
792                                            u32 chunk_id,
793                                            struct yaffs_tnode *passed_tn)
794 {
795         int required_depth;
796         int i;
797         int l;
798         struct yaffs_tnode *tn;
799
800         u32 x;
801
802         /* Check sane level and page Id */
803         if (file_struct->top_level < 0
804             || file_struct->top_level > YAFFS_TNODES_MAX_LEVEL)
805                 return NULL;
806
807         if (chunk_id > YAFFS_MAX_CHUNK_ID)
808                 return NULL;
809
810         /* First check we're tall enough (ie enough top_level) */
811
812         x = chunk_id >> YAFFS_TNODES_LEVEL0_BITS;
813         required_depth = 0;
814         while (x) {
815                 x >>= YAFFS_TNODES_INTERNAL_BITS;
816                 required_depth++;
817         }
818
819         if (required_depth > file_struct->top_level) {
820                 /* Not tall enough, gotta make the tree taller */
821                 for (i = file_struct->top_level; i < required_depth; i++) {
822
823                         tn = yaffs_get_tnode(dev);
824
825                         if (tn) {
826                                 tn->internal[0] = file_struct->top;
827                                 file_struct->top = tn;
828                                 file_struct->top_level++;
829                         } else {
830                                 T(YAFFS_TRACE_ERROR,
831                                   (TSTR("yaffs: no more tnodes" TENDSTR)));
832                                 return NULL;
833                         }
834                 }
835         }
836
837         /* Traverse down to level 0, adding anything we need */
838
839         l = file_struct->top_level;
840         tn = file_struct->top;
841
842         if (l > 0) {
843                 while (l > 0 && tn) {
844                         x = (chunk_id >>
845                              (YAFFS_TNODES_LEVEL0_BITS +
846                               (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
847                             YAFFS_TNODES_INTERNAL_MASK;
848
849                         if ((l > 1) && !tn->internal[x]) {
850                                 /* Add missing non-level-zero tnode */
851                                 tn->internal[x] = yaffs_get_tnode(dev);
852                                 if (!tn->internal[x])
853                                         return NULL;
854                         } else if (l == 1) {
855                                 /* Looking from level 1 at level 0 */
856                                 if (passed_tn) {
857                                         /* If we already have one, then release it. */
858                                         if (tn->internal[x])
859                                                 yaffs_free_tnode(dev,
860                                                                  tn->
861                                                                  internal[x]);
862                                         tn->internal[x] = passed_tn;
863
864                                 } else if (!tn->internal[x]) {
865                                         /* Don't have one, none passed in */
866                                         tn->internal[x] = yaffs_get_tnode(dev);
867                                         if (!tn->internal[x])
868                                                 return NULL;
869                                 }
870                         }
871
872                         tn = tn->internal[x];
873                         l--;
874                 }
875         } else {
876                 /* top is level 0 */
877                 if (passed_tn) {
878                         memcpy(tn, passed_tn,
879                                (dev->tnode_width * YAFFS_NTNODES_LEVEL0) / 8);
880                         yaffs_free_tnode(dev, passed_tn);
881                 }
882         }
883
884         return tn;
885 }
886
887 static int yaffs_find_chunk_in_group(struct yaffs_dev *dev, int the_chunk,
888                                      struct yaffs_ext_tags *tags, int obj_id,
889                                      int inode_chunk)
890 {
891         int j;
892
893         for (j = 0; the_chunk && j < dev->chunk_grp_size; j++) {
894                 if (yaffs_check_chunk_bit
895                     (dev, the_chunk / dev->param.chunks_per_block,
896                      the_chunk % dev->param.chunks_per_block)) {
897
898                         if (dev->chunk_grp_size == 1)
899                                 return the_chunk;
900                         else {
901                                 yaffs_rd_chunk_tags_nand(dev, the_chunk, NULL,
902                                                          tags);
903                                 if (yaffs_tags_match(tags, obj_id, inode_chunk)) {
904                                         /* found it; */
905                                         return the_chunk;
906                                 }
907                         }
908                 }
909                 the_chunk++;
910         }
911         return -1;
912 }
913
914 static void yaffs_soft_del_chunk(struct yaffs_dev *dev, int chunk)
915 {
916         struct yaffs_block_info *the_block;
917         unsigned block_no;
918
919         T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
920
921         block_no = chunk / dev->param.chunks_per_block;
922         the_block = yaffs_get_block_info(dev, block_no);
923         if (the_block) {
924                 the_block->soft_del_pages++;
925                 dev->n_free_chunks++;
926                 yaffs2_update_oldest_dirty_seq(dev, block_no, the_block);
927         }
928 }
929
930 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
931  * All soft deleting does is increment the block's softdelete count and pulls the chunk out
932  * of the tnode.
933  * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
934  */
935
936 static int yaffs_soft_del_worker(struct yaffs_obj *in, struct yaffs_tnode *tn,
937                                  u32 level, int chunk_offset)
938 {
939         int i;
940         int the_chunk;
941         int all_done = 1;
942         struct yaffs_dev *dev = in->my_dev;
943
944         if (tn) {
945                 if (level > 0) {
946
947                         for (i = YAFFS_NTNODES_INTERNAL - 1; all_done && i >= 0;
948                              i--) {
949                                 if (tn->internal[i]) {
950                                         all_done =
951                                             yaffs_soft_del_worker(in,
952                                                                   tn->internal
953                                                                   [i],
954                                                                   level - 1,
955                                                                   (chunk_offset
956                                                                    <<
957                                                                    YAFFS_TNODES_INTERNAL_BITS)
958                                                                   + i);
959                                         if (all_done) {
960                                                 yaffs_free_tnode(dev,
961                                                                  tn->internal
962                                                                  [i]);
963                                                 tn->internal[i] = NULL;
964                                         } else {
965                                                 /* Hoosterman... how could this happen? */
966                                         }
967                                 }
968                         }
969                         return (all_done) ? 1 : 0;
970                 } else if (level == 0) {
971
972                         for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
973                                 the_chunk = yaffs_get_group_base(dev, tn, i);
974                                 if (the_chunk) {
975                                         /* Note this does not find the real chunk, only the chunk group.
976                                          * We make an assumption that a chunk group is not larger than
977                                          * a block.
978                                          */
979                                         yaffs_soft_del_chunk(dev, the_chunk);
980                                         yaffs_load_tnode_0(dev, tn, i, 0);
981                                 }
982
983                         }
984                         return 1;
985
986                 }
987
988         }
989
990         return 1;
991
992 }
993
994 static void yaffs_soft_del_file(struct yaffs_obj *obj)
995 {
996         if (obj->deleted &&
997             obj->variant_type == YAFFS_OBJECT_TYPE_FILE && !obj->soft_del) {
998                 if (obj->n_data_chunks <= 0) {
999                         /* Empty file with no duplicate object headers, just delete it immediately */
1000                         yaffs_free_tnode(obj->my_dev,
1001                                          obj->variant.file_variant.top);
1002                         obj->variant.file_variant.top = NULL;
1003                         T(YAFFS_TRACE_TRACING,
1004                           (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1005                            obj->obj_id));
1006                         yaffs_generic_obj_del(obj);
1007                 } else {
1008                         yaffs_soft_del_worker(obj,
1009                                               obj->variant.file_variant.top,
1010                                               obj->variant.
1011                                               file_variant.top_level, 0);
1012                         obj->soft_del = 1;
1013                 }
1014         }
1015 }
1016
1017 /* Pruning removes any part of the file structure tree that is beyond the
1018  * bounds of the file (ie that does not point to chunks).
1019  *
1020  * A file should only get pruned when its size is reduced.
1021  *
1022  * Before pruning, the chunks must be pulled from the tree and the
1023  * level 0 tnode entries must be zeroed out.
1024  * Could also use this for file deletion, but that's probably better handled
1025  * by a special case.
1026  *
1027  * This function is recursive. For levels > 0 the function is called again on
1028  * any sub-tree. For level == 0 we just check if the sub-tree has data.
1029  * If there is no data in a subtree then it is pruned.
1030  */
1031
1032 static struct yaffs_tnode *yaffs_prune_worker(struct yaffs_dev *dev,
1033                                               struct yaffs_tnode *tn, u32 level,
1034                                               int del0)
1035 {
1036         int i;
1037         int has_data;
1038
1039         if (tn) {
1040                 has_data = 0;
1041
1042                 if (level > 0) {
1043                         for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1044                                 if (tn->internal[i]) {
1045                                         tn->internal[i] =
1046                                             yaffs_prune_worker(dev,
1047                                                                tn->internal[i],
1048                                                                level - 1,
1049                                                                (i ==
1050                                                                 0) ? del0 : 1);
1051                                 }
1052
1053                                 if (tn->internal[i])
1054                                         has_data++;
1055                         }
1056                 } else {
1057                         int tnode_size_u32 = dev->tnode_size / sizeof(u32);
1058                         u32 *map = (u32 *) tn;
1059
1060                         for (i = 0; !has_data && i < tnode_size_u32; i++) {
1061                                 if (map[i])
1062                                         has_data++;
1063                         }
1064                 }
1065
1066                 if (has_data == 0 && del0) {
1067                         /* Free and return NULL */
1068
1069                         yaffs_free_tnode(dev, tn);
1070                         tn = NULL;
1071                 }
1072
1073         }
1074
1075         return tn;
1076
1077 }
1078
1079 static int yaffs_prune_tree(struct yaffs_dev *dev,
1080                             struct yaffs_file_var *file_struct)
1081 {
1082         int i;
1083         int has_data;
1084         int done = 0;
1085         struct yaffs_tnode *tn;
1086
1087         if (file_struct->top_level > 0) {
1088                 file_struct->top =
1089                     yaffs_prune_worker(dev, file_struct->top,
1090                                        file_struct->top_level, 0);
1091
1092                 /* Now we have a tree with all the non-zero branches NULL but the height
1093                  * is the same as it was.
1094                  * Let's see if we can trim internal tnodes to shorten the tree.
1095                  * We can do this if only the 0th element in the tnode is in use
1096                  * (ie all the non-zero are NULL)
1097                  */
1098
1099                 while (file_struct->top_level && !done) {
1100                         tn = file_struct->top;
1101
1102                         has_data = 0;
1103                         for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1104                                 if (tn->internal[i])
1105                                         has_data++;
1106                         }
1107
1108                         if (!has_data) {
1109                                 file_struct->top = tn->internal[0];
1110                                 file_struct->top_level--;
1111                                 yaffs_free_tnode(dev, tn);
1112                         } else {
1113                                 done = 1;
1114                         }
1115                 }
1116         }
1117
1118         return YAFFS_OK;
1119 }
1120
1121 /*-------------------- End of File Structure functions.-------------------*/
1122
1123 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1124 static struct yaffs_obj *yaffs_alloc_empty_obj(struct yaffs_dev *dev)
1125 {
1126         struct yaffs_obj *obj = yaffs_alloc_raw_obj(dev);
1127
1128         if (obj) {
1129                 dev->n_obj++;
1130
1131                 /* Now sweeten it up... */
1132
1133                 memset(obj, 0, sizeof(struct yaffs_obj));
1134                 obj->being_created = 1;
1135
1136                 obj->my_dev = dev;
1137                 obj->hdr_chunk = 0;
1138                 obj->variant_type = YAFFS_OBJECT_TYPE_UNKNOWN;
1139                 INIT_LIST_HEAD(&(obj->hard_links));
1140                 INIT_LIST_HEAD(&(obj->hash_link));
1141                 INIT_LIST_HEAD(&obj->siblings);
1142
1143                 /* Now make the directory sane */
1144                 if (dev->root_dir) {
1145                         obj->parent = dev->root_dir;
1146                         list_add(&(obj->siblings),
1147                                  &dev->root_dir->variant.dir_variant.children);
1148                 }
1149
1150                 /* Add it to the lost and found directory.
1151                  * NB Can't put root or lost-n-found in lost-n-found so
1152                  * check if lost-n-found exists first
1153                  */
1154                 if (dev->lost_n_found)
1155                         yaffs_add_obj_to_dir(dev->lost_n_found, obj);
1156
1157                 obj->being_created = 0;
1158         }
1159
1160         dev->checkpoint_blocks_required = 0;    /* force recalculation */
1161
1162         return obj;
1163 }
1164
1165 static struct yaffs_obj *yaffs_create_fake_dir(struct yaffs_dev *dev,
1166                                                int number, u32 mode)
1167 {
1168
1169         struct yaffs_obj *obj =
1170             yaffs_new_obj(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1171         if (obj) {
1172                 obj->fake = 1;  /* it is fake so it might have no NAND presence... */
1173                 obj->rename_allowed = 0;        /* ... and we're not allowed to rename it... */
1174                 obj->unlink_allowed = 0;        /* ... or unlink it */
1175                 obj->deleted = 0;
1176                 obj->unlinked = 0;
1177                 obj->yst_mode = mode;
1178                 obj->my_dev = dev;
1179                 obj->hdr_chunk = 0;     /* Not a valid chunk. */
1180         }
1181
1182         return obj;
1183
1184 }
1185
1186 static void yaffs_unhash_obj(struct yaffs_obj *obj)
1187 {
1188         int bucket;
1189         struct yaffs_dev *dev = obj->my_dev;
1190
1191         /* If it is still linked into the bucket list, free from the list */
1192         if (!list_empty(&obj->hash_link)) {
1193                 list_del_init(&obj->hash_link);
1194                 bucket = yaffs_hash_fn(obj->obj_id);
1195                 dev->obj_bucket[bucket].count--;
1196         }
1197 }
1198
1199 /*  FreeObject frees up a Object and puts it back on the free list */
1200 static void yaffs_free_obj(struct yaffs_obj *obj)
1201 {
1202         struct yaffs_dev *dev = obj->my_dev;
1203
1204         T(YAFFS_TRACE_OS,
1205           (TSTR("FreeObject %p inode %p" TENDSTR), obj, obj->my_inode));
1206
1207         if (!obj)
1208                 YBUG();
1209         if (obj->parent)
1210                 YBUG();
1211         if (!list_empty(&obj->siblings))
1212                 YBUG();
1213
1214         if (obj->my_inode) {
1215                 /* We're still hooked up to a cached inode.
1216                  * Don't delete now, but mark for later deletion
1217                  */
1218                 obj->defered_free = 1;
1219                 return;
1220         }
1221
1222         yaffs_unhash_obj(obj);
1223
1224         yaffs_free_raw_obj(dev, obj);
1225         dev->n_obj--;
1226         dev->checkpoint_blocks_required = 0;    /* force recalculation */
1227 }
1228
1229 void yaffs_handle_defered_free(struct yaffs_obj *obj)
1230 {
1231         if (obj->defered_free)
1232                 yaffs_free_obj(obj);
1233 }
1234
1235 static void yaffs_init_tnodes_and_objs(struct yaffs_dev *dev)
1236 {
1237         int i;
1238
1239         dev->n_obj = 0;
1240         dev->n_tnodes = 0;
1241
1242         yaffs_init_raw_tnodes_and_objs(dev);
1243
1244         for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
1245                 INIT_LIST_HEAD(&dev->obj_bucket[i].list);
1246                 dev->obj_bucket[i].count = 0;
1247         }
1248 }
1249
1250 static int yaffs_find_nice_bucket(struct yaffs_dev *dev)
1251 {
1252         int i;
1253         int l = 999;
1254         int lowest = 999999;
1255
1256         /* Search for the shortest list or one that
1257          * isn't too long.
1258          */
1259
1260         for (i = 0; i < 10 && lowest > 4; i++) {
1261                 dev->bucket_finder++;
1262                 dev->bucket_finder %= YAFFS_NOBJECT_BUCKETS;
1263                 if (dev->obj_bucket[dev->bucket_finder].count < lowest) {
1264                         lowest = dev->obj_bucket[dev->bucket_finder].count;
1265                         l = dev->bucket_finder;
1266                 }
1267
1268         }
1269
1270         return l;
1271 }
1272
1273 static int yaffs_new_obj_id(struct yaffs_dev *dev)
1274 {
1275         int bucket = yaffs_find_nice_bucket(dev);
1276
1277         /* Now find an object value that has not already been taken
1278          * by scanning the list.
1279          */
1280
1281         int found = 0;
1282         struct list_head *i;
1283
1284         u32 n = (u32) bucket;
1285
1286         /* yaffs_check_obj_hash_sane();  */
1287
1288         while (!found) {
1289                 found = 1;
1290                 n += YAFFS_NOBJECT_BUCKETS;
1291                 if (1 || dev->obj_bucket[bucket].count > 0) {
1292                         list_for_each(i, &dev->obj_bucket[bucket].list) {
1293                                 /* If there is already one in the list */
1294                                 if (i && list_entry(i, struct yaffs_obj,
1295                                                     hash_link)->obj_id == n) {
1296                                         found = 0;
1297                                 }
1298                         }
1299                 }
1300         }
1301
1302         return n;
1303 }
1304
1305 static void yaffs_hash_obj(struct yaffs_obj *in)
1306 {
1307         int bucket = yaffs_hash_fn(in->obj_id);
1308         struct yaffs_dev *dev = in->my_dev;
1309
1310         list_add(&in->hash_link, &dev->obj_bucket[bucket].list);
1311         dev->obj_bucket[bucket].count++;
1312 }
1313
1314 struct yaffs_obj *yaffs_find_by_number(struct yaffs_dev *dev, u32 number)
1315 {
1316         int bucket = yaffs_hash_fn(number);
1317         struct list_head *i;
1318         struct yaffs_obj *in;
1319
1320         list_for_each(i, &dev->obj_bucket[bucket].list) {
1321                 /* Look if it is in the list */
1322                 if (i) {
1323                         in = list_entry(i, struct yaffs_obj, hash_link);
1324                         if (in->obj_id == number) {
1325
1326                                 /* Don't tell the VFS about this one if it is defered free */
1327                                 if (in->defered_free)
1328                                         return NULL;
1329
1330                                 return in;
1331                         }
1332                 }
1333         }
1334
1335         return NULL;
1336 }
1337
1338 struct yaffs_obj *yaffs_new_obj(struct yaffs_dev *dev, int number,
1339                                 enum yaffs_obj_type type)
1340 {
1341         struct yaffs_obj *the_obj = NULL;
1342         struct yaffs_tnode *tn = NULL;
1343
1344         if (number < 0)
1345                 number = yaffs_new_obj_id(dev);
1346
1347         if (type == YAFFS_OBJECT_TYPE_FILE) {
1348                 tn = yaffs_get_tnode(dev);
1349                 if (!tn)
1350                         return NULL;
1351         }
1352
1353         the_obj = yaffs_alloc_empty_obj(dev);
1354         if (!the_obj) {
1355                 if (tn)
1356                         yaffs_free_tnode(dev, tn);
1357                 return NULL;
1358         }
1359
1360         if (the_obj) {
1361                 the_obj->fake = 0;
1362                 the_obj->rename_allowed = 1;
1363                 the_obj->unlink_allowed = 1;
1364                 the_obj->obj_id = number;
1365                 yaffs_hash_obj(the_obj);
1366                 the_obj->variant_type = type;
1367                 yaffs_load_current_time(the_obj, 1, 1);
1368
1369                 switch (type) {
1370                 case YAFFS_OBJECT_TYPE_FILE:
1371                         the_obj->variant.file_variant.file_size = 0;
1372                         the_obj->variant.file_variant.scanned_size = 0;
1373                         the_obj->variant.file_variant.shrink_size = ~0; /* max */
1374                         the_obj->variant.file_variant.top_level = 0;
1375                         the_obj->variant.file_variant.top = tn;
1376                         break;
1377                 case YAFFS_OBJECT_TYPE_DIRECTORY:
1378                         INIT_LIST_HEAD(&the_obj->variant.dir_variant.children);
1379                         INIT_LIST_HEAD(&the_obj->variant.dir_variant.dirty);
1380                         break;
1381                 case YAFFS_OBJECT_TYPE_SYMLINK:
1382                 case YAFFS_OBJECT_TYPE_HARDLINK:
1383                 case YAFFS_OBJECT_TYPE_SPECIAL:
1384                         /* No action required */
1385                         break;
1386                 case YAFFS_OBJECT_TYPE_UNKNOWN:
1387                         /* todo this should not happen */
1388                         break;
1389                 }
1390         }
1391
1392         return the_obj;
1393 }
1394
1395 struct yaffs_obj *yaffs_find_or_create_by_number(struct yaffs_dev *dev,
1396                                                  int number,
1397                                                  enum yaffs_obj_type type)
1398 {
1399         struct yaffs_obj *the_obj = NULL;
1400
1401         if (number > 0)
1402                 the_obj = yaffs_find_by_number(dev, number);
1403
1404         if (!the_obj)
1405                 the_obj = yaffs_new_obj(dev, number, type);
1406
1407         return the_obj;
1408
1409 }
1410
1411 YCHAR *yaffs_clone_str(const YCHAR * str)
1412 {
1413         YCHAR *new_str = NULL;
1414         int len;
1415
1416         if (!str)
1417                 str = _Y("");
1418
1419         len = yaffs_strnlen(str, YAFFS_MAX_ALIAS_LENGTH);
1420         new_str = YMALLOC((len + 1) * sizeof(YCHAR));
1421         if (new_str) {
1422                 yaffs_strncpy(new_str, str, len);
1423                 new_str[len] = 0;
1424         }
1425         return new_str;
1426
1427 }
1428
1429 /*
1430  * Mknod (create) a new object.
1431  * equiv_obj only has meaning for a hard link;
1432  * alias_str only has meaning for a symlink.
1433  * rdev only has meaning for devices (a subset of special objects)
1434  */
1435
1436 static struct yaffs_obj *yaffs_create_obj(enum yaffs_obj_type type,
1437                                           struct yaffs_obj *parent,
1438                                           const YCHAR * name,
1439                                           u32 mode,
1440                                           u32 uid,
1441                                           u32 gid,
1442                                           struct yaffs_obj *equiv_obj,
1443                                           const YCHAR * alias_str, u32 rdev)
1444 {
1445         struct yaffs_obj *in;
1446         YCHAR *str = NULL;
1447
1448         struct yaffs_dev *dev = parent->my_dev;
1449
1450         /* Check if the entry exists. If it does then fail the call since we don't want a dup. */
1451         if (yaffs_find_by_name(parent, name))
1452                 return NULL;
1453
1454         if (type == YAFFS_OBJECT_TYPE_SYMLINK) {
1455                 str = yaffs_clone_str(alias_str);
1456                 if (!str)
1457                         return NULL;
1458         }
1459
1460         in = yaffs_new_obj(dev, -1, type);
1461
1462         if (!in) {
1463                 if (str)
1464                         YFREE(str);
1465                 return NULL;
1466         }
1467
1468         if (in) {
1469                 in->hdr_chunk = 0;
1470                 in->valid = 1;
1471                 in->variant_type = type;
1472
1473                 in->yst_mode = mode;
1474
1475                 yaffs_attribs_init(in, gid, uid, rdev);
1476
1477                 in->n_data_chunks = 0;
1478
1479                 yaffs_set_obj_name(in, name);
1480                 in->dirty = 1;
1481
1482                 yaffs_add_obj_to_dir(parent, in);
1483
1484                 in->my_dev = parent->my_dev;
1485
1486                 switch (type) {
1487                 case YAFFS_OBJECT_TYPE_SYMLINK:
1488                         in->variant.symlink_variant.alias = str;
1489                         break;
1490                 case YAFFS_OBJECT_TYPE_HARDLINK:
1491                         in->variant.hardlink_variant.equiv_obj = equiv_obj;
1492                         in->variant.hardlink_variant.equiv_id =
1493                             equiv_obj->obj_id;
1494                         list_add(&in->hard_links, &equiv_obj->hard_links);
1495                         break;
1496                 case YAFFS_OBJECT_TYPE_FILE:
1497                 case YAFFS_OBJECT_TYPE_DIRECTORY:
1498                 case YAFFS_OBJECT_TYPE_SPECIAL:
1499                 case YAFFS_OBJECT_TYPE_UNKNOWN:
1500                         /* do nothing */
1501                         break;
1502                 }
1503
1504                 if (yaffs_update_oh(in, name, 0, 0, 0, NULL) < 0) {
1505                         /* Could not create the object header, fail the creation */
1506                         yaffs_del_obj(in);
1507                         in = NULL;
1508                 }
1509
1510                 yaffs_update_parent(parent);
1511         }
1512
1513         return in;
1514 }
1515
1516 struct yaffs_obj *yaffs_create_file(struct yaffs_obj *parent,
1517                                     const YCHAR * name, u32 mode, u32 uid,
1518                                     u32 gid)
1519 {
1520         return yaffs_create_obj(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
1521                                 uid, gid, NULL, NULL, 0);
1522 }
1523
1524 struct yaffs_obj *yaffs_create_dir(struct yaffs_obj *parent, const YCHAR * name,
1525                                    u32 mode, u32 uid, u32 gid)
1526 {
1527         return yaffs_create_obj(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
1528                                 mode, uid, gid, NULL, NULL, 0);
1529 }
1530
1531 struct yaffs_obj *yaffs_create_special(struct yaffs_obj *parent,
1532                                        const YCHAR * name, u32 mode, u32 uid,
1533                                        u32 gid, u32 rdev)
1534 {
1535         return yaffs_create_obj(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
1536                                 uid, gid, NULL, NULL, rdev);
1537 }
1538
1539 struct yaffs_obj *yaffs_create_symlink(struct yaffs_obj *parent,
1540                                        const YCHAR * name, u32 mode, u32 uid,
1541                                        u32 gid, const YCHAR * alias)
1542 {
1543         return yaffs_create_obj(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
1544                                 uid, gid, NULL, alias, 0);
1545 }
1546
1547 /* yaffs_link_obj returns the object id of the equivalent object.*/
1548 struct yaffs_obj *yaffs_link_obj(struct yaffs_obj *parent, const YCHAR * name,
1549                                  struct yaffs_obj *equiv_obj)
1550 {
1551         /* Get the real object in case we were fed a hard link as an equivalent object */
1552         equiv_obj = yaffs_get_equivalent_obj(equiv_obj);
1553
1554         if (yaffs_create_obj
1555             (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
1556              equiv_obj, NULL, 0)) {
1557                 return equiv_obj;
1558         } else {
1559                 return NULL;
1560         }
1561
1562 }
1563
1564 static int yaffs_change_obj_name(struct yaffs_obj *obj,
1565                                  struct yaffs_obj *new_dir,
1566                                  const YCHAR * new_name, int force, int shadows)
1567 {
1568         int unlink_op;
1569         int del_op;
1570
1571         struct yaffs_obj *existing_target;
1572
1573         if (new_dir == NULL)
1574                 new_dir = obj->parent;  /* use the old directory */
1575
1576         if (new_dir->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY) {
1577                 T(YAFFS_TRACE_ALWAYS,
1578                   (TSTR
1579                    ("tragedy: yaffs_change_obj_name: new_dir is not a directory"
1580                     TENDSTR)));
1581                 YBUG();
1582         }
1583
1584         /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
1585         if (obj->my_dev->param.is_yaffs2)
1586                 unlink_op = (new_dir == obj->my_dev->unlinked_dir);
1587         else
1588                 unlink_op = (new_dir == obj->my_dev->unlinked_dir
1589                              && obj->variant_type == YAFFS_OBJECT_TYPE_FILE);
1590
1591         del_op = (new_dir == obj->my_dev->del_dir);
1592
1593         existing_target = yaffs_find_by_name(new_dir, new_name);
1594
1595         /* If the object is a file going into the unlinked directory,
1596          *   then it is OK to just stuff it in since duplicate names are allowed.
1597          *   else only proceed if the new name does not exist and if we're putting
1598          *   it into a directory.
1599          */
1600         if ((unlink_op ||
1601              del_op ||
1602              force ||
1603              (shadows > 0) ||
1604              !existing_target) &&
1605             new_dir->variant_type == YAFFS_OBJECT_TYPE_DIRECTORY) {
1606                 yaffs_set_obj_name(obj, new_name);
1607                 obj->dirty = 1;
1608
1609                 yaffs_add_obj_to_dir(new_dir, obj);
1610
1611                 if (unlink_op)
1612                         obj->unlinked = 1;
1613
1614                 /* If it is a deletion then we mark it as a shrink for gc purposes. */
1615                 if (yaffs_update_oh(obj, new_name, 0, del_op, shadows, NULL) >=
1616                     0)
1617                         return YAFFS_OK;
1618         }
1619
1620         return YAFFS_FAIL;
1621 }
1622
1623 int yaffs_rename_obj(struct yaffs_obj *old_dir, const YCHAR * old_name,
1624                      struct yaffs_obj *new_dir, const YCHAR * new_name)
1625 {
1626         struct yaffs_obj *obj = NULL;
1627         struct yaffs_obj *existing_target = NULL;
1628         int force = 0;
1629         int result;
1630         struct yaffs_dev *dev;
1631
1632         if (!old_dir || old_dir->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY)
1633                 YBUG();
1634         if (!new_dir || new_dir->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY)
1635                 YBUG();
1636
1637         dev = old_dir->my_dev;
1638
1639 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1640         /* Special case for case insemsitive systems.
1641          * While look-up is case insensitive, the name isn't.
1642          * Therefore we might want to change x.txt to X.txt
1643          */
1644         if (old_dir == new_dir && yaffs_strcmp(old_name, new_name) == 0)
1645                 force = 1;
1646 #endif
1647
1648         if (yaffs_strnlen(new_name, YAFFS_MAX_NAME_LENGTH + 1) >
1649             YAFFS_MAX_NAME_LENGTH)
1650                 /* ENAMETOOLONG */
1651                 return YAFFS_FAIL;
1652
1653         obj = yaffs_find_by_name(old_dir, old_name);
1654
1655         if (obj && obj->rename_allowed) {
1656
1657                 /* Now do the handling for an existing target, if there is one */
1658
1659                 existing_target = yaffs_find_by_name(new_dir, new_name);
1660                 if (existing_target &&
1661                     existing_target->variant_type == YAFFS_OBJECT_TYPE_DIRECTORY
1662                     && !list_empty(&existing_target->variant.dir_variant.
1663                                    children)) {
1664                         /* There is a target that is a non-empty directory, so we fail */
1665                         return YAFFS_FAIL;      /* EEXIST or ENOTEMPTY */
1666                 } else if (existing_target && existing_target != obj) {
1667                         /* Nuke the target first, using shadowing,
1668                          * but only if it isn't the same object.
1669                          *
1670                          * Note we must disable gc otherwise it can mess up the shadowing.
1671                          *
1672                          */
1673                         dev->gc_disable = 1;
1674                         yaffs_change_obj_name(obj, new_dir, new_name, force,
1675                                               existing_target->obj_id);
1676                         existing_target->is_shadowed = 1;
1677                         yaffs_unlink_obj(existing_target);
1678                         dev->gc_disable = 0;
1679                 }
1680
1681                 result = yaffs_change_obj_name(obj, new_dir, new_name, 1, 0);
1682
1683                 yaffs_update_parent(old_dir);
1684                 if (new_dir != old_dir)
1685                         yaffs_update_parent(new_dir);
1686
1687                 return result;
1688         }
1689         return YAFFS_FAIL;
1690 }
1691
1692 /*------------------------- Block Management and Page Allocation ----------------*/
1693
1694 static int yaffs_init_blocks(struct yaffs_dev *dev)
1695 {
1696         int n_blocks = dev->internal_end_block - dev->internal_start_block + 1;
1697
1698         dev->block_info = NULL;
1699         dev->chunk_bits = NULL;
1700
1701         dev->alloc_block = -1;  /* force it to get a new one */
1702
1703         /* If the first allocation strategy fails, thry the alternate one */
1704         dev->block_info = YMALLOC(n_blocks * sizeof(struct yaffs_block_info));
1705         if (!dev->block_info) {
1706                 dev->block_info =
1707                     YMALLOC_ALT(n_blocks * sizeof(struct yaffs_block_info));
1708                 dev->block_info_alt = 1;
1709         } else {
1710                 dev->block_info_alt = 0;
1711         }
1712
1713         if (dev->block_info) {
1714                 /* Set up dynamic blockinfo stuff. */
1715                 dev->chunk_bit_stride = (dev->param.chunks_per_block + 7) / 8;  /* round up bytes */
1716                 dev->chunk_bits = YMALLOC(dev->chunk_bit_stride * n_blocks);
1717                 if (!dev->chunk_bits) {
1718                         dev->chunk_bits =
1719                             YMALLOC_ALT(dev->chunk_bit_stride * n_blocks);
1720                         dev->chunk_bits_alt = 1;
1721                 } else {
1722                         dev->chunk_bits_alt = 0;
1723                 }
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
2185                                         if (new_chunk < 0) {
2186                                                 ret_val = YAFFS_FAIL;
2187                                         } else {
2188
2189                                                 /* Ok, now fix up the Tnodes etc. */
2190
2191                                                 if (tags.chunk_id == 0) {
2192                                                         /* It's a header */
2193                                                         object->hdr_chunk =
2194                                                             new_chunk;
2195                                                         object->serial =
2196                                                             tags.serial_number;
2197                                                 } else {
2198                                                         /* It's a data chunk */
2199                                                         int ok;
2200                                                         ok = yaffs_put_chunk_in_file(object, tags.chunk_id, new_chunk, 0);
2201                                                 }
2202                                         }
2203                                 }
2204
2205                                 if (ret_val == YAFFS_OK)
2206                                         yaffs_chunk_del(dev, old_chunk,
2207                                                         mark_flash, __LINE__);
2208
2209                         }
2210                 }
2211
2212                 yaffs_release_temp_buffer(dev, buffer, __LINE__);
2213
2214         }
2215
2216         yaffs_verify_collected_blk(dev, bi, block);
2217
2218         if (bi->block_state == YAFFS_BLOCK_STATE_COLLECTING) {
2219                 /*
2220                  * The gc did not complete. Set block state back to FULL
2221                  * because checkpointing does not restore gc.
2222                  */
2223                 bi->block_state = YAFFS_BLOCK_STATE_FULL;
2224         } else {
2225                 /* The gc completed. */
2226                 /* Do any required cleanups */
2227                 for (i = 0; i < dev->n_clean_ups; i++) {
2228                         /* Time to delete the file too */
2229                         object =
2230                             yaffs_find_by_number(dev, dev->gc_cleanup_list[i]);
2231                         if (object) {
2232                                 yaffs_free_tnode(dev,
2233                                                  object->variant.
2234                                                  file_variant.top);
2235                                 object->variant.file_variant.top = NULL;
2236                                 T(YAFFS_TRACE_GC,
2237                                   (TSTR
2238                                    ("yaffs: About to finally delete object %d"
2239                                     TENDSTR), object->obj_id));
2240                                 yaffs_generic_obj_del(object);
2241                                 object->my_dev->n_deleted_files--;
2242                         }
2243
2244                 }
2245
2246                 chunks_after = yaffs_get_erased_chunks(dev);
2247                 if (chunks_before >= chunks_after) {
2248                         T(YAFFS_TRACE_GC,
2249                           (TSTR
2250                            ("gc did not increase free chunks before %d after %d"
2251                             TENDSTR), chunks_before, chunks_after));
2252                 }
2253                 dev->gc_block = 0;
2254                 dev->gc_chunk = 0;
2255                 dev->n_clean_ups = 0;
2256         }
2257
2258         dev->gc_disable = 0;
2259
2260         return ret_val;
2261 }
2262
2263 /*
2264  * FindBlockForgarbageCollection is used to select the dirtiest block (or close enough)
2265  * for garbage collection.
2266  */
2267
2268 static unsigned yaffs_find_gc_block(struct yaffs_dev *dev,
2269                                     int aggressive, int background)
2270 {
2271         int i;
2272         int iterations;
2273         unsigned selected = 0;
2274         int prioritised = 0;
2275         int prioritised_exist = 0;
2276         struct yaffs_block_info *bi;
2277         int threshold;
2278
2279         /* First let's see if we need to grab a prioritised block */
2280         if (dev->has_pending_prioritised_gc && !aggressive) {
2281                 dev->gc_dirtiest = 0;
2282                 bi = dev->block_info;
2283                 for (i = dev->internal_start_block;
2284                      i <= dev->internal_end_block && !selected; i++) {
2285
2286                         if (bi->gc_prioritise) {
2287                                 prioritised_exist = 1;
2288                                 if (bi->block_state == YAFFS_BLOCK_STATE_FULL &&
2289                                     yaffs_block_ok_for_gc(dev, bi)) {
2290                                         selected = i;
2291                                         prioritised = 1;
2292                                 }
2293                         }
2294                         bi++;
2295                 }
2296
2297                 /*
2298                  * If there is a prioritised block and none was selected then
2299                  * this happened because there is at least one old dirty block gumming
2300                  * up the works. Let's gc the oldest dirty block.
2301                  */
2302
2303                 if (prioritised_exist &&
2304                     !selected && dev->oldest_dirty_block > 0)
2305                         selected = dev->oldest_dirty_block;
2306
2307                 if (!prioritised_exist) /* None found, so we can clear this */
2308                         dev->has_pending_prioritised_gc = 0;
2309         }
2310
2311         /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2312          * search harder.
2313          * else (we're doing a leasurely gc), then we only bother to do this if the
2314          * block has only a few pages in use.
2315          */
2316
2317         if (!selected) {
2318                 int pages_used;
2319                 int n_blocks =
2320                     dev->internal_end_block - dev->internal_start_block + 1;
2321                 if (aggressive) {
2322                         threshold = dev->param.chunks_per_block;
2323                         iterations = n_blocks;
2324                 } else {
2325                         int max_threshold;
2326
2327                         if (background)
2328                                 max_threshold = dev->param.chunks_per_block / 2;
2329                         else
2330                                 max_threshold = dev->param.chunks_per_block / 8;
2331
2332                         if (max_threshold < YAFFS_GC_PASSIVE_THRESHOLD)
2333                                 max_threshold = YAFFS_GC_PASSIVE_THRESHOLD;
2334
2335                         threshold = background ? (dev->gc_not_done + 2) * 2 : 0;
2336                         if (threshold < YAFFS_GC_PASSIVE_THRESHOLD)
2337                                 threshold = YAFFS_GC_PASSIVE_THRESHOLD;
2338                         if (threshold > max_threshold)
2339                                 threshold = max_threshold;
2340
2341                         iterations = n_blocks / 16 + 1;
2342                         if (iterations > 100)
2343                                 iterations = 100;
2344                 }
2345
2346                 for (i = 0;
2347                      i < iterations &&
2348                      (dev->gc_dirtiest < 1 ||
2349                       dev->gc_pages_in_use > YAFFS_GC_GOOD_ENOUGH); i++) {
2350                         dev->gc_block_finder++;
2351                         if (dev->gc_block_finder < dev->internal_start_block ||
2352                             dev->gc_block_finder > dev->internal_end_block)
2353                                 dev->gc_block_finder =
2354                                     dev->internal_start_block;
2355
2356                         bi = yaffs_get_block_info(dev, dev->gc_block_finder);
2357
2358                         pages_used = bi->pages_in_use - bi->soft_del_pages;
2359
2360                         if (bi->block_state == YAFFS_BLOCK_STATE_FULL &&
2361                             pages_used < dev->param.chunks_per_block &&
2362                             (dev->gc_dirtiest < 1
2363                              || pages_used < dev->gc_pages_in_use)
2364                             && yaffs_block_ok_for_gc(dev, bi)) {
2365                                 dev->gc_dirtiest = dev->gc_block_finder;
2366                                 dev->gc_pages_in_use = pages_used;
2367                         }
2368                 }
2369
2370                 if (dev->gc_dirtiest > 0 && dev->gc_pages_in_use <= threshold)
2371                         selected = dev->gc_dirtiest;
2372         }
2373
2374         /*
2375          * If nothing has been selected for a while, try selecting the oldest dirty
2376          * because that's gumming up the works.
2377          */
2378
2379         if (!selected && dev->param.is_yaffs2 &&
2380             dev->gc_not_done >= (background ? 10 : 20)) {
2381                 yaffs2_find_oldest_dirty_seq(dev);
2382                 if (dev->oldest_dirty_block > 0) {
2383                         selected = dev->oldest_dirty_block;
2384                         dev->gc_dirtiest = selected;
2385                         dev->oldest_dirty_gc_count++;
2386                         bi = yaffs_get_block_info(dev, selected);
2387                         dev->gc_pages_in_use =
2388                             bi->pages_in_use - bi->soft_del_pages;
2389                 } else {
2390                         dev->gc_not_done = 0;
2391                 }
2392         }
2393
2394         if (selected) {
2395                 T(YAFFS_TRACE_GC,
2396                   (TSTR
2397                    ("GC Selected block %d with %d free, prioritised:%d"
2398                     TENDSTR), selected,
2399                    dev->param.chunks_per_block - dev->gc_pages_in_use,
2400                    prioritised));
2401
2402                 dev->n_gc_blocks++;
2403                 if (background)
2404                         dev->bg_gcs++;
2405
2406                 dev->gc_dirtiest = 0;
2407                 dev->gc_pages_in_use = 0;
2408                 dev->gc_not_done = 0;
2409                 if (dev->refresh_skip > 0)
2410                         dev->refresh_skip--;
2411         } else {
2412                 dev->gc_not_done++;
2413                 T(YAFFS_TRACE_GC,
2414                   (TSTR
2415                    ("GC none: finder %d skip %d threshold %d dirtiest %d using %d oldest %d%s"
2416                     TENDSTR), dev->gc_block_finder, dev->gc_not_done, threshold,
2417                    dev->gc_dirtiest, dev->gc_pages_in_use,
2418                    dev->oldest_dirty_block, background ? " bg" : ""));
2419         }
2420
2421         return selected;
2422 }
2423
2424 /* New garbage collector
2425  * If we're very low on erased blocks then we do aggressive garbage collection
2426  * otherwise we do "leasurely" garbage collection.
2427  * Aggressive gc looks further (whole array) and will accept less dirty blocks.
2428  * Passive gc only inspects smaller areas and will only accept more dirty blocks.
2429  *
2430  * The idea is to help clear out space in a more spread-out manner.
2431  * Dunno if it really does anything useful.
2432  */
2433 static int yaffs_check_gc(struct yaffs_dev *dev, int background)
2434 {
2435         int aggressive = 0;
2436         int gc_ok = YAFFS_OK;
2437         int max_tries = 0;
2438         int min_erased;
2439         int erased_chunks;
2440         int checkpt_block_adjust;
2441
2442         if (dev->param.gc_control && (dev->param.gc_control(dev) & 1) == 0)
2443                 return YAFFS_OK;
2444
2445         if (dev->gc_disable) {
2446                 /* Bail out so we don't get recursive gc */
2447                 return YAFFS_OK;
2448         }
2449
2450         /* This loop should pass the first time.
2451          * We'll only see looping here if the collection does not increase space.
2452          */
2453
2454         do {
2455                 max_tries++;
2456
2457                 checkpt_block_adjust = yaffs_calc_checkpt_blocks_required(dev);
2458
2459                 min_erased =
2460                     dev->param.n_reserved_blocks + checkpt_block_adjust + 1;
2461                 erased_chunks =
2462                     dev->n_erased_blocks * dev->param.chunks_per_block;
2463
2464                 /* If we need a block soon then do aggressive gc. */
2465                 if (dev->n_erased_blocks < min_erased)
2466                         aggressive = 1;
2467                 else {
2468                         if (!background
2469                             && erased_chunks > (dev->n_free_chunks / 4))
2470                                 break;
2471
2472                         if (dev->gc_skip > 20)
2473                                 dev->gc_skip = 20;
2474                         if (erased_chunks < dev->n_free_chunks / 2 ||
2475                             dev->gc_skip < 1 || background)
2476                                 aggressive = 0;
2477                         else {
2478                                 dev->gc_skip--;
2479                                 break;
2480                         }
2481                 }
2482
2483                 dev->gc_skip = 5;
2484
2485                 /* If we don't already have a block being gc'd then see if we should start another */
2486
2487                 if (dev->gc_block < 1 && !aggressive) {
2488                         dev->gc_block = yaffs2_find_refresh_block(dev);
2489                         dev->gc_chunk = 0;
2490                         dev->n_clean_ups = 0;
2491                 }
2492                 if (dev->gc_block < 1) {
2493                         dev->gc_block =
2494                             yaffs_find_gc_block(dev, aggressive, background);
2495                         dev->gc_chunk = 0;
2496                         dev->n_clean_ups = 0;
2497                 }
2498
2499                 if (dev->gc_block > 0) {
2500                         dev->all_gcs++;
2501                         if (!aggressive)
2502                                 dev->passive_gc_count++;
2503
2504                         T(YAFFS_TRACE_GC,
2505                           (TSTR
2506                            ("yaffs: GC n_erased_blocks %d aggressive %d"
2507                             TENDSTR), dev->n_erased_blocks, aggressive));
2508
2509                         gc_ok = yaffs_gc_block(dev, dev->gc_block, aggressive);
2510                 }
2511
2512                 if (dev->n_erased_blocks < (dev->param.n_reserved_blocks)
2513                     && dev->gc_block > 0) {
2514                         T(YAFFS_TRACE_GC,
2515                           (TSTR
2516                            ("yaffs: GC !!!no reclaim!!! n_erased_blocks %d after try %d block %d"
2517                             TENDSTR), dev->n_erased_blocks, max_tries,
2518                            dev->gc_block));
2519                 }
2520         } while ((dev->n_erased_blocks < dev->param.n_reserved_blocks) &&
2521                  (dev->gc_block > 0) && (max_tries < 2));
2522
2523         return aggressive ? gc_ok : YAFFS_OK;
2524 }
2525
2526 /*
2527  * yaffs_bg_gc()
2528  * Garbage collects. Intended to be called from a background thread.
2529  * Returns non-zero if at least half the free chunks are erased.
2530  */
2531 int yaffs_bg_gc(struct yaffs_dev *dev, unsigned urgency)
2532 {
2533         int erased_chunks = dev->n_erased_blocks * dev->param.chunks_per_block;
2534
2535         T(YAFFS_TRACE_BACKGROUND, (TSTR("Background gc %u" TENDSTR), urgency));
2536
2537         yaffs_check_gc(dev, 1);
2538         return erased_chunks > dev->n_free_chunks / 2;
2539 }
2540
2541 /*-------------------------  TAGS --------------------------------*/
2542
2543 static int yaffs_tags_match(const struct yaffs_ext_tags *tags, int obj_id,
2544                             int chunk_obj)
2545 {
2546         return (tags->chunk_id == chunk_obj &&
2547                 tags->obj_id == obj_id && !tags->is_deleted) ? 1 : 0;
2548
2549 }
2550
2551 /*-------------------- Data file manipulation -----------------*/
2552
2553 static int yaffs_find_chunk_in_file(struct yaffs_obj *in, int inode_chunk,
2554                                     struct yaffs_ext_tags *tags)
2555 {
2556         /*Get the Tnode, then get the level 0 offset chunk offset */
2557         struct yaffs_tnode *tn;
2558         int the_chunk = -1;
2559         struct yaffs_ext_tags local_tags;
2560         int ret_val = -1;
2561
2562         struct yaffs_dev *dev = in->my_dev;
2563
2564         if (!tags) {
2565                 /* Passed a NULL, so use our own tags space */
2566                 tags = &local_tags;
2567         }
2568
2569         tn = yaffs_find_tnode_0(dev, &in->variant.file_variant, inode_chunk);
2570
2571         if (tn) {
2572                 the_chunk = yaffs_get_group_base(dev, tn, inode_chunk);
2573
2574                 ret_val =
2575                     yaffs_find_chunk_in_group(dev, the_chunk, tags, in->obj_id,
2576                                               inode_chunk);
2577         }
2578         return ret_val;
2579 }
2580
2581 static int yaffs_find_del_file_chunk(struct yaffs_obj *in, int inode_chunk,
2582                                      struct yaffs_ext_tags *tags)
2583 {
2584         /* Get the Tnode, then get the level 0 offset chunk offset */
2585         struct yaffs_tnode *tn;
2586         int the_chunk = -1;
2587         struct yaffs_ext_tags local_tags;
2588
2589         struct yaffs_dev *dev = in->my_dev;
2590         int ret_val = -1;
2591
2592         if (!tags) {
2593                 /* Passed a NULL, so use our own tags space */
2594                 tags = &local_tags;
2595         }
2596
2597         tn = yaffs_find_tnode_0(dev, &in->variant.file_variant, inode_chunk);
2598
2599         if (tn) {
2600
2601                 the_chunk = yaffs_get_group_base(dev, tn, inode_chunk);
2602
2603                 ret_val =
2604                     yaffs_find_chunk_in_group(dev, the_chunk, tags, in->obj_id,
2605                                               inode_chunk);
2606
2607                 /* Delete the entry in the filestructure (if found) */
2608                 if (ret_val != -1)
2609                         yaffs_load_tnode_0(dev, tn, inode_chunk, 0);
2610         }
2611
2612         return ret_val;
2613 }
2614
2615 int yaffs_put_chunk_in_file(struct yaffs_obj *in, int inode_chunk,
2616                             int nand_chunk, int in_scan)
2617 {
2618         /* NB in_scan is zero unless scanning.
2619          * For forward scanning, in_scan is > 0;
2620          * for backward scanning in_scan is < 0
2621          *
2622          * nand_chunk = 0 is a dummy insert to make sure the tnodes are there.
2623          */
2624
2625         struct yaffs_tnode *tn;
2626         struct yaffs_dev *dev = in->my_dev;
2627         int existing_cunk;
2628         struct yaffs_ext_tags existing_tags;
2629         struct yaffs_ext_tags new_tags;
2630         unsigned existing_serial, new_serial;
2631
2632         if (in->variant_type != YAFFS_OBJECT_TYPE_FILE) {
2633                 /* Just ignore an attempt at putting a chunk into a non-file during scanning
2634                  * If it is not during Scanning then something went wrong!
2635                  */
2636                 if (!in_scan) {
2637                         T(YAFFS_TRACE_ERROR,
2638                           (TSTR
2639                            ("yaffs tragedy:attempt to put data chunk into a non-file"
2640                             TENDSTR)));
2641                         YBUG();
2642                 }
2643
2644                 yaffs_chunk_del(dev, nand_chunk, 1, __LINE__);
2645                 return YAFFS_OK;
2646         }
2647
2648         tn = yaffs_add_find_tnode_0(dev,
2649                                     &in->variant.file_variant,
2650                                     inode_chunk, NULL);
2651         if (!tn)
2652                 return YAFFS_FAIL;
2653
2654         if (!nand_chunk)
2655                 /* Dummy insert, bail now */
2656                 return YAFFS_OK;
2657
2658         existing_cunk = yaffs_get_group_base(dev, tn, inode_chunk);
2659
2660         if (in_scan != 0) {
2661                 /* If we're scanning then we need to test for duplicates
2662                  * NB This does not need to be efficient since it should only ever
2663                  * happen when the power fails during a write, then only one
2664                  * chunk should ever be affected.
2665                  *
2666                  * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
2667                  * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
2668                  */
2669
2670                 if (existing_cunk > 0) {
2671                         /* NB Right now existing chunk will not be real chunk_id if the chunk group size > 1
2672                          *    thus we have to do a FindChunkInFile to get the real chunk id.
2673                          *
2674                          * We have a duplicate now we need to decide which one to use:
2675                          *
2676                          * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
2677                          * Forward scanning YAFFS2: The new one is what we use, dump the old one.
2678                          * YAFFS1: Get both sets of tags and compare serial numbers.
2679                          */
2680
2681                         if (in_scan > 0) {
2682                                 /* Only do this for forward scanning */
2683                                 yaffs_rd_chunk_tags_nand(dev,
2684                                                          nand_chunk,
2685                                                          NULL, &new_tags);
2686
2687                                 /* Do a proper find */
2688                                 existing_cunk =
2689                                     yaffs_find_chunk_in_file(in, inode_chunk,
2690                                                              &existing_tags);
2691                         }
2692
2693                         if (existing_cunk <= 0) {
2694                                 /*Hoosterman - how did this happen? */
2695
2696                                 T(YAFFS_TRACE_ERROR,
2697                                   (TSTR
2698                                    ("yaffs tragedy: existing chunk < 0 in scan"
2699                                     TENDSTR)));
2700
2701                         }
2702
2703                         /* NB The deleted flags should be false, otherwise the chunks will
2704                          * not be loaded during a scan
2705                          */
2706
2707                         if (in_scan > 0) {
2708                                 new_serial = new_tags.serial_number;
2709                                 existing_serial = existing_tags.serial_number;
2710                         }
2711
2712                         if ((in_scan > 0) &&
2713                             (existing_cunk <= 0 ||
2714                              ((existing_serial + 1) & 3) == new_serial)) {
2715                                 /* Forward scanning.
2716                                  * Use new
2717                                  * Delete the old one and drop through to update the tnode
2718                                  */
2719                                 yaffs_chunk_del(dev, existing_cunk, 1,
2720                                                 __LINE__);
2721                         } else {
2722                                 /* Backward scanning or we want to use the existing one
2723                                  * Use existing.
2724                                  * Delete the new one and return early so that the tnode isn't changed
2725                                  */
2726                                 yaffs_chunk_del(dev, nand_chunk, 1, __LINE__);
2727                                 return YAFFS_OK;
2728                         }
2729                 }
2730
2731         }
2732
2733         if (existing_cunk == 0)
2734                 in->n_data_chunks++;
2735
2736         yaffs_load_tnode_0(dev, tn, inode_chunk, nand_chunk);
2737
2738         return YAFFS_OK;
2739 }
2740
2741 static int yaffs_rd_data_obj(struct yaffs_obj *in, int inode_chunk, u8 * buffer)
2742 {
2743         int nand_chunk = yaffs_find_chunk_in_file(in, inode_chunk, NULL);
2744
2745         if (nand_chunk >= 0)
2746                 return yaffs_rd_chunk_tags_nand(in->my_dev, nand_chunk,
2747                                                 buffer, NULL);
2748         else {
2749                 T(YAFFS_TRACE_NANDACCESS,
2750                   (TSTR("Chunk %d not found zero instead" TENDSTR),
2751                    nand_chunk));
2752                 /* get sane (zero) data if you read a hole */
2753                 memset(buffer, 0, in->my_dev->data_bytes_per_chunk);
2754                 return 0;
2755         }
2756
2757 }
2758
2759 void yaffs_chunk_del(struct yaffs_dev *dev, int chunk_id, int mark_flash,
2760                      int lyn)
2761 {
2762         int block;
2763         int page;
2764         struct yaffs_ext_tags tags;
2765         struct yaffs_block_info *bi;
2766
2767         if (chunk_id <= 0)
2768                 return;
2769
2770         dev->n_deletions++;
2771         block = chunk_id / dev->param.chunks_per_block;
2772         page = chunk_id % dev->param.chunks_per_block;
2773
2774         if (!yaffs_check_chunk_bit(dev, block, page))
2775                 T(YAFFS_TRACE_VERIFY,
2776                   (TSTR("Deleting invalid chunk %d" TENDSTR), chunk_id));
2777
2778         bi = yaffs_get_block_info(dev, block);
2779
2780         yaffs2_update_oldest_dirty_seq(dev, block, bi);
2781
2782         T(YAFFS_TRACE_DELETION,
2783           (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunk_id));
2784
2785         if (!dev->param.is_yaffs2 && mark_flash &&
2786             bi->block_state != YAFFS_BLOCK_STATE_COLLECTING) {
2787
2788                 yaffs_init_tags(&tags);
2789
2790                 tags.is_deleted = 1;
2791
2792                 yaffs_wr_chunk_tags_nand(dev, chunk_id, NULL, &tags);
2793                 yaffs_handle_chunk_update(dev, chunk_id, &tags);
2794         } else {
2795                 dev->n_unmarked_deletions++;
2796         }
2797
2798         /* Pull out of the management area.
2799          * If the whole block became dirty, this will kick off an erasure.
2800          */
2801         if (bi->block_state == YAFFS_BLOCK_STATE_ALLOCATING ||
2802             bi->block_state == YAFFS_BLOCK_STATE_FULL ||
2803             bi->block_state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
2804             bi->block_state == YAFFS_BLOCK_STATE_COLLECTING) {
2805                 dev->n_free_chunks++;
2806
2807                 yaffs_clear_chunk_bit(dev, block, page);
2808
2809                 bi->pages_in_use--;
2810
2811                 if (bi->pages_in_use == 0 &&
2812                     !bi->has_shrink_hdr &&
2813                     bi->block_state != YAFFS_BLOCK_STATE_ALLOCATING &&
2814                     bi->block_state != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
2815                         yaffs_block_became_dirty(dev, block);
2816                 }
2817
2818         }
2819
2820 }
2821
2822 static int yaffs_wr_data_obj(struct yaffs_obj *in, int inode_chunk,
2823                              const u8 * buffer, int n_bytes, int use_reserve)
2824 {
2825         /* Find old chunk Need to do this to get serial number
2826          * Write new one and patch into tree.
2827          * Invalidate old tags.
2828          */
2829
2830         int prev_chunk_id;
2831         struct yaffs_ext_tags prev_tags;
2832
2833         int new_chunk_id;
2834         struct yaffs_ext_tags new_tags;
2835
2836         struct yaffs_dev *dev = in->my_dev;
2837
2838         yaffs_check_gc(dev, 0);
2839
2840         /* Get the previous chunk at this location in the file if it exists.
2841          * If it does not exist then put a zero into the tree. This creates
2842          * the tnode now, rather than later when it is harder to clean up.
2843          */
2844         prev_chunk_id = yaffs_find_chunk_in_file(in, inode_chunk, &prev_tags);
2845         if (prev_chunk_id < 1 &&
2846             !yaffs_put_chunk_in_file(in, inode_chunk, 0, 0))
2847                 return 0;
2848
2849         /* Set up new tags */
2850         yaffs_init_tags(&new_tags);
2851
2852         new_tags.chunk_id = inode_chunk;
2853         new_tags.obj_id = in->obj_id;
2854         new_tags.serial_number =
2855             (prev_chunk_id > 0) ? prev_tags.serial_number + 1 : 1;
2856         new_tags.n_bytes = n_bytes;
2857
2858         if (n_bytes < 1 || n_bytes > dev->param.total_bytes_per_chunk) {
2859                 T(YAFFS_TRACE_ERROR,
2860                   (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR),
2861                    n_bytes));
2862                 YBUG();
2863         }
2864
2865         new_chunk_id =
2866             yaffs_write_new_chunk(dev, buffer, &new_tags, use_reserve);
2867
2868         if (new_chunk_id > 0) {
2869                 yaffs_put_chunk_in_file(in, inode_chunk, new_chunk_id, 0);
2870
2871                 if (prev_chunk_id > 0)
2872                         yaffs_chunk_del(dev, prev_chunk_id, 1, __LINE__);
2873
2874                 yaffs_verify_file_sane(in);
2875         }
2876         return new_chunk_id;
2877
2878 }
2879
2880 /* UpdateObjectHeader updates the header on NAND for an object.
2881  * If name is not NULL, then that new name is used.
2882  */
2883 int yaffs_update_oh(struct yaffs_obj *in, const YCHAR * name, int force,
2884                     int is_shrink, int shadows, struct yaffs_xattr_mod *xmod)
2885 {
2886
2887         struct yaffs_block_info *bi;
2888
2889         struct yaffs_dev *dev = in->my_dev;
2890
2891         int prev_chunk_id;
2892         int ret_val = 0;
2893         int result = 0;
2894
2895         int new_chunk_id;
2896         struct yaffs_ext_tags new_tags;
2897         struct yaffs_ext_tags old_tags;
2898         const YCHAR *alias = NULL;
2899
2900         u8 *buffer = NULL;
2901         YCHAR old_name[YAFFS_MAX_NAME_LENGTH + 1];
2902
2903         struct yaffs_obj_hdr *oh = NULL;
2904
2905         yaffs_strcpy(old_name, _Y("silly old name"));
2906
2907         if (!in->fake || in == dev->root_dir || /* The root_dir should also be saved */
2908             force || xmod) {
2909
2910                 yaffs_check_gc(dev, 0);
2911                 yaffs_check_obj_details_loaded(in);
2912
2913                 buffer = yaffs_get_temp_buffer(in->my_dev, __LINE__);
2914                 oh = (struct yaffs_obj_hdr *)buffer;
2915
2916                 prev_chunk_id = in->hdr_chunk;
2917
2918                 if (prev_chunk_id > 0) {
2919                         result = yaffs_rd_chunk_tags_nand(dev, prev_chunk_id,
2920                                                           buffer, &old_tags);
2921
2922                         yaffs_verify_oh(in, oh, &old_tags, 0);
2923
2924                         memcpy(old_name, oh->name, sizeof(oh->name));
2925                         memset(buffer, 0xFF, sizeof(struct yaffs_obj_hdr));
2926                 } else {
2927                         memset(buffer, 0xFF, dev->data_bytes_per_chunk);
2928                 }
2929
2930                 oh->type = in->variant_type;
2931                 oh->yst_mode = in->yst_mode;
2932                 oh->shadows_obj = oh->inband_shadowed_obj_id = shadows;
2933
2934                 yaffs_load_attribs_oh(oh, in);
2935
2936                 if (in->parent)
2937                         oh->parent_obj_id = in->parent->obj_id;
2938                 else
2939                         oh->parent_obj_id = 0;
2940
2941                 if (name && *name) {
2942                         memset(oh->name, 0, sizeof(oh->name));
2943                         yaffs_load_oh_from_name(dev, oh->name, name);
2944                 } else if (prev_chunk_id > 0) {
2945                         memcpy(oh->name, old_name, sizeof(oh->name));
2946                 } else {
2947                         memset(oh->name, 0, sizeof(oh->name));
2948                 }
2949
2950                 oh->is_shrink = is_shrink;
2951
2952                 switch (in->variant_type) {
2953                 case YAFFS_OBJECT_TYPE_UNKNOWN:
2954                         /* Should not happen */
2955                         break;
2956                 case YAFFS_OBJECT_TYPE_FILE:
2957                         oh->file_size =
2958                             (oh->parent_obj_id == YAFFS_OBJECTID_DELETED
2959                              || oh->parent_obj_id ==
2960                              YAFFS_OBJECTID_UNLINKED) ? 0 : in->
2961                             variant.file_variant.file_size;
2962                         break;
2963                 case YAFFS_OBJECT_TYPE_HARDLINK:
2964                         oh->equiv_id = in->variant.hardlink_variant.equiv_id;
2965                         break;
2966                 case YAFFS_OBJECT_TYPE_SPECIAL:
2967                         /* Do nothing */
2968                         break;
2969                 case YAFFS_OBJECT_TYPE_DIRECTORY:
2970                         /* Do nothing */
2971                         break;
2972                 case YAFFS_OBJECT_TYPE_SYMLINK:
2973                         alias = in->variant.symlink_variant.alias;
2974                         if (!alias)
2975                                 alias = _Y("no alias");
2976                         yaffs_strncpy(oh->alias, alias, YAFFS_MAX_ALIAS_LENGTH);
2977                         oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
2978                         break;
2979                 }
2980
2981                 /* process any xattrib modifications */
2982                 if (xmod)
2983                         yaffs_apply_xattrib_mod(in, (char *)buffer, xmod);
2984
2985                 /* Tags */
2986                 yaffs_init_tags(&new_tags);
2987                 in->serial++;
2988                 new_tags.chunk_id = 0;
2989                 new_tags.obj_id = in->obj_id;
2990                 new_tags.serial_number = in->serial;
2991
2992                 /* Add extra info for file header */
2993
2994                 new_tags.extra_available = 1;
2995                 new_tags.extra_parent_id = oh->parent_obj_id;
2996                 new_tags.extra_length = oh->file_size;
2997                 new_tags.extra_is_shrink = oh->is_shrink;
2998                 new_tags.extra_equiv_id = oh->equiv_id;
2999                 new_tags.extra_shadows = (oh->shadows_obj > 0) ? 1 : 0;
3000                 new_tags.extra_obj_type = in->variant_type;
3001
3002                 yaffs_verify_oh(in, oh, &new_tags, 1);
3003
3004                 /* Create new chunk in NAND */
3005                 new_chunk_id =
3006                     yaffs_write_new_chunk(dev, buffer, &new_tags,
3007                                           (prev_chunk_id > 0) ? 1 : 0);
3008
3009                 if (new_chunk_id >= 0) {
3010
3011                         in->hdr_chunk = new_chunk_id;
3012
3013                         if (prev_chunk_id > 0) {
3014                                 yaffs_chunk_del(dev, prev_chunk_id, 1,
3015                                                 __LINE__);
3016                         }
3017
3018                         if (!yaffs_obj_cache_dirty(in))
3019                                 in->dirty = 0;
3020
3021                         /* If this was a shrink, then mark the block that the chunk lives on */
3022                         if (is_shrink) {
3023                                 bi = yaffs_get_block_info(in->my_dev,
3024                                                           new_chunk_id /
3025                                                           in->my_dev->param.
3026                                                           chunks_per_block);
3027                                 bi->has_shrink_hdr = 1;
3028                         }
3029
3030                 }
3031
3032                 ret_val = new_chunk_id;
3033
3034         }
3035
3036         if (buffer)
3037                 yaffs_release_temp_buffer(dev, buffer, __LINE__);
3038
3039         return ret_val;
3040 }
3041
3042 /*------------------------ Short Operations Cache ----------------------------------------
3043  *   In many situations where there is no high level buffering  a lot of
3044  *   reads might be short sequential reads, and a lot of writes may be short
3045  *   sequential writes. eg. scanning/writing a jpeg file.
3046  *   In these cases, a short read/write cache can provide a huge perfomance
3047  *   benefit with dumb-as-a-rock code.
3048  *   In Linux, the page cache provides read buffering and the short op cache 
3049  *   provides write buffering.
3050  *
3051  *   There are a limited number (~10) of cache chunks per device so that we don't
3052  *   need a very intelligent search.
3053  */
3054
3055 static int yaffs_obj_cache_dirty(struct yaffs_obj *obj)
3056 {
3057         struct yaffs_dev *dev = obj->my_dev;
3058         int i;
3059         struct yaffs_cache *cache;
3060         int n_caches = obj->my_dev->param.n_caches;
3061
3062         for (i = 0; i < n_caches; i++) {
3063                 cache = &dev->cache[i];
3064                 if (cache->object == obj && cache->dirty)
3065                         return 1;
3066         }
3067
3068         return 0;
3069 }
3070
3071 static void yaffs_flush_file_cache(struct yaffs_obj *obj)
3072 {
3073         struct yaffs_dev *dev = obj->my_dev;
3074         int lowest = -99;       /* Stop compiler whining. */
3075         int i;
3076         struct yaffs_cache *cache;
3077         int chunk_written = 0;
3078         int n_caches = obj->my_dev->param.n_caches;
3079
3080         if (n_caches > 0) {
3081                 do {
3082                         cache = NULL;
3083
3084                         /* Find the dirty cache for this object with the lowest chunk id. */
3085                         for (i = 0; i < n_caches; i++) {
3086                                 if (dev->cache[i].object == obj &&
3087                                     dev->cache[i].dirty) {
3088                                         if (!cache
3089                                             || dev->cache[i].chunk_id <
3090                                             lowest) {
3091                                                 cache = &dev->cache[i];
3092                                                 lowest = cache->chunk_id;
3093                                         }
3094                                 }
3095                         }
3096
3097                         if (cache && !cache->locked) {
3098                                 /* Write it out and free it up */
3099
3100                                 chunk_written =
3101                                     yaffs_wr_data_obj(cache->object,
3102                                                       cache->chunk_id,
3103                                                       cache->data,
3104                                                       cache->n_bytes, 1);
3105                                 cache->dirty = 0;
3106                                 cache->object = NULL;
3107                         }
3108
3109                 } while (cache && chunk_written > 0);
3110
3111                 if (cache) {
3112                         /* Hoosterman, disk full while writing cache out. */
3113                         T(YAFFS_TRACE_ERROR,
3114                           (TSTR
3115                            ("yaffs tragedy: no space during cache write"
3116                             TENDSTR)));
3117
3118                 }
3119         }
3120
3121 }
3122
3123 /*yaffs_flush_whole_cache(dev)
3124  *
3125  *
3126  */
3127
3128 void yaffs_flush_whole_cache(struct yaffs_dev *dev)
3129 {
3130         struct yaffs_obj *obj;
3131         int n_caches = dev->param.n_caches;
3132         int i;
3133
3134         /* Find a dirty object in the cache and flush it...
3135          * until there are no further dirty objects.
3136          */
3137         do {
3138                 obj = NULL;
3139                 for (i = 0; i < n_caches && !obj; i++) {
3140                         if (dev->cache[i].object && dev->cache[i].dirty)
3141                                 obj = dev->cache[i].object;
3142
3143                 }
3144                 if (obj)
3145                         yaffs_flush_file_cache(obj);
3146
3147         } while (obj);
3148
3149 }
3150
3151 /* Grab us a cache chunk for use.
3152  * First look for an empty one.
3153  * Then look for the least recently used non-dirty one.
3154  * Then look for the least recently used dirty one...., flush and look again.
3155  */
3156 static struct yaffs_cache *yaffs_grab_chunk_worker(struct yaffs_dev *dev)
3157 {
3158         int i;
3159
3160         if (dev->param.n_caches > 0) {
3161                 for (i = 0; i < dev->param.n_caches; i++) {
3162                         if (!dev->cache[i].object)
3163                                 return &dev->cache[i];
3164                 }
3165         }
3166
3167         return NULL;
3168 }
3169
3170 static struct yaffs_cache *yaffs_grab_chunk_cache(struct yaffs_dev *dev)
3171 {
3172         struct yaffs_cache *cache;
3173         struct yaffs_obj *the_obj;
3174         int usage;
3175         int i;
3176         int pushout;
3177
3178         if (dev->param.n_caches > 0) {
3179                 /* Try find a non-dirty one... */
3180
3181                 cache = yaffs_grab_chunk_worker(dev);
3182
3183                 if (!cache) {
3184                         /* They were all dirty, find the last recently used object and flush
3185                          * its cache, then  find again.
3186                          * NB what's here is not very accurate, we actually flush the object
3187                          * the last recently used page.
3188                          */
3189
3190                         /* With locking we can't assume we can use entry zero */
3191
3192                         the_obj = NULL;
3193                         usage = -1;
3194                         cache = NULL;
3195                         pushout = -1;
3196
3197                         for (i = 0; i < dev->param.n_caches; i++) {
3198                                 if (dev->cache[i].object &&
3199                                     !dev->cache[i].locked &&
3200                                     (dev->cache[i].last_use < usage
3201                                      || !cache)) {
3202                                         usage = dev->cache[i].last_use;
3203                                         the_obj = dev->cache[i].object;
3204                                         cache = &dev->cache[i];
3205                                         pushout = i;
3206                                 }
3207                         }
3208
3209                         if (!cache || cache->dirty) {
3210                                 /* Flush and try again */
3211                                 yaffs_flush_file_cache(the_obj);
3212                                 cache = yaffs_grab_chunk_worker(dev);
3213                         }
3214
3215                 }
3216                 return cache;
3217         } else {
3218                 return NULL;
3219         }
3220 }
3221
3222 /* Find a cached chunk */
3223 static struct yaffs_cache *yaffs_find_chunk_cache(const struct yaffs_obj *obj,
3224                                                   int chunk_id)
3225 {
3226         struct yaffs_dev *dev = obj->my_dev;
3227         int i;
3228         if (dev->param.n_caches > 0) {
3229                 for (i = 0; i < dev->param.n_caches; i++) {
3230                         if (dev->cache[i].object == obj &&
3231                             dev->cache[i].chunk_id == chunk_id) {
3232                                 dev->cache_hits++;
3233
3234                                 return &dev->cache[i];
3235                         }
3236                 }
3237         }
3238         return NULL;
3239 }
3240
3241 /* Mark the chunk for the least recently used algorithym */
3242 static void yaffs_use_cache(struct yaffs_dev *dev, struct yaffs_cache *cache,
3243                             int is_write)
3244 {
3245
3246         if (dev->param.n_caches > 0) {
3247                 if (dev->cache_last_use < 0 || dev->cache_last_use > 100000000) {
3248                         /* Reset the cache usages */
3249                         int i;
3250                         for (i = 1; i < dev->param.n_caches; i++)
3251                                 dev->cache[i].last_use = 0;
3252
3253                         dev->cache_last_use = 0;
3254                 }
3255
3256                 dev->cache_last_use++;
3257
3258                 cache->last_use = dev->cache_last_use;
3259
3260                 if (is_write)
3261                         cache->dirty = 1;
3262         }
3263 }
3264
3265 /* Invalidate a single cache page.
3266  * Do this when a whole page gets written,
3267  * ie the short cache for this page is no longer valid.
3268  */
3269 static void yaffs_invalidate_chunk_cache(struct yaffs_obj *object, int chunk_id)
3270 {
3271         if (object->my_dev->param.n_caches > 0) {
3272                 struct yaffs_cache *cache =
3273                     yaffs_find_chunk_cache(object, chunk_id);
3274
3275                 if (cache)
3276                         cache->object = NULL;
3277         }
3278 }
3279
3280 /* Invalidate all the cache pages associated with this object
3281  * Do this whenever ther file is deleted or resized.
3282  */
3283 static void yaffs_invalidate_whole_cache(struct yaffs_obj *in)
3284 {
3285         int i;
3286         struct yaffs_dev *dev = in->my_dev;
3287
3288         if (dev->param.n_caches > 0) {
3289                 /* Invalidate it. */
3290                 for (i = 0; i < dev->param.n_caches; i++) {
3291                         if (dev->cache[i].object == in)
3292                                 dev->cache[i].object = NULL;
3293                 }
3294         }
3295 }
3296
3297 /*--------------------- File read/write ------------------------
3298  * Read and write have very similar structures.
3299  * In general the read/write has three parts to it
3300  * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3301  * Some complete chunks
3302  * An incomplete chunk to end off with
3303  *
3304  * Curve-balls: the first chunk might also be the last chunk.
3305  */
3306
3307 int yaffs_file_rd(struct yaffs_obj *in, u8 * buffer, loff_t offset, int n_bytes)
3308 {
3309
3310         int chunk;
3311         u32 start;
3312         int n_copy;
3313         int n = n_bytes;
3314         int n_done = 0;
3315         struct yaffs_cache *cache;
3316
3317         struct yaffs_dev *dev;
3318
3319         dev = in->my_dev;
3320
3321         while (n > 0) {
3322                 /* chunk = offset / dev->data_bytes_per_chunk + 1; */
3323                 /* start = offset % dev->data_bytes_per_chunk; */
3324                 yaffs_addr_to_chunk(dev, offset, &chunk, &start);
3325                 chunk++;
3326
3327                 /* OK now check for the curveball where the start and end are in
3328                  * the same chunk.
3329                  */
3330                 if ((start + n) < dev->data_bytes_per_chunk)
3331                         n_copy = n;
3332                 else
3333                         n_copy = dev->data_bytes_per_chunk - start;
3334
3335                 cache = yaffs_find_chunk_cache(in, chunk);
3336
3337                 /* If the chunk is already in the cache or it is less than a whole chunk
3338                  * or we're using inband tags then use the cache (if there is caching)
3339                  * else bypass the cache.
3340                  */
3341                 if (cache || n_copy != dev->data_bytes_per_chunk
3342                     || dev->param.inband_tags) {
3343                         if (dev->param.n_caches > 0) {
3344
3345                                 /* If we can't find the data in the cache, then load it up. */
3346
3347                                 if (!cache) {
3348                                         cache =
3349                                             yaffs_grab_chunk_cache(in->my_dev);
3350                                         cache->object = in;
3351                                         cache->chunk_id = chunk;
3352                                         cache->dirty = 0;
3353                                         cache->locked = 0;
3354                                         yaffs_rd_data_obj(in, chunk,
3355                                                           cache->data);
3356                                         cache->n_bytes = 0;
3357                                 }
3358
3359                                 yaffs_use_cache(dev, cache, 0);
3360
3361                                 cache->locked = 1;
3362
3363                                 memcpy(buffer, &cache->data[start], n_copy);
3364
3365                                 cache->locked = 0;
3366                         } else {
3367                                 /* Read into the local buffer then copy.. */
3368
3369                                 u8 *local_buffer =
3370                                     yaffs_get_temp_buffer(dev, __LINE__);
3371                                 yaffs_rd_data_obj(in, chunk, local_buffer);
3372
3373                                 memcpy(buffer, &local_buffer[start], n_copy);
3374
3375                                 yaffs_release_temp_buffer(dev, local_buffer,
3376                                                           __LINE__);
3377                         }
3378
3379                 } else {
3380
3381                         /* A full chunk. Read directly into the supplied buffer. */
3382                         yaffs_rd_data_obj(in, chunk, buffer);
3383
3384                 }
3385
3386                 n -= n_copy;
3387                 offset += n_copy;
3388                 buffer += n_copy;
3389                 n_done += n_copy;
3390
3391         }
3392
3393         return n_done;
3394 }
3395
3396 int yaffs_do_file_wr(struct yaffs_obj *in, const u8 * buffer, loff_t offset,
3397                      int n_bytes, int write_trhrough)
3398 {
3399
3400         int chunk;
3401         u32 start;
3402         int n_copy;
3403         int n = n_bytes;
3404         int n_done = 0;
3405         int n_writeback;
3406         int start_write = offset;
3407         int chunk_written = 0;
3408         u32 n_bytes_read;
3409         u32 chunk_start;
3410
3411         struct yaffs_dev *dev;
3412
3413         dev = in->my_dev;
3414
3415         while (n > 0 && chunk_written >= 0) {
3416                 yaffs_addr_to_chunk(dev, offset, &chunk, &start);
3417
3418                 if (chunk * dev->data_bytes_per_chunk + start != offset ||
3419                     start >= dev->data_bytes_per_chunk) {
3420                         T(YAFFS_TRACE_ERROR,
3421                           (TSTR
3422                            ("AddrToChunk of offset %d gives chunk %d start %d"
3423                             TENDSTR), (int)offset, chunk, start));
3424                 }
3425                 chunk++;        /* File pos to chunk in file offset */
3426
3427                 /* OK now check for the curveball where the start and end are in
3428                  * the same chunk.
3429                  */
3430
3431                 if ((start + n) < dev->data_bytes_per_chunk) {
3432                         n_copy = n;
3433
3434                         /* Now folks, to calculate how many bytes to write back....
3435                          * If we're overwriting and not writing to then end of file then
3436                          * we need to write back as much as was there before.
3437                          */
3438
3439                         chunk_start = ((chunk - 1) * dev->data_bytes_per_chunk);
3440
3441                         if (chunk_start > in->variant.file_variant.file_size)
3442                                 n_bytes_read = 0;       /* Past end of file */
3443                         else
3444                                 n_bytes_read =
3445                                     in->variant.file_variant.file_size -
3446                                     chunk_start;
3447
3448                         if (n_bytes_read > dev->data_bytes_per_chunk)
3449                                 n_bytes_read = dev->data_bytes_per_chunk;
3450
3451                         n_writeback =
3452                             (n_bytes_read >
3453                              (start + n)) ? n_bytes_read : (start + n);
3454
3455                         if (n_writeback < 0
3456                             || n_writeback > dev->data_bytes_per_chunk)
3457                                 YBUG();
3458
3459                 } else {
3460                         n_copy = dev->data_bytes_per_chunk - start;
3461                         n_writeback = dev->data_bytes_per_chunk;
3462                 }
3463
3464                 if (n_copy != dev->data_bytes_per_chunk
3465                     || dev->param.inband_tags) {
3466                         /* An incomplete start or end chunk (or maybe both start and end chunk),
3467                          * or we're using inband tags, so we want to use the cache buffers.
3468                          */
3469                         if (dev->param.n_caches > 0) {
3470                                 struct yaffs_cache *cache;
3471                                 /* If we can't find the data in the cache, then load the cache */
3472                                 cache = yaffs_find_chunk_cache(in, chunk);
3473
3474                                 if (!cache
3475                                     && yaffs_check_alloc_available(dev, 1)) {
3476                                         cache = yaffs_grab_chunk_cache(dev);
3477                                         cache->object = in;
3478                                         cache->chunk_id = chunk;
3479                                         cache->dirty = 0;
3480                                         cache->locked = 0;
3481                                         yaffs_rd_data_obj(in, chunk,
3482                                                           cache->data);
3483                                 } else if (cache &&
3484                                            !cache->dirty &&
3485                                            !yaffs_check_alloc_available(dev,
3486                                                                         1)) {
3487                                         /* Drop the cache if it was a read cache item and
3488                                          * no space check has been made for it.
3489                                          */
3490                                         cache = NULL;
3491                                 }
3492
3493                                 if (cache) {
3494                                         yaffs_use_cache(dev, cache, 1);
3495                                         cache->locked = 1;
3496
3497                                         memcpy(&cache->data[start], buffer,
3498                                                n_copy);
3499
3500                                         cache->locked = 0;
3501                                         cache->n_bytes = n_writeback;
3502
3503                                         if (write_trhrough) {
3504                                                 chunk_written =
3505                                                     yaffs_wr_data_obj
3506                                                     (cache->object,
3507                                                      cache->chunk_id,
3508                                                      cache->data,
3509                                                      cache->n_bytes, 1);
3510                                                 cache->dirty = 0;
3511                                         }
3512
3513                                 } else {
3514                                         chunk_written = -1;     /* fail the write */
3515                                 }
3516                         } else {
3517                                 /* An incomplete start or end chunk (or maybe both start and end chunk)
3518                                  * Read into the local buffer then copy, then copy over and write back.
3519                                  */
3520
3521                                 u8 *local_buffer =
3522                                     yaffs_get_temp_buffer(dev, __LINE__);
3523
3524                                 yaffs_rd_data_obj(in, chunk, local_buffer);
3525
3526                                 memcpy(&local_buffer[start], buffer, n_copy);
3527
3528                                 chunk_written =
3529                                     yaffs_wr_data_obj(in, chunk,
3530                                                       local_buffer,
3531                                                       n_writeback, 0);
3532
3533                                 yaffs_release_temp_buffer(dev, local_buffer,
3534                                                           __LINE__);
3535
3536                         }
3537
3538                 } else {
3539                         /* A full chunk. Write directly from the supplied buffer. */
3540
3541                         chunk_written =
3542                             yaffs_wr_data_obj(in, chunk, buffer,
3543                                               dev->data_bytes_per_chunk, 0);
3544
3545                         /* Since we've overwritten the cached data, we better invalidate it. */
3546                         yaffs_invalidate_chunk_cache(in, chunk);
3547                 }
3548
3549                 if (chunk_written >= 0) {
3550                         n -= n_copy;
3551                         offset += n_copy;
3552                         buffer += n_copy;
3553                         n_done += n_copy;
3554                 }
3555
3556         }
3557
3558         /* Update file object */
3559
3560         if ((start_write + n_done) > in->variant.file_variant.file_size)
3561                 in->variant.file_variant.file_size = (start_write + n_done);
3562
3563         in->dirty = 1;
3564
3565         return n_done;
3566 }
3567
3568 int yaffs_wr_file(struct yaffs_obj *in, const u8 * buffer, loff_t offset,
3569                   int n_bytes, int write_trhrough)
3570 {
3571         yaffs2_handle_hole(in, offset);
3572         return yaffs_do_file_wr(in, buffer, offset, n_bytes, write_trhrough);
3573 }
3574
3575 /* ---------------------- File resizing stuff ------------------ */
3576
3577 static void yaffs_prune_chunks(struct yaffs_obj *in, int new_size)
3578 {
3579
3580         struct yaffs_dev *dev = in->my_dev;
3581         int old_size = in->variant.file_variant.file_size;
3582
3583         int last_del = 1 + (old_size - 1) / dev->data_bytes_per_chunk;
3584
3585         int start_del = 1 + (new_size + dev->data_bytes_per_chunk - 1) /
3586             dev->data_bytes_per_chunk;
3587         int i;
3588         int chunk_id;
3589
3590         /* Delete backwards so that we don't end up with holes if
3591          * power is lost part-way through the operation.
3592          */
3593         for (i = last_del; i >= start_del; i--) {
3594                 /* NB this could be optimised somewhat,
3595                  * eg. could retrieve the tags and write them without
3596                  * using yaffs_chunk_del
3597                  */
3598
3599                 chunk_id = yaffs_find_del_file_chunk(in, i, NULL);
3600                 if (chunk_id > 0) {
3601                         if (chunk_id <
3602                             (dev->internal_start_block *
3603                              dev->param.chunks_per_block)
3604                             || chunk_id >=
3605                             ((dev->internal_end_block +
3606                               1) * dev->param.chunks_per_block)) {
3607                                 T(YAFFS_TRACE_ALWAYS,
3608                                   (TSTR
3609                                    ("Found daft chunk_id %d for %d" TENDSTR),
3610                                    chunk_id, i));
3611                         } else {
3612                                 in->n_data_chunks--;
3613                                 yaffs_chunk_del(dev, chunk_id, 1, __LINE__);
3614                         }
3615                 }
3616         }
3617
3618 }
3619
3620 void yaffs_resize_file_down(struct yaffs_obj *obj, loff_t new_size)
3621 {
3622         int new_full;
3623         u32 new_partial;
3624         struct yaffs_dev *dev = obj->my_dev;
3625
3626         yaffs_addr_to_chunk(dev, new_size, &new_full, &new_partial);
3627
3628         yaffs_prune_chunks(obj, new_size);
3629
3630         if (new_partial != 0) {
3631                 int last_chunk = 1 + new_full;
3632                 u8 *local_buffer = yaffs_get_temp_buffer(dev, __LINE__);
3633
3634                 /* Got to read and rewrite the last chunk with its new size and zero pad */
3635                 yaffs_rd_data_obj(obj, last_chunk, local_buffer);
3636                 memset(local_buffer + new_partial, 0,
3637                        dev->data_bytes_per_chunk - new_partial);
3638
3639                 yaffs_wr_data_obj(obj, last_chunk, local_buffer,
3640                                   new_partial, 1);
3641
3642                 yaffs_release_temp_buffer(dev, local_buffer, __LINE__);
3643         }
3644
3645         obj->variant.file_variant.file_size = new_size;
3646
3647         yaffs_prune_tree(dev, &obj->variant.file_variant);
3648 }
3649
3650 int yaffs_resize_file(struct yaffs_obj *in, loff_t new_size)
3651 {
3652         struct yaffs_dev *dev = in->my_dev;
3653         int old_size = in->variant.file_variant.file_size;
3654
3655         yaffs_flush_file_cache(in);
3656         yaffs_invalidate_whole_cache(in);
3657
3658         yaffs_check_gc(dev, 0);
3659
3660         if (in->variant_type != YAFFS_OBJECT_TYPE_FILE)
3661                 return YAFFS_FAIL;
3662
3663         if (new_size == old_size)
3664                 return YAFFS_OK;
3665
3666         if (new_size > old_size) {
3667                 yaffs2_handle_hole(in, new_size);
3668                 in->variant.file_variant.file_size = new_size;
3669         } else {
3670                 /* new_size < old_size */
3671                 yaffs_resize_file_down(in, new_size);
3672         }
3673
3674         /* Write a new object header to reflect the resize.
3675          * show we've shrunk the file, if need be
3676          * Do this only if the file is not in the deleted directories
3677          * and is not shadowed.
3678          */
3679         if (in->parent &&
3680             !in->is_shadowed &&
3681             in->parent->obj_id != YAFFS_OBJECTID_UNLINKED &&
3682             in->parent->obj_id != YAFFS_OBJECTID_DELETED)
3683                 yaffs_update_oh(in, NULL, 0, 0, 0, NULL);
3684
3685         return YAFFS_OK;
3686 }
3687
3688 int yaffs_flush_file(struct yaffs_obj *in, int update_time, int data_sync)
3689 {
3690         int ret_val;
3691         if (in->dirty) {
3692                 yaffs_flush_file_cache(in);
3693                 if (data_sync)  /* Only sync data */
3694                         ret_val = YAFFS_OK;
3695                 else {
3696                         if (update_time)
3697                                 yaffs_load_current_time(in, 0, 0);
3698
3699                         ret_val = (yaffs_update_oh(in, NULL, 0, 0, 0, NULL) >=
3700                                    0) ? YAFFS_OK : YAFFS_FAIL;
3701                 }
3702         } else {
3703                 ret_val = YAFFS_OK;
3704         }
3705
3706         return ret_val;
3707
3708 }
3709
3710 static int yaffs_generic_obj_del(struct yaffs_obj *in)
3711 {
3712
3713         /* First off, invalidate the file's data in the cache, without flushing. */
3714         yaffs_invalidate_whole_cache(in);
3715
3716         if (in->my_dev->param.is_yaffs2 && (in->parent != in->my_dev->del_dir)) {
3717                 /* Move to the unlinked directory so we have a record that it was deleted. */
3718                 yaffs_change_obj_name(in, in->my_dev->del_dir, _Y("deleted"), 0,
3719                                       0);
3720
3721         }
3722
3723         yaffs_remove_obj_from_dir(in);
3724         yaffs_chunk_del(in->my_dev, in->hdr_chunk, 1, __LINE__);
3725         in->hdr_chunk = 0;
3726
3727         yaffs_free_obj(in);
3728         return YAFFS_OK;
3729
3730 }
3731
3732 /* yaffs_del_file deletes the whole file data
3733  * and the inode associated with the file.
3734  * It does not delete the links associated with the file.
3735  */
3736 static int yaffs_unlink_file_if_needed(struct yaffs_obj *in)
3737 {
3738
3739         int ret_val;
3740         int del_now = 0;
3741         struct yaffs_dev *dev = in->my_dev;
3742
3743         if (!in->my_inode)
3744                 del_now = 1;
3745
3746         if (del_now) {
3747                 ret_val =
3748                     yaffs_change_obj_name(in, in->my_dev->del_dir,
3749                                           _Y("deleted"), 0, 0);