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