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