yaffs Clean up conditional bracing
[yaffs2.git] / yaffs_guts.c
1 /*
2  * YAFFS: Yet Another Flash File System. A NAND-flash specific file system.
3  *
4  * Copyright (C) 2002-2010 Aleph One Ltd.
5  *   for Toby Churchill Ltd and Brightstar Engineering
6  *
7  * Created by Charles Manning <charles@aleph1.co.uk>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License version 2 as
11  * published by the Free Software Foundation.
12  */
13
14 #include "yportenv.h"
15 #include "yaffs_trace.h"
16
17 #include "yaffs_guts.h"
18 #include "yaffs_tagsvalidity.h"
19 #include "yaffs_getblockinfo.h"
20
21 #include "yaffs_tagscompat.h"
22
23 #include "yaffs_nand.h"
24
25 #include "yaffs_yaffs1.h"
26 #include "yaffs_yaffs2.h"
27 #include "yaffs_bitmap.h"
28 #include "yaffs_verify.h"
29
30 #include "yaffs_nand.h"
31 #include "yaffs_packedtags2.h"
32
33 #include "yaffs_nameval.h"
34 #include "yaffs_allocator.h"
35
36 #include "yaffs_attribs.h"
37
38 /* Note YAFFS_GC_GOOD_ENOUGH must be <= YAFFS_GC_PASSIVE_THRESHOLD */
39 #define YAFFS_GC_GOOD_ENOUGH 2
40 #define YAFFS_GC_PASSIVE_THRESHOLD 4
41
42 #include "yaffs_ecc.h"
43
44 /* Robustification (if it ever comes about...) */
45 static void yaffs_retire_block(struct yaffs_dev *dev, int flash_block);
46 static void yaffs_handle_chunk_wr_error(struct yaffs_dev *dev, int nand_chunk,
47                                         int erased_ok);
48 static void yaffs_handle_chunk_wr_ok(struct yaffs_dev *dev, int nand_chunk,
49                                      const u8 * data,
50                                      const struct yaffs_ext_tags *tags);
51 static void yaffs_handle_chunk_update(struct yaffs_dev *dev, int nand_chunk,
52                                       const struct yaffs_ext_tags *tags);
53
54 /* Other local prototypes */
55 static void yaffs_update_parent(struct yaffs_obj *obj);
56 static int yaffs_unlink_obj(struct yaffs_obj *obj);
57 static int yaffs_obj_cache_dirty(struct yaffs_obj *obj);
58
59 static int yaffs_write_new_chunk(struct yaffs_dev *dev,
60                                  const u8 * buffer,
61                                  struct yaffs_ext_tags *tags, int use_reserver);
62
63 static struct yaffs_obj *yaffs_new_obj(struct yaffs_dev *dev, int number,
64                                        enum yaffs_obj_type type);
65
66 static int yaffs_apply_xattrib_mod(struct yaffs_obj *obj, char *buffer,
67                                    struct yaffs_xattr_mod *xmod);
68
69 static void yaffs_remove_obj_from_dir(struct yaffs_obj *obj);
70 static int yaffs_generic_obj_del(struct yaffs_obj *in);
71
72 static int yaffs_check_chunk_erased(struct yaffs_dev *dev, int nand_chunk);
73
74 static int yaffs_unlink_worker(struct yaffs_obj *obj);
75
76 static int yaffs_tags_match(const struct yaffs_ext_tags *tags, int obj_id,
77                             int chunk_obj);
78
79 static int yaffs_alloc_chunk(struct yaffs_dev *dev, int use_reserver,
80                              struct yaffs_block_info **block_ptr);
81
82 static void yaffs_check_obj_details_loaded(struct yaffs_obj *in);
83
84 static void yaffs_invalidate_whole_cache(struct yaffs_obj *in);
85 static void yaffs_invalidate_chunk_cache(struct yaffs_obj *object,
86                                          int chunk_id);
87
88 static int yaffs_find_chunk_in_file(struct yaffs_obj *in, int inode_chunk,
89                                     struct yaffs_ext_tags *tags);
90
91 static int yaffs_verify_chunk_written(struct yaffs_dev *dev,
92                                       int nand_chunk,
93                                       const u8 * data,
94                                       struct yaffs_ext_tags *tags);
95
96 static void yaffs_load_name_from_oh(struct yaffs_dev *dev, YCHAR * name,
97                                     const YCHAR * oh_name, int buff_size);
98 static void yaffs_load_oh_from_name(struct yaffs_dev *dev, YCHAR * oh_name,
99                                     const YCHAR * name);
100
101 /* Function to calculate chunk and offset */
102
103 static void yaffs_addr_to_chunk(struct yaffs_dev *dev, loff_t addr,
104                                 int *chunk_out, u32 * offset_out)
105 {
106         int chunk;
107         u32 offset;
108
109         chunk = (u32) (addr >> dev->chunk_shift);
110
111         if (dev->chunk_div == 1) {
112                 /* easy power of 2 case */
113                 offset = (u32) (addr & dev->chunk_mask);
114         } else {
115                 /* Non power-of-2 case */
116
117                 loff_t chunk_base;
118
119                 chunk /= dev->chunk_div;
120
121                 chunk_base = ((loff_t) chunk) * dev->data_bytes_per_chunk;
122                 offset = (u32) (addr - chunk_base);
123         }
124
125         *chunk_out = chunk;
126         *offset_out = offset;
127 }
128
129 /* Function to return the number of shifts for a power of 2 greater than or
130  * equal to the given number
131  * Note we don't try to cater for all possible numbers and this does not have to
132  * be hellishly efficient.
133  */
134
135 static u32 calc_shifts_ceiling(u32 x)
136 {
137         int extra_bits;
138         int shifts;
139
140         shifts = extra_bits = 0;
141
142         while (x > 1) {
143                 if (x & 1)
144                         extra_bits++;
145                 x >>= 1;
146                 shifts++;
147         }
148
149         if (extra_bits)
150                 shifts++;
151
152         return shifts;
153 }
154
155 /* Function to return the number of shifts to get a 1 in bit 0
156  */
157
158 static u32 calc_shifts(u32 x)
159 {
160         u32 shifts;
161
162         shifts = 0;
163
164         if (!x)
165                 return 0;
166
167         while (!(x & 1)) {
168                 x >>= 1;
169                 shifts++;
170         }
171
172         return shifts;
173 }
174
175 /*
176  * Temporary buffer manipulations.
177  */
178
179 static int yaffs_init_tmp_buffers(struct yaffs_dev *dev)
180 {
181         int i;
182         u8 *buf = (u8 *) 1;
183
184         memset(dev->temp_buffer, 0, sizeof(dev->temp_buffer));
185
186         for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
187                 dev->temp_buffer[i].line = 0;   /* not in use */
188                 dev->temp_buffer[i].buffer = buf =
189                     YMALLOC_DMA(dev->param.total_bytes_per_chunk);
190         }
191
192         return buf ? YAFFS_OK : YAFFS_FAIL;
193 }
194
195 u8 *yaffs_get_temp_buffer(struct yaffs_dev * dev, int line_no)
196 {
197         int i, j;
198
199         dev->temp_in_use++;
200         if (dev->temp_in_use > dev->max_temp)
201                 dev->max_temp = dev->temp_in_use;
202
203         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
204                 if (dev->temp_buffer[i].line == 0) {
205                         dev->temp_buffer[i].line = line_no;
206                         if ((i + 1) > dev->max_temp) {
207                                 dev->max_temp = i + 1;
208                                 for (j = 0; j <= i; j++)
209                                         dev->temp_buffer[j].max_line =
210                                             dev->temp_buffer[j].line;
211                         }
212
213                         return dev->temp_buffer[i].buffer;
214                 }
215         }
216
217         T(YAFFS_TRACE_BUFFERS,
218           (TSTR("Out of temp buffers at line %d, other held by lines:"),
219            line_no));
220         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
221                 T(YAFFS_TRACE_BUFFERS,
222                   (TSTR(" %d "), dev->temp_buffer[i].line));
223
224         T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
225
226         /*
227          * If we got here then we have to allocate an unmanaged one
228          * This is not good.
229          */
230
231         dev->unmanaged_buffer_allocs++;
232         return YMALLOC(dev->data_bytes_per_chunk);
233
234 }
235
236 void yaffs_release_temp_buffer(struct yaffs_dev *dev, u8 * buffer, int line_no)
237 {
238         int i;
239
240         dev->temp_in_use--;
241
242         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
243                 if (dev->temp_buffer[i].buffer == buffer) {
244                         dev->temp_buffer[i].line = 0;
245                         return;
246                 }
247         }
248
249         if (buffer) {
250                 /* assume it is an unmanaged one. */
251                 T(YAFFS_TRACE_BUFFERS,
252                   (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
253                    line_no));
254                 YFREE(buffer);
255                 dev->unmanaged_buffer_deallocs++;
256         }
257
258 }
259
260 /*
261  * Determine if we have a managed buffer.
262  */
263 int yaffs_is_managed_tmp_buffer(struct yaffs_dev *dev, const u8 * buffer)
264 {
265         int i;
266
267         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
268                 if (dev->temp_buffer[i].buffer == buffer)
269                         return 1;
270         }
271
272         for (i = 0; i < dev->param.n_caches; i++) {
273                 if (dev->cache[i].data == buffer)
274                         return 1;
275         }
276
277         if (buffer == dev->checkpt_buffer)
278                 return 1;
279
280         T(YAFFS_TRACE_ALWAYS,
281           (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
282         return 0;
283 }
284
285 /*
286  * Verification code
287  */
288
289 /*
290  *  Simple hash function. Needs to have a reasonable spread
291  */
292
293 static Y_INLINE int yaffs_hash_fn(int n)
294 {
295         n = abs(n);
296         return n % YAFFS_NOBJECT_BUCKETS;
297 }
298
299 /*
300  * Access functions to useful fake objects.
301  * Note that root might have a presence in NAND if permissions are set.
302  */
303
304 struct yaffs_obj *yaffs_root(struct yaffs_dev *dev)
305 {
306         return dev->root_dir;
307 }
308
309 struct yaffs_obj *yaffs_lost_n_found(struct yaffs_dev *dev)
310 {
311         return dev->lost_n_found;
312 }
313
314 /*
315  *  Erased NAND checking functions
316  */
317
318 int yaffs_check_ff(u8 * buffer, int n_bytes)
319 {
320         /* Horrible, slow implementation */
321         while (n_bytes--) {
322                 if (*buffer != 0xFF)
323                         return 0;
324                 buffer++;
325         }
326         return 1;
327 }
328
329 static int yaffs_check_chunk_erased(struct yaffs_dev *dev, int nand_chunk)
330 {
331         int retval = YAFFS_OK;
332         u8 *data = yaffs_get_temp_buffer(dev, __LINE__);
333         struct yaffs_ext_tags tags;
334         int result;
335
336         result = yaffs_rd_chunk_tags_nand(dev, nand_chunk, data, &tags);
337
338         if (tags.ecc_result > YAFFS_ECC_RESULT_NO_ERROR)
339                 retval = YAFFS_FAIL;
340
341         if (!yaffs_check_ff(data, dev->data_bytes_per_chunk) || tags.chunk_used) {
342                 T(YAFFS_TRACE_NANDACCESS,
343                   (TSTR("Chunk %d not erased" TENDSTR), nand_chunk));
344                 retval = YAFFS_FAIL;
345         }
346
347         yaffs_release_temp_buffer(dev, data, __LINE__);
348
349         return retval;
350
351 }
352
353 static int yaffs_verify_chunk_written(struct yaffs_dev *dev,
354                                       int nand_chunk,
355                                       const u8 * data,
356                                       struct yaffs_ext_tags *tags)
357 {
358         int retval = YAFFS_OK;
359         struct yaffs_ext_tags temp_tags;
360         u8 *buffer = yaffs_get_temp_buffer(dev, __LINE__);
361         int result;
362
363         result = yaffs_rd_chunk_tags_nand(dev, nand_chunk, buffer, &temp_tags);
364         if (memcmp(buffer, data, dev->data_bytes_per_chunk) ||
365             temp_tags.obj_id != tags->obj_id ||
366             temp_tags.chunk_id != tags->chunk_id ||
367             temp_tags.n_bytes != tags->n_bytes)
368                 retval = YAFFS_FAIL;
369
370         yaffs_release_temp_buffer(dev, buffer, __LINE__);
371
372         return retval;
373 }
374
375 static int yaffs_write_new_chunk(struct yaffs_dev *dev,
376                                  const u8 * data,
377                                  struct yaffs_ext_tags *tags, int use_reserver)
378 {
379         int attempts = 0;
380         int write_ok = 0;
381         int chunk;
382
383         yaffs2_checkpt_invalidate(dev);
384
385         do {
386                 struct yaffs_block_info *bi = 0;
387                 int erased_ok = 0;
388
389                 chunk = yaffs_alloc_chunk(dev, use_reserver, &bi);
390                 if (chunk < 0) {
391                         /* no space */
392                         break;
393                 }
394
395                 /* First check this chunk is erased, if it needs
396                  * checking.  The checking policy (unless forced
397                  * always on) is as follows:
398                  *
399                  * Check the first page we try to write in a block.
400                  * If the check passes then we don't need to check any
401                  * more.        If the check fails, we check again...
402                  * If the block has been erased, we don't need to check.
403                  *
404                  * However, if the block has been prioritised for gc,
405                  * then we think there might be something odd about
406                  * this block and stop using it.
407                  *
408                  * Rationale: We should only ever see chunks that have
409                  * not been erased if there was a partially written
410                  * chunk due to power loss.  This checking policy should
411                  * catch that case with very few checks and thus save a
412                  * lot of checks that are most likely not needed.
413                  *
414                  * Mods to the above
415                  * If an erase check fails or the write fails we skip the 
416                  * rest of the block.
417                  */
418
419                 /* let's give it a try */
420                 attempts++;
421
422                 if (dev->param.always_check_erased)
423                         bi->skip_erased_check = 0;
424
425                 if (!bi->skip_erased_check) {
426                         erased_ok = yaffs_check_chunk_erased(dev, chunk);
427                         if (erased_ok != YAFFS_OK) {
428                                 T(YAFFS_TRACE_ERROR,
429                                   (TSTR("**>> yaffs chunk %d was not erased"
430                                         TENDSTR), chunk));
431
432                                 /* If not erased, delete this one,
433                                  * skip rest of block and
434                                  * try another chunk */
435                                 yaffs_chunk_del(dev, chunk, 1, __LINE__);
436                                 yaffs_skip_rest_of_block(dev);
437                                 continue;
438                         }
439                 }
440
441                 write_ok = yaffs_wr_chunk_tags_nand(dev, chunk, data, tags);
442
443                 if (!bi->skip_erased_check)
444                         write_ok =
445                             yaffs_verify_chunk_written(dev, chunk, data, tags);
446
447                 if (write_ok != YAFFS_OK) {
448                         /* Clean up aborted write, skip to next block and
449                          * try another chunk */
450                         yaffs_handle_chunk_wr_error(dev, chunk, erased_ok);
451                         continue;
452                 }
453
454                 bi->skip_erased_check = 1;
455
456                 /* Copy the data into the robustification buffer */
457                 yaffs_handle_chunk_wr_ok(dev, chunk, data, tags);
458
459         } while (write_ok != YAFFS_OK &&
460                  (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
461
462         if (!write_ok)
463                 chunk = -1;
464
465         if (attempts > 1) {
466                 T(YAFFS_TRACE_ERROR,
467                   (TSTR("**>> yaffs write required %d attempts" TENDSTR),
468                    attempts));
469
470                 dev->n_retired_writes += (attempts - 1);
471         }
472
473         return chunk;
474 }
475
476 /*
477  * Block retiring for handling a broken block.
478  */
479
480 static void yaffs_retire_block(struct yaffs_dev *dev, int flash_block)
481 {
482         struct yaffs_block_info *bi = yaffs_get_block_info(dev, flash_block);
483
484         yaffs2_checkpt_invalidate(dev);
485
486         yaffs2_clear_oldest_dirty_seq(dev, bi);
487
488         if (yaffs_mark_bad(dev, flash_block) != YAFFS_OK) {
489                 if (yaffs_erase_block(dev, flash_block) != YAFFS_OK) {
490                         T(YAFFS_TRACE_ALWAYS,
491                           (TSTR
492                            ("yaffs: Failed to mark bad and erase block %d"
493                             TENDSTR), flash_block));
494                 } else {
495                         struct yaffs_ext_tags tags;
496                         int chunk_id =
497                             flash_block * dev->param.chunks_per_block;
498
499                         u8 *buffer = yaffs_get_temp_buffer(dev, __LINE__);
500
501                         memset(buffer, 0xff, dev->data_bytes_per_chunk);
502                         yaffs_init_tags(&tags);
503                         tags.seq_number = YAFFS_SEQUENCE_BAD_BLOCK;
504                         if (dev->param.write_chunk_tags_fn(dev, chunk_id -
505                                                            dev->chunk_offset,
506                                                            buffer,
507                                                            &tags) != YAFFS_OK)
508                                 T(YAFFS_TRACE_ALWAYS,
509                                   (TSTR
510                                    ("yaffs: Failed to "
511                                     TCONT("write bad block marker to block %d")
512                                     TENDSTR), flash_block));
513
514                         yaffs_release_temp_buffer(dev, buffer, __LINE__);
515                 }
516         }
517
518         bi->block_state = YAFFS_BLOCK_STATE_DEAD;
519         bi->gc_prioritise = 0;
520         bi->needs_retiring = 0;
521
522         dev->n_retired_blocks++;
523 }
524
525 /*
526  * Functions for robustisizing TODO
527  *
528  */
529
530 static void yaffs_handle_chunk_wr_ok(struct yaffs_dev *dev, int nand_chunk,
531                                      const u8 * data,
532                                      const struct yaffs_ext_tags *tags)
533 {
534         dev = dev;
535         nand_chunk = nand_chunk;
536         data = data;
537         tags = tags;
538 }
539
540 static void yaffs_handle_chunk_update(struct yaffs_dev *dev, int nand_chunk,
541                                       const struct yaffs_ext_tags *tags)
542 {
543         dev = dev;
544         nand_chunk = nand_chunk;
545         tags = tags;
546 }
547
548 void yaffs_handle_chunk_error(struct yaffs_dev *dev,
549                               struct yaffs_block_info *bi)
550 {
551         if (!bi->gc_prioritise) {
552                 bi->gc_prioritise = 1;
553                 dev->has_pending_prioritised_gc = 1;
554                 bi->chunk_error_strikes++;
555
556                 if (bi->chunk_error_strikes > 3) {
557                         bi->needs_retiring = 1; /* Too many stikes, so retire this */
558                         T(YAFFS_TRACE_ALWAYS,
559                           (TSTR("yaffs: Block struck out" TENDSTR)));
560
561                 }
562         }
563 }
564
565 static void yaffs_handle_chunk_wr_error(struct yaffs_dev *dev, int nand_chunk,
566                                         int erased_ok)
567 {
568         int flash_block = nand_chunk / dev->param.chunks_per_block;
569         struct yaffs_block_info *bi = yaffs_get_block_info(dev, flash_block);
570
571         yaffs_handle_chunk_error(dev, bi);
572
573         if (erased_ok) {
574                 /* Was an actual write failure, so mark the block for retirement  */
575                 bi->needs_retiring = 1;
576                 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
577                   (TSTR("**>> Block %d needs retiring" TENDSTR), flash_block));
578         }
579
580         /* Delete the chunk */
581         yaffs_chunk_del(dev, nand_chunk, 1, __LINE__);
582         yaffs_skip_rest_of_block(dev);
583 }
584
585 /*---------------- Name handling functions ------------*/
586
587 static u16 yaffs_calc_name_sum(const YCHAR * name)
588 {
589         u16 sum = 0;
590         u16 i = 1;
591
592         const YUCHAR *bname = (const YUCHAR *)name;
593         if (bname) {
594                 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH / 2))) {
595
596                         /* 0x1f mask is case insensitive */
597                         sum += ((*bname) & 0x1f) * i;
598                         i++;
599                         bname++;
600                 }
601         }
602         return sum;
603 }
604
605 void yaffs_set_obj_name(struct yaffs_obj *obj, const YCHAR * name)
606 {
607 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
608         memset(obj->short_name, 0,
609                sizeof(YCHAR) * (YAFFS_SHORT_NAME_LENGTH + 1));
610         if (name
611             && yaffs_strnlen(name,
612                              YAFFS_SHORT_NAME_LENGTH + 1) <=
613             YAFFS_SHORT_NAME_LENGTH)
614                 yaffs_strcpy(obj->short_name, name);
615         else
616                 obj->short_name[0] = _Y('\0');
617 #endif
618         obj->sum = yaffs_calc_name_sum(name);
619 }
620
621 void yaffs_set_obj_name_from_oh(struct yaffs_obj *obj,
622                                 const struct yaffs_obj_hdr *oh)
623 {
624 #ifdef CONFIG_YAFFS_AUTO_UNICODE
625         YCHAR tmp_name[YAFFS_MAX_NAME_LENGTH + 1];
626         memset(tmp_name, 0, sizeof(tmp_name));
627         yaffs_load_name_from_oh(obj->my_dev, tmp_name, oh->name,
628                                 YAFFS_MAX_NAME_LENGTH + 1);
629         yaffs_set_obj_name(obj, tmp_name);
630 #else
631         yaffs_set_obj_name(obj, oh->name);
632 #endif
633 }
634
635 /*-------------------- TNODES -------------------
636
637  * List of spare tnodes
638  * The list is hooked together using the first pointer
639  * in the tnode.
640  */
641
642 struct yaffs_tnode *yaffs_get_tnode(struct yaffs_dev *dev)
643 {
644         struct yaffs_tnode *tn = yaffs_alloc_raw_tnode(dev);
645         if (tn) {
646                 memset(tn, 0, dev->tnode_size);
647                 dev->n_tnodes++;
648         }
649
650         dev->checkpoint_blocks_required = 0;    /* force recalculation */
651
652         return tn;
653 }
654
655 /* FreeTnode frees up a tnode and puts it back on the free list */
656 static void yaffs_free_tnode(struct yaffs_dev *dev, struct yaffs_tnode *tn)
657 {
658         yaffs_free_raw_tnode(dev, tn);
659         dev->n_tnodes--;
660         dev->checkpoint_blocks_required = 0;    /* force recalculation */
661 }
662
663 static void yaffs_deinit_tnodes_and_objs(struct yaffs_dev *dev)
664 {
665         yaffs_deinit_raw_tnodes_and_objs(dev);
666         dev->n_obj = 0;
667         dev->n_tnodes = 0;
668 }
669
670 void yaffs_load_tnode_0(struct yaffs_dev *dev, struct yaffs_tnode *tn,
671                         unsigned pos, unsigned val)
672 {
673         u32 *map = (u32 *) tn;
674         u32 bit_in_map;
675         u32 bit_in_word;
676         u32 word_in_map;
677         u32 mask;
678
679         pos &= YAFFS_TNODES_LEVEL0_MASK;
680         val >>= dev->chunk_grp_bits;
681
682         bit_in_map = pos * dev->tnode_width;
683         word_in_map = bit_in_map / 32;
684         bit_in_word = bit_in_map & (32 - 1);
685
686         mask = dev->tnode_mask << bit_in_word;
687
688         map[word_in_map] &= ~mask;
689         map[word_in_map] |= (mask & (val << bit_in_word));
690
691         if (dev->tnode_width > (32 - bit_in_word)) {
692                 bit_in_word = (32 - bit_in_word);
693                 word_in_map++;;
694                 mask =
695                     dev->tnode_mask >> ( /*dev->tnode_width - */ bit_in_word);
696                 map[word_in_map] &= ~mask;
697                 map[word_in_map] |= (mask & (val >> bit_in_word));
698         }
699 }
700
701 u32 yaffs_get_group_base(struct yaffs_dev *dev, struct yaffs_tnode *tn,
702                          unsigned pos)
703 {
704         u32 *map = (u32 *) tn;
705         u32 bit_in_map;
706         u32 bit_in_word;
707         u32 word_in_map;
708         u32 val;
709
710         pos &= YAFFS_TNODES_LEVEL0_MASK;
711
712         bit_in_map = pos * dev->tnode_width;
713         word_in_map = bit_in_map / 32;
714         bit_in_word = bit_in_map & (32 - 1);
715
716         val = map[word_in_map] >> bit_in_word;
717
718         if (dev->tnode_width > (32 - bit_in_word)) {
719                 bit_in_word = (32 - bit_in_word);
720                 word_in_map++;;
721                 val |= (map[word_in_map] << bit_in_word);
722         }
723
724         val &= dev->tnode_mask;
725         val <<= dev->chunk_grp_bits;
726
727         return val;
728 }
729
730 /* ------------------- End of individual tnode manipulation -----------------*/
731
732 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
733  * The look up tree is represented by the top tnode and the number of top_level
734  * in the tree. 0 means only the level 0 tnode is in the tree.
735  */
736
737 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
738 struct yaffs_tnode *yaffs_find_tnode_0(struct yaffs_dev *dev,
739                                        struct yaffs_file_var *file_struct,
740                                        u32 chunk_id)
741 {
742         struct yaffs_tnode *tn = file_struct->top;
743         u32 i;
744         int required_depth;
745         int level = file_struct->top_level;
746
747         dev = dev;
748
749         /* Check sane level and chunk Id */
750         if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
751                 return NULL;
752
753         if (chunk_id > YAFFS_MAX_CHUNK_ID)
754                 return NULL;
755
756         /* First check we're tall enough (ie enough top_level) */
757
758         i = chunk_id >> YAFFS_TNODES_LEVEL0_BITS;
759         required_depth = 0;
760         while (i) {
761                 i >>= YAFFS_TNODES_INTERNAL_BITS;
762                 required_depth++;
763         }
764
765         if (required_depth > file_struct->top_level)
766                 return NULL;    /* Not tall enough, so we can't find it */
767
768         /* Traverse down to level 0 */
769         while (level > 0 && tn) {
770                 tn = tn->internal[(chunk_id >>
771                                    (YAFFS_TNODES_LEVEL0_BITS +
772                                     (level - 1) *
773                                     YAFFS_TNODES_INTERNAL_BITS)) &
774                                   YAFFS_TNODES_INTERNAL_MASK];
775                 level--;
776         }
777
778         return tn;
779 }
780
781 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
782  * This happens in two steps:
783  *  1. If the tree isn't tall enough, then make it taller.
784  *  2. Scan down the tree towards the level 0 tnode adding tnodes if required.
785  *
786  * Used when modifying the tree.
787  *
788  *  If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
789  *  be plugged into the ttree.
790  */
791
792 struct yaffs_tnode *yaffs_add_find_tnode_0(struct yaffs_dev *dev,
793                                            struct yaffs_file_var *file_struct,
794                                            u32 chunk_id,
795                                            struct yaffs_tnode *passed_tn)
796 {
797         int required_depth;
798         int i;
799         int l;
800         struct yaffs_tnode *tn;
801
802         u32 x;
803
804         /* Check sane level and page Id */
805         if (file_struct->top_level < 0
806             || file_struct->top_level > YAFFS_TNODES_MAX_LEVEL)
807                 return NULL;
808
809         if (chunk_id > YAFFS_MAX_CHUNK_ID)
810                 return NULL;
811
812         /* First check we're tall enough (ie enough top_level) */
813
814         x = chunk_id >> YAFFS_TNODES_LEVEL0_BITS;
815         required_depth = 0;
816         while (x) {
817                 x >>= YAFFS_TNODES_INTERNAL_BITS;
818                 required_depth++;
819         }
820
821         if (required_depth > file_struct->top_level) {
822                 /* Not tall enough, gotta make the tree taller */
823                 for (i = file_struct->top_level; i < required_depth; i++) {
824
825                         tn = yaffs_get_tnode(dev);
826
827                         if (tn) {
828                                 tn->internal[0] = file_struct->top;
829                                 file_struct->top = tn;
830                                 file_struct->top_level++;
831                         } else {
832                                 T(YAFFS_TRACE_ERROR,
833                                   (TSTR("yaffs: no more tnodes" TENDSTR)));
834                                 return NULL;
835                         }
836                 }
837         }
838
839         /* Traverse down to level 0, adding anything we need */
840
841         l = file_struct->top_level;
842         tn = file_struct->top;
843
844         if (l > 0) {
845                 while (l > 0 && tn) {
846                         x = (chunk_id >>
847                              (YAFFS_TNODES_LEVEL0_BITS +
848                               (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
849                             YAFFS_TNODES_INTERNAL_MASK;
850
851                         if ((l > 1) && !tn->internal[x]) {
852                                 /* Add missing non-level-zero tnode */
853                                 tn->internal[x] = yaffs_get_tnode(dev);
854                                 if (!tn->internal[x])
855                                         return NULL;
856                         } else if (l == 1) {
857                                 /* Looking from level 1 at level 0 */
858                                 if (passed_tn) {
859                                         /* If we already have one, then release it. */
860                                         if (tn->internal[x])
861                                                 yaffs_free_tnode(dev,
862                                                                  tn->
863                                                                  internal[x]);
864                                         tn->internal[x] = passed_tn;
865
866                                 } else if (!tn->internal[x]) {
867                                         /* Don't have one, none passed in */
868                                         tn->internal[x] = yaffs_get_tnode(dev);
869                                         if (!tn->internal[x])
870                                                 return NULL;
871                                 }
872                         }
873
874                         tn = tn->internal[x];
875                         l--;
876                 }
877         } else {
878                 /* top is level 0 */
879                 if (passed_tn) {
880                         memcpy(tn, passed_tn,
881                                (dev->tnode_width * YAFFS_NTNODES_LEVEL0) / 8);
882                         yaffs_free_tnode(dev, passed_tn);
883                 }
884         }
885
886         return tn;
887 }
888
889 static int yaffs_find_chunk_in_group(struct yaffs_dev *dev, int the_chunk,
890                                      struct yaffs_ext_tags *tags, int obj_id,
891                                      int inode_chunk)
892 {
893         int j;
894
895         for (j = 0; the_chunk && j < dev->chunk_grp_size; j++) {
896                 if (yaffs_check_chunk_bit
897                     (dev, the_chunk / dev->param.chunks_per_block,
898                      the_chunk % dev->param.chunks_per_block)) {
899
900                         if (dev->chunk_grp_size == 1)
901                                 return the_chunk;
902                         else {
903                                 yaffs_rd_chunk_tags_nand(dev, the_chunk, NULL,
904                                                          tags);
905                                 if (yaffs_tags_match(tags, obj_id, inode_chunk)) {
906                                         /* found it; */
907                                         return the_chunk;
908                                 }
909                         }
910                 }
911                 the_chunk++;
912         }
913         return -1;
914 }
915
916 static void yaffs_soft_del_chunk(struct yaffs_dev *dev, int chunk)
917 {
918         struct yaffs_block_info *the_block;
919         unsigned block_no;
920
921         T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
922
923         block_no = chunk / dev->param.chunks_per_block;
924         the_block = yaffs_get_block_info(dev, block_no);
925         if (the_block) {
926                 the_block->soft_del_pages++;
927                 dev->n_free_chunks++;
928                 yaffs2_update_oldest_dirty_seq(dev, block_no, the_block);
929         }
930 }
931
932 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
933  * All soft deleting does is increment the block's softdelete count and pulls the chunk out
934  * of the tnode.
935  * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
936  */
937
938 static int yaffs_soft_del_worker(struct yaffs_obj *in, struct yaffs_tnode *tn,
939                                  u32 level, int chunk_offset)
940 {
941         int i;
942         int the_chunk;
943         int all_done = 1;
944         struct yaffs_dev *dev = in->my_dev;
945
946         if (tn) {
947                 if (level > 0) {
948
949                         for (i = YAFFS_NTNODES_INTERNAL - 1; all_done && i >= 0;
950                              i--) {
951                                 if (tn->internal[i]) {
952                                         all_done =
953                                             yaffs_soft_del_worker(in,
954                                                                   tn->internal
955                                                                   [i],
956                                                                   level - 1,
957                                                                   (chunk_offset
958                                                                    <<
959                                                                    YAFFS_TNODES_INTERNAL_BITS)
960                                                                   + i);
961                                         if (all_done) {
962                                                 yaffs_free_tnode(dev,
963                                                                  tn->internal
964                                                                  [i]);
965                                                 tn->internal[i] = NULL;
966                                         } else {
967                                                 /* Hoosterman... how could this happen? */
968                                         }
969                                 }
970                         }
971                         return (all_done) ? 1 : 0;
972                 } else if (level == 0) {
973
974                         for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
975                                 the_chunk = yaffs_get_group_base(dev, tn, i);
976                                 if (the_chunk) {
977                                         /* Note this does not find the real chunk, only the chunk group.
978                                          * We make an assumption that a chunk group is not larger than
979                                          * a block.
980                                          */
981                                         yaffs_soft_del_chunk(dev, the_chunk);
982                                         yaffs_load_tnode_0(dev, tn, i, 0);
983                                 }
984
985                         }
986                         return 1;
987
988                 }
989
990         }
991
992         return 1;
993
994 }
995
996 static void yaffs_soft_del_file(struct yaffs_obj *obj)
997 {
998         if (obj->deleted &&
999             obj->variant_type == YAFFS_OBJECT_TYPE_FILE && !obj->soft_del) {
1000                 if (obj->n_data_chunks <= 0) {
1001                         /* Empty file with no duplicate object headers, just delete it immediately */
1002                         yaffs_free_tnode(obj->my_dev,
1003                                          obj->variant.file_variant.top);
1004                         obj->variant.file_variant.top = NULL;
1005                         T(YAFFS_TRACE_TRACING,
1006                           (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1007                            obj->obj_id));
1008                         yaffs_generic_obj_del(obj);
1009                 } else {
1010                         yaffs_soft_del_worker(obj,
1011                                               obj->variant.file_variant.top,
1012                                               obj->variant.
1013                                               file_variant.top_level, 0);
1014                         obj->soft_del = 1;
1015                 }
1016         }
1017 }
1018
1019 /* Pruning removes any part of the file structure tree that is beyond the
1020  * bounds of the file (ie that does not point to chunks).
1021  *
1022  * A file should only get pruned when its size is reduced.
1023  *
1024  * Before pruning, the chunks must be pulled from the tree and the
1025  * level 0 tnode entries must be zeroed out.
1026  * Could also use this for file deletion, but that's probably better handled
1027  * by a special case.
1028  *
1029  * This function is recursive. For levels > 0 the function is called again on
1030  * any sub-tree. For level == 0 we just check if the sub-tree has data.
1031  * If there is no data in a subtree then it is pruned.
1032  */
1033
1034 static struct yaffs_tnode *yaffs_prune_worker(struct yaffs_dev *dev,
1035                                               struct yaffs_tnode *tn, u32 level,
1036                                               int del0)
1037 {
1038         int i;
1039         int has_data;
1040
1041         if (tn) {
1042                 has_data = 0;
1043
1044                 if (level > 0) {
1045                         for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1046                                 if (tn->internal[i]) {
1047                                         tn->internal[i] =
1048                                             yaffs_prune_worker(dev,
1049                                                                tn->internal[i],
1050                                                                level - 1,
1051                                                                (i ==
1052                                                                 0) ? del0 : 1);
1053                                 }
1054
1055                                 if (tn->internal[i])
1056                                         has_data++;
1057                         }
1058                 } else {
1059                         int tnode_size_u32 = dev->tnode_size / sizeof(u32);
1060                         u32 *map = (u32 *) tn;
1061
1062                         for (i = 0; !has_data && i < tnode_size_u32; i++) {
1063                                 if (map[i])
1064                                         has_data++;
1065                         }
1066                 }
1067
1068                 if (has_data == 0 && del0) {
1069                         /* Free and return NULL */
1070
1071                         yaffs_free_tnode(dev, tn);
1072                         tn = NULL;
1073                 }
1074
1075         }
1076
1077         return tn;
1078
1079 }
1080
1081 static int yaffs_prune_tree(struct yaffs_dev *dev,
1082                             struct yaffs_file_var *file_struct)
1083 {
1084         int i;
1085         int has_data;
1086         int done = 0;
1087         struct yaffs_tnode *tn;
1088
1089         if (file_struct->top_level > 0) {
1090                 file_struct->top =
1091                     yaffs_prune_worker(dev, file_struct->top,
1092                                        file_struct->top_level, 0);
1093
1094                 /* Now we have a tree with all the non-zero branches NULL but the height
1095                  * is the same as it was.
1096                  * Let's see if we can trim internal tnodes to shorten the tree.
1097                  * We can do this if only the 0th element in the tnode is in use
1098                  * (ie all the non-zero are NULL)
1099                  */
1100
1101                 while (file_struct->top_level && !done) {
1102                         tn = file_struct->top;
1103
1104                         has_data = 0;
1105                         for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1106                                 if (tn->internal[i])
1107                                         has_data++;
1108                         }
1109
1110                         if (!has_data) {
1111                                 file_struct->top = tn->internal[0];
1112                                 file_struct->top_level--;
1113                                 yaffs_free_tnode(dev, tn);
1114                         } else {
1115                                 done = 1;
1116                         }
1117                 }
1118         }
1119
1120         return YAFFS_OK;
1121 }
1122
1123 /*-------------------- End of File Structure functions.-------------------*/
1124
1125 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1126 static struct yaffs_obj *yaffs_alloc_empty_obj(struct yaffs_dev *dev)
1127 {
1128         struct yaffs_obj *obj = yaffs_alloc_raw_obj(dev);
1129
1130         if (obj) {
1131                 dev->n_obj++;
1132
1133                 /* Now sweeten it up... */
1134
1135                 memset(obj, 0, sizeof(struct yaffs_obj));
1136                 obj->being_created = 1;
1137
1138                 obj->my_dev = dev;
1139                 obj->hdr_chunk = 0;
1140                 obj->variant_type = YAFFS_OBJECT_TYPE_UNKNOWN;
1141                 INIT_LIST_HEAD(&(obj->hard_links));
1142                 INIT_LIST_HEAD(&(obj->hash_link));
1143                 INIT_LIST_HEAD(&obj->siblings);
1144
1145                 /* Now make the directory sane */
1146                 if (dev->root_dir) {
1147                         obj->parent = dev->root_dir;
1148                         list_add(&(obj->siblings),
1149                                  &dev->root_dir->variant.dir_variant.children);
1150                 }
1151
1152                 /* Add it to the lost and found directory.
1153                  * NB Can't put root or lost-n-found in lost-n-found so
1154                  * check if lost-n-found exists first
1155                  */
1156                 if (dev->lost_n_found)
1157                         yaffs_add_obj_to_dir(dev->lost_n_found, obj);
1158
1159                 obj->being_created = 0;
1160         }
1161
1162         dev->checkpoint_blocks_required = 0;    /* force recalculation */
1163
1164         return obj;
1165 }
1166
1167 static struct yaffs_obj *yaffs_create_fake_dir(struct yaffs_dev *dev,
1168                                                int number, u32 mode)
1169 {
1170
1171         struct yaffs_obj *obj =
1172             yaffs_new_obj(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1173         if (obj) {
1174                 obj->fake = 1;  /* it is fake so it might have no NAND presence... */
1175                 obj->rename_allowed = 0;        /* ... and we're not allowed to rename it... */
1176                 obj->unlink_allowed = 0;        /* ... or unlink it */
1177                 obj->deleted = 0;
1178                 obj->unlinked = 0;
1179                 obj->yst_mode = mode;
1180                 obj->my_dev = dev;
1181                 obj->hdr_chunk = 0;     /* Not a valid chunk. */
1182         }
1183
1184         return obj;
1185
1186 }
1187
1188 static void yaffs_unhash_obj(struct yaffs_obj *obj)
1189 {
1190         int bucket;
1191         struct yaffs_dev *dev = obj->my_dev;
1192
1193         /* If it is still linked into the bucket list, free from the list */
1194         if (!list_empty(&obj->hash_link)) {
1195                 list_del_init(&obj->hash_link);
1196                 bucket = yaffs_hash_fn(obj->obj_id);
1197                 dev->obj_bucket[bucket].count--;
1198         }
1199 }
1200
1201 /*  FreeObject frees up a Object and puts it back on the free list */
1202 static void yaffs_free_obj(struct yaffs_obj *obj)
1203 {
1204         struct yaffs_dev *dev = obj->my_dev;
1205
1206         T(YAFFS_TRACE_OS,
1207           (TSTR("FreeObject %p inode %p" TENDSTR), obj, obj->my_inode));
1208
1209         if (!obj)
1210                 YBUG();
1211         if (obj->parent)
1212                 YBUG();
1213         if (!list_empty(&obj->siblings))
1214                 YBUG();
1215
1216         if (obj->my_inode) {
1217                 /* We're still hooked up to a cached inode.
1218                  * Don't delete now, but mark for later deletion
1219                  */
1220                 obj->defered_free = 1;
1221                 return;
1222         }
1223
1224         yaffs_unhash_obj(obj);
1225
1226         yaffs_free_raw_obj(dev, obj);
1227         dev->n_obj--;
1228         dev->checkpoint_blocks_required = 0;    /* force recalculation */
1229 }
1230
1231 void yaffs_handle_defered_free(struct yaffs_obj *obj)
1232 {
1233         if (obj->defered_free)
1234                 yaffs_free_obj(obj);
1235 }
1236
1237 static void yaffs_init_tnodes_and_objs(struct yaffs_dev *dev)
1238 {
1239         int i;
1240
1241         dev->n_obj = 0;
1242         dev->n_tnodes = 0;
1243
1244         yaffs_init_raw_tnodes_and_objs(dev);
1245
1246         for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
1247                 INIT_LIST_HEAD(&dev->obj_bucket[i].list);
1248                 dev->obj_bucket[i].count = 0;
1249         }
1250 }
1251
1252 static int yaffs_find_nice_bucket(struct yaffs_dev *dev)
1253 {
1254         int i;
1255         int l = 999;
1256         int lowest = 999999;
1257
1258         /* Search for the shortest list or one that
1259          * isn't too long.
1260          */
1261
1262         for (i = 0; i < 10 && lowest > 4; i++) {
1263                 dev->bucket_finder++;
1264                 dev->bucket_finder %= YAFFS_NOBJECT_BUCKETS;
1265                 if (dev->obj_bucket[dev->bucket_finder].count < lowest) {
1266                         lowest = dev->obj_bucket[dev->bucket_finder].count;
1267                         l = dev->bucket_finder;
1268                 }
1269
1270         }
1271
1272         return l;
1273 }
1274
1275 static int yaffs_new_obj_id(struct yaffs_dev *dev)
1276 {
1277         int bucket = yaffs_find_nice_bucket(dev);
1278
1279         /* Now find an object value that has not already been taken
1280          * by scanning the list.
1281          */
1282
1283         int found = 0;
1284         struct list_head *i;
1285
1286         u32 n = (u32) bucket;
1287
1288         /* yaffs_check_obj_hash_sane();  */
1289
1290         while (!found) {
1291                 found = 1;
1292                 n += YAFFS_NOBJECT_BUCKETS;
1293                 if (1 || dev->obj_bucket[bucket].count > 0) {
1294                         list_for_each(i, &dev->obj_bucket[bucket].list) {
1295                                 /* If there is already one in the list */
1296                                 if (i && list_entry(i, struct yaffs_obj,
1297                                                     hash_link)->obj_id == n) {
1298                                         found = 0;
1299                                 }
1300                         }
1301                 }
1302         }
1303
1304         return n;
1305 }
1306
1307 static void yaffs_hash_obj(struct yaffs_obj *in)
1308 {
1309         int bucket = yaffs_hash_fn(in->obj_id);
1310         struct yaffs_dev *dev = in->my_dev;
1311
1312         list_add(&in->hash_link, &dev->obj_bucket[bucket].list);
1313         dev->obj_bucket[bucket].count++;
1314 }
1315
1316 struct yaffs_obj *yaffs_find_by_number(struct yaffs_dev *dev, u32 number)
1317 {
1318         int bucket = yaffs_hash_fn(number);
1319         struct list_head *i;
1320         struct yaffs_obj *in;
1321
1322         list_for_each(i, &dev->obj_bucket[bucket].list) {
1323                 /* Look if it is in the list */
1324                 if (i) {
1325                         in = list_entry(i, struct yaffs_obj, hash_link);
1326                         if (in->obj_id == number) {
1327
1328                                 /* Don't tell the VFS about this one if it is defered free */
1329                                 if (in->defered_free)
1330                                         return NULL;
1331
1332                                 return in;
1333                         }
1334                 }
1335         }
1336
1337         return NULL;
1338 }
1339
1340 struct yaffs_obj *yaffs_new_obj(struct yaffs_dev *dev, int number,
1341                                 enum yaffs_obj_type type)
1342 {
1343         struct yaffs_obj *the_obj = NULL;
1344         struct yaffs_tnode *tn = NULL;
1345
1346         if (number < 0)
1347                 number = yaffs_new_obj_id(dev);
1348
1349         if (type == YAFFS_OBJECT_TYPE_FILE) {
1350                 tn = yaffs_get_tnode(dev);
1351                 if (!tn)
1352                         return NULL;
1353         }
1354
1355         the_obj = yaffs_alloc_empty_obj(dev);
1356         if (!the_obj) {
1357                 if (tn)
1358                         yaffs_free_tnode(dev, tn);
1359                 return NULL;
1360         }
1361
1362         if (the_obj) {
1363                 the_obj->fake = 0;
1364                 the_obj->rename_allowed = 1;
1365                 the_obj->unlink_allowed = 1;
1366                 the_obj->obj_id = number;
1367                 yaffs_hash_obj(the_obj);
1368                 the_obj->variant_type = type;
1369                 yaffs_load_current_time(the_obj, 1, 1);
1370
1371                 switch (type) {
1372                 case YAFFS_OBJECT_TYPE_FILE:
1373                         the_obj->variant.file_variant.file_size = 0;
1374                         the_obj->variant.file_variant.scanned_size = 0;
1375                         the_obj->variant.file_variant.shrink_size = ~0; /* max */
1376                         the_obj->variant.file_variant.top_level = 0;
1377                         the_obj->variant.file_variant.top = tn;
1378                         break;
1379                 case YAFFS_OBJECT_TYPE_DIRECTORY:
1380                         INIT_LIST_HEAD(&the_obj->variant.dir_variant.children);
1381                         INIT_LIST_HEAD(&the_obj->variant.dir_variant.dirty);
1382                         break;
1383                 case YAFFS_OBJECT_TYPE_SYMLINK:
1384                 case YAFFS_OBJECT_TYPE_HARDLINK:
1385                 case YAFFS_OBJECT_TYPE_SPECIAL:
1386                         /* No action required */
1387                         break;
1388                 case YAFFS_OBJECT_TYPE_UNKNOWN:
1389                         /* todo this should not happen */
1390                         break;
1391                 }
1392         }
1393
1394         return the_obj;
1395 }
1396
1397 struct yaffs_obj *yaffs_find_or_create_by_number(struct yaffs_dev *dev,
1398                                                  int number,
1399                                                  enum yaffs_obj_type type)
1400 {
1401         struct yaffs_obj *the_obj = NULL;
1402
1403         if (number > 0)
1404                 the_obj = yaffs_find_by_number(dev, number);
1405
1406         if (!the_obj)
1407                 the_obj = yaffs_new_obj(dev, number, type);
1408
1409         return the_obj;
1410
1411 }
1412
1413 YCHAR *yaffs_clone_str(const YCHAR * str)
1414 {
1415         YCHAR *new_str = NULL;
1416         int len;
1417
1418         if (!str)
1419                 str = _Y("");
1420
1421         len = yaffs_strnlen(str, YAFFS_MAX_ALIAS_LENGTH);
1422         new_str = YMALLOC((len + 1) * sizeof(YCHAR));
1423         if (new_str) {
1424                 yaffs_strncpy(new_str, str, len);
1425                 new_str[len] = 0;
1426         }
1427         return new_str;
1428
1429 }
1430
1431 /*
1432  * Mknod (create) a new object.
1433  * equiv_obj only has meaning for a hard link;
1434  * alias_str only has meaning for a symlink.
1435  * rdev only has meaning for devices (a subset of special objects)
1436  */
1437
1438 static struct yaffs_obj *yaffs_create_obj(enum yaffs_obj_type type,
1439                                           struct yaffs_obj *parent,
1440                                           const YCHAR * name,
1441                                           u32 mode,
1442                                           u32 uid,
1443                                           u32 gid,
1444                                           struct yaffs_obj *equiv_obj,
1445                                           const YCHAR * alias_str, u32 rdev)
1446 {
1447         struct yaffs_obj *in;
1448         YCHAR *str = NULL;
1449
1450         struct yaffs_dev *dev = parent->my_dev;
1451
1452         /* Check if the entry exists. If it does then fail the call since we don't want a dup. */
1453         if (yaffs_find_by_name(parent, name))
1454                 return NULL;
1455
1456         if (type == YAFFS_OBJECT_TYPE_SYMLINK) {
1457                 str = yaffs_clone_str(alias_str);
1458                 if (!str)
1459                         return NULL;
1460         }
1461
1462         in = yaffs_new_obj(dev, -1, type);
1463
1464         if (!in) {
1465                 if (str)
1466                         YFREE(str);
1467                 return NULL;
1468         }
1469
1470         if (in) {
1471                 in->hdr_chunk = 0;
1472                 in->valid = 1;
1473                 in->variant_type = type;
1474
1475                 in->yst_mode = mode;
1476
1477                 yaffs_attribs_init(in, gid, uid, rdev);
1478
1479                 in->n_data_chunks = 0;
1480
1481                 yaffs_set_obj_name(in, name);
1482                 in->dirty = 1;
1483
1484                 yaffs_add_obj_to_dir(parent, in);
1485
1486                 in->my_dev = parent->my_dev;
1487
1488                 switch (type) {
1489                 case YAFFS_OBJECT_TYPE_SYMLINK:
1490                         in->variant.symlink_variant.alias = str;
1491                         break;
1492                 case YAFFS_OBJECT_TYPE_HARDLINK:
1493                         in->variant.hardlink_variant.equiv_obj = equiv_obj;
1494                         in->variant.hardlink_variant.equiv_id =
1495                             equiv_obj->obj_id;
1496                         list_add(&in->hard_links, &equiv_obj->hard_links);
1497                         break;
1498                 case YAFFS_OBJECT_TYPE_FILE:
1499                 case YAFFS_OBJECT_TYPE_DIRECTORY:
1500                 case YAFFS_OBJECT_TYPE_SPECIAL:
1501                 case YAFFS_OBJECT_TYPE_UNKNOWN:
1502                         /* do nothing */
1503                         break;
1504                 }
1505
1506                 if (yaffs_update_oh(in, name, 0, 0, 0, NULL) < 0) {
1507                         /* Could not create the object header, fail the creation */
1508                         yaffs_del_obj(in);
1509                         in = NULL;
1510                 }
1511
1512                 yaffs_update_parent(parent);
1513         }
1514
1515         return in;
1516 }
1517
1518 struct yaffs_obj *yaffs_create_file(struct yaffs_obj *parent,
1519                                     const YCHAR * name, u32 mode, u32 uid,
1520                                     u32 gid)
1521 {
1522         return yaffs_create_obj(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
1523                                 uid, gid, NULL, NULL, 0);
1524 }
1525
1526 struct yaffs_obj *yaffs_create_dir(struct yaffs_obj *parent, const YCHAR * name,
1527                                    u32 mode, u32 uid, u32 gid)
1528 {
1529         return yaffs_create_obj(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
1530                                 mode, uid, gid, NULL, NULL, 0);
1531 }
1532
1533 struct yaffs_obj *yaffs_create_special(struct yaffs_obj *parent,
1534                                        const YCHAR * name, u32 mode, u32 uid,
1535                                        u32 gid, u32 rdev)
1536 {
1537         return yaffs_create_obj(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
1538                                 uid, gid, NULL, NULL, rdev);
1539 }
1540
1541 struct yaffs_obj *yaffs_create_symlink(struct yaffs_obj *parent,
1542                                        const YCHAR * name, u32 mode, u32 uid,
1543                                        u32 gid, const YCHAR * alias)
1544 {
1545         return yaffs_create_obj(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
1546                                 uid, gid, NULL, alias, 0);
1547 }
1548
1549 /* yaffs_link_obj returns the object id of the equivalent object.*/
1550 struct yaffs_obj *yaffs_link_obj(struct yaffs_obj *parent, const YCHAR * name,
1551                                  struct yaffs_obj *equiv_obj)
1552 {
1553         /* Get the real object in case we were fed a hard link as an equivalent object */
1554         equiv_obj = yaffs_get_equivalent_obj(equiv_obj);
1555
1556         if (yaffs_create_obj
1557             (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
1558              equiv_obj, NULL, 0)) {
1559                 return equiv_obj;
1560         } else {
1561                 return NULL;
1562         }
1563
1564 }
1565
1566 static int yaffs_change_obj_name(struct yaffs_obj *obj,
1567                                  struct yaffs_obj *new_dir,
1568                                  const YCHAR * new_name, int force, int shadows)
1569 {
1570         int unlink_op;
1571         int del_op;
1572
1573         struct yaffs_obj *existing_target;
1574
1575         if (new_dir == NULL)
1576                 new_dir = obj->parent;  /* use the old directory */
1577
1578         if (new_dir->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY) {
1579                 T(YAFFS_TRACE_ALWAYS,
1580                   (TSTR
1581                    ("tragedy: yaffs_change_obj_name: new_dir is not a directory"
1582                     TENDSTR)));
1583                 YBUG();
1584         }
1585
1586         /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
1587         if (obj->my_dev->param.is_yaffs2)
1588                 unlink_op = (new_dir == obj->my_dev->unlinked_dir);
1589         else
1590                 unlink_op = (new_dir == obj->my_dev->unlinked_dir
1591                              && obj->variant_type == YAFFS_OBJECT_TYPE_FILE);
1592
1593         del_op = (new_dir == obj->my_dev->del_dir);
1594
1595         existing_target = yaffs_find_by_name(new_dir, new_name);
1596
1597         /* If the object is a file going into the unlinked directory,
1598          *   then it is OK to just stuff it in since duplicate names are allowed.
1599          *   else only proceed if the new name does not exist and if we're putting
1600          *   it into a directory.
1601          */
1602         if ((unlink_op ||
1603              del_op ||
1604              force ||
1605              (shadows > 0) ||
1606              !existing_target) &&
1607             new_dir->variant_type == YAFFS_OBJECT_TYPE_DIRECTORY) {
1608                 yaffs_set_obj_name(obj, new_name);
1609                 obj->dirty = 1;
1610
1611                 yaffs_add_obj_to_dir(new_dir, obj);
1612
1613                 if (unlink_op)
1614                         obj->unlinked = 1;
1615
1616                 /* If it is a deletion then we mark it as a shrink for gc purposes. */
1617                 if (yaffs_update_oh(obj, new_name, 0, del_op, shadows, NULL) >=
1618                     0)
1619                         return YAFFS_OK;
1620         }
1621
1622         return YAFFS_FAIL;
1623 }
1624
1625 int yaffs_rename_obj(struct yaffs_obj *old_dir, const YCHAR * old_name,
1626                      struct yaffs_obj *new_dir, const YCHAR * new_name)
1627 {
1628         struct yaffs_obj *obj = NULL;
1629         struct yaffs_obj *existing_target = NULL;
1630         int force = 0;
1631         int result;
1632         struct yaffs_dev *dev;
1633
1634         if (!old_dir || old_dir->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY)
1635                 YBUG();
1636         if (!new_dir || new_dir->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY)
1637                 YBUG();
1638
1639         dev = old_dir->my_dev;
1640
1641 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1642         /* Special case for case insemsitive systems.
1643          * While look-up is case insensitive, the name isn't.
1644          * Therefore we might want to change x.txt to X.txt
1645          */
1646         if (old_dir == new_dir && yaffs_strcmp(old_name, new_name) == 0)
1647                 force = 1;
1648 #endif
1649
1650         if (yaffs_strnlen(new_name, YAFFS_MAX_NAME_LENGTH + 1) >
1651             YAFFS_MAX_NAME_LENGTH)
1652                 /* ENAMETOOLONG */
1653                 return YAFFS_FAIL;
1654
1655         obj = yaffs_find_by_name(old_dir, old_name);
1656
1657         if (obj && obj->rename_allowed) {
1658
1659                 /* Now do the handling for an existing target, if there is one */
1660
1661                 existing_target = yaffs_find_by_name(new_dir, new_name);
1662                 if (existing_target &&
1663                     existing_target->variant_type == YAFFS_OBJECT_TYPE_DIRECTORY
1664                     && !list_empty(&existing_target->variant.dir_variant.
1665                                    children)) {
1666                         /* There is a target that is a non-empty directory, so we fail */
1667                         return YAFFS_FAIL;      /* EEXIST or ENOTEMPTY */
1668                 } else if (existing_target && existing_target != obj) {
1669                         /* Nuke the target first, using shadowing,
1670                          * but only if it isn't the same object.
1671                          *
1672                          * Note we must disable gc otherwise it can mess up the shadowing.
1673                          *
1674                          */
1675                         dev->gc_disable = 1;
1676                         yaffs_change_obj_name(obj, new_dir, new_name, force,
1677                                               existing_target->obj_id);
1678                         existing_target->is_shadowed = 1;
1679                         yaffs_unlink_obj(existing_target);
1680                         dev->gc_disable = 0;
1681                 }
1682
1683                 result = yaffs_change_obj_name(obj, new_dir, new_name, 1, 0);
1684
1685                 yaffs_update_parent(old_dir);
1686                 if (new_dir != old_dir)
1687                         yaffs_update_parent(new_dir);
1688
1689                 return result;
1690         }
1691         return YAFFS_FAIL;
1692 }
1693
1694 /*------------------------- Block Management and Page Allocation ----------------*/
1695
1696 static int yaffs_init_blocks(struct yaffs_dev *dev)
1697 {
1698         int n_blocks = dev->internal_end_block - dev->internal_start_block + 1;
1699
1700         dev->block_info = NULL;
1701         dev->chunk_bits = NULL;
1702
1703         dev->alloc_block = -1;  /* force it to get a new one */
1704
1705         /* If the first allocation strategy fails, thry the alternate one */
1706         dev->block_info = YMALLOC(n_blocks * sizeof(struct yaffs_block_info));
1707         if (!dev->block_info) {
1708                 dev->block_info =
1709                     YMALLOC_ALT(n_blocks * sizeof(struct yaffs_block_info));
1710                 dev->block_info_alt = 1;
1711         } else {
1712                 dev->block_info_alt = 0;
1713         }
1714
1715         if (dev->block_info) {
1716                 /* Set up dynamic blockinfo stuff. */
1717                 dev->chunk_bit_stride = (dev->param.chunks_per_block + 7) / 8;  /* round up bytes */
1718                 dev->chunk_bits = YMALLOC(dev->chunk_bit_stride * n_blocks);
1719                 if (!dev->chunk_bits) {
1720                         dev->chunk_bits =
1721                             YMALLOC_ALT(dev->chunk_bit_stride * n_blocks);
1722                         dev->chunk_bits_alt = 1;
1723                 } else {
1724                         dev->chunk_bits_alt = 0;
1725                 }
1726         }
1727
1728         if (dev->block_info && dev->chunk_bits) {
1729                 memset(dev->block_info, 0,
1730                        n_blocks * sizeof(struct yaffs_block_info));
1731                 memset(dev->chunk_bits, 0, dev->chunk_bit_stride * n_blocks);
1732                 return YAFFS_OK;
1733         }
1734
1735         return YAFFS_FAIL;
1736 }
1737
1738 static void yaffs_deinit_blocks(struct yaffs_dev *dev)
1739 {
1740         if (dev->block_info_alt && dev->block_info)
1741                 YFREE_ALT(dev->block_info);
1742         else if (dev->block_info)
1743                 YFREE(dev->block_info);
1744
1745         dev->block_info_alt = 0;
1746
1747         dev->block_info = NULL;
1748
1749         if (dev->chunk_bits_alt && dev->chunk_bits)
1750                 YFREE_ALT(dev->chunk_bits);
1751         else if (dev->chunk_bits)
1752                 YFREE(dev->chunk_bits);
1753         dev->chunk_bits_alt = 0;
1754         dev->chunk_bits = NULL;
1755 }
1756
1757 void yaffs_block_became_dirty(struct yaffs_dev *dev, int block_no)
1758 {
1759         struct yaffs_block_info *bi = yaffs_get_block_info(dev, block_no);
1760
1761         int erased_ok = 0;
1762
1763         /* If the block is still healthy erase it and mark as clean.
1764          * If the block has had a data failure, then retire it.
1765          */
1766
1767         T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
1768           (TSTR("yaffs_block_became_dirty block %d state %d %s" TENDSTR),
1769            block_no, bi->block_state,
1770            (bi->needs_retiring) ? "needs retiring" : ""));
1771
1772         yaffs2_clear_oldest_dirty_seq(dev, bi);
1773
1774         bi->block_state = YAFFS_BLOCK_STATE_DIRTY;
1775
1776         /* If this is the block being garbage collected then stop gc'ing this block */
1777         if (block_no == dev->gc_block)
1778                 dev->gc_block = 0;
1779
1780         /* If this block is currently the best candidate for gc then drop as a candidate */
1781         if (block_no == dev->gc_dirtiest) {
1782                 dev->gc_dirtiest = 0;
1783                 dev->gc_pages_in_use = 0;
1784         }
1785
1786         if (!bi->needs_retiring) {
1787                 yaffs2_checkpt_invalidate(dev);
1788                 erased_ok = yaffs_erase_block(dev, block_no);
1789                 if (!erased_ok) {
1790                         dev->n_erase_failures++;
1791                         T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1792                           (TSTR("**>> Erasure failed %d" TENDSTR), block_no));
1793                 }
1794         }
1795
1796         if (erased_ok &&
1797             ((yaffs_trace_mask & YAFFS_TRACE_ERASE)
1798              || !yaffs_skip_verification(dev))) {
1799                 int i;
1800                 for (i = 0; i < dev->param.chunks_per_block; i++) {
1801                         if (!yaffs_check_chunk_erased
1802                             (dev, block_no * dev->param.chunks_per_block + i)) {
1803                                 T(YAFFS_TRACE_ERROR,
1804                                   (TSTR
1805                                    (">>Block %d erasure supposedly OK, but chunk %d not erased"
1806                                     TENDSTR), block_no, i));
1807                         }
1808                 }
1809         }
1810
1811         if (erased_ok) {
1812                 /* Clean it up... */
1813                 bi->block_state = YAFFS_BLOCK_STATE_EMPTY;
1814                 bi->seq_number = 0;
1815                 dev->n_erased_blocks++;
1816                 bi->pages_in_use = 0;
1817                 bi->soft_del_pages = 0;
1818                 bi->has_shrink_hdr = 0;
1819                 bi->skip_erased_check = 1;      /* This is clean, so no need to check */
1820                 bi->gc_prioritise = 0;
1821                 yaffs_clear_chunk_bits(dev, block_no);
1822
1823                 T(YAFFS_TRACE_ERASE,
1824                   (TSTR("Erased block %d" TENDSTR), block_no));
1825         } else {
1826                 dev->n_free_chunks -= dev->param.chunks_per_block;      /* We lost a block of free space */
1827
1828                 yaffs_retire_block(dev, block_no);
1829                 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1830                   (TSTR("**>> Block %d retired" TENDSTR), block_no));
1831         }
1832 }
1833
1834 static int yaffs_find_alloc_block(struct yaffs_dev *dev)
1835 {
1836         int i;
1837
1838         struct yaffs_block_info *bi;
1839
1840         if (dev->n_erased_blocks < 1) {
1841                 /* Hoosterman we've got a problem.
1842                  * Can't get space to gc
1843                  */
1844                 T(YAFFS_TRACE_ERROR,
1845                   (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
1846
1847                 return -1;
1848         }
1849
1850         /* Find an empty block. */
1851
1852         for (i = dev->internal_start_block; i <= dev->internal_end_block; i++) {
1853                 dev->alloc_block_finder++;
1854                 if (dev->alloc_block_finder < dev->internal_start_block
1855                     || dev->alloc_block_finder > dev->internal_end_block) {
1856                         dev->alloc_block_finder = dev->internal_start_block;
1857                 }
1858
1859                 bi = yaffs_get_block_info(dev, dev->alloc_block_finder);
1860
1861                 if (bi->block_state == YAFFS_BLOCK_STATE_EMPTY) {
1862                         bi->block_state = YAFFS_BLOCK_STATE_ALLOCATING;
1863                         dev->seq_number++;
1864                         bi->seq_number = dev->seq_number;
1865                         dev->n_erased_blocks--;
1866                         T(YAFFS_TRACE_ALLOCATE,
1867                           (TSTR("Allocated block %d, seq  %d, %d left" TENDSTR),
1868                            dev->alloc_block_finder, dev->seq_number,
1869                            dev->n_erased_blocks));
1870                         return dev->alloc_block_finder;
1871                 }
1872         }
1873
1874         T(YAFFS_TRACE_ALWAYS,
1875           (TSTR
1876            ("yaffs tragedy: no more erased blocks, but there should have been %d"
1877             TENDSTR), dev->n_erased_blocks));
1878
1879         return -1;
1880 }
1881
1882 /*
1883  * Check if there's space to allocate...
1884  * Thinks.... do we need top make this ths same as yaffs_get_free_chunks()?
1885  */
1886 int yaffs_check_alloc_available(struct yaffs_dev *dev, int n_chunks)
1887 {
1888         int reserved_chunks;
1889         int reserved_blocks = dev->param.n_reserved_blocks;
1890         int checkpt_blocks;
1891
1892         checkpt_blocks = yaffs_calc_checkpt_blocks_required(dev);
1893
1894         reserved_chunks =
1895             ((reserved_blocks + checkpt_blocks) * dev->param.chunks_per_block);
1896
1897         return (dev->n_free_chunks > (reserved_chunks + n_chunks));
1898 }
1899
1900 static int yaffs_alloc_chunk(struct yaffs_dev *dev, int use_reserver,
1901                              struct yaffs_block_info **block_ptr)
1902 {
1903         int ret_val;
1904         struct yaffs_block_info *bi;
1905
1906         if (dev->alloc_block < 0) {
1907                 /* Get next block to allocate off */
1908                 dev->alloc_block = yaffs_find_alloc_block(dev);
1909                 dev->alloc_page = 0;
1910         }
1911
1912         if (!use_reserver && !yaffs_check_alloc_available(dev, 1)) {
1913                 /* Not enough space to allocate unless we're allowed to use the reserve. */
1914                 return -1;
1915         }
1916
1917         if (dev->n_erased_blocks < dev->param.n_reserved_blocks
1918             && dev->alloc_page == 0) {
1919                 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
1920         }
1921
1922         /* Next page please.... */
1923         if (dev->alloc_block >= 0) {
1924                 bi = yaffs_get_block_info(dev, dev->alloc_block);
1925
1926                 ret_val = (dev->alloc_block * dev->param.chunks_per_block) +
1927                     dev->alloc_page;
1928                 bi->pages_in_use++;
1929                 yaffs_set_chunk_bit(dev, dev->alloc_block, dev->alloc_page);
1930
1931                 dev->alloc_page++;
1932
1933                 dev->n_free_chunks--;
1934
1935                 /* If the block is full set the state to full */
1936                 if (dev->alloc_page >= dev->param.chunks_per_block) {
1937                         bi->block_state = YAFFS_BLOCK_STATE_FULL;
1938                         dev->alloc_block = -1;
1939                 }
1940
1941                 if (block_ptr)
1942                         *block_ptr = bi;
1943
1944                 return ret_val;
1945         }
1946
1947         T(YAFFS_TRACE_ERROR,
1948           (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
1949
1950         return -1;
1951 }
1952
1953 static int yaffs_get_erased_chunks(struct yaffs_dev *dev)
1954 {
1955         int n;
1956
1957         n = dev->n_erased_blocks * dev->param.chunks_per_block;
1958
1959         if (dev->alloc_block > 0)
1960                 n += (dev->param.chunks_per_block - dev->alloc_page);
1961
1962         return n;
1963
1964 }
1965
1966 /*
1967  * yaffs_skip_rest_of_block() skips over the rest of the allocation block
1968  * if we don't want to write to it.
1969  */
1970 void yaffs_skip_rest_of_block(struct yaffs_dev *dev)
1971 {
1972         if (dev->alloc_block > 0) {
1973                 struct yaffs_block_info *bi =
1974                     yaffs_get_block_info(dev, dev->alloc_block);
1975                 if (bi->block_state == YAFFS_BLOCK_STATE_ALLOCATING) {
1976                         bi->block_state = YAFFS_BLOCK_STATE_FULL;
1977                         dev->alloc_block = -1;
1978                 }
1979         }
1980 }
1981
1982 static int yaffs_gc_block(struct yaffs_dev *dev, int block, int whole_block)
1983 {
1984         int old_chunk;
1985         int new_chunk;
1986         int mark_flash;
1987         int ret_val = YAFFS_OK;
1988         int i;
1989         int is_checkpt_block;
1990         int matching_chunk;
1991         int max_copies;
1992
1993         int chunks_before = yaffs_get_erased_chunks(dev);
1994         int chunks_after;
1995
1996         struct yaffs_ext_tags tags;
1997
1998         struct yaffs_block_info *bi = yaffs_get_block_info(dev, block);
1999
2000         struct yaffs_obj *object;
2001
2002         is_checkpt_block = (bi->block_state == YAFFS_BLOCK_STATE_CHECKPOINT);
2003
2004         T(YAFFS_TRACE_TRACING,
2005           (TSTR
2006            ("Collecting block %d, in use %d, shrink %d, whole_block %d"
2007             TENDSTR), block, bi->pages_in_use, bi->has_shrink_hdr,
2008            whole_block));
2009
2010         /*yaffs_verify_free_chunks(dev); */
2011
2012         if (bi->block_state == YAFFS_BLOCK_STATE_FULL)
2013                 bi->block_state = YAFFS_BLOCK_STATE_COLLECTING;
2014
2015         bi->has_shrink_hdr = 0; /* clear the flag so that the block can erase */
2016
2017         dev->gc_disable = 1;
2018
2019         if (is_checkpt_block || !yaffs_still_some_chunks(dev, block)) {
2020                 T(YAFFS_TRACE_TRACING,
2021                   (TSTR
2022                    ("Collecting block %d that has no chunks in use" TENDSTR),
2023                    block));
2024                 yaffs_block_became_dirty(dev, block);
2025         } else {
2026
2027                 u8 *buffer = yaffs_get_temp_buffer(dev, __LINE__);
2028
2029                 yaffs_verify_blk(dev, bi, block);
2030
2031                 max_copies = (whole_block) ? dev->param.chunks_per_block : 5;
2032                 old_chunk = block * dev->param.chunks_per_block + dev->gc_chunk;
2033
2034                 for ( /* init already done */ ;
2035                      ret_val == YAFFS_OK &&
2036                      dev->gc_chunk < dev->param.chunks_per_block &&
2037                      (bi->block_state == YAFFS_BLOCK_STATE_COLLECTING) &&
2038                      max_copies > 0; dev->gc_chunk++, old_chunk++) {
2039                         if (yaffs_check_chunk_bit(dev, block, dev->gc_chunk)) {
2040
2041                                 /* This page is in use and might need to be copied off */
2042
2043                                 max_copies--;
2044
2045                                 mark_flash = 1;
2046
2047                                 yaffs_init_tags(&tags);
2048
2049                                 yaffs_rd_chunk_tags_nand(dev, old_chunk,
2050                                                          buffer, &tags);
2051
2052                                 object = yaffs_find_by_number(dev, tags.obj_id);
2053
2054                                 T(YAFFS_TRACE_GC_DETAIL,
2055                                   (TSTR
2056                                    ("Collecting chunk in block %d, %d %d %d "
2057                                     TENDSTR), dev->gc_chunk, tags.obj_id,
2058                                    tags.chunk_id, tags.n_bytes));
2059
2060                                 if (object && !yaffs_skip_verification(dev)) {
2061                                         if (tags.chunk_id == 0)
2062                                                 matching_chunk =
2063                                                     object->hdr_chunk;
2064                                         else if (object->soft_del)
2065                                                 matching_chunk = old_chunk;     /* Defeat the test */
2066                                         else
2067                                                 matching_chunk =
2068                                                     yaffs_find_chunk_in_file
2069                                                     (object, tags.chunk_id,
2070                                                      NULL);
2071
2072                                         if (old_chunk != matching_chunk)
2073                                                 T(YAFFS_TRACE_ERROR,
2074                                                   (TSTR
2075                                                    ("gc: page in gc mismatch: %d %d %d %d"
2076                                                     TENDSTR), old_chunk,
2077                                                    matching_chunk, tags.obj_id,
2078                                                    tags.chunk_id));
2079
2080                                 }
2081
2082                                 if (!object) {
2083                                         T(YAFFS_TRACE_ERROR,
2084                                           (TSTR
2085                                            ("page %d in gc has no object: %d %d %d "
2086                                             TENDSTR), old_chunk,
2087                                            tags.obj_id, tags.chunk_id,
2088                                            tags.n_bytes));
2089                                 }
2090
2091                                 if (object &&
2092                                     object->deleted &&
2093                                     object->soft_del && tags.chunk_id != 0) {
2094                                         /* Data chunk in a soft deleted file, throw it away
2095                                          * It's a soft deleted data chunk,
2096                                          * No need to copy this, just forget about it and
2097                                          * fix up the object.
2098                                          */
2099
2100                                         /* Free chunks already includes softdeleted chunks.
2101                                          * How ever this chunk is going to soon be really deleted
2102                                          * which will increment free chunks.
2103                                          * We have to decrement free chunks so this works out properly.
2104                                          */
2105                                         dev->n_free_chunks--;
2106                                         bi->soft_del_pages--;
2107
2108                                         object->n_data_chunks--;
2109
2110                                         if (object->n_data_chunks <= 0) {
2111                                                 /* remeber to clean up the object */
2112                                                 dev->gc_cleanup_list[dev->
2113                                                                      n_clean_ups]
2114                                                     = tags.obj_id;
2115                                                 dev->n_clean_ups++;
2116                                         }
2117                                         mark_flash = 0;
2118                                 } else if (0) {
2119                                         /* Todo object && object->deleted && object->n_data_chunks == 0 */
2120                                         /* Deleted object header with no data chunks.
2121                                          * Can be discarded and the file deleted.
2122                                          */
2123                                         object->hdr_chunk = 0;
2124                                         yaffs_free_tnode(object->my_dev,
2125                                                          object->
2126                                                          variant.file_variant.
2127                                                          top);
2128                                         object->variant.file_variant.top = NULL;
2129                                         yaffs_generic_obj_del(object);
2130
2131                                 } else if (object) {
2132                                         /* It's either a data chunk in a live file or
2133                                          * an ObjectHeader, so we're interested in it.
2134                                          * NB Need to keep the ObjectHeaders of deleted files
2135                                          * until the whole file has been deleted off
2136                                          */
2137                                         tags.serial_number++;
2138
2139                                         dev->n_gc_copies++;
2140
2141                                         if (tags.chunk_id == 0) {
2142                                                 /* It is an object Id,
2143                                                  * We need to nuke the shrinkheader flags first
2144                                                  * Also need to clean up shadowing.
2145                                                  * We no longer want the shrink_header flag since its work is done
2146                                                  * and if it is left in place it will mess up scanning.
2147                                                  */
2148
2149                                                 struct yaffs_obj_hdr *oh;
2150                                                 oh = (struct yaffs_obj_hdr *)
2151                                                     buffer;
2152
2153                                                 oh->is_shrink = 0;
2154                                                 tags.extra_is_shrink = 0;
2155
2156                                                 oh->shadows_obj = 0;
2157                                                 oh->inband_shadowed_obj_id = 0;
2158                                                 tags.extra_shadows = 0;
2159
2160                                                 /* Update file size */
2161                                                 if (object->variant_type ==
2162                                                     YAFFS_OBJECT_TYPE_FILE) {
2163                                                         oh->file_size =
2164                                                             object->variant.
2165                                                             file_variant.
2166                                                             file_size;
2167                                                         tags.extra_length =
2168                                                             oh->file_size;
2169                                                 }
2170
2171                                                 yaffs_verify_oh(object, oh,
2172                                                                 &tags, 1);
2173                                                 new_chunk =
2174                                                     yaffs_write_new_chunk(dev,
2175                                                                           (u8 *)
2176                                                                           oh,
2177                                                                           &tags,
2178                                                                           1);
2179                                         } else {
2180                                                 new_chunk =
2181                                                     yaffs_write_new_chunk(dev,
2182                                                                           buffer,
2183                                                                           &tags,
2184                                                                           1);
2185                                         }
2186
2187                                         if (new_chunk < 0) {
2188                                                 ret_val = YAFFS_FAIL;
2189                                         } else {
2190
2191                                                 /* Ok, now fix up the Tnodes etc. */
2192
2193                                                 if (tags.chunk_id == 0) {
2194                                                         /* It's a header */
2195                                                         object->hdr_chunk =
2196                                                             new_chunk;
2197                                                         object->serial =
2198                                                             tags.serial_number;
2199                                                 } else {
2200                                                         /* It's a data chunk */
2201                                                         int ok;
2202                                                         ok = yaffs_put_chunk_in_file(object, tags.chunk_id, new_chunk, 0);
2203                                                 }
2204                                         }
2205                                 }
2206
2207                                 if (ret_val == YAFFS_OK)
2208                                         yaffs_chunk_del(dev, old_chunk,
2209                                                         mark_flash, __LINE__);
2210
2211                         }
2212                 }
2213
2214                 yaffs_release_temp_buffer(dev, buffer, __LINE__);
2215
2216         }
2217
2218         yaffs_verify_collected_blk(dev, bi, block);
2219
2220         if (bi->block_state == YAFFS_BLOCK_STATE_COLLECTING) {
2221                 /*
2222                  * The gc did not complete. Set block state back to FULL
2223                  * because checkpointing does not restore gc.
2224                  */
2225                 bi->block_state = YAFFS_BLOCK_STATE_FULL;
2226         } else {
2227                 /* The gc completed. */
2228                 /* Do any required cleanups */
2229                 for (i = 0; i < dev->n_clean_ups; i++) {
2230                         /* Time to delete the file too */
2231                         object =
2232                             yaffs_find_by_number(dev, dev->gc_cleanup_list[i]);
2233                         if (object) {
2234                                 yaffs_free_tnode(dev,
2235                                                  object->variant.
2236                                                  file_variant.top);
2237                                 object->variant.file_variant.top = NULL;
2238                                 T(YAFFS_TRACE_GC,
2239                                   (TSTR
2240                                    ("yaffs: About to finally delete object %d"
2241                                     TENDSTR), object->obj_id));
2242                                 yaffs_generic_obj_del(object);
2243                                 object->my_dev->n_deleted_files--;
2244                         }
2245
2246                 }
2247
2248                 chunks_after = yaffs_get_erased_chunks(dev);
2249                 if (chunks_before >= chunks_after) {
2250                         T(YAFFS_TRACE_GC,
2251                           (TSTR
2252                            ("gc did not increase free chunks before %d after %d"
2253                             TENDSTR), chunks_before, chunks_after));
2254                 }
2255                 dev->gc_block = 0;
2256                 dev->gc_chunk = 0;
2257                 dev->n_clean_ups = 0;
2258         }
2259
2260         dev->gc_disable = 0;
2261
2262         return ret_val;
2263 }
2264
2265 /*
2266  * FindBlockForgarbageCollection is used to select the dirtiest block (or close enough)
2267  * for garbage collection.
2268  */
2269
2270 static unsigned yaffs_find_gc_block(struct yaffs_dev *dev,
2271                                     int aggressive, int background)
2272 {
2273         int i;
2274         int iterations;
2275         unsigned selected = 0;
2276         int prioritised = 0;
2277         int prioritised_exist = 0;
2278         struct yaffs_block_info *bi;
2279         int threshold;
2280
2281         /* First let's see if we need to grab a prioritised block */
2282         if (dev->has_pending_prioritised_gc && !aggressive) {
2283                 dev->gc_dirtiest = 0;
2284                 bi = dev->block_info;
2285                 for (i = dev->internal_start_block;
2286                      i <= dev->internal_end_block && !selected; i++) {
2287
2288                         if (bi->gc_prioritise) {
2289                                 prioritised_exist = 1;
2290                                 if (bi->block_state == YAFFS_BLOCK_STATE_FULL &&
2291                                     yaffs_block_ok_for_gc(dev, bi)) {
2292                                         selected = i;
2293                                         prioritised = 1;
2294                                 }
2295                         }
2296                         bi++;
2297                 }
2298
2299                 /*
2300                  * If there is a prioritised block and none was selected then
2301                  * this happened because there is at least one old dirty block gumming
2302                  * up the works. Let's gc the oldest dirty block.
2303                  */
2304
2305                 if (prioritised_exist &&
2306                     !selected && dev->oldest_dirty_block > 0)
2307                         selected = dev->oldest_dirty_block;
2308
2309                 if (!prioritised_exist) /* None found, so we can clear this */
2310                         dev->has_pending_prioritised_gc = 0;
2311         }
2312
2313         /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2314          * search harder.
2315          * else (we're doing a leasurely gc), then we only bother to do this if the
2316          * block has only a few pages in use.
2317          */
2318
2319         if (!selected) {
2320                 int pages_used;
2321                 int n_blocks =
2322                     dev->internal_end_block - dev->internal_start_block + 1;
2323                 if (aggressive) {
2324                         threshold = dev->param.chunks_per_block;
2325                         iterations = n_blocks;
2326                 } else {
2327                         int max_threshold;
2328
2329                         if (background)
2330                                 max_threshold = dev->param.chunks_per_block / 2;
2331                         else
2332                                 max_threshold = dev->param.chunks_per_block / 8;
2333
2334                         if (max_threshold < YAFFS_GC_PASSIVE_THRESHOLD)
2335                                 max_threshold = YAFFS_GC_PASSIVE_THRESHOLD;
2336
2337                         threshold = background ? (dev->gc_not_done + 2) * 2 : 0;
2338                         if (threshold < YAFFS_GC_PASSIVE_THRESHOLD)
2339                                 threshold = YAFFS_GC_PASSIVE_THRESHOLD;
2340                         if (threshold > max_threshold)
2341                                 threshold = max_threshold;
2342
2343                         iterations = n_blocks / 16 + 1;
2344                         if (iterations > 100)
2345                                 iterations = 100;
2346                 }
2347
2348                 for (i = 0;
2349                      i < iterations &&
2350                      (dev->gc_dirtiest < 1 ||
2351                       dev->gc_pages_in_use > YAFFS_GC_GOOD_ENOUGH); i++) {
2352                         dev->gc_block_finder++;
2353                         if (dev->gc_block_finder < dev->internal_start_block ||
2354                             dev->gc_block_finder > dev->internal_end_block)
2355                                 dev->gc_block_finder =
2356                                     dev->internal_start_block;
2357
2358                         bi = yaffs_get_block_info(dev, dev->gc_block_finder);
2359
2360                         pages_used = bi->pages_in_use - bi->soft_del_pages;
2361
2362                         if (bi->block_state == YAFFS_BLOCK_STATE_FULL &&
2363                             pages_used < dev->param.chunks_per_block &&
2364                             (dev->gc_dirtiest < 1
2365                              || pages_used < dev->gc_pages_in_use)
2366                             && yaffs_block_ok_for_gc(dev, bi)) {
2367                                 dev->gc_dirtiest = dev->gc_block_finder;
2368                                 dev->gc_pages_in_use = pages_used;
2369                         }
2370                 }
2371
2372                 if (dev->gc_dirtiest > 0 && dev->gc_pages_in_use <= threshold)
2373                         selected = dev->gc_dirtiest;
2374         }
2375
2376         /*
2377          * If nothing has been selected for a while, try selecting the oldest dirty
2378          * because that's gumming up the works.
2379          */
2380
2381         if (!selected && dev->param.is_yaffs2 &&
2382             dev->gc_not_done >= (background ? 10 : 20)) {
2383                 yaffs2_find_oldest_dirty_seq(dev);
2384                 if (dev->oldest_dirty_block > 0) {
2385                         selected = dev->oldest_dirty_block;
2386                         dev->gc_dirtiest = selected;
2387                         dev->oldest_dirty_gc_count++;
2388                         bi = yaffs_get_block_info(dev, selected);
2389                         dev->gc_pages_in_use =
2390                             bi->pages_in_use - bi->soft_del_pages;
2391                 } else {
2392                         dev->gc_not_done = 0;
2393                 }
2394         }
2395
2396         if (selected) {
2397                 T(YAFFS_TRACE_GC,
2398                   (TSTR
2399                    ("GC Selected block %d with %d free, prioritised:%d"
2400                     TENDSTR), selected,
2401                    dev->param.chunks_per_block - dev->gc_pages_in_use,
2402                    prioritised));
2403
2404                 dev->n_gc_blocks++;
2405                 if (background)
2406                         dev->bg_gcs++;
2407
2408                 dev->gc_dirtiest = 0;
2409                 dev->gc_pages_in_use = 0;
2410                 dev->gc_not_done = 0;
2411                 if (dev->refresh_skip > 0)
2412                         dev->refresh_skip--;
2413         } else {
2414                 dev->gc_not_done++;
2415                 T(YAFFS_TRACE_GC,
2416                   (TSTR
2417                    ("GC none: finder %d skip %d threshold %d dirtiest %d using %d oldest %d%s"
2418                     TENDSTR), dev->gc_block_finder, dev->gc_not_done, threshold,
2419                    dev->gc_dirtiest, dev->gc_pages_in_use,
2420                    dev->oldest_dirty_block, background ? " bg" : ""));
2421         }
2422
2423         return selected;
2424 }
2425
2426 /* New garbage collector
2427  * If we're very low on erased blocks then we do aggressive garbage collection
2428  * otherwise we do "leasurely" garbage collection.
2429  * Aggressive gc looks further (whole array) and will accept less dirty blocks.
2430  * Passive gc only inspects smaller areas and will only accept more dirty blocks.
2431  *
2432  * The idea is to help clear out space in a more spread-out manner.
2433  * Dunno if it really does anything useful.
2434  */
2435 static int yaffs_check_gc(struct yaffs_dev *dev, int background)
2436 {
2437         int aggressive = 0;
2438         int gc_ok = YAFFS_OK;
2439         int max_tries = 0;
2440         int min_erased;
2441         int erased_chunks;
2442         int checkpt_block_adjust;
2443
2444         if (dev->param.gc_control && (dev->param.gc_control(dev) & 1) == 0)
2445                 return YAFFS_OK;
2446
2447         if (dev->gc_disable) {
2448                 /* Bail out so we don't get recursive gc */
2449                 return YAFFS_OK;
2450         }
2451
2452         /* This loop should pass the first time.
2453          * We'll only see looping here if the collection does not increase space.
2454          */
2455
2456         do {
2457                 max_tries++;
2458
2459                 checkpt_block_adjust = yaffs_calc_checkpt_blocks_required(dev);
2460
2461                 min_erased =
2462                     dev->param.n_reserved_blocks + checkpt_block_adjust + 1;
2463                 erased_chunks =
2464                     dev->n_erased_blocks * dev->param.chunks_per_block;
2465
2466                 /* If we need a block soon then do aggressive gc. */
2467                 if (dev->n_erased_blocks < min_erased)
2468                         aggressive = 1;
2469                 else {
2470                         if (!background
2471                             && erased_chunks > (dev->n_free_chunks / 4))
2472                                 break;
2473
2474                         if (dev->gc_skip > 20)
2475                                 dev->gc_skip = 20;
2476                         if (erased_chunks < dev->n_free_chunks / 2 ||
2477                             dev->gc_skip < 1 || background)
2478                                 aggressive = 0;
2479                         else {
2480                                 dev->gc_skip--;
2481                                 break;
2482                         }
2483                 }
2484
2485                 dev->gc_skip = 5;
2486
2487                 /* If we don't already have a block being gc'd then see if we should start another */
2488
2489                 if (dev->gc_block < 1 && !aggressive) {
2490                         dev->gc_block = yaffs2_find_refresh_block(dev);
2491                         dev->gc_chunk = 0;
2492                         dev->n_clean_ups = 0;
2493                 }
2494                 if (dev->gc_block < 1) {
2495                         dev->gc_block =
2496                             yaffs_find_gc_block(dev, aggressive, background);
2497                         dev->gc_chunk = 0;
2498                         dev->n_clean_ups = 0;
2499                 }
2500
2501                 if (dev->gc_block > 0) {
2502                         dev->all_gcs++;
2503                         if (!aggressive)
2504                                 dev->passive_gc_count++;
2505
2506                         T(YAFFS_TRACE_GC,
2507                           (TSTR
2508                            ("yaffs: GC n_erased_blocks %d aggressive %d"
2509                             TENDSTR), dev->n_erased_blocks, aggressive));
2510
2511                         gc_ok = yaffs_gc_block(dev, dev->gc_block, aggressive);
2512                 }
2513
2514                 if (dev->n_erased_blocks < (dev->param.n_reserved_blocks)
2515                     && dev->gc_block > 0) {
2516                         T(YAFFS_TRACE_GC,
2517                           (TSTR
2518                            ("yaffs: GC !!!no reclaim!!! n_erased_blocks %d after try %d block %d"
2519                             TENDSTR), dev->n_erased_blocks, max_tries,
2520                            dev->gc_block));
2521                 }
2522         } while ((dev->n_erased_blocks < dev->param.n_reserved_blocks) &&
2523                  (dev->gc_block > 0) && (max_tries < 2));
2524
2525         return aggressive ? gc_ok : YAFFS_OK;
2526 }
2527
2528 /*
2529  * yaffs_bg_gc()
2530  * Garbage collects. Intended to be called from a background thread.
2531  * Returns non-zero if at least half the free chunks are erased.
2532  */
2533 int yaffs_bg_gc(struct yaffs_dev *dev, unsigned urgency)
2534 {
2535         int erased_chunks = dev->n_erased_blocks * dev->param.chunks_per_block;
2536
2537         T(YAFFS_TRACE_BACKGROUND, (TSTR("Background gc %u" TENDSTR), urgency));
2538
2539         yaffs_check_gc(dev, 1);
2540         return erased_chunks > dev->n_free_chunks / 2;
2541 }
2542
2543 /*-------------------------  TAGS --------------------------------*/
2544
2545 static int yaffs_tags_match(const struct yaffs_ext_tags *tags, int obj_id,
2546                             int chunk_obj)
2547 {
2548         return (tags->chunk_id == chunk_obj &&
2549                 tags->obj_id == obj_id && !tags->is_deleted) ? 1 : 0;
2550
2551 }
2552
2553 /*-------------------- Data file manipulation -----------------*/
2554
2555 static int yaffs_find_chunk_in_file(struct yaffs_obj *in, int inode_chunk,
2556                                     struct yaffs_ext_tags *tags)
2557 {
2558         /*Get the Tnode, then get the level 0 offset chunk offset */
2559         struct yaffs_tnode *tn;
2560         int the_chunk = -1;
2561         struct yaffs_ext_tags local_tags;
2562         int ret_val = -1;
2563
2564         struct yaffs_dev *dev = in->my_dev;
2565
2566         if (!tags) {
2567                 /* Passed a NULL, so use our own tags space */
2568                 tags = &local_tags;
2569         }
2570
2571         tn = yaffs_find_tnode_0(dev, &in->variant.file_variant, inode_chunk);
2572
2573         if (tn) {
2574                 the_chunk = yaffs_get_group_base(dev, tn, inode_chunk);
2575
2576                 ret_val =
2577                     yaffs_find_chunk_in_group(dev, the_chunk, tags, in->obj_id,
2578                                               inode_chunk);
2579         }
2580         return ret_val;
2581 }
2582
2583 static int yaffs_find_del_file_chunk(struct yaffs_obj *in, int inode_chunk,
2584                                      struct yaffs_ext_tags *tags)
2585 {
2586         /* Get the Tnode, then get the level 0 offset chunk offset */
2587         struct yaffs_tnode *tn;
2588         int the_chunk = -1;
2589         struct yaffs_ext_tags local_tags;
2590
2591         struct yaffs_dev *dev = in->my_dev;
2592         int ret_val = -1;
2593
2594         if (!tags) {
2595                 /* Passed a NULL, so use our own tags space */
2596                 tags = &local_tags;
2597         }
2598
2599         tn = yaffs_find_tnode_0(dev, &in->variant.file_variant, inode_chunk);
2600
2601         if (tn) {
2602
2603                 the_chunk = yaffs_get_group_base(dev, tn, inode_chunk);
2604
2605                 ret_val =
2606                     yaffs_find_chunk_in_group(dev, the_chunk, tags, in->obj_id,
2607                                               inode_chunk);
2608
2609                 /* Delete the entry in the filestructure (if found) */
2610                 if (ret_val != -1)
2611                         yaffs_load_tnode_0(dev, tn, inode_chunk, 0);
2612         }
2613
2614         return ret_val;
2615 }
2616
2617 int yaffs_put_chunk_in_file(struct yaffs_obj *in, int inode_chunk,
2618                             int nand_chunk, int in_scan)
2619 {
2620         /* NB in_scan is zero unless scanning.
2621          * For forward scanning, in_scan is > 0;
2622          * for backward scanning in_scan is < 0
2623          *
2624          * nand_chunk = 0 is a dummy insert to make sure the tnodes are there.
2625          */
2626
2627         struct yaffs_tnode *tn;
2628         struct yaffs_dev *dev = in->my_dev;
2629         int existing_cunk;
2630         struct yaffs_ext_tags existing_tags;
2631         struct yaffs_ext_tags new_tags;
2632         unsigned existing_serial, new_serial;
2633
2634         if (in->variant_type != YAFFS_OBJECT_TYPE_FILE) {
2635                 /* Just ignore an attempt at putting a chunk into a non-file during scanning
2636                  * If it is not during Scanning then something went wrong!
2637                  */
2638                 if (!in_scan) {
2639                         T(YAFFS_TRACE_ERROR,
2640                           (TSTR
2641                            ("yaffs tragedy:attempt to put data chunk into a non-file"
2642                             TENDSTR)));
2643                         YBUG();
2644                 }
2645
2646                 yaffs_chunk_del(dev, nand_chunk, 1, __LINE__);
2647                 return YAFFS_OK;
2648         }
2649
2650         tn = yaffs_add_find_tnode_0(dev,
2651                                     &in->variant.file_variant,
2652                                     inode_chunk, NULL);
2653         if (!tn)
2654                 return YAFFS_FAIL;
2655
2656         if (!nand_chunk)
2657                 /* Dummy insert, bail now */
2658                 return YAFFS_OK;
2659
2660         existing_cunk = yaffs_get_group_base(dev, tn, inode_chunk);
2661
2662         if (in_scan != 0) {
2663                 /* If we're scanning then we need to test for duplicates
2664                  * NB This does not need to be efficient since it should only ever
2665                  * happen when the power fails during a write, then only one
2666                  * chunk should ever be affected.
2667                  *
2668                  * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
2669                  * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
2670                  */
2671
2672                 if (existing_cunk > 0) {
2673                         /* NB Right now existing chunk will not be real chunk_id if the chunk group size > 1
2674                          *    thus we have to do a FindChunkInFile to get the real chunk id.
2675                          *
2676                          * We have a duplicate now we need to decide which one to use:
2677                          *
2678                          * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
2679                          * Forward scanning YAFFS2: The new one is what we use, dump the old one.
2680                          * YAFFS1: Get both sets of tags and compare serial numbers.
2681                          */
2682
2683                         if (in_scan > 0) {
2684                                 /* Only do this for forward scanning */
2685                                 yaffs_rd_chunk_tags_nand(dev,
2686                                                          nand_chunk,
2687                                                          NULL, &new_tags);
2688
2689                                 /* Do a proper find */
2690                                 existing_cunk =
2691                                     yaffs_find_chunk_in_file(in, inode_chunk,
2692                                                              &existing_tags);
2693                         }
2694
2695                         if (existing_cunk <= 0) {
2696                                 /*Hoosterman - how did this happen? */
2697
2698                                 T(YAFFS_TRACE_ERROR,
2699                                   (TSTR
2700                                    ("yaffs tragedy: existing chunk < 0 in scan"
2701                                     TENDSTR)));
2702
2703                         }
2704
2705                         /* NB The deleted flags should be false, otherwise the chunks will
2706                          * not be loaded during a scan
2707                          */
2708
2709                         if (in_scan > 0) {
2710                                 new_serial = new_tags.serial_number;
2711                                 existing_serial = existing_tags.serial_number;
2712                         }
2713
2714                         if ((in_scan > 0) &&
2715                             (existing_cunk <= 0 ||
2716                              ((existing_serial + 1) & 3) == new_serial)) {
2717                                 /* Forward scanning.
2718                                  * Use new
2719                                  * Delete the old one and drop through to update the tnode
2720                                  */
2721                                 yaffs_chunk_del(dev, existing_cunk, 1,
2722                                                 __LINE__);
2723                         } else {
2724                                 /* Backward scanning or we want to use the existing one
2725                                  * Use existing.
2726                                  * Delete the new one and return early so that the tnode isn't changed
2727                                  */
2728                                 yaffs_chunk_del(dev, nand_chunk, 1, __LINE__);
2729                                 return YAFFS_OK;
2730                         }
2731                 }
2732
2733         }
2734
2735         if (existing_cunk == 0)
2736                 in->n_data_chunks++;
2737
2738         yaffs_load_tnode_0(dev, tn, inode_chunk, nand_chunk);
2739
2740         return YAFFS_OK;
2741 }
2742
2743 static int yaffs_rd_data_obj(struct yaffs_obj *in, int inode_chunk, u8 * buffer)
2744 {
2745         int nand_chunk = yaffs_find_chunk_in_file(in, inode_chunk, NULL);
2746
2747         if (nand_chunk >= 0)
2748                 return yaffs_rd_chunk_tags_nand(in->my_dev, nand_chunk,
2749                                                 buffer, NULL);
2750         else {
2751                 T(YAFFS_TRACE_NANDACCESS,
2752                   (TSTR("Chunk %d not found zero instead" TENDSTR),
2753                    nand_chunk));
2754                 /* get sane (zero) data if you read a hole */
2755                 memset(buffer, 0, in->my_dev->data_bytes_per_chunk);
2756                 return 0;
2757         }
2758
2759 }
2760
2761 void yaffs_chunk_del(struct yaffs_dev *dev, int chunk_id, int mark_flash,
2762                      int lyn)
2763 {
2764         int block;
2765         int page;
2766         struct yaffs_ext_tags tags;
2767         struct yaffs_block_info *bi;
2768
2769         if (chunk_id <= 0)
2770                 return;
2771
2772         dev->n_deletions++;
2773         block = chunk_id / dev->param.chunks_per_block;
2774         page = chunk_id % dev->param.chunks_per_block;
2775
2776         if (!yaffs_check_chunk_bit(dev, block, page))
2777                 T(YAFFS_TRACE_VERIFY,
2778                   (TSTR("Deleting invalid chunk %d" TENDSTR), chunk_id));
2779
2780         bi = yaffs_get_block_info(dev, block);
2781
2782         yaffs2_update_oldest_dirty_seq(dev, block, bi);
2783
2784         T(YAFFS_TRACE_DELETION,
2785           (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunk_id));
2786
2787         if (!dev->param.is_yaffs2 && mark_flash &&
2788             bi->block_state != YAFFS_BLOCK_STATE_COLLECTING) {
2789
2790                 yaffs_init_tags(&tags);
2791
2792                 tags.is_deleted = 1;
2793
2794                 yaffs_wr_chunk_tags_nand(dev, chunk_id, NULL, &tags);
2795                 yaffs_handle_chunk_update(dev, chunk_id, &tags);
2796         } else {
2797                 dev->n_unmarked_deletions++;
2798         }
2799
2800         /* Pull out of the management area.
2801          * If the whole block became dirty, this will kick off an erasure.
2802          */
2803         if (bi->block_state == YAFFS_BLOCK_STATE_ALLOCATING ||
2804             bi->block_state == YAFFS_BLOCK_STATE_FULL ||
2805             bi->block_state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
2806             bi->block_state == YAFFS_BLOCK_STATE_COLLECTING) {
2807                 dev->n_free_chunks++;
2808
2809                 yaffs_clear_chunk_bit(dev, block, page);
2810
2811                 bi->pages_in_use--;
2812
2813                 if (bi->pages_in_use == 0 &&
2814                     !bi->has_shrink_hdr &&
2815                     bi->block_state != YAFFS_BLOCK_STATE_ALLOCATING &&
2816                     bi->block_state != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
2817                         yaffs_block_became_dirty(dev, block);
2818                 }
2819
2820         }
2821
2822 }
2823
2824 static int yaffs_wr_data_obj(struct yaffs_obj *in, int inode_chunk,
2825                              const u8 * buffer, int n_bytes, int use_reserve)
2826 {
2827         /* Find old chunk Need to do this to get serial number
2828          * Write new one and patch into tree.
2829          * Invalidate old tags.
2830          */
2831
2832         int prev_chunk_id;
2833         struct yaffs_ext_tags prev_tags;
2834
2835         int new_chunk_id;
2836         struct yaffs_ext_tags new_tags;
2837
2838         struct yaffs_dev *dev = in->my_dev;
2839
2840         yaffs_check_gc(dev, 0);
2841
2842         /* Get the previous chunk at this location in the file if it exists.
2843          * If it does not exist then put a zero into the tree. This creates
2844          * the tnode now, rather than later when it is harder to clean up.
2845          */
2846         prev_chunk_id = yaffs_find_chunk_in_file(in, inode_chunk, &prev_tags);
2847         if (prev_chunk_id < 1 &&
2848             !yaffs_put_chunk_in_file(in, inode_chunk, 0, 0))
2849                 return 0;
2850
2851         /* Set up new tags */
2852         yaffs_init_tags(&new_tags);
2853
2854         new_tags.chunk_id = inode_chunk;
2855         new_tags.obj_id = in->obj_id;
2856         new_tags.serial_number =
2857             (prev_chunk_id > 0) ? prev_tags.serial_number + 1 : 1;
2858         new_tags.n_bytes = n_bytes;
2859
2860         if (n_bytes < 1 || n_bytes > dev->param.total_bytes_per_chunk) {
2861                 T(YAFFS_TRACE_ERROR,
2862                   (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR),
2863                    n_bytes));
2864                 YBUG();
2865         }
2866
2867         new_chunk_id =
2868             yaffs_write_new_chunk(dev, buffer, &new_tags, use_reserve);
2869
2870         if (new_chunk_id > 0) {
2871                 yaffs_put_chunk_in_file(in, inode_chunk, new_chunk_id, 0);
2872
2873                 if (prev_chunk_id > 0)
2874                         yaffs_chunk_del(dev, prev_chunk_id, 1, __LINE__);
2875
2876                 yaffs_verify_file_sane(in);
2877         }
2878         return new_chunk_id;
2879
2880 }
2881
2882 /* UpdateObjectHeader updates the header on NAND for an object.
2883  * If name is not NULL, then that new name is used.
2884  */
2885 int yaffs_update_oh(struct yaffs_obj *in, const YCHAR * name, int force,
2886                     int is_shrink, int shadows, struct yaffs_xattr_mod *xmod)
2887 {
2888
2889         struct yaffs_block_info *bi;
2890
2891         struct yaffs_dev *dev = in->my_dev;
2892
2893         int prev_chunk_id;
2894         int ret_val = 0;
2895         int result = 0;
2896
2897         int new_chunk_id;
2898         struct yaffs_ext_tags new_tags;
2899         struct yaffs_ext_tags old_tags;
2900         const YCHAR *alias = NULL;
2901
2902         u8 *buffer = NULL;
2903         YCHAR old_name[YAFFS_MAX_NAME_LENGTH + 1];
2904
2905         struct yaffs_obj_hdr *oh = NULL;
2906
2907         yaffs_strcpy(old_name, _Y("silly old name"));
2908
2909         if (!in->fake || in == dev->root_dir || /* The root_dir should also be saved */
2910             force || xmod) {
2911
2912                 yaffs_check_gc(dev, 0);
2913                 yaffs_check_obj_details_loaded(in);
2914
2915                 buffer = yaffs_get_temp_buffer(in->my_dev, __LINE__);
2916                 oh = (struct yaffs_obj_hdr *)buffer;
2917
2918                 prev_chunk_id = in->hdr_chunk;
2919
2920                 if (prev_chunk_id > 0) {
2921                         result = yaffs_rd_chunk_tags_nand(dev, prev_chunk_id,
2922                                                           buffer, &old_tags);
2923
2924                         yaffs_verify_oh(in, oh, &old_tags, 0);
2925
2926                         memcpy(old_name, oh->name, sizeof(oh->name));
2927                         memset(buffer, 0xFF, sizeof(struct yaffs_obj_hdr));
2928                 } else {
2929                         memset(buffer, 0xFF, dev->data_bytes_per_chunk);
2930                 }
2931
2932                 oh->type = in->variant_type;
2933                 oh->yst_mode = in->yst_mode;
2934                 oh->shadows_obj = oh->inband_shadowed_obj_id = shadows;
2935
2936                 yaffs_load_attribs_oh(oh, in);
2937
2938                 if (in->parent)
2939                         oh->parent_obj_id = in->parent->obj_id;
2940                 else
2941                         oh->parent_obj_id = 0;
2942
2943                 if (name && *name) {
2944                         memset(oh->name, 0, sizeof(oh->name));
2945                         yaffs_load_oh_from_name(dev, oh->name, name);
2946                 } else if (prev_chunk_id > 0) {
2947                         memcpy(oh->name, old_name, sizeof(oh->name));
2948                 } else {
2949                         memset(oh->name, 0, sizeof(oh->name));
2950                 }
2951
2952                 oh->is_shrink = is_shrink;
2953
2954                 switch (in->variant_type) {
2955                 case YAFFS_OBJECT_TYPE_UNKNOWN:
2956                         /* Should not happen */
2957                         break;
2958                 case YAFFS_OBJECT_TYPE_FILE:
2959                         oh->file_size =
2960                             (oh->parent_obj_id == YAFFS_OBJECTID_DELETED
2961                              || oh->parent_obj_id ==
2962                              YAFFS_OBJECTID_UNLINKED) ? 0 : in->
2963                             variant.file_variant.file_size;
2964                         break;
2965                 case YAFFS_OBJECT_TYPE_HARDLINK:
2966                         oh->equiv_id = in->variant.hardlink_variant.equiv_id;
2967                         break;
2968                 case YAFFS_OBJECT_TYPE_SPECIAL:
2969                         /* Do nothing */
2970                         break;
2971                 case YAFFS_OBJECT_TYPE_DIRECTORY:
2972                         /* Do nothing */
2973                         break;
2974                 case YAFFS_OBJECT_TYPE_SYMLINK:
2975                         alias = in->variant.symlink_variant.alias;
2976                         if (!alias)
2977                                 alias = _Y("no alias");
2978                         yaffs_strncpy(oh->alias, alias, YAFFS_MAX_ALIAS_LENGTH);
2979                         oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
2980                         break;
2981                 }
2982
2983                 /* process any xattrib modifications */
2984                 if (xmod)
2985                         yaffs_apply_xattrib_mod(in, (char *)buffer, xmod);
2986
2987                 /* Tags */
2988                 yaffs_init_tags(&new_tags);
2989                 in->serial++;
2990                 new_tags.chunk_id = 0;
2991                 new_tags.obj_id = in->obj_id;
2992                 new_tags.serial_number = in->serial;
2993
2994                 /* Add extra info for file header */
2995
2996                 new_tags.extra_available = 1;
2997                 new_tags.extra_parent_id = oh->parent_obj_id;
2998                 new_tags.extra_length = oh->file_size;
2999                 new_tags.extra_is_shrink = oh->is_shrink;
3000                 new_tags.extra_equiv_id = oh->equiv_id;
3001                 new_tags.extra_shadows = (oh->shadows_obj > 0) ? 1 : 0;
3002                 new_tags.extra_obj_type = in->variant_type;
3003
3004                 yaffs_verify_oh(in, oh, &new_tags, 1);
3005
3006                 /* Create new chunk in NAND */
3007                 new_chunk_id =
3008                     yaffs_write_new_chunk(dev, buffer, &new_tags,
3009                                           (prev_chunk_id > 0) ? 1 : 0);
3010
3011                 if (new_chunk_id >= 0) {
3012
3013                         in->hdr_chunk = new_chunk_id;
3014
3015                         if (prev_chunk_id > 0) {
3016                                 yaffs_chunk_del(dev, prev_chunk_id, 1,
3017                                                 __LINE__);
3018                         }
3019
3020                         if (!yaffs_obj_cache_dirty(in))
3021                                 in->dirty = 0;
3022
3023                         /* If this was a shrink, then mark the block that the chunk lives on */
3024                         if (is_shrink) {
3025                                 bi = yaffs_get_block_info(in->my_dev,
3026                                                           new_chunk_id /
3027                                                           in->my_dev->param.
3028                                                           chunks_per_block);
3029                                 bi->has_shrink_hdr = 1;
3030                         }
3031
3032                 }
3033
3034                 ret_val = new_chunk_id;
3035
3036         }
3037
3038         if (buffer)
3039                 yaffs_release_temp_buffer(dev, buffer, __LINE__);
3040
3041         return ret_val;
3042 }
3043
3044 /*------------------------ Short Operations Cache ----------------------------------------
3045  *   In many situations where there is no high level buffering  a lot of
3046  *   reads might be short sequential reads, and a lot of writes may be short
3047  *   sequential writes. eg. scanning/writing a jpeg file.
3048  *   In these cases, a short read/write cache can provide a huge perfomance
3049  *   benefit with dumb-as-a-rock code.
3050  *   In Linux, the page cache provides read buffering and the short op cache 
3051  *   provides write buffering.
3052  *
3053  *   There are a limited number (~10) of cache chunks per device so that we don't
3054  *   need a very intelligent search.
3055  */
3056
3057 static int yaffs_obj_cache_dirty(struct yaffs_obj *obj)
3058 {
3059         struct yaffs_dev *dev = obj->my_dev;
3060         int i;
3061         struct yaffs_cache *cache;
3062         int n_caches = obj->my_dev->param.n_caches;
3063
3064         for (i = 0; i < n_caches; i++) {
3065                 cache = &dev->cache[i];
3066                 if (cache->object == obj && cache->dirty)
3067                         return 1;
3068         }
3069
3070         return 0;
3071 }
3072
3073 static void yaffs_flush_file_cache(struct yaffs_obj *obj)
3074 {
3075         struct yaffs_dev *dev = obj->my_dev;
3076         int lowest = -99;       /* Stop compiler whining. */
3077         int i;
3078         struct yaffs_cache *cache;
3079         int chunk_written = 0;
3080         int n_caches = obj->my_dev->param.n_caches;
3081
3082         if (n_caches > 0) {
3083                 do {
3084                         cache = NULL;
3085
3086                         /* Find the dirty cache for this object with the lowest chunk id. */
3087                         for (i = 0; i < n_caches; i++) {
3088                                 if (dev->cache[i].object == obj &&
3089                                     dev->cache[i].dirty) {
3090                                         if (!cache
3091                                             || dev->cache[i].chunk_id <
3092                                             lowest) {
3093                                                 cache = &dev->cache[i];
3094                                                 lowest = cache->chunk_id;
3095                                         }
3096                                 }
3097                         }
3098
3099                         if (cache && !cache->locked) {
3100                                 /* Write it out and free it up */
3101
3102                                 chunk_written =
3103                                     yaffs_wr_data_obj(cache->object,
3104                                                       cache->chunk_id,
3105                                                       cache->data,
3106                                                       cache->n_bytes, 1);
3107                                 cache->dirty = 0;
3108                                 cache->object = NULL;
3109                         }
3110
3111                 } while (cache && chunk_written > 0);
3112
3113                 if (cache) {
3114                         /* Hoosterman, disk full while writing cache out. */
3115                         T(YAFFS_TRACE_ERROR,
3116                           (TSTR
3117                            ("yaffs tragedy: no space during cache write"
3118                             TENDSTR)));
3119
3120                 }
3121         }
3122
3123 }
3124
3125 /*yaffs_flush_whole_cache(dev)
3126  *
3127  *
3128  */
3129
3130 void yaffs_flush_whole_cache(struct yaffs_dev *dev)
3131 {
3132         struct yaffs_obj *obj;
3133         int n_caches = dev->param.n_caches;
3134         int i;
3135
3136         /* Find a dirty object in the cache and flush it...
3137          * until there are no further dirty objects.
3138          */
3139         do {
3140                 obj = NULL;
3141                 for (i = 0; i < n_caches && !obj; i++) {
3142                         if (dev->cache[i].object && dev->cache[i].dirty)
3143                                 obj = dev->cache[i].object;
3144
3145                 }
3146                 if (obj)
3147                         yaffs_flush_file_cache(obj);
3148
3149         } while (obj);
3150
3151 }
3152
3153 /* Grab us a cache chunk for use.
3154  * First look for an empty one.
3155  * Then look for the least recently used non-dirty one.
3156  * Then look for the least recently used dirty one...., flush and look again.
3157  */
3158 static struct yaffs_cache *yaffs_grab_chunk_worker(struct yaffs_dev *dev)
3159 {
3160         int i;
3161
3162         if (dev->param.n_caches > 0) {
3163                 for (i = 0; i < dev->param.n_caches; i++) {
3164                         if (!dev->cache[i].object)
3165                                 return &dev->cache[i];
3166                 }
3167         }
3168
3169         return NULL;
3170 }
3171
3172 static struct yaffs_cache *yaffs_grab_chunk_cache(struct yaffs_dev *dev)
3173 {
3174         struct yaffs_cache *cache;
3175         struct yaffs_obj *the_obj;
3176         int usage;
3177         int i;
3178         int pushout;
3179
3180         if (dev->param.n_caches > 0) {
3181                 /* Try find a non-dirty one... */
3182
3183                 cache = yaffs_grab_chunk_worker(dev);
3184
3185                 if (!cache) {
3186                         /* They were all dirty, find the last recently used object and flush
3187                          * its cache, then  find again.
3188                          * NB what's here is not very accurate, we actually flush the object
3189                          * the last recently used page.
3190                          */
3191
3192                         /* With locking we can't assume we can use entry zero */
3193
3194                         the_obj = NULL;
3195                         usage = -1;
3196                         cache = NULL;
3197                         pushout = -1;
3198
3199                         for (i = 0; i < dev->param.n_caches; i++) {
3200                                 if (dev->cache[i].object &&
3201                                     !dev->cache[i].locked &&
3202                                     (dev->cache[i].last_use < usage
3203                                      || !cache)) {
3204                                         usage = dev->cache[i].last_use;
3205                                         the_obj = dev->cache[i].object;
3206                                         cache = &dev->cache[i];
3207                                         pushout = i;
3208                                 }
3209                         }
3210
3211                         if (!cache || cache->dirty) {
3212                                 /* Flush and try again */
3213                                 yaffs_flush_file_cache(the_obj);
3214                                 cache = yaffs_grab_chunk_worker(dev);
3215                         }
3216
3217                 }
3218                 return cache;
3219         } else {
3220                 return NULL;
3221         }
3222 }
3223
3224 /* Find a cached chunk */
3225 static struct yaffs_cache *yaffs_find_chunk_cache(const struct yaffs_obj *obj,
3226                                                   int chunk_id)
3227 {
3228         struct yaffs_dev *dev = obj->my_dev;
3229         int i;
3230         if (dev->param.n_caches > 0) {
3231                 for (i = 0; i < dev->param.n_caches; i++) {
3232                         if (dev->cache[i].object == obj &&
3233                             dev->cache[i].chunk_id == chunk_id) {
3234                                 dev->cache_hits++;
3235
3236                                 return &dev->cache[i];
3237                         }
3238                 }
3239         }
3240         return NULL;
3241 }
3242
3243 /* Mark the chunk for the least recently used algorithym */
3244 static void yaffs_use_cache(struct yaffs_dev *dev, struct yaffs_cache *cache,
3245                             int is_write)
3246 {
3247
3248         if (dev->param.n_caches > 0) {
3249                 if (dev->cache_last_use < 0 || dev->cache_last_use > 100000000) {
3250                         /* Reset the cache usages */
3251                         int i;
3252                         for (i = 1; i < dev->param.n_caches; i++)
3253                                 dev->cache[i].last_use = 0;
3254
3255                         dev->cache_last_use = 0;
3256                 }
3257
3258                 dev->cache_last_use++;
3259
3260                 cache->last_use = dev->cache_last_use;
3261
3262                 if (is_write)
3263                         cache->dirty = 1;
3264         }
3265 }
3266
3267 /* Invalidate a single cache page.
3268  * Do this when a whole page gets written,
3269  * ie the short cache for this page is no longer valid.
3270  */
3271 static void yaffs_invalidate_chunk_cache(struct yaffs_obj *object, int chunk_id)
3272 {
3273         if (object->my_dev->param.n_caches > 0) {
3274                 struct yaffs_cache *cache =
3275                     yaffs_find_chunk_cache(object, chunk_id);
3276
3277                 if (cache)
3278                         cache->object = NULL;
3279         }
3280 }
3281
3282 /* Invalidate all the cache pages associated with this object
3283  * Do this whenever ther file is deleted or resized.
3284  */
3285 static void yaffs_invalidate_whole_cache(struct yaffs_obj *in)
3286 {
3287         int i;
3288         struct yaffs_dev *dev = in->my_dev;
3289
3290         if (dev->param.n_caches > 0) {
3291                 /* Invalidate it. */
3292                 for (i = 0; i < dev->param.n_caches; i++) {
3293                         if (dev->cache[i].object == in)
3294                                 dev->cache[i].object = NULL;
3295                 }
3296         }
3297 }
3298
3299 /*--------------------- File read/write ------------------------
3300  * Read and write have very similar structures.
3301  * In general the read/write has three parts to it
3302  * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3303  * Some complete chunks
3304  * An incomplete chunk to end off with
3305  *
3306  * Curve-balls: the first chunk might also be the last chunk.
3307  */
3308
3309 int yaffs_file_rd(struct yaffs_obj *in, u8 * buffer, loff_t offset, int n_bytes)
3310 {
3311
3312         int chunk;
3313         u32 start;
3314         int n_copy;
3315         int n = n_bytes;
3316         int n_done = 0;
3317         struct yaffs_cache *cache;
3318
3319         struct yaffs_dev *dev;
3320
3321         dev = in->my_dev;
3322
3323         while (n > 0) {
3324                 /* chunk = offset / dev->data_bytes_per_chunk + 1; */
3325                 /* start = offset % dev->data_bytes_per_chunk; */
3326                 yaffs_addr_to_chunk(dev, offset, &chunk, &start);
3327                 chunk++;
3328
3329                 /* OK now check for the curveball where the start and end are in
3330                  * the same chunk.
3331                  */
3332                 if ((start + n) < dev->data_bytes_per_chunk)
3333                         n_copy = n;
3334                 else
3335                         n_copy = dev->data_bytes_per_chunk - start;
3336
3337                 cache = yaffs_find_chunk_cache(in, chunk);
3338
3339                 /* If the chunk is already in the cache or it is less than a whole chunk
3340                  * or we're using inband tags then use the cache (if there is caching)
3341                  * else bypass the cache.
3342                  */
3343                 if (cache || n_copy != dev->data_bytes_per_chunk
3344                     || dev->param.inband_tags) {
3345                         if (dev->param.n_caches > 0) {
3346
3347                                 /* If we can't find the data in the cache, then load it up. */
3348
3349                                 if (!cache) {
3350                                         cache =
3351                                             yaffs_grab_chunk_cache(in->my_dev);
3352                                         cache->object = in;
3353                                         cache->chunk_id = chunk;
3354                                         cache->dirty = 0;
3355                                         cache->locked = 0;
3356                                         yaffs_rd_data_obj(in, chunk,
3357                                                           cache->data);
3358                                         cache->n_bytes = 0;
3359                                 }
3360
3361                                 yaffs_use_cache(dev, cache, 0);
3362
3363                                 cache->locked = 1;
3364
3365                                 memcpy(buffer, &cache->data[start], n_copy);
3366
3367                                 cache->locked = 0;
3368                         } else {
3369                                 /* Read into the local buffer then copy.. */
3370
3371                                 u8 *local_buffer =
3372                                     yaffs_get_temp_buffer(dev, __LINE__);
3373                                 yaffs_rd_data_obj(in, chunk, local_buffer);
3374
3375                                 memcpy(buffer, &local_buffer[start], n_copy);
3376
3377                                 yaffs_release_temp_buffer(dev, local_buffer,
3378                                                           __LINE__);
3379                         }
3380
3381                 } else {
3382
3383                         /* A full chunk. Read directly into the supplied buffer. */
3384                         yaffs_rd_data_obj(in, chunk, buffer);
3385
3386                 }
3387
3388                 n -= n_copy;
3389                 offset += n_copy;
3390                 buffer += n_copy;
3391                 n_done += n_copy;
3392
3393         }
3394
3395         return n_done;
3396 }
3397
3398 int yaffs_do_file_wr(struct yaffs_obj *in, const u8 * buffer, loff_t offset,
3399                      int n_bytes, int write_trhrough)
3400 {
3401
3402         int chunk;
3403         u32 start;
3404         int n_copy;
3405         int n = n_bytes;
3406         int n_done = 0;
3407         int n_writeback;
3408         int start_write = offset;
3409         int chunk_written = 0;
3410         u32 n_bytes_read;
3411         u32 chunk_start;
3412
3413         struct yaffs_dev *dev;
3414
3415         dev = in->my_dev;
3416
3417         while (n > 0 && chunk_written >= 0) {
3418                 yaffs_addr_to_chunk(dev, offset, &chunk, &start);
3419
3420                 if (chunk * dev->data_bytes_per_chunk + start != offset ||
3421                     start >= dev->data_bytes_per_chunk) {
3422                         T(YAFFS_TRACE_ERROR,
3423                           (TSTR
3424                            ("AddrToChunk of offset %d gives chunk %d start %d"
3425                             TENDSTR), (int)offset, chunk, start));
3426                 }
3427                 chunk++;        /* File pos to chunk in file offset */
3428
3429                 /* OK now check for the curveball where the start and end are in
3430                  * the same chunk.
3431                  */
3432
3433                 if ((start + n) < dev->data_bytes_per_chunk) {
3434                         n_copy = n;
3435
3436                         /* Now folks, to calculate how many bytes to write back....
3437                          * If we're overwriting and not writing to then end of file then
3438                          * we need to write back as much as was there before.
3439                          */
3440
3441                         chunk_start = ((chunk - 1) * dev->data_bytes_per_chunk);
3442
3443                         if (chunk_start > in->variant.file_variant.file_size)
3444                                 n_bytes_read = 0;       /* Past end of file */
3445                         else
3446                                 n_bytes_read =
3447                                     in->variant.file_variant.file_size -
3448                                     chunk_start;
3449
3450                         if (n_bytes_read > dev->data_bytes_per_chunk)
3451                                 n_bytes_read = dev->data_bytes_per_chunk;
3452
3453                         n_writeback =
3454                             (n_bytes_read >
3455                              (start + n)) ? n_bytes_read : (start + n);
3456
3457                         if (n_writeback < 0
3458                             || n_writeback > dev->data_bytes_per_chunk)
3459                                 YBUG();
3460
3461                 } else {
3462                         n_copy = dev->data_bytes_per_chunk - start;
3463                         n_writeback = dev->data_bytes_per_chunk;
3464                 }
3465
3466                 if (n_copy != dev->data_bytes_per_chunk
3467                     || dev->param.inband_tags) {
3468                         /* An incomplete start or end chunk (or maybe both start and end chunk),
3469                          * or we're using inband tags, so we want to use the cache buffers.
3470                          */
3471                         if (dev->param.n_caches > 0) {
3472                                 struct yaffs_cache *cache;
3473                                 /* If we can't find the data in the cache, then load the cache */
3474                                 cache = yaffs_find_chunk_cache(in, chunk);
3475
3476                                 if (!cache
3477                                     && yaffs_check_alloc_available(dev, 1)) {
3478                                         cache = yaffs_grab_chunk_cache(dev);
3479                                         cache->object = in;
3480                                         cache->chunk_id = chunk;
3481                                         cache->dirty = 0;
3482                                         cache->locked = 0;
3483                                         yaffs_rd_data_obj(in, chunk,
3484                                                           cache->data);
3485                                 } else if (cache &&
3486                                            !cache->dirty &&
3487                                            !yaffs_check_alloc_available(dev,
3488                                                                         1)) {
3489                                         /* Drop the cache if it was a read cache item and
3490                                          * no space check has been made for it.
3491                                          */
3492                                         cache = NULL;
3493                                 }
3494
3495                                 if (cache) {
3496                                         yaffs_use_cache(dev, cache, 1);
3497                                         cache->locked = 1;
3498
3499                                         memcpy(&cache->data[start], buffer,
3500                                                n_copy);
3501
3502                                         cache->locked = 0;
3503                                         cache->n_bytes = n_writeback;
3504
3505                                         if (write_trhrough) {
3506                                                 chunk_written =
3507                                                     yaffs_wr_data_obj
3508                                                     (cache->object,
3509                                                      cache->chunk_id,
3510                                                      cache->data,
3511                                                      cache->n_bytes, 1);
3512                                                 cache->dirty = 0;
3513                                         }
3514
3515                                 } else {
3516                                         chunk_written = -1;     /* fail the write */
3517                                 }
3518                         } else {
3519                                 /* An incomplete start or end chunk (or maybe both start and end chunk)
3520                                  * Read into the local buffer then copy, then copy over and write back.
3521                                  */
3522
3523                                 u8 *local_buffer =
3524                                     yaffs_get_temp_buffer(dev, __LINE__);
3525
3526                                 yaffs_rd_data_obj(in, chunk, local_buffer);
3527
3528                                 memcpy(&local_buffer[start], buffer, n_copy);
3529
3530                                 chunk_written =
3531                                     yaffs_wr_data_obj(in, chunk,
3532                                                       local_buffer,
3533                                                       n_writeback, 0);
3534
3535                                 yaffs_release_temp_buffer(dev, local_buffer,
3536                                                           __LINE__);
3537
3538                         }
3539
3540                 } else {
3541                         /* A full chunk. Write directly from the supplied buffer. */
3542
3543                         chunk_written =
3544                             yaffs_wr_data_obj(in, chunk, buffer,
3545                                               dev->data_bytes_per_chunk, 0);
3546
3547                         /* Since we've overwritten the cached data, we better invalidate it. */
3548                         yaffs_invalidate_chunk_cache(in, chunk);
3549                 }
3550
3551                 if (chunk_written >= 0) {
3552                         n -= n_copy;
3553                         offset += n_copy;
3554                         buffer += n_copy;
3555                         n_done += n_copy;
3556                 }
3557
3558         }
3559
3560         /* Update file object */
3561
3562         if ((start_write + n_done) > in->variant.file_variant.file_size)
3563                 in->variant.file_variant.file_size = (start_write + n_done);
3564
3565         in->dirty = 1;
3566
3567         return n_done;
3568 }
3569
3570 int yaffs_wr_file(struct yaffs_obj *in, const u8 * buffer, loff_t offset,
3571                   int n_bytes, int write_trhrough)
3572 {
3573         yaffs2_handle_hole(in, offset);
3574         return yaffs_do_file_wr(in, buffer, offset, n_bytes, write_trhrough);
3575 }
3576
3577 /* ---------------------- File resizing stuff ------------------ */
3578
3579 static void yaffs_prune_chunks(struct yaffs_obj *in, int new_size)
3580 {
3581
3582         struct yaffs_dev *dev = in->my_dev;
3583         int old_size = in->variant.file_variant.file_size;
3584
3585         int last_del = 1 + (old_size - 1) / dev->data_bytes_per_chunk;
3586
3587         int start_del = 1 + (new_size + dev->data_bytes_per_chunk - 1) /
3588             dev->data_bytes_per_chunk;
3589         int i;
3590         int chunk_id;
3591
3592         /* Delete backwards so that we don't end up with holes if
3593          * power is lost part-way through the operation.
3594          */
3595         for (i = last_del; i >= start_del; i--) {
3596                 /* NB this could be optimised somewhat,
3597                  * eg. could retrieve the tags and write them without
3598                  * using yaffs_chunk_del
3599                  */
3600
3601                 chunk_id = yaffs_find_del_file_chunk(in, i, NULL);
3602                 if (chunk_id > 0) {
3603                         if (chunk_id <
3604                             (dev->internal_start_block *
3605                              dev->param.chunks_per_block)
3606                             || chunk_id >=
3607                             ((dev->internal_end_block +
3608                               1) * dev->param.chunks_per_block)) {
3609                                 T(YAFFS_TRACE_ALWAYS,
3610                                   (TSTR
3611                                    ("Found daft chunk_id %d for %d" TENDSTR),
3612                                    chunk_id, i));
3613                         } else {
3614                                 in->n_data_chunks--;
3615                                 yaffs_chunk_del(dev, chunk_id, 1, __LINE__);
3616                         }
3617                 }
3618         }
3619
3620 }
3621
3622 void yaffs_resize_file_down(struct yaffs_obj *obj, loff_t new_size)
3623 {
3624         int new_full;
3625         u32 new_partial;
3626         struct yaffs_dev *dev = obj->my_dev;
3627
3628         yaffs_addr_to_chunk(dev, new_size, &new_full, &new_partial);
3629
3630         yaffs_prune_chunks(obj, new_size);
3631
3632         if (new_partial != 0) {
3633                 int last_chunk = 1 + new_full;
3634                 u8 *local_buffer = yaffs_get_temp_buffer(dev, __LINE__);
3635
3636                 /* Got to read and rewrite the last chunk with its new size and zero pad */
3637                 yaffs_rd_data_obj(obj, last_chunk, local_buffer);
3638                 memset(local_buffer + new_partial, 0,
3639                        dev->data_bytes_per_chunk - new_partial);
3640
3641                 yaffs_wr_data_obj(obj, last_chunk, local_buffer,
3642                                   new_partial, 1);
3643
3644                 yaffs_release_temp_buffer(dev, local_buffer, __LINE__);
3645         }
3646
3647         obj->variant.file_variant.file_size = new_size;
3648
3649         yaffs_prune_tree(dev, &obj->variant.file_variant);
3650 }
3651
3652 int yaffs_resize_file(struct yaffs_obj *in, loff_t new_size)
3653 {
3654         struct yaffs_dev *dev = in->my_dev;
3655         int old_size = in->variant.file_variant.file_size;
3656
3657         yaffs_flush_file_cache(in);
3658         yaffs_invalidate_whole_cache(in);
3659
3660         yaffs_check_gc(dev, 0);
3661
3662         if (in->variant_type != YAFFS_OBJECT_TYPE_FILE)
3663                 return YAFFS_FAIL;
3664
3665         if (new_size == old_size)
3666                 return YAFFS_OK;
3667
3668         if (new_size > old_size) {
3669                 yaffs2_handle_hole(in, new_size);
3670                 in->variant.file_variant.file_size = new_size;
3671         } else {
3672                 /* new_size < old_size */
3673                 yaffs_resize_file_down(in, new_size);
3674         }
3675
3676         /* Write a new object header to reflect the resize.
3677          * show we've shrunk the file, if need be
3678          * Do this only if the file is not in the deleted directories
3679          * and is not shadowed.
3680          */
3681         if (in->parent &&
3682             !in->is_shadowed &&
3683             in->parent->obj_id != YAFFS_OBJECTID_UNLINKED &&
3684             in->parent->obj_id != YAFFS_OBJECTID_DELETED)
3685                 yaffs_update_oh(in, NULL, 0, 0, 0, NULL);
3686
3687         return YAFFS_OK;
3688 }
3689
3690 int yaffs_flush_file(struct yaffs_obj *in, int update_time, int data_sync)
3691 {
3692         int ret_val;
3693         if (in->dirty) {
3694                 yaffs_flush_file_cache(in);
3695                 if (data_sync)  /* Only sync data */
3696                         ret_val = YAFFS_OK;
3697                 else {
3698                         if (update_time)
3699                                 yaffs_load_current_time(in, 0, 0);
3700
3701                         ret_val = (yaffs_update_oh(in, NULL, 0, 0, 0, NULL) >=
3702                                    0) ? YAFFS_OK : YAFFS_FAIL;
3703                 }
3704         } else {
3705                 ret_val = YAFFS_OK;
3706         }
3707
3708         return ret_val;
3709
3710 }
3711
3712 static int yaffs_generic_obj_del(struct yaffs_obj *in)
3713 {
3714
3715         /* First off, invalidate the file's data in the cache, without flushing. */
3716         yaffs_invalidate_whole_cache(in);
3717
3718         if (in->my_dev->param.is_yaffs2 && (in->parent != in->my_dev->del_dir)) {
3719                 /* Move to the unlinked directory so we have a record that it was deleted. */
3720                 yaffs_change_obj_name(in, in->my_dev->del_dir, _Y("deleted"), 0,
3721                                       0);
3722
3723         }
3724
3725         yaffs_remove_obj_from_dir(in);
3726         yaffs_chunk_del(in->my_dev, in->hdr_chunk, 1, __LINE__);
3727         in->hdr_chunk = 0;
3728
3729         yaffs_free_obj(in);
3730         return YAFFS_OK;
3731
3732 }
3733
3734 /* yaffs_del_file deletes the whole file data
3735  * and the inode associated with the file.
3736  * It does not delete the links associated with the file.
3737  */
3738 static int yaffs_unlink_file_if_needed(struct yaffs_obj *in)
3739 {
3740
3741         int ret_val;
3742         int del_now = 0;
3743         struct yaffs_dev *dev = in->my_dev;
3744
3745         if (!in->my_inode)
3746                 del_now = 1;
3747
3748         if (del_now) {
3749                 ret_val =
3750                     yaffs_change_obj_name(in, in->my_dev->del_dir,
3751                                           _Y("deleted"), 0, 0);
3752                 T(YAFFS_TRACE_TRACING,
3753                   (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
3754                    in->obj_id));
3755                 in->deleted = 1;
3756                 in->my_dev->n_deleted_files++;
3757                 if (dev->param.disable_soft_del || dev->param.is_yaffs2)
3758                         yaffs_resize_file(in, 0);
3759                 yaffs_soft_del_file(in);
3760         } else {
3761                 ret_val =
3762                     yaffs_change_obj_name(in, in->my_dev->unlinked_dir,
3763                                           _Y("unlinked"), 0, 0);
3764         }
3765
3766         return ret_val;
3767 }
3768
3769 int yaffs_del_file(struct yaffs_obj *in)
3770 {
3771         int ret_val = YAFFS_OK;
3772         int deleted;            /* Need to cache value on stack if in is freed */
3773         struct yaffs_dev *dev = in->my_dev;
3774
3775         if (dev->param.disable_soft_del || dev->param.is_yaffs2)
3776                 yaffs_resize_file(in, 0);
3777
3778         if (in->n_data_chunks > 0) {
3779                 /* Use soft deletion if there is data in the file.
3780                  * That won't be the case if it has been resized to zero.
3781                  */
3782                 if (!in->unlinked)
3783                         ret_val = yaffs_unlink_file_if_needed(in);
3784
3785                 deleted = in->deleted;
3786
3787                 if (ret_val == YAFFS_OK && in->unlinked && !in->deleted) {
3788                         in->deleted = 1;
3789                         deleted = 1;
3790                         in->my_dev->n_deleted_files++;
3791                         yaffs_soft_del_file(in);
3792                 }
3793                 return deleted ? YAFFS_OK : YAFFS_FAIL;
3794         } else {
3795                 /* The file has no data chunks so we toss it immediately */
3796                 yaffs_free_tnode(in->my_dev, in->variant.file_variant.top);
3797                 in->variant.file_variant.top = NULL;
3798                 yaffs_generic_obj_del(in);
3799
3800                 return YAFFS_OK;
3801         }
3802 }
3803
3804 static int yaffs_is_non_empty_dir(struct yaffs_obj *obj)
3805 {
3806         return (obj->variant_type == YAFFS_OBJECT_TYPE_DIRECTORY) &&
3807             !(list_empty(&obj->variant.dir_variant.children));
3808 }
3809
3810 static int yaffs_del_dir(struct yaffs_obj *obj)
3811 {
3812         /* First check that the directory is empty. */
3813         if (yaffs_is_non_empty_dir(obj))
3814                 return YAFFS_FAIL;
3815
3816         return yaffs_generic_obj_del(obj);
3817 }
3818
3819 static int yaffs_del_symlink(struct yaffs_obj *in)
3820 {
3821         if (in->variant.symlink_variant.alias)
3822                 YFREE(in->variant.symlink_variant.alias);
3823         in->variant.symlink_variant.alias = NULL;
3824
3825         return yaffs_generic_obj_del(in);
3826 }
3827
3828 static int yaffs_del_link(struct yaffs_obj *in)
3829 {
3830         /* remove this hardlink from the list assocaited with the equivalent
3831          * object
3832          */
3833         list_del_init(&in->hard_links);
3834         return yaffs_generic_obj_del(in);
3835 }
3836
3837 int yaffs_del_obj(struct yaffs_obj *obj)
3838 {
3839         int ret_val = -1;
3840         switch (obj->variant_type) {
3841         case YAFFS_OBJECT_TYPE_FILE:
3842                 ret_val = yaffs_del_file(obj);
3843                 break;
3844         case YAFFS_OBJECT_TYPE_DIRECTORY:
3845                 if (!list_empty(&obj->variant.dir_variant.dirty)) {
3846                         T(YAFFS_TRACE_BACKGROUND,
3847                           (TSTR
3848                            ("Remove object %d from dirty directories" TENDSTR),
3849                            obj->obj_id));
3850                         list_del_init(&obj->variant.dir_variant.dirty);
3851                 }
3852                 return yaffs_del_dir(obj);
3853                 break;
3854         case YAFFS_OBJECT_TYPE_SYMLINK:
3855                 ret_val = yaffs_del_symlink(obj);
3856                 break;
3857         case YAFFS_OBJECT_TYPE_HARDLINK:
3858                 ret_val = yaffs_del_link(obj);
3859                 break;
3860         case YAFFS_OBJECT_TYPE_SPECIAL:
3861                 ret_val = yaffs_generic_obj_del(obj);
3862                 break;
3863         case YAFFS_OBJECT_TYPE_UNKNOWN:
3864                 ret_val = 0;
3865                 break;          /* should not happen. */
3866         }
3867
3868         return ret_val;
3869 }
3870
3871 static int yaffs_unlink_worker(struct yaffs_obj *obj)
3872 {
3873
3874         int del_now = 0;
3875
3876         if (!obj->my_inode)
3877                 del_now = 1;
3878
3879         if (obj)
3880                 yaffs_update_parent(obj->parent);
3881
3882         if (obj->variant_type == YAFFS_OBJECT_TYPE_HARDLINK) {
3883                 return yaffs_del_link(obj);
3884         } else if (!list_empty(&obj->hard_links)) {
3885                 /* Curve ball: We're unlinking an object that has a hardlink.
3886                  *
3887                  * This problem arises because we are not strictly following
3888                  * The Linux link/inode model.
3889                  *
3890                  * We can't really delete the object.
3891                  * Instead, we do the following:
3892                  * - Select a hardlink.
3893                  * - Unhook it from the hard links
3894                  * - Move it from its parent directory (so that the rename can work)
3895                  * - Rename the object to the hardlink's name.
3896                  * - Delete the hardlink
3897                  */
3898
3899                 struct yaffs_obj *hl;
3900                 struct yaffs_obj *parent;
3901                 int ret_val;
3902                 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
3903
3904                 hl = list_entry(obj->hard_links.next, struct yaffs_obj,
3905                                 hard_links);
3906
3907                 yaffs_get_obj_name(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
3908                 parent = hl->parent;
3909
3910                 list_del_init(&hl->hard_links);
3911
3912                 yaffs_add_obj_to_dir(obj->my_dev->unlinked_dir, hl);
3913
3914                 ret_val = yaffs_change_obj_name(obj, parent, name, 0, 0);
3915
3916                 if (ret_val == YAFFS_OK)
3917                         ret_val = yaffs_generic_obj_del(hl);
3918
3919                 return ret_val;
3920
3921         } else if (del_now) {
3922                 switch (obj->variant_type) {
3923                 case YAFFS_OBJECT_TYPE_FILE:
3924                         return yaffs_del_file(obj);
3925                         break;
3926                 case YAFFS_OBJECT_TYPE_DIRECTORY:
3927                         list_del_init(&obj->variant.dir_variant.dirty);
3928                         return yaffs_del_dir(obj);
3929                         break;
3930                 case YAFFS_OBJECT_TYPE_SYMLINK:
3931                         return yaffs_del_symlink(obj);
3932                         break;
3933                 case YAFFS_OBJECT_TYPE_SPECIAL:
3934                         return yaffs_generic_obj_del(obj);
3935                         break;
3936                 case YAFFS_OBJECT_TYPE_HARDLINK:
3937                 case YAFFS_OBJECT_TYPE_UNKNOWN:
3938                 default:
3939                         return YAFFS_FAIL;
3940                 }
3941         } else if (yaffs_is_non_empty_dir(obj)) {
3942                 return YAFFS_FAIL;
3943         } else {
3944                 return yaffs_change_obj_name(obj, obj->my_dev->unlinked_dir,
3945                                              _Y("unlinked"), 0, 0);
3946         }
3947 }
3948
3949 static int yaffs_unlink_obj(struct yaffs_obj *obj)
3950 {
3951
3952         if (obj && obj->unlink_allowed)
3953                 return yaffs_unlink_worker(obj);
3954
3955         return YAFFS_FAIL;
3956
3957 }
3958
3959 int yaffs_unlinker(struct yaffs_obj *dir, const YCHAR * name)
3960 {
3961         struct yaffs_obj *obj;
3962
3963         obj = yaffs_find_by_name(dir, name);
3964         return yaffs_unlink_obj(obj);
3965 }
3966
3967 /*----------------------- Initialisation Scanning ---------------------- */
3968
3969 void yaffs_handle_shadowed_obj(struct yaffs_dev *dev, int obj_id,
3970                                int backward_scanning)
3971 {
3972         struct yaffs_obj *obj;
3973
3974         if (!backward_scanning) {
3975                 /* Handle YAFFS1 forward scanning case
3976                  * For YAFFS1 we always do the deletion
3977                  */
3978
3979         } else {
3980                 /* Handle YAFFS2 case (backward scanning)
3981                  * If the shadowed object exists then ignore.
3982                  */
3983                 obj = yaffs_find_by_number(dev, obj_id);
3984                 if (obj)
3985                         return;
3986         }
3987
3988         /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
3989          * We put it in unlinked dir to be cleaned up after the scanning
3990          */
3991         obj =
3992             yaffs_find_or_create_by_number(dev, obj_id, YAFFS_OBJECT_TYPE_FILE);
3993         if (!obj)
3994                 return;
3995         obj->is_shadowed = 1;
3996         yaffs_add_obj_to_dir(dev->unlinked_dir, obj);
3997         obj->variant.file_variant.shrink_size = 0;
3998         obj->valid = 1;         /* So that we don't read any other info for this file */
3999
4000 }
4001
4002 void yaffs_link_fixup(struct yaffs_dev *dev, struct yaffs_obj *hard_list)
4003 {
4004         struct yaffs_obj *hl;
4005         struct yaffs_obj *in;
4006
4007         while (hard_list) {
4008                 hl = hard_list;
4009                 hard_list = (struct yaffs_obj *)(hard_list->hard_links.next);
4010
4011                 in = yaffs_find_by_number(dev,
4012                                           hl->variant.
4013                                           hardlink_variant.equiv_id);
4014
4015                 if (in) {
4016                         /* Add the hardlink pointers */
4017                         hl->variant.hardlink_variant.equiv_obj = in;
4018                         list_add(&hl->hard_links, &in->hard_links);
4019                 } else {
4020                         /* Todo Need to report/handle this better.
4021                          * Got a problem... hardlink to a non-existant object
4022                          */
4023                         hl->variant.hardlink_variant.equiv_obj = NULL;
4024                         INIT_LIST_HEAD(&hl->hard_links);
4025
4026                 }
4027         }
4028 }
4029
4030 static void yaffs_strip_deleted_objs(struct yaffs_dev *dev)
4031 {
4032         /*
4033          *  Sort out state of unlinked and deleted objects after scanning.
4034          */
4035         struct list_head *i;
4036         struct list_head *n;
4037         struct yaffs_obj *l;
4038
4039         if (dev->read_only)
4040                 return;
4041
4042         /* Soft delete all the unlinked files */
4043         list_for_each_safe(i, n,
4044                            &dev->unlinked_dir->variant.dir_variant.children) {
4045                 if (i) {
4046                         l = list_entry(i, struct yaffs_obj, siblings);
4047                         yaffs_del_obj(l);
4048                 }
4049         }
4050
4051         list_for_each_safe(i, n, &dev->del_dir->variant.dir_variant.children) {
4052                 if (i) {
4053                         l = list_entry(i, struct yaffs_obj, siblings);
4054                         yaffs_del_obj(l);
4055                 }
4056         }
4057
4058 }
4059
4060 /*
4061  * This code iterates through all the objects making sure that they are rooted.
4062  * Any unrooted objects are re-rooted in lost+found.
4063  * An object needs to be in one of:
4064  * - Directly under deleted, unlinked
4065  * - Directly or indirectly under root.
4066  *
4067  * Note:
4068  *  This code assumes that we don't ever change the current relationships between
4069  *  directories:
4070  *   root_dir->parent == unlinked_dir->parent == del_dir->parent == NULL
4071  *   lost-n-found->parent == root_dir
4072  *
4073  * This fixes the problem where directories might have inadvertently been deleted
4074  * leaving the object "hanging" without being rooted in the directory tree.
4075  */
4076
4077 static int yaffs_has_null_parent(struct yaffs_dev *dev, struct yaffs_obj *obj)
4078 {
4079         return (obj == dev->del_dir ||
4080                 obj == dev->unlinked_dir || obj == dev->root_dir);
4081 }
4082
4083 static void yaffs_fix_hanging_objs(struct yaffs_dev *dev)
4084 {
4085         struct yaffs_obj *obj;
4086         struct yaffs_obj *parent;
4087         int i;
4088         struct list_head *lh;
4089         struct list_head *n;
4090         int depth_limit;
4091         int hanging;
4092
4093         if (dev->read_only)
4094                 return;
4095
4096         /* Iterate through the objects in each hash entry,
4097          * looking at each object.
4098          * Make sure it is rooted.
4099          */
4100
4101         for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
4102                 list_for_each_safe(lh, n, &dev->obj_bucket[i].list) {
4103                         if (lh) {
4104                                 obj =
4105                                     list_entry(lh, struct yaffs_obj, hash_link);
4106                                 parent = obj->parent;
4107
4108                                 if (yaffs_has_null_parent(dev, obj)) {
4109                                         /* These directories are not hanging */
4110                                         hanging = 0;
4111                                 } else if (!parent
4112                                            || parent->variant_type !=
4113                                            YAFFS_OBJECT_TYPE_DIRECTORY) {
4114                                         hanging = 1;
4115                                 } else if (yaffs_has_null_parent(dev, parent)) {
4116                                         hanging = 0;
4117                                 } else {
4118                                         /*
4119                                          * Need to follow the parent chain to see if it is hanging.
4120                                          */
4121                                         hanging = 0;
4122                                         depth_limit = 100;
4123
4124                                         while (parent != dev->root_dir &&
4125                                                parent->parent &&
4126                                                parent->parent->variant_type ==
4127                                                YAFFS_OBJECT_TYPE_DIRECTORY
4128                                                && depth_limit > 0) {
4129                                                 parent = parent->parent;
4130                                                 depth_limit--;
4131                                         }
4132                                         if (parent != dev->root_dir)
4133                                                 hanging = 1;
4134                                 }
4135                                 if (hanging) {
4136                                         T(YAFFS_TRACE_SCAN,
4137                                           (TSTR
4138                                            ("Hanging object %d moved to lost and found"
4139                                             TENDSTR), obj->obj_id));
4140                                         yaffs_add_obj_to_dir(dev->lost_n_found,
4141                                                              obj);
4142                                 }
4143                         }
4144                 }
4145         }
4146 }
4147
4148 /*
4149  * Delete directory contents for cleaning up lost and found.
4150  */
4151 static void yaffs_del_dir_contents(struct yaffs_obj *dir)
4152 {
4153         struct yaffs_obj *obj;
4154         struct list_head *lh;
4155         struct list_head *n;
4156
4157         if (dir->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY)
4158                 YBUG();
4159
4160         list_for_each_safe(lh, n, &dir->variant.dir_variant.children) {
4161                 if (lh) {
4162                         obj = list_entry(lh, struct yaffs_obj, siblings);
4163                         if (obj->variant_type == YAFFS_OBJECT_TYPE_DIRECTORY)
4164                                 yaffs_del_dir_contents(obj);
4165
4166                         T(YAFFS_TRACE_SCAN,
4167                           (TSTR("Deleting lost_found object %d" TENDSTR),
4168                            obj->obj_id));
4169
4170                         /* Need to use UnlinkObject since Delete would not handle
4171                          * hardlinked objects correctly.
4172                          */
4173                         yaffs_unlink_obj(obj);
4174                 }
4175         }
4176
4177 }
4178
4179 static void yaffs_empty_l_n_f(struct yaffs_dev *dev)
4180 {
4181         yaffs_del_dir_contents(dev->lost_n_found);
4182 }
4183
4184 static void yaffs_check_obj_details_loaded(struct yaffs_obj *in)
4185 {
4186         u8 *chunk_data;
4187         struct yaffs_obj_hdr *oh;
4188         struct yaffs_dev *dev;
4189         struct yaffs_ext_tags tags;
4190         int result;
4191         int alloc_failed = 0;
4192
4193         if (!in)
4194                 return;
4195
4196         dev = in->my_dev;
4197
4198         if (in->lazy_loaded && in->hdr_chunk > 0) {
4199                 in->lazy_loaded = 0;
4200                 chunk_data = yaffs_get_temp_buffer(dev, __LINE__);
4201
4202                 result =
4203                     yaffs_rd_chunk_tags_nand(dev, in->hdr_chunk, chunk_data,
4204                                              &tags);
4205                 oh = (struct yaffs_obj_hdr *)chunk_data;
4206
4207                 in->yst_mode = oh->yst_mode;
4208                 yaffs_load_attribs(in, oh);
4209                 yaffs_set_obj_name_from_oh(in, oh);
4210
4211                 if (in->variant_type == YAFFS_OBJECT_TYPE_SYMLINK) {
4212                         in->variant.symlink_variant.alias =
4213                             yaffs_clone_str(oh->alias);
4214                         if (!in->variant.symlink_variant.alias)
4215                                 alloc_failed = 1;       /* Not returned to caller */
4216                 }
4217
4218                 yaffs_release_temp_buffer(dev, chunk_data, __LINE__);
4219         }
4220 }
4221
4222 /*------------------------------  Directory Functions ----------------------------- */
4223
4224 /*
4225  *yaffs_update_parent() handles fixing a directories mtime and ctime when a new
4226  * link (ie. name) is created or deleted in the directory.
4227  *
4228  * ie.
4229  *   create dir/a : update dir's mtime/ctime
4230  *   rm dir/a:   update dir's mtime/ctime
4231  *   modify dir/a: don't update dir's mtimme/ctime
4232  *
4233  * This can be handled immediately or defered. Defering helps reduce the number
4234  * of updates when many files in a directory are changed within a brief period.
4235  *
4236  * If the directory updating is defered then yaffs_update_dirty_dirs must be
4237  * called periodically.
4238  */
4239
4240 static void yaffs_update_parent(struct yaffs_obj *obj)
4241 {
4242         struct yaffs_dev *dev;
4243         if (!obj)
4244                 return;
4245         dev = obj->my_dev;
4246         obj->dirty = 1;
4247         yaffs_load_current_time(obj, 0, 1);
4248         if (dev->param.defered_dir_update) {
4249                 struct list_head *link = &obj->variant.dir_variant.dirty;
4250
4251                 if (list_empty(link)) {
4252                         list_add(link, &dev->dirty_dirs);
4253                         T(YAFFS_TRACE_BACKGROUND,
4254                           (TSTR("Added object %d to dirty directories" TENDSTR),
4255                            obj->obj_id));
4256                 }
4257
4258         } else {
4259                 yaffs_update_oh(obj, NULL, 0, 0, 0, NULL);
4260         }
4261 }
4262
4263 void yaffs_update_dirty_dirs(struct yaffs_dev *dev)
4264 {
4265         struct list_head *link;
4266         struct yaffs_obj *obj;
4267         struct yaffs_dir_var *d_s;
4268         union yaffs_obj_var *o_v;
4269
4270         T(YAFFS_TRACE_BACKGROUND, (TSTR("Update dirty directories" TENDSTR)));
4271
4272         while (!list_empty(&dev->dirty_dirs)) {
4273                 link = dev->dirty_dirs.next;
4274                 list_del_init(link);
4275
4276                 d_s = list_entry(link, struct yaffs_dir_var, dirty);
4277                 o_v = list_entry(d_s, union yaffs_obj_var, dir_variant);
4278                 obj = list_entry(o_v, struct yaffs_obj, variant);
4279
4280                 T(YAFFS_TRACE_BACKGROUND,
4281                   (TSTR("Update directory %d" TENDSTR), obj->obj_id));
4282
4283                 if (obj->dirty)
4284                         yaffs_update_oh(obj, NULL, 0, 0, 0, NULL);
4285         }
4286 }
4287
4288 static void yaffs_remove_obj_from_dir(struct yaffs_obj *obj)
4289 {
4290         struct yaffs_dev *dev = obj->my_dev;
4291         struct yaffs_obj *parent;
4292
4293         yaffs_verify_obj_in_dir(obj);
4294         parent = obj->parent;
4295
4296         yaffs_verify_dir(parent);
4297
4298         if (dev && dev->param.remove_obj_fn)
4299                 dev->param.remove_obj_fn(obj);
4300
4301         list_del_init(&obj->siblings);
4302         obj->parent = NULL;
4303
4304         yaffs_verify_dir(parent);
4305 }
4306
4307 void yaffs_add_obj_to_dir(struct yaffs_obj *directory, struct yaffs_obj *obj)
4308 {
4309         if (!directory) {
4310                 T(YAFFS_TRACE_ALWAYS,
4311                   (TSTR
4312                    ("tragedy: Trying to add an object to a null pointer directory"
4313                     TENDSTR)));
4314                 YBUG();
4315                 return;
4316         }
4317         if (directory->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY) {
4318                 T(YAFFS_TRACE_ALWAYS,
4319                   (TSTR
4320                    ("tragedy: Trying to add an object to a non-directory"
4321                     TENDSTR)));
4322                 YBUG();
4323         }
4324
4325         if (obj->siblings.prev == NULL) {
4326                 /* Not initialised */
4327                 YBUG();
4328         }
4329
4330         yaffs_verify_dir(directory);
4331
4332         yaffs_remove_obj_from_dir(obj);
4333
4334         /* Now add it */
4335         list_add(&obj->siblings, &directory->variant.dir_variant.children);
4336         obj->parent = directory;
4337
4338         if (directory == obj->my_dev->unlinked_dir
4339             || directory == obj->my_dev->del_dir) {
4340                 obj->unlinked = 1;
4341                 obj->my_dev->n_unlinked_files++;
4342                 obj->rename_allowed = 0;
4343         }
4344
4345         yaffs_verify_dir(directory);
4346         yaffs_verify_obj_in_dir(obj);
4347 }
4348
4349 struct yaffs_obj *yaffs_find_by_name(struct yaffs_obj *directory,
4350                                      const YCHAR * name)
4351 {
4352         int sum;
4353
4354         struct list_head *i;
4355         YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
4356
4357         struct yaffs_obj *l;
4358
4359         if (!name)
4360                 return NULL;
4361
4362         if (!directory) {
4363                 T(YAFFS_TRACE_ALWAYS,
4364                   (TSTR
4365                    ("tragedy: yaffs_find_by_name: null pointer directory"
4366                     TENDSTR)));
4367                 YBUG();
4368                 return NULL;
4369         }
4370         if (directory->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY) {
4371                 T(YAFFS_TRACE_ALWAYS,
4372                   (TSTR("tragedy: yaffs_find_by_name: non-directory" TENDSTR)));
4373                 YBUG();
4374         }
4375
4376         sum = yaffs_calc_name_sum(name);
4377
4378         list_for_each(i, &directory->variant.dir_variant.children) {
4379                 if (i) {
4380                         l = list_entry(i, struct yaffs_obj, siblings);
4381
4382                         if (l->parent != directory)
4383                                 YBUG();
4384
4385                         yaffs_check_obj_details_loaded(l);
4386
4387                         /* Special case for lost-n-found */
4388                         if (l->obj_id == YAFFS_OBJECTID_LOSTNFOUND) {
4389                                 if (!yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME))
4390                                         return l;
4391                         } else if (yaffs_sum_cmp(l->sum, sum)
4392                                    || l->hdr_chunk <= 0) {
4393                                 /* LostnFound chunk called Objxxx
4394                                  * Do a real check
4395                                  */
4396                                 yaffs_get_obj_name(l, buffer,
4397                                                    YAFFS_MAX_NAME_LENGTH + 1);
4398                                 if (yaffs_strncmp
4399                                     (name, buffer, YAFFS_MAX_NAME_LENGTH) == 0)
4400                                         return l;
4401                         }
4402                 }
4403         }
4404
4405         return NULL;
4406 }
4407
4408 /* GetEquivalentObject dereferences any hard links to get to the
4409  * actual object.
4410  */
4411
4412 struct yaffs_obj *yaffs_get_equivalent_obj(struct yaffs_obj *obj)
4413 {
4414         if (obj && obj->variant_type == YAFFS_OBJECT_TYPE_HARDLINK) {
4415                 /* We want the object id of the equivalent object, not this one */
4416                 obj = obj->variant.hardlink_variant.equiv_obj;
4417                 yaffs_check_obj_details_loaded(obj);
4418         }
4419         return obj;
4420 }
4421
4422 /*
4423  *  A note or two on object names.
4424  *  * If the object name is missing, we then make one up in the form objnnn
4425  *
4426  *  * ASCII names are stored in the object header's name field from byte zero
4427  *  * Unicode names are historically stored starting from byte zero.
4428  *
4429  * Then there are automatic Unicode names...
4430  * The purpose of these is to save names in a way that can be read as
4431  * ASCII or Unicode names as appropriate, thus allowing a Unicode and ASCII
4432  * system to share files.
4433  *
4434  * These automatic unicode are stored slightly differently...
4435  *  - If the name can fit in the ASCII character space then they are saved as 
4436  *    ascii names as per above.
4437  *  - If the name needs Unicode then the name is saved in Unicode
4438  *    starting at oh->name[1].
4439
4440  */
4441 static void yaffs_fix_null_name(struct yaffs_obj *obj, YCHAR * name,
4442                                 int buffer_size)
4443 {
4444         /* Create an object name if we could not find one. */
4445         if (yaffs_strnlen(name, YAFFS_MAX_NAME_LENGTH) == 0) {
4446                 YCHAR local_name[20];
4447                 YCHAR num_string[20];
4448                 YCHAR *x = &num_string[19];
4449                 unsigned v = obj->obj_id;
4450                 num_string[19] = 0;
4451                 while (v > 0) {
4452                         x--;
4453                         *x = '0' + (v % 10);
4454                         v /= 10;
4455                 }
4456                 /* make up a name */
4457                 yaffs_strcpy(local_name, YAFFS_LOSTNFOUND_PREFIX);
4458                 yaffs_strcat(local_name, x);
4459                 yaffs_strncpy(name, local_name, buffer_size - 1);
4460         }
4461 }
4462
4463 static void yaffs_load_name_from_oh(struct yaffs_dev *dev, YCHAR * name,
4464                                     const YCHAR * oh_name, int buff_size)
4465 {
4466 #ifdef CONFIG_YAFFS_AUTO_UNICODE
4467         if (dev->param.auto_unicode) {
4468                 if (*oh_name) {
4469                         /* It is an ASCII name, so do an ASCII to unicode conversion */
4470                         const char *ascii_oh_name = (const char *)oh_name;
4471                         int n = buff_size - 1;
4472                         while (n > 0 && *ascii_oh_name) {
4473                                 *name = *ascii_oh_name;
4474                                 name++;
4475                                 ascii_oh_name++;
4476                                 n--;
4477                         }
4478                 } else {
4479                         yaffs_strncpy(name, oh_name + 1, buff_size - 1);
4480                 }
4481         } else {
4482 #else
4483         {
4484 #endif
4485                 yaffs_strncpy(name, oh_name, buff_size - 1);
4486         }
4487 }
4488
4489 static void yaffs_load_oh_from_name(struct yaffs_dev *dev, YCHAR * oh_name,
4490                                     const YCHAR * name)
4491 {
4492 #ifdef CONFIG_YAFFS_AUTO_UNICODE
4493
4494         int is_ascii;
4495         YCHAR *w;
4496
4497         if (dev->param.auto_unicode) {
4498
4499                 is_ascii = 1;
4500                 w = name;
4501
4502                 /* Figure out if the name will fit in ascii character set */
4503                 while (is_ascii && *w) {
4504                         if ((*w) & 0xff00)
4505                                 is_ascii = 0;
4506                         w++;
4507                 }
4508
4509                 if (is_ascii) {
4510                         /* It is an ASCII name, so do a unicode to ascii conversion */
4511                         char *ascii_oh_name = (char *)oh_name;
4512                         int n = YAFFS_MAX_NAME_LENGTH - 1;
4513                         while (n > 0 && *name) {
4514                                 *ascii_oh_name = *name;
4515                                 name++;
4516                                 ascii_oh_name++;
4517                                 n--;
4518                         }
4519                 } else {
4520                         /* It is a unicode name, so save starting at the second YCHAR */
4521                         *oh_name = 0;
4522                         yaffs_strncpy(oh_name + 1, name,
4523                                       YAFFS_MAX_NAME_LENGTH - 2);
4524                 }
4525         } else {
4526 #else
4527         {
4528 #endif
4529                 yaffs_strncpy(oh_name, name, YAFFS_MAX_NAME_LENGTH - 1);
4530         }
4531
4532 }
4533
4534 int yaffs_get_obj_name(struct yaffs_obj *obj, YCHAR * name, int buffer_size)
4535 {
4536         memset(name, 0, buffer_size * sizeof(YCHAR));
4537
4538         yaffs_check_obj_details_loaded(obj);
4539
4540         if (obj->obj_id == YAFFS_OBJECTID_LOSTNFOUND) {
4541                 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffer_size - 1);
4542         }
4543 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
4544         else if (obj->short_name[0]) {
4545                 yaffs_strcpy(name, obj->short_name);
4546         }
4547 #endif
4548         else if (obj->hdr_chunk > 0) {
4549                 int result;
4550                 u8 *buffer = yaffs_get_temp_buffer(obj->my_dev, __LINE__);
4551
4552                 struct yaffs_obj_hdr *oh = (struct yaffs_obj_hdr *)buffer;
4553
4554                 memset(buffer, 0, obj->my_dev->data_bytes_per_chunk);
4555
4556                 if (obj->hdr_chunk > 0) {
4557                         result = yaffs_rd_chunk_tags_nand(obj->my_dev,
4558                                                           obj->hdr_chunk,
4559                                                           buffer, NULL);
4560                 }
4561                 yaffs_load_name_from_oh(obj->my_dev, name, oh->name,
4562                                         buffer_size);
4563
4564                 yaffs_release_temp_buffer(obj->my_dev, buffer, __LINE__);
4565         }
4566
4567         yaffs_fix_null_name(obj, name, buffer_size);
4568
4569         return yaffs_strnlen(name, YAFFS_MAX_NAME_LENGTH);
4570 }
4571
4572 int yaffs_get_obj_length(struct yaffs_obj *obj)
4573 {
4574         /* Dereference any hard linking */
4575         obj = yaffs_get_equivalent_obj(obj);
4576
4577         if (obj->variant_type == YAFFS_OBJECT_TYPE_FILE)
4578                 return obj->variant.file_variant.file_size;
4579         if (obj->variant_type == YAFFS_OBJECT_TYPE_SYMLINK) {
4580                 if (!obj->variant.symlink_variant.alias)
4581                         return 0;
4582                 return yaffs_strnlen(obj->variant.symlink_variant.alias,
4583                                      YAFFS_MAX_ALIAS_LENGTH);
4584         } else {
4585                 /* Only a directory should drop through to here */
4586                 return obj->my_dev->data_bytes_per_chunk;
4587         }
4588 }
4589
4590 int yaffs_get_obj_link_count(struct yaffs_obj *obj)
4591 {
4592         int count = 0;
4593         struct list_head *i;
4594
4595         if (!obj->unlinked)
4596                 count++;        /* the object itself */
4597
4598         list_for_each(i, &obj->hard_links)
4599             count++;            /* add the hard links; */
4600
4601         return count;
4602 }
4603
4604 int yaffs_get_obj_inode(struct yaffs_obj *obj)
4605 {
4606         obj = yaffs_get_equivalent_obj(obj);
4607
4608         return obj->obj_id;
4609 }
4610
4611 unsigned yaffs_get_obj_type(struct yaffs_obj *obj)
4612 {
4613         obj = yaffs_get_equivalent_obj(obj);
4614
4615         switch (obj->variant_type) {
4616         case YAFFS_OBJECT_TYPE_FILE:
4617                 return DT_REG;
4618                 break;
4619         case YAFFS_OBJECT_TYPE_DIRECTORY:
4620                 return DT_DIR;
4621                 break;
4622         case YAFFS_OBJECT_TYPE_SYMLINK:
4623                 return DT_LNK;
4624                 break;
4625         case YAFFS_OBJECT_TYPE_HARDLINK:
4626                 return DT_REG;
4627                 break;
4628         case YAFFS_OBJECT_TYPE_SPECIAL:
4629                 if (S_ISFIFO(obj->yst_mode))
4630                         return DT_FIFO;
4631                 if (S_ISCHR(obj->yst_mode))
4632                         return DT_CHR;
4633                 if (S_ISBLK(obj->yst_mode))
4634                         return DT_BLK;
4635                 if (S_ISSOCK(obj->yst_mode))
4636                         return DT_SOCK;
4637         default:
4638                 return DT_REG;
4639                 break;
4640         }
4641 }
4642
4643 YCHAR *yaffs_get_symlink_alias(struct yaffs_obj *obj)
4644 {
4645         obj = yaffs_get_equivalent_obj(obj);
4646         if (obj->variant_type == YAFFS_OBJECT_TYPE_SYMLINK)
4647                 return yaffs_clone_str(obj->variant.symlink_variant.alias);
4648         else
4649                 return yaffs_clone_str(_Y(""));
4650 }
4651
4652 static int yaffs_do_xattrib_mod(struct yaffs_obj *obj, int set,
4653                                 const YCHAR * name, const void *value, int size,
4654                                 int flags)
4655 {
4656         struct yaffs_xattr_mod xmod;
4657
4658         int result;
4659
4660         xmod.set = set;
4661         xmod.name = name;
4662         xmod.data = value;
4663         xmod.size = size;
4664         xmod.flags = flags;
4665         xmod.result = -ENOSPC;
4666
4667         result = yaffs_update_oh(obj, NULL, 0, 0, 0, &xmod);
4668
4669         if (result > 0)
4670                 return xmod.result;
4671         else
4672                 return -ENOSPC;
4673 }
4674
4675 static int yaffs_apply_xattrib_mod(struct yaffs_obj *obj, char *buffer,
4676                                    struct yaffs_xattr_mod *xmod)
4677 {
4678         int retval = 0;
4679         int x_offs = sizeof(struct yaffs_obj_hdr);
4680         struct yaffs_dev *dev = obj->my_dev;
4681         int x_size = dev->data_bytes_per_chunk - sizeof(struct yaffs_obj_hdr);
4682
4683         char *x_buffer = buffer + x_offs;
4684
4685         if (xmod->set)
4686                 retval =
4687                     nval_set(x_buffer, x_size, xmod->name, xmod->data,
4688                              xmod->size, xmod->flags);
4689         else
4690                 retval = nval_del(x_buffer, x_size, xmod->name);
4691
4692         obj->has_xattr = nval_hasvalues(x_buffer, x_size);
4693         obj->xattr_known = 1;
4694
4695         xmod->result = retval;
4696
4697         return retval;
4698 }
4699
4700 static int yaffs_do_xattrib_fetch(struct yaffs_obj *obj, const YCHAR * name,
4701                                   void *value, int size)
4702 {
4703         char *buffer = NULL;
4704         int result;
4705         struct yaffs_ext_tags tags;
4706         struct yaffs_dev *dev = obj->my_dev;
4707         int x_offs = sizeof(struct yaffs_obj_hdr);
4708         int x_size = dev->data_bytes_per_chunk - sizeof(struct yaffs_obj_hdr);
4709
4710         char *x_buffer;
4711
4712         int retval = 0;
4713
4714         if (obj->hdr_chunk < 1)
4715                 return -ENODATA;
4716
4717         /* If we know that the object has no xattribs then don't do all the
4718          * reading and parsing.
4719          */
4720         if (obj->xattr_known && !obj->has_xattr) {
4721                 if (name)
4722                         return -ENODATA;
4723                 else
4724                         return 0;
4725         }
4726
4727         buffer = (char *)yaffs_get_temp_buffer(dev, __LINE__);
4728         if (!buffer)
4729                 return -ENOMEM;
4730
4731         result =
4732             yaffs_rd_chunk_tags_nand(dev, obj->hdr_chunk, (u8 *) buffer, &tags);
4733
4734         if (result != YAFFS_OK)
4735                 retval = -ENOENT;
4736         else {
4737                 x_buffer = buffer + x_offs;
4738
4739                 if (!obj->xattr_known) {
4740                         obj->has_xattr = nval_hasvalues(x_buffer, x_size);
4741                         obj->xattr_known = 1;
4742                 }
4743
4744                 if (name)
4745                         retval = nval_get(x_buffer, x_size, name, value, size);
4746                 else
4747                         retval = nval_list(x_buffer, x_size, value, size);
4748         }
4749         yaffs_release_temp_buffer(dev, (u8 *) buffer, __LINE__);
4750         return retval;
4751 }
4752
4753 int yaffs_set_xattrib(struct yaffs_obj *obj, const YCHAR * name,
4754                       const void *value, int size, int flags)
4755 {
4756         return yaffs_do_xattrib_mod(obj, 1, name, value, size, flags);
4757 }
4758
4759 int yaffs_remove_xattrib(struct yaffs_obj *obj, const YCHAR * name)
4760 {
4761         return yaffs_do_xattrib_mod(obj, 0, name, NULL, 0, 0);
4762 }
4763
4764 int yaffs_get_xattrib(struct yaffs_obj *obj, const YCHAR * name, void *value,
4765                       int size)
4766 {
4767         return yaffs_do_xattrib_fetch(obj, name, value, size);
4768 }
4769
4770 int yaffs_list_xattrib(struct yaffs_obj *obj, char *buffer, int size)
4771 {
4772         return yaffs_do_xattrib_fetch(obj, NULL, buffer, size);
4773 }
4774
4775 /*---------------------------- Initialisation code -------------------------------------- */
4776
4777 static int yaffs_check_dev_fns(const struct yaffs_dev *dev)
4778 {
4779
4780         /* Common functions, gotta have */
4781         if (!dev->param.erase_fn || !dev->param.initialise_flash_fn)
4782                 return 0;
4783
4784 #ifdef CONFIG_YAFFS_YAFFS2
4785
4786         /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
4787         if (dev->param.write_chunk_tags_fn &&
4788             dev->param.read_chunk_tags_fn &&
4789             !dev->param.write_chunk_fn &&
4790             !dev->param.read_chunk_fn &&
4791             dev->param.bad_block_fn && dev->param.query_block_fn)
4792                 return 1;
4793 #endif
4794
4795         /* Can use the "spare" style interface for yaffs1 */
4796         if (!dev->param.is_yaffs2 &&
4797             !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
4804         return 0;               /* bad */
4805 }
4806
4807 static int yaffs_create_initial_dir(struct yaffs_dev *dev)
4808 {
4809         /* Initialise the unlinked, deleted, root and lost and found directories */
4810
4811         dev->lost_n_found = dev->root_dir = NULL;
4812         dev->unlinked_dir = dev->del_dir = NULL;
4813
4814         dev->unlinked_dir =
4815             yaffs_create_fake_dir(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
4816
4817         dev->del_dir =
4818             yaffs_create_fake_dir(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
4819
4820         dev->root_dir =
4821             yaffs_create_fake_dir(dev, YAFFS_OBJECTID_ROOT,
4822                                   YAFFS_ROOT_MODE | S_IFDIR);
4823         dev->lost_n_found =
4824             yaffs_create_fake_dir(dev, YAFFS_OBJECTID_LOSTNFOUND,
4825                                   YAFFS_LOSTNFOUND_MODE | S_IFDIR);
4826
4827         if (dev->lost_n_found && dev->root_dir && dev->unlinked_dir
4828             && dev->del_dir) {
4829                 yaffs_add_obj_to_dir(dev->root_dir, dev->lost_n_found);
4830                 return YAFFS_OK;
4831         }
4832
4833         return YAFFS_FAIL;
4834 }
4835
4836 int yaffs_guts_initialise(struct yaffs_dev *dev)
4837 {
4838         int init_failed = 0;
4839         unsigned x;
4840         int bits;
4841
4842         T(YAFFS_TRACE_TRACING,
4843           (TSTR("yaffs: yaffs_guts_initialise()" TENDSTR)));
4844
4845         /* Check stuff that must be set */
4846
4847         if (!dev) {
4848                 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
4849                 return YAFFS_FAIL;
4850         }
4851
4852         dev->internal_start_block = dev->param.start_block;
4853         dev->internal_end_block = dev->param.end_block;
4854         dev->block_offset = 0;
4855         dev->chunk_offset = 0;
4856         dev->n_free_chunks = 0;
4857
4858         dev->gc_block = 0;
4859
4860         if (dev->param.start_block == 0) {
4861                 dev->internal_start_block = dev->param.start_block + 1;
4862                 dev->internal_end_block = dev->param.end_block + 1;
4863                 dev->block_offset = 1;
4864                 dev->chunk_offset = dev->param.chunks_per_block;
4865         }
4866
4867         /* Check geometry parameters. */
4868
4869         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 */
4870                 T(YAFFS_TRACE_ALWAYS,
4871                   (TSTR
4872                    ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inband_tags %d "
4873                     TENDSTR), dev->param.total_bytes_per_chunk,
4874                    dev->param.is_yaffs2 ? "2" : "", dev->param.inband_tags));
4875                 return YAFFS_FAIL;
4876         }
4877
4878         if (yaffs_init_nand(dev) != YAFFS_OK) {
4879                 T(YAFFS_TRACE_ALWAYS,
4880                   (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
4881                 return YAFFS_FAIL;
4882         }
4883
4884         /* Sort out space for inband tags, if required */
4885         if (dev->param.inband_tags)
4886                 dev->data_bytes_per_chunk =
4887                     dev->param.total_bytes_per_chunk -
4888                     sizeof(struct yaffs_packed_tags2_tags_only);
4889         else
4890                 dev->data_bytes_per_chunk = dev->param.total_bytes_per_chunk;
4891
4892         /* Got the right mix of functions? */
4893         if (!yaffs_check_dev_fns(dev)) {
4894                 /* Function missing */
4895                 T(YAFFS_TRACE_ALWAYS,
4896                   (TSTR
4897                    ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
4898
4899                 return YAFFS_FAIL;
4900         }
4901
4902         if (dev->is_mounted) {
4903                 T(YAFFS_TRACE_ALWAYS,
4904                   (TSTR("yaffs: device already mounted\n" TENDSTR)));
4905                 return YAFFS_FAIL;
4906         }
4907
4908         /* Finished with most checks. One or two more checks happen later on too. */
4909
4910         dev->is_mounted = 1;
4911
4912         /* OK now calculate a few things for the device */
4913
4914         /*
4915          *  Calculate all the chunk size manipulation numbers:
4916          */
4917         x = dev->data_bytes_per_chunk;
4918         /* We always use dev->chunk_shift and dev->chunk_div */
4919         dev->chunk_shift = calc_shifts(x);
4920         x >>= dev->chunk_shift;
4921         dev->chunk_div = x;
4922         /* We only use chunk mask if chunk_div is 1 */
4923         dev->chunk_mask = (1 << dev->chunk_shift) - 1;
4924
4925         /*
4926          * Calculate chunk_grp_bits.
4927          * We need to find the next power of 2 > than internal_end_block
4928          */
4929
4930         x = dev->param.chunks_per_block * (dev->internal_end_block + 1);
4931
4932         bits = calc_shifts_ceiling(x);
4933
4934         /* Set up tnode width if wide tnodes are enabled. */
4935         if (!dev->param.wide_tnodes_disabled) {
4936                 /* bits must be even so that we end up with 32-bit words */
4937                 if (bits & 1)
4938                         bits++;
4939                 if (bits < 16)
4940                         dev->tnode_width = 16;
4941                 else
4942                         dev->tnode_width = bits;
4943         } else {
4944                 dev->tnode_width = 16;
4945         }
4946
4947         dev->tnode_mask = (1 << dev->tnode_width) - 1;
4948
4949         /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
4950          * so if the bitwidth of the
4951          * chunk range we're using is greater than 16 we need
4952          * to figure out chunk shift and chunk_grp_size
4953          */
4954
4955         if (bits <= dev->tnode_width)
4956                 dev->chunk_grp_bits = 0;
4957         else
4958                 dev->chunk_grp_bits = bits - dev->tnode_width;
4959
4960         dev->tnode_size = (dev->tnode_width * YAFFS_NTNODES_LEVEL0) / 8;
4961         if (dev->tnode_size < sizeof(struct yaffs_tnode))
4962                 dev->tnode_size = sizeof(struct yaffs_tnode);
4963
4964         dev->chunk_grp_size = 1 << dev->chunk_grp_bits;
4965
4966         if (dev->param.chunks_per_block < dev->chunk_grp_size) {
4967                 /* We have a problem because the soft delete won't work if
4968                  * the chunk group size > chunks per block.
4969                  * This can be remedied by using larger "virtual blocks".
4970                  */
4971                 T(YAFFS_TRACE_ALWAYS,
4972                   (TSTR("yaffs: chunk group too large\n" TENDSTR)));
4973
4974                 return YAFFS_FAIL;
4975         }
4976
4977         /* OK, we've finished verifying the device, lets continue with initialisation */
4978
4979         /* More device initialisation */
4980         dev->all_gcs = 0;
4981         dev->passive_gc_count = 0;
4982         dev->oldest_dirty_gc_count = 0;
4983         dev->bg_gcs = 0;
4984         dev->gc_block_finder = 0;
4985         dev->buffered_block = -1;
4986         dev->doing_buffered_block_rewrite = 0;
4987         dev->n_deleted_files = 0;
4988         dev->n_bg_deletions = 0;
4989         dev->n_unlinked_files = 0;
4990         dev->n_ecc_fixed = 0;
4991         dev->n_ecc_unfixed = 0;
4992         dev->n_tags_ecc_fixed = 0;
4993         dev->n_tags_ecc_unfixed = 0;
4994         dev->n_erase_failures = 0;
4995         dev->n_erased_blocks = 0;
4996         dev->gc_disable = 0;
4997         dev->has_pending_prioritised_gc = 1;    /* Assume the worst for now, will get fixed on first GC */
4998         INIT_LIST_HEAD(&dev->dirty_dirs);
4999         dev->oldest_dirty_seq = 0;
5000         dev->oldest_dirty_block = 0;
5001
5002         /* Initialise temporary buffers and caches. */
5003         if (!yaffs_init_tmp_buffers(dev))
5004                 init_failed = 1;
5005
5006         dev->cache = NULL;
5007         dev->gc_cleanup_list = NULL;
5008
5009         if (!init_failed && dev->param.n_caches > 0) {
5010                 int i;
5011                 void *buf;
5012                 int cache_bytes =
5013                     dev->param.n_caches * sizeof(struct yaffs_cache);
5014
5015                 if (dev->param.n_caches > YAFFS_MAX_SHORT_OP_CACHES)
5016                         dev->param.n_caches = YAFFS_MAX_SHORT_OP_CACHES;
5017
5018                 dev->cache = YMALLOC(cache_bytes);
5019
5020                 buf = (u8 *) dev->cache;
5021
5022                 if (dev->cache)
5023                         memset(dev->cache, 0, cache_bytes);
5024
5025                 for (i = 0; i < dev->param.n_caches && buf; i++) {
5026                         dev->cache[i].object = NULL;
5027                         dev->cache[i].last_use = 0;
5028                         dev->cache[i].dirty = 0;
5029                         dev->cache[i].data = buf =
5030                             YMALLOC_DMA(dev->param.total_bytes_per_chunk);
5031                 }
5032                 if (!buf)
5033                         init_failed = 1;
5034
5035                 dev->cache_last_use = 0;
5036         }
5037
5038         dev->cache_hits = 0;
5039
5040         if (!init_failed) {
5041                 dev->gc_cleanup_list =
5042                     YMALLOC(dev->param.chunks_per_block * sizeof(u32));
5043                 if (!dev->gc_cleanup_list)
5044                         init_failed = 1;
5045         }
5046
5047         if (dev->param.is_yaffs2)
5048                 dev->param.use_header_file_size = 1;
5049
5050         if (!init_failed && !yaffs_init_blocks(dev))
5051                 init_failed = 1;
5052
5053         yaffs_init_tnodes_and_objs(dev);
5054
5055         if (!init_failed && !yaffs_create_initial_dir(dev))
5056                 init_failed = 1;
5057
5058         if (!init_failed) {
5059                 /* Now scan the flash. */
5060                 if (dev->param.is_yaffs2) {
5061                         if (yaffs2_checkpt_restore(dev)) {
5062                                 yaffs_check_obj_details_loaded(dev->root_dir);
5063                                 T(YAFFS_TRACE_ALWAYS,
5064                                   (TSTR
5065                                    ("yaffs: restored from checkpoint"
5066                                     TENDSTR)));
5067                         } else {
5068
5069                                 /* Clean up the mess caused by an aborted checkpoint load
5070                                  * and scan backwards.
5071                                  */
5072                                 yaffs_deinit_blocks(dev);
5073
5074                                 yaffs_deinit_tnodes_and_objs(dev);
5075
5076                                 dev->n_erased_blocks = 0;
5077                                 dev->n_free_chunks = 0;
5078                                 dev->alloc_block = -1;
5079                                 dev->alloc_page = -1;
5080                                 dev->n_deleted_files = 0;
5081                                 dev->n_unlinked_files = 0;
5082                                 dev->n_bg_deletions = 0;
5083
5084                                 if (!init_failed && !yaffs_init_blocks(dev))
5085                                         init_failed = 1;
5086
5087                                 yaffs_init_tnodes_and_objs(dev);
5088
5089                                 if (!init_failed
5090                                     && !yaffs_create_initial_dir(dev))
5091                                         init_failed = 1;
5092
5093                                 if (!init_failed && !yaffs2_scan_backwards(dev))
5094                                         init_failed = 1;
5095                         }
5096                 } else if (!yaffs1_scan(dev)) {
5097                         init_failed = 1;
5098                 }
5099
5100                 yaffs_strip_deleted_objs(dev);
5101                 yaffs_fix_hanging_objs(dev);
5102                 if (dev->param.empty_lost_n_found)
5103                         yaffs_empty_l_n_f(dev);
5104         }
5105
5106         if (init_failed) {
5107                 /* Clean up the mess */
5108                 T(YAFFS_TRACE_TRACING,
5109                   (TSTR("yaffs: yaffs_guts_initialise() aborted.\n" TENDSTR)));
5110
5111                 yaffs_deinitialise(dev);
5112                 return YAFFS_FAIL;
5113         }
5114
5115         /* Zero out stats */
5116         dev->n_page_reads = 0;
5117         dev->n_page_writes = 0;
5118         dev->n_erasures = 0;
5119         dev->n_gc_copies = 0;
5120         dev->n_retired_writes = 0;
5121
5122         dev->n_retired_blocks = 0;
5123
5124         yaffs_verify_free_chunks(dev);
5125         yaffs_verify_blocks(dev);
5126
5127         /* Clean up any aborted checkpoint data */
5128         if (!dev->is_checkpointed && dev->blocks_in_checkpt > 0)
5129                 yaffs2_checkpt_invalidate(dev);
5130
5131         T(YAFFS_TRACE_TRACING,
5132           (TSTR("yaffs: yaffs_guts_initialise() done.\n" TENDSTR)));
5133         return YAFFS_OK;
5134
5135 }
5136
5137 void yaffs_deinitialise(struct yaffs_dev *dev)
5138 {
5139         if (dev->is_mounted) {
5140                 int i;
5141
5142                 yaffs_deinit_blocks(dev);
5143                 yaffs_deinit_tnodes_and_objs(dev);
5144                 if (dev->param.n_caches > 0 && dev->cache) {
5145
5146                         for (i = 0; i < dev->param.n_caches; i++) {
5147                                 if (dev->cache[i].data)
5148                                         YFREE(dev->cache[i].data);
5149                                 dev->cache[i].data = NULL;
5150                         }
5151
5152                         YFREE(dev->cache);
5153                         dev->cache = NULL;
5154                 }
5155
5156                 YFREE(dev->gc_cleanup_list);
5157
5158                 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
5159                         YFREE(dev->temp_buffer[i].buffer);
5160
5161                 dev->is_mounted = 0;
5162
5163                 if (dev->param.deinitialise_flash_fn)
5164                         dev->param.deinitialise_flash_fn(dev);
5165         }
5166 }
5167
5168 int yaffs_count_free_chunks(struct yaffs_dev *dev)
5169 {
5170         int n_free = 0;
5171         int b;
5172
5173         struct yaffs_block_info *blk;
5174
5175         blk = dev->block_info;
5176         for (b = dev->internal_start_block; b <= dev->internal_end_block; b++) {
5177                 switch (blk->block_state) {
5178                 case YAFFS_BLOCK_STATE_EMPTY:
5179                 case YAFFS_BLOCK_STATE_ALLOCATING:
5180                 case YAFFS_BLOCK_STATE_COLLECTING:
5181                 case YAFFS_BLOCK_STATE_FULL:
5182                         n_free +=
5183                             (dev->param.chunks_per_block - blk->pages_in_use +
5184                              blk->soft_del_pages);
5185                         break;
5186                 default:
5187                         break;
5188                 }
5189                 blk++;
5190         }
5191
5192         return n_free;
5193 }
5194
5195 int yaffs_get_n_free_chunks(struct yaffs_dev *dev)
5196 {
5197         /* This is what we report to the outside world */
5198
5199         int n_free;
5200         int n_dirty_caches;
5201         int blocks_for_checkpt;
5202         int i;
5203
5204         n_free = dev->n_free_chunks;
5205         n_free += dev->n_deleted_files;
5206
5207         /* Now count the number of dirty chunks in the cache and subtract those */
5208
5209         for (n_dirty_caches = 0, i = 0; i < dev->param.n_caches; i++) {
5210                 if (dev->cache[i].dirty)
5211                         n_dirty_caches++;
5212         }
5213
5214         n_free -= n_dirty_caches;
5215
5216         n_free -=
5217             ((dev->param.n_reserved_blocks + 1) * dev->param.chunks_per_block);
5218
5219         /* Now we figure out how much to reserve for the checkpoint and report that... */
5220         blocks_for_checkpt = yaffs_calc_checkpt_blocks_required(dev);
5221
5222         n_free -= (blocks_for_checkpt * dev->param.chunks_per_block);
5223
5224         if (n_free < 0)
5225                 n_free = 0;
5226
5227         return n_free;
5228
5229 }