xref: /linux/fs/btrfs/disk-io.c (revision 8804d970fab45726b3c7cd7f240b31122aa94219)
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/workqueue.h>
11 #include <linux/kthread.h>
12 #include <linux/slab.h>
13 #include <linux/migrate.h>
14 #include <linux/ratelimit.h>
15 #include <linux/uuid.h>
16 #include <linux/semaphore.h>
17 #include <linux/error-injection.h>
18 #include <linux/crc32c.h>
19 #include <linux/sched/mm.h>
20 #include <linux/unaligned.h>
21 #include <crypto/hash.h>
22 #include "ctree.h"
23 #include "disk-io.h"
24 #include "transaction.h"
25 #include "btrfs_inode.h"
26 #include "bio.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 "dev-replace.h"
33 #include "raid56.h"
34 #include "sysfs.h"
35 #include "qgroup.h"
36 #include "compression.h"
37 #include "tree-checker.h"
38 #include "ref-verify.h"
39 #include "block-group.h"
40 #include "discard.h"
41 #include "space-info.h"
42 #include "zoned.h"
43 #include "subpage.h"
44 #include "fs.h"
45 #include "accessors.h"
46 #include "extent-tree.h"
47 #include "root-tree.h"
48 #include "defrag.h"
49 #include "uuid-tree.h"
50 #include "relocation.h"
51 #include "scrub.h"
52 #include "super.h"
53 
54 #define BTRFS_SUPER_FLAG_SUPP	(BTRFS_HEADER_FLAG_WRITTEN |\
55 				 BTRFS_HEADER_FLAG_RELOC |\
56 				 BTRFS_SUPER_FLAG_ERROR |\
57 				 BTRFS_SUPER_FLAG_SEEDING |\
58 				 BTRFS_SUPER_FLAG_METADUMP |\
59 				 BTRFS_SUPER_FLAG_METADUMP_V2)
60 
61 static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info);
62 static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info);
63 
btrfs_free_csum_hash(struct btrfs_fs_info * fs_info)64 static void btrfs_free_csum_hash(struct btrfs_fs_info *fs_info)
65 {
66 	if (fs_info->csum_shash)
67 		crypto_free_shash(fs_info->csum_shash);
68 }
69 
70 /*
71  * Compute the csum of a btree block and store the result to provided buffer.
72  */
csum_tree_block(struct extent_buffer * buf,u8 * result)73 static void csum_tree_block(struct extent_buffer *buf, u8 *result)
74 {
75 	struct btrfs_fs_info *fs_info = buf->fs_info;
76 	int num_pages;
77 	u32 first_page_part;
78 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
79 	char *kaddr;
80 	int i;
81 
82 	shash->tfm = fs_info->csum_shash;
83 	crypto_shash_init(shash);
84 
85 	if (buf->addr) {
86 		/* Pages are contiguous, handle them as a big one. */
87 		kaddr = buf->addr;
88 		first_page_part = fs_info->nodesize;
89 		num_pages = 1;
90 	} else {
91 		kaddr = folio_address(buf->folios[0]);
92 		first_page_part = min_t(u32, PAGE_SIZE, fs_info->nodesize);
93 		num_pages = num_extent_pages(buf);
94 	}
95 
96 	crypto_shash_update(shash, kaddr + BTRFS_CSUM_SIZE,
97 			    first_page_part - BTRFS_CSUM_SIZE);
98 
99 	/*
100 	 * Multiple single-page folios case would reach here.
101 	 *
102 	 * nodesize <= PAGE_SIZE and large folio all handled by above
103 	 * crypto_shash_update() already.
104 	 */
105 	for (i = 1; i < num_pages && INLINE_EXTENT_BUFFER_PAGES > 1; i++) {
106 		kaddr = folio_address(buf->folios[i]);
107 		crypto_shash_update(shash, kaddr, PAGE_SIZE);
108 	}
109 	memset(result, 0, BTRFS_CSUM_SIZE);
110 	crypto_shash_final(shash, result);
111 }
112 
113 /*
114  * we can't consider a given block up to date unless the transid of the
115  * block matches the transid in the parent node's pointer.  This is how we
116  * detect blocks that either didn't get written at all or got written
117  * in the wrong place.
118  */
btrfs_buffer_uptodate(struct extent_buffer * eb,u64 parent_transid,bool atomic)119 int btrfs_buffer_uptodate(struct extent_buffer *eb, u64 parent_transid, bool atomic)
120 {
121 	if (!extent_buffer_uptodate(eb))
122 		return 0;
123 
124 	if (!parent_transid || btrfs_header_generation(eb) == parent_transid)
125 		return 1;
126 
127 	if (atomic)
128 		return -EAGAIN;
129 
130 	if (!extent_buffer_uptodate(eb) ||
131 	    btrfs_header_generation(eb) != parent_transid) {
132 		btrfs_err_rl(eb->fs_info,
133 "parent transid verify failed on logical %llu mirror %u wanted %llu found %llu",
134 			eb->start, eb->read_mirror,
135 			parent_transid, btrfs_header_generation(eb));
136 		clear_extent_buffer_uptodate(eb);
137 		return 0;
138 	}
139 	return 1;
140 }
141 
btrfs_supported_super_csum(u16 csum_type)142 static bool btrfs_supported_super_csum(u16 csum_type)
143 {
144 	switch (csum_type) {
145 	case BTRFS_CSUM_TYPE_CRC32:
146 	case BTRFS_CSUM_TYPE_XXHASH:
147 	case BTRFS_CSUM_TYPE_SHA256:
148 	case BTRFS_CSUM_TYPE_BLAKE2:
149 		return true;
150 	default:
151 		return false;
152 	}
153 }
154 
155 /*
156  * Return 0 if the superblock checksum type matches the checksum value of that
157  * algorithm. Pass the raw disk superblock data.
158  */
btrfs_check_super_csum(struct btrfs_fs_info * fs_info,const struct btrfs_super_block * disk_sb)159 int btrfs_check_super_csum(struct btrfs_fs_info *fs_info,
160 			   const struct btrfs_super_block *disk_sb)
161 {
162 	char result[BTRFS_CSUM_SIZE];
163 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
164 
165 	shash->tfm = fs_info->csum_shash;
166 
167 	/*
168 	 * The super_block structure does not span the whole
169 	 * BTRFS_SUPER_INFO_SIZE range, we expect that the unused space is
170 	 * filled with zeros and is included in the checksum.
171 	 */
172 	crypto_shash_digest(shash, (const u8 *)disk_sb + BTRFS_CSUM_SIZE,
173 			    BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE, result);
174 
175 	if (memcmp(disk_sb->csum, result, fs_info->csum_size))
176 		return 1;
177 
178 	return 0;
179 }
180 
btrfs_repair_eb_io_failure(const struct extent_buffer * eb,int mirror_num)181 static int btrfs_repair_eb_io_failure(const struct extent_buffer *eb,
182 				      int mirror_num)
183 {
184 	struct btrfs_fs_info *fs_info = eb->fs_info;
185 	int ret = 0;
186 
187 	if (sb_rdonly(fs_info->sb))
188 		return -EROFS;
189 
190 	for (int i = 0; i < num_extent_folios(eb); i++) {
191 		struct folio *folio = eb->folios[i];
192 		u64 start = max_t(u64, eb->start, folio_pos(folio));
193 		u64 end = min_t(u64, eb->start + eb->len,
194 				folio_pos(folio) + eb->folio_size);
195 		u32 len = end - start;
196 		phys_addr_t paddr = PFN_PHYS(folio_pfn(folio)) +
197 				    offset_in_folio(folio, start);
198 
199 		ret = btrfs_repair_io_failure(fs_info, 0, start, len, start,
200 					      paddr, mirror_num);
201 		if (ret)
202 			break;
203 	}
204 
205 	return ret;
206 }
207 
208 /*
209  * helper to read a given tree block, doing retries as required when
210  * the checksums don't match and we have alternate mirrors to try.
211  *
212  * @check:		expected tree parentness check, see the comments of the
213  *			structure for details.
214  */
btrfs_read_extent_buffer(struct extent_buffer * eb,const struct btrfs_tree_parent_check * check)215 int btrfs_read_extent_buffer(struct extent_buffer *eb,
216 			     const struct btrfs_tree_parent_check *check)
217 {
218 	struct btrfs_fs_info *fs_info = eb->fs_info;
219 	int failed = 0;
220 	int ret;
221 	int num_copies = 0;
222 	int mirror_num = 0;
223 	int failed_mirror = 0;
224 
225 	ASSERT(check);
226 
227 	while (1) {
228 		ret = read_extent_buffer_pages(eb, mirror_num, check);
229 		if (!ret)
230 			break;
231 
232 		num_copies = btrfs_num_copies(fs_info,
233 					      eb->start, eb->len);
234 		if (num_copies == 1)
235 			break;
236 
237 		if (!failed_mirror) {
238 			failed = 1;
239 			failed_mirror = eb->read_mirror;
240 		}
241 
242 		mirror_num++;
243 		if (mirror_num == failed_mirror)
244 			mirror_num++;
245 
246 		if (mirror_num > num_copies)
247 			break;
248 	}
249 
250 	if (failed && !ret && failed_mirror)
251 		btrfs_repair_eb_io_failure(eb, failed_mirror);
252 
253 	return ret;
254 }
255 
256 /*
257  * Checksum a dirty tree block before IO.
258  */
btree_csum_one_bio(struct btrfs_bio * bbio)259 int btree_csum_one_bio(struct btrfs_bio *bbio)
260 {
261 	struct extent_buffer *eb = bbio->private;
262 	struct btrfs_fs_info *fs_info = eb->fs_info;
263 	u64 found_start = btrfs_header_bytenr(eb);
264 	u64 last_trans;
265 	u8 result[BTRFS_CSUM_SIZE];
266 	int ret;
267 
268 	/* Btree blocks are always contiguous on disk. */
269 	if (WARN_ON_ONCE(bbio->file_offset != eb->start))
270 		return -EIO;
271 	if (WARN_ON_ONCE(bbio->bio.bi_iter.bi_size != eb->len))
272 		return -EIO;
273 
274 	/*
275 	 * If an extent_buffer is marked as EXTENT_BUFFER_ZONED_ZEROOUT, don't
276 	 * checksum it but zero-out its content. This is done to preserve
277 	 * ordering of I/O without unnecessarily writing out data.
278 	 */
279 	if (test_bit(EXTENT_BUFFER_ZONED_ZEROOUT, &eb->bflags)) {
280 		memzero_extent_buffer(eb, 0, eb->len);
281 		return 0;
282 	}
283 
284 	if (WARN_ON_ONCE(found_start != eb->start))
285 		return -EIO;
286 	if (WARN_ON(!btrfs_meta_folio_test_uptodate(eb->folios[0], eb)))
287 		return -EIO;
288 
289 	ASSERT(memcmp_extent_buffer(eb, fs_info->fs_devices->metadata_uuid,
290 				    offsetof(struct btrfs_header, fsid),
291 				    BTRFS_FSID_SIZE) == 0);
292 	csum_tree_block(eb, result);
293 
294 	if (btrfs_header_level(eb))
295 		ret = btrfs_check_node(eb);
296 	else
297 		ret = btrfs_check_leaf(eb);
298 
299 	if (ret < 0)
300 		goto error;
301 
302 	/*
303 	 * Also check the generation, the eb reached here must be newer than
304 	 * last committed. Or something seriously wrong happened.
305 	 */
306 	last_trans = btrfs_get_last_trans_committed(fs_info);
307 	if (unlikely(btrfs_header_generation(eb) <= last_trans)) {
308 		ret = -EUCLEAN;
309 		btrfs_err(fs_info,
310 			"block=%llu bad generation, have %llu expect > %llu",
311 			  eb->start, btrfs_header_generation(eb), last_trans);
312 		goto error;
313 	}
314 	write_extent_buffer(eb, result, 0, fs_info->csum_size);
315 	return 0;
316 
317 error:
318 	btrfs_print_tree(eb, 0);
319 	btrfs_err(fs_info, "block=%llu write time tree block corruption detected",
320 		  eb->start);
321 	/*
322 	 * Be noisy if this is an extent buffer from a log tree. We don't abort
323 	 * a transaction in case there's a bad log tree extent buffer, we just
324 	 * fallback to a transaction commit. Still we want to know when there is
325 	 * a bad log tree extent buffer, as that may signal a bug somewhere.
326 	 */
327 	WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG) ||
328 		btrfs_header_owner(eb) == BTRFS_TREE_LOG_OBJECTID);
329 	return ret;
330 }
331 
check_tree_block_fsid(struct extent_buffer * eb)332 static bool check_tree_block_fsid(struct extent_buffer *eb)
333 {
334 	struct btrfs_fs_info *fs_info = eb->fs_info;
335 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
336 	u8 fsid[BTRFS_FSID_SIZE];
337 
338 	read_extent_buffer(eb, fsid, offsetof(struct btrfs_header, fsid),
339 			   BTRFS_FSID_SIZE);
340 
341 	/*
342 	 * alloc_fsid_devices() copies the fsid into fs_devices::metadata_uuid.
343 	 * This is then overwritten by metadata_uuid if it is present in the
344 	 * device_list_add(). The same true for a seed device as well. So use of
345 	 * fs_devices::metadata_uuid is appropriate here.
346 	 */
347 	if (memcmp(fsid, fs_info->fs_devices->metadata_uuid, BTRFS_FSID_SIZE) == 0)
348 		return false;
349 
350 	list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list)
351 		if (!memcmp(fsid, seed_devs->fsid, BTRFS_FSID_SIZE))
352 			return false;
353 
354 	return true;
355 }
356 
357 /* Do basic extent buffer checks at read time */
btrfs_validate_extent_buffer(struct extent_buffer * eb,const struct btrfs_tree_parent_check * check)358 int btrfs_validate_extent_buffer(struct extent_buffer *eb,
359 				 const struct btrfs_tree_parent_check *check)
360 {
361 	struct btrfs_fs_info *fs_info = eb->fs_info;
362 	u64 found_start;
363 	const u32 csum_size = fs_info->csum_size;
364 	u8 found_level;
365 	u8 result[BTRFS_CSUM_SIZE];
366 	const u8 *header_csum;
367 	int ret = 0;
368 	const bool ignore_csum = btrfs_test_opt(fs_info, IGNOREMETACSUMS);
369 
370 	ASSERT(check);
371 
372 	found_start = btrfs_header_bytenr(eb);
373 	if (unlikely(found_start != eb->start)) {
374 		btrfs_err_rl(fs_info,
375 			"bad tree block start, mirror %u want %llu have %llu",
376 			     eb->read_mirror, eb->start, found_start);
377 		ret = -EIO;
378 		goto out;
379 	}
380 	if (unlikely(check_tree_block_fsid(eb))) {
381 		btrfs_err_rl(fs_info, "bad fsid on logical %llu mirror %u",
382 			     eb->start, eb->read_mirror);
383 		ret = -EIO;
384 		goto out;
385 	}
386 	found_level = btrfs_header_level(eb);
387 	if (unlikely(found_level >= BTRFS_MAX_LEVEL)) {
388 		btrfs_err(fs_info,
389 			"bad tree block level, mirror %u level %d on logical %llu",
390 			eb->read_mirror, btrfs_header_level(eb), eb->start);
391 		ret = -EIO;
392 		goto out;
393 	}
394 
395 	csum_tree_block(eb, result);
396 	header_csum = folio_address(eb->folios[0]) +
397 		get_eb_offset_in_folio(eb, offsetof(struct btrfs_header, csum));
398 
399 	if (memcmp(result, header_csum, csum_size) != 0) {
400 		btrfs_warn_rl(fs_info,
401 "checksum verify failed on logical %llu mirror %u wanted " CSUM_FMT " found " CSUM_FMT " level %d%s",
402 			      eb->start, eb->read_mirror,
403 			      CSUM_FMT_VALUE(csum_size, header_csum),
404 			      CSUM_FMT_VALUE(csum_size, result),
405 			      btrfs_header_level(eb),
406 			      ignore_csum ? ", ignored" : "");
407 		if (unlikely(!ignore_csum)) {
408 			ret = -EUCLEAN;
409 			goto out;
410 		}
411 	}
412 
413 	if (unlikely(found_level != check->level)) {
414 		btrfs_err(fs_info,
415 		"level verify failed on logical %llu mirror %u wanted %u found %u",
416 			  eb->start, eb->read_mirror, check->level, found_level);
417 		ret = -EIO;
418 		goto out;
419 	}
420 	if (unlikely(check->transid &&
421 		     btrfs_header_generation(eb) != check->transid)) {
422 		btrfs_err_rl(eb->fs_info,
423 "parent transid verify failed on logical %llu mirror %u wanted %llu found %llu",
424 				eb->start, eb->read_mirror, check->transid,
425 				btrfs_header_generation(eb));
426 		ret = -EIO;
427 		goto out;
428 	}
429 	if (check->has_first_key) {
430 		const struct btrfs_key *expect_key = &check->first_key;
431 		struct btrfs_key found_key;
432 
433 		if (found_level)
434 			btrfs_node_key_to_cpu(eb, &found_key, 0);
435 		else
436 			btrfs_item_key_to_cpu(eb, &found_key, 0);
437 		if (unlikely(btrfs_comp_cpu_keys(expect_key, &found_key))) {
438 			btrfs_err(fs_info,
439 "tree first key mismatch detected, bytenr=%llu parent_transid=%llu key expected=(%llu,%u,%llu) has=(%llu,%u,%llu)",
440 				  eb->start, check->transid,
441 				  expect_key->objectid,
442 				  expect_key->type, expect_key->offset,
443 				  found_key.objectid, found_key.type,
444 				  found_key.offset);
445 			ret = -EUCLEAN;
446 			goto out;
447 		}
448 	}
449 	if (check->owner_root) {
450 		ret = btrfs_check_eb_owner(eb, check->owner_root);
451 		if (ret < 0)
452 			goto out;
453 	}
454 
455 	/* If this is a leaf block and it is corrupt, just return -EIO. */
456 	if (found_level == 0 && btrfs_check_leaf(eb))
457 		ret = -EIO;
458 
459 	if (found_level > 0 && btrfs_check_node(eb))
460 		ret = -EIO;
461 
462 	if (ret)
463 		btrfs_err(fs_info,
464 		"read time tree block corruption detected on logical %llu mirror %u",
465 			  eb->start, eb->read_mirror);
466 out:
467 	return ret;
468 }
469 
470 #ifdef CONFIG_MIGRATION
btree_migrate_folio(struct address_space * mapping,struct folio * dst,struct folio * src,enum migrate_mode mode)471 static int btree_migrate_folio(struct address_space *mapping,
472 		struct folio *dst, struct folio *src, enum migrate_mode mode)
473 {
474 	/*
475 	 * we can't safely write a btree page from here,
476 	 * we haven't done the locking hook
477 	 */
478 	if (folio_test_dirty(src))
479 		return -EAGAIN;
480 	/*
481 	 * Buffers may be managed in a filesystem specific way.
482 	 * We must have no buffers or drop them.
483 	 */
484 	if (folio_get_private(src) &&
485 	    !filemap_release_folio(src, GFP_KERNEL))
486 		return -EAGAIN;
487 	return migrate_folio(mapping, dst, src, mode);
488 }
489 #else
490 #define btree_migrate_folio NULL
491 #endif
492 
btree_writepages(struct address_space * mapping,struct writeback_control * wbc)493 static int btree_writepages(struct address_space *mapping,
494 			    struct writeback_control *wbc)
495 {
496 	int ret;
497 
498 	if (wbc->sync_mode == WB_SYNC_NONE) {
499 		struct btrfs_fs_info *fs_info;
500 
501 		if (wbc->for_kupdate)
502 			return 0;
503 
504 		fs_info = inode_to_fs_info(mapping->host);
505 		/* this is a bit racy, but that's ok */
506 		ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
507 					     BTRFS_DIRTY_METADATA_THRESH,
508 					     fs_info->dirty_metadata_batch);
509 		if (ret < 0)
510 			return 0;
511 	}
512 	return btree_write_cache_pages(mapping, wbc);
513 }
514 
btree_release_folio(struct folio * folio,gfp_t gfp_flags)515 static bool btree_release_folio(struct folio *folio, gfp_t gfp_flags)
516 {
517 	if (folio_test_writeback(folio) || folio_test_dirty(folio))
518 		return false;
519 
520 	return try_release_extent_buffer(folio);
521 }
522 
btree_invalidate_folio(struct folio * folio,size_t offset,size_t length)523 static void btree_invalidate_folio(struct folio *folio, size_t offset,
524 				 size_t length)
525 {
526 	struct extent_io_tree *tree;
527 
528 	tree = &folio_to_inode(folio)->io_tree;
529 	extent_invalidate_folio(tree, folio, offset);
530 	btree_release_folio(folio, GFP_NOFS);
531 	if (folio_get_private(folio)) {
532 		btrfs_warn(folio_to_fs_info(folio),
533 			   "folio private not zero on folio %llu",
534 			   (unsigned long long)folio_pos(folio));
535 		folio_detach_private(folio);
536 	}
537 }
538 
539 #ifdef DEBUG
btree_dirty_folio(struct address_space * mapping,struct folio * folio)540 static bool btree_dirty_folio(struct address_space *mapping,
541 		struct folio *folio)
542 {
543 	struct btrfs_fs_info *fs_info = inode_to_fs_info(mapping->host);
544 	struct btrfs_subpage_info *spi = fs_info->subpage_info;
545 	struct btrfs_subpage *subpage;
546 	struct extent_buffer *eb;
547 	int cur_bit = 0;
548 	u64 page_start = folio_pos(folio);
549 
550 	if (fs_info->sectorsize == PAGE_SIZE) {
551 		eb = folio_get_private(folio);
552 		BUG_ON(!eb);
553 		BUG_ON(!test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
554 		BUG_ON(!atomic_read(&eb->refs));
555 		btrfs_assert_tree_write_locked(eb);
556 		return filemap_dirty_folio(mapping, folio);
557 	}
558 
559 	ASSERT(spi);
560 	subpage = folio_get_private(folio);
561 
562 	for (cur_bit = spi->dirty_offset;
563 	     cur_bit < spi->dirty_offset + spi->bitmap_nr_bits;
564 	     cur_bit++) {
565 		unsigned long flags;
566 		u64 cur;
567 
568 		spin_lock_irqsave(&subpage->lock, flags);
569 		if (!test_bit(cur_bit, subpage->bitmaps)) {
570 			spin_unlock_irqrestore(&subpage->lock, flags);
571 			continue;
572 		}
573 		spin_unlock_irqrestore(&subpage->lock, flags);
574 		cur = page_start + cur_bit * fs_info->sectorsize;
575 
576 		eb = find_extent_buffer(fs_info, cur);
577 		ASSERT(eb);
578 		ASSERT(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
579 		ASSERT(atomic_read(&eb->refs));
580 		btrfs_assert_tree_write_locked(eb);
581 		free_extent_buffer(eb);
582 
583 		cur_bit += (fs_info->nodesize >> fs_info->sectorsize_bits) - 1;
584 	}
585 	return filemap_dirty_folio(mapping, folio);
586 }
587 #else
588 #define btree_dirty_folio filemap_dirty_folio
589 #endif
590 
591 static const struct address_space_operations btree_aops = {
592 	.writepages	= btree_writepages,
593 	.release_folio	= btree_release_folio,
594 	.invalidate_folio = btree_invalidate_folio,
595 	.migrate_folio	= btree_migrate_folio,
596 	.dirty_folio	= btree_dirty_folio,
597 };
598 
btrfs_find_create_tree_block(struct btrfs_fs_info * fs_info,u64 bytenr,u64 owner_root,int level)599 struct extent_buffer *btrfs_find_create_tree_block(
600 						struct btrfs_fs_info *fs_info,
601 						u64 bytenr, u64 owner_root,
602 						int level)
603 {
604 	if (btrfs_is_testing(fs_info))
605 		return alloc_test_extent_buffer(fs_info, bytenr);
606 	return alloc_extent_buffer(fs_info, bytenr, owner_root, level);
607 }
608 
609 /*
610  * Read tree block at logical address @bytenr and do variant basic but critical
611  * verification.
612  *
613  * @check:		expected tree parentness check, see comments of the
614  *			structure for details.
615  */
read_tree_block(struct btrfs_fs_info * fs_info,u64 bytenr,struct btrfs_tree_parent_check * check)616 struct extent_buffer *read_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr,
617 				      struct btrfs_tree_parent_check *check)
618 {
619 	struct extent_buffer *buf = NULL;
620 	int ret;
621 
622 	ASSERT(check);
623 
624 	buf = btrfs_find_create_tree_block(fs_info, bytenr, check->owner_root,
625 					   check->level);
626 	if (IS_ERR(buf))
627 		return buf;
628 
629 	ret = btrfs_read_extent_buffer(buf, check);
630 	if (ret) {
631 		free_extent_buffer_stale(buf);
632 		return ERR_PTR(ret);
633 	}
634 	return buf;
635 
636 }
637 
btrfs_alloc_root(struct btrfs_fs_info * fs_info,u64 objectid,gfp_t flags)638 static struct btrfs_root *btrfs_alloc_root(struct btrfs_fs_info *fs_info,
639 					   u64 objectid, gfp_t flags)
640 {
641 	struct btrfs_root *root;
642 
643 	root = kzalloc(sizeof(*root), flags);
644 	if (!root)
645 		return NULL;
646 
647 	memset(&root->root_key, 0, sizeof(root->root_key));
648 	memset(&root->root_item, 0, sizeof(root->root_item));
649 	memset(&root->defrag_progress, 0, sizeof(root->defrag_progress));
650 	root->fs_info = fs_info;
651 	root->root_key.objectid = objectid;
652 	root->node = NULL;
653 	root->commit_root = NULL;
654 	root->state = 0;
655 	RB_CLEAR_NODE(&root->rb_node);
656 
657 	btrfs_set_root_last_trans(root, 0);
658 	root->free_objectid = 0;
659 	root->nr_delalloc_inodes = 0;
660 	root->nr_ordered_extents = 0;
661 	xa_init(&root->inodes);
662 	xa_init(&root->delayed_nodes);
663 
664 	btrfs_init_root_block_rsv(root);
665 
666 	INIT_LIST_HEAD(&root->dirty_list);
667 	INIT_LIST_HEAD(&root->root_list);
668 	INIT_LIST_HEAD(&root->delalloc_inodes);
669 	INIT_LIST_HEAD(&root->delalloc_root);
670 	INIT_LIST_HEAD(&root->ordered_extents);
671 	INIT_LIST_HEAD(&root->ordered_root);
672 	INIT_LIST_HEAD(&root->reloc_dirty_list);
673 	spin_lock_init(&root->delalloc_lock);
674 	spin_lock_init(&root->ordered_extent_lock);
675 	spin_lock_init(&root->accounting_lock);
676 	spin_lock_init(&root->qgroup_meta_rsv_lock);
677 	mutex_init(&root->objectid_mutex);
678 	mutex_init(&root->log_mutex);
679 	mutex_init(&root->ordered_extent_mutex);
680 	mutex_init(&root->delalloc_mutex);
681 	init_waitqueue_head(&root->qgroup_flush_wait);
682 	init_waitqueue_head(&root->log_writer_wait);
683 	init_waitqueue_head(&root->log_commit_wait[0]);
684 	init_waitqueue_head(&root->log_commit_wait[1]);
685 	INIT_LIST_HEAD(&root->log_ctxs[0]);
686 	INIT_LIST_HEAD(&root->log_ctxs[1]);
687 	atomic_set(&root->log_commit[0], 0);
688 	atomic_set(&root->log_commit[1], 0);
689 	atomic_set(&root->log_writers, 0);
690 	atomic_set(&root->log_batch, 0);
691 	refcount_set(&root->refs, 1);
692 	atomic_set(&root->snapshot_force_cow, 0);
693 	atomic_set(&root->nr_swapfiles, 0);
694 	btrfs_set_root_log_transid(root, 0);
695 	root->log_transid_committed = -1;
696 	btrfs_set_root_last_log_commit(root, 0);
697 	root->anon_dev = 0;
698 	if (!btrfs_is_testing(fs_info)) {
699 		btrfs_extent_io_tree_init(fs_info, &root->dirty_log_pages,
700 					  IO_TREE_ROOT_DIRTY_LOG_PAGES);
701 		btrfs_extent_io_tree_init(fs_info, &root->log_csum_range,
702 					  IO_TREE_LOG_CSUM_RANGE);
703 	}
704 
705 	spin_lock_init(&root->root_item_lock);
706 	btrfs_qgroup_init_swapped_blocks(&root->swapped_blocks);
707 #ifdef CONFIG_BTRFS_DEBUG
708 	INIT_LIST_HEAD(&root->leak_list);
709 	spin_lock(&fs_info->fs_roots_radix_lock);
710 	list_add_tail(&root->leak_list, &fs_info->allocated_roots);
711 	spin_unlock(&fs_info->fs_roots_radix_lock);
712 #endif
713 
714 	return root;
715 }
716 
717 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
718 /* Should only be used by the testing infrastructure */
btrfs_alloc_dummy_root(struct btrfs_fs_info * fs_info)719 struct btrfs_root *btrfs_alloc_dummy_root(struct btrfs_fs_info *fs_info)
720 {
721 	struct btrfs_root *root;
722 
723 	if (!fs_info)
724 		return ERR_PTR(-EINVAL);
725 
726 	root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID, GFP_KERNEL);
727 	if (!root)
728 		return ERR_PTR(-ENOMEM);
729 
730 	/* We don't use the stripesize in selftest, set it as sectorsize */
731 	root->alloc_bytenr = 0;
732 
733 	return root;
734 }
735 #endif
736 
global_root_cmp(struct rb_node * a_node,const struct rb_node * b_node)737 static int global_root_cmp(struct rb_node *a_node, const struct rb_node *b_node)
738 {
739 	const struct btrfs_root *a = rb_entry(a_node, struct btrfs_root, rb_node);
740 	const struct btrfs_root *b = rb_entry(b_node, struct btrfs_root, rb_node);
741 
742 	return btrfs_comp_cpu_keys(&a->root_key, &b->root_key);
743 }
744 
global_root_key_cmp(const void * k,const struct rb_node * node)745 static int global_root_key_cmp(const void *k, const struct rb_node *node)
746 {
747 	const struct btrfs_key *key = k;
748 	const struct btrfs_root *root = rb_entry(node, struct btrfs_root, rb_node);
749 
750 	return btrfs_comp_cpu_keys(key, &root->root_key);
751 }
752 
btrfs_global_root_insert(struct btrfs_root * root)753 int btrfs_global_root_insert(struct btrfs_root *root)
754 {
755 	struct btrfs_fs_info *fs_info = root->fs_info;
756 	struct rb_node *tmp;
757 	int ret = 0;
758 
759 	write_lock(&fs_info->global_root_lock);
760 	tmp = rb_find_add(&root->rb_node, &fs_info->global_root_tree, global_root_cmp);
761 	write_unlock(&fs_info->global_root_lock);
762 
763 	if (tmp) {
764 		ret = -EEXIST;
765 		btrfs_warn(fs_info, "global root %llu %llu already exists",
766 			   btrfs_root_id(root), root->root_key.offset);
767 	}
768 	return ret;
769 }
770 
btrfs_global_root_delete(struct btrfs_root * root)771 void btrfs_global_root_delete(struct btrfs_root *root)
772 {
773 	struct btrfs_fs_info *fs_info = root->fs_info;
774 
775 	write_lock(&fs_info->global_root_lock);
776 	rb_erase(&root->rb_node, &fs_info->global_root_tree);
777 	write_unlock(&fs_info->global_root_lock);
778 }
779 
btrfs_global_root(struct btrfs_fs_info * fs_info,struct btrfs_key * key)780 struct btrfs_root *btrfs_global_root(struct btrfs_fs_info *fs_info,
781 				     struct btrfs_key *key)
782 {
783 	struct rb_node *node;
784 	struct btrfs_root *root = NULL;
785 
786 	read_lock(&fs_info->global_root_lock);
787 	node = rb_find(key, &fs_info->global_root_tree, global_root_key_cmp);
788 	if (node)
789 		root = container_of(node, struct btrfs_root, rb_node);
790 	read_unlock(&fs_info->global_root_lock);
791 
792 	return root;
793 }
794 
btrfs_global_root_id(struct btrfs_fs_info * fs_info,u64 bytenr)795 static u64 btrfs_global_root_id(struct btrfs_fs_info *fs_info, u64 bytenr)
796 {
797 	struct btrfs_block_group *block_group;
798 	u64 ret;
799 
800 	if (!btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))
801 		return 0;
802 
803 	if (bytenr)
804 		block_group = btrfs_lookup_block_group(fs_info, bytenr);
805 	else
806 		block_group = btrfs_lookup_first_block_group(fs_info, bytenr);
807 	ASSERT(block_group);
808 	if (!block_group)
809 		return 0;
810 	ret = block_group->global_root_id;
811 	btrfs_put_block_group(block_group);
812 
813 	return ret;
814 }
815 
btrfs_csum_root(struct btrfs_fs_info * fs_info,u64 bytenr)816 struct btrfs_root *btrfs_csum_root(struct btrfs_fs_info *fs_info, u64 bytenr)
817 {
818 	struct btrfs_key key = {
819 		.objectid = BTRFS_CSUM_TREE_OBJECTID,
820 		.type = BTRFS_ROOT_ITEM_KEY,
821 		.offset = btrfs_global_root_id(fs_info, bytenr),
822 	};
823 
824 	return btrfs_global_root(fs_info, &key);
825 }
826 
btrfs_extent_root(struct btrfs_fs_info * fs_info,u64 bytenr)827 struct btrfs_root *btrfs_extent_root(struct btrfs_fs_info *fs_info, u64 bytenr)
828 {
829 	struct btrfs_key key = {
830 		.objectid = BTRFS_EXTENT_TREE_OBJECTID,
831 		.type = BTRFS_ROOT_ITEM_KEY,
832 		.offset = btrfs_global_root_id(fs_info, bytenr),
833 	};
834 
835 	return btrfs_global_root(fs_info, &key);
836 }
837 
btrfs_create_tree(struct btrfs_trans_handle * trans,u64 objectid)838 struct btrfs_root *btrfs_create_tree(struct btrfs_trans_handle *trans,
839 				     u64 objectid)
840 {
841 	struct btrfs_fs_info *fs_info = trans->fs_info;
842 	struct extent_buffer *leaf;
843 	struct btrfs_root *tree_root = fs_info->tree_root;
844 	struct btrfs_root *root;
845 	struct btrfs_key key;
846 	unsigned int nofs_flag;
847 	int ret = 0;
848 
849 	/*
850 	 * We're holding a transaction handle, so use a NOFS memory allocation
851 	 * context to avoid deadlock if reclaim happens.
852 	 */
853 	nofs_flag = memalloc_nofs_save();
854 	root = btrfs_alloc_root(fs_info, objectid, GFP_KERNEL);
855 	memalloc_nofs_restore(nofs_flag);
856 	if (!root)
857 		return ERR_PTR(-ENOMEM);
858 
859 	root->root_key.objectid = objectid;
860 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
861 	root->root_key.offset = 0;
862 
863 	leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0,
864 				      0, BTRFS_NESTING_NORMAL);
865 	if (IS_ERR(leaf)) {
866 		ret = PTR_ERR(leaf);
867 		leaf = NULL;
868 		goto fail;
869 	}
870 
871 	root->node = leaf;
872 	btrfs_mark_buffer_dirty(trans, leaf);
873 
874 	root->commit_root = btrfs_root_node(root);
875 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
876 
877 	btrfs_set_root_flags(&root->root_item, 0);
878 	btrfs_set_root_limit(&root->root_item, 0);
879 	btrfs_set_root_bytenr(&root->root_item, leaf->start);
880 	btrfs_set_root_generation(&root->root_item, trans->transid);
881 	btrfs_set_root_level(&root->root_item, 0);
882 	btrfs_set_root_refs(&root->root_item, 1);
883 	btrfs_set_root_used(&root->root_item, leaf->len);
884 	btrfs_set_root_last_snapshot(&root->root_item, 0);
885 	btrfs_set_root_dirid(&root->root_item, 0);
886 	if (btrfs_is_fstree(objectid))
887 		generate_random_guid(root->root_item.uuid);
888 	else
889 		export_guid(root->root_item.uuid, &guid_null);
890 	btrfs_set_root_drop_level(&root->root_item, 0);
891 
892 	btrfs_tree_unlock(leaf);
893 
894 	key.objectid = objectid;
895 	key.type = BTRFS_ROOT_ITEM_KEY;
896 	key.offset = 0;
897 	ret = btrfs_insert_root(trans, tree_root, &key, &root->root_item);
898 	if (ret)
899 		goto fail;
900 
901 	return root;
902 
903 fail:
904 	btrfs_put_root(root);
905 
906 	return ERR_PTR(ret);
907 }
908 
alloc_log_tree(struct btrfs_fs_info * fs_info)909 static struct btrfs_root *alloc_log_tree(struct btrfs_fs_info *fs_info)
910 {
911 	struct btrfs_root *root;
912 
913 	root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID, GFP_NOFS);
914 	if (!root)
915 		return ERR_PTR(-ENOMEM);
916 
917 	root->root_key.objectid = BTRFS_TREE_LOG_OBJECTID;
918 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
919 	root->root_key.offset = BTRFS_TREE_LOG_OBJECTID;
920 
921 	return root;
922 }
923 
btrfs_alloc_log_tree_node(struct btrfs_trans_handle * trans,struct btrfs_root * root)924 int btrfs_alloc_log_tree_node(struct btrfs_trans_handle *trans,
925 			      struct btrfs_root *root)
926 {
927 	struct extent_buffer *leaf;
928 
929 	/*
930 	 * DON'T set SHAREABLE bit for log trees.
931 	 *
932 	 * Log trees are not exposed to user space thus can't be snapshotted,
933 	 * and they go away before a real commit is actually done.
934 	 *
935 	 * They do store pointers to file data extents, and those reference
936 	 * counts still get updated (along with back refs to the log tree).
937 	 */
938 
939 	leaf = btrfs_alloc_tree_block(trans, root, 0, BTRFS_TREE_LOG_OBJECTID,
940 			NULL, 0, 0, 0, 0, BTRFS_NESTING_NORMAL);
941 	if (IS_ERR(leaf))
942 		return PTR_ERR(leaf);
943 
944 	root->node = leaf;
945 
946 	btrfs_mark_buffer_dirty(trans, root->node);
947 	btrfs_tree_unlock(root->node);
948 
949 	return 0;
950 }
951 
btrfs_init_log_root_tree(struct btrfs_trans_handle * trans,struct btrfs_fs_info * fs_info)952 int btrfs_init_log_root_tree(struct btrfs_trans_handle *trans,
953 			     struct btrfs_fs_info *fs_info)
954 {
955 	struct btrfs_root *log_root;
956 
957 	log_root = alloc_log_tree(fs_info);
958 	if (IS_ERR(log_root))
959 		return PTR_ERR(log_root);
960 
961 	if (!btrfs_is_zoned(fs_info)) {
962 		int ret = btrfs_alloc_log_tree_node(trans, log_root);
963 
964 		if (ret) {
965 			btrfs_put_root(log_root);
966 			return ret;
967 		}
968 	}
969 
970 	WARN_ON(fs_info->log_root_tree);
971 	fs_info->log_root_tree = log_root;
972 	return 0;
973 }
974 
btrfs_add_log_tree(struct btrfs_trans_handle * trans,struct btrfs_root * root)975 int btrfs_add_log_tree(struct btrfs_trans_handle *trans,
976 		       struct btrfs_root *root)
977 {
978 	struct btrfs_fs_info *fs_info = root->fs_info;
979 	struct btrfs_root *log_root;
980 	struct btrfs_inode_item *inode_item;
981 	int ret;
982 
983 	log_root = alloc_log_tree(fs_info);
984 	if (IS_ERR(log_root))
985 		return PTR_ERR(log_root);
986 
987 	ret = btrfs_alloc_log_tree_node(trans, log_root);
988 	if (ret) {
989 		btrfs_put_root(log_root);
990 		return ret;
991 	}
992 
993 	btrfs_set_root_last_trans(log_root, trans->transid);
994 	log_root->root_key.offset = btrfs_root_id(root);
995 
996 	inode_item = &log_root->root_item.inode;
997 	btrfs_set_stack_inode_generation(inode_item, 1);
998 	btrfs_set_stack_inode_size(inode_item, 3);
999 	btrfs_set_stack_inode_nlink(inode_item, 1);
1000 	btrfs_set_stack_inode_nbytes(inode_item,
1001 				     fs_info->nodesize);
1002 	btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
1003 
1004 	btrfs_set_root_node(&log_root->root_item, log_root->node);
1005 
1006 	WARN_ON(root->log_root);
1007 	root->log_root = log_root;
1008 	btrfs_set_root_log_transid(root, 0);
1009 	root->log_transid_committed = -1;
1010 	btrfs_set_root_last_log_commit(root, 0);
1011 	return 0;
1012 }
1013 
read_tree_root_path(struct btrfs_root * tree_root,struct btrfs_path * path,const struct btrfs_key * key)1014 static struct btrfs_root *read_tree_root_path(struct btrfs_root *tree_root,
1015 					      struct btrfs_path *path,
1016 					      const struct btrfs_key *key)
1017 {
1018 	struct btrfs_root *root;
1019 	struct btrfs_tree_parent_check check = { 0 };
1020 	struct btrfs_fs_info *fs_info = tree_root->fs_info;
1021 	u64 generation;
1022 	int ret;
1023 	int level;
1024 
1025 	root = btrfs_alloc_root(fs_info, key->objectid, GFP_NOFS);
1026 	if (!root)
1027 		return ERR_PTR(-ENOMEM);
1028 
1029 	ret = btrfs_find_root(tree_root, key, path,
1030 			      &root->root_item, &root->root_key);
1031 	if (ret) {
1032 		if (ret > 0)
1033 			ret = -ENOENT;
1034 		goto fail;
1035 	}
1036 
1037 	generation = btrfs_root_generation(&root->root_item);
1038 	level = btrfs_root_level(&root->root_item);
1039 	check.level = level;
1040 	check.transid = generation;
1041 	check.owner_root = key->objectid;
1042 	root->node = read_tree_block(fs_info, btrfs_root_bytenr(&root->root_item),
1043 				     &check);
1044 	if (IS_ERR(root->node)) {
1045 		ret = PTR_ERR(root->node);
1046 		root->node = NULL;
1047 		goto fail;
1048 	}
1049 	if (unlikely(!btrfs_buffer_uptodate(root->node, generation, false))) {
1050 		ret = -EIO;
1051 		goto fail;
1052 	}
1053 
1054 	/*
1055 	 * For real fs, and not log/reloc trees, root owner must
1056 	 * match its root node owner
1057 	 */
1058 	if (unlikely(!btrfs_is_testing(fs_info) &&
1059 		     btrfs_root_id(root) != BTRFS_TREE_LOG_OBJECTID &&
1060 		     btrfs_root_id(root) != BTRFS_TREE_RELOC_OBJECTID &&
1061 		     btrfs_root_id(root) != btrfs_header_owner(root->node))) {
1062 		btrfs_crit(fs_info,
1063 "root=%llu block=%llu, tree root owner mismatch, have %llu expect %llu",
1064 			   btrfs_root_id(root), root->node->start,
1065 			   btrfs_header_owner(root->node),
1066 			   btrfs_root_id(root));
1067 		ret = -EUCLEAN;
1068 		goto fail;
1069 	}
1070 	root->commit_root = btrfs_root_node(root);
1071 	return root;
1072 fail:
1073 	btrfs_put_root(root);
1074 	return ERR_PTR(ret);
1075 }
1076 
btrfs_read_tree_root(struct btrfs_root * tree_root,const struct btrfs_key * key)1077 struct btrfs_root *btrfs_read_tree_root(struct btrfs_root *tree_root,
1078 					const struct btrfs_key *key)
1079 {
1080 	struct btrfs_root *root;
1081 	BTRFS_PATH_AUTO_FREE(path);
1082 
1083 	path = btrfs_alloc_path();
1084 	if (!path)
1085 		return ERR_PTR(-ENOMEM);
1086 	root = read_tree_root_path(tree_root, path, key);
1087 
1088 	return root;
1089 }
1090 
1091 /*
1092  * Initialize subvolume root in-memory structure.
1093  *
1094  * @anon_dev:	anonymous device to attach to the root, if zero, allocate new
1095  *
1096  * In case of failure the caller is responsible to call btrfs_free_fs_root()
1097  */
btrfs_init_fs_root(struct btrfs_root * root,dev_t anon_dev)1098 static int btrfs_init_fs_root(struct btrfs_root *root, dev_t anon_dev)
1099 {
1100 	int ret;
1101 
1102 	btrfs_drew_lock_init(&root->snapshot_lock);
1103 
1104 	if (btrfs_root_id(root) != BTRFS_TREE_LOG_OBJECTID &&
1105 	    !btrfs_is_data_reloc_root(root) &&
1106 	    btrfs_is_fstree(btrfs_root_id(root))) {
1107 		set_bit(BTRFS_ROOT_SHAREABLE, &root->state);
1108 		btrfs_check_and_init_root_item(&root->root_item);
1109 	}
1110 
1111 	/*
1112 	 * Don't assign anonymous block device to roots that are not exposed to
1113 	 * userspace, the id pool is limited to 1M
1114 	 */
1115 	if (btrfs_is_fstree(btrfs_root_id(root)) &&
1116 	    btrfs_root_refs(&root->root_item) > 0) {
1117 		if (!anon_dev) {
1118 			ret = get_anon_bdev(&root->anon_dev);
1119 			if (ret)
1120 				return ret;
1121 		} else {
1122 			root->anon_dev = anon_dev;
1123 		}
1124 	}
1125 
1126 	mutex_lock(&root->objectid_mutex);
1127 	ret = btrfs_init_root_free_objectid(root);
1128 	if (ret) {
1129 		mutex_unlock(&root->objectid_mutex);
1130 		return ret;
1131 	}
1132 
1133 	ASSERT(root->free_objectid <= BTRFS_LAST_FREE_OBJECTID);
1134 
1135 	mutex_unlock(&root->objectid_mutex);
1136 
1137 	return 0;
1138 }
1139 
btrfs_lookup_fs_root(struct btrfs_fs_info * fs_info,u64 root_id)1140 static struct btrfs_root *btrfs_lookup_fs_root(struct btrfs_fs_info *fs_info,
1141 					       u64 root_id)
1142 {
1143 	struct btrfs_root *root;
1144 
1145 	spin_lock(&fs_info->fs_roots_radix_lock);
1146 	root = radix_tree_lookup(&fs_info->fs_roots_radix,
1147 				 (unsigned long)root_id);
1148 	root = btrfs_grab_root(root);
1149 	spin_unlock(&fs_info->fs_roots_radix_lock);
1150 	return root;
1151 }
1152 
btrfs_get_global_root(struct btrfs_fs_info * fs_info,u64 objectid)1153 static struct btrfs_root *btrfs_get_global_root(struct btrfs_fs_info *fs_info,
1154 						u64 objectid)
1155 {
1156 	struct btrfs_key key = {
1157 		.objectid = objectid,
1158 		.type = BTRFS_ROOT_ITEM_KEY,
1159 		.offset = 0,
1160 	};
1161 
1162 	switch (objectid) {
1163 	case BTRFS_ROOT_TREE_OBJECTID:
1164 		return btrfs_grab_root(fs_info->tree_root);
1165 	case BTRFS_EXTENT_TREE_OBJECTID:
1166 		return btrfs_grab_root(btrfs_global_root(fs_info, &key));
1167 	case BTRFS_CHUNK_TREE_OBJECTID:
1168 		return btrfs_grab_root(fs_info->chunk_root);
1169 	case BTRFS_DEV_TREE_OBJECTID:
1170 		return btrfs_grab_root(fs_info->dev_root);
1171 	case BTRFS_CSUM_TREE_OBJECTID:
1172 		return btrfs_grab_root(btrfs_global_root(fs_info, &key));
1173 	case BTRFS_QUOTA_TREE_OBJECTID:
1174 		return btrfs_grab_root(fs_info->quota_root);
1175 	case BTRFS_UUID_TREE_OBJECTID:
1176 		return btrfs_grab_root(fs_info->uuid_root);
1177 	case BTRFS_BLOCK_GROUP_TREE_OBJECTID:
1178 		return btrfs_grab_root(fs_info->block_group_root);
1179 	case BTRFS_FREE_SPACE_TREE_OBJECTID:
1180 		return btrfs_grab_root(btrfs_global_root(fs_info, &key));
1181 	case BTRFS_RAID_STRIPE_TREE_OBJECTID:
1182 		return btrfs_grab_root(fs_info->stripe_root);
1183 	default:
1184 		return NULL;
1185 	}
1186 }
1187 
btrfs_insert_fs_root(struct btrfs_fs_info * fs_info,struct btrfs_root * root)1188 int btrfs_insert_fs_root(struct btrfs_fs_info *fs_info,
1189 			 struct btrfs_root *root)
1190 {
1191 	int ret;
1192 
1193 	ret = radix_tree_preload(GFP_NOFS);
1194 	if (ret)
1195 		return ret;
1196 
1197 	spin_lock(&fs_info->fs_roots_radix_lock);
1198 	ret = radix_tree_insert(&fs_info->fs_roots_radix,
1199 				(unsigned long)btrfs_root_id(root),
1200 				root);
1201 	if (ret == 0) {
1202 		btrfs_grab_root(root);
1203 		set_bit(BTRFS_ROOT_IN_RADIX, &root->state);
1204 	}
1205 	spin_unlock(&fs_info->fs_roots_radix_lock);
1206 	radix_tree_preload_end();
1207 
1208 	return ret;
1209 }
1210 
btrfs_check_leaked_roots(const struct btrfs_fs_info * fs_info)1211 void btrfs_check_leaked_roots(const struct btrfs_fs_info *fs_info)
1212 {
1213 #ifdef CONFIG_BTRFS_DEBUG
1214 	struct btrfs_root *root;
1215 
1216 	while (!list_empty(&fs_info->allocated_roots)) {
1217 		char buf[BTRFS_ROOT_NAME_BUF_LEN];
1218 
1219 		root = list_first_entry(&fs_info->allocated_roots,
1220 					struct btrfs_root, leak_list);
1221 		btrfs_err(fs_info, "leaked root %s refcount %d",
1222 			  btrfs_root_name(&root->root_key, buf),
1223 			  refcount_read(&root->refs));
1224 		WARN_ON_ONCE(1);
1225 		while (refcount_read(&root->refs) > 1)
1226 			btrfs_put_root(root);
1227 		btrfs_put_root(root);
1228 	}
1229 #endif
1230 }
1231 
free_global_roots(struct btrfs_fs_info * fs_info)1232 static void free_global_roots(struct btrfs_fs_info *fs_info)
1233 {
1234 	struct btrfs_root *root;
1235 	struct rb_node *node;
1236 
1237 	while ((node = rb_first_postorder(&fs_info->global_root_tree)) != NULL) {
1238 		root = rb_entry(node, struct btrfs_root, rb_node);
1239 		rb_erase(&root->rb_node, &fs_info->global_root_tree);
1240 		btrfs_put_root(root);
1241 	}
1242 }
1243 
btrfs_free_fs_info(struct btrfs_fs_info * fs_info)1244 void btrfs_free_fs_info(struct btrfs_fs_info *fs_info)
1245 {
1246 	struct percpu_counter *em_counter = &fs_info->evictable_extent_maps;
1247 
1248 	if (fs_info->fs_devices)
1249 		btrfs_close_devices(fs_info->fs_devices);
1250 	btrfs_free_compress_wsm(fs_info);
1251 	percpu_counter_destroy(&fs_info->stats_read_blocks);
1252 	percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
1253 	percpu_counter_destroy(&fs_info->delalloc_bytes);
1254 	percpu_counter_destroy(&fs_info->ordered_bytes);
1255 	if (percpu_counter_initialized(em_counter))
1256 		ASSERT(percpu_counter_sum_positive(em_counter) == 0);
1257 	percpu_counter_destroy(em_counter);
1258 	percpu_counter_destroy(&fs_info->dev_replace.bio_counter);
1259 	btrfs_free_csum_hash(fs_info);
1260 	btrfs_free_stripe_hash_table(fs_info);
1261 	btrfs_free_ref_cache(fs_info);
1262 	kfree(fs_info->balance_ctl);
1263 	kfree(fs_info->delayed_root);
1264 	free_global_roots(fs_info);
1265 	btrfs_put_root(fs_info->tree_root);
1266 	btrfs_put_root(fs_info->chunk_root);
1267 	btrfs_put_root(fs_info->dev_root);
1268 	btrfs_put_root(fs_info->quota_root);
1269 	btrfs_put_root(fs_info->uuid_root);
1270 	btrfs_put_root(fs_info->fs_root);
1271 	btrfs_put_root(fs_info->data_reloc_root);
1272 	btrfs_put_root(fs_info->block_group_root);
1273 	btrfs_put_root(fs_info->stripe_root);
1274 	btrfs_check_leaked_roots(fs_info);
1275 	btrfs_extent_buffer_leak_debug_check(fs_info);
1276 	kfree(fs_info->super_copy);
1277 	kfree(fs_info->super_for_commit);
1278 	kvfree(fs_info);
1279 }
1280 
1281 
1282 /*
1283  * Get an in-memory reference of a root structure.
1284  *
1285  * For essential trees like root/extent tree, we grab it from fs_info directly.
1286  * For subvolume trees, we check the cached filesystem roots first. If not
1287  * found, then read it from disk and add it to cached fs roots.
1288  *
1289  * Caller should release the root by calling btrfs_put_root() after the usage.
1290  *
1291  * NOTE: Reloc and log trees can't be read by this function as they share the
1292  *	 same root objectid.
1293  *
1294  * @objectid:	root id
1295  * @anon_dev:	preallocated anonymous block device number for new roots,
1296  *		pass NULL for a new allocation.
1297  * @check_ref:	whether to check root item references, If true, return -ENOENT
1298  *		for orphan roots
1299  */
btrfs_get_root_ref(struct btrfs_fs_info * fs_info,u64 objectid,dev_t * anon_dev,bool check_ref)1300 static struct btrfs_root *btrfs_get_root_ref(struct btrfs_fs_info *fs_info,
1301 					     u64 objectid, dev_t *anon_dev,
1302 					     bool check_ref)
1303 {
1304 	struct btrfs_root *root;
1305 	struct btrfs_path *path;
1306 	struct btrfs_key key;
1307 	int ret;
1308 
1309 	root = btrfs_get_global_root(fs_info, objectid);
1310 	if (root)
1311 		return root;
1312 
1313 	/*
1314 	 * If we're called for non-subvolume trees, and above function didn't
1315 	 * find one, do not try to read it from disk.
1316 	 *
1317 	 * This is namely for free-space-tree and quota tree, which can change
1318 	 * at runtime and should only be grabbed from fs_info.
1319 	 */
1320 	if (!btrfs_is_fstree(objectid) && objectid != BTRFS_DATA_RELOC_TREE_OBJECTID)
1321 		return ERR_PTR(-ENOENT);
1322 again:
1323 	root = btrfs_lookup_fs_root(fs_info, objectid);
1324 	if (root) {
1325 		/*
1326 		 * Some other caller may have read out the newly inserted
1327 		 * subvolume already (for things like backref walk etc).  Not
1328 		 * that common but still possible.  In that case, we just need
1329 		 * to free the anon_dev.
1330 		 */
1331 		if (unlikely(anon_dev && *anon_dev)) {
1332 			free_anon_bdev(*anon_dev);
1333 			*anon_dev = 0;
1334 		}
1335 
1336 		if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
1337 			btrfs_put_root(root);
1338 			return ERR_PTR(-ENOENT);
1339 		}
1340 		return root;
1341 	}
1342 
1343 	key.objectid = objectid;
1344 	key.type = BTRFS_ROOT_ITEM_KEY;
1345 	key.offset = (u64)-1;
1346 	root = btrfs_read_tree_root(fs_info->tree_root, &key);
1347 	if (IS_ERR(root))
1348 		return root;
1349 
1350 	if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
1351 		ret = -ENOENT;
1352 		goto fail;
1353 	}
1354 
1355 	ret = btrfs_init_fs_root(root, anon_dev ? *anon_dev : 0);
1356 	if (ret)
1357 		goto fail;
1358 
1359 	path = btrfs_alloc_path();
1360 	if (!path) {
1361 		ret = -ENOMEM;
1362 		goto fail;
1363 	}
1364 	key.objectid = BTRFS_ORPHAN_OBJECTID;
1365 	key.type = BTRFS_ORPHAN_ITEM_KEY;
1366 	key.offset = objectid;
1367 
1368 	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
1369 	btrfs_free_path(path);
1370 	if (ret < 0)
1371 		goto fail;
1372 	if (ret == 0)
1373 		set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state);
1374 
1375 	ret = btrfs_insert_fs_root(fs_info, root);
1376 	if (ret) {
1377 		if (ret == -EEXIST) {
1378 			btrfs_put_root(root);
1379 			goto again;
1380 		}
1381 		goto fail;
1382 	}
1383 	return root;
1384 fail:
1385 	/*
1386 	 * If our caller provided us an anonymous device, then it's his
1387 	 * responsibility to free it in case we fail. So we have to set our
1388 	 * root's anon_dev to 0 to avoid a double free, once by btrfs_put_root()
1389 	 * and once again by our caller.
1390 	 */
1391 	if (anon_dev && *anon_dev)
1392 		root->anon_dev = 0;
1393 	btrfs_put_root(root);
1394 	return ERR_PTR(ret);
1395 }
1396 
1397 /*
1398  * Get in-memory reference of a root structure
1399  *
1400  * @objectid:	tree objectid
1401  * @check_ref:	if set, verify that the tree exists and the item has at least
1402  *		one reference
1403  */
btrfs_get_fs_root(struct btrfs_fs_info * fs_info,u64 objectid,bool check_ref)1404 struct btrfs_root *btrfs_get_fs_root(struct btrfs_fs_info *fs_info,
1405 				     u64 objectid, bool check_ref)
1406 {
1407 	return btrfs_get_root_ref(fs_info, objectid, NULL, check_ref);
1408 }
1409 
1410 /*
1411  * Get in-memory reference of a root structure, created as new, optionally pass
1412  * the anonymous block device id
1413  *
1414  * @objectid:	tree objectid
1415  * @anon_dev:	if NULL, allocate a new anonymous block device or use the
1416  *		parameter value if not NULL
1417  */
btrfs_get_new_fs_root(struct btrfs_fs_info * fs_info,u64 objectid,dev_t * anon_dev)1418 struct btrfs_root *btrfs_get_new_fs_root(struct btrfs_fs_info *fs_info,
1419 					 u64 objectid, dev_t *anon_dev)
1420 {
1421 	return btrfs_get_root_ref(fs_info, objectid, anon_dev, true);
1422 }
1423 
1424 /*
1425  * Return a root for the given objectid.
1426  *
1427  * @fs_info:	the fs_info
1428  * @objectid:	the objectid we need to lookup
1429  *
1430  * This is exclusively used for backref walking, and exists specifically because
1431  * of how qgroups does lookups.  Qgroups will do a backref lookup at delayed ref
1432  * creation time, which means we may have to read the tree_root in order to look
1433  * up a fs root that is not in memory.  If the root is not in memory we will
1434  * read the tree root commit root and look up the fs root from there.  This is a
1435  * temporary root, it will not be inserted into the radix tree as it doesn't
1436  * have the most uptodate information, it'll simply be discarded once the
1437  * backref code is finished using the root.
1438  */
btrfs_get_fs_root_commit_root(struct btrfs_fs_info * fs_info,struct btrfs_path * path,u64 objectid)1439 struct btrfs_root *btrfs_get_fs_root_commit_root(struct btrfs_fs_info *fs_info,
1440 						 struct btrfs_path *path,
1441 						 u64 objectid)
1442 {
1443 	struct btrfs_root *root;
1444 	struct btrfs_key key;
1445 
1446 	ASSERT(path->search_commit_root && path->skip_locking);
1447 
1448 	/*
1449 	 * This can return -ENOENT if we ask for a root that doesn't exist, but
1450 	 * since this is called via the backref walking code we won't be looking
1451 	 * up a root that doesn't exist, unless there's corruption.  So if root
1452 	 * != NULL just return it.
1453 	 */
1454 	root = btrfs_get_global_root(fs_info, objectid);
1455 	if (root)
1456 		return root;
1457 
1458 	root = btrfs_lookup_fs_root(fs_info, objectid);
1459 	if (root)
1460 		return root;
1461 
1462 	key.objectid = objectid;
1463 	key.type = BTRFS_ROOT_ITEM_KEY;
1464 	key.offset = (u64)-1;
1465 	root = read_tree_root_path(fs_info->tree_root, path, &key);
1466 	btrfs_release_path(path);
1467 
1468 	return root;
1469 }
1470 
cleaner_kthread(void * arg)1471 static int cleaner_kthread(void *arg)
1472 {
1473 	struct btrfs_fs_info *fs_info = arg;
1474 	int again;
1475 
1476 	while (1) {
1477 		again = 0;
1478 
1479 		set_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1480 
1481 		/* Make the cleaner go to sleep early. */
1482 		if (btrfs_need_cleaner_sleep(fs_info))
1483 			goto sleep;
1484 
1485 		/*
1486 		 * Do not do anything if we might cause open_ctree() to block
1487 		 * before we have finished mounting the filesystem.
1488 		 */
1489 		if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
1490 			goto sleep;
1491 
1492 		if (!mutex_trylock(&fs_info->cleaner_mutex))
1493 			goto sleep;
1494 
1495 		/*
1496 		 * Avoid the problem that we change the status of the fs
1497 		 * during the above check and trylock.
1498 		 */
1499 		if (btrfs_need_cleaner_sleep(fs_info)) {
1500 			mutex_unlock(&fs_info->cleaner_mutex);
1501 			goto sleep;
1502 		}
1503 
1504 		if (test_and_clear_bit(BTRFS_FS_FEATURE_CHANGED, &fs_info->flags))
1505 			btrfs_sysfs_feature_update(fs_info);
1506 
1507 		btrfs_run_delayed_iputs(fs_info);
1508 
1509 		again = btrfs_clean_one_deleted_snapshot(fs_info);
1510 		mutex_unlock(&fs_info->cleaner_mutex);
1511 
1512 		/*
1513 		 * The defragger has dealt with the R/O remount and umount,
1514 		 * needn't do anything special here.
1515 		 */
1516 		btrfs_run_defrag_inodes(fs_info);
1517 
1518 		/*
1519 		 * Acquires fs_info->reclaim_bgs_lock to avoid racing
1520 		 * with relocation (btrfs_relocate_chunk) and relocation
1521 		 * acquires fs_info->cleaner_mutex (btrfs_relocate_block_group)
1522 		 * after acquiring fs_info->reclaim_bgs_lock. So we
1523 		 * can't hold, nor need to, fs_info->cleaner_mutex when deleting
1524 		 * unused block groups.
1525 		 */
1526 		btrfs_delete_unused_bgs(fs_info);
1527 
1528 		/*
1529 		 * Reclaim block groups in the reclaim_bgs list after we deleted
1530 		 * all unused block_groups. This possibly gives us some more free
1531 		 * space.
1532 		 */
1533 		btrfs_reclaim_bgs(fs_info);
1534 sleep:
1535 		clear_and_wake_up_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1536 		if (kthread_should_park())
1537 			kthread_parkme();
1538 		if (kthread_should_stop())
1539 			return 0;
1540 		if (!again) {
1541 			set_current_state(TASK_INTERRUPTIBLE);
1542 			schedule();
1543 			__set_current_state(TASK_RUNNING);
1544 		}
1545 	}
1546 }
1547 
transaction_kthread(void * arg)1548 static int transaction_kthread(void *arg)
1549 {
1550 	struct btrfs_root *root = arg;
1551 	struct btrfs_fs_info *fs_info = root->fs_info;
1552 	struct btrfs_trans_handle *trans;
1553 	struct btrfs_transaction *cur;
1554 	u64 transid;
1555 	time64_t delta;
1556 	unsigned long delay;
1557 	bool cannot_commit;
1558 
1559 	do {
1560 		cannot_commit = false;
1561 		delay = secs_to_jiffies(fs_info->commit_interval);
1562 		mutex_lock(&fs_info->transaction_kthread_mutex);
1563 
1564 		spin_lock(&fs_info->trans_lock);
1565 		cur = fs_info->running_transaction;
1566 		if (!cur) {
1567 			spin_unlock(&fs_info->trans_lock);
1568 			goto sleep;
1569 		}
1570 
1571 		delta = ktime_get_seconds() - cur->start_time;
1572 		if (!test_and_clear_bit(BTRFS_FS_COMMIT_TRANS, &fs_info->flags) &&
1573 		    cur->state < TRANS_STATE_COMMIT_PREP &&
1574 		    delta < fs_info->commit_interval) {
1575 			spin_unlock(&fs_info->trans_lock);
1576 			delay -= secs_to_jiffies(delta - 1);
1577 			delay = min(delay,
1578 				    secs_to_jiffies(fs_info->commit_interval));
1579 			goto sleep;
1580 		}
1581 		transid = cur->transid;
1582 		spin_unlock(&fs_info->trans_lock);
1583 
1584 		/* If the file system is aborted, this will always fail. */
1585 		trans = btrfs_attach_transaction(root);
1586 		if (IS_ERR(trans)) {
1587 			if (PTR_ERR(trans) != -ENOENT)
1588 				cannot_commit = true;
1589 			goto sleep;
1590 		}
1591 		if (transid == trans->transid) {
1592 			btrfs_commit_transaction(trans);
1593 		} else {
1594 			btrfs_end_transaction(trans);
1595 		}
1596 sleep:
1597 		wake_up_process(fs_info->cleaner_kthread);
1598 		mutex_unlock(&fs_info->transaction_kthread_mutex);
1599 
1600 		if (BTRFS_FS_ERROR(fs_info))
1601 			btrfs_cleanup_transaction(fs_info);
1602 		if (!kthread_should_stop() &&
1603 				(!btrfs_transaction_blocked(fs_info) ||
1604 				 cannot_commit))
1605 			schedule_timeout_interruptible(delay);
1606 	} while (!kthread_should_stop());
1607 	return 0;
1608 }
1609 
1610 /*
1611  * This will find the highest generation in the array of root backups.  The
1612  * index of the highest array is returned, or -EINVAL if we can't find
1613  * anything.
1614  *
1615  * We check to make sure the array is valid by comparing the
1616  * generation of the latest  root in the array with the generation
1617  * in the super block.  If they don't match we pitch it.
1618  */
find_newest_super_backup(struct btrfs_fs_info * info)1619 static int find_newest_super_backup(struct btrfs_fs_info *info)
1620 {
1621 	const u64 newest_gen = btrfs_super_generation(info->super_copy);
1622 	u64 cur;
1623 	struct btrfs_root_backup *root_backup;
1624 	int i;
1625 
1626 	for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
1627 		root_backup = info->super_copy->super_roots + i;
1628 		cur = btrfs_backup_tree_root_gen(root_backup);
1629 		if (cur == newest_gen)
1630 			return i;
1631 	}
1632 
1633 	return -EINVAL;
1634 }
1635 
1636 /*
1637  * copy all the root pointers into the super backup array.
1638  * this will bump the backup pointer by one when it is
1639  * done
1640  */
backup_super_roots(struct btrfs_fs_info * info)1641 static void backup_super_roots(struct btrfs_fs_info *info)
1642 {
1643 	const int next_backup = info->backup_root_index;
1644 	struct btrfs_root_backup *root_backup;
1645 
1646 	root_backup = info->super_for_commit->super_roots + next_backup;
1647 
1648 	/*
1649 	 * make sure all of our padding and empty slots get zero filled
1650 	 * regardless of which ones we use today
1651 	 */
1652 	memset(root_backup, 0, sizeof(*root_backup));
1653 
1654 	info->backup_root_index = (next_backup + 1) % BTRFS_NUM_BACKUP_ROOTS;
1655 
1656 	btrfs_set_backup_tree_root(root_backup, info->tree_root->node->start);
1657 	btrfs_set_backup_tree_root_gen(root_backup,
1658 			       btrfs_header_generation(info->tree_root->node));
1659 
1660 	btrfs_set_backup_tree_root_level(root_backup,
1661 			       btrfs_header_level(info->tree_root->node));
1662 
1663 	btrfs_set_backup_chunk_root(root_backup, info->chunk_root->node->start);
1664 	btrfs_set_backup_chunk_root_gen(root_backup,
1665 			       btrfs_header_generation(info->chunk_root->node));
1666 	btrfs_set_backup_chunk_root_level(root_backup,
1667 			       btrfs_header_level(info->chunk_root->node));
1668 
1669 	if (!btrfs_fs_compat_ro(info, BLOCK_GROUP_TREE)) {
1670 		struct btrfs_root *extent_root = btrfs_extent_root(info, 0);
1671 		struct btrfs_root *csum_root = btrfs_csum_root(info, 0);
1672 
1673 		btrfs_set_backup_extent_root(root_backup,
1674 					     extent_root->node->start);
1675 		btrfs_set_backup_extent_root_gen(root_backup,
1676 				btrfs_header_generation(extent_root->node));
1677 		btrfs_set_backup_extent_root_level(root_backup,
1678 					btrfs_header_level(extent_root->node));
1679 
1680 		btrfs_set_backup_csum_root(root_backup, csum_root->node->start);
1681 		btrfs_set_backup_csum_root_gen(root_backup,
1682 					       btrfs_header_generation(csum_root->node));
1683 		btrfs_set_backup_csum_root_level(root_backup,
1684 						 btrfs_header_level(csum_root->node));
1685 	}
1686 
1687 	/*
1688 	 * we might commit during log recovery, which happens before we set
1689 	 * the fs_root.  Make sure it is valid before we fill it in.
1690 	 */
1691 	if (info->fs_root && info->fs_root->node) {
1692 		btrfs_set_backup_fs_root(root_backup,
1693 					 info->fs_root->node->start);
1694 		btrfs_set_backup_fs_root_gen(root_backup,
1695 			       btrfs_header_generation(info->fs_root->node));
1696 		btrfs_set_backup_fs_root_level(root_backup,
1697 			       btrfs_header_level(info->fs_root->node));
1698 	}
1699 
1700 	btrfs_set_backup_dev_root(root_backup, info->dev_root->node->start);
1701 	btrfs_set_backup_dev_root_gen(root_backup,
1702 			       btrfs_header_generation(info->dev_root->node));
1703 	btrfs_set_backup_dev_root_level(root_backup,
1704 				       btrfs_header_level(info->dev_root->node));
1705 
1706 	btrfs_set_backup_total_bytes(root_backup,
1707 			     btrfs_super_total_bytes(info->super_copy));
1708 	btrfs_set_backup_bytes_used(root_backup,
1709 			     btrfs_super_bytes_used(info->super_copy));
1710 	btrfs_set_backup_num_devices(root_backup,
1711 			     btrfs_super_num_devices(info->super_copy));
1712 
1713 	/*
1714 	 * if we don't copy this out to the super_copy, it won't get remembered
1715 	 * for the next commit
1716 	 */
1717 	memcpy(&info->super_copy->super_roots,
1718 	       &info->super_for_commit->super_roots,
1719 	       sizeof(*root_backup) * BTRFS_NUM_BACKUP_ROOTS);
1720 }
1721 
1722 /*
1723  * Reads a backup root based on the passed priority. Prio 0 is the newest, prio
1724  * 1/2/3 are 2nd newest/3rd newest/4th (oldest) backup roots
1725  *
1726  * @fs_info:  filesystem whose backup roots need to be read
1727  * @priority: priority of backup root required
1728  *
1729  * Returns backup root index on success and -EINVAL otherwise.
1730  */
read_backup_root(struct btrfs_fs_info * fs_info,u8 priority)1731 static int read_backup_root(struct btrfs_fs_info *fs_info, u8 priority)
1732 {
1733 	int backup_index = find_newest_super_backup(fs_info);
1734 	struct btrfs_super_block *super = fs_info->super_copy;
1735 	struct btrfs_root_backup *root_backup;
1736 
1737 	if (priority < BTRFS_NUM_BACKUP_ROOTS && backup_index >= 0) {
1738 		if (priority == 0)
1739 			return backup_index;
1740 
1741 		backup_index = backup_index + BTRFS_NUM_BACKUP_ROOTS - priority;
1742 		backup_index %= BTRFS_NUM_BACKUP_ROOTS;
1743 	} else {
1744 		return -EINVAL;
1745 	}
1746 
1747 	root_backup = super->super_roots + backup_index;
1748 
1749 	btrfs_set_super_generation(super,
1750 				   btrfs_backup_tree_root_gen(root_backup));
1751 	btrfs_set_super_root(super, btrfs_backup_tree_root(root_backup));
1752 	btrfs_set_super_root_level(super,
1753 				   btrfs_backup_tree_root_level(root_backup));
1754 	btrfs_set_super_bytes_used(super, btrfs_backup_bytes_used(root_backup));
1755 
1756 	/*
1757 	 * Fixme: the total bytes and num_devices need to match or we should
1758 	 * need a fsck
1759 	 */
1760 	btrfs_set_super_total_bytes(super, btrfs_backup_total_bytes(root_backup));
1761 	btrfs_set_super_num_devices(super, btrfs_backup_num_devices(root_backup));
1762 
1763 	return backup_index;
1764 }
1765 
1766 /* helper to cleanup workers */
btrfs_stop_all_workers(struct btrfs_fs_info * fs_info)1767 static void btrfs_stop_all_workers(struct btrfs_fs_info *fs_info)
1768 {
1769 	btrfs_destroy_workqueue(fs_info->fixup_workers);
1770 	btrfs_destroy_workqueue(fs_info->delalloc_workers);
1771 	btrfs_destroy_workqueue(fs_info->workers);
1772 	if (fs_info->endio_workers)
1773 		destroy_workqueue(fs_info->endio_workers);
1774 	if (fs_info->rmw_workers)
1775 		destroy_workqueue(fs_info->rmw_workers);
1776 	if (fs_info->compressed_write_workers)
1777 		destroy_workqueue(fs_info->compressed_write_workers);
1778 	btrfs_destroy_workqueue(fs_info->endio_write_workers);
1779 	btrfs_destroy_workqueue(fs_info->endio_freespace_worker);
1780 	btrfs_destroy_workqueue(fs_info->delayed_workers);
1781 	btrfs_destroy_workqueue(fs_info->caching_workers);
1782 	btrfs_destroy_workqueue(fs_info->flush_workers);
1783 	btrfs_destroy_workqueue(fs_info->qgroup_rescan_workers);
1784 	if (fs_info->discard_ctl.discard_workers)
1785 		destroy_workqueue(fs_info->discard_ctl.discard_workers);
1786 	/*
1787 	 * Now that all other work queues are destroyed, we can safely destroy
1788 	 * the queues used for metadata I/O, since tasks from those other work
1789 	 * queues can do metadata I/O operations.
1790 	 */
1791 	if (fs_info->endio_meta_workers)
1792 		destroy_workqueue(fs_info->endio_meta_workers);
1793 }
1794 
free_root_extent_buffers(struct btrfs_root * root)1795 static void free_root_extent_buffers(struct btrfs_root *root)
1796 {
1797 	if (root) {
1798 		free_extent_buffer(root->node);
1799 		free_extent_buffer(root->commit_root);
1800 		root->node = NULL;
1801 		root->commit_root = NULL;
1802 	}
1803 }
1804 
free_global_root_pointers(struct btrfs_fs_info * fs_info)1805 static void free_global_root_pointers(struct btrfs_fs_info *fs_info)
1806 {
1807 	struct btrfs_root *root, *tmp;
1808 
1809 	rbtree_postorder_for_each_entry_safe(root, tmp,
1810 					     &fs_info->global_root_tree,
1811 					     rb_node)
1812 		free_root_extent_buffers(root);
1813 }
1814 
1815 /* helper to cleanup tree roots */
free_root_pointers(struct btrfs_fs_info * info,bool free_chunk_root)1816 static void free_root_pointers(struct btrfs_fs_info *info, bool free_chunk_root)
1817 {
1818 	free_root_extent_buffers(info->tree_root);
1819 
1820 	free_global_root_pointers(info);
1821 	free_root_extent_buffers(info->dev_root);
1822 	free_root_extent_buffers(info->quota_root);
1823 	free_root_extent_buffers(info->uuid_root);
1824 	free_root_extent_buffers(info->fs_root);
1825 	free_root_extent_buffers(info->data_reloc_root);
1826 	free_root_extent_buffers(info->block_group_root);
1827 	free_root_extent_buffers(info->stripe_root);
1828 	if (free_chunk_root)
1829 		free_root_extent_buffers(info->chunk_root);
1830 }
1831 
btrfs_put_root(struct btrfs_root * root)1832 void btrfs_put_root(struct btrfs_root *root)
1833 {
1834 	if (!root)
1835 		return;
1836 
1837 	if (refcount_dec_and_test(&root->refs)) {
1838 		if (WARN_ON(!xa_empty(&root->inodes)))
1839 			xa_destroy(&root->inodes);
1840 		if (WARN_ON(!xa_empty(&root->delayed_nodes)))
1841 			xa_destroy(&root->delayed_nodes);
1842 		WARN_ON(test_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state));
1843 		if (root->anon_dev)
1844 			free_anon_bdev(root->anon_dev);
1845 		free_root_extent_buffers(root);
1846 #ifdef CONFIG_BTRFS_DEBUG
1847 		spin_lock(&root->fs_info->fs_roots_radix_lock);
1848 		list_del_init(&root->leak_list);
1849 		spin_unlock(&root->fs_info->fs_roots_radix_lock);
1850 #endif
1851 		kfree(root);
1852 	}
1853 }
1854 
btrfs_free_fs_roots(struct btrfs_fs_info * fs_info)1855 void btrfs_free_fs_roots(struct btrfs_fs_info *fs_info)
1856 {
1857 	int ret;
1858 	struct btrfs_root *gang[8];
1859 	int i;
1860 
1861 	while (!list_empty(&fs_info->dead_roots)) {
1862 		gang[0] = list_first_entry(&fs_info->dead_roots,
1863 					   struct btrfs_root, root_list);
1864 		list_del(&gang[0]->root_list);
1865 
1866 		if (test_bit(BTRFS_ROOT_IN_RADIX, &gang[0]->state))
1867 			btrfs_drop_and_free_fs_root(fs_info, gang[0]);
1868 		btrfs_put_root(gang[0]);
1869 	}
1870 
1871 	while (1) {
1872 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
1873 					     (void **)gang, 0,
1874 					     ARRAY_SIZE(gang));
1875 		if (!ret)
1876 			break;
1877 		for (i = 0; i < ret; i++)
1878 			btrfs_drop_and_free_fs_root(fs_info, gang[i]);
1879 	}
1880 }
1881 
btrfs_init_scrub(struct btrfs_fs_info * fs_info)1882 static void btrfs_init_scrub(struct btrfs_fs_info *fs_info)
1883 {
1884 	mutex_init(&fs_info->scrub_lock);
1885 	atomic_set(&fs_info->scrubs_running, 0);
1886 	atomic_set(&fs_info->scrub_pause_req, 0);
1887 	atomic_set(&fs_info->scrubs_paused, 0);
1888 	atomic_set(&fs_info->scrub_cancel_req, 0);
1889 	init_waitqueue_head(&fs_info->scrub_pause_wait);
1890 	refcount_set(&fs_info->scrub_workers_refcnt, 0);
1891 }
1892 
btrfs_init_balance(struct btrfs_fs_info * fs_info)1893 static void btrfs_init_balance(struct btrfs_fs_info *fs_info)
1894 {
1895 	spin_lock_init(&fs_info->balance_lock);
1896 	mutex_init(&fs_info->balance_mutex);
1897 	atomic_set(&fs_info->balance_pause_req, 0);
1898 	atomic_set(&fs_info->balance_cancel_req, 0);
1899 	fs_info->balance_ctl = NULL;
1900 	init_waitqueue_head(&fs_info->balance_wait_q);
1901 	atomic_set(&fs_info->reloc_cancel_req, 0);
1902 }
1903 
btrfs_init_btree_inode(struct super_block * sb)1904 static int btrfs_init_btree_inode(struct super_block *sb)
1905 {
1906 	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
1907 	unsigned long hash = btrfs_inode_hash(BTRFS_BTREE_INODE_OBJECTID,
1908 					      fs_info->tree_root);
1909 	struct inode *inode;
1910 
1911 	inode = new_inode(sb);
1912 	if (!inode)
1913 		return -ENOMEM;
1914 
1915 	btrfs_set_inode_number(BTRFS_I(inode), BTRFS_BTREE_INODE_OBJECTID);
1916 	set_nlink(inode, 1);
1917 	/*
1918 	 * we set the i_size on the btree inode to the max possible int.
1919 	 * the real end of the address space is determined by all of
1920 	 * the devices in the system
1921 	 */
1922 	inode->i_size = OFFSET_MAX;
1923 	inode->i_mapping->a_ops = &btree_aops;
1924 	mapping_set_gfp_mask(inode->i_mapping, GFP_NOFS);
1925 
1926 	btrfs_extent_io_tree_init(fs_info, &BTRFS_I(inode)->io_tree,
1927 				  IO_TREE_BTREE_INODE_IO);
1928 	btrfs_extent_map_tree_init(&BTRFS_I(inode)->extent_tree);
1929 
1930 	BTRFS_I(inode)->root = btrfs_grab_root(fs_info->tree_root);
1931 	set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
1932 	__insert_inode_hash(inode, hash);
1933 	set_bit(AS_KERNEL_FILE, &inode->i_mapping->flags);
1934 	fs_info->btree_inode = inode;
1935 
1936 	return 0;
1937 }
1938 
btrfs_init_dev_replace_locks(struct btrfs_fs_info * fs_info)1939 static void btrfs_init_dev_replace_locks(struct btrfs_fs_info *fs_info)
1940 {
1941 	mutex_init(&fs_info->dev_replace.lock_finishing_cancel_unmount);
1942 	init_rwsem(&fs_info->dev_replace.rwsem);
1943 	init_waitqueue_head(&fs_info->dev_replace.replace_wait);
1944 }
1945 
btrfs_init_qgroup(struct btrfs_fs_info * fs_info)1946 static void btrfs_init_qgroup(struct btrfs_fs_info *fs_info)
1947 {
1948 	spin_lock_init(&fs_info->qgroup_lock);
1949 	mutex_init(&fs_info->qgroup_ioctl_lock);
1950 	fs_info->qgroup_tree = RB_ROOT;
1951 	INIT_LIST_HEAD(&fs_info->dirty_qgroups);
1952 	fs_info->qgroup_seq = 1;
1953 	fs_info->qgroup_rescan_running = false;
1954 	fs_info->qgroup_drop_subtree_thres = BTRFS_QGROUP_DROP_SUBTREE_THRES_DEFAULT;
1955 	mutex_init(&fs_info->qgroup_rescan_lock);
1956 }
1957 
btrfs_init_workqueues(struct btrfs_fs_info * fs_info)1958 static int btrfs_init_workqueues(struct btrfs_fs_info *fs_info)
1959 {
1960 	u32 max_active = fs_info->thread_pool_size;
1961 	unsigned int flags = WQ_MEM_RECLAIM | WQ_FREEZABLE | WQ_UNBOUND;
1962 	unsigned int ordered_flags = WQ_MEM_RECLAIM | WQ_FREEZABLE | WQ_PERCPU;
1963 
1964 	fs_info->workers =
1965 		btrfs_alloc_workqueue(fs_info, "worker", flags, max_active, 16);
1966 
1967 	fs_info->delalloc_workers =
1968 		btrfs_alloc_workqueue(fs_info, "delalloc",
1969 				      flags, max_active, 2);
1970 
1971 	fs_info->flush_workers =
1972 		btrfs_alloc_workqueue(fs_info, "flush_delalloc",
1973 				      flags, max_active, 0);
1974 
1975 	fs_info->caching_workers =
1976 		btrfs_alloc_workqueue(fs_info, "cache", flags, max_active, 0);
1977 
1978 	fs_info->fixup_workers =
1979 		btrfs_alloc_ordered_workqueue(fs_info, "fixup", ordered_flags);
1980 
1981 	fs_info->endio_workers =
1982 		alloc_workqueue("btrfs-endio", flags, max_active);
1983 	fs_info->endio_meta_workers =
1984 		alloc_workqueue("btrfs-endio-meta", flags, max_active);
1985 	fs_info->rmw_workers = alloc_workqueue("btrfs-rmw", flags, max_active);
1986 	fs_info->endio_write_workers =
1987 		btrfs_alloc_workqueue(fs_info, "endio-write", flags,
1988 				      max_active, 2);
1989 	fs_info->compressed_write_workers =
1990 		alloc_workqueue("btrfs-compressed-write", flags, max_active);
1991 	fs_info->endio_freespace_worker =
1992 		btrfs_alloc_workqueue(fs_info, "freespace-write", flags,
1993 				      max_active, 0);
1994 	fs_info->delayed_workers =
1995 		btrfs_alloc_workqueue(fs_info, "delayed-meta", flags,
1996 				      max_active, 0);
1997 	fs_info->qgroup_rescan_workers =
1998 		btrfs_alloc_ordered_workqueue(fs_info, "qgroup-rescan",
1999 					      ordered_flags);
2000 	fs_info->discard_ctl.discard_workers =
2001 		alloc_ordered_workqueue("btrfs-discard", WQ_FREEZABLE);
2002 
2003 	if (!(fs_info->workers &&
2004 	      fs_info->delalloc_workers && fs_info->flush_workers &&
2005 	      fs_info->endio_workers && fs_info->endio_meta_workers &&
2006 	      fs_info->compressed_write_workers &&
2007 	      fs_info->endio_write_workers &&
2008 	      fs_info->endio_freespace_worker && fs_info->rmw_workers &&
2009 	      fs_info->caching_workers && fs_info->fixup_workers &&
2010 	      fs_info->delayed_workers && fs_info->qgroup_rescan_workers &&
2011 	      fs_info->discard_ctl.discard_workers)) {
2012 		return -ENOMEM;
2013 	}
2014 
2015 	return 0;
2016 }
2017 
btrfs_init_csum_hash(struct btrfs_fs_info * fs_info,u16 csum_type)2018 static int btrfs_init_csum_hash(struct btrfs_fs_info *fs_info, u16 csum_type)
2019 {
2020 	struct crypto_shash *csum_shash;
2021 	const char *csum_driver = btrfs_super_csum_driver(csum_type);
2022 
2023 	csum_shash = crypto_alloc_shash(csum_driver, 0, 0);
2024 
2025 	if (IS_ERR(csum_shash)) {
2026 		btrfs_err(fs_info, "error allocating %s hash for checksum",
2027 			  csum_driver);
2028 		return PTR_ERR(csum_shash);
2029 	}
2030 
2031 	fs_info->csum_shash = csum_shash;
2032 
2033 	/* Check if the checksum implementation is a fast accelerated one. */
2034 	switch (csum_type) {
2035 	case BTRFS_CSUM_TYPE_CRC32:
2036 		if (crc32_optimizations() & CRC32C_OPTIMIZATION)
2037 			set_bit(BTRFS_FS_CSUM_IMPL_FAST, &fs_info->flags);
2038 		break;
2039 	case BTRFS_CSUM_TYPE_XXHASH:
2040 		set_bit(BTRFS_FS_CSUM_IMPL_FAST, &fs_info->flags);
2041 		break;
2042 	default:
2043 		break;
2044 	}
2045 
2046 	btrfs_info(fs_info, "using %s (%s) checksum algorithm",
2047 			btrfs_super_csum_name(csum_type),
2048 			crypto_shash_driver_name(csum_shash));
2049 	return 0;
2050 }
2051 
btrfs_replay_log(struct btrfs_fs_info * fs_info,struct btrfs_fs_devices * fs_devices)2052 static int btrfs_replay_log(struct btrfs_fs_info *fs_info,
2053 			    struct btrfs_fs_devices *fs_devices)
2054 {
2055 	int ret;
2056 	struct btrfs_tree_parent_check check = { 0 };
2057 	struct btrfs_root *log_tree_root;
2058 	struct btrfs_super_block *disk_super = fs_info->super_copy;
2059 	u64 bytenr = btrfs_super_log_root(disk_super);
2060 	int level = btrfs_super_log_root_level(disk_super);
2061 
2062 	if (unlikely(fs_devices->rw_devices == 0)) {
2063 		btrfs_warn(fs_info, "log replay required on RO media");
2064 		return -EIO;
2065 	}
2066 
2067 	log_tree_root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID,
2068 					 GFP_KERNEL);
2069 	if (!log_tree_root)
2070 		return -ENOMEM;
2071 
2072 	check.level = level;
2073 	check.transid = fs_info->generation + 1;
2074 	check.owner_root = BTRFS_TREE_LOG_OBJECTID;
2075 	log_tree_root->node = read_tree_block(fs_info, bytenr, &check);
2076 	if (IS_ERR(log_tree_root->node)) {
2077 		btrfs_warn(fs_info, "failed to read log tree");
2078 		ret = PTR_ERR(log_tree_root->node);
2079 		log_tree_root->node = NULL;
2080 		btrfs_put_root(log_tree_root);
2081 		return ret;
2082 	}
2083 	if (unlikely(!extent_buffer_uptodate(log_tree_root->node))) {
2084 		btrfs_err(fs_info, "failed to read log tree");
2085 		btrfs_put_root(log_tree_root);
2086 		return -EIO;
2087 	}
2088 
2089 	/* returns with log_tree_root freed on success */
2090 	ret = btrfs_recover_log_trees(log_tree_root);
2091 	btrfs_put_root(log_tree_root);
2092 	if (ret) {
2093 		btrfs_handle_fs_error(fs_info, ret,
2094 				      "Failed to recover log tree");
2095 		return ret;
2096 	}
2097 
2098 	if (sb_rdonly(fs_info->sb)) {
2099 		ret = btrfs_commit_super(fs_info);
2100 		if (ret)
2101 			return ret;
2102 	}
2103 
2104 	return 0;
2105 }
2106 
load_global_roots_objectid(struct btrfs_root * tree_root,struct btrfs_path * path,u64 objectid,const char * name)2107 static int load_global_roots_objectid(struct btrfs_root *tree_root,
2108 				      struct btrfs_path *path, u64 objectid,
2109 				      const char *name)
2110 {
2111 	struct btrfs_fs_info *fs_info = tree_root->fs_info;
2112 	struct btrfs_root *root;
2113 	u64 max_global_id = 0;
2114 	int ret;
2115 	struct btrfs_key key = {
2116 		.objectid = objectid,
2117 		.type = BTRFS_ROOT_ITEM_KEY,
2118 		.offset = 0,
2119 	};
2120 	bool found = false;
2121 
2122 	/* If we have IGNOREDATACSUMS skip loading these roots. */
2123 	if (objectid == BTRFS_CSUM_TREE_OBJECTID &&
2124 	    btrfs_test_opt(fs_info, IGNOREDATACSUMS)) {
2125 		set_bit(BTRFS_FS_STATE_NO_DATA_CSUMS, &fs_info->fs_state);
2126 		return 0;
2127 	}
2128 
2129 	while (1) {
2130 		ret = btrfs_search_slot(NULL, tree_root, &key, path, 0, 0);
2131 		if (ret < 0)
2132 			break;
2133 
2134 		if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
2135 			ret = btrfs_next_leaf(tree_root, path);
2136 			if (ret) {
2137 				if (ret > 0)
2138 					ret = 0;
2139 				break;
2140 			}
2141 		}
2142 		ret = 0;
2143 
2144 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2145 		if (key.objectid != objectid)
2146 			break;
2147 		btrfs_release_path(path);
2148 
2149 		/*
2150 		 * Just worry about this for extent tree, it'll be the same for
2151 		 * everybody.
2152 		 */
2153 		if (objectid == BTRFS_EXTENT_TREE_OBJECTID)
2154 			max_global_id = max(max_global_id, key.offset);
2155 
2156 		found = true;
2157 		root = read_tree_root_path(tree_root, path, &key);
2158 		if (IS_ERR(root)) {
2159 			ret = PTR_ERR(root);
2160 			break;
2161 		}
2162 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2163 		ret = btrfs_global_root_insert(root);
2164 		if (ret) {
2165 			btrfs_put_root(root);
2166 			break;
2167 		}
2168 		key.offset++;
2169 	}
2170 	btrfs_release_path(path);
2171 
2172 	if (objectid == BTRFS_EXTENT_TREE_OBJECTID)
2173 		fs_info->nr_global_roots = max_global_id + 1;
2174 
2175 	if (!found || ret) {
2176 		if (objectid == BTRFS_CSUM_TREE_OBJECTID)
2177 			set_bit(BTRFS_FS_STATE_NO_DATA_CSUMS, &fs_info->fs_state);
2178 
2179 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS))
2180 			ret = ret ? ret : -ENOENT;
2181 		else
2182 			ret = 0;
2183 		btrfs_err(fs_info, "failed to load root %s", name);
2184 	}
2185 	return ret;
2186 }
2187 
load_global_roots(struct btrfs_root * tree_root)2188 static int load_global_roots(struct btrfs_root *tree_root)
2189 {
2190 	BTRFS_PATH_AUTO_FREE(path);
2191 	int ret;
2192 
2193 	path = btrfs_alloc_path();
2194 	if (!path)
2195 		return -ENOMEM;
2196 
2197 	ret = load_global_roots_objectid(tree_root, path,
2198 					 BTRFS_EXTENT_TREE_OBJECTID, "extent");
2199 	if (ret)
2200 		return ret;
2201 	ret = load_global_roots_objectid(tree_root, path,
2202 					 BTRFS_CSUM_TREE_OBJECTID, "csum");
2203 	if (ret)
2204 		return ret;
2205 	if (!btrfs_fs_compat_ro(tree_root->fs_info, FREE_SPACE_TREE))
2206 		return ret;
2207 	ret = load_global_roots_objectid(tree_root, path,
2208 					 BTRFS_FREE_SPACE_TREE_OBJECTID,
2209 					 "free space");
2210 
2211 	return ret;
2212 }
2213 
btrfs_read_roots(struct btrfs_fs_info * fs_info)2214 static int btrfs_read_roots(struct btrfs_fs_info *fs_info)
2215 {
2216 	struct btrfs_root *tree_root = fs_info->tree_root;
2217 	struct btrfs_root *root;
2218 	struct btrfs_key location;
2219 	int ret;
2220 
2221 	ASSERT(fs_info->tree_root);
2222 
2223 	ret = load_global_roots(tree_root);
2224 	if (ret)
2225 		return ret;
2226 
2227 	location.type = BTRFS_ROOT_ITEM_KEY;
2228 	location.offset = 0;
2229 
2230 	if (btrfs_fs_compat_ro(fs_info, BLOCK_GROUP_TREE)) {
2231 		location.objectid = BTRFS_BLOCK_GROUP_TREE_OBJECTID;
2232 		root = btrfs_read_tree_root(tree_root, &location);
2233 		if (IS_ERR(root)) {
2234 			if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2235 				ret = PTR_ERR(root);
2236 				goto out;
2237 			}
2238 		} else {
2239 			set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2240 			fs_info->block_group_root = root;
2241 		}
2242 	}
2243 
2244 	location.objectid = BTRFS_DEV_TREE_OBJECTID;
2245 	root = btrfs_read_tree_root(tree_root, &location);
2246 	if (IS_ERR(root)) {
2247 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2248 			ret = PTR_ERR(root);
2249 			goto out;
2250 		}
2251 	} else {
2252 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2253 		fs_info->dev_root = root;
2254 	}
2255 	/* Initialize fs_info for all devices in any case */
2256 	ret = btrfs_init_devices_late(fs_info);
2257 	if (ret)
2258 		goto out;
2259 
2260 	/*
2261 	 * This tree can share blocks with some other fs tree during relocation
2262 	 * and we need a proper setup by btrfs_get_fs_root
2263 	 */
2264 	root = btrfs_get_fs_root(tree_root->fs_info,
2265 				 BTRFS_DATA_RELOC_TREE_OBJECTID, true);
2266 	if (IS_ERR(root)) {
2267 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2268 			ret = PTR_ERR(root);
2269 			goto out;
2270 		}
2271 	} else {
2272 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2273 		fs_info->data_reloc_root = root;
2274 	}
2275 
2276 	location.objectid = BTRFS_QUOTA_TREE_OBJECTID;
2277 	root = btrfs_read_tree_root(tree_root, &location);
2278 	if (!IS_ERR(root)) {
2279 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2280 		fs_info->quota_root = root;
2281 	}
2282 
2283 	location.objectid = BTRFS_UUID_TREE_OBJECTID;
2284 	root = btrfs_read_tree_root(tree_root, &location);
2285 	if (IS_ERR(root)) {
2286 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2287 			ret = PTR_ERR(root);
2288 			if (ret != -ENOENT)
2289 				goto out;
2290 		}
2291 	} else {
2292 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2293 		fs_info->uuid_root = root;
2294 	}
2295 
2296 	if (btrfs_fs_incompat(fs_info, RAID_STRIPE_TREE)) {
2297 		location.objectid = BTRFS_RAID_STRIPE_TREE_OBJECTID;
2298 		root = btrfs_read_tree_root(tree_root, &location);
2299 		if (IS_ERR(root)) {
2300 			if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2301 				ret = PTR_ERR(root);
2302 				goto out;
2303 			}
2304 		} else {
2305 			set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2306 			fs_info->stripe_root = root;
2307 		}
2308 	}
2309 
2310 	return 0;
2311 out:
2312 	btrfs_warn(fs_info, "failed to read root (objectid=%llu): %d",
2313 		   location.objectid, ret);
2314 	return ret;
2315 }
2316 
validate_sys_chunk_array(const struct btrfs_fs_info * fs_info,const struct btrfs_super_block * sb)2317 static int validate_sys_chunk_array(const struct btrfs_fs_info *fs_info,
2318 				    const struct btrfs_super_block *sb)
2319 {
2320 	unsigned int cur = 0; /* Offset inside the sys chunk array */
2321 	/*
2322 	 * At sb read time, fs_info is not fully initialized. Thus we have
2323 	 * to use super block sectorsize, which should have been validated.
2324 	 */
2325 	const u32 sectorsize = btrfs_super_sectorsize(sb);
2326 	u32 sys_array_size = btrfs_super_sys_array_size(sb);
2327 
2328 	if (unlikely(sys_array_size > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE)) {
2329 		btrfs_err(fs_info, "system chunk array too big %u > %u",
2330 			  sys_array_size, BTRFS_SYSTEM_CHUNK_ARRAY_SIZE);
2331 		return -EUCLEAN;
2332 	}
2333 
2334 	while (cur < sys_array_size) {
2335 		struct btrfs_disk_key *disk_key;
2336 		struct btrfs_chunk *chunk;
2337 		struct btrfs_key key;
2338 		u64 type;
2339 		u16 num_stripes;
2340 		u32 len;
2341 		int ret;
2342 
2343 		disk_key = (struct btrfs_disk_key *)(sb->sys_chunk_array + cur);
2344 		len = sizeof(*disk_key);
2345 
2346 		if (unlikely(cur + len > sys_array_size))
2347 			goto short_read;
2348 		cur += len;
2349 
2350 		btrfs_disk_key_to_cpu(&key, disk_key);
2351 		if (unlikely(key.type != BTRFS_CHUNK_ITEM_KEY)) {
2352 			btrfs_err(fs_info,
2353 			    "unexpected item type %u in sys_array at offset %u",
2354 				  key.type, cur);
2355 			return -EUCLEAN;
2356 		}
2357 		chunk = (struct btrfs_chunk *)(sb->sys_chunk_array + cur);
2358 		num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2359 		if (unlikely(cur + btrfs_chunk_item_size(num_stripes) > sys_array_size))
2360 			goto short_read;
2361 		type = btrfs_stack_chunk_type(chunk);
2362 		if (unlikely(!(type & BTRFS_BLOCK_GROUP_SYSTEM))) {
2363 			btrfs_err(fs_info,
2364 			"invalid chunk type %llu in sys_array at offset %u",
2365 				  type, cur);
2366 			return -EUCLEAN;
2367 		}
2368 		ret = btrfs_check_chunk_valid(fs_info, NULL, chunk, key.offset,
2369 					      sectorsize);
2370 		if (ret < 0)
2371 			return ret;
2372 		cur += btrfs_chunk_item_size(num_stripes);
2373 	}
2374 	return 0;
2375 short_read:
2376 	btrfs_err(fs_info,
2377 	"super block sys chunk array short read, cur=%u sys_array_size=%u",
2378 		  cur, sys_array_size);
2379 	return -EUCLEAN;
2380 }
2381 
2382 /*
2383  * Real super block validation
2384  * NOTE: super csum type and incompat features will not be checked here.
2385  *
2386  * @sb:		super block to check
2387  * @mirror_num:	the super block number to check its bytenr:
2388  * 		0	the primary (1st) sb
2389  * 		1, 2	2nd and 3rd backup copy
2390  * 	       -1	skip bytenr check
2391  */
btrfs_validate_super(const struct btrfs_fs_info * fs_info,const struct btrfs_super_block * sb,int mirror_num)2392 int btrfs_validate_super(const struct btrfs_fs_info *fs_info,
2393 			 const struct btrfs_super_block *sb, int mirror_num)
2394 {
2395 	u64 nodesize = btrfs_super_nodesize(sb);
2396 	u64 sectorsize = btrfs_super_sectorsize(sb);
2397 	int ret = 0;
2398 	const bool ignore_flags = btrfs_test_opt(fs_info, IGNORESUPERFLAGS);
2399 
2400 	if (btrfs_super_magic(sb) != BTRFS_MAGIC) {
2401 		btrfs_err(fs_info, "no valid FS found");
2402 		ret = -EINVAL;
2403 	}
2404 	if ((btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP)) {
2405 		if (!ignore_flags) {
2406 			btrfs_err(fs_info,
2407 			"unrecognized or unsupported super flag 0x%llx",
2408 				  btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP);
2409 			ret = -EINVAL;
2410 		} else {
2411 			btrfs_info(fs_info,
2412 			"unrecognized or unsupported super flags: 0x%llx, ignored",
2413 				   btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP);
2414 		}
2415 	}
2416 	if (btrfs_super_root_level(sb) >= BTRFS_MAX_LEVEL) {
2417 		btrfs_err(fs_info, "tree_root level too big: %d >= %d",
2418 				btrfs_super_root_level(sb), BTRFS_MAX_LEVEL);
2419 		ret = -EINVAL;
2420 	}
2421 	if (btrfs_super_chunk_root_level(sb) >= BTRFS_MAX_LEVEL) {
2422 		btrfs_err(fs_info, "chunk_root level too big: %d >= %d",
2423 				btrfs_super_chunk_root_level(sb), BTRFS_MAX_LEVEL);
2424 		ret = -EINVAL;
2425 	}
2426 	if (btrfs_super_log_root_level(sb) >= BTRFS_MAX_LEVEL) {
2427 		btrfs_err(fs_info, "log_root level too big: %d >= %d",
2428 				btrfs_super_log_root_level(sb), BTRFS_MAX_LEVEL);
2429 		ret = -EINVAL;
2430 	}
2431 
2432 	/*
2433 	 * Check sectorsize and nodesize first, other check will need it.
2434 	 * Check all possible sectorsize(4K, 8K, 16K, 32K, 64K) here.
2435 	 */
2436 	if (!is_power_of_2(sectorsize) || sectorsize < BTRFS_MIN_BLOCKSIZE ||
2437 	    sectorsize > BTRFS_MAX_METADATA_BLOCKSIZE) {
2438 		btrfs_err(fs_info, "invalid sectorsize %llu", sectorsize);
2439 		ret = -EINVAL;
2440 	}
2441 
2442 	if (!btrfs_supported_blocksize(sectorsize)) {
2443 		btrfs_err(fs_info,
2444 			"sectorsize %llu not yet supported for page size %lu",
2445 			sectorsize, PAGE_SIZE);
2446 		ret = -EINVAL;
2447 	}
2448 
2449 	if (!is_power_of_2(nodesize) || nodesize < sectorsize ||
2450 	    nodesize > BTRFS_MAX_METADATA_BLOCKSIZE) {
2451 		btrfs_err(fs_info, "invalid nodesize %llu", nodesize);
2452 		ret = -EINVAL;
2453 	}
2454 	if (nodesize != le32_to_cpu(sb->__unused_leafsize)) {
2455 		btrfs_err(fs_info, "invalid leafsize %u, should be %llu",
2456 			  le32_to_cpu(sb->__unused_leafsize), nodesize);
2457 		ret = -EINVAL;
2458 	}
2459 
2460 	/* Root alignment check */
2461 	if (!IS_ALIGNED(btrfs_super_root(sb), sectorsize)) {
2462 		btrfs_warn(fs_info, "tree_root block unaligned: %llu",
2463 			   btrfs_super_root(sb));
2464 		ret = -EINVAL;
2465 	}
2466 	if (!IS_ALIGNED(btrfs_super_chunk_root(sb), sectorsize)) {
2467 		btrfs_warn(fs_info, "chunk_root block unaligned: %llu",
2468 			   btrfs_super_chunk_root(sb));
2469 		ret = -EINVAL;
2470 	}
2471 	if (!IS_ALIGNED(btrfs_super_log_root(sb), sectorsize)) {
2472 		btrfs_warn(fs_info, "log_root block unaligned: %llu",
2473 			   btrfs_super_log_root(sb));
2474 		ret = -EINVAL;
2475 	}
2476 
2477 	if (!fs_info->fs_devices->temp_fsid &&
2478 	    memcmp(fs_info->fs_devices->fsid, sb->fsid, BTRFS_FSID_SIZE) != 0) {
2479 		btrfs_err(fs_info,
2480 		"superblock fsid doesn't match fsid of fs_devices: %pU != %pU",
2481 			  sb->fsid, fs_info->fs_devices->fsid);
2482 		ret = -EINVAL;
2483 	}
2484 
2485 	if (memcmp(fs_info->fs_devices->metadata_uuid, btrfs_sb_fsid_ptr(sb),
2486 		   BTRFS_FSID_SIZE) != 0) {
2487 		btrfs_err(fs_info,
2488 "superblock metadata_uuid doesn't match metadata uuid of fs_devices: %pU != %pU",
2489 			  btrfs_sb_fsid_ptr(sb), fs_info->fs_devices->metadata_uuid);
2490 		ret = -EINVAL;
2491 	}
2492 
2493 	if (memcmp(fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid,
2494 		   BTRFS_FSID_SIZE) != 0) {
2495 		btrfs_err(fs_info,
2496 			"dev_item UUID does not match metadata fsid: %pU != %pU",
2497 			fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid);
2498 		ret = -EINVAL;
2499 	}
2500 
2501 	/*
2502 	 * Artificial requirement for block-group-tree to force newer features
2503 	 * (free-space-tree, no-holes) so the test matrix is smaller.
2504 	 */
2505 	if (btrfs_fs_compat_ro(fs_info, BLOCK_GROUP_TREE) &&
2506 	    (!btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID) ||
2507 	     !btrfs_fs_incompat(fs_info, NO_HOLES))) {
2508 		btrfs_err(fs_info,
2509 		"block-group-tree feature requires free-space-tree and no-holes");
2510 		ret = -EINVAL;
2511 	}
2512 
2513 	/*
2514 	 * Hint to catch really bogus numbers, bitflips or so, more exact checks are
2515 	 * done later
2516 	 */
2517 	if (btrfs_super_bytes_used(sb) < 6 * btrfs_super_nodesize(sb)) {
2518 		btrfs_err(fs_info, "bytes_used is too small %llu",
2519 			  btrfs_super_bytes_used(sb));
2520 		ret = -EINVAL;
2521 	}
2522 	if (!is_power_of_2(btrfs_super_stripesize(sb))) {
2523 		btrfs_err(fs_info, "invalid stripesize %u",
2524 			  btrfs_super_stripesize(sb));
2525 		ret = -EINVAL;
2526 	}
2527 	if (btrfs_super_num_devices(sb) > (1UL << 31))
2528 		btrfs_warn(fs_info, "suspicious number of devices: %llu",
2529 			   btrfs_super_num_devices(sb));
2530 	if (btrfs_super_num_devices(sb) == 0) {
2531 		btrfs_err(fs_info, "number of devices is 0");
2532 		ret = -EINVAL;
2533 	}
2534 
2535 	if (mirror_num >= 0 &&
2536 	    btrfs_super_bytenr(sb) != btrfs_sb_offset(mirror_num)) {
2537 		btrfs_err(fs_info, "super offset mismatch %llu != %u",
2538 			  btrfs_super_bytenr(sb), BTRFS_SUPER_INFO_OFFSET);
2539 		ret = -EINVAL;
2540 	}
2541 
2542 	if (ret)
2543 		return ret;
2544 
2545 	ret = validate_sys_chunk_array(fs_info, sb);
2546 
2547 	/*
2548 	 * Obvious sys_chunk_array corruptions, it must hold at least one key
2549 	 * and one chunk
2550 	 */
2551 	if (btrfs_super_sys_array_size(sb) > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
2552 		btrfs_err(fs_info, "system chunk array too big %u > %u",
2553 			  btrfs_super_sys_array_size(sb),
2554 			  BTRFS_SYSTEM_CHUNK_ARRAY_SIZE);
2555 		ret = -EINVAL;
2556 	}
2557 	if (btrfs_super_sys_array_size(sb) < sizeof(struct btrfs_disk_key)
2558 			+ sizeof(struct btrfs_chunk)) {
2559 		btrfs_err(fs_info, "system chunk array too small %u < %zu",
2560 			  btrfs_super_sys_array_size(sb),
2561 			  sizeof(struct btrfs_disk_key)
2562 			  + sizeof(struct btrfs_chunk));
2563 		ret = -EINVAL;
2564 	}
2565 
2566 	/*
2567 	 * The generation is a global counter, we'll trust it more than the others
2568 	 * but it's still possible that it's the one that's wrong.
2569 	 */
2570 	if (btrfs_super_generation(sb) < btrfs_super_chunk_root_generation(sb))
2571 		btrfs_warn(fs_info,
2572 			"suspicious: generation < chunk_root_generation: %llu < %llu",
2573 			btrfs_super_generation(sb),
2574 			btrfs_super_chunk_root_generation(sb));
2575 	if (btrfs_super_generation(sb) < btrfs_super_cache_generation(sb)
2576 	    && btrfs_super_cache_generation(sb) != (u64)-1)
2577 		btrfs_warn(fs_info,
2578 			"suspicious: generation < cache_generation: %llu < %llu",
2579 			btrfs_super_generation(sb),
2580 			btrfs_super_cache_generation(sb));
2581 
2582 	return ret;
2583 }
2584 
2585 /*
2586  * Validation of super block at mount time.
2587  * Some checks already done early at mount time, like csum type and incompat
2588  * flags will be skipped.
2589  */
btrfs_validate_mount_super(struct btrfs_fs_info * fs_info)2590 static int btrfs_validate_mount_super(struct btrfs_fs_info *fs_info)
2591 {
2592 	return btrfs_validate_super(fs_info, fs_info->super_copy, 0);
2593 }
2594 
2595 /*
2596  * Validation of super block at write time.
2597  * Some checks like bytenr check will be skipped as their values will be
2598  * overwritten soon.
2599  * Extra checks like csum type and incompat flags will be done here.
2600  */
btrfs_validate_write_super(struct btrfs_fs_info * fs_info,struct btrfs_super_block * sb)2601 static int btrfs_validate_write_super(struct btrfs_fs_info *fs_info,
2602 				      struct btrfs_super_block *sb)
2603 {
2604 	int ret;
2605 
2606 	ret = btrfs_validate_super(fs_info, sb, -1);
2607 	if (ret < 0)
2608 		goto out;
2609 	if (unlikely(!btrfs_supported_super_csum(btrfs_super_csum_type(sb)))) {
2610 		ret = -EUCLEAN;
2611 		btrfs_err(fs_info, "invalid csum type, has %u want %u",
2612 			  btrfs_super_csum_type(sb), BTRFS_CSUM_TYPE_CRC32);
2613 		goto out;
2614 	}
2615 	if (unlikely(btrfs_super_incompat_flags(sb) & ~BTRFS_FEATURE_INCOMPAT_SUPP)) {
2616 		ret = -EUCLEAN;
2617 		btrfs_err(fs_info,
2618 		"invalid incompat flags, has 0x%llx valid mask 0x%llx",
2619 			  btrfs_super_incompat_flags(sb),
2620 			  (unsigned long long)BTRFS_FEATURE_INCOMPAT_SUPP);
2621 		goto out;
2622 	}
2623 out:
2624 	if (ret < 0)
2625 		btrfs_err(fs_info,
2626 		"super block corruption detected before writing it to disk");
2627 	return ret;
2628 }
2629 
load_super_root(struct btrfs_root * root,u64 bytenr,u64 gen,int level)2630 static int load_super_root(struct btrfs_root *root, u64 bytenr, u64 gen, int level)
2631 {
2632 	struct btrfs_tree_parent_check check = {
2633 		.level = level,
2634 		.transid = gen,
2635 		.owner_root = btrfs_root_id(root)
2636 	};
2637 	int ret = 0;
2638 
2639 	root->node = read_tree_block(root->fs_info, bytenr, &check);
2640 	if (IS_ERR(root->node)) {
2641 		ret = PTR_ERR(root->node);
2642 		root->node = NULL;
2643 		return ret;
2644 	}
2645 	if (unlikely(!extent_buffer_uptodate(root->node))) {
2646 		free_extent_buffer(root->node);
2647 		root->node = NULL;
2648 		return -EIO;
2649 	}
2650 
2651 	btrfs_set_root_node(&root->root_item, root->node);
2652 	root->commit_root = btrfs_root_node(root);
2653 	btrfs_set_root_refs(&root->root_item, 1);
2654 	return ret;
2655 }
2656 
load_important_roots(struct btrfs_fs_info * fs_info)2657 static int load_important_roots(struct btrfs_fs_info *fs_info)
2658 {
2659 	struct btrfs_super_block *sb = fs_info->super_copy;
2660 	u64 gen, bytenr;
2661 	int level, ret;
2662 
2663 	bytenr = btrfs_super_root(sb);
2664 	gen = btrfs_super_generation(sb);
2665 	level = btrfs_super_root_level(sb);
2666 	ret = load_super_root(fs_info->tree_root, bytenr, gen, level);
2667 	if (ret) {
2668 		btrfs_warn(fs_info, "couldn't read tree root");
2669 		return ret;
2670 	}
2671 	return 0;
2672 }
2673 
init_tree_roots(struct btrfs_fs_info * fs_info)2674 static int __cold init_tree_roots(struct btrfs_fs_info *fs_info)
2675 {
2676 	int backup_index = find_newest_super_backup(fs_info);
2677 	struct btrfs_super_block *sb = fs_info->super_copy;
2678 	struct btrfs_root *tree_root = fs_info->tree_root;
2679 	bool handle_error = false;
2680 	int ret = 0;
2681 	int i;
2682 
2683 	for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
2684 		if (handle_error) {
2685 			if (!IS_ERR(tree_root->node))
2686 				free_extent_buffer(tree_root->node);
2687 			tree_root->node = NULL;
2688 
2689 			if (!btrfs_test_opt(fs_info, USEBACKUPROOT))
2690 				break;
2691 
2692 			free_root_pointers(fs_info, 0);
2693 
2694 			/*
2695 			 * Don't use the log in recovery mode, it won't be
2696 			 * valid
2697 			 */
2698 			btrfs_set_super_log_root(sb, 0);
2699 
2700 			btrfs_warn(fs_info, "try to load backup roots slot %d", i);
2701 			ret = read_backup_root(fs_info, i);
2702 			backup_index = ret;
2703 			if (ret < 0)
2704 				return ret;
2705 		}
2706 
2707 		ret = load_important_roots(fs_info);
2708 		if (ret) {
2709 			handle_error = true;
2710 			continue;
2711 		}
2712 
2713 		/*
2714 		 * No need to hold btrfs_root::objectid_mutex since the fs
2715 		 * hasn't been fully initialised and we are the only user
2716 		 */
2717 		ret = btrfs_init_root_free_objectid(tree_root);
2718 		if (ret < 0) {
2719 			handle_error = true;
2720 			continue;
2721 		}
2722 
2723 		ASSERT(tree_root->free_objectid <= BTRFS_LAST_FREE_OBJECTID);
2724 
2725 		ret = btrfs_read_roots(fs_info);
2726 		if (ret < 0) {
2727 			handle_error = true;
2728 			continue;
2729 		}
2730 
2731 		/* All successful */
2732 		fs_info->generation = btrfs_header_generation(tree_root->node);
2733 		btrfs_set_last_trans_committed(fs_info, fs_info->generation);
2734 		fs_info->last_reloc_trans = 0;
2735 
2736 		/* Always begin writing backup roots after the one being used */
2737 		if (backup_index < 0) {
2738 			fs_info->backup_root_index = 0;
2739 		} else {
2740 			fs_info->backup_root_index = backup_index + 1;
2741 			fs_info->backup_root_index %= BTRFS_NUM_BACKUP_ROOTS;
2742 		}
2743 		break;
2744 	}
2745 
2746 	return ret;
2747 }
2748 
2749 /*
2750  * Lockdep gets confused between our buffer_tree which requires IRQ locking because
2751  * we modify marks in the IRQ context, and our delayed inode xarray which doesn't
2752  * have these requirements. Use a class key so lockdep doesn't get them mixed up.
2753  */
2754 static struct lock_class_key buffer_xa_class;
2755 
btrfs_init_fs_info(struct btrfs_fs_info * fs_info)2756 void btrfs_init_fs_info(struct btrfs_fs_info *fs_info)
2757 {
2758 	INIT_RADIX_TREE(&fs_info->fs_roots_radix, GFP_ATOMIC);
2759 
2760 	/* Use the same flags as mapping->i_pages. */
2761 	xa_init_flags(&fs_info->buffer_tree, XA_FLAGS_LOCK_IRQ | XA_FLAGS_ACCOUNT);
2762 	lockdep_set_class(&fs_info->buffer_tree.xa_lock, &buffer_xa_class);
2763 
2764 	INIT_LIST_HEAD(&fs_info->trans_list);
2765 	INIT_LIST_HEAD(&fs_info->dead_roots);
2766 	INIT_LIST_HEAD(&fs_info->delayed_iputs);
2767 	INIT_LIST_HEAD(&fs_info->delalloc_roots);
2768 	INIT_LIST_HEAD(&fs_info->caching_block_groups);
2769 	spin_lock_init(&fs_info->delalloc_root_lock);
2770 	spin_lock_init(&fs_info->trans_lock);
2771 	spin_lock_init(&fs_info->fs_roots_radix_lock);
2772 	spin_lock_init(&fs_info->delayed_iput_lock);
2773 	spin_lock_init(&fs_info->defrag_inodes_lock);
2774 	spin_lock_init(&fs_info->super_lock);
2775 	spin_lock_init(&fs_info->unused_bgs_lock);
2776 	spin_lock_init(&fs_info->treelog_bg_lock);
2777 	spin_lock_init(&fs_info->zone_active_bgs_lock);
2778 	spin_lock_init(&fs_info->relocation_bg_lock);
2779 	rwlock_init(&fs_info->tree_mod_log_lock);
2780 	rwlock_init(&fs_info->global_root_lock);
2781 	mutex_init(&fs_info->unused_bg_unpin_mutex);
2782 	mutex_init(&fs_info->reclaim_bgs_lock);
2783 	mutex_init(&fs_info->reloc_mutex);
2784 	mutex_init(&fs_info->delalloc_root_mutex);
2785 	mutex_init(&fs_info->zoned_meta_io_lock);
2786 	mutex_init(&fs_info->zoned_data_reloc_io_lock);
2787 	seqlock_init(&fs_info->profiles_lock);
2788 
2789 	btrfs_lockdep_init_map(fs_info, btrfs_trans_num_writers);
2790 	btrfs_lockdep_init_map(fs_info, btrfs_trans_num_extwriters);
2791 	btrfs_lockdep_init_map(fs_info, btrfs_trans_pending_ordered);
2792 	btrfs_lockdep_init_map(fs_info, btrfs_ordered_extent);
2793 	btrfs_state_lockdep_init_map(fs_info, btrfs_trans_commit_prep,
2794 				     BTRFS_LOCKDEP_TRANS_COMMIT_PREP);
2795 	btrfs_state_lockdep_init_map(fs_info, btrfs_trans_unblocked,
2796 				     BTRFS_LOCKDEP_TRANS_UNBLOCKED);
2797 	btrfs_state_lockdep_init_map(fs_info, btrfs_trans_super_committed,
2798 				     BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
2799 	btrfs_state_lockdep_init_map(fs_info, btrfs_trans_completed,
2800 				     BTRFS_LOCKDEP_TRANS_COMPLETED);
2801 
2802 	INIT_LIST_HEAD(&fs_info->dirty_cowonly_roots);
2803 	INIT_LIST_HEAD(&fs_info->space_info);
2804 	INIT_LIST_HEAD(&fs_info->tree_mod_seq_list);
2805 	INIT_LIST_HEAD(&fs_info->unused_bgs);
2806 	INIT_LIST_HEAD(&fs_info->reclaim_bgs);
2807 	INIT_LIST_HEAD(&fs_info->zone_active_bgs);
2808 #ifdef CONFIG_BTRFS_DEBUG
2809 	INIT_LIST_HEAD(&fs_info->allocated_roots);
2810 	INIT_LIST_HEAD(&fs_info->allocated_ebs);
2811 	spin_lock_init(&fs_info->eb_leak_lock);
2812 #endif
2813 	fs_info->mapping_tree = RB_ROOT_CACHED;
2814 	rwlock_init(&fs_info->mapping_tree_lock);
2815 	btrfs_init_block_rsv(&fs_info->global_block_rsv,
2816 			     BTRFS_BLOCK_RSV_GLOBAL);
2817 	btrfs_init_block_rsv(&fs_info->trans_block_rsv, BTRFS_BLOCK_RSV_TRANS);
2818 	btrfs_init_block_rsv(&fs_info->chunk_block_rsv, BTRFS_BLOCK_RSV_CHUNK);
2819 	btrfs_init_block_rsv(&fs_info->treelog_rsv, BTRFS_BLOCK_RSV_TREELOG);
2820 	btrfs_init_block_rsv(&fs_info->empty_block_rsv, BTRFS_BLOCK_RSV_EMPTY);
2821 	btrfs_init_block_rsv(&fs_info->delayed_block_rsv,
2822 			     BTRFS_BLOCK_RSV_DELOPS);
2823 	btrfs_init_block_rsv(&fs_info->delayed_refs_rsv,
2824 			     BTRFS_BLOCK_RSV_DELREFS);
2825 
2826 	atomic_set(&fs_info->async_delalloc_pages, 0);
2827 	atomic_set(&fs_info->defrag_running, 0);
2828 	atomic_set(&fs_info->nr_delayed_iputs, 0);
2829 	atomic64_set(&fs_info->tree_mod_seq, 0);
2830 	fs_info->global_root_tree = RB_ROOT;
2831 	fs_info->max_inline = BTRFS_DEFAULT_MAX_INLINE;
2832 	fs_info->metadata_ratio = 0;
2833 	fs_info->defrag_inodes = RB_ROOT;
2834 	atomic64_set(&fs_info->free_chunk_space, 0);
2835 	fs_info->tree_mod_log = RB_ROOT;
2836 	fs_info->commit_interval = BTRFS_DEFAULT_COMMIT_INTERVAL;
2837 	btrfs_init_ref_verify(fs_info);
2838 
2839 	fs_info->thread_pool_size = min_t(unsigned long,
2840 					  num_online_cpus() + 2, 8);
2841 
2842 	INIT_LIST_HEAD(&fs_info->ordered_roots);
2843 	spin_lock_init(&fs_info->ordered_root_lock);
2844 
2845 	btrfs_init_scrub(fs_info);
2846 	btrfs_init_balance(fs_info);
2847 	btrfs_init_async_reclaim_work(fs_info);
2848 	btrfs_init_extent_map_shrinker_work(fs_info);
2849 
2850 	rwlock_init(&fs_info->block_group_cache_lock);
2851 	fs_info->block_group_cache_tree = RB_ROOT_CACHED;
2852 
2853 	btrfs_extent_io_tree_init(fs_info, &fs_info->excluded_extents,
2854 				  IO_TREE_FS_EXCLUDED_EXTENTS);
2855 
2856 	mutex_init(&fs_info->ordered_operations_mutex);
2857 	mutex_init(&fs_info->tree_log_mutex);
2858 	mutex_init(&fs_info->chunk_mutex);
2859 	mutex_init(&fs_info->transaction_kthread_mutex);
2860 	mutex_init(&fs_info->cleaner_mutex);
2861 	mutex_init(&fs_info->ro_block_group_mutex);
2862 	init_rwsem(&fs_info->commit_root_sem);
2863 	init_rwsem(&fs_info->cleanup_work_sem);
2864 	init_rwsem(&fs_info->subvol_sem);
2865 	sema_init(&fs_info->uuid_tree_rescan_sem, 1);
2866 
2867 	btrfs_init_dev_replace_locks(fs_info);
2868 	btrfs_init_qgroup(fs_info);
2869 	btrfs_discard_init(fs_info);
2870 
2871 	btrfs_init_free_cluster(&fs_info->meta_alloc_cluster);
2872 	btrfs_init_free_cluster(&fs_info->data_alloc_cluster);
2873 
2874 	init_waitqueue_head(&fs_info->transaction_throttle);
2875 	init_waitqueue_head(&fs_info->transaction_wait);
2876 	init_waitqueue_head(&fs_info->transaction_blocked_wait);
2877 	init_waitqueue_head(&fs_info->async_submit_wait);
2878 	init_waitqueue_head(&fs_info->delayed_iputs_wait);
2879 
2880 	/* Usable values until the real ones are cached from the superblock */
2881 	fs_info->nodesize = 4096;
2882 	fs_info->sectorsize = 4096;
2883 	fs_info->sectorsize_bits = ilog2(4096);
2884 	fs_info->stripesize = 4096;
2885 
2886 	/* Default compress algorithm when user does -o compress */
2887 	fs_info->compress_type = BTRFS_COMPRESS_ZLIB;
2888 
2889 	fs_info->max_extent_size = BTRFS_MAX_EXTENT_SIZE;
2890 
2891 	spin_lock_init(&fs_info->swapfile_pins_lock);
2892 	fs_info->swapfile_pins = RB_ROOT;
2893 
2894 	fs_info->bg_reclaim_threshold = BTRFS_DEFAULT_RECLAIM_THRESH;
2895 	INIT_WORK(&fs_info->reclaim_bgs_work, btrfs_reclaim_bgs_work);
2896 }
2897 
init_mount_fs_info(struct btrfs_fs_info * fs_info,struct super_block * sb)2898 static int init_mount_fs_info(struct btrfs_fs_info *fs_info, struct super_block *sb)
2899 {
2900 	int ret;
2901 
2902 	fs_info->sb = sb;
2903 	/* Temporary fixed values for block size until we read the superblock. */
2904 	sb->s_blocksize = BTRFS_BDEV_BLOCKSIZE;
2905 	sb->s_blocksize_bits = blksize_bits(BTRFS_BDEV_BLOCKSIZE);
2906 
2907 	ret = percpu_counter_init(&fs_info->ordered_bytes, 0, GFP_KERNEL);
2908 	if (ret)
2909 		return ret;
2910 
2911 	ret = percpu_counter_init(&fs_info->evictable_extent_maps, 0, GFP_KERNEL);
2912 	if (ret)
2913 		return ret;
2914 
2915 	ret = percpu_counter_init(&fs_info->dirty_metadata_bytes, 0, GFP_KERNEL);
2916 	if (ret)
2917 		return ret;
2918 
2919 	ret = percpu_counter_init(&fs_info->stats_read_blocks, 0, GFP_KERNEL);
2920 	if (ret)
2921 		return ret;
2922 
2923 	fs_info->dirty_metadata_batch = PAGE_SIZE *
2924 					(1 + ilog2(nr_cpu_ids));
2925 
2926 	ret = percpu_counter_init(&fs_info->delalloc_bytes, 0, GFP_KERNEL);
2927 	if (ret)
2928 		return ret;
2929 
2930 	ret = percpu_counter_init(&fs_info->dev_replace.bio_counter, 0,
2931 			GFP_KERNEL);
2932 	if (ret)
2933 		return ret;
2934 
2935 	fs_info->delayed_root = kmalloc(sizeof(struct btrfs_delayed_root),
2936 					GFP_KERNEL);
2937 	if (!fs_info->delayed_root)
2938 		return -ENOMEM;
2939 	btrfs_init_delayed_root(fs_info->delayed_root);
2940 
2941 	if (sb_rdonly(sb))
2942 		set_bit(BTRFS_FS_STATE_RO, &fs_info->fs_state);
2943 	if (btrfs_test_opt(fs_info, IGNOREMETACSUMS))
2944 		set_bit(BTRFS_FS_STATE_SKIP_META_CSUMS, &fs_info->fs_state);
2945 
2946 	return btrfs_alloc_stripe_hash_table(fs_info);
2947 }
2948 
btrfs_uuid_rescan_kthread(void * data)2949 static int btrfs_uuid_rescan_kthread(void *data)
2950 {
2951 	struct btrfs_fs_info *fs_info = data;
2952 	int ret;
2953 
2954 	/*
2955 	 * 1st step is to iterate through the existing UUID tree and
2956 	 * to delete all entries that contain outdated data.
2957 	 * 2nd step is to add all missing entries to the UUID tree.
2958 	 */
2959 	ret = btrfs_uuid_tree_iterate(fs_info);
2960 	if (ret < 0) {
2961 		if (ret != -EINTR)
2962 			btrfs_warn(fs_info, "iterating uuid_tree failed %d",
2963 				   ret);
2964 		up(&fs_info->uuid_tree_rescan_sem);
2965 		return ret;
2966 	}
2967 	return btrfs_uuid_scan_kthread(data);
2968 }
2969 
btrfs_check_uuid_tree(struct btrfs_fs_info * fs_info)2970 static int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
2971 {
2972 	struct task_struct *task;
2973 
2974 	down(&fs_info->uuid_tree_rescan_sem);
2975 	task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
2976 	if (IS_ERR(task)) {
2977 		/* fs_info->update_uuid_tree_gen remains 0 in all error case */
2978 		btrfs_warn(fs_info, "failed to start uuid_rescan task");
2979 		up(&fs_info->uuid_tree_rescan_sem);
2980 		return PTR_ERR(task);
2981 	}
2982 
2983 	return 0;
2984 }
2985 
btrfs_cleanup_fs_roots(struct btrfs_fs_info * fs_info)2986 static int btrfs_cleanup_fs_roots(struct btrfs_fs_info *fs_info)
2987 {
2988 	u64 root_objectid = 0;
2989 	struct btrfs_root *gang[8];
2990 	int ret = 0;
2991 
2992 	while (1) {
2993 		unsigned int found;
2994 
2995 		spin_lock(&fs_info->fs_roots_radix_lock);
2996 		found = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
2997 					     (void **)gang, root_objectid,
2998 					     ARRAY_SIZE(gang));
2999 		if (!found) {
3000 			spin_unlock(&fs_info->fs_roots_radix_lock);
3001 			break;
3002 		}
3003 		root_objectid = btrfs_root_id(gang[found - 1]) + 1;
3004 
3005 		for (int i = 0; i < found; i++) {
3006 			/* Avoid to grab roots in dead_roots. */
3007 			if (btrfs_root_refs(&gang[i]->root_item) == 0) {
3008 				gang[i] = NULL;
3009 				continue;
3010 			}
3011 			/* Grab all the search result for later use. */
3012 			gang[i] = btrfs_grab_root(gang[i]);
3013 		}
3014 		spin_unlock(&fs_info->fs_roots_radix_lock);
3015 
3016 		for (int i = 0; i < found; i++) {
3017 			if (!gang[i])
3018 				continue;
3019 			root_objectid = btrfs_root_id(gang[i]);
3020 			/*
3021 			 * Continue to release the remaining roots after the first
3022 			 * error without cleanup and preserve the first error
3023 			 * for the return.
3024 			 */
3025 			if (!ret)
3026 				ret = btrfs_orphan_cleanup(gang[i]);
3027 			btrfs_put_root(gang[i]);
3028 		}
3029 		if (ret)
3030 			break;
3031 
3032 		root_objectid++;
3033 	}
3034 	return ret;
3035 }
3036 
3037 /*
3038  * Mounting logic specific to read-write file systems. Shared by open_ctree
3039  * and btrfs_remount when remounting from read-only to read-write.
3040  */
btrfs_start_pre_rw_mount(struct btrfs_fs_info * fs_info)3041 int btrfs_start_pre_rw_mount(struct btrfs_fs_info *fs_info)
3042 {
3043 	int ret;
3044 	const bool cache_opt = btrfs_test_opt(fs_info, SPACE_CACHE);
3045 	bool rebuild_free_space_tree = false;
3046 
3047 	if (btrfs_test_opt(fs_info, CLEAR_CACHE) &&
3048 	    btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
3049 		if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))
3050 			btrfs_warn(fs_info,
3051 				   "'clear_cache' option is ignored with extent tree v2");
3052 		else
3053 			rebuild_free_space_tree = true;
3054 	} else if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
3055 		   !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID)) {
3056 		btrfs_warn(fs_info, "free space tree is invalid");
3057 		rebuild_free_space_tree = true;
3058 	}
3059 
3060 	if (rebuild_free_space_tree) {
3061 		btrfs_info(fs_info, "rebuilding free space tree");
3062 		ret = btrfs_rebuild_free_space_tree(fs_info);
3063 		if (ret) {
3064 			btrfs_warn(fs_info,
3065 				   "failed to rebuild free space tree: %d", ret);
3066 			goto out;
3067 		}
3068 	}
3069 
3070 	if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
3071 	    !btrfs_test_opt(fs_info, FREE_SPACE_TREE)) {
3072 		btrfs_info(fs_info, "disabling free space tree");
3073 		ret = btrfs_delete_free_space_tree(fs_info);
3074 		if (ret) {
3075 			btrfs_warn(fs_info,
3076 				   "failed to disable free space tree: %d", ret);
3077 			goto out;
3078 		}
3079 	}
3080 
3081 	/*
3082 	 * btrfs_find_orphan_roots() is responsible for finding all the dead
3083 	 * roots (with 0 refs), flag them with BTRFS_ROOT_DEAD_TREE and load
3084 	 * them into the fs_info->fs_roots_radix tree. This must be done before
3085 	 * calling btrfs_orphan_cleanup() on the tree root. If we don't do it
3086 	 * first, then btrfs_orphan_cleanup() will delete a dead root's orphan
3087 	 * item before the root's tree is deleted - this means that if we unmount
3088 	 * or crash before the deletion completes, on the next mount we will not
3089 	 * delete what remains of the tree because the orphan item does not
3090 	 * exists anymore, which is what tells us we have a pending deletion.
3091 	 */
3092 	ret = btrfs_find_orphan_roots(fs_info);
3093 	if (ret)
3094 		goto out;
3095 
3096 	ret = btrfs_cleanup_fs_roots(fs_info);
3097 	if (ret)
3098 		goto out;
3099 
3100 	down_read(&fs_info->cleanup_work_sem);
3101 	if ((ret = btrfs_orphan_cleanup(fs_info->fs_root)) ||
3102 	    (ret = btrfs_orphan_cleanup(fs_info->tree_root))) {
3103 		up_read(&fs_info->cleanup_work_sem);
3104 		goto out;
3105 	}
3106 	up_read(&fs_info->cleanup_work_sem);
3107 
3108 	mutex_lock(&fs_info->cleaner_mutex);
3109 	ret = btrfs_recover_relocation(fs_info);
3110 	mutex_unlock(&fs_info->cleaner_mutex);
3111 	if (ret < 0) {
3112 		btrfs_warn(fs_info, "failed to recover relocation: %d", ret);
3113 		goto out;
3114 	}
3115 
3116 	if (btrfs_test_opt(fs_info, FREE_SPACE_TREE) &&
3117 	    !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
3118 		btrfs_info(fs_info, "creating free space tree");
3119 		ret = btrfs_create_free_space_tree(fs_info);
3120 		if (ret) {
3121 			btrfs_warn(fs_info,
3122 				"failed to create free space tree: %d", ret);
3123 			goto out;
3124 		}
3125 	}
3126 
3127 	if (cache_opt != btrfs_free_space_cache_v1_active(fs_info)) {
3128 		ret = btrfs_set_free_space_cache_v1_active(fs_info, cache_opt);
3129 		if (ret)
3130 			goto out;
3131 	}
3132 
3133 	ret = btrfs_resume_balance_async(fs_info);
3134 	if (ret)
3135 		goto out;
3136 
3137 	ret = btrfs_resume_dev_replace_async(fs_info);
3138 	if (ret) {
3139 		btrfs_warn(fs_info, "failed to resume dev_replace");
3140 		goto out;
3141 	}
3142 
3143 	btrfs_qgroup_rescan_resume(fs_info);
3144 
3145 	if (!fs_info->uuid_root) {
3146 		btrfs_info(fs_info, "creating UUID tree");
3147 		ret = btrfs_create_uuid_tree(fs_info);
3148 		if (ret) {
3149 			btrfs_warn(fs_info,
3150 				   "failed to create the UUID tree %d", ret);
3151 			goto out;
3152 		}
3153 	}
3154 
3155 out:
3156 	return ret;
3157 }
3158 
3159 /*
3160  * Do various sanity and dependency checks of different features.
3161  *
3162  * @is_rw_mount:	If the mount is read-write.
3163  *
3164  * This is the place for less strict checks (like for subpage or artificial
3165  * feature dependencies).
3166  *
3167  * For strict checks or possible corruption detection, see
3168  * btrfs_validate_super().
3169  *
3170  * This should be called after btrfs_parse_options(), as some mount options
3171  * (space cache related) can modify on-disk format like free space tree and
3172  * screw up certain feature dependencies.
3173  */
btrfs_check_features(struct btrfs_fs_info * fs_info,bool is_rw_mount)3174 int btrfs_check_features(struct btrfs_fs_info *fs_info, bool is_rw_mount)
3175 {
3176 	struct btrfs_super_block *disk_super = fs_info->super_copy;
3177 	u64 incompat = btrfs_super_incompat_flags(disk_super);
3178 	const u64 compat_ro = btrfs_super_compat_ro_flags(disk_super);
3179 	const u64 compat_ro_unsupp = (compat_ro & ~BTRFS_FEATURE_COMPAT_RO_SUPP);
3180 
3181 	if (incompat & ~BTRFS_FEATURE_INCOMPAT_SUPP) {
3182 		btrfs_err(fs_info,
3183 		"cannot mount because of unknown incompat features (0x%llx)",
3184 		    incompat);
3185 		return -EINVAL;
3186 	}
3187 
3188 	/* Runtime limitation for mixed block groups. */
3189 	if ((incompat & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) &&
3190 	    (fs_info->sectorsize != fs_info->nodesize)) {
3191 		btrfs_err(fs_info,
3192 "unequal nodesize/sectorsize (%u != %u) are not allowed for mixed block groups",
3193 			fs_info->nodesize, fs_info->sectorsize);
3194 		return -EINVAL;
3195 	}
3196 
3197 	/* Mixed backref is an always-enabled feature. */
3198 	incompat |= BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF;
3199 
3200 	/* Set compression related flags just in case. */
3201 	if (fs_info->compress_type == BTRFS_COMPRESS_LZO)
3202 		incompat |= BTRFS_FEATURE_INCOMPAT_COMPRESS_LZO;
3203 	else if (fs_info->compress_type == BTRFS_COMPRESS_ZSTD)
3204 		incompat |= BTRFS_FEATURE_INCOMPAT_COMPRESS_ZSTD;
3205 
3206 	/*
3207 	 * An ancient flag, which should really be marked deprecated.
3208 	 * Such runtime limitation doesn't really need a incompat flag.
3209 	 */
3210 	if (btrfs_super_nodesize(disk_super) > PAGE_SIZE)
3211 		incompat |= BTRFS_FEATURE_INCOMPAT_BIG_METADATA;
3212 
3213 	if (compat_ro_unsupp && is_rw_mount) {
3214 		btrfs_err(fs_info,
3215 	"cannot mount read-write because of unknown compat_ro features (0x%llx)",
3216 		       compat_ro);
3217 		return -EINVAL;
3218 	}
3219 
3220 	/*
3221 	 * We have unsupported RO compat features, although RO mounted, we
3222 	 * should not cause any metadata writes, including log replay.
3223 	 * Or we could screw up whatever the new feature requires.
3224 	 */
3225 	if (compat_ro_unsupp && btrfs_super_log_root(disk_super) &&
3226 	    !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
3227 		btrfs_err(fs_info,
3228 "cannot replay dirty log with unsupported compat_ro features (0x%llx), try rescue=nologreplay",
3229 			  compat_ro);
3230 		return -EINVAL;
3231 	}
3232 
3233 	/*
3234 	 * Artificial limitations for block group tree, to force
3235 	 * block-group-tree to rely on no-holes and free-space-tree.
3236 	 */
3237 	if (btrfs_fs_compat_ro(fs_info, BLOCK_GROUP_TREE) &&
3238 	    (!btrfs_fs_incompat(fs_info, NO_HOLES) ||
3239 	     !btrfs_test_opt(fs_info, FREE_SPACE_TREE))) {
3240 		btrfs_err(fs_info,
3241 "block-group-tree feature requires no-holes and free-space-tree features");
3242 		return -EINVAL;
3243 	}
3244 
3245 	/*
3246 	 * Subpage/bs > ps runtime limitation on v1 cache.
3247 	 *
3248 	 * V1 space cache still has some hard coded PAGE_SIZE usage, while
3249 	 * we're already defaulting to v2 cache, no need to bother v1 as it's
3250 	 * going to be deprecated anyway.
3251 	 */
3252 	if (fs_info->sectorsize != PAGE_SIZE && btrfs_test_opt(fs_info, SPACE_CACHE)) {
3253 		btrfs_warn(fs_info,
3254 	"v1 space cache is not supported for page size %lu with sectorsize %u",
3255 			   PAGE_SIZE, fs_info->sectorsize);
3256 		return -EINVAL;
3257 	}
3258 	if (fs_info->sectorsize > PAGE_SIZE && btrfs_fs_incompat(fs_info, RAID56)) {
3259 		btrfs_err(fs_info,
3260 		"RAID56 is not supported for page size %lu with sectorsize %u",
3261 			  PAGE_SIZE, fs_info->sectorsize);
3262 		return -EINVAL;
3263 	}
3264 
3265 	/* This can be called by remount, we need to protect the super block. */
3266 	spin_lock(&fs_info->super_lock);
3267 	btrfs_set_super_incompat_flags(disk_super, incompat);
3268 	spin_unlock(&fs_info->super_lock);
3269 
3270 	return 0;
3271 }
3272 
open_ctree(struct super_block * sb,struct btrfs_fs_devices * fs_devices)3273 int __cold open_ctree(struct super_block *sb, struct btrfs_fs_devices *fs_devices)
3274 {
3275 	u32 sectorsize;
3276 	u32 nodesize;
3277 	u32 stripesize;
3278 	u64 generation;
3279 	u16 csum_type;
3280 	struct btrfs_super_block *disk_super;
3281 	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
3282 	struct btrfs_root *tree_root;
3283 	struct btrfs_root *chunk_root;
3284 	int ret;
3285 	int level;
3286 
3287 	ret = init_mount_fs_info(fs_info, sb);
3288 	if (ret)
3289 		goto fail;
3290 
3291 	/* These need to be init'ed before we start creating inodes and such. */
3292 	tree_root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID,
3293 				     GFP_KERNEL);
3294 	fs_info->tree_root = tree_root;
3295 	chunk_root = btrfs_alloc_root(fs_info, BTRFS_CHUNK_TREE_OBJECTID,
3296 				      GFP_KERNEL);
3297 	fs_info->chunk_root = chunk_root;
3298 	if (!tree_root || !chunk_root) {
3299 		ret = -ENOMEM;
3300 		goto fail;
3301 	}
3302 
3303 	ret = btrfs_init_btree_inode(sb);
3304 	if (ret)
3305 		goto fail;
3306 
3307 	invalidate_bdev(fs_devices->latest_dev->bdev);
3308 
3309 	/*
3310 	 * Read super block and check the signature bytes only
3311 	 */
3312 	disk_super = btrfs_read_disk_super(fs_devices->latest_dev->bdev, 0, false);
3313 	if (IS_ERR(disk_super)) {
3314 		ret = PTR_ERR(disk_super);
3315 		goto fail_alloc;
3316 	}
3317 
3318 	btrfs_info(fs_info, "first mount of filesystem %pU", disk_super->fsid);
3319 	/*
3320 	 * Verify the type first, if that or the checksum value are
3321 	 * corrupted, we'll find out
3322 	 */
3323 	csum_type = btrfs_super_csum_type(disk_super);
3324 	if (!btrfs_supported_super_csum(csum_type)) {
3325 		btrfs_err(fs_info, "unsupported checksum algorithm: %u",
3326 			  csum_type);
3327 		ret = -EINVAL;
3328 		btrfs_release_disk_super(disk_super);
3329 		goto fail_alloc;
3330 	}
3331 
3332 	fs_info->csum_size = btrfs_super_csum_size(disk_super);
3333 
3334 	ret = btrfs_init_csum_hash(fs_info, csum_type);
3335 	if (ret) {
3336 		btrfs_release_disk_super(disk_super);
3337 		goto fail_alloc;
3338 	}
3339 
3340 	/*
3341 	 * We want to check superblock checksum, the type is stored inside.
3342 	 * Pass the whole disk block of size BTRFS_SUPER_INFO_SIZE (4k).
3343 	 */
3344 	if (btrfs_check_super_csum(fs_info, disk_super)) {
3345 		btrfs_err(fs_info, "superblock checksum mismatch");
3346 		ret = -EINVAL;
3347 		btrfs_release_disk_super(disk_super);
3348 		goto fail_alloc;
3349 	}
3350 
3351 	/*
3352 	 * super_copy is zeroed at allocation time and we never touch the
3353 	 * following bytes up to INFO_SIZE, the checksum is calculated from
3354 	 * the whole block of INFO_SIZE
3355 	 */
3356 	memcpy(fs_info->super_copy, disk_super, sizeof(*fs_info->super_copy));
3357 	btrfs_release_disk_super(disk_super);
3358 
3359 	disk_super = fs_info->super_copy;
3360 
3361 	memcpy(fs_info->super_for_commit, fs_info->super_copy,
3362 	       sizeof(*fs_info->super_for_commit));
3363 
3364 	ret = btrfs_validate_mount_super(fs_info);
3365 	if (ret) {
3366 		btrfs_err(fs_info, "superblock contains fatal errors");
3367 		ret = -EINVAL;
3368 		goto fail_alloc;
3369 	}
3370 
3371 	if (!btrfs_super_root(disk_super)) {
3372 		btrfs_err(fs_info, "invalid superblock tree root bytenr");
3373 		ret = -EINVAL;
3374 		goto fail_alloc;
3375 	}
3376 
3377 	/* check FS state, whether FS is broken. */
3378 	if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_ERROR)
3379 		WRITE_ONCE(fs_info->fs_error, -EUCLEAN);
3380 
3381 	/* Set up fs_info before parsing mount options */
3382 	nodesize = btrfs_super_nodesize(disk_super);
3383 	sectorsize = btrfs_super_sectorsize(disk_super);
3384 	stripesize = sectorsize;
3385 	fs_info->dirty_metadata_batch = nodesize * (1 + ilog2(nr_cpu_ids));
3386 	fs_info->delalloc_batch = sectorsize * 512 * (1 + ilog2(nr_cpu_ids));
3387 
3388 	fs_info->nodesize = nodesize;
3389 	fs_info->nodesize_bits = ilog2(nodesize);
3390 	fs_info->sectorsize = sectorsize;
3391 	fs_info->sectorsize_bits = ilog2(sectorsize);
3392 	fs_info->block_min_order = ilog2(round_up(sectorsize, PAGE_SIZE) >> PAGE_SHIFT);
3393 	fs_info->block_max_order = ilog2((BITS_PER_LONG << fs_info->sectorsize_bits) >> PAGE_SHIFT);
3394 	fs_info->csums_per_leaf = BTRFS_MAX_ITEM_SIZE(fs_info) / fs_info->csum_size;
3395 	fs_info->stripesize = stripesize;
3396 	fs_info->fs_devices->fs_info = fs_info;
3397 
3398 	if (fs_info->sectorsize > PAGE_SIZE)
3399 		btrfs_warn(fs_info,
3400 			   "support for block size %u with page size %zu is experimental, some features may be missing",
3401 			   fs_info->sectorsize, PAGE_SIZE);
3402 	/*
3403 	 * Handle the space caching options appropriately now that we have the
3404 	 * super block loaded and validated.
3405 	 */
3406 	btrfs_set_free_space_cache_settings(fs_info);
3407 
3408 	if (!btrfs_check_options(fs_info, &fs_info->mount_opt, sb->s_flags)) {
3409 		ret = -EINVAL;
3410 		goto fail_alloc;
3411 	}
3412 
3413 	ret = btrfs_check_features(fs_info, !sb_rdonly(sb));
3414 	if (ret < 0)
3415 		goto fail_alloc;
3416 
3417 	/*
3418 	 * At this point our mount options are validated, if we set ->max_inline
3419 	 * to something non-standard make sure we truncate it to sectorsize.
3420 	 */
3421 	fs_info->max_inline = min_t(u64, fs_info->max_inline, fs_info->sectorsize);
3422 
3423 	ret = btrfs_alloc_compress_wsm(fs_info);
3424 	if (ret)
3425 		goto fail_sb_buffer;
3426 	ret = btrfs_init_workqueues(fs_info);
3427 	if (ret)
3428 		goto fail_sb_buffer;
3429 
3430 	sb->s_bdi->ra_pages *= btrfs_super_num_devices(disk_super);
3431 	sb->s_bdi->ra_pages = max(sb->s_bdi->ra_pages, SZ_4M / PAGE_SIZE);
3432 
3433 	/* Update the values for the current filesystem. */
3434 	sb->s_blocksize = sectorsize;
3435 	sb->s_blocksize_bits = blksize_bits(sectorsize);
3436 	memcpy(&sb->s_uuid, fs_info->fs_devices->fsid, BTRFS_FSID_SIZE);
3437 
3438 	mutex_lock(&fs_info->chunk_mutex);
3439 	ret = btrfs_read_sys_array(fs_info);
3440 	mutex_unlock(&fs_info->chunk_mutex);
3441 	if (ret) {
3442 		btrfs_err(fs_info, "failed to read the system array: %d", ret);
3443 		goto fail_sb_buffer;
3444 	}
3445 
3446 	generation = btrfs_super_chunk_root_generation(disk_super);
3447 	level = btrfs_super_chunk_root_level(disk_super);
3448 	ret = load_super_root(chunk_root, btrfs_super_chunk_root(disk_super),
3449 			      generation, level);
3450 	if (ret) {
3451 		btrfs_err(fs_info, "failed to read chunk root");
3452 		goto fail_tree_roots;
3453 	}
3454 
3455 	read_extent_buffer(chunk_root->node, fs_info->chunk_tree_uuid,
3456 			   offsetof(struct btrfs_header, chunk_tree_uuid),
3457 			   BTRFS_UUID_SIZE);
3458 
3459 	ret = btrfs_read_chunk_tree(fs_info);
3460 	if (ret) {
3461 		btrfs_err(fs_info, "failed to read chunk tree: %d", ret);
3462 		goto fail_tree_roots;
3463 	}
3464 
3465 	/*
3466 	 * At this point we know all the devices that make this filesystem,
3467 	 * including the seed devices but we don't know yet if the replace
3468 	 * target is required. So free devices that are not part of this
3469 	 * filesystem but skip the replace target device which is checked
3470 	 * below in btrfs_init_dev_replace().
3471 	 */
3472 	btrfs_free_extra_devids(fs_devices);
3473 	if (unlikely(!fs_devices->latest_dev->bdev)) {
3474 		btrfs_err(fs_info, "failed to read devices");
3475 		ret = -EIO;
3476 		goto fail_tree_roots;
3477 	}
3478 
3479 	ret = init_tree_roots(fs_info);
3480 	if (ret)
3481 		goto fail_tree_roots;
3482 
3483 	/*
3484 	 * Get zone type information of zoned block devices. This will also
3485 	 * handle emulation of a zoned filesystem if a regular device has the
3486 	 * zoned incompat feature flag set.
3487 	 */
3488 	ret = btrfs_get_dev_zone_info_all_devices(fs_info);
3489 	if (ret) {
3490 		btrfs_err(fs_info,
3491 			  "zoned: failed to read device zone info: %d", ret);
3492 		goto fail_block_groups;
3493 	}
3494 
3495 	/*
3496 	 * If we have a uuid root and we're not being told to rescan we need to
3497 	 * check the generation here so we can set the
3498 	 * BTRFS_FS_UPDATE_UUID_TREE_GEN bit.  Otherwise we could commit the
3499 	 * transaction during a balance or the log replay without updating the
3500 	 * uuid generation, and then if we crash we would rescan the uuid tree,
3501 	 * even though it was perfectly fine.
3502 	 */
3503 	if (fs_info->uuid_root && !btrfs_test_opt(fs_info, RESCAN_UUID_TREE) &&
3504 	    fs_info->generation == btrfs_super_uuid_tree_generation(disk_super))
3505 		set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
3506 
3507 	ret = btrfs_verify_dev_extents(fs_info);
3508 	if (ret) {
3509 		btrfs_err(fs_info,
3510 			  "failed to verify dev extents against chunks: %d",
3511 			  ret);
3512 		goto fail_block_groups;
3513 	}
3514 	ret = btrfs_recover_balance(fs_info);
3515 	if (ret) {
3516 		btrfs_err(fs_info, "failed to recover balance: %d", ret);
3517 		goto fail_block_groups;
3518 	}
3519 
3520 	ret = btrfs_init_dev_stats(fs_info);
3521 	if (ret) {
3522 		btrfs_err(fs_info, "failed to init dev_stats: %d", ret);
3523 		goto fail_block_groups;
3524 	}
3525 
3526 	ret = btrfs_init_dev_replace(fs_info);
3527 	if (ret) {
3528 		btrfs_err(fs_info, "failed to init dev_replace: %d", ret);
3529 		goto fail_block_groups;
3530 	}
3531 
3532 	ret = btrfs_check_zoned_mode(fs_info);
3533 	if (ret) {
3534 		btrfs_err(fs_info, "failed to initialize zoned mode: %d",
3535 			  ret);
3536 		goto fail_block_groups;
3537 	}
3538 
3539 	ret = btrfs_sysfs_add_fsid(fs_devices);
3540 	if (ret) {
3541 		btrfs_err(fs_info, "failed to init sysfs fsid interface: %d",
3542 				ret);
3543 		goto fail_block_groups;
3544 	}
3545 
3546 	ret = btrfs_sysfs_add_mounted(fs_info);
3547 	if (ret) {
3548 		btrfs_err(fs_info, "failed to init sysfs interface: %d", ret);
3549 		goto fail_fsdev_sysfs;
3550 	}
3551 
3552 	ret = btrfs_init_space_info(fs_info);
3553 	if (ret) {
3554 		btrfs_err(fs_info, "failed to initialize space info: %d", ret);
3555 		goto fail_sysfs;
3556 	}
3557 
3558 	ret = btrfs_read_block_groups(fs_info);
3559 	if (ret) {
3560 		btrfs_err(fs_info, "failed to read block groups: %d", ret);
3561 		goto fail_sysfs;
3562 	}
3563 
3564 	btrfs_zoned_reserve_data_reloc_bg(fs_info);
3565 	btrfs_free_zone_cache(fs_info);
3566 
3567 	btrfs_check_active_zone_reservation(fs_info);
3568 
3569 	if (!sb_rdonly(sb) && fs_info->fs_devices->missing_devices &&
3570 	    !btrfs_check_rw_degradable(fs_info, NULL)) {
3571 		btrfs_warn(fs_info,
3572 		"writable mount is not allowed due to too many missing devices");
3573 		ret = -EINVAL;
3574 		goto fail_sysfs;
3575 	}
3576 
3577 	fs_info->cleaner_kthread = kthread_run(cleaner_kthread, fs_info,
3578 					       "btrfs-cleaner");
3579 	if (IS_ERR(fs_info->cleaner_kthread)) {
3580 		ret = PTR_ERR(fs_info->cleaner_kthread);
3581 		goto fail_sysfs;
3582 	}
3583 
3584 	fs_info->transaction_kthread = kthread_run(transaction_kthread,
3585 						   tree_root,
3586 						   "btrfs-transaction");
3587 	if (IS_ERR(fs_info->transaction_kthread)) {
3588 		ret = PTR_ERR(fs_info->transaction_kthread);
3589 		goto fail_cleaner;
3590 	}
3591 
3592 	ret = btrfs_read_qgroup_config(fs_info);
3593 	if (ret)
3594 		goto fail_trans_kthread;
3595 
3596 	if (btrfs_build_ref_tree(fs_info))
3597 		btrfs_err(fs_info, "couldn't build ref tree");
3598 
3599 	/* do not make disk changes in broken FS or nologreplay is given */
3600 	if (btrfs_super_log_root(disk_super) != 0 &&
3601 	    !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
3602 		btrfs_info(fs_info, "start tree-log replay");
3603 		ret = btrfs_replay_log(fs_info, fs_devices);
3604 		if (ret)
3605 			goto fail_qgroup;
3606 	}
3607 
3608 	fs_info->fs_root = btrfs_get_fs_root(fs_info, BTRFS_FS_TREE_OBJECTID, true);
3609 	if (IS_ERR(fs_info->fs_root)) {
3610 		ret = PTR_ERR(fs_info->fs_root);
3611 		btrfs_warn(fs_info, "failed to read fs tree: %d", ret);
3612 		fs_info->fs_root = NULL;
3613 		goto fail_qgroup;
3614 	}
3615 
3616 	if (sb_rdonly(sb))
3617 		return 0;
3618 
3619 	ret = btrfs_start_pre_rw_mount(fs_info);
3620 	if (ret) {
3621 		close_ctree(fs_info);
3622 		return ret;
3623 	}
3624 	btrfs_discard_resume(fs_info);
3625 
3626 	if (fs_info->uuid_root &&
3627 	    (btrfs_test_opt(fs_info, RESCAN_UUID_TREE) ||
3628 	     fs_info->generation != btrfs_super_uuid_tree_generation(disk_super))) {
3629 		btrfs_info(fs_info, "checking UUID tree");
3630 		ret = btrfs_check_uuid_tree(fs_info);
3631 		if (ret) {
3632 			btrfs_warn(fs_info,
3633 				"failed to check the UUID tree: %d", ret);
3634 			close_ctree(fs_info);
3635 			return ret;
3636 		}
3637 	}
3638 
3639 	set_bit(BTRFS_FS_OPEN, &fs_info->flags);
3640 
3641 	/* Kick the cleaner thread so it'll start deleting snapshots. */
3642 	if (test_bit(BTRFS_FS_UNFINISHED_DROPS, &fs_info->flags))
3643 		wake_up_process(fs_info->cleaner_kthread);
3644 
3645 	return 0;
3646 
3647 fail_qgroup:
3648 	btrfs_free_qgroup_config(fs_info);
3649 fail_trans_kthread:
3650 	kthread_stop(fs_info->transaction_kthread);
3651 	btrfs_cleanup_transaction(fs_info);
3652 	btrfs_free_fs_roots(fs_info);
3653 fail_cleaner:
3654 	kthread_stop(fs_info->cleaner_kthread);
3655 
3656 	/*
3657 	 * make sure we're done with the btree inode before we stop our
3658 	 * kthreads
3659 	 */
3660 	filemap_write_and_wait(fs_info->btree_inode->i_mapping);
3661 
3662 fail_sysfs:
3663 	btrfs_sysfs_remove_mounted(fs_info);
3664 
3665 fail_fsdev_sysfs:
3666 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
3667 
3668 fail_block_groups:
3669 	btrfs_put_block_group_cache(fs_info);
3670 
3671 fail_tree_roots:
3672 	if (fs_info->data_reloc_root)
3673 		btrfs_drop_and_free_fs_root(fs_info, fs_info->data_reloc_root);
3674 	free_root_pointers(fs_info, true);
3675 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
3676 
3677 fail_sb_buffer:
3678 	btrfs_stop_all_workers(fs_info);
3679 	btrfs_free_block_groups(fs_info);
3680 fail_alloc:
3681 	btrfs_mapping_tree_free(fs_info);
3682 
3683 	iput(fs_info->btree_inode);
3684 fail:
3685 	ASSERT(ret < 0);
3686 	return ret;
3687 }
3688 ALLOW_ERROR_INJECTION(open_ctree, ERRNO);
3689 
btrfs_end_super_write(struct bio * bio)3690 static void btrfs_end_super_write(struct bio *bio)
3691 {
3692 	struct btrfs_device *device = bio->bi_private;
3693 	struct folio_iter fi;
3694 
3695 	bio_for_each_folio_all(fi, bio) {
3696 		if (bio->bi_status) {
3697 			btrfs_warn_rl(device->fs_info,
3698 				"lost super block write due to IO error on %s (%d)",
3699 				btrfs_dev_name(device),
3700 				blk_status_to_errno(bio->bi_status));
3701 			btrfs_dev_stat_inc_and_print(device,
3702 						     BTRFS_DEV_STAT_WRITE_ERRS);
3703 			/* Ensure failure if the primary sb fails. */
3704 			if (bio->bi_opf & REQ_FUA)
3705 				atomic_add(BTRFS_SUPER_PRIMARY_WRITE_ERROR,
3706 					   &device->sb_write_errors);
3707 			else
3708 				atomic_inc(&device->sb_write_errors);
3709 		}
3710 		folio_unlock(fi.folio);
3711 		folio_put(fi.folio);
3712 	}
3713 
3714 	bio_put(bio);
3715 }
3716 
3717 /*
3718  * Write superblock @sb to the @device. Do not wait for completion, all the
3719  * folios we use for writing are locked.
3720  *
3721  * Write @max_mirrors copies of the superblock, where 0 means default that fit
3722  * the expected device size at commit time. Note that max_mirrors must be
3723  * same for write and wait phases.
3724  *
3725  * Return number of errors when folio is not found or submission fails.
3726  */
write_dev_supers(struct btrfs_device * device,struct btrfs_super_block * sb,int max_mirrors)3727 static int write_dev_supers(struct btrfs_device *device,
3728 			    struct btrfs_super_block *sb, int max_mirrors)
3729 {
3730 	struct btrfs_fs_info *fs_info = device->fs_info;
3731 	struct address_space *mapping = device->bdev->bd_mapping;
3732 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
3733 	int i;
3734 	int ret;
3735 	u64 bytenr, bytenr_orig;
3736 
3737 	atomic_set(&device->sb_write_errors, 0);
3738 
3739 	if (max_mirrors == 0)
3740 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3741 
3742 	shash->tfm = fs_info->csum_shash;
3743 
3744 	for (i = 0; i < max_mirrors; i++) {
3745 		struct folio *folio;
3746 		struct bio *bio;
3747 		struct btrfs_super_block *disk_super;
3748 		size_t offset;
3749 
3750 		bytenr_orig = btrfs_sb_offset(i);
3751 		ret = btrfs_sb_log_location(device, i, WRITE, &bytenr);
3752 		if (ret == -ENOENT) {
3753 			continue;
3754 		} else if (ret < 0) {
3755 			btrfs_err(device->fs_info,
3756 			  "couldn't get super block location for mirror %d error %d",
3757 			  i, ret);
3758 			atomic_inc(&device->sb_write_errors);
3759 			continue;
3760 		}
3761 		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3762 		    device->commit_total_bytes)
3763 			break;
3764 
3765 		btrfs_set_super_bytenr(sb, bytenr_orig);
3766 
3767 		crypto_shash_digest(shash, (const char *)sb + BTRFS_CSUM_SIZE,
3768 				    BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE,
3769 				    sb->csum);
3770 
3771 		folio = __filemap_get_folio(mapping, bytenr >> PAGE_SHIFT,
3772 					    FGP_LOCK | FGP_ACCESSED | FGP_CREAT,
3773 					    GFP_NOFS);
3774 		if (IS_ERR(folio)) {
3775 			btrfs_err(device->fs_info,
3776 			  "couldn't get super block page for bytenr %llu error %ld",
3777 			  bytenr, PTR_ERR(folio));
3778 			atomic_inc(&device->sb_write_errors);
3779 			continue;
3780 		}
3781 
3782 		offset = offset_in_folio(folio, bytenr);
3783 		disk_super = folio_address(folio) + offset;
3784 		memcpy(disk_super, sb, BTRFS_SUPER_INFO_SIZE);
3785 
3786 		/*
3787 		 * Directly use bios here instead of relying on the page cache
3788 		 * to do I/O, so we don't lose the ability to do integrity
3789 		 * checking.
3790 		 */
3791 		bio = bio_alloc(device->bdev, 1,
3792 				REQ_OP_WRITE | REQ_SYNC | REQ_META | REQ_PRIO,
3793 				GFP_NOFS);
3794 		bio->bi_iter.bi_sector = bytenr >> SECTOR_SHIFT;
3795 		bio->bi_private = device;
3796 		bio->bi_end_io = btrfs_end_super_write;
3797 		bio_add_folio_nofail(bio, folio, BTRFS_SUPER_INFO_SIZE, offset);
3798 
3799 		/*
3800 		 * We FUA only the first super block.  The others we allow to
3801 		 * go down lazy and there's a short window where the on-disk
3802 		 * copies might still contain the older version.
3803 		 */
3804 		if (i == 0 && !btrfs_test_opt(device->fs_info, NOBARRIER))
3805 			bio->bi_opf |= REQ_FUA;
3806 		submit_bio(bio);
3807 
3808 		if (btrfs_advance_sb_log(device, i))
3809 			atomic_inc(&device->sb_write_errors);
3810 	}
3811 	return atomic_read(&device->sb_write_errors) < i ? 0 : -1;
3812 }
3813 
3814 /*
3815  * Wait for write completion of superblocks done by write_dev_supers,
3816  * @max_mirrors same for write and wait phases.
3817  *
3818  * Return -1 if primary super block write failed or when there were no super block
3819  * copies written. Otherwise 0.
3820  */
wait_dev_supers(struct btrfs_device * device,int max_mirrors)3821 static int wait_dev_supers(struct btrfs_device *device, int max_mirrors)
3822 {
3823 	int i;
3824 	int errors = 0;
3825 	bool primary_failed = false;
3826 	int ret;
3827 	u64 bytenr;
3828 
3829 	if (max_mirrors == 0)
3830 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3831 
3832 	for (i = 0; i < max_mirrors; i++) {
3833 		struct folio *folio;
3834 
3835 		ret = btrfs_sb_log_location(device, i, READ, &bytenr);
3836 		if (ret == -ENOENT) {
3837 			break;
3838 		} else if (ret < 0) {
3839 			errors++;
3840 			if (i == 0)
3841 				primary_failed = true;
3842 			continue;
3843 		}
3844 		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3845 		    device->commit_total_bytes)
3846 			break;
3847 
3848 		folio = filemap_get_folio(device->bdev->bd_mapping,
3849 					  bytenr >> PAGE_SHIFT);
3850 		/* If the folio has been removed, then we know it completed. */
3851 		if (IS_ERR(folio))
3852 			continue;
3853 
3854 		/* Folio will be unlocked once the write completes. */
3855 		folio_wait_locked(folio);
3856 		folio_put(folio);
3857 	}
3858 
3859 	errors += atomic_read(&device->sb_write_errors);
3860 	if (errors >= BTRFS_SUPER_PRIMARY_WRITE_ERROR)
3861 		primary_failed = true;
3862 	if (primary_failed) {
3863 		btrfs_err(device->fs_info, "error writing primary super block to device %llu",
3864 			  device->devid);
3865 		return -1;
3866 	}
3867 
3868 	return errors < i ? 0 : -1;
3869 }
3870 
3871 /*
3872  * endio for the write_dev_flush, this will wake anyone waiting
3873  * for the barrier when it is done
3874  */
btrfs_end_empty_barrier(struct bio * bio)3875 static void btrfs_end_empty_barrier(struct bio *bio)
3876 {
3877 	bio_uninit(bio);
3878 	complete(bio->bi_private);
3879 }
3880 
3881 /*
3882  * Submit a flush request to the device if it supports it. Error handling is
3883  * done in the waiting counterpart.
3884  */
write_dev_flush(struct btrfs_device * device)3885 static void write_dev_flush(struct btrfs_device *device)
3886 {
3887 	struct bio *bio = &device->flush_bio;
3888 
3889 	device->last_flush_error = BLK_STS_OK;
3890 
3891 	bio_init(bio, device->bdev, NULL, 0,
3892 		 REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH);
3893 	bio->bi_end_io = btrfs_end_empty_barrier;
3894 	init_completion(&device->flush_wait);
3895 	bio->bi_private = &device->flush_wait;
3896 	submit_bio(bio);
3897 	set_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
3898 }
3899 
3900 /*
3901  * If the flush bio has been submitted by write_dev_flush, wait for it.
3902  * Return true for any error, and false otherwise.
3903  */
wait_dev_flush(struct btrfs_device * device)3904 static bool wait_dev_flush(struct btrfs_device *device)
3905 {
3906 	struct bio *bio = &device->flush_bio;
3907 
3908 	if (!test_and_clear_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state))
3909 		return false;
3910 
3911 	wait_for_completion_io(&device->flush_wait);
3912 
3913 	if (bio->bi_status) {
3914 		device->last_flush_error = bio->bi_status;
3915 		btrfs_dev_stat_inc_and_print(device, BTRFS_DEV_STAT_FLUSH_ERRS);
3916 		return true;
3917 	}
3918 
3919 	return false;
3920 }
3921 
3922 /*
3923  * send an empty flush down to each device in parallel,
3924  * then wait for them
3925  */
barrier_all_devices(struct btrfs_fs_info * info)3926 static int barrier_all_devices(struct btrfs_fs_info *info)
3927 {
3928 	struct list_head *head;
3929 	struct btrfs_device *dev;
3930 	int errors_wait = 0;
3931 
3932 	lockdep_assert_held(&info->fs_devices->device_list_mutex);
3933 	/* send down all the barriers */
3934 	head = &info->fs_devices->devices;
3935 	list_for_each_entry(dev, head, dev_list) {
3936 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
3937 			continue;
3938 		if (!dev->bdev)
3939 			continue;
3940 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3941 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3942 			continue;
3943 
3944 		write_dev_flush(dev);
3945 	}
3946 
3947 	/* wait for all the barriers */
3948 	list_for_each_entry(dev, head, dev_list) {
3949 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
3950 			continue;
3951 		if (!dev->bdev) {
3952 			errors_wait++;
3953 			continue;
3954 		}
3955 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3956 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3957 			continue;
3958 
3959 		if (wait_dev_flush(dev))
3960 			errors_wait++;
3961 	}
3962 
3963 	/*
3964 	 * Checks last_flush_error of disks in order to determine the device
3965 	 * state.
3966 	 */
3967 	if (unlikely(errors_wait && !btrfs_check_rw_degradable(info, NULL)))
3968 		return -EIO;
3969 
3970 	return 0;
3971 }
3972 
btrfs_get_num_tolerated_disk_barrier_failures(u64 flags)3973 int btrfs_get_num_tolerated_disk_barrier_failures(u64 flags)
3974 {
3975 	int raid_type;
3976 	int min_tolerated = INT_MAX;
3977 
3978 	if ((flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 ||
3979 	    (flags & BTRFS_AVAIL_ALLOC_BIT_SINGLE))
3980 		min_tolerated = min_t(int, min_tolerated,
3981 				    btrfs_raid_array[BTRFS_RAID_SINGLE].
3982 				    tolerated_failures);
3983 
3984 	for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
3985 		if (raid_type == BTRFS_RAID_SINGLE)
3986 			continue;
3987 		if (!(flags & btrfs_raid_array[raid_type].bg_flag))
3988 			continue;
3989 		min_tolerated = min_t(int, min_tolerated,
3990 				    btrfs_raid_array[raid_type].
3991 				    tolerated_failures);
3992 	}
3993 
3994 	if (min_tolerated == INT_MAX) {
3995 		btrfs_warn(NULL, "unknown raid flag: %llu", flags);
3996 		min_tolerated = 0;
3997 	}
3998 
3999 	return min_tolerated;
4000 }
4001 
write_all_supers(struct btrfs_fs_info * fs_info,int max_mirrors)4002 int write_all_supers(struct btrfs_fs_info *fs_info, int max_mirrors)
4003 {
4004 	struct list_head *head;
4005 	struct btrfs_device *dev;
4006 	struct btrfs_super_block *sb;
4007 	struct btrfs_dev_item *dev_item;
4008 	int ret;
4009 	int do_barriers;
4010 	int max_errors;
4011 	int total_errors = 0;
4012 	u64 flags;
4013 
4014 	do_barriers = !btrfs_test_opt(fs_info, NOBARRIER);
4015 
4016 	/*
4017 	 * max_mirrors == 0 indicates we're from commit_transaction,
4018 	 * not from fsync where the tree roots in fs_info have not
4019 	 * been consistent on disk.
4020 	 */
4021 	if (max_mirrors == 0)
4022 		backup_super_roots(fs_info);
4023 
4024 	sb = fs_info->super_for_commit;
4025 	dev_item = &sb->dev_item;
4026 
4027 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
4028 	head = &fs_info->fs_devices->devices;
4029 	max_errors = btrfs_super_num_devices(fs_info->super_copy) - 1;
4030 
4031 	if (do_barriers) {
4032 		ret = barrier_all_devices(fs_info);
4033 		if (ret) {
4034 			mutex_unlock(
4035 				&fs_info->fs_devices->device_list_mutex);
4036 			btrfs_handle_fs_error(fs_info, ret,
4037 					      "errors while submitting device barriers.");
4038 			return ret;
4039 		}
4040 	}
4041 
4042 	list_for_each_entry(dev, head, dev_list) {
4043 		if (!dev->bdev) {
4044 			total_errors++;
4045 			continue;
4046 		}
4047 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4048 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4049 			continue;
4050 
4051 		btrfs_set_stack_device_generation(dev_item, 0);
4052 		btrfs_set_stack_device_type(dev_item, dev->type);
4053 		btrfs_set_stack_device_id(dev_item, dev->devid);
4054 		btrfs_set_stack_device_total_bytes(dev_item,
4055 						   dev->commit_total_bytes);
4056 		btrfs_set_stack_device_bytes_used(dev_item,
4057 						  dev->commit_bytes_used);
4058 		btrfs_set_stack_device_io_align(dev_item, dev->io_align);
4059 		btrfs_set_stack_device_io_width(dev_item, dev->io_width);
4060 		btrfs_set_stack_device_sector_size(dev_item, dev->sector_size);
4061 		memcpy(dev_item->uuid, dev->uuid, BTRFS_UUID_SIZE);
4062 		memcpy(dev_item->fsid, dev->fs_devices->metadata_uuid,
4063 		       BTRFS_FSID_SIZE);
4064 
4065 		flags = btrfs_super_flags(sb);
4066 		btrfs_set_super_flags(sb, flags | BTRFS_HEADER_FLAG_WRITTEN);
4067 
4068 		ret = btrfs_validate_write_super(fs_info, sb);
4069 		if (unlikely(ret < 0)) {
4070 			mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4071 			btrfs_handle_fs_error(fs_info, -EUCLEAN,
4072 				"unexpected superblock corruption detected");
4073 			return -EUCLEAN;
4074 		}
4075 
4076 		ret = write_dev_supers(dev, sb, max_mirrors);
4077 		if (ret)
4078 			total_errors++;
4079 	}
4080 	if (unlikely(total_errors > max_errors)) {
4081 		btrfs_err(fs_info, "%d errors while writing supers",
4082 			  total_errors);
4083 		mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4084 
4085 		/* FUA is masked off if unsupported and can't be the reason */
4086 		btrfs_handle_fs_error(fs_info, -EIO,
4087 				      "%d errors while writing supers",
4088 				      total_errors);
4089 		return -EIO;
4090 	}
4091 
4092 	total_errors = 0;
4093 	list_for_each_entry(dev, head, dev_list) {
4094 		if (!dev->bdev)
4095 			continue;
4096 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4097 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4098 			continue;
4099 
4100 		ret = wait_dev_supers(dev, max_mirrors);
4101 		if (ret)
4102 			total_errors++;
4103 	}
4104 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4105 	if (unlikely(total_errors > max_errors)) {
4106 		btrfs_handle_fs_error(fs_info, -EIO,
4107 				      "%d errors while writing supers",
4108 				      total_errors);
4109 		return -EIO;
4110 	}
4111 	return 0;
4112 }
4113 
4114 /* Drop a fs root from the radix tree and free it. */
btrfs_drop_and_free_fs_root(struct btrfs_fs_info * fs_info,struct btrfs_root * root)4115 void btrfs_drop_and_free_fs_root(struct btrfs_fs_info *fs_info,
4116 				  struct btrfs_root *root)
4117 {
4118 	bool drop_ref = false;
4119 
4120 	spin_lock(&fs_info->fs_roots_radix_lock);
4121 	radix_tree_delete(&fs_info->fs_roots_radix,
4122 			  (unsigned long)btrfs_root_id(root));
4123 	if (test_and_clear_bit(BTRFS_ROOT_IN_RADIX, &root->state))
4124 		drop_ref = true;
4125 	spin_unlock(&fs_info->fs_roots_radix_lock);
4126 
4127 	if (BTRFS_FS_ERROR(fs_info)) {
4128 		ASSERT(root->log_root == NULL);
4129 		if (root->reloc_root) {
4130 			btrfs_put_root(root->reloc_root);
4131 			root->reloc_root = NULL;
4132 		}
4133 	}
4134 
4135 	if (drop_ref)
4136 		btrfs_put_root(root);
4137 }
4138 
btrfs_commit_super(struct btrfs_fs_info * fs_info)4139 int btrfs_commit_super(struct btrfs_fs_info *fs_info)
4140 {
4141 	mutex_lock(&fs_info->cleaner_mutex);
4142 	btrfs_run_delayed_iputs(fs_info);
4143 	mutex_unlock(&fs_info->cleaner_mutex);
4144 	wake_up_process(fs_info->cleaner_kthread);
4145 
4146 	/* wait until ongoing cleanup work done */
4147 	down_write(&fs_info->cleanup_work_sem);
4148 	up_write(&fs_info->cleanup_work_sem);
4149 
4150 	return btrfs_commit_current_transaction(fs_info->tree_root);
4151 }
4152 
warn_about_uncommitted_trans(struct btrfs_fs_info * fs_info)4153 static void warn_about_uncommitted_trans(struct btrfs_fs_info *fs_info)
4154 {
4155 	struct btrfs_transaction *trans;
4156 	struct btrfs_transaction *tmp;
4157 	bool found = false;
4158 
4159 	/*
4160 	 * This function is only called at the very end of close_ctree(),
4161 	 * thus no other running transaction, no need to take trans_lock.
4162 	 */
4163 	ASSERT(test_bit(BTRFS_FS_CLOSING_DONE, &fs_info->flags));
4164 	list_for_each_entry_safe(trans, tmp, &fs_info->trans_list, list) {
4165 		struct extent_state *cached = NULL;
4166 		u64 dirty_bytes = 0;
4167 		u64 cur = 0;
4168 		u64 found_start;
4169 		u64 found_end;
4170 
4171 		found = true;
4172 		while (btrfs_find_first_extent_bit(&trans->dirty_pages, cur,
4173 						   &found_start, &found_end,
4174 						   EXTENT_DIRTY, &cached)) {
4175 			dirty_bytes += found_end + 1 - found_start;
4176 			cur = found_end + 1;
4177 		}
4178 		btrfs_warn(fs_info,
4179 	"transaction %llu (with %llu dirty metadata bytes) is not committed",
4180 			   trans->transid, dirty_bytes);
4181 		btrfs_cleanup_one_transaction(trans);
4182 
4183 		if (trans == fs_info->running_transaction)
4184 			fs_info->running_transaction = NULL;
4185 		list_del_init(&trans->list);
4186 
4187 		btrfs_put_transaction(trans);
4188 		trace_btrfs_transaction_commit(fs_info);
4189 	}
4190 	ASSERT(!found);
4191 }
4192 
close_ctree(struct btrfs_fs_info * fs_info)4193 void __cold close_ctree(struct btrfs_fs_info *fs_info)
4194 {
4195 	int ret;
4196 
4197 	set_bit(BTRFS_FS_CLOSING_START, &fs_info->flags);
4198 
4199 	/*
4200 	 * If we had UNFINISHED_DROPS we could still be processing them, so
4201 	 * clear that bit and wake up relocation so it can stop.
4202 	 * We must do this before stopping the block group reclaim task, because
4203 	 * at btrfs_relocate_block_group() we wait for this bit, and after the
4204 	 * wait we stop with -EINTR if btrfs_fs_closing() returns non-zero - we
4205 	 * have just set BTRFS_FS_CLOSING_START, so btrfs_fs_closing() will
4206 	 * return 1.
4207 	 */
4208 	btrfs_wake_unfinished_drop(fs_info);
4209 
4210 	/*
4211 	 * We may have the reclaim task running and relocating a data block group,
4212 	 * in which case it may create delayed iputs. So stop it before we park
4213 	 * the cleaner kthread otherwise we can get new delayed iputs after
4214 	 * parking the cleaner, and that can make the async reclaim task to hang
4215 	 * if it's waiting for delayed iputs to complete, since the cleaner is
4216 	 * parked and can not run delayed iputs - this will make us hang when
4217 	 * trying to stop the async reclaim task.
4218 	 */
4219 	cancel_work_sync(&fs_info->reclaim_bgs_work);
4220 	/*
4221 	 * We don't want the cleaner to start new transactions, add more delayed
4222 	 * iputs, etc. while we're closing. We can't use kthread_stop() yet
4223 	 * because that frees the task_struct, and the transaction kthread might
4224 	 * still try to wake up the cleaner.
4225 	 */
4226 	kthread_park(fs_info->cleaner_kthread);
4227 
4228 	/* wait for the qgroup rescan worker to stop */
4229 	btrfs_qgroup_wait_for_completion(fs_info, false);
4230 
4231 	/* wait for the uuid_scan task to finish */
4232 	down(&fs_info->uuid_tree_rescan_sem);
4233 	/* avoid complains from lockdep et al., set sem back to initial state */
4234 	up(&fs_info->uuid_tree_rescan_sem);
4235 
4236 	/* pause restriper - we want to resume on mount */
4237 	btrfs_pause_balance(fs_info);
4238 
4239 	btrfs_dev_replace_suspend_for_unmount(fs_info);
4240 
4241 	btrfs_scrub_cancel(fs_info);
4242 
4243 	/* wait for any defraggers to finish */
4244 	wait_event(fs_info->transaction_wait,
4245 		   (atomic_read(&fs_info->defrag_running) == 0));
4246 
4247 	/* clear out the rbtree of defraggable inodes */
4248 	btrfs_cleanup_defrag_inodes(fs_info);
4249 
4250 	/*
4251 	 * Handle the error fs first, as it will flush and wait for all ordered
4252 	 * extents.  This will generate delayed iputs, thus we want to handle
4253 	 * it first.
4254 	 */
4255 	if (unlikely(BTRFS_FS_ERROR(fs_info)))
4256 		btrfs_error_commit_super(fs_info);
4257 
4258 	/*
4259 	 * Wait for any fixup workers to complete.
4260 	 * If we don't wait for them here and they are still running by the time
4261 	 * we call kthread_stop() against the cleaner kthread further below, we
4262 	 * get an use-after-free on the cleaner because the fixup worker adds an
4263 	 * inode to the list of delayed iputs and then attempts to wakeup the
4264 	 * cleaner kthread, which was already stopped and destroyed. We parked
4265 	 * already the cleaner, but below we run all pending delayed iputs.
4266 	 */
4267 	btrfs_flush_workqueue(fs_info->fixup_workers);
4268 	/*
4269 	 * Similar case here, we have to wait for delalloc workers before we
4270 	 * proceed below and stop the cleaner kthread, otherwise we trigger a
4271 	 * use-after-tree on the cleaner kthread task_struct when a delalloc
4272 	 * worker running submit_compressed_extents() adds a delayed iput, which
4273 	 * does a wake up on the cleaner kthread, which was already freed below
4274 	 * when we call kthread_stop().
4275 	 */
4276 	btrfs_flush_workqueue(fs_info->delalloc_workers);
4277 
4278 	/*
4279 	 * We can have ordered extents getting their last reference dropped from
4280 	 * the fs_info->workers queue because for async writes for data bios we
4281 	 * queue a work for that queue, at btrfs_wq_submit_bio(), that runs
4282 	 * run_one_async_done() which calls btrfs_bio_end_io() in case the bio
4283 	 * has an error, and that later function can do the final
4284 	 * btrfs_put_ordered_extent() on the ordered extent attached to the bio,
4285 	 * which adds a delayed iput for the inode. So we must flush the queue
4286 	 * so that we don't have delayed iputs after committing the current
4287 	 * transaction below and stopping the cleaner and transaction kthreads.
4288 	 */
4289 	btrfs_flush_workqueue(fs_info->workers);
4290 
4291 	/*
4292 	 * When finishing a compressed write bio we schedule a work queue item
4293 	 * to finish an ordered extent - btrfs_finish_compressed_write_work()
4294 	 * calls btrfs_finish_ordered_extent() which in turns does a call to
4295 	 * btrfs_queue_ordered_fn(), and that queues the ordered extent
4296 	 * completion either in the endio_write_workers work queue or in the
4297 	 * fs_info->endio_freespace_worker work queue. We flush those queues
4298 	 * below, so before we flush them we must flush this queue for the
4299 	 * workers of compressed writes.
4300 	 */
4301 	flush_workqueue(fs_info->compressed_write_workers);
4302 
4303 	/*
4304 	 * After we parked the cleaner kthread, ordered extents may have
4305 	 * completed and created new delayed iputs. If one of the async reclaim
4306 	 * tasks is running and in the RUN_DELAYED_IPUTS flush state, then we
4307 	 * can hang forever trying to stop it, because if a delayed iput is
4308 	 * added after it ran btrfs_run_delayed_iputs() and before it called
4309 	 * btrfs_wait_on_delayed_iputs(), it will hang forever since there is
4310 	 * no one else to run iputs.
4311 	 *
4312 	 * So wait for all ongoing ordered extents to complete and then run
4313 	 * delayed iputs. This works because once we reach this point no one
4314 	 * can create new ordered extents, but delayed iputs can still be added
4315 	 * by a reclaim worker (see comments further below).
4316 	 *
4317 	 * Also note that btrfs_wait_ordered_roots() is not safe here, because
4318 	 * it waits for BTRFS_ORDERED_COMPLETE to be set on an ordered extent,
4319 	 * but the delayed iput for the respective inode is made only when doing
4320 	 * the final btrfs_put_ordered_extent() (which must happen at
4321 	 * btrfs_finish_ordered_io() when we are unmounting).
4322 	 */
4323 	btrfs_flush_workqueue(fs_info->endio_write_workers);
4324 	/* Ordered extents for free space inodes. */
4325 	btrfs_flush_workqueue(fs_info->endio_freespace_worker);
4326 	/*
4327 	 * Run delayed iputs in case an async reclaim worker is waiting for them
4328 	 * to be run as mentioned above.
4329 	 */
4330 	btrfs_run_delayed_iputs(fs_info);
4331 
4332 	cancel_work_sync(&fs_info->async_reclaim_work);
4333 	cancel_work_sync(&fs_info->async_data_reclaim_work);
4334 	cancel_work_sync(&fs_info->preempt_reclaim_work);
4335 	cancel_work_sync(&fs_info->em_shrinker_work);
4336 
4337 	/*
4338 	 * Run delayed iputs again because an async reclaim worker may have
4339 	 * added new ones if it was flushing delalloc:
4340 	 *
4341 	 * shrink_delalloc() -> btrfs_start_delalloc_roots() ->
4342 	 *    start_delalloc_inodes() -> btrfs_add_delayed_iput()
4343 	 */
4344 	btrfs_run_delayed_iputs(fs_info);
4345 
4346 	/* There should be no more workload to generate new delayed iputs. */
4347 	set_bit(BTRFS_FS_STATE_NO_DELAYED_IPUT, &fs_info->fs_state);
4348 
4349 	/* Cancel or finish ongoing discard work */
4350 	btrfs_discard_cleanup(fs_info);
4351 
4352 	if (!sb_rdonly(fs_info->sb)) {
4353 		/*
4354 		 * The cleaner kthread is stopped, so do one final pass over
4355 		 * unused block groups.
4356 		 */
4357 		btrfs_delete_unused_bgs(fs_info);
4358 
4359 		/*
4360 		 * There might be existing delayed inode workers still running
4361 		 * and holding an empty delayed inode item. We must wait for
4362 		 * them to complete first because they can create a transaction.
4363 		 * This happens when someone calls btrfs_balance_delayed_items()
4364 		 * and then a transaction commit runs the same delayed nodes
4365 		 * before any delayed worker has done something with the nodes.
4366 		 * We must wait for any worker here and not at transaction
4367 		 * commit time since that could cause a deadlock.
4368 		 * This is a very rare case.
4369 		 */
4370 		btrfs_flush_workqueue(fs_info->delayed_workers);
4371 
4372 		ret = btrfs_commit_super(fs_info);
4373 		if (ret)
4374 			btrfs_err(fs_info, "commit super ret %d", ret);
4375 	}
4376 
4377 	kthread_stop(fs_info->transaction_kthread);
4378 	kthread_stop(fs_info->cleaner_kthread);
4379 
4380 	ASSERT(list_empty(&fs_info->delayed_iputs));
4381 	set_bit(BTRFS_FS_CLOSING_DONE, &fs_info->flags);
4382 
4383 	if (btrfs_check_quota_leak(fs_info)) {
4384 		DEBUG_WARN("qgroup reserved space leaked");
4385 		btrfs_err(fs_info, "qgroup reserved space leaked");
4386 	}
4387 
4388 	btrfs_free_qgroup_config(fs_info);
4389 	ASSERT(list_empty(&fs_info->delalloc_roots));
4390 
4391 	if (percpu_counter_sum(&fs_info->delalloc_bytes)) {
4392 		btrfs_info(fs_info, "at unmount delalloc count %lld",
4393 		       percpu_counter_sum(&fs_info->delalloc_bytes));
4394 	}
4395 
4396 	if (percpu_counter_sum(&fs_info->ordered_bytes))
4397 		btrfs_info(fs_info, "at unmount dio bytes count %lld",
4398 			   percpu_counter_sum(&fs_info->ordered_bytes));
4399 
4400 	btrfs_sysfs_remove_mounted(fs_info);
4401 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
4402 
4403 	btrfs_put_block_group_cache(fs_info);
4404 
4405 	/*
4406 	 * we must make sure there is not any read request to
4407 	 * submit after we stopping all workers.
4408 	 */
4409 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
4410 	btrfs_stop_all_workers(fs_info);
4411 
4412 	/* We shouldn't have any transaction open at this point */
4413 	warn_about_uncommitted_trans(fs_info);
4414 
4415 	clear_bit(BTRFS_FS_OPEN, &fs_info->flags);
4416 	free_root_pointers(fs_info, true);
4417 	btrfs_free_fs_roots(fs_info);
4418 
4419 	/*
4420 	 * We must free the block groups after dropping the fs_roots as we could
4421 	 * have had an IO error and have left over tree log blocks that aren't
4422 	 * cleaned up until the fs roots are freed.  This makes the block group
4423 	 * accounting appear to be wrong because there's pending reserved bytes,
4424 	 * so make sure we do the block group cleanup afterwards.
4425 	 */
4426 	btrfs_free_block_groups(fs_info);
4427 
4428 	iput(fs_info->btree_inode);
4429 
4430 	btrfs_mapping_tree_free(fs_info);
4431 }
4432 
btrfs_mark_buffer_dirty(struct btrfs_trans_handle * trans,struct extent_buffer * buf)4433 void btrfs_mark_buffer_dirty(struct btrfs_trans_handle *trans,
4434 			     struct extent_buffer *buf)
4435 {
4436 	struct btrfs_fs_info *fs_info = buf->fs_info;
4437 	u64 transid = btrfs_header_generation(buf);
4438 
4439 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
4440 	/*
4441 	 * This is a fast path so only do this check if we have sanity tests
4442 	 * enabled.  Normal people shouldn't be using unmapped buffers as dirty
4443 	 * outside of the sanity tests.
4444 	 */
4445 	if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &buf->bflags)))
4446 		return;
4447 #endif
4448 	/* This is an active transaction (its state < TRANS_STATE_UNBLOCKED). */
4449 	ASSERT(trans->transid == fs_info->generation);
4450 	btrfs_assert_tree_write_locked(buf);
4451 	if (unlikely(transid != fs_info->generation)) {
4452 		btrfs_abort_transaction(trans, -EUCLEAN);
4453 		btrfs_crit(fs_info,
4454 "dirty buffer transid mismatch, logical %llu found transid %llu running transid %llu",
4455 			   buf->start, transid, fs_info->generation);
4456 	}
4457 	set_extent_buffer_dirty(buf);
4458 }
4459 
__btrfs_btree_balance_dirty(struct btrfs_fs_info * fs_info,int flush_delayed)4460 static void __btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info,
4461 					int flush_delayed)
4462 {
4463 	/*
4464 	 * looks as though older kernels can get into trouble with
4465 	 * this code, they end up stuck in balance_dirty_pages forever
4466 	 */
4467 	int ret;
4468 
4469 	if (current->flags & PF_MEMALLOC)
4470 		return;
4471 
4472 	if (flush_delayed)
4473 		btrfs_balance_delayed_items(fs_info);
4474 
4475 	ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
4476 				     BTRFS_DIRTY_METADATA_THRESH,
4477 				     fs_info->dirty_metadata_batch);
4478 	if (ret > 0) {
4479 		balance_dirty_pages_ratelimited(fs_info->btree_inode->i_mapping);
4480 	}
4481 }
4482 
btrfs_btree_balance_dirty(struct btrfs_fs_info * fs_info)4483 void btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info)
4484 {
4485 	__btrfs_btree_balance_dirty(fs_info, 1);
4486 }
4487 
btrfs_btree_balance_dirty_nodelay(struct btrfs_fs_info * fs_info)4488 void btrfs_btree_balance_dirty_nodelay(struct btrfs_fs_info *fs_info)
4489 {
4490 	__btrfs_btree_balance_dirty(fs_info, 0);
4491 }
4492 
btrfs_error_commit_super(struct btrfs_fs_info * fs_info)4493 static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info)
4494 {
4495 	/* cleanup FS via transaction */
4496 	btrfs_cleanup_transaction(fs_info);
4497 
4498 	down_write(&fs_info->cleanup_work_sem);
4499 	up_write(&fs_info->cleanup_work_sem);
4500 }
4501 
btrfs_drop_all_logs(struct btrfs_fs_info * fs_info)4502 static void btrfs_drop_all_logs(struct btrfs_fs_info *fs_info)
4503 {
4504 	struct btrfs_root *gang[8];
4505 	u64 root_objectid = 0;
4506 	int ret;
4507 
4508 	spin_lock(&fs_info->fs_roots_radix_lock);
4509 	while ((ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
4510 					     (void **)gang, root_objectid,
4511 					     ARRAY_SIZE(gang))) != 0) {
4512 		int i;
4513 
4514 		for (i = 0; i < ret; i++)
4515 			gang[i] = btrfs_grab_root(gang[i]);
4516 		spin_unlock(&fs_info->fs_roots_radix_lock);
4517 
4518 		for (i = 0; i < ret; i++) {
4519 			if (!gang[i])
4520 				continue;
4521 			root_objectid = btrfs_root_id(gang[i]);
4522 			btrfs_free_log(NULL, gang[i]);
4523 			btrfs_put_root(gang[i]);
4524 		}
4525 		root_objectid++;
4526 		spin_lock(&fs_info->fs_roots_radix_lock);
4527 	}
4528 	spin_unlock(&fs_info->fs_roots_radix_lock);
4529 	btrfs_free_log_root_tree(NULL, fs_info);
4530 }
4531 
btrfs_destroy_ordered_extents(struct btrfs_root * root)4532 static void btrfs_destroy_ordered_extents(struct btrfs_root *root)
4533 {
4534 	struct btrfs_ordered_extent *ordered;
4535 
4536 	spin_lock(&root->ordered_extent_lock);
4537 	/*
4538 	 * This will just short circuit the ordered completion stuff which will
4539 	 * make sure the ordered extent gets properly cleaned up.
4540 	 */
4541 	list_for_each_entry(ordered, &root->ordered_extents,
4542 			    root_extent_list)
4543 		set_bit(BTRFS_ORDERED_IOERR, &ordered->flags);
4544 	spin_unlock(&root->ordered_extent_lock);
4545 }
4546 
btrfs_destroy_all_ordered_extents(struct btrfs_fs_info * fs_info)4547 static void btrfs_destroy_all_ordered_extents(struct btrfs_fs_info *fs_info)
4548 {
4549 	struct btrfs_root *root;
4550 	LIST_HEAD(splice);
4551 
4552 	spin_lock(&fs_info->ordered_root_lock);
4553 	list_splice_init(&fs_info->ordered_roots, &splice);
4554 	while (!list_empty(&splice)) {
4555 		root = list_first_entry(&splice, struct btrfs_root,
4556 					ordered_root);
4557 		list_move_tail(&root->ordered_root,
4558 			       &fs_info->ordered_roots);
4559 
4560 		spin_unlock(&fs_info->ordered_root_lock);
4561 		btrfs_destroy_ordered_extents(root);
4562 
4563 		cond_resched();
4564 		spin_lock(&fs_info->ordered_root_lock);
4565 	}
4566 	spin_unlock(&fs_info->ordered_root_lock);
4567 
4568 	/*
4569 	 * We need this here because if we've been flipped read-only we won't
4570 	 * get sync() from the umount, so we need to make sure any ordered
4571 	 * extents that haven't had their dirty pages IO start writeout yet
4572 	 * actually get run and error out properly.
4573 	 */
4574 	btrfs_wait_ordered_roots(fs_info, U64_MAX, NULL);
4575 }
4576 
btrfs_destroy_delalloc_inodes(struct btrfs_root * root)4577 static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root)
4578 {
4579 	struct btrfs_inode *btrfs_inode;
4580 	LIST_HEAD(splice);
4581 
4582 	spin_lock(&root->delalloc_lock);
4583 	list_splice_init(&root->delalloc_inodes, &splice);
4584 
4585 	while (!list_empty(&splice)) {
4586 		struct inode *inode = NULL;
4587 		btrfs_inode = list_first_entry(&splice, struct btrfs_inode,
4588 					       delalloc_inodes);
4589 		btrfs_del_delalloc_inode(btrfs_inode);
4590 		spin_unlock(&root->delalloc_lock);
4591 
4592 		/*
4593 		 * Make sure we get a live inode and that it'll not disappear
4594 		 * meanwhile.
4595 		 */
4596 		inode = igrab(&btrfs_inode->vfs_inode);
4597 		if (inode) {
4598 			unsigned int nofs_flag;
4599 
4600 			nofs_flag = memalloc_nofs_save();
4601 			invalidate_inode_pages2(inode->i_mapping);
4602 			memalloc_nofs_restore(nofs_flag);
4603 			iput(inode);
4604 		}
4605 		spin_lock(&root->delalloc_lock);
4606 	}
4607 	spin_unlock(&root->delalloc_lock);
4608 }
4609 
btrfs_destroy_all_delalloc_inodes(struct btrfs_fs_info * fs_info)4610 static void btrfs_destroy_all_delalloc_inodes(struct btrfs_fs_info *fs_info)
4611 {
4612 	struct btrfs_root *root;
4613 	LIST_HEAD(splice);
4614 
4615 	spin_lock(&fs_info->delalloc_root_lock);
4616 	list_splice_init(&fs_info->delalloc_roots, &splice);
4617 	while (!list_empty(&splice)) {
4618 		root = list_first_entry(&splice, struct btrfs_root,
4619 					 delalloc_root);
4620 		root = btrfs_grab_root(root);
4621 		BUG_ON(!root);
4622 		spin_unlock(&fs_info->delalloc_root_lock);
4623 
4624 		btrfs_destroy_delalloc_inodes(root);
4625 		btrfs_put_root(root);
4626 
4627 		spin_lock(&fs_info->delalloc_root_lock);
4628 	}
4629 	spin_unlock(&fs_info->delalloc_root_lock);
4630 }
4631 
btrfs_destroy_marked_extents(struct btrfs_fs_info * fs_info,struct extent_io_tree * dirty_pages,int mark)4632 static void btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
4633 					 struct extent_io_tree *dirty_pages,
4634 					 int mark)
4635 {
4636 	struct extent_buffer *eb;
4637 	u64 start = 0;
4638 	u64 end;
4639 
4640 	while (btrfs_find_first_extent_bit(dirty_pages, start, &start, &end,
4641 					   mark, NULL)) {
4642 		btrfs_clear_extent_bit(dirty_pages, start, end, mark, NULL);
4643 		while (start <= end) {
4644 			eb = find_extent_buffer(fs_info, start);
4645 			start += fs_info->nodesize;
4646 			if (!eb)
4647 				continue;
4648 
4649 			btrfs_tree_lock(eb);
4650 			wait_on_extent_buffer_writeback(eb);
4651 			btrfs_clear_buffer_dirty(NULL, eb);
4652 			btrfs_tree_unlock(eb);
4653 
4654 			free_extent_buffer_stale(eb);
4655 		}
4656 	}
4657 }
4658 
btrfs_destroy_pinned_extent(struct btrfs_fs_info * fs_info,struct extent_io_tree * unpin)4659 static void btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
4660 					struct extent_io_tree *unpin)
4661 {
4662 	u64 start;
4663 	u64 end;
4664 
4665 	while (1) {
4666 		struct extent_state *cached_state = NULL;
4667 
4668 		/*
4669 		 * The btrfs_finish_extent_commit() may get the same range as
4670 		 * ours between find_first_extent_bit and clear_extent_dirty.
4671 		 * Hence, hold the unused_bg_unpin_mutex to avoid double unpin
4672 		 * the same extent range.
4673 		 */
4674 		mutex_lock(&fs_info->unused_bg_unpin_mutex);
4675 		if (!btrfs_find_first_extent_bit(unpin, 0, &start, &end,
4676 						 EXTENT_DIRTY, &cached_state)) {
4677 			mutex_unlock(&fs_info->unused_bg_unpin_mutex);
4678 			break;
4679 		}
4680 
4681 		btrfs_clear_extent_dirty(unpin, start, end, &cached_state);
4682 		btrfs_free_extent_state(cached_state);
4683 		btrfs_error_unpin_extent_range(fs_info, start, end);
4684 		mutex_unlock(&fs_info->unused_bg_unpin_mutex);
4685 		cond_resched();
4686 	}
4687 }
4688 
btrfs_cleanup_bg_io(struct btrfs_block_group * cache)4689 static void btrfs_cleanup_bg_io(struct btrfs_block_group *cache)
4690 {
4691 	struct inode *inode;
4692 
4693 	inode = cache->io_ctl.inode;
4694 	if (inode) {
4695 		unsigned int nofs_flag;
4696 
4697 		nofs_flag = memalloc_nofs_save();
4698 		invalidate_inode_pages2(inode->i_mapping);
4699 		memalloc_nofs_restore(nofs_flag);
4700 
4701 		BTRFS_I(inode)->generation = 0;
4702 		cache->io_ctl.inode = NULL;
4703 		iput(inode);
4704 	}
4705 	ASSERT(cache->io_ctl.pages == NULL);
4706 	btrfs_put_block_group(cache);
4707 }
4708 
btrfs_cleanup_dirty_bgs(struct btrfs_transaction * cur_trans,struct btrfs_fs_info * fs_info)4709 void btrfs_cleanup_dirty_bgs(struct btrfs_transaction *cur_trans,
4710 			     struct btrfs_fs_info *fs_info)
4711 {
4712 	struct btrfs_block_group *cache;
4713 
4714 	spin_lock(&cur_trans->dirty_bgs_lock);
4715 	while (!list_empty(&cur_trans->dirty_bgs)) {
4716 		cache = list_first_entry(&cur_trans->dirty_bgs,
4717 					 struct btrfs_block_group,
4718 					 dirty_list);
4719 
4720 		if (!list_empty(&cache->io_list)) {
4721 			spin_unlock(&cur_trans->dirty_bgs_lock);
4722 			list_del_init(&cache->io_list);
4723 			btrfs_cleanup_bg_io(cache);
4724 			spin_lock(&cur_trans->dirty_bgs_lock);
4725 		}
4726 
4727 		list_del_init(&cache->dirty_list);
4728 		spin_lock(&cache->lock);
4729 		cache->disk_cache_state = BTRFS_DC_ERROR;
4730 		spin_unlock(&cache->lock);
4731 
4732 		spin_unlock(&cur_trans->dirty_bgs_lock);
4733 		btrfs_put_block_group(cache);
4734 		btrfs_dec_delayed_refs_rsv_bg_updates(fs_info);
4735 		spin_lock(&cur_trans->dirty_bgs_lock);
4736 	}
4737 	spin_unlock(&cur_trans->dirty_bgs_lock);
4738 
4739 	/*
4740 	 * Refer to the definition of io_bgs member for details why it's safe
4741 	 * to use it without any locking
4742 	 */
4743 	while (!list_empty(&cur_trans->io_bgs)) {
4744 		cache = list_first_entry(&cur_trans->io_bgs,
4745 					 struct btrfs_block_group,
4746 					 io_list);
4747 
4748 		list_del_init(&cache->io_list);
4749 		spin_lock(&cache->lock);
4750 		cache->disk_cache_state = BTRFS_DC_ERROR;
4751 		spin_unlock(&cache->lock);
4752 		btrfs_cleanup_bg_io(cache);
4753 	}
4754 }
4755 
btrfs_free_all_qgroup_pertrans(struct btrfs_fs_info * fs_info)4756 static void btrfs_free_all_qgroup_pertrans(struct btrfs_fs_info *fs_info)
4757 {
4758 	struct btrfs_root *gang[8];
4759 	int i;
4760 	int ret;
4761 
4762 	spin_lock(&fs_info->fs_roots_radix_lock);
4763 	while (1) {
4764 		ret = radix_tree_gang_lookup_tag(&fs_info->fs_roots_radix,
4765 						 (void **)gang, 0,
4766 						 ARRAY_SIZE(gang),
4767 						 BTRFS_ROOT_TRANS_TAG);
4768 		if (ret == 0)
4769 			break;
4770 		for (i = 0; i < ret; i++) {
4771 			struct btrfs_root *root = gang[i];
4772 
4773 			btrfs_qgroup_free_meta_all_pertrans(root);
4774 			radix_tree_tag_clear(&fs_info->fs_roots_radix,
4775 					(unsigned long)btrfs_root_id(root),
4776 					BTRFS_ROOT_TRANS_TAG);
4777 		}
4778 	}
4779 	spin_unlock(&fs_info->fs_roots_radix_lock);
4780 }
4781 
btrfs_cleanup_one_transaction(struct btrfs_transaction * cur_trans)4782 void btrfs_cleanup_one_transaction(struct btrfs_transaction *cur_trans)
4783 {
4784 	struct btrfs_fs_info *fs_info = cur_trans->fs_info;
4785 	struct btrfs_device *dev, *tmp;
4786 
4787 	btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
4788 	ASSERT(list_empty(&cur_trans->dirty_bgs));
4789 	ASSERT(list_empty(&cur_trans->io_bgs));
4790 
4791 	list_for_each_entry_safe(dev, tmp, &cur_trans->dev_update_list,
4792 				 post_commit_list) {
4793 		list_del_init(&dev->post_commit_list);
4794 	}
4795 
4796 	btrfs_destroy_delayed_refs(cur_trans);
4797 
4798 	cur_trans->state = TRANS_STATE_COMMIT_START;
4799 	wake_up(&fs_info->transaction_blocked_wait);
4800 
4801 	cur_trans->state = TRANS_STATE_UNBLOCKED;
4802 	wake_up(&fs_info->transaction_wait);
4803 
4804 	btrfs_destroy_marked_extents(fs_info, &cur_trans->dirty_pages,
4805 				     EXTENT_DIRTY);
4806 	btrfs_destroy_pinned_extent(fs_info, &cur_trans->pinned_extents);
4807 
4808 	cur_trans->state =TRANS_STATE_COMPLETED;
4809 	wake_up(&cur_trans->commit_wait);
4810 }
4811 
btrfs_cleanup_transaction(struct btrfs_fs_info * fs_info)4812 static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info)
4813 {
4814 	struct btrfs_transaction *t;
4815 
4816 	mutex_lock(&fs_info->transaction_kthread_mutex);
4817 
4818 	spin_lock(&fs_info->trans_lock);
4819 	while (!list_empty(&fs_info->trans_list)) {
4820 		t = list_first_entry(&fs_info->trans_list,
4821 				     struct btrfs_transaction, list);
4822 		if (t->state >= TRANS_STATE_COMMIT_PREP) {
4823 			refcount_inc(&t->use_count);
4824 			spin_unlock(&fs_info->trans_lock);
4825 			btrfs_wait_for_commit(fs_info, t->transid);
4826 			btrfs_put_transaction(t);
4827 			spin_lock(&fs_info->trans_lock);
4828 			continue;
4829 		}
4830 		if (t == fs_info->running_transaction) {
4831 			t->state = TRANS_STATE_COMMIT_DOING;
4832 			spin_unlock(&fs_info->trans_lock);
4833 			/*
4834 			 * We wait for 0 num_writers since we don't hold a trans
4835 			 * handle open currently for this transaction.
4836 			 */
4837 			wait_event(t->writer_wait,
4838 				   atomic_read(&t->num_writers) == 0);
4839 		} else {
4840 			spin_unlock(&fs_info->trans_lock);
4841 		}
4842 		btrfs_cleanup_one_transaction(t);
4843 
4844 		spin_lock(&fs_info->trans_lock);
4845 		if (t == fs_info->running_transaction)
4846 			fs_info->running_transaction = NULL;
4847 		list_del_init(&t->list);
4848 		spin_unlock(&fs_info->trans_lock);
4849 
4850 		btrfs_put_transaction(t);
4851 		trace_btrfs_transaction_commit(fs_info);
4852 		spin_lock(&fs_info->trans_lock);
4853 	}
4854 	spin_unlock(&fs_info->trans_lock);
4855 	btrfs_destroy_all_ordered_extents(fs_info);
4856 	btrfs_destroy_delayed_inodes(fs_info);
4857 	btrfs_assert_delayed_root_empty(fs_info);
4858 	btrfs_destroy_all_delalloc_inodes(fs_info);
4859 	btrfs_drop_all_logs(fs_info);
4860 	btrfs_free_all_qgroup_pertrans(fs_info);
4861 	mutex_unlock(&fs_info->transaction_kthread_mutex);
4862 
4863 	return 0;
4864 }
4865 
btrfs_init_root_free_objectid(struct btrfs_root * root)4866 int btrfs_init_root_free_objectid(struct btrfs_root *root)
4867 {
4868 	BTRFS_PATH_AUTO_FREE(path);
4869 	int ret;
4870 	struct extent_buffer *l;
4871 	struct btrfs_key search_key;
4872 	struct btrfs_key found_key;
4873 	int slot;
4874 
4875 	path = btrfs_alloc_path();
4876 	if (!path)
4877 		return -ENOMEM;
4878 
4879 	search_key.objectid = BTRFS_LAST_FREE_OBJECTID;
4880 	search_key.type = -1;
4881 	search_key.offset = (u64)-1;
4882 	ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
4883 	if (ret < 0)
4884 		return ret;
4885 	if (unlikely(ret == 0)) {
4886 		/*
4887 		 * Key with offset -1 found, there would have to exist a root
4888 		 * with such id, but this is out of valid range.
4889 		 */
4890 		return -EUCLEAN;
4891 	}
4892 	if (path->slots[0] > 0) {
4893 		slot = path->slots[0] - 1;
4894 		l = path->nodes[0];
4895 		btrfs_item_key_to_cpu(l, &found_key, slot);
4896 		root->free_objectid = max_t(u64, found_key.objectid + 1,
4897 					    BTRFS_FIRST_FREE_OBJECTID);
4898 	} else {
4899 		root->free_objectid = BTRFS_FIRST_FREE_OBJECTID;
4900 	}
4901 
4902 	return 0;
4903 }
4904 
btrfs_get_free_objectid(struct btrfs_root * root,u64 * objectid)4905 int btrfs_get_free_objectid(struct btrfs_root *root, u64 *objectid)
4906 {
4907 	int ret;
4908 	mutex_lock(&root->objectid_mutex);
4909 
4910 	if (unlikely(root->free_objectid >= BTRFS_LAST_FREE_OBJECTID)) {
4911 		btrfs_warn(root->fs_info,
4912 			   "the objectid of root %llu reaches its highest value",
4913 			   btrfs_root_id(root));
4914 		ret = -ENOSPC;
4915 		goto out;
4916 	}
4917 
4918 	*objectid = root->free_objectid++;
4919 	ret = 0;
4920 out:
4921 	mutex_unlock(&root->objectid_mutex);
4922 	return ret;
4923 }
4924