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