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