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