1bc6d51be66714e253e572ffac34ffc7bf3aebd1
[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
1624 /* Note:
1625  * If old_name is NULL then we take old_dir as the object to be renamed.
1626  */
1627 int yaffs_rename_obj(struct yaffs_obj *old_dir, const YCHAR * old_name,
1628                      struct yaffs_obj *new_dir, const YCHAR * new_name)
1629 {
1630         struct yaffs_obj *obj = NULL;
1631         struct yaffs_obj *existing_target = NULL;
1632         int force = 0;
1633         int result;
1634         struct yaffs_dev *dev;
1635
1636         if (!old_dir || old_dir->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY)
1637                 YBUG();
1638         if (!new_dir || new_dir->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY)
1639                 YBUG();
1640
1641         dev = old_dir->my_dev;
1642
1643 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1644         /* Special case for case insemsitive systems.
1645          * While look-up is case insensitive, the name isn't.
1646          * Therefore we might want to change x.txt to X.txt
1647          */
1648         if (old_dir == new_dir && 
1649                 old_name && new_name && 
1650                 yaffs_strcmp(old_name, new_name) == 0)
1651                 force = 1;
1652 #endif
1653
1654         if (yaffs_strnlen(new_name, YAFFS_MAX_NAME_LENGTH + 1) >
1655             YAFFS_MAX_NAME_LENGTH)
1656                 /* ENAMETOOLONG */
1657                 return YAFFS_FAIL;
1658
1659         if(old_name)
1660                 obj = yaffs_find_by_name(old_dir, old_name);
1661         else{
1662                 obj = old_dir;
1663                 old_dir = obj->parent;
1664         }
1665
1666
1667         if (obj && obj->rename_allowed) {
1668
1669                 /* Now do the handling for an existing target, if there is one */
1670
1671                 existing_target = yaffs_find_by_name(new_dir, new_name);
1672                 if (existing_target &&
1673                     existing_target->variant_type == YAFFS_OBJECT_TYPE_DIRECTORY
1674                     && !list_empty(&existing_target->variant.dir_variant.
1675                                    children)) {
1676                         /* There is a target that is a non-empty directory, so we fail */
1677                         return YAFFS_FAIL;      /* EEXIST or ENOTEMPTY */
1678                 } else if (existing_target && existing_target != obj) {
1679                         /* Nuke the target first, using shadowing,
1680                          * but only if it isn't the same object.
1681                          *
1682                          * Note we must disable gc otherwise it can mess up the shadowing.
1683                          *
1684                          */
1685                         dev->gc_disable = 1;
1686                         yaffs_change_obj_name(obj, new_dir, new_name, force,
1687                                               existing_target->obj_id);
1688                         existing_target->is_shadowed = 1;
1689                         yaffs_unlink_obj(existing_target);
1690                         dev->gc_disable = 0;
1691                 }
1692
1693                 result = yaffs_change_obj_name(obj, new_dir, new_name, 1, 0);
1694
1695                 yaffs_update_parent(old_dir);
1696                 if (new_dir != old_dir)
1697                         yaffs_update_parent(new_dir);
1698
1699                 return result;
1700         }
1701         return YAFFS_FAIL;
1702 }
1703
1704 /*------------------------- Block Management and Page Allocation ----------------*/
1705
1706 static int yaffs_init_blocks(struct yaffs_dev *dev)
1707 {
1708         int n_blocks = dev->internal_end_block - dev->internal_start_block + 1;
1709
1710         dev->block_info = NULL;
1711         dev->chunk_bits = NULL;
1712
1713         dev->alloc_block = -1;  /* force it to get a new one */
1714
1715         /* If the first allocation strategy fails, thry the alternate one */
1716         dev->block_info = YMALLOC(n_blocks * sizeof(struct yaffs_block_info));
1717         if (!dev->block_info) {
1718                 dev->block_info =
1719                     YMALLOC_ALT(n_blocks * sizeof(struct yaffs_block_info));
1720                 dev->block_info_alt = 1;
1721         } else {
1722                 dev->block_info_alt = 0;
1723         }
1724
1725         if (dev->block_info) {
1726                 /* Set up dynamic blockinfo stuff. */
1727                 dev->chunk_bit_stride = (dev->param.chunks_per_block + 7) / 8;  /* round up bytes */
1728                 dev->chunk_bits = YMALLOC(dev->chunk_bit_stride * n_blocks);
1729                 if (!dev->chunk_bits) {
1730                         dev->chunk_bits =
1731                             YMALLOC_ALT(dev->chunk_bit_stride * n_blocks);
1732                         dev->chunk_bits_alt = 1;
1733                 } else {
1734                         dev->chunk_bits_alt = 0;
1735                 }
1736         }
1737
1738         if (dev->block_info && dev->chunk_bits) {
1739                 memset(dev->block_info, 0,
1740                        n_blocks * sizeof(struct yaffs_block_info));
1741                 memset(dev->chunk_bits, 0, dev->chunk_bit_stride * n_blocks);
1742                 return YAFFS_OK;
1743         }
1744
1745         return YAFFS_FAIL;
1746 }
1747
1748 static void yaffs_deinit_blocks(struct yaffs_dev *dev)
1749 {
1750         if (dev->block_info_alt && dev->block_info)
1751                 YFREE_ALT(dev->block_info);
1752         else if (dev->block_info)
1753                 YFREE(dev->block_info);
1754
1755         dev->block_info_alt = 0;
1756
1757         dev->block_info = NULL;
1758
1759         if (dev->chunk_bits_alt && dev->chunk_bits)
1760                 YFREE_ALT(dev->chunk_bits);
1761         else if (dev->chunk_bits)
1762                 YFREE(dev->chunk_bits);
1763         dev->chunk_bits_alt = 0;
1764         dev->chunk_bits = NULL;
1765 }
1766
1767 void yaffs_block_became_dirty(struct yaffs_dev *dev, int block_no)
1768 {
1769         struct yaffs_block_info *bi = yaffs_get_block_info(dev, block_no);
1770
1771         int erased_ok = 0;
1772
1773         /* If the block is still healthy erase it and mark as clean.
1774          * If the block has had a data failure, then retire it.
1775          */
1776
1777         T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
1778           (TSTR("yaffs_block_became_dirty block %d state %d %s" TENDSTR),
1779            block_no, bi->block_state,
1780            (bi->needs_retiring) ? "needs retiring" : ""));
1781
1782         yaffs2_clear_oldest_dirty_seq(dev, bi);
1783
1784         bi->block_state = YAFFS_BLOCK_STATE_DIRTY;
1785
1786         /* If this is the block being garbage collected then stop gc'ing this block */
1787         if (block_no == dev->gc_block)
1788                 dev->gc_block = 0;
1789
1790         /* If this block is currently the best candidate for gc then drop as a candidate */
1791         if (block_no == dev->gc_dirtiest) {
1792                 dev->gc_dirtiest = 0;
1793                 dev->gc_pages_in_use = 0;
1794         }
1795
1796         if (!bi->needs_retiring) {
1797                 yaffs2_checkpt_invalidate(dev);
1798                 erased_ok = yaffs_erase_block(dev, block_no);
1799                 if (!erased_ok) {
1800                         dev->n_erase_failures++;
1801                         T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1802                           (TSTR("**>> Erasure failed %d" TENDSTR), block_no));
1803                 }
1804         }
1805
1806         if (erased_ok &&
1807             ((yaffs_trace_mask & YAFFS_TRACE_ERASE)
1808              || !yaffs_skip_verification(dev))) {
1809                 int i;
1810                 for (i = 0; i < dev->param.chunks_per_block; i++) {
1811                         if (!yaffs_check_chunk_erased
1812                             (dev, block_no * dev->param.chunks_per_block + i)) {
1813                                 T(YAFFS_TRACE_ERROR,
1814                                   (TSTR
1815                                    (">>Block %d erasure supposedly OK, but chunk %d not erased"
1816                                     TENDSTR), block_no, i));
1817                         }
1818                 }
1819         }
1820
1821         if (erased_ok) {
1822                 /* Clean it up... */
1823                 bi->block_state = YAFFS_BLOCK_STATE_EMPTY;
1824                 bi->seq_number = 0;
1825                 dev->n_erased_blocks++;
1826                 bi->pages_in_use = 0;
1827                 bi->soft_del_pages = 0;
1828                 bi->has_shrink_hdr = 0;
1829                 bi->skip_erased_check = 1;      /* This is clean, so no need to check */
1830                 bi->gc_prioritise = 0;
1831                 yaffs_clear_chunk_bits(dev, block_no);
1832
1833                 T(YAFFS_TRACE_ERASE,
1834                   (TSTR("Erased block %d" TENDSTR), block_no));
1835         } else {
1836                 dev->n_free_chunks -= dev->param.chunks_per_block;      /* We lost a block of free space */
1837
1838                 yaffs_retire_block(dev, block_no);
1839                 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1840                   (TSTR("**>> Block %d retired" TENDSTR), block_no));
1841         }
1842 }
1843
1844 static int yaffs_find_alloc_block(struct yaffs_dev *dev)
1845 {
1846         int i;
1847
1848         struct yaffs_block_info *bi;
1849
1850         if (dev->n_erased_blocks < 1) {
1851                 /* Hoosterman we've got a problem.
1852                  * Can't get space to gc
1853                  */
1854                 T(YAFFS_TRACE_ERROR,
1855                   (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
1856
1857                 return -1;
1858         }
1859
1860         /* Find an empty block. */
1861
1862         for (i = dev->internal_start_block; i <= dev->internal_end_block; i++) {
1863                 dev->alloc_block_finder++;
1864                 if (dev->alloc_block_finder < dev->internal_start_block
1865                     || dev->alloc_block_finder > dev->internal_end_block) {
1866                         dev->alloc_block_finder = dev->internal_start_block;
1867                 }
1868
1869                 bi = yaffs_get_block_info(dev, dev->alloc_block_finder);
1870
1871                 if (bi->block_state == YAFFS_BLOCK_STATE_EMPTY) {
1872                         bi->block_state = YAFFS_BLOCK_STATE_ALLOCATING;
1873                         dev->seq_number++;
1874                         bi->seq_number = dev->seq_number;
1875                         dev->n_erased_blocks--;
1876                         T(YAFFS_TRACE_ALLOCATE,
1877                           (TSTR("Allocated block %d, seq  %d, %d left" TENDSTR),
1878                            dev->alloc_block_finder, dev->seq_number,
1879                            dev->n_erased_blocks));
1880                         return dev->alloc_block_finder;
1881                 }
1882         }
1883
1884         T(YAFFS_TRACE_ALWAYS,
1885           (TSTR
1886            ("yaffs tragedy: no more erased blocks, but there should have been %d"
1887             TENDSTR), dev->n_erased_blocks));
1888
1889         return -1;
1890 }
1891
1892 /*
1893  * Check if there's space to allocate...
1894  * Thinks.... do we need top make this ths same as yaffs_get_free_chunks()?
1895  */
1896 int yaffs_check_alloc_available(struct yaffs_dev *dev, int n_chunks)
1897 {
1898         int reserved_chunks;
1899         int reserved_blocks = dev->param.n_reserved_blocks;
1900         int checkpt_blocks;
1901
1902         checkpt_blocks = yaffs_calc_checkpt_blocks_required(dev);
1903
1904         reserved_chunks =
1905             ((reserved_blocks + checkpt_blocks) * dev->param.chunks_per_block);
1906
1907         return (dev->n_free_chunks > (reserved_chunks + n_chunks));
1908 }
1909
1910 static int yaffs_alloc_chunk(struct yaffs_dev *dev, int use_reserver,
1911                              struct yaffs_block_info **block_ptr)
1912 {
1913         int ret_val;
1914         struct yaffs_block_info *bi;
1915
1916         if (dev->alloc_block < 0) {
1917                 /* Get next block to allocate off */
1918                 dev->alloc_block = yaffs_find_alloc_block(dev);
1919                 dev->alloc_page = 0;
1920         }
1921
1922         if (!use_reserver && !yaffs_check_alloc_available(dev, 1)) {
1923                 /* Not enough space to allocate unless we're allowed to use the reserve. */
1924                 return -1;
1925         }
1926
1927         if (dev->n_erased_blocks < dev->param.n_reserved_blocks
1928             && dev->alloc_page == 0) {
1929                 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
1930         }
1931
1932         /* Next page please.... */
1933         if (dev->alloc_block >= 0) {
1934                 bi = yaffs_get_block_info(dev, dev->alloc_block);
1935
1936                 ret_val = (dev->alloc_block * dev->param.chunks_per_block) +
1937                     dev->alloc_page;
1938                 bi->pages_in_use++;
1939                 yaffs_set_chunk_bit(dev, dev->alloc_block, dev->alloc_page);
1940
1941                 dev->alloc_page++;
1942
1943                 dev->n_free_chunks--;
1944
1945                 /* If the block is full set the state to full */
1946                 if (dev->alloc_page >= dev->param.chunks_per_block) {
1947                         bi->block_state = YAFFS_BLOCK_STATE_FULL;
1948                         dev->alloc_block = -1;
1949                 }
1950
1951                 if (block_ptr)
1952                         *block_ptr = bi;
1953
1954                 return ret_val;
1955         }
1956
1957         T(YAFFS_TRACE_ERROR,
1958           (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
1959
1960         return -1;
1961 }
1962
1963 static int yaffs_get_erased_chunks(struct yaffs_dev *dev)
1964 {
1965         int n;
1966
1967         n = dev->n_erased_blocks * dev->param.chunks_per_block;
1968
1969         if (dev->alloc_block > 0)
1970                 n += (dev->param.chunks_per_block - dev->alloc_page);
1971
1972         return n;
1973
1974 }
1975
1976 /*
1977  * yaffs_skip_rest_of_block() skips over the rest of the allocation block
1978  * if we don't want to write to it.
1979  */
1980 void yaffs_skip_rest_of_block(struct yaffs_dev *dev)
1981 {
1982         if (dev->alloc_block > 0) {
1983                 struct yaffs_block_info *bi =
1984                     yaffs_get_block_info(dev, dev->alloc_block);
1985                 if (bi->block_state == YAFFS_BLOCK_STATE_ALLOCATING) {
1986                         bi->block_state = YAFFS_BLOCK_STATE_FULL;
1987                         dev->alloc_block = -1;
1988                 }
1989         }
1990 }
1991
1992 static int yaffs_gc_block(struct yaffs_dev *dev, int block, int whole_block)
1993 {
1994         int old_chunk;
1995         int new_chunk;
1996         int mark_flash;
1997         int ret_val = YAFFS_OK;
1998         int i;
1999         int is_checkpt_block;
2000         int matching_chunk;
2001         int max_copies;
2002
2003         int chunks_before = yaffs_get_erased_chunks(dev);
2004         int chunks_after;
2005
2006         struct yaffs_ext_tags tags;
2007
2008         struct yaffs_block_info *bi = yaffs_get_block_info(dev, block);
2009
2010         struct yaffs_obj *object;
2011
2012         is_checkpt_block = (bi->block_state == YAFFS_BLOCK_STATE_CHECKPOINT);
2013
2014         T(YAFFS_TRACE_TRACING,
2015           (TSTR
2016            ("Collecting block %d, in use %d, shrink %d, whole_block %d"
2017             TENDSTR), block, bi->pages_in_use, bi->has_shrink_hdr,
2018            whole_block));
2019
2020         /*yaffs_verify_free_chunks(dev); */
2021
2022         if (bi->block_state == YAFFS_BLOCK_STATE_FULL)
2023                 bi->block_state = YAFFS_BLOCK_STATE_COLLECTING;
2024
2025         bi->has_shrink_hdr = 0; /* clear the flag so that the block can erase */
2026
2027         dev->gc_disable = 1;
2028
2029         if (is_checkpt_block || !yaffs_still_some_chunks(dev, block)) {
2030                 T(YAFFS_TRACE_TRACING,
2031                   (TSTR
2032                    ("Collecting block %d that has no chunks in use" TENDSTR),
2033                    block));
2034                 yaffs_block_became_dirty(dev, block);
2035         } else {
2036
2037                 u8 *buffer = yaffs_get_temp_buffer(dev, __LINE__);
2038
2039                 yaffs_verify_blk(dev, bi, block);
2040
2041                 max_copies = (whole_block) ? dev->param.chunks_per_block : 5;
2042                 old_chunk = block * dev->param.chunks_per_block + dev->gc_chunk;
2043
2044                 for ( /* init already done */ ;
2045                      ret_val == YAFFS_OK &&
2046                      dev->gc_chunk < dev->param.chunks_per_block &&
2047                      (bi->block_state == YAFFS_BLOCK_STATE_COLLECTING) &&
2048                      max_copies > 0; dev->gc_chunk++, old_chunk++) {
2049                         if (yaffs_check_chunk_bit(dev, block, dev->gc_chunk)) {
2050
2051                                 /* This page is in use and might need to be copied off */
2052
2053                                 max_copies--;
2054
2055                                 mark_flash = 1;
2056
2057                                 yaffs_init_tags(&tags);
2058
2059                                 yaffs_rd_chunk_tags_nand(dev, old_chunk,
2060                                                          buffer, &tags);
2061
2062                                 object = yaffs_find_by_number(dev, tags.obj_id);
2063
2064                                 T(YAFFS_TRACE_GC_DETAIL,
2065                                   (TSTR
2066                                    ("Collecting chunk in block %d, %d %d %d "
2067                                     TENDSTR), dev->gc_chunk, tags.obj_id,
2068                                    tags.chunk_id, tags.n_bytes));
2069
2070                                 if (object && !yaffs_skip_verification(dev)) {
2071                                         if (tags.chunk_id == 0)
2072                                                 matching_chunk =
2073                                                     object->hdr_chunk;
2074                                         else if (object->soft_del)
2075                                                 matching_chunk = old_chunk;     /* Defeat the test */
2076                                         else
2077                                                 matching_chunk =
2078                                                     yaffs_find_chunk_in_file
2079                                                     (object, tags.chunk_id,
2080                                                      NULL);
2081
2082                                         if (old_chunk != matching_chunk)
2083                                                 T(YAFFS_TRACE_ERROR,
2084                                                   (TSTR
2085                                                    ("gc: page in gc mismatch: %d %d %d %d"
2086                                                     TENDSTR), old_chunk,
2087                                                    matching_chunk, tags.obj_id,
2088                                                    tags.chunk_id));
2089
2090                                 }
2091
2092                                 if (!object) {
2093                                         T(YAFFS_TRACE_ERROR,
2094                                           (TSTR
2095                                            ("page %d in gc has no object: %d %d %d "
2096                                             TENDSTR), old_chunk,
2097                                            tags.obj_id, tags.chunk_id,
2098                                            tags.n_bytes));
2099                                 }
2100
2101                                 if (object &&
2102                                     object->deleted &&
2103                                     object->soft_del && tags.chunk_id != 0) {
2104                                         /* Data chunk in a soft deleted file, throw it away
2105                                          * It's a soft deleted data chunk,
2106                                          * No need to copy this, just forget about it and
2107                                          * fix up the object.
2108                                          */
2109
2110                                         /* Free chunks already includes softdeleted chunks.
2111                                          * How ever this chunk is going to soon be really deleted
2112                                          * which will increment free chunks.
2113                                          * We have to decrement free chunks so this works out properly.
2114                                          */
2115                                         dev->n_free_chunks--;
2116                                         bi->soft_del_pages--;
2117
2118                                         object->n_data_chunks--;
2119
2120                                         if (object->n_data_chunks <= 0) {
2121                                                 /* remeber to clean up the object */
2122                                                 dev->gc_cleanup_list[dev->
2123                                                                      n_clean_ups]
2124                                                     = tags.obj_id;
2125                                                 dev->n_clean_ups++;
2126                                         }
2127                                         mark_flash = 0;
2128                                 } else if (0) {
2129                                         /* Todo object && object->deleted && object->n_data_chunks == 0 */
2130                                         /* Deleted object header with no data chunks.
2131                                          * Can be discarded and the file deleted.
2132                                          */
2133                                         object->hdr_chunk = 0;
2134                                         yaffs_free_tnode(object->my_dev,
2135                                                          object->
2136                                                          variant.file_variant.
2137                                                          top);
2138                                         object->variant.file_variant.top = NULL;
2139                                         yaffs_generic_obj_del(object);
2140
2141                                 } else if (object) {
2142                                         /* It's either a data chunk in a live file or
2143                                          * an ObjectHeader, so we're interested in it.
2144                                          * NB Need to keep the ObjectHeaders of deleted files
2145                                          * until the whole file has been deleted off
2146                                          */
2147                                         tags.serial_number++;
2148
2149                                         dev->n_gc_copies++;
2150
2151                                         if (tags.chunk_id == 0) {
2152                                                 /* It is an object Id,
2153                                                  * We need to nuke the shrinkheader flags first
2154                                                  * Also need to clean up shadowing.
2155                                                  * We no longer want the shrink_header flag since its work is done
2156                                                  * and if it is left in place it will mess up scanning.
2157                                                  */
2158
2159                                                 struct yaffs_obj_hdr *oh;
2160                                                 oh = (struct yaffs_obj_hdr *)
2161                                                     buffer;
2162
2163                                                 oh->is_shrink = 0;
2164                                                 tags.extra_is_shrink = 0;
2165
2166                                                 oh->shadows_obj = 0;
2167                                                 oh->inband_shadowed_obj_id = 0;
2168                                                 tags.extra_shadows = 0;
2169
2170                                                 /* Update file size */
2171                                                 if (object->variant_type ==
2172                                                     YAFFS_OBJECT_TYPE_FILE) {
2173                                                         oh->file_size =
2174                                                             object->variant.
2175                                                             file_variant.
2176                                                             file_size;
2177                                                         tags.extra_length =
2178                                                             oh->file_size;
2179                                                 }
2180
2181                                                 yaffs_verify_oh(object, oh,
2182                                                                 &tags, 1);
2183                                                 new_chunk =
2184                                                     yaffs_write_new_chunk(dev,
2185                                                                           (u8 *)
2186                                                                           oh,
2187                                                                           &tags,
2188                                                                           1);
2189                                         } else {
2190                                                 new_chunk =
2191                                                     yaffs_write_new_chunk(dev,
2192                                                                           buffer,
2193                                                                           &tags,
2194                                                                           1);
2195                                         }
2196
2197                                         if (new_chunk < 0) {
2198                                                 ret_val = YAFFS_FAIL;
2199                                         } else {
2200
2201                                                 /* Ok, now fix up the Tnodes etc. */
2202
2203                                                 if (tags.chunk_id == 0) {
2204                                                         /* It's a header */
2205                                                         object->hdr_chunk =
2206                                                             new_chunk;
2207                                                         object->serial =
2208                                                             tags.serial_number;
2209                                                 } else {
2210                                                         /* It's a data chunk */
2211                                                         int ok;
2212                                                         ok = yaffs_put_chunk_in_file(object, tags.chunk_id, new_chunk, 0);
2213                                                 }
2214                                         }
2215                                 }
2216
2217                                 if (ret_val == YAFFS_OK)
2218                                         yaffs_chunk_del(dev, old_chunk,
2219                                                         mark_flash, __LINE__);
2220
2221                         }
2222                 }
2223
2224                 yaffs_release_temp_buffer(dev, buffer, __LINE__);
2225
2226         }
2227
2228         yaffs_verify_collected_blk(dev, bi, block);
2229
2230         if (bi->block_state == YAFFS_BLOCK_STATE_COLLECTING) {
2231                 /*
2232                  * The gc did not complete. Set block state back to FULL
2233                  * because checkpointing does not restore gc.
2234                  */
2235                 bi->block_state = YAFFS_BLOCK_STATE_FULL;
2236         } else {
2237                 /* The gc completed. */
2238                 /* Do any required cleanups */
2239                 for (i = 0; i < dev->n_clean_ups; i++) {
2240                         /* Time to delete the file too */
2241                         object =
2242                             yaffs_find_by_number(dev, dev->gc_cleanup_list[i]);
2243                         if (object) {
2244                                 yaffs_free_tnode(dev,
2245                                                  object->variant.
2246                                                  file_variant.top);
2247                                 object->variant.file_variant.top = NULL;
2248                                 T(YAFFS_TRACE_GC,
2249                                   (TSTR
2250                                    ("yaffs: About to finally delete object %d"
2251                                     TENDSTR), object->obj_id));
2252                                 yaffs_generic_obj_del(object);
2253                                 object->my_dev->n_deleted_files--;
2254                         }
2255
2256                 }
2257
2258                 chunks_after = yaffs_get_erased_chunks(dev);
2259                 if (chunks_before >= chunks_after) {
2260                         T(YAFFS_TRACE_GC,
2261                           (TSTR
2262                            ("gc did not increase free chunks before %d after %d"
2263                             TENDSTR), chunks_before, chunks_after));
2264                 }
2265                 dev->gc_block = 0;
2266                 dev->gc_chunk = 0;
2267                 dev->n_clean_ups = 0;
2268         }
2269
2270         dev->gc_disable = 0;
2271
2272         return ret_val;
2273 }
2274
2275 /*
2276  * FindBlockForgarbageCollection is used to select the dirtiest block (or close enough)
2277  * for garbage collection.
2278  */
2279
2280 static unsigned yaffs_find_gc_block(struct yaffs_dev *dev,
2281                                     int aggressive, int background)
2282 {
2283         int i;
2284         int iterations;
2285         unsigned selected = 0;
2286         int prioritised = 0;
2287         int prioritised_exist = 0;
2288         struct yaffs_block_info *bi;
2289         int threshold;
2290
2291         /* First let's see if we need to grab a prioritised block */
2292         if (dev->has_pending_prioritised_gc && !aggressive) {
2293                 dev->gc_dirtiest = 0;
2294                 bi = dev->block_info;
2295                 for (i = dev->internal_start_block;
2296                      i <= dev->internal_end_block && !selected; i++) {
2297
2298                         if (bi->gc_prioritise) {
2299                                 prioritised_exist = 1;
2300                                 if (bi->block_state == YAFFS_BLOCK_STATE_FULL &&
2301                                     yaffs_block_ok_for_gc(dev, bi)) {
2302                                         selected = i;
2303                                         prioritised = 1;
2304                                 }
2305                         }
2306                         bi++;
2307                 }
2308
2309                 /*
2310                  * If there is a prioritised block and none was selected then
2311                  * this happened because there is at least one old dirty block gumming
2312                  * up the works. Let's gc the oldest dirty block.
2313                  */
2314
2315                 if (prioritised_exist &&
2316                     !selected && dev->oldest_dirty_block > 0)
2317                         selected = dev->oldest_dirty_block;
2318
2319                 if (!prioritised_exist) /* None found, so we can clear this */
2320                         dev->has_pending_prioritised_gc = 0;
2321         }
2322
2323         /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2324          * search harder.
2325          * else (we're doing a leasurely gc), then we only bother to do this if the
2326          * block has only a few pages in use.
2327          */
2328
2329         if (!selected) {
2330                 int pages_used;
2331                 int n_blocks =
2332                     dev->internal_end_block - dev->internal_start_block + 1;
2333                 if (aggressive) {
2334                         threshold = dev->param.chunks_per_block;
2335                         iterations = n_blocks;
2336                 } else {
2337                         int max_threshold;
2338
2339                         if (background)
2340                                 max_threshold = dev->param.chunks_per_block / 2;
2341                         else
2342                                 max_threshold = dev->param.chunks_per_block / 8;
2343
2344                         if (max_threshold < YAFFS_GC_PASSIVE_THRESHOLD)
2345                                 max_threshold = YAFFS_GC_PASSIVE_THRESHOLD;
2346
2347                         threshold = background ? (dev->gc_not_done + 2) * 2 : 0;
2348                         if (threshold < YAFFS_GC_PASSIVE_THRESHOLD)
2349                                 threshold = YAFFS_GC_PASSIVE_THRESHOLD;
2350                         if (threshold > max_threshold)
2351                                 threshold = max_threshold;
2352
2353                         iterations = n_blocks / 16 + 1;
2354                         if (iterations > 100)
2355                                 iterations = 100;
2356                 }
2357
2358                 for (i = 0;
2359                      i < iterations &&
2360                      (dev->gc_dirtiest < 1 ||
2361                       dev->gc_pages_in_use > YAFFS_GC_GOOD_ENOUGH); i++) {
2362                         dev->gc_block_finder++;
2363                         if (dev->gc_block_finder < dev->internal_start_block ||
2364                             dev->gc_block_finder > dev->internal_end_block)
2365                                 dev->gc_block_finder =
2366                                     dev->internal_start_block;
2367
2368                         bi = yaffs_get_block_info(dev, dev->gc_block_finder);
2369
2370                         pages_used = bi->pages_in_use - bi->soft_del_pages;
2371
2372                         if (bi->block_state == YAFFS_BLOCK_STATE_FULL &&
2373                             pages_used < dev->param.chunks_per_block &&
2374                             (dev->gc_dirtiest < 1
2375                              || pages_used < dev->gc_pages_in_use)
2376                             && yaffs_block_ok_for_gc(dev, bi)) {
2377                                 dev->gc_dirtiest = dev->gc_block_finder;
2378                                 dev->gc_pages_in_use = pages_used;
2379                         }
2380                 }
2381
2382                 if (dev->gc_dirtiest > 0 && dev->gc_pages_in_use <= threshold)
2383                         selected = dev->gc_dirtiest;
2384         }
2385
2386         /*
2387          * If nothing has been selected for a while, try selecting the oldest dirty
2388          * because that's gumming up the works.
2389          */
2390
2391         if (!selected && dev->param.is_yaffs2 &&
2392             dev->gc_not_done >= (background ? 10 : 20)) {
2393                 yaffs2_find_oldest_dirty_seq(dev);
2394                 if (dev->oldest_dirty_block > 0) {
2395                         selected = dev->oldest_dirty_block;
2396                         dev->gc_dirtiest = selected;
2397                         dev->oldest_dirty_gc_count++;
2398                         bi = yaffs_get_block_info(dev, selected);
2399                         dev->gc_pages_in_use =
2400                             bi->pages_in_use - bi->soft_del_pages;
2401                 } else {
2402                         dev->gc_not_done = 0;
2403                 }
2404         }
2405
2406         if (selected) {
2407                 T(YAFFS_TRACE_GC,
2408                   (TSTR
2409                    ("GC Selected block %d with %d free, prioritised:%d"
2410                     TENDSTR), selected,
2411                    dev->param.chunks_per_block - dev->gc_pages_in_use,
2412                    prioritised));
2413
2414                 dev->n_gc_blocks++;
2415                 if (background)
2416                         dev->bg_gcs++;
2417
2418                 dev->gc_dirtiest = 0;
2419                 dev->gc_pages_in_use = 0;
2420                 dev->gc_not_done = 0;
2421                 if (dev->refresh_skip > 0)
2422                         dev->refresh_skip--;
2423         } else {
2424                 dev->gc_not_done++;
2425                 T(YAFFS_TRACE_GC,
2426                   (TSTR
2427                    ("GC none: finder %d skip %d threshold %d dirtiest %d using %d oldest %d%s"
2428                     TENDSTR), dev->gc_block_finder, dev->gc_not_done, threshold,
2429                    dev->gc_dirtiest, dev->gc_pages_in_use,
2430                    dev->oldest_dirty_block, background ? " bg" : ""));
2431         }
2432
2433         return selected;
2434 }
2435
2436 /* New garbage collector
2437  * If we're very low on erased blocks then we do aggressive garbage collection
2438  * otherwise we do "leasurely" garbage collection.
2439  * Aggressive gc looks further (whole array) and will accept less dirty blocks.
2440  * Passive gc only inspects smaller areas and will only accept more dirty blocks.
2441  *
2442  * The idea is to help clear out space in a more spread-out manner.
2443  * Dunno if it really does anything useful.
2444  */
2445 static int yaffs_check_gc(struct yaffs_dev *dev, int background)
2446 {
2447         int aggressive = 0;
2448         int gc_ok = YAFFS_OK;
2449         int max_tries = 0;
2450         int min_erased;
2451         int erased_chunks;
2452         int checkpt_block_adjust;
2453
2454         if (dev->param.gc_control && (dev->param.gc_control(dev) & 1) == 0)
2455                 return YAFFS_OK;
2456
2457         if (dev->gc_disable) {
2458                 /* Bail out so we don't get recursive gc */
2459                 return YAFFS_OK;
2460         }
2461
2462         /* This loop should pass the first time.
2463          * We'll only see looping here if the collection does not increase space.
2464          */
2465
2466         do {
2467                 max_tries++;
2468
2469                 checkpt_block_adjust = yaffs_calc_checkpt_blocks_required(dev);
2470
2471                 min_erased =
2472                     dev->param.n_reserved_blocks + checkpt_block_adjust + 1;
2473                 erased_chunks =
2474                     dev->n_erased_blocks * dev->param.chunks_per_block;
2475
2476                 /* If we need a block soon then do aggressive gc. */
2477                 if (dev->n_erased_blocks < min_erased)
2478                         aggressive = 1;
2479                 else {
2480                         if (!background
2481                             && erased_chunks > (dev->n_free_chunks / 4))
2482                                 break;
2483
2484                         if (dev->gc_skip > 20)
2485                                 dev->gc_skip = 20;
2486                         if (erased_chunks < dev->n_free_chunks / 2 ||
2487                             dev->gc_skip < 1 || background)
2488                                 aggressive = 0;
2489                         else {
2490                                 dev->gc_skip--;
2491                                 break;
2492                         }
2493                 }
2494
2495                 dev->gc_skip = 5;
2496
2497                 /* If we don't already have a block being gc'd then see if we should start another */
2498
2499                 if (dev->gc_block < 1 && !aggressive) {
2500                         dev->gc_block = yaffs2_find_refresh_block(dev);
2501                         dev->gc_chunk = 0;
2502                         dev->n_clean_ups = 0;
2503                 }
2504                 if (dev->gc_block < 1) {
2505                         dev->gc_block =
2506                             yaffs_find_gc_block(dev, aggressive, background);
2507                         dev->gc_chunk = 0;
2508                         dev->n_clean_ups = 0;
2509                 }
2510
2511                 if (dev->gc_block > 0) {
2512                         dev->all_gcs++;
2513                         if (!aggressive)
2514                                 dev->passive_gc_count++;
2515
2516                         T(YAFFS_TRACE_GC,
2517                           (TSTR
2518                            ("yaffs: GC n_erased_blocks %d aggressive %d"
2519                             TENDSTR), dev->n_erased_blocks, aggressive));
2520
2521                         gc_ok = yaffs_gc_block(dev, dev->gc_block, aggressive);
2522                 }
2523
2524                 if (dev->n_erased_blocks < (dev->param.n_reserved_blocks)
2525                     && dev->gc_block > 0) {
2526                         T(YAFFS_TRACE_GC,
2527                           (TSTR
2528                            ("yaffs: GC !!!no reclaim!!! n_erased_blocks %d after try %d block %d"
2529                             TENDSTR), dev->n_erased_blocks, max_tries,
2530                            dev->gc_block));
2531                 }
2532         } while ((dev->n_erased_blocks < dev->param.n_reserved_blocks) &&
2533                  (dev->gc_block > 0) && (max_tries < 2));
2534
2535         return aggressive ? gc_ok : YAFFS_OK;
2536 }
2537
2538 /*
2539  * yaffs_bg_gc()
2540  * Garbage collects. Intended to be called from a background thread.
2541  * Returns non-zero if at least half the free chunks are erased.
2542  */
2543 int yaffs_bg_gc(struct yaffs_dev *dev, unsigned urgency)
2544 {
2545         int erased_chunks = dev->n_erased_blocks * dev->param.chunks_per_block;
2546
2547         T(YAFFS_TRACE_BACKGROUND, (TSTR("Background gc %u" TENDSTR), urgency));
2548
2549         yaffs_check_gc(dev, 1);
2550         return erased_chunks > dev->n_free_chunks / 2;
2551 }
2552
2553 /*-------------------------  TAGS --------------------------------*/
2554
2555 static int yaffs_tags_match(const struct yaffs_ext_tags *tags, int obj_id,
2556                             int chunk_obj)
2557 {
2558         return (tags->chunk_id == chunk_obj &&
2559                 tags->obj_id == obj_id && !tags->is_deleted) ? 1 : 0;
2560
2561 }
2562
2563 /*-------------------- Data file manipulation -----------------*/
2564
2565 static int yaffs_find_chunk_in_file(struct yaffs_obj *in, int inode_chunk,
2566                                     struct yaffs_ext_tags *tags)
2567 {
2568         /*Get the Tnode, then get the level 0 offset chunk offset */
2569         struct yaffs_tnode *tn;
2570         int the_chunk = -1;
2571         struct yaffs_ext_tags local_tags;
2572         int ret_val = -1;
2573
2574         struct yaffs_dev *dev = in->my_dev;
2575
2576         if (!tags) {
2577                 /* Passed a NULL, so use our own tags space */
2578                 tags = &local_tags;
2579         }
2580
2581         tn = yaffs_find_tnode_0(dev, &in->variant.file_variant, inode_chunk);
2582
2583         if (tn) {
2584                 the_chunk = yaffs_get_group_base(dev, tn, inode_chunk);
2585
2586                 ret_val =
2587                     yaffs_find_chunk_in_group(dev, the_chunk, tags, in->obj_id,
2588                                               inode_chunk);
2589         }
2590         return ret_val;
2591 }
2592
2593 static int yaffs_find_del_file_chunk(struct yaffs_obj *in, int inode_chunk,
2594                                      struct yaffs_ext_tags *tags)
2595 {
2596         /* Get the Tnode, then get the level 0 offset chunk offset */
2597         struct yaffs_tnode *tn;
2598         int the_chunk = -1;
2599         struct yaffs_ext_tags local_tags;
2600
2601         struct yaffs_dev *dev = in->my_dev;
2602         int ret_val = -1;
2603
2604         if (!tags) {
2605                 /* Passed a NULL, so use our own tags space */
2606                 tags = &local_tags;
2607         }
2608
2609         tn = yaffs_find_tnode_0(dev, &in->variant.file_variant, inode_chunk);
2610
2611         if (tn) {
2612
2613                 the_chunk = yaffs_get_group_base(dev, tn, inode_chunk);
2614
2615                 ret_val =
2616                     yaffs_find_chunk_in_group(dev, the_chunk, tags, in->obj_id,
2617                                               inode_chunk);
2618
2619                 /* Delete the entry in the filestructure (if found) */
2620                 if (ret_val != -1)
2621                         yaffs_load_tnode_0(dev, tn, inode_chunk, 0);
2622         }
2623
2624         return ret_val;
2625 }
2626
2627 int yaffs_put_chunk_in_file(struct yaffs_obj *in, int inode_chunk,
2628                             int nand_chunk, int in_scan)
2629 {
2630         /* NB in_scan is zero unless scanning.
2631          * For forward scanning, in_scan is > 0;
2632          * for backward scanning in_scan is < 0
2633          *
2634          * nand_chunk = 0 is a dummy insert to make sure the tnodes are there.
2635          */
2636
2637         struct yaffs_tnode *tn;
2638         struct yaffs_dev *dev = in->my_dev;
2639         int existing_cunk;
2640         struct yaffs_ext_tags existing_tags;
2641         struct yaffs_ext_tags new_tags;
2642         unsigned existing_serial, new_serial;
2643
2644         if (in->variant_type != YAFFS_OBJECT_TYPE_FILE) {
2645                 /* Just ignore an attempt at putting a chunk into a non-file during scanning
2646                  * If it is not during Scanning then something went wrong!
2647                  */
2648                 if (!in_scan) {
2649                         T(YAFFS_TRACE_ERROR,
2650                           (TSTR
2651                            ("yaffs tragedy:attempt to put data chunk into a non-file"
2652                             TENDSTR)));
2653                         YBUG();
2654                 }
2655
2656                 yaffs_chunk_del(dev, nand_chunk, 1, __LINE__);
2657                 return YAFFS_OK;
2658         }
2659
2660         tn = yaffs_add_find_tnode_0(dev,
2661                                     &in->variant.file_variant,
2662                                     inode_chunk, NULL);
2663         if (!tn)
2664                 return YAFFS_FAIL;
2665
2666         if (!nand_chunk)
2667                 /* Dummy insert, bail now */
2668                 return YAFFS_OK;
2669
2670         existing_cunk = yaffs_get_group_base(dev, tn, inode_chunk);
2671
2672         if (in_scan != 0) {
2673                 /* If we're scanning then we need to test for duplicates
2674                  * NB This does not need to be efficient since it should only ever
2675                  * happen when the power fails during a write, then only one
2676                  * chunk should ever be affected.
2677                  *
2678                  * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
2679                  * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
2680                  */
2681
2682                 if (existing_cunk > 0) {
2683                         /* NB Right now existing chunk will not be real chunk_id if the chunk group size > 1
2684                          *    thus we have to do a FindChunkInFile to get the real chunk id.
2685                          *
2686                          * We have a duplicate now we need to decide which one to use:
2687                          *
2688                          * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
2689                          * Forward scanning YAFFS2: The new one is what we use, dump the old one.
2690                          * YAFFS1: Get both sets of tags and compare serial numbers.
2691                          */
2692
2693                         if (in_scan > 0) {
2694                                 /* Only do this for forward scanning */
2695                                 yaffs_rd_chunk_tags_nand(dev,
2696                                                          nand_chunk,
2697                                                          NULL, &new_tags);
2698
2699                                 /* Do a proper find */
2700                                 existing_cunk =
2701                                     yaffs_find_chunk_in_file(in, inode_chunk,
2702                                                              &existing_tags);
2703                         }
2704
2705                         if (existing_cunk <= 0) {
2706                                 /*Hoosterman - how did this happen? */
2707
2708                                 T(YAFFS_TRACE_ERROR,
2709                                   (TSTR
2710                                    ("yaffs tragedy: existing chunk < 0 in scan"
2711                                     TENDSTR)));
2712
2713                         }
2714
2715                         /* NB The deleted flags should be false, otherwise the chunks will
2716                          * not be loaded during a scan
2717                          */
2718
2719                         if (in_scan > 0) {
2720                                 new_serial = new_tags.serial_number;
2721                                 existing_serial = existing_tags.serial_number;
2722                         }
2723
2724                         if ((in_scan > 0) &&
2725                             (existing_cunk <= 0 ||
2726                              ((existing_serial + 1) & 3) == new_serial)) {
2727                                 /* Forward scanning.
2728                                  * Use new
2729                                  * Delete the old one and drop through to update the tnode
2730                                  */
2731                                 yaffs_chunk_del(dev, existing_cunk, 1,
2732                                                 __LINE__);
2733                         } else {
2734                                 /* Backward scanning or we want to use the existing one
2735                                  * Use existing.
2736                                  * Delete the new one and return early so that the tnode isn't changed
2737                                  */
2738                                 yaffs_chunk_del(dev, nand_chunk, 1, __LINE__);
2739                                 return YAFFS_OK;
2740                         }
2741                 }
2742
2743         }
2744
2745         if (existing_cunk == 0)
2746                 in->n_data_chunks++;
2747
2748         yaffs_load_tnode_0(dev, tn, inode_chunk, nand_chunk);
2749
2750         return YAFFS_OK;
2751 }
2752
2753 static int yaffs_rd_data_obj(struct yaffs_obj *in, int inode_chunk, u8 * buffer)
2754 {
2755         int nand_chunk = yaffs_find_chunk_in_file(in, inode_chunk, NULL);
2756
2757         if (nand_chunk >= 0)
2758                 return yaffs_rd_chunk_tags_nand(in->my_dev, nand_chunk,
2759                                                 buffer, NULL);
2760         else {
2761                 T(YAFFS_TRACE_NANDACCESS,
2762                   (TSTR("Chunk %d not found zero instead" TENDSTR),
2763                    nand_chunk));
2764                 /* get sane (zero) data if you read a hole */
2765                 memset(buffer, 0, in->my_dev->data_bytes_per_chunk);
2766                 return 0;
2767         }
2768
2769 }
2770
2771 void yaffs_chunk_del(struct yaffs_dev *dev, int chunk_id, int mark_flash,
2772                      int lyn)
2773 {
2774         int block;
2775         int page;
2776         struct yaffs_ext_tags tags;
2777         struct yaffs_block_info *bi;
2778
2779         if (chunk_id <= 0)
2780                 return;
2781
2782         dev->n_deletions++;
2783         block = chunk_id / dev->param.chunks_per_block;
2784         page = chunk_id % dev->param.chunks_per_block;
2785
2786         if (!yaffs_check_chunk_bit(dev, block, page))
2787                 T(YAFFS_TRACE_VERIFY,
2788                   (TSTR("Deleting invalid chunk %d" TENDSTR), chunk_id));
2789
2790         bi = yaffs_get_block_info(dev, block);
2791
2792         yaffs2_update_oldest_dirty_seq(dev, block, bi);
2793
2794         T(YAFFS_TRACE_DELETION,
2795           (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunk_id));
2796
2797         if (!dev->param.is_yaffs2 && mark_flash &&
2798             bi->block_state != YAFFS_BLOCK_STATE_COLLECTING) {
2799
2800                 yaffs_init_tags(&tags);
2801
2802                 tags.is_deleted = 1;
2803
2804                 yaffs_wr_chunk_tags_nand(dev, chunk_id, NULL, &tags);
2805                 yaffs_handle_chunk_update(dev, chunk_id, &tags);
2806         } else {
2807                 dev->n_unmarked_deletions++;
2808         }
2809
2810         /* Pull out of the management area.
2811          * If the whole block became dirty, this will kick off an erasure.
2812          */
2813         if (bi->block_state == YAFFS_BLOCK_STATE_ALLOCATING ||
2814             bi->block_state == YAFFS_BLOCK_STATE_FULL ||
2815             bi->block_state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
2816             bi->block_state == YAFFS_BLOCK_STATE_COLLECTING) {
2817                 dev->n_free_chunks++;
2818
2819                 yaffs_clear_chunk_bit(dev, block, page);
2820
2821                 bi->pages_in_use--;
2822
2823                 if (bi->pages_in_use == 0 &&
2824                     !bi->has_shrink_hdr &&
2825                     bi->block_state != YAFFS_BLOCK_STATE_ALLOCATING &&
2826                     bi->block_state != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
2827                         yaffs_block_became_dirty(dev, block);
2828                 }
2829
2830         }
2831
2832 }
2833
2834 static int yaffs_wr_data_obj(struct yaffs_obj *in, int inode_chunk,
2835                              const u8 * buffer, int n_bytes, int use_reserve)
2836 {
2837         /* Find old chunk Need to do this to get serial number
2838          * Write new one and patch into tree.
2839          * Invalidate old tags.
2840          */
2841
2842         int prev_chunk_id;
2843         struct yaffs_ext_tags prev_tags;
2844
2845         int new_chunk_id;
2846         struct yaffs_ext_tags new_tags;
2847
2848         struct yaffs_dev *dev = in->my_dev;
2849
2850         yaffs_check_gc(dev, 0);
2851
2852         /* Get the previous chunk at this location in the file if it exists.
2853          * If it does not exist then put a zero into the tree. This creates
2854          * the tnode now, rather than later when it is harder to clean up.
2855          */
2856         prev_chunk_id = yaffs_find_chunk_in_file(in, inode_chunk, &prev_tags);
2857         if (prev_chunk_id < 1 &&
2858             !yaffs_put_chunk_in_file(in, inode_chunk, 0, 0))
2859                 return 0;
2860
2861         /* Set up new tags */
2862         yaffs_init_tags(&new_tags);
2863
2864         new_tags.chunk_id = inode_chunk;
2865         new_tags.obj_id = in->obj_id;
2866         new_tags.serial_number =
2867             (prev_chunk_id > 0) ? prev_tags.serial_number + 1 : 1;
2868         new_tags.n_bytes = n_bytes;
2869
2870         if (n_bytes < 1 || n_bytes > dev->param.total_bytes_per_chunk) {
2871                 T(YAFFS_TRACE_ERROR,
2872                   (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR),
2873                    n_bytes));
2874                 YBUG();
2875         }
2876
2877         new_chunk_id =
2878             yaffs_write_new_chunk(dev, buffer, &new_tags, use_reserve);
2879
2880         if (new_chunk_id > 0) {
2881                 yaffs_put_chunk_in_file(in, inode_chunk, new_chunk_id, 0);
2882
2883                 if (prev_chunk_id > 0)
2884                         yaffs_chunk_del(dev, prev_chunk_id, 1, __LINE__);
2885
2886                 yaffs_verify_file_sane(in);
2887         }
2888         return new_chunk_id;
2889
2890 }
2891
2892 /* UpdateObjectHeader updates the header on NAND for an object.
2893  * If name is not NULL, then that new name is used.
2894  */
2895 int yaffs_update_oh(struct yaffs_obj *in, const YCHAR * name, int force,
2896                     int is_shrink, int shadows, struct yaffs_xattr_mod *xmod)
2897 {
2898
2899         struct yaffs_block_info *bi;
2900
2901         struct yaffs_dev *dev = in->my_dev;
2902
2903         int prev_chunk_id;
2904         int ret_val = 0;
2905         int result = 0;
2906
2907         int new_chunk_id;
2908         struct yaffs_ext_tags new_tags;
2909         struct yaffs_ext_tags old_tags;
2910         const YCHAR *alias = NULL;
2911
2912         u8 *buffer = NULL;
2913         YCHAR old_name[YAFFS_MAX_NAME_LENGTH + 1];
2914
2915         struct yaffs_obj_hdr *oh = NULL;
2916
2917         yaffs_strcpy(old_name, _Y("silly old name"));
2918
2919         if (!in->fake || in == dev->root_dir || /* The root_dir should also be saved */
2920             force || xmod) {
2921
2922                 yaffs_check_gc(dev, 0);
2923                 yaffs_check_obj_details_loaded(in);
2924
2925                 buffer = yaffs_get_temp_buffer(in->my_dev, __LINE__);
2926                 oh = (struct yaffs_obj_hdr *)buffer;
2927
2928                 prev_chunk_id = in->hdr_chunk;
2929
2930                 if (prev_chunk_id > 0) {
2931                         result = yaffs_rd_chunk_tags_nand(dev, prev_chunk_id,
2932                                                           buffer, &old_tags);
2933
2934                         yaffs_verify_oh(in, oh, &old_tags, 0);
2935
2936                         memcpy(old_name, oh->name, sizeof(oh->name));
2937                         memset(buffer, 0xFF, sizeof(struct yaffs_obj_hdr));
2938                 } else {
2939                         memset(buffer, 0xFF, dev->data_bytes_per_chunk);
2940                 }
2941
2942                 oh->type = in->variant_type;
2943                 oh->yst_mode = in->yst_mode;
2944                 oh->shadows_obj = oh->inband_shadowed_obj_id = shadows;
2945
2946                 yaffs_load_attribs_oh(oh, in);
2947
2948                 if (in->parent)
2949                         oh->parent_obj_id = in->parent->obj_id;
2950                 else
2951                         oh->parent_obj_id = 0;
2952
2953                 if (name && *name) {
2954                         memset(oh->name, 0, sizeof(oh->name));
2955                         yaffs_load_oh_from_name(dev, oh->name, name);
2956                 } else if (prev_chunk_id > 0) {
2957                         memcpy(oh->name, old_name, sizeof(oh->name));
2958                 } else {
2959                         memset(oh->name, 0, sizeof(oh->name));
2960                 }
2961
2962                 oh->is_shrink = is_shrink;
2963
2964                 switch (in->variant_type) {
2965                 case YAFFS_OBJECT_TYPE_UNKNOWN:
2966                         /* Should not happen */
2967                         break;
2968                 case YAFFS_OBJECT_TYPE_FILE:
2969                         oh->file_size =
2970                             (oh->parent_obj_id == YAFFS_OBJECTID_DELETED
2971                              || oh->parent_obj_id ==
2972                              YAFFS_OBJECTID_UNLINKED) ? 0 : in->
2973                             variant.file_variant.file_size;
2974                         break;
2975                 case YAFFS_OBJECT_TYPE_HARDLINK:
2976                         oh->equiv_id = in->variant.hardlink_variant.equiv_id;
2977                         break;
2978                 case YAFFS_OBJECT_TYPE_SPECIAL:
2979                         /* Do nothing */
2980                         break;
2981                 case YAFFS_OBJECT_TYPE_DIRECTORY:
2982                         /* Do nothing */
2983                         break;
2984                 case YAFFS_OBJECT_TYPE_SYMLINK:
2985                         alias = in->variant.symlink_variant.alias;
2986                         if (!alias)
2987                                 alias = _Y("no alias");
2988                         yaffs_strncpy(oh->alias, alias, YAFFS_MAX_ALIAS_LENGTH);
2989                         oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
2990                         break;
2991                 }
2992
2993                 /* process any xattrib modifications */
2994                 if (xmod)
2995                         yaffs_apply_xattrib_mod(in, (char *)buffer, xmod);
2996
2997                 /* Tags */
2998                 yaffs_init_tags(&new_tags);
2999                 in->serial++;
3000                 new_tags.chunk_id = 0;
3001                 new_tags.obj_id = in->obj_id;
3002                 new_tags.serial_number = in->serial;
3003
3004                 /* Add extra info for file header */
3005
3006                 new_tags.extra_available = 1;
3007                 new_tags.extra_parent_id = oh->parent_obj_id;
3008                 new_tags.extra_length = oh->file_size;
3009                 new_tags.extra_is_shrink = oh->is_shrink;
3010                 new_tags.extra_equiv_id = oh->equiv_id;
3011                 new_tags.extra_shadows = (oh->shadows_obj > 0) ? 1 : 0;
3012                 new_tags.extra_obj_type = in->variant_type;
3013
3014                 yaffs_verify_oh(in, oh, &new_tags, 1);
3015
3016                 /* Create new chunk in NAND */
3017                 new_chunk_id =
3018                     yaffs_write_new_chunk(dev, buffer, &new_tags,
3019                                           (prev_chunk_id > 0) ? 1 : 0);
3020
3021                 if (new_chunk_id >= 0) {
3022
3023                         in->hdr_chunk = new_chunk_id;
3024
3025                         if (prev_chunk_id > 0) {
3026                                 yaffs_chunk_del(dev, prev_chunk_id, 1,
3027                                                 __LINE__);
3028                         }
3029
3030                         if (!yaffs_obj_cache_dirty(in))
3031                                 in->dirty = 0;
3032
3033                         /* If this was a shrink, then mark the block that the chunk lives on */
3034                         if (is_shrink) {
3035                                 bi = yaffs_get_block_info(in->my_dev,
3036                                                           new_chunk_id /
3037                                                           in->my_dev->param.
3038                                                           chunks_per_block);
3039                                 bi->has_shrink_hdr = 1;
3040                         }
3041
3042                 }
3043
3044                 ret_val = new_chunk_id;
3045
3046         }
3047
3048         if (buffer)
3049                 yaffs_release_temp_buffer(dev, buffer, __LINE__);
3050
3051         return ret_val;
3052 }
3053
3054 /*------------------------ Short Operations Cache ----------------------------------------
3055  *   In many situations where there is no high level buffering  a lot of
3056  *   reads might be short sequential reads, and a lot of writes may be short
3057  *   sequential writes. eg. scanning/writing a jpeg file.
3058  *   In these cases, a short read/write cache can provide a huge perfomance
3059  *   benefit with dumb-as-a-rock code.
3060  *   In Linux, the page cache provides read buffering and the short op cache 
3061  *   provides write buffering.
3062  *
3063  *   There are a limited number (~10) of cache chunks per device so that we don't
3064  *   need a very intelligent search.
3065  */
3066
3067 static int yaffs_obj_cache_dirty(struct yaffs_obj *obj)
3068 {
3069         struct yaffs_dev *dev = obj->my_dev;
3070         int i;
3071         struct yaffs_cache *cache;
3072         int n_caches = obj->my_dev->param.n_caches;
3073
3074         for (i = 0; i < n_caches; i++) {
3075                 cache = &dev->cache[i];
3076                 if (cache->object == obj && cache->dirty)
3077                         return 1;
3078         }
3079
3080         return 0;
3081 }
3082
3083 static void yaffs_flush_file_cache(struct yaffs_obj *obj)
3084 {
3085         struct yaffs_dev *dev = obj->my_dev;
3086         int lowest = -99;       /* Stop compiler whining. */
3087         int i;
3088         struct yaffs_cache *cache;
3089         int chunk_written = 0;
3090         int n_caches = obj->my_dev->param.n_caches;
3091
3092         if (n_caches > 0) {
3093                 do {
3094                         cache = NULL;
3095
3096                         /* Find the dirty cache for this object with the lowest chunk id. */
3097                         for (i = 0; i < n_caches; i++) {
3098                                 if (dev->cache[i].object == obj &&
3099                                     dev->cache[i].dirty) {
3100                                         if (!cache
3101                                             || dev->cache[i].chunk_id <
3102                                             lowest) {
3103                                                 cache = &dev->cache[i];
3104                                                 lowest = cache->chunk_id;
3105                                         }
3106                                 }
3107                         }
3108
3109                         if (cache && !cache->locked) {
3110                                 /* Write it out and free it up */
3111
3112                                 chunk_written =
3113                                     yaffs_wr_data_obj(cache->object,
3114                                                       cache->chunk_id,
3115                                                       cache->data,
3116                                                       cache->n_bytes, 1);
3117                                 cache->dirty = 0;
3118                                 cache->object = NULL;
3119                         }
3120
3121                 } while (cache && chunk_written > 0);
3122
3123                 if (cache) {
3124                         /* Hoosterman, disk full while writing cache out. */
3125                         T(YAFFS_TRACE_ERROR,
3126                           (TSTR
3127                            ("yaffs tragedy: no space during cache write"
3128                             TENDSTR)));
3129
3130                 }
3131         }
3132
3133 }
3134
3135 /*yaffs_flush_whole_cache(dev)
3136  *
3137  *
3138  */
3139
3140 void yaffs_flush_whole_cache(struct yaffs_dev *dev)
3141 {
3142         struct yaffs_obj *obj;
3143         int n_caches = dev->param.n_caches;
3144         int i;
3145
3146         /* Find a dirty object in the cache and flush it...
3147          * until there are no further dirty objects.
3148          */
3149         do {
3150                 obj = NULL;
3151                 for (i = 0; i < n_caches && !obj; i++) {
3152                         if (dev->cache[i].object && dev->cache[i].dirty)
3153                                 obj = dev->cache[i].object;
3154
3155                 }
3156                 if (obj)
3157                         yaffs_flush_file_cache(obj);
3158
3159         } while (obj);
3160
3161 }
3162
3163 /* Grab us a cache chunk for use.
3164  * First look for an empty one.
3165  * Then look for the least recently used non-dirty one.
3166  * Then look for the least recently used dirty one...., flush and look again.
3167  */
3168 static struct yaffs_cache *yaffs_grab_chunk_worker(struct yaffs_dev *dev)
3169 {
3170         int i;
3171
3172         if (dev->param.n_caches > 0) {
3173                 for (i = 0; i < dev->param.n_caches; i++) {
3174                         if (!dev->cache[i].object)
3175                                 return &dev->cache[i];
3176                 }
3177         }
3178
3179         return NULL;
3180 }
3181
3182 static struct yaffs_cache *yaffs_grab_chunk_cache(struct yaffs_dev *dev)
3183 {
3184         struct yaffs_cache *cache;
3185         struct yaffs_obj *the_obj;
3186         int usage;
3187         int i;
3188         int pushout;
3189
3190         if (dev->param.n_caches > 0) {
3191                 /* Try find a non-dirty one... */
3192
3193                 cache = yaffs_grab_chunk_worker(dev);
3194
3195                 if (!cache) {
3196                         /* They were all dirty, find the last recently used object and flush
3197                          * its cache, then  find again.
3198                          * NB what's here is not very accurate, we actually flush the object
3199                          * the last recently used page.
3200                          */
3201
3202                         /* With locking we can't assume we can use entry zero */
3203
3204                         the_obj = NULL;
3205                         usage = -1;
3206                         cache = NULL;
3207                         pushout = -1;
3208
3209                         for (i = 0; i < dev->param.n_caches; i++) {
3210                                 if (dev->cache[i].object &&
3211                                     !dev->cache[i].locked &&
3212                                     (dev->cache[i].last_use < usage
3213                                      || !cache)) {
3214                                         usage = dev->cache[i].last_use;
3215                                         the_obj = dev->cache[i].object;
3216                                         cache = &dev->cache[i];
3217                                         pushout = i;
3218                                 }
3219                         }
3220
3221                         if (!cache || cache->dirty) {
3222                                 /* Flush and try again */
3223                                 yaffs_flush_file_cache(the_obj);
3224                                 cache = yaffs_grab_chunk_worker(dev);
3225                         }
3226
3227                 }
3228                 return cache;
3229         } else {
3230                 return NULL;
3231         }
3232 }
3233
3234 /* Find a cached chunk */
3235 static struct yaffs_cache *yaffs_find_chunk_cache(const struct yaffs_obj *obj,
3236                                                   int chunk_id)
3237 {
3238         struct yaffs_dev *dev = obj->my_dev;
3239         int i;
3240         if (dev->param.n_caches > 0) {
3241                 for (i = 0; i < dev->param.n_caches; i++) {
3242                         if (dev->cache[i].object == obj &&
3243                             dev->cache[i].chunk_id == chunk_id) {
3244                                 dev->cache_hits++;
3245
3246                                 return &dev->cache[i];
3247                         }
3248                 }
3249         }
3250         return NULL;
3251 }
3252
3253 /* Mark the chunk for the least recently used algorithym */
3254 static void yaffs_use_cache(struct yaffs_dev *dev, struct yaffs_cache *cache,
3255                             int is_write)
3256 {
3257
3258         if (dev->param.n_caches > 0) {
3259                 if (dev->cache_last_use < 0 || dev->cache_last_use > 100000000) {
3260                         /* Reset the cache usages */
3261                         int i;
3262                         for (i = 1; i < dev->param.n_caches; i++)
3263                                 dev->cache[i].last_use = 0;
3264
3265                         dev->cache_last_use = 0;
3266                 }
3267
3268                 dev->cache_last_use++;
3269
3270                 cache->last_use = dev->cache_last_use;
3271
3272                 if (is_write)
3273                         cache->dirty = 1;
3274         }
3275 }
3276
3277 /* Invalidate a single cache page.
3278  * Do this when a whole page gets written,
3279  * ie the short cache for this page is no longer valid.
3280  */
3281 static void yaffs_invalidate_chunk_cache(struct yaffs_obj *object, int chunk_id)
3282 {
3283         if (object->my_dev->param.n_caches > 0) {
3284                 struct yaffs_cache *cache =
3285                     yaffs_find_chunk_cache(object, chunk_id);
3286
3287                 if (cache)
3288                         cache->object = NULL;
3289         }
3290 }
3291
3292 /* Invalidate all the cache pages associated with this object
3293  * Do this whenever ther file is deleted or resized.
3294  */
3295 static void yaffs_invalidate_whole_cache(struct yaffs_obj *in)
3296 {
3297         int i;
3298         struct yaffs_dev *dev = in->my_dev;
3299
3300         if (dev->param.n_caches > 0) {
3301                 /* Invalidate it. */
3302                 for (i = 0; i < dev->param.n_caches; i++) {
3303                         if (dev->cache[i].object == in)
3304                                 dev->cache[i].object = NULL;
3305                 }
3306         }
3307 }
3308
3309 /*--------------------- File read/write ------------------------
3310  * Read and write have very similar structures.
3311  * In general the read/write has three parts to it
3312  * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3313  * Some complete chunks
3314  * An incomplete chunk to end off with
3315  *
3316  * Curve-balls: the first chunk might also be the last chunk.
3317  */
3318
3319 int yaffs_file_rd(struct yaffs_obj *in, u8 * buffer, loff_t offset, int n_bytes)
3320 {
3321
3322         int chunk;
3323         u32 start;
3324         int n_copy;
3325         int n = n_bytes;
3326         int n_done = 0;
3327         struct yaffs_cache *cache;
3328
3329         struct yaffs_dev *dev;
3330
3331         dev = in->my_dev;
3332
3333         while (n > 0) {
3334                 /* chunk = offset / dev->data_bytes_per_chunk + 1; */
3335                 /* start = offset % dev->data_bytes_per_chunk; */
3336                 yaffs_addr_to_chunk(dev, offset, &chunk, &start);
3337                 chunk++;
3338
3339                 /* OK now check for the curveball where the start and end are in
3340                  * the same chunk.
3341                  */
3342                 if ((start + n) < dev->data_bytes_per_chunk)
3343                         n_copy = n;
3344                 else
3345                         n_copy = dev->data_bytes_per_chunk - start;
3346
3347                 cache = yaffs_find_chunk_cache(in, chunk);
3348
3349                 /* If the chunk is already in the cache or it is less than a whole chunk
3350                  * or we're using inband tags then use the cache (if there is caching)
3351                  * else bypass the cache.
3352                  */
3353                 if (cache || n_copy != dev->data_bytes_per_chunk
3354                     || dev->param.inband_tags) {
3355                         if (dev->param.n_caches > 0) {
3356
3357                                 /* If we can't find the data in the cache, then load it up. */
3358
3359                                 if (!cache) {
3360                                         cache =
3361                                             yaffs_grab_chunk_cache(in->my_dev);
3362                                         cache->object = in;
3363                                         cache->chunk_id = chunk;
3364                                         cache->dirty = 0;
3365                                         cache->locked = 0;
3366                                         yaffs_rd_data_obj(in, chunk,
3367                                                           cache->data);
3368                                         cache->n_bytes = 0;
3369                                 }
3370
3371                                 yaffs_use_cache(dev, cache, 0);
3372
3373                                 cache->locked = 1;
3374
3375                                 memcpy(buffer, &cache->data[start], n_copy);
3376
3377                                 cache->locked = 0;
3378                         } else {
3379                                 /* Read into the local buffer then copy.. */
3380
3381                                 u8 *local_buffer =
3382                                     yaffs_get_temp_buffer(dev, __LINE__);
3383                                 yaffs_rd_data_obj(in, chunk, local_buffer);
3384
3385                                 memcpy(buffer, &local_buffer[start], n_copy);
3386
3387                                 yaffs_release_temp_buffer(dev, local_buffer,
3388                                                           __LINE__);
3389                         }
3390
3391                 } else {
3392
3393                         /* A full chunk. Read directly into the supplied buffer. */
3394                         yaffs_rd_data_obj(in, chunk, buffer);
3395
3396                 }
3397
3398                 n -= n_copy;
3399                 offset += n_copy;
3400                 buffer += n_copy;
3401                 n_done += n_copy;
3402
3403         }
3404
3405         return n_done;
3406 }
3407
3408 int yaffs_do_file_wr(struct yaffs_obj *in, const u8 * buffer, loff_t offset,
3409                      int n_bytes, int write_trhrough)
3410 {
3411
3412         int chunk;
3413         u32 start;
3414         int n_copy;
3415         int n = n_bytes;
3416         int n_done = 0;
3417         int n_writeback;
3418         int start_write = offset;
3419         int chunk_written = 0;
3420         u32 n_bytes_read;
3421         u32 chunk_start;
3422
3423         struct yaffs_dev *dev;
3424
3425         dev = in->my_dev;
3426
3427         while (n > 0 && chunk_written >= 0) {
3428                 yaffs_addr_to_chunk(dev, offset, &chunk, &start);
3429
3430                 if (chunk * dev->data_bytes_per_chunk + start != offset ||
3431                     start >= dev->data_bytes_per_chunk) {
3432                         T(YAFFS_TRACE_ERROR,
3433                           (TSTR
3434                            ("AddrToChunk of offset %d gives chunk %d start %d"
3435                             TENDSTR), (int)offset, chunk, start));
3436                 }
3437                 chunk++;        /* File pos to chunk in file offset */
3438
3439                 /* OK now check for the curveball where the start and end are in
3440                  * the same chunk.
3441                  */
3442
3443                 if ((start + n) < dev->data_bytes_per_chunk) {
3444                         n_copy = n;
3445
3446                         /* Now folks, to calculate how many bytes to write back....
3447                          * If we're overwriting and not writing to then end of file then
3448                          * we need to write back as much as was there before.
3449                          */
3450
3451                         chunk_start = ((chunk - 1) * dev->data_bytes_per_chunk);
3452
3453                         if (chunk_start > in->variant.file_variant.file_size)
3454                                 n_bytes_read = 0;       /* Past end of file */
3455                         else
3456                                 n_bytes_read =
3457                                     in->variant.file_variant.file_size -
3458                                     chunk_start;
3459
3460                         if (n_bytes_read > dev->data_bytes_per_chunk)
3461                                 n_bytes_read = dev->data_bytes_per_chunk;
3462
3463                         n_writeback =
3464                             (n_bytes_read >
3465                              (start + n)) ? n_bytes_read : (start + n);
3466
3467                         if (n_writeback < 0
3468                             || n_writeback > dev->data_bytes_per_chunk)
3469                                 YBUG();
3470
3471                 } else {
3472                         n_copy = dev->data_bytes_per_chunk - start;
3473                         n_writeback = dev->data_bytes_per_chunk;
3474                 }
3475
3476                 if (n_copy != dev->data_bytes_per_chunk
3477                     || dev->param.inband_tags) {
3478                         /* An incomplete start or end chunk (or maybe both start and end chunk),
3479                          * or we're using inband tags, so we want to use the cache buffers.
3480                          */
3481                         if (dev->param.n_caches > 0) {
3482                                 struct yaffs_cache *cache;
3483                                 /* If we can't find the data in the cache, then load the cache */
3484                                 cache = yaffs_find_chunk_cache(in, chunk);
3485
3486                                 if (!cache
3487                                     && yaffs_check_alloc_available(dev, 1)) {
3488                                         cache = yaffs_grab_chunk_cache(dev);
3489                                         cache->object = in;
3490                                         cache->chunk_id = chunk;
3491                                         cache->dirty = 0;
3492                                         cache->locked = 0;
3493                                         yaffs_rd_data_obj(in, chunk,
3494                                                           cache->data);
3495                                 } else if (cache &&
3496                                            !cache->dirty &&
3497                                            !yaffs_check_alloc_available(dev,
3498                                                                         1)) {
3499                                         /* Drop the cache if it was a read cache item and
3500                                          * no space check has been made for it.
3501                                          */
3502                                         cache = NULL;
3503                                 }
3504
3505                                 if (cache) {
3506                                         yaffs_use_cache(dev, cache, 1);
3507                                         cache->locked = 1;
3508
3509                                         memcpy(&cache->data[start], buffer,
3510                                                n_copy);
3511
3512                                         cache->locked = 0;
3513                                         cache->n_bytes = n_writeback;
3514
3515                                         if (write_trhrough) {
3516                                                 chunk_written =
3517                                                     yaffs_wr_data_obj
3518                                                     (cache->object,
3519                                                      cache->chunk_id,
3520                                                      cache->data,
3521                                                      cache->n_bytes, 1);
3522                                                 cache->dirty = 0;
3523                                         }
3524
3525                                 } else {
3526                                         chunk_written = -1;     /* fail the write */
3527                                 }
3528                         } else {
3529                                 /* An incomplete start or end chunk (or maybe both start and end chunk)
3530                                  * Read into the local buffer then copy, then copy over and write back.
3531                                  */
3532
3533                                 u8 *local_buffer =
3534                                     yaffs_get_temp_buffer(dev, __LINE__);
3535
3536                                 yaffs_rd_data_obj(in, chunk, local_buffer);
3537
3538                                 memcpy(&local_buffer[start], buffer, n_copy);
3539
3540                                 chunk_written =
3541                                     yaffs_wr_data_obj(in, chunk,
3542                                                       local_buffer,
3543                                                       n_writeback, 0);
3544
3545                                 yaffs_release_temp_buffer(dev, local_buffer,
3546                                                           __LINE__);
3547
3548                         }
3549
3550                 } else {
3551                         /* A full chunk. Write directly from the supplied buffer. */
3552
3553                         chunk_written =
3554                             yaffs_wr_data_obj(in, chunk, buffer,
3555                                               dev->data_bytes_per_chunk, 0);
3556
3557                         /* Since we've overwritten the cached data, we better invalidate it. */
3558                         yaffs_invalidate_chunk_cache(in, chunk);
3559                 }
3560
3561                 if (chunk_written >= 0) {
3562                         n -= n_copy;
3563                         offset += n_copy;
3564                         buffer += n_copy;
3565                         n_done += n_copy;
3566                 }
3567
3568         }
3569
3570         /* Update file object */
3571
3572         if ((start_write + n_done) > in->variant.file_variant.file_size)
3573                 in->variant.file_variant.file_size = (start_write + n_done);
3574
3575         in->dirty = 1;
3576
3577         return n_done;
3578 }
3579
3580 int yaffs_wr_file(struct yaffs_obj *in, const u8 * buffer, loff_t offset,
3581                   int n_bytes, int write_trhrough)
3582 {
3583         yaffs2_handle_hole(in, offset);
3584         return yaffs_do_file_wr(in, buffer, offset, n_bytes, write_trhrough);
3585 }
3586
3587 /* ---------------------- File resizing stuff ------------------ */
3588
3589 static void yaffs_prune_chunks(struct yaffs_obj *in, int new_size)
3590 {
3591
3592         struct yaffs_dev *dev = in->my_dev;
3593         int old_size = in->variant.file_variant.file_size;
3594
3595         int last_del = 1 + (old_size - 1) / dev->data_bytes_per_chunk;
3596
3597         int start_del = 1 + (new_size + dev->data_bytes_per_chunk - 1) /
3598             dev->data_bytes_per_chunk;
3599         int i;
3600         int chunk_id;
3601
3602         /* Delete backwards so that we don't end up with holes if
3603          * power is lost part-way through the operation.
3604          */
3605         for (i = last_del; i >= start_del; i--) {
3606                 /* NB this could be optimised somewhat,
3607                  * eg. could retrieve the tags and write them without
3608                  * using yaffs_chunk_del
3609                  */
3610
3611                 chunk_id = yaffs_find_del_file_chunk(in, i, NULL);
3612                 if (chunk_id > 0) {
3613                         if (chunk_id <
3614                             (dev->internal_start_block *
3615                              dev->param.chunks_per_block)
3616                             || chunk_id >=
3617                             ((dev->internal_end_block +
3618                               1) * dev->param.chunks_per_block)) {
3619                                 T(YAFFS_TRACE_ALWAYS,
3620                                   (TSTR
3621                                    ("Found daft chunk_id %d for %d" TENDSTR),
3622                                    chunk_id, i));
3623                         } else {
3624                                 in->n_data_chunks--;
3625                                 yaffs_chunk_del(dev, chunk_id, 1, __LINE__);
3626                         }
3627                 }
3628         }
3629
3630 }
3631
3632 void yaffs_resize_file_down(struct yaffs_obj *obj, loff_t new_size)
3633 {
3634         int new_full;
3635         u32 new_partial;
3636         struct yaffs_dev *dev = obj->my_dev;
3637
3638         yaffs_addr_to_chunk(dev, new_size, &new_full, &new_partial);
3639
3640         yaffs_prune_chunks(obj, new_size);
3641
3642         if (new_partial != 0) {
3643                 int last_chunk = 1 + new_full;
3644                 u8 *local_buffer = yaffs_get_temp_buffer(dev, __LINE__);
3645
3646                 /* Got to read and rewrite the last chunk with its new size and zero pad */
3647                 yaffs_rd_data_obj(obj, last_chunk, local_buffer);
3648                 memset(local_buffer + new_partial, 0,
3649                        dev->data_bytes_per_chunk - new_partial);
3650
3651                 yaffs_wr_data_obj(obj, last_chunk, local_buffer,
3652                                   new_partial, 1);
3653
3654                 yaffs_release_temp_buffer(dev, local_buffer, __LINE__);
3655         }
3656
3657         obj->variant.file_variant.file_size = new_size;
3658
3659         yaffs_prune_tree(dev, &obj->variant.file_variant);
3660 }
3661
3662 int yaffs_resize_file(struct yaffs_obj *in, loff_t new_size)
3663 {
3664         struct yaffs_dev *dev = in->my_dev;
3665         int old_size = in->variant.file_variant.file_size;
3666
3667         yaffs_flush_file_cache(in);
3668         yaffs_invalidate_whole_cache(in);
3669
3670         yaffs_check_gc(dev, 0);
3671
3672         if (in->variant_type != YAFFS_OBJECT_TYPE_FILE)
3673                 return YAFFS_FAIL;
3674
3675         if (new_size == old_size)
3676                 return YAFFS_OK;
3677
3678         if (new_size > old_size) {
3679                 yaffs2_handle_hole(in, new_size);
3680                 in->variant.file_variant.file_size = new_size;
3681         } else {
3682                 /* new_size < old_size */
3683                 yaffs_resize_file_down(in, new_size);
3684         }
3685
3686         /* Write a new object header to reflect the resize.
3687          * show we've shrunk the file, if need be
3688          * Do this only if the file is not in the deleted directories
3689          * and is not shadowed.
3690          */
3691         if (in->parent &&
3692             !in->is_shadowed &&
3693             in->parent->obj_id != YAFFS_OBJECTID_UNLINKED &&
3694             in->parent->obj_id != YAFFS_OBJECTID_DELETED)
3695                 yaffs_update_oh(in, NULL, 0, 0, 0, NULL);
3696
3697         return YAFFS_OK;
3698 }
3699
3700 int yaffs_flush_file(struct yaffs_obj *in, int update_time, int data_sync)
3701 {
3702         int ret_val;
3703         if (in->dirty) {
3704                 yaffs_flush_file_cache(in);
3705                 if (data_sync)  /* Only sync data */
3706                         ret_val = YAFFS_OK;
3707                 else {
3708                         if (update_time)
3709                                 yaffs_load_current_time(in, 0, 0);
3710
3711                         ret_val = (yaffs_update_oh(in, NULL, 0, 0, 0, NULL) >=
3712                                    0) ? YAFFS_OK : YAFFS_FAIL;
3713                 }
3714         } else {
3715                 ret_val = YAFFS_OK;
3716         }
3717
3718         return ret_val;
3719
3720 }
3721
3722 static int yaffs_generic_obj_del(struct yaffs_obj *in)
3723 {
3724
3725         /* First off, invalidate the file's data in the cache, without flushing. */
3726         yaffs_invalidate_whole_cache(in);
3727
3728         if (in->my_dev->param.is_yaffs2 && (in->parent != in->my_dev->del_dir)) {
3729                 /* Move to the unlinked directory so we have a record that it was deleted. */
3730                 yaffs_change_obj_name(in, in->my_dev->del_dir, _Y("deleted"), 0,
3731                                       0);
3732
3733         }
3734
3735         yaffs_remove_obj_from_dir(in);
3736         yaffs_chunk_del(in->my_dev, in->hdr_chunk, 1, __LINE__);
3737         in->hdr_chunk = 0;
3738
3739         yaffs_free_obj(in);
3740         return YAFFS_OK;
3741
3742 }
3743
3744 /* yaffs_del_file deletes the whole file data
3745  * and the inode associated with the file.
3746  * It does not delete the links associated with the file.
3747  */
3748 static int yaffs_unlink_file_if_needed(struct yaffs_obj *in)
3749 {
3750
3751         int ret_val;
3752         int del_now = 0;
3753         struct yaffs_dev *dev = in->my_dev;
3754
3755         if (!in->my_inode)
3756                 del_now = 1;
3757
3758         if (del_now) {
3759                 ret_val =
3760                     yaffs_change_obj_name(in, in->my_dev->del_dir,
3761                                           _Y("deleted"), 0, 0);
3762                 T(YAFFS_TRACE_TRACING,
3763                   (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
3764                    in->obj_id));
3765                 in->deleted = 1;
3766                 in->my_dev->n_deleted_files++;
3767                 if (dev->param.disable_soft_del || dev->param.is_yaffs2)
3768                         yaffs_resize_file(in, 0);
3769                 yaffs_soft_del_file(in);
3770         } else {
3771                 ret_val =
3772                     yaffs_change_obj_name(in, in->my_dev->unlinked_dir,
3773                                           _Y("unlinked"), 0, 0);
3774         }
3775
3776         return ret_val;
3777 }
3778
3779 int yaffs_del_file(struct yaffs_obj *in)
3780 {
3781         int ret_val = YAFFS_OK;
3782         int deleted;            /* Need to cache value on stack if in is freed */
3783         struct yaffs_dev *dev = in->my_dev;
3784
3785         if (dev->param.disable_soft_del || dev->param.is_yaffs2)
3786                 yaffs_resize_file(in, 0);
3787
3788         if (in->n_data_chunks > 0) {
3789                 /* Use soft deletion if there is data in the file.
3790                  * That won't be the case if it has been resized to zero.
3791                  */
3792                 if (!in->unlinked)
3793                         ret_val = yaffs_unlink_file_if_needed(in);
3794
3795                 deleted = in->deleted;
3796
3797                 if (ret_val == YAFFS_OK && in->unlinked && !in->deleted) {
3798                         in->deleted = 1;
3799                         deleted = 1;
3800                         in->my_dev->n_deleted_files++;
3801                         yaffs_soft_del_file(in);
3802                 }
3803                 return deleted ? YAFFS_OK : YAFFS_FAIL;
3804         } else {
3805                 /* The file has no data chunks so we toss it immediately */
3806                 yaffs_free_tnode(in->my_dev, in->variant.file_variant.top);
3807                 in->variant.file_variant.top = NULL;
3808                 yaffs_generic_obj_del(in);
3809
3810                 return YAFFS_OK;
3811         }
3812 }
3813
3814 static int yaffs_is_non_empty_dir(struct yaffs_obj *obj)
3815 {
3816         return (obj->variant_type == YAFFS_OBJECT_TYPE_DIRECTORY) &&
3817             !(list_empty(&obj->variant.dir_variant.children));
3818 }
3819
3820 static int yaffs_del_dir(struct yaffs_obj *obj)
3821 {
3822         /* First check that the directory is empty. */
3823         if (yaffs_is_non_empty_dir(obj))
3824                 return YAFFS_FAIL;
3825
3826         return yaffs_generic_obj_del(obj);
3827 }
3828
3829 static int yaffs_del_symlink(struct yaffs_obj *in)
3830 {
3831         if (in->variant.symlink_variant.alias)
3832                 YFREE(in->variant.symlink_variant.alias);
3833         in->variant.symlink_variant.alias = NULL;
3834
3835         return yaffs_generic_obj_del(in);
3836 }
3837
3838 static int yaffs_del_link(struct yaffs_obj *in)
3839 {
3840         /* remove this hardlink from the list assocaited with the equivalent
3841          * object
3842          */
3843         list_del_init(&in->hard_links);
3844         return yaffs_generic_obj_del(in);
3845 }
3846
3847 int yaffs_del_obj(struct yaffs_obj *obj)
3848 {
3849         int ret_val = -1;
3850         switch (obj->variant_type) {
3851         case YAFFS_OBJECT_TYPE_FILE:
3852                 ret_val = yaffs_del_file(obj);
3853                 break;
3854         case YAFFS_OBJECT_TYPE_DIRECTORY:
3855                 if (!list_empty(&obj->variant.dir_variant.dirty)) {
3856                         T(YAFFS_TRACE_BACKGROUND,
3857                           (TSTR
3858                            ("Remove object %d from dirty directories" TENDSTR),
3859                            obj->obj_id));
3860                         list_del_init(&obj->variant.dir_variant.dirty);
3861                 }
3862                 return yaffs_del_dir(obj);
3863                 break;
3864         case YAFFS_OBJECT_TYPE_SYMLINK:
3865                 ret_val = yaffs_del_symlink(obj);
3866                 break;
3867         case YAFFS_OBJECT_TYPE_HARDLINK:
3868                 ret_val = yaffs_del_link(obj);
3869                 break;
3870         case YAFFS_OBJECT_TYPE_SPECIAL:
3871                 ret_val = yaffs_generic_obj_del(obj);
3872                 break;
3873         case YAFFS_OBJECT_TYPE_UNKNOWN:
3874                 ret_val = 0;
3875                 break;          /* should not happen. */
3876         }
3877
3878         return ret_val;
3879 }
3880
3881 static int yaffs_unlink_worker(struct yaffs_obj *obj)
3882 {
3883
3884         int del_now = 0;
3885
3886         if (!obj->my_inode)
3887                 del_now = 1;
3888
3889         if (obj)
3890                 yaffs_update_parent(obj->parent);
3891
3892         if (obj->variant_type == YAFFS_OBJECT_TYPE_HARDLINK) {
3893                 return yaffs_del_link(obj);
3894         } else if (!list_empty(&obj->hard_links)) {
3895                 /* Curve ball: We're unlinking an object that has a hardlink.
3896                  *
3897                  * This problem arises because we are not strictly following
3898                  * The Linux link/inode model.
3899                  *
3900                  * We can't really delete the object.
3901                  * Instead, we do the following:
3902                  * - Select a hardlink.
3903                  * - Unhook it from the hard links
3904                  * - Move it from its parent directory (so that the rename can work)
3905                  * - Rename the object to the hardlink's name.
3906                  * - Delete the hardlink
3907                  */
3908
3909                 struct yaffs_obj *hl;
3910                 struct yaffs_obj *parent;
3911                 int ret_val;
3912                 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
3913
3914                 hl = list_entry(obj->hard_links.next, struct yaffs_obj,
3915                                 hard_links);
3916
3917                 yaffs_get_obj_name(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
3918                 parent = hl->parent;
3919
3920                 list_del_init(&hl->hard_links);
3921
3922                 yaffs_add_obj_to_dir(obj->my_dev->unlinked_dir, hl);
3923
3924                 ret_val = yaffs_change_obj_name(obj, parent, name, 0, 0);
3925
3926                 if (ret_val == YAFFS_OK)
3927                         ret_val = yaffs_generic_obj_del(hl);
3928
3929                 return ret_val;
3930
3931         } else if (del_now) {
3932                 switch (obj->variant_type) {
3933                 case YAFFS_OBJECT_TYPE_FILE:
3934                         return yaffs_del_file(obj);
3935                         break;
3936                 case YAFFS_OBJECT_TYPE_DIRECTORY:
3937                         list_del_init(&obj->variant.dir_variant.dirty);
3938                         return yaffs_del_dir(obj);
3939                         break;
3940                 case YAFFS_OBJECT_TYPE_SYMLINK:
3941                         return yaffs_del_symlink(obj);
3942                         break;
3943                 case YAFFS_OBJECT_TYPE_SPECIAL:
3944                         return yaffs_generic_obj_del(obj);
3945                         break;
3946                 case YAFFS_OBJECT_TYPE_HARDLINK:
3947                 case YAFFS_OBJECT_TYPE_UNKNOWN:
3948                 default:
3949                         return YAFFS_FAIL;
3950                 }
3951         } else if (yaffs_is_non_empty_dir(obj)) {
3952                 return YAFFS_FAIL;
3953         } else {
3954                 return yaffs_change_obj_name(obj, obj->my_dev->unlinked_dir,
3955                                              _Y("unlinked"), 0, 0);
3956         }
3957 }
3958
3959 static int yaffs_unlink_obj(struct yaffs_obj *obj)
3960 {
3961
3962         if (obj && obj->unlink_allowed)
3963                 return yaffs_unlink_worker(obj);
3964
3965         return YAFFS_FAIL;
3966
3967 }
3968
3969 int yaffs_unlinker(struct yaffs_obj *dir, const YCHAR * name)
3970 {
3971         struct yaffs_obj *obj;
3972
3973         obj = yaffs_find_by_name(dir, name);
3974         return yaffs_unlink_obj(obj);
3975 }
3976
3977 /*----------------------- Initialisation Scanning ---------------------- */
3978
3979 void yaffs_handle_shadowed_obj(struct yaffs_dev *dev, int obj_id,
3980                                int backward_scanning)
3981 {
3982         struct yaffs_obj *obj;
3983
3984         if (!backward_scanning) {
3985                 /* Handle YAFFS1 forward scanning case
3986                  * For YAFFS1 we always do the deletion
3987                  */
3988
3989         } else {
3990                 /* Handle YAFFS2 case (backward scanning)
3991                  * If the shadowed object exists then ignore.
3992                  */
3993                 obj = yaffs_find_by_number(dev, obj_id);
3994                 if (obj)
3995                         return;
3996         }
3997
3998         /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
3999          * We put it in unlinked dir to be cleaned up after the scanning
4000          */
4001         obj =
4002             yaffs_find_or_create_by_number(dev, obj_id, YAFFS_OBJECT_TYPE_FILE);
4003         if (!obj)
4004                 return;
4005         obj->is_shadowed = 1;
4006         yaffs_add_obj_to_dir(dev->unlinked_dir, obj);
4007         obj->variant.file_variant.shrink_size = 0;
4008         obj->valid = 1;         /* So that we don't read any other info for this file */
4009
4010 }
4011
4012 void yaffs_link_fixup(struct yaffs_dev *dev, struct yaffs_obj *hard_list)
4013 {
4014         struct yaffs_obj *hl;
4015         struct yaffs_obj *in;
4016
4017         while (hard_list) {
4018                 hl = hard_list;
4019                 hard_list = (struct yaffs_obj *)(hard_list->hard_links.next);
4020
4021                 in = yaffs_find_by_number(dev,
4022                                           hl->variant.
4023                                           hardlink_variant.equiv_id);
4024
4025                 if (in) {
4026                         /* Add the hardlink pointers */
4027                         hl->variant.hardlink_variant.equiv_obj = in;
4028                         list_add(&hl->hard_links, &in->hard_links);
4029                 } else {
4030                         /* Todo Need to report/handle this better.
4031                          * Got a problem... hardlink to a non-existant object
4032                          */
4033                         hl->variant.hardlink_variant.equiv_obj = NULL;
4034                         INIT_LIST_HEAD(&hl->hard_links);
4035
4036                 }
4037         }
4038 }
4039
4040 static void yaffs_strip_deleted_objs(struct yaffs_dev *dev)
4041 {
4042         /*
4043          *  Sort out state of unlinked and deleted objects after scanning.
4044          */
4045         struct list_head *i;
4046         struct list_head *n;
4047         struct yaffs_obj *l;
4048
4049         if (dev->read_only)
4050                 return;
4051
4052         /* Soft delete all the unlinked files */
4053         list_for_each_safe(i, n,
4054                            &dev->unlinked_dir->variant.dir_variant.children) {
4055                 if (i) {
4056                         l = list_entry(i, struct yaffs_obj, siblings);
4057                         yaffs_del_obj(l);
4058                 }
4059         }
4060
4061         list_for_each_safe(i, n, &dev->del_dir->variant.dir_variant.children) {
4062                 if (i) {
4063                         l = list_entry(i, struct yaffs_obj, siblings);
4064                         yaffs_del_obj(l);
4065                 }
4066         }
4067
4068 }
4069
4070 /*
4071  * This code iterates through all the objects making sure that they are rooted.
4072  * Any unrooted objects are re-rooted in lost+found.
4073  * An object needs to be in one of:
4074  * - Directly under deleted, unlinked
4075  * - Directly or indirectly under root.
4076  *
4077  * Note:
4078  *  This code assumes that we don't ever change the current relationships between
4079  *  directories:
4080  *   root_dir->parent == unlinked_dir->parent == del_dir->parent == NULL
4081  *   lost-n-found->parent == root_dir
4082  *
4083  * This fixes the problem where directories might have inadvertently been deleted
4084  * leaving the object "hanging" without being rooted in the directory tree.
4085  */
4086
4087 static int yaffs_has_null_parent(struct yaffs_dev *dev, struct yaffs_obj *obj)
4088 {
4089         return (obj == dev->del_dir ||
4090                 obj == dev->unlinked_dir || obj == dev->root_dir);
4091 }
4092
4093 static void yaffs_fix_hanging_objs(struct yaffs_dev *dev)
4094 {
4095         struct yaffs_obj *obj;
4096         struct yaffs_obj *parent;
4097         int i;
4098         struct list_head *lh;
4099         struct list_head *n;
4100         int depth_limit;
4101         int hanging;
4102
4103         if (dev->read_only)
4104                 return;
4105
4106         /* Iterate through the objects in each hash entry,
4107          * looking at each object.
4108          * Make sure it is rooted.
4109          */
4110
4111         for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
4112                 list_for_each_safe(lh, n, &dev->obj_bucket[i].list) {
4113                         if (lh) {
4114                                 obj =
4115                                     list_entry(lh, struct yaffs_obj, hash_link);
4116                                 parent = obj->parent;
4117
4118                                 if (yaffs_has_null_parent(dev, obj)) {
4119                                         /* These directories are not hanging */
4120                                         hanging = 0;
4121                                 } else if (!parent
4122                                            || parent->variant_type !=
4123                                            YAFFS_OBJECT_TYPE_DIRECTORY) {
4124                                         hanging = 1;
4125                                 } else if (yaffs_has_null_parent(dev, parent)) {
4126                                         hanging = 0;
4127                                 } else {
4128                                         /*
4129                                          * Need to follow the parent chain to see if it is hanging.
4130                                          */
4131                                         hanging = 0;
4132                                         depth_limit = 100;
4133
4134                                         while (parent != dev->root_dir &&
4135                                                parent->parent &&
4136                                                parent->parent->variant_type ==
4137                                                YAFFS_OBJECT_TYPE_DIRECTORY
4138                                                && depth_limit > 0) {
4139                                                 parent = parent->parent;
4140                                                 depth_limit--;
4141                                         }
4142                                         if (parent != dev->root_dir)
4143                                                 hanging = 1;
4144                                 }
4145                                 if (hanging) {
4146                                         T(YAFFS_TRACE_SCAN,
4147                                           (TSTR
4148                                            ("Hanging object %d moved to lost and found"
4149                                             TENDSTR), obj->obj_id));
4150                                         yaffs_add_obj_to_dir(dev->lost_n_found,
4151                                                              obj);
4152                                 }
4153                         }
4154                 }
4155         }
4156 }
4157
4158 /*
4159  * Delete directory contents for cleaning up lost and found.
4160  */
4161 static void yaffs_del_dir_contents(struct yaffs_obj *dir)
4162 {
4163         struct yaffs_obj *obj;
4164         struct list_head *lh;
4165         struct list_head *n;
4166
4167         if (dir->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY)
4168                 YBUG();
4169
4170         list_for_each_safe(lh, n, &dir->variant.dir_variant.children) {
4171                 if (lh) {
4172                         obj = list_entry(lh, struct yaffs_obj, siblings);
4173                         if (obj->variant_type == YAFFS_OBJECT_TYPE_DIRECTORY)
4174                                 yaffs_del_dir_contents(obj);
4175
4176                         T(YAFFS_TRACE_SCAN,
4177                           (TSTR("Deleting lost_found object %d" TENDSTR),
4178                            obj->obj_id));
4179
4180                         /* Need to use UnlinkObject since Delete would not handle
4181                          * hardlinked objects correctly.
4182                          */
4183                         yaffs_unlink_obj(obj);
4184                 }
4185         }
4186
4187 }
4188
4189 static void yaffs_empty_l_n_f(struct yaffs_dev *dev)
4190 {
4191         yaffs_del_dir_contents(dev->lost_n_found);
4192 }
4193
4194 static void yaffs_check_obj_details_loaded(struct yaffs_obj *in)
4195 {
4196         u8 *chunk_data;
4197         struct yaffs_obj_hdr *oh;
4198         struct yaffs_dev *dev;
4199         struct yaffs_ext_tags tags;
4200         int result;
4201         int alloc_failed = 0;
4202
4203         if (!in)
4204                 return;
4205
4206         dev = in->my_dev;
4207
4208         if (in->lazy_loaded && in->hdr_chunk > 0) {
4209                 in->lazy_loaded = 0;
4210                 chunk_data = yaffs_get_temp_buffer(dev, __LINE__);
4211
4212                 result =
4213                     yaffs_rd_chunk_tags_nand(dev, in->hdr_chunk, chunk_data,
4214                                              &tags);
4215                 oh = (struct yaffs_obj_hdr *)chunk_data;
4216
4217                 in->yst_mode = oh->yst_mode;
4218                 yaffs_load_attribs(in, oh);
4219                 yaffs_set_obj_name_from_oh(in, oh);
4220
4221                 if (in->variant_type == YAFFS_OBJECT_TYPE_SYMLINK) {
4222                         in->variant.symlink_variant.alias =
4223                             yaffs_clone_str(oh->alias);
4224                         if (!in->variant.symlink_variant.alias)
4225                                 alloc_failed = 1;       /* Not returned to caller */
4226                 }
4227
4228                 yaffs_release_temp_buffer(dev, chunk_data, __LINE__);
4229         }
4230 }
4231
4232 /*------------------------------  Directory Functions ----------------------------- */
4233
4234 /*
4235  *yaffs_update_parent() handles fixing a directories mtime and ctime when a new
4236  * link (ie. name) is created or deleted in the directory.
4237  *
4238  * ie.
4239  *   create dir/a : update dir's mtime/ctime
4240  *   rm dir/a:   update dir's mtime/ctime
4241  *   modify dir/a: don't update dir's mtimme/ctime
4242  *
4243  * This can be handled immediately or defered. Defering helps reduce the number
4244  * of updates when many files in a directory are changed within a brief period.
4245  *
4246  * If the directory updating is defered then yaffs_update_dirty_dirs must be
4247  * called periodically.
4248  */
4249
4250 static void yaffs_update_parent(struct yaffs_obj *obj)
4251 {
4252         struct yaffs_dev *dev;
4253         if (!obj)
4254                 return;
4255         dev = obj->my_dev;
4256         obj->dirty = 1;
4257         yaffs_load_current_time(obj, 0, 1);
4258         if (dev->param.defered_dir_update) {
4259                 struct list_head *link = &obj->variant.dir_variant.dirty;
4260
4261                 if (list_empty(link)) {
4262                         list_add(link, &dev->dirty_dirs);
4263                         T(YAFFS_TRACE_BACKGROUND,
4264                           (TSTR("Added object %d to dirty directories" TENDSTR),
4265                            obj->obj_id));
4266                 }
4267
4268         } else {
4269                 yaffs_update_oh(obj, NULL, 0, 0, 0, NULL);
4270         }
4271 }
4272
4273 void yaffs_update_dirty_dirs(struct yaffs_dev *dev)
4274 {
4275         struct list_head *link;
4276         struct yaffs_obj *obj;
4277         struct yaffs_dir_var *d_s;
4278         union yaffs_obj_var *o_v;
4279
4280         T(YAFFS_TRACE_BACKGROUND, (TSTR("Update dirty directories" TENDSTR)));
4281
4282         while (!list_empty(&dev->dirty_dirs)) {
4283                 link = dev->dirty_dirs.next;
4284                 list_del_init(link);
4285
4286                 d_s = list_entry(link, struct yaffs_dir_var, dirty);
4287                 o_v = list_entry(d_s, union yaffs_obj_var, dir_variant);
4288                 obj = list_entry(o_v, struct yaffs_obj, variant);
4289
4290                 T(YAFFS_TRACE_BACKGROUND,
4291                   (TSTR("Update directory %d" TENDSTR), obj->obj_id));
4292
4293                 if (obj->dirty)
4294                         yaffs_update_oh(obj, NULL, 0, 0, 0, NULL);
4295         }
4296 }
4297
4298 static void yaffs_remove_obj_from_dir(struct yaffs_obj *obj)
4299 {
4300         struct yaffs_dev *dev = obj->my_dev;
4301         struct yaffs_obj *parent;
4302
4303         yaffs_verify_obj_in_dir(obj);
4304         parent = obj->parent;
4305
4306         yaffs_verify_dir(parent);
4307
4308         if (dev && dev->param.remove_obj_fn)
4309                 dev->param.remove_obj_fn(obj);
4310
4311         list_del_init(&obj->siblings);
4312         obj->parent = NULL;
4313
4314         yaffs_verify_dir(parent);
4315 }
4316
4317 void yaffs_add_obj_to_dir(struct yaffs_obj *directory, struct yaffs_obj *obj)
4318 {
4319         if (!directory) {
4320                 T(YAFFS_TRACE_ALWAYS,
4321                   (TSTR
4322                    ("tragedy: Trying to add an object to a null pointer directory"
4323                     TENDSTR)));
4324                 YBUG();
4325                 return;
4326         }
4327         if (directory->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY) {
4328                 T(YAFFS_TRACE_ALWAYS,
4329                   (TSTR
4330                    ("tragedy: Trying to add an object to a non-directory"
4331                     TENDSTR)));
4332                 YBUG();
4333         }
4334
4335         if (obj->siblings.prev == NULL) {
4336                 /* Not initialised */
4337                 YBUG();
4338         }
4339
4340         yaffs_verify_dir(directory);
4341
4342         yaffs_remove_obj_from_dir(obj);
4343
4344         /* Now add it */
4345         list_add(&obj->siblings, &directory->variant.dir_variant.children);
4346         obj->parent = directory;
4347
4348         if (directory == obj->my_dev->unlinked_dir
4349             || directory == obj->my_dev->del_dir) {
4350                 obj->unlinked = 1;
4351                 obj->my_dev->n_unlinked_files++;
4352                 obj->rename_allowed = 0;
4353         }
4354
4355         yaffs_verify_dir(directory);
4356         yaffs_verify_obj_in_dir(obj);
4357 }
4358
4359 struct yaffs_obj *yaffs_find_by_name(struct yaffs_obj *directory,
4360                                      const YCHAR * name)
4361 {
4362         int sum;
4363
4364         struct list_head *i;
4365         YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
4366
4367         struct yaffs_obj *l;
4368
4369         if (!name)
4370                 return NULL;
4371
4372         if (!directory) {
4373                 T(YAFFS_TRACE_ALWAYS,
4374                   (TSTR
4375                    ("tragedy: yaffs_find_by_name: null pointer directory"
4376                     TENDSTR)));
4377                 YBUG();
4378                 return NULL;
4379         }
4380         if (directory->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY) {
4381                 T(YAFFS_TRACE_ALWAYS,
4382                   (TSTR("tragedy: yaffs_find_by_name: non-directory" TENDSTR)));
4383                 YBUG();
4384         }
4385
4386         sum = yaffs_calc_name_sum(name);
4387
4388         list_for_each(i, &directory->variant.dir_variant.children) {
4389                 if (i) {
4390                         l = list_entry(i, struct yaffs_obj, siblings);
4391
4392                         if (l->parent != directory)
4393                                 YBUG();
4394
4395                         yaffs_check_obj_details_loaded(l);
4396
4397                         /* Special case for lost-n-found */
4398                         if (l->obj_id == YAFFS_OBJECTID_LOSTNFOUND) {
4399                                 if (!yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME))
4400                                         return l;
4401                         } else if (yaffs_sum_cmp(l->sum, sum)
4402                                    || l->hdr_chunk <= 0) {
4403                                 /* LostnFound chunk called Objxxx
4404                                  * Do a real check
4405                                  */
4406                                 yaffs_get_obj_name(l, buffer,
4407                                                    YAFFS_MAX_NAME_LENGTH + 1);
4408                                 if (yaffs_strncmp
4409                                     (name, buffer, YAFFS_MAX_NAME_LENGTH) == 0)
4410                                         return l;
4411                         }
4412                 }
4413         }
4414
4415         return NULL;
4416 }
4417
4418 /* GetEquivalentObject dereferences any hard links to get to the
4419  * actual object.
4420  */
4421
4422 struct yaffs_obj *yaffs_get_equivalent_obj(struct yaffs_obj *obj)
4423 {
4424         if (obj && obj->variant_type == YAFFS_OBJECT_TYPE_HARDLINK) {
4425                 /* We want the object id of the equivalent object, not this one */
4426                 obj = obj->variant.hardlink_variant.equiv_obj;
4427                 yaffs_check_obj_details_loaded(obj);
4428         }
4429         return obj;
4430 }
4431
4432 /*
4433  *  A note or two on object names.
4434  *  * If the object name is missing, we then make one up in the form objnnn
4435  *
4436  *  * ASCII names are stored in the object header's name field from byte zero
4437  *  * Unicode names are historically stored starting from byte zero.
4438  *
4439  * Then there are automatic Unicode names...
4440  * The purpose of these is to save names in a way that can be read as
4441  * ASCII or Unicode names as appropriate, thus allowing a Unicode and ASCII
4442  * system to share files.
4443  *
4444  * These automatic unicode are stored slightly differently...
4445  *  - If the name can fit in the ASCII character space then they are saved as 
4446  *    ascii names as per above.
4447  *  - If the name needs Unicode then the name is saved in Unicode
4448  *    starting at oh->name[1].
4449
4450  */
4451 static void yaffs_fix_null_name(struct yaffs_obj *obj, YCHAR * name,
4452                                 int buffer_size)
4453 {
4454         /* Create an object name if we could not find one. */
4455         if (yaffs_strnlen(name, YAFFS_MAX_NAME_LENGTH) == 0) {
4456                 YCHAR local_name[20];
4457                 YCHAR num_string[20];
4458                 YCHAR *x = &num_string[19];
4459                 unsigned v = obj->obj_id;
4460                 num_string[19] = 0;
4461                 while (v > 0) {
4462                         x--;
4463                         *x = '0' + (v % 10);
4464                         v /= 10;
4465                 }
4466                 /* make up a name */
4467                 yaffs_strcpy(local_name, YAFFS_LOSTNFOUND_PREFIX);
4468                 yaffs_strcat(local_name, x);
4469                 yaffs_strncpy(name, local_name, buffer_size - 1);
4470         }
4471 }
4472
4473 static void yaffs_load_name_from_oh(struct yaffs_dev *dev, YCHAR * name,
4474                                     const YCHAR * oh_name, int buff_size)
4475 {
4476 #ifdef CONFIG_YAFFS_AUTO_UNICODE
4477         if (dev->param.auto_unicode) {
4478                 if (*oh_name) {
4479                         /* It is an ASCII name, so do an ASCII to unicode conversion */
4480                         const char *ascii_oh_name = (const char *)oh_name;
4481                         int n = buff_size - 1;
4482                         while (n > 0 && *ascii_oh_name) {
4483                                 *name = *ascii_oh_name;
4484                                 name++;
4485                                 ascii_oh_name++;
4486                                 n--;
4487                         }
4488                 } else {
4489                         yaffs_strncpy(name, oh_name + 1, buff_size - 1);
4490                 }
4491         } else {
4492 #else
4493         {
4494 #endif
4495                 yaffs_strncpy(name, oh_name, buff_size - 1);
4496         }
4497 }
4498
4499 static void yaffs_load_oh_from_name(struct yaffs_dev *dev, YCHAR * oh_name,
4500                                     const YCHAR * name)
4501 {
4502 #ifdef CONFIG_YAFFS_AUTO_UNICODE
4503
4504         int is_ascii;
4505         YCHAR *w;
4506
4507         if (dev->param.auto_unicode) {
4508
4509                 is_ascii = 1;
4510                 w = name;
4511
4512                 /* Figure out if the name will fit in ascii character set */
4513                 while (is_ascii && *w) {
4514                         if ((*w) & 0xff00)
4515                                 is_ascii = 0;
4516                         w++;
4517                 }
4518
4519                 if (is_ascii) {
4520                         /* It is an ASCII name, so do a unicode to ascii conversion */
4521                         char *ascii_oh_name = (char *)oh_name;
4522                         int n = YAFFS_MAX_NAME_LENGTH - 1;
4523                         while (n > 0 && *name) {
4524                                 *ascii_oh_name = *name;
4525                                 name++;
4526                                 ascii_oh_name++;
4527                                 n--;
4528                         }
4529                 } else {
4530                         /* It is a unicode name, so save starting at the second YCHAR */
4531                         *oh_name = 0;
4532                         yaffs_strncpy(oh_name + 1, name,
4533                                       YAFFS_MAX_NAME_LENGTH - 2);
4534                 }
4535         } else {
4536 #else
4537         {
4538 #endif
4539                 yaffs_strncpy(oh_name, name, YAFFS_MAX_NAME_LENGTH - 1);
4540         }
4541
4542 }
4543
4544 int yaffs_get_obj_name(struct yaffs_obj *obj, YCHAR * name, int buffer_size)
4545 {
4546         memset(name, 0, buffer_size * sizeof(YCHAR));
4547
4548         yaffs_check_obj_details_loaded(obj);
4549
4550         if (obj->obj_id == YAFFS_OBJECTID_LOSTNFOUND) {
4551                 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffer_size - 1);
4552         }
4553 #ifndef CONFIG_YAFFS_NO_SHORT_NAMES
4554         else if (obj->short_name[0]) {
4555                 yaffs_strcpy(name, obj->short_name);
4556         }
4557 #endif
4558         else if (obj->hdr_chunk > 0) {
4559                 int result;
4560                 u8 *buffer = yaffs_get_temp_buffer(obj->my_dev, __LINE__);
4561
4562                 struct yaffs_obj_hdr *oh = (struct yaffs_obj_hdr *)buffer;
4563
4564                 memset(buffer, 0, obj->my_dev->data_bytes_per_chunk);
4565
4566                 if (obj->hdr_chunk > 0) {
4567                         result = yaffs_rd_chunk_tags_nand(obj->my_dev,
4568                                                           obj->hdr_chunk,
4569                                                           buffer, NULL);
4570                 }
4571                 yaffs_load_name_from_oh(obj->my_dev, name, oh->name,
4572                                         buffer_size);
4573
4574                 yaffs_release_temp_buffer(obj->my_dev, buffer, __LINE__);
4575         }
4576
4577         yaffs_fix_null_name(obj, name, buffer_size);
4578
4579         return yaffs_strnlen(name, YAFFS_MAX_NAME_LENGTH);
4580 }
4581
4582 int yaffs_get_obj_length(struct yaffs_obj *obj)
4583 {
4584         /* Dereference any hard linking */
4585         obj = yaffs_get_equivalent_obj(obj);
4586
4587         if (obj->variant_type == YAFFS_OBJECT_TYPE_FILE)
4588                 return obj->variant.file_variant.file_size;
4589         if (obj->variant_type == YAFFS_OBJECT_TYPE_SYMLINK) {
4590                 if (!obj->variant.symlink_variant.alias)
4591                         return 0;
4592                 return yaffs_strnlen(obj->variant.symlink_variant.alias,
4593                                      YAFFS_MAX_ALIAS_LENGTH);
4594         } else {
4595                 /* Only a directory should drop through to here */
4596                 return obj->my_dev->data_bytes_per_chunk;
4597         }
4598 }
4599
4600 int yaffs_get_obj_link_count(struct yaffs_obj *obj)
4601 {
4602         int count = 0;
4603         struct list_head *i;
4604
4605         if (!obj->unlinked)
4606                 count++;        /* the object itself */
4607
4608         list_for_each(i, &obj->hard_links)
4609             count++;            /* add the hard links; */
4610
4611         return count;
4612 }
4613
4614 int yaffs_get_obj_inode(struct yaffs_obj *obj)
4615 {
4616         obj = yaffs_get_equivalent_obj(obj);
4617
4618         return obj->obj_id;
4619 }
4620
4621 unsigned yaffs_get_obj_type(struct yaffs_obj *obj)
4622 {
4623         obj = yaffs_get_equivalent_obj(obj);
4624
4625         switch (obj->variant_type) {
4626         case YAFFS_OBJECT_TYPE_FILE:
4627                 return DT_REG;
4628                 break;
4629         case YAFFS_OBJECT_TYPE_DIRECTORY:
4630                 return DT_DIR;
4631                 break;
4632         case YAFFS_OBJECT_TYPE_SYMLINK:
4633                 return DT_LNK;
4634                 break;
4635         case YAFFS_OBJECT_TYPE_HARDLINK:
4636                 return DT_REG;
4637                 break;
4638         case YAFFS_OBJECT_TYPE_SPECIAL:
4639                 if (S_ISFIFO(obj->yst_mode))
4640                         return DT_FIFO;
4641                 if (S_ISCHR(obj->yst_mode))
4642                         return DT_CHR;
4643                 if (S_ISBLK(obj->yst_mode))
4644                         return DT_BLK;
4645                 if (S_ISSOCK(obj->yst_mode))
4646                         return DT_SOCK;
4647         default:
4648                 return DT_REG;
4649                 break;
4650         }
4651 }
4652
4653 YCHAR *yaffs_get_symlink_alias(struct yaffs_obj *obj)
4654 {
4655         obj = yaffs_get_equivalent_obj(obj);
4656         if (obj->variant_type == YAFFS_OBJECT_TYPE_SYMLINK)
4657                 return yaffs_clone_str(obj->variant.symlink_variant.alias);
4658         else
4659                 return yaffs_clone_str(_Y(""));
4660 }
4661
4662 static int yaffs_do_xattrib_mod(struct yaffs_obj *obj, int set,
4663                                 const YCHAR * name, const void *value, int size,
4664                                 int flags)
4665 {
4666         struct yaffs_xattr_mod xmod;
4667
4668         int result;
4669
4670         xmod.set = set;
4671         xmod.name = name;
4672         xmod.data = value;
4673         xmod.size = size;
4674         xmod.flags = flags;
4675         xmod.result = -ENOSPC;
4676
4677         result = yaffs_update_oh(obj, NULL, 0, 0, 0, &xmod);
4678
4679         if (result > 0)
4680                 return xmod.result;
4681         else
4682                 return -ENOSPC;
4683 }
4684
4685 static int yaffs_apply_xattrib_mod(struct yaffs_obj *obj, char *buffer,
4686                                    struct yaffs_xattr_mod *xmod)
4687 {
4688         int retval = 0;
4689         int x_offs = sizeof(struct yaffs_obj_hdr);
4690         struct yaffs_dev *dev = obj->my_dev;
4691         int x_size = dev->data_bytes_per_chunk - sizeof(struct yaffs_obj_hdr);
4692
4693         char *x_buffer = buffer + x_offs;
4694
4695         if (xmod->set)
4696                 retval =
4697                     nval_set(x_buffer, x_size, xmod->name, xmod->data,
4698                              xmod->size, xmod->flags);
4699         else
4700                 retval = nval_del(x_buffer, x_size, xmod->name);
4701
4702         obj->has_xattr = nval_hasvalues(x_buffer, x_size);
4703         obj->xattr_known = 1;
4704
4705         xmod->result = retval;
4706
4707         return retval;
4708 }
4709
4710 static int yaffs_do_xattrib_fetch(struct yaffs_obj *obj, const YCHAR * name,
4711                                   void *value, int size)
4712 {
4713         char *buffer = NULL;
4714         int result;
4715         struct yaffs_ext_tags tags;
4716         struct yaffs_dev *dev = obj->my_dev;
4717         int x_offs = sizeof(struct yaffs_obj_hdr);
4718         int x_size = dev->data_bytes_per_chunk - sizeof(struct yaffs_obj_hdr);
4719
4720         char *x_buffer;
4721
4722         int retval = 0;
4723
4724         if (obj->hdr_chunk < 1)
4725                 return -ENODATA;
4726
4727         /* If we know that the object has no xattribs then don't do all the
4728          * reading and parsing.
4729          */
4730         if (obj->xattr_known && !obj->has_xattr) {
4731                 if (name)
4732                         return -ENODATA;
4733                 else
4734                         return 0;
4735         }
4736
4737         buffer = (char *)yaffs_get_temp_buffer(dev, __LINE__);
4738         if (!buffer)
4739                 return -ENOMEM;
4740
4741         result =
4742             yaffs_rd_chunk_tags_nand(dev, obj->hdr_chunk, (u8 *) buffer, &tags);
4743
4744         if (result != YAFFS_OK)
4745                 retval = -ENOENT;
4746         else {
4747                 x_buffer = buffer + x_offs;
4748
4749                 if (!obj->xattr_known) {
4750                         obj->has_xattr = nval_hasvalues(x_buffer, x_size);
4751                         obj->xattr_known = 1;
4752                 }
4753
4754                 if (name)
4755                         retval = nval_get(x_buffer, x_size, name, value, size);
4756                 else
4757                         retval = nval_list(x_buffer, x_size, value, size);
4758         }
4759         yaffs_release_temp_buffer(dev, (u8 *) buffer, __LINE__);
4760         return retval;
4761 }
4762
4763 int yaffs_set_xattrib(struct yaffs_obj *obj, const YCHAR * name,
4764                       const void *value, int size, int flags)
4765 {
4766         return yaffs_do_xattrib_mod(obj, 1, name, value, size, flags);
4767 }
4768
4769 int yaffs_remove_xattrib(struct yaffs_obj *obj, const YCHAR * name)
4770 {
4771         return yaffs_do_xattrib_mod(obj, 0, name, NULL, 0, 0);
4772 }
4773
4774 int yaffs_get_xattrib(struct yaffs_obj *obj, const YCHAR * name, void *value,
4775                       int size)
4776 {
4777         return yaffs_do_xattrib_fetch(obj, name, value, size);
4778 }
4779
4780 int yaffs_list_xattrib(struct yaffs_obj *obj, char *buffer, int size)
4781 {
4782         return yaffs_do_xattrib_fetch(obj, NULL, buffer, size);
4783 }
4784
4785 /*---------------------------- Initialisation code -------------------------------------- */
4786
4787 static int yaffs_check_dev_fns(const struct yaffs_dev *dev)
4788 {
4789
4790         /* Common functions, gotta have */
4791         if (!dev->param.erase_fn || !dev->param.initialise_flash_fn)
4792                 return 0;
4793
4794 #ifdef CONFIG_YAFFS_YAFFS2
4795
4796         /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
4797         if (dev->param.write_chunk_tags_fn &&
4798             dev->param.read_chunk_tags_fn &&
4799             !dev->param.write_chunk_fn &&
4800             !dev->param.read_chunk_fn &&
4801             dev->param.bad_block_fn && dev->param.query_block_fn)
4802                 return 1;
4803 #endif
4804
4805         /* Can use the "spare" style interface for yaffs1 */
4806         if (!dev->param.is_yaffs2 &&
4807             !dev->param.write_chunk_tags_fn &&
4808             !dev->param.read_chunk_tags_fn &&
4809             dev->param.write_chunk_fn &&
4810             dev->param.read_chunk_fn &&
4811             !dev->param.bad_block_fn && !dev->param.query_block_fn)
4812                 return 1;
4813
4814         return 0;               /* bad */
4815 }
4816
4817 static int yaffs_create_initial_dir(struct yaffs_dev *dev)
4818 {
4819         /* Initialise the unlinked, deleted, root and lost and found directories */
4820
4821         dev->lost_n_found = dev->root_dir = NULL;
4822         dev->unlinked_dir = dev->del_dir = NULL;
4823
4824         dev->unlinked_dir =
4825             yaffs_create_fake_dir(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
4826
4827         dev->del_dir =
4828             yaffs_create_fake_dir(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
4829
4830         dev->root_dir =
4831             yaffs_create_fake_dir(dev, YAFFS_OBJECTID_ROOT,
4832                                   YAFFS_ROOT_MODE | S_IFDIR);
4833         dev->lost_n_found =
4834             yaffs_create_fake_dir(dev, YAFFS_OBJECTID_LOSTNFOUND,
4835                                   YAFFS_LOSTNFOUND_MODE | S_IFDIR);
4836
4837         if (dev->lost_n_found && dev->root_dir && dev->unlinked_dir
4838             && dev->del_dir) {
4839                 yaffs_add_obj_to_dir(dev->root_dir, dev->lost_n_found);
4840                 return YAFFS_OK;
4841         }
4842
4843         return YAFFS_FAIL;
4844 }
4845
4846 int yaffs_guts_initialise(struct yaffs_dev *dev)
4847 {
4848         int init_failed = 0;
4849         unsigned x;
4850         int bits;
4851
4852         T(YAFFS_TRACE_TRACING,
4853           (TSTR("yaffs: yaffs_guts_initialise()" TENDSTR)));
4854
4855         /* Check stuff that must be set */
4856
4857         if (!dev) {
4858                 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
4859                 return YAFFS_FAIL;
4860         }
4861
4862         dev->internal_start_block = dev->param.start_block;
4863         dev->internal_end_block = dev->param.end_block;
4864         dev->block_offset = 0;
4865         dev->chunk_offset = 0;
4866         dev->n_free_chunks = 0;
4867
4868         dev->gc_block = 0;
4869
4870         if (dev->param.start_block == 0) {
4871                 dev->internal_start_block = dev->param.start_block + 1;
4872                 dev->internal_end_block = dev->param.end_block + 1;
4873                 dev->block_offset = 1;
4874                 dev->chunk_offset = dev->param.chunks_per_block;
4875         }
4876
4877         /* Check geometry parameters. */
4878
4879         if ((!dev->param.inband_tags && dev->param.is_yaffs2 && dev->param.total_bytes_per_chunk < 1024) || (!dev->param.is_yaffs2 && dev->param.total_bytes_per_chunk < 512) || (dev->param.inband_tags && !dev->param.is_yaffs2) || dev->param.chunks_per_block < 2 || dev->param.n_reserved_blocks < 2 || dev->internal_start_block <= 0 || dev->internal_end_block <= 0 || dev->internal_end_block <= (dev->internal_start_block + dev->param.n_reserved_blocks + 2)) {     /* otherwise it is too small */
4880                 T(YAFFS_TRACE_ALWAYS,
4881                   (TSTR
4882                    ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inband_tags %d "
4883                     TENDSTR), dev->param.total_bytes_per_chunk,
4884                    dev->param.is_yaffs2 ? "2" : "", dev->param.inband_tags));
4885                 return YAFFS_FAIL;
4886         }
4887
4888         if (yaffs_init_nand(dev) != YAFFS_OK) {
4889                 T(YAFFS_TRACE_ALWAYS,
4890                   (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
4891                 return YAFFS_FAIL;
4892         }
4893
4894         /* Sort out space for inband tags, if required */
4895         if (dev->param.inband_tags)
4896                 dev->data_bytes_per_chunk =
4897                     dev->param.total_bytes_per_chunk -
4898                     sizeof(struct yaffs_packed_tags2_tags_only);
4899         else
4900                 dev->data_bytes_per_chunk = dev->param.total_bytes_per_chunk;
4901
4902         /* Got the right mix of functions? */
4903         if (!yaffs_check_dev_fns(dev)) {
4904                 /* Function missing */
4905                 T(YAFFS_TRACE_ALWAYS,
4906                   (TSTR
4907                    ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
4908
4909                 return YAFFS_FAIL;
4910         }
4911
4912         if (dev->is_mounted) {
4913                 T(YAFFS_TRACE_ALWAYS,
4914                   (TSTR("yaffs: device already mounted\n" TENDSTR)));
4915                 return YAFFS_FAIL;
4916         }
4917
4918         /* Finished with most checks. One or two more checks happen later on too. */
4919
4920         dev->is_mounted = 1;
4921
4922         /* OK now calculate a few things for the device */
4923
4924         /*
4925          *  Calculate all the chunk size manipulation numbers:
4926          */
4927         x = dev->data_bytes_per_chunk;
4928         /* We always use dev->chunk_shift and dev->chunk_div */
4929         dev->chunk_shift = calc_shifts(x);
4930         x >>= dev->chunk_shift;
4931         dev->chunk_div = x;
4932         /* We only use chunk mask if chunk_div is 1 */
4933         dev->chunk_mask = (1 << dev->chunk_shift) - 1;
4934
4935         /*
4936          * Calculate chunk_grp_bits.
4937          * We need to find the next power of 2 > than internal_end_block
4938          */
4939
4940         x = dev->param.chunks_per_block * (dev->internal_end_block + 1);
4941
4942         bits = calc_shifts_ceiling(x);
4943
4944         /* Set up tnode width if wide tnodes are enabled. */
4945         if (!dev->param.wide_tnodes_disabled) {
4946                 /* bits must be even so that we end up with 32-bit words */
4947                 if (bits & 1)
4948                         bits++;
4949                 if (bits < 16)
4950                         dev->tnode_width = 16;
4951                 else
4952                         dev->tnode_width = bits;
4953         } else {
4954                 dev->tnode_width = 16;
4955         }
4956
4957         dev->tnode_mask = (1 << dev->tnode_width) - 1;
4958
4959         /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
4960          * so if the bitwidth of the
4961          * chunk range we're using is greater than 16 we need
4962          * to figure out chunk shift and chunk_grp_size
4963          */
4964
4965         if (bits <= dev->tnode_width)
4966                 dev->chunk_grp_bits = 0;
4967         else
4968                 dev->chunk_grp_bits = bits - dev->tnode_width;
4969
4970         dev->tnode_size = (dev->tnode_width * YAFFS_NTNODES_LEVEL0) / 8;
4971         if (dev->tnode_size < sizeof(struct yaffs_tnode))
4972                 dev->tnode_size = sizeof(struct yaffs_tnode);
4973
4974         dev->chunk_grp_size = 1 << dev->chunk_grp_bits;
4975
4976         if (dev->param.chunks_per_block < dev->chunk_grp_size) {
4977                 /* We have a problem because the soft delete won't work if
4978                  * the chunk group size > chunks per block.
4979                  * This can be remedied by using larger "virtual blocks".
4980                  */
4981                 T(YAFFS_TRACE_ALWAYS,
4982                   (TSTR("yaffs: chunk group too large\n" TENDSTR)));
4983
4984                 return YAFFS_FAIL;
4985         }
4986
4987         /* OK, we've finished verifying the device, lets continue with initialisation */
4988
4989         /* More device initialisation */
4990         dev->all_gcs = 0;
4991         dev->passive_gc_count = 0;
4992         dev->oldest_dirty_gc_count = 0;
4993         dev->bg_gcs = 0;
4994         dev->gc_block_finder = 0;
4995         dev->buffered_block = -1;
4996         dev->doing_buffered_block_rewrite = 0;
4997         dev->n_deleted_files = 0;
4998         dev->n_bg_deletions = 0;
4999         dev->n_unlinked_files = 0;
5000         dev->n_ecc_fixed = 0;
5001         dev->n_ecc_unfixed = 0;
5002         dev->n_tags_ecc_fixed = 0;
5003         dev->n_tags_ecc_unfixed = 0;
5004         dev->n_erase_failures = 0;
5005         dev->n_erased_blocks = 0;
5006         dev->gc_disable = 0;
5007         dev->has_pending_prioritised_gc = 1;    /* Assume the worst for now, will get fixed on first GC */
5008         INIT_LIST_HEAD(&dev->dirty_dirs);
5009         dev->oldest_dirty_seq = 0;
5010         dev->oldest_dirty_block = 0;
5011
5012         /* Initialise temporary buffers and caches. */
5013         if (!yaffs_init_tmp_buffers(dev))
5014                 init_failed = 1;
5015
5016         dev->cache = NULL;
5017         dev->gc_cleanup_list = NULL;
5018
5019         if (!init_failed && dev->param.n_caches > 0) {
5020                 int i;
5021                 void *buf;
5022                 int cache_bytes =
5023                     dev->param.n_caches * sizeof(struct yaffs_cache);
5024
5025                 if (dev->param.n_caches > YAFFS_MAX_SHORT_OP_CACHES)
5026                         dev->param.n_caches = YAFFS_MAX_SHORT_OP_CACHES;
5027
5028                 dev->cache = YMALLOC(cache_bytes);
5029
5030                 buf = (u8 *) dev->cache;
5031
5032                 if (dev->cache)
5033                         memset(dev->cache, 0, cache_bytes);
5034
5035                 for (i = 0; i < dev->param.n_caches && buf; i++) {
5036                         dev->cache[i].object = NULL;
5037                         dev->cache[i].last_use = 0;
5038                         dev->cache[i].dirty = 0;
5039                         dev->cache[i].data = buf =
5040                             YMALLOC_DMA(dev->param.total_bytes_per_chunk);
5041                 }
5042                 if (!buf)
5043                         init_failed = 1;
5044
5045                 dev->cache_last_use = 0;
5046         }
5047
5048         dev->cache_hits = 0;
5049
5050         if (!init_failed) {
5051                 dev->gc_cleanup_list =
5052                     YMALLOC(dev->param.chunks_per_block * sizeof(u32));
5053                 if (!dev->gc_cleanup_list)
5054                         init_failed = 1;
5055         }
5056
5057         if (dev->param.is_yaffs2)
5058                 dev->param.use_header_file_size = 1;
5059
5060         if (!init_failed && !yaffs_init_blocks(dev))
5061                 init_failed = 1;
5062
5063         yaffs_init_tnodes_and_objs(dev);
5064
5065         if (!init_failed && !yaffs_create_initial_dir(dev))
5066                 init_failed = 1;
5067
5068         if (!init_failed) {
5069                 /* Now scan the flash. */
5070                 if (dev->param.is_yaffs2) {
5071                         if (yaffs2_checkpt_restore(dev)) {
5072                                 yaffs_check_obj_details_loaded(dev->root_dir);
5073                                 T(YAFFS_TRACE_CHECKPOINT | YAFFS_TRACE_MOUNT,
5074                                   (TSTR
5075                                    ("yaffs: restored from checkpoint"
5076                                     TENDSTR)));
5077                         } else {
5078
5079                                 /* Clean up the mess caused by an aborted checkpoint load
5080                                  * and scan backwards.
5081                                  */
5082                                 yaffs_deinit_blocks(dev);
5083
5084                                 yaffs_deinit_tnodes_and_objs(dev);
5085
5086                                 dev->n_erased_blocks = 0;
5087                                 dev->n_free_chunks = 0;
5088                                 dev->alloc_block = -1;
5089                                 dev->alloc_page = -1;
5090                                 dev->n_deleted_files = 0;
5091                                 dev->n_unlinked_files = 0;
5092                                 dev->n_bg_deletions = 0;
5093
5094                                 if (!init_failed && !yaffs_init_blocks(dev))
5095                                         init_failed = 1;
5096
5097                                 yaffs_init_tnodes_and_objs(dev);
5098
5099                                 if (!init_failed
5100                                     && !yaffs_create_initial_dir(dev))
5101                                         init_failed = 1;
5102
5103                                 if (!init_failed && !yaffs2_scan_backwards(dev))
5104                                         init_failed = 1;
5105                         }
5106                 } else if (!yaffs1_scan(dev)) {
5107                         init_failed = 1;
5108                 }
5109
5110                 yaffs_strip_deleted_objs(dev);
5111                 yaffs_fix_hanging_objs(dev);
5112                 if (dev->param.empty_lost_n_found)
5113                         yaffs_empty_l_n_f(dev);
5114         }
5115
5116         if (init_failed) {
5117                 /* Clean up the mess */
5118                 T(YAFFS_TRACE_TRACING,
5119                   (TSTR("yaffs: yaffs_guts_initialise() aborted.\n" TENDSTR)));
5120
5121                 yaffs_deinitialise(dev);
5122                 return YAFFS_FAIL;
5123         }
5124
5125         /* Zero out stats */
5126         dev->n_page_reads = 0;
5127         dev->n_page_writes = 0;
5128         dev->n_erasures = 0;
5129         dev->n_gc_copies = 0;
5130         dev->n_retired_writes = 0;
5131
5132         dev->n_retired_blocks = 0;
5133
5134         yaffs_verify_free_chunks(dev);
5135         yaffs_verify_blocks(dev);
5136
5137         /* Clean up any aborted checkpoint data */
5138         if (!dev->is_checkpointed && dev->blocks_in_checkpt > 0)
5139                 yaffs2_checkpt_invalidate(dev);
5140
5141         T(YAFFS_TRACE_TRACING,
5142           (TSTR("yaffs: yaffs_guts_initialise() done.\n" TENDSTR)));
5143         return YAFFS_OK;
5144
5145 }
5146
5147 void yaffs_deinitialise(struct yaffs_dev *dev)
5148 {
5149         if (dev->is_mounted) {
5150                 int i;
5151
5152                 yaffs_deinit_blocks(dev);
5153                 yaffs_deinit_tnodes_and_objs(dev);
5154                 if (dev->param.n_caches > 0 && dev->cache) {
5155
5156                         for (i = 0; i < dev->param.n_caches; i++) {
5157                                 if (dev->cache[i].data)
5158                                         YFREE(dev->cache[i].data);
5159                                 dev->cache[i].data = NULL;
5160                         }
5161
5162                         YFREE(dev->cache);
5163                         dev->cache = NULL;
5164                 }
5165
5166                 YFREE(dev->gc_cleanup_list);
5167
5168                 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
5169                         YFREE(dev->temp_buffer[i].buffer);
5170
5171                 dev->is_mounted = 0;
5172
5173                 if (dev->param.deinitialise_flash_fn)
5174                         dev->param.deinitialise_flash_fn(dev);
5175         }
5176 }
5177
5178 int yaffs_count_free_chunks(struct yaffs_dev *dev)
5179 {
5180         int n_free = 0;
5181         int b;
5182
5183         struct yaffs_block_info *blk;
5184
5185         blk = dev->block_info;
5186         for (b = dev->internal_start_block; b <= dev->internal_end_block; b++) {
5187                 switch (blk->block_state) {
5188                 case YAFFS_BLOCK_STATE_EMPTY:
5189                 case YAFFS_BLOCK_STATE_ALLOCATING:
5190                 case YAFFS_BLOCK_STATE_COLLECTING:
5191                 case YAFFS_BLOCK_STATE_FULL:
5192                         n_free +=
5193                             (dev->param.chunks_per_block - blk->pages_in_use +
5194                              blk->soft_del_pages);
5195                         break;
5196                 default:
5197                         break;
5198                 }
5199                 blk++;
5200         }
5201
5202         return n_free;
5203 }
5204
5205 int yaffs_get_n_free_chunks(struct yaffs_dev *dev)
5206 {
5207         /* This is what we report to the outside world */
5208
5209         int n_free;
5210         int n_dirty_caches;
5211         int blocks_for_checkpt;
5212         int i;
5213
5214         n_free = dev->n_free_chunks;
5215         n_free += dev->n_deleted_files;
5216
5217         /* Now count the number of dirty chunks in the cache and subtract those */
5218
5219         for (n_dirty_caches = 0, i = 0; i < dev->param.n_caches; i++) {
5220                 if (dev->cache[i].dirty)
5221                         n_dirty_caches++;
5222         }
5223
5224         n_free -= n_dirty_caches;
5225
5226         n_free -=
5227             ((dev->param.n_reserved_blocks + 1) * dev->param.chunks_per_block);
5228
5229         /* Now we figure out how much to reserve for the checkpoint and report that... */
5230         blocks_for_checkpt = yaffs_calc_checkpt_blocks_required(dev);
5231
5232         n_free -= (blocks_for_checkpt * dev->param.chunks_per_block);
5233
5234         if (n_free < 0)
5235                 n_free = 0;
5236
5237         return n_free;
5238
5239 }