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