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