1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
6 #include <linux/blkdev.h>
7 #include <linux/module.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>
32 #include "delayed-inode.h"
35 #include "transaction.h"
36 #include "btrfs_inode.h"
41 #include "compression.h"
42 #include "dev-replace.h"
43 #include "free-space-cache.h"
45 #include "space-info.h"
48 #include "tests/btrfs-tests.h"
49 #include "block-group.h"
54 #include "accessors.h"
61 #include "extent-tree.h"
62 #define CREATE_TRACE_POINTS
63 #include <trace/events/btrfs.h>
65 static const struct super_operations btrfs_super_ops;
66 static struct file_system_type btrfs_fs_type;
68 static void btrfs_put_super(struct super_block *sb)
70 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
72 btrfs_info(fs_info, "last unmount of filesystem %pU", fs_info->fs_devices->fsid);
76 /* Store the mount options related information. */
77 struct btrfs_fs_context {
84 unsigned long mount_opt;
85 unsigned long compress_type:4;
86 unsigned int compress_level;
96 Opt_compress_force_type,
110 Opt_rescan_uuid_tree,
113 Opt_space_cache_version,
121 Opt_user_subvol_rm_allowed,
132 /* Debugging options */
134 #ifdef CONFIG_BTRFS_DEBUG
135 Opt_fragment, Opt_fragment_data, Opt_fragment_metadata, Opt_fragment_all,
137 #ifdef CONFIG_BTRFS_FS_REF_VERIFY
144 Opt_fatal_errors_panic,
145 Opt_fatal_errors_bug,
148 static const struct constant_table btrfs_parameter_fatal_errors[] = {
149 { "panic", Opt_fatal_errors_panic },
150 { "bug", Opt_fatal_errors_bug },
159 static const struct constant_table btrfs_parameter_discard[] = {
160 { "sync", Opt_discard_sync },
161 { "async", Opt_discard_async },
170 static const struct constant_table btrfs_parameter_space_cache[] = {
171 { "v1", Opt_space_cache_v1 },
172 { "v2", Opt_space_cache_v2 },
177 Opt_rescue_usebackuproot,
178 Opt_rescue_nologreplay,
179 Opt_rescue_ignorebadroots,
180 Opt_rescue_ignoredatacsums,
181 Opt_rescue_parameter_all,
184 static const struct constant_table btrfs_parameter_rescue[] = {
185 { "usebackuproot", Opt_rescue_usebackuproot },
186 { "nologreplay", Opt_rescue_nologreplay },
187 { "ignorebadroots", Opt_rescue_ignorebadroots },
188 { "ibadroots", Opt_rescue_ignorebadroots },
189 { "ignoredatacsums", Opt_rescue_ignoredatacsums },
190 { "idatacsums", Opt_rescue_ignoredatacsums },
191 { "all", Opt_rescue_parameter_all },
195 #ifdef CONFIG_BTRFS_DEBUG
197 Opt_fragment_parameter_data,
198 Opt_fragment_parameter_metadata,
199 Opt_fragment_parameter_all,
202 static const struct constant_table btrfs_parameter_fragment[] = {
203 { "data", Opt_fragment_parameter_data },
204 { "metadata", Opt_fragment_parameter_metadata },
205 { "all", Opt_fragment_parameter_all },
210 static const struct fs_parameter_spec btrfs_fs_parameters[] = {
211 fsparam_flag_no("acl", Opt_acl),
212 fsparam_flag_no("autodefrag", Opt_defrag),
213 fsparam_flag_no("barrier", Opt_barrier),
214 fsparam_flag("clear_cache", Opt_clear_cache),
215 fsparam_u32("commit", Opt_commit_interval),
216 fsparam_flag("compress", Opt_compress),
217 fsparam_string("compress", Opt_compress_type),
218 fsparam_flag("compress-force", Opt_compress_force),
219 fsparam_string("compress-force", Opt_compress_force_type),
220 fsparam_flag_no("datacow", Opt_datacow),
221 fsparam_flag_no("datasum", Opt_datasum),
222 fsparam_flag("degraded", Opt_degraded),
223 fsparam_string("device", Opt_device),
224 fsparam_flag_no("discard", Opt_discard),
225 fsparam_enum("discard", Opt_discard_mode, btrfs_parameter_discard),
226 fsparam_enum("fatal_errors", Opt_fatal_errors, btrfs_parameter_fatal_errors),
227 fsparam_flag_no("flushoncommit", Opt_flushoncommit),
228 fsparam_string("max_inline", Opt_max_inline),
229 fsparam_u32("metadata_ratio", Opt_ratio),
230 fsparam_flag("rescan_uuid_tree", Opt_rescan_uuid_tree),
231 fsparam_flag("skip_balance", Opt_skip_balance),
232 fsparam_flag_no("space_cache", Opt_space_cache),
233 fsparam_enum("space_cache", Opt_space_cache_version, btrfs_parameter_space_cache),
234 fsparam_flag_no("ssd", Opt_ssd),
235 fsparam_flag_no("ssd_spread", Opt_ssd_spread),
236 fsparam_string("subvol", Opt_subvol),
237 fsparam_flag("subvol=", Opt_subvol_empty),
238 fsparam_u64("subvolid", Opt_subvolid),
239 fsparam_u32("thread_pool", Opt_thread_pool),
240 fsparam_flag_no("treelog", Opt_treelog),
241 fsparam_flag("user_subvol_rm_allowed", Opt_user_subvol_rm_allowed),
243 /* Rescue options. */
244 fsparam_enum("rescue", Opt_rescue, btrfs_parameter_rescue),
245 /* Deprecated, with alias rescue=nologreplay */
246 __fsparam(NULL, "nologreplay", Opt_nologreplay, fs_param_deprecated, NULL),
247 /* Deprecated, with alias rescue=usebackuproot */
248 __fsparam(NULL, "usebackuproot", Opt_usebackuproot, fs_param_deprecated, NULL),
249 /* For compatibility only, alias for "rescue=nologreplay". */
250 fsparam_flag("norecovery", Opt_norecovery),
252 /* Debugging options. */
253 fsparam_flag_no("enospc_debug", Opt_enospc_debug),
254 #ifdef CONFIG_BTRFS_DEBUG
255 fsparam_enum("fragment", Opt_fragment, btrfs_parameter_fragment),
257 #ifdef CONFIG_BTRFS_FS_REF_VERIFY
258 fsparam_flag("ref_verify", Opt_ref_verify),
263 /* No support for restricting writes to btrfs devices yet... */
264 static inline blk_mode_t btrfs_open_mode(struct fs_context *fc)
266 return sb_open_mode(fc->sb_flags) & ~BLK_OPEN_RESTRICT_WRITES;
269 static int btrfs_parse_param(struct fs_context *fc, struct fs_parameter *param)
271 struct btrfs_fs_context *ctx = fc->fs_private;
272 struct fs_parse_result result;
275 opt = fs_parse(fc, btrfs_fs_parameters, param, &result);
281 btrfs_set_opt(ctx->mount_opt, DEGRADED);
283 case Opt_subvol_empty:
285 * This exists because we used to allow it on accident, so we're
286 * keeping it to maintain ABI. See 37becec95ac3 ("Btrfs: allow
287 * empty subvol= again").
291 kfree(ctx->subvol_name);
292 ctx->subvol_name = kstrdup(param->string, GFP_KERNEL);
293 if (!ctx->subvol_name)
297 ctx->subvol_objectid = result.uint_64;
299 /* subvolid=0 means give me the original fs_tree. */
300 if (!ctx->subvol_objectid)
301 ctx->subvol_objectid = BTRFS_FS_TREE_OBJECTID;
304 struct btrfs_device *device;
305 blk_mode_t mode = btrfs_open_mode(fc);
307 mutex_lock(&uuid_mutex);
308 device = btrfs_scan_one_device(param->string, mode, false);
309 mutex_unlock(&uuid_mutex);
311 return PTR_ERR(device);
315 if (result.negated) {
316 btrfs_set_opt(ctx->mount_opt, NODATASUM);
318 btrfs_clear_opt(ctx->mount_opt, NODATACOW);
319 btrfs_clear_opt(ctx->mount_opt, NODATASUM);
323 if (result.negated) {
324 btrfs_clear_opt(ctx->mount_opt, COMPRESS);
325 btrfs_clear_opt(ctx->mount_opt, FORCE_COMPRESS);
326 btrfs_set_opt(ctx->mount_opt, NODATACOW);
327 btrfs_set_opt(ctx->mount_opt, NODATASUM);
329 btrfs_clear_opt(ctx->mount_opt, NODATACOW);
332 case Opt_compress_force:
333 case Opt_compress_force_type:
334 btrfs_set_opt(ctx->mount_opt, FORCE_COMPRESS);
337 case Opt_compress_type:
338 if (opt == Opt_compress || opt == Opt_compress_force) {
339 ctx->compress_type = BTRFS_COMPRESS_ZLIB;
340 ctx->compress_level = BTRFS_ZLIB_DEFAULT_LEVEL;
341 btrfs_set_opt(ctx->mount_opt, COMPRESS);
342 btrfs_clear_opt(ctx->mount_opt, NODATACOW);
343 btrfs_clear_opt(ctx->mount_opt, NODATASUM);
344 } else if (strncmp(param->string, "zlib", 4) == 0) {
345 ctx->compress_type = BTRFS_COMPRESS_ZLIB;
346 ctx->compress_level =
347 btrfs_compress_str2level(BTRFS_COMPRESS_ZLIB,
349 btrfs_set_opt(ctx->mount_opt, COMPRESS);
350 btrfs_clear_opt(ctx->mount_opt, NODATACOW);
351 btrfs_clear_opt(ctx->mount_opt, NODATASUM);
352 } else if (strncmp(param->string, "lzo", 3) == 0) {
353 ctx->compress_type = BTRFS_COMPRESS_LZO;
354 ctx->compress_level = 0;
355 btrfs_set_opt(ctx->mount_opt, COMPRESS);
356 btrfs_clear_opt(ctx->mount_opt, NODATACOW);
357 btrfs_clear_opt(ctx->mount_opt, NODATASUM);
358 } else if (strncmp(param->string, "zstd", 4) == 0) {
359 ctx->compress_type = BTRFS_COMPRESS_ZSTD;
360 ctx->compress_level =
361 btrfs_compress_str2level(BTRFS_COMPRESS_ZSTD,
363 btrfs_set_opt(ctx->mount_opt, COMPRESS);
364 btrfs_clear_opt(ctx->mount_opt, NODATACOW);
365 btrfs_clear_opt(ctx->mount_opt, NODATASUM);
366 } else if (strncmp(param->string, "no", 2) == 0) {
367 ctx->compress_level = 0;
368 ctx->compress_type = 0;
369 btrfs_clear_opt(ctx->mount_opt, COMPRESS);
370 btrfs_clear_opt(ctx->mount_opt, FORCE_COMPRESS);
372 btrfs_err(NULL, "unrecognized compression value %s",
378 if (result.negated) {
379 btrfs_set_opt(ctx->mount_opt, NOSSD);
380 btrfs_clear_opt(ctx->mount_opt, SSD);
381 btrfs_clear_opt(ctx->mount_opt, SSD_SPREAD);
383 btrfs_set_opt(ctx->mount_opt, SSD);
384 btrfs_clear_opt(ctx->mount_opt, NOSSD);
388 if (result.negated) {
389 btrfs_clear_opt(ctx->mount_opt, SSD_SPREAD);
391 btrfs_set_opt(ctx->mount_opt, SSD);
392 btrfs_set_opt(ctx->mount_opt, SSD_SPREAD);
393 btrfs_clear_opt(ctx->mount_opt, NOSSD);
398 btrfs_set_opt(ctx->mount_opt, NOBARRIER);
400 btrfs_clear_opt(ctx->mount_opt, NOBARRIER);
402 case Opt_thread_pool:
403 if (result.uint_32 == 0) {
404 btrfs_err(NULL, "invalid value 0 for thread_pool");
407 ctx->thread_pool_size = result.uint_32;
410 ctx->max_inline = memparse(param->string, NULL);
413 if (result.negated) {
414 fc->sb_flags &= ~SB_POSIXACL;
416 #ifdef CONFIG_BTRFS_FS_POSIX_ACL
417 fc->sb_flags |= SB_POSIXACL;
419 btrfs_err(NULL, "support for ACL not compiled in");
424 * VFS limits the ability to toggle ACL on and off via remount,
425 * despite every file system allowing this. This seems to be
426 * an oversight since we all do, but it'll fail if we're
427 * remounting. So don't set the mask here, we'll check it in
428 * btrfs_reconfigure and do the toggling ourselves.
430 if (fc->purpose != FS_CONTEXT_FOR_RECONFIGURE)
431 fc->sb_flags_mask |= SB_POSIXACL;
435 btrfs_set_opt(ctx->mount_opt, NOTREELOG);
437 btrfs_clear_opt(ctx->mount_opt, NOTREELOG);
439 case Opt_nologreplay:
441 "'nologreplay' is deprecated, use 'rescue=nologreplay' instead");
442 btrfs_set_opt(ctx->mount_opt, NOLOGREPLAY);
446 "'norecovery' is for compatibility only, recommended to use 'rescue=nologreplay'");
447 btrfs_set_opt(ctx->mount_opt, NOLOGREPLAY);
449 case Opt_flushoncommit:
451 btrfs_clear_opt(ctx->mount_opt, FLUSHONCOMMIT);
453 btrfs_set_opt(ctx->mount_opt, FLUSHONCOMMIT);
456 ctx->metadata_ratio = result.uint_32;
459 if (result.negated) {
460 btrfs_clear_opt(ctx->mount_opt, DISCARD_SYNC);
461 btrfs_clear_opt(ctx->mount_opt, DISCARD_ASYNC);
462 btrfs_set_opt(ctx->mount_opt, NODISCARD);
464 btrfs_set_opt(ctx->mount_opt, DISCARD_SYNC);
465 btrfs_clear_opt(ctx->mount_opt, DISCARD_ASYNC);
468 case Opt_discard_mode:
469 switch (result.uint_32) {
470 case Opt_discard_sync:
471 btrfs_clear_opt(ctx->mount_opt, DISCARD_ASYNC);
472 btrfs_set_opt(ctx->mount_opt, DISCARD_SYNC);
474 case Opt_discard_async:
475 btrfs_clear_opt(ctx->mount_opt, DISCARD_SYNC);
476 btrfs_set_opt(ctx->mount_opt, DISCARD_ASYNC);
479 btrfs_err(NULL, "unrecognized discard mode value %s",
483 btrfs_clear_opt(ctx->mount_opt, NODISCARD);
485 case Opt_space_cache:
486 if (result.negated) {
487 btrfs_set_opt(ctx->mount_opt, NOSPACECACHE);
488 btrfs_clear_opt(ctx->mount_opt, SPACE_CACHE);
489 btrfs_clear_opt(ctx->mount_opt, FREE_SPACE_TREE);
491 btrfs_clear_opt(ctx->mount_opt, FREE_SPACE_TREE);
492 btrfs_set_opt(ctx->mount_opt, SPACE_CACHE);
495 case Opt_space_cache_version:
496 switch (result.uint_32) {
497 case Opt_space_cache_v1:
498 btrfs_set_opt(ctx->mount_opt, SPACE_CACHE);
499 btrfs_clear_opt(ctx->mount_opt, FREE_SPACE_TREE);
501 case Opt_space_cache_v2:
502 btrfs_clear_opt(ctx->mount_opt, SPACE_CACHE);
503 btrfs_set_opt(ctx->mount_opt, FREE_SPACE_TREE);
506 btrfs_err(NULL, "unrecognized space_cache value %s",
511 case Opt_rescan_uuid_tree:
512 btrfs_set_opt(ctx->mount_opt, RESCAN_UUID_TREE);
514 case Opt_clear_cache:
515 btrfs_set_opt(ctx->mount_opt, CLEAR_CACHE);
517 case Opt_user_subvol_rm_allowed:
518 btrfs_set_opt(ctx->mount_opt, USER_SUBVOL_RM_ALLOWED);
520 case Opt_enospc_debug:
522 btrfs_clear_opt(ctx->mount_opt, ENOSPC_DEBUG);
524 btrfs_set_opt(ctx->mount_opt, ENOSPC_DEBUG);
528 btrfs_clear_opt(ctx->mount_opt, AUTO_DEFRAG);
530 btrfs_set_opt(ctx->mount_opt, AUTO_DEFRAG);
532 case Opt_usebackuproot:
534 "'usebackuproot' is deprecated, use 'rescue=usebackuproot' instead");
535 btrfs_set_opt(ctx->mount_opt, USEBACKUPROOT);
537 /* If we're loading the backup roots we can't trust the space cache. */
538 btrfs_set_opt(ctx->mount_opt, CLEAR_CACHE);
540 case Opt_skip_balance:
541 btrfs_set_opt(ctx->mount_opt, SKIP_BALANCE);
543 case Opt_fatal_errors:
544 switch (result.uint_32) {
545 case Opt_fatal_errors_panic:
546 btrfs_set_opt(ctx->mount_opt, PANIC_ON_FATAL_ERROR);
548 case Opt_fatal_errors_bug:
549 btrfs_clear_opt(ctx->mount_opt, PANIC_ON_FATAL_ERROR);
552 btrfs_err(NULL, "unrecognized fatal_errors value %s",
557 case Opt_commit_interval:
558 ctx->commit_interval = result.uint_32;
559 if (ctx->commit_interval == 0)
560 ctx->commit_interval = BTRFS_DEFAULT_COMMIT_INTERVAL;
563 switch (result.uint_32) {
564 case Opt_rescue_usebackuproot:
565 btrfs_set_opt(ctx->mount_opt, USEBACKUPROOT);
567 case Opt_rescue_nologreplay:
568 btrfs_set_opt(ctx->mount_opt, NOLOGREPLAY);
570 case Opt_rescue_ignorebadroots:
571 btrfs_set_opt(ctx->mount_opt, IGNOREBADROOTS);
573 case Opt_rescue_ignoredatacsums:
574 btrfs_set_opt(ctx->mount_opt, IGNOREDATACSUMS);
576 case Opt_rescue_parameter_all:
577 btrfs_set_opt(ctx->mount_opt, IGNOREDATACSUMS);
578 btrfs_set_opt(ctx->mount_opt, IGNOREBADROOTS);
579 btrfs_set_opt(ctx->mount_opt, NOLOGREPLAY);
582 btrfs_info(NULL, "unrecognized rescue option '%s'",
587 #ifdef CONFIG_BTRFS_DEBUG
589 switch (result.uint_32) {
590 case Opt_fragment_parameter_all:
591 btrfs_set_opt(ctx->mount_opt, FRAGMENT_DATA);
592 btrfs_set_opt(ctx->mount_opt, FRAGMENT_METADATA);
594 case Opt_fragment_parameter_metadata:
595 btrfs_set_opt(ctx->mount_opt, FRAGMENT_METADATA);
597 case Opt_fragment_parameter_data:
598 btrfs_set_opt(ctx->mount_opt, FRAGMENT_DATA);
601 btrfs_info(NULL, "unrecognized fragment option '%s'",
607 #ifdef CONFIG_BTRFS_FS_REF_VERIFY
609 btrfs_set_opt(ctx->mount_opt, REF_VERIFY);
613 btrfs_err(NULL, "unrecognized mount option '%s'", param->key);
621 * Some options only have meaning at mount time and shouldn't persist across
622 * remounts, or be displayed. Clear these at the end of mount and remount code
625 static void btrfs_clear_oneshot_options(struct btrfs_fs_info *fs_info)
627 btrfs_clear_opt(fs_info->mount_opt, USEBACKUPROOT);
628 btrfs_clear_opt(fs_info->mount_opt, CLEAR_CACHE);
629 btrfs_clear_opt(fs_info->mount_opt, NOSPACECACHE);
632 static bool check_ro_option(struct btrfs_fs_info *fs_info,
633 unsigned long mount_opt, unsigned long opt,
634 const char *opt_name)
636 if (mount_opt & opt) {
637 btrfs_err(fs_info, "%s must be used with ro mount option",
644 bool btrfs_check_options(struct btrfs_fs_info *info, unsigned long *mount_opt,
649 if (!(flags & SB_RDONLY) &&
650 (check_ro_option(info, *mount_opt, BTRFS_MOUNT_NOLOGREPLAY, "nologreplay") ||
651 check_ro_option(info, *mount_opt, BTRFS_MOUNT_IGNOREBADROOTS, "ignorebadroots") ||
652 check_ro_option(info, *mount_opt, BTRFS_MOUNT_IGNOREDATACSUMS, "ignoredatacsums")))
655 if (btrfs_fs_compat_ro(info, FREE_SPACE_TREE) &&
656 !btrfs_raw_test_opt(*mount_opt, FREE_SPACE_TREE) &&
657 !btrfs_raw_test_opt(*mount_opt, CLEAR_CACHE)) {
658 btrfs_err(info, "cannot disable free-space-tree");
661 if (btrfs_fs_compat_ro(info, BLOCK_GROUP_TREE) &&
662 !btrfs_raw_test_opt(*mount_opt, FREE_SPACE_TREE)) {
663 btrfs_err(info, "cannot disable free-space-tree with block-group-tree feature");
667 if (btrfs_check_mountopts_zoned(info, mount_opt))
670 if (!test_bit(BTRFS_FS_STATE_REMOUNTING, &info->fs_state)) {
671 if (btrfs_raw_test_opt(*mount_opt, SPACE_CACHE))
672 btrfs_info(info, "disk space caching is enabled");
673 if (btrfs_raw_test_opt(*mount_opt, FREE_SPACE_TREE))
674 btrfs_info(info, "using free-space-tree");
681 * This is subtle, we only call this during open_ctree(). We need to pre-load
682 * the mount options with the on-disk settings. Before the new mount API took
683 * effect we would do this on mount and remount. With the new mount API we'll
684 * only do this on the initial mount.
686 * This isn't a change in behavior, because we're using the current state of the
687 * file system to set the current mount options. If you mounted with special
688 * options to disable these features and then remounted we wouldn't revert the
689 * settings, because mounting without these features cleared the on-disk
690 * settings, so this being called on re-mount is not needed.
692 void btrfs_set_free_space_cache_settings(struct btrfs_fs_info *fs_info)
694 if (fs_info->sectorsize < PAGE_SIZE) {
695 btrfs_clear_opt(fs_info->mount_opt, SPACE_CACHE);
696 if (!btrfs_test_opt(fs_info, FREE_SPACE_TREE)) {
698 "forcing free space tree for sector size %u with page size %lu",
699 fs_info->sectorsize, PAGE_SIZE);
700 btrfs_set_opt(fs_info->mount_opt, FREE_SPACE_TREE);
705 * At this point our mount options are populated, so we only mess with
706 * these settings if we don't have any settings already.
708 if (btrfs_test_opt(fs_info, FREE_SPACE_TREE))
711 if (btrfs_is_zoned(fs_info) &&
712 btrfs_free_space_cache_v1_active(fs_info)) {
713 btrfs_info(fs_info, "zoned: clearing existing space cache");
714 btrfs_set_super_cache_generation(fs_info->super_copy, 0);
718 if (btrfs_test_opt(fs_info, SPACE_CACHE))
721 if (btrfs_test_opt(fs_info, NOSPACECACHE))
725 * At this point we don't have explicit options set by the user, set
726 * them ourselves based on the state of the file system.
728 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE))
729 btrfs_set_opt(fs_info->mount_opt, FREE_SPACE_TREE);
730 else if (btrfs_free_space_cache_v1_active(fs_info))
731 btrfs_set_opt(fs_info->mount_opt, SPACE_CACHE);
734 static void set_device_specific_options(struct btrfs_fs_info *fs_info)
736 if (!btrfs_test_opt(fs_info, NOSSD) &&
737 !fs_info->fs_devices->rotating)
738 btrfs_set_opt(fs_info->mount_opt, SSD);
741 * For devices supporting discard turn on discard=async automatically,
742 * unless it's already set or disabled. This could be turned off by
743 * nodiscard for the same mount.
745 * The zoned mode piggy backs on the discard functionality for
746 * resetting a zone. There is no reason to delay the zone reset as it is
747 * fast enough. So, do not enable async discard for zoned mode.
749 if (!(btrfs_test_opt(fs_info, DISCARD_SYNC) ||
750 btrfs_test_opt(fs_info, DISCARD_ASYNC) ||
751 btrfs_test_opt(fs_info, NODISCARD)) &&
752 fs_info->fs_devices->discardable &&
753 !btrfs_is_zoned(fs_info))
754 btrfs_set_opt(fs_info->mount_opt, DISCARD_ASYNC);
757 char *btrfs_get_subvol_name_from_objectid(struct btrfs_fs_info *fs_info,
760 struct btrfs_root *root = fs_info->tree_root;
761 struct btrfs_root *fs_root = NULL;
762 struct btrfs_root_ref *root_ref;
763 struct btrfs_inode_ref *inode_ref;
764 struct btrfs_key key;
765 struct btrfs_path *path = NULL;
766 char *name = NULL, *ptr;
771 path = btrfs_alloc_path();
777 name = kmalloc(PATH_MAX, GFP_KERNEL);
782 ptr = name + PATH_MAX - 1;
786 * Walk up the subvolume trees in the tree of tree roots by root
787 * backrefs until we hit the top-level subvolume.
789 while (subvol_objectid != BTRFS_FS_TREE_OBJECTID) {
790 key.objectid = subvol_objectid;
791 key.type = BTRFS_ROOT_BACKREF_KEY;
792 key.offset = (u64)-1;
794 ret = btrfs_search_backwards(root, &key, path);
797 } else if (ret > 0) {
802 subvol_objectid = key.offset;
804 root_ref = btrfs_item_ptr(path->nodes[0], path->slots[0],
805 struct btrfs_root_ref);
806 len = btrfs_root_ref_name_len(path->nodes[0], root_ref);
812 read_extent_buffer(path->nodes[0], ptr + 1,
813 (unsigned long)(root_ref + 1), len);
815 dirid = btrfs_root_ref_dirid(path->nodes[0], root_ref);
816 btrfs_release_path(path);
818 fs_root = btrfs_get_fs_root(fs_info, subvol_objectid, true);
819 if (IS_ERR(fs_root)) {
820 ret = PTR_ERR(fs_root);
826 * Walk up the filesystem tree by inode refs until we hit the
829 while (dirid != BTRFS_FIRST_FREE_OBJECTID) {
830 key.objectid = dirid;
831 key.type = BTRFS_INODE_REF_KEY;
832 key.offset = (u64)-1;
834 ret = btrfs_search_backwards(fs_root, &key, path);
837 } else if (ret > 0) {
844 inode_ref = btrfs_item_ptr(path->nodes[0],
846 struct btrfs_inode_ref);
847 len = btrfs_inode_ref_name_len(path->nodes[0],
854 read_extent_buffer(path->nodes[0], ptr + 1,
855 (unsigned long)(inode_ref + 1), len);
857 btrfs_release_path(path);
859 btrfs_put_root(fs_root);
863 btrfs_free_path(path);
864 if (ptr == name + PATH_MAX - 1) {
868 memmove(name, ptr, name + PATH_MAX - ptr);
873 btrfs_put_root(fs_root);
874 btrfs_free_path(path);
879 static int get_default_subvol_objectid(struct btrfs_fs_info *fs_info, u64 *objectid)
881 struct btrfs_root *root = fs_info->tree_root;
882 struct btrfs_dir_item *di;
883 struct btrfs_path *path;
884 struct btrfs_key location;
885 struct fscrypt_str name = FSTR_INIT("default", 7);
888 path = btrfs_alloc_path();
893 * Find the "default" dir item which points to the root item that we
894 * will mount by default if we haven't been given a specific subvolume
897 dir_id = btrfs_super_root_dir(fs_info->super_copy);
898 di = btrfs_lookup_dir_item(NULL, root, path, dir_id, &name, 0);
900 btrfs_free_path(path);
905 * Ok the default dir item isn't there. This is weird since
906 * it's always been there, but don't freak out, just try and
907 * mount the top-level subvolume.
909 btrfs_free_path(path);
910 *objectid = BTRFS_FS_TREE_OBJECTID;
914 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &location);
915 btrfs_free_path(path);
916 *objectid = location.objectid;
920 static int btrfs_fill_super(struct super_block *sb,
921 struct btrfs_fs_devices *fs_devices,
925 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
928 sb->s_maxbytes = MAX_LFS_FILESIZE;
929 sb->s_magic = BTRFS_SUPER_MAGIC;
930 sb->s_op = &btrfs_super_ops;
931 sb->s_d_op = &btrfs_dentry_operations;
932 sb->s_export_op = &btrfs_export_ops;
933 #ifdef CONFIG_FS_VERITY
934 sb->s_vop = &btrfs_verityops;
936 sb->s_xattr = btrfs_xattr_handlers;
938 sb->s_iflags |= SB_I_CGROUPWB;
940 err = super_setup_bdi(sb);
942 btrfs_err(fs_info, "super_setup_bdi failed");
946 err = open_ctree(sb, fs_devices, (char *)data);
948 btrfs_err(fs_info, "open_ctree failed");
952 inode = btrfs_iget(sb, BTRFS_FIRST_FREE_OBJECTID, fs_info->fs_root);
954 err = PTR_ERR(inode);
955 btrfs_handle_fs_error(fs_info, err, NULL);
959 sb->s_root = d_make_root(inode);
965 sb->s_flags |= SB_ACTIVE;
969 close_ctree(fs_info);
973 int btrfs_sync_fs(struct super_block *sb, int wait)
975 struct btrfs_trans_handle *trans;
976 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
977 struct btrfs_root *root = fs_info->tree_root;
979 trace_btrfs_sync_fs(fs_info, wait);
982 filemap_flush(fs_info->btree_inode->i_mapping);
986 btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
988 trans = btrfs_attach_transaction_barrier(root);
990 /* no transaction, don't bother */
991 if (PTR_ERR(trans) == -ENOENT) {
993 * Exit unless we have some pending changes
994 * that need to go through commit
996 if (!test_bit(BTRFS_FS_NEED_TRANS_COMMIT,
1000 * A non-blocking test if the fs is frozen. We must not
1001 * start a new transaction here otherwise a deadlock
1002 * happens. The pending operations are delayed to the
1003 * next commit after thawing.
1005 if (sb_start_write_trylock(sb))
1009 trans = btrfs_start_transaction(root, 0);
1012 return PTR_ERR(trans);
1014 return btrfs_commit_transaction(trans);
1017 static void print_rescue_option(struct seq_file *seq, const char *s, bool *printed)
1019 seq_printf(seq, "%s%s", (*printed) ? ":" : ",rescue=", s);
1023 static int btrfs_show_options(struct seq_file *seq, struct dentry *dentry)
1025 struct btrfs_fs_info *info = btrfs_sb(dentry->d_sb);
1026 const char *compress_type;
1027 const char *subvol_name;
1028 bool printed = false;
1030 if (btrfs_test_opt(info, DEGRADED))
1031 seq_puts(seq, ",degraded");
1032 if (btrfs_test_opt(info, NODATASUM))
1033 seq_puts(seq, ",nodatasum");
1034 if (btrfs_test_opt(info, NODATACOW))
1035 seq_puts(seq, ",nodatacow");
1036 if (btrfs_test_opt(info, NOBARRIER))
1037 seq_puts(seq, ",nobarrier");
1038 if (info->max_inline != BTRFS_DEFAULT_MAX_INLINE)
1039 seq_printf(seq, ",max_inline=%llu", info->max_inline);
1040 if (info->thread_pool_size != min_t(unsigned long,
1041 num_online_cpus() + 2, 8))
1042 seq_printf(seq, ",thread_pool=%u", info->thread_pool_size);
1043 if (btrfs_test_opt(info, COMPRESS)) {
1044 compress_type = btrfs_compress_type2str(info->compress_type);
1045 if (btrfs_test_opt(info, FORCE_COMPRESS))
1046 seq_printf(seq, ",compress-force=%s", compress_type);
1048 seq_printf(seq, ",compress=%s", compress_type);
1049 if (info->compress_level)
1050 seq_printf(seq, ":%d", info->compress_level);
1052 if (btrfs_test_opt(info, NOSSD))
1053 seq_puts(seq, ",nossd");
1054 if (btrfs_test_opt(info, SSD_SPREAD))
1055 seq_puts(seq, ",ssd_spread");
1056 else if (btrfs_test_opt(info, SSD))
1057 seq_puts(seq, ",ssd");
1058 if (btrfs_test_opt(info, NOTREELOG))
1059 seq_puts(seq, ",notreelog");
1060 if (btrfs_test_opt(info, NOLOGREPLAY))
1061 print_rescue_option(seq, "nologreplay", &printed);
1062 if (btrfs_test_opt(info, USEBACKUPROOT))
1063 print_rescue_option(seq, "usebackuproot", &printed);
1064 if (btrfs_test_opt(info, IGNOREBADROOTS))
1065 print_rescue_option(seq, "ignorebadroots", &printed);
1066 if (btrfs_test_opt(info, IGNOREDATACSUMS))
1067 print_rescue_option(seq, "ignoredatacsums", &printed);
1068 if (btrfs_test_opt(info, FLUSHONCOMMIT))
1069 seq_puts(seq, ",flushoncommit");
1070 if (btrfs_test_opt(info, DISCARD_SYNC))
1071 seq_puts(seq, ",discard");
1072 if (btrfs_test_opt(info, DISCARD_ASYNC))
1073 seq_puts(seq, ",discard=async");
1074 if (!(info->sb->s_flags & SB_POSIXACL))
1075 seq_puts(seq, ",noacl");
1076 if (btrfs_free_space_cache_v1_active(info))
1077 seq_puts(seq, ",space_cache");
1078 else if (btrfs_fs_compat_ro(info, FREE_SPACE_TREE))
1079 seq_puts(seq, ",space_cache=v2");
1081 seq_puts(seq, ",nospace_cache");
1082 if (btrfs_test_opt(info, RESCAN_UUID_TREE))
1083 seq_puts(seq, ",rescan_uuid_tree");
1084 if (btrfs_test_opt(info, CLEAR_CACHE))
1085 seq_puts(seq, ",clear_cache");
1086 if (btrfs_test_opt(info, USER_SUBVOL_RM_ALLOWED))
1087 seq_puts(seq, ",user_subvol_rm_allowed");
1088 if (btrfs_test_opt(info, ENOSPC_DEBUG))
1089 seq_puts(seq, ",enospc_debug");
1090 if (btrfs_test_opt(info, AUTO_DEFRAG))
1091 seq_puts(seq, ",autodefrag");
1092 if (btrfs_test_opt(info, SKIP_BALANCE))
1093 seq_puts(seq, ",skip_balance");
1094 if (info->metadata_ratio)
1095 seq_printf(seq, ",metadata_ratio=%u", info->metadata_ratio);
1096 if (btrfs_test_opt(info, PANIC_ON_FATAL_ERROR))
1097 seq_puts(seq, ",fatal_errors=panic");
1098 if (info->commit_interval != BTRFS_DEFAULT_COMMIT_INTERVAL)
1099 seq_printf(seq, ",commit=%u", info->commit_interval);
1100 #ifdef CONFIG_BTRFS_DEBUG
1101 if (btrfs_test_opt(info, FRAGMENT_DATA))
1102 seq_puts(seq, ",fragment=data");
1103 if (btrfs_test_opt(info, FRAGMENT_METADATA))
1104 seq_puts(seq, ",fragment=metadata");
1106 if (btrfs_test_opt(info, REF_VERIFY))
1107 seq_puts(seq, ",ref_verify");
1108 seq_printf(seq, ",subvolid=%llu", btrfs_root_id(BTRFS_I(d_inode(dentry))->root));
1109 subvol_name = btrfs_get_subvol_name_from_objectid(info,
1110 btrfs_root_id(BTRFS_I(d_inode(dentry))->root));
1111 if (!IS_ERR(subvol_name)) {
1112 seq_puts(seq, ",subvol=");
1113 seq_escape(seq, subvol_name, " \t\n\\");
1120 * subvolumes are identified by ino 256
1122 static inline int is_subvolume_inode(struct inode *inode)
1124 if (inode && inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)
1129 static struct dentry *mount_subvol(const char *subvol_name, u64 subvol_objectid,
1130 struct vfsmount *mnt)
1132 struct dentry *root;
1136 if (!subvol_objectid) {
1137 ret = get_default_subvol_objectid(btrfs_sb(mnt->mnt_sb),
1140 root = ERR_PTR(ret);
1144 subvol_name = btrfs_get_subvol_name_from_objectid(
1145 btrfs_sb(mnt->mnt_sb), subvol_objectid);
1146 if (IS_ERR(subvol_name)) {
1147 root = ERR_CAST(subvol_name);
1154 root = mount_subtree(mnt, subvol_name);
1155 /* mount_subtree() drops our reference on the vfsmount. */
1158 if (!IS_ERR(root)) {
1159 struct super_block *s = root->d_sb;
1160 struct btrfs_fs_info *fs_info = btrfs_sb(s);
1161 struct inode *root_inode = d_inode(root);
1162 u64 root_objectid = btrfs_root_id(BTRFS_I(root_inode)->root);
1165 if (!is_subvolume_inode(root_inode)) {
1166 btrfs_err(fs_info, "'%s' is not a valid subvolume",
1170 if (subvol_objectid && root_objectid != subvol_objectid) {
1172 * This will also catch a race condition where a
1173 * subvolume which was passed by ID is renamed and
1174 * another subvolume is renamed over the old location.
1177 "subvol '%s' does not match subvolid %llu",
1178 subvol_name, subvol_objectid);
1183 root = ERR_PTR(ret);
1184 deactivate_locked_super(s);
1194 static void btrfs_resize_thread_pool(struct btrfs_fs_info *fs_info,
1195 u32 new_pool_size, u32 old_pool_size)
1197 if (new_pool_size == old_pool_size)
1200 fs_info->thread_pool_size = new_pool_size;
1202 btrfs_info(fs_info, "resize thread pool %d -> %d",
1203 old_pool_size, new_pool_size);
1205 btrfs_workqueue_set_max(fs_info->workers, new_pool_size);
1206 btrfs_workqueue_set_max(fs_info->delalloc_workers, new_pool_size);
1207 btrfs_workqueue_set_max(fs_info->caching_workers, new_pool_size);
1208 workqueue_set_max_active(fs_info->endio_workers, new_pool_size);
1209 workqueue_set_max_active(fs_info->endio_meta_workers, new_pool_size);
1210 btrfs_workqueue_set_max(fs_info->endio_write_workers, new_pool_size);
1211 btrfs_workqueue_set_max(fs_info->endio_freespace_worker, new_pool_size);
1212 btrfs_workqueue_set_max(fs_info->delayed_workers, new_pool_size);
1215 static inline void btrfs_remount_begin(struct btrfs_fs_info *fs_info,
1216 unsigned long old_opts, int flags)
1218 if (btrfs_raw_test_opt(old_opts, AUTO_DEFRAG) &&
1219 (!btrfs_raw_test_opt(fs_info->mount_opt, AUTO_DEFRAG) ||
1220 (flags & SB_RDONLY))) {
1221 /* wait for any defraggers to finish */
1222 wait_event(fs_info->transaction_wait,
1223 (atomic_read(&fs_info->defrag_running) == 0));
1224 if (flags & SB_RDONLY)
1225 sync_filesystem(fs_info->sb);
1229 static inline void btrfs_remount_cleanup(struct btrfs_fs_info *fs_info,
1230 unsigned long old_opts)
1232 const bool cache_opt = btrfs_test_opt(fs_info, SPACE_CACHE);
1235 * We need to cleanup all defragable inodes if the autodefragment is
1236 * close or the filesystem is read only.
1238 if (btrfs_raw_test_opt(old_opts, AUTO_DEFRAG) &&
1239 (!btrfs_raw_test_opt(fs_info->mount_opt, AUTO_DEFRAG) || sb_rdonly(fs_info->sb))) {
1240 btrfs_cleanup_defrag_inodes(fs_info);
1243 /* If we toggled discard async */
1244 if (!btrfs_raw_test_opt(old_opts, DISCARD_ASYNC) &&
1245 btrfs_test_opt(fs_info, DISCARD_ASYNC))
1246 btrfs_discard_resume(fs_info);
1247 else if (btrfs_raw_test_opt(old_opts, DISCARD_ASYNC) &&
1248 !btrfs_test_opt(fs_info, DISCARD_ASYNC))
1249 btrfs_discard_cleanup(fs_info);
1251 /* If we toggled space cache */
1252 if (cache_opt != btrfs_free_space_cache_v1_active(fs_info))
1253 btrfs_set_free_space_cache_v1_active(fs_info, cache_opt);
1256 static int btrfs_remount_rw(struct btrfs_fs_info *fs_info)
1260 if (BTRFS_FS_ERROR(fs_info)) {
1262 "remounting read-write after error is not allowed");
1266 if (fs_info->fs_devices->rw_devices == 0)
1269 if (!btrfs_check_rw_degradable(fs_info, NULL)) {
1271 "too many missing devices, writable remount is not allowed");
1275 if (btrfs_super_log_root(fs_info->super_copy) != 0) {
1277 "mount required to replay tree-log, cannot remount read-write");
1282 * NOTE: when remounting with a change that does writes, don't put it
1283 * anywhere above this point, as we are not sure to be safe to write
1284 * until we pass the above checks.
1286 ret = btrfs_start_pre_rw_mount(fs_info);
1290 btrfs_clear_sb_rdonly(fs_info->sb);
1292 set_bit(BTRFS_FS_OPEN, &fs_info->flags);
1295 * If we've gone from readonly -> read-write, we need to get our
1296 * sync/async discard lists in the right state.
1298 btrfs_discard_resume(fs_info);
1303 static int btrfs_remount_ro(struct btrfs_fs_info *fs_info)
1306 * This also happens on 'umount -rf' or on shutdown, when the
1307 * filesystem is busy.
1309 cancel_work_sync(&fs_info->async_reclaim_work);
1310 cancel_work_sync(&fs_info->async_data_reclaim_work);
1312 btrfs_discard_cleanup(fs_info);
1314 /* Wait for the uuid_scan task to finish */
1315 down(&fs_info->uuid_tree_rescan_sem);
1316 /* Avoid complains from lockdep et al. */
1317 up(&fs_info->uuid_tree_rescan_sem);
1319 btrfs_set_sb_rdonly(fs_info->sb);
1322 * Setting SB_RDONLY will put the cleaner thread to sleep at the next
1323 * loop if it's already active. If it's already asleep, we'll leave
1324 * unused block groups on disk until we're mounted read-write again
1325 * unless we clean them up here.
1327 btrfs_delete_unused_bgs(fs_info);
1330 * The cleaner task could be already running before we set the flag
1331 * BTRFS_FS_STATE_RO (and SB_RDONLY in the superblock). We must make
1332 * sure that after we finish the remount, i.e. after we call
1333 * btrfs_commit_super(), the cleaner can no longer start a transaction
1334 * - either because it was dropping a dead root, running delayed iputs
1335 * or deleting an unused block group (the cleaner picked a block
1336 * group from the list of unused block groups before we were able to
1337 * in the previous call to btrfs_delete_unused_bgs()).
1339 wait_on_bit(&fs_info->flags, BTRFS_FS_CLEANER_RUNNING, TASK_UNINTERRUPTIBLE);
1342 * We've set the superblock to RO mode, so we might have made the
1343 * cleaner task sleep without running all pending delayed iputs. Go
1344 * through all the delayed iputs here, so that if an unmount happens
1345 * without remounting RW we don't end up at finishing close_ctree()
1346 * with a non-empty list of delayed iputs.
1348 btrfs_run_delayed_iputs(fs_info);
1350 btrfs_dev_replace_suspend_for_unmount(fs_info);
1351 btrfs_scrub_cancel(fs_info);
1352 btrfs_pause_balance(fs_info);
1355 * Pause the qgroup rescan worker if it is running. We don't want it to
1356 * be still running after we are in RO mode, as after that, by the time
1357 * we unmount, it might have left a transaction open, so we would leak
1358 * the transaction and/or crash.
1360 btrfs_qgroup_wait_for_completion(fs_info, false);
1362 return btrfs_commit_super(fs_info);
1365 static void btrfs_ctx_to_info(struct btrfs_fs_info *fs_info, struct btrfs_fs_context *ctx)
1367 fs_info->max_inline = ctx->max_inline;
1368 fs_info->commit_interval = ctx->commit_interval;
1369 fs_info->metadata_ratio = ctx->metadata_ratio;
1370 fs_info->thread_pool_size = ctx->thread_pool_size;
1371 fs_info->mount_opt = ctx->mount_opt;
1372 fs_info->compress_type = ctx->compress_type;
1373 fs_info->compress_level = ctx->compress_level;
1376 static void btrfs_info_to_ctx(struct btrfs_fs_info *fs_info, struct btrfs_fs_context *ctx)
1378 ctx->max_inline = fs_info->max_inline;
1379 ctx->commit_interval = fs_info->commit_interval;
1380 ctx->metadata_ratio = fs_info->metadata_ratio;
1381 ctx->thread_pool_size = fs_info->thread_pool_size;
1382 ctx->mount_opt = fs_info->mount_opt;
1383 ctx->compress_type = fs_info->compress_type;
1384 ctx->compress_level = fs_info->compress_level;
1387 #define btrfs_info_if_set(fs_info, old_ctx, opt, fmt, args...) \
1389 if ((!old_ctx || !btrfs_raw_test_opt(old_ctx->mount_opt, opt)) && \
1390 btrfs_raw_test_opt(fs_info->mount_opt, opt)) \
1391 btrfs_info(fs_info, fmt, ##args); \
1394 #define btrfs_info_if_unset(fs_info, old_ctx, opt, fmt, args...) \
1396 if ((old_ctx && btrfs_raw_test_opt(old_ctx->mount_opt, opt)) && \
1397 !btrfs_raw_test_opt(fs_info->mount_opt, opt)) \
1398 btrfs_info(fs_info, fmt, ##args); \
1401 static void btrfs_emit_options(struct btrfs_fs_info *info,
1402 struct btrfs_fs_context *old)
1404 btrfs_info_if_set(info, old, NODATASUM, "setting nodatasum");
1405 btrfs_info_if_set(info, old, DEGRADED, "allowing degraded mounts");
1406 btrfs_info_if_set(info, old, NODATASUM, "setting nodatasum");
1407 btrfs_info_if_set(info, old, SSD, "enabling ssd optimizations");
1408 btrfs_info_if_set(info, old, SSD_SPREAD, "using spread ssd allocation scheme");
1409 btrfs_info_if_set(info, old, NOBARRIER, "turning off barriers");
1410 btrfs_info_if_set(info, old, NOTREELOG, "disabling tree log");
1411 btrfs_info_if_set(info, old, NOLOGREPLAY, "disabling log replay at mount time");
1412 btrfs_info_if_set(info, old, FLUSHONCOMMIT, "turning on flush-on-commit");
1413 btrfs_info_if_set(info, old, DISCARD_SYNC, "turning on sync discard");
1414 btrfs_info_if_set(info, old, DISCARD_ASYNC, "turning on async discard");
1415 btrfs_info_if_set(info, old, FREE_SPACE_TREE, "enabling free space tree");
1416 btrfs_info_if_set(info, old, SPACE_CACHE, "enabling disk space caching");
1417 btrfs_info_if_set(info, old, CLEAR_CACHE, "force clearing of disk cache");
1418 btrfs_info_if_set(info, old, AUTO_DEFRAG, "enabling auto defrag");
1419 btrfs_info_if_set(info, old, FRAGMENT_DATA, "fragmenting data");
1420 btrfs_info_if_set(info, old, FRAGMENT_METADATA, "fragmenting metadata");
1421 btrfs_info_if_set(info, old, REF_VERIFY, "doing ref verification");
1422 btrfs_info_if_set(info, old, USEBACKUPROOT, "trying to use backup root at mount time");
1423 btrfs_info_if_set(info, old, IGNOREBADROOTS, "ignoring bad roots");
1424 btrfs_info_if_set(info, old, IGNOREDATACSUMS, "ignoring data csums");
1426 btrfs_info_if_unset(info, old, NODATACOW, "setting datacow");
1427 btrfs_info_if_unset(info, old, SSD, "not using ssd optimizations");
1428 btrfs_info_if_unset(info, old, SSD_SPREAD, "not using spread ssd allocation scheme");
1429 btrfs_info_if_unset(info, old, NOBARRIER, "turning off barriers");
1430 btrfs_info_if_unset(info, old, NOTREELOG, "enabling tree log");
1431 btrfs_info_if_unset(info, old, SPACE_CACHE, "disabling disk space caching");
1432 btrfs_info_if_unset(info, old, FREE_SPACE_TREE, "disabling free space tree");
1433 btrfs_info_if_unset(info, old, AUTO_DEFRAG, "disabling auto defrag");
1434 btrfs_info_if_unset(info, old, COMPRESS, "use no compression");
1436 /* Did the compression settings change? */
1437 if (btrfs_test_opt(info, COMPRESS) &&
1439 old->compress_type != info->compress_type ||
1440 old->compress_level != info->compress_level ||
1441 (!btrfs_raw_test_opt(old->mount_opt, FORCE_COMPRESS) &&
1442 btrfs_raw_test_opt(info->mount_opt, FORCE_COMPRESS)))) {
1443 const char *compress_type = btrfs_compress_type2str(info->compress_type);
1445 btrfs_info(info, "%s %s compression, level %d",
1446 btrfs_test_opt(info, FORCE_COMPRESS) ? "force" : "use",
1447 compress_type, info->compress_level);
1450 if (info->max_inline != BTRFS_DEFAULT_MAX_INLINE)
1451 btrfs_info(info, "max_inline set to %llu", info->max_inline);
1454 static int btrfs_reconfigure(struct fs_context *fc)
1456 struct super_block *sb = fc->root->d_sb;
1457 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
1458 struct btrfs_fs_context *ctx = fc->fs_private;
1459 struct btrfs_fs_context old_ctx;
1461 bool mount_reconfigure = (fc->s_fs_info != NULL);
1463 btrfs_info_to_ctx(fs_info, &old_ctx);
1466 * This is our "bind mount" trick, we don't want to allow the user to do
1467 * anything other than mount a different ro/rw and a different subvol,
1468 * all of the mount options should be maintained.
1470 if (mount_reconfigure)
1471 ctx->mount_opt = old_ctx.mount_opt;
1473 sync_filesystem(sb);
1474 set_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state);
1476 if (!mount_reconfigure &&
1477 !btrfs_check_options(fs_info, &ctx->mount_opt, fc->sb_flags))
1480 ret = btrfs_check_features(fs_info, !(fc->sb_flags & SB_RDONLY));
1484 btrfs_ctx_to_info(fs_info, ctx);
1485 btrfs_remount_begin(fs_info, old_ctx.mount_opt, fc->sb_flags);
1486 btrfs_resize_thread_pool(fs_info, fs_info->thread_pool_size,
1487 old_ctx.thread_pool_size);
1489 if ((bool)btrfs_test_opt(fs_info, FREE_SPACE_TREE) !=
1490 (bool)btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
1491 (!sb_rdonly(sb) || (fc->sb_flags & SB_RDONLY))) {
1493 "remount supports changing free space tree only from RO to RW");
1494 /* Make sure free space cache options match the state on disk. */
1495 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
1496 btrfs_set_opt(fs_info->mount_opt, FREE_SPACE_TREE);
1497 btrfs_clear_opt(fs_info->mount_opt, SPACE_CACHE);
1499 if (btrfs_free_space_cache_v1_active(fs_info)) {
1500 btrfs_clear_opt(fs_info->mount_opt, FREE_SPACE_TREE);
1501 btrfs_set_opt(fs_info->mount_opt, SPACE_CACHE);
1506 if (!sb_rdonly(sb) && (fc->sb_flags & SB_RDONLY))
1507 ret = btrfs_remount_ro(fs_info);
1508 else if (sb_rdonly(sb) && !(fc->sb_flags & SB_RDONLY))
1509 ret = btrfs_remount_rw(fs_info);
1514 * If we set the mask during the parameter parsing VFS would reject the
1515 * remount. Here we can set the mask and the value will be updated
1518 if ((fc->sb_flags & SB_POSIXACL) != (sb->s_flags & SB_POSIXACL))
1519 fc->sb_flags_mask |= SB_POSIXACL;
1521 btrfs_emit_options(fs_info, &old_ctx);
1522 wake_up_process(fs_info->transaction_kthread);
1523 btrfs_remount_cleanup(fs_info, old_ctx.mount_opt);
1524 btrfs_clear_oneshot_options(fs_info);
1525 clear_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state);
1529 btrfs_ctx_to_info(fs_info, &old_ctx);
1530 btrfs_remount_cleanup(fs_info, old_ctx.mount_opt);
1531 clear_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state);
1535 /* Used to sort the devices by max_avail(descending sort) */
1536 static int btrfs_cmp_device_free_bytes(const void *a, const void *b)
1538 const struct btrfs_device_info *dev_info1 = a;
1539 const struct btrfs_device_info *dev_info2 = b;
1541 if (dev_info1->max_avail > dev_info2->max_avail)
1543 else if (dev_info1->max_avail < dev_info2->max_avail)
1549 * sort the devices by max_avail, in which max free extent size of each device
1550 * is stored.(Descending Sort)
1552 static inline void btrfs_descending_sort_devices(
1553 struct btrfs_device_info *devices,
1556 sort(devices, nr_devices, sizeof(struct btrfs_device_info),
1557 btrfs_cmp_device_free_bytes, NULL);
1561 * The helper to calc the free space on the devices that can be used to store
1564 static inline int btrfs_calc_avail_data_space(struct btrfs_fs_info *fs_info,
1567 struct btrfs_device_info *devices_info;
1568 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
1569 struct btrfs_device *device;
1572 u64 min_stripe_size;
1573 int num_stripes = 1;
1574 int i = 0, nr_devices;
1575 const struct btrfs_raid_attr *rattr;
1578 * We aren't under the device list lock, so this is racy-ish, but good
1579 * enough for our purposes.
1581 nr_devices = fs_info->fs_devices->open_devices;
1584 nr_devices = fs_info->fs_devices->open_devices;
1592 devices_info = kmalloc_array(nr_devices, sizeof(*devices_info),
1597 /* calc min stripe number for data space allocation */
1598 type = btrfs_data_alloc_profile(fs_info);
1599 rattr = &btrfs_raid_array[btrfs_bg_flags_to_raid_index(type)];
1601 if (type & BTRFS_BLOCK_GROUP_RAID0)
1602 num_stripes = nr_devices;
1603 else if (type & BTRFS_BLOCK_GROUP_RAID1_MASK)
1604 num_stripes = rattr->ncopies;
1605 else if (type & BTRFS_BLOCK_GROUP_RAID10)
1608 /* Adjust for more than 1 stripe per device */
1609 min_stripe_size = rattr->dev_stripes * BTRFS_STRIPE_LEN;
1612 list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
1613 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
1614 &device->dev_state) ||
1616 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
1619 if (i >= nr_devices)
1622 avail_space = device->total_bytes - device->bytes_used;
1624 /* align with stripe_len */
1625 avail_space = rounddown(avail_space, BTRFS_STRIPE_LEN);
1628 * Ensure we have at least min_stripe_size on top of the
1629 * reserved space on the device.
1631 if (avail_space <= BTRFS_DEVICE_RANGE_RESERVED + min_stripe_size)
1634 avail_space -= BTRFS_DEVICE_RANGE_RESERVED;
1636 devices_info[i].dev = device;
1637 devices_info[i].max_avail = avail_space;
1645 btrfs_descending_sort_devices(devices_info, nr_devices);
1649 while (nr_devices >= rattr->devs_min) {
1650 num_stripes = min(num_stripes, nr_devices);
1652 if (devices_info[i].max_avail >= min_stripe_size) {
1656 avail_space += devices_info[i].max_avail * num_stripes;
1657 alloc_size = devices_info[i].max_avail;
1658 for (j = i + 1 - num_stripes; j <= i; j++)
1659 devices_info[j].max_avail -= alloc_size;
1665 kfree(devices_info);
1666 *free_bytes = avail_space;
1671 * Calculate numbers for 'df', pessimistic in case of mixed raid profiles.
1673 * If there's a redundant raid level at DATA block groups, use the respective
1674 * multiplier to scale the sizes.
1676 * Unused device space usage is based on simulating the chunk allocator
1677 * algorithm that respects the device sizes and order of allocations. This is
1678 * a close approximation of the actual use but there are other factors that may
1679 * change the result (like a new metadata chunk).
1681 * If metadata is exhausted, f_bavail will be 0.
1683 static int btrfs_statfs(struct dentry *dentry, struct kstatfs *buf)
1685 struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
1686 struct btrfs_super_block *disk_super = fs_info->super_copy;
1687 struct btrfs_space_info *found;
1689 u64 total_free_data = 0;
1690 u64 total_free_meta = 0;
1691 u32 bits = fs_info->sectorsize_bits;
1692 __be32 *fsid = (__be32 *)fs_info->fs_devices->fsid;
1693 unsigned factor = 1;
1694 struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
1699 list_for_each_entry(found, &fs_info->space_info, list) {
1700 if (found->flags & BTRFS_BLOCK_GROUP_DATA) {
1703 total_free_data += found->disk_total - found->disk_used;
1705 btrfs_account_ro_block_groups_free_space(found);
1707 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
1708 if (!list_empty(&found->block_groups[i]))
1709 factor = btrfs_bg_type_to_factor(
1710 btrfs_raid_array[i].bg_flag);
1715 * Metadata in mixed block group profiles are accounted in data
1717 if (!mixed && found->flags & BTRFS_BLOCK_GROUP_METADATA) {
1718 if (found->flags & BTRFS_BLOCK_GROUP_DATA)
1721 total_free_meta += found->disk_total -
1725 total_used += found->disk_used;
1728 buf->f_blocks = div_u64(btrfs_super_total_bytes(disk_super), factor);
1729 buf->f_blocks >>= bits;
1730 buf->f_bfree = buf->f_blocks - (div_u64(total_used, factor) >> bits);
1732 /* Account global block reserve as used, it's in logical size already */
1733 spin_lock(&block_rsv->lock);
1734 /* Mixed block groups accounting is not byte-accurate, avoid overflow */
1735 if (buf->f_bfree >= block_rsv->size >> bits)
1736 buf->f_bfree -= block_rsv->size >> bits;
1739 spin_unlock(&block_rsv->lock);
1741 buf->f_bavail = div_u64(total_free_data, factor);
1742 ret = btrfs_calc_avail_data_space(fs_info, &total_free_data);
1745 buf->f_bavail += div_u64(total_free_data, factor);
1746 buf->f_bavail = buf->f_bavail >> bits;
1749 * We calculate the remaining metadata space minus global reserve. If
1750 * this is (supposedly) smaller than zero, there's no space. But this
1751 * does not hold in practice, the exhausted state happens where's still
1752 * some positive delta. So we apply some guesswork and compare the
1753 * delta to a 4M threshold. (Practically observed delta was ~2M.)
1755 * We probably cannot calculate the exact threshold value because this
1756 * depends on the internal reservations requested by various
1757 * operations, so some operations that consume a few metadata will
1758 * succeed even if the Avail is zero. But this is better than the other
1764 * We only want to claim there's no available space if we can no longer
1765 * allocate chunks for our metadata profile and our global reserve will
1766 * not fit in the free metadata space. If we aren't ->full then we
1767 * still can allocate chunks and thus are fine using the currently
1768 * calculated f_bavail.
1770 if (!mixed && block_rsv->space_info->full &&
1771 (total_free_meta < thresh || total_free_meta - thresh < block_rsv->size))
1774 buf->f_type = BTRFS_SUPER_MAGIC;
1775 buf->f_bsize = fs_info->sectorsize;
1776 buf->f_namelen = BTRFS_NAME_LEN;
1778 /* We treat it as constant endianness (it doesn't matter _which_)
1779 because we want the fsid to come out the same whether mounted
1780 on a big-endian or little-endian host */
1781 buf->f_fsid.val[0] = be32_to_cpu(fsid[0]) ^ be32_to_cpu(fsid[2]);
1782 buf->f_fsid.val[1] = be32_to_cpu(fsid[1]) ^ be32_to_cpu(fsid[3]);
1783 /* Mask in the root object ID too, to disambiguate subvols */
1784 buf->f_fsid.val[0] ^= btrfs_root_id(BTRFS_I(d_inode(dentry))->root) >> 32;
1785 buf->f_fsid.val[1] ^= btrfs_root_id(BTRFS_I(d_inode(dentry))->root);
1790 static int btrfs_fc_test_super(struct super_block *sb, struct fs_context *fc)
1792 struct btrfs_fs_info *p = fc->s_fs_info;
1793 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
1795 return fs_info->fs_devices == p->fs_devices;
1798 static int btrfs_get_tree_super(struct fs_context *fc)
1800 struct btrfs_fs_info *fs_info = fc->s_fs_info;
1801 struct btrfs_fs_context *ctx = fc->fs_private;
1802 struct btrfs_fs_devices *fs_devices = NULL;
1803 struct block_device *bdev;
1804 struct btrfs_device *device;
1805 struct super_block *sb;
1806 blk_mode_t mode = btrfs_open_mode(fc);
1809 btrfs_ctx_to_info(fs_info, ctx);
1810 mutex_lock(&uuid_mutex);
1813 * With 'true' passed to btrfs_scan_one_device() (mount time) we expect
1814 * either a valid device or an error.
1816 device = btrfs_scan_one_device(fc->source, mode, true);
1817 ASSERT(device != NULL);
1818 if (IS_ERR(device)) {
1819 mutex_unlock(&uuid_mutex);
1820 return PTR_ERR(device);
1823 fs_devices = device->fs_devices;
1824 fs_info->fs_devices = fs_devices;
1826 ret = btrfs_open_devices(fs_devices, mode, &btrfs_fs_type);
1827 mutex_unlock(&uuid_mutex);
1831 if (!(fc->sb_flags & SB_RDONLY) && fs_devices->rw_devices == 0) {
1836 bdev = fs_devices->latest_dev->bdev;
1839 * From now on the error handling is not straightforward.
1841 * If successful, this will transfer the fs_info into the super block,
1842 * and fc->s_fs_info will be NULL. However if there's an existing
1843 * super, we'll still have fc->s_fs_info populated. If we error
1844 * completely out it'll be cleaned up when we drop the fs_context,
1845 * otherwise it's tied to the lifetime of the super_block.
1847 sb = sget_fc(fc, btrfs_fc_test_super, set_anon_super_fc);
1853 set_device_specific_options(fs_info);
1856 btrfs_close_devices(fs_devices);
1857 if ((fc->sb_flags ^ sb->s_flags) & SB_RDONLY)
1860 snprintf(sb->s_id, sizeof(sb->s_id), "%pg", bdev);
1861 shrinker_debugfs_rename(sb->s_shrink, "sb-btrfs:%s", sb->s_id);
1862 btrfs_sb(sb)->bdev_holder = &btrfs_fs_type;
1863 ret = btrfs_fill_super(sb, fs_devices, NULL);
1867 deactivate_locked_super(sb);
1871 btrfs_clear_oneshot_options(fs_info);
1873 fc->root = dget(sb->s_root);
1877 btrfs_close_devices(fs_devices);
1882 * Ever since commit 0723a0473fb4 ("btrfs: allow mounting btrfs subvolumes
1883 * with different ro/rw options") the following works:
1885 * (i) mount /dev/sda3 -o subvol=foo,ro /mnt/foo
1886 * (ii) mount /dev/sda3 -o subvol=bar,rw /mnt/bar
1888 * which looks nice and innocent but is actually pretty intricate and deserves
1891 * On another filesystem a subvolume mount is close to something like:
1893 * (iii) # create rw superblock + initial mount
1894 * mount -t xfs /dev/sdb /opt/
1896 * # create ro bind mount
1897 * mount --bind -o ro /opt/foo /mnt/foo
1899 * # unmount initial mount
1902 * Of course, there's some special subvolume sauce and there's the fact that the
1903 * sb->s_root dentry is really swapped after mount_subtree(). But conceptually
1904 * it's very close and will help us understand the issue.
1906 * The old mount API didn't cleanly distinguish between a mount being made ro
1907 * and a superblock being made ro. The only way to change the ro state of
1908 * either object was by passing ms_rdonly. If a new mount was created via
1911 * mount("/dev/sdb", "/mnt", "xfs", ms_rdonly, null);
1913 * the MS_RDONLY flag being specified had two effects:
1915 * (1) MNT_READONLY was raised -> the resulting mount got
1916 * @mnt->mnt_flags |= MNT_READONLY raised.
1918 * (2) MS_RDONLY was passed to the filesystem's mount method and the filesystems
1919 * made the superblock ro. Note, how SB_RDONLY has the same value as
1920 * ms_rdonly and is raised whenever MS_RDONLY is passed through mount(2).
1922 * Creating a subtree mount via (iii) ends up leaving a rw superblock with a
1923 * subtree mounted ro.
1925 * But consider the effect on the old mount API on btrfs subvolume mounting
1926 * which combines the distinct step in (iii) into a single step.
1928 * By issuing (i) both the mount and the superblock are turned ro. Now when (ii)
1929 * is issued the superblock is ro and thus even if the mount created for (ii) is
1930 * rw it wouldn't help. Hence, btrfs needed to transition the superblock from ro
1931 * to rw for (ii) which it did using an internal remount call.
1933 * IOW, subvolume mounting was inherently complicated due to the ambiguity of
1934 * MS_RDONLY in mount(2). Note, this ambiguity has mount(8) always translate
1935 * "ro" to MS_RDONLY. IOW, in both (i) and (ii) "ro" becomes MS_RDONLY when
1936 * passed by mount(8) to mount(2).
1938 * Enter the new mount API. The new mount API disambiguates making a mount ro
1939 * and making a superblock ro.
1941 * (3) To turn a mount ro the MOUNT_ATTR_ONLY flag can be used with either
1942 * fsmount() or mount_setattr() this is a pure VFS level change for a
1943 * specific mount or mount tree that is never seen by the filesystem itself.
1945 * (4) To turn a superblock ro the "ro" flag must be used with
1946 * fsconfig(FSCONFIG_SET_FLAG, "ro"). This option is seen by the filesystem
1949 * This disambiguation has rather positive consequences. Mounting a subvolume
1950 * ro will not also turn the superblock ro. Only the mount for the subvolume
1953 * So, if the superblock creation request comes from the new mount API the
1954 * caller must have explicitly done:
1956 * fsconfig(FSCONFIG_SET_FLAG, "ro")
1957 * fsmount/mount_setattr(MOUNT_ATTR_RDONLY)
1959 * IOW, at some point the caller must have explicitly turned the whole
1960 * superblock ro and we shouldn't just undo it like we did for the old mount
1961 * API. In any case, it lets us avoid the hack in the new mount API.
1963 * Consequently, the remounting hack must only be used for requests originating
1964 * from the old mount API and should be marked for full deprecation so it can be
1965 * turned off in a couple of years.
1967 * The new mount API has no reason to support this hack.
1969 static struct vfsmount *btrfs_reconfigure_for_mount(struct fs_context *fc)
1971 struct vfsmount *mnt;
1973 const bool ro2rw = !(fc->sb_flags & SB_RDONLY);
1976 * We got an EBUSY because our SB_RDONLY flag didn't match the existing
1977 * super block, so invert our setting here and retry the mount so we
1978 * can get our vfsmount.
1981 fc->sb_flags |= SB_RDONLY;
1983 fc->sb_flags &= ~SB_RDONLY;
1989 if (!fc->oldapi || !ro2rw)
1992 /* We need to convert to rw, call reconfigure. */
1993 fc->sb_flags &= ~SB_RDONLY;
1994 down_write(&mnt->mnt_sb->s_umount);
1995 ret = btrfs_reconfigure(fc);
1996 up_write(&mnt->mnt_sb->s_umount);
1999 return ERR_PTR(ret);
2004 static int btrfs_get_tree_subvol(struct fs_context *fc)
2006 struct btrfs_fs_info *fs_info = NULL;
2007 struct btrfs_fs_context *ctx = fc->fs_private;
2008 struct fs_context *dup_fc;
2009 struct dentry *dentry;
2010 struct vfsmount *mnt;
2013 * Setup a dummy root and fs_info for test/set super. This is because
2014 * we don't actually fill this stuff out until open_ctree, but we need
2015 * then open_ctree will properly initialize the file system specific
2016 * settings later. btrfs_init_fs_info initializes the static elements
2017 * of the fs_info (locks and such) to make cleanup easier if we find a
2018 * superblock with our given fs_devices later on at sget() time.
2020 fs_info = kvzalloc(sizeof(struct btrfs_fs_info), GFP_KERNEL);
2024 fs_info->super_copy = kzalloc(BTRFS_SUPER_INFO_SIZE, GFP_KERNEL);
2025 fs_info->super_for_commit = kzalloc(BTRFS_SUPER_INFO_SIZE, GFP_KERNEL);
2026 if (!fs_info->super_copy || !fs_info->super_for_commit) {
2027 btrfs_free_fs_info(fs_info);
2030 btrfs_init_fs_info(fs_info);
2032 dup_fc = vfs_dup_fs_context(fc);
2033 if (IS_ERR(dup_fc)) {
2034 btrfs_free_fs_info(fs_info);
2035 return PTR_ERR(dup_fc);
2039 * When we do the sget_fc this gets transferred to the sb, so we only
2040 * need to set it on the dup_fc as this is what creates the super block.
2042 dup_fc->s_fs_info = fs_info;
2045 * We'll do the security settings in our btrfs_get_tree_super() mount
2046 * loop, they were duplicated into dup_fc, we can drop the originals
2049 security_free_mnt_opts(&fc->security);
2050 fc->security = NULL;
2052 mnt = fc_mount(dup_fc);
2053 if (PTR_ERR_OR_ZERO(mnt) == -EBUSY)
2054 mnt = btrfs_reconfigure_for_mount(dup_fc);
2055 put_fs_context(dup_fc);
2057 return PTR_ERR(mnt);
2060 * This free's ->subvol_name, because if it isn't set we have to
2061 * allocate a buffer to hold the subvol_name, so we just drop our
2062 * reference to it here.
2064 dentry = mount_subvol(ctx->subvol_name, ctx->subvol_objectid, mnt);
2065 ctx->subvol_name = NULL;
2067 return PTR_ERR(dentry);
2073 static int btrfs_get_tree(struct fs_context *fc)
2076 * Since we use mount_subtree to mount the default/specified subvol, we
2077 * have to do mounts in two steps.
2079 * First pass through we call btrfs_get_tree_subvol(), this is just a
2080 * wrapper around fc_mount() to call back into here again, and this time
2081 * we'll call btrfs_get_tree_super(). This will do the open_ctree() and
2082 * everything to open the devices and file system. Then we return back
2083 * with a fully constructed vfsmount in btrfs_get_tree_subvol(), and
2084 * from there we can do our mount_subvol() call, which will lookup
2085 * whichever subvol we're mounting and setup this fc with the
2086 * appropriate dentry for the subvol.
2089 return btrfs_get_tree_super(fc);
2090 return btrfs_get_tree_subvol(fc);
2093 static void btrfs_kill_super(struct super_block *sb)
2095 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
2096 kill_anon_super(sb);
2097 btrfs_free_fs_info(fs_info);
2100 static void btrfs_free_fs_context(struct fs_context *fc)
2102 struct btrfs_fs_context *ctx = fc->fs_private;
2103 struct btrfs_fs_info *fs_info = fc->s_fs_info;
2106 btrfs_free_fs_info(fs_info);
2108 if (ctx && refcount_dec_and_test(&ctx->refs)) {
2109 kfree(ctx->subvol_name);
2114 static int btrfs_dup_fs_context(struct fs_context *fc, struct fs_context *src_fc)
2116 struct btrfs_fs_context *ctx = src_fc->fs_private;
2119 * Give a ref to our ctx to this dup, as we want to keep it around for
2120 * our original fc so we can have the subvolume name or objectid.
2122 * We unset ->source in the original fc because the dup needs it for
2123 * mounting, and then once we free the dup it'll free ->source, so we
2124 * need to make sure we're only pointing to it in one fc.
2126 refcount_inc(&ctx->refs);
2127 fc->fs_private = ctx;
2128 fc->source = src_fc->source;
2129 src_fc->source = NULL;
2133 static const struct fs_context_operations btrfs_fs_context_ops = {
2134 .parse_param = btrfs_parse_param,
2135 .reconfigure = btrfs_reconfigure,
2136 .get_tree = btrfs_get_tree,
2137 .dup = btrfs_dup_fs_context,
2138 .free = btrfs_free_fs_context,
2141 static int btrfs_init_fs_context(struct fs_context *fc)
2143 struct btrfs_fs_context *ctx;
2145 ctx = kzalloc(sizeof(struct btrfs_fs_context), GFP_KERNEL);
2149 refcount_set(&ctx->refs, 1);
2150 fc->fs_private = ctx;
2151 fc->ops = &btrfs_fs_context_ops;
2153 if (fc->purpose == FS_CONTEXT_FOR_RECONFIGURE) {
2154 btrfs_info_to_ctx(btrfs_sb(fc->root->d_sb), ctx);
2156 ctx->thread_pool_size =
2157 min_t(unsigned long, num_online_cpus() + 2, 8);
2158 ctx->max_inline = BTRFS_DEFAULT_MAX_INLINE;
2159 ctx->commit_interval = BTRFS_DEFAULT_COMMIT_INTERVAL;
2162 #ifdef CONFIG_BTRFS_FS_POSIX_ACL
2163 fc->sb_flags |= SB_POSIXACL;
2165 fc->sb_flags |= SB_I_VERSION;
2170 static struct file_system_type btrfs_fs_type = {
2171 .owner = THIS_MODULE,
2173 .init_fs_context = btrfs_init_fs_context,
2174 .parameters = btrfs_fs_parameters,
2175 .kill_sb = btrfs_kill_super,
2176 .fs_flags = FS_REQUIRES_DEV | FS_BINARY_MOUNTDATA | FS_ALLOW_IDMAP,
2179 MODULE_ALIAS_FS("btrfs");
2181 static int btrfs_control_open(struct inode *inode, struct file *file)
2184 * The control file's private_data is used to hold the
2185 * transaction when it is started and is used to keep
2186 * track of whether a transaction is already in progress.
2188 file->private_data = NULL;
2193 * Used by /dev/btrfs-control for devices ioctls.
2195 static long btrfs_control_ioctl(struct file *file, unsigned int cmd,
2198 struct btrfs_ioctl_vol_args *vol;
2199 struct btrfs_device *device = NULL;
2203 if (!capable(CAP_SYS_ADMIN))
2206 vol = memdup_user((void __user *)arg, sizeof(*vol));
2208 return PTR_ERR(vol);
2209 ret = btrfs_check_ioctl_vol_args_path(vol);
2214 case BTRFS_IOC_SCAN_DEV:
2215 mutex_lock(&uuid_mutex);
2217 * Scanning outside of mount can return NULL which would turn
2218 * into 0 error code.
2220 device = btrfs_scan_one_device(vol->name, BLK_OPEN_READ, false);
2221 ret = PTR_ERR_OR_ZERO(device);
2222 mutex_unlock(&uuid_mutex);
2224 case BTRFS_IOC_FORGET_DEV:
2225 if (vol->name[0] != 0) {
2226 ret = lookup_bdev(vol->name, &devt);
2230 ret = btrfs_forget_devices(devt);
2232 case BTRFS_IOC_DEVICES_READY:
2233 mutex_lock(&uuid_mutex);
2235 * Scanning outside of mount can return NULL which would turn
2236 * into 0 error code.
2238 device = btrfs_scan_one_device(vol->name, BLK_OPEN_READ, false);
2239 if (IS_ERR_OR_NULL(device)) {
2240 mutex_unlock(&uuid_mutex);
2241 ret = PTR_ERR(device);
2244 ret = !(device->fs_devices->num_devices ==
2245 device->fs_devices->total_devices);
2246 mutex_unlock(&uuid_mutex);
2248 case BTRFS_IOC_GET_SUPPORTED_FEATURES:
2249 ret = btrfs_ioctl_get_supported_features((void __user*)arg);
2258 static int btrfs_freeze(struct super_block *sb)
2260 struct btrfs_trans_handle *trans;
2261 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
2262 struct btrfs_root *root = fs_info->tree_root;
2264 set_bit(BTRFS_FS_FROZEN, &fs_info->flags);
2266 * We don't need a barrier here, we'll wait for any transaction that
2267 * could be in progress on other threads (and do delayed iputs that
2268 * we want to avoid on a frozen filesystem), or do the commit
2271 trans = btrfs_attach_transaction_barrier(root);
2272 if (IS_ERR(trans)) {
2273 /* no transaction, don't bother */
2274 if (PTR_ERR(trans) == -ENOENT)
2276 return PTR_ERR(trans);
2278 return btrfs_commit_transaction(trans);
2281 static int check_dev_super(struct btrfs_device *dev)
2283 struct btrfs_fs_info *fs_info = dev->fs_info;
2284 struct btrfs_super_block *sb;
2289 /* This should be called with fs still frozen. */
2290 ASSERT(test_bit(BTRFS_FS_FROZEN, &fs_info->flags));
2292 /* Missing dev, no need to check. */
2296 /* Only need to check the primary super block. */
2297 sb = btrfs_read_dev_one_super(dev->bdev, 0, true);
2301 /* Verify the checksum. */
2302 csum_type = btrfs_super_csum_type(sb);
2303 if (csum_type != btrfs_super_csum_type(fs_info->super_copy)) {
2304 btrfs_err(fs_info, "csum type changed, has %u expect %u",
2305 csum_type, btrfs_super_csum_type(fs_info->super_copy));
2310 if (btrfs_check_super_csum(fs_info, sb)) {
2311 btrfs_err(fs_info, "csum for on-disk super block no longer matches");
2316 /* Btrfs_validate_super() includes fsid check against super->fsid. */
2317 ret = btrfs_validate_super(fs_info, sb, 0);
2321 last_trans = btrfs_get_last_trans_committed(fs_info);
2322 if (btrfs_super_generation(sb) != last_trans) {
2323 btrfs_err(fs_info, "transid mismatch, has %llu expect %llu",
2324 btrfs_super_generation(sb), last_trans);
2329 btrfs_release_disk_super(sb);
2333 static int btrfs_unfreeze(struct super_block *sb)
2335 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
2336 struct btrfs_device *device;
2340 * Make sure the fs is not changed by accident (like hibernation then
2341 * modified by other OS).
2342 * If we found anything wrong, we mark the fs error immediately.
2344 * And since the fs is frozen, no one can modify the fs yet, thus
2345 * we don't need to hold device_list_mutex.
2347 list_for_each_entry(device, &fs_info->fs_devices->devices, dev_list) {
2348 ret = check_dev_super(device);
2350 btrfs_handle_fs_error(fs_info, ret,
2351 "super block on devid %llu got modified unexpectedly",
2356 clear_bit(BTRFS_FS_FROZEN, &fs_info->flags);
2359 * We still return 0, to allow VFS layer to unfreeze the fs even the
2360 * above checks failed. Since the fs is either fine or read-only, we're
2361 * safe to continue, without causing further damage.
2366 static int btrfs_show_devname(struct seq_file *m, struct dentry *root)
2368 struct btrfs_fs_info *fs_info = btrfs_sb(root->d_sb);
2371 * There should be always a valid pointer in latest_dev, it may be stale
2372 * for a short moment in case it's being deleted but still valid until
2373 * the end of RCU grace period.
2376 seq_escape(m, btrfs_dev_name(fs_info->fs_devices->latest_dev), " \t\n\\");
2382 static long btrfs_nr_cached_objects(struct super_block *sb, struct shrink_control *sc)
2384 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
2385 const s64 nr = percpu_counter_sum_positive(&fs_info->evictable_extent_maps);
2387 trace_btrfs_extent_map_shrinker_count(fs_info, nr);
2392 static long btrfs_free_cached_objects(struct super_block *sb, struct shrink_control *sc)
2394 const long nr_to_scan = min_t(unsigned long, LONG_MAX, sc->nr_to_scan);
2395 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
2397 return btrfs_free_extent_maps(fs_info, nr_to_scan);
2400 static const struct super_operations btrfs_super_ops = {
2401 .drop_inode = btrfs_drop_inode,
2402 .evict_inode = btrfs_evict_inode,
2403 .put_super = btrfs_put_super,
2404 .sync_fs = btrfs_sync_fs,
2405 .show_options = btrfs_show_options,
2406 .show_devname = btrfs_show_devname,
2407 .alloc_inode = btrfs_alloc_inode,
2408 .destroy_inode = btrfs_destroy_inode,
2409 .free_inode = btrfs_free_inode,
2410 .statfs = btrfs_statfs,
2411 .freeze_fs = btrfs_freeze,
2412 .unfreeze_fs = btrfs_unfreeze,
2413 .nr_cached_objects = btrfs_nr_cached_objects,
2414 .free_cached_objects = btrfs_free_cached_objects,
2417 static const struct file_operations btrfs_ctl_fops = {
2418 .open = btrfs_control_open,
2419 .unlocked_ioctl = btrfs_control_ioctl,
2420 .compat_ioctl = compat_ptr_ioctl,
2421 .owner = THIS_MODULE,
2422 .llseek = noop_llseek,
2425 static struct miscdevice btrfs_misc = {
2426 .minor = BTRFS_MINOR,
2427 .name = "btrfs-control",
2428 .fops = &btrfs_ctl_fops
2431 MODULE_ALIAS_MISCDEV(BTRFS_MINOR);
2432 MODULE_ALIAS("devname:btrfs-control");
2434 static int __init btrfs_interface_init(void)
2436 return misc_register(&btrfs_misc);
2439 static __cold void btrfs_interface_exit(void)
2441 misc_deregister(&btrfs_misc);
2444 static int __init btrfs_print_mod_info(void)
2446 static const char options[] = ""
2447 #ifdef CONFIG_BTRFS_DEBUG
2450 #ifdef CONFIG_BTRFS_ASSERT
2453 #ifdef CONFIG_BTRFS_FS_REF_VERIFY
2456 #ifdef CONFIG_BLK_DEV_ZONED
2461 #ifdef CONFIG_FS_VERITY
2467 pr_info("Btrfs loaded%s\n", options);
2471 static int register_btrfs(void)
2473 return register_filesystem(&btrfs_fs_type);
2476 static void unregister_btrfs(void)
2478 unregister_filesystem(&btrfs_fs_type);
2481 /* Helper structure for long init/exit functions. */
2482 struct init_sequence {
2483 int (*init_func)(void);
2484 /* Can be NULL if the init_func doesn't need cleanup. */
2485 void (*exit_func)(void);
2488 static const struct init_sequence mod_init_seq[] = {
2490 .init_func = btrfs_props_init,
2493 .init_func = btrfs_init_sysfs,
2494 .exit_func = btrfs_exit_sysfs,
2496 .init_func = btrfs_init_compress,
2497 .exit_func = btrfs_exit_compress,
2499 .init_func = btrfs_init_cachep,
2500 .exit_func = btrfs_destroy_cachep,
2502 .init_func = btrfs_transaction_init,
2503 .exit_func = btrfs_transaction_exit,
2505 .init_func = btrfs_ctree_init,
2506 .exit_func = btrfs_ctree_exit,
2508 .init_func = btrfs_free_space_init,
2509 .exit_func = btrfs_free_space_exit,
2511 .init_func = extent_state_init_cachep,
2512 .exit_func = extent_state_free_cachep,
2514 .init_func = extent_buffer_init_cachep,
2515 .exit_func = extent_buffer_free_cachep,
2517 .init_func = btrfs_bioset_init,
2518 .exit_func = btrfs_bioset_exit,
2520 .init_func = extent_map_init,
2521 .exit_func = extent_map_exit,
2523 .init_func = ordered_data_init,
2524 .exit_func = ordered_data_exit,
2526 .init_func = btrfs_delayed_inode_init,
2527 .exit_func = btrfs_delayed_inode_exit,
2529 .init_func = btrfs_auto_defrag_init,
2530 .exit_func = btrfs_auto_defrag_exit,
2532 .init_func = btrfs_delayed_ref_init,
2533 .exit_func = btrfs_delayed_ref_exit,
2535 .init_func = btrfs_prelim_ref_init,
2536 .exit_func = btrfs_prelim_ref_exit,
2538 .init_func = btrfs_interface_init,
2539 .exit_func = btrfs_interface_exit,
2541 .init_func = btrfs_print_mod_info,
2544 .init_func = btrfs_run_sanity_tests,
2547 .init_func = register_btrfs,
2548 .exit_func = unregister_btrfs,
2552 static bool mod_init_result[ARRAY_SIZE(mod_init_seq)];
2554 static __always_inline void btrfs_exit_btrfs_fs(void)
2558 for (i = ARRAY_SIZE(mod_init_seq) - 1; i >= 0; i--) {
2559 if (!mod_init_result[i])
2561 if (mod_init_seq[i].exit_func)
2562 mod_init_seq[i].exit_func();
2563 mod_init_result[i] = false;
2567 static void __exit exit_btrfs_fs(void)
2569 btrfs_exit_btrfs_fs();
2570 btrfs_cleanup_fs_uuids();
2573 static int __init init_btrfs_fs(void)
2578 for (i = 0; i < ARRAY_SIZE(mod_init_seq); i++) {
2579 ASSERT(!mod_init_result[i]);
2580 ret = mod_init_seq[i].init_func();
2582 btrfs_exit_btrfs_fs();
2585 mod_init_result[i] = true;
2590 late_initcall(init_btrfs_fs);
2591 module_exit(exit_btrfs_fs)
2593 MODULE_LICENSE("GPL");
2594 MODULE_SOFTDEP("pre: crc32c");
2595 MODULE_SOFTDEP("pre: xxhash64");
2596 MODULE_SOFTDEP("pre: sha256");
2597 MODULE_SOFTDEP("pre: blake2b-256");