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