c9ce0b0020084e336a1f99b8e623a5bfe9f8404f
[sfrench/cifs-2.6.git] / fs / btrfs / disk-io.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2007 Oracle.  All rights reserved.
4  */
5
6 #include <linux/fs.h>
7 #include <linux/blkdev.h>
8 #include <linux/radix-tree.h>
9 #include <linux/writeback.h>
10 #include <linux/buffer_head.h>
11 #include <linux/workqueue.h>
12 #include <linux/kthread.h>
13 #include <linux/slab.h>
14 #include <linux/migrate.h>
15 #include <linux/ratelimit.h>
16 #include <linux/uuid.h>
17 #include <linux/semaphore.h>
18 #include <linux/error-injection.h>
19 #include <linux/crc32c.h>
20 #include <linux/sched/mm.h>
21 #include <asm/unaligned.h>
22 #include "ctree.h"
23 #include "disk-io.h"
24 #include "transaction.h"
25 #include "btrfs_inode.h"
26 #include "volumes.h"
27 #include "print-tree.h"
28 #include "locking.h"
29 #include "tree-log.h"
30 #include "free-space-cache.h"
31 #include "free-space-tree.h"
32 #include "inode-map.h"
33 #include "check-integrity.h"
34 #include "rcu-string.h"
35 #include "dev-replace.h"
36 #include "raid56.h"
37 #include "sysfs.h"
38 #include "qgroup.h"
39 #include "compression.h"
40 #include "tree-checker.h"
41 #include "ref-verify.h"
42
43 #define BTRFS_SUPER_FLAG_SUPP   (BTRFS_HEADER_FLAG_WRITTEN |\
44                                  BTRFS_HEADER_FLAG_RELOC |\
45                                  BTRFS_SUPER_FLAG_ERROR |\
46                                  BTRFS_SUPER_FLAG_SEEDING |\
47                                  BTRFS_SUPER_FLAG_METADUMP |\
48                                  BTRFS_SUPER_FLAG_METADUMP_V2)
49
50 static const struct extent_io_ops btree_extent_io_ops;
51 static void end_workqueue_fn(struct btrfs_work *work);
52 static void btrfs_destroy_ordered_extents(struct btrfs_root *root);
53 static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
54                                       struct btrfs_fs_info *fs_info);
55 static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root);
56 static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
57                                         struct extent_io_tree *dirty_pages,
58                                         int mark);
59 static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
60                                        struct extent_io_tree *pinned_extents);
61 static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info);
62 static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info);
63
64 /*
65  * btrfs_end_io_wq structs are used to do processing in task context when an IO
66  * is complete.  This is used during reads to verify checksums, and it is used
67  * by writes to insert metadata for new file extents after IO is complete.
68  */
69 struct btrfs_end_io_wq {
70         struct bio *bio;
71         bio_end_io_t *end_io;
72         void *private;
73         struct btrfs_fs_info *info;
74         blk_status_t status;
75         enum btrfs_wq_endio_type metadata;
76         struct btrfs_work work;
77 };
78
79 static struct kmem_cache *btrfs_end_io_wq_cache;
80
81 int __init btrfs_end_io_wq_init(void)
82 {
83         btrfs_end_io_wq_cache = kmem_cache_create("btrfs_end_io_wq",
84                                         sizeof(struct btrfs_end_io_wq),
85                                         0,
86                                         SLAB_MEM_SPREAD,
87                                         NULL);
88         if (!btrfs_end_io_wq_cache)
89                 return -ENOMEM;
90         return 0;
91 }
92
93 void __cold btrfs_end_io_wq_exit(void)
94 {
95         kmem_cache_destroy(btrfs_end_io_wq_cache);
96 }
97
98 /*
99  * async submit bios are used to offload expensive checksumming
100  * onto the worker threads.  They checksum file and metadata bios
101  * just before they are sent down the IO stack.
102  */
103 struct async_submit_bio {
104         void *private_data;
105         struct bio *bio;
106         extent_submit_bio_start_t *submit_bio_start;
107         int mirror_num;
108         /*
109          * bio_offset is optional, can be used if the pages in the bio
110          * can't tell us where in the file the bio should go
111          */
112         u64 bio_offset;
113         struct btrfs_work work;
114         blk_status_t status;
115 };
116
117 /*
118  * Lockdep class keys for extent_buffer->lock's in this root.  For a given
119  * eb, the lockdep key is determined by the btrfs_root it belongs to and
120  * the level the eb occupies in the tree.
121  *
122  * Different roots are used for different purposes and may nest inside each
123  * other and they require separate keysets.  As lockdep keys should be
124  * static, assign keysets according to the purpose of the root as indicated
125  * by btrfs_root->root_key.objectid.  This ensures that all special purpose
126  * roots have separate keysets.
127  *
128  * Lock-nesting across peer nodes is always done with the immediate parent
129  * node locked thus preventing deadlock.  As lockdep doesn't know this, use
130  * subclass to avoid triggering lockdep warning in such cases.
131  *
132  * The key is set by the readpage_end_io_hook after the buffer has passed
133  * csum validation but before the pages are unlocked.  It is also set by
134  * btrfs_init_new_buffer on freshly allocated blocks.
135  *
136  * We also add a check to make sure the highest level of the tree is the
137  * same as our lockdep setup here.  If BTRFS_MAX_LEVEL changes, this code
138  * needs update as well.
139  */
140 #ifdef CONFIG_DEBUG_LOCK_ALLOC
141 # if BTRFS_MAX_LEVEL != 8
142 #  error
143 # endif
144
145 static struct btrfs_lockdep_keyset {
146         u64                     id;             /* root objectid */
147         const char              *name_stem;     /* lock name stem */
148         char                    names[BTRFS_MAX_LEVEL + 1][20];
149         struct lock_class_key   keys[BTRFS_MAX_LEVEL + 1];
150 } btrfs_lockdep_keysets[] = {
151         { .id = BTRFS_ROOT_TREE_OBJECTID,       .name_stem = "root"     },
152         { .id = BTRFS_EXTENT_TREE_OBJECTID,     .name_stem = "extent"   },
153         { .id = BTRFS_CHUNK_TREE_OBJECTID,      .name_stem = "chunk"    },
154         { .id = BTRFS_DEV_TREE_OBJECTID,        .name_stem = "dev"      },
155         { .id = BTRFS_FS_TREE_OBJECTID,         .name_stem = "fs"       },
156         { .id = BTRFS_CSUM_TREE_OBJECTID,       .name_stem = "csum"     },
157         { .id = BTRFS_QUOTA_TREE_OBJECTID,      .name_stem = "quota"    },
158         { .id = BTRFS_TREE_LOG_OBJECTID,        .name_stem = "log"      },
159         { .id = BTRFS_TREE_RELOC_OBJECTID,      .name_stem = "treloc"   },
160         { .id = BTRFS_DATA_RELOC_TREE_OBJECTID, .name_stem = "dreloc"   },
161         { .id = BTRFS_UUID_TREE_OBJECTID,       .name_stem = "uuid"     },
162         { .id = BTRFS_FREE_SPACE_TREE_OBJECTID, .name_stem = "free-space" },
163         { .id = 0,                              .name_stem = "tree"     },
164 };
165
166 void __init btrfs_init_lockdep(void)
167 {
168         int i, j;
169
170         /* initialize lockdep class names */
171         for (i = 0; i < ARRAY_SIZE(btrfs_lockdep_keysets); i++) {
172                 struct btrfs_lockdep_keyset *ks = &btrfs_lockdep_keysets[i];
173
174                 for (j = 0; j < ARRAY_SIZE(ks->names); j++)
175                         snprintf(ks->names[j], sizeof(ks->names[j]),
176                                  "btrfs-%s-%02d", ks->name_stem, j);
177         }
178 }
179
180 void btrfs_set_buffer_lockdep_class(u64 objectid, struct extent_buffer *eb,
181                                     int level)
182 {
183         struct btrfs_lockdep_keyset *ks;
184
185         BUG_ON(level >= ARRAY_SIZE(ks->keys));
186
187         /* find the matching keyset, id 0 is the default entry */
188         for (ks = btrfs_lockdep_keysets; ks->id; ks++)
189                 if (ks->id == objectid)
190                         break;
191
192         lockdep_set_class_and_name(&eb->lock,
193                                    &ks->keys[level], ks->names[level]);
194 }
195
196 #endif
197
198 /*
199  * extents on the btree inode are pretty simple, there's one extent
200  * that covers the entire device
201  */
202 struct extent_map *btree_get_extent(struct btrfs_inode *inode,
203                 struct page *page, size_t pg_offset, u64 start, u64 len,
204                 int create)
205 {
206         struct btrfs_fs_info *fs_info = inode->root->fs_info;
207         struct extent_map_tree *em_tree = &inode->extent_tree;
208         struct extent_map *em;
209         int ret;
210
211         read_lock(&em_tree->lock);
212         em = lookup_extent_mapping(em_tree, start, len);
213         if (em) {
214                 em->bdev = fs_info->fs_devices->latest_bdev;
215                 read_unlock(&em_tree->lock);
216                 goto out;
217         }
218         read_unlock(&em_tree->lock);
219
220         em = alloc_extent_map();
221         if (!em) {
222                 em = ERR_PTR(-ENOMEM);
223                 goto out;
224         }
225         em->start = 0;
226         em->len = (u64)-1;
227         em->block_len = (u64)-1;
228         em->block_start = 0;
229         em->bdev = fs_info->fs_devices->latest_bdev;
230
231         write_lock(&em_tree->lock);
232         ret = add_extent_mapping(em_tree, em, 0);
233         if (ret == -EEXIST) {
234                 free_extent_map(em);
235                 em = lookup_extent_mapping(em_tree, start, len);
236                 if (!em)
237                         em = ERR_PTR(-EIO);
238         } else if (ret) {
239                 free_extent_map(em);
240                 em = ERR_PTR(ret);
241         }
242         write_unlock(&em_tree->lock);
243
244 out:
245         return em;
246 }
247
248 u32 btrfs_csum_data(const char *data, u32 seed, size_t len)
249 {
250         return crc32c(seed, data, len);
251 }
252
253 void btrfs_csum_final(u32 crc, u8 *result)
254 {
255         put_unaligned_le32(~crc, result);
256 }
257
258 /*
259  * Compute the csum of a btree block and store the result to provided buffer.
260  *
261  * Returns error if the extent buffer cannot be mapped.
262  */
263 static int csum_tree_block(struct extent_buffer *buf, u8 *result)
264 {
265         unsigned long len;
266         unsigned long cur_len;
267         unsigned long offset = BTRFS_CSUM_SIZE;
268         char *kaddr;
269         unsigned long map_start;
270         unsigned long map_len;
271         int err;
272         u32 crc = ~(u32)0;
273
274         len = buf->len - offset;
275         while (len > 0) {
276                 /*
277                  * Note: we don't need to check for the err == 1 case here, as
278                  * with the given combination of 'start = BTRFS_CSUM_SIZE (32)'
279                  * and 'min_len = 32' and the currently implemented mapping
280                  * algorithm we cannot cross a page boundary.
281                  */
282                 err = map_private_extent_buffer(buf, offset, 32,
283                                         &kaddr, &map_start, &map_len);
284                 if (WARN_ON(err))
285                         return err;
286                 cur_len = min(len, map_len - (offset - map_start));
287                 crc = btrfs_csum_data(kaddr + offset - map_start,
288                                       crc, cur_len);
289                 len -= cur_len;
290                 offset += cur_len;
291         }
292         memset(result, 0, BTRFS_CSUM_SIZE);
293
294         btrfs_csum_final(crc, result);
295
296         return 0;
297 }
298
299 /*
300  * we can't consider a given block up to date unless the transid of the
301  * block matches the transid in the parent node's pointer.  This is how we
302  * detect blocks that either didn't get written at all or got written
303  * in the wrong place.
304  */
305 static int verify_parent_transid(struct extent_io_tree *io_tree,
306                                  struct extent_buffer *eb, u64 parent_transid,
307                                  int atomic)
308 {
309         struct extent_state *cached_state = NULL;
310         int ret;
311         bool need_lock = (current->journal_info == BTRFS_SEND_TRANS_STUB);
312
313         if (!parent_transid || btrfs_header_generation(eb) == parent_transid)
314                 return 0;
315
316         if (atomic)
317                 return -EAGAIN;
318
319         if (need_lock) {
320                 btrfs_tree_read_lock(eb);
321                 btrfs_set_lock_blocking_read(eb);
322         }
323
324         lock_extent_bits(io_tree, eb->start, eb->start + eb->len - 1,
325                          &cached_state);
326         if (extent_buffer_uptodate(eb) &&
327             btrfs_header_generation(eb) == parent_transid) {
328                 ret = 0;
329                 goto out;
330         }
331         btrfs_err_rl(eb->fs_info,
332                 "parent transid verify failed on %llu wanted %llu found %llu",
333                         eb->start,
334                         parent_transid, btrfs_header_generation(eb));
335         ret = 1;
336
337         /*
338          * Things reading via commit roots that don't have normal protection,
339          * like send, can have a really old block in cache that may point at a
340          * block that has been freed and re-allocated.  So don't clear uptodate
341          * if we find an eb that is under IO (dirty/writeback) because we could
342          * end up reading in the stale data and then writing it back out and
343          * making everybody very sad.
344          */
345         if (!extent_buffer_under_io(eb))
346                 clear_extent_buffer_uptodate(eb);
347 out:
348         unlock_extent_cached(io_tree, eb->start, eb->start + eb->len - 1,
349                              &cached_state);
350         if (need_lock)
351                 btrfs_tree_read_unlock_blocking(eb);
352         return ret;
353 }
354
355 static bool btrfs_supported_super_csum(u16 csum_type)
356 {
357         switch (csum_type) {
358         case BTRFS_CSUM_TYPE_CRC32:
359                 return true;
360         default:
361                 return false;
362         }
363 }
364
365 /*
366  * Return 0 if the superblock checksum type matches the checksum value of that
367  * algorithm. Pass the raw disk superblock data.
368  */
369 static int btrfs_check_super_csum(struct btrfs_fs_info *fs_info,
370                                   char *raw_disk_sb)
371 {
372         struct btrfs_super_block *disk_sb =
373                 (struct btrfs_super_block *)raw_disk_sb;
374         u32 crc = ~(u32)0;
375         char result[BTRFS_CSUM_SIZE];
376
377         /*
378          * The super_block structure does not span the whole
379          * BTRFS_SUPER_INFO_SIZE range, we expect that the unused space is
380          * filled with zeros and is included in the checksum.
381          */
382         crc = btrfs_csum_data(raw_disk_sb + BTRFS_CSUM_SIZE,
383                               crc, BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE);
384         btrfs_csum_final(crc, result);
385
386         if (memcmp(disk_sb->csum, result, btrfs_super_csum_size(disk_sb)))
387                 return 1;
388
389         return 0;
390 }
391
392 int btrfs_verify_level_key(struct extent_buffer *eb, int level,
393                            struct btrfs_key *first_key, u64 parent_transid)
394 {
395         struct btrfs_fs_info *fs_info = eb->fs_info;
396         int found_level;
397         struct btrfs_key found_key;
398         int ret;
399
400         found_level = btrfs_header_level(eb);
401         if (found_level != level) {
402                 WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
403                      KERN_ERR "BTRFS: tree level check failed\n");
404                 btrfs_err(fs_info,
405 "tree level mismatch detected, bytenr=%llu level expected=%u has=%u",
406                           eb->start, level, found_level);
407                 return -EIO;
408         }
409
410         if (!first_key)
411                 return 0;
412
413         /*
414          * For live tree block (new tree blocks in current transaction),
415          * we need proper lock context to avoid race, which is impossible here.
416          * So we only checks tree blocks which is read from disk, whose
417          * generation <= fs_info->last_trans_committed.
418          */
419         if (btrfs_header_generation(eb) > fs_info->last_trans_committed)
420                 return 0;
421         if (found_level)
422                 btrfs_node_key_to_cpu(eb, &found_key, 0);
423         else
424                 btrfs_item_key_to_cpu(eb, &found_key, 0);
425         ret = btrfs_comp_cpu_keys(first_key, &found_key);
426
427         if (ret) {
428                 WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
429                      KERN_ERR "BTRFS: tree first key check failed\n");
430                 btrfs_err(fs_info,
431 "tree first key mismatch detected, bytenr=%llu parent_transid=%llu key expected=(%llu,%u,%llu) has=(%llu,%u,%llu)",
432                           eb->start, parent_transid, first_key->objectid,
433                           first_key->type, first_key->offset,
434                           found_key.objectid, found_key.type,
435                           found_key.offset);
436         }
437         return ret;
438 }
439
440 /*
441  * helper to read a given tree block, doing retries as required when
442  * the checksums don't match and we have alternate mirrors to try.
443  *
444  * @parent_transid:     expected transid, skip check if 0
445  * @level:              expected level, mandatory check
446  * @first_key:          expected key of first slot, skip check if NULL
447  */
448 static int btree_read_extent_buffer_pages(struct extent_buffer *eb,
449                                           u64 parent_transid, int level,
450                                           struct btrfs_key *first_key)
451 {
452         struct btrfs_fs_info *fs_info = eb->fs_info;
453         struct extent_io_tree *io_tree;
454         int failed = 0;
455         int ret;
456         int num_copies = 0;
457         int mirror_num = 0;
458         int failed_mirror = 0;
459
460         io_tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
461         while (1) {
462                 clear_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
463                 ret = read_extent_buffer_pages(eb, WAIT_COMPLETE, mirror_num);
464                 if (!ret) {
465                         if (verify_parent_transid(io_tree, eb,
466                                                    parent_transid, 0))
467                                 ret = -EIO;
468                         else if (btrfs_verify_level_key(eb, level,
469                                                 first_key, parent_transid))
470                                 ret = -EUCLEAN;
471                         else
472                                 break;
473                 }
474
475                 num_copies = btrfs_num_copies(fs_info,
476                                               eb->start, eb->len);
477                 if (num_copies == 1)
478                         break;
479
480                 if (!failed_mirror) {
481                         failed = 1;
482                         failed_mirror = eb->read_mirror;
483                 }
484
485                 mirror_num++;
486                 if (mirror_num == failed_mirror)
487                         mirror_num++;
488
489                 if (mirror_num > num_copies)
490                         break;
491         }
492
493         if (failed && !ret && failed_mirror)
494                 btrfs_repair_eb_io_failure(eb, failed_mirror);
495
496         return ret;
497 }
498
499 /*
500  * checksum a dirty tree block before IO.  This has extra checks to make sure
501  * we only fill in the checksum field in the first page of a multi-page block
502  */
503
504 static int csum_dirty_buffer(struct btrfs_fs_info *fs_info, struct page *page)
505 {
506         u64 start = page_offset(page);
507         u64 found_start;
508         u8 result[BTRFS_CSUM_SIZE];
509         u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
510         struct extent_buffer *eb;
511         int ret;
512
513         eb = (struct extent_buffer *)page->private;
514         if (page != eb->pages[0])
515                 return 0;
516
517         found_start = btrfs_header_bytenr(eb);
518         /*
519          * Please do not consolidate these warnings into a single if.
520          * It is useful to know what went wrong.
521          */
522         if (WARN_ON(found_start != start))
523                 return -EUCLEAN;
524         if (WARN_ON(!PageUptodate(page)))
525                 return -EUCLEAN;
526
527         ASSERT(memcmp_extent_buffer(eb, fs_info->fs_devices->metadata_uuid,
528                         btrfs_header_fsid(), BTRFS_FSID_SIZE) == 0);
529
530         if (csum_tree_block(eb, result))
531                 return -EINVAL;
532
533         if (btrfs_header_level(eb))
534                 ret = btrfs_check_node(eb);
535         else
536                 ret = btrfs_check_leaf_full(eb);
537
538         if (ret < 0) {
539                 btrfs_err(fs_info,
540                 "block=%llu write time tree block corruption detected",
541                           eb->start);
542                 return ret;
543         }
544         write_extent_buffer(eb, result, 0, csum_size);
545
546         return 0;
547 }
548
549 static int check_tree_block_fsid(struct extent_buffer *eb)
550 {
551         struct btrfs_fs_info *fs_info = eb->fs_info;
552         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
553         u8 fsid[BTRFS_FSID_SIZE];
554         int ret = 1;
555
556         read_extent_buffer(eb, fsid, btrfs_header_fsid(), BTRFS_FSID_SIZE);
557         while (fs_devices) {
558                 u8 *metadata_uuid;
559
560                 /*
561                  * Checking the incompat flag is only valid for the current
562                  * fs. For seed devices it's forbidden to have their uuid
563                  * changed so reading ->fsid in this case is fine
564                  */
565                 if (fs_devices == fs_info->fs_devices &&
566                     btrfs_fs_incompat(fs_info, METADATA_UUID))
567                         metadata_uuid = fs_devices->metadata_uuid;
568                 else
569                         metadata_uuid = fs_devices->fsid;
570
571                 if (!memcmp(fsid, metadata_uuid, BTRFS_FSID_SIZE)) {
572                         ret = 0;
573                         break;
574                 }
575                 fs_devices = fs_devices->seed;
576         }
577         return ret;
578 }
579
580 static int btree_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
581                                       u64 phy_offset, struct page *page,
582                                       u64 start, u64 end, int mirror)
583 {
584         u64 found_start;
585         int found_level;
586         struct extent_buffer *eb;
587         struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
588         struct btrfs_fs_info *fs_info = root->fs_info;
589         u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
590         int ret = 0;
591         u8 result[BTRFS_CSUM_SIZE];
592         int reads_done;
593
594         if (!page->private)
595                 goto out;
596
597         eb = (struct extent_buffer *)page->private;
598
599         /* the pending IO might have been the only thing that kept this buffer
600          * in memory.  Make sure we have a ref for all this other checks
601          */
602         extent_buffer_get(eb);
603
604         reads_done = atomic_dec_and_test(&eb->io_pages);
605         if (!reads_done)
606                 goto err;
607
608         eb->read_mirror = mirror;
609         if (test_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags)) {
610                 ret = -EIO;
611                 goto err;
612         }
613
614         found_start = btrfs_header_bytenr(eb);
615         if (found_start != eb->start) {
616                 btrfs_err_rl(fs_info, "bad tree block start, want %llu have %llu",
617                              eb->start, found_start);
618                 ret = -EIO;
619                 goto err;
620         }
621         if (check_tree_block_fsid(eb)) {
622                 btrfs_err_rl(fs_info, "bad fsid on block %llu",
623                              eb->start);
624                 ret = -EIO;
625                 goto err;
626         }
627         found_level = btrfs_header_level(eb);
628         if (found_level >= BTRFS_MAX_LEVEL) {
629                 btrfs_err(fs_info, "bad tree block level %d on %llu",
630                           (int)btrfs_header_level(eb), eb->start);
631                 ret = -EIO;
632                 goto err;
633         }
634
635         btrfs_set_buffer_lockdep_class(btrfs_header_owner(eb),
636                                        eb, found_level);
637
638         ret = csum_tree_block(eb, result);
639         if (ret)
640                 goto err;
641
642         if (memcmp_extent_buffer(eb, result, 0, csum_size)) {
643                 u32 val;
644                 u32 found = 0;
645
646                 memcpy(&found, result, csum_size);
647
648                 read_extent_buffer(eb, &val, 0, csum_size);
649                 btrfs_warn_rl(fs_info,
650                 "%s checksum verify failed on %llu wanted %x found %x level %d",
651                               fs_info->sb->s_id, eb->start,
652                               val, found, btrfs_header_level(eb));
653                 ret = -EUCLEAN;
654                 goto err;
655         }
656
657         /*
658          * If this is a leaf block and it is corrupt, set the corrupt bit so
659          * that we don't try and read the other copies of this block, just
660          * return -EIO.
661          */
662         if (found_level == 0 && btrfs_check_leaf_full(eb)) {
663                 set_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
664                 ret = -EIO;
665         }
666
667         if (found_level > 0 && btrfs_check_node(eb))
668                 ret = -EIO;
669
670         if (!ret)
671                 set_extent_buffer_uptodate(eb);
672         else
673                 btrfs_err(fs_info,
674                           "block=%llu read time tree block corruption detected",
675                           eb->start);
676 err:
677         if (reads_done &&
678             test_and_clear_bit(EXTENT_BUFFER_READAHEAD, &eb->bflags))
679                 btree_readahead_hook(eb, ret);
680
681         if (ret) {
682                 /*
683                  * our io error hook is going to dec the io pages
684                  * again, we have to make sure it has something
685                  * to decrement
686                  */
687                 atomic_inc(&eb->io_pages);
688                 clear_extent_buffer_uptodate(eb);
689         }
690         free_extent_buffer(eb);
691 out:
692         return ret;
693 }
694
695 static void end_workqueue_bio(struct bio *bio)
696 {
697         struct btrfs_end_io_wq *end_io_wq = bio->bi_private;
698         struct btrfs_fs_info *fs_info;
699         struct btrfs_workqueue *wq;
700         btrfs_work_func_t func;
701
702         fs_info = end_io_wq->info;
703         end_io_wq->status = bio->bi_status;
704
705         if (bio_op(bio) == REQ_OP_WRITE) {
706                 if (end_io_wq->metadata == BTRFS_WQ_ENDIO_METADATA) {
707                         wq = fs_info->endio_meta_write_workers;
708                         func = btrfs_endio_meta_write_helper;
709                 } else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_FREE_SPACE) {
710                         wq = fs_info->endio_freespace_worker;
711                         func = btrfs_freespace_write_helper;
712                 } else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56) {
713                         wq = fs_info->endio_raid56_workers;
714                         func = btrfs_endio_raid56_helper;
715                 } else {
716                         wq = fs_info->endio_write_workers;
717                         func = btrfs_endio_write_helper;
718                 }
719         } else {
720                 if (unlikely(end_io_wq->metadata ==
721                              BTRFS_WQ_ENDIO_DIO_REPAIR)) {
722                         wq = fs_info->endio_repair_workers;
723                         func = btrfs_endio_repair_helper;
724                 } else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56) {
725                         wq = fs_info->endio_raid56_workers;
726                         func = btrfs_endio_raid56_helper;
727                 } else if (end_io_wq->metadata) {
728                         wq = fs_info->endio_meta_workers;
729                         func = btrfs_endio_meta_helper;
730                 } else {
731                         wq = fs_info->endio_workers;
732                         func = btrfs_endio_helper;
733                 }
734         }
735
736         btrfs_init_work(&end_io_wq->work, func, end_workqueue_fn, NULL, NULL);
737         btrfs_queue_work(wq, &end_io_wq->work);
738 }
739
740 blk_status_t btrfs_bio_wq_end_io(struct btrfs_fs_info *info, struct bio *bio,
741                         enum btrfs_wq_endio_type metadata)
742 {
743         struct btrfs_end_io_wq *end_io_wq;
744
745         end_io_wq = kmem_cache_alloc(btrfs_end_io_wq_cache, GFP_NOFS);
746         if (!end_io_wq)
747                 return BLK_STS_RESOURCE;
748
749         end_io_wq->private = bio->bi_private;
750         end_io_wq->end_io = bio->bi_end_io;
751         end_io_wq->info = info;
752         end_io_wq->status = 0;
753         end_io_wq->bio = bio;
754         end_io_wq->metadata = metadata;
755
756         bio->bi_private = end_io_wq;
757         bio->bi_end_io = end_workqueue_bio;
758         return 0;
759 }
760
761 static void run_one_async_start(struct btrfs_work *work)
762 {
763         struct async_submit_bio *async;
764         blk_status_t ret;
765
766         async = container_of(work, struct  async_submit_bio, work);
767         ret = async->submit_bio_start(async->private_data, async->bio,
768                                       async->bio_offset);
769         if (ret)
770                 async->status = ret;
771 }
772
773 /*
774  * In order to insert checksums into the metadata in large chunks, we wait
775  * until bio submission time.   All the pages in the bio are checksummed and
776  * sums are attached onto the ordered extent record.
777  *
778  * At IO completion time the csums attached on the ordered extent record are
779  * inserted into the tree.
780  */
781 static void run_one_async_done(struct btrfs_work *work)
782 {
783         struct async_submit_bio *async;
784         struct inode *inode;
785         blk_status_t ret;
786
787         async = container_of(work, struct  async_submit_bio, work);
788         inode = async->private_data;
789
790         /* If an error occurred we just want to clean up the bio and move on */
791         if (async->status) {
792                 async->bio->bi_status = async->status;
793                 bio_endio(async->bio);
794                 return;
795         }
796
797         ret = btrfs_map_bio(btrfs_sb(inode->i_sb), async->bio,
798                         async->mirror_num, 1);
799         if (ret) {
800                 async->bio->bi_status = ret;
801                 bio_endio(async->bio);
802         }
803 }
804
805 static void run_one_async_free(struct btrfs_work *work)
806 {
807         struct async_submit_bio *async;
808
809         async = container_of(work, struct  async_submit_bio, work);
810         kfree(async);
811 }
812
813 blk_status_t btrfs_wq_submit_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
814                                  int mirror_num, unsigned long bio_flags,
815                                  u64 bio_offset, void *private_data,
816                                  extent_submit_bio_start_t *submit_bio_start)
817 {
818         struct async_submit_bio *async;
819
820         async = kmalloc(sizeof(*async), GFP_NOFS);
821         if (!async)
822                 return BLK_STS_RESOURCE;
823
824         async->private_data = private_data;
825         async->bio = bio;
826         async->mirror_num = mirror_num;
827         async->submit_bio_start = submit_bio_start;
828
829         btrfs_init_work(&async->work, btrfs_worker_helper, run_one_async_start,
830                         run_one_async_done, run_one_async_free);
831
832         async->bio_offset = bio_offset;
833
834         async->status = 0;
835
836         if (op_is_sync(bio->bi_opf))
837                 btrfs_set_work_high_priority(&async->work);
838
839         btrfs_queue_work(fs_info->workers, &async->work);
840         return 0;
841 }
842
843 static blk_status_t btree_csum_one_bio(struct bio *bio)
844 {
845         struct bio_vec *bvec;
846         struct btrfs_root *root;
847         int ret = 0;
848         struct bvec_iter_all iter_all;
849
850         ASSERT(!bio_flagged(bio, BIO_CLONED));
851         bio_for_each_segment_all(bvec, bio, iter_all) {
852                 root = BTRFS_I(bvec->bv_page->mapping->host)->root;
853                 ret = csum_dirty_buffer(root->fs_info, bvec->bv_page);
854                 if (ret)
855                         break;
856         }
857
858         return errno_to_blk_status(ret);
859 }
860
861 static blk_status_t btree_submit_bio_start(void *private_data, struct bio *bio,
862                                              u64 bio_offset)
863 {
864         /*
865          * when we're called for a write, we're already in the async
866          * submission context.  Just jump into btrfs_map_bio
867          */
868         return btree_csum_one_bio(bio);
869 }
870
871 static int check_async_write(struct btrfs_fs_info *fs_info,
872                              struct btrfs_inode *bi)
873 {
874         if (atomic_read(&bi->sync_writers))
875                 return 0;
876         if (test_bit(BTRFS_FS_CSUM_IMPL_FAST, &fs_info->flags))
877                 return 0;
878         return 1;
879 }
880
881 static blk_status_t btree_submit_bio_hook(struct inode *inode, struct bio *bio,
882                                           int mirror_num,
883                                           unsigned long bio_flags)
884 {
885         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
886         int async = check_async_write(fs_info, BTRFS_I(inode));
887         blk_status_t ret;
888
889         if (bio_op(bio) != REQ_OP_WRITE) {
890                 /*
891                  * called for a read, do the setup so that checksum validation
892                  * can happen in the async kernel threads
893                  */
894                 ret = btrfs_bio_wq_end_io(fs_info, bio,
895                                           BTRFS_WQ_ENDIO_METADATA);
896                 if (ret)
897                         goto out_w_error;
898                 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
899         } else if (!async) {
900                 ret = btree_csum_one_bio(bio);
901                 if (ret)
902                         goto out_w_error;
903                 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
904         } else {
905                 /*
906                  * kthread helpers are used to submit writes so that
907                  * checksumming can happen in parallel across all CPUs
908                  */
909                 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, 0,
910                                           0, inode, btree_submit_bio_start);
911         }
912
913         if (ret)
914                 goto out_w_error;
915         return 0;
916
917 out_w_error:
918         bio->bi_status = ret;
919         bio_endio(bio);
920         return ret;
921 }
922
923 #ifdef CONFIG_MIGRATION
924 static int btree_migratepage(struct address_space *mapping,
925                         struct page *newpage, struct page *page,
926                         enum migrate_mode mode)
927 {
928         /*
929          * we can't safely write a btree page from here,
930          * we haven't done the locking hook
931          */
932         if (PageDirty(page))
933                 return -EAGAIN;
934         /*
935          * Buffers may be managed in a filesystem specific way.
936          * We must have no buffers or drop them.
937          */
938         if (page_has_private(page) &&
939             !try_to_release_page(page, GFP_KERNEL))
940                 return -EAGAIN;
941         return migrate_page(mapping, newpage, page, mode);
942 }
943 #endif
944
945
946 static int btree_writepages(struct address_space *mapping,
947                             struct writeback_control *wbc)
948 {
949         struct btrfs_fs_info *fs_info;
950         int ret;
951
952         if (wbc->sync_mode == WB_SYNC_NONE) {
953
954                 if (wbc->for_kupdate)
955                         return 0;
956
957                 fs_info = BTRFS_I(mapping->host)->root->fs_info;
958                 /* this is a bit racy, but that's ok */
959                 ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
960                                              BTRFS_DIRTY_METADATA_THRESH,
961                                              fs_info->dirty_metadata_batch);
962                 if (ret < 0)
963                         return 0;
964         }
965         return btree_write_cache_pages(mapping, wbc);
966 }
967
968 static int btree_readpage(struct file *file, struct page *page)
969 {
970         struct extent_io_tree *tree;
971         tree = &BTRFS_I(page->mapping->host)->io_tree;
972         return extent_read_full_page(tree, page, btree_get_extent, 0);
973 }
974
975 static int btree_releasepage(struct page *page, gfp_t gfp_flags)
976 {
977         if (PageWriteback(page) || PageDirty(page))
978                 return 0;
979
980         return try_release_extent_buffer(page);
981 }
982
983 static void btree_invalidatepage(struct page *page, unsigned int offset,
984                                  unsigned int length)
985 {
986         struct extent_io_tree *tree;
987         tree = &BTRFS_I(page->mapping->host)->io_tree;
988         extent_invalidatepage(tree, page, offset);
989         btree_releasepage(page, GFP_NOFS);
990         if (PagePrivate(page)) {
991                 btrfs_warn(BTRFS_I(page->mapping->host)->root->fs_info,
992                            "page private not zero on page %llu",
993                            (unsigned long long)page_offset(page));
994                 ClearPagePrivate(page);
995                 set_page_private(page, 0);
996                 put_page(page);
997         }
998 }
999
1000 static int btree_set_page_dirty(struct page *page)
1001 {
1002 #ifdef DEBUG
1003         struct extent_buffer *eb;
1004
1005         BUG_ON(!PagePrivate(page));
1006         eb = (struct extent_buffer *)page->private;
1007         BUG_ON(!eb);
1008         BUG_ON(!test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
1009         BUG_ON(!atomic_read(&eb->refs));
1010         btrfs_assert_tree_locked(eb);
1011 #endif
1012         return __set_page_dirty_nobuffers(page);
1013 }
1014
1015 static const struct address_space_operations btree_aops = {
1016         .readpage       = btree_readpage,
1017         .writepages     = btree_writepages,
1018         .releasepage    = btree_releasepage,
1019         .invalidatepage = btree_invalidatepage,
1020 #ifdef CONFIG_MIGRATION
1021         .migratepage    = btree_migratepage,
1022 #endif
1023         .set_page_dirty = btree_set_page_dirty,
1024 };
1025
1026 void readahead_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr)
1027 {
1028         struct extent_buffer *buf = NULL;
1029         int ret;
1030
1031         buf = btrfs_find_create_tree_block(fs_info, bytenr);
1032         if (IS_ERR(buf))
1033                 return;
1034
1035         ret = read_extent_buffer_pages(buf, WAIT_NONE, 0);
1036         if (ret < 0)
1037                 free_extent_buffer_stale(buf);
1038         else
1039                 free_extent_buffer(buf);
1040 }
1041
1042 int reada_tree_block_flagged(struct btrfs_fs_info *fs_info, u64 bytenr,
1043                          int mirror_num, struct extent_buffer **eb)
1044 {
1045         struct extent_buffer *buf = NULL;
1046         int ret;
1047
1048         buf = btrfs_find_create_tree_block(fs_info, bytenr);
1049         if (IS_ERR(buf))
1050                 return 0;
1051
1052         set_bit(EXTENT_BUFFER_READAHEAD, &buf->bflags);
1053
1054         ret = read_extent_buffer_pages(buf, WAIT_PAGE_LOCK, mirror_num);
1055         if (ret) {
1056                 free_extent_buffer_stale(buf);
1057                 return ret;
1058         }
1059
1060         if (test_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags)) {
1061                 free_extent_buffer_stale(buf);
1062                 return -EIO;
1063         } else if (extent_buffer_uptodate(buf)) {
1064                 *eb = buf;
1065         } else {
1066                 free_extent_buffer(buf);
1067         }
1068         return 0;
1069 }
1070
1071 struct extent_buffer *btrfs_find_create_tree_block(
1072                                                 struct btrfs_fs_info *fs_info,
1073                                                 u64 bytenr)
1074 {
1075         if (btrfs_is_testing(fs_info))
1076                 return alloc_test_extent_buffer(fs_info, bytenr);
1077         return alloc_extent_buffer(fs_info, bytenr);
1078 }
1079
1080 /*
1081  * Read tree block at logical address @bytenr and do variant basic but critical
1082  * verification.
1083  *
1084  * @parent_transid:     expected transid of this tree block, skip check if 0
1085  * @level:              expected level, mandatory check
1086  * @first_key:          expected key in slot 0, skip check if NULL
1087  */
1088 struct extent_buffer *read_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr,
1089                                       u64 parent_transid, int level,
1090                                       struct btrfs_key *first_key)
1091 {
1092         struct extent_buffer *buf = NULL;
1093         int ret;
1094
1095         buf = btrfs_find_create_tree_block(fs_info, bytenr);
1096         if (IS_ERR(buf))
1097                 return buf;
1098
1099         ret = btree_read_extent_buffer_pages(buf, parent_transid,
1100                                              level, first_key);
1101         if (ret) {
1102                 free_extent_buffer_stale(buf);
1103                 return ERR_PTR(ret);
1104         }
1105         return buf;
1106
1107 }
1108
1109 void btrfs_clean_tree_block(struct extent_buffer *buf)
1110 {
1111         struct btrfs_fs_info *fs_info = buf->fs_info;
1112         if (btrfs_header_generation(buf) ==
1113             fs_info->running_transaction->transid) {
1114                 btrfs_assert_tree_locked(buf);
1115
1116                 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &buf->bflags)) {
1117                         percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
1118                                                  -buf->len,
1119                                                  fs_info->dirty_metadata_batch);
1120                         /* ugh, clear_extent_buffer_dirty needs to lock the page */
1121                         btrfs_set_lock_blocking_write(buf);
1122                         clear_extent_buffer_dirty(buf);
1123                 }
1124         }
1125 }
1126
1127 static struct btrfs_subvolume_writers *btrfs_alloc_subvolume_writers(void)
1128 {
1129         struct btrfs_subvolume_writers *writers;
1130         int ret;
1131
1132         writers = kmalloc(sizeof(*writers), GFP_NOFS);
1133         if (!writers)
1134                 return ERR_PTR(-ENOMEM);
1135
1136         ret = percpu_counter_init(&writers->counter, 0, GFP_NOFS);
1137         if (ret < 0) {
1138                 kfree(writers);
1139                 return ERR_PTR(ret);
1140         }
1141
1142         init_waitqueue_head(&writers->wait);
1143         return writers;
1144 }
1145
1146 static void
1147 btrfs_free_subvolume_writers(struct btrfs_subvolume_writers *writers)
1148 {
1149         percpu_counter_destroy(&writers->counter);
1150         kfree(writers);
1151 }
1152
1153 static void __setup_root(struct btrfs_root *root, struct btrfs_fs_info *fs_info,
1154                          u64 objectid)
1155 {
1156         bool dummy = test_bit(BTRFS_FS_STATE_DUMMY_FS_INFO, &fs_info->fs_state);
1157         root->node = NULL;
1158         root->commit_root = NULL;
1159         root->state = 0;
1160         root->orphan_cleanup_state = 0;
1161
1162         root->last_trans = 0;
1163         root->highest_objectid = 0;
1164         root->nr_delalloc_inodes = 0;
1165         root->nr_ordered_extents = 0;
1166         root->inode_tree = RB_ROOT;
1167         INIT_RADIX_TREE(&root->delayed_nodes_tree, GFP_ATOMIC);
1168         root->block_rsv = NULL;
1169
1170         INIT_LIST_HEAD(&root->dirty_list);
1171         INIT_LIST_HEAD(&root->root_list);
1172         INIT_LIST_HEAD(&root->delalloc_inodes);
1173         INIT_LIST_HEAD(&root->delalloc_root);
1174         INIT_LIST_HEAD(&root->ordered_extents);
1175         INIT_LIST_HEAD(&root->ordered_root);
1176         INIT_LIST_HEAD(&root->reloc_dirty_list);
1177         INIT_LIST_HEAD(&root->logged_list[0]);
1178         INIT_LIST_HEAD(&root->logged_list[1]);
1179         spin_lock_init(&root->inode_lock);
1180         spin_lock_init(&root->delalloc_lock);
1181         spin_lock_init(&root->ordered_extent_lock);
1182         spin_lock_init(&root->accounting_lock);
1183         spin_lock_init(&root->log_extents_lock[0]);
1184         spin_lock_init(&root->log_extents_lock[1]);
1185         spin_lock_init(&root->qgroup_meta_rsv_lock);
1186         mutex_init(&root->objectid_mutex);
1187         mutex_init(&root->log_mutex);
1188         mutex_init(&root->ordered_extent_mutex);
1189         mutex_init(&root->delalloc_mutex);
1190         init_waitqueue_head(&root->log_writer_wait);
1191         init_waitqueue_head(&root->log_commit_wait[0]);
1192         init_waitqueue_head(&root->log_commit_wait[1]);
1193         INIT_LIST_HEAD(&root->log_ctxs[0]);
1194         INIT_LIST_HEAD(&root->log_ctxs[1]);
1195         atomic_set(&root->log_commit[0], 0);
1196         atomic_set(&root->log_commit[1], 0);
1197         atomic_set(&root->log_writers, 0);
1198         atomic_set(&root->log_batch, 0);
1199         refcount_set(&root->refs, 1);
1200         atomic_set(&root->will_be_snapshotted, 0);
1201         atomic_set(&root->snapshot_force_cow, 0);
1202         atomic_set(&root->nr_swapfiles, 0);
1203         root->log_transid = 0;
1204         root->log_transid_committed = -1;
1205         root->last_log_commit = 0;
1206         if (!dummy)
1207                 extent_io_tree_init(fs_info, &root->dirty_log_pages,
1208                                     IO_TREE_ROOT_DIRTY_LOG_PAGES, NULL);
1209
1210         memset(&root->root_key, 0, sizeof(root->root_key));
1211         memset(&root->root_item, 0, sizeof(root->root_item));
1212         memset(&root->defrag_progress, 0, sizeof(root->defrag_progress));
1213         if (!dummy)
1214                 root->defrag_trans_start = fs_info->generation;
1215         else
1216                 root->defrag_trans_start = 0;
1217         root->root_key.objectid = objectid;
1218         root->anon_dev = 0;
1219
1220         spin_lock_init(&root->root_item_lock);
1221         btrfs_qgroup_init_swapped_blocks(&root->swapped_blocks);
1222 }
1223
1224 static struct btrfs_root *btrfs_alloc_root(struct btrfs_fs_info *fs_info,
1225                 gfp_t flags)
1226 {
1227         struct btrfs_root *root = kzalloc(sizeof(*root), flags);
1228         if (root)
1229                 root->fs_info = fs_info;
1230         return root;
1231 }
1232
1233 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
1234 /* Should only be used by the testing infrastructure */
1235 struct btrfs_root *btrfs_alloc_dummy_root(struct btrfs_fs_info *fs_info)
1236 {
1237         struct btrfs_root *root;
1238
1239         if (!fs_info)
1240                 return ERR_PTR(-EINVAL);
1241
1242         root = btrfs_alloc_root(fs_info, GFP_KERNEL);
1243         if (!root)
1244                 return ERR_PTR(-ENOMEM);
1245
1246         /* We don't use the stripesize in selftest, set it as sectorsize */
1247         __setup_root(root, fs_info, BTRFS_ROOT_TREE_OBJECTID);
1248         root->alloc_bytenr = 0;
1249
1250         return root;
1251 }
1252 #endif
1253
1254 struct btrfs_root *btrfs_create_tree(struct btrfs_trans_handle *trans,
1255                                      u64 objectid)
1256 {
1257         struct btrfs_fs_info *fs_info = trans->fs_info;
1258         struct extent_buffer *leaf;
1259         struct btrfs_root *tree_root = fs_info->tree_root;
1260         struct btrfs_root *root;
1261         struct btrfs_key key;
1262         unsigned int nofs_flag;
1263         int ret = 0;
1264         uuid_le uuid = NULL_UUID_LE;
1265
1266         /*
1267          * We're holding a transaction handle, so use a NOFS memory allocation
1268          * context to avoid deadlock if reclaim happens.
1269          */
1270         nofs_flag = memalloc_nofs_save();
1271         root = btrfs_alloc_root(fs_info, GFP_KERNEL);
1272         memalloc_nofs_restore(nofs_flag);
1273         if (!root)
1274                 return ERR_PTR(-ENOMEM);
1275
1276         __setup_root(root, fs_info, objectid);
1277         root->root_key.objectid = objectid;
1278         root->root_key.type = BTRFS_ROOT_ITEM_KEY;
1279         root->root_key.offset = 0;
1280
1281         leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0);
1282         if (IS_ERR(leaf)) {
1283                 ret = PTR_ERR(leaf);
1284                 leaf = NULL;
1285                 goto fail;
1286         }
1287
1288         root->node = leaf;
1289         btrfs_mark_buffer_dirty(leaf);
1290
1291         root->commit_root = btrfs_root_node(root);
1292         set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
1293
1294         root->root_item.flags = 0;
1295         root->root_item.byte_limit = 0;
1296         btrfs_set_root_bytenr(&root->root_item, leaf->start);
1297         btrfs_set_root_generation(&root->root_item, trans->transid);
1298         btrfs_set_root_level(&root->root_item, 0);
1299         btrfs_set_root_refs(&root->root_item, 1);
1300         btrfs_set_root_used(&root->root_item, leaf->len);
1301         btrfs_set_root_last_snapshot(&root->root_item, 0);
1302         btrfs_set_root_dirid(&root->root_item, 0);
1303         if (is_fstree(objectid))
1304                 uuid_le_gen(&uuid);
1305         memcpy(root->root_item.uuid, uuid.b, BTRFS_UUID_SIZE);
1306         root->root_item.drop_level = 0;
1307
1308         key.objectid = objectid;
1309         key.type = BTRFS_ROOT_ITEM_KEY;
1310         key.offset = 0;
1311         ret = btrfs_insert_root(trans, tree_root, &key, &root->root_item);
1312         if (ret)
1313                 goto fail;
1314
1315         btrfs_tree_unlock(leaf);
1316
1317         return root;
1318
1319 fail:
1320         if (leaf) {
1321                 btrfs_tree_unlock(leaf);
1322                 free_extent_buffer(root->commit_root);
1323                 free_extent_buffer(leaf);
1324         }
1325         kfree(root);
1326
1327         return ERR_PTR(ret);
1328 }
1329
1330 static struct btrfs_root *alloc_log_tree(struct btrfs_trans_handle *trans,
1331                                          struct btrfs_fs_info *fs_info)
1332 {
1333         struct btrfs_root *root;
1334         struct extent_buffer *leaf;
1335
1336         root = btrfs_alloc_root(fs_info, GFP_NOFS);
1337         if (!root)
1338                 return ERR_PTR(-ENOMEM);
1339
1340         __setup_root(root, fs_info, BTRFS_TREE_LOG_OBJECTID);
1341
1342         root->root_key.objectid = BTRFS_TREE_LOG_OBJECTID;
1343         root->root_key.type = BTRFS_ROOT_ITEM_KEY;
1344         root->root_key.offset = BTRFS_TREE_LOG_OBJECTID;
1345
1346         /*
1347          * DON'T set REF_COWS for log trees
1348          *
1349          * log trees do not get reference counted because they go away
1350          * before a real commit is actually done.  They do store pointers
1351          * to file data extents, and those reference counts still get
1352          * updated (along with back refs to the log tree).
1353          */
1354
1355         leaf = btrfs_alloc_tree_block(trans, root, 0, BTRFS_TREE_LOG_OBJECTID,
1356                         NULL, 0, 0, 0);
1357         if (IS_ERR(leaf)) {
1358                 kfree(root);
1359                 return ERR_CAST(leaf);
1360         }
1361
1362         root->node = leaf;
1363
1364         btrfs_mark_buffer_dirty(root->node);
1365         btrfs_tree_unlock(root->node);
1366         return root;
1367 }
1368
1369 int btrfs_init_log_root_tree(struct btrfs_trans_handle *trans,
1370                              struct btrfs_fs_info *fs_info)
1371 {
1372         struct btrfs_root *log_root;
1373
1374         log_root = alloc_log_tree(trans, fs_info);
1375         if (IS_ERR(log_root))
1376                 return PTR_ERR(log_root);
1377         WARN_ON(fs_info->log_root_tree);
1378         fs_info->log_root_tree = log_root;
1379         return 0;
1380 }
1381
1382 int btrfs_add_log_tree(struct btrfs_trans_handle *trans,
1383                        struct btrfs_root *root)
1384 {
1385         struct btrfs_fs_info *fs_info = root->fs_info;
1386         struct btrfs_root *log_root;
1387         struct btrfs_inode_item *inode_item;
1388
1389         log_root = alloc_log_tree(trans, fs_info);
1390         if (IS_ERR(log_root))
1391                 return PTR_ERR(log_root);
1392
1393         log_root->last_trans = trans->transid;
1394         log_root->root_key.offset = root->root_key.objectid;
1395
1396         inode_item = &log_root->root_item.inode;
1397         btrfs_set_stack_inode_generation(inode_item, 1);
1398         btrfs_set_stack_inode_size(inode_item, 3);
1399         btrfs_set_stack_inode_nlink(inode_item, 1);
1400         btrfs_set_stack_inode_nbytes(inode_item,
1401                                      fs_info->nodesize);
1402         btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
1403
1404         btrfs_set_root_node(&log_root->root_item, log_root->node);
1405
1406         WARN_ON(root->log_root);
1407         root->log_root = log_root;
1408         root->log_transid = 0;
1409         root->log_transid_committed = -1;
1410         root->last_log_commit = 0;
1411         return 0;
1412 }
1413
1414 static struct btrfs_root *btrfs_read_tree_root(struct btrfs_root *tree_root,
1415                                                struct btrfs_key *key)
1416 {
1417         struct btrfs_root *root;
1418         struct btrfs_fs_info *fs_info = tree_root->fs_info;
1419         struct btrfs_path *path;
1420         u64 generation;
1421         int ret;
1422         int level;
1423
1424         path = btrfs_alloc_path();
1425         if (!path)
1426                 return ERR_PTR(-ENOMEM);
1427
1428         root = btrfs_alloc_root(fs_info, GFP_NOFS);
1429         if (!root) {
1430                 ret = -ENOMEM;
1431                 goto alloc_fail;
1432         }
1433
1434         __setup_root(root, fs_info, key->objectid);
1435
1436         ret = btrfs_find_root(tree_root, key, path,
1437                               &root->root_item, &root->root_key);
1438         if (ret) {
1439                 if (ret > 0)
1440                         ret = -ENOENT;
1441                 goto find_fail;
1442         }
1443
1444         generation = btrfs_root_generation(&root->root_item);
1445         level = btrfs_root_level(&root->root_item);
1446         root->node = read_tree_block(fs_info,
1447                                      btrfs_root_bytenr(&root->root_item),
1448                                      generation, level, NULL);
1449         if (IS_ERR(root->node)) {
1450                 ret = PTR_ERR(root->node);
1451                 goto find_fail;
1452         } else if (!btrfs_buffer_uptodate(root->node, generation, 0)) {
1453                 ret = -EIO;
1454                 free_extent_buffer(root->node);
1455                 goto find_fail;
1456         }
1457         root->commit_root = btrfs_root_node(root);
1458 out:
1459         btrfs_free_path(path);
1460         return root;
1461
1462 find_fail:
1463         kfree(root);
1464 alloc_fail:
1465         root = ERR_PTR(ret);
1466         goto out;
1467 }
1468
1469 struct btrfs_root *btrfs_read_fs_root(struct btrfs_root *tree_root,
1470                                       struct btrfs_key *location)
1471 {
1472         struct btrfs_root *root;
1473
1474         root = btrfs_read_tree_root(tree_root, location);
1475         if (IS_ERR(root))
1476                 return root;
1477
1478         if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
1479                 set_bit(BTRFS_ROOT_REF_COWS, &root->state);
1480                 btrfs_check_and_init_root_item(&root->root_item);
1481         }
1482
1483         return root;
1484 }
1485
1486 int btrfs_init_fs_root(struct btrfs_root *root)
1487 {
1488         int ret;
1489         struct btrfs_subvolume_writers *writers;
1490
1491         root->free_ino_ctl = kzalloc(sizeof(*root->free_ino_ctl), GFP_NOFS);
1492         root->free_ino_pinned = kzalloc(sizeof(*root->free_ino_pinned),
1493                                         GFP_NOFS);
1494         if (!root->free_ino_pinned || !root->free_ino_ctl) {
1495                 ret = -ENOMEM;
1496                 goto fail;
1497         }
1498
1499         writers = btrfs_alloc_subvolume_writers();
1500         if (IS_ERR(writers)) {
1501                 ret = PTR_ERR(writers);
1502                 goto fail;
1503         }
1504         root->subv_writers = writers;
1505
1506         btrfs_init_free_ino_ctl(root);
1507         spin_lock_init(&root->ino_cache_lock);
1508         init_waitqueue_head(&root->ino_cache_wait);
1509
1510         ret = get_anon_bdev(&root->anon_dev);
1511         if (ret)
1512                 goto fail;
1513
1514         mutex_lock(&root->objectid_mutex);
1515         ret = btrfs_find_highest_objectid(root,
1516                                         &root->highest_objectid);
1517         if (ret) {
1518                 mutex_unlock(&root->objectid_mutex);
1519                 goto fail;
1520         }
1521
1522         ASSERT(root->highest_objectid <= BTRFS_LAST_FREE_OBJECTID);
1523
1524         mutex_unlock(&root->objectid_mutex);
1525
1526         return 0;
1527 fail:
1528         /* The caller is responsible to call btrfs_free_fs_root */
1529         return ret;
1530 }
1531
1532 struct btrfs_root *btrfs_lookup_fs_root(struct btrfs_fs_info *fs_info,
1533                                         u64 root_id)
1534 {
1535         struct btrfs_root *root;
1536
1537         spin_lock(&fs_info->fs_roots_radix_lock);
1538         root = radix_tree_lookup(&fs_info->fs_roots_radix,
1539                                  (unsigned long)root_id);
1540         spin_unlock(&fs_info->fs_roots_radix_lock);
1541         return root;
1542 }
1543
1544 int btrfs_insert_fs_root(struct btrfs_fs_info *fs_info,
1545                          struct btrfs_root *root)
1546 {
1547         int ret;
1548
1549         ret = radix_tree_preload(GFP_NOFS);
1550         if (ret)
1551                 return ret;
1552
1553         spin_lock(&fs_info->fs_roots_radix_lock);
1554         ret = radix_tree_insert(&fs_info->fs_roots_radix,
1555                                 (unsigned long)root->root_key.objectid,
1556                                 root);
1557         if (ret == 0)
1558                 set_bit(BTRFS_ROOT_IN_RADIX, &root->state);
1559         spin_unlock(&fs_info->fs_roots_radix_lock);
1560         radix_tree_preload_end();
1561
1562         return ret;
1563 }
1564
1565 struct btrfs_root *btrfs_get_fs_root(struct btrfs_fs_info *fs_info,
1566                                      struct btrfs_key *location,
1567                                      bool check_ref)
1568 {
1569         struct btrfs_root *root;
1570         struct btrfs_path *path;
1571         struct btrfs_key key;
1572         int ret;
1573
1574         if (location->objectid == BTRFS_ROOT_TREE_OBJECTID)
1575                 return fs_info->tree_root;
1576         if (location->objectid == BTRFS_EXTENT_TREE_OBJECTID)
1577                 return fs_info->extent_root;
1578         if (location->objectid == BTRFS_CHUNK_TREE_OBJECTID)
1579                 return fs_info->chunk_root;
1580         if (location->objectid == BTRFS_DEV_TREE_OBJECTID)
1581                 return fs_info->dev_root;
1582         if (location->objectid == BTRFS_CSUM_TREE_OBJECTID)
1583                 return fs_info->csum_root;
1584         if (location->objectid == BTRFS_QUOTA_TREE_OBJECTID)
1585                 return fs_info->quota_root ? fs_info->quota_root :
1586                                              ERR_PTR(-ENOENT);
1587         if (location->objectid == BTRFS_UUID_TREE_OBJECTID)
1588                 return fs_info->uuid_root ? fs_info->uuid_root :
1589                                             ERR_PTR(-ENOENT);
1590         if (location->objectid == BTRFS_FREE_SPACE_TREE_OBJECTID)
1591                 return fs_info->free_space_root ? fs_info->free_space_root :
1592                                                   ERR_PTR(-ENOENT);
1593 again:
1594         root = btrfs_lookup_fs_root(fs_info, location->objectid);
1595         if (root) {
1596                 if (check_ref && btrfs_root_refs(&root->root_item) == 0)
1597                         return ERR_PTR(-ENOENT);
1598                 return root;
1599         }
1600
1601         root = btrfs_read_fs_root(fs_info->tree_root, location);
1602         if (IS_ERR(root))
1603                 return root;
1604
1605         if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
1606                 ret = -ENOENT;
1607                 goto fail;
1608         }
1609
1610         ret = btrfs_init_fs_root(root);
1611         if (ret)
1612                 goto fail;
1613
1614         path = btrfs_alloc_path();
1615         if (!path) {
1616                 ret = -ENOMEM;
1617                 goto fail;
1618         }
1619         key.objectid = BTRFS_ORPHAN_OBJECTID;
1620         key.type = BTRFS_ORPHAN_ITEM_KEY;
1621         key.offset = location->objectid;
1622
1623         ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
1624         btrfs_free_path(path);
1625         if (ret < 0)
1626                 goto fail;
1627         if (ret == 0)
1628                 set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state);
1629
1630         ret = btrfs_insert_fs_root(fs_info, root);
1631         if (ret) {
1632                 if (ret == -EEXIST) {
1633                         btrfs_free_fs_root(root);
1634                         goto again;
1635                 }
1636                 goto fail;
1637         }
1638         return root;
1639 fail:
1640         btrfs_free_fs_root(root);
1641         return ERR_PTR(ret);
1642 }
1643
1644 static int btrfs_congested_fn(void *congested_data, int bdi_bits)
1645 {
1646         struct btrfs_fs_info *info = (struct btrfs_fs_info *)congested_data;
1647         int ret = 0;
1648         struct btrfs_device *device;
1649         struct backing_dev_info *bdi;
1650
1651         rcu_read_lock();
1652         list_for_each_entry_rcu(device, &info->fs_devices->devices, dev_list) {
1653                 if (!device->bdev)
1654                         continue;
1655                 bdi = device->bdev->bd_bdi;
1656                 if (bdi_congested(bdi, bdi_bits)) {
1657                         ret = 1;
1658                         break;
1659                 }
1660         }
1661         rcu_read_unlock();
1662         return ret;
1663 }
1664
1665 /*
1666  * called by the kthread helper functions to finally call the bio end_io
1667  * functions.  This is where read checksum verification actually happens
1668  */
1669 static void end_workqueue_fn(struct btrfs_work *work)
1670 {
1671         struct bio *bio;
1672         struct btrfs_end_io_wq *end_io_wq;
1673
1674         end_io_wq = container_of(work, struct btrfs_end_io_wq, work);
1675         bio = end_io_wq->bio;
1676
1677         bio->bi_status = end_io_wq->status;
1678         bio->bi_private = end_io_wq->private;
1679         bio->bi_end_io = end_io_wq->end_io;
1680         kmem_cache_free(btrfs_end_io_wq_cache, end_io_wq);
1681         bio_endio(bio);
1682 }
1683
1684 static int cleaner_kthread(void *arg)
1685 {
1686         struct btrfs_root *root = arg;
1687         struct btrfs_fs_info *fs_info = root->fs_info;
1688         int again;
1689
1690         while (1) {
1691                 again = 0;
1692
1693                 set_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1694
1695                 /* Make the cleaner go to sleep early. */
1696                 if (btrfs_need_cleaner_sleep(fs_info))
1697                         goto sleep;
1698
1699                 /*
1700                  * Do not do anything if we might cause open_ctree() to block
1701                  * before we have finished mounting the filesystem.
1702                  */
1703                 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
1704                         goto sleep;
1705
1706                 if (!mutex_trylock(&fs_info->cleaner_mutex))
1707                         goto sleep;
1708
1709                 /*
1710                  * Avoid the problem that we change the status of the fs
1711                  * during the above check and trylock.
1712                  */
1713                 if (btrfs_need_cleaner_sleep(fs_info)) {
1714                         mutex_unlock(&fs_info->cleaner_mutex);
1715                         goto sleep;
1716                 }
1717
1718                 btrfs_run_delayed_iputs(fs_info);
1719
1720                 again = btrfs_clean_one_deleted_snapshot(root);
1721                 mutex_unlock(&fs_info->cleaner_mutex);
1722
1723                 /*
1724                  * The defragger has dealt with the R/O remount and umount,
1725                  * needn't do anything special here.
1726                  */
1727                 btrfs_run_defrag_inodes(fs_info);
1728
1729                 /*
1730                  * Acquires fs_info->delete_unused_bgs_mutex to avoid racing
1731                  * with relocation (btrfs_relocate_chunk) and relocation
1732                  * acquires fs_info->cleaner_mutex (btrfs_relocate_block_group)
1733                  * after acquiring fs_info->delete_unused_bgs_mutex. So we
1734                  * can't hold, nor need to, fs_info->cleaner_mutex when deleting
1735                  * unused block groups.
1736                  */
1737                 btrfs_delete_unused_bgs(fs_info);
1738 sleep:
1739                 clear_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1740                 if (kthread_should_park())
1741                         kthread_parkme();
1742                 if (kthread_should_stop())
1743                         return 0;
1744                 if (!again) {
1745                         set_current_state(TASK_INTERRUPTIBLE);
1746                         schedule();
1747                         __set_current_state(TASK_RUNNING);
1748                 }
1749         }
1750 }
1751
1752 static int transaction_kthread(void *arg)
1753 {
1754         struct btrfs_root *root = arg;
1755         struct btrfs_fs_info *fs_info = root->fs_info;
1756         struct btrfs_trans_handle *trans;
1757         struct btrfs_transaction *cur;
1758         u64 transid;
1759         time64_t now;
1760         unsigned long delay;
1761         bool cannot_commit;
1762
1763         do {
1764                 cannot_commit = false;
1765                 delay = HZ * fs_info->commit_interval;
1766                 mutex_lock(&fs_info->transaction_kthread_mutex);
1767
1768                 spin_lock(&fs_info->trans_lock);
1769                 cur = fs_info->running_transaction;
1770                 if (!cur) {
1771                         spin_unlock(&fs_info->trans_lock);
1772                         goto sleep;
1773                 }
1774
1775                 now = ktime_get_seconds();
1776                 if (cur->state < TRANS_STATE_BLOCKED &&
1777                     !test_bit(BTRFS_FS_NEED_ASYNC_COMMIT, &fs_info->flags) &&
1778                     (now < cur->start_time ||
1779                      now - cur->start_time < fs_info->commit_interval)) {
1780                         spin_unlock(&fs_info->trans_lock);
1781                         delay = HZ * 5;
1782                         goto sleep;
1783                 }
1784                 transid = cur->transid;
1785                 spin_unlock(&fs_info->trans_lock);
1786
1787                 /* If the file system is aborted, this will always fail. */
1788                 trans = btrfs_attach_transaction(root);
1789                 if (IS_ERR(trans)) {
1790                         if (PTR_ERR(trans) != -ENOENT)
1791                                 cannot_commit = true;
1792                         goto sleep;
1793                 }
1794                 if (transid == trans->transid) {
1795                         btrfs_commit_transaction(trans);
1796                 } else {
1797                         btrfs_end_transaction(trans);
1798                 }
1799 sleep:
1800                 wake_up_process(fs_info->cleaner_kthread);
1801                 mutex_unlock(&fs_info->transaction_kthread_mutex);
1802
1803                 if (unlikely(test_bit(BTRFS_FS_STATE_ERROR,
1804                                       &fs_info->fs_state)))
1805                         btrfs_cleanup_transaction(fs_info);
1806                 if (!kthread_should_stop() &&
1807                                 (!btrfs_transaction_blocked(fs_info) ||
1808                                  cannot_commit))
1809                         schedule_timeout_interruptible(delay);
1810         } while (!kthread_should_stop());
1811         return 0;
1812 }
1813
1814 /*
1815  * this will find the highest generation in the array of
1816  * root backups.  The index of the highest array is returned,
1817  * or -1 if we can't find anything.
1818  *
1819  * We check to make sure the array is valid by comparing the
1820  * generation of the latest  root in the array with the generation
1821  * in the super block.  If they don't match we pitch it.
1822  */
1823 static int find_newest_super_backup(struct btrfs_fs_info *info, u64 newest_gen)
1824 {
1825         u64 cur;
1826         int newest_index = -1;
1827         struct btrfs_root_backup *root_backup;
1828         int i;
1829
1830         for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
1831                 root_backup = info->super_copy->super_roots + i;
1832                 cur = btrfs_backup_tree_root_gen(root_backup);
1833                 if (cur == newest_gen)
1834                         newest_index = i;
1835         }
1836
1837         /* check to see if we actually wrapped around */
1838         if (newest_index == BTRFS_NUM_BACKUP_ROOTS - 1) {
1839                 root_backup = info->super_copy->super_roots;
1840                 cur = btrfs_backup_tree_root_gen(root_backup);
1841                 if (cur == newest_gen)
1842                         newest_index = 0;
1843         }
1844         return newest_index;
1845 }
1846
1847
1848 /*
1849  * find the oldest backup so we know where to store new entries
1850  * in the backup array.  This will set the backup_root_index
1851  * field in the fs_info struct
1852  */
1853 static void find_oldest_super_backup(struct btrfs_fs_info *info,
1854                                      u64 newest_gen)
1855 {
1856         int newest_index = -1;
1857
1858         newest_index = find_newest_super_backup(info, newest_gen);
1859         /* if there was garbage in there, just move along */
1860         if (newest_index == -1) {
1861                 info->backup_root_index = 0;
1862         } else {
1863                 info->backup_root_index = (newest_index + 1) % BTRFS_NUM_BACKUP_ROOTS;
1864         }
1865 }
1866
1867 /*
1868  * copy all the root pointers into the super backup array.
1869  * this will bump the backup pointer by one when it is
1870  * done
1871  */
1872 static void backup_super_roots(struct btrfs_fs_info *info)
1873 {
1874         int next_backup;
1875         struct btrfs_root_backup *root_backup;
1876         int last_backup;
1877
1878         next_backup = info->backup_root_index;
1879         last_backup = (next_backup + BTRFS_NUM_BACKUP_ROOTS - 1) %
1880                 BTRFS_NUM_BACKUP_ROOTS;
1881
1882         /*
1883          * just overwrite the last backup if we're at the same generation
1884          * this happens only at umount
1885          */
1886         root_backup = info->super_for_commit->super_roots + last_backup;
1887         if (btrfs_backup_tree_root_gen(root_backup) ==
1888             btrfs_header_generation(info->tree_root->node))
1889                 next_backup = last_backup;
1890
1891         root_backup = info->super_for_commit->super_roots + next_backup;
1892
1893         /*
1894          * make sure all of our padding and empty slots get zero filled
1895          * regardless of which ones we use today
1896          */
1897         memset(root_backup, 0, sizeof(*root_backup));
1898
1899         info->backup_root_index = (next_backup + 1) % BTRFS_NUM_BACKUP_ROOTS;
1900
1901         btrfs_set_backup_tree_root(root_backup, info->tree_root->node->start);
1902         btrfs_set_backup_tree_root_gen(root_backup,
1903                                btrfs_header_generation(info->tree_root->node));
1904
1905         btrfs_set_backup_tree_root_level(root_backup,
1906                                btrfs_header_level(info->tree_root->node));
1907
1908         btrfs_set_backup_chunk_root(root_backup, info->chunk_root->node->start);
1909         btrfs_set_backup_chunk_root_gen(root_backup,
1910                                btrfs_header_generation(info->chunk_root->node));
1911         btrfs_set_backup_chunk_root_level(root_backup,
1912                                btrfs_header_level(info->chunk_root->node));
1913
1914         btrfs_set_backup_extent_root(root_backup, info->extent_root->node->start);
1915         btrfs_set_backup_extent_root_gen(root_backup,
1916                                btrfs_header_generation(info->extent_root->node));
1917         btrfs_set_backup_extent_root_level(root_backup,
1918                                btrfs_header_level(info->extent_root->node));
1919
1920         /*
1921          * we might commit during log recovery, which happens before we set
1922          * the fs_root.  Make sure it is valid before we fill it in.
1923          */
1924         if (info->fs_root && info->fs_root->node) {
1925                 btrfs_set_backup_fs_root(root_backup,
1926                                          info->fs_root->node->start);
1927                 btrfs_set_backup_fs_root_gen(root_backup,
1928                                btrfs_header_generation(info->fs_root->node));
1929                 btrfs_set_backup_fs_root_level(root_backup,
1930                                btrfs_header_level(info->fs_root->node));
1931         }
1932
1933         btrfs_set_backup_dev_root(root_backup, info->dev_root->node->start);
1934         btrfs_set_backup_dev_root_gen(root_backup,
1935                                btrfs_header_generation(info->dev_root->node));
1936         btrfs_set_backup_dev_root_level(root_backup,
1937                                        btrfs_header_level(info->dev_root->node));
1938
1939         btrfs_set_backup_csum_root(root_backup, info->csum_root->node->start);
1940         btrfs_set_backup_csum_root_gen(root_backup,
1941                                btrfs_header_generation(info->csum_root->node));
1942         btrfs_set_backup_csum_root_level(root_backup,
1943                                btrfs_header_level(info->csum_root->node));
1944
1945         btrfs_set_backup_total_bytes(root_backup,
1946                              btrfs_super_total_bytes(info->super_copy));
1947         btrfs_set_backup_bytes_used(root_backup,
1948                              btrfs_super_bytes_used(info->super_copy));
1949         btrfs_set_backup_num_devices(root_backup,
1950                              btrfs_super_num_devices(info->super_copy));
1951
1952         /*
1953          * if we don't copy this out to the super_copy, it won't get remembered
1954          * for the next commit
1955          */
1956         memcpy(&info->super_copy->super_roots,
1957                &info->super_for_commit->super_roots,
1958                sizeof(*root_backup) * BTRFS_NUM_BACKUP_ROOTS);
1959 }
1960
1961 /*
1962  * this copies info out of the root backup array and back into
1963  * the in-memory super block.  It is meant to help iterate through
1964  * the array, so you send it the number of backups you've already
1965  * tried and the last backup index you used.
1966  *
1967  * this returns -1 when it has tried all the backups
1968  */
1969 static noinline int next_root_backup(struct btrfs_fs_info *info,
1970                                      struct btrfs_super_block *super,
1971                                      int *num_backups_tried, int *backup_index)
1972 {
1973         struct btrfs_root_backup *root_backup;
1974         int newest = *backup_index;
1975
1976         if (*num_backups_tried == 0) {
1977                 u64 gen = btrfs_super_generation(super);
1978
1979                 newest = find_newest_super_backup(info, gen);
1980                 if (newest == -1)
1981                         return -1;
1982
1983                 *backup_index = newest;
1984                 *num_backups_tried = 1;
1985         } else if (*num_backups_tried == BTRFS_NUM_BACKUP_ROOTS) {
1986                 /* we've tried all the backups, all done */
1987                 return -1;
1988         } else {
1989                 /* jump to the next oldest backup */
1990                 newest = (*backup_index + BTRFS_NUM_BACKUP_ROOTS - 1) %
1991                         BTRFS_NUM_BACKUP_ROOTS;
1992                 *backup_index = newest;
1993                 *num_backups_tried += 1;
1994         }
1995         root_backup = super->super_roots + newest;
1996
1997         btrfs_set_super_generation(super,
1998                                    btrfs_backup_tree_root_gen(root_backup));
1999         btrfs_set_super_root(super, btrfs_backup_tree_root(root_backup));
2000         btrfs_set_super_root_level(super,
2001                                    btrfs_backup_tree_root_level(root_backup));
2002         btrfs_set_super_bytes_used(super, btrfs_backup_bytes_used(root_backup));
2003
2004         /*
2005          * fixme: the total bytes and num_devices need to match or we should
2006          * need a fsck
2007          */
2008         btrfs_set_super_total_bytes(super, btrfs_backup_total_bytes(root_backup));
2009         btrfs_set_super_num_devices(super, btrfs_backup_num_devices(root_backup));
2010         return 0;
2011 }
2012
2013 /* helper to cleanup workers */
2014 static void btrfs_stop_all_workers(struct btrfs_fs_info *fs_info)
2015 {
2016         btrfs_destroy_workqueue(fs_info->fixup_workers);
2017         btrfs_destroy_workqueue(fs_info->delalloc_workers);
2018         btrfs_destroy_workqueue(fs_info->workers);
2019         btrfs_destroy_workqueue(fs_info->endio_workers);
2020         btrfs_destroy_workqueue(fs_info->endio_raid56_workers);
2021         btrfs_destroy_workqueue(fs_info->endio_repair_workers);
2022         btrfs_destroy_workqueue(fs_info->rmw_workers);
2023         btrfs_destroy_workqueue(fs_info->endio_write_workers);
2024         btrfs_destroy_workqueue(fs_info->endio_freespace_worker);
2025         btrfs_destroy_workqueue(fs_info->submit_workers);
2026         btrfs_destroy_workqueue(fs_info->delayed_workers);
2027         btrfs_destroy_workqueue(fs_info->caching_workers);
2028         btrfs_destroy_workqueue(fs_info->readahead_workers);
2029         btrfs_destroy_workqueue(fs_info->flush_workers);
2030         btrfs_destroy_workqueue(fs_info->qgroup_rescan_workers);
2031         btrfs_destroy_workqueue(fs_info->extent_workers);
2032         /*
2033          * Now that all other work queues are destroyed, we can safely destroy
2034          * the queues used for metadata I/O, since tasks from those other work
2035          * queues can do metadata I/O operations.
2036          */
2037         btrfs_destroy_workqueue(fs_info->endio_meta_workers);
2038         btrfs_destroy_workqueue(fs_info->endio_meta_write_workers);
2039 }
2040
2041 static void free_root_extent_buffers(struct btrfs_root *root)
2042 {
2043         if (root) {
2044                 free_extent_buffer(root->node);
2045                 free_extent_buffer(root->commit_root);
2046                 root->node = NULL;
2047                 root->commit_root = NULL;
2048         }
2049 }
2050
2051 /* helper to cleanup tree roots */
2052 static void free_root_pointers(struct btrfs_fs_info *info, int chunk_root)
2053 {
2054         free_root_extent_buffers(info->tree_root);
2055
2056         free_root_extent_buffers(info->dev_root);
2057         free_root_extent_buffers(info->extent_root);
2058         free_root_extent_buffers(info->csum_root);
2059         free_root_extent_buffers(info->quota_root);
2060         free_root_extent_buffers(info->uuid_root);
2061         if (chunk_root)
2062                 free_root_extent_buffers(info->chunk_root);
2063         free_root_extent_buffers(info->free_space_root);
2064 }
2065
2066 void btrfs_free_fs_roots(struct btrfs_fs_info *fs_info)
2067 {
2068         int ret;
2069         struct btrfs_root *gang[8];
2070         int i;
2071
2072         while (!list_empty(&fs_info->dead_roots)) {
2073                 gang[0] = list_entry(fs_info->dead_roots.next,
2074                                      struct btrfs_root, root_list);
2075                 list_del(&gang[0]->root_list);
2076
2077                 if (test_bit(BTRFS_ROOT_IN_RADIX, &gang[0]->state)) {
2078                         btrfs_drop_and_free_fs_root(fs_info, gang[0]);
2079                 } else {
2080                         free_extent_buffer(gang[0]->node);
2081                         free_extent_buffer(gang[0]->commit_root);
2082                         btrfs_put_fs_root(gang[0]);
2083                 }
2084         }
2085
2086         while (1) {
2087                 ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
2088                                              (void **)gang, 0,
2089                                              ARRAY_SIZE(gang));
2090                 if (!ret)
2091                         break;
2092                 for (i = 0; i < ret; i++)
2093                         btrfs_drop_and_free_fs_root(fs_info, gang[i]);
2094         }
2095
2096         if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
2097                 btrfs_free_log_root_tree(NULL, fs_info);
2098                 btrfs_destroy_pinned_extent(fs_info, fs_info->pinned_extents);
2099         }
2100 }
2101
2102 static void btrfs_init_scrub(struct btrfs_fs_info *fs_info)
2103 {
2104         mutex_init(&fs_info->scrub_lock);
2105         atomic_set(&fs_info->scrubs_running, 0);
2106         atomic_set(&fs_info->scrub_pause_req, 0);
2107         atomic_set(&fs_info->scrubs_paused, 0);
2108         atomic_set(&fs_info->scrub_cancel_req, 0);
2109         init_waitqueue_head(&fs_info->scrub_pause_wait);
2110         refcount_set(&fs_info->scrub_workers_refcnt, 0);
2111 }
2112
2113 static void btrfs_init_balance(struct btrfs_fs_info *fs_info)
2114 {
2115         spin_lock_init(&fs_info->balance_lock);
2116         mutex_init(&fs_info->balance_mutex);
2117         atomic_set(&fs_info->balance_pause_req, 0);
2118         atomic_set(&fs_info->balance_cancel_req, 0);
2119         fs_info->balance_ctl = NULL;
2120         init_waitqueue_head(&fs_info->balance_wait_q);
2121 }
2122
2123 static void btrfs_init_btree_inode(struct btrfs_fs_info *fs_info)
2124 {
2125         struct inode *inode = fs_info->btree_inode;
2126
2127         inode->i_ino = BTRFS_BTREE_INODE_OBJECTID;
2128         set_nlink(inode, 1);
2129         /*
2130          * we set the i_size on the btree inode to the max possible int.
2131          * the real end of the address space is determined by all of
2132          * the devices in the system
2133          */
2134         inode->i_size = OFFSET_MAX;
2135         inode->i_mapping->a_ops = &btree_aops;
2136
2137         RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
2138         extent_io_tree_init(fs_info, &BTRFS_I(inode)->io_tree,
2139                             IO_TREE_INODE_IO, inode);
2140         BTRFS_I(inode)->io_tree.track_uptodate = false;
2141         extent_map_tree_init(&BTRFS_I(inode)->extent_tree);
2142
2143         BTRFS_I(inode)->io_tree.ops = &btree_extent_io_ops;
2144
2145         BTRFS_I(inode)->root = fs_info->tree_root;
2146         memset(&BTRFS_I(inode)->location, 0, sizeof(struct btrfs_key));
2147         set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
2148         btrfs_insert_inode_hash(inode);
2149 }
2150
2151 static void btrfs_init_dev_replace_locks(struct btrfs_fs_info *fs_info)
2152 {
2153         mutex_init(&fs_info->dev_replace.lock_finishing_cancel_unmount);
2154         init_rwsem(&fs_info->dev_replace.rwsem);
2155         init_waitqueue_head(&fs_info->dev_replace.replace_wait);
2156 }
2157
2158 static void btrfs_init_qgroup(struct btrfs_fs_info *fs_info)
2159 {
2160         spin_lock_init(&fs_info->qgroup_lock);
2161         mutex_init(&fs_info->qgroup_ioctl_lock);
2162         fs_info->qgroup_tree = RB_ROOT;
2163         INIT_LIST_HEAD(&fs_info->dirty_qgroups);
2164         fs_info->qgroup_seq = 1;
2165         fs_info->qgroup_ulist = NULL;
2166         fs_info->qgroup_rescan_running = false;
2167         mutex_init(&fs_info->qgroup_rescan_lock);
2168 }
2169
2170 static int btrfs_init_workqueues(struct btrfs_fs_info *fs_info,
2171                 struct btrfs_fs_devices *fs_devices)
2172 {
2173         u32 max_active = fs_info->thread_pool_size;
2174         unsigned int flags = WQ_MEM_RECLAIM | WQ_FREEZABLE | WQ_UNBOUND;
2175
2176         fs_info->workers =
2177                 btrfs_alloc_workqueue(fs_info, "worker",
2178                                       flags | WQ_HIGHPRI, max_active, 16);
2179
2180         fs_info->delalloc_workers =
2181                 btrfs_alloc_workqueue(fs_info, "delalloc",
2182                                       flags, max_active, 2);
2183
2184         fs_info->flush_workers =
2185                 btrfs_alloc_workqueue(fs_info, "flush_delalloc",
2186                                       flags, max_active, 0);
2187
2188         fs_info->caching_workers =
2189                 btrfs_alloc_workqueue(fs_info, "cache", flags, max_active, 0);
2190
2191         /*
2192          * a higher idle thresh on the submit workers makes it much more
2193          * likely that bios will be send down in a sane order to the
2194          * devices
2195          */
2196         fs_info->submit_workers =
2197                 btrfs_alloc_workqueue(fs_info, "submit", flags,
2198                                       min_t(u64, fs_devices->num_devices,
2199                                             max_active), 64);
2200
2201         fs_info->fixup_workers =
2202                 btrfs_alloc_workqueue(fs_info, "fixup", flags, 1, 0);
2203
2204         /*
2205          * endios are largely parallel and should have a very
2206          * low idle thresh
2207          */
2208         fs_info->endio_workers =
2209                 btrfs_alloc_workqueue(fs_info, "endio", flags, max_active, 4);
2210         fs_info->endio_meta_workers =
2211                 btrfs_alloc_workqueue(fs_info, "endio-meta", flags,
2212                                       max_active, 4);
2213         fs_info->endio_meta_write_workers =
2214                 btrfs_alloc_workqueue(fs_info, "endio-meta-write", flags,
2215                                       max_active, 2);
2216         fs_info->endio_raid56_workers =
2217                 btrfs_alloc_workqueue(fs_info, "endio-raid56", flags,
2218                                       max_active, 4);
2219         fs_info->endio_repair_workers =
2220                 btrfs_alloc_workqueue(fs_info, "endio-repair", flags, 1, 0);
2221         fs_info->rmw_workers =
2222                 btrfs_alloc_workqueue(fs_info, "rmw", flags, max_active, 2);
2223         fs_info->endio_write_workers =
2224                 btrfs_alloc_workqueue(fs_info, "endio-write", flags,
2225                                       max_active, 2);
2226         fs_info->endio_freespace_worker =
2227                 btrfs_alloc_workqueue(fs_info, "freespace-write", flags,
2228                                       max_active, 0);
2229         fs_info->delayed_workers =
2230                 btrfs_alloc_workqueue(fs_info, "delayed-meta", flags,
2231                                       max_active, 0);
2232         fs_info->readahead_workers =
2233                 btrfs_alloc_workqueue(fs_info, "readahead", flags,
2234                                       max_active, 2);
2235         fs_info->qgroup_rescan_workers =
2236                 btrfs_alloc_workqueue(fs_info, "qgroup-rescan", flags, 1, 0);
2237         fs_info->extent_workers =
2238                 btrfs_alloc_workqueue(fs_info, "extent-refs", flags,
2239                                       min_t(u64, fs_devices->num_devices,
2240                                             max_active), 8);
2241
2242         if (!(fs_info->workers && fs_info->delalloc_workers &&
2243               fs_info->submit_workers && fs_info->flush_workers &&
2244               fs_info->endio_workers && fs_info->endio_meta_workers &&
2245               fs_info->endio_meta_write_workers &&
2246               fs_info->endio_repair_workers &&
2247               fs_info->endio_write_workers && fs_info->endio_raid56_workers &&
2248               fs_info->endio_freespace_worker && fs_info->rmw_workers &&
2249               fs_info->caching_workers && fs_info->readahead_workers &&
2250               fs_info->fixup_workers && fs_info->delayed_workers &&
2251               fs_info->extent_workers &&
2252               fs_info->qgroup_rescan_workers)) {
2253                 return -ENOMEM;
2254         }
2255
2256         return 0;
2257 }
2258
2259 static int btrfs_replay_log(struct btrfs_fs_info *fs_info,
2260                             struct btrfs_fs_devices *fs_devices)
2261 {
2262         int ret;
2263         struct btrfs_root *log_tree_root;
2264         struct btrfs_super_block *disk_super = fs_info->super_copy;
2265         u64 bytenr = btrfs_super_log_root(disk_super);
2266         int level = btrfs_super_log_root_level(disk_super);
2267
2268         if (fs_devices->rw_devices == 0) {
2269                 btrfs_warn(fs_info, "log replay required on RO media");
2270                 return -EIO;
2271         }
2272
2273         log_tree_root = btrfs_alloc_root(fs_info, GFP_KERNEL);
2274         if (!log_tree_root)
2275                 return -ENOMEM;
2276
2277         __setup_root(log_tree_root, fs_info, BTRFS_TREE_LOG_OBJECTID);
2278
2279         log_tree_root->node = read_tree_block(fs_info, bytenr,
2280                                               fs_info->generation + 1,
2281                                               level, NULL);
2282         if (IS_ERR(log_tree_root->node)) {
2283                 btrfs_warn(fs_info, "failed to read log tree");
2284                 ret = PTR_ERR(log_tree_root->node);
2285                 kfree(log_tree_root);
2286                 return ret;
2287         } else if (!extent_buffer_uptodate(log_tree_root->node)) {
2288                 btrfs_err(fs_info, "failed to read log tree");
2289                 free_extent_buffer(log_tree_root->node);
2290                 kfree(log_tree_root);
2291                 return -EIO;
2292         }
2293         /* returns with log_tree_root freed on success */
2294         ret = btrfs_recover_log_trees(log_tree_root);
2295         if (ret) {
2296                 btrfs_handle_fs_error(fs_info, ret,
2297                                       "Failed to recover log tree");
2298                 free_extent_buffer(log_tree_root->node);
2299                 kfree(log_tree_root);
2300                 return ret;
2301         }
2302
2303         if (sb_rdonly(fs_info->sb)) {
2304                 ret = btrfs_commit_super(fs_info);
2305                 if (ret)
2306                         return ret;
2307         }
2308
2309         return 0;
2310 }
2311
2312 static int btrfs_read_roots(struct btrfs_fs_info *fs_info)
2313 {
2314         struct btrfs_root *tree_root = fs_info->tree_root;
2315         struct btrfs_root *root;
2316         struct btrfs_key location;
2317         int ret;
2318
2319         BUG_ON(!fs_info->tree_root);
2320
2321         location.objectid = BTRFS_EXTENT_TREE_OBJECTID;
2322         location.type = BTRFS_ROOT_ITEM_KEY;
2323         location.offset = 0;
2324
2325         root = btrfs_read_tree_root(tree_root, &location);
2326         if (IS_ERR(root)) {
2327                 ret = PTR_ERR(root);
2328                 goto out;
2329         }
2330         set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2331         fs_info->extent_root = root;
2332
2333         location.objectid = BTRFS_DEV_TREE_OBJECTID;
2334         root = btrfs_read_tree_root(tree_root, &location);
2335         if (IS_ERR(root)) {
2336                 ret = PTR_ERR(root);
2337                 goto out;
2338         }
2339         set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2340         fs_info->dev_root = root;
2341         btrfs_init_devices_late(fs_info);
2342
2343         location.objectid = BTRFS_CSUM_TREE_OBJECTID;
2344         root = btrfs_read_tree_root(tree_root, &location);
2345         if (IS_ERR(root)) {
2346                 ret = PTR_ERR(root);
2347                 goto out;
2348         }
2349         set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2350         fs_info->csum_root = root;
2351
2352         location.objectid = BTRFS_QUOTA_TREE_OBJECTID;
2353         root = btrfs_read_tree_root(tree_root, &location);
2354         if (!IS_ERR(root)) {
2355                 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2356                 set_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
2357                 fs_info->quota_root = root;
2358         }
2359
2360         location.objectid = BTRFS_UUID_TREE_OBJECTID;
2361         root = btrfs_read_tree_root(tree_root, &location);
2362         if (IS_ERR(root)) {
2363                 ret = PTR_ERR(root);
2364                 if (ret != -ENOENT)
2365                         goto out;
2366         } else {
2367                 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2368                 fs_info->uuid_root = root;
2369         }
2370
2371         if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
2372                 location.objectid = BTRFS_FREE_SPACE_TREE_OBJECTID;
2373                 root = btrfs_read_tree_root(tree_root, &location);
2374                 if (IS_ERR(root)) {
2375                         ret = PTR_ERR(root);
2376                         goto out;
2377                 }
2378                 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2379                 fs_info->free_space_root = root;
2380         }
2381
2382         return 0;
2383 out:
2384         btrfs_warn(fs_info, "failed to read root (objectid=%llu): %d",
2385                    location.objectid, ret);
2386         return ret;
2387 }
2388
2389 /*
2390  * Real super block validation
2391  * NOTE: super csum type and incompat features will not be checked here.
2392  *
2393  * @sb:         super block to check
2394  * @mirror_num: the super block number to check its bytenr:
2395  *              0       the primary (1st) sb
2396  *              1, 2    2nd and 3rd backup copy
2397  *             -1       skip bytenr check
2398  */
2399 static int validate_super(struct btrfs_fs_info *fs_info,
2400                             struct btrfs_super_block *sb, int mirror_num)
2401 {
2402         u64 nodesize = btrfs_super_nodesize(sb);
2403         u64 sectorsize = btrfs_super_sectorsize(sb);
2404         int ret = 0;
2405
2406         if (btrfs_super_magic(sb) != BTRFS_MAGIC) {
2407                 btrfs_err(fs_info, "no valid FS found");
2408                 ret = -EINVAL;
2409         }
2410         if (btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP) {
2411                 btrfs_err(fs_info, "unrecognized or unsupported super flag: %llu",
2412                                 btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP);
2413                 ret = -EINVAL;
2414         }
2415         if (btrfs_super_root_level(sb) >= BTRFS_MAX_LEVEL) {
2416                 btrfs_err(fs_info, "tree_root level too big: %d >= %d",
2417                                 btrfs_super_root_level(sb), BTRFS_MAX_LEVEL);
2418                 ret = -EINVAL;
2419         }
2420         if (btrfs_super_chunk_root_level(sb) >= BTRFS_MAX_LEVEL) {
2421                 btrfs_err(fs_info, "chunk_root level too big: %d >= %d",
2422                                 btrfs_super_chunk_root_level(sb), BTRFS_MAX_LEVEL);
2423                 ret = -EINVAL;
2424         }
2425         if (btrfs_super_log_root_level(sb) >= BTRFS_MAX_LEVEL) {
2426                 btrfs_err(fs_info, "log_root level too big: %d >= %d",
2427                                 btrfs_super_log_root_level(sb), BTRFS_MAX_LEVEL);
2428                 ret = -EINVAL;
2429         }
2430
2431         /*
2432          * Check sectorsize and nodesize first, other check will need it.
2433          * Check all possible sectorsize(4K, 8K, 16K, 32K, 64K) here.
2434          */
2435         if (!is_power_of_2(sectorsize) || sectorsize < 4096 ||
2436             sectorsize > BTRFS_MAX_METADATA_BLOCKSIZE) {
2437                 btrfs_err(fs_info, "invalid sectorsize %llu", sectorsize);
2438                 ret = -EINVAL;
2439         }
2440         /* Only PAGE SIZE is supported yet */
2441         if (sectorsize != PAGE_SIZE) {
2442                 btrfs_err(fs_info,
2443                         "sectorsize %llu not supported yet, only support %lu",
2444                         sectorsize, PAGE_SIZE);
2445                 ret = -EINVAL;
2446         }
2447         if (!is_power_of_2(nodesize) || nodesize < sectorsize ||
2448             nodesize > BTRFS_MAX_METADATA_BLOCKSIZE) {
2449                 btrfs_err(fs_info, "invalid nodesize %llu", nodesize);
2450                 ret = -EINVAL;
2451         }
2452         if (nodesize != le32_to_cpu(sb->__unused_leafsize)) {
2453                 btrfs_err(fs_info, "invalid leafsize %u, should be %llu",
2454                           le32_to_cpu(sb->__unused_leafsize), nodesize);
2455                 ret = -EINVAL;
2456         }
2457
2458         /* Root alignment check */
2459         if (!IS_ALIGNED(btrfs_super_root(sb), sectorsize)) {
2460                 btrfs_warn(fs_info, "tree_root block unaligned: %llu",
2461                            btrfs_super_root(sb));
2462                 ret = -EINVAL;
2463         }
2464         if (!IS_ALIGNED(btrfs_super_chunk_root(sb), sectorsize)) {
2465                 btrfs_warn(fs_info, "chunk_root block unaligned: %llu",
2466                            btrfs_super_chunk_root(sb));
2467                 ret = -EINVAL;
2468         }
2469         if (!IS_ALIGNED(btrfs_super_log_root(sb), sectorsize)) {
2470                 btrfs_warn(fs_info, "log_root block unaligned: %llu",
2471                            btrfs_super_log_root(sb));
2472                 ret = -EINVAL;
2473         }
2474
2475         if (memcmp(fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid,
2476                    BTRFS_FSID_SIZE) != 0) {
2477                 btrfs_err(fs_info,
2478                         "dev_item UUID does not match metadata fsid: %pU != %pU",
2479                         fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid);
2480                 ret = -EINVAL;
2481         }
2482
2483         /*
2484          * Hint to catch really bogus numbers, bitflips or so, more exact checks are
2485          * done later
2486          */
2487         if (btrfs_super_bytes_used(sb) < 6 * btrfs_super_nodesize(sb)) {
2488                 btrfs_err(fs_info, "bytes_used is too small %llu",
2489                           btrfs_super_bytes_used(sb));
2490                 ret = -EINVAL;
2491         }
2492         if (!is_power_of_2(btrfs_super_stripesize(sb))) {
2493                 btrfs_err(fs_info, "invalid stripesize %u",
2494                           btrfs_super_stripesize(sb));
2495                 ret = -EINVAL;
2496         }
2497         if (btrfs_super_num_devices(sb) > (1UL << 31))
2498                 btrfs_warn(fs_info, "suspicious number of devices: %llu",
2499                            btrfs_super_num_devices(sb));
2500         if (btrfs_super_num_devices(sb) == 0) {
2501                 btrfs_err(fs_info, "number of devices is 0");
2502                 ret = -EINVAL;
2503         }
2504
2505         if (mirror_num >= 0 &&
2506             btrfs_super_bytenr(sb) != btrfs_sb_offset(mirror_num)) {
2507                 btrfs_err(fs_info, "super offset mismatch %llu != %u",
2508                           btrfs_super_bytenr(sb), BTRFS_SUPER_INFO_OFFSET);
2509                 ret = -EINVAL;
2510         }
2511
2512         /*
2513          * Obvious sys_chunk_array corruptions, it must hold at least one key
2514          * and one chunk
2515          */
2516         if (btrfs_super_sys_array_size(sb) > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
2517                 btrfs_err(fs_info, "system chunk array too big %u > %u",
2518                           btrfs_super_sys_array_size(sb),
2519                           BTRFS_SYSTEM_CHUNK_ARRAY_SIZE);
2520                 ret = -EINVAL;
2521         }
2522         if (btrfs_super_sys_array_size(sb) < sizeof(struct btrfs_disk_key)
2523                         + sizeof(struct btrfs_chunk)) {
2524                 btrfs_err(fs_info, "system chunk array too small %u < %zu",
2525                           btrfs_super_sys_array_size(sb),
2526                           sizeof(struct btrfs_disk_key)
2527                           + sizeof(struct btrfs_chunk));
2528                 ret = -EINVAL;
2529         }
2530
2531         /*
2532          * The generation is a global counter, we'll trust it more than the others
2533          * but it's still possible that it's the one that's wrong.
2534          */
2535         if (btrfs_super_generation(sb) < btrfs_super_chunk_root_generation(sb))
2536                 btrfs_warn(fs_info,
2537                         "suspicious: generation < chunk_root_generation: %llu < %llu",
2538                         btrfs_super_generation(sb),
2539                         btrfs_super_chunk_root_generation(sb));
2540         if (btrfs_super_generation(sb) < btrfs_super_cache_generation(sb)
2541             && btrfs_super_cache_generation(sb) != (u64)-1)
2542                 btrfs_warn(fs_info,
2543                         "suspicious: generation < cache_generation: %llu < %llu",
2544                         btrfs_super_generation(sb),
2545                         btrfs_super_cache_generation(sb));
2546
2547         return ret;
2548 }
2549
2550 /*
2551  * Validation of super block at mount time.
2552  * Some checks already done early at mount time, like csum type and incompat
2553  * flags will be skipped.
2554  */
2555 static int btrfs_validate_mount_super(struct btrfs_fs_info *fs_info)
2556 {
2557         return validate_super(fs_info, fs_info->super_copy, 0);
2558 }
2559
2560 /*
2561  * Validation of super block at write time.
2562  * Some checks like bytenr check will be skipped as their values will be
2563  * overwritten soon.
2564  * Extra checks like csum type and incompat flags will be done here.
2565  */
2566 static int btrfs_validate_write_super(struct btrfs_fs_info *fs_info,
2567                                       struct btrfs_super_block *sb)
2568 {
2569         int ret;
2570
2571         ret = validate_super(fs_info, sb, -1);
2572         if (ret < 0)
2573                 goto out;
2574         if (!btrfs_supported_super_csum(btrfs_super_csum_type(sb))) {
2575                 ret = -EUCLEAN;
2576                 btrfs_err(fs_info, "invalid csum type, has %u want %u",
2577                           btrfs_super_csum_type(sb), BTRFS_CSUM_TYPE_CRC32);
2578                 goto out;
2579         }
2580         if (btrfs_super_incompat_flags(sb) & ~BTRFS_FEATURE_INCOMPAT_SUPP) {
2581                 ret = -EUCLEAN;
2582                 btrfs_err(fs_info,
2583                 "invalid incompat flags, has 0x%llx valid mask 0x%llx",
2584                           btrfs_super_incompat_flags(sb),
2585                           (unsigned long long)BTRFS_FEATURE_INCOMPAT_SUPP);
2586                 goto out;
2587         }
2588 out:
2589         if (ret < 0)
2590                 btrfs_err(fs_info,
2591                 "super block corruption detected before writing it to disk");
2592         return ret;
2593 }
2594
2595 int open_ctree(struct super_block *sb,
2596                struct btrfs_fs_devices *fs_devices,
2597                char *options)
2598 {
2599         u32 sectorsize;
2600         u32 nodesize;
2601         u32 stripesize;
2602         u64 generation;
2603         u64 features;
2604         u16 csum_type;
2605         struct btrfs_key location;
2606         struct buffer_head *bh;
2607         struct btrfs_super_block *disk_super;
2608         struct btrfs_fs_info *fs_info = btrfs_sb(sb);
2609         struct btrfs_root *tree_root;
2610         struct btrfs_root *chunk_root;
2611         int ret;
2612         int err = -EINVAL;
2613         int num_backups_tried = 0;
2614         int backup_index = 0;
2615         int clear_free_space_tree = 0;
2616         int level;
2617
2618         tree_root = fs_info->tree_root = btrfs_alloc_root(fs_info, GFP_KERNEL);
2619         chunk_root = fs_info->chunk_root = btrfs_alloc_root(fs_info, GFP_KERNEL);
2620         if (!tree_root || !chunk_root) {
2621                 err = -ENOMEM;
2622                 goto fail;
2623         }
2624
2625         ret = init_srcu_struct(&fs_info->subvol_srcu);
2626         if (ret) {
2627                 err = ret;
2628                 goto fail;
2629         }
2630
2631         ret = percpu_counter_init(&fs_info->dio_bytes, 0, GFP_KERNEL);
2632         if (ret) {
2633                 err = ret;
2634                 goto fail_srcu;
2635         }
2636
2637         ret = percpu_counter_init(&fs_info->dirty_metadata_bytes, 0, GFP_KERNEL);
2638         if (ret) {
2639                 err = ret;
2640                 goto fail_dio_bytes;
2641         }
2642         fs_info->dirty_metadata_batch = PAGE_SIZE *
2643                                         (1 + ilog2(nr_cpu_ids));
2644
2645         ret = percpu_counter_init(&fs_info->delalloc_bytes, 0, GFP_KERNEL);
2646         if (ret) {
2647                 err = ret;
2648                 goto fail_dirty_metadata_bytes;
2649         }
2650
2651         ret = percpu_counter_init(&fs_info->dev_replace.bio_counter, 0,
2652                         GFP_KERNEL);
2653         if (ret) {
2654                 err = ret;
2655                 goto fail_delalloc_bytes;
2656         }
2657
2658         INIT_RADIX_TREE(&fs_info->fs_roots_radix, GFP_ATOMIC);
2659         INIT_RADIX_TREE(&fs_info->buffer_radix, GFP_ATOMIC);
2660         INIT_LIST_HEAD(&fs_info->trans_list);
2661         INIT_LIST_HEAD(&fs_info->dead_roots);
2662         INIT_LIST_HEAD(&fs_info->delayed_iputs);
2663         INIT_LIST_HEAD(&fs_info->delalloc_roots);
2664         INIT_LIST_HEAD(&fs_info->caching_block_groups);
2665         INIT_LIST_HEAD(&fs_info->pending_raid_kobjs);
2666         spin_lock_init(&fs_info->pending_raid_kobjs_lock);
2667         spin_lock_init(&fs_info->delalloc_root_lock);
2668         spin_lock_init(&fs_info->trans_lock);
2669         spin_lock_init(&fs_info->fs_roots_radix_lock);
2670         spin_lock_init(&fs_info->delayed_iput_lock);
2671         spin_lock_init(&fs_info->defrag_inodes_lock);
2672         spin_lock_init(&fs_info->tree_mod_seq_lock);
2673         spin_lock_init(&fs_info->super_lock);
2674         spin_lock_init(&fs_info->buffer_lock);
2675         spin_lock_init(&fs_info->unused_bgs_lock);
2676         rwlock_init(&fs_info->tree_mod_log_lock);
2677         mutex_init(&fs_info->unused_bg_unpin_mutex);
2678         mutex_init(&fs_info->delete_unused_bgs_mutex);
2679         mutex_init(&fs_info->reloc_mutex);
2680         mutex_init(&fs_info->delalloc_root_mutex);
2681         seqlock_init(&fs_info->profiles_lock);
2682
2683         INIT_LIST_HEAD(&fs_info->dirty_cowonly_roots);
2684         INIT_LIST_HEAD(&fs_info->space_info);
2685         INIT_LIST_HEAD(&fs_info->tree_mod_seq_list);
2686         INIT_LIST_HEAD(&fs_info->unused_bgs);
2687         extent_map_tree_init(&fs_info->mapping_tree);
2688         btrfs_init_block_rsv(&fs_info->global_block_rsv,
2689                              BTRFS_BLOCK_RSV_GLOBAL);
2690         btrfs_init_block_rsv(&fs_info->trans_block_rsv, BTRFS_BLOCK_RSV_TRANS);
2691         btrfs_init_block_rsv(&fs_info->chunk_block_rsv, BTRFS_BLOCK_RSV_CHUNK);
2692         btrfs_init_block_rsv(&fs_info->empty_block_rsv, BTRFS_BLOCK_RSV_EMPTY);
2693         btrfs_init_block_rsv(&fs_info->delayed_block_rsv,
2694                              BTRFS_BLOCK_RSV_DELOPS);
2695         btrfs_init_block_rsv(&fs_info->delayed_refs_rsv,
2696                              BTRFS_BLOCK_RSV_DELREFS);
2697
2698         atomic_set(&fs_info->async_delalloc_pages, 0);
2699         atomic_set(&fs_info->defrag_running, 0);
2700         atomic_set(&fs_info->reada_works_cnt, 0);
2701         atomic_set(&fs_info->nr_delayed_iputs, 0);
2702         atomic64_set(&fs_info->tree_mod_seq, 0);
2703         fs_info->sb = sb;
2704         fs_info->max_inline = BTRFS_DEFAULT_MAX_INLINE;
2705         fs_info->metadata_ratio = 0;
2706         fs_info->defrag_inodes = RB_ROOT;
2707         atomic64_set(&fs_info->free_chunk_space, 0);
2708         fs_info->tree_mod_log = RB_ROOT;
2709         fs_info->commit_interval = BTRFS_DEFAULT_COMMIT_INTERVAL;
2710         fs_info->avg_delayed_ref_runtime = NSEC_PER_SEC >> 6; /* div by 64 */
2711         /* readahead state */
2712         INIT_RADIX_TREE(&fs_info->reada_tree, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
2713         spin_lock_init(&fs_info->reada_lock);
2714         btrfs_init_ref_verify(fs_info);
2715
2716         fs_info->thread_pool_size = min_t(unsigned long,
2717                                           num_online_cpus() + 2, 8);
2718
2719         INIT_LIST_HEAD(&fs_info->ordered_roots);
2720         spin_lock_init(&fs_info->ordered_root_lock);
2721
2722         fs_info->btree_inode = new_inode(sb);
2723         if (!fs_info->btree_inode) {
2724                 err = -ENOMEM;
2725                 goto fail_bio_counter;
2726         }
2727         mapping_set_gfp_mask(fs_info->btree_inode->i_mapping, GFP_NOFS);
2728
2729         fs_info->delayed_root = kmalloc(sizeof(struct btrfs_delayed_root),
2730                                         GFP_KERNEL);
2731         if (!fs_info->delayed_root) {
2732                 err = -ENOMEM;
2733                 goto fail_iput;
2734         }
2735         btrfs_init_delayed_root(fs_info->delayed_root);
2736
2737         btrfs_init_scrub(fs_info);
2738 #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
2739         fs_info->check_integrity_print_mask = 0;
2740 #endif
2741         btrfs_init_balance(fs_info);
2742         btrfs_init_async_reclaim_work(&fs_info->async_reclaim_work);
2743
2744         sb->s_blocksize = BTRFS_BDEV_BLOCKSIZE;
2745         sb->s_blocksize_bits = blksize_bits(BTRFS_BDEV_BLOCKSIZE);
2746
2747         btrfs_init_btree_inode(fs_info);
2748
2749         spin_lock_init(&fs_info->block_group_cache_lock);
2750         fs_info->block_group_cache_tree = RB_ROOT;
2751         fs_info->first_logical_byte = (u64)-1;
2752
2753         extent_io_tree_init(fs_info, &fs_info->freed_extents[0],
2754                             IO_TREE_FS_INFO_FREED_EXTENTS0, NULL);
2755         extent_io_tree_init(fs_info, &fs_info->freed_extents[1],
2756                             IO_TREE_FS_INFO_FREED_EXTENTS1, NULL);
2757         fs_info->pinned_extents = &fs_info->freed_extents[0];
2758         set_bit(BTRFS_FS_BARRIER, &fs_info->flags);
2759
2760         mutex_init(&fs_info->ordered_operations_mutex);
2761         mutex_init(&fs_info->tree_log_mutex);
2762         mutex_init(&fs_info->chunk_mutex);
2763         mutex_init(&fs_info->transaction_kthread_mutex);
2764         mutex_init(&fs_info->cleaner_mutex);
2765         mutex_init(&fs_info->ro_block_group_mutex);
2766         init_rwsem(&fs_info->commit_root_sem);
2767         init_rwsem(&fs_info->cleanup_work_sem);
2768         init_rwsem(&fs_info->subvol_sem);
2769         sema_init(&fs_info->uuid_tree_rescan_sem, 1);
2770
2771         btrfs_init_dev_replace_locks(fs_info);
2772         btrfs_init_qgroup(fs_info);
2773
2774         btrfs_init_free_cluster(&fs_info->meta_alloc_cluster);
2775         btrfs_init_free_cluster(&fs_info->data_alloc_cluster);
2776
2777         init_waitqueue_head(&fs_info->transaction_throttle);
2778         init_waitqueue_head(&fs_info->transaction_wait);
2779         init_waitqueue_head(&fs_info->transaction_blocked_wait);
2780         init_waitqueue_head(&fs_info->async_submit_wait);
2781         init_waitqueue_head(&fs_info->delayed_iputs_wait);
2782
2783         /* Usable values until the real ones are cached from the superblock */
2784         fs_info->nodesize = 4096;
2785         fs_info->sectorsize = 4096;
2786         fs_info->stripesize = 4096;
2787
2788         spin_lock_init(&fs_info->swapfile_pins_lock);
2789         fs_info->swapfile_pins = RB_ROOT;
2790
2791         ret = btrfs_alloc_stripe_hash_table(fs_info);
2792         if (ret) {
2793                 err = ret;
2794                 goto fail_alloc;
2795         }
2796
2797         __setup_root(tree_root, fs_info, BTRFS_ROOT_TREE_OBJECTID);
2798
2799         invalidate_bdev(fs_devices->latest_bdev);
2800
2801         /*
2802          * Read super block and check the signature bytes only
2803          */
2804         bh = btrfs_read_dev_super(fs_devices->latest_bdev);
2805         if (IS_ERR(bh)) {
2806                 err = PTR_ERR(bh);
2807                 goto fail_alloc;
2808         }
2809
2810         /*
2811          * Verify the type first, if that or the the checksum value are
2812          * corrupted, we'll find out
2813          */
2814         csum_type = btrfs_super_csum_type((struct btrfs_super_block *)bh->b_data);
2815         if (!btrfs_supported_super_csum(csum_type)) {
2816                 btrfs_err(fs_info, "unsupported checksum algorithm: %u",
2817                           csum_type);
2818                 err = -EINVAL;
2819                 brelse(bh);
2820                 goto fail_alloc;
2821         }
2822
2823         /*
2824          * We want to check superblock checksum, the type is stored inside.
2825          * Pass the whole disk block of size BTRFS_SUPER_INFO_SIZE (4k).
2826          */
2827         if (btrfs_check_super_csum(fs_info, bh->b_data)) {
2828                 btrfs_err(fs_info, "superblock checksum mismatch");
2829                 err = -EINVAL;
2830                 brelse(bh);
2831                 goto fail_alloc;
2832         }
2833
2834         /*
2835          * super_copy is zeroed at allocation time and we never touch the
2836          * following bytes up to INFO_SIZE, the checksum is calculated from
2837          * the whole block of INFO_SIZE
2838          */
2839         memcpy(fs_info->super_copy, bh->b_data, sizeof(*fs_info->super_copy));
2840         brelse(bh);
2841
2842         disk_super = fs_info->super_copy;
2843
2844         ASSERT(!memcmp(fs_info->fs_devices->fsid, fs_info->super_copy->fsid,
2845                        BTRFS_FSID_SIZE));
2846
2847         if (btrfs_fs_incompat(fs_info, METADATA_UUID)) {
2848                 ASSERT(!memcmp(fs_info->fs_devices->metadata_uuid,
2849                                 fs_info->super_copy->metadata_uuid,
2850                                 BTRFS_FSID_SIZE));
2851         }
2852
2853         features = btrfs_super_flags(disk_super);
2854         if (features & BTRFS_SUPER_FLAG_CHANGING_FSID_V2) {
2855                 features &= ~BTRFS_SUPER_FLAG_CHANGING_FSID_V2;
2856                 btrfs_set_super_flags(disk_super, features);
2857                 btrfs_info(fs_info,
2858                         "found metadata UUID change in progress flag, clearing");
2859         }
2860
2861         memcpy(fs_info->super_for_commit, fs_info->super_copy,
2862                sizeof(*fs_info->super_for_commit));
2863
2864         ret = btrfs_validate_mount_super(fs_info);
2865         if (ret) {
2866                 btrfs_err(fs_info, "superblock contains fatal errors");
2867                 err = -EINVAL;
2868                 goto fail_alloc;
2869         }
2870
2871         if (!btrfs_super_root(disk_super))
2872                 goto fail_alloc;
2873
2874         /* check FS state, whether FS is broken. */
2875         if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_ERROR)
2876                 set_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state);
2877
2878         /*
2879          * run through our array of backup supers and setup
2880          * our ring pointer to the oldest one
2881          */
2882         generation = btrfs_super_generation(disk_super);
2883         find_oldest_super_backup(fs_info, generation);
2884
2885         /*
2886          * In the long term, we'll store the compression type in the super
2887          * block, and it'll be used for per file compression control.
2888          */
2889         fs_info->compress_type = BTRFS_COMPRESS_ZLIB;
2890
2891         ret = btrfs_parse_options(fs_info, options, sb->s_flags);
2892         if (ret) {
2893                 err = ret;
2894                 goto fail_alloc;
2895         }
2896
2897         features = btrfs_super_incompat_flags(disk_super) &
2898                 ~BTRFS_FEATURE_INCOMPAT_SUPP;
2899         if (features) {
2900                 btrfs_err(fs_info,
2901                     "cannot mount because of unsupported optional features (%llx)",
2902                     features);
2903                 err = -EINVAL;
2904                 goto fail_alloc;
2905         }
2906
2907         features = btrfs_super_incompat_flags(disk_super);
2908         features |= BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF;
2909         if (fs_info->compress_type == BTRFS_COMPRESS_LZO)
2910                 features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_LZO;
2911         else if (fs_info->compress_type == BTRFS_COMPRESS_ZSTD)
2912                 features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_ZSTD;
2913
2914         if (features & BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA)
2915                 btrfs_info(fs_info, "has skinny extents");
2916
2917         /*
2918          * flag our filesystem as having big metadata blocks if
2919          * they are bigger than the page size
2920          */
2921         if (btrfs_super_nodesize(disk_super) > PAGE_SIZE) {
2922                 if (!(features & BTRFS_FEATURE_INCOMPAT_BIG_METADATA))
2923                         btrfs_info(fs_info,
2924                                 "flagging fs with big metadata feature");
2925                 features |= BTRFS_FEATURE_INCOMPAT_BIG_METADATA;
2926         }
2927
2928         nodesize = btrfs_super_nodesize(disk_super);
2929         sectorsize = btrfs_super_sectorsize(disk_super);
2930         stripesize = sectorsize;
2931         fs_info->dirty_metadata_batch = nodesize * (1 + ilog2(nr_cpu_ids));
2932         fs_info->delalloc_batch = sectorsize * 512 * (1 + ilog2(nr_cpu_ids));
2933
2934         /* Cache block sizes */
2935         fs_info->nodesize = nodesize;
2936         fs_info->sectorsize = sectorsize;
2937         fs_info->stripesize = stripesize;
2938
2939         /*
2940          * mixed block groups end up with duplicate but slightly offset
2941          * extent buffers for the same range.  It leads to corruptions
2942          */
2943         if ((features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) &&
2944             (sectorsize != nodesize)) {
2945                 btrfs_err(fs_info,
2946 "unequal nodesize/sectorsize (%u != %u) are not allowed for mixed block groups",
2947                         nodesize, sectorsize);
2948                 goto fail_alloc;
2949         }
2950
2951         /*
2952          * Needn't use the lock because there is no other task which will
2953          * update the flag.
2954          */
2955         btrfs_set_super_incompat_flags(disk_super, features);
2956
2957         features = btrfs_super_compat_ro_flags(disk_super) &
2958                 ~BTRFS_FEATURE_COMPAT_RO_SUPP;
2959         if (!sb_rdonly(sb) && features) {
2960                 btrfs_err(fs_info,
2961         "cannot mount read-write because of unsupported optional features (%llx)",
2962                        features);
2963                 err = -EINVAL;
2964                 goto fail_alloc;
2965         }
2966
2967         ret = btrfs_init_workqueues(fs_info, fs_devices);
2968         if (ret) {
2969                 err = ret;
2970                 goto fail_sb_buffer;
2971         }
2972
2973         sb->s_bdi->congested_fn = btrfs_congested_fn;
2974         sb->s_bdi->congested_data = fs_info;
2975         sb->s_bdi->capabilities |= BDI_CAP_CGROUP_WRITEBACK;
2976         sb->s_bdi->ra_pages = VM_READAHEAD_PAGES;
2977         sb->s_bdi->ra_pages *= btrfs_super_num_devices(disk_super);
2978         sb->s_bdi->ra_pages = max(sb->s_bdi->ra_pages, SZ_4M / PAGE_SIZE);
2979
2980         sb->s_blocksize = sectorsize;
2981         sb->s_blocksize_bits = blksize_bits(sectorsize);
2982         memcpy(&sb->s_uuid, fs_info->fs_devices->fsid, BTRFS_FSID_SIZE);
2983
2984         mutex_lock(&fs_info->chunk_mutex);
2985         ret = btrfs_read_sys_array(fs_info);
2986         mutex_unlock(&fs_info->chunk_mutex);
2987         if (ret) {
2988                 btrfs_err(fs_info, "failed to read the system array: %d", ret);
2989                 goto fail_sb_buffer;
2990         }
2991
2992         generation = btrfs_super_chunk_root_generation(disk_super);
2993         level = btrfs_super_chunk_root_level(disk_super);
2994
2995         __setup_root(chunk_root, fs_info, BTRFS_CHUNK_TREE_OBJECTID);
2996
2997         chunk_root->node = read_tree_block(fs_info,
2998                                            btrfs_super_chunk_root(disk_super),
2999                                            generation, level, NULL);
3000         if (IS_ERR(chunk_root->node) ||
3001             !extent_buffer_uptodate(chunk_root->node)) {
3002                 btrfs_err(fs_info, "failed to read chunk root");
3003                 if (!IS_ERR(chunk_root->node))
3004                         free_extent_buffer(chunk_root->node);
3005                 chunk_root->node = NULL;
3006                 goto fail_tree_roots;
3007         }
3008         btrfs_set_root_node(&chunk_root->root_item, chunk_root->node);
3009         chunk_root->commit_root = btrfs_root_node(chunk_root);
3010
3011         read_extent_buffer(chunk_root->node, fs_info->chunk_tree_uuid,
3012            btrfs_header_chunk_tree_uuid(chunk_root->node), BTRFS_UUID_SIZE);
3013
3014         ret = btrfs_read_chunk_tree(fs_info);
3015         if (ret) {
3016                 btrfs_err(fs_info, "failed to read chunk tree: %d", ret);
3017                 goto fail_tree_roots;
3018         }
3019
3020         /*
3021          * Keep the devid that is marked to be the target device for the
3022          * device replace procedure
3023          */
3024         btrfs_free_extra_devids(fs_devices, 0);
3025
3026         if (!fs_devices->latest_bdev) {
3027                 btrfs_err(fs_info, "failed to read devices");
3028                 goto fail_tree_roots;
3029         }
3030
3031 retry_root_backup:
3032         generation = btrfs_super_generation(disk_super);
3033         level = btrfs_super_root_level(disk_super);
3034
3035         tree_root->node = read_tree_block(fs_info,
3036                                           btrfs_super_root(disk_super),
3037                                           generation, level, NULL);
3038         if (IS_ERR(tree_root->node) ||
3039             !extent_buffer_uptodate(tree_root->node)) {
3040                 btrfs_warn(fs_info, "failed to read tree root");
3041                 if (!IS_ERR(tree_root->node))
3042                         free_extent_buffer(tree_root->node);
3043                 tree_root->node = NULL;
3044                 goto recovery_tree_root;
3045         }
3046
3047         btrfs_set_root_node(&tree_root->root_item, tree_root->node);
3048         tree_root->commit_root = btrfs_root_node(tree_root);
3049         btrfs_set_root_refs(&tree_root->root_item, 1);
3050
3051         mutex_lock(&tree_root->objectid_mutex);
3052         ret = btrfs_find_highest_objectid(tree_root,
3053                                         &tree_root->highest_objectid);
3054         if (ret) {
3055                 mutex_unlock(&tree_root->objectid_mutex);
3056                 goto recovery_tree_root;
3057         }
3058
3059         ASSERT(tree_root->highest_objectid <= BTRFS_LAST_FREE_OBJECTID);
3060
3061         mutex_unlock(&tree_root->objectid_mutex);
3062
3063         ret = btrfs_read_roots(fs_info);
3064         if (ret)
3065                 goto recovery_tree_root;
3066
3067         fs_info->generation = generation;
3068         fs_info->last_trans_committed = generation;
3069
3070         ret = btrfs_verify_dev_extents(fs_info);
3071         if (ret) {
3072                 btrfs_err(fs_info,
3073                           "failed to verify dev extents against chunks: %d",
3074                           ret);
3075                 goto fail_block_groups;
3076         }
3077         ret = btrfs_recover_balance(fs_info);
3078         if (ret) {
3079                 btrfs_err(fs_info, "failed to recover balance: %d", ret);
3080                 goto fail_block_groups;
3081         }
3082
3083         ret = btrfs_init_dev_stats(fs_info);
3084         if (ret) {
3085                 btrfs_err(fs_info, "failed to init dev_stats: %d", ret);
3086                 goto fail_block_groups;
3087         }
3088
3089         ret = btrfs_init_dev_replace(fs_info);
3090         if (ret) {
3091                 btrfs_err(fs_info, "failed to init dev_replace: %d", ret);
3092                 goto fail_block_groups;
3093         }
3094
3095         btrfs_free_extra_devids(fs_devices, 1);
3096
3097         ret = btrfs_sysfs_add_fsid(fs_devices, NULL);
3098         if (ret) {
3099                 btrfs_err(fs_info, "failed to init sysfs fsid interface: %d",
3100                                 ret);
3101                 goto fail_block_groups;
3102         }
3103
3104         ret = btrfs_sysfs_add_device(fs_devices);
3105         if (ret) {
3106                 btrfs_err(fs_info, "failed to init sysfs device interface: %d",
3107                                 ret);
3108                 goto fail_fsdev_sysfs;
3109         }
3110
3111         ret = btrfs_sysfs_add_mounted(fs_info);
3112         if (ret) {
3113                 btrfs_err(fs_info, "failed to init sysfs interface: %d", ret);
3114                 goto fail_fsdev_sysfs;
3115         }
3116
3117         ret = btrfs_init_space_info(fs_info);
3118         if (ret) {
3119                 btrfs_err(fs_info, "failed to initialize space info: %d", ret);
3120                 goto fail_sysfs;
3121         }
3122
3123         ret = btrfs_read_block_groups(fs_info);
3124         if (ret) {
3125                 btrfs_err(fs_info, "failed to read block groups: %d", ret);
3126                 goto fail_sysfs;
3127         }
3128
3129         if (!sb_rdonly(sb) && !btrfs_check_rw_degradable(fs_info, NULL)) {
3130                 btrfs_warn(fs_info,
3131                 "writable mount is not allowed due to too many missing devices");
3132                 goto fail_sysfs;
3133         }
3134
3135         fs_info->cleaner_kthread = kthread_run(cleaner_kthread, tree_root,
3136                                                "btrfs-cleaner");
3137         if (IS_ERR(fs_info->cleaner_kthread))
3138                 goto fail_sysfs;
3139
3140         fs_info->transaction_kthread = kthread_run(transaction_kthread,
3141                                                    tree_root,
3142                                                    "btrfs-transaction");
3143         if (IS_ERR(fs_info->transaction_kthread))
3144                 goto fail_cleaner;
3145
3146         if (!btrfs_test_opt(fs_info, NOSSD) &&
3147             !fs_info->fs_devices->rotating) {
3148                 btrfs_set_and_info(fs_info, SSD, "enabling ssd optimizations");
3149         }
3150
3151         /*
3152          * Mount does not set all options immediately, we can do it now and do
3153          * not have to wait for transaction commit
3154          */
3155         btrfs_apply_pending_changes(fs_info);
3156
3157 #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
3158         if (btrfs_test_opt(fs_info, CHECK_INTEGRITY)) {
3159                 ret = btrfsic_mount(fs_info, fs_devices,
3160                                     btrfs_test_opt(fs_info,
3161                                         CHECK_INTEGRITY_INCLUDING_EXTENT_DATA) ?
3162                                     1 : 0,
3163                                     fs_info->check_integrity_print_mask);
3164                 if (ret)
3165                         btrfs_warn(fs_info,
3166                                 "failed to initialize integrity check module: %d",
3167                                 ret);
3168         }
3169 #endif
3170         ret = btrfs_read_qgroup_config(fs_info);
3171         if (ret)
3172                 goto fail_trans_kthread;
3173
3174         if (btrfs_build_ref_tree(fs_info))
3175                 btrfs_err(fs_info, "couldn't build ref tree");
3176
3177         /* do not make disk changes in broken FS or nologreplay is given */
3178         if (btrfs_super_log_root(disk_super) != 0 &&
3179             !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
3180                 ret = btrfs_replay_log(fs_info, fs_devices);
3181                 if (ret) {
3182                         err = ret;
3183                         goto fail_qgroup;
3184                 }
3185         }
3186
3187         ret = btrfs_find_orphan_roots(fs_info);
3188         if (ret)
3189                 goto fail_qgroup;
3190
3191         if (!sb_rdonly(sb)) {
3192                 ret = btrfs_cleanup_fs_roots(fs_info);
3193                 if (ret)
3194                         goto fail_qgroup;
3195
3196                 mutex_lock(&fs_info->cleaner_mutex);
3197                 ret = btrfs_recover_relocation(tree_root);
3198                 mutex_unlock(&fs_info->cleaner_mutex);
3199                 if (ret < 0) {
3200                         btrfs_warn(fs_info, "failed to recover relocation: %d",
3201                                         ret);
3202                         err = -EINVAL;
3203                         goto fail_qgroup;
3204                 }
3205         }
3206
3207         location.objectid = BTRFS_FS_TREE_OBJECTID;
3208         location.type = BTRFS_ROOT_ITEM_KEY;
3209         location.offset = 0;
3210
3211         fs_info->fs_root = btrfs_read_fs_root_no_name(fs_info, &location);
3212         if (IS_ERR(fs_info->fs_root)) {
3213                 err = PTR_ERR(fs_info->fs_root);
3214                 btrfs_warn(fs_info, "failed to read fs tree: %d", err);
3215                 goto fail_qgroup;
3216         }
3217
3218         if (sb_rdonly(sb))
3219                 return 0;
3220
3221         if (btrfs_test_opt(fs_info, CLEAR_CACHE) &&
3222             btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
3223                 clear_free_space_tree = 1;
3224         } else if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
3225                    !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID)) {
3226                 btrfs_warn(fs_info, "free space tree is invalid");
3227                 clear_free_space_tree = 1;
3228         }
3229
3230         if (clear_free_space_tree) {
3231                 btrfs_info(fs_info, "clearing free space tree");
3232                 ret = btrfs_clear_free_space_tree(fs_info);
3233                 if (ret) {
3234                         btrfs_warn(fs_info,
3235                                    "failed to clear free space tree: %d", ret);
3236                         close_ctree(fs_info);
3237                         return ret;
3238                 }
3239         }
3240
3241         if (btrfs_test_opt(fs_info, FREE_SPACE_TREE) &&
3242             !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
3243                 btrfs_info(fs_info, "creating free space tree");
3244                 ret = btrfs_create_free_space_tree(fs_info);
3245                 if (ret) {
3246                         btrfs_warn(fs_info,
3247                                 "failed to create free space tree: %d", ret);
3248                         close_ctree(fs_info);
3249                         return ret;
3250                 }
3251         }
3252
3253         down_read(&fs_info->cleanup_work_sem);
3254         if ((ret = btrfs_orphan_cleanup(fs_info->fs_root)) ||
3255             (ret = btrfs_orphan_cleanup(fs_info->tree_root))) {
3256                 up_read(&fs_info->cleanup_work_sem);
3257                 close_ctree(fs_info);
3258                 return ret;
3259         }
3260         up_read(&fs_info->cleanup_work_sem);
3261
3262         ret = btrfs_resume_balance_async(fs_info);
3263         if (ret) {
3264                 btrfs_warn(fs_info, "failed to resume balance: %d", ret);
3265                 close_ctree(fs_info);
3266                 return ret;
3267         }
3268
3269         ret = btrfs_resume_dev_replace_async(fs_info);
3270         if (ret) {
3271                 btrfs_warn(fs_info, "failed to resume device replace: %d", ret);
3272                 close_ctree(fs_info);
3273                 return ret;
3274         }
3275
3276         btrfs_qgroup_rescan_resume(fs_info);
3277
3278         if (!fs_info->uuid_root) {
3279                 btrfs_info(fs_info, "creating UUID tree");
3280                 ret = btrfs_create_uuid_tree(fs_info);
3281                 if (ret) {
3282                         btrfs_warn(fs_info,
3283                                 "failed to create the UUID tree: %d", ret);
3284                         close_ctree(fs_info);
3285                         return ret;
3286                 }
3287         } else if (btrfs_test_opt(fs_info, RESCAN_UUID_TREE) ||
3288                    fs_info->generation !=
3289                                 btrfs_super_uuid_tree_generation(disk_super)) {
3290                 btrfs_info(fs_info, "checking UUID tree");
3291                 ret = btrfs_check_uuid_tree(fs_info);
3292                 if (ret) {
3293                         btrfs_warn(fs_info,
3294                                 "failed to check the UUID tree: %d", ret);
3295                         close_ctree(fs_info);
3296                         return ret;
3297                 }
3298         } else {
3299                 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
3300         }
3301         set_bit(BTRFS_FS_OPEN, &fs_info->flags);
3302
3303         /*
3304          * backuproot only affect mount behavior, and if open_ctree succeeded,
3305          * no need to keep the flag
3306          */
3307         btrfs_clear_opt(fs_info->mount_opt, USEBACKUPROOT);
3308
3309         return 0;
3310
3311 fail_qgroup:
3312         btrfs_free_qgroup_config(fs_info);
3313 fail_trans_kthread:
3314         kthread_stop(fs_info->transaction_kthread);
3315         btrfs_cleanup_transaction(fs_info);
3316         btrfs_free_fs_roots(fs_info);
3317 fail_cleaner:
3318         kthread_stop(fs_info->cleaner_kthread);
3319
3320         /*
3321          * make sure we're done with the btree inode before we stop our
3322          * kthreads
3323          */
3324         filemap_write_and_wait(fs_info->btree_inode->i_mapping);
3325
3326 fail_sysfs:
3327         btrfs_sysfs_remove_mounted(fs_info);
3328
3329 fail_fsdev_sysfs:
3330         btrfs_sysfs_remove_fsid(fs_info->fs_devices);
3331
3332 fail_block_groups:
3333         btrfs_put_block_group_cache(fs_info);
3334
3335 fail_tree_roots:
3336         free_root_pointers(fs_info, 1);
3337         invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
3338
3339 fail_sb_buffer:
3340         btrfs_stop_all_workers(fs_info);
3341         btrfs_free_block_groups(fs_info);
3342 fail_alloc:
3343 fail_iput:
3344         btrfs_mapping_tree_free(&fs_info->mapping_tree);
3345
3346         iput(fs_info->btree_inode);
3347 fail_bio_counter:
3348         percpu_counter_destroy(&fs_info->dev_replace.bio_counter);
3349 fail_delalloc_bytes:
3350         percpu_counter_destroy(&fs_info->delalloc_bytes);
3351 fail_dirty_metadata_bytes:
3352         percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
3353 fail_dio_bytes:
3354         percpu_counter_destroy(&fs_info->dio_bytes);
3355 fail_srcu:
3356         cleanup_srcu_struct(&fs_info->subvol_srcu);
3357 fail:
3358         btrfs_free_stripe_hash_table(fs_info);
3359         btrfs_close_devices(fs_info->fs_devices);
3360         return err;
3361
3362 recovery_tree_root:
3363         if (!btrfs_test_opt(fs_info, USEBACKUPROOT))
3364                 goto fail_tree_roots;
3365
3366         free_root_pointers(fs_info, 0);
3367
3368         /* don't use the log in recovery mode, it won't be valid */
3369         btrfs_set_super_log_root(disk_super, 0);
3370
3371         /* we can't trust the free space cache either */
3372         btrfs_set_opt(fs_info->mount_opt, CLEAR_CACHE);
3373
3374         ret = next_root_backup(fs_info, fs_info->super_copy,
3375                                &num_backups_tried, &backup_index);
3376         if (ret == -1)
3377                 goto fail_block_groups;
3378         goto retry_root_backup;
3379 }
3380 ALLOW_ERROR_INJECTION(open_ctree, ERRNO);
3381
3382 static void btrfs_end_buffer_write_sync(struct buffer_head *bh, int uptodate)
3383 {
3384         if (uptodate) {
3385                 set_buffer_uptodate(bh);
3386         } else {
3387                 struct btrfs_device *device = (struct btrfs_device *)
3388                         bh->b_private;
3389
3390                 btrfs_warn_rl_in_rcu(device->fs_info,
3391                                 "lost page write due to IO error on %s",
3392                                           rcu_str_deref(device->name));
3393                 /* note, we don't set_buffer_write_io_error because we have
3394                  * our own ways of dealing with the IO errors
3395                  */
3396                 clear_buffer_uptodate(bh);
3397                 btrfs_dev_stat_inc_and_print(device, BTRFS_DEV_STAT_WRITE_ERRS);
3398         }
3399         unlock_buffer(bh);
3400         put_bh(bh);
3401 }
3402
3403 int btrfs_read_dev_one_super(struct block_device *bdev, int copy_num,
3404                         struct buffer_head **bh_ret)
3405 {
3406         struct buffer_head *bh;
3407         struct btrfs_super_block *super;
3408         u64 bytenr;
3409
3410         bytenr = btrfs_sb_offset(copy_num);
3411         if (bytenr + BTRFS_SUPER_INFO_SIZE >= i_size_read(bdev->bd_inode))
3412                 return -EINVAL;
3413
3414         bh = __bread(bdev, bytenr / BTRFS_BDEV_BLOCKSIZE, BTRFS_SUPER_INFO_SIZE);
3415         /*
3416          * If we fail to read from the underlying devices, as of now
3417          * the best option we have is to mark it EIO.
3418          */
3419         if (!bh)
3420                 return -EIO;
3421
3422         super = (struct btrfs_super_block *)bh->b_data;
3423         if (btrfs_super_bytenr(super) != bytenr ||
3424                     btrfs_super_magic(super) != BTRFS_MAGIC) {
3425                 brelse(bh);
3426                 return -EINVAL;
3427         }
3428
3429         *bh_ret = bh;
3430         return 0;
3431 }
3432
3433
3434 struct buffer_head *btrfs_read_dev_super(struct block_device *bdev)
3435 {
3436         struct buffer_head *bh;
3437         struct buffer_head *latest = NULL;
3438         struct btrfs_super_block *super;
3439         int i;
3440         u64 transid = 0;
3441         int ret = -EINVAL;
3442
3443         /* we would like to check all the supers, but that would make
3444          * a btrfs mount succeed after a mkfs from a different FS.
3445          * So, we need to add a special mount option to scan for
3446          * later supers, using BTRFS_SUPER_MIRROR_MAX instead
3447          */
3448         for (i = 0; i < 1; i++) {
3449                 ret = btrfs_read_dev_one_super(bdev, i, &bh);
3450                 if (ret)
3451                         continue;
3452
3453                 super = (struct btrfs_super_block *)bh->b_data;
3454
3455                 if (!latest || btrfs_super_generation(super) > transid) {
3456                         brelse(latest);
3457                         latest = bh;
3458                         transid = btrfs_super_generation(super);
3459                 } else {
3460                         brelse(bh);
3461                 }
3462         }
3463
3464         if (!latest)
3465                 return ERR_PTR(ret);
3466
3467         return latest;
3468 }
3469
3470 /*
3471  * Write superblock @sb to the @device. Do not wait for completion, all the
3472  * buffer heads we write are pinned.
3473  *
3474  * Write @max_mirrors copies of the superblock, where 0 means default that fit
3475  * the expected device size at commit time. Note that max_mirrors must be
3476  * same for write and wait phases.
3477  *
3478  * Return number of errors when buffer head is not found or submission fails.
3479  */
3480 static int write_dev_supers(struct btrfs_device *device,
3481                             struct btrfs_super_block *sb, int max_mirrors)
3482 {
3483         struct buffer_head *bh;
3484         int i;
3485         int ret;
3486         int errors = 0;
3487         u32 crc;
3488         u64 bytenr;
3489         int op_flags;
3490
3491         if (max_mirrors == 0)
3492                 max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3493
3494         for (i = 0; i < max_mirrors; i++) {
3495                 bytenr = btrfs_sb_offset(i);
3496                 if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3497                     device->commit_total_bytes)
3498                         break;
3499
3500                 btrfs_set_super_bytenr(sb, bytenr);
3501
3502                 crc = ~(u32)0;
3503                 crc = btrfs_csum_data((const char *)sb + BTRFS_CSUM_SIZE, crc,
3504                                       BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE);
3505                 btrfs_csum_final(crc, sb->csum);
3506
3507                 /* One reference for us, and we leave it for the caller */
3508                 bh = __getblk(device->bdev, bytenr / BTRFS_BDEV_BLOCKSIZE,
3509                               BTRFS_SUPER_INFO_SIZE);
3510                 if (!bh) {
3511                         btrfs_err(device->fs_info,
3512                             "couldn't get super buffer head for bytenr %llu",
3513                             bytenr);
3514                         errors++;
3515                         continue;
3516                 }
3517
3518                 memcpy(bh->b_data, sb, BTRFS_SUPER_INFO_SIZE);
3519
3520                 /* one reference for submit_bh */
3521                 get_bh(bh);
3522
3523                 set_buffer_uptodate(bh);
3524                 lock_buffer(bh);
3525                 bh->b_end_io = btrfs_end_buffer_write_sync;
3526                 bh->b_private = device;
3527
3528                 /*
3529                  * we fua the first super.  The others we allow
3530                  * to go down lazy.
3531                  */
3532                 op_flags = REQ_SYNC | REQ_META | REQ_PRIO;
3533                 if (i == 0 && !btrfs_test_opt(device->fs_info, NOBARRIER))
3534                         op_flags |= REQ_FUA;
3535                 ret = btrfsic_submit_bh(REQ_OP_WRITE, op_flags, bh);
3536                 if (ret)
3537                         errors++;
3538         }
3539         return errors < i ? 0 : -1;
3540 }
3541
3542 /*
3543  * Wait for write completion of superblocks done by write_dev_supers,
3544  * @max_mirrors same for write and wait phases.
3545  *
3546  * Return number of errors when buffer head is not found or not marked up to
3547  * date.
3548  */
3549 static int wait_dev_supers(struct btrfs_device *device, int max_mirrors)
3550 {
3551         struct buffer_head *bh;
3552         int i;
3553         int errors = 0;
3554         bool primary_failed = false;
3555         u64 bytenr;
3556
3557         if (max_mirrors == 0)
3558                 max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3559
3560         for (i = 0; i < max_mirrors; i++) {
3561                 bytenr = btrfs_sb_offset(i);
3562                 if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3563                     device->commit_total_bytes)
3564                         break;
3565
3566                 bh = __find_get_block(device->bdev,
3567                                       bytenr / BTRFS_BDEV_BLOCKSIZE,
3568                                       BTRFS_SUPER_INFO_SIZE);
3569                 if (!bh) {
3570                         errors++;
3571                         if (i == 0)
3572                                 primary_failed = true;
3573                         continue;
3574                 }
3575                 wait_on_buffer(bh);
3576                 if (!buffer_uptodate(bh)) {
3577                         errors++;
3578                         if (i == 0)
3579                                 primary_failed = true;
3580                 }
3581
3582                 /* drop our reference */
3583                 brelse(bh);
3584
3585                 /* drop the reference from the writing run */
3586                 brelse(bh);
3587         }
3588
3589         /* log error, force error return */
3590         if (primary_failed) {
3591                 btrfs_err(device->fs_info, "error writing primary super block to device %llu",
3592                           device->devid);
3593                 return -1;
3594         }
3595
3596         return errors < i ? 0 : -1;
3597 }
3598
3599 /*
3600  * endio for the write_dev_flush, this will wake anyone waiting
3601  * for the barrier when it is done
3602  */
3603 static void btrfs_end_empty_barrier(struct bio *bio)
3604 {
3605         complete(bio->bi_private);
3606 }
3607
3608 /*
3609  * Submit a flush request to the device if it supports it. Error handling is
3610  * done in the waiting counterpart.
3611  */
3612 static void write_dev_flush(struct btrfs_device *device)
3613 {
3614         struct request_queue *q = bdev_get_queue(device->bdev);
3615         struct bio *bio = device->flush_bio;
3616
3617         if (!test_bit(QUEUE_FLAG_WC, &q->queue_flags))
3618                 return;
3619
3620         bio_reset(bio);
3621         bio->bi_end_io = btrfs_end_empty_barrier;
3622         bio_set_dev(bio, device->bdev);
3623         bio->bi_opf = REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH;
3624         init_completion(&device->flush_wait);
3625         bio->bi_private = &device->flush_wait;
3626
3627         btrfsic_submit_bio(bio);
3628         set_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
3629 }
3630
3631 /*
3632  * If the flush bio has been submitted by write_dev_flush, wait for it.
3633  */
3634 static blk_status_t wait_dev_flush(struct btrfs_device *device)
3635 {
3636         struct bio *bio = device->flush_bio;
3637
3638         if (!test_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state))
3639                 return BLK_STS_OK;
3640
3641         clear_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
3642         wait_for_completion_io(&device->flush_wait);
3643
3644         return bio->bi_status;
3645 }
3646
3647 static int check_barrier_error(struct btrfs_fs_info *fs_info)
3648 {
3649         if (!btrfs_check_rw_degradable(fs_info, NULL))
3650                 return -EIO;
3651         return 0;
3652 }
3653
3654 /*
3655  * send an empty flush down to each device in parallel,
3656  * then wait for them
3657  */
3658 static int barrier_all_devices(struct btrfs_fs_info *info)
3659 {
3660         struct list_head *head;
3661         struct btrfs_device *dev;
3662         int errors_wait = 0;
3663         blk_status_t ret;
3664
3665         lockdep_assert_held(&info->fs_devices->device_list_mutex);
3666         /* send down all the barriers */
3667         head = &info->fs_devices->devices;
3668         list_for_each_entry(dev, head, dev_list) {
3669                 if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
3670                         continue;
3671                 if (!dev->bdev)
3672                         continue;
3673                 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3674                     !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3675                         continue;
3676
3677                 write_dev_flush(dev);
3678                 dev->last_flush_error = BLK_STS_OK;
3679         }
3680
3681         /* wait for all the barriers */
3682         list_for_each_entry(dev, head, dev_list) {
3683                 if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
3684                         continue;
3685                 if (!dev->bdev) {
3686                         errors_wait++;
3687                         continue;
3688                 }
3689                 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3690                     !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3691                         continue;
3692
3693                 ret = wait_dev_flush(dev);
3694                 if (ret) {
3695                         dev->last_flush_error = ret;
3696                         btrfs_dev_stat_inc_and_print(dev,
3697                                         BTRFS_DEV_STAT_FLUSH_ERRS);
3698                         errors_wait++;
3699                 }
3700         }
3701
3702         if (errors_wait) {
3703                 /*
3704                  * At some point we need the status of all disks
3705                  * to arrive at the volume status. So error checking
3706                  * is being pushed to a separate loop.
3707                  */
3708                 return check_barrier_error(info);
3709         }
3710         return 0;
3711 }
3712
3713 int btrfs_get_num_tolerated_disk_barrier_failures(u64 flags)
3714 {
3715         int raid_type;
3716         int min_tolerated = INT_MAX;
3717
3718         if ((flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 ||
3719             (flags & BTRFS_AVAIL_ALLOC_BIT_SINGLE))
3720                 min_tolerated = min_t(int, min_tolerated,
3721                                     btrfs_raid_array[BTRFS_RAID_SINGLE].
3722                                     tolerated_failures);
3723
3724         for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
3725                 if (raid_type == BTRFS_RAID_SINGLE)
3726                         continue;
3727                 if (!(flags & btrfs_raid_array[raid_type].bg_flag))
3728                         continue;
3729                 min_tolerated = min_t(int, min_tolerated,
3730                                     btrfs_raid_array[raid_type].
3731                                     tolerated_failures);
3732         }
3733
3734         if (min_tolerated == INT_MAX) {
3735                 pr_warn("BTRFS: unknown raid flag: %llu", flags);
3736                 min_tolerated = 0;
3737         }
3738
3739         return min_tolerated;
3740 }
3741
3742 int write_all_supers(struct btrfs_fs_info *fs_info, int max_mirrors)
3743 {
3744         struct list_head *head;
3745         struct btrfs_device *dev;
3746         struct btrfs_super_block *sb;
3747         struct btrfs_dev_item *dev_item;
3748         int ret;
3749         int do_barriers;
3750         int max_errors;
3751         int total_errors = 0;
3752         u64 flags;
3753
3754         do_barriers = !btrfs_test_opt(fs_info, NOBARRIER);
3755
3756         /*
3757          * max_mirrors == 0 indicates we're from commit_transaction,
3758          * not from fsync where the tree roots in fs_info have not
3759          * been consistent on disk.
3760          */
3761         if (max_mirrors == 0)
3762                 backup_super_roots(fs_info);
3763
3764         sb = fs_info->super_for_commit;
3765         dev_item = &sb->dev_item;
3766
3767         mutex_lock(&fs_info->fs_devices->device_list_mutex);
3768         head = &fs_info->fs_devices->devices;
3769         max_errors = btrfs_super_num_devices(fs_info->super_copy) - 1;
3770
3771         if (do_barriers) {
3772                 ret = barrier_all_devices(fs_info);
3773                 if (ret) {
3774                         mutex_unlock(
3775                                 &fs_info->fs_devices->device_list_mutex);
3776                         btrfs_handle_fs_error(fs_info, ret,
3777                                               "errors while submitting device barriers.");
3778                         return ret;
3779                 }
3780         }
3781
3782         list_for_each_entry(dev, head, dev_list) {
3783                 if (!dev->bdev) {
3784                         total_errors++;
3785                         continue;
3786                 }
3787                 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3788                     !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3789                         continue;
3790
3791               &nbs