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