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