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