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