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