btrfs: replace GPL boilerplate by SPDX -- headers
[linux-block.git] / fs / btrfs / disk-io.c
CommitLineData
6cbd5570
CM
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
e20d96d6 19#include <linux/fs.h>
d98237b3 20#include <linux/blkdev.h>
87cbda5c 21#include <linux/scatterlist.h>
22b0ebda 22#include <linux/swap.h>
0f7d52f4 23#include <linux/radix-tree.h>
35b7e476 24#include <linux/writeback.h>
d397712b 25#include <linux/buffer_head.h>
ce9adaa5 26#include <linux/workqueue.h>
a74a4b97 27#include <linux/kthread.h>
5a0e3ad6 28#include <linux/slab.h>
784b4e29 29#include <linux/migrate.h>
7a36ddec 30#include <linux/ratelimit.h>
6463fe58 31#include <linux/uuid.h>
803b2f54 32#include <linux/semaphore.h>
540adea3 33#include <linux/error-injection.h>
9678c543 34#include <linux/crc32c.h>
7e75bf3f 35#include <asm/unaligned.h>
eb60ceac
CM
36#include "ctree.h"
37#include "disk-io.h"
e089f05c 38#include "transaction.h"
0f7d52f4 39#include "btrfs_inode.h"
0b86a832 40#include "volumes.h"
db94535d 41#include "print-tree.h"
925baedd 42#include "locking.h"
e02119d5 43#include "tree-log.h"
fa9c0d79 44#include "free-space-cache.h"
70f6d82e 45#include "free-space-tree.h"
581bb050 46#include "inode-map.h"
21adbd5c 47#include "check-integrity.h"
606686ee 48#include "rcu-string.h"
8dabb742 49#include "dev-replace.h"
53b381b3 50#include "raid56.h"
5ac1d209 51#include "sysfs.h"
fcebe456 52#include "qgroup.h"
ebb8765b 53#include "compression.h"
557ea5dd 54#include "tree-checker.h"
fd708b81 55#include "ref-verify.h"
eb60ceac 56
de0022b9
JB
57#ifdef CONFIG_X86
58#include <asm/cpufeature.h>
59#endif
60
319e4d06
QW
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 |\
e2731e55
AJ
65 BTRFS_SUPER_FLAG_METADUMP |\
66 BTRFS_SUPER_FLAG_METADUMP_V2)
319e4d06 67
e8c9f186 68static const struct extent_io_ops btree_extent_io_ops;
8b712842 69static void end_workqueue_fn(struct btrfs_work *work);
4df27c4d 70static void free_fs_root(struct btrfs_root *root);
3d3a126a 71static int btrfs_check_super_valid(struct btrfs_fs_info *fs_info);
143bede5 72static void btrfs_destroy_ordered_extents(struct btrfs_root *root);
acce952b 73static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
2ff7e61e 74 struct btrfs_fs_info *fs_info);
143bede5 75static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root);
2ff7e61e 76static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
acce952b 77 struct extent_io_tree *dirty_pages,
78 int mark);
2ff7e61e 79static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
acce952b 80 struct extent_io_tree *pinned_extents);
2ff7e61e
JM
81static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info);
82static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info);
ce9adaa5 83
d352ac68 84/*
97eb6b69
DS
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
d352ac68
CM
87 * by writes to insert metadata for new file extents after IO is complete.
88 */
97eb6b69 89struct btrfs_end_io_wq {
ce9adaa5
CM
90 struct bio *bio;
91 bio_end_io_t *end_io;
92 void *private;
93 struct btrfs_fs_info *info;
4e4cbee9 94 blk_status_t status;
bfebd8b5 95 enum btrfs_wq_endio_type metadata;
8b712842 96 struct btrfs_work work;
ce9adaa5 97};
0da5468f 98
97eb6b69
DS
99static struct kmem_cache *btrfs_end_io_wq_cache;
100
101int __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,
fba4b697 106 SLAB_MEM_SPREAD,
97eb6b69
DS
107 NULL);
108 if (!btrfs_end_io_wq_cache)
109 return -ENOMEM;
110 return 0;
111}
112
e67c718b 113void __cold btrfs_end_io_wq_exit(void)
97eb6b69 114{
5598e900 115 kmem_cache_destroy(btrfs_end_io_wq_cache);
97eb6b69
DS
116}
117
d352ac68
CM
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 */
44b8bd7e 123struct async_submit_bio {
c6100a4b
JB
124 void *private_data;
125 struct btrfs_fs_info *fs_info;
44b8bd7e 126 struct bio *bio;
a758781d
DS
127 extent_submit_bio_start_t *submit_bio_start;
128 extent_submit_bio_done_t *submit_bio_done;
44b8bd7e 129 int mirror_num;
c8b97818 130 unsigned long bio_flags;
eaf25d93
CM
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;
8b712842 136 struct btrfs_work work;
4e4cbee9 137 blk_status_t status;
44b8bd7e
CM
138};
139
85d4e461
CM
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.
4008c04a 150 *
85d4e461
CM
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.
4008c04a 154 *
85d4e461
CM
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.
4008c04a 158 *
85d4e461
CM
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.
4008c04a
CM
162 */
163#ifdef CONFIG_DEBUG_LOCK_ALLOC
164# if BTRFS_MAX_LEVEL != 8
165# error
166# endif
85d4e461
CM
167
168static 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" },
60b62978 180 { .id = BTRFS_QUOTA_TREE_OBJECTID, .name_stem = "quota" },
85d4e461
CM
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" },
13fd8da9 184 { .id = BTRFS_UUID_TREE_OBJECTID, .name_stem = "uuid" },
6b20e0ad 185 { .id = BTRFS_FREE_SPACE_TREE_OBJECTID, .name_stem = "free-space" },
85d4e461 186 { .id = 0, .name_stem = "tree" },
4008c04a 187};
85d4e461
CM
188
189void __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
203void 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
4008c04a
CM
219#endif
220
d352ac68
CM
221/*
222 * extents on the btree inode are pretty simple, there's one extent
223 * that covers the entire device
224 */
6af49dbd 225struct extent_map *btree_get_extent(struct btrfs_inode *inode,
306e16ce 226 struct page *page, size_t pg_offset, u64 start, u64 len,
b2950863 227 int create)
7eccb903 228{
fc4f21b1
NB
229 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
230 struct extent_map_tree *em_tree = &inode->extent_tree;
5f39d397
CM
231 struct extent_map *em;
232 int ret;
233
890871be 234 read_lock(&em_tree->lock);
d1310b2e 235 em = lookup_extent_mapping(em_tree, start, len);
a061fc8d 236 if (em) {
0b246afa 237 em->bdev = fs_info->fs_devices->latest_bdev;
890871be 238 read_unlock(&em_tree->lock);
5f39d397 239 goto out;
a061fc8d 240 }
890871be 241 read_unlock(&em_tree->lock);
7b13b7b1 242
172ddd60 243 em = alloc_extent_map();
5f39d397
CM
244 if (!em) {
245 em = ERR_PTR(-ENOMEM);
246 goto out;
247 }
248 em->start = 0;
0afbaf8c 249 em->len = (u64)-1;
c8b97818 250 em->block_len = (u64)-1;
5f39d397 251 em->block_start = 0;
0b246afa 252 em->bdev = fs_info->fs_devices->latest_bdev;
d1310b2e 253
890871be 254 write_lock(&em_tree->lock);
09a2a8f9 255 ret = add_extent_mapping(em_tree, em, 0);
5f39d397
CM
256 if (ret == -EEXIST) {
257 free_extent_map(em);
7b13b7b1 258 em = lookup_extent_mapping(em_tree, start, len);
b4f359ab 259 if (!em)
0433f20d 260 em = ERR_PTR(-EIO);
5f39d397 261 } else if (ret) {
7b13b7b1 262 free_extent_map(em);
0433f20d 263 em = ERR_PTR(ret);
5f39d397 264 }
890871be 265 write_unlock(&em_tree->lock);
7b13b7b1 266
5f39d397
CM
267out:
268 return em;
7eccb903
CM
269}
270
9ed57367 271u32 btrfs_csum_data(const char *data, u32 seed, size_t len)
19c00ddc 272{
9678c543 273 return crc32c(seed, data, len);
19c00ddc
CM
274}
275
0b5e3daf 276void btrfs_csum_final(u32 crc, u8 *result)
19c00ddc 277{
7e75bf3f 278 put_unaligned_le32(~crc, result);
19c00ddc
CM
279}
280
d352ac68
CM
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 */
01d58472
DD
285static int csum_tree_block(struct btrfs_fs_info *fs_info,
286 struct extent_buffer *buf,
19c00ddc
CM
287 int verify)
288{
01d58472 289 u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
71a63551 290 char result[BTRFS_CSUM_SIZE];
19c00ddc
CM
291 unsigned long len;
292 unsigned long cur_len;
293 unsigned long offset = BTRFS_CSUM_SIZE;
19c00ddc
CM
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;
d397712b 301 while (len > 0) {
19c00ddc 302 err = map_private_extent_buffer(buf, offset, 32,
a6591715 303 &kaddr, &map_start, &map_len);
d397712b 304 if (err)
8bd98f0e 305 return err;
19c00ddc 306 cur_len = min(len, map_len - (offset - map_start));
b0496686 307 crc = btrfs_csum_data(kaddr + offset - map_start,
19c00ddc
CM
308 crc, cur_len);
309 len -= cur_len;
310 offset += cur_len;
19c00ddc 311 }
71a63551 312 memset(result, 0, BTRFS_CSUM_SIZE);
607d432d 313
19c00ddc
CM
314 btrfs_csum_final(crc, result);
315
316 if (verify) {
607d432d 317 if (memcmp_extent_buffer(buf, result, 0, csum_size)) {
e4204ded
CM
318 u32 val;
319 u32 found = 0;
607d432d 320 memcpy(&found, result, csum_size);
e4204ded 321
607d432d 322 read_extent_buffer(buf, &val, 0, csum_size);
94647322 323 btrfs_warn_rl(fs_info,
5d163e0e 324 "%s checksum verify failed on %llu wanted %X found %X level %d",
01d58472 325 fs_info->sb->s_id, buf->start,
efe120a0 326 val, found, btrfs_header_level(buf));
8bd98f0e 327 return -EUCLEAN;
19c00ddc
CM
328 }
329 } else {
607d432d 330 write_extent_buffer(buf, result, 0, csum_size);
19c00ddc 331 }
71a63551 332
19c00ddc
CM
333 return 0;
334}
335
d352ac68
CM
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 */
1259ab75 342static int verify_parent_transid(struct extent_io_tree *io_tree,
b9fab919
CM
343 struct extent_buffer *eb, u64 parent_transid,
344 int atomic)
1259ab75 345{
2ac55d41 346 struct extent_state *cached_state = NULL;
1259ab75 347 int ret;
2755a0de 348 bool need_lock = (current->journal_info == BTRFS_SEND_TRANS_STUB);
1259ab75
CM
349
350 if (!parent_transid || btrfs_header_generation(eb) == parent_transid)
351 return 0;
352
b9fab919
CM
353 if (atomic)
354 return -EAGAIN;
355
a26e8c9f
JB
356 if (need_lock) {
357 btrfs_tree_read_lock(eb);
358 btrfs_set_lock_blocking_rw(eb, BTRFS_READ_LOCK);
359 }
360
2ac55d41 361 lock_extent_bits(io_tree, eb->start, eb->start + eb->len - 1,
ff13db41 362 &cached_state);
0b32f4bb 363 if (extent_buffer_uptodate(eb) &&
1259ab75
CM
364 btrfs_header_generation(eb) == parent_transid) {
365 ret = 0;
366 goto out;
367 }
94647322
DS
368 btrfs_err_rl(eb->fs_info,
369 "parent transid verify failed on %llu wanted %llu found %llu",
370 eb->start,
29549aec 371 parent_transid, btrfs_header_generation(eb));
1259ab75 372 ret = 1;
a26e8c9f
JB
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
01327610 377 * block that has been freed and re-allocated. So don't clear uptodate
a26e8c9f
JB
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);
33958dc6 384out:
2ac55d41 385 unlock_extent_cached(io_tree, eb->start, eb->start + eb->len - 1,
e43bbe5e 386 &cached_state);
472b909f
JB
387 if (need_lock)
388 btrfs_tree_read_unlock_blocking(eb);
1259ab75 389 return ret;
1259ab75
CM
390}
391
1104a885
DS
392/*
393 * Return 0 if the superblock checksum type matches the checksum value of that
394 * algorithm. Pass the raw disk superblock data.
395 */
ab8d0fc4
JM
396static int btrfs_check_super_csum(struct btrfs_fs_info *fs_info,
397 char *raw_disk_sb)
1104a885
DS
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;
776c4a7c 406 char result[sizeof(crc)];
1104a885
DS
407
408 /*
409 * The super_block structure does not span the whole
410 * BTRFS_SUPER_INFO_SIZE range, we expect that the unused space
01327610 411 * is filled with zeros and is included in the checksum.
1104a885
DS
412 */
413 crc = btrfs_csum_data(raw_disk_sb + BTRFS_CSUM_SIZE,
414 crc, BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE);
415 btrfs_csum_final(crc, result);
416
776c4a7c 417 if (memcmp(raw_disk_sb, result, sizeof(result)))
1104a885
DS
418 ret = 1;
419 }
420
421 if (csum_type >= ARRAY_SIZE(btrfs_csum_sizes)) {
ab8d0fc4 422 btrfs_err(fs_info, "unsupported checksum algorithm %u",
1104a885
DS
423 csum_type);
424 ret = 1;
425 }
426
427 return ret;
428}
429
581c1760
QW
430static int verify_level_key(struct btrfs_fs_info *fs_info,
431 struct extent_buffer *eb, int level,
432 struct btrfs_key *first_key)
433{
434 int found_level;
435 struct btrfs_key found_key;
436 int ret;
437
438 found_level = btrfs_header_level(eb);
439 if (found_level != level) {
440#ifdef CONFIG_BTRFS_DEBUG
441 WARN_ON(1);
442 btrfs_err(fs_info,
443"tree level mismatch detected, bytenr=%llu level expected=%u has=%u",
444 eb->start, level, found_level);
445#endif
446 return -EIO;
447 }
448
449 if (!first_key)
450 return 0;
451
452 if (found_level)
453 btrfs_node_key_to_cpu(eb, &found_key, 0);
454 else
455 btrfs_item_key_to_cpu(eb, &found_key, 0);
456 ret = btrfs_comp_cpu_keys(first_key, &found_key);
457
458#ifdef CONFIG_BTRFS_DEBUG
459 if (ret) {
460 WARN_ON(1);
461 btrfs_err(fs_info,
462"tree first key mismatch detected, bytenr=%llu key expected=(%llu, %u, %llu) has=(%llu, %u, %llu)",
463 eb->start, first_key->objectid, first_key->type,
464 first_key->offset, found_key.objectid,
465 found_key.type, found_key.offset);
466 }
467#endif
468 return ret;
469}
470
d352ac68
CM
471/*
472 * helper to read a given tree block, doing retries as required when
473 * the checksums don't match and we have alternate mirrors to try.
581c1760
QW
474 *
475 * @parent_transid: expected transid, skip check if 0
476 * @level: expected level, mandatory check
477 * @first_key: expected key of first slot, skip check if NULL
d352ac68 478 */
2ff7e61e 479static int btree_read_extent_buffer_pages(struct btrfs_fs_info *fs_info,
f188591e 480 struct extent_buffer *eb,
581c1760
QW
481 u64 parent_transid, int level,
482 struct btrfs_key *first_key)
f188591e
CM
483{
484 struct extent_io_tree *io_tree;
ea466794 485 int failed = 0;
f188591e
CM
486 int ret;
487 int num_copies = 0;
488 int mirror_num = 0;
ea466794 489 int failed_mirror = 0;
f188591e 490
a826d6dc 491 clear_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
0b246afa 492 io_tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
f188591e 493 while (1) {
8436ea91 494 ret = read_extent_buffer_pages(io_tree, eb, WAIT_COMPLETE,
6af49dbd 495 mirror_num);
256dd1bb 496 if (!ret) {
581c1760 497 if (verify_parent_transid(io_tree, eb,
b9fab919 498 parent_transid, 0))
256dd1bb 499 ret = -EIO;
581c1760
QW
500 else if (verify_level_key(fs_info, eb, level,
501 first_key))
502 ret = -EUCLEAN;
503 else
504 break;
256dd1bb 505 }
d397712b 506
a826d6dc
JB
507 /*
508 * This buffer's crc is fine, but its contents are corrupted, so
509 * there is no reason to read the other copies, they won't be
510 * any less wrong.
511 */
581c1760
QW
512 if (test_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags) ||
513 ret == -EUCLEAN)
ea466794
JB
514 break;
515
0b246afa 516 num_copies = btrfs_num_copies(fs_info,
f188591e 517 eb->start, eb->len);
4235298e 518 if (num_copies == 1)
ea466794 519 break;
4235298e 520
5cf1ab56
JB
521 if (!failed_mirror) {
522 failed = 1;
523 failed_mirror = eb->read_mirror;
524 }
525
f188591e 526 mirror_num++;
ea466794
JB
527 if (mirror_num == failed_mirror)
528 mirror_num++;
529
4235298e 530 if (mirror_num > num_copies)
ea466794 531 break;
f188591e 532 }
ea466794 533
c0901581 534 if (failed && !ret && failed_mirror)
2ff7e61e 535 repair_eb_io_failure(fs_info, eb, failed_mirror);
ea466794
JB
536
537 return ret;
f188591e 538}
19c00ddc 539
d352ac68 540/*
d397712b
CM
541 * checksum a dirty tree block before IO. This has extra checks to make sure
542 * we only fill in the checksum field in the first page of a multi-page block
d352ac68 543 */
d397712b 544
01d58472 545static int csum_dirty_buffer(struct btrfs_fs_info *fs_info, struct page *page)
19c00ddc 546{
4eee4fa4 547 u64 start = page_offset(page);
19c00ddc 548 u64 found_start;
19c00ddc 549 struct extent_buffer *eb;
f188591e 550
4f2de97a
JB
551 eb = (struct extent_buffer *)page->private;
552 if (page != eb->pages[0])
553 return 0;
0f805531 554
19c00ddc 555 found_start = btrfs_header_bytenr(eb);
0f805531
AL
556 /*
557 * Please do not consolidate these warnings into a single if.
558 * It is useful to know what went wrong.
559 */
560 if (WARN_ON(found_start != start))
561 return -EUCLEAN;
562 if (WARN_ON(!PageUptodate(page)))
563 return -EUCLEAN;
564
565 ASSERT(memcmp_extent_buffer(eb, fs_info->fsid,
566 btrfs_header_fsid(), BTRFS_FSID_SIZE) == 0);
567
8bd98f0e 568 return csum_tree_block(fs_info, eb, 0);
19c00ddc
CM
569}
570
01d58472 571static int check_tree_block_fsid(struct btrfs_fs_info *fs_info,
2b82032c
YZ
572 struct extent_buffer *eb)
573{
01d58472 574 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
44880fdc 575 u8 fsid[BTRFS_FSID_SIZE];
2b82032c
YZ
576 int ret = 1;
577
0a4e5586 578 read_extent_buffer(eb, fsid, btrfs_header_fsid(), BTRFS_FSID_SIZE);
2b82032c
YZ
579 while (fs_devices) {
580 if (!memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE)) {
581 ret = 0;
582 break;
583 }
584 fs_devices = fs_devices->seed;
585 }
586 return ret;
587}
588
facc8a22
MX
589static int btree_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
590 u64 phy_offset, struct page *page,
591 u64 start, u64 end, int mirror)
ce9adaa5 592{
ce9adaa5
CM
593 u64 found_start;
594 int found_level;
ce9adaa5
CM
595 struct extent_buffer *eb;
596 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
02873e43 597 struct btrfs_fs_info *fs_info = root->fs_info;
f188591e 598 int ret = 0;
727011e0 599 int reads_done;
ce9adaa5 600
ce9adaa5
CM
601 if (!page->private)
602 goto out;
d397712b 603
4f2de97a 604 eb = (struct extent_buffer *)page->private;
d397712b 605
0b32f4bb
JB
606 /* the pending IO might have been the only thing that kept this buffer
607 * in memory. Make sure we have a ref for all this other checks
608 */
609 extent_buffer_get(eb);
610
611 reads_done = atomic_dec_and_test(&eb->io_pages);
727011e0
CM
612 if (!reads_done)
613 goto err;
f188591e 614
5cf1ab56 615 eb->read_mirror = mirror;
656f30db 616 if (test_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags)) {
ea466794
JB
617 ret = -EIO;
618 goto err;
619 }
620
ce9adaa5 621 found_start = btrfs_header_bytenr(eb);
727011e0 622 if (found_start != eb->start) {
02873e43
ZL
623 btrfs_err_rl(fs_info, "bad tree block start %llu %llu",
624 found_start, eb->start);
f188591e 625 ret = -EIO;
ce9adaa5
CM
626 goto err;
627 }
02873e43
ZL
628 if (check_tree_block_fsid(fs_info, eb)) {
629 btrfs_err_rl(fs_info, "bad fsid on block %llu",
630 eb->start);
1259ab75
CM
631 ret = -EIO;
632 goto err;
633 }
ce9adaa5 634 found_level = btrfs_header_level(eb);
1c24c3ce 635 if (found_level >= BTRFS_MAX_LEVEL) {
02873e43
ZL
636 btrfs_err(fs_info, "bad tree block level %d",
637 (int)btrfs_header_level(eb));
1c24c3ce
JB
638 ret = -EIO;
639 goto err;
640 }
ce9adaa5 641
85d4e461
CM
642 btrfs_set_buffer_lockdep_class(btrfs_header_owner(eb),
643 eb, found_level);
4008c04a 644
02873e43 645 ret = csum_tree_block(fs_info, eb, 1);
8bd98f0e 646 if (ret)
a826d6dc 647 goto err;
a826d6dc
JB
648
649 /*
650 * If this is a leaf block and it is corrupt, set the corrupt bit so
651 * that we don't try and read the other copies of this block, just
652 * return -EIO.
653 */
2f659546 654 if (found_level == 0 && btrfs_check_leaf_full(fs_info, eb)) {
a826d6dc
JB
655 set_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
656 ret = -EIO;
657 }
ce9adaa5 658
2f659546 659 if (found_level > 0 && btrfs_check_node(fs_info, eb))
053ab70f
LB
660 ret = -EIO;
661
0b32f4bb
JB
662 if (!ret)
663 set_extent_buffer_uptodate(eb);
ce9adaa5 664err:
79fb65a1
JB
665 if (reads_done &&
666 test_and_clear_bit(EXTENT_BUFFER_READAHEAD, &eb->bflags))
d48d71aa 667 btree_readahead_hook(eb, ret);
4bb31e92 668
53b381b3
DW
669 if (ret) {
670 /*
671 * our io error hook is going to dec the io pages
672 * again, we have to make sure it has something
673 * to decrement
674 */
675 atomic_inc(&eb->io_pages);
0b32f4bb 676 clear_extent_buffer_uptodate(eb);
53b381b3 677 }
0b32f4bb 678 free_extent_buffer(eb);
ce9adaa5 679out:
f188591e 680 return ret;
ce9adaa5
CM
681}
682
ea466794 683static int btree_io_failed_hook(struct page *page, int failed_mirror)
4bb31e92 684{
4bb31e92 685 struct extent_buffer *eb;
4bb31e92 686
4f2de97a 687 eb = (struct extent_buffer *)page->private;
656f30db 688 set_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
5cf1ab56 689 eb->read_mirror = failed_mirror;
53b381b3 690 atomic_dec(&eb->io_pages);
ea466794 691 if (test_and_clear_bit(EXTENT_BUFFER_READAHEAD, &eb->bflags))
d48d71aa 692 btree_readahead_hook(eb, -EIO);
4bb31e92
AJ
693 return -EIO; /* we fixed nothing */
694}
695
4246a0b6 696static void end_workqueue_bio(struct bio *bio)
ce9adaa5 697{
97eb6b69 698 struct btrfs_end_io_wq *end_io_wq = bio->bi_private;
ce9adaa5 699 struct btrfs_fs_info *fs_info;
9e0af237
LB
700 struct btrfs_workqueue *wq;
701 btrfs_work_func_t func;
ce9adaa5 702
ce9adaa5 703 fs_info = end_io_wq->info;
4e4cbee9 704 end_io_wq->status = bio->bi_status;
d20f7043 705
37226b21 706 if (bio_op(bio) == REQ_OP_WRITE) {
9e0af237
LB
707 if (end_io_wq->metadata == BTRFS_WQ_ENDIO_METADATA) {
708 wq = fs_info->endio_meta_write_workers;
709 func = btrfs_endio_meta_write_helper;
710 } else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_FREE_SPACE) {
711 wq = fs_info->endio_freespace_worker;
712 func = btrfs_freespace_write_helper;
713 } else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56) {
714 wq = fs_info->endio_raid56_workers;
715 func = btrfs_endio_raid56_helper;
716 } else {
717 wq = fs_info->endio_write_workers;
718 func = btrfs_endio_write_helper;
719 }
d20f7043 720 } else {
8b110e39
MX
721 if (unlikely(end_io_wq->metadata ==
722 BTRFS_WQ_ENDIO_DIO_REPAIR)) {
723 wq = fs_info->endio_repair_workers;
724 func = btrfs_endio_repair_helper;
725 } else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56) {
9e0af237
LB
726 wq = fs_info->endio_raid56_workers;
727 func = btrfs_endio_raid56_helper;
728 } else if (end_io_wq->metadata) {
729 wq = fs_info->endio_meta_workers;
730 func = btrfs_endio_meta_helper;
731 } else {
732 wq = fs_info->endio_workers;
733 func = btrfs_endio_helper;
734 }
d20f7043 735 }
9e0af237
LB
736
737 btrfs_init_work(&end_io_wq->work, func, end_workqueue_fn, NULL, NULL);
738 btrfs_queue_work(wq, &end_io_wq->work);
ce9adaa5
CM
739}
740
4e4cbee9 741blk_status_t btrfs_bio_wq_end_io(struct btrfs_fs_info *info, struct bio *bio,
bfebd8b5 742 enum btrfs_wq_endio_type metadata)
0b86a832 743{
97eb6b69 744 struct btrfs_end_io_wq *end_io_wq;
8b110e39 745
97eb6b69 746 end_io_wq = kmem_cache_alloc(btrfs_end_io_wq_cache, GFP_NOFS);
ce9adaa5 747 if (!end_io_wq)
4e4cbee9 748 return BLK_STS_RESOURCE;
ce9adaa5
CM
749
750 end_io_wq->private = bio->bi_private;
751 end_io_wq->end_io = bio->bi_end_io;
22c59948 752 end_io_wq->info = info;
4e4cbee9 753 end_io_wq->status = 0;
ce9adaa5 754 end_io_wq->bio = bio;
22c59948 755 end_io_wq->metadata = metadata;
ce9adaa5
CM
756
757 bio->bi_private = end_io_wq;
758 bio->bi_end_io = end_workqueue_bio;
22c59948
CM
759 return 0;
760}
761
4a69a410
CM
762static void run_one_async_start(struct btrfs_work *work)
763{
4a69a410 764 struct async_submit_bio *async;
4e4cbee9 765 blk_status_t ret;
4a69a410
CM
766
767 async = container_of(work, struct async_submit_bio, work);
c6100a4b 768 ret = async->submit_bio_start(async->private_data, async->bio,
79787eaa
JM
769 async->bio_offset);
770 if (ret)
4e4cbee9 771 async->status = ret;
4a69a410
CM
772}
773
774static void run_one_async_done(struct btrfs_work *work)
8b712842 775{
8b712842
CM
776 struct async_submit_bio *async;
777
778 async = container_of(work, struct async_submit_bio, work);
4854ddd0 779
bb7ab3b9 780 /* If an error occurred we just want to clean up the bio and move on */
4e4cbee9
CH
781 if (async->status) {
782 async->bio->bi_status = async->status;
4246a0b6 783 bio_endio(async->bio);
79787eaa
JM
784 return;
785 }
786
6c553435 787 async->submit_bio_done(async->private_data, async->bio, async->mirror_num);
4a69a410
CM
788}
789
790static void run_one_async_free(struct btrfs_work *work)
791{
792 struct async_submit_bio *async;
793
794 async = container_of(work, struct async_submit_bio, work);
8b712842
CM
795 kfree(async);
796}
797
8c27cb35
LT
798blk_status_t btrfs_wq_submit_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
799 int mirror_num, unsigned long bio_flags,
800 u64 bio_offset, void *private_data,
a758781d
DS
801 extent_submit_bio_start_t *submit_bio_start,
802 extent_submit_bio_done_t *submit_bio_done)
44b8bd7e
CM
803{
804 struct async_submit_bio *async;
805
806 async = kmalloc(sizeof(*async), GFP_NOFS);
807 if (!async)
4e4cbee9 808 return BLK_STS_RESOURCE;
44b8bd7e 809
c6100a4b
JB
810 async->private_data = private_data;
811 async->fs_info = fs_info;
44b8bd7e
CM
812 async->bio = bio;
813 async->mirror_num = mirror_num;
4a69a410
CM
814 async->submit_bio_start = submit_bio_start;
815 async->submit_bio_done = submit_bio_done;
816
9e0af237 817 btrfs_init_work(&async->work, btrfs_worker_helper, run_one_async_start,
5cdc7ad3 818 run_one_async_done, run_one_async_free);
4a69a410 819
c8b97818 820 async->bio_flags = bio_flags;
eaf25d93 821 async->bio_offset = bio_offset;
8c8bee1d 822
4e4cbee9 823 async->status = 0;
79787eaa 824
67f055c7 825 if (op_is_sync(bio->bi_opf))
5cdc7ad3 826 btrfs_set_work_high_priority(&async->work);
d313d7a3 827
5cdc7ad3 828 btrfs_queue_work(fs_info->workers, &async->work);
44b8bd7e
CM
829 return 0;
830}
831
4e4cbee9 832static blk_status_t btree_csum_one_bio(struct bio *bio)
ce3ed71a 833{
2c30c71b 834 struct bio_vec *bvec;
ce3ed71a 835 struct btrfs_root *root;
2c30c71b 836 int i, ret = 0;
ce3ed71a 837
c09abff8 838 ASSERT(!bio_flagged(bio, BIO_CLONED));
2c30c71b 839 bio_for_each_segment_all(bvec, bio, i) {
ce3ed71a 840 root = BTRFS_I(bvec->bv_page->mapping->host)->root;
01d58472 841 ret = csum_dirty_buffer(root->fs_info, bvec->bv_page);
79787eaa
JM
842 if (ret)
843 break;
ce3ed71a 844 }
2c30c71b 845
4e4cbee9 846 return errno_to_blk_status(ret);
ce3ed71a
CM
847}
848
d0ee3934 849static blk_status_t btree_submit_bio_start(void *private_data, struct bio *bio,
8c27cb35 850 u64 bio_offset)
22c59948 851{
8b712842
CM
852 /*
853 * when we're called for a write, we're already in the async
5443be45 854 * submission context. Just jump into btrfs_map_bio
8b712842 855 */
79787eaa 856 return btree_csum_one_bio(bio);
4a69a410 857}
22c59948 858
d0ee3934 859static blk_status_t btree_submit_bio_done(void *private_data, struct bio *bio,
6c553435 860 int mirror_num)
4a69a410 861{
c6100a4b 862 struct inode *inode = private_data;
4e4cbee9 863 blk_status_t ret;
61891923 864
8b712842 865 /*
4a69a410
CM
866 * when we're called for a write, we're already in the async
867 * submission context. Just jump into btrfs_map_bio
8b712842 868 */
2ff7e61e 869 ret = btrfs_map_bio(btrfs_sb(inode->i_sb), bio, mirror_num, 1);
4246a0b6 870 if (ret) {
4e4cbee9 871 bio->bi_status = ret;
4246a0b6
CH
872 bio_endio(bio);
873 }
61891923 874 return ret;
0b86a832
CM
875}
876
18fdc679 877static int check_async_write(struct btrfs_inode *bi)
de0022b9 878{
6300463b
LB
879 if (atomic_read(&bi->sync_writers))
880 return 0;
de0022b9 881#ifdef CONFIG_X86
bc696ca0 882 if (static_cpu_has(X86_FEATURE_XMM4_2))
de0022b9
JB
883 return 0;
884#endif
885 return 1;
886}
887
8c27cb35
LT
888static blk_status_t btree_submit_bio_hook(void *private_data, struct bio *bio,
889 int mirror_num, unsigned long bio_flags,
890 u64 bio_offset)
44b8bd7e 891{
c6100a4b 892 struct inode *inode = private_data;
0b246afa 893 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
18fdc679 894 int async = check_async_write(BTRFS_I(inode));
4e4cbee9 895 blk_status_t ret;
cad321ad 896
37226b21 897 if (bio_op(bio) != REQ_OP_WRITE) {
4a69a410
CM
898 /*
899 * called for a read, do the setup so that checksum validation
900 * can happen in the async kernel threads
901 */
0b246afa
JM
902 ret = btrfs_bio_wq_end_io(fs_info, bio,
903 BTRFS_WQ_ENDIO_METADATA);
1d4284bd 904 if (ret)
61891923 905 goto out_w_error;
2ff7e61e 906 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
de0022b9
JB
907 } else if (!async) {
908 ret = btree_csum_one_bio(bio);
909 if (ret)
61891923 910 goto out_w_error;
2ff7e61e 911 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
61891923
SB
912 } else {
913 /*
914 * kthread helpers are used to submit writes so that
915 * checksumming can happen in parallel across all CPUs
916 */
c6100a4b
JB
917 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, 0,
918 bio_offset, private_data,
d0ee3934
DS
919 btree_submit_bio_start,
920 btree_submit_bio_done);
44b8bd7e 921 }
d313d7a3 922
4246a0b6
CH
923 if (ret)
924 goto out_w_error;
925 return 0;
926
61891923 927out_w_error:
4e4cbee9 928 bio->bi_status = ret;
4246a0b6 929 bio_endio(bio);
61891923 930 return ret;
44b8bd7e
CM
931}
932
3dd1462e 933#ifdef CONFIG_MIGRATION
784b4e29 934static int btree_migratepage(struct address_space *mapping,
a6bc32b8
MG
935 struct page *newpage, struct page *page,
936 enum migrate_mode mode)
784b4e29
CM
937{
938 /*
939 * we can't safely write a btree page from here,
940 * we haven't done the locking hook
941 */
942 if (PageDirty(page))
943 return -EAGAIN;
944 /*
945 * Buffers may be managed in a filesystem specific way.
946 * We must have no buffers or drop them.
947 */
948 if (page_has_private(page) &&
949 !try_to_release_page(page, GFP_KERNEL))
950 return -EAGAIN;
a6bc32b8 951 return migrate_page(mapping, newpage, page, mode);
784b4e29 952}
3dd1462e 953#endif
784b4e29 954
0da5468f
CM
955
956static int btree_writepages(struct address_space *mapping,
957 struct writeback_control *wbc)
958{
e2d84521
MX
959 struct btrfs_fs_info *fs_info;
960 int ret;
961
d8d5f3e1 962 if (wbc->sync_mode == WB_SYNC_NONE) {
448d640b
CM
963
964 if (wbc->for_kupdate)
965 return 0;
966
e2d84521 967 fs_info = BTRFS_I(mapping->host)->root->fs_info;
b9473439 968 /* this is a bit racy, but that's ok */
e2d84521
MX
969 ret = percpu_counter_compare(&fs_info->dirty_metadata_bytes,
970 BTRFS_DIRTY_METADATA_THRESH);
971 if (ret < 0)
793955bc 972 return 0;
793955bc 973 }
0b32f4bb 974 return btree_write_cache_pages(mapping, wbc);
0da5468f
CM
975}
976
b2950863 977static int btree_readpage(struct file *file, struct page *page)
5f39d397 978{
d1310b2e
CM
979 struct extent_io_tree *tree;
980 tree = &BTRFS_I(page->mapping->host)->io_tree;
8ddc7d9c 981 return extent_read_full_page(tree, page, btree_get_extent, 0);
5f39d397 982}
22b0ebda 983
70dec807 984static int btree_releasepage(struct page *page, gfp_t gfp_flags)
5f39d397 985{
98509cfc 986 if (PageWriteback(page) || PageDirty(page))
d397712b 987 return 0;
0c4e538b 988
f7a52a40 989 return try_release_extent_buffer(page);
d98237b3
CM
990}
991
d47992f8
LC
992static void btree_invalidatepage(struct page *page, unsigned int offset,
993 unsigned int length)
d98237b3 994{
d1310b2e
CM
995 struct extent_io_tree *tree;
996 tree = &BTRFS_I(page->mapping->host)->io_tree;
5f39d397
CM
997 extent_invalidatepage(tree, page, offset);
998 btree_releasepage(page, GFP_NOFS);
9ad6b7bc 999 if (PagePrivate(page)) {
efe120a0
FH
1000 btrfs_warn(BTRFS_I(page->mapping->host)->root->fs_info,
1001 "page private not zero on page %llu",
1002 (unsigned long long)page_offset(page));
9ad6b7bc
CM
1003 ClearPagePrivate(page);
1004 set_page_private(page, 0);
09cbfeaf 1005 put_page(page);
9ad6b7bc 1006 }
d98237b3
CM
1007}
1008
0b32f4bb
JB
1009static int btree_set_page_dirty(struct page *page)
1010{
bb146eb2 1011#ifdef DEBUG
0b32f4bb
JB
1012 struct extent_buffer *eb;
1013
1014 BUG_ON(!PagePrivate(page));
1015 eb = (struct extent_buffer *)page->private;
1016 BUG_ON(!eb);
1017 BUG_ON(!test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
1018 BUG_ON(!atomic_read(&eb->refs));
1019 btrfs_assert_tree_locked(eb);
bb146eb2 1020#endif
0b32f4bb
JB
1021 return __set_page_dirty_nobuffers(page);
1022}
1023
7f09410b 1024static const struct address_space_operations btree_aops = {
d98237b3 1025 .readpage = btree_readpage,
0da5468f 1026 .writepages = btree_writepages,
5f39d397
CM
1027 .releasepage = btree_releasepage,
1028 .invalidatepage = btree_invalidatepage,
5a92bc88 1029#ifdef CONFIG_MIGRATION
784b4e29 1030 .migratepage = btree_migratepage,
5a92bc88 1031#endif
0b32f4bb 1032 .set_page_dirty = btree_set_page_dirty,
d98237b3
CM
1033};
1034
2ff7e61e 1035void readahead_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr)
090d1875 1036{
5f39d397 1037 struct extent_buffer *buf = NULL;
2ff7e61e 1038 struct inode *btree_inode = fs_info->btree_inode;
090d1875 1039
2ff7e61e 1040 buf = btrfs_find_create_tree_block(fs_info, bytenr);
c871b0f2 1041 if (IS_ERR(buf))
6197d86e 1042 return;
d1310b2e 1043 read_extent_buffer_pages(&BTRFS_I(btree_inode)->io_tree,
6af49dbd 1044 buf, WAIT_NONE, 0);
5f39d397 1045 free_extent_buffer(buf);
090d1875
CM
1046}
1047
2ff7e61e 1048int reada_tree_block_flagged(struct btrfs_fs_info *fs_info, u64 bytenr,
ab0fff03
AJ
1049 int mirror_num, struct extent_buffer **eb)
1050{
1051 struct extent_buffer *buf = NULL;
2ff7e61e 1052 struct inode *btree_inode = fs_info->btree_inode;
ab0fff03
AJ
1053 struct extent_io_tree *io_tree = &BTRFS_I(btree_inode)->io_tree;
1054 int ret;
1055
2ff7e61e 1056 buf = btrfs_find_create_tree_block(fs_info, bytenr);
c871b0f2 1057 if (IS_ERR(buf))
ab0fff03
AJ
1058 return 0;
1059
1060 set_bit(EXTENT_BUFFER_READAHEAD, &buf->bflags);
1061
8436ea91 1062 ret = read_extent_buffer_pages(io_tree, buf, WAIT_PAGE_LOCK,
6af49dbd 1063 mirror_num);
ab0fff03
AJ
1064 if (ret) {
1065 free_extent_buffer(buf);
1066 return ret;
1067 }
1068
1069 if (test_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags)) {
1070 free_extent_buffer(buf);
1071 return -EIO;
0b32f4bb 1072 } else if (extent_buffer_uptodate(buf)) {
ab0fff03
AJ
1073 *eb = buf;
1074 } else {
1075 free_extent_buffer(buf);
1076 }
1077 return 0;
1078}
1079
2ff7e61e
JM
1080struct extent_buffer *btrfs_find_create_tree_block(
1081 struct btrfs_fs_info *fs_info,
1082 u64 bytenr)
0999df54 1083{
0b246afa
JM
1084 if (btrfs_is_testing(fs_info))
1085 return alloc_test_extent_buffer(fs_info, bytenr);
1086 return alloc_extent_buffer(fs_info, bytenr);
0999df54
CM
1087}
1088
1089
e02119d5
CM
1090int btrfs_write_tree_block(struct extent_buffer *buf)
1091{
727011e0 1092 return filemap_fdatawrite_range(buf->pages[0]->mapping, buf->start,
8aa38c31 1093 buf->start + buf->len - 1);
e02119d5
CM
1094}
1095
3189ff77 1096void btrfs_wait_tree_block_writeback(struct extent_buffer *buf)
e02119d5 1097{
3189ff77
JL
1098 filemap_fdatawait_range(buf->pages[0]->mapping,
1099 buf->start, buf->start + buf->len - 1);
e02119d5
CM
1100}
1101
581c1760
QW
1102/*
1103 * Read tree block at logical address @bytenr and do variant basic but critical
1104 * verification.
1105 *
1106 * @parent_transid: expected transid of this tree block, skip check if 0
1107 * @level: expected level, mandatory check
1108 * @first_key: expected key in slot 0, skip check if NULL
1109 */
2ff7e61e 1110struct extent_buffer *read_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr,
581c1760
QW
1111 u64 parent_transid, int level,
1112 struct btrfs_key *first_key)
0999df54
CM
1113{
1114 struct extent_buffer *buf = NULL;
0999df54
CM
1115 int ret;
1116
2ff7e61e 1117 buf = btrfs_find_create_tree_block(fs_info, bytenr);
c871b0f2
LB
1118 if (IS_ERR(buf))
1119 return buf;
0999df54 1120
581c1760
QW
1121 ret = btree_read_extent_buffer_pages(fs_info, buf, parent_transid,
1122 level, first_key);
0f0fe8f7
FDBM
1123 if (ret) {
1124 free_extent_buffer(buf);
64c043de 1125 return ERR_PTR(ret);
0f0fe8f7 1126 }
5f39d397 1127 return buf;
ce9adaa5 1128
eb60ceac
CM
1129}
1130
7c302b49 1131void clean_tree_block(struct btrfs_fs_info *fs_info,
d5c13f92 1132 struct extent_buffer *buf)
ed2ff2cb 1133{
55c69072 1134 if (btrfs_header_generation(buf) ==
e2d84521 1135 fs_info->running_transaction->transid) {
b9447ef8 1136 btrfs_assert_tree_locked(buf);
b4ce94de 1137
b9473439 1138 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &buf->bflags)) {
104b4e51
NB
1139 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
1140 -buf->len,
1141 fs_info->dirty_metadata_batch);
ed7b63eb
JB
1142 /* ugh, clear_extent_buffer_dirty needs to lock the page */
1143 btrfs_set_lock_blocking(buf);
1144 clear_extent_buffer_dirty(buf);
1145 }
925baedd 1146 }
5f39d397
CM
1147}
1148
8257b2dc
MX
1149static struct btrfs_subvolume_writers *btrfs_alloc_subvolume_writers(void)
1150{
1151 struct btrfs_subvolume_writers *writers;
1152 int ret;
1153
1154 writers = kmalloc(sizeof(*writers), GFP_NOFS);
1155 if (!writers)
1156 return ERR_PTR(-ENOMEM);
1157
8a5a916d 1158 ret = percpu_counter_init(&writers->counter, 0, GFP_NOFS);
8257b2dc
MX
1159 if (ret < 0) {
1160 kfree(writers);
1161 return ERR_PTR(ret);
1162 }
1163
1164 init_waitqueue_head(&writers->wait);
1165 return writers;
1166}
1167
1168static void
1169btrfs_free_subvolume_writers(struct btrfs_subvolume_writers *writers)
1170{
1171 percpu_counter_destroy(&writers->counter);
1172 kfree(writers);
1173}
1174
da17066c 1175static void __setup_root(struct btrfs_root *root, struct btrfs_fs_info *fs_info,
143bede5 1176 u64 objectid)
d97e63b6 1177{
7c0260ee 1178 bool dummy = test_bit(BTRFS_FS_STATE_DUMMY_FS_INFO, &fs_info->fs_state);
cfaa7295 1179 root->node = NULL;
a28ec197 1180 root->commit_root = NULL;
27cdeb70 1181 root->state = 0;
d68fc57b 1182 root->orphan_cleanup_state = 0;
0b86a832 1183
0f7d52f4
CM
1184 root->objectid = objectid;
1185 root->last_trans = 0;
13a8a7c8 1186 root->highest_objectid = 0;
eb73c1b7 1187 root->nr_delalloc_inodes = 0;
199c2a9c 1188 root->nr_ordered_extents = 0;
58176a96 1189 root->name = NULL;
6bef4d31 1190 root->inode_tree = RB_ROOT;
16cdcec7 1191 INIT_RADIX_TREE(&root->delayed_nodes_tree, GFP_ATOMIC);
f0486c68 1192 root->block_rsv = NULL;
d68fc57b 1193 root->orphan_block_rsv = NULL;
0b86a832
CM
1194
1195 INIT_LIST_HEAD(&root->dirty_list);
5d4f98a2 1196 INIT_LIST_HEAD(&root->root_list);
eb73c1b7
MX
1197 INIT_LIST_HEAD(&root->delalloc_inodes);
1198 INIT_LIST_HEAD(&root->delalloc_root);
199c2a9c
MX
1199 INIT_LIST_HEAD(&root->ordered_extents);
1200 INIT_LIST_HEAD(&root->ordered_root);
2ab28f32
JB
1201 INIT_LIST_HEAD(&root->logged_list[0]);
1202 INIT_LIST_HEAD(&root->logged_list[1]);
d68fc57b 1203 spin_lock_init(&root->orphan_lock);
5d4f98a2 1204 spin_lock_init(&root->inode_lock);
eb73c1b7 1205 spin_lock_init(&root->delalloc_lock);
199c2a9c 1206 spin_lock_init(&root->ordered_extent_lock);
f0486c68 1207 spin_lock_init(&root->accounting_lock);
2ab28f32
JB
1208 spin_lock_init(&root->log_extents_lock[0]);
1209 spin_lock_init(&root->log_extents_lock[1]);
8287475a 1210 spin_lock_init(&root->qgroup_meta_rsv_lock);
a2135011 1211 mutex_init(&root->objectid_mutex);
e02119d5 1212 mutex_init(&root->log_mutex);
31f3d255 1213 mutex_init(&root->ordered_extent_mutex);
573bfb72 1214 mutex_init(&root->delalloc_mutex);
7237f183
YZ
1215 init_waitqueue_head(&root->log_writer_wait);
1216 init_waitqueue_head(&root->log_commit_wait[0]);
1217 init_waitqueue_head(&root->log_commit_wait[1]);
8b050d35
MX
1218 INIT_LIST_HEAD(&root->log_ctxs[0]);
1219 INIT_LIST_HEAD(&root->log_ctxs[1]);
7237f183
YZ
1220 atomic_set(&root->log_commit[0], 0);
1221 atomic_set(&root->log_commit[1], 0);
1222 atomic_set(&root->log_writers, 0);
2ecb7923 1223 atomic_set(&root->log_batch, 0);
8a35d95f 1224 atomic_set(&root->orphan_inodes, 0);
0700cea7 1225 refcount_set(&root->refs, 1);
ea14b57f 1226 atomic_set(&root->will_be_snapshotted, 0);
7237f183 1227 root->log_transid = 0;
d1433deb 1228 root->log_transid_committed = -1;
257c62e1 1229 root->last_log_commit = 0;
7c0260ee 1230 if (!dummy)
c6100a4b 1231 extent_io_tree_init(&root->dirty_log_pages, NULL);
017e5369 1232
3768f368
CM
1233 memset(&root->root_key, 0, sizeof(root->root_key));
1234 memset(&root->root_item, 0, sizeof(root->root_item));
6702ed49 1235 memset(&root->defrag_progress, 0, sizeof(root->defrag_progress));
7c0260ee 1236 if (!dummy)
06ea65a3
JB
1237 root->defrag_trans_start = fs_info->generation;
1238 else
1239 root->defrag_trans_start = 0;
4d775673 1240 root->root_key.objectid = objectid;
0ee5dc67 1241 root->anon_dev = 0;
8ea05e3a 1242
5f3ab90a 1243 spin_lock_init(&root->root_item_lock);
3768f368
CM
1244}
1245
74e4d827
DS
1246static struct btrfs_root *btrfs_alloc_root(struct btrfs_fs_info *fs_info,
1247 gfp_t flags)
6f07e42e 1248{
74e4d827 1249 struct btrfs_root *root = kzalloc(sizeof(*root), flags);
6f07e42e
AV
1250 if (root)
1251 root->fs_info = fs_info;
1252 return root;
1253}
1254
06ea65a3
JB
1255#ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
1256/* Should only be used by the testing infrastructure */
da17066c 1257struct btrfs_root *btrfs_alloc_dummy_root(struct btrfs_fs_info *fs_info)
06ea65a3
JB
1258{
1259 struct btrfs_root *root;
1260
7c0260ee
JM
1261 if (!fs_info)
1262 return ERR_PTR(-EINVAL);
1263
1264 root = btrfs_alloc_root(fs_info, GFP_KERNEL);
06ea65a3
JB
1265 if (!root)
1266 return ERR_PTR(-ENOMEM);
da17066c 1267
b9ef22de 1268 /* We don't use the stripesize in selftest, set it as sectorsize */
da17066c 1269 __setup_root(root, fs_info, BTRFS_ROOT_TREE_OBJECTID);
faa2dbf0 1270 root->alloc_bytenr = 0;
06ea65a3
JB
1271
1272 return root;
1273}
1274#endif
1275
20897f5c
AJ
1276struct btrfs_root *btrfs_create_tree(struct btrfs_trans_handle *trans,
1277 struct btrfs_fs_info *fs_info,
1278 u64 objectid)
1279{
1280 struct extent_buffer *leaf;
1281 struct btrfs_root *tree_root = fs_info->tree_root;
1282 struct btrfs_root *root;
1283 struct btrfs_key key;
1284 int ret = 0;
33d85fda 1285 uuid_le uuid = NULL_UUID_LE;
20897f5c 1286
74e4d827 1287 root = btrfs_alloc_root(fs_info, GFP_KERNEL);
20897f5c
AJ
1288 if (!root)
1289 return ERR_PTR(-ENOMEM);
1290
da17066c 1291 __setup_root(root, fs_info, objectid);
20897f5c
AJ
1292 root->root_key.objectid = objectid;
1293 root->root_key.type = BTRFS_ROOT_ITEM_KEY;
1294 root->root_key.offset = 0;
1295
4d75f8a9 1296 leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0);
20897f5c
AJ
1297 if (IS_ERR(leaf)) {
1298 ret = PTR_ERR(leaf);
1dd05682 1299 leaf = NULL;
20897f5c
AJ
1300 goto fail;
1301 }
1302
b159fa28 1303 memzero_extent_buffer(leaf, 0, sizeof(struct btrfs_header));
20897f5c
AJ
1304 btrfs_set_header_bytenr(leaf, leaf->start);
1305 btrfs_set_header_generation(leaf, trans->transid);
1306 btrfs_set_header_backref_rev(leaf, BTRFS_MIXED_BACKREF_REV);
1307 btrfs_set_header_owner(leaf, objectid);
1308 root->node = leaf;
1309
d24ee97b
DS
1310 write_extent_buffer_fsid(leaf, fs_info->fsid);
1311 write_extent_buffer_chunk_tree_uuid(leaf, fs_info->chunk_tree_uuid);
20897f5c
AJ
1312 btrfs_mark_buffer_dirty(leaf);
1313
1314 root->commit_root = btrfs_root_node(root);
27cdeb70 1315 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
20897f5c
AJ
1316
1317 root->root_item.flags = 0;
1318 root->root_item.byte_limit = 0;
1319 btrfs_set_root_bytenr(&root->root_item, leaf->start);
1320 btrfs_set_root_generation(&root->root_item, trans->transid);
1321 btrfs_set_root_level(&root->root_item, 0);
1322 btrfs_set_root_refs(&root->root_item, 1);
1323 btrfs_set_root_used(&root->root_item, leaf->len);
1324 btrfs_set_root_last_snapshot(&root->root_item, 0);
1325 btrfs_set_root_dirid(&root->root_item, 0);
33d85fda
QW
1326 if (is_fstree(objectid))
1327 uuid_le_gen(&uuid);
6463fe58 1328 memcpy(root->root_item.uuid, uuid.b, BTRFS_UUID_SIZE);
20897f5c
AJ
1329 root->root_item.drop_level = 0;
1330
1331 key.objectid = objectid;
1332 key.type = BTRFS_ROOT_ITEM_KEY;
1333 key.offset = 0;
1334 ret = btrfs_insert_root(trans, tree_root, &key, &root->root_item);
1335 if (ret)
1336 goto fail;
1337
1338 btrfs_tree_unlock(leaf);
1339
1dd05682
TI
1340 return root;
1341
20897f5c 1342fail:
1dd05682
TI
1343 if (leaf) {
1344 btrfs_tree_unlock(leaf);
59885b39 1345 free_extent_buffer(root->commit_root);
1dd05682
TI
1346 free_extent_buffer(leaf);
1347 }
1348 kfree(root);
20897f5c 1349
1dd05682 1350 return ERR_PTR(ret);
20897f5c
AJ
1351}
1352
7237f183
YZ
1353static struct btrfs_root *alloc_log_tree(struct btrfs_trans_handle *trans,
1354 struct btrfs_fs_info *fs_info)
0f7d52f4
CM
1355{
1356 struct btrfs_root *root;
7237f183 1357 struct extent_buffer *leaf;
e02119d5 1358
74e4d827 1359 root = btrfs_alloc_root(fs_info, GFP_NOFS);
e02119d5 1360 if (!root)
7237f183 1361 return ERR_PTR(-ENOMEM);
e02119d5 1362
da17066c 1363 __setup_root(root, fs_info, BTRFS_TREE_LOG_OBJECTID);
e02119d5
CM
1364
1365 root->root_key.objectid = BTRFS_TREE_LOG_OBJECTID;
1366 root->root_key.type = BTRFS_ROOT_ITEM_KEY;
1367 root->root_key.offset = BTRFS_TREE_LOG_OBJECTID;
27cdeb70 1368
7237f183 1369 /*
27cdeb70
MX
1370 * DON'T set REF_COWS for log trees
1371 *
7237f183
YZ
1372 * log trees do not get reference counted because they go away
1373 * before a real commit is actually done. They do store pointers
1374 * to file data extents, and those reference counts still get
1375 * updated (along with back refs to the log tree).
1376 */
e02119d5 1377
4d75f8a9
DS
1378 leaf = btrfs_alloc_tree_block(trans, root, 0, BTRFS_TREE_LOG_OBJECTID,
1379 NULL, 0, 0, 0);
7237f183
YZ
1380 if (IS_ERR(leaf)) {
1381 kfree(root);
1382 return ERR_CAST(leaf);
1383 }
e02119d5 1384
b159fa28 1385 memzero_extent_buffer(leaf, 0, sizeof(struct btrfs_header));
5d4f98a2
YZ
1386 btrfs_set_header_bytenr(leaf, leaf->start);
1387 btrfs_set_header_generation(leaf, trans->transid);
1388 btrfs_set_header_backref_rev(leaf, BTRFS_MIXED_BACKREF_REV);
1389 btrfs_set_header_owner(leaf, BTRFS_TREE_LOG_OBJECTID);
7237f183 1390 root->node = leaf;
e02119d5 1391
0b246afa 1392 write_extent_buffer_fsid(root->node, fs_info->fsid);
e02119d5
CM
1393 btrfs_mark_buffer_dirty(root->node);
1394 btrfs_tree_unlock(root->node);
7237f183
YZ
1395 return root;
1396}
1397
1398int btrfs_init_log_root_tree(struct btrfs_trans_handle *trans,
1399 struct btrfs_fs_info *fs_info)
1400{
1401 struct btrfs_root *log_root;
1402
1403 log_root = alloc_log_tree(trans, fs_info);
1404 if (IS_ERR(log_root))
1405 return PTR_ERR(log_root);
1406 WARN_ON(fs_info->log_root_tree);
1407 fs_info->log_root_tree = log_root;
1408 return 0;
1409}
1410
1411int btrfs_add_log_tree(struct btrfs_trans_handle *trans,
1412 struct btrfs_root *root)
1413{
0b246afa 1414 struct btrfs_fs_info *fs_info = root->fs_info;
7237f183
YZ
1415 struct btrfs_root *log_root;
1416 struct btrfs_inode_item *inode_item;
1417
0b246afa 1418 log_root = alloc_log_tree(trans, fs_info);
7237f183
YZ
1419 if (IS_ERR(log_root))
1420 return PTR_ERR(log_root);
1421
1422 log_root->last_trans = trans->transid;
1423 log_root->root_key.offset = root->root_key.objectid;
1424
1425 inode_item = &log_root->root_item.inode;
3cae210f
QW
1426 btrfs_set_stack_inode_generation(inode_item, 1);
1427 btrfs_set_stack_inode_size(inode_item, 3);
1428 btrfs_set_stack_inode_nlink(inode_item, 1);
da17066c 1429 btrfs_set_stack_inode_nbytes(inode_item,
0b246afa 1430 fs_info->nodesize);
3cae210f 1431 btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
7237f183 1432
5d4f98a2 1433 btrfs_set_root_node(&log_root->root_item, log_root->node);
7237f183
YZ
1434
1435 WARN_ON(root->log_root);
1436 root->log_root = log_root;
1437 root->log_transid = 0;
d1433deb 1438 root->log_transid_committed = -1;
257c62e1 1439 root->last_log_commit = 0;
e02119d5
CM
1440 return 0;
1441}
1442
35a3621b
SB
1443static struct btrfs_root *btrfs_read_tree_root(struct btrfs_root *tree_root,
1444 struct btrfs_key *key)
e02119d5
CM
1445{
1446 struct btrfs_root *root;
1447 struct btrfs_fs_info *fs_info = tree_root->fs_info;
0f7d52f4 1448 struct btrfs_path *path;
84234f3a 1449 u64 generation;
cb517eab 1450 int ret;
581c1760 1451 int level;
0f7d52f4 1452
cb517eab
MX
1453 path = btrfs_alloc_path();
1454 if (!path)
0f7d52f4 1455 return ERR_PTR(-ENOMEM);
cb517eab 1456
74e4d827 1457 root = btrfs_alloc_root(fs_info, GFP_NOFS);
cb517eab
MX
1458 if (!root) {
1459 ret = -ENOMEM;
1460 goto alloc_fail;
0f7d52f4
CM
1461 }
1462
da17066c 1463 __setup_root(root, fs_info, key->objectid);
0f7d52f4 1464
cb517eab
MX
1465 ret = btrfs_find_root(tree_root, key, path,
1466 &root->root_item, &root->root_key);
0f7d52f4 1467 if (ret) {
13a8a7c8
YZ
1468 if (ret > 0)
1469 ret = -ENOENT;
cb517eab 1470 goto find_fail;
0f7d52f4 1471 }
13a8a7c8 1472
84234f3a 1473 generation = btrfs_root_generation(&root->root_item);
581c1760 1474 level = btrfs_root_level(&root->root_item);
2ff7e61e
JM
1475 root->node = read_tree_block(fs_info,
1476 btrfs_root_bytenr(&root->root_item),
581c1760 1477 generation, level, NULL);
64c043de
LB
1478 if (IS_ERR(root->node)) {
1479 ret = PTR_ERR(root->node);
cb517eab
MX
1480 goto find_fail;
1481 } else if (!btrfs_buffer_uptodate(root->node, generation, 0)) {
1482 ret = -EIO;
64c043de
LB
1483 free_extent_buffer(root->node);
1484 goto find_fail;
416bc658 1485 }
5d4f98a2 1486 root->commit_root = btrfs_root_node(root);
13a8a7c8 1487out:
cb517eab
MX
1488 btrfs_free_path(path);
1489 return root;
1490
cb517eab
MX
1491find_fail:
1492 kfree(root);
1493alloc_fail:
1494 root = ERR_PTR(ret);
1495 goto out;
1496}
1497
1498struct btrfs_root *btrfs_read_fs_root(struct btrfs_root *tree_root,
1499 struct btrfs_key *location)
1500{
1501 struct btrfs_root *root;
1502
1503 root = btrfs_read_tree_root(tree_root, location);
1504 if (IS_ERR(root))
1505 return root;
1506
1507 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
27cdeb70 1508 set_bit(BTRFS_ROOT_REF_COWS, &root->state);
08fe4db1
LZ
1509 btrfs_check_and_init_root_item(&root->root_item);
1510 }
13a8a7c8 1511
5eda7b5e
CM
1512 return root;
1513}
1514
cb517eab
MX
1515int btrfs_init_fs_root(struct btrfs_root *root)
1516{
1517 int ret;
8257b2dc 1518 struct btrfs_subvolume_writers *writers;
cb517eab
MX
1519
1520 root->free_ino_ctl = kzalloc(sizeof(*root->free_ino_ctl), GFP_NOFS);
1521 root->free_ino_pinned = kzalloc(sizeof(*root->free_ino_pinned),
1522 GFP_NOFS);
1523 if (!root->free_ino_pinned || !root->free_ino_ctl) {
1524 ret = -ENOMEM;
1525 goto fail;
1526 }
1527
8257b2dc
MX
1528 writers = btrfs_alloc_subvolume_writers();
1529 if (IS_ERR(writers)) {
1530 ret = PTR_ERR(writers);
1531 goto fail;
1532 }
1533 root->subv_writers = writers;
1534
cb517eab 1535 btrfs_init_free_ino_ctl(root);
57cdc8db
DS
1536 spin_lock_init(&root->ino_cache_lock);
1537 init_waitqueue_head(&root->ino_cache_wait);
cb517eab
MX
1538
1539 ret = get_anon_bdev(&root->anon_dev);
1540 if (ret)
876d2cf1 1541 goto fail;
f32e48e9
CR
1542
1543 mutex_lock(&root->objectid_mutex);
1544 ret = btrfs_find_highest_objectid(root,
1545 &root->highest_objectid);
1546 if (ret) {
1547 mutex_unlock(&root->objectid_mutex);
876d2cf1 1548 goto fail;
f32e48e9
CR
1549 }
1550
1551 ASSERT(root->highest_objectid <= BTRFS_LAST_FREE_OBJECTID);
1552
1553 mutex_unlock(&root->objectid_mutex);
1554
cb517eab
MX
1555 return 0;
1556fail:
876d2cf1 1557 /* the caller is responsible to call free_fs_root */
cb517eab
MX
1558 return ret;
1559}
1560
35bbb97f
JM
1561struct btrfs_root *btrfs_lookup_fs_root(struct btrfs_fs_info *fs_info,
1562 u64 root_id)
cb517eab
MX
1563{
1564 struct btrfs_root *root;
1565
1566 spin_lock(&fs_info->fs_roots_radix_lock);
1567 root = radix_tree_lookup(&fs_info->fs_roots_radix,
1568 (unsigned long)root_id);
1569 spin_unlock(&fs_info->fs_roots_radix_lock);
1570 return root;
1571}
1572
1573int btrfs_insert_fs_root(struct btrfs_fs_info *fs_info,
1574 struct btrfs_root *root)
1575{
1576 int ret;
1577
e1860a77 1578 ret = radix_tree_preload(GFP_NOFS);
cb517eab
MX
1579 if (ret)
1580 return ret;
1581
1582 spin_lock(&fs_info->fs_roots_radix_lock);
1583 ret = radix_tree_insert(&fs_info->fs_roots_radix,
1584 (unsigned long)root->root_key.objectid,
1585 root);
1586 if (ret == 0)
27cdeb70 1587 set_bit(BTRFS_ROOT_IN_RADIX, &root->state);
cb517eab
MX
1588 spin_unlock(&fs_info->fs_roots_radix_lock);
1589 radix_tree_preload_end();
1590
1591 return ret;
1592}
1593
c00869f1
MX
1594struct btrfs_root *btrfs_get_fs_root(struct btrfs_fs_info *fs_info,
1595 struct btrfs_key *location,
1596 bool check_ref)
5eda7b5e
CM
1597{
1598 struct btrfs_root *root;
381cf658 1599 struct btrfs_path *path;
1d4c08e0 1600 struct btrfs_key key;
5eda7b5e
CM
1601 int ret;
1602
edbd8d4e
CM
1603 if (location->objectid == BTRFS_ROOT_TREE_OBJECTID)
1604 return fs_info->tree_root;
1605 if (location->objectid == BTRFS_EXTENT_TREE_OBJECTID)
1606 return fs_info->extent_root;
8f18cf13
CM
1607 if (location->objectid == BTRFS_CHUNK_TREE_OBJECTID)
1608 return fs_info->chunk_root;
1609 if (location->objectid == BTRFS_DEV_TREE_OBJECTID)
1610 return fs_info->dev_root;
0403e47e
YZ
1611 if (location->objectid == BTRFS_CSUM_TREE_OBJECTID)
1612 return fs_info->csum_root;
bcef60f2
AJ
1613 if (location->objectid == BTRFS_QUOTA_TREE_OBJECTID)
1614 return fs_info->quota_root ? fs_info->quota_root :
1615 ERR_PTR(-ENOENT);
f7a81ea4
SB
1616 if (location->objectid == BTRFS_UUID_TREE_OBJECTID)
1617 return fs_info->uuid_root ? fs_info->uuid_root :
1618 ERR_PTR(-ENOENT);
70f6d82e
OS
1619 if (location->objectid == BTRFS_FREE_SPACE_TREE_OBJECTID)
1620 return fs_info->free_space_root ? fs_info->free_space_root :
1621 ERR_PTR(-ENOENT);
4df27c4d 1622again:
cb517eab 1623 root = btrfs_lookup_fs_root(fs_info, location->objectid);
48475471 1624 if (root) {
c00869f1 1625 if (check_ref && btrfs_root_refs(&root->root_item) == 0)
48475471 1626 return ERR_PTR(-ENOENT);
5eda7b5e 1627 return root;
48475471 1628 }
5eda7b5e 1629
cb517eab 1630 root = btrfs_read_fs_root(fs_info->tree_root, location);
5eda7b5e
CM
1631 if (IS_ERR(root))
1632 return root;
3394e160 1633
c00869f1 1634 if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
cb517eab 1635 ret = -ENOENT;
581bb050 1636 goto fail;
35a30d7c 1637 }
581bb050 1638
cb517eab 1639 ret = btrfs_init_fs_root(root);
ac08aedf
CM
1640 if (ret)
1641 goto fail;
3394e160 1642
381cf658
DS
1643 path = btrfs_alloc_path();
1644 if (!path) {
1645 ret = -ENOMEM;
1646 goto fail;
1647 }
1d4c08e0
DS
1648 key.objectid = BTRFS_ORPHAN_OBJECTID;
1649 key.type = BTRFS_ORPHAN_ITEM_KEY;
1650 key.offset = location->objectid;
1651
1652 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
381cf658 1653 btrfs_free_path(path);
d68fc57b
YZ
1654 if (ret < 0)
1655 goto fail;
1656 if (ret == 0)
27cdeb70 1657 set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state);
d68fc57b 1658
cb517eab 1659 ret = btrfs_insert_fs_root(fs_info, root);
0f7d52f4 1660 if (ret) {
4df27c4d
YZ
1661 if (ret == -EEXIST) {
1662 free_fs_root(root);
1663 goto again;
1664 }
1665 goto fail;
0f7d52f4 1666 }
edbd8d4e 1667 return root;
4df27c4d
YZ
1668fail:
1669 free_fs_root(root);
1670 return ERR_PTR(ret);
edbd8d4e
CM
1671}
1672
04160088
CM
1673static int btrfs_congested_fn(void *congested_data, int bdi_bits)
1674{
1675 struct btrfs_fs_info *info = (struct btrfs_fs_info *)congested_data;
1676 int ret = 0;
04160088
CM
1677 struct btrfs_device *device;
1678 struct backing_dev_info *bdi;
b7967db7 1679
1f78160c
XG
1680 rcu_read_lock();
1681 list_for_each_entry_rcu(device, &info->fs_devices->devices, dev_list) {
dfe25020
CM
1682 if (!device->bdev)
1683 continue;
efa7c9f9 1684 bdi = device->bdev->bd_bdi;
ff9ea323 1685 if (bdi_congested(bdi, bdi_bits)) {
04160088
CM
1686 ret = 1;
1687 break;
1688 }
1689 }
1f78160c 1690 rcu_read_unlock();
04160088
CM
1691 return ret;
1692}
1693
8b712842
CM
1694/*
1695 * called by the kthread helper functions to finally call the bio end_io
1696 * functions. This is where read checksum verification actually happens
1697 */
1698static void end_workqueue_fn(struct btrfs_work *work)
ce9adaa5 1699{
ce9adaa5 1700 struct bio *bio;
97eb6b69 1701 struct btrfs_end_io_wq *end_io_wq;
ce9adaa5 1702
97eb6b69 1703 end_io_wq = container_of(work, struct btrfs_end_io_wq, work);
8b712842 1704 bio = end_io_wq->bio;
ce9adaa5 1705
4e4cbee9 1706 bio->bi_status = end_io_wq->status;
8b712842
CM
1707 bio->bi_private = end_io_wq->private;
1708 bio->bi_end_io = end_io_wq->end_io;
97eb6b69 1709 kmem_cache_free(btrfs_end_io_wq_cache, end_io_wq);
4246a0b6 1710 bio_endio(bio);
44b8bd7e
CM
1711}
1712
a74a4b97
CM
1713static int cleaner_kthread(void *arg)
1714{
1715 struct btrfs_root *root = arg;
0b246afa 1716 struct btrfs_fs_info *fs_info = root->fs_info;
d0278245 1717 int again;
da288d28 1718 struct btrfs_trans_handle *trans;
a74a4b97
CM
1719
1720 do {
d0278245 1721 again = 0;
a74a4b97 1722
d0278245 1723 /* Make the cleaner go to sleep early. */
2ff7e61e 1724 if (btrfs_need_cleaner_sleep(fs_info))
d0278245
MX
1725 goto sleep;
1726
90c711ab
ZB
1727 /*
1728 * Do not do anything if we might cause open_ctree() to block
1729 * before we have finished mounting the filesystem.
1730 */
0b246afa 1731 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
90c711ab
ZB
1732 goto sleep;
1733
0b246afa 1734 if (!mutex_trylock(&fs_info->cleaner_mutex))
d0278245
MX
1735 goto sleep;
1736
dc7f370c
MX
1737 /*
1738 * Avoid the problem that we change the status of the fs
1739 * during the above check and trylock.
1740 */
2ff7e61e 1741 if (btrfs_need_cleaner_sleep(fs_info)) {
0b246afa 1742 mutex_unlock(&fs_info->cleaner_mutex);
dc7f370c 1743 goto sleep;
76dda93c 1744 }
a74a4b97 1745
0b246afa 1746 mutex_lock(&fs_info->cleaner_delayed_iput_mutex);
2ff7e61e 1747 btrfs_run_delayed_iputs(fs_info);
0b246afa 1748 mutex_unlock(&fs_info->cleaner_delayed_iput_mutex);
c2d6cb16 1749
d0278245 1750 again = btrfs_clean_one_deleted_snapshot(root);
0b246afa 1751 mutex_unlock(&fs_info->cleaner_mutex);
d0278245
MX
1752
1753 /*
05323cd1
MX
1754 * The defragger has dealt with the R/O remount and umount,
1755 * needn't do anything special here.
d0278245 1756 */
0b246afa 1757 btrfs_run_defrag_inodes(fs_info);
67c5e7d4
FM
1758
1759 /*
1760 * Acquires fs_info->delete_unused_bgs_mutex to avoid racing
1761 * with relocation (btrfs_relocate_chunk) and relocation
1762 * acquires fs_info->cleaner_mutex (btrfs_relocate_block_group)
1763 * after acquiring fs_info->delete_unused_bgs_mutex. So we
1764 * can't hold, nor need to, fs_info->cleaner_mutex when deleting
1765 * unused block groups.
1766 */
0b246afa 1767 btrfs_delete_unused_bgs(fs_info);
d0278245 1768sleep:
838fe188 1769 if (!again) {
a74a4b97 1770 set_current_state(TASK_INTERRUPTIBLE);
8929ecfa
YZ
1771 if (!kthread_should_stop())
1772 schedule();
a74a4b97
CM
1773 __set_current_state(TASK_RUNNING);
1774 }
1775 } while (!kthread_should_stop());
da288d28
FM
1776
1777 /*
1778 * Transaction kthread is stopped before us and wakes us up.
1779 * However we might have started a new transaction and COWed some
1780 * tree blocks when deleting unused block groups for example. So
1781 * make sure we commit the transaction we started to have a clean
1782 * shutdown when evicting the btree inode - if it has dirty pages
1783 * when we do the final iput() on it, eviction will trigger a
1784 * writeback for it which will fail with null pointer dereferences
1785 * since work queues and other resources were already released and
1786 * destroyed by the time the iput/eviction/writeback is made.
1787 */
1788 trans = btrfs_attach_transaction(root);
1789 if (IS_ERR(trans)) {
1790 if (PTR_ERR(trans) != -ENOENT)
0b246afa 1791 btrfs_err(fs_info,
da288d28
FM
1792 "cleaner transaction attach returned %ld",
1793 PTR_ERR(trans));
1794 } else {
1795 int ret;
1796
3a45bb20 1797 ret = btrfs_commit_transaction(trans);
da288d28 1798 if (ret)
0b246afa 1799 btrfs_err(fs_info,
da288d28
FM
1800 "cleaner open transaction commit returned %d",
1801 ret);
1802 }
1803
a74a4b97
CM
1804 return 0;
1805}
1806
1807static int transaction_kthread(void *arg)
1808{
1809 struct btrfs_root *root = arg;
0b246afa 1810 struct btrfs_fs_info *fs_info = root->fs_info;
a74a4b97
CM
1811 struct btrfs_trans_handle *trans;
1812 struct btrfs_transaction *cur;
8929ecfa 1813 u64 transid;
a74a4b97
CM
1814 unsigned long now;
1815 unsigned long delay;
914b2007 1816 bool cannot_commit;
a74a4b97
CM
1817
1818 do {
914b2007 1819 cannot_commit = false;
0b246afa
JM
1820 delay = HZ * fs_info->commit_interval;
1821 mutex_lock(&fs_info->transaction_kthread_mutex);
a74a4b97 1822
0b246afa
JM
1823 spin_lock(&fs_info->trans_lock);
1824 cur = fs_info->running_transaction;
a74a4b97 1825 if (!cur) {
0b246afa 1826 spin_unlock(&fs_info->trans_lock);
a74a4b97
CM
1827 goto sleep;
1828 }
31153d81 1829
a74a4b97 1830 now = get_seconds();
4a9d8bde 1831 if (cur->state < TRANS_STATE_BLOCKED &&
8b87dc17 1832 (now < cur->start_time ||
0b246afa
JM
1833 now - cur->start_time < fs_info->commit_interval)) {
1834 spin_unlock(&fs_info->trans_lock);
a74a4b97
CM
1835 delay = HZ * 5;
1836 goto sleep;
1837 }
8929ecfa 1838 transid = cur->transid;
0b246afa 1839 spin_unlock(&fs_info->trans_lock);
56bec294 1840
79787eaa 1841 /* If the file system is aborted, this will always fail. */
354aa0fb 1842 trans = btrfs_attach_transaction(root);
914b2007 1843 if (IS_ERR(trans)) {
354aa0fb
MX
1844 if (PTR_ERR(trans) != -ENOENT)
1845 cannot_commit = true;
79787eaa 1846 goto sleep;
914b2007 1847 }
8929ecfa 1848 if (transid == trans->transid) {
3a45bb20 1849 btrfs_commit_transaction(trans);
8929ecfa 1850 } else {
3a45bb20 1851 btrfs_end_transaction(trans);
8929ecfa 1852 }
a74a4b97 1853sleep:
0b246afa
JM
1854 wake_up_process(fs_info->cleaner_kthread);
1855 mutex_unlock(&fs_info->transaction_kthread_mutex);
a74a4b97 1856
4e121c06 1857 if (unlikely(test_bit(BTRFS_FS_STATE_ERROR,
0b246afa 1858 &fs_info->fs_state)))
2ff7e61e 1859 btrfs_cleanup_transaction(fs_info);
ce63f891 1860 if (!kthread_should_stop() &&
0b246afa 1861 (!btrfs_transaction_blocked(fs_info) ||
ce63f891 1862 cannot_commit))
bc5511d0 1863 schedule_timeout_interruptible(delay);
a74a4b97
CM
1864 } while (!kthread_should_stop());
1865 return 0;
1866}
1867
af31f5e5
CM
1868/*
1869 * this will find the highest generation in the array of
1870 * root backups. The index of the highest array is returned,
1871 * or -1 if we can't find anything.
1872 *
1873 * We check to make sure the array is valid by comparing the
1874 * generation of the latest root in the array with the generation
1875 * in the super block. If they don't match we pitch it.
1876 */
1877static int find_newest_super_backup(struct btrfs_fs_info *info, u64 newest_gen)
1878{
1879 u64 cur;
1880 int newest_index = -1;
1881 struct btrfs_root_backup *root_backup;
1882 int i;
1883
1884 for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
1885 root_backup = info->super_copy->super_roots + i;
1886 cur = btrfs_backup_tree_root_gen(root_backup);
1887 if (cur == newest_gen)
1888 newest_index = i;
1889 }
1890
1891 /* check to see if we actually wrapped around */
1892 if (newest_index == BTRFS_NUM_BACKUP_ROOTS - 1) {
1893 root_backup = info->super_copy->super_roots;
1894 cur = btrfs_backup_tree_root_gen(root_backup);
1895 if (cur == newest_gen)
1896 newest_index = 0;
1897 }
1898 return newest_index;
1899}
1900
1901
1902/*
1903 * find the oldest backup so we know where to store new entries
1904 * in the backup array. This will set the backup_root_index
1905 * field in the fs_info struct
1906 */
1907static void find_oldest_super_backup(struct btrfs_fs_info *info,
1908 u64 newest_gen)
1909{
1910 int newest_index = -1;
1911
1912 newest_index = find_newest_super_backup(info, newest_gen);
1913 /* if there was garbage in there, just move along */
1914 if (newest_index == -1) {
1915 info->backup_root_index = 0;
1916 } else {
1917 info->backup_root_index = (newest_index + 1) % BTRFS_NUM_BACKUP_ROOTS;
1918 }
1919}
1920
1921/*
1922 * copy all the root pointers into the super backup array.
1923 * this will bump the backup pointer by one when it is
1924 * done
1925 */
1926static void backup_super_roots(struct btrfs_fs_info *info)
1927{
1928 int next_backup;
1929 struct btrfs_root_backup *root_backup;
1930 int last_backup;
1931
1932 next_backup = info->backup_root_index;
1933 last_backup = (next_backup + BTRFS_NUM_BACKUP_ROOTS - 1) %
1934 BTRFS_NUM_BACKUP_ROOTS;
1935
1936 /*
1937 * just overwrite the last backup if we're at the same generation
1938 * this happens only at umount
1939 */
1940 root_backup = info->super_for_commit->super_roots + last_backup;
1941 if (btrfs_backup_tree_root_gen(root_backup) ==
1942 btrfs_header_generation(info->tree_root->node))
1943 next_backup = last_backup;
1944
1945 root_backup = info->super_for_commit->super_roots + next_backup;
1946
1947 /*
1948 * make sure all of our padding and empty slots get zero filled
1949 * regardless of which ones we use today
1950 */
1951 memset(root_backup, 0, sizeof(*root_backup));
1952
1953 info->backup_root_index = (next_backup + 1) % BTRFS_NUM_BACKUP_ROOTS;
1954
1955 btrfs_set_backup_tree_root(root_backup, info->tree_root->node->start);
1956 btrfs_set_backup_tree_root_gen(root_backup,
1957 btrfs_header_generation(info->tree_root->node));
1958
1959 btrfs_set_backup_tree_root_level(root_backup,
1960 btrfs_header_level(info->tree_root->node));
1961
1962 btrfs_set_backup_chunk_root(root_backup, info->chunk_root->node->start);
1963 btrfs_set_backup_chunk_root_gen(root_backup,
1964 btrfs_header_generation(info->chunk_root->node));
1965 btrfs_set_backup_chunk_root_level(root_backup,
1966 btrfs_header_level(info->chunk_root->node));
1967
1968 btrfs_set_backup_extent_root(root_backup, info->extent_root->node->start);
1969 btrfs_set_backup_extent_root_gen(root_backup,
1970 btrfs_header_generation(info->extent_root->node));
1971 btrfs_set_backup_extent_root_level(root_backup,
1972 btrfs_header_level(info->extent_root->node));
1973
7c7e82a7
CM
1974 /*
1975 * we might commit during log recovery, which happens before we set
1976 * the fs_root. Make sure it is valid before we fill it in.
1977 */
1978 if (info->fs_root && info->fs_root->node) {
1979 btrfs_set_backup_fs_root(root_backup,
1980 info->fs_root->node->start);
1981 btrfs_set_backup_fs_root_gen(root_backup,
af31f5e5 1982 btrfs_header_generation(info->fs_root->node));
7c7e82a7 1983 btrfs_set_backup_fs_root_level(root_backup,
af31f5e5 1984 btrfs_header_level(info->fs_root->node));
7c7e82a7 1985 }
af31f5e5
CM
1986
1987 btrfs_set_backup_dev_root(root_backup, info->dev_root->node->start);
1988 btrfs_set_backup_dev_root_gen(root_backup,
1989 btrfs_header_generation(info->dev_root->node));
1990 btrfs_set_backup_dev_root_level(root_backup,
1991 btrfs_header_level(info->dev_root->node));
1992
1993 btrfs_set_backup_csum_root(root_backup, info->csum_root->node->start);
1994 btrfs_set_backup_csum_root_gen(root_backup,
1995 btrfs_header_generation(info->csum_root->node));
1996 btrfs_set_backup_csum_root_level(root_backup,
1997 btrfs_header_level(info->csum_root->node));
1998
1999 btrfs_set_backup_total_bytes(root_backup,
2000 btrfs_super_total_bytes(info->super_copy));
2001 btrfs_set_backup_bytes_used(root_backup,
2002 btrfs_super_bytes_used(info->super_copy));
2003 btrfs_set_backup_num_devices(root_backup,
2004 btrfs_super_num_devices(info->super_copy));
2005
2006 /*
2007 * if we don't copy this out to the super_copy, it won't get remembered
2008 * for the next commit
2009 */
2010 memcpy(&info->super_copy->super_roots,
2011 &info->super_for_commit->super_roots,
2012 sizeof(*root_backup) * BTRFS_NUM_BACKUP_ROOTS);
2013}
2014
2015/*
2016 * this copies info out of the root backup array and back into
2017 * the in-memory super block. It is meant to help iterate through
2018 * the array, so you send it the number of backups you've already
2019 * tried and the last backup index you used.
2020 *
2021 * this returns -1 when it has tried all the backups
2022 */
2023static noinline int next_root_backup(struct btrfs_fs_info *info,
2024 struct btrfs_super_block *super,
2025 int *num_backups_tried, int *backup_index)
2026{
2027 struct btrfs_root_backup *root_backup;
2028 int newest = *backup_index;
2029
2030 if (*num_backups_tried == 0) {
2031 u64 gen = btrfs_super_generation(super);
2032
2033 newest = find_newest_super_backup(info, gen);
2034 if (newest == -1)
2035 return -1;
2036
2037 *backup_index = newest;
2038 *num_backups_tried = 1;
2039 } else if (*num_backups_tried == BTRFS_NUM_BACKUP_ROOTS) {
2040 /* we've tried all the backups, all done */
2041 return -1;
2042 } else {
2043 /* jump to the next oldest backup */
2044 newest = (*backup_index + BTRFS_NUM_BACKUP_ROOTS - 1) %
2045 BTRFS_NUM_BACKUP_ROOTS;
2046 *backup_index = newest;
2047 *num_backups_tried += 1;
2048 }
2049 root_backup = super->super_roots + newest;
2050
2051 btrfs_set_super_generation(super,
2052 btrfs_backup_tree_root_gen(root_backup));
2053 btrfs_set_super_root(super, btrfs_backup_tree_root(root_backup));
2054 btrfs_set_super_root_level(super,
2055 btrfs_backup_tree_root_level(root_backup));
2056 btrfs_set_super_bytes_used(super, btrfs_backup_bytes_used(root_backup));
2057
2058 /*
2059 * fixme: the total bytes and num_devices need to match or we should
2060 * need a fsck
2061 */
2062 btrfs_set_super_total_bytes(super, btrfs_backup_total_bytes(root_backup));
2063 btrfs_set_super_num_devices(super, btrfs_backup_num_devices(root_backup));
2064 return 0;
2065}
2066
7abadb64
LB
2067/* helper to cleanup workers */
2068static void btrfs_stop_all_workers(struct btrfs_fs_info *fs_info)
2069{
dc6e3209 2070 btrfs_destroy_workqueue(fs_info->fixup_workers);
afe3d242 2071 btrfs_destroy_workqueue(fs_info->delalloc_workers);
5cdc7ad3 2072 btrfs_destroy_workqueue(fs_info->workers);
fccb5d86 2073 btrfs_destroy_workqueue(fs_info->endio_workers);
fccb5d86 2074 btrfs_destroy_workqueue(fs_info->endio_raid56_workers);
8b110e39 2075 btrfs_destroy_workqueue(fs_info->endio_repair_workers);
d05a33ac 2076 btrfs_destroy_workqueue(fs_info->rmw_workers);
fccb5d86
QW
2077 btrfs_destroy_workqueue(fs_info->endio_write_workers);
2078 btrfs_destroy_workqueue(fs_info->endio_freespace_worker);
a8c93d4e 2079 btrfs_destroy_workqueue(fs_info->submit_workers);
5b3bc44e 2080 btrfs_destroy_workqueue(fs_info->delayed_workers);
e66f0bb1 2081 btrfs_destroy_workqueue(fs_info->caching_workers);
736cfa15 2082 btrfs_destroy_workqueue(fs_info->readahead_workers);
a44903ab 2083 btrfs_destroy_workqueue(fs_info->flush_workers);
fc97fab0 2084 btrfs_destroy_workqueue(fs_info->qgroup_rescan_workers);
a79b7d4b 2085 btrfs_destroy_workqueue(fs_info->extent_workers);
a9b9477d
FM
2086 /*
2087 * Now that all other work queues are destroyed, we can safely destroy
2088 * the queues used for metadata I/O, since tasks from those other work
2089 * queues can do metadata I/O operations.
2090 */
2091 btrfs_destroy_workqueue(fs_info->endio_meta_workers);
2092 btrfs_destroy_workqueue(fs_info->endio_meta_write_workers);
7abadb64
LB
2093}
2094
2e9f5954
R
2095static void free_root_extent_buffers(struct btrfs_root *root)
2096{
2097 if (root) {
2098 free_extent_buffer(root->node);
2099 free_extent_buffer(root->commit_root);
2100 root->node = NULL;
2101 root->commit_root = NULL;
2102 }
2103}
2104
af31f5e5
CM
2105/* helper to cleanup tree roots */
2106static void free_root_pointers(struct btrfs_fs_info *info, int chunk_root)
2107{
2e9f5954 2108 free_root_extent_buffers(info->tree_root);
655b09fe 2109
2e9f5954
R
2110 free_root_extent_buffers(info->dev_root);
2111 free_root_extent_buffers(info->extent_root);
2112 free_root_extent_buffers(info->csum_root);
2113 free_root_extent_buffers(info->quota_root);
2114 free_root_extent_buffers(info->uuid_root);
2115 if (chunk_root)
2116 free_root_extent_buffers(info->chunk_root);
70f6d82e 2117 free_root_extent_buffers(info->free_space_root);
af31f5e5
CM
2118}
2119
faa2dbf0 2120void btrfs_free_fs_roots(struct btrfs_fs_info *fs_info)
171f6537
JB
2121{
2122 int ret;
2123 struct btrfs_root *gang[8];
2124 int i;
2125
2126 while (!list_empty(&fs_info->dead_roots)) {
2127 gang[0] = list_entry(fs_info->dead_roots.next,
2128 struct btrfs_root, root_list);
2129 list_del(&gang[0]->root_list);
2130
27cdeb70 2131 if (test_bit(BTRFS_ROOT_IN_RADIX, &gang[0]->state)) {
cb517eab 2132 btrfs_drop_and_free_fs_root(fs_info, gang[0]);
171f6537
JB
2133 } else {
2134 free_extent_buffer(gang[0]->node);
2135 free_extent_buffer(gang[0]->commit_root);
b0feb9d9 2136 btrfs_put_fs_root(gang[0]);
171f6537
JB
2137 }
2138 }
2139
2140 while (1) {
2141 ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
2142 (void **)gang, 0,
2143 ARRAY_SIZE(gang));
2144 if (!ret)
2145 break;
2146 for (i = 0; i < ret; i++)
cb517eab 2147 btrfs_drop_and_free_fs_root(fs_info, gang[i]);
171f6537 2148 }
1a4319cc
LB
2149
2150 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
2151 btrfs_free_log_root_tree(NULL, fs_info);
2ff7e61e 2152 btrfs_destroy_pinned_extent(fs_info, fs_info->pinned_extents);
1a4319cc 2153 }
171f6537 2154}
af31f5e5 2155
638aa7ed
ES
2156static void btrfs_init_scrub(struct btrfs_fs_info *fs_info)
2157{
2158 mutex_init(&fs_info->scrub_lock);
2159 atomic_set(&fs_info->scrubs_running, 0);
2160 atomic_set(&fs_info->scrub_pause_req, 0);
2161 atomic_set(&fs_info->scrubs_paused, 0);
2162 atomic_set(&fs_info->scrub_cancel_req, 0);
2163 init_waitqueue_head(&fs_info->scrub_pause_wait);
2164 fs_info->scrub_workers_refcnt = 0;
2165}
2166
779a65a4
ES
2167static void btrfs_init_balance(struct btrfs_fs_info *fs_info)
2168{
2169 spin_lock_init(&fs_info->balance_lock);
2170 mutex_init(&fs_info->balance_mutex);
2171 atomic_set(&fs_info->balance_running, 0);
2172 atomic_set(&fs_info->balance_pause_req, 0);
2173 atomic_set(&fs_info->balance_cancel_req, 0);
2174 fs_info->balance_ctl = NULL;
2175 init_waitqueue_head(&fs_info->balance_wait_q);
2176}
2177
6bccf3ab 2178static void btrfs_init_btree_inode(struct btrfs_fs_info *fs_info)
f37938e0 2179{
2ff7e61e
JM
2180 struct inode *inode = fs_info->btree_inode;
2181
2182 inode->i_ino = BTRFS_BTREE_INODE_OBJECTID;
2183 set_nlink(inode, 1);
f37938e0
ES
2184 /*
2185 * we set the i_size on the btree inode to the max possible int.
2186 * the real end of the address space is determined by all of
2187 * the devices in the system
2188 */
2ff7e61e
JM
2189 inode->i_size = OFFSET_MAX;
2190 inode->i_mapping->a_ops = &btree_aops;
f37938e0 2191
2ff7e61e 2192 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
c6100a4b 2193 extent_io_tree_init(&BTRFS_I(inode)->io_tree, inode);
2ff7e61e
JM
2194 BTRFS_I(inode)->io_tree.track_uptodate = 0;
2195 extent_map_tree_init(&BTRFS_I(inode)->extent_tree);
f37938e0 2196
2ff7e61e 2197 BTRFS_I(inode)->io_tree.ops = &btree_extent_io_ops;
f37938e0 2198
2ff7e61e
JM
2199 BTRFS_I(inode)->root = fs_info->tree_root;
2200 memset(&BTRFS_I(inode)->location, 0, sizeof(struct btrfs_key));
2201 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
2202 btrfs_insert_inode_hash(inode);
f37938e0
ES
2203}
2204
ad618368
ES
2205static void btrfs_init_dev_replace_locks(struct btrfs_fs_info *fs_info)
2206{
2207 fs_info->dev_replace.lock_owner = 0;
2208 atomic_set(&fs_info->dev_replace.nesting_level, 0);
2209 mutex_init(&fs_info->dev_replace.lock_finishing_cancel_unmount);
73beece9
LB
2210 rwlock_init(&fs_info->dev_replace.lock);
2211 atomic_set(&fs_info->dev_replace.read_locks, 0);
2212 atomic_set(&fs_info->dev_replace.blocking_readers, 0);
ad618368 2213 init_waitqueue_head(&fs_info->replace_wait);
73beece9 2214 init_waitqueue_head(&fs_info->dev_replace.read_lock_wq);
ad618368
ES
2215}
2216
f9e92e40
ES
2217static void btrfs_init_qgroup(struct btrfs_fs_info *fs_info)
2218{
2219 spin_lock_init(&fs_info->qgroup_lock);
2220 mutex_init(&fs_info->qgroup_ioctl_lock);
2221 fs_info->qgroup_tree = RB_ROOT;
2222 fs_info->qgroup_op_tree = RB_ROOT;
2223 INIT_LIST_HEAD(&fs_info->dirty_qgroups);
2224 fs_info->qgroup_seq = 1;
f9e92e40 2225 fs_info->qgroup_ulist = NULL;
d2c609b8 2226 fs_info->qgroup_rescan_running = false;
f9e92e40
ES
2227 mutex_init(&fs_info->qgroup_rescan_lock);
2228}
2229
2a458198
ES
2230static int btrfs_init_workqueues(struct btrfs_fs_info *fs_info,
2231 struct btrfs_fs_devices *fs_devices)
2232{
f7b885be 2233 u32 max_active = fs_info->thread_pool_size;
6f011058 2234 unsigned int flags = WQ_MEM_RECLAIM | WQ_FREEZABLE | WQ_UNBOUND;
2a458198
ES
2235
2236 fs_info->workers =
cb001095
JM
2237 btrfs_alloc_workqueue(fs_info, "worker",
2238 flags | WQ_HIGHPRI, max_active, 16);
2a458198
ES
2239
2240 fs_info->delalloc_workers =
cb001095
JM
2241 btrfs_alloc_workqueue(fs_info, "delalloc",
2242 flags, max_active, 2);
2a458198
ES
2243
2244 fs_info->flush_workers =
cb001095
JM
2245 btrfs_alloc_workqueue(fs_info, "flush_delalloc",
2246 flags, max_active, 0);
2a458198
ES
2247
2248 fs_info->caching_workers =
cb001095 2249 btrfs_alloc_workqueue(fs_info, "cache", flags, max_active, 0);
2a458198
ES
2250
2251 /*
2252 * a higher idle thresh on the submit workers makes it much more
2253 * likely that bios will be send down in a sane order to the
2254 * devices
2255 */
2256 fs_info->submit_workers =
cb001095 2257 btrfs_alloc_workqueue(fs_info, "submit", flags,
2a458198
ES
2258 min_t(u64, fs_devices->num_devices,
2259 max_active), 64);
2260
2261 fs_info->fixup_workers =
cb001095 2262 btrfs_alloc_workqueue(fs_info, "fixup", flags, 1, 0);
2a458198
ES
2263
2264 /*
2265 * endios are largely parallel and should have a very
2266 * low idle thresh
2267 */
2268 fs_info->endio_workers =
cb001095 2269 btrfs_alloc_workqueue(fs_info, "endio", flags, max_active, 4);
2a458198 2270 fs_info->endio_meta_workers =
cb001095
JM
2271 btrfs_alloc_workqueue(fs_info, "endio-meta", flags,
2272 max_active, 4);
2a458198 2273 fs_info->endio_meta_write_workers =
cb001095
JM
2274 btrfs_alloc_workqueue(fs_info, "endio-meta-write", flags,
2275 max_active, 2);
2a458198 2276 fs_info->endio_raid56_workers =
cb001095
JM
2277 btrfs_alloc_workqueue(fs_info, "endio-raid56", flags,
2278 max_active, 4);
2a458198 2279 fs_info->endio_repair_workers =
cb001095 2280 btrfs_alloc_workqueue(fs_info, "endio-repair", flags, 1, 0);
2a458198 2281 fs_info->rmw_workers =
cb001095 2282 btrfs_alloc_workqueue(fs_info, "rmw", flags, max_active, 2);
2a458198 2283 fs_info->endio_write_workers =
cb001095
JM
2284 btrfs_alloc_workqueue(fs_info, "endio-write", flags,
2285 max_active, 2);
2a458198 2286 fs_info->endio_freespace_worker =
cb001095
JM
2287 btrfs_alloc_workqueue(fs_info, "freespace-write", flags,
2288 max_active, 0);
2a458198 2289 fs_info->delayed_workers =
cb001095
JM
2290 btrfs_alloc_workqueue(fs_info, "delayed-meta", flags,
2291 max_active, 0);
2a458198 2292 fs_info->readahead_workers =
cb001095
JM
2293 btrfs_alloc_workqueue(fs_info, "readahead", flags,
2294 max_active, 2);
2a458198 2295 fs_info->qgroup_rescan_workers =
cb001095 2296 btrfs_alloc_workqueue(fs_info, "qgroup-rescan", flags, 1, 0);
2a458198 2297 fs_info->extent_workers =
cb001095 2298 btrfs_alloc_workqueue(fs_info, "extent-refs", flags,
2a458198
ES
2299 min_t(u64, fs_devices->num_devices,
2300 max_active), 8);
2301
2302 if (!(fs_info->workers && fs_info->delalloc_workers &&
2303 fs_info->submit_workers && fs_info->flush_workers &&
2304 fs_info->endio_workers && fs_info->endio_meta_workers &&
2305 fs_info->endio_meta_write_workers &&
2306 fs_info->endio_repair_workers &&
2307 fs_info->endio_write_workers && fs_info->endio_raid56_workers &&
2308 fs_info->endio_freespace_worker && fs_info->rmw_workers &&
2309 fs_info->caching_workers && fs_info->readahead_workers &&
2310 fs_info->fixup_workers && fs_info->delayed_workers &&
2311 fs_info->extent_workers &&
2312 fs_info->qgroup_rescan_workers)) {
2313 return -ENOMEM;
2314 }
2315
2316 return 0;
2317}
2318
63443bf5
ES
2319static int btrfs_replay_log(struct btrfs_fs_info *fs_info,
2320 struct btrfs_fs_devices *fs_devices)
2321{
2322 int ret;
63443bf5
ES
2323 struct btrfs_root *log_tree_root;
2324 struct btrfs_super_block *disk_super = fs_info->super_copy;
2325 u64 bytenr = btrfs_super_log_root(disk_super);
581c1760 2326 int level = btrfs_super_log_root_level(disk_super);
63443bf5
ES
2327
2328 if (fs_devices->rw_devices == 0) {
f14d104d 2329 btrfs_warn(fs_info, "log replay required on RO media");
63443bf5
ES
2330 return -EIO;
2331 }
2332
74e4d827 2333 log_tree_root = btrfs_alloc_root(fs_info, GFP_KERNEL);
63443bf5
ES
2334 if (!log_tree_root)
2335 return -ENOMEM;
2336
da17066c 2337 __setup_root(log_tree_root, fs_info, BTRFS_TREE_LOG_OBJECTID);
63443bf5 2338
2ff7e61e 2339 log_tree_root->node = read_tree_block(fs_info, bytenr,
581c1760
QW
2340 fs_info->generation + 1,
2341 level, NULL);
64c043de 2342 if (IS_ERR(log_tree_root->node)) {
f14d104d 2343 btrfs_warn(fs_info, "failed to read log tree");
0eeff236 2344 ret = PTR_ERR(log_tree_root->node);
64c043de 2345 kfree(log_tree_root);
0eeff236 2346 return ret;
64c043de 2347 } else if (!extent_buffer_uptodate(log_tree_root->node)) {
f14d104d 2348 btrfs_err(fs_info, "failed to read log tree");
63443bf5
ES
2349 free_extent_buffer(log_tree_root->node);
2350 kfree(log_tree_root);
2351 return -EIO;
2352 }
2353 /* returns with log_tree_root freed on success */
2354 ret = btrfs_recover_log_trees(log_tree_root);
2355 if (ret) {
0b246afa
JM
2356 btrfs_handle_fs_error(fs_info, ret,
2357 "Failed to recover log tree");
63443bf5
ES
2358 free_extent_buffer(log_tree_root->node);
2359 kfree(log_tree_root);
2360 return ret;
2361 }
2362
bc98a42c 2363 if (sb_rdonly(fs_info->sb)) {
6bccf3ab 2364 ret = btrfs_commit_super(fs_info);
63443bf5
ES
2365 if (ret)
2366 return ret;
2367 }
2368
2369 return 0;
2370}
2371
6bccf3ab 2372static int btrfs_read_roots(struct btrfs_fs_info *fs_info)
4bbcaa64 2373{
6bccf3ab 2374 struct btrfs_root *tree_root = fs_info->tree_root;
a4f3d2c4 2375 struct btrfs_root *root;
4bbcaa64
ES
2376 struct btrfs_key location;
2377 int ret;
2378
6bccf3ab
JM
2379 BUG_ON(!fs_info->tree_root);
2380
4bbcaa64
ES
2381 location.objectid = BTRFS_EXTENT_TREE_OBJECTID;
2382 location.type = BTRFS_ROOT_ITEM_KEY;
2383 location.offset = 0;
2384
a4f3d2c4 2385 root = btrfs_read_tree_root(tree_root, &location);
f50f4353
LB
2386 if (IS_ERR(root)) {
2387 ret = PTR_ERR(root);
2388 goto out;
2389 }
a4f3d2c4
DS
2390 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2391 fs_info->extent_root = root;
4bbcaa64
ES
2392
2393 location.objectid = BTRFS_DEV_TREE_OBJECTID;
a4f3d2c4 2394 root = btrfs_read_tree_root(tree_root, &location);
f50f4353
LB
2395 if (IS_ERR(root)) {
2396 ret = PTR_ERR(root);
2397 goto out;
2398 }
a4f3d2c4
DS
2399 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2400 fs_info->dev_root = root;
4bbcaa64
ES
2401 btrfs_init_devices_late(fs_info);
2402
2403 location.objectid = BTRFS_CSUM_TREE_OBJECTID;
a4f3d2c4 2404 root = btrfs_read_tree_root(tree_root, &location);
f50f4353
LB
2405 if (IS_ERR(root)) {
2406 ret = PTR_ERR(root);
2407 goto out;
2408 }
a4f3d2c4
DS
2409 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2410 fs_info->csum_root = root;
4bbcaa64
ES
2411
2412 location.objectid = BTRFS_QUOTA_TREE_OBJECTID;
a4f3d2c4
DS
2413 root = btrfs_read_tree_root(tree_root, &location);
2414 if (!IS_ERR(root)) {
2415 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
afcdd129 2416 set_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
a4f3d2c4 2417 fs_info->quota_root = root;
4bbcaa64
ES
2418 }
2419
2420 location.objectid = BTRFS_UUID_TREE_OBJECTID;
a4f3d2c4
DS
2421 root = btrfs_read_tree_root(tree_root, &location);
2422 if (IS_ERR(root)) {
2423 ret = PTR_ERR(root);
4bbcaa64 2424 if (ret != -ENOENT)
f50f4353 2425 goto out;
4bbcaa64 2426 } else {
a4f3d2c4
DS
2427 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2428 fs_info->uuid_root = root;
4bbcaa64
ES
2429 }
2430
70f6d82e
OS
2431 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
2432 location.objectid = BTRFS_FREE_SPACE_TREE_OBJECTID;
2433 root = btrfs_read_tree_root(tree_root, &location);
f50f4353
LB
2434 if (IS_ERR(root)) {
2435 ret = PTR_ERR(root);
2436 goto out;
2437 }
70f6d82e
OS
2438 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2439 fs_info->free_space_root = root;
2440 }
2441
4bbcaa64 2442 return 0;
f50f4353
LB
2443out:
2444 btrfs_warn(fs_info, "failed to read root (objectid=%llu): %d",
2445 location.objectid, ret);
2446 return ret;
4bbcaa64
ES
2447}
2448
ad2b2c80
AV
2449int open_ctree(struct super_block *sb,
2450 struct btrfs_fs_devices *fs_devices,
2451 char *options)
2e635a27 2452{
db94535d
CM
2453 u32 sectorsize;
2454 u32 nodesize;
87ee04eb 2455 u32 stripesize;
84234f3a 2456 u64 generation;
f2b636e8 2457 u64 features;
3de4586c 2458 struct btrfs_key location;
a061fc8d 2459 struct buffer_head *bh;
4d34b278 2460 struct btrfs_super_block *disk_super;
815745cf 2461 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
f84a8bd6 2462 struct btrfs_root *tree_root;
4d34b278 2463 struct btrfs_root *chunk_root;
eb60ceac 2464 int ret;
e58ca020 2465 int err = -EINVAL;
af31f5e5
CM
2466 int num_backups_tried = 0;
2467 int backup_index = 0;
6675df31 2468 int clear_free_space_tree = 0;
581c1760 2469 int level;
4543df7e 2470
74e4d827
DS
2471 tree_root = fs_info->tree_root = btrfs_alloc_root(fs_info, GFP_KERNEL);
2472 chunk_root = fs_info->chunk_root = btrfs_alloc_root(fs_info, GFP_KERNEL);
cb517eab 2473 if (!tree_root || !chunk_root) {
39279cc3
CM
2474 err = -ENOMEM;
2475 goto fail;
2476 }
76dda93c
YZ
2477
2478 ret = init_srcu_struct(&fs_info->subvol_srcu);
2479 if (ret) {
2480 err = ret;
2481 goto fail;
2482 }
2483
908c7f19 2484 ret = percpu_counter_init(&fs_info->dirty_metadata_bytes, 0, GFP_KERNEL);
e2d84521
MX
2485 if (ret) {
2486 err = ret;
9e11ceee 2487 goto fail_srcu;
e2d84521 2488 }
09cbfeaf 2489 fs_info->dirty_metadata_batch = PAGE_SIZE *
e2d84521
MX
2490 (1 + ilog2(nr_cpu_ids));
2491
908c7f19 2492 ret = percpu_counter_init(&fs_info->delalloc_bytes, 0, GFP_KERNEL);
963d678b
MX
2493 if (ret) {
2494 err = ret;
2495 goto fail_dirty_metadata_bytes;
2496 }
2497
908c7f19 2498 ret = percpu_counter_init(&fs_info->bio_counter, 0, GFP_KERNEL);
c404e0dc
MX
2499 if (ret) {
2500 err = ret;
2501 goto fail_delalloc_bytes;
2502 }
2503
76dda93c 2504 INIT_RADIX_TREE(&fs_info->fs_roots_radix, GFP_ATOMIC);
f28491e0 2505 INIT_RADIX_TREE(&fs_info->buffer_radix, GFP_ATOMIC);
8fd17795 2506 INIT_LIST_HEAD(&fs_info->trans_list);
facda1e7 2507 INIT_LIST_HEAD(&fs_info->dead_roots);
24bbcf04 2508 INIT_LIST_HEAD(&fs_info->delayed_iputs);
eb73c1b7 2509 INIT_LIST_HEAD(&fs_info->delalloc_roots);
11833d66 2510 INIT_LIST_HEAD(&fs_info->caching_block_groups);
75cb379d
JM
2511 INIT_LIST_HEAD(&fs_info->pending_raid_kobjs);
2512 spin_lock_init(&fs_info->pending_raid_kobjs_lock);
eb73c1b7 2513 spin_lock_init(&fs_info->delalloc_root_lock);
a4abeea4 2514 spin_lock_init(&fs_info->trans_lock);
76dda93c 2515 spin_lock_init(&fs_info->fs_roots_radix_lock);
24bbcf04 2516 spin_lock_init(&fs_info->delayed_iput_lock);
4cb5300b 2517 spin_lock_init(&fs_info->defrag_inodes_lock);
f29021b2 2518 spin_lock_init(&fs_info->tree_mod_seq_lock);
ceda0864 2519 spin_lock_init(&fs_info->super_lock);
fcebe456 2520 spin_lock_init(&fs_info->qgroup_op_lock);
f28491e0 2521 spin_lock_init(&fs_info->buffer_lock);
47ab2a6c 2522 spin_lock_init(&fs_info->unused_bgs_lock);
f29021b2 2523 rwlock_init(&fs_info->tree_mod_log_lock);
d7c15171 2524 mutex_init(&fs_info->unused_bg_unpin_mutex);
67c5e7d4 2525 mutex_init(&fs_info->delete_unused_bgs_mutex);
7585717f 2526 mutex_init(&fs_info->reloc_mutex);
573bfb72 2527 mutex_init(&fs_info->delalloc_root_mutex);
c2d6cb16 2528 mutex_init(&fs_info->cleaner_delayed_iput_mutex);
de98ced9 2529 seqlock_init(&fs_info->profiles_lock);
19c00ddc 2530
0b86a832 2531 INIT_LIST_HEAD(&fs_info->dirty_cowonly_roots);
6324fbf3 2532 INIT_LIST_HEAD(&fs_info->space_info);
f29021b2 2533 INIT_LIST_HEAD(&fs_info->tree_mod_seq_list);
47ab2a6c 2534 INIT_LIST_HEAD(&fs_info->unused_bgs);
0b86a832 2535 btrfs_mapping_init(&fs_info->mapping_tree);
66d8f3dd
MX
2536 btrfs_init_block_rsv(&fs_info->global_block_rsv,
2537 BTRFS_BLOCK_RSV_GLOBAL);
66d8f3dd
MX
2538 btrfs_init_block_rsv(&fs_info->trans_block_rsv, BTRFS_BLOCK_RSV_TRANS);
2539 btrfs_init_block_rsv(&fs_info->chunk_block_rsv, BTRFS_BLOCK_RSV_CHUNK);
2540 btrfs_init_block_rsv(&fs_info->empty_block_rsv, BTRFS_BLOCK_RSV_EMPTY);
2541 btrfs_init_block_rsv(&fs_info->delayed_block_rsv,
2542 BTRFS_BLOCK_RSV_DELOPS);
771ed689 2543 atomic_set(&fs_info->async_delalloc_pages, 0);
4cb5300b 2544 atomic_set(&fs_info->defrag_running, 0);
fcebe456 2545 atomic_set(&fs_info->qgroup_op_seq, 0);
2fefd558 2546 atomic_set(&fs_info->reada_works_cnt, 0);
fc36ed7e 2547 atomic64_set(&fs_info->tree_mod_seq, 0);
e20d96d6 2548 fs_info->sb = sb;
95ac567a 2549 fs_info->max_inline = BTRFS_DEFAULT_MAX_INLINE;
9ed74f2d 2550 fs_info->metadata_ratio = 0;
4cb5300b 2551 fs_info->defrag_inodes = RB_ROOT;
a5ed45f8 2552 atomic64_set(&fs_info->free_chunk_space, 0);
f29021b2 2553 fs_info->tree_mod_log = RB_ROOT;
8b87dc17 2554 fs_info->commit_interval = BTRFS_DEFAULT_COMMIT_INTERVAL;
f8c269d7 2555 fs_info->avg_delayed_ref_runtime = NSEC_PER_SEC >> 6; /* div by 64 */
90519d66 2556 /* readahead state */
d0164adc 2557 INIT_RADIX_TREE(&fs_info->reada_tree, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
90519d66 2558 spin_lock_init(&fs_info->reada_lock);
fd708b81 2559 btrfs_init_ref_verify(fs_info);
c8b97818 2560
b34b086c
CM
2561 fs_info->thread_pool_size = min_t(unsigned long,
2562 num_online_cpus() + 2, 8);
0afbaf8c 2563
199c2a9c
MX
2564 INIT_LIST_HEAD(&fs_info->ordered_roots);
2565 spin_lock_init(&fs_info->ordered_root_lock);
69fe2d75
JB
2566
2567 fs_info->btree_inode = new_inode(sb);
2568 if (!fs_info->btree_inode) {
2569 err = -ENOMEM;
2570 goto fail_bio_counter;
2571 }
2572 mapping_set_gfp_mask(fs_info->btree_inode->i_mapping, GFP_NOFS);
2573
16cdcec7 2574 fs_info->delayed_root = kmalloc(sizeof(struct btrfs_delayed_root),
74e4d827 2575 GFP_KERNEL);
16cdcec7
MX
2576 if (!fs_info->delayed_root) {
2577 err = -ENOMEM;
2578 goto fail_iput;
2579 }
2580 btrfs_init_delayed_root(fs_info->delayed_root);
3eaa2885 2581
638aa7ed 2582 btrfs_init_scrub(fs_info);
21adbd5c
SB
2583#ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
2584 fs_info->check_integrity_print_mask = 0;
2585#endif
779a65a4 2586 btrfs_init_balance(fs_info);
21c7e756 2587 btrfs_init_async_reclaim_work(&fs_info->async_reclaim_work);
a2de733c 2588
9f6d2510
DS
2589 sb->s_blocksize = BTRFS_BDEV_BLOCKSIZE;
2590 sb->s_blocksize_bits = blksize_bits(BTRFS_BDEV_BLOCKSIZE);
a061fc8d 2591
6bccf3ab 2592 btrfs_init_btree_inode(fs_info);
76dda93c 2593
0f9dd46c 2594 spin_lock_init(&fs_info->block_group_cache_lock);
6bef4d31 2595 fs_info->block_group_cache_tree = RB_ROOT;
a1897fdd 2596 fs_info->first_logical_byte = (u64)-1;
0f9dd46c 2597
c6100a4b
JB
2598 extent_io_tree_init(&fs_info->freed_extents[0], NULL);
2599 extent_io_tree_init(&fs_info->freed_extents[1], NULL);
11833d66 2600 fs_info->pinned_extents = &fs_info->freed_extents[0];
afcdd129 2601 set_bit(BTRFS_FS_BARRIER, &fs_info->flags);
39279cc3 2602
5a3f23d5 2603 mutex_init(&fs_info->ordered_operations_mutex);
e02119d5 2604 mutex_init(&fs_info->tree_log_mutex);
925baedd 2605 mutex_init(&fs_info->chunk_mutex);
a74a4b97
CM
2606 mutex_init(&fs_info->transaction_kthread_mutex);
2607 mutex_init(&fs_info->cleaner_mutex);
7d9eb12c 2608 mutex_init(&fs_info->volume_mutex);
1bbc621e 2609 mutex_init(&fs_info->ro_block_group_mutex);
9e351cc8 2610 init_rwsem(&fs_info->commit_root_sem);
c71bf099 2611 init_rwsem(&fs_info->cleanup_work_sem);
76dda93c 2612 init_rwsem(&fs_info->subvol_sem);
803b2f54 2613 sema_init(&fs_info->uuid_tree_rescan_sem, 1);
fa9c0d79 2614
ad618368 2615 btrfs_init_dev_replace_locks(fs_info);
f9e92e40 2616 btrfs_init_qgroup(fs_info);
416ac51d 2617
fa9c0d79
CM
2618 btrfs_init_free_cluster(&fs_info->meta_alloc_cluster);
2619 btrfs_init_free_cluster(&fs_info->data_alloc_cluster);
2620
e6dcd2dc 2621 init_waitqueue_head(&fs_info->transaction_throttle);
f9295749 2622 init_waitqueue_head(&fs_info->transaction_wait);
bb9c12c9 2623 init_waitqueue_head(&fs_info->transaction_blocked_wait);
4854ddd0 2624 init_waitqueue_head(&fs_info->async_submit_wait);
3768f368 2625
04216820
FM
2626 INIT_LIST_HEAD(&fs_info->pinned_chunks);
2627
da17066c
JM
2628 /* Usable values until the real ones are cached from the superblock */
2629 fs_info->nodesize = 4096;
2630 fs_info->sectorsize = 4096;
2631 fs_info->stripesize = 4096;
2632
53b381b3
DW
2633 ret = btrfs_alloc_stripe_hash_table(fs_info);
2634 if (ret) {
83c8266a 2635 err = ret;
53b381b3
DW
2636 goto fail_alloc;
2637 }
2638
da17066c 2639 __setup_root(tree_root, fs_info, BTRFS_ROOT_TREE_OBJECTID);
7eccb903 2640
3c4bb26b 2641 invalidate_bdev(fs_devices->latest_bdev);
1104a885
DS
2642
2643 /*
2644 * Read super block and check the signature bytes only
2645 */
a512bbf8 2646 bh = btrfs_read_dev_super(fs_devices->latest_bdev);
92fc03fb
AJ
2647 if (IS_ERR(bh)) {
2648 err = PTR_ERR(bh);
16cdcec7 2649 goto fail_alloc;
20b45077 2650 }
39279cc3 2651
1104a885
DS
2652 /*
2653 * We want to check superblock checksum, the type is stored inside.
2654 * Pass the whole disk block of size BTRFS_SUPER_INFO_SIZE (4k).
2655 */
ab8d0fc4 2656 if (btrfs_check_super_csum(fs_info, bh->b_data)) {
05135f59 2657 btrfs_err(fs_info, "superblock checksum mismatch");
1104a885 2658 err = -EINVAL;
b2acdddf 2659 brelse(bh);
1104a885
DS
2660 goto fail_alloc;
2661 }
2662
2663 /*
2664 * super_copy is zeroed at allocation time and we never touch the
2665 * following bytes up to INFO_SIZE, the checksum is calculated from
2666 * the whole block of INFO_SIZE
2667 */
6c41761f
DS
2668 memcpy(fs_info->super_copy, bh->b_data, sizeof(*fs_info->super_copy));
2669 memcpy(fs_info->super_for_commit, fs_info->super_copy,
2670 sizeof(*fs_info->super_for_commit));
a061fc8d 2671 brelse(bh);
5f39d397 2672
6c41761f 2673 memcpy(fs_info->fsid, fs_info->super_copy->fsid, BTRFS_FSID_SIZE);
0b86a832 2674
3d3a126a 2675 ret = btrfs_check_super_valid(fs_info);
1104a885 2676 if (ret) {
05135f59 2677 btrfs_err(fs_info, "superblock contains fatal errors");
1104a885
DS
2678 err = -EINVAL;
2679 goto fail_alloc;
2680 }
2681
6c41761f 2682 disk_super = fs_info->super_copy;
0f7d52f4 2683 if (!btrfs_super_root(disk_super))
16cdcec7 2684 goto fail_alloc;
0f7d52f4 2685
acce952b 2686 /* check FS state, whether FS is broken. */
87533c47
MX
2687 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_ERROR)
2688 set_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state);
acce952b 2689
af31f5e5
CM
2690 /*
2691 * run through our array of backup supers and setup
2692 * our ring pointer to the oldest one
2693 */
2694 generation = btrfs_super_generation(disk_super);
2695 find_oldest_super_backup(fs_info, generation);
2696
75e7cb7f
LB
2697 /*
2698 * In the long term, we'll store the compression type in the super
2699 * block, and it'll be used for per file compression control.
2700 */
2701 fs_info->compress_type = BTRFS_COMPRESS_ZLIB;
2702
2ff7e61e 2703 ret = btrfs_parse_options(fs_info, options, sb->s_flags);
2b82032c
YZ
2704 if (ret) {
2705 err = ret;
16cdcec7 2706 goto fail_alloc;
2b82032c 2707 }
dfe25020 2708
f2b636e8
JB
2709 features = btrfs_super_incompat_flags(disk_super) &
2710 ~BTRFS_FEATURE_INCOMPAT_SUPP;
2711 if (features) {
05135f59
DS
2712 btrfs_err(fs_info,
2713 "cannot mount because of unsupported optional features (%llx)",
2714 features);
f2b636e8 2715 err = -EINVAL;
16cdcec7 2716 goto fail_alloc;
f2b636e8
JB
2717 }
2718
5d4f98a2 2719 features = btrfs_super_incompat_flags(disk_super);
a6fa6fae 2720 features |= BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF;
0b246afa 2721 if (fs_info->compress_type == BTRFS_COMPRESS_LZO)
a6fa6fae 2722 features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_LZO;
5c1aab1d
NT
2723 else if (fs_info->compress_type == BTRFS_COMPRESS_ZSTD)
2724 features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_ZSTD;
727011e0 2725
3173a18f 2726 if (features & BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA)
05135f59 2727 btrfs_info(fs_info, "has skinny extents");
3173a18f 2728
727011e0
CM
2729 /*
2730 * flag our filesystem as having big metadata blocks if
2731 * they are bigger than the page size
2732 */
09cbfeaf 2733 if (btrfs_super_nodesize(disk_super) > PAGE_SIZE) {
727011e0 2734 if (!(features & BTRFS_FEATURE_INCOMPAT_BIG_METADATA))
05135f59
DS
2735 btrfs_info(fs_info,
2736 "flagging fs with big metadata feature");
727011e0
CM
2737 features |= BTRFS_FEATURE_INCOMPAT_BIG_METADATA;
2738 }
2739
bc3f116f 2740 nodesize = btrfs_super_nodesize(disk_super);
bc3f116f 2741 sectorsize = btrfs_super_sectorsize(disk_super);
b7f67055 2742 stripesize = sectorsize;
707e8a07 2743 fs_info->dirty_metadata_batch = nodesize * (1 + ilog2(nr_cpu_ids));
963d678b 2744 fs_info->delalloc_batch = sectorsize * 512 * (1 + ilog2(nr_cpu_ids));
bc3f116f 2745
da17066c
JM
2746 /* Cache block sizes */
2747 fs_info->nodesize = nodesize;
2748 fs_info->sectorsize = sectorsize;
2749 fs_info->stripesize = stripesize;
2750
bc3f116f
CM
2751 /*
2752 * mixed block groups end up with duplicate but slightly offset
2753 * extent buffers for the same range. It leads to corruptions
2754 */
2755 if ((features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) &&
707e8a07 2756 (sectorsize != nodesize)) {
05135f59
DS
2757 btrfs_err(fs_info,
2758"unequal nodesize/sectorsize (%u != %u) are not allowed for mixed block groups",
2759 nodesize, sectorsize);
bc3f116f
CM
2760 goto fail_alloc;
2761 }
2762
ceda0864
MX
2763 /*
2764 * Needn't use the lock because there is no other task which will
2765 * update the flag.
2766 */
a6fa6fae 2767 btrfs_set_super_incompat_flags(disk_super, features);
5d4f98a2 2768
f2b636e8
JB
2769 features = btrfs_super_compat_ro_flags(disk_super) &
2770 ~BTRFS_FEATURE_COMPAT_RO_SUPP;
bc98a42c 2771 if (!sb_rdonly(sb) && features) {
05135f59
DS
2772 btrfs_err(fs_info,
2773 "cannot mount read-write because of unsupported optional features (%llx)",
c1c9ff7c 2774 features);
f2b636e8 2775 err = -EINVAL;
16cdcec7 2776 goto fail_alloc;
f2b636e8 2777 }
61d92c32 2778
2a458198
ES
2779 ret = btrfs_init_workqueues(fs_info, fs_devices);
2780 if (ret) {
2781 err = ret;
0dc3b84a
JB
2782 goto fail_sb_buffer;
2783 }
4543df7e 2784
9e11ceee
JK
2785 sb->s_bdi->congested_fn = btrfs_congested_fn;
2786 sb->s_bdi->congested_data = fs_info;
2787 sb->s_bdi->capabilities |= BDI_CAP_CGROUP_WRITEBACK;
d4417e22 2788 sb->s_bdi->ra_pages = VM_MAX_READAHEAD * SZ_1K / PAGE_SIZE;
9e11ceee
JK
2789 sb->s_bdi->ra_pages *= btrfs_super_num_devices(disk_super);
2790 sb->s_bdi->ra_pages = max(sb->s_bdi->ra_pages, SZ_4M / PAGE_SIZE);
4575c9cc 2791
a061fc8d
CM
2792 sb->s_blocksize = sectorsize;
2793 sb->s_blocksize_bits = blksize_bits(sectorsize);
ee87cf5e 2794 memcpy(&sb->s_uuid, fs_info->fsid, BTRFS_FSID_SIZE);
db94535d 2795
925baedd 2796 mutex_lock(&fs_info->chunk_mutex);
6bccf3ab 2797 ret = btrfs_read_sys_array(fs_info);
925baedd 2798 mutex_unlock(&fs_info->chunk_mutex);
84eed90f 2799 if (ret) {
05135f59 2800 btrfs_err(fs_info, "failed to read the system array: %d", ret);
5d4f98a2 2801 goto fail_sb_buffer;
84eed90f 2802 }
0b86a832 2803
84234f3a 2804 generation = btrfs_super_chunk_root_generation(disk_super);
581c1760 2805 level = btrfs_super_chunk_root_level(disk_super);
0b86a832 2806
da17066c 2807 __setup_root(chunk_root, fs_info, BTRFS_CHUNK_TREE_OBJECTID);
0b86a832 2808
2ff7e61e 2809 chunk_root->node = read_tree_block(fs_info,
0b86a832 2810 btrfs_super_chunk_root(disk_super),
581c1760 2811 generation, level, NULL);
64c043de
LB
2812 if (IS_ERR(chunk_root->node) ||
2813 !extent_buffer_uptodate(chunk_root->node)) {
05135f59 2814 btrfs_err(fs_info, "failed to read chunk root");
e5fffbac 2815 if (!IS_ERR(chunk_root->node))
2816 free_extent_buffer(chunk_root->node);
95ab1f64 2817 chunk_root->node = NULL;
af31f5e5 2818 goto fail_tree_roots;
83121942 2819 }
5d4f98a2
YZ
2820 btrfs_set_root_node(&chunk_root->root_item, chunk_root->node);
2821 chunk_root->commit_root = btrfs_root_node(chunk_root);
0b86a832 2822
e17cade2 2823 read_extent_buffer(chunk_root->node, fs_info->chunk_tree_uuid,
b308bc2f 2824 btrfs_header_chunk_tree_uuid(chunk_root->node), BTRFS_UUID_SIZE);
e17cade2 2825
5b4aacef 2826 ret = btrfs_read_chunk_tree(fs_info);
2b82032c 2827 if (ret) {
05135f59 2828 btrfs_err(fs_info, "failed to read chunk tree: %d", ret);
af31f5e5 2829 goto fail_tree_roots;
2b82032c 2830 }
0b86a832 2831
8dabb742 2832 /*
9b99b115
AJ
2833 * Keep the devid that is marked to be the target device for the
2834 * device replace procedure
8dabb742 2835 */
9b99b115 2836 btrfs_free_extra_devids(fs_devices, 0);
dfe25020 2837
a6b0d5c8 2838 if (!fs_devices->latest_bdev) {
05135f59 2839 btrfs_err(fs_info, "failed to read devices");
a6b0d5c8
CM
2840 goto fail_tree_roots;
2841 }
2842
af31f5e5 2843retry_root_backup:
84234f3a 2844 generation = btrfs_super_generation(disk_super);
581c1760 2845 level = btrfs_super_root_level(disk_super);
0b86a832 2846
2ff7e61e 2847 tree_root->node = read_tree_block(fs_info,
db94535d 2848 btrfs_super_root(disk_super),
581c1760 2849 generation, level, NULL);
64c043de
LB
2850 if (IS_ERR(tree_root->node) ||
2851 !extent_buffer_uptodate(tree_root->node)) {
05135f59 2852 btrfs_warn(fs_info, "failed to read tree root");
e5fffbac 2853 if (!IS_ERR(tree_root->node))
2854 free_extent_buffer(tree_root->node);
95ab1f64 2855 tree_root->node = NULL;
af31f5e5 2856 goto recovery_tree_root;
83121942 2857 }
af31f5e5 2858
5d4f98a2
YZ
2859 btrfs_set_root_node(&tree_root->root_item, tree_root->node);
2860 tree_root->commit_root = btrfs_root_node(tree_root);
69e9c6c6 2861 btrfs_set_root_refs(&tree_root->root_item, 1);
db94535d 2862
f32e48e9
CR
2863 mutex_lock(&tree_root->objectid_mutex);
2864 ret = btrfs_find_highest_objectid(tree_root,
2865 &tree_root->highest_objectid);
2866 if (ret) {
2867 mutex_unlock(&tree_root->objectid_mutex);
2868 goto recovery_tree_root;
2869 }
2870
2871 ASSERT(tree_root->highest_objectid <= BTRFS_LAST_FREE_OBJECTID);
2872
2873 mutex_unlock(&tree_root->objectid_mutex);
2874
6bccf3ab 2875 ret = btrfs_read_roots(fs_info);
4bbcaa64 2876 if (ret)
af31f5e5 2877 goto recovery_tree_root;
f7a81ea4 2878
8929ecfa
YZ
2879 fs_info->generation = generation;
2880 fs_info->last_trans_committed = generation;
8929ecfa 2881
68310a5e
ID
2882 ret = btrfs_recover_balance(fs_info);
2883 if (ret) {
05135f59 2884 btrfs_err(fs_info, "failed to recover balance: %d", ret);
68310a5e
ID
2885 goto fail_block_groups;
2886 }
2887
733f4fbb
SB
2888 ret = btrfs_init_dev_stats(fs_info);
2889 if (ret) {
05135f59 2890 btrfs_err(fs_info, "failed to init dev_stats: %d", ret);
733f4fbb
SB
2891 goto fail_block_groups;
2892 }
2893
8dabb742
SB
2894 ret = btrfs_init_dev_replace(fs_info);
2895 if (ret) {
05135f59 2896 btrfs_err(fs_info, "failed to init dev_replace: %d", ret);
8dabb742
SB
2897 goto fail_block_groups;
2898 }
2899
9b99b115 2900 btrfs_free_extra_devids(fs_devices, 1);
8dabb742 2901
b7c35e81
AJ
2902 ret = btrfs_sysfs_add_fsid(fs_devices, NULL);
2903 if (ret) {
05135f59
DS
2904 btrfs_err(fs_info, "failed to init sysfs fsid interface: %d",
2905 ret);
b7c35e81
AJ
2906 goto fail_block_groups;
2907 }
2908
2909 ret = btrfs_sysfs_add_device(fs_devices);
2910 if (ret) {
05135f59
DS
2911 btrfs_err(fs_info, "failed to init sysfs device interface: %d",
2912 ret);
b7c35e81
AJ
2913 goto fail_fsdev_sysfs;
2914 }
2915
96f3136e 2916 ret = btrfs_sysfs_add_mounted(fs_info);
c59021f8 2917 if (ret) {
05135f59 2918 btrfs_err(fs_info, "failed to init sysfs interface: %d", ret);
b7c35e81 2919 goto fail_fsdev_sysfs;
c59021f8 2920 }
2921
c59021f8 2922 ret = btrfs_init_space_info(fs_info);
2923 if (ret) {
05135f59 2924 btrfs_err(fs_info, "failed to initialize space info: %d", ret);
2365dd3c 2925 goto fail_sysfs;
c59021f8 2926 }
2927
5b4aacef 2928 ret = btrfs_read_block_groups(fs_info);
1b1d1f66 2929 if (ret) {
05135f59 2930 btrfs_err(fs_info, "failed to read block groups: %d", ret);
2365dd3c 2931 goto fail_sysfs;
1b1d1f66 2932 }
4330e183 2933
6528b99d 2934 if (!sb_rdonly(sb) && !btrfs_check_rw_degradable(fs_info, NULL)) {
05135f59 2935 btrfs_warn(fs_info,
4330e183 2936 "writeable mount is not allowed due to too many missing devices");
2365dd3c 2937 goto fail_sysfs;
292fd7fc 2938 }
9078a3e1 2939
a74a4b97
CM
2940 fs_info->cleaner_kthread = kthread_run(cleaner_kthread, tree_root,
2941 "btrfs-cleaner");
57506d50 2942 if (IS_ERR(fs_info->cleaner_kthread))
2365dd3c 2943 goto fail_sysfs;
a74a4b97
CM
2944
2945 fs_info->transaction_kthread = kthread_run(transaction_kthread,
2946 tree_root,
2947 "btrfs-transaction");
57506d50 2948 if (IS_ERR(fs_info->transaction_kthread))
3f157a2f 2949 goto fail_cleaner;
a74a4b97 2950
583b7231 2951 if (!btrfs_test_opt(fs_info, NOSSD) &&
c289811c 2952 !fs_info->fs_devices->rotating) {
583b7231 2953 btrfs_set_and_info(fs_info, SSD, "enabling ssd optimizations");
c289811c
CM
2954 }
2955
572d9ab7 2956 /*
01327610 2957 * Mount does not set all options immediately, we can do it now and do
572d9ab7
DS
2958 * not have to wait for transaction commit
2959 */
2960 btrfs_apply_pending_changes(fs_info);
3818aea2 2961
21adbd5c 2962#ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
0b246afa 2963 if (btrfs_test_opt(fs_info, CHECK_INTEGRITY)) {
2ff7e61e 2964 ret = btrfsic_mount(fs_info, fs_devices,
0b246afa 2965 btrfs_test_opt(fs_info,
21adbd5c
SB
2966 CHECK_INTEGRITY_INCLUDING_EXTENT_DATA) ?
2967 1 : 0,
2968 fs_info->check_integrity_print_mask);
2969 if (ret)
05135f59
DS
2970 btrfs_warn(fs_info,
2971 "failed to initialize integrity check module: %d",
2972 ret);
21adbd5c
SB
2973 }
2974#endif
bcef60f2
AJ
2975 ret = btrfs_read_qgroup_config(fs_info);
2976 if (ret)
2977 goto fail_trans_kthread;
21adbd5c 2978
fd708b81
JB
2979 if (btrfs_build_ref_tree(fs_info))
2980 btrfs_err(fs_info, "couldn't build ref tree");
2981
96da0919
QW
2982 /* do not make disk changes in broken FS or nologreplay is given */
2983 if (btrfs_super_log_root(disk_super) != 0 &&
0b246afa 2984 !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
63443bf5 2985 ret = btrfs_replay_log(fs_info, fs_devices);
79787eaa 2986 if (ret) {
63443bf5 2987 err = ret;
28c16cbb 2988 goto fail_qgroup;
79787eaa 2989 }
e02119d5 2990 }
1a40e23b 2991
6bccf3ab 2992 ret = btrfs_find_orphan_roots(fs_info);
79787eaa 2993 if (ret)
28c16cbb 2994 goto fail_qgroup;
76dda93c 2995
bc98a42c 2996 if (!sb_rdonly(sb)) {
d68fc57b 2997 ret = btrfs_cleanup_fs_roots(fs_info);
44c44af2 2998 if (ret)
28c16cbb 2999 goto fail_qgroup;
90c711ab
ZB
3000
3001 mutex_lock(&fs_info->cleaner_mutex);
5d4f98a2 3002 ret = btrfs_recover_relocation(tree_root);
90c711ab 3003 mutex_unlock(&fs_info->cleaner_mutex);
d7ce5843 3004 if (ret < 0) {
05135f59
DS
3005 btrfs_warn(fs_info, "failed to recover relocation: %d",
3006 ret);
d7ce5843 3007 err = -EINVAL;
bcef60f2 3008 goto fail_qgroup;
d7ce5843 3009 }
7c2ca468 3010 }
1a40e23b 3011
3de4586c
CM
3012 location.objectid = BTRFS_FS_TREE_OBJECTID;
3013 location.type = BTRFS_ROOT_ITEM_KEY;
cb517eab 3014 location.offset = 0;
3de4586c 3015
3de4586c 3016 fs_info->fs_root = btrfs_read_fs_root_no_name(fs_info, &location);
3140c9a3
DC
3017 if (IS_ERR(fs_info->fs_root)) {
3018 err = PTR_ERR(fs_info->fs_root);
f50f4353 3019 btrfs_warn(fs_info, "failed to read fs tree: %d", err);
bcef60f2 3020 goto fail_qgroup;
3140c9a3 3021 }
c289811c 3022
bc98a42c 3023 if (sb_rdonly(sb))
2b6ba629 3024 return 0;
59641015 3025
f8d468a1
OS
3026 if (btrfs_test_opt(fs_info, CLEAR_CACHE) &&
3027 btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
6675df31
OS
3028 clear_free_space_tree = 1;
3029 } else if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
3030 !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID)) {
3031 btrfs_warn(fs_info, "free space tree is invalid");
3032 clear_free_space_tree = 1;
3033 }
3034
3035 if (clear_free_space_tree) {
f8d468a1
OS
3036 btrfs_info(fs_info, "clearing free space tree");
3037 ret = btrfs_clear_free_space_tree(fs_info);
3038 if (ret) {
3039 btrfs_warn(fs_info,
3040 "failed to clear free space tree: %d", ret);
6bccf3ab 3041 close_ctree(fs_info);
f8d468a1
OS
3042 return ret;
3043 }
3044 }
3045
0b246afa 3046 if (btrfs_test_opt(fs_info, FREE_SPACE_TREE) &&
511711af 3047 !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
05135f59 3048 btrfs_info(fs_info, "creating free space tree");
511711af
CM
3049 ret = btrfs_create_free_space_tree(fs_info);
3050 if (ret) {
05135f59
DS
3051 btrfs_warn(fs_info,
3052 "failed to create free space tree: %d", ret);
6bccf3ab 3053 close_ctree(fs_info);
511711af
CM
3054 return ret;
3055 }
3056 }
3057
2b6ba629
ID
3058 down_read(&fs_info->cleanup_work_sem);
3059 if ((ret = btrfs_orphan_cleanup(fs_info->fs_root)) ||
3060 (ret = btrfs_orphan_cleanup(fs_info->tree_root))) {
e3acc2a6 3061 up_read(&fs_info->cleanup_work_sem);
6bccf3ab 3062 close_ctree(fs_info);
2b6ba629
ID
3063 return ret;
3064 }
3065 up_read(&fs_info->cleanup_work_sem);
59641015 3066
2b6ba629
ID
3067 ret = btrfs_resume_balance_async(fs_info);
3068 if (ret) {
05135f59 3069 btrfs_warn(fs_info, "failed to resume balance: %d", ret);
6bccf3ab 3070 close_ctree(fs_info);
2b6ba629 3071 return ret;
e3acc2a6
JB
3072 }
3073
8dabb742
SB
3074 ret = btrfs_resume_dev_replace_async(fs_info);
3075 if (ret) {
05135f59 3076 btrfs_warn(fs_info, "failed to resume device replace: %d", ret);
6bccf3ab 3077 close_ctree(fs_info);
8dabb742
SB
3078 return ret;
3079 }
3080
b382a324
JS
3081 btrfs_qgroup_rescan_resume(fs_info);
3082
4bbcaa64 3083 if (!fs_info->uuid_root) {
05135f59 3084 btrfs_info(fs_info, "creating UUID tree");
f7a81ea4
SB
3085 ret = btrfs_create_uuid_tree(fs_info);
3086 if (ret) {
05135f59
DS
3087 btrfs_warn(fs_info,
3088 "failed to create the UUID tree: %d", ret);
6bccf3ab 3089 close_ctree(fs_info);
f7a81ea4
SB
3090 return ret;
3091 }
0b246afa 3092 } else if (btrfs_test_opt(fs_info, RESCAN_UUID_TREE) ||
4bbcaa64
ES
3093 fs_info->generation !=
3094 btrfs_super_uuid_tree_generation(disk_super)) {
05135f59 3095 btrfs_info(fs_info, "checking UUID tree");
70f80175
SB
3096 ret = btrfs_check_uuid_tree(fs_info);
3097 if (ret) {
05135f59
DS
3098 btrfs_warn(fs_info,
3099 "failed to check the UUID tree: %d", ret);
6bccf3ab 3100 close_ctree(fs_info);
70f80175
SB
3101 return ret;
3102 }
3103 } else {
afcdd129 3104 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
f7a81ea4 3105 }
afcdd129 3106 set_bit(BTRFS_FS_OPEN, &fs_info->flags);
47ab2a6c 3107
8dcddfa0
QW
3108 /*
3109 * backuproot only affect mount behavior, and if open_ctree succeeded,
3110 * no need to keep the flag
3111 */
3112 btrfs_clear_opt(fs_info->mount_opt, USEBACKUPROOT);
3113
ad2b2c80 3114 return 0;
39279cc3 3115
bcef60f2
AJ
3116fail_qgroup:
3117 btrfs_free_qgroup_config(fs_info);
7c2ca468
CM
3118fail_trans_kthread:
3119 kthread_stop(fs_info->transaction_kthread);
2ff7e61e 3120 btrfs_cleanup_transaction(fs_info);
faa2dbf0 3121 btrfs_free_fs_roots(fs_info);
3f157a2f 3122fail_cleaner:
a74a4b97 3123 kthread_stop(fs_info->cleaner_kthread);
7c2ca468
CM
3124
3125 /*
3126 * make sure we're done with the btree inode before we stop our
3127 * kthreads
3128 */
3129 filemap_write_and_wait(fs_info->btree_inode->i_mapping);
7c2ca468 3130
2365dd3c 3131fail_sysfs:
6618a59b 3132 btrfs_sysfs_remove_mounted(fs_info);
2365dd3c 3133
b7c35e81
AJ
3134fail_fsdev_sysfs:
3135 btrfs_sysfs_remove_fsid(fs_info->fs_devices);
3136
1b1d1f66 3137fail_block_groups:
54067ae9 3138 btrfs_put_block_group_cache(fs_info);
af31f5e5
CM
3139
3140fail_tree_roots:
3141 free_root_pointers(fs_info, 1);
2b8195bb 3142 invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
af31f5e5 3143
39279cc3 3144fail_sb_buffer:
7abadb64 3145 btrfs_stop_all_workers(fs_info);
5cdd7db6 3146 btrfs_free_block_groups(fs_info);
16cdcec7 3147fail_alloc:
4543df7e 3148fail_iput:
586e46e2
ID
3149 btrfs_mapping_tree_free(&fs_info->mapping_tree);
3150
4543df7e 3151 iput(fs_info->btree_inode);
c404e0dc
MX
3152fail_bio_counter:
3153 percpu_counter_destroy(&fs_info->bio_counter);
963d678b
MX
3154fail_delalloc_bytes:
3155 percpu_counter_destroy(&fs_info->delalloc_bytes);
e2d84521
MX
3156fail_dirty_metadata_bytes:
3157 percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
76dda93c
YZ
3158fail_srcu:
3159 cleanup_srcu_struct(&fs_info->subvol_srcu);
7e662854 3160fail:
53b381b3 3161 btrfs_free_stripe_hash_table(fs_info);
586e46e2 3162 btrfs_close_devices(fs_info->fs_devices);
ad2b2c80 3163 return err;
af31f5e5
CM
3164
3165recovery_tree_root:
0b246afa 3166 if (!btrfs_test_opt(fs_info, USEBACKUPROOT))
af31f5e5
CM
3167 goto fail_tree_roots;
3168
3169 free_root_pointers(fs_info, 0);
3170
3171 /* don't use the log in recovery mode, it won't be valid */
3172 btrfs_set_super_log_root(disk_super, 0);
3173
3174 /* we can't trust the free space cache either */
3175 btrfs_set_opt(fs_info->mount_opt, CLEAR_CACHE);
3176
3177 ret = next_root_backup(fs_info, fs_info->super_copy,
3178 &num_backups_tried, &backup_index);
3179 if (ret == -1)
3180 goto fail_block_groups;
3181 goto retry_root_backup;
eb60ceac 3182}
663faf9f 3183ALLOW_ERROR_INJECTION(open_ctree, ERRNO);
eb60ceac 3184
f2984462
CM
3185static void btrfs_end_buffer_write_sync(struct buffer_head *bh, int uptodate)
3186{
f2984462
CM
3187 if (uptodate) {
3188 set_buffer_uptodate(bh);
3189 } else {
442a4f63
SB
3190 struct btrfs_device *device = (struct btrfs_device *)
3191 bh->b_private;
3192
fb456252 3193 btrfs_warn_rl_in_rcu(device->fs_info,
b14af3b4 3194 "lost page write due to IO error on %s",
606686ee 3195 rcu_str_deref(device->name));
01327610 3196 /* note, we don't set_buffer_write_io_error because we have
1259ab75
CM
3197 * our own ways of dealing with the IO errors
3198 */
f2984462 3199 clear_buffer_uptodate(bh);
442a4f63 3200 btrfs_dev_stat_inc_and_print(device, BTRFS_DEV_STAT_WRITE_ERRS);
f2984462
CM
3201 }
3202 unlock_buffer(bh);
3203 put_bh(bh);
3204}
3205
29c36d72
AJ
3206int btrfs_read_dev_one_super(struct block_device *bdev, int copy_num,
3207 struct buffer_head **bh_ret)
3208{
3209 struct buffer_head *bh;
3210 struct btrfs_super_block *super;
3211 u64 bytenr;
3212
3213 bytenr = btrfs_sb_offset(copy_num);
3214 if (bytenr + BTRFS_SUPER_INFO_SIZE >= i_size_read(bdev->bd_inode))
3215 return -EINVAL;
3216
9f6d2510 3217 bh = __bread(bdev, bytenr / BTRFS_BDEV_BLOCKSIZE, BTRFS_SUPER_INFO_SIZE);
29c36d72
AJ
3218 /*
3219 * If we fail to read from the underlying devices, as of now
3220 * the best option we have is to mark it EIO.
3221 */
3222 if (!bh)
3223 return -EIO;
3224
3225 super = (struct btrfs_super_block *)bh->b_data;
3226 if (btrfs_super_bytenr(super) != bytenr ||
3227 btrfs_super_magic(super) != BTRFS_MAGIC) {
3228 brelse(bh);
3229 return -EINVAL;
3230 }
3231
3232 *bh_ret = bh;
3233 return 0;
3234}
3235
3236
a512bbf8
YZ
3237struct buffer_head *btrfs_read_dev_super(struct block_device *bdev)
3238{
3239 struct buffer_head *bh;
3240 struct buffer_head *latest = NULL;
3241 struct btrfs_super_block *super;
3242 int i;
3243 u64 transid = 0;
92fc03fb 3244 int ret = -EINVAL;
a512bbf8
YZ
3245
3246 /* we would like to check all the supers, but that would make
3247 * a btrfs mount succeed after a mkfs from a different FS.
3248 * So, we need to add a special mount option to scan for
3249 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
3250 */
3251 for (i = 0; i < 1; i++) {
29c36d72
AJ
3252 ret = btrfs_read_dev_one_super(bdev, i, &bh);
3253 if (ret)
a512bbf8
YZ
3254 continue;
3255
3256 super = (struct btrfs_super_block *)bh->b_data;
a512bbf8
YZ
3257
3258 if (!latest || btrfs_super_generation(super) > transid) {
3259 brelse(latest);
3260 latest = bh;
3261 transid = btrfs_super_generation(super);
3262 } else {
3263 brelse(bh);
3264 }
3265 }
92fc03fb
AJ
3266
3267 if (!latest)
3268 return ERR_PTR(ret);
3269
a512bbf8
YZ
3270 return latest;
3271}
3272
4eedeb75 3273/*
abbb3b8e
DS
3274 * Write superblock @sb to the @device. Do not wait for completion, all the
3275 * buffer heads we write are pinned.
4eedeb75 3276 *
abbb3b8e
DS
3277 * Write @max_mirrors copies of the superblock, where 0 means default that fit
3278 * the expected device size at commit time. Note that max_mirrors must be
3279 * same for write and wait phases.
4eedeb75 3280 *
abbb3b8e 3281 * Return number of errors when buffer head is not found or submission fails.
4eedeb75 3282 */
a512bbf8 3283static int write_dev_supers(struct btrfs_device *device,
abbb3b8e 3284 struct btrfs_super_block *sb, int max_mirrors)
a512bbf8
YZ
3285{
3286 struct buffer_head *bh;
3287 int i;
3288 int ret;
3289 int errors = 0;
3290 u32 crc;
3291 u64 bytenr;
1b9e619c 3292 int op_flags;
a512bbf8
YZ
3293
3294 if (max_mirrors == 0)
3295 max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3296
a512bbf8
YZ
3297 for (i = 0; i < max_mirrors; i++) {
3298 bytenr = btrfs_sb_offset(i);
935e5cc9
MX
3299 if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3300 device->commit_total_bytes)
a512bbf8
YZ
3301 break;
3302
abbb3b8e 3303 btrfs_set_super_bytenr(sb, bytenr);
4eedeb75 3304
abbb3b8e
DS
3305 crc = ~(u32)0;
3306 crc = btrfs_csum_data((const char *)sb + BTRFS_CSUM_SIZE, crc,
3307 BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE);
3308 btrfs_csum_final(crc, sb->csum);
4eedeb75 3309
abbb3b8e 3310 /* One reference for us, and we leave it for the caller */
9f6d2510 3311 bh = __getblk(device->bdev, bytenr / BTRFS_BDEV_BLOCKSIZE,
abbb3b8e
DS
3312 BTRFS_SUPER_INFO_SIZE);
3313 if (!bh) {
3314 btrfs_err(device->fs_info,
3315 "couldn't get super buffer head for bytenr %llu",
3316 bytenr);
3317 errors++;
4eedeb75 3318 continue;
abbb3b8e 3319 }
634554dc 3320
abbb3b8e 3321 memcpy(bh->b_data, sb, BTRFS_SUPER_INFO_SIZE);
a512bbf8 3322
abbb3b8e
DS
3323 /* one reference for submit_bh */
3324 get_bh(bh);
4eedeb75 3325
abbb3b8e
DS
3326 set_buffer_uptodate(bh);
3327 lock_buffer(bh);
3328 bh->b_end_io = btrfs_end_buffer_write_sync;
3329 bh->b_private = device;
a512bbf8 3330
387125fc
CM
3331 /*
3332 * we fua the first super. The others we allow
3333 * to go down lazy.
3334 */
1b9e619c
OS
3335 op_flags = REQ_SYNC | REQ_META | REQ_PRIO;
3336 if (i == 0 && !btrfs_test_opt(device->fs_info, NOBARRIER))
3337 op_flags |= REQ_FUA;
3338 ret = btrfsic_submit_bh(REQ_OP_WRITE, op_flags, bh);
4eedeb75 3339 if (ret)
a512bbf8 3340 errors++;
a512bbf8
YZ
3341 }
3342 return errors < i ? 0 : -1;
3343}
3344
abbb3b8e
DS
3345/*
3346 * Wait for write completion of superblocks done by write_dev_supers,
3347 * @max_mirrors same for write and wait phases.
3348 *
3349 * Return number of errors when buffer head is not found or not marked up to
3350 * date.
3351 */
3352static int wait_dev_supers(struct btrfs_device *device, int max_mirrors)
3353{
3354 struct buffer_head *bh;
3355 int i;
3356 int errors = 0;
b6a535fa 3357 bool primary_failed = false;
abbb3b8e
DS
3358 u64 bytenr;
3359
3360 if (max_mirrors == 0)
3361 max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3362
3363 for (i = 0; i < max_mirrors; i++) {
3364 bytenr = btrfs_sb_offset(i);
3365 if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3366 device->commit_total_bytes)
3367 break;
3368
9f6d2510
DS
3369 bh = __find_get_block(device->bdev,
3370 bytenr / BTRFS_BDEV_BLOCKSIZE,
abbb3b8e
DS
3371 BTRFS_SUPER_INFO_SIZE);
3372 if (!bh) {
3373 errors++;
b6a535fa
HM
3374 if (i == 0)
3375 primary_failed = true;
abbb3b8e
DS
3376 continue;
3377 }
3378 wait_on_buffer(bh);
b6a535fa 3379 if (!buffer_uptodate(bh)) {
abbb3b8e 3380 errors++;
b6a535fa
HM
3381 if (i == 0)
3382 primary_failed = true;
3383 }
abbb3b8e
DS
3384
3385 /* drop our reference */
3386 brelse(bh);
3387
3388 /* drop the reference from the writing run */
3389 brelse(bh);
3390 }
3391
b6a535fa
HM
3392 /* log error, force error return */
3393 if (primary_failed) {
3394 btrfs_err(device->fs_info, "error writing primary super block to device %llu",
3395 device->devid);
3396 return -1;
3397 }
3398
abbb3b8e
DS
3399 return errors < i ? 0 : -1;
3400}
3401
387125fc
CM
3402/*
3403 * endio for the write_dev_flush, this will wake anyone waiting
3404 * for the barrier when it is done
3405 */
4246a0b6 3406static void btrfs_end_empty_barrier(struct bio *bio)
387125fc 3407{
e0ae9994 3408 complete(bio->bi_private);
387125fc
CM
3409}
3410
3411/*
4fc6441a
AJ
3412 * Submit a flush request to the device if it supports it. Error handling is
3413 * done in the waiting counterpart.
387125fc 3414 */
4fc6441a 3415static void write_dev_flush(struct btrfs_device *device)
387125fc 3416{
c2a9c7ab 3417 struct request_queue *q = bdev_get_queue(device->bdev);
e0ae9994 3418 struct bio *bio = device->flush_bio;
387125fc 3419
c2a9c7ab 3420 if (!test_bit(QUEUE_FLAG_WC, &q->queue_flags))
4fc6441a 3421 return;
387125fc 3422
e0ae9994 3423 bio_reset(bio);
387125fc 3424 bio->bi_end_io = btrfs_end_empty_barrier;
74d46992 3425 bio_set_dev(bio, device->bdev);
8d910125 3426 bio->bi_opf = REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH;
387125fc
CM
3427 init_completion(&device->flush_wait);
3428 bio->bi_private = &device->flush_wait;
387125fc 3429
43a01111 3430 btrfsic_submit_bio(bio);
1c3063b6 3431 set_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
4fc6441a 3432}
387125fc 3433
4fc6441a
AJ
3434/*
3435 * If the flush bio has been submitted by write_dev_flush, wait for it.
3436 */
8c27cb35 3437static blk_status_t wait_dev_flush(struct btrfs_device *device)
4fc6441a 3438{
4fc6441a 3439 struct bio *bio = device->flush_bio;
387125fc 3440
1c3063b6 3441 if (!test_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state))
58efbc9f 3442 return BLK_STS_OK;
387125fc 3443
1c3063b6 3444 clear_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
2980d574 3445 wait_for_completion_io(&device->flush_wait);
387125fc 3446
8c27cb35 3447 return bio->bi_status;
387125fc 3448}
387125fc 3449
d10b82fe 3450static int check_barrier_error(struct btrfs_fs_info *fs_info)
401b41e5 3451{
6528b99d 3452 if (!btrfs_check_rw_degradable(fs_info, NULL))
401b41e5 3453 return -EIO;
387125fc
CM
3454 return 0;
3455}
3456
3457/*
3458 * send an empty flush down to each device in parallel,
3459 * then wait for them
3460 */
3461static int barrier_all_devices(struct btrfs_fs_info *info)
3462{
3463 struct list_head *head;
3464 struct btrfs_device *dev;
5af3e8cc 3465 int errors_wait = 0;
4e4cbee9 3466 blk_status_t ret;
387125fc 3467
1538e6c5 3468 lockdep_assert_held(&info->fs_devices->device_list_mutex);
387125fc
CM
3469 /* send down all the barriers */
3470 head = &info->fs_devices->devices;
1538e6c5 3471 list_for_each_entry(dev, head, dev_list) {
e6e674bd 3472 if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
f88ba6a2 3473 continue;
cea7c8bf 3474 if (!dev->bdev)
387125fc 3475 continue;
e12c9621 3476 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
ebbede42 3477 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
387125fc
CM
3478 continue;
3479
4fc6441a 3480 write_dev_flush(dev);
58efbc9f 3481 dev->last_flush_error = BLK_STS_OK;
387125fc
CM
3482 }
3483
3484 /* wait for all the barriers */
1538e6c5 3485 list_for_each_entry(dev, head, dev_list) {
e6e674bd 3486 if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
f88ba6a2 3487 continue;
387125fc 3488 if (!dev->bdev) {
5af3e8cc 3489 errors_wait++;
387125fc
CM
3490 continue;
3491 }
e12c9621 3492 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
ebbede42 3493 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
387125fc
CM
3494 continue;
3495
4fc6441a 3496 ret = wait_dev_flush(dev);
401b41e5
AJ
3497 if (ret) {
3498 dev->last_flush_error = ret;
66b4993e
DS
3499 btrfs_dev_stat_inc_and_print(dev,
3500 BTRFS_DEV_STAT_FLUSH_ERRS);
5af3e8cc 3501 errors_wait++;
401b41e5
AJ
3502 }
3503 }
3504
cea7c8bf 3505 if (errors_wait) {
401b41e5
AJ
3506 /*
3507 * At some point we need the status of all disks
3508 * to arrive at the volume status. So error checking
3509 * is being pushed to a separate loop.
3510 */
d10b82fe 3511 return check_barrier_error(info);
387125fc 3512 }
387125fc
CM
3513 return 0;
3514}
3515
943c6e99
ZL
3516int btrfs_get_num_tolerated_disk_barrier_failures(u64 flags)
3517{
8789f4fe
ZL
3518 int raid_type;
3519 int min_tolerated = INT_MAX;
943c6e99 3520
8789f4fe
ZL
3521 if ((flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 ||
3522 (flags & BTRFS_AVAIL_ALLOC_BIT_SINGLE))
3523 min_tolerated = min(min_tolerated,
3524 btrfs_raid_array[BTRFS_RAID_SINGLE].
3525 tolerated_failures);
943c6e99 3526
8789f4fe
ZL
3527 for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
3528 if (raid_type == BTRFS_RAID_SINGLE)
3529 continue;
3530 if (!(flags & btrfs_raid_group[raid_type]))
3531 continue;
3532 min_tolerated = min(min_tolerated,
3533 btrfs_raid_array[raid_type].
3534 tolerated_failures);
3535 }
943c6e99 3536
8789f4fe 3537 if (min_tolerated == INT_MAX) {
ab8d0fc4 3538 pr_warn("BTRFS: unknown raid flag: %llu", flags);
8789f4fe
ZL
3539 min_tolerated = 0;
3540 }
3541
3542 return min_tolerated;
943c6e99
ZL
3543}
3544
eece6a9c 3545int write_all_supers(struct btrfs_fs_info *fs_info, int max_mirrors)
f2984462 3546{
e5e9a520 3547 struct list_head *head;
f2984462 3548 struct btrfs_device *dev;
a061fc8d 3549 struct btrfs_super_block *sb;
f2984462 3550 struct btrfs_dev_item *dev_item;
f2984462
CM
3551 int ret;
3552 int do_barriers;
a236aed1
CM
3553 int max_errors;
3554 int total_errors = 0;
a061fc8d 3555 u64 flags;
f2984462 3556
0b246afa 3557 do_barriers = !btrfs_test_opt(fs_info, NOBARRIER);
fed3b381
LB
3558
3559 /*
3560 * max_mirrors == 0 indicates we're from commit_transaction,
3561 * not from fsync where the tree roots in fs_info have not
3562 * been consistent on disk.
3563 */
3564 if (max_mirrors == 0)
3565 backup_super_roots(fs_info);
f2984462 3566
0b246afa 3567 sb = fs_info->super_for_commit;
a061fc8d 3568 dev_item = &sb->dev_item;
e5e9a520 3569
0b246afa
JM
3570 mutex_lock(&fs_info->fs_devices->device_list_mutex);
3571 head = &fs_info->fs_devices->devices;
3572 max_errors = btrfs_super_num_devices(fs_info->super_copy) - 1;
387125fc 3573
5af3e8cc 3574 if (do_barriers) {
0b246afa 3575 ret = barrier_all_devices(fs_info);
5af3e8cc
SB
3576 if (ret) {
3577 mutex_unlock(
0b246afa
JM
3578 &fs_info->fs_devices->device_list_mutex);
3579 btrfs_handle_fs_error(fs_info, ret,
3580 "errors while submitting device barriers.");
5af3e8cc
SB
3581 return ret;
3582 }
3583 }
387125fc 3584
1538e6c5 3585 list_for_each_entry(dev, head, dev_list) {
dfe25020
CM
3586 if (!dev->bdev) {
3587 total_errors++;
3588 continue;
3589 }
e12c9621 3590 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
ebbede42 3591 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
dfe25020
CM
3592 continue;
3593
2b82032c 3594 btrfs_set_stack_device_generation(dev_item, 0);
a061fc8d
CM
3595 btrfs_set_stack_device_type(dev_item, dev->type);
3596 btrfs_set_stack_device_id(dev_item, dev->devid);
7df69d3e 3597 btrfs_set_stack_device_total_bytes(dev_item,
935e5cc9 3598 dev->commit_total_bytes);
ce7213c7
MX
3599 btrfs_set_stack_device_bytes_used(dev_item,
3600 dev->commit_bytes_used);
a061fc8d
CM
3601 btrfs_set_stack_device_io_align(dev_item, dev->io_align);
3602 btrfs_set_stack_device_io_width(dev_item, dev->io_width);
3603 btrfs_set_stack_device_sector_size(dev_item, dev->sector_size);
3604 memcpy(dev_item->uuid, dev->uuid, BTRFS_UUID_SIZE);
44880fdc 3605 memcpy(dev_item->fsid, dev->fs_devices->fsid, BTRFS_FSID_SIZE);
a512bbf8 3606
a061fc8d
CM
3607 flags = btrfs_super_flags(sb);
3608 btrfs_set_super_flags(sb, flags | BTRFS_HEADER_FLAG_WRITTEN);
3609
abbb3b8e 3610 ret = write_dev_supers(dev, sb, max_mirrors);
a236aed1
CM
3611 if (ret)
3612 total_errors++;
f2984462 3613 }
a236aed1 3614 if (total_errors > max_errors) {
0b246afa
JM
3615 btrfs_err(fs_info, "%d errors while writing supers",
3616 total_errors);
3617 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
79787eaa 3618
9d565ba4 3619 /* FUA is masked off if unsupported and can't be the reason */
0b246afa
JM
3620 btrfs_handle_fs_error(fs_info, -EIO,
3621 "%d errors while writing supers",
3622 total_errors);
9d565ba4 3623 return -EIO;
a236aed1 3624 }
f2984462 3625
a512bbf8 3626 total_errors = 0;
1538e6c5 3627 list_for_each_entry(dev, head, dev_list) {
dfe25020
CM
3628 if (!dev->bdev)
3629 continue;
e12c9621 3630 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
ebbede42 3631 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
dfe25020
CM
3632 continue;
3633
abbb3b8e 3634 ret = wait_dev_supers(dev, max_mirrors);
a512bbf8
YZ
3635 if (ret)
3636 total_errors++;
f2984462 3637 }
0b246afa 3638 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
a236aed1 3639 if (total_errors > max_errors) {
0b246afa
JM
3640 btrfs_handle_fs_error(fs_info, -EIO,
3641 "%d errors while writing supers",
3642 total_errors);
79787eaa 3643 return -EIO;
a236aed1 3644 }
f2984462
CM
3645 return 0;
3646}
3647
cb517eab
MX
3648/* Drop a fs root from the radix tree and free it. */
3649void btrfs_drop_and_free_fs_root(struct btrfs_fs_info *fs_info,
3650 struct btrfs_root *root)
2619ba1f 3651{
4df27c4d 3652 spin_lock(&fs_info->fs_roots_radix_lock);
2619ba1f
CM
3653 radix_tree_delete(&fs_info->fs_roots_radix,
3654 (unsigned long)root->root_key.objectid);
4df27c4d 3655 spin_unlock(&fs_info->fs_roots_radix_lock);
76dda93c
YZ
3656
3657 if (btrfs_root_refs(&root->root_item) == 0)
3658 synchronize_srcu(&fs_info->subvol_srcu);
3659
1c1ea4f7 3660 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
3321719e 3661 btrfs_free_log(NULL, root);
1c1ea4f7
LB
3662 if (root->reloc_root) {
3663 free_extent_buffer(root->reloc_root->node);
3664 free_extent_buffer(root->reloc_root->commit_root);
3665 btrfs_put_fs_root(root->reloc_root);
3666 root->reloc_root = NULL;
3667 }
3668 }
3321719e 3669
faa2dbf0
JB
3670 if (root->free_ino_pinned)
3671 __btrfs_remove_free_space_cache(root->free_ino_pinned);
3672 if (root->free_ino_ctl)
3673 __btrfs_remove_free_space_cache(root->free_ino_ctl);
4df27c4d 3674 free_fs_root(root);
4df27c4d
YZ
3675}
3676
3677static void free_fs_root(struct btrfs_root *root)
3678{
57cdc8db 3679 iput(root->ino_cache_inode);
4df27c4d 3680 WARN_ON(!RB_EMPTY_ROOT(&root->inode_tree));
2ff7e61e 3681 btrfs_free_block_rsv(root->fs_info, root->orphan_block_rsv);
1cb048f5 3682 root->orphan_block_rsv = NULL;
0ee5dc67
AV
3683 if (root->anon_dev)
3684 free_anon_bdev(root->anon_dev);
8257b2dc
MX
3685 if (root->subv_writers)
3686 btrfs_free_subvolume_writers(root->subv_writers);
4df27c4d
YZ
3687 free_extent_buffer(root->node);
3688 free_extent_buffer(root->commit_root);
581bb050
LZ
3689 kfree(root->free_ino_ctl);
3690 kfree(root->free_ino_pinned);
d397712b 3691 kfree(root->name);
b0feb9d9 3692 btrfs_put_fs_root(root);
2619ba1f
CM
3693}
3694
cb517eab
MX
3695void btrfs_free_fs_root(struct btrfs_root *root)
3696{
3697 free_fs_root(root);
2619ba1f
CM
3698}
3699
c146afad 3700int btrfs_cleanup_fs_roots(struct btrfs_fs_info *fs_info)
cfaa7295 3701{
c146afad
YZ
3702 u64 root_objectid = 0;
3703 struct btrfs_root *gang[8];
65d33fd7
QW
3704 int i = 0;
3705 int err = 0;
3706 unsigned int ret = 0;
3707 int index;
e089f05c 3708
c146afad 3709 while (1) {
65d33fd7 3710 index = srcu_read_lock(&fs_info->subvol_srcu);
c146afad
YZ
3711 ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
3712 (void **)gang, root_objectid,
3713 ARRAY_SIZE(gang));
65d33fd7
QW
3714 if (!ret) {
3715 srcu_read_unlock(&fs_info->subvol_srcu, index);
c146afad 3716 break;
65d33fd7 3717 }
5d4f98a2 3718 root_objectid = gang[ret - 1]->root_key.objectid + 1;
65d33fd7 3719
c146afad 3720 for (i = 0; i < ret; i++) {
65d33fd7
QW
3721 /* Avoid to grab roots in dead_roots */
3722 if (btrfs_root_refs(&gang[i]->root_item) == 0) {
3723 gang[i] = NULL;
3724 continue;
3725 }
3726 /* grab all the search result for later use */
3727 gang[i] = btrfs_grab_fs_root(gang[i]);
3728 }
3729 srcu_read_unlock(&fs_info->subvol_srcu, index);
66b4ffd1 3730
65d33fd7
QW
3731 for (i = 0; i < ret; i++) {
3732 if (!gang[i])
3733 continue;
c146afad 3734 root_objectid = gang[i]->root_key.objectid;
66b4ffd1
JB
3735 err = btrfs_orphan_cleanup(gang[i]);
3736 if (err)
65d33fd7
QW
3737 break;
3738 btrfs_put_fs_root(gang[i]);
c146afad
YZ
3739 }
3740 root_objectid++;
3741 }
65d33fd7
QW
3742
3743 /* release the uncleaned roots due to error */
3744 for (; i < ret; i++) {
3745 if (gang[i])
3746 btrfs_put_fs_root(gang[i]);
3747 }
3748 return err;
c146afad 3749}
a2135011 3750
6bccf3ab 3751int btrfs_commit_super(struct btrfs_fs_info *fs_info)
c146afad 3752{
6bccf3ab 3753 struct btrfs_root *root = fs_info->tree_root;
c146afad 3754 struct btrfs_trans_handle *trans;
a74a4b97 3755
0b246afa 3756 mutex_lock(&fs_info->cleaner_mutex);
2ff7e61e 3757 btrfs_run_delayed_iputs(fs_info);
0b246afa
JM
3758 mutex_unlock(&fs_info->cleaner_mutex);
3759 wake_up_process(fs_info->cleaner_kthread);
c71bf099
YZ
3760
3761 /* wait until ongoing cleanup work done */
0b246afa
JM
3762 down_write(&fs_info->cleanup_work_sem);
3763 up_write(&fs_info->cleanup_work_sem);
c71bf099 3764
7a7eaa40 3765 trans = btrfs_join_transaction(root);
3612b495
TI
3766 if (IS_ERR(trans))
3767 return PTR_ERR(trans);
3a45bb20 3768 return btrfs_commit_transaction(trans);
c146afad
YZ
3769}
3770
6bccf3ab 3771void close_ctree(struct btrfs_fs_info *fs_info)
c146afad 3772{
6bccf3ab 3773 struct btrfs_root *root = fs_info->tree_root;
c146afad
YZ
3774 int ret;
3775
afcdd129 3776 set_bit(BTRFS_FS_CLOSING_START, &fs_info->flags);
c146afad 3777
7343dd61 3778 /* wait for the qgroup rescan worker to stop */
d06f23d6 3779 btrfs_qgroup_wait_for_completion(fs_info, false);
7343dd61 3780
803b2f54
SB
3781 /* wait for the uuid_scan task to finish */
3782 down(&fs_info->uuid_tree_rescan_sem);
3783 /* avoid complains from lockdep et al., set sem back to initial state */
3784 up(&fs_info->uuid_tree_rescan_sem);
3785
837d5b6e 3786 /* pause restriper - we want to resume on mount */
aa1b8cd4 3787 btrfs_pause_balance(fs_info);
837d5b6e 3788
8dabb742
SB
3789 btrfs_dev_replace_suspend_for_unmount(fs_info);
3790
aa1b8cd4 3791 btrfs_scrub_cancel(fs_info);
4cb5300b
CM
3792
3793 /* wait for any defraggers to finish */
3794 wait_event(fs_info->transaction_wait,
3795 (atomic_read(&fs_info->defrag_running) == 0));
3796
3797 /* clear out the rbtree of defraggable inodes */
26176e7c 3798 btrfs_cleanup_defrag_inodes(fs_info);
4cb5300b 3799
21c7e756
MX
3800 cancel_work_sync(&fs_info->async_reclaim_work);
3801
bc98a42c 3802 if (!sb_rdonly(fs_info->sb)) {
e44163e1
JM
3803 /*
3804 * If the cleaner thread is stopped and there are
3805 * block groups queued for removal, the deletion will be
3806 * skipped when we quit the cleaner thread.
3807 */
0b246afa 3808 btrfs_delete_unused_bgs(fs_info);
e44163e1 3809
6bccf3ab 3810 ret = btrfs_commit_super(fs_info);
acce952b 3811 if (ret)
04892340 3812 btrfs_err(fs_info, "commit super ret %d", ret);
acce952b 3813 }
3814
af722733
LB
3815 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state) ||
3816 test_bit(BTRFS_FS_STATE_TRANS_ABORTED, &fs_info->fs_state))
2ff7e61e 3817 btrfs_error_commit_super(fs_info);
0f7d52f4 3818
e3029d9f
AV
3819 kthread_stop(fs_info->transaction_kthread);
3820 kthread_stop(fs_info->cleaner_kthread);
8929ecfa 3821
afcdd129 3822 set_bit(BTRFS_FS_CLOSING_DONE, &fs_info->flags);
f25784b3 3823
04892340 3824 btrfs_free_qgroup_config(fs_info);
bcef60f2 3825
963d678b 3826 if (percpu_counter_sum(&fs_info->delalloc_bytes)) {
04892340 3827 btrfs_info(fs_info, "at unmount delalloc count %lld",
963d678b 3828 percpu_counter_sum(&fs_info->delalloc_bytes));
b0c68f8b 3829 }
bcc63abb 3830
6618a59b 3831 btrfs_sysfs_remove_mounted(fs_info);
b7c35e81 3832 btrfs_sysfs_remove_fsid(fs_info->fs_devices);
5ac1d209 3833
faa2dbf0 3834 btrfs_free_fs_roots(fs_info);
d10c5f31 3835
1a4319cc
LB
3836 btrfs_put_block_group_cache(fs_info);
3837
de348ee0
WS
3838 /*
3839 * we must make sure there is not any read request to
3840 * submit after we stopping all workers.
3841 */
3842 invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
96192499
JB
3843 btrfs_stop_all_workers(fs_info);
3844
5cdd7db6
FM
3845 btrfs_free_block_groups(fs_info);
3846
afcdd129 3847 clear_bit(BTRFS_FS_OPEN, &fs_info->flags);
13e6c37b 3848 free_root_pointers(fs_info, 1);
9ad6b7bc 3849
13e6c37b 3850 iput(fs_info->btree_inode);
d6bfde87 3851
21adbd5c 3852#ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
0b246afa 3853 if (btrfs_test_opt(fs_info, CHECK_INTEGRITY))
2ff7e61e 3854 btrfsic_unmount(fs_info->fs_devices);
21adbd5c
SB
3855#endif
3856
dfe25020 3857 btrfs_close_devices(fs_info->fs_devices);
0b86a832 3858 btrfs_mapping_tree_free(&fs_info->mapping_tree);
b248a415 3859
e2d84521 3860 percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
963d678b 3861 percpu_counter_destroy(&fs_info->delalloc_bytes);
c404e0dc 3862 percpu_counter_destroy(&fs_info->bio_counter);
76dda93c 3863 cleanup_srcu_struct(&fs_info->subvol_srcu);
0b86a832 3864
53b381b3 3865 btrfs_free_stripe_hash_table(fs_info);
fd708b81 3866 btrfs_free_ref_cache(fs_info);
53b381b3 3867
cdfb080e 3868 __btrfs_free_block_rsv(root->orphan_block_rsv);
1cb048f5 3869 root->orphan_block_rsv = NULL;
04216820 3870
04216820
FM
3871 while (!list_empty(&fs_info->pinned_chunks)) {
3872 struct extent_map *em;
3873
3874 em = list_first_entry(&fs_info->pinned_chunks,
3875 struct extent_map, list);
3876 list_del_init(&em->list);
3877 free_extent_map(em);
3878 }
eb60ceac
CM
3879}
3880
b9fab919
CM
3881int btrfs_buffer_uptodate(struct extent_buffer *buf, u64 parent_transid,
3882 int atomic)
5f39d397 3883{
1259ab75 3884 int ret;
727011e0 3885 struct inode *btree_inode = buf->pages[0]->mapping->host;
1259ab75 3886
0b32f4bb 3887 ret = extent_buffer_uptodate(buf);
1259ab75
CM
3888 if (!ret)
3889 return ret;
3890
3891 ret = verify_parent_transid(&BTRFS_I(btree_inode)->io_tree, buf,
b9fab919
CM
3892 parent_transid, atomic);
3893 if (ret == -EAGAIN)
3894 return ret;
1259ab75 3895 return !ret;
5f39d397
CM
3896}
3897
5f39d397
CM
3898void btrfs_mark_buffer_dirty(struct extent_buffer *buf)
3899{
0b246afa 3900 struct btrfs_fs_info *fs_info;
06ea65a3 3901 struct btrfs_root *root;
5f39d397 3902 u64 transid = btrfs_header_generation(buf);
b9473439 3903 int was_dirty;
b4ce94de 3904
06ea65a3
JB
3905#ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
3906 /*
3907 * This is a fast path so only do this check if we have sanity tests
3908 * enabled. Normal people shouldn't be marking dummy buffers as dirty
3909 * outside of the sanity tests.
3910 */
3911 if (unlikely(test_bit(EXTENT_BUFFER_DUMMY, &buf->bflags)))
3912 return;
3913#endif
3914 root = BTRFS_I(buf->pages[0]->mapping->host)->root;
0b246afa 3915 fs_info = root->fs_info;
b9447ef8 3916 btrfs_assert_tree_locked(buf);
0b246afa 3917 if (transid != fs_info->generation)
5d163e0e 3918 WARN(1, KERN_CRIT "btrfs transid mismatch buffer %llu, found %llu running %llu\n",
0b246afa 3919 buf->start, transid, fs_info->generation);
0b32f4bb 3920 was_dirty = set_extent_buffer_dirty(buf);
e2d84521 3921 if (!was_dirty)
104b4e51
NB
3922 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
3923 buf->len,
3924 fs_info->dirty_metadata_batch);
1f21ef0a 3925#ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
69fc6cbb
QW
3926 /*
3927 * Since btrfs_mark_buffer_dirty() can be called with item pointer set
3928 * but item data not updated.
3929 * So here we should only check item pointers, not item data.
3930 */
3931 if (btrfs_header_level(buf) == 0 &&
2f659546 3932 btrfs_check_leaf_relaxed(fs_info, buf)) {
a4f78750 3933 btrfs_print_leaf(buf);
1f21ef0a
FM
3934 ASSERT(0);
3935 }
3936#endif
eb60ceac
CM
3937}
3938
2ff7e61e 3939static void __btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info,
b53d3f5d 3940 int flush_delayed)
16cdcec7
MX
3941{
3942 /*
3943 * looks as though older kernels can get into trouble with
3944 * this code, they end up stuck in balance_dirty_pages forever
3945 */
e2d84521 3946 int ret;
16cdcec7
MX
3947
3948 if (current->flags & PF_MEMALLOC)
3949 return;
3950
b53d3f5d 3951 if (flush_delayed)
2ff7e61e 3952 btrfs_balance_delayed_items(fs_info);
16cdcec7 3953
0b246afa 3954 ret = percpu_counter_compare(&fs_info->dirty_metadata_bytes,
e2d84521
MX
3955 BTRFS_DIRTY_METADATA_THRESH);
3956 if (ret > 0) {
0b246afa 3957 balance_dirty_pages_ratelimited(fs_info->btree_inode->i_mapping);
16cdcec7 3958 }
16cdcec7
MX
3959}
3960
2ff7e61e 3961void btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info)
35b7e476 3962{
2ff7e61e 3963 __btrfs_btree_balance_dirty(fs_info, 1);
b53d3f5d 3964}
585ad2c3 3965
2ff7e61e 3966void btrfs_btree_balance_dirty_nodelay(struct btrfs_fs_info *fs_info)
b53d3f5d 3967{
2ff7e61e 3968 __btrfs_btree_balance_dirty(fs_info, 0);
35b7e476 3969}
6b80053d 3970
581c1760
QW
3971int btrfs_read_buffer(struct extent_buffer *buf, u64 parent_transid, int level,
3972 struct btrfs_key *first_key)
6b80053d 3973{
727011e0 3974 struct btrfs_root *root = BTRFS_I(buf->pages[0]->mapping->host)->root;
2ff7e61e
JM
3975 struct btrfs_fs_info *fs_info = root->fs_info;
3976
581c1760
QW
3977 return btree_read_extent_buffer_pages(fs_info, buf, parent_transid,
3978 level, first_key);
6b80053d 3979}
0da5468f 3980
3d3a126a 3981static int btrfs_check_super_valid(struct btrfs_fs_info *fs_info)
acce952b 3982{
c926093e 3983 struct btrfs_super_block *sb = fs_info->super_copy;
319e4d06
QW
3984 u64 nodesize = btrfs_super_nodesize(sb);
3985 u64 sectorsize = btrfs_super_sectorsize(sb);
c926093e
DS
3986 int ret = 0;
3987
319e4d06 3988 if (btrfs_super_magic(sb) != BTRFS_MAGIC) {
ab8d0fc4 3989 btrfs_err(fs_info, "no valid FS found");
319e4d06
QW
3990 ret = -EINVAL;
3991 }
6f794e3c
AJ
3992 if (btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP) {
3993 btrfs_err(fs_info, "unrecognized or unsupported super flag: %llu",
319e4d06 3994 btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP);
6f794e3c
AJ
3995 ret = -EINVAL;
3996 }
21e7626b 3997 if (btrfs_super_root_level(sb) >= BTRFS_MAX_LEVEL) {
ab8d0fc4 3998 btrfs_err(fs_info, "tree_root level too big: %d >= %d",
21e7626b 3999 btrfs_super_root_level(sb), BTRFS_MAX_LEVEL);
c926093e
DS
4000 ret = -EINVAL;
4001 }
21e7626b 4002 if (btrfs_super_chunk_root_level(sb) >= BTRFS_MAX_LEVEL) {
ab8d0fc4 4003 btrfs_err(fs_info, "chunk_root level too big: %d >= %d",
21e7626b 4004 btrfs_super_chunk_root_level(sb), BTRFS_MAX_LEVEL);
c926093e
DS
4005 ret = -EINVAL;
4006 }
21e7626b 4007 if (btrfs_super_log_root_level(sb) >= BTRFS_MAX_LEVEL) {
ab8d0fc4 4008 btrfs_err(fs_info, "log_root level too big: %d >= %d",
21e7626b 4009 btrfs_super_log_root_level(sb), BTRFS_MAX_LEVEL);
c926093e
DS
4010 ret = -EINVAL;
4011 }
4012
1104a885 4013 /*
319e4d06
QW
4014 * Check sectorsize and nodesize first, other check will need it.
4015 * Check all possible sectorsize(4K, 8K, 16K, 32K, 64K) here.
1104a885 4016 */
319e4d06
QW
4017 if (!is_power_of_2(sectorsize) || sectorsize < 4096 ||
4018 sectorsize > BTRFS_MAX_METADATA_BLOCKSIZE) {
ab8d0fc4 4019 btrfs_err(fs_info, "invalid sectorsize %llu", sectorsize);
319e4d06
QW
4020 ret = -EINVAL;
4021 }
4022 /* Only PAGE SIZE is supported yet */
09cbfeaf 4023 if (sectorsize != PAGE_SIZE) {
ab8d0fc4
JM
4024 btrfs_err(fs_info,
4025 "sectorsize %llu not supported yet, only support %lu",
4026 sectorsize, PAGE_SIZE);
319e4d06
QW
4027 ret = -EINVAL;
4028 }
4029 if (!is_power_of_2(nodesize) || nodesize < sectorsize ||
4030 nodesize > BTRFS_MAX_METADATA_BLOCKSIZE) {
ab8d0fc4 4031 btrfs_err(fs_info, "invalid nodesize %llu", nodesize);
319e4d06
QW
4032 ret = -EINVAL;
4033 }
4034 if (nodesize != le32_to_cpu(sb->__unused_leafsize)) {
ab8d0fc4
JM
4035 btrfs_err(fs_info, "invalid leafsize %u, should be %llu",
4036 le32_to_cpu(sb->__unused_leafsize), nodesize);
319e4d06
QW
4037 ret = -EINVAL;
4038 }
4039
4040 /* Root alignment check */
4041 if (!IS_ALIGNED(btrfs_super_root(sb), sectorsize)) {
ab8d0fc4
JM
4042 btrfs_warn(fs_info, "tree_root block unaligned: %llu",
4043 btrfs_super_root(sb));
319e4d06
QW
4044 ret = -EINVAL;
4045 }
4046 if (!IS_ALIGNED(btrfs_super_chunk_root(sb), sectorsize)) {
ab8d0fc4
JM
4047 btrfs_warn(fs_info, "chunk_root block unaligned: %llu",
4048 btrfs_super_chunk_root(sb));
75d6ad38
DS
4049 ret = -EINVAL;
4050 }
319e4d06 4051 if (!IS_ALIGNED(btrfs_super_log_root(sb), sectorsize)) {
ab8d0fc4
JM
4052 btrfs_warn(fs_info, "log_root block unaligned: %llu",
4053 btrfs_super_log_root(sb));
75d6ad38
DS
4054 ret = -EINVAL;
4055 }
4056
44880fdc 4057 if (memcmp(fs_info->fsid, sb->dev_item.fsid, BTRFS_FSID_SIZE) != 0) {
ab8d0fc4
JM
4058 btrfs_err(fs_info,
4059 "dev_item UUID does not match fsid: %pU != %pU",
4060 fs_info->fsid, sb->dev_item.fsid);
c926093e
DS
4061 ret = -EINVAL;
4062 }
4063
4064 /*
4065 * Hint to catch really bogus numbers, bitflips or so, more exact checks are
4066 * done later
4067 */
99e3ecfc
LB
4068 if (btrfs_super_bytes_used(sb) < 6 * btrfs_super_nodesize(sb)) {
4069 btrfs_err(fs_info, "bytes_used is too small %llu",
ab8d0fc4 4070 btrfs_super_bytes_used(sb));
99e3ecfc
LB
4071 ret = -EINVAL;
4072 }
b7f67055 4073 if (!is_power_of_2(btrfs_super_stripesize(sb))) {
99e3ecfc 4074 btrfs_err(fs_info, "invalid stripesize %u",
ab8d0fc4 4075 btrfs_super_stripesize(sb));
99e3ecfc
LB
4076 ret = -EINVAL;
4077 }
21e7626b 4078 if (btrfs_super_num_devices(sb) > (1UL << 31))
ab8d0fc4
JM
4079 btrfs_warn(fs_info, "suspicious number of devices: %llu",
4080 btrfs_super_num_devices(sb));
75d6ad38 4081 if (btrfs_super_num_devices(sb) == 0) {
ab8d0fc4 4082 btrfs_err(fs_info, "number of devices is 0");
75d6ad38
DS
4083 ret = -EINVAL;
4084 }
c926093e 4085
21e7626b 4086 if (btrfs_super_bytenr(sb) != BTRFS_SUPER_INFO_OFFSET) {
ab8d0fc4
JM
4087 btrfs_err(fs_info, "super offset mismatch %llu != %u",
4088 btrfs_super_bytenr(sb), BTRFS_SUPER_INFO_OFFSET);
c926093e
DS
4089 ret = -EINVAL;
4090 }
4091
ce7fca5f
DS
4092 /*
4093 * Obvious sys_chunk_array corruptions, it must hold at least one key
4094 * and one chunk
4095 */
4096 if (btrfs_super_sys_array_size(sb) > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
ab8d0fc4
JM
4097 btrfs_err(fs_info, "system chunk array too big %u > %u",
4098 btrfs_super_sys_array_size(sb),
4099 BTRFS_SYSTEM_CHUNK_ARRAY_SIZE);
ce7fca5f
DS
4100 ret = -EINVAL;
4101 }
4102 if (btrfs_super_sys_array_size(sb) < sizeof(struct btrfs_disk_key)
4103 + sizeof(struct btrfs_chunk)) {
ab8d0fc4
JM
4104 btrfs_err(fs_info, "system chunk array too small %u < %zu",
4105 btrfs_super_sys_array_size(sb),
4106 sizeof(struct btrfs_disk_key)
4107 + sizeof(struct btrfs_chunk));
ce7fca5f
DS
4108 ret = -EINVAL;
4109 }
4110
c926093e
DS
4111 /*
4112 * The generation is a global counter, we'll trust it more than the others
4113 * but it's still possible that it's the one that's wrong.
4114 */
21e7626b 4115 if (btrfs_super_generation(sb) < btrfs_super_chunk_root_generation(sb))
ab8d0fc4
JM
4116 btrfs_warn(fs_info,
4117 "suspicious: generation < chunk_root_generation: %llu < %llu",
4118 btrfs_super_generation(sb),
4119 btrfs_super_chunk_root_generation(sb));
21e7626b
DS
4120 if (btrfs_super_generation(sb) < btrfs_super_cache_generation(sb)
4121 && btrfs_super_cache_generation(sb) != (u64)-1)
ab8d0fc4
JM
4122 btrfs_warn(fs_info,
4123 "suspicious: generation < cache_generation: %llu < %llu",
4124 btrfs_super_generation(sb),
4125 btrfs_super_cache_generation(sb));
c926093e
DS
4126
4127 return ret;
acce952b 4128}
4129
2ff7e61e 4130static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info)
acce952b 4131{
0b246afa 4132 mutex_lock(&fs_info->cleaner_mutex);
2ff7e61e 4133 btrfs_run_delayed_iputs(fs_info);
0b246afa 4134 mutex_unlock(&fs_info->cleaner_mutex);
acce952b 4135
0b246afa
JM
4136 down_write(&fs_info->cleanup_work_sem);
4137 up_write(&fs_info->cleanup_work_sem);
acce952b 4138
4139 /* cleanup FS via transaction */
2ff7e61e 4140 btrfs_cleanup_transaction(fs_info);
acce952b 4141}
4142
143bede5 4143static void btrfs_destroy_ordered_extents(struct btrfs_root *root)
acce952b 4144{
acce952b 4145 struct btrfs_ordered_extent *ordered;
acce952b 4146
199c2a9c 4147 spin_lock(&root->ordered_extent_lock);
779880ef
JB
4148 /*
4149 * This will just short circuit the ordered completion stuff which will
4150 * make sure the ordered extent gets properly cleaned up.
4151 */
199c2a9c 4152 list_for_each_entry(ordered, &root->ordered_extents,
779880ef
JB
4153 root_extent_list)
4154 set_bit(BTRFS_ORDERED_IOERR, &ordered->flags);
199c2a9c
MX
4155 spin_unlock(&root->ordered_extent_lock);
4156}
4157
4158static void btrfs_destroy_all_ordered_extents(struct btrfs_fs_info *fs_info)
4159{
4160 struct btrfs_root *root;
4161 struct list_head splice;
4162
4163 INIT_LIST_HEAD(&splice);
4164
4165 spin_lock(&fs_info->ordered_root_lock);
4166 list_splice_init(&fs_info->ordered_roots, &splice);
4167 while (!list_empty(&splice)) {
4168 root = list_first_entry(&splice, struct btrfs_root,
4169 ordered_root);
1de2cfde
JB
4170 list_move_tail(&root->ordered_root,
4171 &fs_info->ordered_roots);
199c2a9c 4172
2a85d9ca 4173 spin_unlock(&fs_info->ordered_root_lock);
199c2a9c
MX
4174 btrfs_destroy_ordered_extents(root);
4175
2a85d9ca
LB
4176 cond_resched();
4177 spin_lock(&fs_info->ordered_root_lock);
199c2a9c
MX
4178 }
4179 spin_unlock(&fs_info->ordered_root_lock);
acce952b 4180}
4181
35a3621b 4182static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
2ff7e61e 4183 struct btrfs_fs_info *fs_info)
acce952b 4184{
4185 struct rb_node *node;
4186 struct btrfs_delayed_ref_root *delayed_refs;
4187 struct btrfs_delayed_ref_node *ref;
4188 int ret = 0;
4189
4190 delayed_refs = &trans->delayed_refs;
4191
4192 spin_lock(&delayed_refs->lock);
d7df2c79 4193 if (atomic_read(&delayed_refs->num_entries) == 0) {
cfece4db 4194 spin_unlock(&delayed_refs->lock);
0b246afa 4195 btrfs_info(fs_info, "delayed_refs has NO entry");
acce952b 4196 return ret;
4197 }
4198
d7df2c79
JB
4199 while ((node = rb_first(&delayed_refs->href_root)) != NULL) {
4200 struct btrfs_delayed_ref_head *head;
0e0adbcf 4201 struct rb_node *n;
e78417d1 4202 bool pin_bytes = false;
acce952b 4203
d7df2c79
JB
4204 head = rb_entry(node, struct btrfs_delayed_ref_head,
4205 href_node);
4206 if (!mutex_trylock(&head->mutex)) {
d278850e 4207 refcount_inc(&head->refs);
d7df2c79 4208 spin_unlock(&delayed_refs->lock);
eb12db69 4209
d7df2c79 4210 mutex_lock(&head->mutex);
e78417d1 4211 mutex_unlock(&head->mutex);
d278850e 4212 btrfs_put_delayed_ref_head(head);
d7df2c79
JB
4213 spin_lock(&delayed_refs->lock);
4214 continue;
4215 }
4216 spin_lock(&head->lock);
0e0adbcf
JB
4217 while ((n = rb_first(&head->ref_tree)) != NULL) {
4218 ref = rb_entry(n, struct btrfs_delayed_ref_node,
4219 ref_node);
d7df2c79 4220 ref->in_tree = 0;
0e0adbcf
JB
4221 rb_erase(&ref->ref_node, &head->ref_tree);
4222 RB_CLEAR_NODE(&ref->ref_node);
1d57ee94
WX
4223 if (!list_empty(&ref->add_list))
4224 list_del(&ref->add_list);
d7df2c79
JB
4225 atomic_dec(&delayed_refs->num_entries);
4226 btrfs_put_delayed_ref(ref);
e78417d1 4227 }
d7df2c79
JB
4228 if (head->must_insert_reserved)
4229 pin_bytes = true;
4230 btrfs_free_delayed_extent_op(head->extent_op);
4231 delayed_refs->num_heads--;
4232 if (head->processing == 0)
4233 delayed_refs->num_heads_ready--;
4234 atomic_dec(&delayed_refs->num_entries);
d7df2c79 4235 rb_erase(&head->href_node, &delayed_refs->href_root);
d278850e 4236 RB_CLEAR_NODE(&head->href_node);
d7df2c79
JB
4237 spin_unlock(&head->lock);
4238 spin_unlock(&delayed_refs->lock);
4239 mutex_unlock(&head->mutex);
acce952b 4240
d7df2c79 4241 if (pin_bytes)
d278850e
JB
4242 btrfs_pin_extent(fs_info, head->bytenr,
4243 head->num_bytes, 1);
4244 btrfs_put_delayed_ref_head(head);
acce952b 4245 cond_resched();
4246 spin_lock(&delayed_refs->lock);
4247 }
4248
4249 spin_unlock(&delayed_refs->lock);
4250
4251 return ret;
4252}
4253
143bede5 4254static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root)
acce952b 4255{
4256 struct btrfs_inode *btrfs_inode;
4257 struct list_head splice;
4258
4259 INIT_LIST_HEAD(&splice);
4260
eb73c1b7
MX
4261 spin_lock(&root->delalloc_lock);
4262 list_splice_init(&root->delalloc_inodes, &splice);
acce952b 4263
4264 while (!list_empty(&splice)) {
eb73c1b7
MX
4265 btrfs_inode = list_first_entry(&splice, struct btrfs_inode,
4266 delalloc_inodes);
acce952b 4267
4268 list_del_init(&btrfs_inode->delalloc_inodes);
df0af1a5
MX
4269 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
4270 &btrfs_inode->runtime_flags);
eb73c1b7 4271 spin_unlock(&root->delalloc_lock);
acce952b 4272
4273 btrfs_invalidate_inodes(btrfs_inode->root);
b216cbfb 4274
eb73c1b7 4275 spin_lock(&root->delalloc_lock);
acce952b 4276 }
4277
eb73c1b7
MX
4278 spin_unlock(&root->delalloc_lock);
4279}
4280
4281static void btrfs_destroy_all_delalloc_inodes(struct btrfs_fs_info *fs_info)
4282{
4283 struct btrfs_root *root;
4284 struct list_head splice;
4285
4286 INIT_LIST_HEAD(&splice);
4287
4288 spin_lock(&fs_info->delalloc_root_lock);
4289 list_splice_init(&fs_info->delalloc_roots, &splice);
4290 while (!list_empty(&splice)) {
4291 root = list_first_entry(&splice, struct btrfs_root,
4292 delalloc_root);
4293 list_del_init(&root->delalloc_root);
4294 root = btrfs_grab_fs_root(root);
4295 BUG_ON(!root);
4296 spin_unlock(&fs_info->delalloc_root_lock);
4297
4298 btrfs_destroy_delalloc_inodes(root);
4299 btrfs_put_fs_root(root);
4300
4301 spin_lock(&fs_info->delalloc_root_lock);
4302 }
4303 spin_unlock(&fs_info->delalloc_root_lock);
acce952b 4304}
4305
2ff7e61e 4306static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
acce952b 4307 struct extent_io_tree *dirty_pages,
4308 int mark)
4309{
4310 int ret;
acce952b 4311 struct extent_buffer *eb;
4312 u64 start = 0;
4313 u64 end;
acce952b 4314
4315 while (1) {
4316 ret = find_first_extent_bit(dirty_pages, start, &start, &end,
e6138876 4317 mark, NULL);
acce952b 4318 if (ret)
4319 break;
4320
91166212 4321 clear_extent_bits(dirty_pages, start, end, mark);
acce952b 4322 while (start <= end) {
0b246afa
JM
4323 eb = find_extent_buffer(fs_info, start);
4324 start += fs_info->nodesize;
fd8b2b61 4325 if (!eb)
acce952b 4326 continue;
fd8b2b61 4327 wait_on_extent_buffer_writeback(eb);
acce952b 4328
fd8b2b61
JB
4329 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY,
4330 &eb->bflags))
4331 clear_extent_buffer_dirty(eb);
4332 free_extent_buffer_stale(eb);
acce952b 4333 }
4334 }
4335
4336 return ret;
4337}
4338
2ff7e61e 4339static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
acce952b 4340 struct extent_io_tree *pinned_extents)
4341{
4342 struct extent_io_tree *unpin;
4343 u64 start;
4344 u64 end;
4345 int ret;
ed0eaa14 4346 bool loop = true;
acce952b 4347
4348 unpin = pinned_extents;
ed0eaa14 4349again:
acce952b 4350 while (1) {
4351 ret = find_first_extent_bit(unpin, 0, &start, &end,
e6138876 4352 EXTENT_DIRTY, NULL);
acce952b 4353 if (ret)
4354 break;
4355
af6f8f60 4356 clear_extent_dirty(unpin, start, end);
2ff7e61e 4357 btrfs_error_unpin_extent_range(fs_info, start, end);
acce952b 4358 cond_resched();
4359 }
4360
ed0eaa14 4361 if (loop) {
0b246afa
JM
4362 if (unpin == &fs_info->freed_extents[0])
4363 unpin = &fs_info->freed_extents[1];
ed0eaa14 4364 else
0b246afa 4365 unpin = &fs_info->freed_extents[0];
ed0eaa14
LB
4366 loop = false;
4367 goto again;
4368 }
4369
acce952b 4370 return 0;
4371}
4372
c79a1751
LB
4373static void btrfs_cleanup_bg_io(struct btrfs_block_group_cache *cache)
4374{
4375 struct inode *inode;
4376
4377 inode = cache->io_ctl.inode;
4378 if (inode) {
4379 invalidate_inode_pages2(inode->i_mapping);
4380 BTRFS_I(inode)->generation = 0;
4381 cache->io_ctl.inode = NULL;
4382 iput(inode);
4383 }
4384 btrfs_put_block_group(cache);
4385}
4386
4387void btrfs_cleanup_dirty_bgs(struct btrfs_transaction *cur_trans,
2ff7e61e 4388 struct btrfs_fs_info *fs_info)
c79a1751
LB
4389{
4390 struct btrfs_block_group_cache *cache;
4391
4392 spin_lock(&cur_trans->dirty_bgs_lock);
4393 while (!list_empty(&cur_trans->dirty_bgs)) {
4394 cache = list_first_entry(&cur_trans->dirty_bgs,
4395 struct btrfs_block_group_cache,
4396 dirty_list);
c79a1751
LB
4397
4398 if (!list_empty(&cache->io_list)) {
4399 spin_unlock(&cur_trans->dirty_bgs_lock);
4400 list_del_init(&cache->io_list);
4401 btrfs_cleanup_bg_io(cache);
4402 spin_lock(&cur_trans->dirty_bgs_lock);
4403 }
4404
4405 list_del_init(&cache->dirty_list);
4406 spin_lock(&cache->lock);
4407 cache->disk_cache_state = BTRFS_DC_ERROR;
4408 spin_unlock(&cache->lock);
4409
4410 spin_unlock(&cur_trans->dirty_bgs_lock);
4411 btrfs_put_block_group(cache);
4412 spin_lock(&cur_trans->dirty_bgs_lock);
4413 }
4414 spin_unlock(&cur_trans->dirty_bgs_lock);
4415
45ae2c18
NB
4416 /*
4417 * Refer to the definition of io_bgs member for details why it's safe
4418 * to use it without any locking
4419 */
c79a1751
LB
4420 while (!list_empty(&cur_trans->io_bgs)) {
4421 cache = list_first_entry(&cur_trans->io_bgs,
4422 struct btrfs_block_group_cache,
4423 io_list);
c79a1751
LB
4424
4425 list_del_init(&cache->io_list);
4426 spin_lock(&cache->lock);
4427 cache->disk_cache_state = BTRFS_DC_ERROR;
4428 spin_unlock(&cache->lock);
4429 btrfs_cleanup_bg_io(cache);
4430 }
4431}
4432
49b25e05 4433void btrfs_cleanup_one_transaction(struct btrfs_transaction *cur_trans,
2ff7e61e 4434 struct btrfs_fs_info *fs_info)
49b25e05 4435{
2ff7e61e 4436 btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
c79a1751
LB
4437 ASSERT(list_empty(&cur_trans->dirty_bgs));
4438 ASSERT(list_empty(&cur_trans->io_bgs));
4439
2ff7e61e 4440 btrfs_destroy_delayed_refs(cur_trans, fs_info);
49b25e05 4441
4a9d8bde 4442 cur_trans->state = TRANS_STATE_COMMIT_START;
0b246afa 4443 wake_up(&fs_info->transaction_blocked_wait);
49b25e05 4444
4a9d8bde 4445 cur_trans->state = TRANS_STATE_UNBLOCKED;
0b246afa 4446 wake_up(&fs_info->transaction_wait);
49b25e05 4447
ccdf9b30
JM
4448 btrfs_destroy_delayed_inodes(fs_info);
4449 btrfs_assert_delayed_root_empty(fs_info);
49b25e05 4450
2ff7e61e 4451 btrfs_destroy_marked_extents(fs_info, &cur_trans->dirty_pages,
49b25e05 4452 EXTENT_DIRTY);
2ff7e61e 4453 btrfs_destroy_pinned_extent(fs_info,
0b246afa 4454 fs_info->pinned_extents);
49b25e05 4455
4a9d8bde
MX
4456 cur_trans->state =TRANS_STATE_COMPLETED;
4457 wake_up(&cur_trans->commit_wait);
49b25e05
JM
4458}
4459
2ff7e61e 4460static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info)
acce952b 4461{
4462 struct btrfs_transaction *t;
acce952b 4463
0b246afa 4464 mutex_lock(&fs_info->transaction_kthread_mutex);
acce952b 4465
0b246afa
JM
4466 spin_lock(&fs_info->trans_lock);
4467 while (!list_empty(&fs_info->trans_list)) {
4468 t = list_first_entry(&fs_info->trans_list,
724e2315
JB
4469 struct btrfs_transaction, list);
4470 if (t->state >= TRANS_STATE_COMMIT_START) {
9b64f57d 4471 refcount_inc(&t->use_count);
0b246afa 4472 spin_unlock(&fs_info->trans_lock);
2ff7e61e 4473 btrfs_wait_for_commit(fs_info, t->transid);
724e2315 4474 btrfs_put_transaction(t);
0b246afa 4475 spin_lock(&fs_info->trans_lock);
724e2315
JB
4476 continue;
4477 }
0b246afa 4478 if (t == fs_info->running_transaction) {
724e2315 4479 t->state = TRANS_STATE_COMMIT_DOING;
0b246afa 4480 spin_unlock(&fs_info->trans_lock);
724e2315
JB
4481 /*
4482 * We wait for 0 num_writers since we don't hold a trans
4483 * handle open currently for this transaction.
4484 */
4485 wait_event(t->writer_wait,
4486 atomic_read(&t->num_writers) == 0);
4487 } else {
0b246afa 4488 spin_unlock(&fs_info->trans_lock);
724e2315 4489 }
2ff7e61e 4490 btrfs_cleanup_one_transaction(t, fs_info);
4a9d8bde 4491
0b246afa
JM
4492 spin_lock(&fs_info->trans_lock);
4493 if (t == fs_info->running_transaction)
4494 fs_info->running_transaction = NULL;
acce952b 4495 list_del_init(&t->list);
0b246afa 4496 spin_unlock(&fs_info->trans_lock);
acce952b 4497
724e2315 4498 btrfs_put_transaction(t);
2ff7e61e 4499 trace_btrfs_transaction_commit(fs_info->tree_root);
0b246afa 4500 spin_lock(&fs_info->trans_lock);
724e2315 4501 }
0b246afa
JM
4502 spin_unlock(&fs_info->trans_lock);
4503 btrfs_destroy_all_ordered_extents(fs_info);
ccdf9b30
JM
4504 btrfs_destroy_delayed_inodes(fs_info);
4505 btrfs_assert_delayed_root_empty(fs_info);
2ff7e61e 4506 btrfs_destroy_pinned_extent(fs_info, fs_info->pinned_extents);
0b246afa
JM
4507 btrfs_destroy_all_delalloc_inodes(fs_info);
4508 mutex_unlock(&fs_info->transaction_kthread_mutex);
acce952b 4509
4510 return 0;
4511}
4512
c6100a4b
JB
4513static struct btrfs_fs_info *btree_fs_info(void *private_data)
4514{
4515 struct inode *inode = private_data;
4516 return btrfs_sb(inode->i_sb);
4517}
4518
e8c9f186 4519static const struct extent_io_ops btree_extent_io_ops = {
4d53dddb 4520 /* mandatory callbacks */
0b86a832 4521 .submit_bio_hook = btree_submit_bio_hook,
4d53dddb 4522 .readpage_end_io_hook = btree_readpage_end_io_hook,
239b14b3
CM
4523 /* note we're sharing with inode.c for the merge bio hook */
4524 .merge_bio_hook = btrfs_merge_bio_hook,
20a7db8a 4525 .readpage_io_failed_hook = btree_io_failed_hook,
c6100a4b
JB
4526 .set_range_writeback = btrfs_set_range_writeback,
4527 .tree_fs_info = btree_fs_info,
4d53dddb
DS
4528
4529 /* optional callbacks */
0da5468f 4530};