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