GNU Linux-libre 6.1.90-gnu
[releases.git] / fs / btrfs / super.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2007 Oracle.  All rights reserved.
4  */
5
6 #include <linux/blkdev.h>
7 #include <linux/module.h>
8 #include <linux/fs.h>
9 #include <linux/pagemap.h>
10 #include <linux/highmem.h>
11 #include <linux/time.h>
12 #include <linux/init.h>
13 #include <linux/seq_file.h>
14 #include <linux/string.h>
15 #include <linux/backing-dev.h>
16 #include <linux/mount.h>
17 #include <linux/writeback.h>
18 #include <linux/statfs.h>
19 #include <linux/compat.h>
20 #include <linux/parser.h>
21 #include <linux/ctype.h>
22 #include <linux/namei.h>
23 #include <linux/miscdevice.h>
24 #include <linux/magic.h>
25 #include <linux/slab.h>
26 #include <linux/ratelimit.h>
27 #include <linux/crc32c.h>
28 #include <linux/btrfs.h>
29 #include "delayed-inode.h"
30 #include "ctree.h"
31 #include "disk-io.h"
32 #include "transaction.h"
33 #include "btrfs_inode.h"
34 #include "print-tree.h"
35 #include "props.h"
36 #include "xattr.h"
37 #include "volumes.h"
38 #include "export.h"
39 #include "compression.h"
40 #include "rcu-string.h"
41 #include "dev-replace.h"
42 #include "free-space-cache.h"
43 #include "backref.h"
44 #include "space-info.h"
45 #include "sysfs.h"
46 #include "zoned.h"
47 #include "tests/btrfs-tests.h"
48 #include "block-group.h"
49 #include "discard.h"
50 #include "qgroup.h"
51 #include "raid56.h"
52 #define CREATE_TRACE_POINTS
53 #include <trace/events/btrfs.h>
54
55 static const struct super_operations btrfs_super_ops;
56
57 /*
58  * Types for mounting the default subvolume and a subvolume explicitly
59  * requested by subvol=/path. That way the callchain is straightforward and we
60  * don't have to play tricks with the mount options and recursive calls to
61  * btrfs_mount.
62  *
63  * The new btrfs_root_fs_type also servers as a tag for the bdev_holder.
64  */
65 static struct file_system_type btrfs_fs_type;
66 static struct file_system_type btrfs_root_fs_type;
67
68 static int btrfs_remount(struct super_block *sb, int *flags, char *data);
69
70 #ifdef CONFIG_PRINTK
71
72 #define STATE_STRING_PREFACE    ": state "
73 #define STATE_STRING_BUF_LEN    (sizeof(STATE_STRING_PREFACE) + BTRFS_FS_STATE_COUNT)
74
75 /*
76  * Characters to print to indicate error conditions or uncommon filesystem state.
77  * RO is not an error.
78  */
79 static const char fs_state_chars[] = {
80         [BTRFS_FS_STATE_ERROR]                  = 'E',
81         [BTRFS_FS_STATE_REMOUNTING]             = 'M',
82         [BTRFS_FS_STATE_RO]                     = 0,
83         [BTRFS_FS_STATE_TRANS_ABORTED]          = 'A',
84         [BTRFS_FS_STATE_DEV_REPLACING]          = 'R',
85         [BTRFS_FS_STATE_DUMMY_FS_INFO]          = 0,
86         [BTRFS_FS_STATE_NO_CSUMS]               = 'C',
87         [BTRFS_FS_STATE_LOG_CLEANUP_ERROR]      = 'L',
88 };
89
90 static void btrfs_state_to_string(const struct btrfs_fs_info *info, char *buf)
91 {
92         unsigned int bit;
93         bool states_printed = false;
94         unsigned long fs_state = READ_ONCE(info->fs_state);
95         char *curr = buf;
96
97         memcpy(curr, STATE_STRING_PREFACE, sizeof(STATE_STRING_PREFACE));
98         curr += sizeof(STATE_STRING_PREFACE) - 1;
99
100         for_each_set_bit(bit, &fs_state, sizeof(fs_state)) {
101                 WARN_ON_ONCE(bit >= BTRFS_FS_STATE_COUNT);
102                 if ((bit < BTRFS_FS_STATE_COUNT) && fs_state_chars[bit]) {
103                         *curr++ = fs_state_chars[bit];
104                         states_printed = true;
105                 }
106         }
107
108         /* If no states were printed, reset the buffer */
109         if (!states_printed)
110                 curr = buf;
111
112         *curr++ = 0;
113 }
114 #endif
115
116 /*
117  * Generally the error codes correspond to their respective errors, but there
118  * are a few special cases.
119  *
120  * EUCLEAN: Any sort of corruption that we encounter.  The tree-checker for
121  *          instance will return EUCLEAN if any of the blocks are corrupted in
122  *          a way that is problematic.  We want to reserve EUCLEAN for these
123  *          sort of corruptions.
124  *
125  * EROFS: If we check BTRFS_FS_STATE_ERROR and fail out with a return error, we
126  *        need to use EROFS for this case.  We will have no idea of the
127  *        original failure, that will have been reported at the time we tripped
128  *        over the error.  Each subsequent error that doesn't have any context
129  *        of the original error should use EROFS when handling BTRFS_FS_STATE_ERROR.
130  */
131 const char * __attribute_const__ btrfs_decode_error(int errno)
132 {
133         char *errstr = "unknown";
134
135         switch (errno) {
136         case -ENOENT:           /* -2 */
137                 errstr = "No such entry";
138                 break;
139         case -EIO:              /* -5 */
140                 errstr = "IO failure";
141                 break;
142         case -ENOMEM:           /* -12*/
143                 errstr = "Out of memory";
144                 break;
145         case -EEXIST:           /* -17 */
146                 errstr = "Object already exists";
147                 break;
148         case -ENOSPC:           /* -28 */
149                 errstr = "No space left";
150                 break;
151         case -EROFS:            /* -30 */
152                 errstr = "Readonly filesystem";
153                 break;
154         case -EOPNOTSUPP:       /* -95 */
155                 errstr = "Operation not supported";
156                 break;
157         case -EUCLEAN:          /* -117 */
158                 errstr = "Filesystem corrupted";
159                 break;
160         case -EDQUOT:           /* -122 */
161                 errstr = "Quota exceeded";
162                 break;
163         }
164
165         return errstr;
166 }
167
168 /*
169  * __btrfs_handle_fs_error decodes expected errors from the caller and
170  * invokes the appropriate error response.
171  */
172 __cold
173 void __btrfs_handle_fs_error(struct btrfs_fs_info *fs_info, const char *function,
174                        unsigned int line, int errno, const char *fmt, ...)
175 {
176         struct super_block *sb = fs_info->sb;
177 #ifdef CONFIG_PRINTK
178         char statestr[STATE_STRING_BUF_LEN];
179         const char *errstr;
180 #endif
181
182         /*
183          * Special case: if the error is EROFS, and we're already
184          * under SB_RDONLY, then it is safe here.
185          */
186         if (errno == -EROFS && sb_rdonly(sb))
187                 return;
188
189 #ifdef CONFIG_PRINTK
190         errstr = btrfs_decode_error(errno);
191         btrfs_state_to_string(fs_info, statestr);
192         if (fmt) {
193                 struct va_format vaf;
194                 va_list args;
195
196                 va_start(args, fmt);
197                 vaf.fmt = fmt;
198                 vaf.va = &args;
199
200                 pr_crit("BTRFS: error (device %s%s) in %s:%d: errno=%d %s (%pV)\n",
201                         sb->s_id, statestr, function, line, errno, errstr, &vaf);
202                 va_end(args);
203         } else {
204                 pr_crit("BTRFS: error (device %s%s) in %s:%d: errno=%d %s\n",
205                         sb->s_id, statestr, function, line, errno, errstr);
206         }
207 #endif
208
209         /*
210          * Today we only save the error info to memory.  Long term we'll
211          * also send it down to the disk
212          */
213         set_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state);
214
215         /* Don't go through full error handling during mount */
216         if (!(sb->s_flags & SB_BORN))
217                 return;
218
219         if (sb_rdonly(sb))
220                 return;
221
222         btrfs_discard_stop(fs_info);
223
224         /* btrfs handle error by forcing the filesystem readonly */
225         btrfs_set_sb_rdonly(sb);
226         btrfs_info(fs_info, "forced readonly");
227         /*
228          * Note that a running device replace operation is not canceled here
229          * although there is no way to update the progress. It would add the
230          * risk of a deadlock, therefore the canceling is omitted. The only
231          * penalty is that some I/O remains active until the procedure
232          * completes. The next time when the filesystem is mounted writable
233          * again, the device replace operation continues.
234          */
235 }
236
237 #ifdef CONFIG_PRINTK
238 static const char * const logtypes[] = {
239         "emergency",
240         "alert",
241         "critical",
242         "error",
243         "warning",
244         "notice",
245         "info",
246         "debug",
247 };
248
249
250 /*
251  * Use one ratelimit state per log level so that a flood of less important
252  * messages doesn't cause more important ones to be dropped.
253  */
254 static struct ratelimit_state printk_limits[] = {
255         RATELIMIT_STATE_INIT(printk_limits[0], DEFAULT_RATELIMIT_INTERVAL, 100),
256         RATELIMIT_STATE_INIT(printk_limits[1], DEFAULT_RATELIMIT_INTERVAL, 100),
257         RATELIMIT_STATE_INIT(printk_limits[2], DEFAULT_RATELIMIT_INTERVAL, 100),
258         RATELIMIT_STATE_INIT(printk_limits[3], DEFAULT_RATELIMIT_INTERVAL, 100),
259         RATELIMIT_STATE_INIT(printk_limits[4], DEFAULT_RATELIMIT_INTERVAL, 100),
260         RATELIMIT_STATE_INIT(printk_limits[5], DEFAULT_RATELIMIT_INTERVAL, 100),
261         RATELIMIT_STATE_INIT(printk_limits[6], DEFAULT_RATELIMIT_INTERVAL, 100),
262         RATELIMIT_STATE_INIT(printk_limits[7], DEFAULT_RATELIMIT_INTERVAL, 100),
263 };
264
265 void __cold _btrfs_printk(const struct btrfs_fs_info *fs_info, const char *fmt, ...)
266 {
267         char lvl[PRINTK_MAX_SINGLE_HEADER_LEN + 1] = "\0";
268         struct va_format vaf;
269         va_list args;
270         int kern_level;
271         const char *type = logtypes[4];
272         struct ratelimit_state *ratelimit = &printk_limits[4];
273
274         va_start(args, fmt);
275
276         while ((kern_level = printk_get_level(fmt)) != 0) {
277                 size_t size = printk_skip_level(fmt) - fmt;
278
279                 if (kern_level >= '0' && kern_level <= '7') {
280                         memcpy(lvl, fmt,  size);
281                         lvl[size] = '\0';
282                         type = logtypes[kern_level - '0'];
283                         ratelimit = &printk_limits[kern_level - '0'];
284                 }
285                 fmt += size;
286         }
287
288         vaf.fmt = fmt;
289         vaf.va = &args;
290
291         if (__ratelimit(ratelimit)) {
292                 if (fs_info) {
293                         char statestr[STATE_STRING_BUF_LEN];
294
295                         btrfs_state_to_string(fs_info, statestr);
296                         _printk("%sBTRFS %s (device %s%s): %pV\n", lvl, type,
297                                 fs_info->sb->s_id, statestr, &vaf);
298                 } else {
299                         _printk("%sBTRFS %s: %pV\n", lvl, type, &vaf);
300                 }
301         }
302
303         va_end(args);
304 }
305 #endif
306
307 #if BITS_PER_LONG == 32
308 void __cold btrfs_warn_32bit_limit(struct btrfs_fs_info *fs_info)
309 {
310         if (!test_and_set_bit(BTRFS_FS_32BIT_WARN, &fs_info->flags)) {
311                 btrfs_warn(fs_info, "reaching 32bit limit for logical addresses");
312                 btrfs_warn(fs_info,
313 "due to page cache limit on 32bit systems, btrfs can't access metadata at or beyond %lluT",
314                            BTRFS_32BIT_MAX_FILE_SIZE >> 40);
315                 btrfs_warn(fs_info,
316                            "please consider upgrading to 64bit kernel/hardware");
317         }
318 }
319
320 void __cold btrfs_err_32bit_limit(struct btrfs_fs_info *fs_info)
321 {
322         if (!test_and_set_bit(BTRFS_FS_32BIT_ERROR, &fs_info->flags)) {
323                 btrfs_err(fs_info, "reached 32bit limit for logical addresses");
324                 btrfs_err(fs_info,
325 "due to page cache limit on 32bit systems, metadata beyond %lluT can't be accessed",
326                           BTRFS_32BIT_MAX_FILE_SIZE >> 40);
327                 btrfs_err(fs_info,
328                            "please consider upgrading to 64bit kernel/hardware");
329         }
330 }
331 #endif
332
333 /*
334  * We only mark the transaction aborted and then set the file system read-only.
335  * This will prevent new transactions from starting or trying to join this
336  * one.
337  *
338  * This means that error recovery at the call site is limited to freeing
339  * any local memory allocations and passing the error code up without
340  * further cleanup. The transaction should complete as it normally would
341  * in the call path but will return -EIO.
342  *
343  * We'll complete the cleanup in btrfs_end_transaction and
344  * btrfs_commit_transaction.
345  */
346 __cold
347 void __btrfs_abort_transaction(struct btrfs_trans_handle *trans,
348                                const char *function,
349                                unsigned int line, int errno, bool first_hit)
350 {
351         struct btrfs_fs_info *fs_info = trans->fs_info;
352
353         WRITE_ONCE(trans->aborted, errno);
354         WRITE_ONCE(trans->transaction->aborted, errno);
355         if (first_hit && errno == -ENOSPC)
356                 btrfs_dump_space_info_for_trans_abort(fs_info);
357         /* Wake up anybody who may be waiting on this transaction */
358         wake_up(&fs_info->transaction_wait);
359         wake_up(&fs_info->transaction_blocked_wait);
360         __btrfs_handle_fs_error(fs_info, function, line, errno, NULL);
361 }
362 /*
363  * __btrfs_panic decodes unexpected, fatal errors from the caller,
364  * issues an alert, and either panics or BUGs, depending on mount options.
365  */
366 __cold
367 void __btrfs_panic(struct btrfs_fs_info *fs_info, const char *function,
368                    unsigned int line, int errno, const char *fmt, ...)
369 {
370         char *s_id = "<unknown>";
371         const char *errstr;
372         struct va_format vaf = { .fmt = fmt };
373         va_list args;
374
375         if (fs_info)
376                 s_id = fs_info->sb->s_id;
377
378         va_start(args, fmt);
379         vaf.va = &args;
380
381         errstr = btrfs_decode_error(errno);
382         if (fs_info && (btrfs_test_opt(fs_info, PANIC_ON_FATAL_ERROR)))
383                 panic(KERN_CRIT "BTRFS panic (device %s) in %s:%d: %pV (errno=%d %s)\n",
384                         s_id, function, line, &vaf, errno, errstr);
385
386         btrfs_crit(fs_info, "panic in %s:%d: %pV (errno=%d %s)",
387                    function, line, &vaf, errno, errstr);
388         va_end(args);
389         /* Caller calls BUG() */
390 }
391
392 static void btrfs_put_super(struct super_block *sb)
393 {
394         struct btrfs_fs_info *fs_info = btrfs_sb(sb);
395
396         btrfs_info(fs_info, "last unmount of filesystem %pU", fs_info->fs_devices->fsid);
397         close_ctree(fs_info);
398 }
399
400 enum {
401         Opt_acl, Opt_noacl,
402         Opt_clear_cache,
403         Opt_commit_interval,
404         Opt_compress,
405         Opt_compress_force,
406         Opt_compress_force_type,
407         Opt_compress_type,
408         Opt_degraded,
409         Opt_device,
410         Opt_fatal_errors,
411         Opt_flushoncommit, Opt_noflushoncommit,
412         Opt_max_inline,
413         Opt_barrier, Opt_nobarrier,
414         Opt_datacow, Opt_nodatacow,
415         Opt_datasum, Opt_nodatasum,
416         Opt_defrag, Opt_nodefrag,
417         Opt_discard, Opt_nodiscard,
418         Opt_discard_mode,
419         Opt_norecovery,
420         Opt_ratio,
421         Opt_rescan_uuid_tree,
422         Opt_skip_balance,
423         Opt_space_cache, Opt_no_space_cache,
424         Opt_space_cache_version,
425         Opt_ssd, Opt_nossd,
426         Opt_ssd_spread, Opt_nossd_spread,
427         Opt_subvol,
428         Opt_subvol_empty,
429         Opt_subvolid,
430         Opt_thread_pool,
431         Opt_treelog, Opt_notreelog,
432         Opt_user_subvol_rm_allowed,
433
434         /* Rescue options */
435         Opt_rescue,
436         Opt_usebackuproot,
437         Opt_nologreplay,
438         Opt_ignorebadroots,
439         Opt_ignoredatacsums,
440         Opt_rescue_all,
441
442         /* Deprecated options */
443         Opt_recovery,
444         Opt_inode_cache, Opt_noinode_cache,
445
446         /* Debugging options */
447         Opt_check_integrity,
448         Opt_check_integrity_including_extent_data,
449         Opt_check_integrity_print_mask,
450         Opt_enospc_debug, Opt_noenospc_debug,
451 #ifdef CONFIG_BTRFS_DEBUG
452         Opt_fragment_data, Opt_fragment_metadata, Opt_fragment_all,
453 #endif
454 #ifdef CONFIG_BTRFS_FS_REF_VERIFY
455         Opt_ref_verify,
456 #endif
457         Opt_err,
458 };
459
460 static const match_table_t tokens = {
461         {Opt_acl, "acl"},
462         {Opt_noacl, "noacl"},
463         {Opt_clear_cache, "clear_cache"},
464         {Opt_commit_interval, "commit=%u"},
465         {Opt_compress, "compress"},
466         {Opt_compress_type, "compress=%s"},
467         {Opt_compress_force, "compress-force"},
468         {Opt_compress_force_type, "compress-force=%s"},
469         {Opt_degraded, "degraded"},
470         {Opt_device, "device=%s"},
471         {Opt_fatal_errors, "fatal_errors=%s"},
472         {Opt_flushoncommit, "flushoncommit"},
473         {Opt_noflushoncommit, "noflushoncommit"},
474         {Opt_inode_cache, "inode_cache"},
475         {Opt_noinode_cache, "noinode_cache"},
476         {Opt_max_inline, "max_inline=%s"},
477         {Opt_barrier, "barrier"},
478         {Opt_nobarrier, "nobarrier"},
479         {Opt_datacow, "datacow"},
480         {Opt_nodatacow, "nodatacow"},
481         {Opt_datasum, "datasum"},
482         {Opt_nodatasum, "nodatasum"},
483         {Opt_defrag, "autodefrag"},
484         {Opt_nodefrag, "noautodefrag"},
485         {Opt_discard, "discard"},
486         {Opt_discard_mode, "discard=%s"},
487         {Opt_nodiscard, "nodiscard"},
488         {Opt_norecovery, "norecovery"},
489         {Opt_ratio, "metadata_ratio=%u"},
490         {Opt_rescan_uuid_tree, "rescan_uuid_tree"},
491         {Opt_skip_balance, "skip_balance"},
492         {Opt_space_cache, "space_cache"},
493         {Opt_no_space_cache, "nospace_cache"},
494         {Opt_space_cache_version, "space_cache=%s"},
495         {Opt_ssd, "ssd"},
496         {Opt_nossd, "nossd"},
497         {Opt_ssd_spread, "ssd_spread"},
498         {Opt_nossd_spread, "nossd_spread"},
499         {Opt_subvol, "subvol=%s"},
500         {Opt_subvol_empty, "subvol="},
501         {Opt_subvolid, "subvolid=%s"},
502         {Opt_thread_pool, "thread_pool=%u"},
503         {Opt_treelog, "treelog"},
504         {Opt_notreelog, "notreelog"},
505         {Opt_user_subvol_rm_allowed, "user_subvol_rm_allowed"},
506
507         /* Rescue options */
508         {Opt_rescue, "rescue=%s"},
509         /* Deprecated, with alias rescue=nologreplay */
510         {Opt_nologreplay, "nologreplay"},
511         /* Deprecated, with alias rescue=usebackuproot */
512         {Opt_usebackuproot, "usebackuproot"},
513
514         /* Deprecated options */
515         {Opt_recovery, "recovery"},
516
517         /* Debugging options */
518         {Opt_check_integrity, "check_int"},
519         {Opt_check_integrity_including_extent_data, "check_int_data"},
520         {Opt_check_integrity_print_mask, "check_int_print_mask=%u"},
521         {Opt_enospc_debug, "enospc_debug"},
522         {Opt_noenospc_debug, "noenospc_debug"},
523 #ifdef CONFIG_BTRFS_DEBUG
524         {Opt_fragment_data, "fragment=data"},
525         {Opt_fragment_metadata, "fragment=metadata"},
526         {Opt_fragment_all, "fragment=all"},
527 #endif
528 #ifdef CONFIG_BTRFS_FS_REF_VERIFY
529         {Opt_ref_verify, "ref_verify"},
530 #endif
531         {Opt_err, NULL},
532 };
533
534 static const match_table_t rescue_tokens = {
535         {Opt_usebackuproot, "usebackuproot"},
536         {Opt_nologreplay, "nologreplay"},
537         {Opt_ignorebadroots, "ignorebadroots"},
538         {Opt_ignorebadroots, "ibadroots"},
539         {Opt_ignoredatacsums, "ignoredatacsums"},
540         {Opt_ignoredatacsums, "idatacsums"},
541         {Opt_rescue_all, "all"},
542         {Opt_err, NULL},
543 };
544
545 static bool check_ro_option(struct btrfs_fs_info *fs_info, unsigned long opt,
546                             const char *opt_name)
547 {
548         if (fs_info->mount_opt & opt) {
549                 btrfs_err(fs_info, "%s must be used with ro mount option",
550                           opt_name);
551                 return true;
552         }
553         return false;
554 }
555
556 static int parse_rescue_options(struct btrfs_fs_info *info, const char *options)
557 {
558         char *opts;
559         char *orig;
560         char *p;
561         substring_t args[MAX_OPT_ARGS];
562         int ret = 0;
563
564         opts = kstrdup(options, GFP_KERNEL);
565         if (!opts)
566                 return -ENOMEM;
567         orig = opts;
568
569         while ((p = strsep(&opts, ":")) != NULL) {
570                 int token;
571
572                 if (!*p)
573                         continue;
574                 token = match_token(p, rescue_tokens, args);
575                 switch (token){
576                 case Opt_usebackuproot:
577                         btrfs_info(info,
578                                    "trying to use backup root at mount time");
579                         btrfs_set_opt(info->mount_opt, USEBACKUPROOT);
580                         break;
581                 case Opt_nologreplay:
582                         btrfs_set_and_info(info, NOLOGREPLAY,
583                                            "disabling log replay at mount time");
584                         break;
585                 case Opt_ignorebadroots:
586                         btrfs_set_and_info(info, IGNOREBADROOTS,
587                                            "ignoring bad roots");
588                         break;
589                 case Opt_ignoredatacsums:
590                         btrfs_set_and_info(info, IGNOREDATACSUMS,
591                                            "ignoring data csums");
592                         break;
593                 case Opt_rescue_all:
594                         btrfs_info(info, "enabling all of the rescue options");
595                         btrfs_set_and_info(info, IGNOREDATACSUMS,
596                                            "ignoring data csums");
597                         btrfs_set_and_info(info, IGNOREBADROOTS,
598                                            "ignoring bad roots");
599                         btrfs_set_and_info(info, NOLOGREPLAY,
600                                            "disabling log replay at mount time");
601                         break;
602                 case Opt_err:
603                         btrfs_info(info, "unrecognized rescue option '%s'", p);
604                         ret = -EINVAL;
605                         goto out;
606                 default:
607                         break;
608                 }
609
610         }
611 out:
612         kfree(orig);
613         return ret;
614 }
615
616 /*
617  * Regular mount options parser.  Everything that is needed only when
618  * reading in a new superblock is parsed here.
619  * XXX JDM: This needs to be cleaned up for remount.
620  */
621 int btrfs_parse_options(struct btrfs_fs_info *info, char *options,
622                         unsigned long new_flags)
623 {
624         substring_t args[MAX_OPT_ARGS];
625         char *p, *num;
626         int intarg;
627         int ret = 0;
628         char *compress_type;
629         bool compress_force = false;
630         enum btrfs_compression_type saved_compress_type;
631         int saved_compress_level;
632         bool saved_compress_force;
633         int no_compress = 0;
634         const bool remounting = test_bit(BTRFS_FS_STATE_REMOUNTING, &info->fs_state);
635
636         if (btrfs_fs_compat_ro(info, FREE_SPACE_TREE))
637                 btrfs_set_opt(info->mount_opt, FREE_SPACE_TREE);
638         else if (btrfs_free_space_cache_v1_active(info)) {
639                 if (btrfs_is_zoned(info)) {
640                         btrfs_info(info,
641                         "zoned: clearing existing space cache");
642                         btrfs_set_super_cache_generation(info->super_copy, 0);
643                 } else {
644                         btrfs_set_opt(info->mount_opt, SPACE_CACHE);
645                 }
646         }
647
648         /*
649          * Even the options are empty, we still need to do extra check
650          * against new flags
651          */
652         if (!options)
653                 goto check;
654
655         while ((p = strsep(&options, ",")) != NULL) {
656                 int token;
657                 if (!*p)
658                         continue;
659
660                 token = match_token(p, tokens, args);
661                 switch (token) {
662                 case Opt_degraded:
663                         btrfs_info(info, "allowing degraded mounts");
664                         btrfs_set_opt(info->mount_opt, DEGRADED);
665                         break;
666                 case Opt_subvol:
667                 case Opt_subvol_empty:
668                 case Opt_subvolid:
669                 case Opt_device:
670                         /*
671                          * These are parsed by btrfs_parse_subvol_options or
672                          * btrfs_parse_device_options and can be ignored here.
673                          */
674                         break;
675                 case Opt_nodatasum:
676                         btrfs_set_and_info(info, NODATASUM,
677                                            "setting nodatasum");
678                         break;
679                 case Opt_datasum:
680                         if (btrfs_test_opt(info, NODATASUM)) {
681                                 if (btrfs_test_opt(info, NODATACOW))
682                                         btrfs_info(info,
683                                                    "setting datasum, datacow enabled");
684                                 else
685                                         btrfs_info(info, "setting datasum");
686                         }
687                         btrfs_clear_opt(info->mount_opt, NODATACOW);
688                         btrfs_clear_opt(info->mount_opt, NODATASUM);
689                         break;
690                 case Opt_nodatacow:
691                         if (!btrfs_test_opt(info, NODATACOW)) {
692                                 if (!btrfs_test_opt(info, COMPRESS) ||
693                                     !btrfs_test_opt(info, FORCE_COMPRESS)) {
694                                         btrfs_info(info,
695                                                    "setting nodatacow, compression disabled");
696                                 } else {
697                                         btrfs_info(info, "setting nodatacow");
698                                 }
699                         }
700                         btrfs_clear_opt(info->mount_opt, COMPRESS);
701                         btrfs_clear_opt(info->mount_opt, FORCE_COMPRESS);
702                         btrfs_set_opt(info->mount_opt, NODATACOW);
703                         btrfs_set_opt(info->mount_opt, NODATASUM);
704                         break;
705                 case Opt_datacow:
706                         btrfs_clear_and_info(info, NODATACOW,
707                                              "setting datacow");
708                         break;
709                 case Opt_compress_force:
710                 case Opt_compress_force_type:
711                         compress_force = true;
712                         fallthrough;
713                 case Opt_compress:
714                 case Opt_compress_type:
715                         saved_compress_type = btrfs_test_opt(info,
716                                                              COMPRESS) ?
717                                 info->compress_type : BTRFS_COMPRESS_NONE;
718                         saved_compress_force =
719                                 btrfs_test_opt(info, FORCE_COMPRESS);
720                         saved_compress_level = info->compress_level;
721                         if (token == Opt_compress ||
722                             token == Opt_compress_force ||
723                             strncmp(args[0].from, "zlib", 4) == 0) {
724                                 compress_type = "zlib";
725
726                                 info->compress_type = BTRFS_COMPRESS_ZLIB;
727                                 info->compress_level = BTRFS_ZLIB_DEFAULT_LEVEL;
728                                 /*
729                                  * args[0] contains uninitialized data since
730                                  * for these tokens we don't expect any
731                                  * parameter.
732                                  */
733                                 if (token != Opt_compress &&
734                                     token != Opt_compress_force)
735                                         info->compress_level =
736                                           btrfs_compress_str2level(
737                                                         BTRFS_COMPRESS_ZLIB,
738                                                         args[0].from + 4);
739                                 btrfs_set_opt(info->mount_opt, COMPRESS);
740                                 btrfs_clear_opt(info->mount_opt, NODATACOW);
741                                 btrfs_clear_opt(info->mount_opt, NODATASUM);
742                                 no_compress = 0;
743                         } else if (strncmp(args[0].from, "lzo", 3) == 0) {
744                                 compress_type = "lzo";
745                                 info->compress_type = BTRFS_COMPRESS_LZO;
746                                 info->compress_level = 0;
747                                 btrfs_set_opt(info->mount_opt, COMPRESS);
748                                 btrfs_clear_opt(info->mount_opt, NODATACOW);
749                                 btrfs_clear_opt(info->mount_opt, NODATASUM);
750                                 btrfs_set_fs_incompat(info, COMPRESS_LZO);
751                                 no_compress = 0;
752                         } else if (strncmp(args[0].from, "zstd", 4) == 0) {
753                                 compress_type = "zstd";
754                                 info->compress_type = BTRFS_COMPRESS_ZSTD;
755                                 info->compress_level =
756                                         btrfs_compress_str2level(
757                                                          BTRFS_COMPRESS_ZSTD,
758                                                          args[0].from + 4);
759                                 btrfs_set_opt(info->mount_opt, COMPRESS);
760                                 btrfs_clear_opt(info->mount_opt, NODATACOW);
761                                 btrfs_clear_opt(info->mount_opt, NODATASUM);
762                                 btrfs_set_fs_incompat(info, COMPRESS_ZSTD);
763                                 no_compress = 0;
764                         } else if (strncmp(args[0].from, "no", 2) == 0) {
765                                 compress_type = "no";
766                                 info->compress_level = 0;
767                                 info->compress_type = 0;
768                                 btrfs_clear_opt(info->mount_opt, COMPRESS);
769                                 btrfs_clear_opt(info->mount_opt, FORCE_COMPRESS);
770                                 compress_force = false;
771                                 no_compress++;
772                         } else {
773                                 btrfs_err(info, "unrecognized compression value %s",
774                                           args[0].from);
775                                 ret = -EINVAL;
776                                 goto out;
777                         }
778
779                         if (compress_force) {
780                                 btrfs_set_opt(info->mount_opt, FORCE_COMPRESS);
781                         } else {
782                                 /*
783                                  * If we remount from compress-force=xxx to
784                                  * compress=xxx, we need clear FORCE_COMPRESS
785                                  * flag, otherwise, there is no way for users
786                                  * to disable forcible compression separately.
787                                  */
788                                 btrfs_clear_opt(info->mount_opt, FORCE_COMPRESS);
789                         }
790                         if (no_compress == 1) {
791                                 btrfs_info(info, "use no compression");
792                         } else if ((info->compress_type != saved_compress_type) ||
793                                    (compress_force != saved_compress_force) ||
794                                    (info->compress_level != saved_compress_level)) {
795                                 btrfs_info(info, "%s %s compression, level %d",
796                                            (compress_force) ? "force" : "use",
797                                            compress_type, info->compress_level);
798                         }
799                         compress_force = false;
800                         break;
801                 case Opt_ssd:
802                         btrfs_set_and_info(info, SSD,
803                                            "enabling ssd optimizations");
804                         btrfs_clear_opt(info->mount_opt, NOSSD);
805                         break;
806                 case Opt_ssd_spread:
807                         btrfs_set_and_info(info, SSD,
808                                            "enabling ssd optimizations");
809                         btrfs_set_and_info(info, SSD_SPREAD,
810                                            "using spread ssd allocation scheme");
811                         btrfs_clear_opt(info->mount_opt, NOSSD);
812                         break;
813                 case Opt_nossd:
814                         btrfs_set_opt(info->mount_opt, NOSSD);
815                         btrfs_clear_and_info(info, SSD,
816                                              "not using ssd optimizations");
817                         fallthrough;
818                 case Opt_nossd_spread:
819                         btrfs_clear_and_info(info, SSD_SPREAD,
820                                              "not using spread ssd allocation scheme");
821                         break;
822                 case Opt_barrier:
823                         btrfs_clear_and_info(info, NOBARRIER,
824                                              "turning on barriers");
825                         break;
826                 case Opt_nobarrier:
827                         btrfs_set_and_info(info, NOBARRIER,
828                                            "turning off barriers");
829                         break;
830                 case Opt_thread_pool:
831                         ret = match_int(&args[0], &intarg);
832                         if (ret) {
833                                 btrfs_err(info, "unrecognized thread_pool value %s",
834                                           args[0].from);
835                                 goto out;
836                         } else if (intarg == 0) {
837                                 btrfs_err(info, "invalid value 0 for thread_pool");
838                                 ret = -EINVAL;
839                                 goto out;
840                         }
841                         info->thread_pool_size = intarg;
842                         break;
843                 case Opt_max_inline:
844                         num = match_strdup(&args[0]);
845                         if (num) {
846                                 info->max_inline = memparse(num, NULL);
847                                 kfree(num);
848
849                                 if (info->max_inline) {
850                                         info->max_inline = min_t(u64,
851                                                 info->max_inline,
852                                                 info->sectorsize);
853                                 }
854                                 btrfs_info(info, "max_inline at %llu",
855                                            info->max_inline);
856                         } else {
857                                 ret = -ENOMEM;
858                                 goto out;
859                         }
860                         break;
861                 case Opt_acl:
862 #ifdef CONFIG_BTRFS_FS_POSIX_ACL
863                         info->sb->s_flags |= SB_POSIXACL;
864                         break;
865 #else
866                         btrfs_err(info, "support for ACL not compiled in!");
867                         ret = -EINVAL;
868                         goto out;
869 #endif
870                 case Opt_noacl:
871                         info->sb->s_flags &= ~SB_POSIXACL;
872                         break;
873                 case Opt_notreelog:
874                         btrfs_set_and_info(info, NOTREELOG,
875                                            "disabling tree log");
876                         break;
877                 case Opt_treelog:
878                         btrfs_clear_and_info(info, NOTREELOG,
879                                              "enabling tree log");
880                         break;
881                 case Opt_norecovery:
882                 case Opt_nologreplay:
883                         btrfs_warn(info,
884                 "'nologreplay' is deprecated, use 'rescue=nologreplay' instead");
885                         btrfs_set_and_info(info, NOLOGREPLAY,
886                                            "disabling log replay at mount time");
887                         break;
888                 case Opt_flushoncommit:
889                         btrfs_set_and_info(info, FLUSHONCOMMIT,
890                                            "turning on flush-on-commit");
891                         break;
892                 case Opt_noflushoncommit:
893                         btrfs_clear_and_info(info, FLUSHONCOMMIT,
894                                              "turning off flush-on-commit");
895                         break;
896                 case Opt_ratio:
897                         ret = match_int(&args[0], &intarg);
898                         if (ret) {
899                                 btrfs_err(info, "unrecognized metadata_ratio value %s",
900                                           args[0].from);
901                                 goto out;
902                         }
903                         info->metadata_ratio = intarg;
904                         btrfs_info(info, "metadata ratio %u",
905                                    info->metadata_ratio);
906                         break;
907                 case Opt_discard:
908                 case Opt_discard_mode:
909                         if (token == Opt_discard ||
910                             strcmp(args[0].from, "sync") == 0) {
911                                 btrfs_clear_opt(info->mount_opt, DISCARD_ASYNC);
912                                 btrfs_set_and_info(info, DISCARD_SYNC,
913                                                    "turning on sync discard");
914                         } else if (strcmp(args[0].from, "async") == 0) {
915                                 btrfs_clear_opt(info->mount_opt, DISCARD_SYNC);
916                                 btrfs_set_and_info(info, DISCARD_ASYNC,
917                                                    "turning on async discard");
918                         } else {
919                                 btrfs_err(info, "unrecognized discard mode value %s",
920                                           args[0].from);
921                                 ret = -EINVAL;
922                                 goto out;
923                         }
924                         break;
925                 case Opt_nodiscard:
926                         btrfs_clear_and_info(info, DISCARD_SYNC,
927                                              "turning off discard");
928                         btrfs_clear_and_info(info, DISCARD_ASYNC,
929                                              "turning off async discard");
930                         break;
931                 case Opt_space_cache:
932                 case Opt_space_cache_version:
933                         /*
934                          * We already set FREE_SPACE_TREE above because we have
935                          * compat_ro(FREE_SPACE_TREE) set, and we aren't going
936                          * to allow v1 to be set for extent tree v2, simply
937                          * ignore this setting if we're extent tree v2.
938                          */
939                         if (btrfs_fs_incompat(info, EXTENT_TREE_V2))
940                                 break;
941                         if (token == Opt_space_cache ||
942                             strcmp(args[0].from, "v1") == 0) {
943                                 btrfs_clear_opt(info->mount_opt,
944                                                 FREE_SPACE_TREE);
945                                 btrfs_set_and_info(info, SPACE_CACHE,
946                                            "enabling disk space caching");
947                         } else if (strcmp(args[0].from, "v2") == 0) {
948                                 btrfs_clear_opt(info->mount_opt,
949                                                 SPACE_CACHE);
950                                 btrfs_set_and_info(info, FREE_SPACE_TREE,
951                                                    "enabling free space tree");
952                         } else {
953                                 btrfs_err(info, "unrecognized space_cache value %s",
954                                           args[0].from);
955                                 ret = -EINVAL;
956                                 goto out;
957                         }
958                         break;
959                 case Opt_rescan_uuid_tree:
960                         btrfs_set_opt(info->mount_opt, RESCAN_UUID_TREE);
961                         break;
962                 case Opt_no_space_cache:
963                         /*
964                          * We cannot operate without the free space tree with
965                          * extent tree v2, ignore this option.
966                          */
967                         if (btrfs_fs_incompat(info, EXTENT_TREE_V2))
968                                 break;
969                         if (btrfs_test_opt(info, SPACE_CACHE)) {
970                                 btrfs_clear_and_info(info, SPACE_CACHE,
971                                              "disabling disk space caching");
972                         }
973                         if (btrfs_test_opt(info, FREE_SPACE_TREE)) {
974                                 btrfs_clear_and_info(info, FREE_SPACE_TREE,
975                                              "disabling free space tree");
976                         }
977                         break;
978                 case Opt_inode_cache:
979                 case Opt_noinode_cache:
980                         btrfs_warn(info,
981         "the 'inode_cache' option is deprecated and has no effect since 5.11");
982                         break;
983                 case Opt_clear_cache:
984                         /*
985                          * We cannot clear the free space tree with extent tree
986                          * v2, ignore this option.
987                          */
988                         if (btrfs_fs_incompat(info, EXTENT_TREE_V2))
989                                 break;
990                         btrfs_set_and_info(info, CLEAR_CACHE,
991                                            "force clearing of disk cache");
992                         break;
993                 case Opt_user_subvol_rm_allowed:
994                         btrfs_set_opt(info->mount_opt, USER_SUBVOL_RM_ALLOWED);
995                         break;
996                 case Opt_enospc_debug:
997                         btrfs_set_opt(info->mount_opt, ENOSPC_DEBUG);
998                         break;
999                 case Opt_noenospc_debug:
1000                         btrfs_clear_opt(info->mount_opt, ENOSPC_DEBUG);
1001                         break;
1002                 case Opt_defrag:
1003                         btrfs_set_and_info(info, AUTO_DEFRAG,
1004                                            "enabling auto defrag");
1005                         break;
1006                 case Opt_nodefrag:
1007                         btrfs_clear_and_info(info, AUTO_DEFRAG,
1008                                              "disabling auto defrag");
1009                         break;
1010                 case Opt_recovery:
1011                 case Opt_usebackuproot:
1012                         btrfs_warn(info,
1013                         "'%s' is deprecated, use 'rescue=usebackuproot' instead",
1014                                    token == Opt_recovery ? "recovery" :
1015                                    "usebackuproot");
1016                         btrfs_info(info,
1017                                    "trying to use backup root at mount time");
1018                         btrfs_set_opt(info->mount_opt, USEBACKUPROOT);
1019                         break;
1020                 case Opt_skip_balance:
1021                         btrfs_set_opt(info->mount_opt, SKIP_BALANCE);
1022                         break;
1023 #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
1024                 case Opt_check_integrity_including_extent_data:
1025                         btrfs_info(info,
1026                                    "enabling check integrity including extent data");
1027                         btrfs_set_opt(info->mount_opt, CHECK_INTEGRITY_DATA);
1028                         btrfs_set_opt(info->mount_opt, CHECK_INTEGRITY);
1029                         break;
1030                 case Opt_check_integrity:
1031                         btrfs_info(info, "enabling check integrity");
1032                         btrfs_set_opt(info->mount_opt, CHECK_INTEGRITY);
1033                         break;
1034                 case Opt_check_integrity_print_mask:
1035                         ret = match_int(&args[0], &intarg);
1036                         if (ret) {
1037                                 btrfs_err(info,
1038                                 "unrecognized check_integrity_print_mask value %s",
1039                                         args[0].from);
1040                                 goto out;
1041                         }
1042                         info->check_integrity_print_mask = intarg;
1043                         btrfs_info(info, "check_integrity_print_mask 0x%x",
1044                                    info->check_integrity_print_mask);
1045                         break;
1046 #else
1047                 case Opt_check_integrity_including_extent_data:
1048                 case Opt_check_integrity:
1049                 case Opt_check_integrity_print_mask:
1050                         btrfs_err(info,
1051                                   "support for check_integrity* not compiled in!");
1052                         ret = -EINVAL;
1053                         goto out;
1054 #endif
1055                 case Opt_fatal_errors:
1056                         if (strcmp(args[0].from, "panic") == 0) {
1057                                 btrfs_set_opt(info->mount_opt,
1058                                               PANIC_ON_FATAL_ERROR);
1059                         } else if (strcmp(args[0].from, "bug") == 0) {
1060                                 btrfs_clear_opt(info->mount_opt,
1061                                               PANIC_ON_FATAL_ERROR);
1062                         } else {
1063                                 btrfs_err(info, "unrecognized fatal_errors value %s",
1064                                           args[0].from);
1065                                 ret = -EINVAL;
1066                                 goto out;
1067                         }
1068                         break;
1069                 case Opt_commit_interval:
1070                         intarg = 0;
1071                         ret = match_int(&args[0], &intarg);
1072                         if (ret) {
1073                                 btrfs_err(info, "unrecognized commit_interval value %s",
1074                                           args[0].from);
1075                                 ret = -EINVAL;
1076                                 goto out;
1077                         }
1078                         if (intarg == 0) {
1079                                 btrfs_info(info,
1080                                            "using default commit interval %us",
1081                                            BTRFS_DEFAULT_COMMIT_INTERVAL);
1082                                 intarg = BTRFS_DEFAULT_COMMIT_INTERVAL;
1083                         } else if (intarg > 300) {
1084                                 btrfs_warn(info, "excessive commit interval %d",
1085                                            intarg);
1086                         }
1087                         info->commit_interval = intarg;
1088                         break;
1089                 case Opt_rescue:
1090                         ret = parse_rescue_options(info, args[0].from);
1091                         if (ret < 0) {
1092                                 btrfs_err(info, "unrecognized rescue value %s",
1093                                           args[0].from);
1094                                 goto out;
1095                         }
1096                         break;
1097 #ifdef CONFIG_BTRFS_DEBUG
1098                 case Opt_fragment_all:
1099                         btrfs_info(info, "fragmenting all space");
1100                         btrfs_set_opt(info->mount_opt, FRAGMENT_DATA);
1101                         btrfs_set_opt(info->mount_opt, FRAGMENT_METADATA);
1102                         break;
1103                 case Opt_fragment_metadata:
1104                         btrfs_info(info, "fragmenting metadata");
1105                         btrfs_set_opt(info->mount_opt,
1106                                       FRAGMENT_METADATA);
1107                         break;
1108                 case Opt_fragment_data:
1109                         btrfs_info(info, "fragmenting data");
1110                         btrfs_set_opt(info->mount_opt, FRAGMENT_DATA);
1111                         break;
1112 #endif
1113 #ifdef CONFIG_BTRFS_FS_REF_VERIFY
1114                 case Opt_ref_verify:
1115                         btrfs_info(info, "doing ref verification");
1116                         btrfs_set_opt(info->mount_opt, REF_VERIFY);
1117                         break;
1118 #endif
1119                 case Opt_err:
1120                         btrfs_err(info, "unrecognized mount option '%s'", p);
1121                         ret = -EINVAL;
1122                         goto out;
1123                 default:
1124                         break;
1125                 }
1126         }
1127 check:
1128         /* We're read-only, don't have to check. */
1129         if (new_flags & SB_RDONLY)
1130                 goto out;
1131
1132         if (check_ro_option(info, BTRFS_MOUNT_NOLOGREPLAY, "nologreplay") ||
1133             check_ro_option(info, BTRFS_MOUNT_IGNOREBADROOTS, "ignorebadroots") ||
1134             check_ro_option(info, BTRFS_MOUNT_IGNOREDATACSUMS, "ignoredatacsums"))
1135                 ret = -EINVAL;
1136 out:
1137         if (btrfs_fs_compat_ro(info, FREE_SPACE_TREE) &&
1138             !btrfs_test_opt(info, FREE_SPACE_TREE) &&
1139             !btrfs_test_opt(info, CLEAR_CACHE)) {
1140                 btrfs_err(info, "cannot disable free space tree");
1141                 ret = -EINVAL;
1142         }
1143         if (btrfs_fs_compat_ro(info, BLOCK_GROUP_TREE) &&
1144              !btrfs_test_opt(info, FREE_SPACE_TREE)) {
1145                 btrfs_err(info, "cannot disable free space tree with block-group-tree feature");
1146                 ret = -EINVAL;
1147         }
1148         if (!ret)
1149                 ret = btrfs_check_mountopts_zoned(info);
1150         if (!ret && !remounting) {
1151                 if (btrfs_test_opt(info, SPACE_CACHE))
1152                         btrfs_info(info, "disk space caching is enabled");
1153                 if (btrfs_test_opt(info, FREE_SPACE_TREE))
1154                         btrfs_info(info, "using free space tree");
1155         }
1156         return ret;
1157 }
1158
1159 /*
1160  * Parse mount options that are required early in the mount process.
1161  *
1162  * All other options will be parsed on much later in the mount process and
1163  * only when we need to allocate a new super block.
1164  */
1165 static int btrfs_parse_device_options(const char *options, fmode_t flags,
1166                                       void *holder)
1167 {
1168         substring_t args[MAX_OPT_ARGS];
1169         char *device_name, *opts, *orig, *p;
1170         struct btrfs_device *device = NULL;
1171         int error = 0;
1172
1173         lockdep_assert_held(&uuid_mutex);
1174
1175         if (!options)
1176                 return 0;
1177
1178         /*
1179          * strsep changes the string, duplicate it because btrfs_parse_options
1180          * gets called later
1181          */
1182         opts = kstrdup(options, GFP_KERNEL);
1183         if (!opts)
1184                 return -ENOMEM;
1185         orig = opts;
1186
1187         while ((p = strsep(&opts, ",")) != NULL) {
1188                 int token;
1189
1190                 if (!*p)
1191                         continue;
1192
1193                 token = match_token(p, tokens, args);
1194                 if (token == Opt_device) {
1195                         device_name = match_strdup(&args[0]);
1196                         if (!device_name) {
1197                                 error = -ENOMEM;
1198                                 goto out;
1199                         }
1200                         device = btrfs_scan_one_device(device_name, flags,
1201                                         holder);
1202                         kfree(device_name);
1203                         if (IS_ERR(device)) {
1204                                 error = PTR_ERR(device);
1205                                 goto out;
1206                         }
1207                 }
1208         }
1209
1210 out:
1211         kfree(orig);
1212         return error;
1213 }
1214
1215 /*
1216  * Parse mount options that are related to subvolume id
1217  *
1218  * The value is later passed to mount_subvol()
1219  */
1220 static int btrfs_parse_subvol_options(const char *options, char **subvol_name,
1221                 u64 *subvol_objectid)
1222 {
1223         substring_t args[MAX_OPT_ARGS];
1224         char *opts, *orig, *p;
1225         int error = 0;
1226         u64 subvolid;
1227
1228         if (!options)
1229                 return 0;
1230
1231         /*
1232          * strsep changes the string, duplicate it because
1233          * btrfs_parse_device_options gets called later
1234          */
1235         opts = kstrdup(options, GFP_KERNEL);
1236         if (!opts)
1237                 return -ENOMEM;
1238         orig = opts;
1239
1240         while ((p = strsep(&opts, ",")) != NULL) {
1241                 int token;
1242                 if (!*p)
1243                         continue;
1244
1245                 token = match_token(p, tokens, args);
1246                 switch (token) {
1247                 case Opt_subvol:
1248                         kfree(*subvol_name);
1249                         *subvol_name = match_strdup(&args[0]);
1250                         if (!*subvol_name) {
1251                                 error = -ENOMEM;
1252                                 goto out;
1253                         }
1254                         break;
1255                 case Opt_subvolid:
1256                         error = match_u64(&args[0], &subvolid);
1257                         if (error)
1258                                 goto out;
1259
1260                         /* we want the original fs_tree */
1261                         if (subvolid == 0)
1262                                 subvolid = BTRFS_FS_TREE_OBJECTID;
1263
1264                         *subvol_objectid = subvolid;
1265                         break;
1266                 default:
1267                         break;
1268                 }
1269         }
1270
1271 out:
1272         kfree(orig);
1273         return error;
1274 }
1275
1276 char *btrfs_get_subvol_name_from_objectid(struct btrfs_fs_info *fs_info,
1277                                           u64 subvol_objectid)
1278 {
1279         struct btrfs_root *root = fs_info->tree_root;
1280         struct btrfs_root *fs_root = NULL;
1281         struct btrfs_root_ref *root_ref;
1282         struct btrfs_inode_ref *inode_ref;
1283         struct btrfs_key key;
1284         struct btrfs_path *path = NULL;
1285         char *name = NULL, *ptr;
1286         u64 dirid;
1287         int len;
1288         int ret;
1289
1290         path = btrfs_alloc_path();
1291         if (!path) {
1292                 ret = -ENOMEM;
1293                 goto err;
1294         }
1295
1296         name = kmalloc(PATH_MAX, GFP_KERNEL);
1297         if (!name) {
1298                 ret = -ENOMEM;
1299                 goto err;
1300         }
1301         ptr = name + PATH_MAX - 1;
1302         ptr[0] = '\0';
1303
1304         /*
1305          * Walk up the subvolume trees in the tree of tree roots by root
1306          * backrefs until we hit the top-level subvolume.
1307          */
1308         while (subvol_objectid != BTRFS_FS_TREE_OBJECTID) {
1309                 key.objectid = subvol_objectid;
1310                 key.type = BTRFS_ROOT_BACKREF_KEY;
1311                 key.offset = (u64)-1;
1312
1313                 ret = btrfs_search_backwards(root, &key, path);
1314                 if (ret < 0) {
1315                         goto err;
1316                 } else if (ret > 0) {
1317                         ret = -ENOENT;
1318                         goto err;
1319                 }
1320
1321                 subvol_objectid = key.offset;
1322
1323                 root_ref = btrfs_item_ptr(path->nodes[0], path->slots[0],
1324                                           struct btrfs_root_ref);
1325                 len = btrfs_root_ref_name_len(path->nodes[0], root_ref);
1326                 ptr -= len + 1;
1327                 if (ptr < name) {
1328                         ret = -ENAMETOOLONG;
1329                         goto err;
1330                 }
1331                 read_extent_buffer(path->nodes[0], ptr + 1,
1332                                    (unsigned long)(root_ref + 1), len);
1333                 ptr[0] = '/';
1334                 dirid = btrfs_root_ref_dirid(path->nodes[0], root_ref);
1335                 btrfs_release_path(path);
1336
1337                 fs_root = btrfs_get_fs_root(fs_info, subvol_objectid, true);
1338                 if (IS_ERR(fs_root)) {
1339                         ret = PTR_ERR(fs_root);
1340                         fs_root = NULL;
1341                         goto err;
1342                 }
1343
1344                 /*
1345                  * Walk up the filesystem tree by inode refs until we hit the
1346                  * root directory.
1347                  */
1348                 while (dirid != BTRFS_FIRST_FREE_OBJECTID) {
1349                         key.objectid = dirid;
1350                         key.type = BTRFS_INODE_REF_KEY;
1351                         key.offset = (u64)-1;
1352
1353                         ret = btrfs_search_backwards(fs_root, &key, path);
1354                         if (ret < 0) {
1355                                 goto err;
1356                         } else if (ret > 0) {
1357                                 ret = -ENOENT;
1358                                 goto err;
1359                         }
1360
1361                         dirid = key.offset;
1362
1363                         inode_ref = btrfs_item_ptr(path->nodes[0],
1364                                                    path->slots[0],
1365                                                    struct btrfs_inode_ref);
1366                         len = btrfs_inode_ref_name_len(path->nodes[0],
1367                                                        inode_ref);
1368                         ptr -= len + 1;
1369                         if (ptr < name) {
1370                                 ret = -ENAMETOOLONG;
1371                                 goto err;
1372                         }
1373                         read_extent_buffer(path->nodes[0], ptr + 1,
1374                                            (unsigned long)(inode_ref + 1), len);
1375                         ptr[0] = '/';
1376                         btrfs_release_path(path);
1377                 }
1378                 btrfs_put_root(fs_root);
1379                 fs_root = NULL;
1380         }
1381
1382         btrfs_free_path(path);
1383         if (ptr == name + PATH_MAX - 1) {
1384                 name[0] = '/';
1385                 name[1] = '\0';
1386         } else {
1387                 memmove(name, ptr, name + PATH_MAX - ptr);
1388         }
1389         return name;
1390
1391 err:
1392         btrfs_put_root(fs_root);
1393         btrfs_free_path(path);
1394         kfree(name);
1395         return ERR_PTR(ret);
1396 }
1397
1398 static int get_default_subvol_objectid(struct btrfs_fs_info *fs_info, u64 *objectid)
1399 {
1400         struct btrfs_root *root = fs_info->tree_root;
1401         struct btrfs_dir_item *di;
1402         struct btrfs_path *path;
1403         struct btrfs_key location;
1404         struct fscrypt_str name = FSTR_INIT("default", 7);
1405         u64 dir_id;
1406
1407         path = btrfs_alloc_path();
1408         if (!path)
1409                 return -ENOMEM;
1410
1411         /*
1412          * Find the "default" dir item which points to the root item that we
1413          * will mount by default if we haven't been given a specific subvolume
1414          * to mount.
1415          */
1416         dir_id = btrfs_super_root_dir(fs_info->super_copy);
1417         di = btrfs_lookup_dir_item(NULL, root, path, dir_id, &name, 0);
1418         if (IS_ERR(di)) {
1419                 btrfs_free_path(path);
1420                 return PTR_ERR(di);
1421         }
1422         if (!di) {
1423                 /*
1424                  * Ok the default dir item isn't there.  This is weird since
1425                  * it's always been there, but don't freak out, just try and
1426                  * mount the top-level subvolume.
1427                  */
1428                 btrfs_free_path(path);
1429                 *objectid = BTRFS_FS_TREE_OBJECTID;
1430                 return 0;
1431         }
1432
1433         btrfs_dir_item_key_to_cpu(path->nodes[0], di, &location);
1434         btrfs_free_path(path);
1435         *objectid = location.objectid;
1436         return 0;
1437 }
1438
1439 static int btrfs_fill_super(struct super_block *sb,
1440                             struct btrfs_fs_devices *fs_devices,
1441                             void *data)
1442 {
1443         struct inode *inode;
1444         struct btrfs_fs_info *fs_info = btrfs_sb(sb);
1445         int err;
1446
1447         sb->s_maxbytes = MAX_LFS_FILESIZE;
1448         sb->s_magic = BTRFS_SUPER_MAGIC;
1449         sb->s_op = &btrfs_super_ops;
1450         sb->s_d_op = &btrfs_dentry_operations;
1451         sb->s_export_op = &btrfs_export_ops;
1452 #ifdef CONFIG_FS_VERITY
1453         sb->s_vop = &btrfs_verityops;
1454 #endif
1455         sb->s_xattr = btrfs_xattr_handlers;
1456         sb->s_time_gran = 1;
1457 #ifdef CONFIG_BTRFS_FS_POSIX_ACL
1458         sb->s_flags |= SB_POSIXACL;
1459 #endif
1460         sb->s_flags |= SB_I_VERSION;
1461         sb->s_iflags |= SB_I_CGROUPWB;
1462
1463         err = super_setup_bdi(sb);
1464         if (err) {
1465                 btrfs_err(fs_info, "super_setup_bdi failed");
1466                 return err;
1467         }
1468
1469         err = open_ctree(sb, fs_devices, (char *)data);
1470         if (err) {
1471                 btrfs_err(fs_info, "open_ctree failed");
1472                 return err;
1473         }
1474
1475         inode = btrfs_iget(sb, BTRFS_FIRST_FREE_OBJECTID, fs_info->fs_root);
1476         if (IS_ERR(inode)) {
1477                 err = PTR_ERR(inode);
1478                 goto fail_close;
1479         }
1480
1481         sb->s_root = d_make_root(inode);
1482         if (!sb->s_root) {
1483                 err = -ENOMEM;
1484                 goto fail_close;
1485         }
1486
1487         sb->s_flags |= SB_ACTIVE;
1488         return 0;
1489
1490 fail_close:
1491         close_ctree(fs_info);
1492         return err;
1493 }
1494
1495 int btrfs_sync_fs(struct super_block *sb, int wait)
1496 {
1497         struct btrfs_trans_handle *trans;
1498         struct btrfs_fs_info *fs_info = btrfs_sb(sb);
1499         struct btrfs_root *root = fs_info->tree_root;
1500
1501         trace_btrfs_sync_fs(fs_info, wait);
1502
1503         if (!wait) {
1504                 filemap_flush(fs_info->btree_inode->i_mapping);
1505                 return 0;
1506         }
1507
1508         btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
1509
1510         trans = btrfs_attach_transaction_barrier(root);
1511         if (IS_ERR(trans)) {
1512                 /* no transaction, don't bother */
1513                 if (PTR_ERR(trans) == -ENOENT) {
1514                         /*
1515                          * Exit unless we have some pending changes
1516                          * that need to go through commit
1517                          */
1518                         if (fs_info->pending_changes == 0)
1519                                 return 0;
1520                         /*
1521                          * A non-blocking test if the fs is frozen. We must not
1522                          * start a new transaction here otherwise a deadlock
1523                          * happens. The pending operations are delayed to the
1524                          * next commit after thawing.
1525                          */
1526                         if (sb_start_write_trylock(sb))
1527                                 sb_end_write(sb);
1528                         else
1529                                 return 0;
1530                         trans = btrfs_start_transaction(root, 0);
1531                 }
1532                 if (IS_ERR(trans))
1533                         return PTR_ERR(trans);
1534         }
1535         return btrfs_commit_transaction(trans);
1536 }
1537
1538 static void print_rescue_option(struct seq_file *seq, const char *s, bool *printed)
1539 {
1540         seq_printf(seq, "%s%s", (*printed) ? ":" : ",rescue=", s);
1541         *printed = true;
1542 }
1543
1544 static int btrfs_show_options(struct seq_file *seq, struct dentry *dentry)
1545 {
1546         struct btrfs_fs_info *info = btrfs_sb(dentry->d_sb);
1547         const char *compress_type;
1548         const char *subvol_name;
1549         bool printed = false;
1550
1551         if (btrfs_test_opt(info, DEGRADED))
1552                 seq_puts(seq, ",degraded");
1553         if (btrfs_test_opt(info, NODATASUM))
1554                 seq_puts(seq, ",nodatasum");
1555         if (btrfs_test_opt(info, NODATACOW))
1556                 seq_puts(seq, ",nodatacow");
1557         if (btrfs_test_opt(info, NOBARRIER))
1558                 seq_puts(seq, ",nobarrier");
1559         if (info->max_inline != BTRFS_DEFAULT_MAX_INLINE)
1560                 seq_printf(seq, ",max_inline=%llu", info->max_inline);
1561         if (info->thread_pool_size !=  min_t(unsigned long,
1562                                              num_online_cpus() + 2, 8))
1563                 seq_printf(seq, ",thread_pool=%u", info->thread_pool_size);
1564         if (btrfs_test_opt(info, COMPRESS)) {
1565                 compress_type = btrfs_compress_type2str(info->compress_type);
1566                 if (btrfs_test_opt(info, FORCE_COMPRESS))
1567                         seq_printf(seq, ",compress-force=%s", compress_type);
1568                 else
1569                         seq_printf(seq, ",compress=%s", compress_type);
1570                 if (info->compress_level)
1571                         seq_printf(seq, ":%d", info->compress_level);
1572         }
1573         if (btrfs_test_opt(info, NOSSD))
1574                 seq_puts(seq, ",nossd");
1575         if (btrfs_test_opt(info, SSD_SPREAD))
1576                 seq_puts(seq, ",ssd_spread");
1577         else if (btrfs_test_opt(info, SSD))
1578                 seq_puts(seq, ",ssd");
1579         if (btrfs_test_opt(info, NOTREELOG))
1580                 seq_puts(seq, ",notreelog");
1581         if (btrfs_test_opt(info, NOLOGREPLAY))
1582                 print_rescue_option(seq, "nologreplay", &printed);
1583         if (btrfs_test_opt(info, USEBACKUPROOT))
1584                 print_rescue_option(seq, "usebackuproot", &printed);
1585         if (btrfs_test_opt(info, IGNOREBADROOTS))
1586                 print_rescue_option(seq, "ignorebadroots", &printed);
1587         if (btrfs_test_opt(info, IGNOREDATACSUMS))
1588                 print_rescue_option(seq, "ignoredatacsums", &printed);
1589         if (btrfs_test_opt(info, FLUSHONCOMMIT))
1590                 seq_puts(seq, ",flushoncommit");
1591         if (btrfs_test_opt(info, DISCARD_SYNC))
1592                 seq_puts(seq, ",discard");
1593         if (btrfs_test_opt(info, DISCARD_ASYNC))
1594                 seq_puts(seq, ",discard=async");
1595         if (!(info->sb->s_flags & SB_POSIXACL))
1596                 seq_puts(seq, ",noacl");
1597         if (btrfs_free_space_cache_v1_active(info))
1598                 seq_puts(seq, ",space_cache");
1599         else if (btrfs_fs_compat_ro(info, FREE_SPACE_TREE))
1600                 seq_puts(seq, ",space_cache=v2");
1601         else
1602                 seq_puts(seq, ",nospace_cache");
1603         if (btrfs_test_opt(info, RESCAN_UUID_TREE))
1604                 seq_puts(seq, ",rescan_uuid_tree");
1605         if (btrfs_test_opt(info, CLEAR_CACHE))
1606                 seq_puts(seq, ",clear_cache");
1607         if (btrfs_test_opt(info, USER_SUBVOL_RM_ALLOWED))
1608                 seq_puts(seq, ",user_subvol_rm_allowed");
1609         if (btrfs_test_opt(info, ENOSPC_DEBUG))
1610                 seq_puts(seq, ",enospc_debug");
1611         if (btrfs_test_opt(info, AUTO_DEFRAG))
1612                 seq_puts(seq, ",autodefrag");
1613         if (btrfs_test_opt(info, SKIP_BALANCE))
1614                 seq_puts(seq, ",skip_balance");
1615 #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
1616         if (btrfs_test_opt(info, CHECK_INTEGRITY_DATA))
1617                 seq_puts(seq, ",check_int_data");
1618         else if (btrfs_test_opt(info, CHECK_INTEGRITY))
1619                 seq_puts(seq, ",check_int");
1620         if (info->check_integrity_print_mask)
1621                 seq_printf(seq, ",check_int_print_mask=%d",
1622                                 info->check_integrity_print_mask);
1623 #endif
1624         if (info->metadata_ratio)
1625                 seq_printf(seq, ",metadata_ratio=%u", info->metadata_ratio);
1626         if (btrfs_test_opt(info, PANIC_ON_FATAL_ERROR))
1627                 seq_puts(seq, ",fatal_errors=panic");
1628         if (info->commit_interval != BTRFS_DEFAULT_COMMIT_INTERVAL)
1629                 seq_printf(seq, ",commit=%u", info->commit_interval);
1630 #ifdef CONFIG_BTRFS_DEBUG
1631         if (btrfs_test_opt(info, FRAGMENT_DATA))
1632                 seq_puts(seq, ",fragment=data");
1633         if (btrfs_test_opt(info, FRAGMENT_METADATA))
1634                 seq_puts(seq, ",fragment=metadata");
1635 #endif
1636         if (btrfs_test_opt(info, REF_VERIFY))
1637                 seq_puts(seq, ",ref_verify");
1638         seq_printf(seq, ",subvolid=%llu",
1639                   BTRFS_I(d_inode(dentry))->root->root_key.objectid);
1640         subvol_name = btrfs_get_subvol_name_from_objectid(info,
1641                         BTRFS_I(d_inode(dentry))->root->root_key.objectid);
1642         if (!IS_ERR(subvol_name)) {
1643                 seq_puts(seq, ",subvol=");
1644                 seq_escape(seq, subvol_name, " \t\n\\");
1645                 kfree(subvol_name);
1646         }
1647         return 0;
1648 }
1649
1650 static int btrfs_test_super(struct super_block *s, void *data)
1651 {
1652         struct btrfs_fs_info *p = data;
1653         struct btrfs_fs_info *fs_info = btrfs_sb(s);
1654
1655         return fs_info->fs_devices == p->fs_devices;
1656 }
1657
1658 static int btrfs_set_super(struct super_block *s, void *data)
1659 {
1660         int err = set_anon_super(s, data);
1661         if (!err)
1662                 s->s_fs_info = data;
1663         return err;
1664 }
1665
1666 /*
1667  * subvolumes are identified by ino 256
1668  */
1669 static inline int is_subvolume_inode(struct inode *inode)
1670 {
1671         if (inode && inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)
1672                 return 1;
1673         return 0;
1674 }
1675
1676 static struct dentry *mount_subvol(const char *subvol_name, u64 subvol_objectid,
1677                                    struct vfsmount *mnt)
1678 {
1679         struct dentry *root;
1680         int ret;
1681
1682         if (!subvol_name) {
1683                 if (!subvol_objectid) {
1684                         ret = get_default_subvol_objectid(btrfs_sb(mnt->mnt_sb),
1685                                                           &subvol_objectid);
1686                         if (ret) {
1687                                 root = ERR_PTR(ret);
1688                                 goto out;
1689                         }
1690                 }
1691                 subvol_name = btrfs_get_subvol_name_from_objectid(
1692                                         btrfs_sb(mnt->mnt_sb), subvol_objectid);
1693                 if (IS_ERR(subvol_name)) {
1694                         root = ERR_CAST(subvol_name);
1695                         subvol_name = NULL;
1696                         goto out;
1697                 }
1698
1699         }
1700
1701         root = mount_subtree(mnt, subvol_name);
1702         /* mount_subtree() drops our reference on the vfsmount. */
1703         mnt = NULL;
1704
1705         if (!IS_ERR(root)) {
1706                 struct super_block *s = root->d_sb;
1707                 struct btrfs_fs_info *fs_info = btrfs_sb(s);
1708                 struct inode *root_inode = d_inode(root);
1709                 u64 root_objectid = BTRFS_I(root_inode)->root->root_key.objectid;
1710
1711                 ret = 0;
1712                 if (!is_subvolume_inode(root_inode)) {
1713                         btrfs_err(fs_info, "'%s' is not a valid subvolume",
1714                                subvol_name);
1715                         ret = -EINVAL;
1716                 }
1717                 if (subvol_objectid && root_objectid != subvol_objectid) {
1718                         /*
1719                          * This will also catch a race condition where a
1720                          * subvolume which was passed by ID is renamed and
1721                          * another subvolume is renamed over the old location.
1722                          */
1723                         btrfs_err(fs_info,
1724                                   "subvol '%s' does not match subvolid %llu",
1725                                   subvol_name, subvol_objectid);
1726                         ret = -EINVAL;
1727                 }
1728                 if (ret) {
1729                         dput(root);
1730                         root = ERR_PTR(ret);
1731                         deactivate_locked_super(s);
1732                 }
1733         }
1734
1735 out:
1736         mntput(mnt);
1737         kfree(subvol_name);
1738         return root;
1739 }
1740
1741 /*
1742  * Find a superblock for the given device / mount point.
1743  *
1744  * Note: This is based on mount_bdev from fs/super.c with a few additions
1745  *       for multiple device setup.  Make sure to keep it in sync.
1746  */
1747 static struct dentry *btrfs_mount_root(struct file_system_type *fs_type,
1748                 int flags, const char *device_name, void *data)
1749 {
1750         struct block_device *bdev = NULL;
1751         struct super_block *s;
1752         struct btrfs_device *device = NULL;
1753         struct btrfs_fs_devices *fs_devices = NULL;
1754         struct btrfs_fs_info *fs_info = NULL;
1755         void *new_sec_opts = NULL;
1756         fmode_t mode = FMODE_READ;
1757         int error = 0;
1758
1759         if (!(flags & SB_RDONLY))
1760                 mode |= FMODE_WRITE;
1761
1762         if (data) {
1763                 error = security_sb_eat_lsm_opts(data, &new_sec_opts);
1764                 if (error)
1765                         return ERR_PTR(error);
1766         }
1767
1768         /*
1769          * Setup a dummy root and fs_info for test/set super.  This is because
1770          * we don't actually fill this stuff out until open_ctree, but we need
1771          * then open_ctree will properly initialize the file system specific
1772          * settings later.  btrfs_init_fs_info initializes the static elements
1773          * of the fs_info (locks and such) to make cleanup easier if we find a
1774          * superblock with our given fs_devices later on at sget() time.
1775          */
1776         fs_info = kvzalloc(sizeof(struct btrfs_fs_info), GFP_KERNEL);
1777         if (!fs_info) {
1778                 error = -ENOMEM;
1779                 goto error_sec_opts;
1780         }
1781         btrfs_init_fs_info(fs_info);
1782
1783         fs_info->super_copy = kzalloc(BTRFS_SUPER_INFO_SIZE, GFP_KERNEL);
1784         fs_info->super_for_commit = kzalloc(BTRFS_SUPER_INFO_SIZE, GFP_KERNEL);
1785         if (!fs_info->super_copy || !fs_info->super_for_commit) {
1786                 error = -ENOMEM;
1787                 goto error_fs_info;
1788         }
1789
1790         mutex_lock(&uuid_mutex);
1791         error = btrfs_parse_device_options(data, mode, fs_type);
1792         if (error) {
1793                 mutex_unlock(&uuid_mutex);
1794                 goto error_fs_info;
1795         }
1796
1797         device = btrfs_scan_one_device(device_name, mode, fs_type);
1798         if (IS_ERR(device)) {
1799                 mutex_unlock(&uuid_mutex);
1800                 error = PTR_ERR(device);
1801                 goto error_fs_info;
1802         }
1803
1804         fs_devices = device->fs_devices;
1805         fs_info->fs_devices = fs_devices;
1806
1807         error = btrfs_open_devices(fs_devices, mode, fs_type);
1808         mutex_unlock(&uuid_mutex);
1809         if (error)
1810                 goto error_fs_info;
1811
1812         if (!(flags & SB_RDONLY) && fs_devices->rw_devices == 0) {
1813                 error = -EACCES;
1814                 goto error_close_devices;
1815         }
1816
1817         bdev = fs_devices->latest_dev->bdev;
1818         s = sget(fs_type, btrfs_test_super, btrfs_set_super, flags | SB_NOSEC,
1819                  fs_info);
1820         if (IS_ERR(s)) {
1821                 error = PTR_ERR(s);
1822                 goto error_close_devices;
1823         }
1824
1825         if (s->s_root) {
1826                 btrfs_close_devices(fs_devices);
1827                 btrfs_free_fs_info(fs_info);
1828                 if ((flags ^ s->s_flags) & SB_RDONLY)
1829                         error = -EBUSY;
1830         } else {
1831                 snprintf(s->s_id, sizeof(s->s_id), "%pg", bdev);
1832                 shrinker_debugfs_rename(&s->s_shrink, "sb-%s:%s", fs_type->name,
1833                                         s->s_id);
1834                 btrfs_sb(s)->bdev_holder = fs_type;
1835                 error = btrfs_fill_super(s, fs_devices, data);
1836         }
1837         if (!error)
1838                 error = security_sb_set_mnt_opts(s, new_sec_opts, 0, NULL);
1839         security_free_mnt_opts(&new_sec_opts);
1840         if (error) {
1841                 deactivate_locked_super(s);
1842                 return ERR_PTR(error);
1843         }
1844
1845         return dget(s->s_root);
1846
1847 error_close_devices:
1848         btrfs_close_devices(fs_devices);
1849 error_fs_info:
1850         btrfs_free_fs_info(fs_info);
1851 error_sec_opts:
1852         security_free_mnt_opts(&new_sec_opts);
1853         return ERR_PTR(error);
1854 }
1855
1856 /*
1857  * Mount function which is called by VFS layer.
1858  *
1859  * In order to allow mounting a subvolume directly, btrfs uses mount_subtree()
1860  * which needs vfsmount* of device's root (/).  This means device's root has to
1861  * be mounted internally in any case.
1862  *
1863  * Operation flow:
1864  *   1. Parse subvol id related options for later use in mount_subvol().
1865  *
1866  *   2. Mount device's root (/) by calling vfs_kern_mount().
1867  *
1868  *      NOTE: vfs_kern_mount() is used by VFS to call btrfs_mount() in the
1869  *      first place. In order to avoid calling btrfs_mount() again, we use
1870  *      different file_system_type which is not registered to VFS by
1871  *      register_filesystem() (btrfs_root_fs_type). As a result,
1872  *      btrfs_mount_root() is called. The return value will be used by
1873  *      mount_subtree() in mount_subvol().
1874  *
1875  *   3. Call mount_subvol() to get the dentry of subvolume. Since there is
1876  *      "btrfs subvolume set-default", mount_subvol() is called always.
1877  */
1878 static struct dentry *btrfs_mount(struct file_system_type *fs_type, int flags,
1879                 const char *device_name, void *data)
1880 {
1881         struct vfsmount *mnt_root;
1882         struct dentry *root;
1883         char *subvol_name = NULL;
1884         u64 subvol_objectid = 0;
1885         int error = 0;
1886
1887         error = btrfs_parse_subvol_options(data, &subvol_name,
1888                                         &subvol_objectid);
1889         if (error) {
1890                 kfree(subvol_name);
1891                 return ERR_PTR(error);
1892         }
1893
1894         /* mount device's root (/) */
1895         mnt_root = vfs_kern_mount(&btrfs_root_fs_type, flags, device_name, data);
1896         if (PTR_ERR_OR_ZERO(mnt_root) == -EBUSY) {
1897                 if (flags & SB_RDONLY) {
1898                         mnt_root = vfs_kern_mount(&btrfs_root_fs_type,
1899                                 flags & ~SB_RDONLY, device_name, data);
1900                 } else {
1901                         mnt_root = vfs_kern_mount(&btrfs_root_fs_type,
1902                                 flags | SB_RDONLY, device_name, data);
1903                         if (IS_ERR(mnt_root)) {
1904                                 root = ERR_CAST(mnt_root);
1905                                 kfree(subvol_name);
1906                                 goto out;
1907                         }
1908
1909                         down_write(&mnt_root->mnt_sb->s_umount);
1910                         error = btrfs_remount(mnt_root->mnt_sb, &flags, NULL);
1911                         up_write(&mnt_root->mnt_sb->s_umount);
1912                         if (error < 0) {
1913                                 root = ERR_PTR(error);
1914                                 mntput(mnt_root);
1915                                 kfree(subvol_name);
1916                                 goto out;
1917                         }
1918                 }
1919         }
1920         if (IS_ERR(mnt_root)) {
1921                 root = ERR_CAST(mnt_root);
1922                 kfree(subvol_name);
1923                 goto out;
1924         }
1925
1926         /* mount_subvol() will free subvol_name and mnt_root */
1927         root = mount_subvol(subvol_name, subvol_objectid, mnt_root);
1928
1929 out:
1930         return root;
1931 }
1932
1933 static void btrfs_resize_thread_pool(struct btrfs_fs_info *fs_info,
1934                                      u32 new_pool_size, u32 old_pool_size)
1935 {
1936         if (new_pool_size == old_pool_size)
1937                 return;
1938
1939         fs_info->thread_pool_size = new_pool_size;
1940
1941         btrfs_info(fs_info, "resize thread pool %d -> %d",
1942                old_pool_size, new_pool_size);
1943
1944         btrfs_workqueue_set_max(fs_info->workers, new_pool_size);
1945         btrfs_workqueue_set_max(fs_info->hipri_workers, new_pool_size);
1946         btrfs_workqueue_set_max(fs_info->delalloc_workers, new_pool_size);
1947         btrfs_workqueue_set_max(fs_info->caching_workers, new_pool_size);
1948         workqueue_set_max_active(fs_info->endio_workers, new_pool_size);
1949         workqueue_set_max_active(fs_info->endio_meta_workers, new_pool_size);
1950         btrfs_workqueue_set_max(fs_info->endio_write_workers, new_pool_size);
1951         btrfs_workqueue_set_max(fs_info->endio_freespace_worker, new_pool_size);
1952         btrfs_workqueue_set_max(fs_info->delayed_workers, new_pool_size);
1953 }
1954
1955 static inline void btrfs_remount_begin(struct btrfs_fs_info *fs_info,
1956                                        unsigned long old_opts, int flags)
1957 {
1958         if (btrfs_raw_test_opt(old_opts, AUTO_DEFRAG) &&
1959             (!btrfs_raw_test_opt(fs_info->mount_opt, AUTO_DEFRAG) ||
1960              (flags & SB_RDONLY))) {
1961                 /* wait for any defraggers to finish */
1962                 wait_event(fs_info->transaction_wait,
1963                            (atomic_read(&fs_info->defrag_running) == 0));
1964                 if (flags & SB_RDONLY)
1965                         sync_filesystem(fs_info->sb);
1966         }
1967 }
1968
1969 static inline void btrfs_remount_cleanup(struct btrfs_fs_info *fs_info,
1970                                          unsigned long old_opts)
1971 {
1972         const bool cache_opt = btrfs_test_opt(fs_info, SPACE_CACHE);
1973
1974         /*
1975          * We need to cleanup all defragable inodes if the autodefragment is
1976          * close or the filesystem is read only.
1977          */
1978         if (btrfs_raw_test_opt(old_opts, AUTO_DEFRAG) &&
1979             (!btrfs_raw_test_opt(fs_info->mount_opt, AUTO_DEFRAG) || sb_rdonly(fs_info->sb))) {
1980                 btrfs_cleanup_defrag_inodes(fs_info);
1981         }
1982
1983         /* If we toggled discard async */
1984         if (!btrfs_raw_test_opt(old_opts, DISCARD_ASYNC) &&
1985             btrfs_test_opt(fs_info, DISCARD_ASYNC))
1986                 btrfs_discard_resume(fs_info);
1987         else if (btrfs_raw_test_opt(old_opts, DISCARD_ASYNC) &&
1988                  !btrfs_test_opt(fs_info, DISCARD_ASYNC))
1989                 btrfs_discard_cleanup(fs_info);
1990
1991         /* If we toggled space cache */
1992         if (cache_opt != btrfs_free_space_cache_v1_active(fs_info))
1993                 btrfs_set_free_space_cache_v1_active(fs_info, cache_opt);
1994 }
1995
1996 static int btrfs_remount(struct super_block *sb, int *flags, char *data)
1997 {
1998         struct btrfs_fs_info *fs_info = btrfs_sb(sb);
1999         unsigned old_flags = sb->s_flags;
2000         unsigned long old_opts = fs_info->mount_opt;
2001         unsigned long old_compress_type = fs_info->compress_type;
2002         u64 old_max_inline = fs_info->max_inline;
2003         u32 old_thread_pool_size = fs_info->thread_pool_size;
2004         u32 old_metadata_ratio = fs_info->metadata_ratio;
2005         int ret;
2006
2007         sync_filesystem(sb);
2008         set_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state);
2009
2010         if (data) {
2011                 void *new_sec_opts = NULL;
2012
2013                 ret = security_sb_eat_lsm_opts(data, &new_sec_opts);
2014                 if (!ret)
2015                         ret = security_sb_remount(sb, new_sec_opts);
2016                 security_free_mnt_opts(&new_sec_opts);
2017                 if (ret)
2018                         goto restore;
2019         }
2020
2021         ret = btrfs_parse_options(fs_info, data, *flags);
2022         if (ret)
2023                 goto restore;
2024
2025         ret = btrfs_check_features(fs_info, !(*flags & SB_RDONLY));
2026         if (ret < 0)
2027                 goto restore;
2028
2029         btrfs_remount_begin(fs_info, old_opts, *flags);
2030         btrfs_resize_thread_pool(fs_info,
2031                 fs_info->thread_pool_size, old_thread_pool_size);
2032
2033         if ((bool)btrfs_test_opt(fs_info, FREE_SPACE_TREE) !=
2034             (bool)btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
2035             (!sb_rdonly(sb) || (*flags & SB_RDONLY))) {
2036                 btrfs_warn(fs_info,
2037                 "remount supports changing free space tree only from ro to rw");
2038                 /* Make sure free space cache options match the state on disk */
2039                 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
2040                         btrfs_set_opt(fs_info->mount_opt, FREE_SPACE_TREE);
2041                         btrfs_clear_opt(fs_info->mount_opt, SPACE_CACHE);
2042                 }
2043                 if (btrfs_free_space_cache_v1_active(fs_info)) {
2044                         btrfs_clear_opt(fs_info->mount_opt, FREE_SPACE_TREE);
2045                         btrfs_set_opt(fs_info->mount_opt, SPACE_CACHE);
2046                 }
2047         }
2048
2049         if ((bool)(*flags & SB_RDONLY) == sb_rdonly(sb))
2050                 goto out;
2051
2052         if (*flags & SB_RDONLY) {
2053                 /*
2054                  * this also happens on 'umount -rf' or on shutdown, when
2055                  * the filesystem is busy.
2056                  */
2057                 cancel_work_sync(&fs_info->async_reclaim_work);
2058                 cancel_work_sync(&fs_info->async_data_reclaim_work);
2059
2060                 btrfs_discard_cleanup(fs_info);
2061
2062                 /* wait for the uuid_scan task to finish */
2063                 down(&fs_info->uuid_tree_rescan_sem);
2064                 /* avoid complains from lockdep et al. */
2065                 up(&fs_info->uuid_tree_rescan_sem);
2066
2067                 btrfs_set_sb_rdonly(sb);
2068
2069                 /*
2070                  * Setting SB_RDONLY will put the cleaner thread to
2071                  * sleep at the next loop if it's already active.
2072                  * If it's already asleep, we'll leave unused block
2073                  * groups on disk until we're mounted read-write again
2074                  * unless we clean them up here.
2075                  */
2076                 btrfs_delete_unused_bgs(fs_info);
2077
2078                 /*
2079                  * The cleaner task could be already running before we set the
2080                  * flag BTRFS_FS_STATE_RO (and SB_RDONLY in the superblock).
2081                  * We must make sure that after we finish the remount, i.e. after
2082                  * we call btrfs_commit_super(), the cleaner can no longer start
2083                  * a transaction - either because it was dropping a dead root,
2084                  * running delayed iputs or deleting an unused block group (the
2085                  * cleaner picked a block group from the list of unused block
2086                  * groups before we were able to in the previous call to
2087                  * btrfs_delete_unused_bgs()).
2088                  */
2089                 wait_on_bit(&fs_info->flags, BTRFS_FS_CLEANER_RUNNING,
2090                             TASK_UNINTERRUPTIBLE);
2091
2092                 /*
2093                  * We've set the superblock to RO mode, so we might have made
2094                  * the cleaner task sleep without running all pending delayed
2095                  * iputs. Go through all the delayed iputs here, so that if an
2096                  * unmount happens without remounting RW we don't end up at
2097                  * finishing close_ctree() with a non-empty list of delayed
2098                  * iputs.
2099                  */
2100                 btrfs_run_delayed_iputs(fs_info);
2101
2102                 btrfs_dev_replace_suspend_for_unmount(fs_info);
2103                 btrfs_scrub_cancel(fs_info);
2104                 btrfs_pause_balance(fs_info);
2105
2106                 /*
2107                  * Pause the qgroup rescan worker if it is running. We don't want
2108                  * it to be still running after we are in RO mode, as after that,
2109                  * by the time we unmount, it might have left a transaction open,
2110                  * so we would leak the transaction and/or crash.
2111                  */
2112                 btrfs_qgroup_wait_for_completion(fs_info, false);
2113
2114                 ret = btrfs_commit_super(fs_info);
2115                 if (ret)
2116                         goto restore;
2117         } else {
2118                 if (BTRFS_FS_ERROR(fs_info)) {
2119                         btrfs_err(fs_info,
2120                                 "Remounting read-write after error is not allowed");
2121                         ret = -EINVAL;
2122                         goto restore;
2123                 }
2124                 if (fs_info->fs_devices->rw_devices == 0) {
2125                         ret = -EACCES;
2126                         goto restore;
2127                 }
2128
2129                 if (!btrfs_check_rw_degradable(fs_info, NULL)) {
2130                         btrfs_warn(fs_info,
2131                 "too many missing devices, writable remount is not allowed");
2132                         ret = -EACCES;
2133                         goto restore;
2134                 }
2135
2136                 if (btrfs_super_log_root(fs_info->super_copy) != 0) {
2137                         btrfs_warn(fs_info,
2138                 "mount required to replay tree-log, cannot remount read-write");
2139                         ret = -EINVAL;
2140                         goto restore;
2141                 }
2142
2143                 /*
2144                  * NOTE: when remounting with a change that does writes, don't
2145                  * put it anywhere above this point, as we are not sure to be
2146                  * safe to write until we pass the above checks.
2147                  */
2148                 ret = btrfs_start_pre_rw_mount(fs_info);
2149                 if (ret)
2150                         goto restore;
2151
2152                 btrfs_clear_sb_rdonly(sb);
2153
2154                 set_bit(BTRFS_FS_OPEN, &fs_info->flags);
2155         }
2156 out:
2157         /*
2158          * We need to set SB_I_VERSION here otherwise it'll get cleared by VFS,
2159          * since the absence of the flag means it can be toggled off by remount.
2160          */
2161         *flags |= SB_I_VERSION;
2162
2163         wake_up_process(fs_info->transaction_kthread);
2164         btrfs_remount_cleanup(fs_info, old_opts);
2165         btrfs_clear_oneshot_options(fs_info);
2166         clear_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state);
2167
2168         return 0;
2169
2170 restore:
2171         /* We've hit an error - don't reset SB_RDONLY */
2172         if (sb_rdonly(sb))
2173                 old_flags |= SB_RDONLY;
2174         if (!(old_flags & SB_RDONLY))
2175                 clear_bit(BTRFS_FS_STATE_RO, &fs_info->fs_state);
2176         sb->s_flags = old_flags;
2177         fs_info->mount_opt = old_opts;
2178         fs_info->compress_type = old_compress_type;
2179         fs_info->max_inline = old_max_inline;
2180         btrfs_resize_thread_pool(fs_info,
2181                 old_thread_pool_size, fs_info->thread_pool_size);
2182         fs_info->metadata_ratio = old_metadata_ratio;
2183         btrfs_remount_cleanup(fs_info, old_opts);
2184         clear_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state);
2185
2186         return ret;
2187 }
2188
2189 /* Used to sort the devices by max_avail(descending sort) */
2190 static int btrfs_cmp_device_free_bytes(const void *a, const void *b)
2191 {
2192         const struct btrfs_device_info *dev_info1 = a;
2193         const struct btrfs_device_info *dev_info2 = b;
2194
2195         if (dev_info1->max_avail > dev_info2->max_avail)
2196                 return -1;
2197         else if (dev_info1->max_avail < dev_info2->max_avail)
2198                 return 1;
2199         return 0;
2200 }
2201
2202 /*
2203  * sort the devices by max_avail, in which max free extent size of each device
2204  * is stored.(Descending Sort)
2205  */
2206 static inline void btrfs_descending_sort_devices(
2207                                         struct btrfs_device_info *devices,
2208                                         size_t nr_devices)
2209 {
2210         sort(devices, nr_devices, sizeof(struct btrfs_device_info),
2211              btrfs_cmp_device_free_bytes, NULL);
2212 }
2213
2214 /*
2215  * The helper to calc the free space on the devices that can be used to store
2216  * file data.
2217  */
2218 static inline int btrfs_calc_avail_data_space(struct btrfs_fs_info *fs_info,
2219                                               u64 *free_bytes)
2220 {
2221         struct btrfs_device_info *devices_info;
2222         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2223         struct btrfs_device *device;
2224         u64 type;
2225         u64 avail_space;
2226         u64 min_stripe_size;
2227         int num_stripes = 1;
2228         int i = 0, nr_devices;
2229         const struct btrfs_raid_attr *rattr;
2230
2231         /*
2232          * We aren't under the device list lock, so this is racy-ish, but good
2233          * enough for our purposes.
2234          */
2235         nr_devices = fs_info->fs_devices->open_devices;
2236         if (!nr_devices) {
2237                 smp_mb();
2238                 nr_devices = fs_info->fs_devices->open_devices;
2239                 ASSERT(nr_devices);
2240                 if (!nr_devices) {
2241                         *free_bytes = 0;
2242                         return 0;
2243                 }
2244         }
2245
2246         devices_info = kmalloc_array(nr_devices, sizeof(*devices_info),
2247                                GFP_KERNEL);
2248         if (!devices_info)
2249                 return -ENOMEM;
2250
2251         /* calc min stripe number for data space allocation */
2252         type = btrfs_data_alloc_profile(fs_info);
2253         rattr = &btrfs_raid_array[btrfs_bg_flags_to_raid_index(type)];
2254
2255         if (type & BTRFS_BLOCK_GROUP_RAID0)
2256                 num_stripes = nr_devices;
2257         else if (type & BTRFS_BLOCK_GROUP_RAID1_MASK)
2258                 num_stripes = rattr->ncopies;
2259         else if (type & BTRFS_BLOCK_GROUP_RAID10)
2260                 num_stripes = 4;
2261
2262         /* Adjust for more than 1 stripe per device */
2263         min_stripe_size = rattr->dev_stripes * BTRFS_STRIPE_LEN;
2264
2265         rcu_read_lock();
2266         list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
2267                 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
2268                                                 &device->dev_state) ||
2269                     !device->bdev ||
2270                     test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
2271                         continue;
2272
2273                 if (i >= nr_devices)
2274                         break;
2275
2276                 avail_space = device->total_bytes - device->bytes_used;
2277
2278                 /* align with stripe_len */
2279                 avail_space = rounddown(avail_space, BTRFS_STRIPE_LEN);
2280
2281                 /*
2282                  * Ensure we have at least min_stripe_size on top of the
2283                  * reserved space on the device.
2284                  */
2285                 if (avail_space <= BTRFS_DEVICE_RANGE_RESERVED + min_stripe_size)
2286                         continue;
2287
2288                 avail_space -= BTRFS_DEVICE_RANGE_RESERVED;
2289
2290                 devices_info[i].dev = device;
2291                 devices_info[i].max_avail = avail_space;
2292
2293                 i++;
2294         }
2295         rcu_read_unlock();
2296
2297         nr_devices = i;
2298
2299         btrfs_descending_sort_devices(devices_info, nr_devices);
2300
2301         i = nr_devices - 1;
2302         avail_space = 0;
2303         while (nr_devices >= rattr->devs_min) {
2304                 num_stripes = min(num_stripes, nr_devices);
2305
2306                 if (devices_info[i].max_avail >= min_stripe_size) {
2307                         int j;
2308                         u64 alloc_size;
2309
2310                         avail_space += devices_info[i].max_avail * num_stripes;
2311                         alloc_size = devices_info[i].max_avail;
2312                         for (j = i + 1 - num_stripes; j <= i; j++)
2313                                 devices_info[j].max_avail -= alloc_size;
2314                 }
2315                 i--;
2316                 nr_devices--;
2317         }
2318
2319         kfree(devices_info);
2320         *free_bytes = avail_space;
2321         return 0;
2322 }
2323
2324 /*
2325  * Calculate numbers for 'df', pessimistic in case of mixed raid profiles.
2326  *
2327  * If there's a redundant raid level at DATA block groups, use the respective
2328  * multiplier to scale the sizes.
2329  *
2330  * Unused device space usage is based on simulating the chunk allocator
2331  * algorithm that respects the device sizes and order of allocations.  This is
2332  * a close approximation of the actual use but there are other factors that may
2333  * change the result (like a new metadata chunk).
2334  *
2335  * If metadata is exhausted, f_bavail will be 0.
2336  */
2337 static int btrfs_statfs(struct dentry *dentry, struct kstatfs *buf)
2338 {
2339         struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
2340         struct btrfs_super_block *disk_super = fs_info->super_copy;
2341         struct btrfs_space_info *found;
2342         u64 total_used = 0;
2343         u64 total_free_data = 0;
2344         u64 total_free_meta = 0;
2345         u32 bits = fs_info->sectorsize_bits;
2346         __be32 *fsid = (__be32 *)fs_info->fs_devices->fsid;
2347         unsigned factor = 1;
2348         struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
2349         int ret;
2350         u64 thresh = 0;
2351         int mixed = 0;
2352
2353         list_for_each_entry(found, &fs_info->space_info, list) {
2354                 if (found->flags & BTRFS_BLOCK_GROUP_DATA) {
2355                         int i;
2356
2357                         total_free_data += found->disk_total - found->disk_used;
2358                         total_free_data -=
2359                                 btrfs_account_ro_block_groups_free_space(found);
2360
2361                         for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
2362                                 if (!list_empty(&found->block_groups[i]))
2363                                         factor = btrfs_bg_type_to_factor(
2364                                                 btrfs_raid_array[i].bg_flag);
2365                         }
2366                 }
2367
2368                 /*
2369                  * Metadata in mixed block goup profiles are accounted in data
2370                  */
2371                 if (!mixed && found->flags & BTRFS_BLOCK_GROUP_METADATA) {
2372                         if (found->flags & BTRFS_BLOCK_GROUP_DATA)
2373                                 mixed = 1;
2374                         else
2375                                 total_free_meta += found->disk_total -
2376                                         found->disk_used;
2377                 }
2378
2379                 total_used += found->disk_used;
2380         }
2381
2382         buf->f_blocks = div_u64(btrfs_super_total_bytes(disk_super), factor);
2383         buf->f_blocks >>= bits;
2384         buf->f_bfree = buf->f_blocks - (div_u64(total_used, factor) >> bits);
2385
2386         /* Account global block reserve as used, it's in logical size already */
2387         spin_lock(&block_rsv->lock);
2388         /* Mixed block groups accounting is not byte-accurate, avoid overflow */
2389         if (buf->f_bfree >= block_rsv->size >> bits)
2390                 buf->f_bfree -= block_rsv->size >> bits;
2391         else
2392                 buf->f_bfree = 0;
2393         spin_unlock(&block_rsv->lock);
2394
2395         buf->f_bavail = div_u64(total_free_data, factor);
2396         ret = btrfs_calc_avail_data_space(fs_info, &total_free_data);
2397         if (ret)
2398                 return ret;
2399         buf->f_bavail += div_u64(total_free_data, factor);
2400         buf->f_bavail = buf->f_bavail >> bits;
2401
2402         /*
2403          * We calculate the remaining metadata space minus global reserve. If
2404          * this is (supposedly) smaller than zero, there's no space. But this
2405          * does not hold in practice, the exhausted state happens where's still
2406          * some positive delta. So we apply some guesswork and compare the
2407          * delta to a 4M threshold.  (Practically observed delta was ~2M.)
2408          *
2409          * We probably cannot calculate the exact threshold value because this
2410          * depends on the internal reservations requested by various
2411          * operations, so some operations that consume a few metadata will
2412          * succeed even if the Avail is zero. But this is better than the other
2413          * way around.
2414          */
2415         thresh = SZ_4M;
2416
2417         /*
2418          * We only want to claim there's no available space if we can no longer
2419          * allocate chunks for our metadata profile and our global reserve will
2420          * not fit in the free metadata space.  If we aren't ->full then we
2421          * still can allocate chunks and thus are fine using the currently
2422          * calculated f_bavail.
2423          */
2424         if (!mixed && block_rsv->space_info->full &&
2425             (total_free_meta < thresh || total_free_meta - thresh < block_rsv->size))
2426                 buf->f_bavail = 0;
2427
2428         buf->f_type = BTRFS_SUPER_MAGIC;
2429         buf->f_bsize = dentry->d_sb->s_blocksize;
2430         buf->f_namelen = BTRFS_NAME_LEN;
2431
2432         /* We treat it as constant endianness (it doesn't matter _which_)
2433            because we want the fsid to come out the same whether mounted
2434            on a big-endian or little-endian host */
2435         buf->f_fsid.val[0] = be32_to_cpu(fsid[0]) ^ be32_to_cpu(fsid[2]);
2436         buf->f_fsid.val[1] = be32_to_cpu(fsid[1]) ^ be32_to_cpu(fsid[3]);
2437         /* Mask in the root object ID too, to disambiguate subvols */
2438         buf->f_fsid.val[0] ^=
2439                 BTRFS_I(d_inode(dentry))->root->root_key.objectid >> 32;
2440         buf->f_fsid.val[1] ^=
2441                 BTRFS_I(d_inode(dentry))->root->root_key.objectid;
2442
2443         return 0;
2444 }
2445
2446 static void btrfs_kill_super(struct super_block *sb)
2447 {
2448         struct btrfs_fs_info *fs_info = btrfs_sb(sb);
2449         kill_anon_super(sb);
2450         btrfs_free_fs_info(fs_info);
2451 }
2452
2453 static struct file_system_type btrfs_fs_type = {
2454         .owner          = THIS_MODULE,
2455         .name           = "btrfs",
2456         .mount          = btrfs_mount,
2457         .kill_sb        = btrfs_kill_super,
2458         .fs_flags       = FS_REQUIRES_DEV | FS_BINARY_MOUNTDATA,
2459 };
2460
2461 static struct file_system_type btrfs_root_fs_type = {
2462         .owner          = THIS_MODULE,
2463         .name           = "btrfs",
2464         .mount          = btrfs_mount_root,
2465         .kill_sb        = btrfs_kill_super,
2466         .fs_flags       = FS_REQUIRES_DEV | FS_BINARY_MOUNTDATA | FS_ALLOW_IDMAP,
2467 };
2468
2469 MODULE_ALIAS_FS("btrfs");
2470
2471 static int btrfs_control_open(struct inode *inode, struct file *file)
2472 {
2473         /*
2474          * The control file's private_data is used to hold the
2475          * transaction when it is started and is used to keep
2476          * track of whether a transaction is already in progress.
2477          */
2478         file->private_data = NULL;
2479         return 0;
2480 }
2481
2482 /*
2483  * Used by /dev/btrfs-control for devices ioctls.
2484  */
2485 static long btrfs_control_ioctl(struct file *file, unsigned int cmd,
2486                                 unsigned long arg)
2487 {
2488         struct btrfs_ioctl_vol_args *vol;
2489         struct btrfs_device *device = NULL;
2490         dev_t devt = 0;
2491         int ret = -ENOTTY;
2492
2493         if (!capable(CAP_SYS_ADMIN))
2494                 return -EPERM;
2495
2496         vol = memdup_user((void __user *)arg, sizeof(*vol));
2497         if (IS_ERR(vol))
2498                 return PTR_ERR(vol);
2499         vol->name[BTRFS_PATH_NAME_MAX] = '\0';
2500
2501         switch (cmd) {
2502         case BTRFS_IOC_SCAN_DEV:
2503                 mutex_lock(&uuid_mutex);
2504                 device = btrfs_scan_one_device(vol->name, FMODE_READ,
2505                                                &btrfs_root_fs_type);
2506                 ret = PTR_ERR_OR_ZERO(device);
2507                 mutex_unlock(&uuid_mutex);
2508                 break;
2509         case BTRFS_IOC_FORGET_DEV:
2510                 if (vol->name[0] != 0) {
2511                         ret = lookup_bdev(vol->name, &devt);
2512                         if (ret)
2513                                 break;
2514                 }
2515                 ret = btrfs_forget_devices(devt);
2516                 break;
2517         case BTRFS_IOC_DEVICES_READY:
2518                 mutex_lock(&uuid_mutex);
2519                 device = btrfs_scan_one_device(vol->name, FMODE_READ,
2520                                                &btrfs_root_fs_type);
2521                 if (IS_ERR(device)) {
2522                         mutex_unlock(&uuid_mutex);
2523                         ret = PTR_ERR(device);
2524                         break;
2525                 }
2526                 ret = !(device->fs_devices->num_devices ==
2527                         device->fs_devices->total_devices);
2528                 mutex_unlock(&uuid_mutex);
2529                 break;
2530         case BTRFS_IOC_GET_SUPPORTED_FEATURES:
2531                 ret = btrfs_ioctl_get_supported_features((void __user*)arg);
2532                 break;
2533         }
2534
2535         kfree(vol);
2536         return ret;
2537 }
2538
2539 static int btrfs_freeze(struct super_block *sb)
2540 {
2541         struct btrfs_trans_handle *trans;
2542         struct btrfs_fs_info *fs_info = btrfs_sb(sb);
2543         struct btrfs_root *root = fs_info->tree_root;
2544
2545         set_bit(BTRFS_FS_FROZEN, &fs_info->flags);
2546         /*
2547          * We don't need a barrier here, we'll wait for any transaction that
2548          * could be in progress on other threads (and do delayed iputs that
2549          * we want to avoid on a frozen filesystem), or do the commit
2550          * ourselves.
2551          */
2552         trans = btrfs_attach_transaction_barrier(root);
2553         if (IS_ERR(trans)) {
2554                 /* no transaction, don't bother */
2555                 if (PTR_ERR(trans) == -ENOENT)
2556                         return 0;
2557                 return PTR_ERR(trans);
2558         }
2559         return btrfs_commit_transaction(trans);
2560 }
2561
2562 static int check_dev_super(struct btrfs_device *dev)
2563 {
2564         struct btrfs_fs_info *fs_info = dev->fs_info;
2565         struct btrfs_super_block *sb;
2566         u16 csum_type;
2567         int ret = 0;
2568
2569         /* This should be called with fs still frozen. */
2570         ASSERT(test_bit(BTRFS_FS_FROZEN, &fs_info->flags));
2571
2572         /* Missing dev, no need to check. */
2573         if (!dev->bdev)
2574                 return 0;
2575
2576         /* Only need to check the primary super block. */
2577         sb = btrfs_read_dev_one_super(dev->bdev, 0, true);
2578         if (IS_ERR(sb))
2579                 return PTR_ERR(sb);
2580
2581         /* Verify the checksum. */
2582         csum_type = btrfs_super_csum_type(sb);
2583         if (csum_type != btrfs_super_csum_type(fs_info->super_copy)) {
2584                 btrfs_err(fs_info, "csum type changed, has %u expect %u",
2585                           csum_type, btrfs_super_csum_type(fs_info->super_copy));
2586                 ret = -EUCLEAN;
2587                 goto out;
2588         }
2589
2590         if (btrfs_check_super_csum(fs_info, sb)) {
2591                 btrfs_err(fs_info, "csum for on-disk super block no longer matches");
2592                 ret = -EUCLEAN;
2593                 goto out;
2594         }
2595
2596         /* Btrfs_validate_super() includes fsid check against super->fsid. */
2597         ret = btrfs_validate_super(fs_info, sb, 0);
2598         if (ret < 0)
2599                 goto out;
2600
2601         if (btrfs_super_generation(sb) != fs_info->last_trans_committed) {
2602                 btrfs_err(fs_info, "transid mismatch, has %llu expect %llu",
2603                         btrfs_super_generation(sb),
2604                         fs_info->last_trans_committed);
2605                 ret = -EUCLEAN;
2606                 goto out;
2607         }
2608 out:
2609         btrfs_release_disk_super(sb);
2610         return ret;
2611 }
2612
2613 static int btrfs_unfreeze(struct super_block *sb)
2614 {
2615         struct btrfs_fs_info *fs_info = btrfs_sb(sb);
2616         struct btrfs_device *device;
2617         int ret = 0;
2618
2619         /*
2620          * Make sure the fs is not changed by accident (like hibernation then
2621          * modified by other OS).
2622          * If we found anything wrong, we mark the fs error immediately.
2623          *
2624          * And since the fs is frozen, no one can modify the fs yet, thus
2625          * we don't need to hold device_list_mutex.
2626          */
2627         list_for_each_entry(device, &fs_info->fs_devices->devices, dev_list) {
2628                 ret = check_dev_super(device);
2629                 if (ret < 0) {
2630                         btrfs_handle_fs_error(fs_info, ret,
2631                                 "super block on devid %llu got modified unexpectedly",
2632                                 device->devid);
2633                         break;
2634                 }
2635         }
2636         clear_bit(BTRFS_FS_FROZEN, &fs_info->flags);
2637
2638         /*
2639          * We still return 0, to allow VFS layer to unfreeze the fs even the
2640          * above checks failed. Since the fs is either fine or read-only, we're
2641          * safe to continue, without causing further damage.
2642          */
2643         return 0;
2644 }
2645
2646 static int btrfs_show_devname(struct seq_file *m, struct dentry *root)
2647 {
2648         struct btrfs_fs_info *fs_info = btrfs_sb(root->d_sb);
2649
2650         /*
2651          * There should be always a valid pointer in latest_dev, it may be stale
2652          * for a short moment in case it's being deleted but still valid until
2653          * the end of RCU grace period.
2654          */
2655         rcu_read_lock();
2656         seq_escape(m, rcu_str_deref(fs_info->fs_devices->latest_dev->name), " \t\n\\");
2657         rcu_read_unlock();
2658
2659         return 0;
2660 }
2661
2662 static const struct super_operations btrfs_super_ops = {
2663         .drop_inode     = btrfs_drop_inode,
2664         .evict_inode    = btrfs_evict_inode,
2665         .put_super      = btrfs_put_super,
2666         .sync_fs        = btrfs_sync_fs,
2667         .show_options   = btrfs_show_options,
2668         .show_devname   = btrfs_show_devname,
2669         .alloc_inode    = btrfs_alloc_inode,
2670         .destroy_inode  = btrfs_destroy_inode,
2671         .free_inode     = btrfs_free_inode,
2672         .statfs         = btrfs_statfs,
2673         .remount_fs     = btrfs_remount,
2674         .freeze_fs      = btrfs_freeze,
2675         .unfreeze_fs    = btrfs_unfreeze,
2676 };
2677
2678 static const struct file_operations btrfs_ctl_fops = {
2679         .open = btrfs_control_open,
2680         .unlocked_ioctl  = btrfs_control_ioctl,
2681         .compat_ioctl = compat_ptr_ioctl,
2682         .owner   = THIS_MODULE,
2683         .llseek = noop_llseek,
2684 };
2685
2686 static struct miscdevice btrfs_misc = {
2687         .minor          = BTRFS_MINOR,
2688         .name           = "btrfs-control",
2689         .fops           = &btrfs_ctl_fops
2690 };
2691
2692 MODULE_ALIAS_MISCDEV(BTRFS_MINOR);
2693 MODULE_ALIAS("devname:btrfs-control");
2694
2695 static int __init btrfs_interface_init(void)
2696 {
2697         return misc_register(&btrfs_misc);
2698 }
2699
2700 static __cold void btrfs_interface_exit(void)
2701 {
2702         misc_deregister(&btrfs_misc);
2703 }
2704
2705 static void __init btrfs_print_mod_info(void)
2706 {
2707         static const char options[] = ""
2708 #ifdef CONFIG_BTRFS_DEBUG
2709                         ", debug=on"
2710 #endif
2711 #ifdef CONFIG_BTRFS_ASSERT
2712                         ", assert=on"
2713 #endif
2714 #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
2715                         ", integrity-checker=on"
2716 #endif
2717 #ifdef CONFIG_BTRFS_FS_REF_VERIFY
2718                         ", ref-verify=on"
2719 #endif
2720 #ifdef CONFIG_BLK_DEV_ZONED
2721                         ", zoned=yes"
2722 #else
2723                         ", zoned=no"
2724 #endif
2725 #ifdef CONFIG_FS_VERITY
2726                         ", fsverity=yes"
2727 #else
2728                         ", fsverity=no"
2729 #endif
2730                         ;
2731         pr_info("Btrfs loaded, crc32c=%s%s\n", crc32c_impl(), options);
2732 }
2733
2734 static int __init init_btrfs_fs(void)
2735 {
2736         int err;
2737
2738         btrfs_props_init();
2739
2740         err = btrfs_init_sysfs();
2741         if (err)
2742                 return err;
2743
2744         btrfs_init_compress();
2745
2746         err = btrfs_init_cachep();
2747         if (err)
2748                 goto free_compress;
2749
2750         err = extent_state_init_cachep();
2751         if (err)
2752                 goto free_cachep;
2753
2754         err = extent_buffer_init_cachep();
2755         if (err)
2756                 goto free_extent_cachep;
2757
2758         err = btrfs_bioset_init();
2759         if (err)
2760                 goto free_eb_cachep;
2761
2762         err = extent_map_init();
2763         if (err)
2764                 goto free_bioset;
2765
2766         err = ordered_data_init();
2767         if (err)
2768                 goto free_extent_map;
2769
2770         err = btrfs_delayed_inode_init();
2771         if (err)
2772                 goto free_ordered_data;
2773
2774         err = btrfs_auto_defrag_init();
2775         if (err)
2776                 goto free_delayed_inode;
2777
2778         err = btrfs_delayed_ref_init();
2779         if (err)
2780                 goto free_auto_defrag;
2781
2782         err = btrfs_prelim_ref_init();
2783         if (err)
2784                 goto free_delayed_ref;
2785
2786         err = btrfs_interface_init();
2787         if (err)
2788                 goto free_prelim_ref;
2789
2790         btrfs_print_mod_info();
2791
2792         err = btrfs_run_sanity_tests();
2793         if (err)
2794                 goto unregister_ioctl;
2795
2796         err = register_filesystem(&btrfs_fs_type);
2797         if (err)
2798                 goto unregister_ioctl;
2799
2800         return 0;
2801
2802 unregister_ioctl:
2803         btrfs_interface_exit();
2804 free_prelim_ref:
2805         btrfs_prelim_ref_exit();
2806 free_delayed_ref:
2807         btrfs_delayed_ref_exit();
2808 free_auto_defrag:
2809         btrfs_auto_defrag_exit();
2810 free_delayed_inode:
2811         btrfs_delayed_inode_exit();
2812 free_ordered_data:
2813         ordered_data_exit();
2814 free_extent_map:
2815         extent_map_exit();
2816 free_bioset:
2817         btrfs_bioset_exit();
2818 free_eb_cachep:
2819         extent_buffer_free_cachep();
2820 free_extent_cachep:
2821         extent_state_free_cachep();
2822 free_cachep:
2823         btrfs_destroy_cachep();
2824 free_compress:
2825         btrfs_exit_compress();
2826         btrfs_exit_sysfs();
2827
2828         return err;
2829 }
2830
2831 static void __exit exit_btrfs_fs(void)
2832 {
2833         btrfs_destroy_cachep();
2834         btrfs_delayed_ref_exit();
2835         btrfs_auto_defrag_exit();
2836         btrfs_delayed_inode_exit();
2837         btrfs_prelim_ref_exit();
2838         ordered_data_exit();
2839         extent_map_exit();
2840         btrfs_bioset_exit();
2841         extent_state_free_cachep();
2842         extent_buffer_free_cachep();
2843         btrfs_interface_exit();
2844         unregister_filesystem(&btrfs_fs_type);
2845         btrfs_exit_sysfs();
2846         btrfs_cleanup_fs_uuids();
2847         btrfs_exit_compress();
2848 }
2849
2850 late_initcall(init_btrfs_fs);
2851 module_exit(exit_btrfs_fs)
2852
2853 MODULE_LICENSE("GPL");
2854 MODULE_SOFTDEP("pre: crc32c");
2855 MODULE_SOFTDEP("pre: xxhash64");
2856 MODULE_SOFTDEP("pre: sha256");
2857 MODULE_SOFTDEP("pre: blake2b-256");