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