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