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