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