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