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