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