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