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