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