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