btrfs: make btrfs_super_block::log_root_transid deprecated
[linux-2.6-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>
fc7cbcd4 8#include <linux/radix-tree.h>
35b7e476 9#include <linux/writeback.h>
ce9adaa5 10#include <linux/workqueue.h>
a74a4b97 11#include <linux/kthread.h>
5a0e3ad6 12#include <linux/slab.h>
784b4e29 13#include <linux/migrate.h>
7a36ddec 14#include <linux/ratelimit.h>
6463fe58 15#include <linux/uuid.h>
803b2f54 16#include <linux/semaphore.h>
540adea3 17#include <linux/error-injection.h>
9678c543 18#include <linux/crc32c.h>
b89f6d1f 19#include <linux/sched/mm.h>
7e75bf3f 20#include <asm/unaligned.h>
6d97c6e3 21#include <crypto/hash.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"
21adbd5c 32#include "check-integrity.h"
606686ee 33#include "rcu-string.h"
8dabb742 34#include "dev-replace.h"
53b381b3 35#include "raid56.h"
5ac1d209 36#include "sysfs.h"
fcebe456 37#include "qgroup.h"
ebb8765b 38#include "compression.h"
557ea5dd 39#include "tree-checker.h"
fd708b81 40#include "ref-verify.h"
aac0023c 41#include "block-group.h"
b0643e59 42#include "discard.h"
f603bb94 43#include "space-info.h"
b70f5097 44#include "zoned.h"
139e8cd3 45#include "subpage.h"
eb60ceac 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
143bede5 54static void btrfs_destroy_ordered_extents(struct btrfs_root *root);
acce952b 55static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
2ff7e61e 56 struct btrfs_fs_info *fs_info);
143bede5 57static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root);
2ff7e61e 58static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
acce952b 59 struct extent_io_tree *dirty_pages,
60 int mark);
2ff7e61e 61static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
acce952b 62 struct extent_io_tree *pinned_extents);
2ff7e61e
JM
63static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info);
64static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info);
ce9adaa5 65
141386e1
JB
66static void btrfs_free_csum_hash(struct btrfs_fs_info *fs_info)
67{
68 if (fs_info->csum_shash)
69 crypto_free_shash(fs_info->csum_shash);
70}
71
d352ac68
CM
72/*
73 * async submit bios are used to offload expensive checksumming
74 * onto the worker threads. They checksum file and metadata bios
75 * just before they are sent down the IO stack.
76 */
44b8bd7e 77struct async_submit_bio {
8896a08d 78 struct inode *inode;
44b8bd7e 79 struct bio *bio;
a758781d 80 extent_submit_bio_start_t *submit_bio_start;
44b8bd7e 81 int mirror_num;
1941b64b
QW
82
83 /* Optional parameter for submit_bio_start used by direct io */
84 u64 dio_file_offset;
8b712842 85 struct btrfs_work work;
4e4cbee9 86 blk_status_t status;
44b8bd7e
CM
87};
88
85d4e461
CM
89/*
90 * Lockdep class keys for extent_buffer->lock's in this root. For a given
91 * eb, the lockdep key is determined by the btrfs_root it belongs to and
92 * the level the eb occupies in the tree.
93 *
94 * Different roots are used for different purposes and may nest inside each
95 * other and they require separate keysets. As lockdep keys should be
96 * static, assign keysets according to the purpose of the root as indicated
4fd786e6
MT
97 * by btrfs_root->root_key.objectid. This ensures that all special purpose
98 * roots have separate keysets.
4008c04a 99 *
85d4e461
CM
100 * Lock-nesting across peer nodes is always done with the immediate parent
101 * node locked thus preventing deadlock. As lockdep doesn't know this, use
102 * subclass to avoid triggering lockdep warning in such cases.
4008c04a 103 *
85d4e461
CM
104 * The key is set by the readpage_end_io_hook after the buffer has passed
105 * csum validation but before the pages are unlocked. It is also set by
106 * btrfs_init_new_buffer on freshly allocated blocks.
4008c04a 107 *
85d4e461
CM
108 * We also add a check to make sure the highest level of the tree is the
109 * same as our lockdep setup here. If BTRFS_MAX_LEVEL changes, this code
110 * needs update as well.
4008c04a
CM
111 */
112#ifdef CONFIG_DEBUG_LOCK_ALLOC
113# if BTRFS_MAX_LEVEL != 8
114# error
115# endif
85d4e461 116
ab1405aa
DS
117#define DEFINE_LEVEL(stem, level) \
118 .names[level] = "btrfs-" stem "-0" #level,
119
120#define DEFINE_NAME(stem) \
121 DEFINE_LEVEL(stem, 0) \
122 DEFINE_LEVEL(stem, 1) \
123 DEFINE_LEVEL(stem, 2) \
124 DEFINE_LEVEL(stem, 3) \
125 DEFINE_LEVEL(stem, 4) \
126 DEFINE_LEVEL(stem, 5) \
127 DEFINE_LEVEL(stem, 6) \
128 DEFINE_LEVEL(stem, 7)
129
85d4e461
CM
130static struct btrfs_lockdep_keyset {
131 u64 id; /* root objectid */
ab1405aa 132 /* Longest entry: btrfs-free-space-00 */
387824af
DS
133 char names[BTRFS_MAX_LEVEL][20];
134 struct lock_class_key keys[BTRFS_MAX_LEVEL];
85d4e461 135} btrfs_lockdep_keysets[] = {
ab1405aa
DS
136 { .id = BTRFS_ROOT_TREE_OBJECTID, DEFINE_NAME("root") },
137 { .id = BTRFS_EXTENT_TREE_OBJECTID, DEFINE_NAME("extent") },
138 { .id = BTRFS_CHUNK_TREE_OBJECTID, DEFINE_NAME("chunk") },
139 { .id = BTRFS_DEV_TREE_OBJECTID, DEFINE_NAME("dev") },
ab1405aa
DS
140 { .id = BTRFS_CSUM_TREE_OBJECTID, DEFINE_NAME("csum") },
141 { .id = BTRFS_QUOTA_TREE_OBJECTID, DEFINE_NAME("quota") },
142 { .id = BTRFS_TREE_LOG_OBJECTID, DEFINE_NAME("log") },
143 { .id = BTRFS_TREE_RELOC_OBJECTID, DEFINE_NAME("treloc") },
144 { .id = BTRFS_DATA_RELOC_TREE_OBJECTID, DEFINE_NAME("dreloc") },
145 { .id = BTRFS_UUID_TREE_OBJECTID, DEFINE_NAME("uuid") },
146 { .id = BTRFS_FREE_SPACE_TREE_OBJECTID, DEFINE_NAME("free-space") },
147 { .id = 0, DEFINE_NAME("tree") },
4008c04a 148};
85d4e461 149
ab1405aa
DS
150#undef DEFINE_LEVEL
151#undef DEFINE_NAME
85d4e461
CM
152
153void btrfs_set_buffer_lockdep_class(u64 objectid, struct extent_buffer *eb,
154 int level)
155{
156 struct btrfs_lockdep_keyset *ks;
157
158 BUG_ON(level >= ARRAY_SIZE(ks->keys));
159
160 /* find the matching keyset, id 0 is the default entry */
161 for (ks = btrfs_lockdep_keysets; ks->id; ks++)
162 if (ks->id == objectid)
163 break;
164
165 lockdep_set_class_and_name(&eb->lock,
166 &ks->keys[level], ks->names[level]);
167}
168
4008c04a
CM
169#endif
170
d352ac68 171/*
2996e1f8 172 * Compute the csum of a btree block and store the result to provided buffer.
d352ac68 173 */
c67b3892 174static void csum_tree_block(struct extent_buffer *buf, u8 *result)
19c00ddc 175{
d5178578 176 struct btrfs_fs_info *fs_info = buf->fs_info;
7280305e 177 const int num_pages = num_extent_pages(buf);
a26663e7 178 const int first_page_part = min_t(u32, PAGE_SIZE, fs_info->nodesize);
d5178578 179 SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
19c00ddc 180 char *kaddr;
e9be5a30 181 int i;
d5178578
JT
182
183 shash->tfm = fs_info->csum_shash;
184 crypto_shash_init(shash);
a26663e7 185 kaddr = page_address(buf->pages[0]) + offset_in_page(buf->start);
e9be5a30 186 crypto_shash_update(shash, kaddr + BTRFS_CSUM_SIZE,
a26663e7 187 first_page_part - BTRFS_CSUM_SIZE);
19c00ddc 188
e9be5a30
DS
189 for (i = 1; i < num_pages; i++) {
190 kaddr = page_address(buf->pages[i]);
191 crypto_shash_update(shash, kaddr, PAGE_SIZE);
19c00ddc 192 }
71a63551 193 memset(result, 0, BTRFS_CSUM_SIZE);
d5178578 194 crypto_shash_final(shash, result);
19c00ddc
CM
195}
196
d352ac68
CM
197/*
198 * we can't consider a given block up to date unless the transid of the
199 * block matches the transid in the parent node's pointer. This is how we
200 * detect blocks that either didn't get written at all or got written
201 * in the wrong place.
202 */
1259ab75 203static int verify_parent_transid(struct extent_io_tree *io_tree,
b9fab919
CM
204 struct extent_buffer *eb, u64 parent_transid,
205 int atomic)
1259ab75 206{
2ac55d41 207 struct extent_state *cached_state = NULL;
1259ab75
CM
208 int ret;
209
210 if (!parent_transid || btrfs_header_generation(eb) == parent_transid)
211 return 0;
212
b9fab919
CM
213 if (atomic)
214 return -EAGAIN;
215
2ac55d41 216 lock_extent_bits(io_tree, eb->start, eb->start + eb->len - 1,
ff13db41 217 &cached_state);
0b32f4bb 218 if (extent_buffer_uptodate(eb) &&
1259ab75
CM
219 btrfs_header_generation(eb) == parent_transid) {
220 ret = 0;
221 goto out;
222 }
94647322
DS
223 btrfs_err_rl(eb->fs_info,
224 "parent transid verify failed on %llu wanted %llu found %llu",
225 eb->start,
29549aec 226 parent_transid, btrfs_header_generation(eb));
1259ab75 227 ret = 1;
35b22c19 228 clear_extent_buffer_uptodate(eb);
33958dc6 229out:
2ac55d41 230 unlock_extent_cached(io_tree, eb->start, eb->start + eb->len - 1,
e43bbe5e 231 &cached_state);
1259ab75 232 return ret;
1259ab75
CM
233}
234
e7e16f48
JT
235static bool btrfs_supported_super_csum(u16 csum_type)
236{
237 switch (csum_type) {
238 case BTRFS_CSUM_TYPE_CRC32:
3951e7f0 239 case BTRFS_CSUM_TYPE_XXHASH:
3831bf00 240 case BTRFS_CSUM_TYPE_SHA256:
352ae07b 241 case BTRFS_CSUM_TYPE_BLAKE2:
e7e16f48
JT
242 return true;
243 default:
244 return false;
245 }
246}
247
1104a885
DS
248/*
249 * Return 0 if the superblock checksum type matches the checksum value of that
250 * algorithm. Pass the raw disk superblock data.
251 */
ab8d0fc4
JM
252static int btrfs_check_super_csum(struct btrfs_fs_info *fs_info,
253 char *raw_disk_sb)
1104a885
DS
254{
255 struct btrfs_super_block *disk_sb =
256 (struct btrfs_super_block *)raw_disk_sb;
51bce6c9 257 char result[BTRFS_CSUM_SIZE];
d5178578
JT
258 SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
259
260 shash->tfm = fs_info->csum_shash;
1104a885 261
51bce6c9
JT
262 /*
263 * The super_block structure does not span the whole
264 * BTRFS_SUPER_INFO_SIZE range, we expect that the unused space is
265 * filled with zeros and is included in the checksum.
266 */
fd08001f
EB
267 crypto_shash_digest(shash, raw_disk_sb + BTRFS_CSUM_SIZE,
268 BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE, result);
1104a885 269
55fc29be 270 if (memcmp(disk_sb->csum, result, fs_info->csum_size))
51bce6c9 271 return 1;
1104a885 272
e7e16f48 273 return 0;
1104a885
DS
274}
275
e064d5e9 276int btrfs_verify_level_key(struct extent_buffer *eb, int level,
448de471 277 struct btrfs_key *first_key, u64 parent_transid)
581c1760 278{
e064d5e9 279 struct btrfs_fs_info *fs_info = eb->fs_info;
581c1760
QW
280 int found_level;
281 struct btrfs_key found_key;
282 int ret;
283
284 found_level = btrfs_header_level(eb);
285 if (found_level != level) {
63489055
QW
286 WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
287 KERN_ERR "BTRFS: tree level check failed\n");
581c1760
QW
288 btrfs_err(fs_info,
289"tree level mismatch detected, bytenr=%llu level expected=%u has=%u",
290 eb->start, level, found_level);
581c1760
QW
291 return -EIO;
292 }
293
294 if (!first_key)
295 return 0;
296
5d41be6f
QW
297 /*
298 * For live tree block (new tree blocks in current transaction),
299 * we need proper lock context to avoid race, which is impossible here.
300 * So we only checks tree blocks which is read from disk, whose
301 * generation <= fs_info->last_trans_committed.
302 */
303 if (btrfs_header_generation(eb) > fs_info->last_trans_committed)
304 return 0;
62fdaa52
QW
305
306 /* We have @first_key, so this @eb must have at least one item */
307 if (btrfs_header_nritems(eb) == 0) {
308 btrfs_err(fs_info,
309 "invalid tree nritems, bytenr=%llu nritems=0 expect >0",
310 eb->start);
311 WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
312 return -EUCLEAN;
313 }
314
581c1760
QW
315 if (found_level)
316 btrfs_node_key_to_cpu(eb, &found_key, 0);
317 else
318 btrfs_item_key_to_cpu(eb, &found_key, 0);
319 ret = btrfs_comp_cpu_keys(first_key, &found_key);
320
581c1760 321 if (ret) {
63489055
QW
322 WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
323 KERN_ERR "BTRFS: tree first key check failed\n");
581c1760 324 btrfs_err(fs_info,
ff76a864
LB
325"tree first key mismatch detected, bytenr=%llu parent_transid=%llu key expected=(%llu,%u,%llu) has=(%llu,%u,%llu)",
326 eb->start, parent_transid, first_key->objectid,
327 first_key->type, first_key->offset,
328 found_key.objectid, found_key.type,
329 found_key.offset);
581c1760 330 }
581c1760
QW
331 return ret;
332}
333
d352ac68
CM
334/*
335 * helper to read a given tree block, doing retries as required when
336 * the checksums don't match and we have alternate mirrors to try.
581c1760
QW
337 *
338 * @parent_transid: expected transid, skip check if 0
339 * @level: expected level, mandatory check
340 * @first_key: expected key of first slot, skip check if NULL
d352ac68 341 */
6a2e9dc4
FM
342int btrfs_read_extent_buffer(struct extent_buffer *eb,
343 u64 parent_transid, int level,
344 struct btrfs_key *first_key)
f188591e 345{
5ab12d1f 346 struct btrfs_fs_info *fs_info = eb->fs_info;
f188591e 347 struct extent_io_tree *io_tree;
ea466794 348 int failed = 0;
f188591e
CM
349 int ret;
350 int num_copies = 0;
351 int mirror_num = 0;
ea466794 352 int failed_mirror = 0;
f188591e 353
0b246afa 354 io_tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
f188591e 355 while (1) {
f8397d69 356 clear_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
c2ccfbc6 357 ret = read_extent_buffer_pages(eb, WAIT_COMPLETE, mirror_num);
256dd1bb 358 if (!ret) {
581c1760 359 if (verify_parent_transid(io_tree, eb,
b9fab919 360 parent_transid, 0))
256dd1bb 361 ret = -EIO;
e064d5e9 362 else if (btrfs_verify_level_key(eb, level,
448de471 363 first_key, parent_transid))
581c1760
QW
364 ret = -EUCLEAN;
365 else
366 break;
256dd1bb 367 }
d397712b 368
0b246afa 369 num_copies = btrfs_num_copies(fs_info,
f188591e 370 eb->start, eb->len);
4235298e 371 if (num_copies == 1)
ea466794 372 break;
4235298e 373
5cf1ab56
JB
374 if (!failed_mirror) {
375 failed = 1;
376 failed_mirror = eb->read_mirror;
377 }
378
f188591e 379 mirror_num++;
ea466794
JB
380 if (mirror_num == failed_mirror)
381 mirror_num++;
382
4235298e 383 if (mirror_num > num_copies)
ea466794 384 break;
f188591e 385 }
ea466794 386
c0901581 387 if (failed && !ret && failed_mirror)
20a1fbf9 388 btrfs_repair_eb_io_failure(eb, failed_mirror);
ea466794
JB
389
390 return ret;
f188591e 391}
19c00ddc 392
eca0f6f6
QW
393static int csum_one_extent_buffer(struct extent_buffer *eb)
394{
395 struct btrfs_fs_info *fs_info = eb->fs_info;
396 u8 result[BTRFS_CSUM_SIZE];
397 int ret;
398
399 ASSERT(memcmp_extent_buffer(eb, fs_info->fs_devices->metadata_uuid,
400 offsetof(struct btrfs_header, fsid),
401 BTRFS_FSID_SIZE) == 0);
402 csum_tree_block(eb, result);
403
404 if (btrfs_header_level(eb))
405 ret = btrfs_check_node(eb);
406 else
407 ret = btrfs_check_leaf_full(eb);
408
3777369f
QW
409 if (ret < 0)
410 goto error;
411
412 /*
413 * Also check the generation, the eb reached here must be newer than
414 * last committed. Or something seriously wrong happened.
415 */
416 if (unlikely(btrfs_header_generation(eb) <= fs_info->last_trans_committed)) {
417 ret = -EUCLEAN;
eca0f6f6 418 btrfs_err(fs_info,
3777369f
QW
419 "block=%llu bad generation, have %llu expect > %llu",
420 eb->start, btrfs_header_generation(eb),
421 fs_info->last_trans_committed);
422 goto error;
eca0f6f6
QW
423 }
424 write_extent_buffer(eb, result, 0, fs_info->csum_size);
425
426 return 0;
3777369f
QW
427
428error:
429 btrfs_print_tree(eb, 0);
430 btrfs_err(fs_info, "block=%llu write time tree block corruption detected",
431 eb->start);
432 WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
433 return ret;
eca0f6f6
QW
434}
435
436/* Checksum all dirty extent buffers in one bio_vec */
437static int csum_dirty_subpage_buffers(struct btrfs_fs_info *fs_info,
438 struct bio_vec *bvec)
439{
440 struct page *page = bvec->bv_page;
441 u64 bvec_start = page_offset(page) + bvec->bv_offset;
442 u64 cur;
443 int ret = 0;
444
445 for (cur = bvec_start; cur < bvec_start + bvec->bv_len;
446 cur += fs_info->nodesize) {
447 struct extent_buffer *eb;
448 bool uptodate;
449
450 eb = find_extent_buffer(fs_info, cur);
451 uptodate = btrfs_subpage_test_uptodate(fs_info, page, cur,
452 fs_info->nodesize);
453
01cd3909 454 /* A dirty eb shouldn't disappear from buffer_radix */
eca0f6f6
QW
455 if (WARN_ON(!eb))
456 return -EUCLEAN;
457
458 if (WARN_ON(cur != btrfs_header_bytenr(eb))) {
459 free_extent_buffer(eb);
460 return -EUCLEAN;
461 }
462 if (WARN_ON(!uptodate)) {
463 free_extent_buffer(eb);
464 return -EUCLEAN;
465 }
466
467 ret = csum_one_extent_buffer(eb);
468 free_extent_buffer(eb);
469 if (ret < 0)
470 return ret;
471 }
472 return ret;
473}
474
d352ac68 475/*
ac303b69
QW
476 * Checksum a dirty tree block before IO. This has extra checks to make sure
477 * we only fill in the checksum field in the first page of a multi-page block.
478 * For subpage extent buffers we need bvec to also read the offset in the page.
d352ac68 479 */
ac303b69 480static int csum_dirty_buffer(struct btrfs_fs_info *fs_info, struct bio_vec *bvec)
19c00ddc 481{
ac303b69 482 struct page *page = bvec->bv_page;
4eee4fa4 483 u64 start = page_offset(page);
19c00ddc 484 u64 found_start;
19c00ddc 485 struct extent_buffer *eb;
eca0f6f6 486
fbca46eb 487 if (fs_info->nodesize < PAGE_SIZE)
eca0f6f6 488 return csum_dirty_subpage_buffers(fs_info, bvec);
f188591e 489
4f2de97a
JB
490 eb = (struct extent_buffer *)page->private;
491 if (page != eb->pages[0])
492 return 0;
0f805531 493
19c00ddc 494 found_start = btrfs_header_bytenr(eb);
d3575156
NA
495
496 if (test_bit(EXTENT_BUFFER_NO_CHECK, &eb->bflags)) {
497 WARN_ON(found_start != 0);
498 return 0;
499 }
500
0f805531
AL
501 /*
502 * Please do not consolidate these warnings into a single if.
503 * It is useful to know what went wrong.
504 */
505 if (WARN_ON(found_start != start))
506 return -EUCLEAN;
507 if (WARN_ON(!PageUptodate(page)))
508 return -EUCLEAN;
509
eca0f6f6 510 return csum_one_extent_buffer(eb);
19c00ddc
CM
511}
512
b0c9b3b0 513static int check_tree_block_fsid(struct extent_buffer *eb)
2b82032c 514{
b0c9b3b0 515 struct btrfs_fs_info *fs_info = eb->fs_info;
944d3f9f 516 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
44880fdc 517 u8 fsid[BTRFS_FSID_SIZE];
944d3f9f 518 u8 *metadata_uuid;
2b82032c 519
9a8658e3
DS
520 read_extent_buffer(eb, fsid, offsetof(struct btrfs_header, fsid),
521 BTRFS_FSID_SIZE);
944d3f9f
NB
522 /*
523 * Checking the incompat flag is only valid for the current fs. For
524 * seed devices it's forbidden to have their uuid changed so reading
525 * ->fsid in this case is fine
526 */
527 if (btrfs_fs_incompat(fs_info, METADATA_UUID))
528 metadata_uuid = fs_devices->metadata_uuid;
529 else
530 metadata_uuid = fs_devices->fsid;
531
532 if (!memcmp(fsid, metadata_uuid, BTRFS_FSID_SIZE))
533 return 0;
534
535 list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list)
536 if (!memcmp(fsid, seed_devs->fsid, BTRFS_FSID_SIZE))
537 return 0;
538
539 return 1;
2b82032c
YZ
540}
541
77bf40a2
QW
542/* Do basic extent buffer checks at read time */
543static int validate_extent_buffer(struct extent_buffer *eb)
ce9adaa5 544{
77bf40a2 545 struct btrfs_fs_info *fs_info = eb->fs_info;
ce9adaa5 546 u64 found_start;
77bf40a2
QW
547 const u32 csum_size = fs_info->csum_size;
548 u8 found_level;
2996e1f8 549 u8 result[BTRFS_CSUM_SIZE];
dfd29eed 550 const u8 *header_csum;
77bf40a2 551 int ret = 0;
ea466794 552
ce9adaa5 553 found_start = btrfs_header_bytenr(eb);
727011e0 554 if (found_start != eb->start) {
893bf4b1
SY
555 btrfs_err_rl(fs_info, "bad tree block start, want %llu have %llu",
556 eb->start, found_start);
f188591e 557 ret = -EIO;
77bf40a2 558 goto out;
ce9adaa5 559 }
b0c9b3b0 560 if (check_tree_block_fsid(eb)) {
02873e43
ZL
561 btrfs_err_rl(fs_info, "bad fsid on block %llu",
562 eb->start);
1259ab75 563 ret = -EIO;
77bf40a2 564 goto out;
1259ab75 565 }
ce9adaa5 566 found_level = btrfs_header_level(eb);
1c24c3ce 567 if (found_level >= BTRFS_MAX_LEVEL) {
893bf4b1
SY
568 btrfs_err(fs_info, "bad tree block level %d on %llu",
569 (int)btrfs_header_level(eb), eb->start);
1c24c3ce 570 ret = -EIO;
77bf40a2 571 goto out;
1c24c3ce 572 }
ce9adaa5 573
c67b3892 574 csum_tree_block(eb, result);
dfd29eed
DS
575 header_csum = page_address(eb->pages[0]) +
576 get_eb_offset_in_page(eb, offsetof(struct btrfs_header, csum));
a826d6dc 577
dfd29eed 578 if (memcmp(result, header_csum, csum_size) != 0) {
2996e1f8 579 btrfs_warn_rl(fs_info,
ff14aa79
DS
580 "checksum verify failed on %llu wanted " CSUM_FMT " found " CSUM_FMT " level %d",
581 eb->start,
dfd29eed 582 CSUM_FMT_VALUE(csum_size, header_csum),
35be8851
JT
583 CSUM_FMT_VALUE(csum_size, result),
584 btrfs_header_level(eb));
2996e1f8 585 ret = -EUCLEAN;
77bf40a2 586 goto out;
2996e1f8
JT
587 }
588
a826d6dc
JB
589 /*
590 * If this is a leaf block and it is corrupt, set the corrupt bit so
591 * that we don't try and read the other copies of this block, just
592 * return -EIO.
593 */
1c4360ee 594 if (found_level == 0 && btrfs_check_leaf_full(eb)) {
a826d6dc
JB
595 set_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
596 ret = -EIO;
597 }
ce9adaa5 598
813fd1dc 599 if (found_level > 0 && btrfs_check_node(eb))
053ab70f
LB
600 ret = -EIO;
601
0b32f4bb
JB
602 if (!ret)
603 set_extent_buffer_uptodate(eb);
75391f0d
QW
604 else
605 btrfs_err(fs_info,
606 "block=%llu read time tree block corruption detected",
607 eb->start);
77bf40a2
QW
608out:
609 return ret;
610}
611
371cdc07
QW
612static int validate_subpage_buffer(struct page *page, u64 start, u64 end,
613 int mirror)
614{
615 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
616 struct extent_buffer *eb;
617 bool reads_done;
618 int ret = 0;
619
620 /*
621 * We don't allow bio merge for subpage metadata read, so we should
622 * only get one eb for each endio hook.
623 */
624 ASSERT(end == start + fs_info->nodesize - 1);
625 ASSERT(PagePrivate(page));
626
627 eb = find_extent_buffer(fs_info, start);
628 /*
629 * When we are reading one tree block, eb must have been inserted into
630 * the radix tree. If not, something is wrong.
631 */
632 ASSERT(eb);
633
634 reads_done = atomic_dec_and_test(&eb->io_pages);
635 /* Subpage read must finish in page read */
636 ASSERT(reads_done);
637
638 eb->read_mirror = mirror;
639 if (test_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags)) {
640 ret = -EIO;
641 goto err;
642 }
643 ret = validate_extent_buffer(eb);
644 if (ret < 0)
645 goto err;
646
371cdc07
QW
647 set_extent_buffer_uptodate(eb);
648
649 free_extent_buffer(eb);
650 return ret;
651err:
652 /*
653 * end_bio_extent_readpage decrements io_pages in case of error,
654 * make sure it has something to decrement.
655 */
656 atomic_inc(&eb->io_pages);
657 clear_extent_buffer_uptodate(eb);
658 free_extent_buffer(eb);
659 return ret;
660}
661
c3a3b19b 662int btrfs_validate_metadata_buffer(struct btrfs_bio *bbio,
77bf40a2
QW
663 struct page *page, u64 start, u64 end,
664 int mirror)
665{
666 struct extent_buffer *eb;
667 int ret = 0;
668 int reads_done;
669
670 ASSERT(page->private);
371cdc07 671
fbca46eb 672 if (btrfs_sb(page->mapping->host->i_sb)->nodesize < PAGE_SIZE)
371cdc07
QW
673 return validate_subpage_buffer(page, start, end, mirror);
674
77bf40a2
QW
675 eb = (struct extent_buffer *)page->private;
676
677 /*
678 * The pending IO might have been the only thing that kept this buffer
679 * in memory. Make sure we have a ref for all this other checks
680 */
681 atomic_inc(&eb->refs);
682
683 reads_done = atomic_dec_and_test(&eb->io_pages);
684 if (!reads_done)
685 goto err;
686
687 eb->read_mirror = mirror;
688 if (test_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags)) {
689 ret = -EIO;
690 goto err;
691 }
692 ret = validate_extent_buffer(eb);
ce9adaa5 693err:
53b381b3
DW
694 if (ret) {
695 /*
696 * our io error hook is going to dec the io pages
697 * again, we have to make sure it has something
698 * to decrement
699 */
700 atomic_inc(&eb->io_pages);
0b32f4bb 701 clear_extent_buffer_uptodate(eb);
53b381b3 702 }
0b32f4bb 703 free_extent_buffer(eb);
77bf40a2 704
f188591e 705 return ret;
ce9adaa5
CM
706}
707
4a69a410
CM
708static void run_one_async_start(struct btrfs_work *work)
709{
4a69a410 710 struct async_submit_bio *async;
4e4cbee9 711 blk_status_t ret;
4a69a410
CM
712
713 async = container_of(work, struct async_submit_bio, work);
1941b64b
QW
714 ret = async->submit_bio_start(async->inode, async->bio,
715 async->dio_file_offset);
79787eaa 716 if (ret)
4e4cbee9 717 async->status = ret;
4a69a410
CM
718}
719
06ea01b1
DS
720/*
721 * In order to insert checksums into the metadata in large chunks, we wait
722 * until bio submission time. All the pages in the bio are checksummed and
723 * sums are attached onto the ordered extent record.
724 *
725 * At IO completion time the csums attached on the ordered extent record are
726 * inserted into the tree.
727 */
4a69a410 728static void run_one_async_done(struct btrfs_work *work)
8b712842 729{
8b712842 730 struct async_submit_bio *async;
06ea01b1
DS
731 struct inode *inode;
732 blk_status_t ret;
8b712842
CM
733
734 async = container_of(work, struct async_submit_bio, work);
8896a08d 735 inode = async->inode;
4854ddd0 736
bb7ab3b9 737 /* If an error occurred we just want to clean up the bio and move on */
4e4cbee9
CH
738 if (async->status) {
739 async->bio->bi_status = async->status;
4246a0b6 740 bio_endio(async->bio);
79787eaa
JM
741 return;
742 }
743
ec39f769
CM
744 /*
745 * All of the bios that pass through here are from async helpers.
746 * Use REQ_CGROUP_PUNT to issue them from the owning cgroup's context.
747 * This changes nothing when cgroups aren't in use.
748 */
749 async->bio->bi_opf |= REQ_CGROUP_PUNT;
08635bae 750 ret = btrfs_map_bio(btrfs_sb(inode->i_sb), async->bio, async->mirror_num);
06ea01b1
DS
751 if (ret) {
752 async->bio->bi_status = ret;
753 bio_endio(async->bio);
754 }
4a69a410
CM
755}
756
757static void run_one_async_free(struct btrfs_work *work)
758{
759 struct async_submit_bio *async;
760
761 async = container_of(work, struct async_submit_bio, work);
8b712842
CM
762 kfree(async);
763}
764
8896a08d 765blk_status_t btrfs_wq_submit_bio(struct inode *inode, struct bio *bio,
a6f5e39e 766 int mirror_num, u64 dio_file_offset,
e288c080 767 extent_submit_bio_start_t *submit_bio_start)
44b8bd7e 768{
8896a08d 769 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
44b8bd7e
CM
770 struct async_submit_bio *async;
771
772 async = kmalloc(sizeof(*async), GFP_NOFS);
773 if (!async)
4e4cbee9 774 return BLK_STS_RESOURCE;
44b8bd7e 775
8896a08d 776 async->inode = inode;
44b8bd7e
CM
777 async->bio = bio;
778 async->mirror_num = mirror_num;
4a69a410 779 async->submit_bio_start = submit_bio_start;
4a69a410 780
a0cac0ec
OS
781 btrfs_init_work(&async->work, run_one_async_start, run_one_async_done,
782 run_one_async_free);
4a69a410 783
1941b64b 784 async->dio_file_offset = dio_file_offset;
8c8bee1d 785
4e4cbee9 786 async->status = 0;
79787eaa 787
67f055c7 788 if (op_is_sync(bio->bi_opf))
a31b4a43
CH
789 btrfs_queue_work(fs_info->hipri_workers, &async->work);
790 else
791 btrfs_queue_work(fs_info->workers, &async->work);
44b8bd7e
CM
792 return 0;
793}
794
4e4cbee9 795static blk_status_t btree_csum_one_bio(struct bio *bio)
ce3ed71a 796{
2c30c71b 797 struct bio_vec *bvec;
ce3ed71a 798 struct btrfs_root *root;
2b070cfe 799 int ret = 0;
6dc4f100 800 struct bvec_iter_all iter_all;
ce3ed71a 801
c09abff8 802 ASSERT(!bio_flagged(bio, BIO_CLONED));
2b070cfe 803 bio_for_each_segment_all(bvec, bio, iter_all) {
ce3ed71a 804 root = BTRFS_I(bvec->bv_page->mapping->host)->root;
ac303b69 805 ret = csum_dirty_buffer(root->fs_info, bvec);
79787eaa
JM
806 if (ret)
807 break;
ce3ed71a 808 }
2c30c71b 809
4e4cbee9 810 return errno_to_blk_status(ret);
ce3ed71a
CM
811}
812
8896a08d 813static blk_status_t btree_submit_bio_start(struct inode *inode, struct bio *bio,
1941b64b 814 u64 dio_file_offset)
22c59948 815{
8b712842
CM
816 /*
817 * when we're called for a write, we're already in the async
5443be45 818 * submission context. Just jump into btrfs_map_bio
8b712842 819 */
79787eaa 820 return btree_csum_one_bio(bio);
4a69a410 821}
22c59948 822
f4dcfb30 823static bool should_async_write(struct btrfs_fs_info *fs_info,
9b4e675a 824 struct btrfs_inode *bi)
de0022b9 825{
4eef29ef 826 if (btrfs_is_zoned(fs_info))
f4dcfb30 827 return false;
6300463b 828 if (atomic_read(&bi->sync_writers))
f4dcfb30 829 return false;
9b4e675a 830 if (test_bit(BTRFS_FS_CSUM_IMPL_FAST, &fs_info->flags))
f4dcfb30
JT
831 return false;
832 return true;
de0022b9
JB
833}
834
94d9e11b 835void btrfs_submit_metadata_bio(struct inode *inode, struct bio *bio, int mirror_num)
44b8bd7e 836{
0b246afa 837 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4e4cbee9 838 blk_status_t ret;
cad321ad 839
08a6f464
CH
840 bio->bi_opf |= REQ_META;
841
cfe94440 842 if (btrfs_op(bio) != BTRFS_MAP_WRITE) {
d7b9416f 843 ret = btrfs_map_bio(fs_info, bio, mirror_num);
f4dcfb30 844 } else if (!should_async_write(fs_info, BTRFS_I(inode))) {
de0022b9 845 ret = btree_csum_one_bio(bio);
94d9e11b
CH
846 if (!ret)
847 ret = btrfs_map_bio(fs_info, bio, mirror_num);
61891923
SB
848 } else {
849 /*
850 * kthread helpers are used to submit writes so that
851 * checksumming can happen in parallel across all CPUs
852 */
8896a08d 853 ret = btrfs_wq_submit_bio(inode, bio, mirror_num, 0,
a6f5e39e 854 btree_submit_bio_start);
44b8bd7e 855 }
d313d7a3 856
94d9e11b
CH
857 if (ret) {
858 bio->bi_status = ret;
859 bio_endio(bio);
860 }
44b8bd7e
CM
861}
862
3dd1462e 863#ifdef CONFIG_MIGRATION
784b4e29 864static int btree_migratepage(struct address_space *mapping,
a6bc32b8
MG
865 struct page *newpage, struct page *page,
866 enum migrate_mode mode)
784b4e29
CM
867{
868 /*
869 * we can't safely write a btree page from here,
870 * we haven't done the locking hook
871 */
872 if (PageDirty(page))
873 return -EAGAIN;
874 /*
875 * Buffers may be managed in a filesystem specific way.
876 * We must have no buffers or drop them.
877 */
878 if (page_has_private(page) &&
879 !try_to_release_page(page, GFP_KERNEL))
880 return -EAGAIN;
a6bc32b8 881 return migrate_page(mapping, newpage, page, mode);
784b4e29 882}
3dd1462e 883#endif
784b4e29 884
0da5468f
CM
885
886static int btree_writepages(struct address_space *mapping,
887 struct writeback_control *wbc)
888{
e2d84521
MX
889 struct btrfs_fs_info *fs_info;
890 int ret;
891
d8d5f3e1 892 if (wbc->sync_mode == WB_SYNC_NONE) {
448d640b
CM
893
894 if (wbc->for_kupdate)
895 return 0;
896
e2d84521 897 fs_info = BTRFS_I(mapping->host)->root->fs_info;
b9473439 898 /* this is a bit racy, but that's ok */
d814a491
EL
899 ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
900 BTRFS_DIRTY_METADATA_THRESH,
901 fs_info->dirty_metadata_batch);
e2d84521 902 if (ret < 0)
793955bc 903 return 0;
793955bc 904 }
0b32f4bb 905 return btree_write_cache_pages(mapping, wbc);
0da5468f
CM
906}
907
f913cff3 908static bool btree_release_folio(struct folio *folio, gfp_t gfp_flags)
5f39d397 909{
f913cff3
MWO
910 if (folio_test_writeback(folio) || folio_test_dirty(folio))
911 return false;
0c4e538b 912
f913cff3 913 return try_release_extent_buffer(&folio->page);
d98237b3
CM
914}
915
895586eb
MWO
916static void btree_invalidate_folio(struct folio *folio, size_t offset,
917 size_t length)
d98237b3 918{
d1310b2e 919 struct extent_io_tree *tree;
895586eb
MWO
920 tree = &BTRFS_I(folio->mapping->host)->io_tree;
921 extent_invalidate_folio(tree, folio, offset);
f913cff3 922 btree_release_folio(folio, GFP_NOFS);
895586eb
MWO
923 if (folio_get_private(folio)) {
924 btrfs_warn(BTRFS_I(folio->mapping->host)->root->fs_info,
925 "folio private not zero on folio %llu",
926 (unsigned long long)folio_pos(folio));
927 folio_detach_private(folio);
9ad6b7bc 928 }
d98237b3
CM
929}
930
bb146eb2 931#ifdef DEBUG
0079c3b1
MWO
932static bool btree_dirty_folio(struct address_space *mapping,
933 struct folio *folio)
934{
935 struct btrfs_fs_info *fs_info = btrfs_sb(mapping->host->i_sb);
139e8cd3 936 struct btrfs_subpage *subpage;
0b32f4bb 937 struct extent_buffer *eb;
139e8cd3 938 int cur_bit = 0;
0079c3b1 939 u64 page_start = folio_pos(folio);
139e8cd3
QW
940
941 if (fs_info->sectorsize == PAGE_SIZE) {
0079c3b1 942 eb = folio_get_private(folio);
139e8cd3
QW
943 BUG_ON(!eb);
944 BUG_ON(!test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
945 BUG_ON(!atomic_read(&eb->refs));
49d0c642 946 btrfs_assert_tree_write_locked(eb);
0079c3b1 947 return filemap_dirty_folio(mapping, folio);
139e8cd3 948 }
0079c3b1 949 subpage = folio_get_private(folio);
139e8cd3
QW
950
951 ASSERT(subpage->dirty_bitmap);
952 while (cur_bit < BTRFS_SUBPAGE_BITMAP_SIZE) {
953 unsigned long flags;
954 u64 cur;
955 u16 tmp = (1 << cur_bit);
956
957 spin_lock_irqsave(&subpage->lock, flags);
958 if (!(tmp & subpage->dirty_bitmap)) {
959 spin_unlock_irqrestore(&subpage->lock, flags);
960 cur_bit++;
961 continue;
962 }
963 spin_unlock_irqrestore(&subpage->lock, flags);
964 cur = page_start + cur_bit * fs_info->sectorsize;
0b32f4bb 965
139e8cd3
QW
966 eb = find_extent_buffer(fs_info, cur);
967 ASSERT(eb);
968 ASSERT(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
969 ASSERT(atomic_read(&eb->refs));
49d0c642 970 btrfs_assert_tree_write_locked(eb);
139e8cd3
QW
971 free_extent_buffer(eb);
972
973 cur_bit += (fs_info->nodesize >> fs_info->sectorsize_bits);
974 }
0079c3b1 975 return filemap_dirty_folio(mapping, folio);
0b32f4bb 976}
0079c3b1
MWO
977#else
978#define btree_dirty_folio filemap_dirty_folio
979#endif
0b32f4bb 980
7f09410b 981static const struct address_space_operations btree_aops = {
0da5468f 982 .writepages = btree_writepages,
f913cff3 983 .release_folio = btree_release_folio,
895586eb 984 .invalidate_folio = btree_invalidate_folio,
5a92bc88 985#ifdef CONFIG_MIGRATION
784b4e29 986 .migratepage = btree_migratepage,
5a92bc88 987#endif
0079c3b1 988 .dirty_folio = btree_dirty_folio,
d98237b3
CM
989};
990
2ff7e61e
JM
991struct extent_buffer *btrfs_find_create_tree_block(
992 struct btrfs_fs_info *fs_info,
3fbaf258
JB
993 u64 bytenr, u64 owner_root,
994 int level)
0999df54 995{
0b246afa
JM
996 if (btrfs_is_testing(fs_info))
997 return alloc_test_extent_buffer(fs_info, bytenr);
3fbaf258 998 return alloc_extent_buffer(fs_info, bytenr, owner_root, level);
0999df54
CM
999}
1000
581c1760
QW
1001/*
1002 * Read tree block at logical address @bytenr and do variant basic but critical
1003 * verification.
1004 *
1b7ec85e 1005 * @owner_root: the objectid of the root owner for this block.
581c1760
QW
1006 * @parent_transid: expected transid of this tree block, skip check if 0
1007 * @level: expected level, mandatory check
1008 * @first_key: expected key in slot 0, skip check if NULL
1009 */
2ff7e61e 1010struct extent_buffer *read_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr,
1b7ec85e
JB
1011 u64 owner_root, u64 parent_transid,
1012 int level, struct btrfs_key *first_key)
0999df54
CM
1013{
1014 struct extent_buffer *buf = NULL;
0999df54
CM
1015 int ret;
1016
3fbaf258 1017 buf = btrfs_find_create_tree_block(fs_info, bytenr, owner_root, level);
c871b0f2
LB
1018 if (IS_ERR(buf))
1019 return buf;
0999df54 1020
6a2e9dc4 1021 ret = btrfs_read_extent_buffer(buf, parent_transid, level, first_key);
0f0fe8f7 1022 if (ret) {
537f38f0 1023 free_extent_buffer_stale(buf);
64c043de 1024 return ERR_PTR(ret);
0f0fe8f7 1025 }
88c602ab
QW
1026 if (btrfs_check_eb_owner(buf, owner_root)) {
1027 free_extent_buffer_stale(buf);
1028 return ERR_PTR(-EUCLEAN);
1029 }
5f39d397 1030 return buf;
ce9adaa5 1031
eb60ceac
CM
1032}
1033
6a884d7d 1034void btrfs_clean_tree_block(struct extent_buffer *buf)
ed2ff2cb 1035{
6a884d7d 1036 struct btrfs_fs_info *fs_info = buf->fs_info;
55c69072 1037 if (btrfs_header_generation(buf) ==
e2d84521 1038 fs_info->running_transaction->transid) {
49d0c642 1039 btrfs_assert_tree_write_locked(buf);
b4ce94de 1040
b9473439 1041 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &buf->bflags)) {
104b4e51
NB
1042 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
1043 -buf->len,
1044 fs_info->dirty_metadata_batch);
ed7b63eb
JB
1045 clear_extent_buffer_dirty(buf);
1046 }
925baedd 1047 }
5f39d397
CM
1048}
1049
da17066c 1050static void __setup_root(struct btrfs_root *root, struct btrfs_fs_info *fs_info,
143bede5 1051 u64 objectid)
d97e63b6 1052{
7c0260ee 1053 bool dummy = test_bit(BTRFS_FS_STATE_DUMMY_FS_INFO, &fs_info->fs_state);
2e608bd1
JB
1054
1055 memset(&root->root_key, 0, sizeof(root->root_key));
1056 memset(&root->root_item, 0, sizeof(root->root_item));
1057 memset(&root->defrag_progress, 0, sizeof(root->defrag_progress));
96dfcb46 1058 root->fs_info = fs_info;
2e608bd1 1059 root->root_key.objectid = objectid;
cfaa7295 1060 root->node = NULL;
a28ec197 1061 root->commit_root = NULL;
27cdeb70 1062 root->state = 0;
abed4aaa 1063 RB_CLEAR_NODE(&root->rb_node);
0b86a832 1064
0f7d52f4 1065 root->last_trans = 0;
6b8fad57 1066 root->free_objectid = 0;
eb73c1b7 1067 root->nr_delalloc_inodes = 0;
199c2a9c 1068 root->nr_ordered_extents = 0;
6bef4d31 1069 root->inode_tree = RB_ROOT;
088aea3b 1070 INIT_RADIX_TREE(&root->delayed_nodes_tree, GFP_ATOMIC);
2e608bd1
JB
1071
1072 btrfs_init_root_block_rsv(root);
0b86a832
CM
1073
1074 INIT_LIST_HEAD(&root->dirty_list);
5d4f98a2 1075 INIT_LIST_HEAD(&root->root_list);
eb73c1b7
MX
1076 INIT_LIST_HEAD(&root->delalloc_inodes);
1077 INIT_LIST_HEAD(&root->delalloc_root);
199c2a9c
MX
1078 INIT_LIST_HEAD(&root->ordered_extents);
1079 INIT_LIST_HEAD(&root->ordered_root);
d2311e69 1080 INIT_LIST_HEAD(&root->reloc_dirty_list);
2ab28f32
JB
1081 INIT_LIST_HEAD(&root->logged_list[0]);
1082 INIT_LIST_HEAD(&root->logged_list[1]);
5d4f98a2 1083 spin_lock_init(&root->inode_lock);
eb73c1b7 1084 spin_lock_init(&root->delalloc_lock);
199c2a9c 1085 spin_lock_init(&root->ordered_extent_lock);
f0486c68 1086 spin_lock_init(&root->accounting_lock);
2ab28f32
JB
1087 spin_lock_init(&root->log_extents_lock[0]);
1088 spin_lock_init(&root->log_extents_lock[1]);
8287475a 1089 spin_lock_init(&root->qgroup_meta_rsv_lock);
a2135011 1090 mutex_init(&root->objectid_mutex);
e02119d5 1091 mutex_init(&root->log_mutex);
31f3d255 1092 mutex_init(&root->ordered_extent_mutex);
573bfb72 1093 mutex_init(&root->delalloc_mutex);
c53e9653 1094 init_waitqueue_head(&root->qgroup_flush_wait);
7237f183
YZ
1095 init_waitqueue_head(&root->log_writer_wait);
1096 init_waitqueue_head(&root->log_commit_wait[0]);
1097 init_waitqueue_head(&root->log_commit_wait[1]);
8b050d35
MX
1098 INIT_LIST_HEAD(&root->log_ctxs[0]);
1099 INIT_LIST_HEAD(&root->log_ctxs[1]);
7237f183
YZ
1100 atomic_set(&root->log_commit[0], 0);
1101 atomic_set(&root->log_commit[1], 0);
1102 atomic_set(&root->log_writers, 0);
2ecb7923 1103 atomic_set(&root->log_batch, 0);
0700cea7 1104 refcount_set(&root->refs, 1);
8ecebf4d 1105 atomic_set(&root->snapshot_force_cow, 0);
eede2bf3 1106 atomic_set(&root->nr_swapfiles, 0);
7237f183 1107 root->log_transid = 0;
d1433deb 1108 root->log_transid_committed = -1;
257c62e1 1109 root->last_log_commit = 0;
2e608bd1 1110 root->anon_dev = 0;
e289f03e 1111 if (!dummy) {
43eb5f29
QW
1112 extent_io_tree_init(fs_info, &root->dirty_log_pages,
1113 IO_TREE_ROOT_DIRTY_LOG_PAGES, NULL);
e289f03e
FM
1114 extent_io_tree_init(fs_info, &root->log_csum_range,
1115 IO_TREE_LOG_CSUM_RANGE, NULL);
1116 }
017e5369 1117
5f3ab90a 1118 spin_lock_init(&root->root_item_lock);
370a11b8 1119 btrfs_qgroup_init_swapped_blocks(&root->swapped_blocks);
bd647ce3
JB
1120#ifdef CONFIG_BTRFS_DEBUG
1121 INIT_LIST_HEAD(&root->leak_list);
fc7cbcd4 1122 spin_lock(&fs_info->fs_roots_radix_lock);
bd647ce3 1123 list_add_tail(&root->leak_list, &fs_info->allocated_roots);
fc7cbcd4 1124 spin_unlock(&fs_info->fs_roots_radix_lock);
bd647ce3 1125#endif
3768f368
CM
1126}
1127
74e4d827 1128static struct btrfs_root *btrfs_alloc_root(struct btrfs_fs_info *fs_info,
96dfcb46 1129 u64 objectid, gfp_t flags)
6f07e42e 1130{
74e4d827 1131 struct btrfs_root *root = kzalloc(sizeof(*root), flags);
6f07e42e 1132 if (root)
96dfcb46 1133 __setup_root(root, fs_info, objectid);
6f07e42e
AV
1134 return root;
1135}
1136
06ea65a3
JB
1137#ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
1138/* Should only be used by the testing infrastructure */
da17066c 1139struct btrfs_root *btrfs_alloc_dummy_root(struct btrfs_fs_info *fs_info)
06ea65a3
JB
1140{
1141 struct btrfs_root *root;
1142
7c0260ee
JM
1143 if (!fs_info)
1144 return ERR_PTR(-EINVAL);
1145
96dfcb46 1146 root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID, GFP_KERNEL);
06ea65a3
JB
1147 if (!root)
1148 return ERR_PTR(-ENOMEM);
da17066c 1149
b9ef22de 1150 /* We don't use the stripesize in selftest, set it as sectorsize */
faa2dbf0 1151 root->alloc_bytenr = 0;
06ea65a3
JB
1152
1153 return root;
1154}
1155#endif
1156
abed4aaa
JB
1157static int global_root_cmp(struct rb_node *a_node, const struct rb_node *b_node)
1158{
1159 const struct btrfs_root *a = rb_entry(a_node, struct btrfs_root, rb_node);
1160 const struct btrfs_root *b = rb_entry(b_node, struct btrfs_root, rb_node);
1161
1162 return btrfs_comp_cpu_keys(&a->root_key, &b->root_key);
1163}
1164
1165static int global_root_key_cmp(const void *k, const struct rb_node *node)
1166{
1167 const struct btrfs_key *key = k;
1168 const struct btrfs_root *root = rb_entry(node, struct btrfs_root, rb_node);
1169
1170 return btrfs_comp_cpu_keys(key, &root->root_key);
1171}
1172
1173int btrfs_global_root_insert(struct btrfs_root *root)
1174{
1175 struct btrfs_fs_info *fs_info = root->fs_info;
1176 struct rb_node *tmp;
1177
1178 write_lock(&fs_info->global_root_lock);
1179 tmp = rb_find_add(&root->rb_node, &fs_info->global_root_tree, global_root_cmp);
1180 write_unlock(&fs_info->global_root_lock);
1181 ASSERT(!tmp);
1182
1183 return tmp ? -EEXIST : 0;
1184}
1185
1186void btrfs_global_root_delete(struct btrfs_root *root)
1187{
1188 struct btrfs_fs_info *fs_info = root->fs_info;
1189
1190 write_lock(&fs_info->global_root_lock);
1191 rb_erase(&root->rb_node, &fs_info->global_root_tree);
1192 write_unlock(&fs_info->global_root_lock);
1193}
1194
1195struct btrfs_root *btrfs_global_root(struct btrfs_fs_info *fs_info,
1196 struct btrfs_key *key)
1197{
1198 struct rb_node *node;
1199 struct btrfs_root *root = NULL;
1200
1201 read_lock(&fs_info->global_root_lock);
1202 node = rb_find(key, &fs_info->global_root_tree, global_root_key_cmp);
1203 if (node)
1204 root = container_of(node, struct btrfs_root, rb_node);
1205 read_unlock(&fs_info->global_root_lock);
1206
1207 return root;
1208}
1209
f7238e50
JB
1210static u64 btrfs_global_root_id(struct btrfs_fs_info *fs_info, u64 bytenr)
1211{
1212 struct btrfs_block_group *block_group;
1213 u64 ret;
1214
1215 if (!btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))
1216 return 0;
1217
1218 if (bytenr)
1219 block_group = btrfs_lookup_block_group(fs_info, bytenr);
1220 else
1221 block_group = btrfs_lookup_first_block_group(fs_info, bytenr);
1222 ASSERT(block_group);
1223 if (!block_group)
1224 return 0;
1225 ret = block_group->global_root_id;
1226 btrfs_put_block_group(block_group);
1227
1228 return ret;
1229}
1230
abed4aaa
JB
1231struct btrfs_root *btrfs_csum_root(struct btrfs_fs_info *fs_info, u64 bytenr)
1232{
1233 struct btrfs_key key = {
1234 .objectid = BTRFS_CSUM_TREE_OBJECTID,
1235 .type = BTRFS_ROOT_ITEM_KEY,
f7238e50 1236 .offset = btrfs_global_root_id(fs_info, bytenr),
abed4aaa
JB
1237 };
1238
1239 return btrfs_global_root(fs_info, &key);
1240}
1241
1242struct btrfs_root *btrfs_extent_root(struct btrfs_fs_info *fs_info, u64 bytenr)
1243{
1244 struct btrfs_key key = {
1245 .objectid = BTRFS_EXTENT_TREE_OBJECTID,
1246 .type = BTRFS_ROOT_ITEM_KEY,
f7238e50 1247 .offset = btrfs_global_root_id(fs_info, bytenr),
abed4aaa
JB
1248 };
1249
1250 return btrfs_global_root(fs_info, &key);
1251}
1252
20897f5c 1253struct btrfs_root *btrfs_create_tree(struct btrfs_trans_handle *trans,
20897f5c
AJ
1254 u64 objectid)
1255{
9b7a2440 1256 struct btrfs_fs_info *fs_info = trans->fs_info;
20897f5c
AJ
1257 struct extent_buffer *leaf;
1258 struct btrfs_root *tree_root = fs_info->tree_root;
1259 struct btrfs_root *root;
1260 struct btrfs_key key;
b89f6d1f 1261 unsigned int nofs_flag;
20897f5c 1262 int ret = 0;
20897f5c 1263
b89f6d1f
FM
1264 /*
1265 * We're holding a transaction handle, so use a NOFS memory allocation
1266 * context to avoid deadlock if reclaim happens.
1267 */
1268 nofs_flag = memalloc_nofs_save();
96dfcb46 1269 root = btrfs_alloc_root(fs_info, objectid, GFP_KERNEL);
b89f6d1f 1270 memalloc_nofs_restore(nofs_flag);
20897f5c
AJ
1271 if (!root)
1272 return ERR_PTR(-ENOMEM);
1273
20897f5c
AJ
1274 root->root_key.objectid = objectid;
1275 root->root_key.type = BTRFS_ROOT_ITEM_KEY;
1276 root->root_key.offset = 0;
1277
9631e4cc
JB
1278 leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0,
1279 BTRFS_NESTING_NORMAL);
20897f5c
AJ
1280 if (IS_ERR(leaf)) {
1281 ret = PTR_ERR(leaf);
1dd05682 1282 leaf = NULL;
8a6a87cd 1283 goto fail_unlock;
20897f5c
AJ
1284 }
1285
20897f5c 1286 root->node = leaf;
20897f5c
AJ
1287 btrfs_mark_buffer_dirty(leaf);
1288
1289 root->commit_root = btrfs_root_node(root);
27cdeb70 1290 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
20897f5c 1291
f944d2cb
DS
1292 btrfs_set_root_flags(&root->root_item, 0);
1293 btrfs_set_root_limit(&root->root_item, 0);
20897f5c
AJ
1294 btrfs_set_root_bytenr(&root->root_item, leaf->start);
1295 btrfs_set_root_generation(&root->root_item, trans->transid);
1296 btrfs_set_root_level(&root->root_item, 0);
1297 btrfs_set_root_refs(&root->root_item, 1);
1298 btrfs_set_root_used(&root->root_item, leaf->len);
1299 btrfs_set_root_last_snapshot(&root->root_item, 0);
1300 btrfs_set_root_dirid(&root->root_item, 0);
33d85fda 1301 if (is_fstree(objectid))
807fc790
AS
1302 generate_random_guid(root->root_item.uuid);
1303 else
1304 export_guid(root->root_item.uuid, &guid_null);
c8422684 1305 btrfs_set_root_drop_level(&root->root_item, 0);
20897f5c 1306
8a6a87cd
BB
1307 btrfs_tree_unlock(leaf);
1308
20897f5c
AJ
1309 key.objectid = objectid;
1310 key.type = BTRFS_ROOT_ITEM_KEY;
1311 key.offset = 0;
1312 ret = btrfs_insert_root(trans, tree_root, &key, &root->root_item);
1313 if (ret)
1314 goto fail;
1315
1dd05682
TI
1316 return root;
1317
8a6a87cd 1318fail_unlock:
8c38938c 1319 if (leaf)
1dd05682 1320 btrfs_tree_unlock(leaf);
8a6a87cd 1321fail:
00246528 1322 btrfs_put_root(root);
20897f5c 1323
1dd05682 1324 return ERR_PTR(ret);
20897f5c
AJ
1325}
1326
7237f183
YZ
1327static struct btrfs_root *alloc_log_tree(struct btrfs_trans_handle *trans,
1328 struct btrfs_fs_info *fs_info)
0f7d52f4
CM
1329{
1330 struct btrfs_root *root;
e02119d5 1331
96dfcb46 1332 root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID, GFP_NOFS);
e02119d5 1333 if (!root)
7237f183 1334 return ERR_PTR(-ENOMEM);
e02119d5 1335
e02119d5
CM
1336 root->root_key.objectid = BTRFS_TREE_LOG_OBJECTID;
1337 root->root_key.type = BTRFS_ROOT_ITEM_KEY;
1338 root->root_key.offset = BTRFS_TREE_LOG_OBJECTID;
27cdeb70 1339
6ab6ebb7
NA
1340 return root;
1341}
1342
1343int btrfs_alloc_log_tree_node(struct btrfs_trans_handle *trans,
1344 struct btrfs_root *root)
1345{
1346 struct extent_buffer *leaf;
1347
7237f183 1348 /*
92a7cc42 1349 * DON'T set SHAREABLE bit for log trees.
27cdeb70 1350 *
92a7cc42
QW
1351 * Log trees are not exposed to user space thus can't be snapshotted,
1352 * and they go away before a real commit is actually done.
1353 *
1354 * They do store pointers to file data extents, and those reference
1355 * counts still get updated (along with back refs to the log tree).
7237f183 1356 */
e02119d5 1357
4d75f8a9 1358 leaf = btrfs_alloc_tree_block(trans, root, 0, BTRFS_TREE_LOG_OBJECTID,
9631e4cc 1359 NULL, 0, 0, 0, BTRFS_NESTING_NORMAL);
6ab6ebb7
NA
1360 if (IS_ERR(leaf))
1361 return PTR_ERR(leaf);
e02119d5 1362
7237f183 1363 root->node = leaf;
e02119d5 1364
e02119d5
CM
1365 btrfs_mark_buffer_dirty(root->node);
1366 btrfs_tree_unlock(root->node);
6ab6ebb7
NA
1367
1368 return 0;
7237f183
YZ
1369}
1370
1371int btrfs_init_log_root_tree(struct btrfs_trans_handle *trans,
1372 struct btrfs_fs_info *fs_info)
1373{
1374 struct btrfs_root *log_root;
1375
1376 log_root = alloc_log_tree(trans, fs_info);
1377 if (IS_ERR(log_root))
1378 return PTR_ERR(log_root);
6ab6ebb7 1379
3ddebf27
NA
1380 if (!btrfs_is_zoned(fs_info)) {
1381 int ret = btrfs_alloc_log_tree_node(trans, log_root);
1382
1383 if (ret) {
1384 btrfs_put_root(log_root);
1385 return ret;
1386 }
6ab6ebb7
NA
1387 }
1388
7237f183
YZ
1389 WARN_ON(fs_info->log_root_tree);
1390 fs_info->log_root_tree = log_root;
1391 return 0;
1392}
1393
1394int btrfs_add_log_tree(struct btrfs_trans_handle *trans,
1395 struct btrfs_root *root)
1396{
0b246afa 1397 struct btrfs_fs_info *fs_info = root->fs_info;
7237f183
YZ
1398 struct btrfs_root *log_root;
1399 struct btrfs_inode_item *inode_item;
6ab6ebb7 1400 int ret;
7237f183 1401
0b246afa 1402 log_root = alloc_log_tree(trans, fs_info);
7237f183
YZ
1403 if (IS_ERR(log_root))
1404 return PTR_ERR(log_root);
1405
6ab6ebb7
NA
1406 ret = btrfs_alloc_log_tree_node(trans, log_root);
1407 if (ret) {
1408 btrfs_put_root(log_root);
1409 return ret;
1410 }
1411
7237f183
YZ
1412 log_root->last_trans = trans->transid;
1413 log_root->root_key.offset = root->root_key.objectid;
1414
1415 inode_item = &log_root->root_item.inode;
3cae210f
QW
1416 btrfs_set_stack_inode_generation(inode_item, 1);
1417 btrfs_set_stack_inode_size(inode_item, 3);
1418 btrfs_set_stack_inode_nlink(inode_item, 1);
da17066c 1419 btrfs_set_stack_inode_nbytes(inode_item,
0b246afa 1420 fs_info->nodesize);
3cae210f 1421 btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
7237f183 1422
5d4f98a2 1423 btrfs_set_root_node(&log_root->root_item, log_root->node);
7237f183
YZ
1424
1425 WARN_ON(root->log_root);
1426 root->log_root = log_root;
1427 root->log_transid = 0;
d1433deb 1428 root->log_transid_committed = -1;
257c62e1 1429 root->last_log_commit = 0;
e02119d5
CM
1430 return 0;
1431}
1432
49d11bea
JB
1433static struct btrfs_root *read_tree_root_path(struct btrfs_root *tree_root,
1434 struct btrfs_path *path,
1435 struct btrfs_key *key)
e02119d5
CM
1436{
1437 struct btrfs_root *root;
1438 struct btrfs_fs_info *fs_info = tree_root->fs_info;
84234f3a 1439 u64 generation;
cb517eab 1440 int ret;
581c1760 1441 int level;
0f7d52f4 1442
96dfcb46 1443 root = btrfs_alloc_root(fs_info, key->objectid, GFP_NOFS);
49d11bea
JB
1444 if (!root)
1445 return ERR_PTR(-ENOMEM);
0f7d52f4 1446
cb517eab
MX
1447 ret = btrfs_find_root(tree_root, key, path,
1448 &root->root_item, &root->root_key);
0f7d52f4 1449 if (ret) {
13a8a7c8
YZ
1450 if (ret > 0)
1451 ret = -ENOENT;
49d11bea 1452 goto fail;
0f7d52f4 1453 }
13a8a7c8 1454
84234f3a 1455 generation = btrfs_root_generation(&root->root_item);
581c1760 1456 level = btrfs_root_level(&root->root_item);
2ff7e61e
JM
1457 root->node = read_tree_block(fs_info,
1458 btrfs_root_bytenr(&root->root_item),
1b7ec85e 1459 key->objectid, generation, level, NULL);
64c043de
LB
1460 if (IS_ERR(root->node)) {
1461 ret = PTR_ERR(root->node);
8c38938c 1462 root->node = NULL;
49d11bea 1463 goto fail;
4eb150d6
QW
1464 }
1465 if (!btrfs_buffer_uptodate(root->node, generation, 0)) {
cb517eab 1466 ret = -EIO;
49d11bea 1467 goto fail;
416bc658 1468 }
88c602ab
QW
1469
1470 /*
1471 * For real fs, and not log/reloc trees, root owner must
1472 * match its root node owner
1473 */
1474 if (!test_bit(BTRFS_FS_STATE_DUMMY_FS_INFO, &fs_info->fs_state) &&
1475 root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID &&
1476 root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
1477 root->root_key.objectid != btrfs_header_owner(root->node)) {
1478 btrfs_crit(fs_info,
1479"root=%llu block=%llu, tree root owner mismatch, have %llu expect %llu",
1480 root->root_key.objectid, root->node->start,
1481 btrfs_header_owner(root->node),
1482 root->root_key.objectid);
1483 ret = -EUCLEAN;
1484 goto fail;
1485 }
5d4f98a2 1486 root->commit_root = btrfs_root_node(root);
cb517eab 1487 return root;
49d11bea 1488fail:
00246528 1489 btrfs_put_root(root);
49d11bea
JB
1490 return ERR_PTR(ret);
1491}
1492
1493struct btrfs_root *btrfs_read_tree_root(struct btrfs_root *tree_root,
1494 struct btrfs_key *key)
1495{
1496 struct btrfs_root *root;
1497 struct btrfs_path *path;
1498
1499 path = btrfs_alloc_path();
1500 if (!path)
1501 return ERR_PTR(-ENOMEM);
1502 root = read_tree_root_path(tree_root, path, key);
1503 btrfs_free_path(path);
1504
1505 return root;
cb517eab
MX
1506}
1507
2dfb1e43
QW
1508/*
1509 * Initialize subvolume root in-memory structure
1510 *
1511 * @anon_dev: anonymous device to attach to the root, if zero, allocate new
1512 */
1513static int btrfs_init_fs_root(struct btrfs_root *root, dev_t anon_dev)
cb517eab
MX
1514{
1515 int ret;
dcc3eb96 1516 unsigned int nofs_flag;
cb517eab 1517
dcc3eb96
NB
1518 /*
1519 * We might be called under a transaction (e.g. indirect backref
1520 * resolution) which could deadlock if it triggers memory reclaim
1521 */
1522 nofs_flag = memalloc_nofs_save();
1523 ret = btrfs_drew_lock_init(&root->snapshot_lock);
1524 memalloc_nofs_restore(nofs_flag);
1525 if (ret)
8257b2dc 1526 goto fail;
8257b2dc 1527
aeb935a4 1528 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID &&
37f00a6d 1529 !btrfs_is_data_reloc_root(root)) {
92a7cc42 1530 set_bit(BTRFS_ROOT_SHAREABLE, &root->state);
f39e4571
JB
1531 btrfs_check_and_init_root_item(&root->root_item);
1532 }
1533
851fd730
QW
1534 /*
1535 * Don't assign anonymous block device to roots that are not exposed to
1536 * userspace, the id pool is limited to 1M
1537 */
1538 if (is_fstree(root->root_key.objectid) &&
1539 btrfs_root_refs(&root->root_item) > 0) {
2dfb1e43
QW
1540 if (!anon_dev) {
1541 ret = get_anon_bdev(&root->anon_dev);
1542 if (ret)
1543 goto fail;
1544 } else {
1545 root->anon_dev = anon_dev;
1546 }
851fd730 1547 }
f32e48e9
CR
1548
1549 mutex_lock(&root->objectid_mutex);
453e4873 1550 ret = btrfs_init_root_free_objectid(root);
f32e48e9
CR
1551 if (ret) {
1552 mutex_unlock(&root->objectid_mutex);
876d2cf1 1553 goto fail;
f32e48e9
CR
1554 }
1555
6b8fad57 1556 ASSERT(root->free_objectid <= BTRFS_LAST_FREE_OBJECTID);
f32e48e9
CR
1557
1558 mutex_unlock(&root->objectid_mutex);
1559
cb517eab
MX
1560 return 0;
1561fail:
84db5ccf 1562 /* The caller is responsible to call btrfs_free_fs_root */
cb517eab
MX
1563 return ret;
1564}
1565
a98db0f3
JB
1566static struct btrfs_root *btrfs_lookup_fs_root(struct btrfs_fs_info *fs_info,
1567 u64 root_id)
cb517eab
MX
1568{
1569 struct btrfs_root *root;
1570
fc7cbcd4
DS
1571 spin_lock(&fs_info->fs_roots_radix_lock);
1572 root = radix_tree_lookup(&fs_info->fs_roots_radix,
1573 (unsigned long)root_id);
bc44d7c4 1574 if (root)
00246528 1575 root = btrfs_grab_root(root);
fc7cbcd4 1576 spin_unlock(&fs_info->fs_roots_radix_lock);
cb517eab
MX
1577 return root;
1578}
1579
49d11bea
JB
1580static struct btrfs_root *btrfs_get_global_root(struct btrfs_fs_info *fs_info,
1581 u64 objectid)
1582{
abed4aaa
JB
1583 struct btrfs_key key = {
1584 .objectid = objectid,
1585 .type = BTRFS_ROOT_ITEM_KEY,
1586 .offset = 0,
1587 };
1588
49d11bea
JB
1589 if (objectid == BTRFS_ROOT_TREE_OBJECTID)
1590 return btrfs_grab_root(fs_info->tree_root);
1591 if (objectid == BTRFS_EXTENT_TREE_OBJECTID)
abed4aaa 1592 return btrfs_grab_root(btrfs_global_root(fs_info, &key));
49d11bea
JB
1593 if (objectid == BTRFS_CHUNK_TREE_OBJECTID)
1594 return btrfs_grab_root(fs_info->chunk_root);
1595 if (objectid == BTRFS_DEV_TREE_OBJECTID)
1596 return btrfs_grab_root(fs_info->dev_root);
1597 if (objectid == BTRFS_CSUM_TREE_OBJECTID)
abed4aaa 1598 return btrfs_grab_root(btrfs_global_root(fs_info, &key));
49d11bea
JB
1599 if (objectid == BTRFS_QUOTA_TREE_OBJECTID)
1600 return btrfs_grab_root(fs_info->quota_root) ?
1601 fs_info->quota_root : ERR_PTR(-ENOENT);
1602 if (objectid == BTRFS_UUID_TREE_OBJECTID)
1603 return btrfs_grab_root(fs_info->uuid_root) ?
1604 fs_info->uuid_root : ERR_PTR(-ENOENT);
abed4aaa
JB
1605 if (objectid == BTRFS_FREE_SPACE_TREE_OBJECTID) {
1606 struct btrfs_root *root = btrfs_global_root(fs_info, &key);
1607
1608 return btrfs_grab_root(root) ? root : ERR_PTR(-ENOENT);
1609 }
49d11bea
JB
1610 return NULL;
1611}
1612
cb517eab
MX
1613int btrfs_insert_fs_root(struct btrfs_fs_info *fs_info,
1614 struct btrfs_root *root)
1615{
1616 int ret;
1617
fc7cbcd4
DS
1618 ret = radix_tree_preload(GFP_NOFS);
1619 if (ret)
1620 return ret;
1621
1622 spin_lock(&fs_info->fs_roots_radix_lock);
1623 ret = radix_tree_insert(&fs_info->fs_roots_radix,
1624 (unsigned long)root->root_key.objectid,
1625 root);
af01d2e5 1626 if (ret == 0) {
00246528 1627 btrfs_grab_root(root);
fc7cbcd4 1628 set_bit(BTRFS_ROOT_IN_RADIX, &root->state);
af01d2e5 1629 }
fc7cbcd4
DS
1630 spin_unlock(&fs_info->fs_roots_radix_lock);
1631 radix_tree_preload_end();
cb517eab
MX
1632
1633 return ret;
1634}
1635
bd647ce3
JB
1636void btrfs_check_leaked_roots(struct btrfs_fs_info *fs_info)
1637{
1638#ifdef CONFIG_BTRFS_DEBUG
1639 struct btrfs_root *root;
1640
1641 while (!list_empty(&fs_info->allocated_roots)) {
457f1864
JB
1642 char buf[BTRFS_ROOT_NAME_BUF_LEN];
1643
bd647ce3
JB
1644 root = list_first_entry(&fs_info->allocated_roots,
1645 struct btrfs_root, leak_list);
457f1864 1646 btrfs_err(fs_info, "leaked root %s refcount %d",
71008734 1647 btrfs_root_name(&root->root_key, buf),
bd647ce3
JB
1648 refcount_read(&root->refs));
1649 while (refcount_read(&root->refs) > 1)
00246528
JB
1650 btrfs_put_root(root);
1651 btrfs_put_root(root);
bd647ce3
JB
1652 }
1653#endif
1654}
1655
abed4aaa
JB
1656static void free_global_roots(struct btrfs_fs_info *fs_info)
1657{
1658 struct btrfs_root *root;
1659 struct rb_node *node;
1660
1661 while ((node = rb_first_postorder(&fs_info->global_root_tree)) != NULL) {
1662 root = rb_entry(node, struct btrfs_root, rb_node);
1663 rb_erase(&root->rb_node, &fs_info->global_root_tree);
1664 btrfs_put_root(root);
1665 }
1666}
1667
0d4b0463
JB
1668void btrfs_free_fs_info(struct btrfs_fs_info *fs_info)
1669{
141386e1
JB
1670 percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
1671 percpu_counter_destroy(&fs_info->delalloc_bytes);
5deb17e1 1672 percpu_counter_destroy(&fs_info->ordered_bytes);
141386e1
JB
1673 percpu_counter_destroy(&fs_info->dev_replace.bio_counter);
1674 btrfs_free_csum_hash(fs_info);
1675 btrfs_free_stripe_hash_table(fs_info);
1676 btrfs_free_ref_cache(fs_info);
0d4b0463
JB
1677 kfree(fs_info->balance_ctl);
1678 kfree(fs_info->delayed_root);
abed4aaa 1679 free_global_roots(fs_info);
00246528
JB
1680 btrfs_put_root(fs_info->tree_root);
1681 btrfs_put_root(fs_info->chunk_root);
1682 btrfs_put_root(fs_info->dev_root);
00246528
JB
1683 btrfs_put_root(fs_info->quota_root);
1684 btrfs_put_root(fs_info->uuid_root);
00246528 1685 btrfs_put_root(fs_info->fs_root);
aeb935a4 1686 btrfs_put_root(fs_info->data_reloc_root);
9c54e80d 1687 btrfs_put_root(fs_info->block_group_root);
bd647ce3 1688 btrfs_check_leaked_roots(fs_info);
3fd63727 1689 btrfs_extent_buffer_leak_debug_check(fs_info);
0d4b0463
JB
1690 kfree(fs_info->super_copy);
1691 kfree(fs_info->super_for_commit);
8481dd80 1692 kfree(fs_info->subpage_info);
0d4b0463
JB
1693 kvfree(fs_info);
1694}
1695
1696
2dfb1e43
QW
1697/*
1698 * Get an in-memory reference of a root structure.
1699 *
1700 * For essential trees like root/extent tree, we grab it from fs_info directly.
1701 * For subvolume trees, we check the cached filesystem roots first. If not
1702 * found, then read it from disk and add it to cached fs roots.
1703 *
1704 * Caller should release the root by calling btrfs_put_root() after the usage.
1705 *
1706 * NOTE: Reloc and log trees can't be read by this function as they share the
1707 * same root objectid.
1708 *
1709 * @objectid: root id
1710 * @anon_dev: preallocated anonymous block device number for new roots,
1711 * pass 0 for new allocation.
1712 * @check_ref: whether to check root item references, If true, return -ENOENT
1713 * for orphan roots
1714 */
1715static struct btrfs_root *btrfs_get_root_ref(struct btrfs_fs_info *fs_info,
1716 u64 objectid, dev_t anon_dev,
1717 bool check_ref)
5eda7b5e
CM
1718{
1719 struct btrfs_root *root;
381cf658 1720 struct btrfs_path *path;
1d4c08e0 1721 struct btrfs_key key;
5eda7b5e
CM
1722 int ret;
1723
49d11bea
JB
1724 root = btrfs_get_global_root(fs_info, objectid);
1725 if (root)
1726 return root;
4df27c4d 1727again:
56e9357a 1728 root = btrfs_lookup_fs_root(fs_info, objectid);
48475471 1729 if (root) {
2dfb1e43
QW
1730 /* Shouldn't get preallocated anon_dev for cached roots */
1731 ASSERT(!anon_dev);
bc44d7c4 1732 if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
00246528 1733 btrfs_put_root(root);
48475471 1734 return ERR_PTR(-ENOENT);
bc44d7c4 1735 }
5eda7b5e 1736 return root;
48475471 1737 }
5eda7b5e 1738
56e9357a
DS
1739 key.objectid = objectid;
1740 key.type = BTRFS_ROOT_ITEM_KEY;
1741 key.offset = (u64)-1;
1742 root = btrfs_read_tree_root(fs_info->tree_root, &key);
5eda7b5e
CM
1743 if (IS_ERR(root))
1744 return root;
3394e160 1745
c00869f1 1746 if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
cb517eab 1747 ret = -ENOENT;
581bb050 1748 goto fail;
35a30d7c 1749 }
581bb050 1750
2dfb1e43 1751 ret = btrfs_init_fs_root(root, anon_dev);
ac08aedf
CM
1752 if (ret)
1753 goto fail;
3394e160 1754
381cf658
DS
1755 path = btrfs_alloc_path();
1756 if (!path) {
1757 ret = -ENOMEM;
1758 goto fail;
1759 }
1d4c08e0
DS
1760 key.objectid = BTRFS_ORPHAN_OBJECTID;
1761 key.type = BTRFS_ORPHAN_ITEM_KEY;
56e9357a 1762 key.offset = objectid;
1d4c08e0
DS
1763
1764 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
381cf658 1765 btrfs_free_path(path);
d68fc57b
YZ
1766 if (ret < 0)
1767 goto fail;
1768 if (ret == 0)
27cdeb70 1769 set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state);
d68fc57b 1770
cb517eab 1771 ret = btrfs_insert_fs_root(fs_info, root);
0f7d52f4 1772 if (ret) {
168a2f77
JJB
1773 if (ret == -EEXIST) {
1774 btrfs_put_root(root);
4df27c4d 1775 goto again;
168a2f77 1776 }
4df27c4d 1777 goto fail;
0f7d52f4 1778 }
edbd8d4e 1779 return root;
4df27c4d 1780fail:
33fab972
FM
1781 /*
1782 * If our caller provided us an anonymous device, then it's his
143823cf 1783 * responsibility to free it in case we fail. So we have to set our
33fab972
FM
1784 * root's anon_dev to 0 to avoid a double free, once by btrfs_put_root()
1785 * and once again by our caller.
1786 */
1787 if (anon_dev)
1788 root->anon_dev = 0;
8c38938c 1789 btrfs_put_root(root);
4df27c4d 1790 return ERR_PTR(ret);
edbd8d4e
CM
1791}
1792
2dfb1e43
QW
1793/*
1794 * Get in-memory reference of a root structure
1795 *
1796 * @objectid: tree objectid
1797 * @check_ref: if set, verify that the tree exists and the item has at least
1798 * one reference
1799 */
1800struct btrfs_root *btrfs_get_fs_root(struct btrfs_fs_info *fs_info,
1801 u64 objectid, bool check_ref)
1802{
1803 return btrfs_get_root_ref(fs_info, objectid, 0, check_ref);
1804}
1805
1806/*
1807 * Get in-memory reference of a root structure, created as new, optionally pass
1808 * the anonymous block device id
1809 *
1810 * @objectid: tree objectid
1811 * @anon_dev: if zero, allocate a new anonymous block device or use the
1812 * parameter value
1813 */
1814struct btrfs_root *btrfs_get_new_fs_root(struct btrfs_fs_info *fs_info,
1815 u64 objectid, dev_t anon_dev)
1816{
1817 return btrfs_get_root_ref(fs_info, objectid, anon_dev, true);
1818}
1819
49d11bea
JB
1820/*
1821 * btrfs_get_fs_root_commit_root - return a root for the given objectid
1822 * @fs_info: the fs_info
1823 * @objectid: the objectid we need to lookup
1824 *
1825 * This is exclusively used for backref walking, and exists specifically because
1826 * of how qgroups does lookups. Qgroups will do a backref lookup at delayed ref
1827 * creation time, which means we may have to read the tree_root in order to look
1828 * up a fs root that is not in memory. If the root is not in memory we will
1829 * read the tree root commit root and look up the fs root from there. This is a
1830 * temporary root, it will not be inserted into the radix tree as it doesn't
1831 * have the most uptodate information, it'll simply be discarded once the
1832 * backref code is finished using the root.
1833 */
1834struct btrfs_root *btrfs_get_fs_root_commit_root(struct btrfs_fs_info *fs_info,
1835 struct btrfs_path *path,
1836 u64 objectid)
1837{
1838 struct btrfs_root *root;
1839 struct btrfs_key key;
1840
1841 ASSERT(path->search_commit_root && path->skip_locking);
1842
1843 /*
1844 * This can return -ENOENT if we ask for a root that doesn't exist, but
1845 * since this is called via the backref walking code we won't be looking
1846 * up a root that doesn't exist, unless there's corruption. So if root
1847 * != NULL just return it.
1848 */
1849 root = btrfs_get_global_root(fs_info, objectid);
1850 if (root)
1851 return root;
1852
1853 root = btrfs_lookup_fs_root(fs_info, objectid);
1854 if (root)
1855 return root;
1856
1857 key.objectid = objectid;
1858 key.type = BTRFS_ROOT_ITEM_KEY;
1859 key.offset = (u64)-1;
1860 root = read_tree_root_path(fs_info->tree_root, path, &key);
1861 btrfs_release_path(path);
1862
1863 return root;
1864}
1865
a74a4b97
CM
1866static int cleaner_kthread(void *arg)
1867{
0d031dc4 1868 struct btrfs_fs_info *fs_info = arg;
d0278245 1869 int again;
a74a4b97 1870
d6fd0ae2 1871 while (1) {
d0278245 1872 again = 0;
a74a4b97 1873
fd340d0f
JB
1874 set_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1875
d0278245 1876 /* Make the cleaner go to sleep early. */
2ff7e61e 1877 if (btrfs_need_cleaner_sleep(fs_info))
d0278245
MX
1878 goto sleep;
1879
90c711ab
ZB
1880 /*
1881 * Do not do anything if we might cause open_ctree() to block
1882 * before we have finished mounting the filesystem.
1883 */
0b246afa 1884 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
90c711ab
ZB
1885 goto sleep;
1886
0b246afa 1887 if (!mutex_trylock(&fs_info->cleaner_mutex))
d0278245
MX
1888 goto sleep;
1889
dc7f370c
MX
1890 /*
1891 * Avoid the problem that we change the status of the fs
1892 * during the above check and trylock.
1893 */
2ff7e61e 1894 if (btrfs_need_cleaner_sleep(fs_info)) {
0b246afa 1895 mutex_unlock(&fs_info->cleaner_mutex);
dc7f370c 1896 goto sleep;
76dda93c 1897 }
a74a4b97 1898
2ff7e61e 1899 btrfs_run_delayed_iputs(fs_info);
c2d6cb16 1900
33c44184 1901 again = btrfs_clean_one_deleted_snapshot(fs_info);
0b246afa 1902 mutex_unlock(&fs_info->cleaner_mutex);
d0278245
MX
1903
1904 /*
05323cd1
MX
1905 * The defragger has dealt with the R/O remount and umount,
1906 * needn't do anything special here.
d0278245 1907 */
0b246afa 1908 btrfs_run_defrag_inodes(fs_info);
67c5e7d4
FM
1909
1910 /*
f3372065 1911 * Acquires fs_info->reclaim_bgs_lock to avoid racing
67c5e7d4
FM
1912 * with relocation (btrfs_relocate_chunk) and relocation
1913 * acquires fs_info->cleaner_mutex (btrfs_relocate_block_group)
f3372065 1914 * after acquiring fs_info->reclaim_bgs_lock. So we
67c5e7d4
FM
1915 * can't hold, nor need to, fs_info->cleaner_mutex when deleting
1916 * unused block groups.
1917 */
0b246afa 1918 btrfs_delete_unused_bgs(fs_info);
18bb8bbf
JT
1919
1920 /*
1921 * Reclaim block groups in the reclaim_bgs list after we deleted
1922 * all unused block_groups. This possibly gives us some more free
1923 * space.
1924 */
1925 btrfs_reclaim_bgs(fs_info);
d0278245 1926sleep:
a0a1db70 1927 clear_and_wake_up_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
d6fd0ae2
OS
1928 if (kthread_should_park())
1929 kthread_parkme();
1930 if (kthread_should_stop())
1931 return 0;
838fe188 1932 if (!again) {
a74a4b97 1933 set_current_state(TASK_INTERRUPTIBLE);
d6fd0ae2 1934 schedule();
a74a4b97
CM
1935 __set_current_state(TASK_RUNNING);
1936 }
da288d28 1937 }
a74a4b97
CM
1938}
1939
1940static int transaction_kthread(void *arg)
1941{
1942 struct btrfs_root *root = arg;
0b246afa 1943 struct btrfs_fs_info *fs_info = root->fs_info;
a74a4b97
CM
1944 struct btrfs_trans_handle *trans;
1945 struct btrfs_transaction *cur;
8929ecfa 1946 u64 transid;
643900be 1947 time64_t delta;
a74a4b97 1948 unsigned long delay;
914b2007 1949 bool cannot_commit;
a74a4b97
CM
1950
1951 do {
914b2007 1952 cannot_commit = false;
ba1bc00f 1953 delay = msecs_to_jiffies(fs_info->commit_interval * 1000);
0b246afa 1954 mutex_lock(&fs_info->transaction_kthread_mutex);
a74a4b97 1955
0b246afa
JM
1956 spin_lock(&fs_info->trans_lock);
1957 cur = fs_info->running_transaction;
a74a4b97 1958 if (!cur) {
0b246afa 1959 spin_unlock(&fs_info->trans_lock);
a74a4b97
CM
1960 goto sleep;
1961 }
31153d81 1962
643900be 1963 delta = ktime_get_seconds() - cur->start_time;
fdfbf020
JB
1964 if (!test_and_clear_bit(BTRFS_FS_COMMIT_TRANS, &fs_info->flags) &&
1965 cur->state < TRANS_STATE_COMMIT_START &&
643900be 1966 delta < fs_info->commit_interval) {
0b246afa 1967 spin_unlock(&fs_info->trans_lock);
fb8a7e94
NB
1968 delay -= msecs_to_jiffies((delta - 1) * 1000);
1969 delay = min(delay,
1970 msecs_to_jiffies(fs_info->commit_interval * 1000));
a74a4b97
CM
1971 goto sleep;
1972 }
8929ecfa 1973 transid = cur->transid;
0b246afa 1974 spin_unlock(&fs_info->trans_lock);
56bec294 1975
79787eaa 1976 /* If the file system is aborted, this will always fail. */
354aa0fb 1977 trans = btrfs_attach_transaction(root);
914b2007 1978 if (IS_ERR(trans)) {
354aa0fb
MX
1979 if (PTR_ERR(trans) != -ENOENT)
1980 cannot_commit = true;
79787eaa 1981 goto sleep;
914b2007 1982 }
8929ecfa 1983 if (transid == trans->transid) {
3a45bb20 1984 btrfs_commit_transaction(trans);
8929ecfa 1985 } else {
3a45bb20 1986 btrfs_end_transaction(trans);
8929ecfa 1987 }
a74a4b97 1988sleep:
0b246afa
JM
1989 wake_up_process(fs_info->cleaner_kthread);
1990 mutex_unlock(&fs_info->transaction_kthread_mutex);
a74a4b97 1991
84961539 1992 if (BTRFS_FS_ERROR(fs_info))
2ff7e61e 1993 btrfs_cleanup_transaction(fs_info);
ce63f891 1994 if (!kthread_should_stop() &&
0b246afa 1995 (!btrfs_transaction_blocked(fs_info) ||
ce63f891 1996 cannot_commit))
bc5511d0 1997 schedule_timeout_interruptible(delay);
a74a4b97
CM
1998 } while (!kthread_should_stop());
1999 return 0;
2000}
2001
af31f5e5 2002/*
01f0f9da
NB
2003 * This will find the highest generation in the array of root backups. The
2004 * index of the highest array is returned, or -EINVAL if we can't find
2005 * anything.
af31f5e5
CM
2006 *
2007 * We check to make sure the array is valid by comparing the
2008 * generation of the latest root in the array with the generation
2009 * in the super block. If they don't match we pitch it.
2010 */
01f0f9da 2011static int find_newest_super_backup(struct btrfs_fs_info *info)
af31f5e5 2012{
01f0f9da 2013 const u64 newest_gen = btrfs_super_generation(info->super_copy);
af31f5e5 2014 u64 cur;
af31f5e5
CM
2015 struct btrfs_root_backup *root_backup;
2016 int i;
2017
2018 for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
2019 root_backup = info->super_copy->super_roots + i;
2020 cur = btrfs_backup_tree_root_gen(root_backup);
2021 if (cur == newest_gen)
01f0f9da 2022 return i;
af31f5e5
CM
2023 }
2024
01f0f9da 2025 return -EINVAL;
af31f5e5
CM
2026}
2027
af31f5e5
CM
2028/*
2029 * copy all the root pointers into the super backup array.
2030 * this will bump the backup pointer by one when it is
2031 * done
2032 */
2033static void backup_super_roots(struct btrfs_fs_info *info)
2034{
6ef108dd 2035 const int next_backup = info->backup_root_index;
af31f5e5 2036 struct btrfs_root_backup *root_backup;
af31f5e5
CM
2037
2038 root_backup = info->super_for_commit->super_roots + next_backup;
2039
2040 /*
2041 * make sure all of our padding and empty slots get zero filled
2042 * regardless of which ones we use today
2043 */
2044 memset(root_backup, 0, sizeof(*root_backup));
2045
2046 info->backup_root_index = (next_backup + 1) % BTRFS_NUM_BACKUP_ROOTS;
2047
2048 btrfs_set_backup_tree_root(root_backup, info->tree_root->node->start);
2049 btrfs_set_backup_tree_root_gen(root_backup,
2050 btrfs_header_generation(info->tree_root->node));
2051
2052 btrfs_set_backup_tree_root_level(root_backup,
2053 btrfs_header_level(info->tree_root->node));
2054
2055 btrfs_set_backup_chunk_root(root_backup, info->chunk_root->node->start);
2056 btrfs_set_backup_chunk_root_gen(root_backup,
2057 btrfs_header_generation(info->chunk_root->node));
2058 btrfs_set_backup_chunk_root_level(root_backup,
2059 btrfs_header_level(info->chunk_root->node));
2060
9c54e80d
JB
2061 if (btrfs_fs_incompat(info, EXTENT_TREE_V2)) {
2062 btrfs_set_backup_block_group_root(root_backup,
2063 info->block_group_root->node->start);
2064 btrfs_set_backup_block_group_root_gen(root_backup,
2065 btrfs_header_generation(info->block_group_root->node));
2066 btrfs_set_backup_block_group_root_level(root_backup,
2067 btrfs_header_level(info->block_group_root->node));
2068 } else {
2069 struct btrfs_root *extent_root = btrfs_extent_root(info, 0);
f7238e50 2070 struct btrfs_root *csum_root = btrfs_csum_root(info, 0);
9c54e80d
JB
2071
2072 btrfs_set_backup_extent_root(root_backup,
2073 extent_root->node->start);
2074 btrfs_set_backup_extent_root_gen(root_backup,
2075 btrfs_header_generation(extent_root->node));
2076 btrfs_set_backup_extent_root_level(root_backup,
2077 btrfs_header_level(extent_root->node));
f7238e50
JB
2078
2079 btrfs_set_backup_csum_root(root_backup, csum_root->node->start);
2080 btrfs_set_backup_csum_root_gen(root_backup,
2081 btrfs_header_generation(csum_root->node));
2082 btrfs_set_backup_csum_root_level(root_backup,
2083 btrfs_header_level(csum_root->node));
9c54e80d 2084 }
af31f5e5 2085
7c7e82a7
CM
2086 /*
2087 * we might commit during log recovery, which happens before we set
2088 * the fs_root. Make sure it is valid before we fill it in.
2089 */
2090 if (info->fs_root && info->fs_root->node) {
2091 btrfs_set_backup_fs_root(root_backup,
2092 info->fs_root->node->start);
2093 btrfs_set_backup_fs_root_gen(root_backup,
af31f5e5 2094 btrfs_header_generation(info->fs_root->node));
7c7e82a7 2095 btrfs_set_backup_fs_root_level(root_backup,
af31f5e5 2096 btrfs_header_level(info->fs_root->node));
7c7e82a7 2097 }
af31f5e5
CM
2098
2099 btrfs_set_backup_dev_root(root_backup, info->dev_root->node->start);
2100 btrfs_set_backup_dev_root_gen(root_backup,
2101 btrfs_header_generation(info->dev_root->node));
2102 btrfs_set_backup_dev_root_level(root_backup,
2103 btrfs_header_level(info->dev_root->node));
2104
af31f5e5
CM
2105 btrfs_set_backup_total_bytes(root_backup,
2106 btrfs_super_total_bytes(info->super_copy));
2107 btrfs_set_backup_bytes_used(root_backup,
2108 btrfs_super_bytes_used(info->super_copy));
2109 btrfs_set_backup_num_devices(root_backup,
2110 btrfs_super_num_devices(info->super_copy));
2111
2112 /*
2113 * if we don't copy this out to the super_copy, it won't get remembered
2114 * for the next commit
2115 */
2116 memcpy(&info->super_copy->super_roots,
2117 &info->super_for_commit->super_roots,
2118 sizeof(*root_backup) * BTRFS_NUM_BACKUP_ROOTS);
2119}
2120
bd2336b2
NB
2121/*
2122 * read_backup_root - Reads a backup root based on the passed priority. Prio 0
2123 * is the newest, prio 1/2/3 are 2nd newest/3rd newest/4th (oldest) backup roots
2124 *
2125 * fs_info - filesystem whose backup roots need to be read
2126 * priority - priority of backup root required
2127 *
2128 * Returns backup root index on success and -EINVAL otherwise.
2129 */
2130static int read_backup_root(struct btrfs_fs_info *fs_info, u8 priority)
2131{
2132 int backup_index = find_newest_super_backup(fs_info);
2133 struct btrfs_super_block *super = fs_info->super_copy;
2134 struct btrfs_root_backup *root_backup;
2135
2136 if (priority < BTRFS_NUM_BACKUP_ROOTS && backup_index >= 0) {
2137 if (priority == 0)
2138 return backup_index;
2139
2140 backup_index = backup_index + BTRFS_NUM_BACKUP_ROOTS - priority;
2141 backup_index %= BTRFS_NUM_BACKUP_ROOTS;
2142 } else {
2143 return -EINVAL;
2144 }
2145
2146 root_backup = super->super_roots + backup_index;
2147
2148 btrfs_set_super_generation(super,
2149 btrfs_backup_tree_root_gen(root_backup));
2150 btrfs_set_super_root(super, btrfs_backup_tree_root(root_backup));
2151 btrfs_set_super_root_level(super,
2152 btrfs_backup_tree_root_level(root_backup));
2153 btrfs_set_super_bytes_used(super, btrfs_backup_bytes_used(root_backup));
2154
2155 /*
2156 * Fixme: the total bytes and num_devices need to match or we should
2157 * need a fsck
2158 */
2159 btrfs_set_super_total_bytes(super, btrfs_backup_total_bytes(root_backup));
2160 btrfs_set_super_num_devices(super, btrfs_backup_num_devices(root_backup));
2161
2162 return backup_index;
2163}
2164
7abadb64
LB
2165/* helper to cleanup workers */
2166static void btrfs_stop_all_workers(struct btrfs_fs_info *fs_info)
2167{
dc6e3209 2168 btrfs_destroy_workqueue(fs_info->fixup_workers);
afe3d242 2169 btrfs_destroy_workqueue(fs_info->delalloc_workers);
a31b4a43 2170 btrfs_destroy_workqueue(fs_info->hipri_workers);
5cdc7ad3 2171 btrfs_destroy_workqueue(fs_info->workers);
d7b9416f
CH
2172 if (fs_info->endio_workers)
2173 destroy_workqueue(fs_info->endio_workers);
d34e123d
CH
2174 if (fs_info->endio_raid56_workers)
2175 destroy_workqueue(fs_info->endio_raid56_workers);
385de0ef
CH
2176 if (fs_info->rmw_workers)
2177 destroy_workqueue(fs_info->rmw_workers);
fed8a72d
CH
2178 if (fs_info->compressed_write_workers)
2179 destroy_workqueue(fs_info->compressed_write_workers);
fccb5d86
QW
2180 btrfs_destroy_workqueue(fs_info->endio_write_workers);
2181 btrfs_destroy_workqueue(fs_info->endio_freespace_worker);
5b3bc44e 2182 btrfs_destroy_workqueue(fs_info->delayed_workers);
e66f0bb1 2183 btrfs_destroy_workqueue(fs_info->caching_workers);
a44903ab 2184 btrfs_destroy_workqueue(fs_info->flush_workers);
fc97fab0 2185 btrfs_destroy_workqueue(fs_info->qgroup_rescan_workers);
b0643e59
DZ
2186 if (fs_info->discard_ctl.discard_workers)
2187 destroy_workqueue(fs_info->discard_ctl.discard_workers);
a9b9477d
FM
2188 /*
2189 * Now that all other work queues are destroyed, we can safely destroy
2190 * the queues used for metadata I/O, since tasks from those other work
2191 * queues can do metadata I/O operations.
2192 */
d7b9416f
CH
2193 if (fs_info->endio_meta_workers)
2194 destroy_workqueue(fs_info->endio_meta_workers);
7abadb64
LB
2195}
2196
2e9f5954
R
2197static void free_root_extent_buffers(struct btrfs_root *root)
2198{
2199 if (root) {
2200 free_extent_buffer(root->node);
2201 free_extent_buffer(root->commit_root);
2202 root->node = NULL;
2203 root->commit_root = NULL;
2204 }
2205}
2206
abed4aaa
JB
2207static void free_global_root_pointers(struct btrfs_fs_info *fs_info)
2208{
2209 struct btrfs_root *root, *tmp;
2210
2211 rbtree_postorder_for_each_entry_safe(root, tmp,
2212 &fs_info->global_root_tree,
2213 rb_node)
2214 free_root_extent_buffers(root);
2215}
2216
af31f5e5 2217/* helper to cleanup tree roots */
4273eaff 2218static void free_root_pointers(struct btrfs_fs_info *info, bool free_chunk_root)
af31f5e5 2219{
2e9f5954 2220 free_root_extent_buffers(info->tree_root);
655b09fe 2221
abed4aaa 2222 free_global_root_pointers(info);
2e9f5954 2223 free_root_extent_buffers(info->dev_root);
2e9f5954
R
2224 free_root_extent_buffers(info->quota_root);
2225 free_root_extent_buffers(info->uuid_root);
8c38938c 2226 free_root_extent_buffers(info->fs_root);
aeb935a4 2227 free_root_extent_buffers(info->data_reloc_root);
9c54e80d 2228 free_root_extent_buffers(info->block_group_root);
4273eaff 2229 if (free_chunk_root)
2e9f5954 2230 free_root_extent_buffers(info->chunk_root);
af31f5e5
CM
2231}
2232
8c38938c
JB
2233void btrfs_put_root(struct btrfs_root *root)
2234{
2235 if (!root)
2236 return;
2237
2238 if (refcount_dec_and_test(&root->refs)) {
2239 WARN_ON(!RB_EMPTY_ROOT(&root->inode_tree));
1dae7e0e 2240 WARN_ON(test_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state));
8c38938c
JB
2241 if (root->anon_dev)
2242 free_anon_bdev(root->anon_dev);
2243 btrfs_drew_lock_destroy(&root->snapshot_lock);
923eb523 2244 free_root_extent_buffers(root);
8c38938c 2245#ifdef CONFIG_BTRFS_DEBUG
fc7cbcd4 2246 spin_lock(&root->fs_info->fs_roots_radix_lock);
8c38938c 2247 list_del_init(&root->leak_list);
fc7cbcd4 2248 spin_unlock(&root->fs_info->fs_roots_radix_lock);
8c38938c
JB
2249#endif
2250 kfree(root);
2251 }
2252}
2253
faa2dbf0 2254void btrfs_free_fs_roots(struct btrfs_fs_info *fs_info)
171f6537 2255{
fc7cbcd4
DS
2256 int ret;
2257 struct btrfs_root *gang[8];
2258 int i;
171f6537
JB
2259
2260 while (!list_empty(&fs_info->dead_roots)) {
fc7cbcd4
DS
2261 gang[0] = list_entry(fs_info->dead_roots.next,
2262 struct btrfs_root, root_list);
2263 list_del(&gang[0]->root_list);
171f6537 2264
fc7cbcd4
DS
2265 if (test_bit(BTRFS_ROOT_IN_RADIX, &gang[0]->state))
2266 btrfs_drop_and_free_fs_root(fs_info, gang[0]);
2267 btrfs_put_root(gang[0]);
171f6537
JB
2268 }
2269
fc7cbcd4
DS
2270 while (1) {
2271 ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
2272 (void **)gang, 0,
2273 ARRAY_SIZE(gang));
2274 if (!ret)
2275 break;
2276 for (i = 0; i < ret; i++)
2277 btrfs_drop_and_free_fs_root(fs_info, gang[i]);
171f6537
JB
2278 }
2279}
af31f5e5 2280
638aa7ed
ES
2281static void btrfs_init_scrub(struct btrfs_fs_info *fs_info)
2282{
2283 mutex_init(&fs_info->scrub_lock);
2284 atomic_set(&fs_info->scrubs_running, 0);
2285 atomic_set(&fs_info->scrub_pause_req, 0);
2286 atomic_set(&fs_info->scrubs_paused, 0);
2287 atomic_set(&fs_info->scrub_cancel_req, 0);
2288 init_waitqueue_head(&fs_info->scrub_pause_wait);
ff09c4ca 2289 refcount_set(&fs_info->scrub_workers_refcnt, 0);
638aa7ed
ES
2290}
2291
779a65a4
ES
2292static void btrfs_init_balance(struct btrfs_fs_info *fs_info)
2293{
2294 spin_lock_init(&fs_info->balance_lock);
2295 mutex_init(&fs_info->balance_mutex);
779a65a4
ES
2296 atomic_set(&fs_info->balance_pause_req, 0);
2297 atomic_set(&fs_info->balance_cancel_req, 0);
2298 fs_info->balance_ctl = NULL;
2299 init_waitqueue_head(&fs_info->balance_wait_q);
907d2710 2300 atomic_set(&fs_info->reloc_cancel_req, 0);
779a65a4
ES
2301}
2302
6bccf3ab 2303static void btrfs_init_btree_inode(struct btrfs_fs_info *fs_info)
f37938e0 2304{
2ff7e61e
JM
2305 struct inode *inode = fs_info->btree_inode;
2306
2307 inode->i_ino = BTRFS_BTREE_INODE_OBJECTID;
2308 set_nlink(inode, 1);
f37938e0
ES
2309 /*
2310 * we set the i_size on the btree inode to the max possible int.
2311 * the real end of the address space is determined by all of
2312 * the devices in the system
2313 */
2ff7e61e
JM
2314 inode->i_size = OFFSET_MAX;
2315 inode->i_mapping->a_ops = &btree_aops;
f37938e0 2316
2ff7e61e 2317 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
43eb5f29 2318 extent_io_tree_init(fs_info, &BTRFS_I(inode)->io_tree,
2c53a14d 2319 IO_TREE_BTREE_INODE_IO, inode);
7b439738 2320 BTRFS_I(inode)->io_tree.track_uptodate = false;
2ff7e61e 2321 extent_map_tree_init(&BTRFS_I(inode)->extent_tree);
f37938e0 2322
5c8fd99f 2323 BTRFS_I(inode)->root = btrfs_grab_root(fs_info->tree_root);
2ff7e61e
JM
2324 memset(&BTRFS_I(inode)->location, 0, sizeof(struct btrfs_key));
2325 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
2326 btrfs_insert_inode_hash(inode);
f37938e0
ES
2327}
2328
ad618368
ES
2329static void btrfs_init_dev_replace_locks(struct btrfs_fs_info *fs_info)
2330{
ad618368 2331 mutex_init(&fs_info->dev_replace.lock_finishing_cancel_unmount);
129827e3 2332 init_rwsem(&fs_info->dev_replace.rwsem);
7f8d236a 2333 init_waitqueue_head(&fs_info->dev_replace.replace_wait);
ad618368
ES
2334}
2335
f9e92e40
ES
2336static void btrfs_init_qgroup(struct btrfs_fs_info *fs_info)
2337{
2338 spin_lock_init(&fs_info->qgroup_lock);
2339 mutex_init(&fs_info->qgroup_ioctl_lock);
2340 fs_info->qgroup_tree = RB_ROOT;
f9e92e40
ES
2341 INIT_LIST_HEAD(&fs_info->dirty_qgroups);
2342 fs_info->qgroup_seq = 1;
f9e92e40 2343 fs_info->qgroup_ulist = NULL;
d2c609b8 2344 fs_info->qgroup_rescan_running = false;
f9e92e40
ES
2345 mutex_init(&fs_info->qgroup_rescan_lock);
2346}
2347
d21deec5 2348static int btrfs_init_workqueues(struct btrfs_fs_info *fs_info)
2a458198 2349{
f7b885be 2350 u32 max_active = fs_info->thread_pool_size;
6f011058 2351 unsigned int flags = WQ_MEM_RECLAIM | WQ_FREEZABLE | WQ_UNBOUND;
2a458198
ES
2352
2353 fs_info->workers =
a31b4a43
CH
2354 btrfs_alloc_workqueue(fs_info, "worker", flags, max_active, 16);
2355 fs_info->hipri_workers =
2356 btrfs_alloc_workqueue(fs_info, "worker-high",
cb001095 2357 flags | WQ_HIGHPRI, max_active, 16);
2a458198
ES
2358
2359 fs_info->delalloc_workers =
cb001095
JM
2360 btrfs_alloc_workqueue(fs_info, "delalloc",
2361 flags, max_active, 2);
2a458198
ES
2362
2363 fs_info->flush_workers =
cb001095
JM
2364 btrfs_alloc_workqueue(fs_info, "flush_delalloc",
2365 flags, max_active, 0);
2a458198
ES
2366
2367 fs_info->caching_workers =
cb001095 2368 btrfs_alloc_workqueue(fs_info, "cache", flags, max_active, 0);
2a458198 2369
2a458198 2370 fs_info->fixup_workers =
cb001095 2371 btrfs_alloc_workqueue(fs_info, "fixup", flags, 1, 0);
2a458198 2372
2a458198 2373 fs_info->endio_workers =
d7b9416f 2374 alloc_workqueue("btrfs-endio", flags, max_active);
2a458198 2375 fs_info->endio_meta_workers =
d7b9416f 2376 alloc_workqueue("btrfs-endio-meta", flags, max_active);
2a458198 2377 fs_info->endio_raid56_workers =
d34e123d 2378 alloc_workqueue("btrfs-endio-raid56", flags, max_active);
385de0ef 2379 fs_info->rmw_workers = alloc_workqueue("btrfs-rmw", flags, max_active);
2a458198 2380 fs_info->endio_write_workers =
cb001095
JM
2381 btrfs_alloc_workqueue(fs_info, "endio-write", flags,
2382 max_active, 2);
fed8a72d
CH
2383 fs_info->compressed_write_workers =
2384 alloc_workqueue("btrfs-compressed-write", flags, max_active);
2a458198 2385 fs_info->endio_freespace_worker =
cb001095
JM
2386 btrfs_alloc_workqueue(fs_info, "freespace-write", flags,
2387 max_active, 0);
2a458198 2388 fs_info->delayed_workers =
cb001095
JM
2389 btrfs_alloc_workqueue(fs_info, "delayed-meta", flags,
2390 max_active, 0);
2a458198 2391 fs_info->qgroup_rescan_workers =
cb001095 2392 btrfs_alloc_workqueue(fs_info, "qgroup-rescan", flags, 1, 0);
b0643e59
DZ
2393 fs_info->discard_ctl.discard_workers =
2394 alloc_workqueue("btrfs_discard", WQ_UNBOUND | WQ_FREEZABLE, 1);
2a458198 2395
a31b4a43
CH
2396 if (!(fs_info->workers && fs_info->hipri_workers &&
2397 fs_info->delalloc_workers && fs_info->flush_workers &&
2a458198 2398 fs_info->endio_workers && fs_info->endio_meta_workers &&
fed8a72d 2399 fs_info->compressed_write_workers &&
2a458198
ES
2400 fs_info->endio_write_workers && fs_info->endio_raid56_workers &&
2401 fs_info->endio_freespace_worker && fs_info->rmw_workers &&
f26c9238
QW
2402 fs_info->caching_workers && fs_info->fixup_workers &&
2403 fs_info->delayed_workers && fs_info->qgroup_rescan_workers &&
b0643e59 2404 fs_info->discard_ctl.discard_workers)) {
2a458198
ES
2405 return -ENOMEM;
2406 }
2407
2408 return 0;
2409}
2410
6d97c6e3
JT
2411static int btrfs_init_csum_hash(struct btrfs_fs_info *fs_info, u16 csum_type)
2412{
2413 struct crypto_shash *csum_shash;
b4e967be 2414 const char *csum_driver = btrfs_super_csum_driver(csum_type);
6d97c6e3 2415
b4e967be 2416 csum_shash = crypto_alloc_shash(csum_driver, 0, 0);
6d97c6e3
JT
2417
2418 if (IS_ERR(csum_shash)) {
2419 btrfs_err(fs_info, "error allocating %s hash for checksum",
b4e967be 2420 csum_driver);
6d97c6e3
JT
2421 return PTR_ERR(csum_shash);
2422 }
2423
2424 fs_info->csum_shash = csum_shash;
2425
2426 return 0;
2427}
2428
63443bf5
ES
2429static int btrfs_replay_log(struct btrfs_fs_info *fs_info,
2430 struct btrfs_fs_devices *fs_devices)
2431{
2432 int ret;
63443bf5
ES
2433 struct btrfs_root *log_tree_root;
2434 struct btrfs_super_block *disk_super = fs_info->super_copy;
2435 u64 bytenr = btrfs_super_log_root(disk_super);
581c1760 2436 int level = btrfs_super_log_root_level(disk_super);
63443bf5
ES
2437
2438 if (fs_devices->rw_devices == 0) {
f14d104d 2439 btrfs_warn(fs_info, "log replay required on RO media");
63443bf5
ES
2440 return -EIO;
2441 }
2442
96dfcb46
JB
2443 log_tree_root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID,
2444 GFP_KERNEL);
63443bf5
ES
2445 if (!log_tree_root)
2446 return -ENOMEM;
2447
2ff7e61e 2448 log_tree_root->node = read_tree_block(fs_info, bytenr,
1b7ec85e
JB
2449 BTRFS_TREE_LOG_OBJECTID,
2450 fs_info->generation + 1, level,
2451 NULL);
64c043de 2452 if (IS_ERR(log_tree_root->node)) {
f14d104d 2453 btrfs_warn(fs_info, "failed to read log tree");
0eeff236 2454 ret = PTR_ERR(log_tree_root->node);
8c38938c 2455 log_tree_root->node = NULL;
00246528 2456 btrfs_put_root(log_tree_root);
0eeff236 2457 return ret;
4eb150d6
QW
2458 }
2459 if (!extent_buffer_uptodate(log_tree_root->node)) {
f14d104d 2460 btrfs_err(fs_info, "failed to read log tree");
00246528 2461 btrfs_put_root(log_tree_root);
63443bf5
ES
2462 return -EIO;
2463 }
4eb150d6 2464
63443bf5
ES
2465 /* returns with log_tree_root freed on success */
2466 ret = btrfs_recover_log_trees(log_tree_root);
2467 if (ret) {
0b246afa
JM
2468 btrfs_handle_fs_error(fs_info, ret,
2469 "Failed to recover log tree");
00246528 2470 btrfs_put_root(log_tree_root);
63443bf5
ES
2471 return ret;
2472 }
2473
bc98a42c 2474 if (sb_rdonly(fs_info->sb)) {
6bccf3ab 2475 ret = btrfs_commit_super(fs_info);
63443bf5
ES
2476 if (ret)
2477 return ret;
2478 }
2479
2480 return 0;
2481}
2482
abed4aaa
JB
2483static int load_global_roots_objectid(struct btrfs_root *tree_root,
2484 struct btrfs_path *path, u64 objectid,
2485 const char *name)
2486{
2487 struct btrfs_fs_info *fs_info = tree_root->fs_info;
2488 struct btrfs_root *root;
f7238e50 2489 u64 max_global_id = 0;
abed4aaa
JB
2490 int ret;
2491 struct btrfs_key key = {
2492 .objectid = objectid,
2493 .type = BTRFS_ROOT_ITEM_KEY,
2494 .offset = 0,
2495 };
2496 bool found = false;
2497
2498 /* If we have IGNOREDATACSUMS skip loading these roots. */
2499 if (objectid == BTRFS_CSUM_TREE_OBJECTID &&
2500 btrfs_test_opt(fs_info, IGNOREDATACSUMS)) {
2501 set_bit(BTRFS_FS_STATE_NO_CSUMS, &fs_info->fs_state);
2502 return 0;
2503 }
2504
2505 while (1) {
2506 ret = btrfs_search_slot(NULL, tree_root, &key, path, 0, 0);
2507 if (ret < 0)
2508 break;
2509
2510 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
2511 ret = btrfs_next_leaf(tree_root, path);
2512 if (ret) {
2513 if (ret > 0)
2514 ret = 0;
2515 break;
2516 }
2517 }
2518 ret = 0;
2519
2520 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2521 if (key.objectid != objectid)
2522 break;
2523 btrfs_release_path(path);
2524
f7238e50
JB
2525 /*
2526 * Just worry about this for extent tree, it'll be the same for
2527 * everybody.
2528 */
2529 if (objectid == BTRFS_EXTENT_TREE_OBJECTID)
2530 max_global_id = max(max_global_id, key.offset);
2531
abed4aaa
JB
2532 found = true;
2533 root = read_tree_root_path(tree_root, path, &key);
2534 if (IS_ERR(root)) {
2535 if (!btrfs_test_opt(fs_info, IGNOREBADROOTS))
2536 ret = PTR_ERR(root);
2537 break;
2538 }
2539 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2540 ret = btrfs_global_root_insert(root);
2541 if (ret) {
2542 btrfs_put_root(root);
2543 break;
2544 }
2545 key.offset++;
2546 }
2547 btrfs_release_path(path);
2548
f7238e50
JB
2549 if (objectid == BTRFS_EXTENT_TREE_OBJECTID)
2550 fs_info->nr_global_roots = max_global_id + 1;
2551
abed4aaa
JB
2552 if (!found || ret) {
2553 if (objectid == BTRFS_CSUM_TREE_OBJECTID)
2554 set_bit(BTRFS_FS_STATE_NO_CSUMS, &fs_info->fs_state);
2555
2556 if (!btrfs_test_opt(fs_info, IGNOREBADROOTS))
2557 ret = ret ? ret : -ENOENT;
2558 else
2559 ret = 0;
2560 btrfs_err(fs_info, "failed to load root %s", name);
2561 }
2562 return ret;
2563}
2564
2565static int load_global_roots(struct btrfs_root *tree_root)
2566{
2567 struct btrfs_path *path;
2568 int ret = 0;
2569
2570 path = btrfs_alloc_path();
2571 if (!path)
2572 return -ENOMEM;
2573
2574 ret = load_global_roots_objectid(tree_root, path,
2575 BTRFS_EXTENT_TREE_OBJECTID, "extent");
2576 if (ret)
2577 goto out;
2578 ret = load_global_roots_objectid(tree_root, path,
2579 BTRFS_CSUM_TREE_OBJECTID, "csum");
2580 if (ret)
2581 goto out;
2582 if (!btrfs_fs_compat_ro(tree_root->fs_info, FREE_SPACE_TREE))
2583 goto out;
2584 ret = load_global_roots_objectid(tree_root, path,
2585 BTRFS_FREE_SPACE_TREE_OBJECTID,
2586 "free space");
2587out:
2588 btrfs_free_path(path);
2589 return ret;
2590}
2591
6bccf3ab 2592static int btrfs_read_roots(struct btrfs_fs_info *fs_info)
4bbcaa64 2593{
6bccf3ab 2594 struct btrfs_root *tree_root = fs_info->tree_root;
a4f3d2c4 2595 struct btrfs_root *root;
4bbcaa64
ES
2596 struct btrfs_key location;
2597 int ret;
2598
6bccf3ab
JM
2599 BUG_ON(!fs_info->tree_root);
2600
abed4aaa
JB
2601 ret = load_global_roots(tree_root);
2602 if (ret)
2603 return ret;
2604
2605 location.objectid = BTRFS_DEV_TREE_OBJECTID;
4bbcaa64
ES
2606 location.type = BTRFS_ROOT_ITEM_KEY;
2607 location.offset = 0;
2608
a4f3d2c4 2609 root = btrfs_read_tree_root(tree_root, &location);
f50f4353 2610 if (IS_ERR(root)) {
42437a63
JB
2611 if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2612 ret = PTR_ERR(root);
2613 goto out;
2614 }
2615 } else {
2616 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2617 fs_info->dev_root = root;
f50f4353 2618 }
820a49da
JB
2619 /* Initialize fs_info for all devices in any case */
2620 btrfs_init_devices_late(fs_info);
4bbcaa64 2621
aeb935a4
QW
2622 /*
2623 * This tree can share blocks with some other fs tree during relocation
2624 * and we need a proper setup by btrfs_get_fs_root
2625 */
56e9357a
DS
2626 root = btrfs_get_fs_root(tree_root->fs_info,
2627 BTRFS_DATA_RELOC_TREE_OBJECTID, true);
aeb935a4 2628 if (IS_ERR(root)) {
42437a63
JB
2629 if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2630 ret = PTR_ERR(root);
2631 goto out;
2632 }
2633 } else {
2634 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2635 fs_info->data_reloc_root = root;
aeb935a4 2636 }
aeb935a4 2637
4bbcaa64 2638 location.objectid = BTRFS_QUOTA_TREE_OBJECTID;
a4f3d2c4
DS
2639 root = btrfs_read_tree_root(tree_root, &location);
2640 if (!IS_ERR(root)) {
2641 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
afcdd129 2642 set_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
a4f3d2c4 2643 fs_info->quota_root = root;
4bbcaa64
ES
2644 }
2645
2646 location.objectid = BTRFS_UUID_TREE_OBJECTID;
a4f3d2c4
DS
2647 root = btrfs_read_tree_root(tree_root, &location);
2648 if (IS_ERR(root)) {
42437a63
JB
2649 if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2650 ret = PTR_ERR(root);
2651 if (ret != -ENOENT)
2652 goto out;
2653 }
4bbcaa64 2654 } else {
a4f3d2c4
DS
2655 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2656 fs_info->uuid_root = root;
4bbcaa64
ES
2657 }
2658
2659 return 0;
f50f4353
LB
2660out:
2661 btrfs_warn(fs_info, "failed to read root (objectid=%llu): %d",
2662 location.objectid, ret);
2663 return ret;
4bbcaa64
ES
2664}
2665
069ec957
QW
2666/*
2667 * Real super block validation
2668 * NOTE: super csum type and incompat features will not be checked here.
2669 *
2670 * @sb: super block to check
2671 * @mirror_num: the super block number to check its bytenr:
2672 * 0 the primary (1st) sb
2673 * 1, 2 2nd and 3rd backup copy
2674 * -1 skip bytenr check
2675 */
2676static int validate_super(struct btrfs_fs_info *fs_info,
2677 struct btrfs_super_block *sb, int mirror_num)
21a852b0 2678{
21a852b0
QW
2679 u64 nodesize = btrfs_super_nodesize(sb);
2680 u64 sectorsize = btrfs_super_sectorsize(sb);
2681 int ret = 0;
2682
2683 if (btrfs_super_magic(sb) != BTRFS_MAGIC) {
2684 btrfs_err(fs_info, "no valid FS found");
2685 ret = -EINVAL;
2686 }
2687 if (btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP) {
2688 btrfs_err(fs_info, "unrecognized or unsupported super flag: %llu",
2689 btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP);
2690 ret = -EINVAL;
2691 }
2692 if (btrfs_super_root_level(sb) >= BTRFS_MAX_LEVEL) {
2693 btrfs_err(fs_info, "tree_root level too big: %d >= %d",
2694 btrfs_super_root_level(sb), BTRFS_MAX_LEVEL);
2695 ret = -EINVAL;
2696 }
2697 if (btrfs_super_chunk_root_level(sb) >= BTRFS_MAX_LEVEL) {
2698 btrfs_err(fs_info, "chunk_root level too big: %d >= %d",
2699 btrfs_super_chunk_root_level(sb), BTRFS_MAX_LEVEL);
2700 ret = -EINVAL;
2701 }
2702 if (btrfs_super_log_root_level(sb) >= BTRFS_MAX_LEVEL) {
2703 btrfs_err(fs_info, "log_root level too big: %d >= %d",
2704 btrfs_super_log_root_level(sb), BTRFS_MAX_LEVEL);
2705 ret = -EINVAL;
2706 }
2707
2708 /*
2709 * Check sectorsize and nodesize first, other check will need it.
2710 * Check all possible sectorsize(4K, 8K, 16K, 32K, 64K) here.
2711 */
2712 if (!is_power_of_2(sectorsize) || sectorsize < 4096 ||
2713 sectorsize > BTRFS_MAX_METADATA_BLOCKSIZE) {
2714 btrfs_err(fs_info, "invalid sectorsize %llu", sectorsize);
2715 ret = -EINVAL;
2716 }
0bb3eb3e
QW
2717
2718 /*
1a42daab
QW
2719 * We only support at most two sectorsizes: 4K and PAGE_SIZE.
2720 *
2721 * We can support 16K sectorsize with 64K page size without problem,
2722 * but such sectorsize/pagesize combination doesn't make much sense.
2723 * 4K will be our future standard, PAGE_SIZE is supported from the very
2724 * beginning.
0bb3eb3e 2725 */
1a42daab 2726 if (sectorsize > PAGE_SIZE || (sectorsize != SZ_4K && sectorsize != PAGE_SIZE)) {
21a852b0 2727 btrfs_err(fs_info,
0bb3eb3e 2728 "sectorsize %llu not yet supported for page size %lu",
21a852b0
QW
2729 sectorsize, PAGE_SIZE);
2730 ret = -EINVAL;
2731 }
0bb3eb3e 2732
21a852b0
QW
2733 if (!is_power_of_2(nodesize) || nodesize < sectorsize ||
2734 nodesize > BTRFS_MAX_METADATA_BLOCKSIZE) {
2735 btrfs_err(fs_info, "invalid nodesize %llu", nodesize);
2736 ret = -EINVAL;
2737 }
2738 if (nodesize != le32_to_cpu(sb->__unused_leafsize)) {
2739 btrfs_err(fs_info, "invalid leafsize %u, should be %llu",
2740 le32_to_cpu(sb->__unused_leafsize), nodesize);
2741 ret = -EINVAL;
2742 }
2743
2744 /* Root alignment check */
2745 if (!IS_ALIGNED(btrfs_super_root(sb), sectorsize)) {
2746 btrfs_warn(fs_info, "tree_root block unaligned: %llu",
2747 btrfs_super_root(sb));
2748 ret = -EINVAL;
2749 }
2750 if (!IS_ALIGNED(btrfs_super_chunk_root(sb), sectorsize)) {
2751 btrfs_warn(fs_info, "chunk_root block unaligned: %llu",
2752 btrfs_super_chunk_root(sb));
2753 ret = -EINVAL;
2754 }
2755 if (!IS_ALIGNED(btrfs_super_log_root(sb), sectorsize)) {
2756 btrfs_warn(fs_info, "log_root block unaligned: %llu",
2757 btrfs_super_log_root(sb));
2758 ret = -EINVAL;
2759 }
2760
aefd7f70
NB
2761 if (memcmp(fs_info->fs_devices->fsid, fs_info->super_copy->fsid,
2762 BTRFS_FSID_SIZE)) {
2763 btrfs_err(fs_info,
2764 "superblock fsid doesn't match fsid of fs_devices: %pU != %pU",
2765 fs_info->super_copy->fsid, fs_info->fs_devices->fsid);
2766 ret = -EINVAL;
2767 }
2768
2769 if (btrfs_fs_incompat(fs_info, METADATA_UUID) &&
2770 memcmp(fs_info->fs_devices->metadata_uuid,
2771 fs_info->super_copy->metadata_uuid, BTRFS_FSID_SIZE)) {
2772 btrfs_err(fs_info,
2773"superblock metadata_uuid doesn't match metadata uuid of fs_devices: %pU != %pU",
2774 fs_info->super_copy->metadata_uuid,
2775 fs_info->fs_devices->metadata_uuid);
2776 ret = -EINVAL;
2777 }
2778
de37aa51 2779 if (memcmp(fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid,
7239ff4b 2780 BTRFS_FSID_SIZE) != 0) {
21a852b0 2781 btrfs_err(fs_info,
7239ff4b 2782 "dev_item UUID does not match metadata fsid: %pU != %pU",
de37aa51 2783 fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid);
21a852b0
QW
2784 ret = -EINVAL;
2785 }
2786
2787 /*
2788 * Hint to catch really bogus numbers, bitflips or so, more exact checks are
2789 * done later
2790 */
2791 if (btrfs_super_bytes_used(sb) < 6 * btrfs_super_nodesize(sb)) {
2792 btrfs_err(fs_info, "bytes_used is too small %llu",
2793 btrfs_super_bytes_used(sb));
2794 ret = -EINVAL;
2795 }
2796 if (!is_power_of_2(btrfs_super_stripesize(sb))) {
2797 btrfs_err(fs_info, "invalid stripesize %u",
2798 btrfs_super_stripesize(sb));
2799 ret = -EINVAL;
2800 }
2801 if (btrfs_super_num_devices(sb) > (1UL << 31))
2802 btrfs_warn(fs_info, "suspicious number of devices: %llu",
2803 btrfs_super_num_devices(sb));
2804 if (btrfs_super_num_devices(sb) == 0) {
2805 btrfs_err(fs_info, "number of devices is 0");
2806 ret = -EINVAL;
2807 }
2808
069ec957
QW
2809 if (mirror_num >= 0 &&
2810 btrfs_super_bytenr(sb) != btrfs_sb_offset(mirror_num)) {
21a852b0
QW
2811 btrfs_err(fs_info, "super offset mismatch %llu != %u",
2812 btrfs_super_bytenr(sb), BTRFS_SUPER_INFO_OFFSET);
2813 ret = -EINVAL;
2814 }
2815
2816 /*
2817 * Obvious sys_chunk_array corruptions, it must hold at least one key
2818 * and one chunk
2819 */
2820 if (btrfs_super_sys_array_size(sb) > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
2821 btrfs_err(fs_info, "system chunk array too big %u > %u",
2822 btrfs_super_sys_array_size(sb),
2823 BTRFS_SYSTEM_CHUNK_ARRAY_SIZE);
2824 ret = -EINVAL;
2825 }
2826 if (btrfs_super_sys_array_size(sb) < sizeof(struct btrfs_disk_key)
2827 + sizeof(struct btrfs_chunk)) {
2828 btrfs_err(fs_info, "system chunk array too small %u < %zu",
2829 btrfs_super_sys_array_size(sb),
2830 sizeof(struct btrfs_disk_key)
2831 + sizeof(struct btrfs_chunk));
2832 ret = -EINVAL;
2833 }
2834
2835 /*
2836 * The generation is a global counter, we'll trust it more than the others
2837 * but it's still possible that it's the one that's wrong.
2838 */
2839 if (btrfs_super_generation(sb) < btrfs_super_chunk_root_generation(sb))
2840 btrfs_warn(fs_info,
2841 "suspicious: generation < chunk_root_generation: %llu < %llu",
2842 btrfs_super_generation(sb),
2843 btrfs_super_chunk_root_generation(sb));
2844 if (btrfs_super_generation(sb) < btrfs_super_cache_generation(sb)
2845 && btrfs_super_cache_generation(sb) != (u64)-1)
2846 btrfs_warn(fs_info,
2847 "suspicious: generation < cache_generation: %llu < %llu",
2848 btrfs_super_generation(sb),
2849 btrfs_super_cache_generation(sb));
2850
2851 return ret;
2852}
2853
069ec957
QW
2854/*
2855 * Validation of super block at mount time.
2856 * Some checks already done early at mount time, like csum type and incompat
2857 * flags will be skipped.
2858 */
2859static int btrfs_validate_mount_super(struct btrfs_fs_info *fs_info)
2860{
2861 return validate_super(fs_info, fs_info->super_copy, 0);
2862}
2863
75cb857d
QW
2864/*
2865 * Validation of super block at write time.
2866 * Some checks like bytenr check will be skipped as their values will be
2867 * overwritten soon.
2868 * Extra checks like csum type and incompat flags will be done here.
2869 */
2870static int btrfs_validate_write_super(struct btrfs_fs_info *fs_info,
2871 struct btrfs_super_block *sb)
2872{
2873 int ret;
2874
2875 ret = validate_super(fs_info, sb, -1);
2876 if (ret < 0)
2877 goto out;
e7e16f48 2878 if (!btrfs_supported_super_csum(btrfs_super_csum_type(sb))) {
75cb857d
QW
2879 ret = -EUCLEAN;
2880 btrfs_err(fs_info, "invalid csum type, has %u want %u",
2881 btrfs_super_csum_type(sb), BTRFS_CSUM_TYPE_CRC32);
2882 goto out;
2883 }
2884 if (btrfs_super_incompat_flags(sb) & ~BTRFS_FEATURE_INCOMPAT_SUPP) {
2885 ret = -EUCLEAN;
2886 btrfs_err(fs_info,
2887 "invalid incompat flags, has 0x%llx valid mask 0x%llx",
2888 btrfs_super_incompat_flags(sb),
2889 (unsigned long long)BTRFS_FEATURE_INCOMPAT_SUPP);
2890 goto out;
2891 }
2892out:
2893 if (ret < 0)
2894 btrfs_err(fs_info,
2895 "super block corruption detected before writing it to disk");
2896 return ret;
2897}
2898
bd676446
JB
2899static int load_super_root(struct btrfs_root *root, u64 bytenr, u64 gen, int level)
2900{
2901 int ret = 0;
2902
2903 root->node = read_tree_block(root->fs_info, bytenr,
2904 root->root_key.objectid, gen, level, NULL);
2905 if (IS_ERR(root->node)) {
2906 ret = PTR_ERR(root->node);
2907 root->node = NULL;
4eb150d6
QW
2908 return ret;
2909 }
2910 if (!extent_buffer_uptodate(root->node)) {
bd676446
JB
2911 free_extent_buffer(root->node);
2912 root->node = NULL;
4eb150d6 2913 return -EIO;
bd676446
JB
2914 }
2915
bd676446
JB
2916 btrfs_set_root_node(&root->root_item, root->node);
2917 root->commit_root = btrfs_root_node(root);
2918 btrfs_set_root_refs(&root->root_item, 1);
2919 return ret;
2920}
2921
2922static int load_important_roots(struct btrfs_fs_info *fs_info)
2923{
2924 struct btrfs_super_block *sb = fs_info->super_copy;
2925 u64 gen, bytenr;
2926 int level, ret;
2927
2928 bytenr = btrfs_super_root(sb);
2929 gen = btrfs_super_generation(sb);
2930 level = btrfs_super_root_level(sb);
2931 ret = load_super_root(fs_info->tree_root, bytenr, gen, level);
9c54e80d 2932 if (ret) {
bd676446 2933 btrfs_warn(fs_info, "couldn't read tree root");
9c54e80d
JB
2934 return ret;
2935 }
2936
2937 if (!btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))
2938 return 0;
2939
2940 bytenr = btrfs_super_block_group_root(sb);
2941 gen = btrfs_super_block_group_root_generation(sb);
2942 level = btrfs_super_block_group_root_level(sb);
2943 ret = load_super_root(fs_info->block_group_root, bytenr, gen, level);
2944 if (ret)
2945 btrfs_warn(fs_info, "couldn't read block group root");
bd676446
JB
2946 return ret;
2947}
2948
6ef108dd 2949static int __cold init_tree_roots(struct btrfs_fs_info *fs_info)
b8522a1e 2950{
6ef108dd 2951 int backup_index = find_newest_super_backup(fs_info);
b8522a1e
NB
2952 struct btrfs_super_block *sb = fs_info->super_copy;
2953 struct btrfs_root *tree_root = fs_info->tree_root;
2954 bool handle_error = false;
2955 int ret = 0;
2956 int i;
2957
9c54e80d
JB
2958 if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) {
2959 struct btrfs_root *root;
2960
2961 root = btrfs_alloc_root(fs_info, BTRFS_BLOCK_GROUP_TREE_OBJECTID,
2962 GFP_KERNEL);
2963 if (!root)
2964 return -ENOMEM;
2965 fs_info->block_group_root = root;
2966 }
b8522a1e 2967
b8522a1e 2968 for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
b8522a1e
NB
2969 if (handle_error) {
2970 if (!IS_ERR(tree_root->node))
2971 free_extent_buffer(tree_root->node);
2972 tree_root->node = NULL;
2973
2974 if (!btrfs_test_opt(fs_info, USEBACKUPROOT))
2975 break;
2976
2977 free_root_pointers(fs_info, 0);
2978
2979 /*
2980 * Don't use the log in recovery mode, it won't be
2981 * valid
2982 */
2983 btrfs_set_super_log_root(sb, 0);
2984
2985 /* We can't trust the free space cache either */
2986 btrfs_set_opt(fs_info->mount_opt, CLEAR_CACHE);
2987
2988 ret = read_backup_root(fs_info, i);
6ef108dd 2989 backup_index = ret;
b8522a1e
NB
2990 if (ret < 0)
2991 return ret;
2992 }
b8522a1e 2993
bd676446
JB
2994 ret = load_important_roots(fs_info);
2995 if (ret) {
217f5004 2996 handle_error = true;
b8522a1e
NB
2997 continue;
2998 }
2999
336a0d8d
NB
3000 /*
3001 * No need to hold btrfs_root::objectid_mutex since the fs
3002 * hasn't been fully initialised and we are the only user
3003 */
453e4873 3004 ret = btrfs_init_root_free_objectid(tree_root);
b8522a1e 3005 if (ret < 0) {
b8522a1e
NB
3006 handle_error = true;
3007 continue;
3008 }
3009
6b8fad57 3010 ASSERT(tree_root->free_objectid <= BTRFS_LAST_FREE_OBJECTID);
b8522a1e
NB
3011
3012 ret = btrfs_read_roots(fs_info);
3013 if (ret < 0) {
3014 handle_error = true;
3015 continue;
3016 }
3017
3018 /* All successful */
bd676446
JB
3019 fs_info->generation = btrfs_header_generation(tree_root->node);
3020 fs_info->last_trans_committed = fs_info->generation;
d96b3424 3021 fs_info->last_reloc_trans = 0;
6ef108dd
NB
3022
3023 /* Always begin writing backup roots after the one being used */
3024 if (backup_index < 0) {
3025 fs_info->backup_root_index = 0;
3026 } else {
3027 fs_info->backup_root_index = backup_index + 1;
3028 fs_info->backup_root_index %= BTRFS_NUM_BACKUP_ROOTS;
3029 }
b8522a1e
NB
3030 break;
3031 }
3032
3033 return ret;
3034}
3035
8260edba 3036void btrfs_init_fs_info(struct btrfs_fs_info *fs_info)
2e635a27 3037{
fc7cbcd4 3038 INIT_RADIX_TREE(&fs_info->fs_roots_radix, GFP_ATOMIC);
01cd3909 3039 INIT_RADIX_TREE(&fs_info->buffer_radix, GFP_ATOMIC);
8fd17795 3040 INIT_LIST_HEAD(&fs_info->trans_list);
facda1e7 3041 INIT_LIST_HEAD(&fs_info->dead_roots);
24bbcf04 3042 INIT_LIST_HEAD(&fs_info->delayed_iputs);
eb73c1b7 3043 INIT_LIST_HEAD(&fs_info->delalloc_roots);
11833d66 3044 INIT_LIST_HEAD(&fs_info->caching_block_groups);
eb73c1b7 3045 spin_lock_init(&fs_info->delalloc_root_lock);
a4abeea4 3046 spin_lock_init(&fs_info->trans_lock);
fc7cbcd4 3047 spin_lock_init(&fs_info->fs_roots_radix_lock);
24bbcf04 3048 spin_lock_init(&fs_info->delayed_iput_lock);
4cb5300b 3049 spin_lock_init(&fs_info->defrag_inodes_lock);
ceda0864 3050 spin_lock_init(&fs_info->super_lock);
f28491e0 3051 spin_lock_init(&fs_info->buffer_lock);
47ab2a6c 3052 spin_lock_init(&fs_info->unused_bgs_lock);
40ab3be1 3053 spin_lock_init(&fs_info->treelog_bg_lock);
afba2bc0 3054 spin_lock_init(&fs_info->zone_active_bgs_lock);
c2707a25 3055 spin_lock_init(&fs_info->relocation_bg_lock);
f29021b2 3056 rwlock_init(&fs_info->tree_mod_log_lock);
abed4aaa 3057 rwlock_init(&fs_info->global_root_lock);
d7c15171 3058 mutex_init(&fs_info->unused_bg_unpin_mutex);
f3372065 3059 mutex_init(&fs_info->reclaim_bgs_lock);
7585717f 3060 mutex_init(&fs_info->reloc_mutex);
573bfb72 3061 mutex_init(&fs_info->delalloc_root_mutex);
0bc09ca1 3062 mutex_init(&fs_info->zoned_meta_io_lock);
5f0addf7 3063 mutex_init(&fs_info->zoned_data_reloc_io_lock);
de98ced9 3064 seqlock_init(&fs_info->profiles_lock);
19c00ddc 3065
0b86a832 3066 INIT_LIST_HEAD(&fs_info->dirty_cowonly_roots);
6324fbf3 3067 INIT_LIST_HEAD(&fs_info->space_info);
f29021b2 3068 INIT_LIST_HEAD(&fs_info->tree_mod_seq_list);
47ab2a6c 3069 INIT_LIST_HEAD(&fs_info->unused_bgs);
18bb8bbf 3070 INIT_LIST_HEAD(&fs_info->reclaim_bgs);
afba2bc0 3071 INIT_LIST_HEAD(&fs_info->zone_active_bgs);
bd647ce3
JB
3072#ifdef CONFIG_BTRFS_DEBUG
3073 INIT_LIST_HEAD(&fs_info->allocated_roots);
3fd63727
JB
3074 INIT_LIST_HEAD(&fs_info->allocated_ebs);
3075 spin_lock_init(&fs_info->eb_leak_lock);
bd647ce3 3076#endif
c8bf1b67 3077 extent_map_tree_init(&fs_info->mapping_tree);
66d8f3dd
MX
3078 btrfs_init_block_rsv(&fs_info->global_block_rsv,
3079 BTRFS_BLOCK_RSV_GLOBAL);
66d8f3dd
MX
3080 btrfs_init_block_rsv(&fs_info->trans_block_rsv, BTRFS_BLOCK_RSV_TRANS);
3081 btrfs_init_block_rsv(&fs_info->chunk_block_rsv, BTRFS_BLOCK_RSV_CHUNK);
3082 btrfs_init_block_rsv(&fs_info->empty_block_rsv, BTRFS_BLOCK_RSV_EMPTY);
3083 btrfs_init_block_rsv(&fs_info->delayed_block_rsv,
3084 BTRFS_BLOCK_RSV_DELOPS);
ba2c4d4e
JB
3085 btrfs_init_block_rsv(&fs_info->delayed_refs_rsv,
3086 BTRFS_BLOCK_RSV_DELREFS);
3087
771ed689 3088 atomic_set(&fs_info->async_delalloc_pages, 0);
4cb5300b 3089 atomic_set(&fs_info->defrag_running, 0);
034f784d 3090 atomic_set(&fs_info->nr_delayed_iputs, 0);
fc36ed7e 3091 atomic64_set(&fs_info->tree_mod_seq, 0);
abed4aaa 3092 fs_info->global_root_tree = RB_ROOT;
95ac567a 3093 fs_info->max_inline = BTRFS_DEFAULT_MAX_INLINE;
9ed74f2d 3094 fs_info->metadata_ratio = 0;
4cb5300b 3095 fs_info->defrag_inodes = RB_ROOT;
a5ed45f8 3096 atomic64_set(&fs_info->free_chunk_space, 0);
f29021b2 3097 fs_info->tree_mod_log = RB_ROOT;
8b87dc17 3098 fs_info->commit_interval = BTRFS_DEFAULT_COMMIT_INTERVAL;
f8c269d7 3099 fs_info->avg_delayed_ref_runtime = NSEC_PER_SEC >> 6; /* div by 64 */
fd708b81 3100 btrfs_init_ref_verify(fs_info);
c8b97818 3101
b34b086c
CM
3102 fs_info->thread_pool_size = min_t(unsigned long,
3103 num_online_cpus() + 2, 8);
0afbaf8c 3104
199c2a9c
MX
3105 INIT_LIST_HEAD(&fs_info->ordered_roots);
3106 spin_lock_init(&fs_info->ordered_root_lock);
69fe2d75 3107
638aa7ed 3108 btrfs_init_scrub(fs_info);
21adbd5c
SB
3109#ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
3110 fs_info->check_integrity_print_mask = 0;
3111#endif
779a65a4 3112 btrfs_init_balance(fs_info);
57056740 3113 btrfs_init_async_reclaim_work(fs_info);
a2de733c 3114
16b0c258 3115 rwlock_init(&fs_info->block_group_cache_lock);
08dddb29 3116 fs_info->block_group_cache_tree = RB_ROOT_CACHED;
0f9dd46c 3117
fe119a6e
NB
3118 extent_io_tree_init(fs_info, &fs_info->excluded_extents,
3119 IO_TREE_FS_EXCLUDED_EXTENTS, NULL);
39279cc3 3120
5a3f23d5 3121 mutex_init(&fs_info->ordered_operations_mutex);
e02119d5 3122 mutex_init(&fs_info->tree_log_mutex);
925baedd 3123 mutex_init(&fs_info->chunk_mutex);
a74a4b97
CM
3124 mutex_init(&fs_info->transaction_kthread_mutex);
3125 mutex_init(&fs_info->cleaner_mutex);
1bbc621e 3126 mutex_init(&fs_info->ro_block_group_mutex);
9e351cc8 3127 init_rwsem(&fs_info->commit_root_sem);
c71bf099 3128 init_rwsem(&fs_info->cleanup_work_sem);
76dda93c 3129 init_rwsem(&fs_info->subvol_sem);
803b2f54 3130 sema_init(&fs_info->uuid_tree_rescan_sem, 1);
fa9c0d79 3131
ad618368 3132 btrfs_init_dev_replace_locks(fs_info);
f9e92e40 3133 btrfs_init_qgroup(fs_info);
b0643e59 3134 btrfs_discard_init(fs_info);
416ac51d 3135
fa9c0d79
CM
3136 btrfs_init_free_cluster(&fs_info->meta_alloc_cluster);
3137 btrfs_init_free_cluster(&fs_info->data_alloc_cluster);
3138
e6dcd2dc 3139 init_waitqueue_head(&fs_info->transaction_throttle);
f9295749 3140 init_waitqueue_head(&fs_info->transaction_wait);
bb9c12c9 3141 init_waitqueue_head(&fs_info->transaction_blocked_wait);
4854ddd0 3142 init_waitqueue_head(&fs_info->async_submit_wait);
034f784d 3143 init_waitqueue_head(&fs_info->delayed_iputs_wait);
3768f368 3144
da17066c
JM
3145 /* Usable values until the real ones are cached from the superblock */
3146 fs_info->nodesize = 4096;
3147 fs_info->sectorsize = 4096;
ab108d99 3148 fs_info->sectorsize_bits = ilog2(4096);
da17066c
JM
3149 fs_info->stripesize = 4096;
3150
eede2bf3
OS
3151 spin_lock_init(&fs_info->swapfile_pins_lock);
3152 fs_info->swapfile_pins = RB_ROOT;
3153
18bb8bbf
JT
3154 fs_info->bg_reclaim_threshold = BTRFS_DEFAULT_RECLAIM_THRESH;
3155 INIT_WORK(&fs_info->reclaim_bgs_work, btrfs_reclaim_bgs_work);
8260edba
JB
3156}
3157
3158static int init_mount_fs_info(struct btrfs_fs_info *fs_info, struct super_block *sb)
3159{
3160 int ret;
3161
3162 fs_info->sb = sb;
3163 sb->s_blocksize = BTRFS_BDEV_BLOCKSIZE;
3164 sb->s_blocksize_bits = blksize_bits(BTRFS_BDEV_BLOCKSIZE);
9e967495 3165
5deb17e1 3166 ret = percpu_counter_init(&fs_info->ordered_bytes, 0, GFP_KERNEL);
ae18c37a 3167 if (ret)
c75e8394 3168 return ret;
ae18c37a
JB
3169
3170 ret = percpu_counter_init(&fs_info->dirty_metadata_bytes, 0, GFP_KERNEL);
3171 if (ret)
c75e8394 3172 return ret;
ae18c37a
JB
3173
3174 fs_info->dirty_metadata_batch = PAGE_SIZE *
3175 (1 + ilog2(nr_cpu_ids));
3176
3177 ret = percpu_counter_init(&fs_info->delalloc_bytes, 0, GFP_KERNEL);
3178 if (ret)
c75e8394 3179 return ret;
ae18c37a
JB
3180
3181 ret = percpu_counter_init(&fs_info->dev_replace.bio_counter, 0,
3182 GFP_KERNEL);
3183 if (ret)
c75e8394 3184 return ret;
ae18c37a
JB
3185
3186 fs_info->delayed_root = kmalloc(sizeof(struct btrfs_delayed_root),
3187 GFP_KERNEL);
c75e8394
JB
3188 if (!fs_info->delayed_root)
3189 return -ENOMEM;
ae18c37a
JB
3190 btrfs_init_delayed_root(fs_info->delayed_root);
3191
a0a1db70
FM
3192 if (sb_rdonly(sb))
3193 set_bit(BTRFS_FS_STATE_RO, &fs_info->fs_state);
3194
c75e8394 3195 return btrfs_alloc_stripe_hash_table(fs_info);
ae18c37a
JB
3196}
3197
97f4dd09
NB
3198static int btrfs_uuid_rescan_kthread(void *data)
3199{
0d031dc4 3200 struct btrfs_fs_info *fs_info = data;
97f4dd09
NB
3201 int ret;
3202
3203 /*
3204 * 1st step is to iterate through the existing UUID tree and
3205 * to delete all entries that contain outdated data.
3206 * 2nd step is to add all missing entries to the UUID tree.
3207 */
3208 ret = btrfs_uuid_tree_iterate(fs_info);
3209 if (ret < 0) {
c94bec2c
JB
3210 if (ret != -EINTR)
3211 btrfs_warn(fs_info, "iterating uuid_tree failed %d",
3212 ret);
97f4dd09
NB
3213 up(&fs_info->uuid_tree_rescan_sem);
3214 return ret;
3215 }
3216 return btrfs_uuid_scan_kthread(data);
3217}
3218
3219static int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
3220{
3221 struct task_struct *task;
3222
3223 down(&fs_info->uuid_tree_rescan_sem);
3224 task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
3225 if (IS_ERR(task)) {
3226 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
3227 btrfs_warn(fs_info, "failed to start uuid_rescan task");
3228 up(&fs_info->uuid_tree_rescan_sem);
3229 return PTR_ERR(task);
3230 }
3231
3232 return 0;
3233}
3234
8cd29088
BB
3235/*
3236 * Some options only have meaning at mount time and shouldn't persist across
3237 * remounts, or be displayed. Clear these at the end of mount and remount
3238 * code paths.
3239 */
3240void btrfs_clear_oneshot_options(struct btrfs_fs_info *fs_info)
3241{
3242 btrfs_clear_opt(fs_info->mount_opt, USEBACKUPROOT);
8b228324 3243 btrfs_clear_opt(fs_info->mount_opt, CLEAR_CACHE);
8cd29088
BB
3244}
3245
44c0ca21
BB
3246/*
3247 * Mounting logic specific to read-write file systems. Shared by open_ctree
3248 * and btrfs_remount when remounting from read-only to read-write.
3249 */
3250int btrfs_start_pre_rw_mount(struct btrfs_fs_info *fs_info)
3251{
3252 int ret;
94846229 3253 const bool cache_opt = btrfs_test_opt(fs_info, SPACE_CACHE);
8b228324
BB
3254 bool clear_free_space_tree = false;
3255
3256 if (btrfs_test_opt(fs_info, CLEAR_CACHE) &&
3257 btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
3258 clear_free_space_tree = true;
3259 } else if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
3260 !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID)) {
3261 btrfs_warn(fs_info, "free space tree is invalid");
3262 clear_free_space_tree = true;
3263 }
3264
3265 if (clear_free_space_tree) {
3266 btrfs_info(fs_info, "clearing free space tree");
3267 ret = btrfs_clear_free_space_tree(fs_info);
3268 if (ret) {
3269 btrfs_warn(fs_info,
3270 "failed to clear free space tree: %d", ret);
3271 goto out;
3272 }
3273 }
44c0ca21 3274
8d488a8c
FM
3275 /*
3276 * btrfs_find_orphan_roots() is responsible for finding all the dead
3277 * roots (with 0 refs), flag them with BTRFS_ROOT_DEAD_TREE and load
fc7cbcd4 3278 * them into the fs_info->fs_roots_radix tree. This must be done before
8d488a8c
FM
3279 * calling btrfs_orphan_cleanup() on the tree root. If we don't do it
3280 * first, then btrfs_orphan_cleanup() will delete a dead root's orphan
3281 * item before the root's tree is deleted - this means that if we unmount
3282 * or crash before the deletion completes, on the next mount we will not
3283 * delete what remains of the tree because the orphan item does not
3284 * exists anymore, which is what tells us we have a pending deletion.
3285 */
3286 ret = btrfs_find_orphan_roots(fs_info);
3287 if (ret)
3288 goto out;
3289
44c0ca21
BB
3290 ret = btrfs_cleanup_fs_roots(fs_info);
3291 if (ret)
3292 goto out;
3293
8f1c21d7
BB
3294 down_read(&fs_info->cleanup_work_sem);
3295 if ((ret = btrfs_orphan_cleanup(fs_info->fs_root)) ||
3296 (ret = btrfs_orphan_cleanup(fs_info->tree_root))) {
3297 up_read(&fs_info->cleanup_work_sem);
3298 goto out;
3299 }
3300 up_read(&fs_info->cleanup_work_sem);
3301
44c0ca21 3302 mutex_lock(&fs_info->cleaner_mutex);
7eefae6b 3303 ret = btrfs_recover_relocation(fs_info);
44c0ca21
BB
3304 mutex_unlock(&fs_info->cleaner_mutex);
3305 if (ret < 0) {
3306 btrfs_warn(fs_info, "failed to recover relocation: %d", ret);
3307 goto out;
3308 }
3309
5011139a
BB
3310 if (btrfs_test_opt(fs_info, FREE_SPACE_TREE) &&
3311 !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
3312 btrfs_info(fs_info, "creating free space tree");
3313 ret = btrfs_create_free_space_tree(fs_info);
3314 if (ret) {
3315 btrfs_warn(fs_info,
3316 "failed to create free space tree: %d", ret);
3317 goto out;
3318 }
3319 }
3320
94846229
BB
3321 if (cache_opt != btrfs_free_space_cache_v1_active(fs_info)) {
3322 ret = btrfs_set_free_space_cache_v1_active(fs_info, cache_opt);
3323 if (ret)
3324 goto out;
3325 }
3326
44c0ca21
BB
3327 ret = btrfs_resume_balance_async(fs_info);
3328 if (ret)
3329 goto out;
3330
3331 ret = btrfs_resume_dev_replace_async(fs_info);
3332 if (ret) {
3333 btrfs_warn(fs_info, "failed to resume dev_replace");
3334 goto out;
3335 }
3336
3337 btrfs_qgroup_rescan_resume(fs_info);
3338
3339 if (!fs_info->uuid_root) {
3340 btrfs_info(fs_info, "creating UUID tree");
3341 ret = btrfs_create_uuid_tree(fs_info);
3342 if (ret) {
3343 btrfs_warn(fs_info,
3344 "failed to create the UUID tree %d", ret);
3345 goto out;
3346 }
3347 }
3348
3349out:
3350 return ret;
3351}
3352
ae18c37a
JB
3353int __cold open_ctree(struct super_block *sb, struct btrfs_fs_devices *fs_devices,
3354 char *options)
3355{
3356 u32 sectorsize;
3357 u32 nodesize;
3358 u32 stripesize;
3359 u64 generation;
3360 u64 features;
3361 u16 csum_type;
ae18c37a
JB
3362 struct btrfs_super_block *disk_super;
3363 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
3364 struct btrfs_root *tree_root;
3365 struct btrfs_root *chunk_root;
3366 int ret;
3367 int err = -EINVAL;
ae18c37a
JB
3368 int level;
3369
8260edba 3370 ret = init_mount_fs_info(fs_info, sb);
53b381b3 3371 if (ret) {
83c8266a 3372 err = ret;
ae18c37a 3373 goto fail;
53b381b3
DW
3374 }
3375
ae18c37a
JB
3376 /* These need to be init'ed before we start creating inodes and such. */
3377 tree_root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID,
3378 GFP_KERNEL);
3379 fs_info->tree_root = tree_root;
3380 chunk_root = btrfs_alloc_root(fs_info, BTRFS_CHUNK_TREE_OBJECTID,
3381 GFP_KERNEL);
3382 fs_info->chunk_root = chunk_root;
3383 if (!tree_root || !chunk_root) {
3384 err = -ENOMEM;
c75e8394 3385 goto fail;
ae18c37a
JB
3386 }
3387
3388 fs_info->btree_inode = new_inode(sb);
3389 if (!fs_info->btree_inode) {
3390 err = -ENOMEM;
c75e8394 3391 goto fail;
ae18c37a
JB
3392 }
3393 mapping_set_gfp_mask(fs_info->btree_inode->i_mapping, GFP_NOFS);
3394 btrfs_init_btree_inode(fs_info);
3395
d24fa5c1 3396 invalidate_bdev(fs_devices->latest_dev->bdev);
1104a885
DS
3397
3398 /*
3399 * Read super block and check the signature bytes only
3400 */
d24fa5c1 3401 disk_super = btrfs_read_dev_super(fs_devices->latest_dev->bdev);
8f32380d
JT
3402 if (IS_ERR(disk_super)) {
3403 err = PTR_ERR(disk_super);
16cdcec7 3404 goto fail_alloc;
20b45077 3405 }
39279cc3 3406
8dc3f22c 3407 /*
260db43c 3408 * Verify the type first, if that or the checksum value are
8dc3f22c
JT
3409 * corrupted, we'll find out
3410 */
8f32380d 3411 csum_type = btrfs_super_csum_type(disk_super);
51bce6c9 3412 if (!btrfs_supported_super_csum(csum_type)) {
8dc3f22c 3413 btrfs_err(fs_info, "unsupported checksum algorithm: %u",
51bce6c9 3414 csum_type);
8dc3f22c 3415 err = -EINVAL;
8f32380d 3416 btrfs_release_disk_super(disk_super);
8dc3f22c
JT
3417 goto fail_alloc;
3418 }
3419
83c68bbc
SY
3420 fs_info->csum_size = btrfs_super_csum_size(disk_super);
3421
6d97c6e3
JT
3422 ret = btrfs_init_csum_hash(fs_info, csum_type);
3423 if (ret) {
3424 err = ret;
8f32380d 3425 btrfs_release_disk_super(disk_super);
6d97c6e3
JT
3426 goto fail_alloc;
3427 }
3428
1104a885
DS
3429 /*
3430 * We want to check superblock checksum, the type is stored inside.
3431 * Pass the whole disk block of size BTRFS_SUPER_INFO_SIZE (4k).
3432 */
8f32380d 3433 if (btrfs_check_super_csum(fs_info, (u8 *)disk_super)) {
05135f59 3434 btrfs_err(fs_info, "superblock checksum mismatch");
1104a885 3435 err = -EINVAL;
8f32380d 3436 btrfs_release_disk_super(disk_super);
141386e1 3437 goto fail_alloc;
1104a885
DS
3438 }
3439
3440 /*
3441 * super_copy is zeroed at allocation time and we never touch the
3442 * following bytes up to INFO_SIZE, the checksum is calculated from
3443 * the whole block of INFO_SIZE
3444 */
8f32380d
JT
3445 memcpy(fs_info->super_copy, disk_super, sizeof(*fs_info->super_copy));
3446 btrfs_release_disk_super(disk_super);
5f39d397 3447
fbc6feae
NB
3448 disk_super = fs_info->super_copy;
3449
0b86a832 3450
fbc6feae
NB
3451 features = btrfs_super_flags(disk_super);
3452 if (features & BTRFS_SUPER_FLAG_CHANGING_FSID_V2) {
3453 features &= ~BTRFS_SUPER_FLAG_CHANGING_FSID_V2;
3454 btrfs_set_super_flags(disk_super, features);
3455 btrfs_info(fs_info,
3456 "found metadata UUID change in progress flag, clearing");
3457 }
3458
3459 memcpy(fs_info->super_for_commit, fs_info->super_copy,
3460 sizeof(*fs_info->super_for_commit));
de37aa51 3461
069ec957 3462 ret = btrfs_validate_mount_super(fs_info);
1104a885 3463 if (ret) {
05135f59 3464 btrfs_err(fs_info, "superblock contains fatal errors");
1104a885 3465 err = -EINVAL;
141386e1 3466 goto fail_alloc;
1104a885
DS
3467 }
3468
0f7d52f4 3469 if (!btrfs_super_root(disk_super))
141386e1 3470 goto fail_alloc;
0f7d52f4 3471
acce952b 3472 /* check FS state, whether FS is broken. */
87533c47
MX
3473 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_ERROR)
3474 set_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state);
acce952b 3475
75e7cb7f
LB
3476 /*
3477 * In the long term, we'll store the compression type in the super
3478 * block, and it'll be used for per file compression control.
3479 */
3480 fs_info->compress_type = BTRFS_COMPRESS_ZLIB;
3481
6f93e834
AJ
3482 /*
3483 * Flag our filesystem as having big metadata blocks if they are bigger
3484 * than the page size.
3485 */
3486 if (btrfs_super_nodesize(disk_super) > PAGE_SIZE) {
3487 if (!(features & BTRFS_FEATURE_INCOMPAT_BIG_METADATA))
3488 btrfs_info(fs_info,
3489 "flagging fs with big metadata feature");
3490 features |= BTRFS_FEATURE_INCOMPAT_BIG_METADATA;
3491 }
3492
3493 /* Set up fs_info before parsing mount options */
3494 nodesize = btrfs_super_nodesize(disk_super);
3495 sectorsize = btrfs_super_sectorsize(disk_super);
3496 stripesize = sectorsize;
3497 fs_info->dirty_metadata_batch = nodesize * (1 + ilog2(nr_cpu_ids));
3498 fs_info->delalloc_batch = sectorsize * 512 * (1 + ilog2(nr_cpu_ids));
3499
3500 fs_info->nodesize = nodesize;
3501 fs_info->sectorsize = sectorsize;
3502 fs_info->sectorsize_bits = ilog2(sectorsize);
3503 fs_info->csums_per_leaf = BTRFS_MAX_ITEM_SIZE(fs_info) / fs_info->csum_size;
3504 fs_info->stripesize = stripesize;
3505
2ff7e61e 3506 ret = btrfs_parse_options(fs_info, options, sb->s_flags);
2b82032c
YZ
3507 if (ret) {
3508 err = ret;
141386e1 3509 goto fail_alloc;
2b82032c 3510 }
dfe25020 3511
f2b636e8
JB
3512 features = btrfs_super_incompat_flags(disk_super) &
3513 ~BTRFS_FEATURE_INCOMPAT_SUPP;
3514 if (features) {
05135f59 3515 btrfs_err(fs_info,
d5321a0f 3516 "cannot mount because of unsupported optional features (0x%llx)",
05135f59 3517 features);
f2b636e8 3518 err = -EINVAL;
141386e1 3519 goto fail_alloc;
f2b636e8
JB
3520 }
3521
5d4f98a2 3522 features = btrfs_super_incompat_flags(disk_super);
a6fa6fae 3523 features |= BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF;
0b246afa 3524 if (fs_info->compress_type == BTRFS_COMPRESS_LZO)
a6fa6fae 3525 features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_LZO;
5c1aab1d
NT
3526 else if (fs_info->compress_type == BTRFS_COMPRESS_ZSTD)
3527 features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_ZSTD;
727011e0 3528
3173a18f 3529 if (features & BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA)
05135f59 3530 btrfs_info(fs_info, "has skinny extents");
3173a18f 3531
bc3f116f
CM
3532 /*
3533 * mixed block groups end up with duplicate but slightly offset
3534 * extent buffers for the same range. It leads to corruptions
3535 */
3536 if ((features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) &&
707e8a07 3537 (sectorsize != nodesize)) {
05135f59
DS
3538 btrfs_err(fs_info,
3539"unequal nodesize/sectorsize (%u != %u) are not allowed for mixed block groups",
3540 nodesize, sectorsize);
141386e1 3541 goto fail_alloc;
bc3f116f
CM
3542 }
3543
ceda0864
MX
3544 /*
3545 * Needn't use the lock because there is no other task which will
3546 * update the flag.
3547 */
a6fa6fae 3548 btrfs_set_super_incompat_flags(disk_super, features);
5d4f98a2 3549
f2b636e8
JB
3550 features = btrfs_super_compat_ro_flags(disk_super) &
3551 ~BTRFS_FEATURE_COMPAT_RO_SUPP;
bc98a42c 3552 if (!sb_rdonly(sb) && features) {
05135f59 3553 btrfs_err(fs_info,
d5321a0f 3554 "cannot mount read-write because of unsupported optional features (0x%llx)",
c1c9ff7c 3555 features);
f2b636e8 3556 err = -EINVAL;
141386e1 3557 goto fail_alloc;
f2b636e8 3558 }
61d92c32 3559
8481dd80
QW
3560 if (sectorsize < PAGE_SIZE) {
3561 struct btrfs_subpage_info *subpage_info;
3562
9f73f1ae
QW
3563 /*
3564 * V1 space cache has some hardcoded PAGE_SIZE usage, and is
3565 * going to be deprecated.
3566 *
3567 * Force to use v2 cache for subpage case.
3568 */
3569 btrfs_clear_opt(fs_info->mount_opt, SPACE_CACHE);
3570 btrfs_set_and_info(fs_info, FREE_SPACE_TREE,
3571 "forcing free space tree for sector size %u with page size %lu",
3572 sectorsize, PAGE_SIZE);
3573
95ea0486
QW
3574 btrfs_warn(fs_info,
3575 "read-write for sector size %u with page size %lu is experimental",
3576 sectorsize, PAGE_SIZE);
8481dd80
QW
3577 subpage_info = kzalloc(sizeof(*subpage_info), GFP_KERNEL);
3578 if (!subpage_info)
3579 goto fail_alloc;
3580 btrfs_init_subpage_info(subpage_info, sectorsize);
3581 fs_info->subpage_info = subpage_info;
c8050b3b 3582 }
0bb3eb3e 3583
d21deec5 3584 ret = btrfs_init_workqueues(fs_info);
2a458198
ES
3585 if (ret) {
3586 err = ret;
0dc3b84a
JB
3587 goto fail_sb_buffer;
3588 }
4543df7e 3589
9e11ceee
JK
3590 sb->s_bdi->ra_pages *= btrfs_super_num_devices(disk_super);
3591 sb->s_bdi->ra_pages = max(sb->s_bdi->ra_pages, SZ_4M / PAGE_SIZE);
4575c9cc 3592
a061fc8d
CM
3593 sb->s_blocksize = sectorsize;
3594 sb->s_blocksize_bits = blksize_bits(sectorsize);
de37aa51 3595 memcpy(&sb->s_uuid, fs_info->fs_devices->fsid, BTRFS_FSID_SIZE);
db94535d 3596
925baedd 3597 mutex_lock(&fs_info->chunk_mutex);
6bccf3ab 3598 ret = btrfs_read_sys_array(fs_info);
925baedd 3599 mutex_unlock(&fs_info->chunk_mutex);
84eed90f 3600 if (ret) {
05135f59 3601 btrfs_err(fs_info, "failed to read the system array: %d", ret);
5d4f98a2 3602 goto fail_sb_buffer;
84eed90f 3603 }
0b86a832 3604
84234f3a 3605 generation = btrfs_super_chunk_root_generation(disk_super);
581c1760 3606 level = btrfs_super_chunk_root_level(disk_super);
bd676446
JB
3607 ret = load_super_root(chunk_root, btrfs_super_chunk_root(disk_super),
3608 generation, level);
3609 if (ret) {
05135f59 3610 btrfs_err(fs_info, "failed to read chunk root");
af31f5e5 3611 goto fail_tree_roots;
83121942 3612 }
0b86a832 3613
e17cade2 3614 read_extent_buffer(chunk_root->node, fs_info->chunk_tree_uuid,
c4ac7541
DS
3615 offsetof(struct btrfs_header, chunk_tree_uuid),
3616 BTRFS_UUID_SIZE);
e17cade2 3617
5b4aacef 3618 ret = btrfs_read_chunk_tree(fs_info);
2b82032c 3619 if (ret) {
05135f59 3620 btrfs_err(fs_info, "failed to read chunk tree: %d", ret);
af31f5e5 3621 goto fail_tree_roots;
2b82032c 3622 }
0b86a832 3623
8dabb742 3624 /*
bacce86a
AJ
3625 * At this point we know all the devices that make this filesystem,
3626 * including the seed devices but we don't know yet if the replace
3627 * target is required. So free devices that are not part of this
1a9fd417 3628 * filesystem but skip the replace target device which is checked
bacce86a 3629 * below in btrfs_init_dev_replace().
8dabb742 3630 */
bacce86a 3631 btrfs_free_extra_devids(fs_devices);
d24fa5c1 3632 if (!fs_devices->latest_dev->bdev) {
05135f59 3633 btrfs_err(fs_info, "failed to read devices");
a6b0d5c8
CM
3634 goto fail_tree_roots;
3635 }
3636
b8522a1e 3637 ret = init_tree_roots(fs_info);
4bbcaa64 3638 if (ret)
b8522a1e 3639 goto fail_tree_roots;
8929ecfa 3640
73651042
NA
3641 /*
3642 * Get zone type information of zoned block devices. This will also
3643 * handle emulation of a zoned filesystem if a regular device has the
3644 * zoned incompat feature flag set.
3645 */
3646 ret = btrfs_get_dev_zone_info_all_devices(fs_info);
3647 if (ret) {
3648 btrfs_err(fs_info,
3649 "zoned: failed to read device zone info: %d",
3650 ret);
3651 goto fail_block_groups;
3652 }
3653
75ec1db8
JB
3654 /*
3655 * If we have a uuid root and we're not being told to rescan we need to
3656 * check the generation here so we can set the
3657 * BTRFS_FS_UPDATE_UUID_TREE_GEN bit. Otherwise we could commit the
3658 * transaction during a balance or the log replay without updating the
3659 * uuid generation, and then if we crash we would rescan the uuid tree,
3660 * even though it was perfectly fine.
3661 */
3662 if (fs_info->uuid_root && !btrfs_test_opt(fs_info, RESCAN_UUID_TREE) &&
3663 fs_info->generation == btrfs_super_uuid_tree_generation(disk_super))
3664 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
3665
cf90d884
QW
3666 ret = btrfs_verify_dev_extents(fs_info);
3667 if (ret) {
3668 btrfs_err(fs_info,
3669 "failed to verify dev extents against chunks: %d",
3670 ret);
3671 goto fail_block_groups;
3672 }
68310a5e
ID
3673 ret = btrfs_recover_balance(fs_info);
3674 if (ret) {
05135f59 3675 btrfs_err(fs_info, "failed to recover balance: %d", ret);
68310a5e
ID
3676 goto fail_block_groups;
3677 }
3678
733f4fbb
SB
3679 ret = btrfs_init_dev_stats(fs_info);
3680 if (ret) {
05135f59 3681 btrfs_err(fs_info, "failed to init dev_stats: %d", ret);
733f4fbb
SB
3682 goto fail_block_groups;
3683 }
3684
8dabb742
SB
3685 ret = btrfs_init_dev_replace(fs_info);
3686 if (ret) {
05135f59 3687 btrfs_err(fs_info, "failed to init dev_replace: %d", ret);
8dabb742
SB
3688 goto fail_block_groups;
3689 }
3690
b70f5097
NA
3691 ret = btrfs_check_zoned_mode(fs_info);
3692 if (ret) {
3693 btrfs_err(fs_info, "failed to initialize zoned mode: %d",
3694 ret);
3695 goto fail_block_groups;
3696 }
3697
c6761a9e 3698 ret = btrfs_sysfs_add_fsid(fs_devices);
b7c35e81 3699 if (ret) {
05135f59
DS
3700 btrfs_err(fs_info, "failed to init sysfs fsid interface: %d",
3701 ret);
b7c35e81
AJ
3702 goto fail_block_groups;
3703 }
3704
96f3136e 3705 ret = btrfs_sysfs_add_mounted(fs_info);
c59021f8 3706 if (ret) {
05135f59 3707 btrfs_err(fs_info, "failed to init sysfs interface: %d", ret);
b7c35e81 3708 goto fail_fsdev_sysfs;
c59021f8 3709 }
3710
c59021f8 3711 ret = btrfs_init_space_info(fs_info);
3712 if (ret) {
05135f59 3713 btrfs_err(fs_info, "failed to initialize space info: %d", ret);
2365dd3c 3714 goto fail_sysfs;
c59021f8 3715 }
3716
5b4aacef 3717 ret = btrfs_read_block_groups(fs_info);
1b1d1f66 3718 if (ret) {
05135f59 3719 btrfs_err(fs_info, "failed to read block groups: %d", ret);
2365dd3c 3720 goto fail_sysfs;
1b1d1f66 3721 }
4330e183 3722
16beac87
NA
3723 btrfs_free_zone_cache(fs_info);
3724
5c78a5e7
AJ
3725 if (!sb_rdonly(sb) && fs_info->fs_devices->missing_devices &&
3726 !btrfs_check_rw_degradable(fs_info, NULL)) {
05135f59 3727 btrfs_warn(fs_info,
52042d8e 3728 "writable mount is not allowed due to too many missing devices");
2365dd3c 3729 goto fail_sysfs;
292fd7fc 3730 }
9078a3e1 3731
33c44184 3732 fs_info->cleaner_kthread = kthread_run(cleaner_kthread, fs_info,
a74a4b97 3733 "btrfs-cleaner");
57506d50 3734 if (IS_ERR(fs_info->cleaner_kthread))
2365dd3c 3735 goto fail_sysfs;
a74a4b97
CM
3736
3737 fs_info->transaction_kthread = kthread_run(transaction_kthread,
3738 tree_root,
3739 "btrfs-transaction");
57506d50 3740 if (IS_ERR(fs_info->transaction_kthread))
3f157a2f 3741 goto fail_cleaner;
a74a4b97 3742
583b7231 3743 if (!btrfs_test_opt(fs_info, NOSSD) &&
c289811c 3744 !fs_info->fs_devices->rotating) {
583b7231 3745 btrfs_set_and_info(fs_info, SSD, "enabling ssd optimizations");
c289811c
CM
3746 }
3747
572d9ab7 3748 /*
01327610 3749 * Mount does not set all options immediately, we can do it now and do
572d9ab7
DS
3750 * not have to wait for transaction commit
3751 */
3752 btrfs_apply_pending_changes(fs_info);
3818aea2 3753
21adbd5c 3754#ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
0b246afa 3755 if (btrfs_test_opt(fs_info, CHECK_INTEGRITY)) {
2ff7e61e 3756 ret = btrfsic_mount(fs_info, fs_devices,
0b246afa 3757 btrfs_test_opt(fs_info,
cbeaae4f 3758 CHECK_INTEGRITY_DATA) ? 1 : 0,
21adbd5c
SB
3759 fs_info->check_integrity_print_mask);
3760 if (ret)
05135f59
DS
3761 btrfs_warn(fs_info,
3762 "failed to initialize integrity check module: %d",
3763 ret);
21adbd5c
SB
3764 }
3765#endif
bcef60f2
AJ
3766 ret = btrfs_read_qgroup_config(fs_info);
3767 if (ret)
3768 goto fail_trans_kthread;
21adbd5c 3769
fd708b81
JB
3770 if (btrfs_build_ref_tree(fs_info))
3771 btrfs_err(fs_info, "couldn't build ref tree");
3772
96da0919
QW
3773 /* do not make disk changes in broken FS or nologreplay is given */
3774 if (btrfs_super_log_root(disk_super) != 0 &&
0b246afa 3775 !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
e8294f2f 3776 btrfs_info(fs_info, "start tree-log replay");
63443bf5 3777 ret = btrfs_replay_log(fs_info, fs_devices);
79787eaa 3778 if (ret) {
63443bf5 3779 err = ret;
28c16cbb 3780 goto fail_qgroup;
79787eaa 3781 }
e02119d5 3782 }
1a40e23b 3783
56e9357a 3784 fs_info->fs_root = btrfs_get_fs_root(fs_info, BTRFS_FS_TREE_OBJECTID, true);
3140c9a3
DC
3785 if (IS_ERR(fs_info->fs_root)) {
3786 err = PTR_ERR(fs_info->fs_root);
f50f4353 3787 btrfs_warn(fs_info, "failed to read fs tree: %d", err);
315bf8ef 3788 fs_info->fs_root = NULL;
bcef60f2 3789 goto fail_qgroup;
3140c9a3 3790 }
c289811c 3791
bc98a42c 3792 if (sb_rdonly(sb))
8cd29088 3793 goto clear_oneshot;
59641015 3794
44c0ca21 3795 ret = btrfs_start_pre_rw_mount(fs_info);
2b6ba629 3796 if (ret) {
6bccf3ab 3797 close_ctree(fs_info);
2b6ba629 3798 return ret;
e3acc2a6 3799 }
b0643e59 3800 btrfs_discard_resume(fs_info);
b382a324 3801
44c0ca21
BB
3802 if (fs_info->uuid_root &&
3803 (btrfs_test_opt(fs_info, RESCAN_UUID_TREE) ||
3804 fs_info->generation != btrfs_super_uuid_tree_generation(disk_super))) {
05135f59 3805 btrfs_info(fs_info, "checking UUID tree");
70f80175
SB
3806 ret = btrfs_check_uuid_tree(fs_info);
3807 if (ret) {
05135f59
DS
3808 btrfs_warn(fs_info,
3809 "failed to check the UUID tree: %d", ret);
6bccf3ab 3810 close_ctree(fs_info);
70f80175
SB
3811 return ret;
3812 }
f7a81ea4 3813 }
94846229 3814
afcdd129 3815 set_bit(BTRFS_FS_OPEN, &fs_info->flags);
47ab2a6c 3816
b4be6aef
JB
3817 /* Kick the cleaner thread so it'll start deleting snapshots. */
3818 if (test_bit(BTRFS_FS_UNFINISHED_DROPS, &fs_info->flags))
3819 wake_up_process(fs_info->cleaner_kthread);
3820
8cd29088
BB
3821clear_oneshot:
3822 btrfs_clear_oneshot_options(fs_info);
ad2b2c80 3823 return 0;
39279cc3 3824
bcef60f2
AJ
3825fail_qgroup:
3826 btrfs_free_qgroup_config(fs_info);
7c2ca468
CM
3827fail_trans_kthread:
3828 kthread_stop(fs_info->transaction_kthread);
2ff7e61e 3829 btrfs_cleanup_transaction(fs_info);
faa2dbf0 3830 btrfs_free_fs_roots(fs_info);
3f157a2f 3831fail_cleaner:
a74a4b97 3832 kthread_stop(fs_info->cleaner_kthread);
7c2ca468
CM
3833
3834 /*
3835 * make sure we're done with the btree inode before we stop our
3836 * kthreads
3837 */
3838 filemap_write_and_wait(fs_info->btree_inode->i_mapping);
7c2ca468 3839
2365dd3c 3840fail_sysfs:
6618a59b 3841 btrfs_sysfs_remove_mounted(fs_info);
2365dd3c 3842
b7c35e81
AJ
3843fail_fsdev_sysfs:
3844 btrfs_sysfs_remove_fsid(fs_info->fs_devices);
3845
1b1d1f66 3846fail_block_groups:
54067ae9 3847 btrfs_put_block_group_cache(fs_info);
af31f5e5
CM
3848
3849fail_tree_roots:
9e3aa805
JB
3850 if (fs_info->data_reloc_root)
3851 btrfs_drop_and_free_fs_root(fs_info, fs_info->data_reloc_root);
4273eaff 3852 free_root_pointers(fs_info, true);
2b8195bb 3853 invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
af31f5e5 3854
39279cc3 3855fail_sb_buffer:
7abadb64 3856 btrfs_stop_all_workers(fs_info);
5cdd7db6 3857 btrfs_free_block_groups(fs_info);
16cdcec7 3858fail_alloc:
586e46e2
ID
3859 btrfs_mapping_tree_free(&fs_info->mapping_tree);
3860
4543df7e 3861 iput(fs_info->btree_inode);
7e662854 3862fail:
586e46e2 3863 btrfs_close_devices(fs_info->fs_devices);
ad2b2c80 3864 return err;
eb60ceac 3865}
663faf9f 3866ALLOW_ERROR_INJECTION(open_ctree, ERRNO);
eb60ceac 3867
314b6dd0 3868static void btrfs_end_super_write(struct bio *bio)
f2984462 3869{
314b6dd0
JT
3870 struct btrfs_device *device = bio->bi_private;
3871 struct bio_vec *bvec;
3872 struct bvec_iter_all iter_all;
3873 struct page *page;
3874
3875 bio_for_each_segment_all(bvec, bio, iter_all) {
3876 page = bvec->bv_page;
3877
3878 if (bio->bi_status) {
3879 btrfs_warn_rl_in_rcu(device->fs_info,
3880 "lost page write due to IO error on %s (%d)",
3881 rcu_str_deref(device->name),
3882 blk_status_to_errno(bio->bi_status));
3883 ClearPageUptodate(page);
3884 SetPageError(page);
3885 btrfs_dev_stat_inc_and_print(device,
3886 BTRFS_DEV_STAT_WRITE_ERRS);
3887 } else {
3888 SetPageUptodate(page);
3889 }
3890
3891 put_page(page);
3892 unlock_page(page);
f2984462 3893 }
314b6dd0
JT
3894
3895 bio_put(bio);
f2984462
CM
3896}
3897
8f32380d
JT
3898struct btrfs_super_block *btrfs_read_dev_one_super(struct block_device *bdev,
3899 int copy_num)
29c36d72 3900{
29c36d72 3901 struct btrfs_super_block *super;
8f32380d 3902 struct page *page;
12659251 3903 u64 bytenr, bytenr_orig;
8f32380d 3904 struct address_space *mapping = bdev->bd_inode->i_mapping;
12659251
NA
3905 int ret;
3906
3907 bytenr_orig = btrfs_sb_offset(copy_num);
3908 ret = btrfs_sb_log_location_bdev(bdev, copy_num, READ, &bytenr);
3909 if (ret == -ENOENT)
3910 return ERR_PTR(-EINVAL);
3911 else if (ret)
3912 return ERR_PTR(ret);
29c36d72 3913
cda00eba 3914 if (bytenr + BTRFS_SUPER_INFO_SIZE >= bdev_nr_bytes(bdev))
8f32380d 3915 return ERR_PTR(-EINVAL);
29c36d72 3916
8f32380d
JT
3917 page = read_cache_page_gfp(mapping, bytenr >> PAGE_SHIFT, GFP_NOFS);
3918 if (IS_ERR(page))
3919 return ERR_CAST(page);
29c36d72 3920
8f32380d 3921 super = page_address(page);
96c2e067
AJ
3922 if (btrfs_super_magic(super) != BTRFS_MAGIC) {
3923 btrfs_release_disk_super(super);
3924 return ERR_PTR(-ENODATA);
3925 }
3926
12659251 3927 if (btrfs_super_bytenr(super) != bytenr_orig) {
8f32380d
JT
3928 btrfs_release_disk_super(super);
3929 return ERR_PTR(-EINVAL);
29c36d72
AJ
3930 }
3931
8f32380d 3932 return super;
29c36d72
AJ
3933}
3934
3935
8f32380d 3936struct btrfs_super_block *btrfs_read_dev_super(struct block_device *bdev)
a512bbf8 3937{
8f32380d 3938 struct btrfs_super_block *super, *latest = NULL;
a512bbf8
YZ
3939 int i;
3940 u64 transid = 0;
a512bbf8
YZ
3941
3942 /* we would like to check all the supers, but that would make
3943 * a btrfs mount succeed after a mkfs from a different FS.
3944 * So, we need to add a special mount option to scan for
3945 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
3946 */
3947 for (i = 0; i < 1; i++) {
8f32380d
JT
3948 super = btrfs_read_dev_one_super(bdev, i);
3949 if (IS_ERR(super))
a512bbf8
YZ
3950 continue;
3951
a512bbf8 3952 if (!latest || btrfs_super_generation(super) > transid) {
8f32380d
JT
3953 if (latest)
3954 btrfs_release_disk_super(super);
3955
3956 latest = super;
a512bbf8 3957 transid = btrfs_super_generation(super);
a512bbf8
YZ
3958 }
3959 }
92fc03fb 3960
8f32380d 3961 return super;
a512bbf8
YZ
3962}
3963
4eedeb75 3964/*
abbb3b8e 3965 * Write superblock @sb to the @device. Do not wait for completion, all the
314b6dd0 3966 * pages we use for writing are locked.
4eedeb75 3967 *
abbb3b8e
DS
3968 * Write @max_mirrors copies of the superblock, where 0 means default that fit
3969 * the expected device size at commit time. Note that max_mirrors must be
3970 * same for write and wait phases.
4eedeb75 3971 *
314b6dd0 3972 * Return number of errors when page is not found or submission fails.
4eedeb75 3973 */
a512bbf8 3974static int write_dev_supers(struct btrfs_device *device,
abbb3b8e 3975 struct btrfs_super_block *sb, int max_mirrors)
a512bbf8 3976{
d5178578 3977 struct btrfs_fs_info *fs_info = device->fs_info;
314b6dd0 3978 struct address_space *mapping = device->bdev->bd_inode->i_mapping;
d5178578 3979 SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
a512bbf8 3980 int i;
a512bbf8 3981 int errors = 0;
12659251
NA
3982 int ret;
3983 u64 bytenr, bytenr_orig;
a512bbf8
YZ
3984
3985 if (max_mirrors == 0)
3986 max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3987
d5178578
JT
3988 shash->tfm = fs_info->csum_shash;
3989
a512bbf8 3990 for (i = 0; i < max_mirrors; i++) {
314b6dd0
JT
3991 struct page *page;
3992 struct bio *bio;
3993 struct btrfs_super_block *disk_super;
3994
12659251
NA
3995 bytenr_orig = btrfs_sb_offset(i);
3996 ret = btrfs_sb_log_location(device, i, WRITE, &bytenr);
3997 if (ret == -ENOENT) {
3998 continue;
3999 } else if (ret < 0) {
4000 btrfs_err(device->fs_info,
4001 "couldn't get super block location for mirror %d",
4002 i);
4003 errors++;
4004 continue;
4005 }
935e5cc9
MX
4006 if (bytenr + BTRFS_SUPER_INFO_SIZE >=
4007 device->commit_total_bytes)
a512bbf8
YZ
4008 break;
4009
12659251 4010 btrfs_set_super_bytenr(sb, bytenr_orig);
4eedeb75 4011
fd08001f
EB
4012 crypto_shash_digest(shash, (const char *)sb + BTRFS_CSUM_SIZE,
4013 BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE,
4014 sb->csum);
4eedeb75 4015
314b6dd0
JT
4016 page = find_or_create_page(mapping, bytenr >> PAGE_SHIFT,
4017 GFP_NOFS);
4018 if (!page) {
abbb3b8e 4019 btrfs_err(device->fs_info,
314b6dd0 4020 "couldn't get super block page for bytenr %llu",
abbb3b8e
DS
4021 bytenr);
4022 errors++;
4eedeb75 4023 continue;
abbb3b8e 4024 }
634554dc 4025
314b6dd0
JT
4026 /* Bump the refcount for wait_dev_supers() */
4027 get_page(page);
a512bbf8 4028
314b6dd0
JT
4029 disk_super = page_address(page);
4030 memcpy(disk_super, sb, BTRFS_SUPER_INFO_SIZE);
4eedeb75 4031
314b6dd0
JT
4032 /*
4033 * Directly use bios here instead of relying on the page cache
4034 * to do I/O, so we don't lose the ability to do integrity
4035 * checking.
4036 */
07888c66
CH
4037 bio = bio_alloc(device->bdev, 1,
4038 REQ_OP_WRITE | REQ_SYNC | REQ_META | REQ_PRIO,
4039 GFP_NOFS);
314b6dd0
JT
4040 bio->bi_iter.bi_sector = bytenr >> SECTOR_SHIFT;
4041 bio->bi_private = device;
4042 bio->bi_end_io = btrfs_end_super_write;
4043 __bio_add_page(bio, page, BTRFS_SUPER_INFO_SIZE,
4044 offset_in_page(bytenr));
a512bbf8 4045
387125fc 4046 /*
314b6dd0
JT
4047 * We FUA only the first super block. The others we allow to
4048 * go down lazy and there's a short window where the on-disk
4049 * copies might still contain the older version.
387125fc 4050 */
1b9e619c 4051 if (i == 0 && !btrfs_test_opt(device->fs_info, NOBARRIER))
314b6dd0
JT
4052 bio->bi_opf |= REQ_FUA;
4053
58ff51f1
CH
4054 btrfsic_check_bio(bio);
4055 submit_bio(bio);
8376d9e1
NA
4056
4057 if (btrfs_advance_sb_log(device, i))
4058 errors++;
a512bbf8
YZ
4059 }
4060 return errors < i ? 0 : -1;
4061}
4062
abbb3b8e
DS
4063/*
4064 * Wait for write completion of superblocks done by write_dev_supers,
4065 * @max_mirrors same for write and wait phases.
4066 *
314b6dd0 4067 * Return number of errors when page is not found or not marked up to
abbb3b8e
DS
4068 * date.
4069 */
4070static int wait_dev_supers(struct btrfs_device *device, int max_mirrors)
4071{
abbb3b8e
DS
4072 int i;
4073 int errors = 0;
b6a535fa 4074 bool primary_failed = false;
12659251 4075 int ret;
abbb3b8e
DS
4076 u64 bytenr;
4077
4078 if (max_mirrors == 0)
4079 max_mirrors = BTRFS_SUPER_MIRROR_MAX;
4080
4081 for (i = 0; i < max_mirrors; i++) {
314b6dd0
JT
4082 struct page *page;
4083
12659251
NA
4084 ret = btrfs_sb_log_location(device, i, READ, &bytenr);
4085 if (ret == -ENOENT) {
4086 break;
4087 } else if (ret < 0) {
4088 errors++;
4089 if (i == 0)
4090 primary_failed = true;
4091 continue;
4092 }
abbb3b8e
DS
4093 if (bytenr + BTRFS_SUPER_INFO_SIZE >=
4094 device->commit_total_bytes)
4095 break;
4096
314b6dd0
JT
4097 page = find_get_page(device->bdev->bd_inode->i_mapping,
4098 bytenr >> PAGE_SHIFT);
4099 if (!page) {
abbb3b8e 4100 errors++;
b6a535fa
HM
4101 if (i == 0)
4102 primary_failed = true;
abbb3b8e
DS
4103 continue;
4104 }
314b6dd0
JT
4105 /* Page is submitted locked and unlocked once the IO completes */
4106 wait_on_page_locked(page);
4107 if (PageError(page)) {
abbb3b8e 4108 errors++;
b6a535fa
HM
4109 if (i == 0)
4110 primary_failed = true;
4111 }
abbb3b8e 4112
314b6dd0
JT
4113 /* Drop our reference */
4114 put_page(page);
abbb3b8e 4115
314b6dd0
JT
4116 /* Drop the reference from the writing run */
4117 put_page(page);
abbb3b8e
DS
4118 }
4119
b6a535fa
HM
4120 /* log error, force error return */
4121 if (primary_failed) {
4122 btrfs_err(device->fs_info, "error writing primary super block to device %llu",
4123 device->devid);
4124 return -1;
4125 }
4126
abbb3b8e
DS
4127 return errors < i ? 0 : -1;
4128}
4129
387125fc
CM
4130/*
4131 * endio for the write_dev_flush, this will wake anyone waiting
4132 * for the barrier when it is done
4133 */
4246a0b6 4134static void btrfs_end_empty_barrier(struct bio *bio)
387125fc 4135{
f9e69aa9 4136 bio_uninit(bio);
e0ae9994 4137 complete(bio->bi_private);
387125fc
CM
4138}
4139
4140/*
4fc6441a
AJ
4141 * Submit a flush request to the device if it supports it. Error handling is
4142 * done in the waiting counterpart.
387125fc 4143 */
4fc6441a 4144static void write_dev_flush(struct btrfs_device *device)
387125fc 4145{
f9e69aa9 4146 struct bio *bio = &device->flush_bio;
387125fc 4147
a91cf0ff
WY
4148#ifndef CONFIG_BTRFS_FS_CHECK_INTEGRITY
4149 /*
4150 * When a disk has write caching disabled, we skip submission of a bio
4151 * with flush and sync requests before writing the superblock, since
4152 * it's not needed. However when the integrity checker is enabled, this
4153 * results in reports that there are metadata blocks referred by a
4154 * superblock that were not properly flushed. So don't skip the bio
4155 * submission only when the integrity checker is enabled for the sake
4156 * of simplicity, since this is a debug tool and not meant for use in
4157 * non-debug builds.
4158 */
08e688fd 4159 if (!bdev_write_cache(device->bdev))
4fc6441a 4160 return;
a91cf0ff 4161#endif
387125fc 4162
f9e69aa9
CH
4163 bio_init(bio, device->bdev, NULL, 0,
4164 REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH);
387125fc 4165 bio->bi_end_io = btrfs_end_empty_barrier;
387125fc
CM
4166 init_completion(&device->flush_wait);
4167 bio->bi_private = &device->flush_wait;
387125fc 4168
58ff51f1
CH
4169 btrfsic_check_bio(bio);
4170 submit_bio(bio);
1c3063b6 4171 set_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
4fc6441a 4172}
387125fc 4173
4fc6441a
AJ
4174/*
4175 * If the flush bio has been submitted by write_dev_flush, wait for it.
4176 */
8c27cb35 4177static blk_status_t wait_dev_flush(struct btrfs_device *device)
4fc6441a 4178{
f9e69aa9 4179 struct bio *bio = &device->flush_bio;
387125fc 4180
1c3063b6 4181 if (!test_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state))
58efbc9f 4182 return BLK_STS_OK;
387125fc 4183
1c3063b6 4184 clear_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
2980d574 4185 wait_for_completion_io(&device->flush_wait);
387125fc 4186
8c27cb35 4187 return bio->bi_status;
387125fc 4188}
387125fc 4189
d10b82fe 4190static int check_barrier_error(struct btrfs_fs_info *fs_info)
401b41e5 4191{
6528b99d 4192 if (!btrfs_check_rw_degradable(fs_info, NULL))
401b41e5 4193 return -EIO;
387125fc
CM
4194 return 0;
4195}
4196
4197/*
4198 * send an empty flush down to each device in parallel,
4199 * then wait for them
4200 */
4201static int barrier_all_devices(struct btrfs_fs_info *info)
4202{
4203 struct list_head *head;
4204 struct btrfs_device *dev;
5af3e8cc 4205 int errors_wait = 0;
4e4cbee9 4206 blk_status_t ret;
387125fc 4207
1538e6c5 4208 lockdep_assert_held(&info->fs_devices->device_list_mutex);
387125fc
CM
4209 /* send down all the barriers */
4210 head = &info->fs_devices->devices;
1538e6c5 4211 list_for_each_entry(dev, head, dev_list) {
e6e674bd 4212 if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
f88ba6a2 4213 continue;
cea7c8bf 4214 if (!dev->bdev)
387125fc 4215 continue;
e12c9621 4216 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
ebbede42 4217 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
387125fc
CM
4218 continue;
4219
4fc6441a 4220 write_dev_flush(dev);
58efbc9f 4221 dev->last_flush_error = BLK_STS_OK;
387125fc
CM
4222 }
4223
4224 /* wait for all the barriers */
1538e6c5 4225 list_for_each_entry(dev, head, dev_list) {
e6e674bd 4226 if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
f88ba6a2 4227 continue;
387125fc 4228 if (!dev->bdev) {
5af3e8cc 4229 errors_wait++;
387125fc
CM
4230 continue;
4231 }
e12c9621 4232 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
ebbede42 4233 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
387125fc
CM
4234 continue;
4235
4fc6441a 4236 ret = wait_dev_flush(dev);
401b41e5
AJ
4237 if (ret) {
4238 dev->last_flush_error = ret;
66b4993e
DS
4239 btrfs_dev_stat_inc_and_print(dev,
4240 BTRFS_DEV_STAT_FLUSH_ERRS);
5af3e8cc 4241 errors_wait++;
401b41e5
AJ
4242 }
4243 }
4244
cea7c8bf 4245 if (errors_wait) {
401b41e5
AJ
4246 /*
4247 * At some point we need the status of all disks
4248 * to arrive at the volume status. So error checking
4249 * is being pushed to a separate loop.
4250 */
d10b82fe 4251 return check_barrier_error(info);
387125fc 4252 }
387125fc
CM
4253 return 0;
4254}
4255
943c6e99
ZL
4256int btrfs_get_num_tolerated_disk_barrier_failures(u64 flags)
4257{
8789f4fe
ZL
4258 int raid_type;
4259 int min_tolerated = INT_MAX;
943c6e99 4260
8789f4fe
ZL
4261 if ((flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 ||
4262 (flags & BTRFS_AVAIL_ALLOC_BIT_SINGLE))
8c3e3582 4263 min_tolerated = min_t(int, min_tolerated,
8789f4fe
ZL
4264 btrfs_raid_array[BTRFS_RAID_SINGLE].
4265 tolerated_failures);
943c6e99 4266
8789f4fe
ZL
4267 for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
4268 if (raid_type == BTRFS_RAID_SINGLE)
4269 continue;
41a6e891 4270 if (!(flags & btrfs_raid_array[raid_type].bg_flag))
8789f4fe 4271 continue;
8c3e3582 4272 min_tolerated = min_t(int, min_tolerated,
8789f4fe
ZL
4273 btrfs_raid_array[raid_type].
4274 tolerated_failures);
4275 }
943c6e99 4276
8789f4fe 4277 if (min_tolerated == INT_MAX) {
ab8d0fc4 4278 pr_warn("BTRFS: unknown raid flag: %llu", flags);
8789f4fe
ZL
4279 min_tolerated = 0;
4280 }
4281
4282 return min_tolerated;
943c6e99
ZL
4283}
4284
eece6a9c 4285int write_all_supers(struct btrfs_fs_info *fs_info, int max_mirrors)
f2984462 4286{
e5e9a520 4287 struct list_head *head;
f2984462 4288 struct btrfs_device *dev;
a061fc8d 4289 struct btrfs_super_block *sb;
f2984462 4290 struct btrfs_dev_item *dev_item;
f2984462
CM
4291 int ret;
4292 int do_barriers;
a236aed1
CM
4293 int max_errors;
4294 int total_errors = 0;
a061fc8d 4295 u64 flags;
f2984462 4296
0b246afa 4297 do_barriers = !btrfs_test_opt(fs_info, NOBARRIER);
fed3b381
LB
4298
4299 /*
4300 * max_mirrors == 0 indicates we're from commit_transaction,
4301 * not from fsync where the tree roots in fs_info have not
4302 * been consistent on disk.
4303 */
4304 if (max_mirrors == 0)
4305 backup_super_roots(fs_info);
f2984462 4306
0b246afa 4307 sb = fs_info->super_for_commit;
a061fc8d 4308 dev_item = &sb->dev_item;
e5e9a520 4309
0b246afa
JM
4310 mutex_lock(&fs_info->fs_devices->device_list_mutex);
4311 head = &fs_info->fs_devices->devices;
4312 max_errors = btrfs_super_num_devices(fs_info->super_copy) - 1;
387125fc 4313
5af3e8cc 4314 if (do_barriers) {
0b246afa 4315 ret = barrier_all_devices(fs_info);
5af3e8cc
SB
4316 if (ret) {
4317 mutex_unlock(
0b246afa
JM
4318 &fs_info->fs_devices->device_list_mutex);
4319 btrfs_handle_fs_error(fs_info, ret,
4320 "errors while submitting device barriers.");
5af3e8cc
SB
4321 return ret;
4322 }
4323 }
387125fc 4324
1538e6c5 4325 list_for_each_entry(dev, head, dev_list) {
dfe25020
CM
4326 if (!dev->bdev) {
4327 total_errors++;
4328 continue;
4329 }
e12c9621 4330 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
ebbede42 4331 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
dfe25020
CM
4332 continue;
4333
2b82032c 4334 btrfs_set_stack_device_generation(dev_item, 0);
a061fc8d
CM
4335 btrfs_set_stack_device_type(dev_item, dev->type);
4336 btrfs_set_stack_device_id(dev_item, dev->devid);
7df69d3e 4337 btrfs_set_stack_device_total_bytes(dev_item,
935e5cc9 4338 dev->commit_total_bytes);
ce7213c7
MX
4339 btrfs_set_stack_device_bytes_used(dev_item,
4340 dev->commit_bytes_used);
a061fc8d
CM
4341 btrfs_set_stack_device_io_align(dev_item, dev->io_align);
4342 btrfs_set_stack_device_io_width(dev_item, dev->io_width);
4343 btrfs_set_stack_device_sector_size(dev_item, dev->sector_size);
4344 memcpy(dev_item->uuid, dev->uuid, BTRFS_UUID_SIZE);
7239ff4b
NB
4345 memcpy(dev_item->fsid, dev->fs_devices->metadata_uuid,
4346 BTRFS_FSID_SIZE);
a512bbf8 4347
a061fc8d
CM
4348 flags = btrfs_super_flags(sb);
4349 btrfs_set_super_flags(sb, flags | BTRFS_HEADER_FLAG_WRITTEN);
4350
75cb857d
QW
4351 ret = btrfs_validate_write_super(fs_info, sb);
4352 if (ret < 0) {
4353 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4354 btrfs_handle_fs_error(fs_info, -EUCLEAN,
4355 "unexpected superblock corruption detected");
4356 return -EUCLEAN;
4357 }
4358
abbb3b8e 4359 ret = write_dev_supers(dev, sb, max_mirrors);
a236aed1
CM
4360 if (ret)
4361 total_errors++;
f2984462 4362 }
a236aed1 4363 if (total_errors > max_errors) {
0b246afa
JM
4364 btrfs_err(fs_info, "%d errors while writing supers",
4365 total_errors);
4366 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
79787eaa 4367
9d565ba4 4368 /* FUA is masked off if unsupported and can't be the reason */
0b246afa
JM
4369 btrfs_handle_fs_error(fs_info, -EIO,
4370 "%d errors while writing supers",
4371 total_errors);
9d565ba4 4372 return -EIO;
a236aed1 4373 }
f2984462 4374
a512bbf8 4375 total_errors = 0;
1538e6c5 4376 list_for_each_entry(dev, head, dev_list) {
dfe25020
CM
4377 if (!dev->bdev)
4378 continue;
e12c9621 4379 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
ebbede42 4380 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
dfe25020
CM
4381 continue;
4382
abbb3b8e 4383 ret = wait_dev_supers(dev, max_mirrors);
a512bbf8
YZ
4384 if (ret)
4385 total_errors++;
f2984462 4386 }
0b246afa 4387 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
a236aed1 4388 if (total_errors > max_errors) {
0b246afa
JM
4389 btrfs_handle_fs_error(fs_info, -EIO,
4390 "%d errors while writing supers",
4391 total_errors);
79787eaa 4392 return -EIO;
a236aed1 4393 }
f2984462
CM
4394 return 0;
4395}
4396
cb517eab
MX
4397/* Drop a fs root from the radix tree and free it. */
4398void btrfs_drop_and_free_fs_root(struct btrfs_fs_info *fs_info,
4399 struct btrfs_root *root)
2619ba1f 4400{
4785e24f
JB
4401 bool drop_ref = false;
4402
fc7cbcd4
DS
4403 spin_lock(&fs_info->fs_roots_radix_lock);
4404 radix_tree_delete(&fs_info->fs_roots_radix,
4405 (unsigned long)root->root_key.objectid);
4406 if (test_and_clear_bit(BTRFS_ROOT_IN_RADIX, &root->state))
4785e24f 4407 drop_ref = true;
fc7cbcd4 4408 spin_unlock(&fs_info->fs_roots_radix_lock);
76dda93c 4409
84961539 4410 if (BTRFS_FS_ERROR(fs_info)) {
ef67963d 4411 ASSERT(root->log_root == NULL);
1c1ea4f7 4412 if (root->reloc_root) {
00246528 4413 btrfs_put_root(root->reloc_root);
1c1ea4f7
LB
4414 root->reloc_root = NULL;
4415 }
4416 }
3321719e 4417
4785e24f
JB
4418 if (drop_ref)
4419 btrfs_put_root(root);
2619ba1f
CM
4420}
4421
c146afad 4422int btrfs_cleanup_fs_roots(struct btrfs_fs_info *fs_info)
cfaa7295 4423{
fc7cbcd4
DS
4424 u64 root_objectid = 0;
4425 struct btrfs_root *gang[8];
4426 int i = 0;
65d33fd7 4427 int err = 0;
fc7cbcd4 4428 unsigned int ret = 0;
e089f05c 4429
c146afad 4430 while (1) {
fc7cbcd4
DS
4431 spin_lock(&fs_info->fs_roots_radix_lock);
4432 ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
4433 (void **)gang, root_objectid,
4434 ARRAY_SIZE(gang));
4435 if (!ret) {
4436 spin_unlock(&fs_info->fs_roots_radix_lock);
4437 break;
65d33fd7 4438 }
fc7cbcd4 4439 root_objectid = gang[ret - 1]->root_key.objectid + 1;
65d33fd7 4440
fc7cbcd4
DS
4441 for (i = 0; i < ret; i++) {
4442 /* Avoid to grab roots in dead_roots */
4443 if (btrfs_root_refs(&gang[i]->root_item) == 0) {
4444 gang[i] = NULL;
4445 continue;
4446 }
4447 /* grab all the search result for later use */
4448 gang[i] = btrfs_grab_root(gang[i]);
65d33fd7 4449 }
fc7cbcd4 4450 spin_unlock(&fs_info->fs_roots_radix_lock);
66b4ffd1 4451
fc7cbcd4
DS
4452 for (i = 0; i < ret; i++) {
4453 if (!gang[i])
65d33fd7 4454 continue;
fc7cbcd4
DS
4455 root_objectid = gang[i]->root_key.objectid;
4456 err = btrfs_orphan_cleanup(gang[i]);
66b4ffd1 4457 if (err)
fc7cbcd4
DS
4458 break;
4459 btrfs_put_root(gang[i]);
c146afad 4460 }
fc7cbcd4 4461 root_objectid++;
c146afad 4462 }
65d33fd7 4463
fc7cbcd4
DS
4464 /* release the uncleaned roots due to error */
4465 for (; i < ret; i++) {
4466 if (gang[i])
4467 btrfs_put_root(gang[i]);
65d33fd7
QW
4468 }
4469 return err;
c146afad 4470}
a2135011 4471
6bccf3ab 4472int btrfs_commit_super(struct btrfs_fs_info *fs_info)
c146afad 4473{
6bccf3ab 4474 struct btrfs_root *root = fs_info->tree_root;
c146afad 4475 struct btrfs_trans_handle *trans;
a74a4b97 4476
0b246afa 4477 mutex_lock(&fs_info->cleaner_mutex);
2ff7e61e 4478 btrfs_run_delayed_iputs(fs_info);
0b246afa
JM
4479 mutex_unlock(&fs_info->cleaner_mutex);
4480 wake_up_process(fs_info->cleaner_kthread);
c71bf099
YZ
4481
4482 /* wait until ongoing cleanup work done */
0b246afa
JM
4483 down_write(&fs_info->cleanup_work_sem);
4484 up_write(&fs_info->cleanup_work_sem);
c71bf099 4485
7a7eaa40 4486 trans = btrfs_join_transaction(root);
3612b495
TI
4487 if (IS_ERR(trans))
4488 return PTR_ERR(trans);
3a45bb20 4489 return btrfs_commit_transaction(trans);
c146afad
YZ
4490}
4491
36c86a9e
QW
4492static void warn_about_uncommitted_trans(struct btrfs_fs_info *fs_info)
4493{
4494 struct btrfs_transaction *trans;
4495 struct btrfs_transaction *tmp;
4496 bool found = false;
4497
4498 if (list_empty(&fs_info->trans_list))
4499 return;
4500
4501 /*
4502 * This function is only called at the very end of close_ctree(),
4503 * thus no other running transaction, no need to take trans_lock.
4504 */
4505 ASSERT(test_bit(BTRFS_FS_CLOSING_DONE, &fs_info->flags));
4506 list_for_each_entry_safe(trans, tmp, &fs_info->trans_list, list) {
4507 struct extent_state *cached = NULL;
4508 u64 dirty_bytes = 0;
4509 u64 cur = 0;
4510 u64 found_start;
4511 u64 found_end;
4512
4513 found = true;
4514 while (!find_first_extent_bit(&trans->dirty_pages, cur,
4515 &found_start, &found_end, EXTENT_DIRTY, &cached)) {
4516 dirty_bytes += found_end + 1 - found_start;
4517 cur = found_end + 1;
4518 }
4519 btrfs_warn(fs_info,
4520 "transaction %llu (with %llu dirty metadata bytes) is not committed",
4521 trans->transid, dirty_bytes);
4522 btrfs_cleanup_one_transaction(trans, fs_info);
4523
4524 if (trans == fs_info->running_transaction)
4525 fs_info->running_transaction = NULL;
4526 list_del_init(&trans->list);
4527
4528 btrfs_put_transaction(trans);
4529 trace_btrfs_transaction_commit(fs_info);
4530 }
4531 ASSERT(!found);
4532}
4533
b105e927 4534void __cold close_ctree(struct btrfs_fs_info *fs_info)
c146afad 4535{
c146afad
YZ
4536 int ret;
4537
afcdd129 4538 set_bit(BTRFS_FS_CLOSING_START, &fs_info->flags);
31e70e52
FM
4539
4540 /*
4541 * We may have the reclaim task running and relocating a data block group,
4542 * in which case it may create delayed iputs. So stop it before we park
4543 * the cleaner kthread otherwise we can get new delayed iputs after
4544 * parking the cleaner, and that can make the async reclaim task to hang
4545 * if it's waiting for delayed iputs to complete, since the cleaner is
4546 * parked and can not run delayed iputs - this will make us hang when
4547 * trying to stop the async reclaim task.
4548 */
4549 cancel_work_sync(&fs_info->reclaim_bgs_work);
d6fd0ae2
OS
4550 /*
4551 * We don't want the cleaner to start new transactions, add more delayed
4552 * iputs, etc. while we're closing. We can't use kthread_stop() yet
4553 * because that frees the task_struct, and the transaction kthread might
4554 * still try to wake up the cleaner.
4555 */
4556 kthread_park(fs_info->cleaner_kthread);
c146afad 4557
b4be6aef
JB
4558 /*
4559 * If we had UNFINISHED_DROPS we could still be processing them, so
4560 * clear that bit and wake up relocation so it can stop.
4561 */
4562 btrfs_wake_unfinished_drop(fs_info);
4563
7343dd61 4564 /* wait for the qgroup rescan worker to stop */
d06f23d6 4565 btrfs_qgroup_wait_for_completion(fs_info, false);
7343dd61 4566
803b2f54
SB
4567 /* wait for the uuid_scan task to finish */
4568 down(&fs_info->uuid_tree_rescan_sem);
4569 /* avoid complains from lockdep et al., set sem back to initial state */
4570 up(&fs_info->uuid_tree_rescan_sem);
4571
837d5b6e 4572 /* pause restriper - we want to resume on mount */
aa1b8cd4 4573 btrfs_pause_balance(fs_info);
837d5b6e 4574
8dabb742
SB
4575 btrfs_dev_replace_suspend_for_unmount(fs_info);
4576
aa1b8cd4 4577 btrfs_scrub_cancel(fs_info);
4cb5300b
CM
4578
4579 /* wait for any defraggers to finish */
4580 wait_event(fs_info->transaction_wait,
4581 (atomic_read(&fs_info->defrag_running) == 0));
4582
4583 /* clear out the rbtree of defraggable inodes */
26176e7c 4584 btrfs_cleanup_defrag_inodes(fs_info);
4cb5300b 4585
21c7e756 4586 cancel_work_sync(&fs_info->async_reclaim_work);
57056740 4587 cancel_work_sync(&fs_info->async_data_reclaim_work);
576fa348 4588 cancel_work_sync(&fs_info->preempt_reclaim_work);
21c7e756 4589
b0643e59
DZ
4590 /* Cancel or finish ongoing discard work */
4591 btrfs_discard_cleanup(fs_info);
4592
bc98a42c 4593 if (!sb_rdonly(fs_info->sb)) {
e44163e1 4594 /*
d6fd0ae2
OS
4595 * The cleaner kthread is stopped, so do one final pass over
4596 * unused block groups.
e44163e1 4597 */
0b246afa 4598 btrfs_delete_unused_bgs(fs_info);
e44163e1 4599
f0cc2cd7
FM
4600 /*
4601 * There might be existing delayed inode workers still running
4602 * and holding an empty delayed inode item. We must wait for
4603 * them to complete first because they can create a transaction.
4604 * This happens when someone calls btrfs_balance_delayed_items()
4605 * and then a transaction commit runs the same delayed nodes
4606 * before any delayed worker has done something with the nodes.
4607 * We must wait for any worker here and not at transaction
4608 * commit time since that could cause a deadlock.
4609 * This is a very rare case.
4610 */
4611 btrfs_flush_workqueue(fs_info->delayed_workers);
4612
6bccf3ab 4613 ret = btrfs_commit_super(fs_info);
acce952b 4614 if (ret)
04892340 4615 btrfs_err(fs_info, "commit super ret %d", ret);
acce952b 4616 }
4617
84961539 4618 if (BTRFS_FS_ERROR(fs_info))
2ff7e61e 4619 btrfs_error_commit_super(fs_info);
0f7d52f4 4620
e3029d9f
AV
4621 kthread_stop(fs_info->transaction_kthread);
4622 kthread_stop(fs_info->cleaner_kthread);
8929ecfa 4623
e187831e 4624 ASSERT(list_empty(&fs_info->delayed_iputs));
afcdd129 4625 set_bit(BTRFS_FS_CLOSING_DONE, &fs_info->flags);
f25784b3 4626
5958253c
QW
4627 if (btrfs_check_quota_leak(fs_info)) {
4628 WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
4629 btrfs_err(fs_info, "qgroup reserved space leaked");
4630 }
4631
04892340 4632 btrfs_free_qgroup_config(fs_info);
fe816d0f 4633 ASSERT(list_empty(&fs_info->delalloc_roots));
bcef60f2 4634
963d678b 4635 if (percpu_counter_sum(&fs_info->delalloc_bytes)) {
04892340 4636 btrfs_info(fs_info, "at unmount delalloc count %lld",
963d678b 4637 percpu_counter_sum(&fs_info->delalloc_bytes));
b0c68f8b 4638 }
bcc63abb 4639
5deb17e1 4640 if (percpu_counter_sum(&fs_info->ordered_bytes))
4297ff84 4641 btrfs_info(fs_info, "at unmount dio bytes count %lld",
5deb17e1 4642 percpu_counter_sum(&fs_info->ordered_bytes));
4297ff84 4643
6618a59b 4644 btrfs_sysfs_remove_mounted(fs_info);
b7c35e81 4645 btrfs_sysfs_remove_fsid(fs_info->fs_devices);
5ac1d209 4646
1a4319cc
LB
4647 btrfs_put_block_group_cache(fs_info);
4648
de348ee0
WS
4649 /*
4650 * we must make sure there is not any read request to
4651 * submit after we stopping all workers.
4652 */
4653 invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
96192499
JB
4654 btrfs_stop_all_workers(fs_info);
4655
0a31daa4 4656 /* We shouldn't have any transaction open at this point */
36c86a9e 4657 warn_about_uncommitted_trans(fs_info);
0a31daa4 4658
afcdd129 4659 clear_bit(BTRFS_FS_OPEN, &fs_info->flags);
4273eaff 4660 free_root_pointers(fs_info, true);
8c38938c 4661 btrfs_free_fs_roots(fs_info);
9ad6b7bc 4662
4e19443d
JB
4663 /*
4664 * We must free the block groups after dropping the fs_roots as we could
4665 * have had an IO error and have left over tree log blocks that aren't
4666 * cleaned up until the fs roots are freed. This makes the block group
4667 * accounting appear to be wrong because there's pending reserved bytes,
4668 * so make sure we do the block group cleanup afterwards.
4669 */
4670 btrfs_free_block_groups(fs_info);
4671
13e6c37b 4672 iput(fs_info->btree_inode);
d6bfde87 4673
21adbd5c 4674#ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
0b246afa 4675 if (btrfs_test_opt(fs_info, CHECK_INTEGRITY))
2ff7e61e 4676 btrfsic_unmount(fs_info->fs_devices);
21adbd5c
SB
4677#endif
4678
0b86a832 4679 btrfs_mapping_tree_free(&fs_info->mapping_tree);
68c94e55 4680 btrfs_close_devices(fs_info->fs_devices);
eb60ceac
CM
4681}
4682
b9fab919
CM
4683int btrfs_buffer_uptodate(struct extent_buffer *buf, u64 parent_transid,
4684 int atomic)
5f39d397 4685{
1259ab75 4686 int ret;
727011e0 4687 struct inode *btree_inode = buf->pages[0]->mapping->host;
1259ab75 4688
0b32f4bb 4689 ret = extent_buffer_uptodate(buf);
1259ab75
CM
4690 if (!ret)
4691 return ret;
4692
4693 ret = verify_parent_transid(&BTRFS_I(btree_inode)->io_tree, buf,
b9fab919
CM
4694 parent_transid, atomic);
4695 if (ret == -EAGAIN)
4696 return ret;
1259ab75 4697 return !ret;
5f39d397
CM
4698}
4699
5f39d397
CM
4700void btrfs_mark_buffer_dirty(struct extent_buffer *buf)
4701{
2f4d60df 4702 struct btrfs_fs_info *fs_info = buf->fs_info;
5f39d397 4703 u64 transid = btrfs_header_generation(buf);
b9473439 4704 int was_dirty;
b4ce94de 4705
06ea65a3
JB
4706#ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
4707 /*
4708 * This is a fast path so only do this check if we have sanity tests
52042d8e 4709 * enabled. Normal people shouldn't be using unmapped buffers as dirty
06ea65a3
JB
4710 * outside of the sanity tests.
4711 */
b0132a3b 4712 if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &buf->bflags)))
06ea65a3
JB
4713 return;
4714#endif
49d0c642 4715 btrfs_assert_tree_write_locked(buf);
0b246afa 4716 if (transid != fs_info->generation)
5d163e0e 4717 WARN(1, KERN_CRIT "btrfs transid mismatch buffer %llu, found %llu running %llu\n",
0b246afa 4718 buf->start, transid, fs_info->generation);
0b32f4bb 4719 was_dirty = set_extent_buffer_dirty(buf);
e2d84521 4720 if (!was_dirty)
104b4e51
NB
4721 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
4722 buf->len,
4723 fs_info->dirty_metadata_batch);
1f21ef0a 4724#ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
69fc6cbb
QW
4725 /*
4726 * Since btrfs_mark_buffer_dirty() can be called with item pointer set
4727 * but item data not updated.
4728 * So here we should only check item pointers, not item data.
4729 */
4730 if (btrfs_header_level(buf) == 0 &&
cfdaad5e 4731 btrfs_check_leaf_relaxed(buf)) {
a4f78750 4732 btrfs_print_leaf(buf);
1f21ef0a
FM
4733 ASSERT(0);
4734 }
4735#endif
eb60ceac
CM
4736}
4737
2ff7e61e 4738static void __btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info,
b53d3f5d 4739 int flush_delayed)
16cdcec7
MX
4740{
4741 /*
4742 * looks as though older kernels can get into trouble with
4743 * this code, they end up stuck in balance_dirty_pages forever
4744 */
e2d84521 4745 int ret;
16cdcec7
MX
4746
4747 if (current->flags & PF_MEMALLOC)
4748 return;
4749
b53d3f5d 4750 if (flush_delayed)
2ff7e61e 4751 btrfs_balance_delayed_items(fs_info);
16cdcec7 4752
d814a491
EL
4753 ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
4754 BTRFS_DIRTY_METADATA_THRESH,
4755 fs_info->dirty_metadata_batch);
e2d84521 4756 if (ret > 0) {
0b246afa 4757 balance_dirty_pages_ratelimited(fs_info->btree_inode->i_mapping);
16cdcec7 4758 }
16cdcec7
MX
4759}
4760
2ff7e61e 4761void btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info)
35b7e476 4762{
2ff7e61e 4763 __btrfs_btree_balance_dirty(fs_info, 1);
b53d3f5d 4764}
585ad2c3 4765
2ff7e61e 4766void btrfs_btree_balance_dirty_nodelay(struct btrfs_fs_info *fs_info)
b53d3f5d 4767{
2ff7e61e 4768 __btrfs_btree_balance_dirty(fs_info, 0);
35b7e476 4769}
6b80053d 4770
2ff7e61e 4771static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info)
acce952b 4772{
fe816d0f
NB
4773 /* cleanup FS via transaction */
4774 btrfs_cleanup_transaction(fs_info);
4775
0b246afa 4776 mutex_lock(&fs_info->cleaner_mutex);
2ff7e61e 4777 btrfs_run_delayed_iputs(fs_info);
0b246afa 4778 mutex_unlock(&fs_info->cleaner_mutex);
acce952b 4779
0b246afa
JM
4780 down_write(&fs_info->cleanup_work_sem);
4781 up_write(&fs_info->cleanup_work_sem);
acce952b 4782}
4783
ef67963d
JB
4784static void btrfs_drop_all_logs(struct btrfs_fs_info *fs_info)
4785{
fc7cbcd4
DS
4786 struct btrfs_root *gang[8];
4787 u64 root_objectid = 0;
4788 int ret;
4789
4790 spin_lock(&fs_info->fs_roots_radix_lock);
4791 while ((ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
4792 (void **)gang, root_objectid,
4793 ARRAY_SIZE(gang))) != 0) {
4794 int i;
4795
4796 for (i = 0; i < ret; i++)
4797 gang[i] = btrfs_grab_root(gang[i]);
4798 spin_unlock(&fs_info->fs_roots_radix_lock);
4799
4800 for (i = 0; i < ret; i++) {
4801 if (!gang[i])
ef67963d 4802 continue;
fc7cbcd4
DS
4803 root_objectid = gang[i]->root_key.objectid;
4804 btrfs_free_log(NULL, gang[i]);
4805 btrfs_put_root(gang[i]);
ef67963d 4806 }
fc7cbcd4
DS
4807 root_objectid++;
4808 spin_lock(&fs_info->fs_roots_radix_lock);
ef67963d 4809 }
fc7cbcd4 4810 spin_unlock(&fs_info->fs_roots_radix_lock);
ef67963d
JB
4811 btrfs_free_log_root_tree(NULL, fs_info);
4812}
4813
143bede5 4814static void btrfs_destroy_ordered_extents(struct btrfs_root *root)
acce952b 4815{
acce952b 4816 struct btrfs_ordered_extent *ordered;
acce952b 4817
199c2a9c 4818 spin_lock(&root->ordered_extent_lock);
779880ef
JB
4819 /*
4820 * This will just short circuit the ordered completion stuff which will
4821 * make sure the ordered extent gets properly cleaned up.
4822 */
199c2a9c 4823 list_for_each_entry(ordered, &root->ordered_extents,
779880ef
JB
4824 root_extent_list)
4825 set_bit(BTRFS_ORDERED_IOERR, &ordered->flags);
199c2a9c
MX
4826 spin_unlock(&root->ordered_extent_lock);
4827}
4828
4829static void btrfs_destroy_all_ordered_extents(struct btrfs_fs_info *fs_info)
4830{
4831 struct btrfs_root *root;
4832 struct list_head splice;
4833
4834 INIT_LIST_HEAD(&splice);
4835
4836 spin_lock(&fs_info->ordered_root_lock);
4837 list_splice_init(&fs_info->ordered_roots, &splice);
4838 while (!list_empty(&splice)) {
4839 root = list_first_entry(&splice, struct btrfs_root,
4840 ordered_root);
1de2cfde
JB
4841 list_move_tail(&root->ordered_root,
4842 &fs_info->ordered_roots);
199c2a9c 4843
2a85d9ca 4844 spin_unlock(&fs_info->ordered_root_lock);
199c2a9c
MX
4845 btrfs_destroy_ordered_extents(root);
4846
2a85d9ca
LB
4847 cond_resched();
4848 spin_lock(&fs_info->ordered_root_lock);
199c2a9c
MX
4849 }
4850 spin_unlock(&fs_info->ordered_root_lock);
74d5d229
JB
4851
4852 /*
4853 * We need this here because if we've been flipped read-only we won't
4854 * get sync() from the umount, so we need to make sure any ordered
4855 * extents that haven't had their dirty pages IO start writeout yet
4856 * actually get run and error out properly.
4857 */
4858 btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
acce952b 4859}
4860
35a3621b 4861static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
2ff7e61e 4862 struct btrfs_fs_info *fs_info)
acce952b 4863{
4864 struct rb_node *node;
4865 struct btrfs_delayed_ref_root *delayed_refs;
4866 struct btrfs_delayed_ref_node *ref;
4867 int ret = 0;
4868
4869 delayed_refs = &trans->delayed_refs;
4870
4871 spin_lock(&delayed_refs->lock);
d7df2c79 4872 if (atomic_read(&delayed_refs->num_entries) == 0) {
cfece4db 4873 spin_unlock(&delayed_refs->lock);
b79ce3dd 4874 btrfs_debug(fs_info, "delayed_refs has NO entry");
acce952b 4875 return ret;
4876 }
4877
5c9d028b 4878 while ((node = rb_first_cached(&delayed_refs->href_root)) != NULL) {
d7df2c79 4879 struct btrfs_delayed_ref_head *head;
0e0adbcf 4880 struct rb_node *n;
e78417d1 4881 bool pin_bytes = false;
acce952b 4882
d7df2c79
JB
4883 head = rb_entry(node, struct btrfs_delayed_ref_head,
4884 href_node);
3069bd26 4885 if (btrfs_delayed_ref_lock(delayed_refs, head))
d7df2c79 4886 continue;
3069bd26 4887
d7df2c79 4888 spin_lock(&head->lock);
e3d03965 4889 while ((n = rb_first_cached(&head->ref_tree)) != NULL) {
0e0adbcf
JB
4890 ref = rb_entry(n, struct btrfs_delayed_ref_node,
4891 ref_node);
d7df2c79 4892 ref->in_tree = 0;
e3d03965 4893 rb_erase_cached(&ref->ref_node, &head->ref_tree);
0e0adbcf 4894 RB_CLEAR_NODE(&ref->ref_node);
1d57ee94
WX
4895 if (!list_empty(&ref->add_list))
4896 list_del(&ref->add_list);
d7df2c79
JB
4897 atomic_dec(&delayed_refs->num_entries);
4898 btrfs_put_delayed_ref(ref);
e78417d1 4899 }
d7df2c79
JB
4900 if (head->must_insert_reserved)
4901 pin_bytes = true;
4902 btrfs_free_delayed_extent_op(head->extent_op);
fa781cea 4903 btrfs_delete_ref_head(delayed_refs, head);
d7df2c79
JB
4904 spin_unlock(&head->lock);
4905 spin_unlock(&delayed_refs->lock);
4906 mutex_unlock(&head->mutex);
acce952b 4907
f603bb94
NB
4908 if (pin_bytes) {
4909 struct btrfs_block_group *cache;
4910
4911 cache = btrfs_lookup_block_group(fs_info, head->bytenr);
4912 BUG_ON(!cache);
4913
4914 spin_lock(&cache->space_info->lock);
4915 spin_lock(&cache->lock);
4916 cache->pinned += head->num_bytes;
4917 btrfs_space_info_update_bytes_pinned(fs_info,
4918 cache->space_info, head->num_bytes);
4919 cache->reserved -= head->num_bytes;
4920 cache->space_info->bytes_reserved -= head->num_bytes;
4921 spin_unlock(&cache->lock);
4922 spin_unlock(&cache->space_info->lock);
f603bb94
NB
4923
4924 btrfs_put_block_group(cache);
4925
4926 btrfs_error_unpin_extent_range(fs_info, head->bytenr,
4927 head->bytenr + head->num_bytes - 1);
4928 }
31890da0 4929 btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
d278850e 4930 btrfs_put_delayed_ref_head(head);
acce952b 4931 cond_resched();
4932 spin_lock(&delayed_refs->lock);
4933 }
81f7eb00 4934 btrfs_qgroup_destroy_extent_records(trans);
acce952b 4935
4936 spin_unlock(&delayed_refs->lock);
4937
4938 return ret;
4939}
4940
143bede5 4941static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root)
acce952b 4942{
4943 struct btrfs_inode *btrfs_inode;
4944 struct list_head splice;
4945
4946 INIT_LIST_HEAD(&splice);
4947
eb73c1b7
MX
4948 spin_lock(&root->delalloc_lock);
4949 list_splice_init(&root->delalloc_inodes, &splice);
acce952b 4950
4951 while (!list_empty(&splice)) {
fe816d0f 4952 struct inode *inode = NULL;
eb73c1b7
MX
4953 btrfs_inode = list_first_entry(&splice, struct btrfs_inode,
4954 delalloc_inodes);
fe816d0f 4955 __btrfs_del_delalloc_inode(root, btrfs_inode);
eb73c1b7 4956 spin_unlock(&root->delalloc_lock);
acce952b 4957
fe816d0f
NB
4958 /*
4959 * Make sure we get a live inode and that it'll not disappear
4960 * meanwhile.
4961 */
4962 inode = igrab(&btrfs_inode->vfs_inode);
4963 if (inode) {
4964 invalidate_inode_pages2(inode->i_mapping);
4965 iput(inode);
4966 }
eb73c1b7 4967 spin_lock(&root->delalloc_lock);
acce952b 4968 }
eb73c1b7
MX
4969 spin_unlock(&root->delalloc_lock);
4970}
4971
4972static void btrfs_destroy_all_delalloc_inodes(struct btrfs_fs_info *fs_info)
4973{
4974 struct btrfs_root *root;
4975 struct list_head splice;
4976
4977 INIT_LIST_HEAD(&splice);
4978
4979 spin_lock(&fs_info->delalloc_root_lock);
4980 list_splice_init(&fs_info->delalloc_roots, &splice);
4981 while (!list_empty(&splice)) {
4982 root = list_first_entry(&splice, struct btrfs_root,
4983 delalloc_root);
00246528 4984 root = btrfs_grab_root(root);
eb73c1b7
MX
4985 BUG_ON(!root);
4986 spin_unlock(&fs_info->delalloc_root_lock);
4987
4988 btrfs_destroy_delalloc_inodes(root);
00246528 4989 btrfs_put_root(root);
eb73c1b7
MX
4990
4991 spin_lock(&fs_info->delalloc_root_lock);
4992 }
4993 spin_unlock(&fs_info->delalloc_root_lock);
acce952b 4994}
4995
2ff7e61e 4996static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
acce952b 4997 struct extent_io_tree *dirty_pages,
4998 int mark)
4999{
5000 int ret;
acce952b 5001 struct extent_buffer *eb;
5002 u64 start = 0;
5003 u64 end;
acce952b 5004
5005 while (1) {
5006 ret = find_first_extent_bit(dirty_pages, start, &start, &end,
e6138876 5007 mark, NULL);
acce952b 5008 if (ret)
5009 break;
5010
91166212 5011 clear_extent_bits(dirty_pages, start, end, mark);
acce952b 5012 while (start <= end) {
0b246afa
JM
5013 eb = find_extent_buffer(fs_info, start);
5014 start += fs_info->nodesize;
fd8b2b61 5015 if (!eb)
acce952b 5016 continue;
fd8b2b61 5017 wait_on_extent_buffer_writeback(eb);
acce952b 5018
fd8b2b61
JB
5019 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY,
5020 &eb->bflags))
5021 clear_extent_buffer_dirty(eb);
5022 free_extent_buffer_stale(eb);
acce952b 5023 }
5024 }
5025
5026 return ret;
5027}
5028
2ff7e61e 5029static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
fe119a6e 5030 struct extent_io_tree *unpin)
acce952b 5031{
acce952b 5032 u64 start;
5033 u64 end;
5034 int ret;
5035
acce952b 5036 while (1) {
0e6ec385
FM
5037 struct extent_state *cached_state = NULL;
5038
fcd5e742
LF
5039 /*
5040 * The btrfs_finish_extent_commit() may get the same range as
5041 * ours between find_first_extent_bit and clear_extent_dirty.
5042 * Hence, hold the unused_bg_unpin_mutex to avoid double unpin
5043 * the same extent range.
5044 */
5045 mutex_lock(&fs_info->unused_bg_unpin_mutex);
acce952b 5046 ret = find_first_extent_bit(unpin, 0, &start, &end,
0e6ec385 5047 EXTENT_DIRTY, &cached_state);
fcd5e742
LF
5048 if (ret) {
5049 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
acce952b 5050 break;
fcd5e742 5051 }
acce952b 5052
0e6ec385
FM
5053 clear_extent_dirty(unpin, start, end, &cached_state);
5054 free_extent_state(cached_state);
2ff7e61e 5055 btrfs_error_unpin_extent_range(fs_info, start, end);
fcd5e742 5056 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
acce952b 5057 cond_resched();
5058 }
5059
5060 return 0;
5061}
5062
32da5386 5063static void btrfs_cleanup_bg_io(struct btrfs_block_group *cache)
c79a1751
LB
5064{
5065 struct inode *inode;
5066
5067 inode = cache->io_ctl.inode;
5068 if (inode) {
5069 invalidate_inode_pages2(inode->i_mapping);
5070 BTRFS_I(inode)->generation = 0;
5071 cache->io_ctl.inode = NULL;
5072 iput(inode);
5073 }
bbc37d6e 5074 ASSERT(cache->io_ctl.pages == NULL);
c79a1751
LB
5075 btrfs_put_block_group(cache);
5076}
5077
5078void btrfs_cleanup_dirty_bgs(struct btrfs_transaction *cur_trans,
2ff7e61e 5079 struct btrfs_fs_info *fs_info)
c79a1751 5080{
32da5386 5081 struct btrfs_block_group *cache;
c79a1751
LB
5082
5083 spin_lock(&cur_trans->dirty_bgs_lock);
5084 while (!list_empty(&cur_trans->dirty_bgs)) {
5085 cache = list_first_entry(&cur_trans->dirty_bgs,
32da5386 5086 struct btrfs_block_group,
c79a1751 5087 dirty_list);
c79a1751
LB
5088
5089 if (!list_empty(&cache->io_list)) {
5090 spin_unlock(&cur_trans->dirty_bgs_lock);
5091 list_del_init(&cache->io_list);
5092 btrfs_cleanup_bg_io(cache);
5093 spin_lock(&cur_trans->dirty_bgs_lock);
5094 }
5095
5096 list_del_init(&cache->dirty_list);
5097 spin_lock(&cache->lock);
5098 cache->disk_cache_state = BTRFS_DC_ERROR;
5099 spin_unlock(&cache->lock);
5100
5101 spin_unlock(&cur_trans->dirty_bgs_lock);
5102 btrfs_put_block_group(cache);
ba2c4d4e 5103 btrfs_delayed_refs_rsv_release(fs_info, 1);
c79a1751
LB
5104 spin_lock(&cur_trans->dirty_bgs_lock);
5105 }
5106 spin_unlock(&cur_trans->dirty_bgs_lock);
5107
45ae2c18
NB
5108 /*
5109 * Refer to the definition of io_bgs member for details why it's safe
5110 * to use it without any locking
5111 */
c79a1751
LB
5112 while (!list_empty(&cur_trans->io_bgs)) {
5113 cache = list_first_entry(&cur_trans->io_bgs,
32da5386 5114 struct btrfs_block_group,
c79a1751 5115 io_list);
c79a1751
LB
5116
5117 list_del_init(&cache->io_list);
5118 spin_lock(&cache->lock);
5119 cache->disk_cache_state = BTRFS_DC_ERROR;
5120 spin_unlock(&cache->lock);
5121 btrfs_cleanup_bg_io(cache);
5122 }
5123}
5124
49b25e05 5125void btrfs_cleanup_one_transaction(struct btrfs_transaction *cur_trans,
2ff7e61e 5126 struct btrfs_fs_info *fs_info)
49b25e05 5127{
bbbf7243
NB
5128 struct btrfs_device *dev, *tmp;
5129
2ff7e61e 5130 btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
c79a1751
LB
5131 ASSERT(list_empty(&cur_trans->dirty_bgs));
5132 ASSERT(list_empty(&cur_trans->io_bgs));
5133
bbbf7243
NB
5134 list_for_each_entry_safe(dev, tmp, &cur_trans->dev_update_list,
5135 post_commit_list) {
5136 list_del_init(&dev->post_commit_list);
5137 }
5138
2ff7e61e 5139 btrfs_destroy_delayed_refs(cur_trans, fs_info);
49b25e05 5140
4a9d8bde 5141 cur_trans->state = TRANS_STATE_COMMIT_START;
0b246afa 5142 wake_up(&fs_info->transaction_blocked_wait);
49b25e05 5143
4a9d8bde 5144 cur_trans->state = TRANS_STATE_UNBLOCKED;
0b246afa 5145 wake_up(&fs_info->transaction_wait);
49b25e05 5146
ccdf9b30 5147 btrfs_destroy_delayed_inodes(fs_info);
49b25e05 5148
2ff7e61e 5149 btrfs_destroy_marked_extents(fs_info, &cur_trans->dirty_pages,
49b25e05 5150 EXTENT_DIRTY);
fe119a6e 5151 btrfs_destroy_pinned_extent(fs_info, &cur_trans->pinned_extents);
49b25e05 5152
d3575156
NA
5153 btrfs_free_redirty_list(cur_trans);
5154
4a9d8bde
MX
5155 cur_trans->state =TRANS_STATE_COMPLETED;
5156 wake_up(&cur_trans->commit_wait);
49b25e05
JM
5157}
5158
2ff7e61e 5159static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info)
acce952b 5160{
5161 struct btrfs_transaction *t;
acce952b 5162
0b246afa 5163 mutex_lock(&fs_info->transaction_kthread_mutex);
acce952b 5164
0b246afa
JM
5165 spin_lock(&fs_info->trans_lock);
5166 while (!list_empty(&fs_info->trans_list)) {
5167 t = list_first_entry(&fs_info->trans_list,
724e2315
JB
5168 struct btrfs_transaction, list);
5169 if (t->state >= TRANS_STATE_COMMIT_START) {
9b64f57d 5170 refcount_inc(&t->use_count);
0b246afa 5171 spin_unlock(&fs_info->trans_lock);
2ff7e61e 5172 btrfs_wait_for_commit(fs_info, t->transid);
724e2315 5173 btrfs_put_transaction(t);
0b246afa 5174 spin_lock(&fs_info->trans_lock);
724e2315
JB
5175 continue;
5176 }
0b246afa 5177 if (t == fs_info->running_transaction) {
724e2315 5178 t->state = TRANS_STATE_COMMIT_DOING;
0b246afa 5179 spin_unlock(&fs_info->trans_lock);
724e2315
JB
5180 /*
5181 * We wait for 0 num_writers since we don't hold a trans
5182 * handle open currently for this transaction.
5183 */
5184 wait_event(t->writer_wait,
5185 atomic_read(&t->num_writers) == 0);
5186 } else {
0b246afa 5187 spin_unlock(&fs_info->trans_lock);
724e2315 5188 }
2ff7e61e 5189 btrfs_cleanup_one_transaction(t, fs_info);
4a9d8bde 5190
0b246afa
JM
5191 spin_lock(&fs_info->trans_lock);
5192 if (t == fs_info->running_transaction)
5193 fs_info->running_transaction = NULL;
acce952b 5194 list_del_init(&t->list);
0b246afa 5195 spin_unlock(&fs_info->trans_lock);
acce952b 5196
724e2315 5197 btrfs_put_transaction(t);
2e4e97ab 5198 trace_btrfs_transaction_commit(fs_info);
0b246afa 5199 spin_lock(&fs_info->trans_lock);
724e2315 5200 }
0b246afa
JM
5201 spin_unlock(&fs_info->trans_lock);
5202 btrfs_destroy_all_ordered_extents(fs_info);
ccdf9b30
JM
5203 btrfs_destroy_delayed_inodes(fs_info);
5204 btrfs_assert_delayed_root_empty(fs_info);
0b246afa 5205 btrfs_destroy_all_delalloc_inodes(fs_info);
ef67963d 5206 btrfs_drop_all_logs(fs_info);
0b246afa 5207 mutex_unlock(&fs_info->transaction_kthread_mutex);
acce952b 5208
5209 return 0;
5210}
ec7d6dfd 5211
453e4873 5212int btrfs_init_root_free_objectid(struct btrfs_root *root)
ec7d6dfd
NB
5213{
5214 struct btrfs_path *path;
5215 int ret;
5216 struct extent_buffer *l;
5217 struct btrfs_key search_key;
5218 struct btrfs_key found_key;
5219 int slot;
5220
5221 path = btrfs_alloc_path();
5222 if (!path)
5223 return -ENOMEM;
5224
5225 search_key.objectid = BTRFS_LAST_FREE_OBJECTID;
5226 search_key.type = -1;
5227 search_key.offset = (u64)-1;
5228 ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
5229 if (ret < 0)
5230 goto error;
5231 BUG_ON(ret == 0); /* Corruption */
5232 if (path->slots[0] > 0) {
5233 slot = path->slots[0] - 1;
5234 l = path->nodes[0];
5235 btrfs_item_key_to_cpu(l, &found_key, slot);
23125104
NB
5236 root->free_objectid = max_t(u64, found_key.objectid + 1,
5237 BTRFS_FIRST_FREE_OBJECTID);
ec7d6dfd 5238 } else {
23125104 5239 root->free_objectid = BTRFS_FIRST_FREE_OBJECTID;
ec7d6dfd
NB
5240 }
5241 ret = 0;
5242error:
5243 btrfs_free_path(path);
5244 return ret;
5245}
5246
543068a2 5247int btrfs_get_free_objectid(struct btrfs_root *root, u64 *objectid)
ec7d6dfd
NB
5248{
5249 int ret;
5250 mutex_lock(&root->objectid_mutex);
5251
6b8fad57 5252 if (unlikely(root->free_objectid >= BTRFS_LAST_FREE_OBJECTID)) {
ec7d6dfd
NB
5253 btrfs_warn(root->fs_info,
5254 "the objectid of root %llu reaches its highest value",
5255 root->root_key.objectid);
5256 ret = -ENOSPC;
5257 goto out;
5258 }
5259
23125104 5260 *objectid = root->free_objectid++;
ec7d6dfd
NB
5261 ret = 0;
5262out:
5263 mutex_unlock(&root->objectid_mutex);
5264 return ret;
5265}