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