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