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