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