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