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/cleancache.h>
27 #include <linux/ratelimit.h>
28 #include <linux/crc32c.h>
29 #include <linux/btrfs.h>
30 #include "delayed-inode.h"
33 #include "transaction.h"
34 #include "btrfs_inode.h"
35 #include "print-tree.h"
40 #include "compression.h"
41 #include "rcu-string.h"
42 #include "dev-replace.h"
43 #include "free-space-cache.h"
45 #include "space-info.h"
47 #include "tests/btrfs-tests.h"
48 #include "block-group.h"
51 #define CREATE_TRACE_POINTS
52 #include <trace/events/btrfs.h>
54 static const struct super_operations btrfs_super_ops;
57 * Types for mounting the default subvolume and a subvolume explicitly
58 * requested by subvol=/path. That way the callchain is straightforward and we
59 * don't have to play tricks with the mount options and recursive calls to
62 * The new btrfs_root_fs_type also servers as a tag for the bdev_holder.
64 static struct file_system_type btrfs_fs_type;
65 static struct file_system_type btrfs_root_fs_type;
67 static int btrfs_remount(struct super_block *sb, int *flags, char *data);
69 const char *btrfs_decode_error(int errno)
71 char *errstr = "unknown";
75 errstr = "IO failure";
78 errstr = "Out of memory";
81 errstr = "Readonly filesystem";
84 errstr = "Object already exists";
87 errstr = "No space left";
90 errstr = "No such entry";
98 * __btrfs_handle_fs_error decodes expected errors from the caller and
99 * invokes the appropriate error response.
102 void __btrfs_handle_fs_error(struct btrfs_fs_info *fs_info, const char *function,
103 unsigned int line, int errno, const char *fmt, ...)
105 struct super_block *sb = fs_info->sb;
111 * Special case: if the error is EROFS, and we're already
112 * under SB_RDONLY, then it is safe here.
114 if (errno == -EROFS && sb_rdonly(sb))
118 errstr = btrfs_decode_error(errno);
120 struct va_format vaf;
127 pr_crit("BTRFS: error (device %s) in %s:%d: errno=%d %s (%pV)\n",
128 sb->s_id, function, line, errno, errstr, &vaf);
131 pr_crit("BTRFS: error (device %s) in %s:%d: errno=%d %s\n",
132 sb->s_id, function, line, errno, errstr);
137 * Today we only save the error info to memory. Long term we'll
138 * also send it down to the disk
140 set_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state);
142 /* Don't go through full error handling during mount */
143 if (!(sb->s_flags & SB_BORN))
149 /* btrfs handle error by forcing the filesystem readonly */
150 sb->s_flags |= SB_RDONLY;
151 btrfs_info(fs_info, "forced readonly");
153 * Note that a running device replace operation is not canceled here
154 * although there is no way to update the progress. It would add the
155 * risk of a deadlock, therefore the canceling is omitted. The only
156 * penalty is that some I/O remains active until the procedure
157 * completes. The next time when the filesystem is mounted writable
158 * again, the device replace operation continues.
163 static const char * const logtypes[] = {
176 * Use one ratelimit state per log level so that a flood of less important
177 * messages doesn't cause more important ones to be dropped.
179 static struct ratelimit_state printk_limits[] = {
180 RATELIMIT_STATE_INIT(printk_limits[0], DEFAULT_RATELIMIT_INTERVAL, 100),
181 RATELIMIT_STATE_INIT(printk_limits[1], DEFAULT_RATELIMIT_INTERVAL, 100),
182 RATELIMIT_STATE_INIT(printk_limits[2], DEFAULT_RATELIMIT_INTERVAL, 100),
183 RATELIMIT_STATE_INIT(printk_limits[3], DEFAULT_RATELIMIT_INTERVAL, 100),
184 RATELIMIT_STATE_INIT(printk_limits[4], DEFAULT_RATELIMIT_INTERVAL, 100),
185 RATELIMIT_STATE_INIT(printk_limits[5], DEFAULT_RATELIMIT_INTERVAL, 100),
186 RATELIMIT_STATE_INIT(printk_limits[6], DEFAULT_RATELIMIT_INTERVAL, 100),
187 RATELIMIT_STATE_INIT(printk_limits[7], DEFAULT_RATELIMIT_INTERVAL, 100),
190 void btrfs_printk(const struct btrfs_fs_info *fs_info, const char *fmt, ...)
192 char lvl[PRINTK_MAX_SINGLE_HEADER_LEN + 1] = "\0";
193 struct va_format vaf;
196 const char *type = logtypes[4];
197 struct ratelimit_state *ratelimit = &printk_limits[4];
201 while ((kern_level = printk_get_level(fmt)) != 0) {
202 size_t size = printk_skip_level(fmt) - fmt;
204 if (kern_level >= '0' && kern_level <= '7') {
205 memcpy(lvl, fmt, size);
207 type = logtypes[kern_level - '0'];
208 ratelimit = &printk_limits[kern_level - '0'];
216 if (__ratelimit(ratelimit))
217 printk("%sBTRFS %s (device %s): %pV\n", lvl, type,
218 fs_info ? fs_info->sb->s_id : "<unknown>", &vaf);
225 * We only mark the transaction aborted and then set the file system read-only.
226 * This will prevent new transactions from starting or trying to join this
229 * This means that error recovery at the call site is limited to freeing
230 * any local memory allocations and passing the error code up without
231 * further cleanup. The transaction should complete as it normally would
232 * in the call path but will return -EIO.
234 * We'll complete the cleanup in btrfs_end_transaction and
235 * btrfs_commit_transaction.
238 void __btrfs_abort_transaction(struct btrfs_trans_handle *trans,
239 const char *function,
240 unsigned int line, int errno)
242 struct btrfs_fs_info *fs_info = trans->fs_info;
244 WRITE_ONCE(trans->aborted, errno);
245 /* Nothing used. The other threads that have joined this
246 * transaction may be able to continue. */
247 if (!trans->dirty && list_empty(&trans->new_bgs)) {
250 errstr = btrfs_decode_error(errno);
252 "%s:%d: Aborting unused transaction(%s).",
253 function, line, errstr);
256 WRITE_ONCE(trans->transaction->aborted, errno);
257 /* Wake up anybody who may be waiting on this transaction */
258 wake_up(&fs_info->transaction_wait);
259 wake_up(&fs_info->transaction_blocked_wait);
260 __btrfs_handle_fs_error(fs_info, function, line, errno, NULL);
263 * __btrfs_panic decodes unexpected, fatal errors from the caller,
264 * issues an alert, and either panics or BUGs, depending on mount options.
267 void __btrfs_panic(struct btrfs_fs_info *fs_info, const char *function,
268 unsigned int line, int errno, const char *fmt, ...)
270 char *s_id = "<unknown>";
272 struct va_format vaf = { .fmt = fmt };
276 s_id = fs_info->sb->s_id;
281 errstr = btrfs_decode_error(errno);
282 if (fs_info && (btrfs_test_opt(fs_info, PANIC_ON_FATAL_ERROR)))
283 panic(KERN_CRIT "BTRFS panic (device %s) in %s:%d: %pV (errno=%d %s)\n",
284 s_id, function, line, &vaf, errno, errstr);
286 btrfs_crit(fs_info, "panic in %s:%d: %pV (errno=%d %s)",
287 function, line, &vaf, errno, errstr);
289 /* Caller calls BUG() */
292 static void btrfs_put_super(struct super_block *sb)
294 close_ctree(btrfs_sb(sb));
303 Opt_compress_force_type,
308 Opt_flushoncommit, Opt_noflushoncommit,
309 Opt_inode_cache, Opt_noinode_cache,
311 Opt_barrier, Opt_nobarrier,
312 Opt_datacow, Opt_nodatacow,
313 Opt_datasum, Opt_nodatasum,
314 Opt_defrag, Opt_nodefrag,
315 Opt_discard, Opt_nodiscard,
319 Opt_rescan_uuid_tree,
321 Opt_space_cache, Opt_no_space_cache,
322 Opt_space_cache_version,
324 Opt_ssd_spread, Opt_nossd_spread,
329 Opt_treelog, Opt_notreelog,
331 Opt_user_subvol_rm_allowed,
333 /* Deprecated options */
338 /* Debugging options */
340 Opt_check_integrity_including_extent_data,
341 Opt_check_integrity_print_mask,
342 Opt_enospc_debug, Opt_noenospc_debug,
343 #ifdef CONFIG_BTRFS_DEBUG
344 Opt_fragment_data, Opt_fragment_metadata, Opt_fragment_all,
346 #ifdef CONFIG_BTRFS_FS_REF_VERIFY
352 static const match_table_t tokens = {
354 {Opt_noacl, "noacl"},
355 {Opt_clear_cache, "clear_cache"},
356 {Opt_commit_interval, "commit=%u"},
357 {Opt_compress, "compress"},
358 {Opt_compress_type, "compress=%s"},
359 {Opt_compress_force, "compress-force"},
360 {Opt_compress_force_type, "compress-force=%s"},
361 {Opt_degraded, "degraded"},
362 {Opt_device, "device=%s"},
363 {Opt_fatal_errors, "fatal_errors=%s"},
364 {Opt_flushoncommit, "flushoncommit"},
365 {Opt_noflushoncommit, "noflushoncommit"},
366 {Opt_inode_cache, "inode_cache"},
367 {Opt_noinode_cache, "noinode_cache"},
368 {Opt_max_inline, "max_inline=%s"},
369 {Opt_barrier, "barrier"},
370 {Opt_nobarrier, "nobarrier"},
371 {Opt_datacow, "datacow"},
372 {Opt_nodatacow, "nodatacow"},
373 {Opt_datasum, "datasum"},
374 {Opt_nodatasum, "nodatasum"},
375 {Opt_defrag, "autodefrag"},
376 {Opt_nodefrag, "noautodefrag"},
377 {Opt_discard, "discard"},
378 {Opt_nodiscard, "nodiscard"},
379 {Opt_nologreplay, "nologreplay"},
380 {Opt_norecovery, "norecovery"},
381 {Opt_ratio, "metadata_ratio=%u"},
382 {Opt_rescan_uuid_tree, "rescan_uuid_tree"},
383 {Opt_skip_balance, "skip_balance"},
384 {Opt_space_cache, "space_cache"},
385 {Opt_no_space_cache, "nospace_cache"},
386 {Opt_space_cache_version, "space_cache=%s"},
388 {Opt_nossd, "nossd"},
389 {Opt_ssd_spread, "ssd_spread"},
390 {Opt_nossd_spread, "nossd_spread"},
391 {Opt_subvol, "subvol=%s"},
392 {Opt_subvol_empty, "subvol="},
393 {Opt_subvolid, "subvolid=%s"},
394 {Opt_thread_pool, "thread_pool=%u"},
395 {Opt_treelog, "treelog"},
396 {Opt_notreelog, "notreelog"},
397 {Opt_usebackuproot, "usebackuproot"},
398 {Opt_user_subvol_rm_allowed, "user_subvol_rm_allowed"},
400 /* Deprecated options */
401 {Opt_alloc_start, "alloc_start=%s"},
402 {Opt_recovery, "recovery"},
403 {Opt_subvolrootid, "subvolrootid=%d"},
405 /* Debugging options */
406 {Opt_check_integrity, "check_int"},
407 {Opt_check_integrity_including_extent_data, "check_int_data"},
408 {Opt_check_integrity_print_mask, "check_int_print_mask=%u"},
409 {Opt_enospc_debug, "enospc_debug"},
410 {Opt_noenospc_debug, "noenospc_debug"},
411 #ifdef CONFIG_BTRFS_DEBUG
412 {Opt_fragment_data, "fragment=data"},
413 {Opt_fragment_metadata, "fragment=metadata"},
414 {Opt_fragment_all, "fragment=all"},
416 #ifdef CONFIG_BTRFS_FS_REF_VERIFY
417 {Opt_ref_verify, "ref_verify"},
423 * Regular mount options parser. Everything that is needed only when
424 * reading in a new superblock is parsed here.
425 * XXX JDM: This needs to be cleaned up for remount.
427 int btrfs_parse_options(struct btrfs_fs_info *info, char *options,
428 unsigned long new_flags)
430 substring_t args[MAX_OPT_ARGS];
436 bool compress_force = false;
437 enum btrfs_compression_type saved_compress_type;
438 int saved_compress_level;
439 bool saved_compress_force;
442 cache_gen = btrfs_super_cache_generation(info->super_copy);
443 if (btrfs_fs_compat_ro(info, FREE_SPACE_TREE))
444 btrfs_set_opt(info->mount_opt, FREE_SPACE_TREE);
446 btrfs_set_opt(info->mount_opt, SPACE_CACHE);
449 * Even the options are empty, we still need to do extra check
455 while ((p = strsep(&options, ",")) != NULL) {
460 token = match_token(p, tokens, args);
463 btrfs_info(info, "allowing degraded mounts");
464 btrfs_set_opt(info->mount_opt, DEGRADED);
467 case Opt_subvol_empty:
469 case Opt_subvolrootid:
472 * These are parsed by btrfs_parse_subvol_options or
473 * btrfs_parse_device_options and can be ignored here.
477 btrfs_set_and_info(info, NODATASUM,
478 "setting nodatasum");
481 if (btrfs_test_opt(info, NODATASUM)) {
482 if (btrfs_test_opt(info, NODATACOW))
484 "setting datasum, datacow enabled");
486 btrfs_info(info, "setting datasum");
488 btrfs_clear_opt(info->mount_opt, NODATACOW);
489 btrfs_clear_opt(info->mount_opt, NODATASUM);
492 if (!btrfs_test_opt(info, NODATACOW)) {
493 if (!btrfs_test_opt(info, COMPRESS) ||
494 !btrfs_test_opt(info, FORCE_COMPRESS)) {
496 "setting nodatacow, compression disabled");
498 btrfs_info(info, "setting nodatacow");
501 btrfs_clear_opt(info->mount_opt, COMPRESS);
502 btrfs_clear_opt(info->mount_opt, FORCE_COMPRESS);
503 btrfs_set_opt(info->mount_opt, NODATACOW);
504 btrfs_set_opt(info->mount_opt, NODATASUM);
507 btrfs_clear_and_info(info, NODATACOW,
510 case Opt_compress_force:
511 case Opt_compress_force_type:
512 compress_force = true;
515 case Opt_compress_type:
516 saved_compress_type = btrfs_test_opt(info,
518 info->compress_type : BTRFS_COMPRESS_NONE;
519 saved_compress_force =
520 btrfs_test_opt(info, FORCE_COMPRESS);
521 saved_compress_level = info->compress_level;
522 if (token == Opt_compress ||
523 token == Opt_compress_force ||
524 strncmp(args[0].from, "zlib", 4) == 0) {
525 compress_type = "zlib";
527 info->compress_type = BTRFS_COMPRESS_ZLIB;
528 info->compress_level = BTRFS_ZLIB_DEFAULT_LEVEL;
530 * args[0] contains uninitialized data since
531 * for these tokens we don't expect any
534 if (token != Opt_compress &&
535 token != Opt_compress_force)
536 info->compress_level =
537 btrfs_compress_str2level(
540 btrfs_set_opt(info->mount_opt, COMPRESS);
541 btrfs_clear_opt(info->mount_opt, NODATACOW);
542 btrfs_clear_opt(info->mount_opt, NODATASUM);
544 } else if (strncmp(args[0].from, "lzo", 3) == 0) {
545 compress_type = "lzo";
546 info->compress_type = BTRFS_COMPRESS_LZO;
547 info->compress_level = 0;
548 btrfs_set_opt(info->mount_opt, COMPRESS);
549 btrfs_clear_opt(info->mount_opt, NODATACOW);
550 btrfs_clear_opt(info->mount_opt, NODATASUM);
551 btrfs_set_fs_incompat(info, COMPRESS_LZO);
553 } else if (strncmp(args[0].from, "zstd", 4) == 0) {
554 compress_type = "zstd";
555 info->compress_type = BTRFS_COMPRESS_ZSTD;
556 info->compress_level =
557 btrfs_compress_str2level(
560 btrfs_set_opt(info->mount_opt, COMPRESS);
561 btrfs_clear_opt(info->mount_opt, NODATACOW);
562 btrfs_clear_opt(info->mount_opt, NODATASUM);
563 btrfs_set_fs_incompat(info, COMPRESS_ZSTD);
565 } else if (strncmp(args[0].from, "no", 2) == 0) {
566 compress_type = "no";
567 info->compress_level = 0;
568 info->compress_type = 0;
569 btrfs_clear_opt(info->mount_opt, COMPRESS);
570 btrfs_clear_opt(info->mount_opt, FORCE_COMPRESS);
571 compress_force = false;
578 if (compress_force) {
579 btrfs_set_opt(info->mount_opt, FORCE_COMPRESS);
582 * If we remount from compress-force=xxx to
583 * compress=xxx, we need clear FORCE_COMPRESS
584 * flag, otherwise, there is no way for users
585 * to disable forcible compression separately.
587 btrfs_clear_opt(info->mount_opt, FORCE_COMPRESS);
589 if (no_compress == 1) {
590 btrfs_info(info, "use no compression");
591 } else if ((info->compress_type != saved_compress_type) ||
592 (compress_force != saved_compress_force) ||
593 (info->compress_level != saved_compress_level)) {
594 btrfs_info(info, "%s %s compression, level %d",
595 (compress_force) ? "force" : "use",
596 compress_type, info->compress_level);
598 compress_force = false;
601 btrfs_set_and_info(info, SSD,
602 "enabling ssd optimizations");
603 btrfs_clear_opt(info->mount_opt, NOSSD);
606 btrfs_set_and_info(info, SSD,
607 "enabling ssd optimizations");
608 btrfs_set_and_info(info, SSD_SPREAD,
609 "using spread ssd allocation scheme");
610 btrfs_clear_opt(info->mount_opt, NOSSD);
613 btrfs_set_opt(info->mount_opt, NOSSD);
614 btrfs_clear_and_info(info, SSD,
615 "not using ssd optimizations");
617 case Opt_nossd_spread:
618 btrfs_clear_and_info(info, SSD_SPREAD,
619 "not using spread ssd allocation scheme");
622 btrfs_clear_and_info(info, NOBARRIER,
623 "turning on barriers");
626 btrfs_set_and_info(info, NOBARRIER,
627 "turning off barriers");
629 case Opt_thread_pool:
630 ret = match_int(&args[0], &intarg);
633 } else if (intarg == 0) {
637 info->thread_pool_size = intarg;
640 num = match_strdup(&args[0]);
642 info->max_inline = memparse(num, NULL);
645 if (info->max_inline) {
646 info->max_inline = min_t(u64,
650 btrfs_info(info, "max_inline at %llu",
657 case Opt_alloc_start:
659 "option alloc_start is obsolete, ignored");
662 #ifdef CONFIG_BTRFS_FS_POSIX_ACL
663 info->sb->s_flags |= SB_POSIXACL;
666 btrfs_err(info, "support for ACL not compiled in!");
671 info->sb->s_flags &= ~SB_POSIXACL;
674 btrfs_set_and_info(info, NOTREELOG,
675 "disabling tree log");
678 btrfs_clear_and_info(info, NOTREELOG,
679 "enabling tree log");
682 case Opt_nologreplay:
683 btrfs_set_and_info(info, NOLOGREPLAY,
684 "disabling log replay at mount time");
686 case Opt_flushoncommit:
687 btrfs_set_and_info(info, FLUSHONCOMMIT,
688 "turning on flush-on-commit");
690 case Opt_noflushoncommit:
691 btrfs_clear_and_info(info, FLUSHONCOMMIT,
692 "turning off flush-on-commit");
695 ret = match_int(&args[0], &intarg);
698 info->metadata_ratio = intarg;
699 btrfs_info(info, "metadata ratio %u",
700 info->metadata_ratio);
703 btrfs_set_and_info(info, DISCARD,
704 "turning on discard");
707 btrfs_clear_and_info(info, DISCARD,
708 "turning off discard");
710 case Opt_space_cache:
711 case Opt_space_cache_version:
712 if (token == Opt_space_cache ||
713 strcmp(args[0].from, "v1") == 0) {
714 btrfs_clear_opt(info->mount_opt,
716 btrfs_set_and_info(info, SPACE_CACHE,
717 "enabling disk space caching");
718 } else if (strcmp(args[0].from, "v2") == 0) {
719 btrfs_clear_opt(info->mount_opt,
721 btrfs_set_and_info(info, FREE_SPACE_TREE,
722 "enabling free space tree");
728 case Opt_rescan_uuid_tree:
729 btrfs_set_opt(info->mount_opt, RESCAN_UUID_TREE);
731 case Opt_no_space_cache:
732 if (btrfs_test_opt(info, SPACE_CACHE)) {
733 btrfs_clear_and_info(info, SPACE_CACHE,
734 "disabling disk space caching");
736 if (btrfs_test_opt(info, FREE_SPACE_TREE)) {
737 btrfs_clear_and_info(info, FREE_SPACE_TREE,
738 "disabling free space tree");
741 case Opt_inode_cache:
742 btrfs_set_pending_and_info(info, INODE_MAP_CACHE,
743 "enabling inode map caching");
745 case Opt_noinode_cache:
746 btrfs_clear_pending_and_info(info, INODE_MAP_CACHE,
747 "disabling inode map caching");
749 case Opt_clear_cache:
750 btrfs_set_and_info(info, CLEAR_CACHE,
751 "force clearing of disk cache");
753 case Opt_user_subvol_rm_allowed:
754 btrfs_set_opt(info->mount_opt, USER_SUBVOL_RM_ALLOWED);
756 case Opt_enospc_debug:
757 btrfs_set_opt(info->mount_opt, ENOSPC_DEBUG);
759 case Opt_noenospc_debug:
760 btrfs_clear_opt(info->mount_opt, ENOSPC_DEBUG);
763 btrfs_set_and_info(info, AUTO_DEFRAG,
764 "enabling auto defrag");
767 btrfs_clear_and_info(info, AUTO_DEFRAG,
768 "disabling auto defrag");
772 "'recovery' is deprecated, use 'usebackuproot' instead");
774 case Opt_usebackuproot:
776 "trying to use backup root at mount time");
777 btrfs_set_opt(info->mount_opt, USEBACKUPROOT);
779 case Opt_skip_balance:
780 btrfs_set_opt(info->mount_opt, SKIP_BALANCE);
782 #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
783 case Opt_check_integrity_including_extent_data:
785 "enabling check integrity including extent data");
786 btrfs_set_opt(info->mount_opt,
787 CHECK_INTEGRITY_INCLUDING_EXTENT_DATA);
788 btrfs_set_opt(info->mount_opt, CHECK_INTEGRITY);
790 case Opt_check_integrity:
791 btrfs_info(info, "enabling check integrity");
792 btrfs_set_opt(info->mount_opt, CHECK_INTEGRITY);
794 case Opt_check_integrity_print_mask:
795 ret = match_int(&args[0], &intarg);
798 info->check_integrity_print_mask = intarg;
799 btrfs_info(info, "check_integrity_print_mask 0x%x",
800 info->check_integrity_print_mask);
803 case Opt_check_integrity_including_extent_data:
804 case Opt_check_integrity:
805 case Opt_check_integrity_print_mask:
807 "support for check_integrity* not compiled in!");
811 case Opt_fatal_errors:
812 if (strcmp(args[0].from, "panic") == 0)
813 btrfs_set_opt(info->mount_opt,
814 PANIC_ON_FATAL_ERROR);
815 else if (strcmp(args[0].from, "bug") == 0)
816 btrfs_clear_opt(info->mount_opt,
817 PANIC_ON_FATAL_ERROR);
823 case Opt_commit_interval:
825 ret = match_int(&args[0], &intarg);
830 "using default commit interval %us",
831 BTRFS_DEFAULT_COMMIT_INTERVAL);
832 intarg = BTRFS_DEFAULT_COMMIT_INTERVAL;
833 } else if (intarg > 300) {
834 btrfs_warn(info, "excessive commit interval %d",
837 info->commit_interval = intarg;
839 #ifdef CONFIG_BTRFS_DEBUG
840 case Opt_fragment_all:
841 btrfs_info(info, "fragmenting all space");
842 btrfs_set_opt(info->mount_opt, FRAGMENT_DATA);
843 btrfs_set_opt(info->mount_opt, FRAGMENT_METADATA);
845 case Opt_fragment_metadata:
846 btrfs_info(info, "fragmenting metadata");
847 btrfs_set_opt(info->mount_opt,
850 case Opt_fragment_data:
851 btrfs_info(info, "fragmenting data");
852 btrfs_set_opt(info->mount_opt, FRAGMENT_DATA);
855 #ifdef CONFIG_BTRFS_FS_REF_VERIFY
857 btrfs_info(info, "doing ref verification");
858 btrfs_set_opt(info->mount_opt, REF_VERIFY);
862 btrfs_info(info, "unrecognized mount option '%s'", p);
871 * Extra check for current option against current flag
873 if (btrfs_test_opt(info, NOLOGREPLAY) && !(new_flags & SB_RDONLY)) {
875 "nologreplay must be used with ro mount option");
879 if (btrfs_fs_compat_ro(info, FREE_SPACE_TREE) &&
880 !btrfs_test_opt(info, FREE_SPACE_TREE) &&
881 !btrfs_test_opt(info, CLEAR_CACHE)) {
882 btrfs_err(info, "cannot disable free space tree");
886 if (!ret && btrfs_test_opt(info, SPACE_CACHE))
887 btrfs_info(info, "disk space caching is enabled");
888 if (!ret && btrfs_test_opt(info, FREE_SPACE_TREE))
889 btrfs_info(info, "using free space tree");
894 * Parse mount options that are required early in the mount process.
896 * All other options will be parsed on much later in the mount process and
897 * only when we need to allocate a new super block.
899 static int btrfs_parse_device_options(const char *options, fmode_t flags,
902 substring_t args[MAX_OPT_ARGS];
903 char *device_name, *opts, *orig, *p;
904 struct btrfs_device *device = NULL;
907 lockdep_assert_held(&uuid_mutex);
913 * strsep changes the string, duplicate it because btrfs_parse_options
916 opts = kstrdup(options, GFP_KERNEL);
921 while ((p = strsep(&opts, ",")) != NULL) {
927 token = match_token(p, tokens, args);
928 if (token == Opt_device) {
929 device_name = match_strdup(&args[0]);
934 device = btrfs_scan_one_device(device_name, flags,
937 if (IS_ERR(device)) {
938 error = PTR_ERR(device);
950 * Parse mount options that are related to subvolume id
952 * The value is later passed to mount_subvol()
954 static int btrfs_parse_subvol_options(const char *options, char **subvol_name,
955 u64 *subvol_objectid)
957 substring_t args[MAX_OPT_ARGS];
958 char *opts, *orig, *p;
966 * strsep changes the string, duplicate it because
967 * btrfs_parse_device_options gets called later
969 opts = kstrdup(options, GFP_KERNEL);
974 while ((p = strsep(&opts, ",")) != NULL) {
979 token = match_token(p, tokens, args);
983 *subvol_name = match_strdup(&args[0]);
990 error = match_u64(&args[0], &subvolid);
994 /* we want the original fs_tree */
996 subvolid = BTRFS_FS_TREE_OBJECTID;
998 *subvol_objectid = subvolid;
1000 case Opt_subvolrootid:
1001 pr_warn("BTRFS: 'subvolrootid' mount option is deprecated and has no effect\n");
1013 char *btrfs_get_subvol_name_from_objectid(struct btrfs_fs_info *fs_info,
1014 u64 subvol_objectid)
1016 struct btrfs_root *root = fs_info->tree_root;
1017 struct btrfs_root *fs_root;
1018 struct btrfs_root_ref *root_ref;
1019 struct btrfs_inode_ref *inode_ref;
1020 struct btrfs_key key;
1021 struct btrfs_path *path = NULL;
1022 char *name = NULL, *ptr;
1027 path = btrfs_alloc_path();
1032 path->leave_spinning = 1;
1034 name = kmalloc(PATH_MAX, GFP_KERNEL);
1039 ptr = name + PATH_MAX - 1;
1043 * Walk up the subvolume trees in the tree of tree roots by root
1044 * backrefs until we hit the top-level subvolume.
1046 while (subvol_objectid != BTRFS_FS_TREE_OBJECTID) {
1047 key.objectid = subvol_objectid;
1048 key.type = BTRFS_ROOT_BACKREF_KEY;
1049 key.offset = (u64)-1;
1051 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1054 } else if (ret > 0) {
1055 ret = btrfs_previous_item(root, path, subvol_objectid,
1056 BTRFS_ROOT_BACKREF_KEY);
1059 } else if (ret > 0) {
1065 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1066 subvol_objectid = key.offset;
1068 root_ref = btrfs_item_ptr(path->nodes[0], path->slots[0],
1069 struct btrfs_root_ref);
1070 len = btrfs_root_ref_name_len(path->nodes[0], root_ref);
1073 ret = -ENAMETOOLONG;
1076 read_extent_buffer(path->nodes[0], ptr + 1,
1077 (unsigned long)(root_ref + 1), len);
1079 dirid = btrfs_root_ref_dirid(path->nodes[0], root_ref);
1080 btrfs_release_path(path);
1082 key.objectid = subvol_objectid;
1083 key.type = BTRFS_ROOT_ITEM_KEY;
1084 key.offset = (u64)-1;
1085 fs_root = btrfs_read_fs_root_no_name(fs_info, &key);
1086 if (IS_ERR(fs_root)) {
1087 ret = PTR_ERR(fs_root);
1092 * Walk up the filesystem tree by inode refs until we hit the
1095 while (dirid != BTRFS_FIRST_FREE_OBJECTID) {
1096 key.objectid = dirid;
1097 key.type = BTRFS_INODE_REF_KEY;
1098 key.offset = (u64)-1;
1100 ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
1103 } else if (ret > 0) {
1104 ret = btrfs_previous_item(fs_root, path, dirid,
1105 BTRFS_INODE_REF_KEY);
1108 } else if (ret > 0) {
1114 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1117 inode_ref = btrfs_item_ptr(path->nodes[0],
1119 struct btrfs_inode_ref);
1120 len = btrfs_inode_ref_name_len(path->nodes[0],
1124 ret = -ENAMETOOLONG;
1127 read_extent_buffer(path->nodes[0], ptr + 1,
1128 (unsigned long)(inode_ref + 1), len);
1130 btrfs_release_path(path);
1134 btrfs_free_path(path);
1135 if (ptr == name + PATH_MAX - 1) {
1139 memmove(name, ptr, name + PATH_MAX - ptr);
1144 btrfs_free_path(path);
1146 return ERR_PTR(ret);
1149 static int get_default_subvol_objectid(struct btrfs_fs_info *fs_info, u64 *objectid)
1151 struct btrfs_root *root = fs_info->tree_root;
1152 struct btrfs_dir_item *di;
1153 struct btrfs_path *path;
1154 struct btrfs_key location;
1157 path = btrfs_alloc_path();
1160 path->leave_spinning = 1;
1163 * Find the "default" dir item which points to the root item that we
1164 * will mount by default if we haven't been given a specific subvolume
1167 dir_id = btrfs_super_root_dir(fs_info->super_copy);
1168 di = btrfs_lookup_dir_item(NULL, root, path, dir_id, "default", 7, 0);
1170 btrfs_free_path(path);
1175 * Ok the default dir item isn't there. This is weird since
1176 * it's always been there, but don't freak out, just try and
1177 * mount the top-level subvolume.
1179 btrfs_free_path(path);
1180 *objectid = BTRFS_FS_TREE_OBJECTID;
1184 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &location);
1185 btrfs_free_path(path);
1186 *objectid = location.objectid;
1190 static int btrfs_fill_super(struct super_block *sb,
1191 struct btrfs_fs_devices *fs_devices,
1194 struct inode *inode;
1195 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
1196 struct btrfs_key key;
1199 sb->s_maxbytes = MAX_LFS_FILESIZE;
1200 sb->s_magic = BTRFS_SUPER_MAGIC;
1201 sb->s_op = &btrfs_super_ops;
1202 sb->s_d_op = &btrfs_dentry_operations;
1203 sb->s_export_op = &btrfs_export_ops;
1204 sb->s_xattr = btrfs_xattr_handlers;
1205 sb->s_time_gran = 1;
1206 #ifdef CONFIG_BTRFS_FS_POSIX_ACL
1207 sb->s_flags |= SB_POSIXACL;
1209 sb->s_flags |= SB_I_VERSION;
1210 sb->s_iflags |= SB_I_CGROUPWB;
1212 err = super_setup_bdi(sb);
1214 btrfs_err(fs_info, "super_setup_bdi failed");
1218 err = open_ctree(sb, fs_devices, (char *)data);
1220 btrfs_err(fs_info, "open_ctree failed");
1224 key.objectid = BTRFS_FIRST_FREE_OBJECTID;
1225 key.type = BTRFS_INODE_ITEM_KEY;
1227 inode = btrfs_iget(sb, &key, fs_info->fs_root, NULL);
1228 if (IS_ERR(inode)) {
1229 err = PTR_ERR(inode);
1233 sb->s_root = d_make_root(inode);
1239 cleancache_init_fs(sb);
1240 sb->s_flags |= SB_ACTIVE;
1244 close_ctree(fs_info);
1248 int btrfs_sync_fs(struct super_block *sb, int wait)
1250 struct btrfs_trans_handle *trans;
1251 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
1252 struct btrfs_root *root = fs_info->tree_root;
1254 trace_btrfs_sync_fs(fs_info, wait);
1257 filemap_flush(fs_info->btree_inode->i_mapping);
1261 btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
1263 trans = btrfs_attach_transaction_barrier(root);
1264 if (IS_ERR(trans)) {
1265 /* no transaction, don't bother */
1266 if (PTR_ERR(trans) == -ENOENT) {
1268 * Exit unless we have some pending changes
1269 * that need to go through commit
1271 if (fs_info->pending_changes == 0)
1274 * A non-blocking test if the fs is frozen. We must not
1275 * start a new transaction here otherwise a deadlock
1276 * happens. The pending operations are delayed to the
1277 * next commit after thawing.
1279 if (sb_start_write_trylock(sb))
1283 trans = btrfs_start_transaction(root, 0);
1286 return PTR_ERR(trans);
1288 return btrfs_commit_transaction(trans);
1291 static int btrfs_show_options(struct seq_file *seq, struct dentry *dentry)
1293 struct btrfs_fs_info *info = btrfs_sb(dentry->d_sb);
1294 const char *compress_type;
1295 const char *subvol_name;
1297 if (btrfs_test_opt(info, DEGRADED))
1298 seq_puts(seq, ",degraded");
1299 if (btrfs_test_opt(info, NODATASUM))
1300 seq_puts(seq, ",nodatasum");
1301 if (btrfs_test_opt(info, NODATACOW))
1302 seq_puts(seq, ",nodatacow");
1303 if (btrfs_test_opt(info, NOBARRIER))
1304 seq_puts(seq, ",nobarrier");
1305 if (info->max_inline != BTRFS_DEFAULT_MAX_INLINE)
1306 seq_printf(seq, ",max_inline=%llu", info->max_inline);
1307 if (info->thread_pool_size != min_t(unsigned long,
1308 num_online_cpus() + 2, 8))
1309 seq_printf(seq, ",thread_pool=%u", info->thread_pool_size);
1310 if (btrfs_test_opt(info, COMPRESS)) {
1311 compress_type = btrfs_compress_type2str(info->compress_type);
1312 if (btrfs_test_opt(info, FORCE_COMPRESS))
1313 seq_printf(seq, ",compress-force=%s", compress_type);
1315 seq_printf(seq, ",compress=%s", compress_type);
1316 if (info->compress_level)
1317 seq_printf(seq, ":%d", info->compress_level);
1319 if (btrfs_test_opt(info, NOSSD))
1320 seq_puts(seq, ",nossd");
1321 if (btrfs_test_opt(info, SSD_SPREAD))
1322 seq_puts(seq, ",ssd_spread");
1323 else if (btrfs_test_opt(info, SSD))
1324 seq_puts(seq, ",ssd");
1325 if (btrfs_test_opt(info, NOTREELOG))
1326 seq_puts(seq, ",notreelog");
1327 if (btrfs_test_opt(info, NOLOGREPLAY))
1328 seq_puts(seq, ",nologreplay");
1329 if (btrfs_test_opt(info, FLUSHONCOMMIT))
1330 seq_puts(seq, ",flushoncommit");
1331 if (btrfs_test_opt(info, DISCARD))
1332 seq_puts(seq, ",discard");
1333 if (!(info->sb->s_flags & SB_POSIXACL))
1334 seq_puts(seq, ",noacl");
1335 if (btrfs_test_opt(info, SPACE_CACHE))
1336 seq_puts(seq, ",space_cache");
1337 else if (btrfs_test_opt(info, FREE_SPACE_TREE))
1338 seq_puts(seq, ",space_cache=v2");
1340 seq_puts(seq, ",nospace_cache");
1341 if (btrfs_test_opt(info, RESCAN_UUID_TREE))
1342 seq_puts(seq, ",rescan_uuid_tree");
1343 if (btrfs_test_opt(info, CLEAR_CACHE))
1344 seq_puts(seq, ",clear_cache");
1345 if (btrfs_test_opt(info, USER_SUBVOL_RM_ALLOWED))
1346 seq_puts(seq, ",user_subvol_rm_allowed");
1347 if (btrfs_test_opt(info, ENOSPC_DEBUG))
1348 seq_puts(seq, ",enospc_debug");
1349 if (btrfs_test_opt(info, AUTO_DEFRAG))
1350 seq_puts(seq, ",autodefrag");
1351 if (btrfs_test_opt(info, INODE_MAP_CACHE))
1352 seq_puts(seq, ",inode_cache");
1353 if (btrfs_test_opt(info, SKIP_BALANCE))
1354 seq_puts(seq, ",skip_balance");
1355 #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
1356 if (btrfs_test_opt(info, CHECK_INTEGRITY_INCLUDING_EXTENT_DATA))
1357 seq_puts(seq, ",check_int_data");
1358 else if (btrfs_test_opt(info, CHECK_INTEGRITY))
1359 seq_puts(seq, ",check_int");
1360 if (info->check_integrity_print_mask)
1361 seq_printf(seq, ",check_int_print_mask=%d",
1362 info->check_integrity_print_mask);
1364 if (info->metadata_ratio)
1365 seq_printf(seq, ",metadata_ratio=%u", info->metadata_ratio);
1366 if (btrfs_test_opt(info, PANIC_ON_FATAL_ERROR))
1367 seq_puts(seq, ",fatal_errors=panic");
1368 if (info->commit_interval != BTRFS_DEFAULT_COMMIT_INTERVAL)
1369 seq_printf(seq, ",commit=%u", info->commit_interval);
1370 #ifdef CONFIG_BTRFS_DEBUG
1371 if (btrfs_test_opt(info, FRAGMENT_DATA))
1372 seq_puts(seq, ",fragment=data");
1373 if (btrfs_test_opt(info, FRAGMENT_METADATA))
1374 seq_puts(seq, ",fragment=metadata");
1376 if (btrfs_test_opt(info, REF_VERIFY))
1377 seq_puts(seq, ",ref_verify");
1378 seq_printf(seq, ",subvolid=%llu",
1379 BTRFS_I(d_inode(dentry))->root->root_key.objectid);
1380 subvol_name = btrfs_get_subvol_name_from_objectid(info,
1381 BTRFS_I(d_inode(dentry))->root->root_key.objectid);
1382 if (!IS_ERR(subvol_name)) {
1383 seq_puts(seq, ",subvol=");
1384 seq_escape(seq, subvol_name, " \t\n\\");
1390 static int btrfs_test_super(struct super_block *s, void *data)
1392 struct btrfs_fs_info *p = data;
1393 struct btrfs_fs_info *fs_info = btrfs_sb(s);
1395 return fs_info->fs_devices == p->fs_devices;
1398 static int btrfs_set_super(struct super_block *s, void *data)
1400 int err = set_anon_super(s, data);
1402 s->s_fs_info = data;
1407 * subvolumes are identified by ino 256
1409 static inline int is_subvolume_inode(struct inode *inode)
1411 if (inode && inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)
1416 static struct dentry *mount_subvol(const char *subvol_name, u64 subvol_objectid,
1417 struct vfsmount *mnt)
1419 struct dentry *root;
1423 if (!subvol_objectid) {
1424 ret = get_default_subvol_objectid(btrfs_sb(mnt->mnt_sb),
1427 root = ERR_PTR(ret);
1431 subvol_name = btrfs_get_subvol_name_from_objectid(
1432 btrfs_sb(mnt->mnt_sb), subvol_objectid);
1433 if (IS_ERR(subvol_name)) {
1434 root = ERR_CAST(subvol_name);
1441 root = mount_subtree(mnt, subvol_name);
1442 /* mount_subtree() drops our reference on the vfsmount. */
1445 if (!IS_ERR(root)) {
1446 struct super_block *s = root->d_sb;
1447 struct btrfs_fs_info *fs_info = btrfs_sb(s);
1448 struct inode *root_inode = d_inode(root);
1449 u64 root_objectid = BTRFS_I(root_inode)->root->root_key.objectid;
1452 if (!is_subvolume_inode(root_inode)) {
1453 btrfs_err(fs_info, "'%s' is not a valid subvolume",
1457 if (subvol_objectid && root_objectid != subvol_objectid) {
1459 * This will also catch a race condition where a
1460 * subvolume which was passed by ID is renamed and
1461 * another subvolume is renamed over the old location.
1464 "subvol '%s' does not match subvolid %llu",
1465 subvol_name, subvol_objectid);
1470 root = ERR_PTR(ret);
1471 deactivate_locked_super(s);
1482 * Find a superblock for the given device / mount point.
1484 * Note: This is based on mount_bdev from fs/super.c with a few additions
1485 * for multiple device setup. Make sure to keep it in sync.
1487 static struct dentry *btrfs_mount_root(struct file_system_type *fs_type,
1488 int flags, const char *device_name, void *data)
1490 struct block_device *bdev = NULL;
1491 struct super_block *s;
1492 struct btrfs_device *device = NULL;
1493 struct btrfs_fs_devices *fs_devices = NULL;
1494 struct btrfs_fs_info *fs_info = NULL;
1495 void *new_sec_opts = NULL;
1496 fmode_t mode = FMODE_READ;
1499 if (!(flags & SB_RDONLY))
1500 mode |= FMODE_WRITE;
1503 error = security_sb_eat_lsm_opts(data, &new_sec_opts);
1505 return ERR_PTR(error);
1509 * Setup a dummy root and fs_info for test/set super. This is because
1510 * we don't actually fill this stuff out until open_ctree, but we need
1511 * it for searching for existing supers, so this lets us do that and
1512 * then open_ctree will properly initialize everything later.
1514 fs_info = kvzalloc(sizeof(struct btrfs_fs_info), GFP_KERNEL);
1517 goto error_sec_opts;
1520 fs_info->super_copy = kzalloc(BTRFS_SUPER_INFO_SIZE, GFP_KERNEL);
1521 fs_info->super_for_commit = kzalloc(BTRFS_SUPER_INFO_SIZE, GFP_KERNEL);
1522 if (!fs_info->super_copy || !fs_info->super_for_commit) {
1527 mutex_lock(&uuid_mutex);
1528 error = btrfs_parse_device_options(data, mode, fs_type);
1530 mutex_unlock(&uuid_mutex);
1534 device = btrfs_scan_one_device(device_name, mode, fs_type);
1535 if (IS_ERR(device)) {
1536 mutex_unlock(&uuid_mutex);
1537 error = PTR_ERR(device);
1541 fs_devices = device->fs_devices;
1542 fs_info->fs_devices = fs_devices;
1544 error = btrfs_open_devices(fs_devices, mode, fs_type);
1545 mutex_unlock(&uuid_mutex);
1549 if (!(flags & SB_RDONLY) && fs_devices->rw_devices == 0) {
1551 goto error_close_devices;
1554 bdev = fs_devices->latest_bdev;
1555 s = sget(fs_type, btrfs_test_super, btrfs_set_super, flags | SB_NOSEC,
1559 goto error_close_devices;
1563 btrfs_close_devices(fs_devices);
1564 free_fs_info(fs_info);
1565 if ((flags ^ s->s_flags) & SB_RDONLY)
1568 snprintf(s->s_id, sizeof(s->s_id), "%pg", bdev);
1569 btrfs_sb(s)->bdev_holder = fs_type;
1570 error = btrfs_fill_super(s, fs_devices, data);
1573 error = security_sb_set_mnt_opts(s, new_sec_opts, 0, NULL);
1574 security_free_mnt_opts(&new_sec_opts);
1576 deactivate_locked_super(s);
1577 return ERR_PTR(error);
1580 return dget(s->s_root);
1582 error_close_devices:
1583 btrfs_close_devices(fs_devices);
1585 free_fs_info(fs_info);
1587 security_free_mnt_opts(&new_sec_opts);
1588 return ERR_PTR(error);
1592 * Mount function which is called by VFS layer.
1594 * In order to allow mounting a subvolume directly, btrfs uses mount_subtree()
1595 * which needs vfsmount* of device's root (/). This means device's root has to
1596 * be mounted internally in any case.
1599 * 1. Parse subvol id related options for later use in mount_subvol().
1601 * 2. Mount device's root (/) by calling vfs_kern_mount().
1603 * NOTE: vfs_kern_mount() is used by VFS to call btrfs_mount() in the
1604 * first place. In order to avoid calling btrfs_mount() again, we use
1605 * different file_system_type which is not registered to VFS by
1606 * register_filesystem() (btrfs_root_fs_type). As a result,
1607 * btrfs_mount_root() is called. The return value will be used by
1608 * mount_subtree() in mount_subvol().
1610 * 3. Call mount_subvol() to get the dentry of subvolume. Since there is
1611 * "btrfs subvolume set-default", mount_subvol() is called always.
1613 static struct dentry *btrfs_mount(struct file_system_type *fs_type, int flags,
1614 const char *device_name, void *data)
1616 struct vfsmount *mnt_root;
1617 struct dentry *root;
1618 char *subvol_name = NULL;
1619 u64 subvol_objectid = 0;
1622 error = btrfs_parse_subvol_options(data, &subvol_name,
1626 return ERR_PTR(error);
1629 /* mount device's root (/) */
1630 mnt_root = vfs_kern_mount(&btrfs_root_fs_type, flags, device_name, data);
1631 if (PTR_ERR_OR_ZERO(mnt_root) == -EBUSY) {
1632 if (flags & SB_RDONLY) {
1633 mnt_root = vfs_kern_mount(&btrfs_root_fs_type,
1634 flags & ~SB_RDONLY, device_name, data);
1636 mnt_root = vfs_kern_mount(&btrfs_root_fs_type,
1637 flags | SB_RDONLY, device_name, data);
1638 if (IS_ERR(mnt_root)) {
1639 root = ERR_CAST(mnt_root);
1644 down_write(&mnt_root->mnt_sb->s_umount);
1645 error = btrfs_remount(mnt_root->mnt_sb, &flags, NULL);
1646 up_write(&mnt_root->mnt_sb->s_umount);
1648 root = ERR_PTR(error);
1655 if (IS_ERR(mnt_root)) {
1656 root = ERR_CAST(mnt_root);
1661 /* mount_subvol() will free subvol_name and mnt_root */
1662 root = mount_subvol(subvol_name, subvol_objectid, mnt_root);
1668 static void btrfs_resize_thread_pool(struct btrfs_fs_info *fs_info,
1669 u32 new_pool_size, u32 old_pool_size)
1671 if (new_pool_size == old_pool_size)
1674 fs_info->thread_pool_size = new_pool_size;
1676 btrfs_info(fs_info, "resize thread pool %d -> %d",
1677 old_pool_size, new_pool_size);
1679 btrfs_workqueue_set_max(fs_info->workers, new_pool_size);
1680 btrfs_workqueue_set_max(fs_info->delalloc_workers, new_pool_size);
1681 btrfs_workqueue_set_max(fs_info->submit_workers, new_pool_size);
1682 btrfs_workqueue_set_max(fs_info->caching_workers, new_pool_size);
1683 btrfs_workqueue_set_max(fs_info->endio_workers, new_pool_size);
1684 btrfs_workqueue_set_max(fs_info->endio_meta_workers, new_pool_size);
1685 btrfs_workqueue_set_max(fs_info->endio_meta_write_workers,
1687 btrfs_workqueue_set_max(fs_info->endio_write_workers, new_pool_size);
1688 btrfs_workqueue_set_max(fs_info->endio_freespace_worker, new_pool_size);
1689 btrfs_workqueue_set_max(fs_info->delayed_workers, new_pool_size);
1690 btrfs_workqueue_set_max(fs_info->readahead_workers, new_pool_size);
1691 btrfs_workqueue_set_max(fs_info->scrub_wr_completion_workers,
1695 static inline void btrfs_remount_prepare(struct btrfs_fs_info *fs_info)
1697 set_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state);
1700 static inline void btrfs_remount_begin(struct btrfs_fs_info *fs_info,
1701 unsigned long old_opts, int flags)
1703 if (btrfs_raw_test_opt(old_opts, AUTO_DEFRAG) &&
1704 (!btrfs_raw_test_opt(fs_info->mount_opt, AUTO_DEFRAG) ||
1705 (flags & SB_RDONLY))) {
1706 /* wait for any defraggers to finish */
1707 wait_event(fs_info->transaction_wait,
1708 (atomic_read(&fs_info->defrag_running) == 0));
1709 if (flags & SB_RDONLY)
1710 sync_filesystem(fs_info->sb);
1714 static inline void btrfs_remount_cleanup(struct btrfs_fs_info *fs_info,
1715 unsigned long old_opts)
1718 * We need to cleanup all defragable inodes if the autodefragment is
1719 * close or the filesystem is read only.
1721 if (btrfs_raw_test_opt(old_opts, AUTO_DEFRAG) &&
1722 (!btrfs_raw_test_opt(fs_info->mount_opt, AUTO_DEFRAG) || sb_rdonly(fs_info->sb))) {
1723 btrfs_cleanup_defrag_inodes(fs_info);
1726 clear_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state);
1729 static int btrfs_remount(struct super_block *sb, int *flags, char *data)
1731 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
1732 struct btrfs_root *root = fs_info->tree_root;
1733 unsigned old_flags = sb->s_flags;
1734 unsigned long old_opts = fs_info->mount_opt;
1735 unsigned long old_compress_type = fs_info->compress_type;
1736 u64 old_max_inline = fs_info->max_inline;
1737 u32 old_thread_pool_size = fs_info->thread_pool_size;
1738 u32 old_metadata_ratio = fs_info->metadata_ratio;
1741 sync_filesystem(sb);
1742 btrfs_remount_prepare(fs_info);
1745 void *new_sec_opts = NULL;
1747 ret = security_sb_eat_lsm_opts(data, &new_sec_opts);
1749 ret = security_sb_remount(sb, new_sec_opts);
1750 security_free_mnt_opts(&new_sec_opts);
1755 ret = btrfs_parse_options(fs_info, data, *flags);
1759 btrfs_remount_begin(fs_info, old_opts, *flags);
1760 btrfs_resize_thread_pool(fs_info,
1761 fs_info->thread_pool_size, old_thread_pool_size);
1763 if ((bool)(*flags & SB_RDONLY) == sb_rdonly(sb))
1766 if (*flags & SB_RDONLY) {
1768 * this also happens on 'umount -rf' or on shutdown, when
1769 * the filesystem is busy.
1771 cancel_work_sync(&fs_info->async_reclaim_work);
1773 /* wait for the uuid_scan task to finish */
1774 down(&fs_info->uuid_tree_rescan_sem);
1775 /* avoid complains from lockdep et al. */
1776 up(&fs_info->uuid_tree_rescan_sem);
1778 sb->s_flags |= SB_RDONLY;
1781 * Setting SB_RDONLY will put the cleaner thread to
1782 * sleep at the next loop if it's already active.
1783 * If it's already asleep, we'll leave unused block
1784 * groups on disk until we're mounted read-write again
1785 * unless we clean them up here.
1787 btrfs_delete_unused_bgs(fs_info);
1789 btrfs_dev_replace_suspend_for_unmount(fs_info);
1790 btrfs_scrub_cancel(fs_info);
1791 btrfs_pause_balance(fs_info);
1794 * Pause the qgroup rescan worker if it is running. We don't want
1795 * it to be still running after we are in RO mode, as after that,
1796 * by the time we unmount, it might have left a transaction open,
1797 * so we would leak the transaction and/or crash.
1799 btrfs_qgroup_wait_for_completion(fs_info, false);
1801 ret = btrfs_commit_super(fs_info);
1805 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
1807 "Remounting read-write after error is not allowed");
1811 if (fs_info->fs_devices->rw_devices == 0) {
1816 if (!btrfs_check_rw_degradable(fs_info, NULL)) {
1818 "too many missing devices, writable remount is not allowed");
1823 if (btrfs_super_log_root(fs_info->super_copy) != 0) {
1825 "mount required to replay tree-log, cannot remount read-write");
1830 ret = btrfs_cleanup_fs_roots(fs_info);
1834 /* recover relocation */
1835 mutex_lock(&fs_info->cleaner_mutex);
1836 ret = btrfs_recover_relocation(root);
1837 mutex_unlock(&fs_info->cleaner_mutex);
1841 ret = btrfs_resume_balance_async(fs_info);
1845 ret = btrfs_resume_dev_replace_async(fs_info);
1847 btrfs_warn(fs_info, "failed to resume dev_replace");
1851 btrfs_qgroup_rescan_resume(fs_info);
1853 if (!fs_info->uuid_root) {
1854 btrfs_info(fs_info, "creating UUID tree");
1855 ret = btrfs_create_uuid_tree(fs_info);
1858 "failed to create the UUID tree %d",
1863 sb->s_flags &= ~SB_RDONLY;
1865 set_bit(BTRFS_FS_OPEN, &fs_info->flags);
1869 * We need to set SB_I_VERSION here otherwise it'll get cleared by VFS,
1870 * since the absence of the flag means it can be toggled off by remount.
1872 *flags |= SB_I_VERSION;
1874 wake_up_process(fs_info->transaction_kthread);
1875 btrfs_remount_cleanup(fs_info, old_opts);
1879 /* We've hit an error - don't reset SB_RDONLY */
1881 old_flags |= SB_RDONLY;
1882 sb->s_flags = old_flags;
1883 fs_info->mount_opt = old_opts;
1884 fs_info->compress_type = old_compress_type;
1885 fs_info->max_inline = old_max_inline;
1886 btrfs_resize_thread_pool(fs_info,
1887 old_thread_pool_size, fs_info->thread_pool_size);
1888 fs_info->metadata_ratio = old_metadata_ratio;
1889 btrfs_remount_cleanup(fs_info, old_opts);
1893 /* Used to sort the devices by max_avail(descending sort) */
1894 static inline int btrfs_cmp_device_free_bytes(const void *dev_info1,
1895 const void *dev_info2)
1897 if (((struct btrfs_device_info *)dev_info1)->max_avail >
1898 ((struct btrfs_device_info *)dev_info2)->max_avail)
1900 else if (((struct btrfs_device_info *)dev_info1)->max_avail <
1901 ((struct btrfs_device_info *)dev_info2)->max_avail)
1908 * sort the devices by max_avail, in which max free extent size of each device
1909 * is stored.(Descending Sort)
1911 static inline void btrfs_descending_sort_devices(
1912 struct btrfs_device_info *devices,
1915 sort(devices, nr_devices, sizeof(struct btrfs_device_info),
1916 btrfs_cmp_device_free_bytes, NULL);
1920 * The helper to calc the free space on the devices that can be used to store
1923 static inline int btrfs_calc_avail_data_space(struct btrfs_fs_info *fs_info,
1926 struct btrfs_device_info *devices_info;
1927 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
1928 struct btrfs_device *device;
1931 u64 min_stripe_size;
1932 int num_stripes = 1;
1933 int i = 0, nr_devices;
1934 const struct btrfs_raid_attr *rattr;
1937 * We aren't under the device list lock, so this is racy-ish, but good
1938 * enough for our purposes.
1940 nr_devices = fs_info->fs_devices->open_devices;
1943 nr_devices = fs_info->fs_devices->open_devices;
1951 devices_info = kmalloc_array(nr_devices, sizeof(*devices_info),
1956 /* calc min stripe number for data space allocation */
1957 type = btrfs_data_alloc_profile(fs_info);
1958 rattr = &btrfs_raid_array[btrfs_bg_flags_to_raid_index(type)];
1960 if (type & BTRFS_BLOCK_GROUP_RAID0)
1961 num_stripes = nr_devices;
1962 else if (type & BTRFS_BLOCK_GROUP_RAID1)
1964 else if (type & BTRFS_BLOCK_GROUP_RAID10)
1967 /* Adjust for more than 1 stripe per device */
1968 min_stripe_size = rattr->dev_stripes * BTRFS_STRIPE_LEN;
1971 list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
1972 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
1973 &device->dev_state) ||
1975 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
1978 if (i >= nr_devices)
1981 avail_space = device->total_bytes - device->bytes_used;
1983 /* align with stripe_len */
1984 avail_space = rounddown(avail_space, BTRFS_STRIPE_LEN);
1987 * In order to avoid overwriting the superblock on the drive,
1988 * btrfs starts at an offset of at least 1MB when doing chunk
1991 * This ensures we have at least min_stripe_size free space
1992 * after excluding 1MB.
1994 if (avail_space <= SZ_1M + min_stripe_size)
1997 avail_space -= SZ_1M;
1999 devices_info[i].dev = device;
2000 devices_info[i].max_avail = avail_space;
2008 btrfs_descending_sort_devices(devices_info, nr_devices);
2012 while (nr_devices >= rattr->devs_min) {
2013 num_stripes = min(num_stripes, nr_devices);
2015 if (devices_info[i].max_avail >= min_stripe_size) {
2019 avail_space += devices_info[i].max_avail * num_stripes;
2020 alloc_size = devices_info[i].max_avail;
2021 for (j = i + 1 - num_stripes; j <= i; j++)
2022 devices_info[j].max_avail -= alloc_size;
2028 kfree(devices_info);
2029 *free_bytes = avail_space;
2034 * Calculate numbers for 'df', pessimistic in case of mixed raid profiles.
2036 * If there's a redundant raid level at DATA block groups, use the respective
2037 * multiplier to scale the sizes.
2039 * Unused device space usage is based on simulating the chunk allocator
2040 * algorithm that respects the device sizes and order of allocations. This is
2041 * a close approximation of the actual use but there are other factors that may
2042 * change the result (like a new metadata chunk).
2044 * If metadata is exhausted, f_bavail will be 0.
2046 static int btrfs_statfs(struct dentry *dentry, struct kstatfs *buf)
2048 struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
2049 struct btrfs_super_block *disk_super = fs_info->super_copy;
2050 struct list_head *head = &fs_info->space_info;
2051 struct btrfs_space_info *found;
2053 u64 total_free_data = 0;
2054 u64 total_free_meta = 0;
2055 int bits = dentry->d_sb->s_blocksize_bits;
2056 __be32 *fsid = (__be32 *)fs_info->fs_devices->fsid;
2057 unsigned factor = 1;
2058 struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
2064 list_for_each_entry_rcu(found, head, list) {
2065 if (found->flags & BTRFS_BLOCK_GROUP_DATA) {
2068 total_free_data += found->disk_total - found->disk_used;
2070 btrfs_account_ro_block_groups_free_space(found);
2072 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
2073 if (!list_empty(&found->block_groups[i]))
2074 factor = btrfs_bg_type_to_factor(
2075 btrfs_raid_array[i].bg_flag);
2080 * Metadata in mixed block goup profiles are accounted in data
2082 if (!mixed && found->flags & BTRFS_BLOCK_GROUP_METADATA) {
2083 if (found->flags & BTRFS_BLOCK_GROUP_DATA)
2086 total_free_meta += found->disk_total -
2090 total_used += found->disk_used;
2095 buf->f_blocks = div_u64(btrfs_super_total_bytes(disk_super), factor);
2096 buf->f_blocks >>= bits;
2097 buf->f_bfree = buf->f_blocks - (div_u64(total_used, factor) >> bits);
2099 /* Account global block reserve as used, it's in logical size already */
2100 spin_lock(&block_rsv->lock);
2101 /* Mixed block groups accounting is not byte-accurate, avoid overflow */
2102 if (buf->f_bfree >= block_rsv->size >> bits)
2103 buf->f_bfree -= block_rsv->size >> bits;
2106 spin_unlock(&block_rsv->lock);
2108 buf->f_bavail = div_u64(total_free_data, factor);
2109 ret = btrfs_calc_avail_data_space(fs_info, &total_free_data);
2112 buf->f_bavail += div_u64(total_free_data, factor);
2113 buf->f_bavail = buf->f_bavail >> bits;
2116 * We calculate the remaining metadata space minus global reserve. If
2117 * this is (supposedly) smaller than zero, there's no space. But this
2118 * does not hold in practice, the exhausted state happens where's still
2119 * some positive delta. So we apply some guesswork and compare the
2120 * delta to a 4M threshold. (Practically observed delta was ~2M.)
2122 * We probably cannot calculate the exact threshold value because this
2123 * depends on the internal reservations requested by various
2124 * operations, so some operations that consume a few metadata will
2125 * succeed even if the Avail is zero. But this is better than the other
2131 * We only want to claim there's no available space if we can no longer
2132 * allocate chunks for our metadata profile and our global reserve will
2133 * not fit in the free metadata space. If we aren't ->full then we
2134 * still can allocate chunks and thus are fine using the currently
2135 * calculated f_bavail.
2137 if (!mixed && block_rsv->space_info->full &&
2138 total_free_meta - thresh < block_rsv->size)
2141 buf->f_type = BTRFS_SUPER_MAGIC;
2142 buf->f_bsize = dentry->d_sb->s_blocksize;
2143 buf->f_namelen = BTRFS_NAME_LEN;
2145 /* We treat it as constant endianness (it doesn't matter _which_)
2146 because we want the fsid to come out the same whether mounted
2147 on a big-endian or little-endian host */
2148 buf->f_fsid.val[0] = be32_to_cpu(fsid[0]) ^ be32_to_cpu(fsid[2]);
2149 buf->f_fsid.val[1] = be32_to_cpu(fsid[1]) ^ be32_to_cpu(fsid[3]);
2150 /* Mask in the root object ID too, to disambiguate subvols */
2151 buf->f_fsid.val[0] ^=
2152 BTRFS_I(d_inode(dentry))->root->root_key.objectid >> 32;
2153 buf->f_fsid.val[1] ^=
2154 BTRFS_I(d_inode(dentry))->root->root_key.objectid;
2159 static void btrfs_kill_super(struct super_block *sb)
2161 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
2162 kill_anon_super(sb);
2163 free_fs_info(fs_info);
2166 static struct file_system_type btrfs_fs_type = {
2167 .owner = THIS_MODULE,
2169 .mount = btrfs_mount,
2170 .kill_sb = btrfs_kill_super,
2171 .fs_flags = FS_REQUIRES_DEV | FS_BINARY_MOUNTDATA,
2174 static struct file_system_type btrfs_root_fs_type = {
2175 .owner = THIS_MODULE,
2177 .mount = btrfs_mount_root,
2178 .kill_sb = btrfs_kill_super,
2179 .fs_flags = FS_REQUIRES_DEV | FS_BINARY_MOUNTDATA,
2182 MODULE_ALIAS_FS("btrfs");
2184 static int btrfs_control_open(struct inode *inode, struct file *file)
2187 * The control file's private_data is used to hold the
2188 * transaction when it is started and is used to keep
2189 * track of whether a transaction is already in progress.
2191 file->private_data = NULL;
2196 * used by btrfsctl to scan devices when no FS is mounted
2198 static long btrfs_control_ioctl(struct file *file, unsigned int cmd,
2201 struct btrfs_ioctl_vol_args *vol;
2202 struct btrfs_device *device = NULL;
2205 if (!capable(CAP_SYS_ADMIN))
2208 vol = memdup_user((void __user *)arg, sizeof(*vol));
2210 return PTR_ERR(vol);
2211 vol->name[BTRFS_PATH_NAME_MAX] = '\0';
2214 case BTRFS_IOC_SCAN_DEV:
2215 mutex_lock(&uuid_mutex);
2216 device = btrfs_scan_one_device(vol->name, FMODE_READ,
2217 &btrfs_root_fs_type);
2218 ret = PTR_ERR_OR_ZERO(device);
2219 mutex_unlock(&uuid_mutex);
2221 case BTRFS_IOC_FORGET_DEV:
2222 ret = btrfs_forget_devices(vol->name);
2224 case BTRFS_IOC_DEVICES_READY:
2225 mutex_lock(&uuid_mutex);
2226 device = btrfs_scan_one_device(vol->name, FMODE_READ,
2227 &btrfs_root_fs_type);
2228 if (IS_ERR(device)) {
2229 mutex_unlock(&uuid_mutex);
2230 ret = PTR_ERR(device);
2233 ret = !(device->fs_devices->num_devices ==
2234 device->fs_devices->total_devices);
2235 mutex_unlock(&uuid_mutex);
2237 case BTRFS_IOC_GET_SUPPORTED_FEATURES:
2238 ret = btrfs_ioctl_get_supported_features((void __user*)arg);
2246 static int btrfs_freeze(struct super_block *sb)
2248 struct btrfs_trans_handle *trans;
2249 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
2250 struct btrfs_root *root = fs_info->tree_root;
2252 set_bit(BTRFS_FS_FROZEN, &fs_info->flags);
2254 * We don't need a barrier here, we'll wait for any transaction that
2255 * could be in progress on other threads (and do delayed iputs that
2256 * we want to avoid on a frozen filesystem), or do the commit
2259 trans = btrfs_attach_transaction_barrier(root);
2260 if (IS_ERR(trans)) {
2261 /* no transaction, don't bother */
2262 if (PTR_ERR(trans) == -ENOENT)
2264 return PTR_ERR(trans);
2266 return btrfs_commit_transaction(trans);
2269 static int btrfs_unfreeze(struct super_block *sb)
2271 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
2273 clear_bit(BTRFS_FS_FROZEN, &fs_info->flags);
2277 static int btrfs_show_devname(struct seq_file *m, struct dentry *root)
2279 struct btrfs_fs_info *fs_info = btrfs_sb(root->d_sb);
2280 struct btrfs_device *dev, *first_dev = NULL;
2283 * Lightweight locking of the devices. We should not need
2284 * device_list_mutex here as we only read the device data and the list
2285 * is protected by RCU. Even if a device is deleted during the list
2286 * traversals, we'll get valid data, the freeing callback will wait at
2287 * least until the rcu_read_unlock.
2290 list_for_each_entry_rcu(dev, &fs_info->fs_devices->devices, dev_list) {
2291 if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
2295 if (!first_dev || dev->devid < first_dev->devid)
2300 seq_escape(m, rcu_str_deref(first_dev->name), " \t\n\\");
2307 static const struct super_operations btrfs_super_ops = {
2308 .drop_inode = btrfs_drop_inode,
2309 .evict_inode = btrfs_evict_inode,
2310 .put_super = btrfs_put_super,
2311 .sync_fs = btrfs_sync_fs,
2312 .show_options = btrfs_show_options,
2313 .show_devname = btrfs_show_devname,
2314 .alloc_inode = btrfs_alloc_inode,
2315 .destroy_inode = btrfs_destroy_inode,
2316 .free_inode = btrfs_free_inode,
2317 .statfs = btrfs_statfs,
2318 .remount_fs = btrfs_remount,
2319 .freeze_fs = btrfs_freeze,
2320 .unfreeze_fs = btrfs_unfreeze,
2323 static const struct file_operations btrfs_ctl_fops = {
2324 .open = btrfs_control_open,
2325 .unlocked_ioctl = btrfs_control_ioctl,
2326 .compat_ioctl = btrfs_control_ioctl,
2327 .owner = THIS_MODULE,
2328 .llseek = noop_llseek,
2331 static struct miscdevice btrfs_misc = {
2332 .minor = BTRFS_MINOR,
2333 .name = "btrfs-control",
2334 .fops = &btrfs_ctl_fops
2337 MODULE_ALIAS_MISCDEV(BTRFS_MINOR);
2338 MODULE_ALIAS("devname:btrfs-control");
2340 static int __init btrfs_interface_init(void)
2342 return misc_register(&btrfs_misc);
2345 static __cold void btrfs_interface_exit(void)
2347 misc_deregister(&btrfs_misc);
2350 static void __init btrfs_print_mod_info(void)
2352 static const char options[] = ""
2353 #ifdef CONFIG_BTRFS_DEBUG
2356 #ifdef CONFIG_BTRFS_ASSERT
2359 #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
2360 ", integrity-checker=on"
2362 #ifdef CONFIG_BTRFS_FS_REF_VERIFY
2366 pr_info("Btrfs loaded, crc32c=%s%s\n", crc32c_impl(), options);
2369 static int __init init_btrfs_fs(void)
2375 err = btrfs_init_sysfs();
2379 btrfs_init_compress();
2381 err = btrfs_init_cachep();
2385 err = extent_io_init();
2389 err = extent_map_init();
2391 goto free_extent_io;
2393 err = ordered_data_init();
2395 goto free_extent_map;
2397 err = btrfs_delayed_inode_init();
2399 goto free_ordered_data;
2401 err = btrfs_auto_defrag_init();
2403 goto free_delayed_inode;
2405 err = btrfs_delayed_ref_init();
2407 goto free_auto_defrag;
2409 err = btrfs_prelim_ref_init();
2411 goto free_delayed_ref;
2413 err = btrfs_end_io_wq_init();
2415 goto free_prelim_ref;
2417 err = btrfs_interface_init();
2419 goto free_end_io_wq;
2421 btrfs_init_lockdep();
2423 btrfs_print_mod_info();
2425 err = btrfs_run_sanity_tests();
2427 goto unregister_ioctl;
2429 err = register_filesystem(&btrfs_fs_type);
2431 goto unregister_ioctl;
2436 btrfs_interface_exit();
2438 btrfs_end_io_wq_exit();
2440 btrfs_prelim_ref_exit();
2442 btrfs_delayed_ref_exit();
2444 btrfs_auto_defrag_exit();
2446 btrfs_delayed_inode_exit();
2448 ordered_data_exit();
2454 btrfs_destroy_cachep();
2456 btrfs_exit_compress();
2462 static void __exit exit_btrfs_fs(void)
2464 btrfs_destroy_cachep();
2465 btrfs_delayed_ref_exit();
2466 btrfs_auto_defrag_exit();
2467 btrfs_delayed_inode_exit();
2468 btrfs_prelim_ref_exit();
2469 ordered_data_exit();
2472 btrfs_interface_exit();
2473 btrfs_end_io_wq_exit();
2474 unregister_filesystem(&btrfs_fs_type);
2476 btrfs_cleanup_fs_uuids();
2477 btrfs_exit_compress();
2480 late_initcall(init_btrfs_fs);
2481 module_exit(exit_btrfs_fs)
2483 MODULE_LICENSE("GPL");
2484 MODULE_SOFTDEP("pre: crc32c");