xref: /openbmc/linux/fs/btrfs/super.c (revision 5c11adcc383a94cacd652461c9435bf7a5c53c9c)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2007 Oracle.  All rights reserved.
4  */
5 
6 #include <linux/blkdev.h>
7 #include <linux/module.h>
8 #include <linux/fs.h>
9 #include <linux/pagemap.h>
10 #include <linux/highmem.h>
11 #include <linux/time.h>
12 #include <linux/init.h>
13 #include <linux/seq_file.h>
14 #include <linux/string.h>
15 #include <linux/backing-dev.h>
16 #include <linux/mount.h>
17 #include <linux/writeback.h>
18 #include <linux/statfs.h>
19 #include <linux/compat.h>
20 #include <linux/parser.h>
21 #include <linux/ctype.h>
22 #include <linux/namei.h>
23 #include <linux/miscdevice.h>
24 #include <linux/magic.h>
25 #include <linux/slab.h>
26 #include <linux/ratelimit.h>
27 #include <linux/crc32c.h>
28 #include <linux/btrfs.h>
29 #include "messages.h"
30 #include "delayed-inode.h"
31 #include "ctree.h"
32 #include "disk-io.h"
33 #include "transaction.h"
34 #include "btrfs_inode.h"
35 #include "print-tree.h"
36 #include "props.h"
37 #include "xattr.h"
38 #include "volumes.h"
39 #include "export.h"
40 #include "compression.h"
41 #include "rcu-string.h"
42 #include "dev-replace.h"
43 #include "free-space-cache.h"
44 #include "backref.h"
45 #include "space-info.h"
46 #include "sysfs.h"
47 #include "zoned.h"
48 #include "tests/btrfs-tests.h"
49 #include "block-group.h"
50 #include "discard.h"
51 #include "qgroup.h"
52 #include "raid56.h"
53 #include "fs.h"
54 #include "accessors.h"
55 #include "defrag.h"
56 #include "dir-item.h"
57 #include "ioctl.h"
58 #include "scrub.h"
59 #include "verity.h"
60 #define CREATE_TRACE_POINTS
61 #include <trace/events/btrfs.h>
62 
63 static const struct super_operations btrfs_super_ops;
64 
65 /*
66  * Types for mounting the default subvolume and a subvolume explicitly
67  * requested by subvol=/path. That way the callchain is straightforward and we
68  * don't have to play tricks with the mount options and recursive calls to
69  * btrfs_mount.
70  *
71  * The new btrfs_root_fs_type also servers as a tag for the bdev_holder.
72  */
73 static struct file_system_type btrfs_fs_type;
74 static struct file_system_type btrfs_root_fs_type;
75 
76 static int btrfs_remount(struct super_block *sb, int *flags, char *data);
77 
78 static void btrfs_put_super(struct super_block *sb)
79 {
80 	close_ctree(btrfs_sb(sb));
81 }
82 
83 enum {
84 	Opt_acl, Opt_noacl,
85 	Opt_clear_cache,
86 	Opt_commit_interval,
87 	Opt_compress,
88 	Opt_compress_force,
89 	Opt_compress_force_type,
90 	Opt_compress_type,
91 	Opt_degraded,
92 	Opt_device,
93 	Opt_fatal_errors,
94 	Opt_flushoncommit, Opt_noflushoncommit,
95 	Opt_max_inline,
96 	Opt_barrier, Opt_nobarrier,
97 	Opt_datacow, Opt_nodatacow,
98 	Opt_datasum, Opt_nodatasum,
99 	Opt_defrag, Opt_nodefrag,
100 	Opt_discard, Opt_nodiscard,
101 	Opt_discard_mode,
102 	Opt_norecovery,
103 	Opt_ratio,
104 	Opt_rescan_uuid_tree,
105 	Opt_skip_balance,
106 	Opt_space_cache, Opt_no_space_cache,
107 	Opt_space_cache_version,
108 	Opt_ssd, Opt_nossd,
109 	Opt_ssd_spread, Opt_nossd_spread,
110 	Opt_subvol,
111 	Opt_subvol_empty,
112 	Opt_subvolid,
113 	Opt_thread_pool,
114 	Opt_treelog, Opt_notreelog,
115 	Opt_user_subvol_rm_allowed,
116 
117 	/* Rescue options */
118 	Opt_rescue,
119 	Opt_usebackuproot,
120 	Opt_nologreplay,
121 	Opt_ignorebadroots,
122 	Opt_ignoredatacsums,
123 	Opt_rescue_all,
124 
125 	/* Deprecated options */
126 	Opt_recovery,
127 	Opt_inode_cache, Opt_noinode_cache,
128 
129 	/* Debugging options */
130 	Opt_check_integrity,
131 	Opt_check_integrity_including_extent_data,
132 	Opt_check_integrity_print_mask,
133 	Opt_enospc_debug, Opt_noenospc_debug,
134 #ifdef CONFIG_BTRFS_DEBUG
135 	Opt_fragment_data, Opt_fragment_metadata, Opt_fragment_all,
136 #endif
137 #ifdef CONFIG_BTRFS_FS_REF_VERIFY
138 	Opt_ref_verify,
139 #endif
140 	Opt_err,
141 };
142 
143 static const match_table_t tokens = {
144 	{Opt_acl, "acl"},
145 	{Opt_noacl, "noacl"},
146 	{Opt_clear_cache, "clear_cache"},
147 	{Opt_commit_interval, "commit=%u"},
148 	{Opt_compress, "compress"},
149 	{Opt_compress_type, "compress=%s"},
150 	{Opt_compress_force, "compress-force"},
151 	{Opt_compress_force_type, "compress-force=%s"},
152 	{Opt_degraded, "degraded"},
153 	{Opt_device, "device=%s"},
154 	{Opt_fatal_errors, "fatal_errors=%s"},
155 	{Opt_flushoncommit, "flushoncommit"},
156 	{Opt_noflushoncommit, "noflushoncommit"},
157 	{Opt_inode_cache, "inode_cache"},
158 	{Opt_noinode_cache, "noinode_cache"},
159 	{Opt_max_inline, "max_inline=%s"},
160 	{Opt_barrier, "barrier"},
161 	{Opt_nobarrier, "nobarrier"},
162 	{Opt_datacow, "datacow"},
163 	{Opt_nodatacow, "nodatacow"},
164 	{Opt_datasum, "datasum"},
165 	{Opt_nodatasum, "nodatasum"},
166 	{Opt_defrag, "autodefrag"},
167 	{Opt_nodefrag, "noautodefrag"},
168 	{Opt_discard, "discard"},
169 	{Opt_discard_mode, "discard=%s"},
170 	{Opt_nodiscard, "nodiscard"},
171 	{Opt_norecovery, "norecovery"},
172 	{Opt_ratio, "metadata_ratio=%u"},
173 	{Opt_rescan_uuid_tree, "rescan_uuid_tree"},
174 	{Opt_skip_balance, "skip_balance"},
175 	{Opt_space_cache, "space_cache"},
176 	{Opt_no_space_cache, "nospace_cache"},
177 	{Opt_space_cache_version, "space_cache=%s"},
178 	{Opt_ssd, "ssd"},
179 	{Opt_nossd, "nossd"},
180 	{Opt_ssd_spread, "ssd_spread"},
181 	{Opt_nossd_spread, "nossd_spread"},
182 	{Opt_subvol, "subvol=%s"},
183 	{Opt_subvol_empty, "subvol="},
184 	{Opt_subvolid, "subvolid=%s"},
185 	{Opt_thread_pool, "thread_pool=%u"},
186 	{Opt_treelog, "treelog"},
187 	{Opt_notreelog, "notreelog"},
188 	{Opt_user_subvol_rm_allowed, "user_subvol_rm_allowed"},
189 
190 	/* Rescue options */
191 	{Opt_rescue, "rescue=%s"},
192 	/* Deprecated, with alias rescue=nologreplay */
193 	{Opt_nologreplay, "nologreplay"},
194 	/* Deprecated, with alias rescue=usebackuproot */
195 	{Opt_usebackuproot, "usebackuproot"},
196 
197 	/* Deprecated options */
198 	{Opt_recovery, "recovery"},
199 
200 	/* Debugging options */
201 	{Opt_check_integrity, "check_int"},
202 	{Opt_check_integrity_including_extent_data, "check_int_data"},
203 	{Opt_check_integrity_print_mask, "check_int_print_mask=%u"},
204 	{Opt_enospc_debug, "enospc_debug"},
205 	{Opt_noenospc_debug, "noenospc_debug"},
206 #ifdef CONFIG_BTRFS_DEBUG
207 	{Opt_fragment_data, "fragment=data"},
208 	{Opt_fragment_metadata, "fragment=metadata"},
209 	{Opt_fragment_all, "fragment=all"},
210 #endif
211 #ifdef CONFIG_BTRFS_FS_REF_VERIFY
212 	{Opt_ref_verify, "ref_verify"},
213 #endif
214 	{Opt_err, NULL},
215 };
216 
217 static const match_table_t rescue_tokens = {
218 	{Opt_usebackuproot, "usebackuproot"},
219 	{Opt_nologreplay, "nologreplay"},
220 	{Opt_ignorebadroots, "ignorebadroots"},
221 	{Opt_ignorebadroots, "ibadroots"},
222 	{Opt_ignoredatacsums, "ignoredatacsums"},
223 	{Opt_ignoredatacsums, "idatacsums"},
224 	{Opt_rescue_all, "all"},
225 	{Opt_err, NULL},
226 };
227 
228 static bool check_ro_option(struct btrfs_fs_info *fs_info, unsigned long opt,
229 			    const char *opt_name)
230 {
231 	if (fs_info->mount_opt & opt) {
232 		btrfs_err(fs_info, "%s must be used with ro mount option",
233 			  opt_name);
234 		return true;
235 	}
236 	return false;
237 }
238 
239 static int parse_rescue_options(struct btrfs_fs_info *info, const char *options)
240 {
241 	char *opts;
242 	char *orig;
243 	char *p;
244 	substring_t args[MAX_OPT_ARGS];
245 	int ret = 0;
246 
247 	opts = kstrdup(options, GFP_KERNEL);
248 	if (!opts)
249 		return -ENOMEM;
250 	orig = opts;
251 
252 	while ((p = strsep(&opts, ":")) != NULL) {
253 		int token;
254 
255 		if (!*p)
256 			continue;
257 		token = match_token(p, rescue_tokens, args);
258 		switch (token){
259 		case Opt_usebackuproot:
260 			btrfs_info(info,
261 				   "trying to use backup root at mount time");
262 			btrfs_set_opt(info->mount_opt, USEBACKUPROOT);
263 			break;
264 		case Opt_nologreplay:
265 			btrfs_set_and_info(info, NOLOGREPLAY,
266 					   "disabling log replay at mount time");
267 			break;
268 		case Opt_ignorebadroots:
269 			btrfs_set_and_info(info, IGNOREBADROOTS,
270 					   "ignoring bad roots");
271 			break;
272 		case Opt_ignoredatacsums:
273 			btrfs_set_and_info(info, IGNOREDATACSUMS,
274 					   "ignoring data csums");
275 			break;
276 		case Opt_rescue_all:
277 			btrfs_info(info, "enabling all of the rescue options");
278 			btrfs_set_and_info(info, IGNOREDATACSUMS,
279 					   "ignoring data csums");
280 			btrfs_set_and_info(info, IGNOREBADROOTS,
281 					   "ignoring bad roots");
282 			btrfs_set_and_info(info, NOLOGREPLAY,
283 					   "disabling log replay at mount time");
284 			break;
285 		case Opt_err:
286 			btrfs_info(info, "unrecognized rescue option '%s'", p);
287 			ret = -EINVAL;
288 			goto out;
289 		default:
290 			break;
291 		}
292 
293 	}
294 out:
295 	kfree(orig);
296 	return ret;
297 }
298 
299 /*
300  * Regular mount options parser.  Everything that is needed only when
301  * reading in a new superblock is parsed here.
302  * XXX JDM: This needs to be cleaned up for remount.
303  */
304 int btrfs_parse_options(struct btrfs_fs_info *info, char *options,
305 			unsigned long new_flags)
306 {
307 	substring_t args[MAX_OPT_ARGS];
308 	char *p, *num;
309 	int intarg;
310 	int ret = 0;
311 	char *compress_type;
312 	bool compress_force = false;
313 	enum btrfs_compression_type saved_compress_type;
314 	int saved_compress_level;
315 	bool saved_compress_force;
316 	int no_compress = 0;
317 	const bool remounting = test_bit(BTRFS_FS_STATE_REMOUNTING, &info->fs_state);
318 
319 	if (btrfs_fs_compat_ro(info, FREE_SPACE_TREE))
320 		btrfs_set_opt(info->mount_opt, FREE_SPACE_TREE);
321 	else if (btrfs_free_space_cache_v1_active(info)) {
322 		if (btrfs_is_zoned(info)) {
323 			btrfs_info(info,
324 			"zoned: clearing existing space cache");
325 			btrfs_set_super_cache_generation(info->super_copy, 0);
326 		} else {
327 			btrfs_set_opt(info->mount_opt, SPACE_CACHE);
328 		}
329 	}
330 
331 	/*
332 	 * Even the options are empty, we still need to do extra check
333 	 * against new flags
334 	 */
335 	if (!options)
336 		goto check;
337 
338 	while ((p = strsep(&options, ",")) != NULL) {
339 		int token;
340 		if (!*p)
341 			continue;
342 
343 		token = match_token(p, tokens, args);
344 		switch (token) {
345 		case Opt_degraded:
346 			btrfs_info(info, "allowing degraded mounts");
347 			btrfs_set_opt(info->mount_opt, DEGRADED);
348 			break;
349 		case Opt_subvol:
350 		case Opt_subvol_empty:
351 		case Opt_subvolid:
352 		case Opt_device:
353 			/*
354 			 * These are parsed by btrfs_parse_subvol_options or
355 			 * btrfs_parse_device_options and can be ignored here.
356 			 */
357 			break;
358 		case Opt_nodatasum:
359 			btrfs_set_and_info(info, NODATASUM,
360 					   "setting nodatasum");
361 			break;
362 		case Opt_datasum:
363 			if (btrfs_test_opt(info, NODATASUM)) {
364 				if (btrfs_test_opt(info, NODATACOW))
365 					btrfs_info(info,
366 						   "setting datasum, datacow enabled");
367 				else
368 					btrfs_info(info, "setting datasum");
369 			}
370 			btrfs_clear_opt(info->mount_opt, NODATACOW);
371 			btrfs_clear_opt(info->mount_opt, NODATASUM);
372 			break;
373 		case Opt_nodatacow:
374 			if (!btrfs_test_opt(info, NODATACOW)) {
375 				if (!btrfs_test_opt(info, COMPRESS) ||
376 				    !btrfs_test_opt(info, FORCE_COMPRESS)) {
377 					btrfs_info(info,
378 						   "setting nodatacow, compression disabled");
379 				} else {
380 					btrfs_info(info, "setting nodatacow");
381 				}
382 			}
383 			btrfs_clear_opt(info->mount_opt, COMPRESS);
384 			btrfs_clear_opt(info->mount_opt, FORCE_COMPRESS);
385 			btrfs_set_opt(info->mount_opt, NODATACOW);
386 			btrfs_set_opt(info->mount_opt, NODATASUM);
387 			break;
388 		case Opt_datacow:
389 			btrfs_clear_and_info(info, NODATACOW,
390 					     "setting datacow");
391 			break;
392 		case Opt_compress_force:
393 		case Opt_compress_force_type:
394 			compress_force = true;
395 			fallthrough;
396 		case Opt_compress:
397 		case Opt_compress_type:
398 			saved_compress_type = btrfs_test_opt(info,
399 							     COMPRESS) ?
400 				info->compress_type : BTRFS_COMPRESS_NONE;
401 			saved_compress_force =
402 				btrfs_test_opt(info, FORCE_COMPRESS);
403 			saved_compress_level = info->compress_level;
404 			if (token == Opt_compress ||
405 			    token == Opt_compress_force ||
406 			    strncmp(args[0].from, "zlib", 4) == 0) {
407 				compress_type = "zlib";
408 
409 				info->compress_type = BTRFS_COMPRESS_ZLIB;
410 				info->compress_level = BTRFS_ZLIB_DEFAULT_LEVEL;
411 				/*
412 				 * args[0] contains uninitialized data since
413 				 * for these tokens we don't expect any
414 				 * parameter.
415 				 */
416 				if (token != Opt_compress &&
417 				    token != Opt_compress_force)
418 					info->compress_level =
419 					  btrfs_compress_str2level(
420 							BTRFS_COMPRESS_ZLIB,
421 							args[0].from + 4);
422 				btrfs_set_opt(info->mount_opt, COMPRESS);
423 				btrfs_clear_opt(info->mount_opt, NODATACOW);
424 				btrfs_clear_opt(info->mount_opt, NODATASUM);
425 				no_compress = 0;
426 			} else if (strncmp(args[0].from, "lzo", 3) == 0) {
427 				compress_type = "lzo";
428 				info->compress_type = BTRFS_COMPRESS_LZO;
429 				info->compress_level = 0;
430 				btrfs_set_opt(info->mount_opt, COMPRESS);
431 				btrfs_clear_opt(info->mount_opt, NODATACOW);
432 				btrfs_clear_opt(info->mount_opt, NODATASUM);
433 				btrfs_set_fs_incompat(info, COMPRESS_LZO);
434 				no_compress = 0;
435 			} else if (strncmp(args[0].from, "zstd", 4) == 0) {
436 				compress_type = "zstd";
437 				info->compress_type = BTRFS_COMPRESS_ZSTD;
438 				info->compress_level =
439 					btrfs_compress_str2level(
440 							 BTRFS_COMPRESS_ZSTD,
441 							 args[0].from + 4);
442 				btrfs_set_opt(info->mount_opt, COMPRESS);
443 				btrfs_clear_opt(info->mount_opt, NODATACOW);
444 				btrfs_clear_opt(info->mount_opt, NODATASUM);
445 				btrfs_set_fs_incompat(info, COMPRESS_ZSTD);
446 				no_compress = 0;
447 			} else if (strncmp(args[0].from, "no", 2) == 0) {
448 				compress_type = "no";
449 				info->compress_level = 0;
450 				info->compress_type = 0;
451 				btrfs_clear_opt(info->mount_opt, COMPRESS);
452 				btrfs_clear_opt(info->mount_opt, FORCE_COMPRESS);
453 				compress_force = false;
454 				no_compress++;
455 			} else {
456 				btrfs_err(info, "unrecognized compression value %s",
457 					  args[0].from);
458 				ret = -EINVAL;
459 				goto out;
460 			}
461 
462 			if (compress_force) {
463 				btrfs_set_opt(info->mount_opt, FORCE_COMPRESS);
464 			} else {
465 				/*
466 				 * If we remount from compress-force=xxx to
467 				 * compress=xxx, we need clear FORCE_COMPRESS
468 				 * flag, otherwise, there is no way for users
469 				 * to disable forcible compression separately.
470 				 */
471 				btrfs_clear_opt(info->mount_opt, FORCE_COMPRESS);
472 			}
473 			if (no_compress == 1) {
474 				btrfs_info(info, "use no compression");
475 			} else if ((info->compress_type != saved_compress_type) ||
476 				   (compress_force != saved_compress_force) ||
477 				   (info->compress_level != saved_compress_level)) {
478 				btrfs_info(info, "%s %s compression, level %d",
479 					   (compress_force) ? "force" : "use",
480 					   compress_type, info->compress_level);
481 			}
482 			compress_force = false;
483 			break;
484 		case Opt_ssd:
485 			btrfs_set_and_info(info, SSD,
486 					   "enabling ssd optimizations");
487 			btrfs_clear_opt(info->mount_opt, NOSSD);
488 			break;
489 		case Opt_ssd_spread:
490 			btrfs_set_and_info(info, SSD,
491 					   "enabling ssd optimizations");
492 			btrfs_set_and_info(info, SSD_SPREAD,
493 					   "using spread ssd allocation scheme");
494 			btrfs_clear_opt(info->mount_opt, NOSSD);
495 			break;
496 		case Opt_nossd:
497 			btrfs_set_opt(info->mount_opt, NOSSD);
498 			btrfs_clear_and_info(info, SSD,
499 					     "not using ssd optimizations");
500 			fallthrough;
501 		case Opt_nossd_spread:
502 			btrfs_clear_and_info(info, SSD_SPREAD,
503 					     "not using spread ssd allocation scheme");
504 			break;
505 		case Opt_barrier:
506 			btrfs_clear_and_info(info, NOBARRIER,
507 					     "turning on barriers");
508 			break;
509 		case Opt_nobarrier:
510 			btrfs_set_and_info(info, NOBARRIER,
511 					   "turning off barriers");
512 			break;
513 		case Opt_thread_pool:
514 			ret = match_int(&args[0], &intarg);
515 			if (ret) {
516 				btrfs_err(info, "unrecognized thread_pool value %s",
517 					  args[0].from);
518 				goto out;
519 			} else if (intarg == 0) {
520 				btrfs_err(info, "invalid value 0 for thread_pool");
521 				ret = -EINVAL;
522 				goto out;
523 			}
524 			info->thread_pool_size = intarg;
525 			break;
526 		case Opt_max_inline:
527 			num = match_strdup(&args[0]);
528 			if (num) {
529 				info->max_inline = memparse(num, NULL);
530 				kfree(num);
531 
532 				if (info->max_inline) {
533 					info->max_inline = min_t(u64,
534 						info->max_inline,
535 						info->sectorsize);
536 				}
537 				btrfs_info(info, "max_inline at %llu",
538 					   info->max_inline);
539 			} else {
540 				ret = -ENOMEM;
541 				goto out;
542 			}
543 			break;
544 		case Opt_acl:
545 #ifdef CONFIG_BTRFS_FS_POSIX_ACL
546 			info->sb->s_flags |= SB_POSIXACL;
547 			break;
548 #else
549 			btrfs_err(info, "support for ACL not compiled in!");
550 			ret = -EINVAL;
551 			goto out;
552 #endif
553 		case Opt_noacl:
554 			info->sb->s_flags &= ~SB_POSIXACL;
555 			break;
556 		case Opt_notreelog:
557 			btrfs_set_and_info(info, NOTREELOG,
558 					   "disabling tree log");
559 			break;
560 		case Opt_treelog:
561 			btrfs_clear_and_info(info, NOTREELOG,
562 					     "enabling tree log");
563 			break;
564 		case Opt_norecovery:
565 		case Opt_nologreplay:
566 			btrfs_warn(info,
567 		"'nologreplay' is deprecated, use 'rescue=nologreplay' instead");
568 			btrfs_set_and_info(info, NOLOGREPLAY,
569 					   "disabling log replay at mount time");
570 			break;
571 		case Opt_flushoncommit:
572 			btrfs_set_and_info(info, FLUSHONCOMMIT,
573 					   "turning on flush-on-commit");
574 			break;
575 		case Opt_noflushoncommit:
576 			btrfs_clear_and_info(info, FLUSHONCOMMIT,
577 					     "turning off flush-on-commit");
578 			break;
579 		case Opt_ratio:
580 			ret = match_int(&args[0], &intarg);
581 			if (ret) {
582 				btrfs_err(info, "unrecognized metadata_ratio value %s",
583 					  args[0].from);
584 				goto out;
585 			}
586 			info->metadata_ratio = intarg;
587 			btrfs_info(info, "metadata ratio %u",
588 				   info->metadata_ratio);
589 			break;
590 		case Opt_discard:
591 		case Opt_discard_mode:
592 			if (token == Opt_discard ||
593 			    strcmp(args[0].from, "sync") == 0) {
594 				btrfs_clear_opt(info->mount_opt, DISCARD_ASYNC);
595 				btrfs_set_and_info(info, DISCARD_SYNC,
596 						   "turning on sync discard");
597 			} else if (strcmp(args[0].from, "async") == 0) {
598 				btrfs_clear_opt(info->mount_opt, DISCARD_SYNC);
599 				btrfs_set_and_info(info, DISCARD_ASYNC,
600 						   "turning on async discard");
601 			} else {
602 				btrfs_err(info, "unrecognized discard mode value %s",
603 					  args[0].from);
604 				ret = -EINVAL;
605 				goto out;
606 			}
607 			btrfs_clear_opt(info->mount_opt, NODISCARD);
608 			break;
609 		case Opt_nodiscard:
610 			btrfs_clear_and_info(info, DISCARD_SYNC,
611 					     "turning off discard");
612 			btrfs_clear_and_info(info, DISCARD_ASYNC,
613 					     "turning off async discard");
614 			btrfs_set_opt(info->mount_opt, NODISCARD);
615 			break;
616 		case Opt_space_cache:
617 		case Opt_space_cache_version:
618 			/*
619 			 * We already set FREE_SPACE_TREE above because we have
620 			 * compat_ro(FREE_SPACE_TREE) set, and we aren't going
621 			 * to allow v1 to be set for extent tree v2, simply
622 			 * ignore this setting if we're extent tree v2.
623 			 */
624 			if (btrfs_fs_incompat(info, EXTENT_TREE_V2))
625 				break;
626 			if (token == Opt_space_cache ||
627 			    strcmp(args[0].from, "v1") == 0) {
628 				btrfs_clear_opt(info->mount_opt,
629 						FREE_SPACE_TREE);
630 				btrfs_set_and_info(info, SPACE_CACHE,
631 					   "enabling disk space caching");
632 			} else if (strcmp(args[0].from, "v2") == 0) {
633 				btrfs_clear_opt(info->mount_opt,
634 						SPACE_CACHE);
635 				btrfs_set_and_info(info, FREE_SPACE_TREE,
636 						   "enabling free space tree");
637 			} else {
638 				btrfs_err(info, "unrecognized space_cache value %s",
639 					  args[0].from);
640 				ret = -EINVAL;
641 				goto out;
642 			}
643 			break;
644 		case Opt_rescan_uuid_tree:
645 			btrfs_set_opt(info->mount_opt, RESCAN_UUID_TREE);
646 			break;
647 		case Opt_no_space_cache:
648 			/*
649 			 * We cannot operate without the free space tree with
650 			 * extent tree v2, ignore this option.
651 			 */
652 			if (btrfs_fs_incompat(info, EXTENT_TREE_V2))
653 				break;
654 			if (btrfs_test_opt(info, SPACE_CACHE)) {
655 				btrfs_clear_and_info(info, SPACE_CACHE,
656 					     "disabling disk space caching");
657 			}
658 			if (btrfs_test_opt(info, FREE_SPACE_TREE)) {
659 				btrfs_clear_and_info(info, FREE_SPACE_TREE,
660 					     "disabling free space tree");
661 			}
662 			break;
663 		case Opt_inode_cache:
664 		case Opt_noinode_cache:
665 			btrfs_warn(info,
666 	"the 'inode_cache' option is deprecated and has no effect since 5.11");
667 			break;
668 		case Opt_clear_cache:
669 			/*
670 			 * We cannot clear the free space tree with extent tree
671 			 * v2, ignore this option.
672 			 */
673 			if (btrfs_fs_incompat(info, EXTENT_TREE_V2))
674 				break;
675 			btrfs_set_and_info(info, CLEAR_CACHE,
676 					   "force clearing of disk cache");
677 			break;
678 		case Opt_user_subvol_rm_allowed:
679 			btrfs_set_opt(info->mount_opt, USER_SUBVOL_RM_ALLOWED);
680 			break;
681 		case Opt_enospc_debug:
682 			btrfs_set_opt(info->mount_opt, ENOSPC_DEBUG);
683 			break;
684 		case Opt_noenospc_debug:
685 			btrfs_clear_opt(info->mount_opt, ENOSPC_DEBUG);
686 			break;
687 		case Opt_defrag:
688 			btrfs_set_and_info(info, AUTO_DEFRAG,
689 					   "enabling auto defrag");
690 			break;
691 		case Opt_nodefrag:
692 			btrfs_clear_and_info(info, AUTO_DEFRAG,
693 					     "disabling auto defrag");
694 			break;
695 		case Opt_recovery:
696 		case Opt_usebackuproot:
697 			btrfs_warn(info,
698 			"'%s' is deprecated, use 'rescue=usebackuproot' instead",
699 				   token == Opt_recovery ? "recovery" :
700 				   "usebackuproot");
701 			btrfs_info(info,
702 				   "trying to use backup root at mount time");
703 			btrfs_set_opt(info->mount_opt, USEBACKUPROOT);
704 			break;
705 		case Opt_skip_balance:
706 			btrfs_set_opt(info->mount_opt, SKIP_BALANCE);
707 			break;
708 #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
709 		case Opt_check_integrity_including_extent_data:
710 			btrfs_info(info,
711 				   "enabling check integrity including extent data");
712 			btrfs_set_opt(info->mount_opt, CHECK_INTEGRITY_DATA);
713 			btrfs_set_opt(info->mount_opt, CHECK_INTEGRITY);
714 			break;
715 		case Opt_check_integrity:
716 			btrfs_info(info, "enabling check integrity");
717 			btrfs_set_opt(info->mount_opt, CHECK_INTEGRITY);
718 			break;
719 		case Opt_check_integrity_print_mask:
720 			ret = match_int(&args[0], &intarg);
721 			if (ret) {
722 				btrfs_err(info,
723 				"unrecognized check_integrity_print_mask value %s",
724 					args[0].from);
725 				goto out;
726 			}
727 			info->check_integrity_print_mask = intarg;
728 			btrfs_info(info, "check_integrity_print_mask 0x%x",
729 				   info->check_integrity_print_mask);
730 			break;
731 #else
732 		case Opt_check_integrity_including_extent_data:
733 		case Opt_check_integrity:
734 		case Opt_check_integrity_print_mask:
735 			btrfs_err(info,
736 				  "support for check_integrity* not compiled in!");
737 			ret = -EINVAL;
738 			goto out;
739 #endif
740 		case Opt_fatal_errors:
741 			if (strcmp(args[0].from, "panic") == 0) {
742 				btrfs_set_opt(info->mount_opt,
743 					      PANIC_ON_FATAL_ERROR);
744 			} else if (strcmp(args[0].from, "bug") == 0) {
745 				btrfs_clear_opt(info->mount_opt,
746 					      PANIC_ON_FATAL_ERROR);
747 			} else {
748 				btrfs_err(info, "unrecognized fatal_errors value %s",
749 					  args[0].from);
750 				ret = -EINVAL;
751 				goto out;
752 			}
753 			break;
754 		case Opt_commit_interval:
755 			intarg = 0;
756 			ret = match_int(&args[0], &intarg);
757 			if (ret) {
758 				btrfs_err(info, "unrecognized commit_interval value %s",
759 					  args[0].from);
760 				ret = -EINVAL;
761 				goto out;
762 			}
763 			if (intarg == 0) {
764 				btrfs_info(info,
765 					   "using default commit interval %us",
766 					   BTRFS_DEFAULT_COMMIT_INTERVAL);
767 				intarg = BTRFS_DEFAULT_COMMIT_INTERVAL;
768 			} else if (intarg > 300) {
769 				btrfs_warn(info, "excessive commit interval %d",
770 					   intarg);
771 			}
772 			info->commit_interval = intarg;
773 			break;
774 		case Opt_rescue:
775 			ret = parse_rescue_options(info, args[0].from);
776 			if (ret < 0) {
777 				btrfs_err(info, "unrecognized rescue value %s",
778 					  args[0].from);
779 				goto out;
780 			}
781 			break;
782 #ifdef CONFIG_BTRFS_DEBUG
783 		case Opt_fragment_all:
784 			btrfs_info(info, "fragmenting all space");
785 			btrfs_set_opt(info->mount_opt, FRAGMENT_DATA);
786 			btrfs_set_opt(info->mount_opt, FRAGMENT_METADATA);
787 			break;
788 		case Opt_fragment_metadata:
789 			btrfs_info(info, "fragmenting metadata");
790 			btrfs_set_opt(info->mount_opt,
791 				      FRAGMENT_METADATA);
792 			break;
793 		case Opt_fragment_data:
794 			btrfs_info(info, "fragmenting data");
795 			btrfs_set_opt(info->mount_opt, FRAGMENT_DATA);
796 			break;
797 #endif
798 #ifdef CONFIG_BTRFS_FS_REF_VERIFY
799 		case Opt_ref_verify:
800 			btrfs_info(info, "doing ref verification");
801 			btrfs_set_opt(info->mount_opt, REF_VERIFY);
802 			break;
803 #endif
804 		case Opt_err:
805 			btrfs_err(info, "unrecognized mount option '%s'", p);
806 			ret = -EINVAL;
807 			goto out;
808 		default:
809 			break;
810 		}
811 	}
812 check:
813 	/* We're read-only, don't have to check. */
814 	if (new_flags & SB_RDONLY)
815 		goto out;
816 
817 	if (check_ro_option(info, BTRFS_MOUNT_NOLOGREPLAY, "nologreplay") ||
818 	    check_ro_option(info, BTRFS_MOUNT_IGNOREBADROOTS, "ignorebadroots") ||
819 	    check_ro_option(info, BTRFS_MOUNT_IGNOREDATACSUMS, "ignoredatacsums"))
820 		ret = -EINVAL;
821 out:
822 	if (btrfs_fs_compat_ro(info, FREE_SPACE_TREE) &&
823 	    !btrfs_test_opt(info, FREE_SPACE_TREE) &&
824 	    !btrfs_test_opt(info, CLEAR_CACHE)) {
825 		btrfs_err(info, "cannot disable free space tree");
826 		ret = -EINVAL;
827 
828 	}
829 	if (!ret)
830 		ret = btrfs_check_mountopts_zoned(info);
831 	if (!ret && !remounting) {
832 		if (btrfs_test_opt(info, SPACE_CACHE))
833 			btrfs_info(info, "disk space caching is enabled");
834 		if (btrfs_test_opt(info, FREE_SPACE_TREE))
835 			btrfs_info(info, "using free space tree");
836 	}
837 	return ret;
838 }
839 
840 /*
841  * Parse mount options that are required early in the mount process.
842  *
843  * All other options will be parsed on much later in the mount process and
844  * only when we need to allocate a new super block.
845  */
846 static int btrfs_parse_device_options(const char *options, fmode_t flags,
847 				      void *holder)
848 {
849 	substring_t args[MAX_OPT_ARGS];
850 	char *device_name, *opts, *orig, *p;
851 	struct btrfs_device *device = NULL;
852 	int error = 0;
853 
854 	lockdep_assert_held(&uuid_mutex);
855 
856 	if (!options)
857 		return 0;
858 
859 	/*
860 	 * strsep changes the string, duplicate it because btrfs_parse_options
861 	 * gets called later
862 	 */
863 	opts = kstrdup(options, GFP_KERNEL);
864 	if (!opts)
865 		return -ENOMEM;
866 	orig = opts;
867 
868 	while ((p = strsep(&opts, ",")) != NULL) {
869 		int token;
870 
871 		if (!*p)
872 			continue;
873 
874 		token = match_token(p, tokens, args);
875 		if (token == Opt_device) {
876 			device_name = match_strdup(&args[0]);
877 			if (!device_name) {
878 				error = -ENOMEM;
879 				goto out;
880 			}
881 			device = btrfs_scan_one_device(device_name, flags,
882 					holder);
883 			kfree(device_name);
884 			if (IS_ERR(device)) {
885 				error = PTR_ERR(device);
886 				goto out;
887 			}
888 		}
889 	}
890 
891 out:
892 	kfree(orig);
893 	return error;
894 }
895 
896 /*
897  * Parse mount options that are related to subvolume id
898  *
899  * The value is later passed to mount_subvol()
900  */
901 static int btrfs_parse_subvol_options(const char *options, char **subvol_name,
902 		u64 *subvol_objectid)
903 {
904 	substring_t args[MAX_OPT_ARGS];
905 	char *opts, *orig, *p;
906 	int error = 0;
907 	u64 subvolid;
908 
909 	if (!options)
910 		return 0;
911 
912 	/*
913 	 * strsep changes the string, duplicate it because
914 	 * btrfs_parse_device_options gets called later
915 	 */
916 	opts = kstrdup(options, GFP_KERNEL);
917 	if (!opts)
918 		return -ENOMEM;
919 	orig = opts;
920 
921 	while ((p = strsep(&opts, ",")) != NULL) {
922 		int token;
923 		if (!*p)
924 			continue;
925 
926 		token = match_token(p, tokens, args);
927 		switch (token) {
928 		case Opt_subvol:
929 			kfree(*subvol_name);
930 			*subvol_name = match_strdup(&args[0]);
931 			if (!*subvol_name) {
932 				error = -ENOMEM;
933 				goto out;
934 			}
935 			break;
936 		case Opt_subvolid:
937 			error = match_u64(&args[0], &subvolid);
938 			if (error)
939 				goto out;
940 
941 			/* we want the original fs_tree */
942 			if (subvolid == 0)
943 				subvolid = BTRFS_FS_TREE_OBJECTID;
944 
945 			*subvol_objectid = subvolid;
946 			break;
947 		default:
948 			break;
949 		}
950 	}
951 
952 out:
953 	kfree(orig);
954 	return error;
955 }
956 
957 char *btrfs_get_subvol_name_from_objectid(struct btrfs_fs_info *fs_info,
958 					  u64 subvol_objectid)
959 {
960 	struct btrfs_root *root = fs_info->tree_root;
961 	struct btrfs_root *fs_root = NULL;
962 	struct btrfs_root_ref *root_ref;
963 	struct btrfs_inode_ref *inode_ref;
964 	struct btrfs_key key;
965 	struct btrfs_path *path = NULL;
966 	char *name = NULL, *ptr;
967 	u64 dirid;
968 	int len;
969 	int ret;
970 
971 	path = btrfs_alloc_path();
972 	if (!path) {
973 		ret = -ENOMEM;
974 		goto err;
975 	}
976 
977 	name = kmalloc(PATH_MAX, GFP_KERNEL);
978 	if (!name) {
979 		ret = -ENOMEM;
980 		goto err;
981 	}
982 	ptr = name + PATH_MAX - 1;
983 	ptr[0] = '\0';
984 
985 	/*
986 	 * Walk up the subvolume trees in the tree of tree roots by root
987 	 * backrefs until we hit the top-level subvolume.
988 	 */
989 	while (subvol_objectid != BTRFS_FS_TREE_OBJECTID) {
990 		key.objectid = subvol_objectid;
991 		key.type = BTRFS_ROOT_BACKREF_KEY;
992 		key.offset = (u64)-1;
993 
994 		ret = btrfs_search_backwards(root, &key, path);
995 		if (ret < 0) {
996 			goto err;
997 		} else if (ret > 0) {
998 			ret = -ENOENT;
999 			goto err;
1000 		}
1001 
1002 		subvol_objectid = key.offset;
1003 
1004 		root_ref = btrfs_item_ptr(path->nodes[0], path->slots[0],
1005 					  struct btrfs_root_ref);
1006 		len = btrfs_root_ref_name_len(path->nodes[0], root_ref);
1007 		ptr -= len + 1;
1008 		if (ptr < name) {
1009 			ret = -ENAMETOOLONG;
1010 			goto err;
1011 		}
1012 		read_extent_buffer(path->nodes[0], ptr + 1,
1013 				   (unsigned long)(root_ref + 1), len);
1014 		ptr[0] = '/';
1015 		dirid = btrfs_root_ref_dirid(path->nodes[0], root_ref);
1016 		btrfs_release_path(path);
1017 
1018 		fs_root = btrfs_get_fs_root(fs_info, subvol_objectid, true);
1019 		if (IS_ERR(fs_root)) {
1020 			ret = PTR_ERR(fs_root);
1021 			fs_root = NULL;
1022 			goto err;
1023 		}
1024 
1025 		/*
1026 		 * Walk up the filesystem tree by inode refs until we hit the
1027 		 * root directory.
1028 		 */
1029 		while (dirid != BTRFS_FIRST_FREE_OBJECTID) {
1030 			key.objectid = dirid;
1031 			key.type = BTRFS_INODE_REF_KEY;
1032 			key.offset = (u64)-1;
1033 
1034 			ret = btrfs_search_backwards(fs_root, &key, path);
1035 			if (ret < 0) {
1036 				goto err;
1037 			} else if (ret > 0) {
1038 				ret = -ENOENT;
1039 				goto err;
1040 			}
1041 
1042 			dirid = key.offset;
1043 
1044 			inode_ref = btrfs_item_ptr(path->nodes[0],
1045 						   path->slots[0],
1046 						   struct btrfs_inode_ref);
1047 			len = btrfs_inode_ref_name_len(path->nodes[0],
1048 						       inode_ref);
1049 			ptr -= len + 1;
1050 			if (ptr < name) {
1051 				ret = -ENAMETOOLONG;
1052 				goto err;
1053 			}
1054 			read_extent_buffer(path->nodes[0], ptr + 1,
1055 					   (unsigned long)(inode_ref + 1), len);
1056 			ptr[0] = '/';
1057 			btrfs_release_path(path);
1058 		}
1059 		btrfs_put_root(fs_root);
1060 		fs_root = NULL;
1061 	}
1062 
1063 	btrfs_free_path(path);
1064 	if (ptr == name + PATH_MAX - 1) {
1065 		name[0] = '/';
1066 		name[1] = '\0';
1067 	} else {
1068 		memmove(name, ptr, name + PATH_MAX - ptr);
1069 	}
1070 	return name;
1071 
1072 err:
1073 	btrfs_put_root(fs_root);
1074 	btrfs_free_path(path);
1075 	kfree(name);
1076 	return ERR_PTR(ret);
1077 }
1078 
1079 static int get_default_subvol_objectid(struct btrfs_fs_info *fs_info, u64 *objectid)
1080 {
1081 	struct btrfs_root *root = fs_info->tree_root;
1082 	struct btrfs_dir_item *di;
1083 	struct btrfs_path *path;
1084 	struct btrfs_key location;
1085 	struct fscrypt_str name = FSTR_INIT("default", 7);
1086 	u64 dir_id;
1087 
1088 	path = btrfs_alloc_path();
1089 	if (!path)
1090 		return -ENOMEM;
1091 
1092 	/*
1093 	 * Find the "default" dir item which points to the root item that we
1094 	 * will mount by default if we haven't been given a specific subvolume
1095 	 * to mount.
1096 	 */
1097 	dir_id = btrfs_super_root_dir(fs_info->super_copy);
1098 	di = btrfs_lookup_dir_item(NULL, root, path, dir_id, &name, 0);
1099 	if (IS_ERR(di)) {
1100 		btrfs_free_path(path);
1101 		return PTR_ERR(di);
1102 	}
1103 	if (!di) {
1104 		/*
1105 		 * Ok the default dir item isn't there.  This is weird since
1106 		 * it's always been there, but don't freak out, just try and
1107 		 * mount the top-level subvolume.
1108 		 */
1109 		btrfs_free_path(path);
1110 		*objectid = BTRFS_FS_TREE_OBJECTID;
1111 		return 0;
1112 	}
1113 
1114 	btrfs_dir_item_key_to_cpu(path->nodes[0], di, &location);
1115 	btrfs_free_path(path);
1116 	*objectid = location.objectid;
1117 	return 0;
1118 }
1119 
1120 static int btrfs_fill_super(struct super_block *sb,
1121 			    struct btrfs_fs_devices *fs_devices,
1122 			    void *data)
1123 {
1124 	struct inode *inode;
1125 	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
1126 	int err;
1127 
1128 	sb->s_maxbytes = MAX_LFS_FILESIZE;
1129 	sb->s_magic = BTRFS_SUPER_MAGIC;
1130 	sb->s_op = &btrfs_super_ops;
1131 	sb->s_d_op = &btrfs_dentry_operations;
1132 	sb->s_export_op = &btrfs_export_ops;
1133 #ifdef CONFIG_FS_VERITY
1134 	sb->s_vop = &btrfs_verityops;
1135 #endif
1136 	sb->s_xattr = btrfs_xattr_handlers;
1137 	sb->s_time_gran = 1;
1138 #ifdef CONFIG_BTRFS_FS_POSIX_ACL
1139 	sb->s_flags |= SB_POSIXACL;
1140 #endif
1141 	sb->s_flags |= SB_I_VERSION;
1142 	sb->s_iflags |= SB_I_CGROUPWB;
1143 
1144 	err = super_setup_bdi(sb);
1145 	if (err) {
1146 		btrfs_err(fs_info, "super_setup_bdi failed");
1147 		return err;
1148 	}
1149 
1150 	err = open_ctree(sb, fs_devices, (char *)data);
1151 	if (err) {
1152 		btrfs_err(fs_info, "open_ctree failed");
1153 		return err;
1154 	}
1155 
1156 	inode = btrfs_iget(sb, BTRFS_FIRST_FREE_OBJECTID, fs_info->fs_root);
1157 	if (IS_ERR(inode)) {
1158 		err = PTR_ERR(inode);
1159 		goto fail_close;
1160 	}
1161 
1162 	sb->s_root = d_make_root(inode);
1163 	if (!sb->s_root) {
1164 		err = -ENOMEM;
1165 		goto fail_close;
1166 	}
1167 
1168 	sb->s_flags |= SB_ACTIVE;
1169 	return 0;
1170 
1171 fail_close:
1172 	close_ctree(fs_info);
1173 	return err;
1174 }
1175 
1176 int btrfs_sync_fs(struct super_block *sb, int wait)
1177 {
1178 	struct btrfs_trans_handle *trans;
1179 	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
1180 	struct btrfs_root *root = fs_info->tree_root;
1181 
1182 	trace_btrfs_sync_fs(fs_info, wait);
1183 
1184 	if (!wait) {
1185 		filemap_flush(fs_info->btree_inode->i_mapping);
1186 		return 0;
1187 	}
1188 
1189 	btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
1190 
1191 	trans = btrfs_attach_transaction_barrier(root);
1192 	if (IS_ERR(trans)) {
1193 		/* no transaction, don't bother */
1194 		if (PTR_ERR(trans) == -ENOENT) {
1195 			/*
1196 			 * Exit unless we have some pending changes
1197 			 * that need to go through commit
1198 			 */
1199 			if (!test_bit(BTRFS_FS_NEED_TRANS_COMMIT,
1200 				      &fs_info->flags))
1201 				return 0;
1202 			/*
1203 			 * A non-blocking test if the fs is frozen. We must not
1204 			 * start a new transaction here otherwise a deadlock
1205 			 * happens. The pending operations are delayed to the
1206 			 * next commit after thawing.
1207 			 */
1208 			if (sb_start_write_trylock(sb))
1209 				sb_end_write(sb);
1210 			else
1211 				return 0;
1212 			trans = btrfs_start_transaction(root, 0);
1213 		}
1214 		if (IS_ERR(trans))
1215 			return PTR_ERR(trans);
1216 	}
1217 	return btrfs_commit_transaction(trans);
1218 }
1219 
1220 static void print_rescue_option(struct seq_file *seq, const char *s, bool *printed)
1221 {
1222 	seq_printf(seq, "%s%s", (*printed) ? ":" : ",rescue=", s);
1223 	*printed = true;
1224 }
1225 
1226 static int btrfs_show_options(struct seq_file *seq, struct dentry *dentry)
1227 {
1228 	struct btrfs_fs_info *info = btrfs_sb(dentry->d_sb);
1229 	const char *compress_type;
1230 	const char *subvol_name;
1231 	bool printed = false;
1232 
1233 	if (btrfs_test_opt(info, DEGRADED))
1234 		seq_puts(seq, ",degraded");
1235 	if (btrfs_test_opt(info, NODATASUM))
1236 		seq_puts(seq, ",nodatasum");
1237 	if (btrfs_test_opt(info, NODATACOW))
1238 		seq_puts(seq, ",nodatacow");
1239 	if (btrfs_test_opt(info, NOBARRIER))
1240 		seq_puts(seq, ",nobarrier");
1241 	if (info->max_inline != BTRFS_DEFAULT_MAX_INLINE)
1242 		seq_printf(seq, ",max_inline=%llu", info->max_inline);
1243 	if (info->thread_pool_size !=  min_t(unsigned long,
1244 					     num_online_cpus() + 2, 8))
1245 		seq_printf(seq, ",thread_pool=%u", info->thread_pool_size);
1246 	if (btrfs_test_opt(info, COMPRESS)) {
1247 		compress_type = btrfs_compress_type2str(info->compress_type);
1248 		if (btrfs_test_opt(info, FORCE_COMPRESS))
1249 			seq_printf(seq, ",compress-force=%s", compress_type);
1250 		else
1251 			seq_printf(seq, ",compress=%s", compress_type);
1252 		if (info->compress_level)
1253 			seq_printf(seq, ":%d", info->compress_level);
1254 	}
1255 	if (btrfs_test_opt(info, NOSSD))
1256 		seq_puts(seq, ",nossd");
1257 	if (btrfs_test_opt(info, SSD_SPREAD))
1258 		seq_puts(seq, ",ssd_spread");
1259 	else if (btrfs_test_opt(info, SSD))
1260 		seq_puts(seq, ",ssd");
1261 	if (btrfs_test_opt(info, NOTREELOG))
1262 		seq_puts(seq, ",notreelog");
1263 	if (btrfs_test_opt(info, NOLOGREPLAY))
1264 		print_rescue_option(seq, "nologreplay", &printed);
1265 	if (btrfs_test_opt(info, USEBACKUPROOT))
1266 		print_rescue_option(seq, "usebackuproot", &printed);
1267 	if (btrfs_test_opt(info, IGNOREBADROOTS))
1268 		print_rescue_option(seq, "ignorebadroots", &printed);
1269 	if (btrfs_test_opt(info, IGNOREDATACSUMS))
1270 		print_rescue_option(seq, "ignoredatacsums", &printed);
1271 	if (btrfs_test_opt(info, FLUSHONCOMMIT))
1272 		seq_puts(seq, ",flushoncommit");
1273 	if (btrfs_test_opt(info, DISCARD_SYNC))
1274 		seq_puts(seq, ",discard");
1275 	if (btrfs_test_opt(info, DISCARD_ASYNC))
1276 		seq_puts(seq, ",discard=async");
1277 	if (!(info->sb->s_flags & SB_POSIXACL))
1278 		seq_puts(seq, ",noacl");
1279 	if (btrfs_free_space_cache_v1_active(info))
1280 		seq_puts(seq, ",space_cache");
1281 	else if (btrfs_fs_compat_ro(info, FREE_SPACE_TREE))
1282 		seq_puts(seq, ",space_cache=v2");
1283 	else
1284 		seq_puts(seq, ",nospace_cache");
1285 	if (btrfs_test_opt(info, RESCAN_UUID_TREE))
1286 		seq_puts(seq, ",rescan_uuid_tree");
1287 	if (btrfs_test_opt(info, CLEAR_CACHE))
1288 		seq_puts(seq, ",clear_cache");
1289 	if (btrfs_test_opt(info, USER_SUBVOL_RM_ALLOWED))
1290 		seq_puts(seq, ",user_subvol_rm_allowed");
1291 	if (btrfs_test_opt(info, ENOSPC_DEBUG))
1292 		seq_puts(seq, ",enospc_debug");
1293 	if (btrfs_test_opt(info, AUTO_DEFRAG))
1294 		seq_puts(seq, ",autodefrag");
1295 	if (btrfs_test_opt(info, SKIP_BALANCE))
1296 		seq_puts(seq, ",skip_balance");
1297 #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
1298 	if (btrfs_test_opt(info, CHECK_INTEGRITY_DATA))
1299 		seq_puts(seq, ",check_int_data");
1300 	else if (btrfs_test_opt(info, CHECK_INTEGRITY))
1301 		seq_puts(seq, ",check_int");
1302 	if (info->check_integrity_print_mask)
1303 		seq_printf(seq, ",check_int_print_mask=%d",
1304 				info->check_integrity_print_mask);
1305 #endif
1306 	if (info->metadata_ratio)
1307 		seq_printf(seq, ",metadata_ratio=%u", info->metadata_ratio);
1308 	if (btrfs_test_opt(info, PANIC_ON_FATAL_ERROR))
1309 		seq_puts(seq, ",fatal_errors=panic");
1310 	if (info->commit_interval != BTRFS_DEFAULT_COMMIT_INTERVAL)
1311 		seq_printf(seq, ",commit=%u", info->commit_interval);
1312 #ifdef CONFIG_BTRFS_DEBUG
1313 	if (btrfs_test_opt(info, FRAGMENT_DATA))
1314 		seq_puts(seq, ",fragment=data");
1315 	if (btrfs_test_opt(info, FRAGMENT_METADATA))
1316 		seq_puts(seq, ",fragment=metadata");
1317 #endif
1318 	if (btrfs_test_opt(info, REF_VERIFY))
1319 		seq_puts(seq, ",ref_verify");
1320 	seq_printf(seq, ",subvolid=%llu",
1321 		  BTRFS_I(d_inode(dentry))->root->root_key.objectid);
1322 	subvol_name = btrfs_get_subvol_name_from_objectid(info,
1323 			BTRFS_I(d_inode(dentry))->root->root_key.objectid);
1324 	if (!IS_ERR(subvol_name)) {
1325 		seq_puts(seq, ",subvol=");
1326 		seq_escape(seq, subvol_name, " \t\n\\");
1327 		kfree(subvol_name);
1328 	}
1329 	return 0;
1330 }
1331 
1332 static int btrfs_test_super(struct super_block *s, void *data)
1333 {
1334 	struct btrfs_fs_info *p = data;
1335 	struct btrfs_fs_info *fs_info = btrfs_sb(s);
1336 
1337 	return fs_info->fs_devices == p->fs_devices;
1338 }
1339 
1340 static int btrfs_set_super(struct super_block *s, void *data)
1341 {
1342 	int err = set_anon_super(s, data);
1343 	if (!err)
1344 		s->s_fs_info = data;
1345 	return err;
1346 }
1347 
1348 /*
1349  * subvolumes are identified by ino 256
1350  */
1351 static inline int is_subvolume_inode(struct inode *inode)
1352 {
1353 	if (inode && inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)
1354 		return 1;
1355 	return 0;
1356 }
1357 
1358 static struct dentry *mount_subvol(const char *subvol_name, u64 subvol_objectid,
1359 				   struct vfsmount *mnt)
1360 {
1361 	struct dentry *root;
1362 	int ret;
1363 
1364 	if (!subvol_name) {
1365 		if (!subvol_objectid) {
1366 			ret = get_default_subvol_objectid(btrfs_sb(mnt->mnt_sb),
1367 							  &subvol_objectid);
1368 			if (ret) {
1369 				root = ERR_PTR(ret);
1370 				goto out;
1371 			}
1372 		}
1373 		subvol_name = btrfs_get_subvol_name_from_objectid(
1374 					btrfs_sb(mnt->mnt_sb), subvol_objectid);
1375 		if (IS_ERR(subvol_name)) {
1376 			root = ERR_CAST(subvol_name);
1377 			subvol_name = NULL;
1378 			goto out;
1379 		}
1380 
1381 	}
1382 
1383 	root = mount_subtree(mnt, subvol_name);
1384 	/* mount_subtree() drops our reference on the vfsmount. */
1385 	mnt = NULL;
1386 
1387 	if (!IS_ERR(root)) {
1388 		struct super_block *s = root->d_sb;
1389 		struct btrfs_fs_info *fs_info = btrfs_sb(s);
1390 		struct inode *root_inode = d_inode(root);
1391 		u64 root_objectid = BTRFS_I(root_inode)->root->root_key.objectid;
1392 
1393 		ret = 0;
1394 		if (!is_subvolume_inode(root_inode)) {
1395 			btrfs_err(fs_info, "'%s' is not a valid subvolume",
1396 			       subvol_name);
1397 			ret = -EINVAL;
1398 		}
1399 		if (subvol_objectid && root_objectid != subvol_objectid) {
1400 			/*
1401 			 * This will also catch a race condition where a
1402 			 * subvolume which was passed by ID is renamed and
1403 			 * another subvolume is renamed over the old location.
1404 			 */
1405 			btrfs_err(fs_info,
1406 				  "subvol '%s' does not match subvolid %llu",
1407 				  subvol_name, subvol_objectid);
1408 			ret = -EINVAL;
1409 		}
1410 		if (ret) {
1411 			dput(root);
1412 			root = ERR_PTR(ret);
1413 			deactivate_locked_super(s);
1414 		}
1415 	}
1416 
1417 out:
1418 	mntput(mnt);
1419 	kfree(subvol_name);
1420 	return root;
1421 }
1422 
1423 /*
1424  * Find a superblock for the given device / mount point.
1425  *
1426  * Note: This is based on mount_bdev from fs/super.c with a few additions
1427  *       for multiple device setup.  Make sure to keep it in sync.
1428  */
1429 static struct dentry *btrfs_mount_root(struct file_system_type *fs_type,
1430 		int flags, const char *device_name, void *data)
1431 {
1432 	struct block_device *bdev = NULL;
1433 	struct super_block *s;
1434 	struct btrfs_device *device = NULL;
1435 	struct btrfs_fs_devices *fs_devices = NULL;
1436 	struct btrfs_fs_info *fs_info = NULL;
1437 	void *new_sec_opts = NULL;
1438 	fmode_t mode = FMODE_READ;
1439 	int error = 0;
1440 
1441 	if (!(flags & SB_RDONLY))
1442 		mode |= FMODE_WRITE;
1443 
1444 	if (data) {
1445 		error = security_sb_eat_lsm_opts(data, &new_sec_opts);
1446 		if (error)
1447 			return ERR_PTR(error);
1448 	}
1449 
1450 	/*
1451 	 * Setup a dummy root and fs_info for test/set super.  This is because
1452 	 * we don't actually fill this stuff out until open_ctree, but we need
1453 	 * then open_ctree will properly initialize the file system specific
1454 	 * settings later.  btrfs_init_fs_info initializes the static elements
1455 	 * of the fs_info (locks and such) to make cleanup easier if we find a
1456 	 * superblock with our given fs_devices later on at sget() time.
1457 	 */
1458 	fs_info = kvzalloc(sizeof(struct btrfs_fs_info), GFP_KERNEL);
1459 	if (!fs_info) {
1460 		error = -ENOMEM;
1461 		goto error_sec_opts;
1462 	}
1463 	btrfs_init_fs_info(fs_info);
1464 
1465 	fs_info->super_copy = kzalloc(BTRFS_SUPER_INFO_SIZE, GFP_KERNEL);
1466 	fs_info->super_for_commit = kzalloc(BTRFS_SUPER_INFO_SIZE, GFP_KERNEL);
1467 	if (!fs_info->super_copy || !fs_info->super_for_commit) {
1468 		error = -ENOMEM;
1469 		goto error_fs_info;
1470 	}
1471 
1472 	mutex_lock(&uuid_mutex);
1473 	error = btrfs_parse_device_options(data, mode, fs_type);
1474 	if (error) {
1475 		mutex_unlock(&uuid_mutex);
1476 		goto error_fs_info;
1477 	}
1478 
1479 	device = btrfs_scan_one_device(device_name, mode, fs_type);
1480 	if (IS_ERR(device)) {
1481 		mutex_unlock(&uuid_mutex);
1482 		error = PTR_ERR(device);
1483 		goto error_fs_info;
1484 	}
1485 
1486 	fs_devices = device->fs_devices;
1487 	fs_info->fs_devices = fs_devices;
1488 
1489 	error = btrfs_open_devices(fs_devices, mode, fs_type);
1490 	mutex_unlock(&uuid_mutex);
1491 	if (error)
1492 		goto error_fs_info;
1493 
1494 	if (!(flags & SB_RDONLY) && fs_devices->rw_devices == 0) {
1495 		error = -EACCES;
1496 		goto error_close_devices;
1497 	}
1498 
1499 	bdev = fs_devices->latest_dev->bdev;
1500 	s = sget(fs_type, btrfs_test_super, btrfs_set_super, flags | SB_NOSEC,
1501 		 fs_info);
1502 	if (IS_ERR(s)) {
1503 		error = PTR_ERR(s);
1504 		goto error_close_devices;
1505 	}
1506 
1507 	if (s->s_root) {
1508 		btrfs_close_devices(fs_devices);
1509 		btrfs_free_fs_info(fs_info);
1510 		if ((flags ^ s->s_flags) & SB_RDONLY)
1511 			error = -EBUSY;
1512 	} else {
1513 		snprintf(s->s_id, sizeof(s->s_id), "%pg", bdev);
1514 		shrinker_debugfs_rename(&s->s_shrink, "sb-%s:%s", fs_type->name,
1515 					s->s_id);
1516 		btrfs_sb(s)->bdev_holder = fs_type;
1517 		if (!strstr(crc32c_impl(), "generic"))
1518 			set_bit(BTRFS_FS_CSUM_IMPL_FAST, &fs_info->flags);
1519 		error = btrfs_fill_super(s, fs_devices, data);
1520 	}
1521 	if (!error)
1522 		error = security_sb_set_mnt_opts(s, new_sec_opts, 0, NULL);
1523 	security_free_mnt_opts(&new_sec_opts);
1524 	if (error) {
1525 		deactivate_locked_super(s);
1526 		return ERR_PTR(error);
1527 	}
1528 
1529 	return dget(s->s_root);
1530 
1531 error_close_devices:
1532 	btrfs_close_devices(fs_devices);
1533 error_fs_info:
1534 	btrfs_free_fs_info(fs_info);
1535 error_sec_opts:
1536 	security_free_mnt_opts(&new_sec_opts);
1537 	return ERR_PTR(error);
1538 }
1539 
1540 /*
1541  * Mount function which is called by VFS layer.
1542  *
1543  * In order to allow mounting a subvolume directly, btrfs uses mount_subtree()
1544  * which needs vfsmount* of device's root (/).  This means device's root has to
1545  * be mounted internally in any case.
1546  *
1547  * Operation flow:
1548  *   1. Parse subvol id related options for later use in mount_subvol().
1549  *
1550  *   2. Mount device's root (/) by calling vfs_kern_mount().
1551  *
1552  *      NOTE: vfs_kern_mount() is used by VFS to call btrfs_mount() in the
1553  *      first place. In order to avoid calling btrfs_mount() again, we use
1554  *      different file_system_type which is not registered to VFS by
1555  *      register_filesystem() (btrfs_root_fs_type). As a result,
1556  *      btrfs_mount_root() is called. The return value will be used by
1557  *      mount_subtree() in mount_subvol().
1558  *
1559  *   3. Call mount_subvol() to get the dentry of subvolume. Since there is
1560  *      "btrfs subvolume set-default", mount_subvol() is called always.
1561  */
1562 static struct dentry *btrfs_mount(struct file_system_type *fs_type, int flags,
1563 		const char *device_name, void *data)
1564 {
1565 	struct vfsmount *mnt_root;
1566 	struct dentry *root;
1567 	char *subvol_name = NULL;
1568 	u64 subvol_objectid = 0;
1569 	int error = 0;
1570 
1571 	error = btrfs_parse_subvol_options(data, &subvol_name,
1572 					&subvol_objectid);
1573 	if (error) {
1574 		kfree(subvol_name);
1575 		return ERR_PTR(error);
1576 	}
1577 
1578 	/* mount device's root (/) */
1579 	mnt_root = vfs_kern_mount(&btrfs_root_fs_type, flags, device_name, data);
1580 	if (PTR_ERR_OR_ZERO(mnt_root) == -EBUSY) {
1581 		if (flags & SB_RDONLY) {
1582 			mnt_root = vfs_kern_mount(&btrfs_root_fs_type,
1583 				flags & ~SB_RDONLY, device_name, data);
1584 		} else {
1585 			mnt_root = vfs_kern_mount(&btrfs_root_fs_type,
1586 				flags | SB_RDONLY, device_name, data);
1587 			if (IS_ERR(mnt_root)) {
1588 				root = ERR_CAST(mnt_root);
1589 				kfree(subvol_name);
1590 				goto out;
1591 			}
1592 
1593 			down_write(&mnt_root->mnt_sb->s_umount);
1594 			error = btrfs_remount(mnt_root->mnt_sb, &flags, NULL);
1595 			up_write(&mnt_root->mnt_sb->s_umount);
1596 			if (error < 0) {
1597 				root = ERR_PTR(error);
1598 				mntput(mnt_root);
1599 				kfree(subvol_name);
1600 				goto out;
1601 			}
1602 		}
1603 	}
1604 	if (IS_ERR(mnt_root)) {
1605 		root = ERR_CAST(mnt_root);
1606 		kfree(subvol_name);
1607 		goto out;
1608 	}
1609 
1610 	/* mount_subvol() will free subvol_name and mnt_root */
1611 	root = mount_subvol(subvol_name, subvol_objectid, mnt_root);
1612 
1613 out:
1614 	return root;
1615 }
1616 
1617 static void btrfs_resize_thread_pool(struct btrfs_fs_info *fs_info,
1618 				     u32 new_pool_size, u32 old_pool_size)
1619 {
1620 	if (new_pool_size == old_pool_size)
1621 		return;
1622 
1623 	fs_info->thread_pool_size = new_pool_size;
1624 
1625 	btrfs_info(fs_info, "resize thread pool %d -> %d",
1626 	       old_pool_size, new_pool_size);
1627 
1628 	btrfs_workqueue_set_max(fs_info->workers, new_pool_size);
1629 	btrfs_workqueue_set_max(fs_info->hipri_workers, new_pool_size);
1630 	btrfs_workqueue_set_max(fs_info->delalloc_workers, new_pool_size);
1631 	btrfs_workqueue_set_max(fs_info->caching_workers, new_pool_size);
1632 	btrfs_workqueue_set_max(fs_info->endio_write_workers, new_pool_size);
1633 	btrfs_workqueue_set_max(fs_info->endio_freespace_worker, new_pool_size);
1634 	btrfs_workqueue_set_max(fs_info->delayed_workers, new_pool_size);
1635 }
1636 
1637 static inline void btrfs_remount_begin(struct btrfs_fs_info *fs_info,
1638 				       unsigned long old_opts, int flags)
1639 {
1640 	if (btrfs_raw_test_opt(old_opts, AUTO_DEFRAG) &&
1641 	    (!btrfs_raw_test_opt(fs_info->mount_opt, AUTO_DEFRAG) ||
1642 	     (flags & SB_RDONLY))) {
1643 		/* wait for any defraggers to finish */
1644 		wait_event(fs_info->transaction_wait,
1645 			   (atomic_read(&fs_info->defrag_running) == 0));
1646 		if (flags & SB_RDONLY)
1647 			sync_filesystem(fs_info->sb);
1648 	}
1649 }
1650 
1651 static inline void btrfs_remount_cleanup(struct btrfs_fs_info *fs_info,
1652 					 unsigned long old_opts)
1653 {
1654 	const bool cache_opt = btrfs_test_opt(fs_info, SPACE_CACHE);
1655 
1656 	/*
1657 	 * We need to cleanup all defragable inodes if the autodefragment is
1658 	 * close or the filesystem is read only.
1659 	 */
1660 	if (btrfs_raw_test_opt(old_opts, AUTO_DEFRAG) &&
1661 	    (!btrfs_raw_test_opt(fs_info->mount_opt, AUTO_DEFRAG) || sb_rdonly(fs_info->sb))) {
1662 		btrfs_cleanup_defrag_inodes(fs_info);
1663 	}
1664 
1665 	/* If we toggled discard async */
1666 	if (!btrfs_raw_test_opt(old_opts, DISCARD_ASYNC) &&
1667 	    btrfs_test_opt(fs_info, DISCARD_ASYNC))
1668 		btrfs_discard_resume(fs_info);
1669 	else if (btrfs_raw_test_opt(old_opts, DISCARD_ASYNC) &&
1670 		 !btrfs_test_opt(fs_info, DISCARD_ASYNC))
1671 		btrfs_discard_cleanup(fs_info);
1672 
1673 	/* If we toggled space cache */
1674 	if (cache_opt != btrfs_free_space_cache_v1_active(fs_info))
1675 		btrfs_set_free_space_cache_v1_active(fs_info, cache_opt);
1676 }
1677 
1678 static int btrfs_remount(struct super_block *sb, int *flags, char *data)
1679 {
1680 	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
1681 	unsigned old_flags = sb->s_flags;
1682 	unsigned long old_opts = fs_info->mount_opt;
1683 	unsigned long old_compress_type = fs_info->compress_type;
1684 	u64 old_max_inline = fs_info->max_inline;
1685 	u32 old_thread_pool_size = fs_info->thread_pool_size;
1686 	u32 old_metadata_ratio = fs_info->metadata_ratio;
1687 	int ret;
1688 
1689 	sync_filesystem(sb);
1690 	set_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state);
1691 
1692 	if (data) {
1693 		void *new_sec_opts = NULL;
1694 
1695 		ret = security_sb_eat_lsm_opts(data, &new_sec_opts);
1696 		if (!ret)
1697 			ret = security_sb_remount(sb, new_sec_opts);
1698 		security_free_mnt_opts(&new_sec_opts);
1699 		if (ret)
1700 			goto restore;
1701 	}
1702 
1703 	ret = btrfs_parse_options(fs_info, data, *flags);
1704 	if (ret)
1705 		goto restore;
1706 
1707 	ret = btrfs_check_features(fs_info, sb);
1708 	if (ret < 0)
1709 		goto restore;
1710 
1711 	btrfs_remount_begin(fs_info, old_opts, *flags);
1712 	btrfs_resize_thread_pool(fs_info,
1713 		fs_info->thread_pool_size, old_thread_pool_size);
1714 
1715 	if ((bool)btrfs_test_opt(fs_info, FREE_SPACE_TREE) !=
1716 	    (bool)btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
1717 	    (!sb_rdonly(sb) || (*flags & SB_RDONLY))) {
1718 		btrfs_warn(fs_info,
1719 		"remount supports changing free space tree only from ro to rw");
1720 		/* Make sure free space cache options match the state on disk */
1721 		if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
1722 			btrfs_set_opt(fs_info->mount_opt, FREE_SPACE_TREE);
1723 			btrfs_clear_opt(fs_info->mount_opt, SPACE_CACHE);
1724 		}
1725 		if (btrfs_free_space_cache_v1_active(fs_info)) {
1726 			btrfs_clear_opt(fs_info->mount_opt, FREE_SPACE_TREE);
1727 			btrfs_set_opt(fs_info->mount_opt, SPACE_CACHE);
1728 		}
1729 	}
1730 
1731 	if ((bool)(*flags & SB_RDONLY) == sb_rdonly(sb))
1732 		goto out;
1733 
1734 	if (*flags & SB_RDONLY) {
1735 		/*
1736 		 * this also happens on 'umount -rf' or on shutdown, when
1737 		 * the filesystem is busy.
1738 		 */
1739 		cancel_work_sync(&fs_info->async_reclaim_work);
1740 		cancel_work_sync(&fs_info->async_data_reclaim_work);
1741 
1742 		btrfs_discard_cleanup(fs_info);
1743 
1744 		/* wait for the uuid_scan task to finish */
1745 		down(&fs_info->uuid_tree_rescan_sem);
1746 		/* avoid complains from lockdep et al. */
1747 		up(&fs_info->uuid_tree_rescan_sem);
1748 
1749 		btrfs_set_sb_rdonly(sb);
1750 
1751 		/*
1752 		 * Setting SB_RDONLY will put the cleaner thread to
1753 		 * sleep at the next loop if it's already active.
1754 		 * If it's already asleep, we'll leave unused block
1755 		 * groups on disk until we're mounted read-write again
1756 		 * unless we clean them up here.
1757 		 */
1758 		btrfs_delete_unused_bgs(fs_info);
1759 
1760 		/*
1761 		 * The cleaner task could be already running before we set the
1762 		 * flag BTRFS_FS_STATE_RO (and SB_RDONLY in the superblock).
1763 		 * We must make sure that after we finish the remount, i.e. after
1764 		 * we call btrfs_commit_super(), the cleaner can no longer start
1765 		 * a transaction - either because it was dropping a dead root,
1766 		 * running delayed iputs or deleting an unused block group (the
1767 		 * cleaner picked a block group from the list of unused block
1768 		 * groups before we were able to in the previous call to
1769 		 * btrfs_delete_unused_bgs()).
1770 		 */
1771 		wait_on_bit(&fs_info->flags, BTRFS_FS_CLEANER_RUNNING,
1772 			    TASK_UNINTERRUPTIBLE);
1773 
1774 		/*
1775 		 * We've set the superblock to RO mode, so we might have made
1776 		 * the cleaner task sleep without running all pending delayed
1777 		 * iputs. Go through all the delayed iputs here, so that if an
1778 		 * unmount happens without remounting RW we don't end up at
1779 		 * finishing close_ctree() with a non-empty list of delayed
1780 		 * iputs.
1781 		 */
1782 		btrfs_run_delayed_iputs(fs_info);
1783 
1784 		btrfs_dev_replace_suspend_for_unmount(fs_info);
1785 		btrfs_scrub_cancel(fs_info);
1786 		btrfs_pause_balance(fs_info);
1787 
1788 		/*
1789 		 * Pause the qgroup rescan worker if it is running. We don't want
1790 		 * it to be still running after we are in RO mode, as after that,
1791 		 * by the time we unmount, it might have left a transaction open,
1792 		 * so we would leak the transaction and/or crash.
1793 		 */
1794 		btrfs_qgroup_wait_for_completion(fs_info, false);
1795 
1796 		ret = btrfs_commit_super(fs_info);
1797 		if (ret)
1798 			goto restore;
1799 	} else {
1800 		if (BTRFS_FS_ERROR(fs_info)) {
1801 			btrfs_err(fs_info,
1802 				"Remounting read-write after error is not allowed");
1803 			ret = -EINVAL;
1804 			goto restore;
1805 		}
1806 		if (fs_info->fs_devices->rw_devices == 0) {
1807 			ret = -EACCES;
1808 			goto restore;
1809 		}
1810 
1811 		if (!btrfs_check_rw_degradable(fs_info, NULL)) {
1812 			btrfs_warn(fs_info,
1813 		"too many missing devices, writable remount is not allowed");
1814 			ret = -EACCES;
1815 			goto restore;
1816 		}
1817 
1818 		if (btrfs_super_log_root(fs_info->super_copy) != 0) {
1819 			btrfs_warn(fs_info,
1820 		"mount required to replay tree-log, cannot remount read-write");
1821 			ret = -EINVAL;
1822 			goto restore;
1823 		}
1824 
1825 		/*
1826 		 * NOTE: when remounting with a change that does writes, don't
1827 		 * put it anywhere above this point, as we are not sure to be
1828 		 * safe to write until we pass the above checks.
1829 		 */
1830 		ret = btrfs_start_pre_rw_mount(fs_info);
1831 		if (ret)
1832 			goto restore;
1833 
1834 		btrfs_clear_sb_rdonly(sb);
1835 
1836 		set_bit(BTRFS_FS_OPEN, &fs_info->flags);
1837 	}
1838 out:
1839 	/*
1840 	 * We need to set SB_I_VERSION here otherwise it'll get cleared by VFS,
1841 	 * since the absence of the flag means it can be toggled off by remount.
1842 	 */
1843 	*flags |= SB_I_VERSION;
1844 
1845 	wake_up_process(fs_info->transaction_kthread);
1846 	btrfs_remount_cleanup(fs_info, old_opts);
1847 	btrfs_clear_oneshot_options(fs_info);
1848 	clear_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state);
1849 
1850 	return 0;
1851 
1852 restore:
1853 	/* We've hit an error - don't reset SB_RDONLY */
1854 	if (sb_rdonly(sb))
1855 		old_flags |= SB_RDONLY;
1856 	if (!(old_flags & SB_RDONLY))
1857 		clear_bit(BTRFS_FS_STATE_RO, &fs_info->fs_state);
1858 	sb->s_flags = old_flags;
1859 	fs_info->mount_opt = old_opts;
1860 	fs_info->compress_type = old_compress_type;
1861 	fs_info->max_inline = old_max_inline;
1862 	btrfs_resize_thread_pool(fs_info,
1863 		old_thread_pool_size, fs_info->thread_pool_size);
1864 	fs_info->metadata_ratio = old_metadata_ratio;
1865 	btrfs_remount_cleanup(fs_info, old_opts);
1866 	clear_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state);
1867 
1868 	return ret;
1869 }
1870 
1871 /* Used to sort the devices by max_avail(descending sort) */
1872 static int btrfs_cmp_device_free_bytes(const void *a, const void *b)
1873 {
1874 	const struct btrfs_device_info *dev_info1 = a;
1875 	const struct btrfs_device_info *dev_info2 = b;
1876 
1877 	if (dev_info1->max_avail > dev_info2->max_avail)
1878 		return -1;
1879 	else if (dev_info1->max_avail < dev_info2->max_avail)
1880 		return 1;
1881 	return 0;
1882 }
1883 
1884 /*
1885  * sort the devices by max_avail, in which max free extent size of each device
1886  * is stored.(Descending Sort)
1887  */
1888 static inline void btrfs_descending_sort_devices(
1889 					struct btrfs_device_info *devices,
1890 					size_t nr_devices)
1891 {
1892 	sort(devices, nr_devices, sizeof(struct btrfs_device_info),
1893 	     btrfs_cmp_device_free_bytes, NULL);
1894 }
1895 
1896 /*
1897  * The helper to calc the free space on the devices that can be used to store
1898  * file data.
1899  */
1900 static inline int btrfs_calc_avail_data_space(struct btrfs_fs_info *fs_info,
1901 					      u64 *free_bytes)
1902 {
1903 	struct btrfs_device_info *devices_info;
1904 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
1905 	struct btrfs_device *device;
1906 	u64 type;
1907 	u64 avail_space;
1908 	u64 min_stripe_size;
1909 	int num_stripes = 1;
1910 	int i = 0, nr_devices;
1911 	const struct btrfs_raid_attr *rattr;
1912 
1913 	/*
1914 	 * We aren't under the device list lock, so this is racy-ish, but good
1915 	 * enough for our purposes.
1916 	 */
1917 	nr_devices = fs_info->fs_devices->open_devices;
1918 	if (!nr_devices) {
1919 		smp_mb();
1920 		nr_devices = fs_info->fs_devices->open_devices;
1921 		ASSERT(nr_devices);
1922 		if (!nr_devices) {
1923 			*free_bytes = 0;
1924 			return 0;
1925 		}
1926 	}
1927 
1928 	devices_info = kmalloc_array(nr_devices, sizeof(*devices_info),
1929 			       GFP_KERNEL);
1930 	if (!devices_info)
1931 		return -ENOMEM;
1932 
1933 	/* calc min stripe number for data space allocation */
1934 	type = btrfs_data_alloc_profile(fs_info);
1935 	rattr = &btrfs_raid_array[btrfs_bg_flags_to_raid_index(type)];
1936 
1937 	if (type & BTRFS_BLOCK_GROUP_RAID0)
1938 		num_stripes = nr_devices;
1939 	else if (type & BTRFS_BLOCK_GROUP_RAID1_MASK)
1940 		num_stripes = rattr->ncopies;
1941 	else if (type & BTRFS_BLOCK_GROUP_RAID10)
1942 		num_stripes = 4;
1943 
1944 	/* Adjust for more than 1 stripe per device */
1945 	min_stripe_size = rattr->dev_stripes * BTRFS_STRIPE_LEN;
1946 
1947 	rcu_read_lock();
1948 	list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
1949 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
1950 						&device->dev_state) ||
1951 		    !device->bdev ||
1952 		    test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
1953 			continue;
1954 
1955 		if (i >= nr_devices)
1956 			break;
1957 
1958 		avail_space = device->total_bytes - device->bytes_used;
1959 
1960 		/* align with stripe_len */
1961 		avail_space = rounddown(avail_space, BTRFS_STRIPE_LEN);
1962 
1963 		/*
1964 		 * Ensure we have at least min_stripe_size on top of the
1965 		 * reserved space on the device.
1966 		 */
1967 		if (avail_space <= BTRFS_DEVICE_RANGE_RESERVED + min_stripe_size)
1968 			continue;
1969 
1970 		avail_space -= BTRFS_DEVICE_RANGE_RESERVED;
1971 
1972 		devices_info[i].dev = device;
1973 		devices_info[i].max_avail = avail_space;
1974 
1975 		i++;
1976 	}
1977 	rcu_read_unlock();
1978 
1979 	nr_devices = i;
1980 
1981 	btrfs_descending_sort_devices(devices_info, nr_devices);
1982 
1983 	i = nr_devices - 1;
1984 	avail_space = 0;
1985 	while (nr_devices >= rattr->devs_min) {
1986 		num_stripes = min(num_stripes, nr_devices);
1987 
1988 		if (devices_info[i].max_avail >= min_stripe_size) {
1989 			int j;
1990 			u64 alloc_size;
1991 
1992 			avail_space += devices_info[i].max_avail * num_stripes;
1993 			alloc_size = devices_info[i].max_avail;
1994 			for (j = i + 1 - num_stripes; j <= i; j++)
1995 				devices_info[j].max_avail -= alloc_size;
1996 		}
1997 		i--;
1998 		nr_devices--;
1999 	}
2000 
2001 	kfree(devices_info);
2002 	*free_bytes = avail_space;
2003 	return 0;
2004 }
2005 
2006 /*
2007  * Calculate numbers for 'df', pessimistic in case of mixed raid profiles.
2008  *
2009  * If there's a redundant raid level at DATA block groups, use the respective
2010  * multiplier to scale the sizes.
2011  *
2012  * Unused device space usage is based on simulating the chunk allocator
2013  * algorithm that respects the device sizes and order of allocations.  This is
2014  * a close approximation of the actual use but there are other factors that may
2015  * change the result (like a new metadata chunk).
2016  *
2017  * If metadata is exhausted, f_bavail will be 0.
2018  */
2019 static int btrfs_statfs(struct dentry *dentry, struct kstatfs *buf)
2020 {
2021 	struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
2022 	struct btrfs_super_block *disk_super = fs_info->super_copy;
2023 	struct btrfs_space_info *found;
2024 	u64 total_used = 0;
2025 	u64 total_free_data = 0;
2026 	u64 total_free_meta = 0;
2027 	u32 bits = fs_info->sectorsize_bits;
2028 	__be32 *fsid = (__be32 *)fs_info->fs_devices->fsid;
2029 	unsigned factor = 1;
2030 	struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
2031 	int ret;
2032 	u64 thresh = 0;
2033 	int mixed = 0;
2034 
2035 	list_for_each_entry(found, &fs_info->space_info, list) {
2036 		if (found->flags & BTRFS_BLOCK_GROUP_DATA) {
2037 			int i;
2038 
2039 			total_free_data += found->disk_total - found->disk_used;
2040 			total_free_data -=
2041 				btrfs_account_ro_block_groups_free_space(found);
2042 
2043 			for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
2044 				if (!list_empty(&found->block_groups[i]))
2045 					factor = btrfs_bg_type_to_factor(
2046 						btrfs_raid_array[i].bg_flag);
2047 			}
2048 		}
2049 
2050 		/*
2051 		 * Metadata in mixed block goup profiles are accounted in data
2052 		 */
2053 		if (!mixed && found->flags & BTRFS_BLOCK_GROUP_METADATA) {
2054 			if (found->flags & BTRFS_BLOCK_GROUP_DATA)
2055 				mixed = 1;
2056 			else
2057 				total_free_meta += found->disk_total -
2058 					found->disk_used;
2059 		}
2060 
2061 		total_used += found->disk_used;
2062 	}
2063 
2064 	buf->f_blocks = div_u64(btrfs_super_total_bytes(disk_super), factor);
2065 	buf->f_blocks >>= bits;
2066 	buf->f_bfree = buf->f_blocks - (div_u64(total_used, factor) >> bits);
2067 
2068 	/* Account global block reserve as used, it's in logical size already */
2069 	spin_lock(&block_rsv->lock);
2070 	/* Mixed block groups accounting is not byte-accurate, avoid overflow */
2071 	if (buf->f_bfree >= block_rsv->size >> bits)
2072 		buf->f_bfree -= block_rsv->size >> bits;
2073 	else
2074 		buf->f_bfree = 0;
2075 	spin_unlock(&block_rsv->lock);
2076 
2077 	buf->f_bavail = div_u64(total_free_data, factor);
2078 	ret = btrfs_calc_avail_data_space(fs_info, &total_free_data);
2079 	if (ret)
2080 		return ret;
2081 	buf->f_bavail += div_u64(total_free_data, factor);
2082 	buf->f_bavail = buf->f_bavail >> bits;
2083 
2084 	/*
2085 	 * We calculate the remaining metadata space minus global reserve. If
2086 	 * this is (supposedly) smaller than zero, there's no space. But this
2087 	 * does not hold in practice, the exhausted state happens where's still
2088 	 * some positive delta. So we apply some guesswork and compare the
2089 	 * delta to a 4M threshold.  (Practically observed delta was ~2M.)
2090 	 *
2091 	 * We probably cannot calculate the exact threshold value because this
2092 	 * depends on the internal reservations requested by various
2093 	 * operations, so some operations that consume a few metadata will
2094 	 * succeed even if the Avail is zero. But this is better than the other
2095 	 * way around.
2096 	 */
2097 	thresh = SZ_4M;
2098 
2099 	/*
2100 	 * We only want to claim there's no available space if we can no longer
2101 	 * allocate chunks for our metadata profile and our global reserve will
2102 	 * not fit in the free metadata space.  If we aren't ->full then we
2103 	 * still can allocate chunks and thus are fine using the currently
2104 	 * calculated f_bavail.
2105 	 */
2106 	if (!mixed && block_rsv->space_info->full &&
2107 	    total_free_meta - thresh < block_rsv->size)
2108 		buf->f_bavail = 0;
2109 
2110 	buf->f_type = BTRFS_SUPER_MAGIC;
2111 	buf->f_bsize = dentry->d_sb->s_blocksize;
2112 	buf->f_namelen = BTRFS_NAME_LEN;
2113 
2114 	/* We treat it as constant endianness (it doesn't matter _which_)
2115 	   because we want the fsid to come out the same whether mounted
2116 	   on a big-endian or little-endian host */
2117 	buf->f_fsid.val[0] = be32_to_cpu(fsid[0]) ^ be32_to_cpu(fsid[2]);
2118 	buf->f_fsid.val[1] = be32_to_cpu(fsid[1]) ^ be32_to_cpu(fsid[3]);
2119 	/* Mask in the root object ID too, to disambiguate subvols */
2120 	buf->f_fsid.val[0] ^=
2121 		BTRFS_I(d_inode(dentry))->root->root_key.objectid >> 32;
2122 	buf->f_fsid.val[1] ^=
2123 		BTRFS_I(d_inode(dentry))->root->root_key.objectid;
2124 
2125 	return 0;
2126 }
2127 
2128 static void btrfs_kill_super(struct super_block *sb)
2129 {
2130 	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
2131 	kill_anon_super(sb);
2132 	btrfs_free_fs_info(fs_info);
2133 }
2134 
2135 static struct file_system_type btrfs_fs_type = {
2136 	.owner		= THIS_MODULE,
2137 	.name		= "btrfs",
2138 	.mount		= btrfs_mount,
2139 	.kill_sb	= btrfs_kill_super,
2140 	.fs_flags	= FS_REQUIRES_DEV | FS_BINARY_MOUNTDATA,
2141 };
2142 
2143 static struct file_system_type btrfs_root_fs_type = {
2144 	.owner		= THIS_MODULE,
2145 	.name		= "btrfs",
2146 	.mount		= btrfs_mount_root,
2147 	.kill_sb	= btrfs_kill_super,
2148 	.fs_flags	= FS_REQUIRES_DEV | FS_BINARY_MOUNTDATA | FS_ALLOW_IDMAP,
2149 };
2150 
2151 MODULE_ALIAS_FS("btrfs");
2152 
2153 static int btrfs_control_open(struct inode *inode, struct file *file)
2154 {
2155 	/*
2156 	 * The control file's private_data is used to hold the
2157 	 * transaction when it is started and is used to keep
2158 	 * track of whether a transaction is already in progress.
2159 	 */
2160 	file->private_data = NULL;
2161 	return 0;
2162 }
2163 
2164 /*
2165  * Used by /dev/btrfs-control for devices ioctls.
2166  */
2167 static long btrfs_control_ioctl(struct file *file, unsigned int cmd,
2168 				unsigned long arg)
2169 {
2170 	struct btrfs_ioctl_vol_args *vol;
2171 	struct btrfs_device *device = NULL;
2172 	dev_t devt = 0;
2173 	int ret = -ENOTTY;
2174 
2175 	if (!capable(CAP_SYS_ADMIN))
2176 		return -EPERM;
2177 
2178 	vol = memdup_user((void __user *)arg, sizeof(*vol));
2179 	if (IS_ERR(vol))
2180 		return PTR_ERR(vol);
2181 	vol->name[BTRFS_PATH_NAME_MAX] = '\0';
2182 
2183 	switch (cmd) {
2184 	case BTRFS_IOC_SCAN_DEV:
2185 		mutex_lock(&uuid_mutex);
2186 		device = btrfs_scan_one_device(vol->name, FMODE_READ,
2187 					       &btrfs_root_fs_type);
2188 		ret = PTR_ERR_OR_ZERO(device);
2189 		mutex_unlock(&uuid_mutex);
2190 		break;
2191 	case BTRFS_IOC_FORGET_DEV:
2192 		if (vol->name[0] != 0) {
2193 			ret = lookup_bdev(vol->name, &devt);
2194 			if (ret)
2195 				break;
2196 		}
2197 		ret = btrfs_forget_devices(devt);
2198 		break;
2199 	case BTRFS_IOC_DEVICES_READY:
2200 		mutex_lock(&uuid_mutex);
2201 		device = btrfs_scan_one_device(vol->name, FMODE_READ,
2202 					       &btrfs_root_fs_type);
2203 		if (IS_ERR(device)) {
2204 			mutex_unlock(&uuid_mutex);
2205 			ret = PTR_ERR(device);
2206 			break;
2207 		}
2208 		ret = !(device->fs_devices->num_devices ==
2209 			device->fs_devices->total_devices);
2210 		mutex_unlock(&uuid_mutex);
2211 		break;
2212 	case BTRFS_IOC_GET_SUPPORTED_FEATURES:
2213 		ret = btrfs_ioctl_get_supported_features((void __user*)arg);
2214 		break;
2215 	}
2216 
2217 	kfree(vol);
2218 	return ret;
2219 }
2220 
2221 static int btrfs_freeze(struct super_block *sb)
2222 {
2223 	struct btrfs_trans_handle *trans;
2224 	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
2225 	struct btrfs_root *root = fs_info->tree_root;
2226 
2227 	set_bit(BTRFS_FS_FROZEN, &fs_info->flags);
2228 	/*
2229 	 * We don't need a barrier here, we'll wait for any transaction that
2230 	 * could be in progress on other threads (and do delayed iputs that
2231 	 * we want to avoid on a frozen filesystem), or do the commit
2232 	 * ourselves.
2233 	 */
2234 	trans = btrfs_attach_transaction_barrier(root);
2235 	if (IS_ERR(trans)) {
2236 		/* no transaction, don't bother */
2237 		if (PTR_ERR(trans) == -ENOENT)
2238 			return 0;
2239 		return PTR_ERR(trans);
2240 	}
2241 	return btrfs_commit_transaction(trans);
2242 }
2243 
2244 static int check_dev_super(struct btrfs_device *dev)
2245 {
2246 	struct btrfs_fs_info *fs_info = dev->fs_info;
2247 	struct btrfs_super_block *sb;
2248 	u16 csum_type;
2249 	int ret = 0;
2250 
2251 	/* This should be called with fs still frozen. */
2252 	ASSERT(test_bit(BTRFS_FS_FROZEN, &fs_info->flags));
2253 
2254 	/* Missing dev, no need to check. */
2255 	if (!dev->bdev)
2256 		return 0;
2257 
2258 	/* Only need to check the primary super block. */
2259 	sb = btrfs_read_dev_one_super(dev->bdev, 0, true);
2260 	if (IS_ERR(sb))
2261 		return PTR_ERR(sb);
2262 
2263 	/* Verify the checksum. */
2264 	csum_type = btrfs_super_csum_type(sb);
2265 	if (csum_type != btrfs_super_csum_type(fs_info->super_copy)) {
2266 		btrfs_err(fs_info, "csum type changed, has %u expect %u",
2267 			  csum_type, btrfs_super_csum_type(fs_info->super_copy));
2268 		ret = -EUCLEAN;
2269 		goto out;
2270 	}
2271 
2272 	if (btrfs_check_super_csum(fs_info, sb)) {
2273 		btrfs_err(fs_info, "csum for on-disk super block no longer matches");
2274 		ret = -EUCLEAN;
2275 		goto out;
2276 	}
2277 
2278 	/* Btrfs_validate_super() includes fsid check against super->fsid. */
2279 	ret = btrfs_validate_super(fs_info, sb, 0);
2280 	if (ret < 0)
2281 		goto out;
2282 
2283 	if (btrfs_super_generation(sb) != fs_info->last_trans_committed) {
2284 		btrfs_err(fs_info, "transid mismatch, has %llu expect %llu",
2285 			btrfs_super_generation(sb),
2286 			fs_info->last_trans_committed);
2287 		ret = -EUCLEAN;
2288 		goto out;
2289 	}
2290 out:
2291 	btrfs_release_disk_super(sb);
2292 	return ret;
2293 }
2294 
2295 static int btrfs_unfreeze(struct super_block *sb)
2296 {
2297 	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
2298 	struct btrfs_device *device;
2299 	int ret = 0;
2300 
2301 	/*
2302 	 * Make sure the fs is not changed by accident (like hibernation then
2303 	 * modified by other OS).
2304 	 * If we found anything wrong, we mark the fs error immediately.
2305 	 *
2306 	 * And since the fs is frozen, no one can modify the fs yet, thus
2307 	 * we don't need to hold device_list_mutex.
2308 	 */
2309 	list_for_each_entry(device, &fs_info->fs_devices->devices, dev_list) {
2310 		ret = check_dev_super(device);
2311 		if (ret < 0) {
2312 			btrfs_handle_fs_error(fs_info, ret,
2313 				"super block on devid %llu got modified unexpectedly",
2314 				device->devid);
2315 			break;
2316 		}
2317 	}
2318 	clear_bit(BTRFS_FS_FROZEN, &fs_info->flags);
2319 
2320 	/*
2321 	 * We still return 0, to allow VFS layer to unfreeze the fs even the
2322 	 * above checks failed. Since the fs is either fine or read-only, we're
2323 	 * safe to continue, without causing further damage.
2324 	 */
2325 	return 0;
2326 }
2327 
2328 static int btrfs_show_devname(struct seq_file *m, struct dentry *root)
2329 {
2330 	struct btrfs_fs_info *fs_info = btrfs_sb(root->d_sb);
2331 
2332 	/*
2333 	 * There should be always a valid pointer in latest_dev, it may be stale
2334 	 * for a short moment in case it's being deleted but still valid until
2335 	 * the end of RCU grace period.
2336 	 */
2337 	rcu_read_lock();
2338 	seq_escape(m, rcu_str_deref(fs_info->fs_devices->latest_dev->name), " \t\n\\");
2339 	rcu_read_unlock();
2340 
2341 	return 0;
2342 }
2343 
2344 static const struct super_operations btrfs_super_ops = {
2345 	.drop_inode	= btrfs_drop_inode,
2346 	.evict_inode	= btrfs_evict_inode,
2347 	.put_super	= btrfs_put_super,
2348 	.sync_fs	= btrfs_sync_fs,
2349 	.show_options	= btrfs_show_options,
2350 	.show_devname	= btrfs_show_devname,
2351 	.alloc_inode	= btrfs_alloc_inode,
2352 	.destroy_inode	= btrfs_destroy_inode,
2353 	.free_inode	= btrfs_free_inode,
2354 	.statfs		= btrfs_statfs,
2355 	.remount_fs	= btrfs_remount,
2356 	.freeze_fs	= btrfs_freeze,
2357 	.unfreeze_fs	= btrfs_unfreeze,
2358 };
2359 
2360 static const struct file_operations btrfs_ctl_fops = {
2361 	.open = btrfs_control_open,
2362 	.unlocked_ioctl	 = btrfs_control_ioctl,
2363 	.compat_ioctl = compat_ptr_ioctl,
2364 	.owner	 = THIS_MODULE,
2365 	.llseek = noop_llseek,
2366 };
2367 
2368 static struct miscdevice btrfs_misc = {
2369 	.minor		= BTRFS_MINOR,
2370 	.name		= "btrfs-control",
2371 	.fops		= &btrfs_ctl_fops
2372 };
2373 
2374 MODULE_ALIAS_MISCDEV(BTRFS_MINOR);
2375 MODULE_ALIAS("devname:btrfs-control");
2376 
2377 static int __init btrfs_interface_init(void)
2378 {
2379 	return misc_register(&btrfs_misc);
2380 }
2381 
2382 static __cold void btrfs_interface_exit(void)
2383 {
2384 	misc_deregister(&btrfs_misc);
2385 }
2386 
2387 static int __init btrfs_print_mod_info(void)
2388 {
2389 	static const char options[] = ""
2390 #ifdef CONFIG_BTRFS_DEBUG
2391 			", debug=on"
2392 #endif
2393 #ifdef CONFIG_BTRFS_ASSERT
2394 			", assert=on"
2395 #endif
2396 #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
2397 			", integrity-checker=on"
2398 #endif
2399 #ifdef CONFIG_BTRFS_FS_REF_VERIFY
2400 			", ref-verify=on"
2401 #endif
2402 #ifdef CONFIG_BLK_DEV_ZONED
2403 			", zoned=yes"
2404 #else
2405 			", zoned=no"
2406 #endif
2407 #ifdef CONFIG_FS_VERITY
2408 			", fsverity=yes"
2409 #else
2410 			", fsverity=no"
2411 #endif
2412 			;
2413 	pr_info("Btrfs loaded, crc32c=%s%s\n", crc32c_impl(), options);
2414 	return 0;
2415 }
2416 
2417 static int register_btrfs(void)
2418 {
2419 	return register_filesystem(&btrfs_fs_type);
2420 }
2421 
2422 static void unregister_btrfs(void)
2423 {
2424 	unregister_filesystem(&btrfs_fs_type);
2425 }
2426 
2427 /* Helper structure for long init/exit functions. */
2428 struct init_sequence {
2429 	int (*init_func)(void);
2430 	/* Can be NULL if the init_func doesn't need cleanup. */
2431 	void (*exit_func)(void);
2432 };
2433 
2434 static const struct init_sequence mod_init_seq[] = {
2435 	{
2436 		.init_func = btrfs_props_init,
2437 		.exit_func = NULL,
2438 	}, {
2439 		.init_func = btrfs_init_sysfs,
2440 		.exit_func = btrfs_exit_sysfs,
2441 	}, {
2442 		.init_func = btrfs_init_compress,
2443 		.exit_func = btrfs_exit_compress,
2444 	}, {
2445 		.init_func = btrfs_init_cachep,
2446 		.exit_func = btrfs_destroy_cachep,
2447 	}, {
2448 		.init_func = btrfs_transaction_init,
2449 		.exit_func = btrfs_transaction_exit,
2450 	}, {
2451 		.init_func = btrfs_ctree_init,
2452 		.exit_func = btrfs_ctree_exit,
2453 	}, {
2454 		.init_func = btrfs_free_space_init,
2455 		.exit_func = btrfs_free_space_exit,
2456 	}, {
2457 		.init_func = extent_state_init_cachep,
2458 		.exit_func = extent_state_free_cachep,
2459 	}, {
2460 		.init_func = extent_buffer_init_cachep,
2461 		.exit_func = extent_buffer_free_cachep,
2462 	}, {
2463 		.init_func = btrfs_bioset_init,
2464 		.exit_func = btrfs_bioset_exit,
2465 	}, {
2466 		.init_func = extent_map_init,
2467 		.exit_func = extent_map_exit,
2468 	}, {
2469 		.init_func = ordered_data_init,
2470 		.exit_func = ordered_data_exit,
2471 	}, {
2472 		.init_func = btrfs_delayed_inode_init,
2473 		.exit_func = btrfs_delayed_inode_exit,
2474 	}, {
2475 		.init_func = btrfs_auto_defrag_init,
2476 		.exit_func = btrfs_auto_defrag_exit,
2477 	}, {
2478 		.init_func = btrfs_delayed_ref_init,
2479 		.exit_func = btrfs_delayed_ref_exit,
2480 	}, {
2481 		.init_func = btrfs_prelim_ref_init,
2482 		.exit_func = btrfs_prelim_ref_exit,
2483 	}, {
2484 		.init_func = btrfs_interface_init,
2485 		.exit_func = btrfs_interface_exit,
2486 	}, {
2487 		.init_func = btrfs_print_mod_info,
2488 		.exit_func = NULL,
2489 	}, {
2490 		.init_func = btrfs_run_sanity_tests,
2491 		.exit_func = NULL,
2492 	}, {
2493 		.init_func = register_btrfs,
2494 		.exit_func = unregister_btrfs,
2495 	}
2496 };
2497 
2498 static bool mod_init_result[ARRAY_SIZE(mod_init_seq)];
2499 
2500 static __always_inline void btrfs_exit_btrfs_fs(void)
2501 {
2502 	int i;
2503 
2504 	for (i = ARRAY_SIZE(mod_init_seq) - 1; i >= 0; i--) {
2505 		if (!mod_init_result[i])
2506 			continue;
2507 		if (mod_init_seq[i].exit_func)
2508 			mod_init_seq[i].exit_func();
2509 		mod_init_result[i] = false;
2510 	}
2511 }
2512 
2513 static void __exit exit_btrfs_fs(void)
2514 {
2515 	btrfs_exit_btrfs_fs();
2516 }
2517 
2518 static int __init init_btrfs_fs(void)
2519 {
2520 	int ret;
2521 	int i;
2522 
2523 	for (i = 0; i < ARRAY_SIZE(mod_init_seq); i++) {
2524 		ASSERT(!mod_init_result[i]);
2525 		ret = mod_init_seq[i].init_func();
2526 		if (ret < 0) {
2527 			btrfs_exit_btrfs_fs();
2528 			return ret;
2529 		}
2530 		mod_init_result[i] = true;
2531 	}
2532 	return 0;
2533 }
2534 
2535 late_initcall(init_btrfs_fs);
2536 module_exit(exit_btrfs_fs)
2537 
2538 MODULE_LICENSE("GPL");
2539 MODULE_SOFTDEP("pre: crc32c");
2540 MODULE_SOFTDEP("pre: xxhash64");
2541 MODULE_SOFTDEP("pre: sha256");
2542 MODULE_SOFTDEP("pre: blake2b-256");
2543