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