btrfs: make writepage_delalloc take btrfs_inode
[sfrench/cifs-2.6.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_warn(info,
825         "the 'inode_cache' option is deprecated and will have no effect from 5.11");
826                         btrfs_set_pending_and_info(info, INODE_MAP_CACHE,
827                                            "enabling inode map caching");
828                         break;
829                 case Opt_noinode_cache:
830                         btrfs_clear_pending_and_info(info, INODE_MAP_CACHE,
831                                              "disabling inode map caching");
832                         break;
833                 case Opt_clear_cache:
834                         btrfs_set_and_info(info, CLEAR_CACHE,
835                                            "force clearing of disk cache");
836                         break;
837                 case Opt_user_subvol_rm_allowed:
838                         btrfs_set_opt(info->mount_opt, USER_SUBVOL_RM_ALLOWED);
839                         break;
840                 case Opt_enospc_debug:
841                         btrfs_set_opt(info->mount_opt, ENOSPC_DEBUG);
842                         break;
843                 case Opt_noenospc_debug:
844                         btrfs_clear_opt(info->mount_opt, ENOSPC_DEBUG);
845                         break;
846                 case Opt_defrag:
847                         btrfs_set_and_info(info, AUTO_DEFRAG,
848                                            "enabling auto defrag");
849                         break;
850                 case Opt_nodefrag:
851                         btrfs_clear_and_info(info, AUTO_DEFRAG,
852                                              "disabling auto defrag");
853                         break;
854                 case Opt_recovery:
855                 case Opt_usebackuproot:
856                         btrfs_warn(info,
857                         "'%s' is deprecated, use 'rescue=usebackuproot' instead",
858                                    token == Opt_recovery ? "recovery" :
859                                    "usebackuproot");
860                         btrfs_info(info,
861                                    "trying to use backup root at mount time");
862                         btrfs_set_opt(info->mount_opt, USEBACKUPROOT);
863                         break;
864                 case Opt_skip_balance:
865                         btrfs_set_opt(info->mount_opt, SKIP_BALANCE);
866                         break;
867 #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
868                 case Opt_check_integrity_including_extent_data:
869                         btrfs_info(info,
870                                    "enabling check integrity including extent data");
871                         btrfs_set_opt(info->mount_opt,
872                                       CHECK_INTEGRITY_INCLUDING_EXTENT_DATA);
873                         btrfs_set_opt(info->mount_opt, CHECK_INTEGRITY);
874                         break;
875                 case Opt_check_integrity:
876                         btrfs_info(info, "enabling check integrity");
877                         btrfs_set_opt(info->mount_opt, CHECK_INTEGRITY);
878                         break;
879                 case Opt_check_integrity_print_mask:
880                         ret = match_int(&args[0], &intarg);
881                         if (ret)
882                                 goto out;
883                         info->check_integrity_print_mask = intarg;
884                         btrfs_info(info, "check_integrity_print_mask 0x%x",
885                                    info->check_integrity_print_mask);
886                         break;
887 #else
888                 case Opt_check_integrity_including_extent_data:
889                 case Opt_check_integrity:
890                 case Opt_check_integrity_print_mask:
891                         btrfs_err(info,
892                                   "support for check_integrity* not compiled in!");
893                         ret = -EINVAL;
894                         goto out;
895 #endif
896                 case Opt_fatal_errors:
897                         if (strcmp(args[0].from, "panic") == 0)
898                                 btrfs_set_opt(info->mount_opt,
899                                               PANIC_ON_FATAL_ERROR);
900                         else if (strcmp(args[0].from, "bug") == 0)
901                                 btrfs_clear_opt(info->mount_opt,
902                                               PANIC_ON_FATAL_ERROR);
903                         else {
904                                 ret = -EINVAL;
905                                 goto out;
906                         }
907                         break;
908                 case Opt_commit_interval:
909                         intarg = 0;
910                         ret = match_int(&args[0], &intarg);
911                         if (ret)
912                                 goto out;
913                         if (intarg == 0) {
914                                 btrfs_info(info,
915                                            "using default commit interval %us",
916                                            BTRFS_DEFAULT_COMMIT_INTERVAL);
917                                 intarg = BTRFS_DEFAULT_COMMIT_INTERVAL;
918                         } else if (intarg > 300) {
919                                 btrfs_warn(info, "excessive commit interval %d",
920                                            intarg);
921                         }
922                         info->commit_interval = intarg;
923                         break;
924                 case Opt_rescue:
925                         ret = parse_rescue_options(info, args[0].from);
926                         if (ret < 0)
927                                 goto out;
928                         break;
929 #ifdef CONFIG_BTRFS_DEBUG
930                 case Opt_fragment_all:
931                         btrfs_info(info, "fragmenting all space");
932                         btrfs_set_opt(info->mount_opt, FRAGMENT_DATA);
933                         btrfs_set_opt(info->mount_opt, FRAGMENT_METADATA);
934                         break;
935                 case Opt_fragment_metadata:
936                         btrfs_info(info, "fragmenting metadata");
937                         btrfs_set_opt(info->mount_opt,
938                                       FRAGMENT_METADATA);
939                         break;
940                 case Opt_fragment_data:
941                         btrfs_info(info, "fragmenting data");
942                         btrfs_set_opt(info->mount_opt, FRAGMENT_DATA);
943                         break;
944 #endif
945 #ifdef CONFIG_BTRFS_FS_REF_VERIFY
946                 case Opt_ref_verify:
947                         btrfs_info(info, "doing ref verification");
948                         btrfs_set_opt(info->mount_opt, REF_VERIFY);
949                         break;
950 #endif
951                 case Opt_err:
952                         btrfs_err(info, "unrecognized mount option '%s'", p);
953                         ret = -EINVAL;
954                         goto out;
955                 default:
956                         break;
957                 }
958         }
959 check:
960         /*
961          * Extra check for current option against current flag
962          */
963         if (btrfs_test_opt(info, NOLOGREPLAY) && !(new_flags & SB_RDONLY)) {
964                 btrfs_err(info,
965                           "nologreplay must be used with ro mount option");
966                 ret = -EINVAL;
967         }
968 out:
969         if (btrfs_fs_compat_ro(info, FREE_SPACE_TREE) &&
970             !btrfs_test_opt(info, FREE_SPACE_TREE) &&
971             !btrfs_test_opt(info, CLEAR_CACHE)) {
972                 btrfs_err(info, "cannot disable free space tree");
973                 ret = -EINVAL;
974
975         }
976         if (!ret && btrfs_test_opt(info, SPACE_CACHE))
977                 btrfs_info(info, "disk space caching is enabled");
978         if (!ret && btrfs_test_opt(info, FREE_SPACE_TREE))
979                 btrfs_info(info, "using free space tree");
980         return ret;
981 }
982
983 /*
984  * Parse mount options that are required early in the mount process.
985  *
986  * All other options will be parsed on much later in the mount process and
987  * only when we need to allocate a new super block.
988  */
989 static int btrfs_parse_device_options(const char *options, fmode_t flags,
990                                       void *holder)
991 {
992         substring_t args[MAX_OPT_ARGS];
993         char *device_name, *opts, *orig, *p;
994         struct btrfs_device *device = NULL;
995         int error = 0;
996
997         lockdep_assert_held(&uuid_mutex);
998
999         if (!options)
1000                 return 0;
1001
1002         /*
1003          * strsep changes the string, duplicate it because btrfs_parse_options
1004          * gets called later
1005          */
1006         opts = kstrdup(options, GFP_KERNEL);
1007         if (!opts)
1008                 return -ENOMEM;
1009         orig = opts;
1010
1011         while ((p = strsep(&opts, ",")) != NULL) {
1012                 int token;
1013
1014                 if (!*p)
1015                         continue;
1016
1017                 token = match_token(p, tokens, args);
1018                 if (token == Opt_device) {
1019                         device_name = match_strdup(&args[0]);
1020                         if (!device_name) {
1021                                 error = -ENOMEM;
1022                                 goto out;
1023                         }
1024                         device = btrfs_scan_one_device(device_name, flags,
1025                                         holder);
1026                         kfree(device_name);
1027                         if (IS_ERR(device)) {
1028                                 error = PTR_ERR(device);
1029                                 goto out;
1030                         }
1031                 }
1032         }
1033
1034 out:
1035         kfree(orig);
1036         return error;
1037 }
1038
1039 /*
1040  * Parse mount options that are related to subvolume id
1041  *
1042  * The value is later passed to mount_subvol()
1043  */
1044 static int btrfs_parse_subvol_options(const char *options, char **subvol_name,
1045                 u64 *subvol_objectid)
1046 {
1047         substring_t args[MAX_OPT_ARGS];
1048         char *opts, *orig, *p;
1049         int error = 0;
1050         u64 subvolid;
1051
1052         if (!options)
1053                 return 0;
1054
1055         /*
1056          * strsep changes the string, duplicate it because
1057          * btrfs_parse_device_options gets called later
1058          */
1059         opts = kstrdup(options, GFP_KERNEL);
1060         if (!opts)
1061                 return -ENOMEM;
1062         orig = opts;
1063
1064         while ((p = strsep(&opts, ",")) != NULL) {
1065                 int token;
1066                 if (!*p)
1067                         continue;
1068
1069                 token = match_token(p, tokens, args);
1070                 switch (token) {
1071                 case Opt_subvol:
1072                         kfree(*subvol_name);
1073                         *subvol_name = match_strdup(&args[0]);
1074                         if (!*subvol_name) {
1075                                 error = -ENOMEM;
1076                                 goto out;
1077                         }
1078                         break;
1079                 case Opt_subvolid:
1080                         error = match_u64(&args[0], &subvolid);
1081                         if (error)
1082                                 goto out;
1083
1084                         /* we want the original fs_tree */
1085                         if (subvolid == 0)
1086                                 subvolid = BTRFS_FS_TREE_OBJECTID;
1087
1088                         *subvol_objectid = subvolid;
1089                         break;
1090                 case Opt_subvolrootid:
1091                         pr_warn("BTRFS: 'subvolrootid' mount option is deprecated and has no effect\n");
1092                         break;
1093                 default:
1094                         break;
1095                 }
1096         }
1097
1098 out:
1099         kfree(orig);
1100         return error;
1101 }
1102
1103 char *btrfs_get_subvol_name_from_objectid(struct btrfs_fs_info *fs_info,
1104                                           u64 subvol_objectid)
1105 {
1106         struct btrfs_root *root = fs_info->tree_root;
1107         struct btrfs_root *fs_root = NULL;
1108         struct btrfs_root_ref *root_ref;
1109         struct btrfs_inode_ref *inode_ref;
1110         struct btrfs_key key;
1111         struct btrfs_path *path = NULL;
1112         char *name = NULL, *ptr;
1113         u64 dirid;
1114         int len;
1115         int ret;
1116
1117         path = btrfs_alloc_path();
1118         if (!path) {
1119                 ret = -ENOMEM;
1120                 goto err;
1121         }
1122         path->leave_spinning = 1;
1123
1124         name = kmalloc(PATH_MAX, GFP_KERNEL);
1125         if (!name) {
1126                 ret = -ENOMEM;
1127                 goto err;
1128         }
1129         ptr = name + PATH_MAX - 1;
1130         ptr[0] = '\0';
1131
1132         /*
1133          * Walk up the subvolume trees in the tree of tree roots by root
1134          * backrefs until we hit the top-level subvolume.
1135          */
1136         while (subvol_objectid != BTRFS_FS_TREE_OBJECTID) {
1137                 key.objectid = subvol_objectid;
1138                 key.type = BTRFS_ROOT_BACKREF_KEY;
1139                 key.offset = (u64)-1;
1140
1141                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1142                 if (ret < 0) {
1143                         goto err;
1144                 } else if (ret > 0) {
1145                         ret = btrfs_previous_item(root, path, subvol_objectid,
1146                                                   BTRFS_ROOT_BACKREF_KEY);
1147                         if (ret < 0) {
1148                                 goto err;
1149                         } else if (ret > 0) {
1150                                 ret = -ENOENT;
1151                                 goto err;
1152                         }
1153                 }
1154
1155                 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1156                 subvol_objectid = key.offset;
1157
1158                 root_ref = btrfs_item_ptr(path->nodes[0], path->slots[0],
1159                                           struct btrfs_root_ref);
1160                 len = btrfs_root_ref_name_len(path->nodes[0], root_ref);
1161                 ptr -= len + 1;
1162                 if (ptr < name) {
1163                         ret = -ENAMETOOLONG;
1164                         goto err;
1165                 }
1166                 read_extent_buffer(path->nodes[0], ptr + 1,
1167                                    (unsigned long)(root_ref + 1), len);
1168                 ptr[0] = '/';
1169                 dirid = btrfs_root_ref_dirid(path->nodes[0], root_ref);
1170                 btrfs_release_path(path);
1171
1172                 fs_root = btrfs_get_fs_root(fs_info, subvol_objectid, true);
1173                 if (IS_ERR(fs_root)) {
1174                         ret = PTR_ERR(fs_root);
1175                         fs_root = NULL;
1176                         goto err;
1177                 }
1178
1179                 /*
1180                  * Walk up the filesystem tree by inode refs until we hit the
1181                  * root directory.
1182                  */
1183                 while (dirid != BTRFS_FIRST_FREE_OBJECTID) {
1184                         key.objectid = dirid;
1185                         key.type = BTRFS_INODE_REF_KEY;
1186                         key.offset = (u64)-1;
1187
1188                         ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
1189                         if (ret < 0) {
1190                                 goto err;
1191                         } else if (ret > 0) {
1192                                 ret = btrfs_previous_item(fs_root, path, dirid,
1193                                                           BTRFS_INODE_REF_KEY);
1194                                 if (ret < 0) {
1195                                         goto err;
1196                                 } else if (ret > 0) {
1197                                         ret = -ENOENT;
1198                                         goto err;
1199                                 }
1200                         }
1201
1202                         btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1203                         dirid = key.offset;
1204
1205                         inode_ref = btrfs_item_ptr(path->nodes[0],
1206                                                    path->slots[0],
1207                                                    struct btrfs_inode_ref);
1208                         len = btrfs_inode_ref_name_len(path->nodes[0],
1209                                                        inode_ref);
1210                         ptr -= len + 1;
1211                         if (ptr < name) {
1212                                 ret = -ENAMETOOLONG;
1213                                 goto err;
1214                         }
1215                         read_extent_buffer(path->nodes[0], ptr + 1,
1216                                            (unsigned long)(inode_ref + 1), len);
1217                         ptr[0] = '/';
1218                         btrfs_release_path(path);
1219                 }
1220                 btrfs_put_root(fs_root);
1221                 fs_root = NULL;
1222         }
1223
1224         btrfs_free_path(path);
1225         if (ptr == name + PATH_MAX - 1) {
1226                 name[0] = '/';
1227                 name[1] = '\0';
1228         } else {
1229                 memmove(name, ptr, name + PATH_MAX - ptr);
1230         }
1231         return name;
1232
1233 err:
1234         btrfs_put_root(fs_root);
1235         btrfs_free_path(path);
1236         kfree(name);
1237         return ERR_PTR(ret);
1238 }
1239
1240 static int get_default_subvol_objectid(struct btrfs_fs_info *fs_info, u64 *objectid)
1241 {
1242         struct btrfs_root *root = fs_info->tree_root;
1243         struct btrfs_dir_item *di;
1244         struct btrfs_path *path;
1245         struct btrfs_key location;
1246         u64 dir_id;
1247
1248         path = btrfs_alloc_path();
1249         if (!path)
1250                 return -ENOMEM;
1251         path->leave_spinning = 1;
1252
1253         /*
1254          * Find the "default" dir item which points to the root item that we
1255          * will mount by default if we haven't been given a specific subvolume
1256          * to mount.
1257          */
1258         dir_id = btrfs_super_root_dir(fs_info->super_copy);
1259         di = btrfs_lookup_dir_item(NULL, root, path, dir_id, "default", 7, 0);
1260         if (IS_ERR(di)) {
1261                 btrfs_free_path(path);
1262                 return PTR_ERR(di);
1263         }
1264         if (!di) {
1265                 /*
1266                  * Ok the default dir item isn't there.  This is weird since
1267                  * it's always been there, but don't freak out, just try and
1268                  * mount the top-level subvolume.
1269                  */
1270                 btrfs_free_path(path);
1271                 *objectid = BTRFS_FS_TREE_OBJECTID;
1272                 return 0;
1273         }
1274
1275         btrfs_dir_item_key_to_cpu(path->nodes[0], di, &location);
1276         btrfs_free_path(path);
1277         *objectid = location.objectid;
1278         return 0;
1279 }
1280
1281 static int btrfs_fill_super(struct super_block *sb,
1282                             struct btrfs_fs_devices *fs_devices,
1283                             void *data)
1284 {
1285         struct inode *inode;
1286         struct btrfs_fs_info *fs_info = btrfs_sb(sb);
1287         int err;
1288
1289         sb->s_maxbytes = MAX_LFS_FILESIZE;
1290         sb->s_magic = BTRFS_SUPER_MAGIC;
1291         sb->s_op = &btrfs_super_ops;
1292         sb->s_d_op = &btrfs_dentry_operations;
1293         sb->s_export_op = &btrfs_export_ops;
1294         sb->s_xattr = btrfs_xattr_handlers;
1295         sb->s_time_gran = 1;
1296 #ifdef CONFIG_BTRFS_FS_POSIX_ACL
1297         sb->s_flags |= SB_POSIXACL;
1298 #endif
1299         sb->s_flags |= SB_I_VERSION;
1300         sb->s_iflags |= SB_I_CGROUPWB;
1301
1302         err = super_setup_bdi(sb);
1303         if (err) {
1304                 btrfs_err(fs_info, "super_setup_bdi failed");
1305                 return err;
1306         }
1307
1308         err = open_ctree(sb, fs_devices, (char *)data);
1309         if (err) {
1310                 btrfs_err(fs_info, "open_ctree failed");
1311                 return err;
1312         }
1313
1314         inode = btrfs_iget(sb, BTRFS_FIRST_FREE_OBJECTID, fs_info->fs_root);
1315         if (IS_ERR(inode)) {
1316                 err = PTR_ERR(inode);
1317                 goto fail_close;
1318         }
1319
1320         sb->s_root = d_make_root(inode);
1321         if (!sb->s_root) {
1322                 err = -ENOMEM;
1323                 goto fail_close;
1324         }
1325
1326         cleancache_init_fs(sb);
1327         sb->s_flags |= SB_ACTIVE;
1328         return 0;
1329
1330 fail_close:
1331         close_ctree(fs_info);
1332         return err;
1333 }
1334
1335 int btrfs_sync_fs(struct super_block *sb, int wait)
1336 {
1337         struct btrfs_trans_handle *trans;
1338         struct btrfs_fs_info *fs_info = btrfs_sb(sb);
1339         struct btrfs_root *root = fs_info->tree_root;
1340
1341         trace_btrfs_sync_fs(fs_info, wait);
1342
1343         if (!wait) {
1344                 filemap_flush(fs_info->btree_inode->i_mapping);
1345                 return 0;
1346         }
1347
1348         btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
1349
1350         trans = btrfs_attach_transaction_barrier(root);
1351         if (IS_ERR(trans)) {
1352                 /* no transaction, don't bother */
1353                 if (PTR_ERR(trans) == -ENOENT) {
1354                         /*
1355                          * Exit unless we have some pending changes
1356                          * that need to go through commit
1357                          */
1358                         if (fs_info->pending_changes == 0)
1359                                 return 0;
1360                         /*
1361                          * A non-blocking test if the fs is frozen. We must not
1362                          * start a new transaction here otherwise a deadlock
1363                          * happens. The pending operations are delayed to the
1364                          * next commit after thawing.
1365                          */
1366                         if (sb_start_write_trylock(sb))
1367                                 sb_end_write(sb);
1368                         else
1369                                 return 0;
1370                         trans = btrfs_start_transaction(root, 0);
1371                 }
1372                 if (IS_ERR(trans))
1373                         return PTR_ERR(trans);
1374         }
1375         return btrfs_commit_transaction(trans);
1376 }
1377
1378 static int btrfs_show_options(struct seq_file *seq, struct dentry *dentry)
1379 {
1380         struct btrfs_fs_info *info = btrfs_sb(dentry->d_sb);
1381         const char *compress_type;
1382
1383         if (btrfs_test_opt(info, DEGRADED))
1384                 seq_puts(seq, ",degraded");
1385         if (btrfs_test_opt(info, NODATASUM))
1386                 seq_puts(seq, ",nodatasum");
1387         if (btrfs_test_opt(info, NODATACOW))
1388                 seq_puts(seq, ",nodatacow");
1389         if (btrfs_test_opt(info, NOBARRIER))
1390                 seq_puts(seq, ",nobarrier");
1391         if (info->max_inline != BTRFS_DEFAULT_MAX_INLINE)
1392                 seq_printf(seq, ",max_inline=%llu", info->max_inline);
1393         if (info->thread_pool_size !=  min_t(unsigned long,
1394                                              num_online_cpus() + 2, 8))
1395                 seq_printf(seq, ",thread_pool=%u", info->thread_pool_size);
1396         if (btrfs_test_opt(info, COMPRESS)) {
1397                 compress_type = btrfs_compress_type2str(info->compress_type);
1398                 if (btrfs_test_opt(info, FORCE_COMPRESS))
1399                         seq_printf(seq, ",compress-force=%s", compress_type);
1400                 else
1401                         seq_printf(seq, ",compress=%s", compress_type);
1402                 if (info->compress_level)
1403                         seq_printf(seq, ":%d", info->compress_level);
1404         }
1405         if (btrfs_test_opt(info, NOSSD))
1406                 seq_puts(seq, ",nossd");
1407         if (btrfs_test_opt(info, SSD_SPREAD))
1408                 seq_puts(seq, ",ssd_spread");
1409         else if (btrfs_test_opt(info, SSD))
1410                 seq_puts(seq, ",ssd");
1411         if (btrfs_test_opt(info, NOTREELOG))
1412                 seq_puts(seq, ",notreelog");
1413         if (btrfs_test_opt(info, NOLOGREPLAY))
1414                 seq_puts(seq, ",rescue=nologreplay");
1415         if (btrfs_test_opt(info, FLUSHONCOMMIT))
1416                 seq_puts(seq, ",flushoncommit");
1417         if (btrfs_test_opt(info, DISCARD_SYNC))
1418                 seq_puts(seq, ",discard");
1419         if (btrfs_test_opt(info, DISCARD_ASYNC))
1420                 seq_puts(seq, ",discard=async");
1421         if (!(info->sb->s_flags & SB_POSIXACL))
1422                 seq_puts(seq, ",noacl");
1423         if (btrfs_test_opt(info, SPACE_CACHE))
1424                 seq_puts(seq, ",space_cache");
1425         else if (btrfs_test_opt(info, FREE_SPACE_TREE))
1426                 seq_puts(seq, ",space_cache=v2");
1427         else
1428                 seq_puts(seq, ",nospace_cache");
1429         if (btrfs_test_opt(info, RESCAN_UUID_TREE))
1430                 seq_puts(seq, ",rescan_uuid_tree");
1431         if (btrfs_test_opt(info, CLEAR_CACHE))
1432                 seq_puts(seq, ",clear_cache");
1433         if (btrfs_test_opt(info, USER_SUBVOL_RM_ALLOWED))
1434                 seq_puts(seq, ",user_subvol_rm_allowed");
1435         if (btrfs_test_opt(info, ENOSPC_DEBUG))
1436                 seq_puts(seq, ",enospc_debug");
1437         if (btrfs_test_opt(info, AUTO_DEFRAG))
1438                 seq_puts(seq, ",autodefrag");
1439         if (btrfs_test_opt(info, INODE_MAP_CACHE))
1440                 seq_puts(seq, ",inode_cache");
1441         if (btrfs_test_opt(info, SKIP_BALANCE))
1442                 seq_puts(seq, ",skip_balance");
1443 #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
1444         if (btrfs_test_opt(info, CHECK_INTEGRITY_INCLUDING_EXTENT_DATA))
1445                 seq_puts(seq, ",check_int_data");
1446         else if (btrfs_test_opt(info, CHECK_INTEGRITY))
1447                 seq_puts(seq, ",check_int");
1448         if (info->check_integrity_print_mask)
1449                 seq_printf(seq, ",check_int_print_mask=%d",
1450                                 info->check_integrity_print_mask);
1451 #endif
1452         if (info->metadata_ratio)
1453                 seq_printf(seq, ",metadata_ratio=%u", info->metadata_ratio);
1454         if (btrfs_test_opt(info, PANIC_ON_FATAL_ERROR))
1455                 seq_puts(seq, ",fatal_errors=panic");
1456         if (info->commit_interval != BTRFS_DEFAULT_COMMIT_INTERVAL)
1457                 seq_printf(seq, ",commit=%u", info->commit_interval);
1458 #ifdef CONFIG_BTRFS_DEBUG
1459         if (btrfs_test_opt(info, FRAGMENT_DATA))
1460                 seq_puts(seq, ",fragment=data");
1461         if (btrfs_test_opt(info, FRAGMENT_METADATA))
1462                 seq_puts(seq, ",fragment=metadata");
1463 #endif
1464         if (btrfs_test_opt(info, REF_VERIFY))
1465                 seq_puts(seq, ",ref_verify");
1466         seq_printf(seq, ",subvolid=%llu",
1467                   BTRFS_I(d_inode(dentry))->root->root_key.objectid);
1468         seq_puts(seq, ",subvol=");
1469         seq_dentry(seq, dentry, " \t\n\\");
1470         return 0;
1471 }
1472
1473 static int btrfs_test_super(struct super_block *s, void *data)
1474 {
1475         struct btrfs_fs_info *p = data;
1476         struct btrfs_fs_info *fs_info = btrfs_sb(s);
1477
1478         return fs_info->fs_devices == p->fs_devices;
1479 }
1480
1481 static int btrfs_set_super(struct super_block *s, void *data)
1482 {
1483         int err = set_anon_super(s, data);
1484         if (!err)
1485                 s->s_fs_info = data;
1486         return err;
1487 }
1488
1489 /*
1490  * subvolumes are identified by ino 256
1491  */
1492 static inline int is_subvolume_inode(struct inode *inode)
1493 {
1494         if (inode && inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)
1495                 return 1;
1496         return 0;
1497 }
1498
1499 static struct dentry *mount_subvol(const char *subvol_name, u64 subvol_objectid,
1500                                    struct vfsmount *mnt)
1501 {
1502         struct dentry *root;
1503         int ret;
1504
1505         if (!subvol_name) {
1506                 if (!subvol_objectid) {
1507                         ret = get_default_subvol_objectid(btrfs_sb(mnt->mnt_sb),
1508                                                           &subvol_objectid);
1509                         if (ret) {
1510                                 root = ERR_PTR(ret);
1511                                 goto out;
1512                         }
1513                 }
1514                 subvol_name = btrfs_get_subvol_name_from_objectid(
1515                                         btrfs_sb(mnt->mnt_sb), subvol_objectid);
1516                 if (IS_ERR(subvol_name)) {
1517                         root = ERR_CAST(subvol_name);
1518                         subvol_name = NULL;
1519                         goto out;
1520                 }
1521
1522         }
1523
1524         root = mount_subtree(mnt, subvol_name);
1525         /* mount_subtree() drops our reference on the vfsmount. */
1526         mnt = NULL;
1527
1528         if (!IS_ERR(root)) {
1529                 struct super_block *s = root->d_sb;
1530                 struct btrfs_fs_info *fs_info = btrfs_sb(s);
1531                 struct inode *root_inode = d_inode(root);
1532                 u64 root_objectid = BTRFS_I(root_inode)->root->root_key.objectid;
1533
1534                 ret = 0;
1535                 if (!is_subvolume_inode(root_inode)) {
1536                         btrfs_err(fs_info, "'%s' is not a valid subvolume",
1537                                subvol_name);
1538                         ret = -EINVAL;
1539                 }
1540                 if (subvol_objectid && root_objectid != subvol_objectid) {
1541                         /*
1542                          * This will also catch a race condition where a
1543                          * subvolume which was passed by ID is renamed and
1544                          * another subvolume is renamed over the old location.
1545                          */
1546                         btrfs_err(fs_info,
1547                                   "subvol '%s' does not match subvolid %llu",
1548                                   subvol_name, subvol_objectid);
1549                         ret = -EINVAL;
1550                 }
1551                 if (ret) {
1552                         dput(root);
1553                         root = ERR_PTR(ret);
1554                         deactivate_locked_super(s);
1555                 }
1556         }
1557
1558 out:
1559         mntput(mnt);
1560         kfree(subvol_name);
1561         return root;
1562 }
1563
1564 /*
1565  * Find a superblock for the given device / mount point.
1566  *
1567  * Note: This is based on mount_bdev from fs/super.c with a few additions
1568  *       for multiple device setup.  Make sure to keep it in sync.
1569  */
1570 static struct dentry *btrfs_mount_root(struct file_system_type *fs_type,
1571                 int flags, const char *device_name, void *data)
1572 {
1573         struct block_device *bdev = NULL;
1574         struct super_block *s;
1575         struct btrfs_device *device = NULL;
1576         struct btrfs_fs_devices *fs_devices = NULL;
1577         struct btrfs_fs_info *fs_info = NULL;
1578         void *new_sec_opts = NULL;
1579         fmode_t mode = FMODE_READ;
1580         int error = 0;
1581
1582         if (!(flags & SB_RDONLY))
1583                 mode |= FMODE_WRITE;
1584
1585         if (data) {
1586                 error = security_sb_eat_lsm_opts(data, &new_sec_opts);
1587                 if (error)
1588                         return ERR_PTR(error);
1589         }
1590
1591         /*
1592          * Setup a dummy root and fs_info for test/set super.  This is because
1593          * we don't actually fill this stuff out until open_ctree, but we need
1594          * then open_ctree will properly initialize the file system specific
1595          * settings later.  btrfs_init_fs_info initializes the static elements
1596          * of the fs_info (locks and such) to make cleanup easier if we find a
1597          * superblock with our given fs_devices later on at sget() time.
1598          */
1599         fs_info = kvzalloc(sizeof(struct btrfs_fs_info), GFP_KERNEL);
1600         if (!fs_info) {
1601                 error = -ENOMEM;
1602                 goto error_sec_opts;
1603         }
1604         btrfs_init_fs_info(fs_info);
1605
1606         fs_info->super_copy = kzalloc(BTRFS_SUPER_INFO_SIZE, GFP_KERNEL);
1607         fs_info->super_for_commit = kzalloc(BTRFS_SUPER_INFO_SIZE, GFP_KERNEL);
1608         if (!fs_info->super_copy || !fs_info->super_for_commit) {
1609                 error = -ENOMEM;
1610                 goto error_fs_info;
1611         }
1612
1613         mutex_lock(&uuid_mutex);
1614         error = btrfs_parse_device_options(data, mode, fs_type);
1615         if (error) {
1616                 mutex_unlock(&uuid_mutex);
1617                 goto error_fs_info;
1618         }
1619
1620         device = btrfs_scan_one_device(device_name, mode, fs_type);
1621         if (IS_ERR(device)) {
1622                 mutex_unlock(&uuid_mutex);
1623                 error = PTR_ERR(device);
1624                 goto error_fs_info;
1625         }
1626
1627         fs_devices = device->fs_devices;
1628         fs_info->fs_devices = fs_devices;
1629
1630         error = btrfs_open_devices(fs_devices, mode, fs_type);
1631         mutex_unlock(&uuid_mutex);
1632         if (error)
1633                 goto error_fs_info;
1634
1635         if (!(flags & SB_RDONLY) && fs_devices->rw_devices == 0) {
1636                 error = -EACCES;
1637                 goto error_close_devices;
1638         }
1639
1640         bdev = fs_devices->latest_bdev;
1641         s = sget(fs_type, btrfs_test_super, btrfs_set_super, flags | SB_NOSEC,
1642                  fs_info);
1643         if (IS_ERR(s)) {
1644                 error = PTR_ERR(s);
1645                 goto error_close_devices;
1646         }
1647
1648         if (s->s_root) {
1649                 btrfs_close_devices(fs_devices);
1650                 btrfs_free_fs_info(fs_info);
1651                 if ((flags ^ s->s_flags) & SB_RDONLY)
1652                         error = -EBUSY;
1653         } else {
1654                 snprintf(s->s_id, sizeof(s->s_id), "%pg", bdev);
1655                 btrfs_sb(s)->bdev_holder = fs_type;
1656                 if (!strstr(crc32c_impl(), "generic"))
1657                         set_bit(BTRFS_FS_CSUM_IMPL_FAST, &fs_info->flags);
1658                 error = btrfs_fill_super(s, fs_devices, data);
1659         }
1660         if (!error)
1661                 error = security_sb_set_mnt_opts(s, new_sec_opts, 0, NULL);
1662         security_free_mnt_opts(&new_sec_opts);
1663         if (error) {
1664                 deactivate_locked_super(s);
1665                 return ERR_PTR(error);
1666         }
1667
1668         return dget(s->s_root);
1669
1670 error_close_devices:
1671         btrfs_close_devices(fs_devices);
1672 error_fs_info:
1673         btrfs_free_fs_info(fs_info);
1674 error_sec_opts:
1675         security_free_mnt_opts(&new_sec_opts);
1676         return ERR_PTR(error);
1677 }
1678
1679 /*
1680  * Mount function which is called by VFS layer.
1681  *
1682  * In order to allow mounting a subvolume directly, btrfs uses mount_subtree()
1683  * which needs vfsmount* of device's root (/).  This means device's root has to
1684  * be mounted internally in any case.
1685  *
1686  * Operation flow:
1687  *   1. Parse subvol id related options for later use in mount_subvol().
1688  *
1689  *   2. Mount device's root (/) by calling vfs_kern_mount().
1690  *
1691  *      NOTE: vfs_kern_mount() is used by VFS to call btrfs_mount() in the
1692  *      first place. In order to avoid calling btrfs_mount() again, we use
1693  *      different file_system_type which is not registered to VFS by
1694  *      register_filesystem() (btrfs_root_fs_type). As a result,
1695  *      btrfs_mount_root() is called. The return value will be used by
1696  *      mount_subtree() in mount_subvol().
1697  *
1698  *   3. Call mount_subvol() to get the dentry of subvolume. Since there is
1699  *      "btrfs subvolume set-default", mount_subvol() is called always.
1700  */
1701 static struct dentry *btrfs_mount(struct file_system_type *fs_type, int flags,
1702                 const char *device_name, void *data)
1703 {
1704         struct vfsmount *mnt_root;
1705         struct dentry *root;
1706         char *subvol_name = NULL;
1707         u64 subvol_objectid = 0;
1708         int error = 0;
1709
1710         error = btrfs_parse_subvol_options(data, &subvol_name,
1711                                         &subvol_objectid);
1712         if (error) {
1713                 kfree(subvol_name);
1714                 return ERR_PTR(error);
1715         }
1716
1717         /* mount device's root (/) */
1718         mnt_root = vfs_kern_mount(&btrfs_root_fs_type, flags, device_name, data);
1719         if (PTR_ERR_OR_ZERO(mnt_root) == -EBUSY) {
1720                 if (flags & SB_RDONLY) {
1721                         mnt_root = vfs_kern_mount(&btrfs_root_fs_type,
1722                                 flags & ~SB_RDONLY, device_name, data);
1723                 } else {
1724                         mnt_root = vfs_kern_mount(&btrfs_root_fs_type,
1725                                 flags | SB_RDONLY, device_name, data);
1726                         if (IS_ERR(mnt_root)) {
1727                                 root = ERR_CAST(mnt_root);
1728                                 kfree(subvol_name);
1729                                 goto out;
1730                         }
1731
1732                         down_write(&mnt_root->mnt_sb->s_umount);
1733                         error = btrfs_remount(mnt_root->mnt_sb, &flags, NULL);
1734                         up_write(&mnt_root->mnt_sb->s_umount);
1735                         if (error < 0) {
1736                                 root = ERR_PTR(error);
1737                                 mntput(mnt_root);
1738                                 kfree(subvol_name);
1739                                 goto out;
1740                         }
1741                 }
1742         }
1743         if (IS_ERR(mnt_root)) {
1744                 root = ERR_CAST(mnt_root);
1745                 kfree(subvol_name);
1746                 goto out;
1747         }
1748
1749         /* mount_subvol() will free subvol_name and mnt_root */
1750         root = mount_subvol(subvol_name, subvol_objectid, mnt_root);
1751
1752 out:
1753         return root;
1754 }
1755
1756 static void btrfs_resize_thread_pool(struct btrfs_fs_info *fs_info,
1757                                      u32 new_pool_size, u32 old_pool_size)
1758 {
1759         if (new_pool_size == old_pool_size)
1760                 return;
1761
1762         fs_info->thread_pool_size = new_pool_size;
1763
1764         btrfs_info(fs_info, "resize thread pool %d -> %d",
1765                old_pool_size, new_pool_size);
1766
1767         btrfs_workqueue_set_max(fs_info->workers, new_pool_size);
1768         btrfs_workqueue_set_max(fs_info->delalloc_workers, new_pool_size);
1769         btrfs_workqueue_set_max(fs_info->caching_workers, new_pool_size);
1770         btrfs_workqueue_set_max(fs_info->endio_workers, new_pool_size);
1771         btrfs_workqueue_set_max(fs_info->endio_meta_workers, new_pool_size);
1772         btrfs_workqueue_set_max(fs_info->endio_meta_write_workers,
1773                                 new_pool_size);
1774         btrfs_workqueue_set_max(fs_info->endio_write_workers, new_pool_size);
1775         btrfs_workqueue_set_max(fs_info->endio_freespace_worker, new_pool_size);
1776         btrfs_workqueue_set_max(fs_info->delayed_workers, new_pool_size);
1777         btrfs_workqueue_set_max(fs_info->readahead_workers, new_pool_size);
1778         btrfs_workqueue_set_max(fs_info->scrub_wr_completion_workers,
1779                                 new_pool_size);
1780 }
1781
1782 static inline void btrfs_remount_prepare(struct btrfs_fs_info *fs_info)
1783 {
1784         set_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state);
1785 }
1786
1787 static inline void btrfs_remount_begin(struct btrfs_fs_info *fs_info,
1788                                        unsigned long old_opts, int flags)
1789 {
1790         if (btrfs_raw_test_opt(old_opts, AUTO_DEFRAG) &&
1791             (!btrfs_raw_test_opt(fs_info->mount_opt, AUTO_DEFRAG) ||
1792              (flags & SB_RDONLY))) {
1793                 /* wait for any defraggers to finish */
1794                 wait_event(fs_info->transaction_wait,
1795                            (atomic_read(&fs_info->defrag_running) == 0));
1796                 if (flags & SB_RDONLY)
1797                         sync_filesystem(fs_info->sb);
1798         }
1799 }
1800
1801 static inline void btrfs_remount_cleanup(struct btrfs_fs_info *fs_info,
1802                                          unsigned long old_opts)
1803 {
1804         /*
1805          * We need to cleanup all defragable inodes if the autodefragment is
1806          * close or the filesystem is read only.
1807          */
1808         if (btrfs_raw_test_opt(old_opts, AUTO_DEFRAG) &&
1809             (!btrfs_raw_test_opt(fs_info->mount_opt, AUTO_DEFRAG) || sb_rdonly(fs_info->sb))) {
1810                 btrfs_cleanup_defrag_inodes(fs_info);
1811         }
1812
1813         /* If we toggled discard async */
1814         if (!btrfs_raw_test_opt(old_opts, DISCARD_ASYNC) &&
1815             btrfs_test_opt(fs_info, DISCARD_ASYNC))
1816                 btrfs_discard_resume(fs_info);
1817         else if (btrfs_raw_test_opt(old_opts, DISCARD_ASYNC) &&
1818                  !btrfs_test_opt(fs_info, DISCARD_ASYNC))
1819                 btrfs_discard_cleanup(fs_info);
1820
1821         clear_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state);
1822 }
1823
1824 static int btrfs_remount(struct super_block *sb, int *flags, char *data)
1825 {
1826         struct btrfs_fs_info *fs_info = btrfs_sb(sb);
1827         struct btrfs_root *root = fs_info->tree_root;
1828         unsigned old_flags = sb->s_flags;
1829         unsigned long old_opts = fs_info->mount_opt;
1830         unsigned long old_compress_type = fs_info->compress_type;
1831         u64 old_max_inline = fs_info->max_inline;
1832         u32 old_thread_pool_size = fs_info->thread_pool_size;
1833         u32 old_metadata_ratio = fs_info->metadata_ratio;
1834         int ret;
1835
1836         sync_filesystem(sb);
1837         btrfs_remount_prepare(fs_info);
1838
1839         if (data) {
1840                 void *new_sec_opts = NULL;
1841
1842                 ret = security_sb_eat_lsm_opts(data, &new_sec_opts);
1843                 if (!ret)
1844                         ret = security_sb_remount(sb, new_sec_opts);
1845                 security_free_mnt_opts(&new_sec_opts);
1846                 if (ret)
1847                         goto restore;
1848         }
1849
1850         ret = btrfs_parse_options(fs_info, data, *flags);
1851         if (ret)
1852                 goto restore;
1853
1854         btrfs_remount_begin(fs_info, old_opts, *flags);
1855         btrfs_resize_thread_pool(fs_info,
1856                 fs_info->thread_pool_size, old_thread_pool_size);
1857
1858         if ((bool)(*flags & SB_RDONLY) == sb_rdonly(sb))
1859                 goto out;
1860
1861         if (*flags & SB_RDONLY) {
1862                 /*
1863                  * this also happens on 'umount -rf' or on shutdown, when
1864                  * the filesystem is busy.
1865                  */
1866                 cancel_work_sync(&fs_info->async_reclaim_work);
1867
1868                 btrfs_discard_cleanup(fs_info);
1869
1870                 /* wait for the uuid_scan task to finish */
1871                 down(&fs_info->uuid_tree_rescan_sem);
1872                 /* avoid complains from lockdep et al. */
1873                 up(&fs_info->uuid_tree_rescan_sem);
1874
1875                 sb->s_flags |= SB_RDONLY;
1876
1877                 /*
1878                  * Setting SB_RDONLY will put the cleaner thread to
1879                  * sleep at the next loop if it's already active.
1880                  * If it's already asleep, we'll leave unused block
1881                  * groups on disk until we're mounted read-write again
1882                  * unless we clean them up here.
1883                  */
1884                 btrfs_delete_unused_bgs(fs_info);
1885
1886                 btrfs_dev_replace_suspend_for_unmount(fs_info);
1887                 btrfs_scrub_cancel(fs_info);
1888                 btrfs_pause_balance(fs_info);
1889
1890                 ret = btrfs_commit_super(fs_info);
1891                 if (ret)
1892                         goto restore;
1893         } else {
1894                 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
1895                         btrfs_err(fs_info,
1896                                 "Remounting read-write after error is not allowed");
1897                         ret = -EINVAL;
1898                         goto restore;
1899                 }
1900                 if (fs_info->fs_devices->rw_devices == 0) {
1901                         ret = -EACCES;
1902                         goto restore;
1903                 }
1904
1905                 if (!btrfs_check_rw_degradable(fs_info, NULL)) {
1906                         btrfs_warn(fs_info,
1907                 "too many missing devices, writable remount is not allowed");
1908                         ret = -EACCES;
1909                         goto restore;
1910                 }
1911
1912                 if (btrfs_super_log_root(fs_info->super_copy) != 0) {
1913                         btrfs_warn(fs_info,
1914                 "mount required to replay tree-log, cannot remount read-write");
1915                         ret = -EINVAL;
1916                         goto restore;
1917                 }
1918
1919                 ret = btrfs_cleanup_fs_roots(fs_info);
1920                 if (ret)
1921                         goto restore;
1922
1923                 /* recover relocation */
1924                 mutex_lock(&fs_info->cleaner_mutex);
1925                 ret = btrfs_recover_relocation(root);
1926                 mutex_unlock(&fs_info->cleaner_mutex);
1927                 if (ret)
1928                         goto restore;
1929
1930                 ret = btrfs_resume_balance_async(fs_info);
1931                 if (ret)
1932                         goto restore;
1933
1934                 ret = btrfs_resume_dev_replace_async(fs_info);
1935                 if (ret) {
1936                         btrfs_warn(fs_info, "failed to resume dev_replace");
1937                         goto restore;
1938                 }
1939
1940                 btrfs_qgroup_rescan_resume(fs_info);
1941
1942                 if (!fs_info->uuid_root) {
1943                         btrfs_info(fs_info, "creating UUID tree");
1944                         ret = btrfs_create_uuid_tree(fs_info);
1945                         if (ret) {
1946                                 btrfs_warn(fs_info,
1947                                            "failed to create the UUID tree %d",
1948                                            ret);
1949                                 goto restore;
1950                         }
1951                 }
1952                 sb->s_flags &= ~SB_RDONLY;
1953
1954                 set_bit(BTRFS_FS_OPEN, &fs_info->flags);
1955         }
1956 out:
1957         wake_up_process(fs_info->transaction_kthread);
1958         btrfs_remount_cleanup(fs_info, old_opts);
1959         return 0;
1960
1961 restore:
1962         /* We've hit an error - don't reset SB_RDONLY */
1963         if (sb_rdonly(sb))
1964                 old_flags |= SB_RDONLY;
1965         sb->s_flags = old_flags;
1966         fs_info->mount_opt = old_opts;
1967         fs_info->compress_type = old_compress_type;
1968         fs_info->max_inline = old_max_inline;
1969         btrfs_resize_thread_pool(fs_info,
1970                 old_thread_pool_size, fs_info->thread_pool_size);
1971         fs_info->metadata_ratio = old_metadata_ratio;
1972         btrfs_remount_cleanup(fs_info, old_opts);
1973         return ret;
1974 }
1975
1976 /* Used to sort the devices by max_avail(descending sort) */
1977 static inline int btrfs_cmp_device_free_bytes(const void *dev_info1,
1978                                        const void *dev_info2)
1979 {
1980         if (((struct btrfs_device_info *)dev_info1)->max_avail >
1981             ((struct btrfs_device_info *)dev_info2)->max_avail)
1982                 return -1;
1983         else if (((struct btrfs_device_info *)dev_info1)->max_avail <
1984                  ((struct btrfs_device_info *)dev_info2)->max_avail)
1985                 return 1;
1986         else
1987         return 0;
1988 }
1989
1990 /*
1991  * sort the devices by max_avail, in which max free extent size of each device
1992  * is stored.(Descending Sort)
1993  */
1994 static inline void btrfs_descending_sort_devices(
1995                                         struct btrfs_device_info *devices,
1996                                         size_t nr_devices)
1997 {
1998         sort(devices, nr_devices, sizeof(struct btrfs_device_info),
1999              btrfs_cmp_device_free_bytes, NULL);
2000 }
2001
2002 /*
2003  * The helper to calc the free space on the devices that can be used to store
2004  * file data.
2005  */
2006 static inline int btrfs_calc_avail_data_space(struct btrfs_fs_info *fs_info,
2007                                               u64 *free_bytes)
2008 {
2009         struct btrfs_device_info *devices_info;
2010         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2011         struct btrfs_device *device;
2012         u64 type;
2013         u64 avail_space;
2014         u64 min_stripe_size;
2015         int num_stripes = 1;
2016         int i = 0, nr_devices;
2017         const struct btrfs_raid_attr *rattr;
2018
2019         /*
2020          * We aren't under the device list lock, so this is racy-ish, but good
2021          * enough for our purposes.
2022          */
2023         nr_devices = fs_info->fs_devices->open_devices;
2024         if (!nr_devices) {
2025                 smp_mb();
2026                 nr_devices = fs_info->fs_devices->open_devices;
2027                 ASSERT(nr_devices);
2028                 if (!nr_devices) {
2029                         *free_bytes = 0;
2030                         return 0;
2031                 }
2032         }
2033
2034         devices_info = kmalloc_array(nr_devices, sizeof(*devices_info),
2035                                GFP_KERNEL);
2036         if (!devices_info)
2037                 return -ENOMEM;
2038
2039         /* calc min stripe number for data space allocation */
2040         type = btrfs_data_alloc_profile(fs_info);
2041         rattr = &btrfs_raid_array[btrfs_bg_flags_to_raid_index(type)];
2042
2043         if (type & BTRFS_BLOCK_GROUP_RAID0)
2044                 num_stripes = nr_devices;
2045         else if (type & BTRFS_BLOCK_GROUP_RAID1)
2046                 num_stripes = 2;
2047         else if (type & BTRFS_BLOCK_GROUP_RAID1C3)
2048                 num_stripes = 3;
2049         else if (type & BTRFS_BLOCK_GROUP_RAID1C4)
2050                 num_stripes = 4;
2051         else if (type & BTRFS_BLOCK_GROUP_RAID10)
2052                 num_stripes = 4;
2053
2054         /* Adjust for more than 1 stripe per device */
2055         min_stripe_size = rattr->dev_stripes * BTRFS_STRIPE_LEN;
2056
2057         rcu_read_lock();
2058         list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
2059                 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
2060                                                 &device->dev_state) ||
2061                     !device->bdev ||
2062                     test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
2063                         continue;
2064
2065                 if (i >= nr_devices)
2066                         break;
2067
2068                 avail_space = device->total_bytes - device->bytes_used;
2069
2070                 /* align with stripe_len */
2071                 avail_space = rounddown(avail_space, BTRFS_STRIPE_LEN);
2072
2073                 /*
2074                  * In order to avoid overwriting the superblock on the drive,
2075                  * btrfs starts at an offset of at least 1MB when doing chunk
2076                  * allocation.
2077                  *
2078                  * This ensures we have at least min_stripe_size free space
2079                  * after excluding 1MB.
2080                  */
2081                 if (avail_space <= SZ_1M + min_stripe_size)
2082                         continue;
2083
2084                 avail_space -= SZ_1M;
2085
2086                 devices_info[i].dev = device;
2087                 devices_info[i].max_avail = avail_space;
2088
2089                 i++;
2090         }
2091         rcu_read_unlock();
2092
2093         nr_devices = i;
2094
2095         btrfs_descending_sort_devices(devices_info, nr_devices);
2096
2097         i = nr_devices - 1;
2098         avail_space = 0;
2099         while (nr_devices >= rattr->devs_min) {
2100                 num_stripes = min(num_stripes, nr_devices);
2101
2102                 if (devices_info[i].max_avail >= min_stripe_size) {
2103                         int j;
2104                         u64 alloc_size;
2105
2106                         avail_space += devices_info[i].max_avail * num_stripes;
2107                         alloc_size = devices_info[i].max_avail;
2108                         for (j = i + 1 - num_stripes; j <= i; j++)
2109                                 devices_info[j].max_avail -= alloc_size;
2110                 }
2111                 i--;
2112                 nr_devices--;
2113         }
2114
2115         kfree(devices_info);
2116         *free_bytes = avail_space;
2117         return 0;
2118 }
2119
2120 /*
2121  * Calculate numbers for 'df', pessimistic in case of mixed raid profiles.
2122  *
2123  * If there's a redundant raid level at DATA block groups, use the respective
2124  * multiplier to scale the sizes.
2125  *
2126  * Unused device space usage is based on simulating the chunk allocator
2127  * algorithm that respects the device sizes and order of allocations.  This is
2128  * a close approximation of the actual use but there are other factors that may
2129  * change the result (like a new metadata chunk).
2130  *
2131  * If metadata is exhausted, f_bavail will be 0.
2132  */
2133 static int btrfs_statfs(struct dentry *dentry, struct kstatfs *buf)
2134 {
2135         struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
2136         struct btrfs_super_block *disk_super = fs_info->super_copy;
2137         struct btrfs_space_info *found;
2138         u64 total_used = 0;
2139         u64 total_free_data = 0;
2140         u64 total_free_meta = 0;
2141         int bits = dentry->d_sb->s_blocksize_bits;
2142         __be32 *fsid = (__be32 *)fs_info->fs_devices->fsid;
2143         unsigned factor = 1;
2144         struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
2145         int ret;
2146         u64 thresh = 0;
2147         int mixed = 0;
2148
2149         rcu_read_lock();
2150         list_for_each_entry_rcu(found, &fs_info->space_info, list) {
2151                 if (found->flags & BTRFS_BLOCK_GROUP_DATA) {
2152                         int i;
2153
2154                         total_free_data += found->disk_total - found->disk_used;
2155                         total_free_data -=
2156                                 btrfs_account_ro_block_groups_free_space(found);
2157
2158                         for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
2159                                 if (!list_empty(&found->block_groups[i]))
2160                                         factor = btrfs_bg_type_to_factor(
2161                                                 btrfs_raid_array[i].bg_flag);
2162                         }
2163                 }
2164
2165                 /*
2166                  * Metadata in mixed block goup profiles are accounted in data
2167                  */
2168                 if (!mixed && found->flags & BTRFS_BLOCK_GROUP_METADATA) {
2169                         if (found->flags & BTRFS_BLOCK_GROUP_DATA)
2170                                 mixed = 1;
2171                         else
2172                                 total_free_meta += found->disk_total -
2173                                         found->disk_used;
2174                 }
2175
2176                 total_used += found->disk_used;
2177         }
2178
2179         rcu_read_unlock();
2180
2181         buf->f_blocks = div_u64(btrfs_super_total_bytes(disk_super), factor);
2182         buf->f_blocks >>= bits;
2183         buf->f_bfree = buf->f_blocks - (div_u64(total_used, factor) >> bits);
2184
2185         /* Account global block reserve as used, it's in logical size already */
2186         spin_lock(&block_rsv->lock);
2187         /* Mixed block groups accounting is not byte-accurate, avoid overflow */
2188         if (buf->f_bfree >= block_rsv->size >> bits)
2189                 buf->f_bfree -= block_rsv->size >> bits;
2190         else
2191                 buf->f_bfree = 0;
2192         spin_unlock(&block_rsv->lock);
2193
2194         buf->f_bavail = div_u64(total_free_data, factor);
2195         ret = btrfs_calc_avail_data_space(fs_info, &total_free_data);
2196         if (ret)
2197                 return ret;
2198         buf->f_bavail += div_u64(total_free_data, factor);
2199         buf->f_bavail = buf->f_bavail >> bits;
2200
2201         /*
2202          * We calculate the remaining metadata space minus global reserve. If
2203          * this is (supposedly) smaller than zero, there's no space. But this
2204          * does not hold in practice, the exhausted state happens where's still
2205          * some positive delta. So we apply some guesswork and compare the
2206          * delta to a 4M threshold.  (Practically observed delta was ~2M.)
2207          *
2208          * We probably cannot calculate the exact threshold value because this
2209          * depends on the internal reservations requested by various
2210          * operations, so some operations that consume a few metadata will
2211          * succeed even if the Avail is zero. But this is better than the other
2212          * way around.
2213          */
2214         thresh = SZ_4M;
2215
2216         /*
2217          * We only want to claim there's no available space if we can no longer
2218          * allocate chunks for our metadata profile and our global reserve will
2219          * not fit in the free metadata space.  If we aren't ->full then we
2220          * still can allocate chunks and thus are fine using the currently
2221          * calculated f_bavail.
2222          */
2223         if (!mixed && block_rsv->space_info->full &&
2224             total_free_meta - thresh < block_rsv->size)
2225                 buf->f_bavail = 0;
2226
2227         buf->f_type = BTRFS_SUPER_MAGIC;
2228         buf->f_bsize = dentry->d_sb->s_blocksize;
2229         buf->f_namelen = BTRFS_NAME_LEN;
2230
2231         /* We treat it as constant endianness (it doesn't matter _which_)
2232            because we want the fsid to come out the same whether mounted
2233            on a big-endian or little-endian host */
2234         buf->f_fsid.val[0] = be32_to_cpu(fsid[0]) ^ be32_to_cpu(fsid[2]);
2235         buf->f_fsid.val[1] = be32_to_cpu(fsid[1]) ^ be32_to_cpu(fsid[3]);
2236         /* Mask in the root object ID too, to disambiguate subvols */
2237         buf->f_fsid.val[0] ^=
2238                 BTRFS_I(d_inode(dentry))->root->root_key.objectid >> 32;
2239         buf->f_fsid.val[1] ^=
2240                 BTRFS_I(d_inode(dentry))->root->root_key.objectid;
2241
2242         return 0;
2243 }
2244
2245 static void btrfs_kill_super(struct super_block *sb)
2246 {
2247         struct btrfs_fs_info *fs_info = btrfs_sb(sb);
2248         kill_anon_super(sb);
2249         btrfs_free_fs_info(fs_info);
2250 }
2251
2252 static struct file_system_type btrfs_fs_type = {
2253         .owner          = THIS_MODULE,
2254         .name           = "btrfs",
2255         .mount          = btrfs_mount,
2256         .kill_sb        = btrfs_kill_super,
2257         .fs_flags       = FS_REQUIRES_DEV | FS_BINARY_MOUNTDATA,
2258 };
2259
2260 static struct file_system_type btrfs_root_fs_type = {
2261         .owner          = THIS_MODULE,
2262         .name           = "btrfs",
2263         .mount          = btrfs_mount_root,
2264         .kill_sb        = btrfs_kill_super,
2265         .fs_flags       = FS_REQUIRES_DEV | FS_BINARY_MOUNTDATA,
2266 };
2267
2268 MODULE_ALIAS_FS("btrfs");
2269
2270 static int btrfs_control_open(struct inode *inode, struct file *file)
2271 {
2272         /*
2273          * The control file's private_data is used to hold the
2274          * transaction when it is started and is used to keep
2275          * track of whether a transaction is already in progress.
2276          */
2277         file->private_data = NULL;
2278         return 0;
2279 }
2280
2281 /*
2282  * Used by /dev/btrfs-control for devices ioctls.
2283  */
2284 static long btrfs_control_ioctl(struct file *file, unsigned int cmd,
2285                                 unsigned long arg)
2286 {
2287         struct btrfs_ioctl_vol_args *vol;
2288         struct btrfs_device *device = NULL;
2289         int ret = -ENOTTY;
2290
2291         if (!capable(CAP_SYS_ADMIN))
2292                 return -EPERM;
2293
2294         vol = memdup_user((void __user *)arg, sizeof(*vol));
2295         if (IS_ERR(vol))
2296                 return PTR_ERR(vol);
2297         vol->name[BTRFS_PATH_NAME_MAX] = '\0';
2298
2299         switch (cmd) {
2300         case BTRFS_IOC_SCAN_DEV:
2301                 mutex_lock(&uuid_mutex);
2302                 device = btrfs_scan_one_device(vol->name, FMODE_READ,
2303                                                &btrfs_root_fs_type);
2304                 ret = PTR_ERR_OR_ZERO(device);
2305                 mutex_unlock(&uuid_mutex);
2306                 break;
2307         case BTRFS_IOC_FORGET_DEV:
2308                 ret = btrfs_forget_devices(vol->name);
2309                 break;
2310         case BTRFS_IOC_DEVICES_READY:
2311                 mutex_lock(&uuid_mutex);
2312                 device = btrfs_scan_one_device(vol->name, FMODE_READ,
2313                                                &btrfs_root_fs_type);
2314                 if (IS_ERR(device)) {
2315                         mutex_unlock(&uuid_mutex);
2316                         ret = PTR_ERR(device);
2317                         break;
2318                 }
2319                 ret = !(device->fs_devices->num_devices ==
2320                         device->fs_devices->total_devices);
2321                 mutex_unlock(&uuid_mutex);
2322                 break;
2323         case BTRFS_IOC_GET_SUPPORTED_FEATURES:
2324                 ret = btrfs_ioctl_get_supported_features((void __user*)arg);
2325                 break;
2326         }
2327
2328         kfree(vol);
2329         return ret;
2330 }
2331
2332 static int btrfs_freeze(struct super_block *sb)
2333 {
2334         struct btrfs_trans_handle *trans;
2335         struct btrfs_fs_info *fs_info = btrfs_sb(sb);
2336         struct btrfs_root *root = fs_info->tree_root;
2337
2338         set_bit(BTRFS_FS_FROZEN, &fs_info->flags);
2339         /*
2340          * We don't need a barrier here, we'll wait for any transaction that
2341          * could be in progress on other threads (and do delayed iputs that
2342          * we want to avoid on a frozen filesystem), or do the commit
2343          * ourselves.
2344          */
2345         trans = btrfs_attach_transaction_barrier(root);
2346         if (IS_ERR(trans)) {
2347                 /* no transaction, don't bother */
2348                 if (PTR_ERR(trans) == -ENOENT)
2349                         return 0;
2350                 return PTR_ERR(trans);
2351         }
2352         return btrfs_commit_transaction(trans);
2353 }
2354
2355 static int btrfs_unfreeze(struct super_block *sb)
2356 {
2357         struct btrfs_fs_info *fs_info = btrfs_sb(sb);
2358
2359         clear_bit(BTRFS_FS_FROZEN, &fs_info->flags);
2360         return 0;
2361 }
2362
2363 static int btrfs_show_devname(struct seq_file *m, struct dentry *root)
2364 {
2365         struct btrfs_fs_info *fs_info = btrfs_sb(root->d_sb);
2366         struct btrfs_fs_devices *cur_devices;
2367         struct btrfs_device *dev, *first_dev = NULL;
2368         struct list_head *head;
2369
2370         /*
2371          * Lightweight locking of the devices. We should not need
2372          * device_list_mutex here as we only read the device data and the list
2373          * is protected by RCU.  Even if a device is deleted during the list
2374          * traversals, we'll get valid data, the freeing callback will wait at
2375          * least until the rcu_read_unlock.
2376          */
2377         rcu_read_lock();
2378         cur_devices = fs_info->fs_devices;
2379         while (cur_devices) {
2380                 head = &cur_devices->devices;
2381                 list_for_each_entry_rcu(dev, head, dev_list) {
2382                         if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
2383                                 continue;
2384                         if (!dev->name)
2385                                 continue;
2386                         if (!first_dev || dev->devid < first_dev->devid)
2387                                 first_dev = dev;
2388                 }
2389                 cur_devices = cur_devices->seed;
2390         }
2391
2392         if (first_dev)
2393                 seq_escape(m, rcu_str_deref(first_dev->name), " \t\n\\");
2394         else
2395                 WARN_ON(1);
2396         rcu_read_unlock();
2397         return 0;
2398 }
2399
2400 static const struct super_operations btrfs_super_ops = {
2401         .drop_inode     = btrfs_drop_inode,
2402         .evict_inode    = btrfs_evict_inode,
2403         .put_super      = btrfs_put_super,
2404         .sync_fs        = btrfs_sync_fs,
2405         .show_options   = btrfs_show_options,
2406         .show_devname   = btrfs_show_devname,
2407         .alloc_inode    = btrfs_alloc_inode,
2408         .destroy_inode  = btrfs_destroy_inode,
2409         .free_inode     = btrfs_free_inode,
2410         .statfs         = btrfs_statfs,
2411         .remount_fs     = btrfs_remount,
2412         .freeze_fs      = btrfs_freeze,
2413         .unfreeze_fs    = btrfs_unfreeze,
2414 };
2415
2416 static const struct file_operations btrfs_ctl_fops = {
2417         .open = btrfs_control_open,
2418         .unlocked_ioctl  = btrfs_control_ioctl,
2419         .compat_ioctl = compat_ptr_ioctl,
2420         .owner   = THIS_MODULE,
2421         .llseek = noop_llseek,
2422 };
2423
2424 static struct miscdevice btrfs_misc = {
2425         .minor          = BTRFS_MINOR,
2426         .name           = "btrfs-control",
2427         .fops           = &btrfs_ctl_fops
2428 };
2429
2430 MODULE_ALIAS_MISCDEV(BTRFS_MINOR);
2431 MODULE_ALIAS("devname:btrfs-control");
2432
2433 static int __init btrfs_interface_init(void)
2434 {
2435         return misc_register(&btrfs_misc);
2436 }
2437
2438 static __cold void btrfs_interface_exit(void)
2439 {
2440         misc_deregister(&btrfs_misc);
2441 }
2442
2443 static void __init btrfs_print_mod_info(void)
2444 {
2445         static const char options[] = ""
2446 #ifdef CONFIG_BTRFS_DEBUG
2447                         ", debug=on"
2448 #endif
2449 #ifdef CONFIG_BTRFS_ASSERT
2450                         ", assert=on"
2451 #endif
2452 #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
2453                         ", integrity-checker=on"
2454 #endif
2455 #ifdef CONFIG_BTRFS_FS_REF_VERIFY
2456                         ", ref-verify=on"
2457 #endif
2458                         ;
2459         pr_info("Btrfs loaded, crc32c=%s%s\n", crc32c_impl(), options);
2460 }
2461
2462 static int __init init_btrfs_fs(void)
2463 {
2464         int err;
2465
2466         btrfs_props_init();
2467
2468         err = btrfs_init_sysfs();
2469         if (err)
2470                 return err;
2471
2472         btrfs_init_compress();
2473
2474         err = btrfs_init_cachep();
2475         if (err)
2476                 goto free_compress;
2477
2478         err = extent_io_init();
2479         if (err)
2480                 goto free_cachep;
2481
2482         err = extent_state_cache_init();
2483         if (err)
2484                 goto free_extent_io;
2485
2486         err = extent_map_init();
2487         if (err)
2488                 goto free_extent_state_cache;
2489
2490         err = ordered_data_init();
2491         if (err)
2492                 goto free_extent_map;
2493
2494         err = btrfs_delayed_inode_init();
2495         if (err)
2496                 goto free_ordered_data;
2497
2498         err = btrfs_auto_defrag_init();
2499         if (err)
2500                 goto free_delayed_inode;
2501
2502         err = btrfs_delayed_ref_init();
2503         if (err)
2504                 goto free_auto_defrag;
2505
2506         err = btrfs_prelim_ref_init();
2507         if (err)
2508                 goto free_delayed_ref;
2509
2510         err = btrfs_end_io_wq_init();
2511         if (err)
2512                 goto free_prelim_ref;
2513
2514         err = btrfs_interface_init();
2515         if (err)
2516                 goto free_end_io_wq;
2517
2518         btrfs_init_lockdep();
2519
2520         btrfs_print_mod_info();
2521
2522         err = btrfs_run_sanity_tests();
2523         if (err)
2524                 goto unregister_ioctl;
2525
2526         err = register_filesystem(&btrfs_fs_type);
2527         if (err)
2528                 goto unregister_ioctl;
2529
2530         return 0;
2531
2532 unregister_ioctl:
2533         btrfs_interface_exit();
2534 free_end_io_wq:
2535         btrfs_end_io_wq_exit();
2536 free_prelim_ref:
2537         btrfs_prelim_ref_exit();
2538 free_delayed_ref:
2539         btrfs_delayed_ref_exit();
2540 free_auto_defrag:
2541         btrfs_auto_defrag_exit();
2542 free_delayed_inode:
2543         btrfs_delayed_inode_exit();
2544 free_ordered_data:
2545         ordered_data_exit();
2546 free_extent_map:
2547         extent_map_exit();
2548 free_extent_state_cache:
2549         extent_state_cache_exit();
2550 free_extent_io:
2551         extent_io_exit();
2552 free_cachep:
2553         btrfs_destroy_cachep();
2554 free_compress:
2555         btrfs_exit_compress();
2556         btrfs_exit_sysfs();
2557
2558         return err;
2559 }
2560
2561 static void __exit exit_btrfs_fs(void)
2562 {
2563         btrfs_destroy_cachep();
2564         btrfs_delayed_ref_exit();
2565         btrfs_auto_defrag_exit();
2566         btrfs_delayed_inode_exit();
2567         btrfs_prelim_ref_exit();
2568         ordered_data_exit();
2569         extent_map_exit();
2570         extent_state_cache_exit();
2571         extent_io_exit();
2572         btrfs_interface_exit();
2573         btrfs_end_io_wq_exit();
2574         unregister_filesystem(&btrfs_fs_type);
2575         btrfs_exit_sysfs();
2576         btrfs_cleanup_fs_uuids();
2577         btrfs_exit_compress();
2578 }
2579
2580 late_initcall(init_btrfs_fs);
2581 module_exit(exit_btrfs_fs)
2582
2583 MODULE_LICENSE("GPL");
2584 MODULE_SOFTDEP("pre: crc32c");
2585 MODULE_SOFTDEP("pre: xxhash64");
2586 MODULE_SOFTDEP("pre: sha256");
2587 MODULE_SOFTDEP("pre: blake2b-256");