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