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