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