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