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