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