Merge tag 'for-4.15-rc2-tag' of git://git.kernel.org/pub/scm/linux/kernel/git/kdave...
[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 |= SB_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 SB_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 & SB_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
511                                 info->compress_type = BTRFS_COMPRESS_ZLIB;
512                                 info->compress_level = BTRFS_ZLIB_DEFAULT_LEVEL;
513                                 /*
514                                  * args[0] contains uninitialized data since
515                                  * for these tokens we don't expect any
516                                  * parameter.
517                                  */
518                                 if (token != Opt_compress &&
519                                     token != Opt_compress_force)
520                                         info->compress_level =
521                                           btrfs_compress_str2level(args[0].from);
522                                 btrfs_set_opt(info->mount_opt, COMPRESS);
523                                 btrfs_clear_opt(info->mount_opt, NODATACOW);
524                                 btrfs_clear_opt(info->mount_opt, NODATASUM);
525                                 no_compress = 0;
526                         } else if (strncmp(args[0].from, "lzo", 3) == 0) {
527                                 compress_type = "lzo";
528                                 info->compress_type = BTRFS_COMPRESS_LZO;
529                                 btrfs_set_opt(info->mount_opt, COMPRESS);
530                                 btrfs_clear_opt(info->mount_opt, NODATACOW);
531                                 btrfs_clear_opt(info->mount_opt, NODATASUM);
532                                 btrfs_set_fs_incompat(info, COMPRESS_LZO);
533                                 no_compress = 0;
534                         } else if (strcmp(args[0].from, "zstd") == 0) {
535                                 compress_type = "zstd";
536                                 info->compress_type = BTRFS_COMPRESS_ZSTD;
537                                 btrfs_set_opt(info->mount_opt, COMPRESS);
538                                 btrfs_clear_opt(info->mount_opt, NODATACOW);
539                                 btrfs_clear_opt(info->mount_opt, NODATASUM);
540                                 btrfs_set_fs_incompat(info, COMPRESS_ZSTD);
541                                 no_compress = 0;
542                         } else if (strncmp(args[0].from, "no", 2) == 0) {
543                                 compress_type = "no";
544                                 btrfs_clear_opt(info->mount_opt, COMPRESS);
545                                 btrfs_clear_opt(info->mount_opt, FORCE_COMPRESS);
546                                 compress_force = false;
547                                 no_compress++;
548                         } else {
549                                 ret = -EINVAL;
550                                 goto out;
551                         }
552
553                         if (compress_force) {
554                                 btrfs_set_opt(info->mount_opt, FORCE_COMPRESS);
555                         } else {
556                                 /*
557                                  * If we remount from compress-force=xxx to
558                                  * compress=xxx, we need clear FORCE_COMPRESS
559                                  * flag, otherwise, there is no way for users
560                                  * to disable forcible compression separately.
561                                  */
562                                 btrfs_clear_opt(info->mount_opt, FORCE_COMPRESS);
563                         }
564                         if ((btrfs_test_opt(info, COMPRESS) &&
565                              (info->compress_type != saved_compress_type ||
566                               compress_force != saved_compress_force)) ||
567                             (!btrfs_test_opt(info, COMPRESS) &&
568                              no_compress == 1)) {
569                                 btrfs_info(info, "%s %s compression, level %d",
570                                            (compress_force) ? "force" : "use",
571                                            compress_type, info->compress_level);
572                         }
573                         compress_force = false;
574                         break;
575                 case Opt_ssd:
576                         btrfs_set_and_info(info, SSD,
577                                            "enabling ssd optimizations");
578                         btrfs_clear_opt(info->mount_opt, NOSSD);
579                         break;
580                 case Opt_ssd_spread:
581                         btrfs_set_and_info(info, SSD,
582                                            "enabling ssd optimizations");
583                         btrfs_set_and_info(info, SSD_SPREAD,
584                                            "using spread ssd allocation scheme");
585                         btrfs_clear_opt(info->mount_opt, NOSSD);
586                         break;
587                 case Opt_nossd:
588                         btrfs_set_opt(info->mount_opt, NOSSD);
589                         btrfs_clear_and_info(info, SSD,
590                                              "not using ssd optimizations");
591                         btrfs_clear_and_info(info, SSD_SPREAD,
592                                              "not using spread ssd allocation scheme");
593                         break;
594                 case Opt_barrier:
595                         btrfs_clear_and_info(info, NOBARRIER,
596                                              "turning on barriers");
597                         break;
598                 case Opt_nobarrier:
599                         btrfs_set_and_info(info, NOBARRIER,
600                                            "turning off barriers");
601                         break;
602                 case Opt_thread_pool:
603                         ret = match_int(&args[0], &intarg);
604                         if (ret) {
605                                 goto out;
606                         } else if (intarg > 0) {
607                                 info->thread_pool_size = intarg;
608                         } else {
609                                 ret = -EINVAL;
610                                 goto out;
611                         }
612                         break;
613                 case Opt_max_inline:
614                         num = match_strdup(&args[0]);
615                         if (num) {
616                                 info->max_inline = memparse(num, NULL);
617                                 kfree(num);
618
619                                 if (info->max_inline) {
620                                         info->max_inline = min_t(u64,
621                                                 info->max_inline,
622                                                 info->sectorsize);
623                                 }
624                                 btrfs_info(info, "max_inline at %llu",
625                                            info->max_inline);
626                         } else {
627                                 ret = -ENOMEM;
628                                 goto out;
629                         }
630                         break;
631                 case Opt_alloc_start:
632                         btrfs_info(info,
633                                 "option alloc_start is obsolete, ignored");
634                         break;
635                 case Opt_acl:
636 #ifdef CONFIG_BTRFS_FS_POSIX_ACL
637                         info->sb->s_flags |= SB_POSIXACL;
638                         break;
639 #else
640                         btrfs_err(info, "support for ACL not compiled in!");
641                         ret = -EINVAL;
642                         goto out;
643 #endif
644                 case Opt_noacl:
645                         info->sb->s_flags &= ~SB_POSIXACL;
646                         break;
647                 case Opt_notreelog:
648                         btrfs_set_and_info(info, NOTREELOG,
649                                            "disabling tree log");
650                         break;
651                 case Opt_treelog:
652                         btrfs_clear_and_info(info, NOTREELOG,
653                                              "enabling tree log");
654                         break;
655                 case Opt_norecovery:
656                 case Opt_nologreplay:
657                         btrfs_set_and_info(info, NOLOGREPLAY,
658                                            "disabling log replay at mount time");
659                         break;
660                 case Opt_flushoncommit:
661                         btrfs_set_and_info(info, FLUSHONCOMMIT,
662                                            "turning on flush-on-commit");
663                         break;
664                 case Opt_noflushoncommit:
665                         btrfs_clear_and_info(info, FLUSHONCOMMIT,
666                                              "turning off flush-on-commit");
667                         break;
668                 case Opt_ratio:
669                         ret = match_int(&args[0], &intarg);
670                         if (ret) {
671                                 goto out;
672                         } else if (intarg >= 0) {
673                                 info->metadata_ratio = intarg;
674                                 btrfs_info(info, "metadata ratio %d",
675                                            info->metadata_ratio);
676                         } else {
677                                 ret = -EINVAL;
678                                 goto out;
679                         }
680                         break;
681                 case Opt_discard:
682                         btrfs_set_and_info(info, DISCARD,
683                                            "turning on discard");
684                         break;
685                 case Opt_nodiscard:
686                         btrfs_clear_and_info(info, DISCARD,
687                                              "turning off discard");
688                         break;
689                 case Opt_space_cache:
690                 case Opt_space_cache_version:
691                         if (token == Opt_space_cache ||
692                             strcmp(args[0].from, "v1") == 0) {
693                                 btrfs_clear_opt(info->mount_opt,
694                                                 FREE_SPACE_TREE);
695                                 btrfs_set_and_info(info, SPACE_CACHE,
696                                            "enabling disk space caching");
697                         } else if (strcmp(args[0].from, "v2") == 0) {
698                                 btrfs_clear_opt(info->mount_opt,
699                                                 SPACE_CACHE);
700                                 btrfs_set_and_info(info, FREE_SPACE_TREE,
701                                                    "enabling free space tree");
702                         } else {
703                                 ret = -EINVAL;
704                                 goto out;
705                         }
706                         break;
707                 case Opt_rescan_uuid_tree:
708                         btrfs_set_opt(info->mount_opt, RESCAN_UUID_TREE);
709                         break;
710                 case Opt_no_space_cache:
711                         if (btrfs_test_opt(info, SPACE_CACHE)) {
712                                 btrfs_clear_and_info(info, SPACE_CACHE,
713                                              "disabling disk space caching");
714                         }
715                         if (btrfs_test_opt(info, FREE_SPACE_TREE)) {
716                                 btrfs_clear_and_info(info, FREE_SPACE_TREE,
717                                              "disabling free space tree");
718                         }
719                         break;
720                 case Opt_inode_cache:
721                         btrfs_set_pending_and_info(info, INODE_MAP_CACHE,
722                                            "enabling inode map caching");
723                         break;
724                 case Opt_noinode_cache:
725                         btrfs_clear_pending_and_info(info, INODE_MAP_CACHE,
726                                              "disabling inode map caching");
727                         break;
728                 case Opt_clear_cache:
729                         btrfs_set_and_info(info, CLEAR_CACHE,
730                                            "force clearing of disk cache");
731                         break;
732                 case Opt_user_subvol_rm_allowed:
733                         btrfs_set_opt(info->mount_opt, USER_SUBVOL_RM_ALLOWED);
734                         break;
735                 case Opt_enospc_debug:
736                         btrfs_set_opt(info->mount_opt, ENOSPC_DEBUG);
737                         break;
738                 case Opt_noenospc_debug:
739                         btrfs_clear_opt(info->mount_opt, ENOSPC_DEBUG);
740                         break;
741                 case Opt_defrag:
742                         btrfs_set_and_info(info, AUTO_DEFRAG,
743                                            "enabling auto defrag");
744                         break;
745                 case Opt_nodefrag:
746                         btrfs_clear_and_info(info, AUTO_DEFRAG,
747                                              "disabling auto defrag");
748                         break;
749                 case Opt_recovery:
750                         btrfs_warn(info,
751                                    "'recovery' is deprecated, use 'usebackuproot' instead");
752                 case Opt_usebackuproot:
753                         btrfs_info(info,
754                                    "trying to use backup root at mount time");
755                         btrfs_set_opt(info->mount_opt, USEBACKUPROOT);
756                         break;
757                 case Opt_skip_balance:
758                         btrfs_set_opt(info->mount_opt, SKIP_BALANCE);
759                         break;
760 #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
761                 case Opt_check_integrity_including_extent_data:
762                         btrfs_info(info,
763                                    "enabling check integrity including extent data");
764                         btrfs_set_opt(info->mount_opt,
765                                       CHECK_INTEGRITY_INCLUDING_EXTENT_DATA);
766                         btrfs_set_opt(info->mount_opt, CHECK_INTEGRITY);
767                         break;
768                 case Opt_check_integrity:
769                         btrfs_info(info, "enabling check integrity");
770                         btrfs_set_opt(info->mount_opt, CHECK_INTEGRITY);
771                         break;
772                 case Opt_check_integrity_print_mask:
773                         ret = match_int(&args[0], &intarg);
774                         if (ret) {
775                                 goto out;
776                         } else if (intarg >= 0) {
777                                 info->check_integrity_print_mask = intarg;
778                                 btrfs_info(info,
779                                            "check_integrity_print_mask 0x%x",
780                                            info->check_integrity_print_mask);
781                         } else {
782                                 ret = -EINVAL;
783                                 goto out;
784                         }
785                         break;
786 #else
787                 case Opt_check_integrity_including_extent_data:
788                 case Opt_check_integrity:
789                 case Opt_check_integrity_print_mask:
790                         btrfs_err(info,
791                                   "support for check_integrity* not compiled in!");
792                         ret = -EINVAL;
793                         goto out;
794 #endif
795                 case Opt_fatal_errors:
796                         if (strcmp(args[0].from, "panic") == 0)
797                                 btrfs_set_opt(info->mount_opt,
798                                               PANIC_ON_FATAL_ERROR);
799                         else if (strcmp(args[0].from, "bug") == 0)
800                                 btrfs_clear_opt(info->mount_opt,
801                                               PANIC_ON_FATAL_ERROR);
802                         else {
803                                 ret = -EINVAL;
804                                 goto out;
805                         }
806                         break;
807                 case Opt_commit_interval:
808                         intarg = 0;
809                         ret = match_int(&args[0], &intarg);
810                         if (ret < 0) {
811                                 btrfs_err(info, "invalid commit interval");
812                                 ret = -EINVAL;
813                                 goto out;
814                         }
815                         if (intarg > 0) {
816                                 if (intarg > 300) {
817                                         btrfs_warn(info,
818                                                 "excessive commit interval %d",
819                                                 intarg);
820                                 }
821                                 info->commit_interval = intarg;
822                         } else {
823                                 btrfs_info(info,
824                                            "using default commit interval %ds",
825                                            BTRFS_DEFAULT_COMMIT_INTERVAL);
826                                 info->commit_interval = BTRFS_DEFAULT_COMMIT_INTERVAL;
827                         }
828                         break;
829 #ifdef CONFIG_BTRFS_DEBUG
830                 case Opt_fragment_all:
831                         btrfs_info(info, "fragmenting all space");
832                         btrfs_set_opt(info->mount_opt, FRAGMENT_DATA);
833                         btrfs_set_opt(info->mount_opt, FRAGMENT_METADATA);
834                         break;
835                 case Opt_fragment_metadata:
836                         btrfs_info(info, "fragmenting metadata");
837                         btrfs_set_opt(info->mount_opt,
838                                       FRAGMENT_METADATA);
839                         break;
840                 case Opt_fragment_data:
841                         btrfs_info(info, "fragmenting data");
842                         btrfs_set_opt(info->mount_opt, FRAGMENT_DATA);
843                         break;
844 #endif
845 #ifdef CONFIG_BTRFS_FS_REF_VERIFY
846                 case Opt_ref_verify:
847                         btrfs_info(info, "doing ref verification");
848                         btrfs_set_opt(info->mount_opt, REF_VERIFY);
849                         break;
850 #endif
851                 case Opt_err:
852                         btrfs_info(info, "unrecognized mount option '%s'", p);
853                         ret = -EINVAL;
854                         goto out;
855                 default:
856                         break;
857                 }
858         }
859 check:
860         /*
861          * Extra check for current option against current flag
862          */
863         if (btrfs_test_opt(info, NOLOGREPLAY) && !(new_flags & SB_RDONLY)) {
864                 btrfs_err(info,
865                           "nologreplay must be used with ro mount option");
866                 ret = -EINVAL;
867         }
868 out:
869         if (btrfs_fs_compat_ro(info, FREE_SPACE_TREE) &&
870             !btrfs_test_opt(info, FREE_SPACE_TREE) &&
871             !btrfs_test_opt(info, CLEAR_CACHE)) {
872                 btrfs_err(info, "cannot disable free space tree");
873                 ret = -EINVAL;
874
875         }
876         if (!ret && btrfs_test_opt(info, SPACE_CACHE))
877                 btrfs_info(info, "disk space caching is enabled");
878         if (!ret && btrfs_test_opt(info, FREE_SPACE_TREE))
879                 btrfs_info(info, "using free space tree");
880         kfree(orig);
881         return ret;
882 }
883
884 /*
885  * Parse mount options that are required early in the mount process.
886  *
887  * All other options will be parsed on much later in the mount process and
888  * only when we need to allocate a new super block.
889  */
890 static int btrfs_parse_early_options(const char *options, fmode_t flags,
891                 void *holder, char **subvol_name, u64 *subvol_objectid,
892                 struct btrfs_fs_devices **fs_devices)
893 {
894         substring_t args[MAX_OPT_ARGS];
895         char *device_name, *opts, *orig, *p;
896         char *num = NULL;
897         int error = 0;
898
899         if (!options)
900                 return 0;
901
902         /*
903          * strsep changes the string, duplicate it because parse_options
904          * gets called twice
905          */
906         opts = kstrdup(options, GFP_KERNEL);
907         if (!opts)
908                 return -ENOMEM;
909         orig = opts;
910
911         while ((p = strsep(&opts, ",")) != NULL) {
912                 int token;
913                 if (!*p)
914                         continue;
915
916                 token = match_token(p, tokens, args);
917                 switch (token) {
918                 case Opt_subvol:
919                         kfree(*subvol_name);
920                         *subvol_name = match_strdup(&args[0]);
921                         if (!*subvol_name) {
922                                 error = -ENOMEM;
923                                 goto out;
924                         }
925                         break;
926                 case Opt_subvolid:
927                         num = match_strdup(&args[0]);
928                         if (num) {
929                                 *subvol_objectid = memparse(num, NULL);
930                                 kfree(num);
931                                 /* we want the original fs_tree */
932                                 if (!*subvol_objectid)
933                                         *subvol_objectid =
934                                                 BTRFS_FS_TREE_OBJECTID;
935                         } else {
936                                 error = -EINVAL;
937                                 goto out;
938                         }
939                         break;
940                 case Opt_subvolrootid:
941                         pr_warn("BTRFS: 'subvolrootid' mount option is deprecated and has no effect\n");
942                         break;
943                 case Opt_device:
944                         device_name = match_strdup(&args[0]);
945                         if (!device_name) {
946                                 error = -ENOMEM;
947                                 goto out;
948                         }
949                         error = btrfs_scan_one_device(device_name,
950                                         flags, holder, fs_devices);
951                         kfree(device_name);
952                         if (error)
953                                 goto out;
954                         break;
955                 default:
956                         break;
957                 }
958         }
959
960 out:
961         kfree(orig);
962         return error;
963 }
964
965 static char *get_subvol_name_from_objectid(struct btrfs_fs_info *fs_info,
966                                            u64 subvol_objectid)
967 {
968         struct btrfs_root *root = fs_info->tree_root;
969         struct btrfs_root *fs_root;
970         struct btrfs_root_ref *root_ref;
971         struct btrfs_inode_ref *inode_ref;
972         struct btrfs_key key;
973         struct btrfs_path *path = NULL;
974         char *name = NULL, *ptr;
975         u64 dirid;
976         int len;
977         int ret;
978
979         path = btrfs_alloc_path();
980         if (!path) {
981                 ret = -ENOMEM;
982                 goto err;
983         }
984         path->leave_spinning = 1;
985
986         name = kmalloc(PATH_MAX, GFP_KERNEL);
987         if (!name) {
988                 ret = -ENOMEM;
989                 goto err;
990         }
991         ptr = name + PATH_MAX - 1;
992         ptr[0] = '\0';
993
994         /*
995          * Walk up the subvolume trees in the tree of tree roots by root
996          * backrefs until we hit the top-level subvolume.
997          */
998         while (subvol_objectid != BTRFS_FS_TREE_OBJECTID) {
999                 key.objectid = subvol_objectid;
1000                 key.type = BTRFS_ROOT_BACKREF_KEY;
1001                 key.offset = (u64)-1;
1002
1003                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1004                 if (ret < 0) {
1005                         goto err;
1006                 } else if (ret > 0) {
1007                         ret = btrfs_previous_item(root, path, subvol_objectid,
1008                                                   BTRFS_ROOT_BACKREF_KEY);
1009                         if (ret < 0) {
1010                                 goto err;
1011                         } else if (ret > 0) {
1012                                 ret = -ENOENT;
1013                                 goto err;
1014                         }
1015                 }
1016
1017                 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1018                 subvol_objectid = key.offset;
1019
1020                 root_ref = btrfs_item_ptr(path->nodes[0], path->slots[0],
1021                                           struct btrfs_root_ref);
1022                 len = btrfs_root_ref_name_len(path->nodes[0], root_ref);
1023                 ptr -= len + 1;
1024                 if (ptr < name) {
1025                         ret = -ENAMETOOLONG;
1026                         goto err;
1027                 }
1028                 read_extent_buffer(path->nodes[0], ptr + 1,
1029                                    (unsigned long)(root_ref + 1), len);
1030                 ptr[0] = '/';
1031                 dirid = btrfs_root_ref_dirid(path->nodes[0], root_ref);
1032                 btrfs_release_path(path);
1033
1034                 key.objectid = subvol_objectid;
1035                 key.type = BTRFS_ROOT_ITEM_KEY;
1036                 key.offset = (u64)-1;
1037                 fs_root = btrfs_read_fs_root_no_name(fs_info, &key);
1038                 if (IS_ERR(fs_root)) {
1039                         ret = PTR_ERR(fs_root);
1040                         goto err;
1041                 }
1042
1043                 /*
1044                  * Walk up the filesystem tree by inode refs until we hit the
1045                  * root directory.
1046                  */
1047                 while (dirid != BTRFS_FIRST_FREE_OBJECTID) {
1048                         key.objectid = dirid;
1049                         key.type = BTRFS_INODE_REF_KEY;
1050                         key.offset = (u64)-1;
1051
1052                         ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
1053                         if (ret < 0) {
1054                                 goto err;
1055                         } else if (ret > 0) {
1056                                 ret = btrfs_previous_item(fs_root, path, dirid,
1057                                                           BTRFS_INODE_REF_KEY);
1058                                 if (ret < 0) {
1059                                         goto err;
1060                                 } else if (ret > 0) {
1061                                         ret = -ENOENT;
1062                                         goto err;
1063                                 }
1064                         }
1065
1066                         btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1067                         dirid = key.offset;
1068
1069                         inode_ref = btrfs_item_ptr(path->nodes[0],
1070                                                    path->slots[0],
1071                                                    struct btrfs_inode_ref);
1072                         len = btrfs_inode_ref_name_len(path->nodes[0],
1073                                                        inode_ref);
1074                         ptr -= len + 1;
1075                         if (ptr < name) {
1076                                 ret = -ENAMETOOLONG;
1077                                 goto err;
1078                         }
1079                         read_extent_buffer(path->nodes[0], ptr + 1,
1080                                            (unsigned long)(inode_ref + 1), len);
1081                         ptr[0] = '/';
1082                         btrfs_release_path(path);
1083                 }
1084         }
1085
1086         btrfs_free_path(path);
1087         if (ptr == name + PATH_MAX - 1) {
1088                 name[0] = '/';
1089                 name[1] = '\0';
1090         } else {
1091                 memmove(name, ptr, name + PATH_MAX - ptr);
1092         }
1093         return name;
1094
1095 err:
1096         btrfs_free_path(path);
1097         kfree(name);
1098         return ERR_PTR(ret);
1099 }
1100
1101 static int get_default_subvol_objectid(struct btrfs_fs_info *fs_info, u64 *objectid)
1102 {
1103         struct btrfs_root *root = fs_info->tree_root;
1104         struct btrfs_dir_item *di;
1105         struct btrfs_path *path;
1106         struct btrfs_key location;
1107         u64 dir_id;
1108
1109         path = btrfs_alloc_path();
1110         if (!path)
1111                 return -ENOMEM;
1112         path->leave_spinning = 1;
1113
1114         /*
1115          * Find the "default" dir item which points to the root item that we
1116          * will mount by default if we haven't been given a specific subvolume
1117          * to mount.
1118          */
1119         dir_id = btrfs_super_root_dir(fs_info->super_copy);
1120         di = btrfs_lookup_dir_item(NULL, root, path, dir_id, "default", 7, 0);
1121         if (IS_ERR(di)) {
1122                 btrfs_free_path(path);
1123                 return PTR_ERR(di);
1124         }
1125         if (!di) {
1126                 /*
1127                  * Ok the default dir item isn't there.  This is weird since
1128                  * it's always been there, but don't freak out, just try and
1129                  * mount the top-level subvolume.
1130                  */
1131                 btrfs_free_path(path);
1132                 *objectid = BTRFS_FS_TREE_OBJECTID;
1133                 return 0;
1134         }
1135
1136         btrfs_dir_item_key_to_cpu(path->nodes[0], di, &location);
1137         btrfs_free_path(path);
1138         *objectid = location.objectid;
1139         return 0;
1140 }
1141
1142 static int btrfs_fill_super(struct super_block *sb,
1143                             struct btrfs_fs_devices *fs_devices,
1144                             void *data)
1145 {
1146         struct inode *inode;
1147         struct btrfs_fs_info *fs_info = btrfs_sb(sb);
1148         struct btrfs_key key;
1149         int err;
1150
1151         sb->s_maxbytes = MAX_LFS_FILESIZE;
1152         sb->s_magic = BTRFS_SUPER_MAGIC;
1153         sb->s_op = &btrfs_super_ops;
1154         sb->s_d_op = &btrfs_dentry_operations;
1155         sb->s_export_op = &btrfs_export_ops;
1156         sb->s_xattr = btrfs_xattr_handlers;
1157         sb->s_time_gran = 1;
1158 #ifdef CONFIG_BTRFS_FS_POSIX_ACL
1159         sb->s_flags |= SB_POSIXACL;
1160 #endif
1161         sb->s_flags |= SB_I_VERSION;
1162         sb->s_iflags |= SB_I_CGROUPWB;
1163
1164         err = super_setup_bdi(sb);
1165         if (err) {
1166                 btrfs_err(fs_info, "super_setup_bdi failed");
1167                 return err;
1168         }
1169
1170         err = open_ctree(sb, fs_devices, (char *)data);
1171         if (err) {
1172                 btrfs_err(fs_info, "open_ctree failed");
1173                 return err;
1174         }
1175
1176         key.objectid = BTRFS_FIRST_FREE_OBJECTID;
1177         key.type = BTRFS_INODE_ITEM_KEY;
1178         key.offset = 0;
1179         inode = btrfs_iget(sb, &key, fs_info->fs_root, NULL);
1180         if (IS_ERR(inode)) {
1181                 err = PTR_ERR(inode);
1182                 goto fail_close;
1183         }
1184
1185         sb->s_root = d_make_root(inode);
1186         if (!sb->s_root) {
1187                 err = -ENOMEM;
1188                 goto fail_close;
1189         }
1190
1191         cleancache_init_fs(sb);
1192         sb->s_flags |= SB_ACTIVE;
1193         return 0;
1194
1195 fail_close:
1196         close_ctree(fs_info);
1197         return err;
1198 }
1199
1200 int btrfs_sync_fs(struct super_block *sb, int wait)
1201 {
1202         struct btrfs_trans_handle *trans;
1203         struct btrfs_fs_info *fs_info = btrfs_sb(sb);
1204         struct btrfs_root *root = fs_info->tree_root;
1205
1206         trace_btrfs_sync_fs(fs_info, wait);
1207
1208         if (!wait) {
1209                 filemap_flush(fs_info->btree_inode->i_mapping);
1210                 return 0;
1211         }
1212
1213         btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
1214
1215         trans = btrfs_attach_transaction_barrier(root);
1216         if (IS_ERR(trans)) {
1217                 /* no transaction, don't bother */
1218                 if (PTR_ERR(trans) == -ENOENT) {
1219                         /*
1220                          * Exit unless we have some pending changes
1221                          * that need to go through commit
1222                          */
1223                         if (fs_info->pending_changes == 0)
1224                                 return 0;
1225                         /*
1226                          * A non-blocking test if the fs is frozen. We must not
1227                          * start a new transaction here otherwise a deadlock
1228                          * happens. The pending operations are delayed to the
1229                          * next commit after thawing.
1230                          */
1231                         if (sb_start_write_trylock(sb))
1232                                 sb_end_write(sb);
1233                         else
1234                                 return 0;
1235                         trans = btrfs_start_transaction(root, 0);
1236                 }
1237                 if (IS_ERR(trans))
1238                         return PTR_ERR(trans);
1239         }
1240         return btrfs_commit_transaction(trans);
1241 }
1242
1243 static int btrfs_show_options(struct seq_file *seq, struct dentry *dentry)
1244 {
1245         struct btrfs_fs_info *info = btrfs_sb(dentry->d_sb);
1246         char *compress_type;
1247
1248         if (btrfs_test_opt(info, DEGRADED))
1249                 seq_puts(seq, ",degraded");
1250         if (btrfs_test_opt(info, NODATASUM))
1251                 seq_puts(seq, ",nodatasum");
1252         if (btrfs_test_opt(info, NODATACOW))
1253                 seq_puts(seq, ",nodatacow");
1254         if (btrfs_test_opt(info, NOBARRIER))
1255                 seq_puts(seq, ",nobarrier");
1256         if (info->max_inline != BTRFS_DEFAULT_MAX_INLINE)
1257                 seq_printf(seq, ",max_inline=%llu", info->max_inline);
1258         if (info->thread_pool_size !=  min_t(unsigned long,
1259                                              num_online_cpus() + 2, 8))
1260                 seq_printf(seq, ",thread_pool=%d", info->thread_pool_size);
1261         if (btrfs_test_opt(info, COMPRESS)) {
1262                 if (info->compress_type == BTRFS_COMPRESS_ZLIB)
1263                         compress_type = "zlib";
1264                 else if (info->compress_type == BTRFS_COMPRESS_LZO)
1265                         compress_type = "lzo";
1266                 else
1267                         compress_type = "zstd";
1268                 if (btrfs_test_opt(info, FORCE_COMPRESS))
1269                         seq_printf(seq, ",compress-force=%s", compress_type);
1270                 else
1271                         seq_printf(seq, ",compress=%s", compress_type);
1272                 if (info->compress_level)
1273                         seq_printf(seq, ":%d", info->compress_level);
1274         }
1275         if (btrfs_test_opt(info, NOSSD))
1276                 seq_puts(seq, ",nossd");
1277         if (btrfs_test_opt(info, SSD_SPREAD))
1278                 seq_puts(seq, ",ssd_spread");
1279         else if (btrfs_test_opt(info, SSD))
1280                 seq_puts(seq, ",ssd");
1281         if (btrfs_test_opt(info, NOTREELOG))
1282                 seq_puts(seq, ",notreelog");
1283         if (btrfs_test_opt(info, NOLOGREPLAY))
1284                 seq_puts(seq, ",nologreplay");
1285         if (btrfs_test_opt(info, FLUSHONCOMMIT))
1286                 seq_puts(seq, ",flushoncommit");
1287         if (btrfs_test_opt(info, DISCARD))
1288                 seq_puts(seq, ",discard");
1289         if (!(info->sb->s_flags & SB_POSIXACL))
1290                 seq_puts(seq, ",noacl");
1291         if (btrfs_test_opt(info, SPACE_CACHE))
1292                 seq_puts(seq, ",space_cache");
1293         else if (btrfs_test_opt(info, FREE_SPACE_TREE))
1294                 seq_puts(seq, ",space_cache=v2");
1295         else
1296                 seq_puts(seq, ",nospace_cache");
1297         if (btrfs_test_opt(info, RESCAN_UUID_TREE))
1298                 seq_puts(seq, ",rescan_uuid_tree");
1299         if (btrfs_test_opt(info, CLEAR_CACHE))
1300                 seq_puts(seq, ",clear_cache");
1301         if (btrfs_test_opt(info, USER_SUBVOL_RM_ALLOWED))
1302                 seq_puts(seq, ",user_subvol_rm_allowed");
1303         if (btrfs_test_opt(info, ENOSPC_DEBUG))
1304                 seq_puts(seq, ",enospc_debug");
1305         if (btrfs_test_opt(info, AUTO_DEFRAG))
1306                 seq_puts(seq, ",autodefrag");
1307         if (btrfs_test_opt(info, INODE_MAP_CACHE))
1308                 seq_puts(seq, ",inode_cache");
1309         if (btrfs_test_opt(info, SKIP_BALANCE))
1310                 seq_puts(seq, ",skip_balance");
1311 #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
1312         if (btrfs_test_opt(info, CHECK_INTEGRITY_INCLUDING_EXTENT_DATA))
1313                 seq_puts(seq, ",check_int_data");
1314         else if (btrfs_test_opt(info, CHECK_INTEGRITY))
1315                 seq_puts(seq, ",check_int");
1316         if (info->check_integrity_print_mask)
1317                 seq_printf(seq, ",check_int_print_mask=%d",
1318                                 info->check_integrity_print_mask);
1319 #endif
1320         if (info->metadata_ratio)
1321                 seq_printf(seq, ",metadata_ratio=%d",
1322                                 info->metadata_ratio);
1323         if (btrfs_test_opt(info, PANIC_ON_FATAL_ERROR))
1324                 seq_puts(seq, ",fatal_errors=panic");
1325         if (info->commit_interval != BTRFS_DEFAULT_COMMIT_INTERVAL)
1326                 seq_printf(seq, ",commit=%d", info->commit_interval);
1327 #ifdef CONFIG_BTRFS_DEBUG
1328         if (btrfs_test_opt(info, FRAGMENT_DATA))
1329                 seq_puts(seq, ",fragment=data");
1330         if (btrfs_test_opt(info, FRAGMENT_METADATA))
1331                 seq_puts(seq, ",fragment=metadata");
1332 #endif
1333         if (btrfs_test_opt(info, REF_VERIFY))
1334                 seq_puts(seq, ",ref_verify");
1335         seq_printf(seq, ",subvolid=%llu",
1336                   BTRFS_I(d_inode(dentry))->root->root_key.objectid);
1337         seq_puts(seq, ",subvol=");
1338         seq_dentry(seq, dentry, " \t\n\\");
1339         return 0;
1340 }
1341
1342 static int btrfs_test_super(struct super_block *s, void *data)
1343 {
1344         struct btrfs_fs_info *p = data;
1345         struct btrfs_fs_info *fs_info = btrfs_sb(s);
1346
1347         return fs_info->fs_devices == p->fs_devices;
1348 }
1349
1350 static int btrfs_set_super(struct super_block *s, void *data)
1351 {
1352         int err = set_anon_super(s, data);
1353         if (!err)
1354                 s->s_fs_info = data;
1355         return err;
1356 }
1357
1358 /*
1359  * subvolumes are identified by ino 256
1360  */
1361 static inline int is_subvolume_inode(struct inode *inode)
1362 {
1363         if (inode && inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)
1364                 return 1;
1365         return 0;
1366 }
1367
1368 /*
1369  * This will add subvolid=0 to the argument string while removing any subvol=
1370  * and subvolid= arguments to make sure we get the top-level root for path
1371  * walking to the subvol we want.
1372  */
1373 static char *setup_root_args(char *args)
1374 {
1375         char *buf, *dst, *sep;
1376
1377         if (!args)
1378                 return kstrdup("subvolid=0", GFP_KERNEL);
1379
1380         /* The worst case is that we add ",subvolid=0" to the end. */
1381         buf = dst = kmalloc(strlen(args) + strlen(",subvolid=0") + 1,
1382                         GFP_KERNEL);
1383         if (!buf)
1384                 return NULL;
1385
1386         while (1) {
1387                 sep = strchrnul(args, ',');
1388                 if (!strstarts(args, "subvol=") &&
1389                     !strstarts(args, "subvolid=")) {
1390                         memcpy(dst, args, sep - args);
1391                         dst += sep - args;
1392                         *dst++ = ',';
1393                 }
1394                 if (*sep)
1395                         args = sep + 1;
1396                 else
1397                         break;
1398         }
1399         strcpy(dst, "subvolid=0");
1400
1401         return buf;
1402 }
1403
1404 static struct dentry *mount_subvol(const char *subvol_name, u64 subvol_objectid,
1405                                    int flags, const char *device_name,
1406                                    char *data)
1407 {
1408         struct dentry *root;
1409         struct vfsmount *mnt = NULL;
1410         char *newargs;
1411         int ret;
1412
1413         newargs = setup_root_args(data);
1414         if (!newargs) {
1415                 root = ERR_PTR(-ENOMEM);
1416                 goto out;
1417         }
1418
1419         mnt = vfs_kern_mount(&btrfs_fs_type, flags, device_name, newargs);
1420         if (PTR_ERR_OR_ZERO(mnt) == -EBUSY) {
1421                 if (flags & SB_RDONLY) {
1422                         mnt = vfs_kern_mount(&btrfs_fs_type, flags & ~SB_RDONLY,
1423                                              device_name, newargs);
1424                 } else {
1425                         mnt = vfs_kern_mount(&btrfs_fs_type, flags | SB_RDONLY,
1426                                              device_name, newargs);
1427                         if (IS_ERR(mnt)) {
1428                                 root = ERR_CAST(mnt);
1429                                 mnt = NULL;
1430                                 goto out;
1431                         }
1432
1433                         down_write(&mnt->mnt_sb->s_umount);
1434                         ret = btrfs_remount(mnt->mnt_sb, &flags, NULL);
1435                         up_write(&mnt->mnt_sb->s_umount);
1436                         if (ret < 0) {
1437                                 root = ERR_PTR(ret);
1438                                 goto out;
1439                         }
1440                 }
1441         }
1442         if (IS_ERR(mnt)) {
1443                 root = ERR_CAST(mnt);
1444                 mnt = NULL;
1445                 goto out;
1446         }
1447
1448         if (!subvol_name) {
1449                 if (!subvol_objectid) {
1450                         ret = get_default_subvol_objectid(btrfs_sb(mnt->mnt_sb),
1451                                                           &subvol_objectid);
1452                         if (ret) {
1453                                 root = ERR_PTR(ret);
1454                                 goto out;
1455                         }
1456                 }
1457                 subvol_name = get_subvol_name_from_objectid(btrfs_sb(mnt->mnt_sb),
1458                                                             subvol_objectid);
1459                 if (IS_ERR(subvol_name)) {
1460                         root = ERR_CAST(subvol_name);
1461                         subvol_name = NULL;
1462                         goto out;
1463                 }
1464
1465         }
1466
1467         root = mount_subtree(mnt, subvol_name);
1468         /* mount_subtree() drops our reference on the vfsmount. */
1469         mnt = NULL;
1470
1471         if (!IS_ERR(root)) {
1472                 struct super_block *s = root->d_sb;
1473                 struct btrfs_fs_info *fs_info = btrfs_sb(s);
1474                 struct inode *root_inode = d_inode(root);
1475                 u64 root_objectid = BTRFS_I(root_inode)->root->root_key.objectid;
1476
1477                 ret = 0;
1478                 if (!is_subvolume_inode(root_inode)) {
1479                         btrfs_err(fs_info, "'%s' is not a valid subvolume",
1480                                subvol_name);
1481                         ret = -EINVAL;
1482                 }
1483                 if (subvol_objectid && root_objectid != subvol_objectid) {
1484                         /*
1485                          * This will also catch a race condition where a
1486                          * subvolume which was passed by ID is renamed and
1487                          * another subvolume is renamed over the old location.
1488                          */
1489                         btrfs_err(fs_info,
1490                                   "subvol '%s' does not match subvolid %llu",
1491                                   subvol_name, subvol_objectid);
1492                         ret = -EINVAL;
1493                 }
1494                 if (ret) {
1495                         dput(root);
1496                         root = ERR_PTR(ret);
1497                         deactivate_locked_super(s);
1498                 }
1499         }
1500
1501 out:
1502         mntput(mnt);
1503         kfree(newargs);
1504         kfree(subvol_name);
1505         return root;
1506 }
1507
1508 static int parse_security_options(char *orig_opts,
1509                                   struct security_mnt_opts *sec_opts)
1510 {
1511         char *secdata = NULL;
1512         int ret = 0;
1513
1514         secdata = alloc_secdata();
1515         if (!secdata)
1516                 return -ENOMEM;
1517         ret = security_sb_copy_data(orig_opts, secdata);
1518         if (ret) {
1519                 free_secdata(secdata);
1520                 return ret;
1521         }
1522         ret = security_sb_parse_opts_str(secdata, sec_opts);
1523         free_secdata(secdata);
1524         return ret;
1525 }
1526
1527 static int setup_security_options(struct btrfs_fs_info *fs_info,
1528                                   struct super_block *sb,
1529                                   struct security_mnt_opts *sec_opts)
1530 {
1531         int ret = 0;
1532
1533         /*
1534          * Call security_sb_set_mnt_opts() to check whether new sec_opts
1535          * is valid.
1536          */
1537         ret = security_sb_set_mnt_opts(sb, sec_opts, 0, NULL);
1538         if (ret)
1539                 return ret;
1540
1541 #ifdef CONFIG_SECURITY
1542         if (!fs_info->security_opts.num_mnt_opts) {
1543                 /* first time security setup, copy sec_opts to fs_info */
1544                 memcpy(&fs_info->security_opts, sec_opts, sizeof(*sec_opts));
1545         } else {
1546                 /*
1547                  * Since SELinux (the only one supporting security_mnt_opts)
1548                  * does NOT support changing context during remount/mount of
1549                  * the same sb, this must be the same or part of the same
1550                  * security options, just free it.
1551                  */
1552                 security_free_mnt_opts(sec_opts);
1553         }
1554 #endif
1555         return ret;
1556 }
1557
1558 /*
1559  * Find a superblock for the given device / mount point.
1560  *
1561  * Note:  This is based on get_sb_bdev from fs/super.c with a few additions
1562  *        for multiple device setup.  Make sure to keep it in sync.
1563  */
1564 static struct dentry *btrfs_mount(struct file_system_type *fs_type, int flags,
1565                 const char *device_name, void *data)
1566 {
1567         struct block_device *bdev = NULL;
1568         struct super_block *s;
1569         struct btrfs_fs_devices *fs_devices = NULL;
1570         struct btrfs_fs_info *fs_info = NULL;
1571         struct security_mnt_opts new_sec_opts;
1572         fmode_t mode = FMODE_READ;
1573         char *subvol_name = NULL;
1574         u64 subvol_objectid = 0;
1575         int error = 0;
1576
1577         if (!(flags & SB_RDONLY))
1578                 mode |= FMODE_WRITE;
1579
1580         error = btrfs_parse_early_options(data, mode, fs_type,
1581                                           &subvol_name, &subvol_objectid,
1582                                           &fs_devices);
1583         if (error) {
1584                 kfree(subvol_name);
1585                 return ERR_PTR(error);
1586         }
1587
1588         if (subvol_name || subvol_objectid != BTRFS_FS_TREE_OBJECTID) {
1589                 /* mount_subvol() will free subvol_name. */
1590                 return mount_subvol(subvol_name, subvol_objectid, flags,
1591                                     device_name, data);
1592         }
1593
1594         security_init_mnt_opts(&new_sec_opts);
1595         if (data) {
1596                 error = parse_security_options(data, &new_sec_opts);
1597                 if (error)
1598                         return ERR_PTR(error);
1599         }
1600
1601         error = btrfs_scan_one_device(device_name, mode, fs_type, &fs_devices);
1602         if (error)
1603                 goto error_sec_opts;
1604
1605         /*
1606          * Setup a dummy root and fs_info for test/set super.  This is because
1607          * we don't actually fill this stuff out until open_ctree, but we need
1608          * it for searching for existing supers, so this lets us do that and
1609          * then open_ctree will properly initialize everything later.
1610          */
1611         fs_info = kzalloc(sizeof(struct btrfs_fs_info), GFP_KERNEL);
1612         if (!fs_info) {
1613                 error = -ENOMEM;
1614                 goto error_sec_opts;
1615         }
1616
1617         fs_info->fs_devices = fs_devices;
1618
1619         fs_info->super_copy = kzalloc(BTRFS_SUPER_INFO_SIZE, GFP_KERNEL);
1620         fs_info->super_for_commit = kzalloc(BTRFS_SUPER_INFO_SIZE, GFP_KERNEL);
1621         security_init_mnt_opts(&fs_info->security_opts);
1622         if (!fs_info->super_copy || !fs_info->super_for_commit) {
1623                 error = -ENOMEM;
1624                 goto error_fs_info;
1625         }
1626
1627         error = btrfs_open_devices(fs_devices, mode, fs_type);
1628         if (error)
1629                 goto error_fs_info;
1630
1631         if (!(flags & SB_RDONLY) && fs_devices->rw_devices == 0) {
1632                 error = -EACCES;
1633                 goto error_close_devices;
1634         }
1635
1636         bdev = fs_devices->latest_bdev;
1637         s = sget(fs_type, btrfs_test_super, btrfs_set_super, flags | SB_NOSEC,
1638                  fs_info);
1639         if (IS_ERR(s)) {
1640                 error = PTR_ERR(s);
1641                 goto error_close_devices;
1642         }
1643
1644         if (s->s_root) {
1645                 btrfs_close_devices(fs_devices);
1646                 free_fs_info(fs_info);
1647                 if ((flags ^ s->s_flags) & SB_RDONLY)
1648                         error = -EBUSY;
1649         } else {
1650                 snprintf(s->s_id, sizeof(s->s_id), "%pg", bdev);
1651                 btrfs_sb(s)->bdev_holder = fs_type;
1652                 error = btrfs_fill_super(s, fs_devices, data);
1653         }
1654         if (error) {
1655                 deactivate_locked_super(s);
1656                 goto error_sec_opts;
1657         }
1658
1659         fs_info = btrfs_sb(s);
1660         error = setup_security_options(fs_info, s, &new_sec_opts);
1661         if (error) {
1662                 deactivate_locked_super(s);
1663                 goto error_sec_opts;
1664         }
1665
1666         return dget(s->s_root);
1667
1668 error_close_devices:
1669         btrfs_close_devices(fs_devices);
1670 error_fs_info:
1671         free_fs_info(fs_info);
1672 error_sec_opts:
1673         security_free_mnt_opts(&new_sec_opts);
1674         return ERR_PTR(error);
1675 }
1676
1677 static void btrfs_resize_thread_pool(struct btrfs_fs_info *fs_info,
1678                                      int new_pool_size, int old_pool_size)
1679 {
1680         if (new_pool_size == old_pool_size)
1681                 return;
1682
1683         fs_info->thread_pool_size = new_pool_size;
1684
1685         btrfs_info(fs_info, "resize thread pool %d -> %d",
1686                old_pool_size, new_pool_size);
1687
1688         btrfs_workqueue_set_max(fs_info->workers, new_pool_size);
1689         btrfs_workqueue_set_max(fs_info->delalloc_workers, new_pool_size);
1690         btrfs_workqueue_set_max(fs_info->submit_workers, new_pool_size);
1691         btrfs_workqueue_set_max(fs_info->caching_workers, new_pool_size);
1692         btrfs_workqueue_set_max(fs_info->endio_workers, new_pool_size);
1693         btrfs_workqueue_set_max(fs_info->endio_meta_workers, new_pool_size);
1694         btrfs_workqueue_set_max(fs_info->endio_meta_write_workers,
1695                                 new_pool_size);
1696         btrfs_workqueue_set_max(fs_info->endio_write_workers, new_pool_size);
1697         btrfs_workqueue_set_max(fs_info->endio_freespace_worker, new_pool_size);
1698         btrfs_workqueue_set_max(fs_info->delayed_workers, new_pool_size);
1699         btrfs_workqueue_set_max(fs_info->readahead_workers, new_pool_size);
1700         btrfs_workqueue_set_max(fs_info->scrub_wr_completion_workers,
1701                                 new_pool_size);
1702 }
1703
1704 static inline void btrfs_remount_prepare(struct btrfs_fs_info *fs_info)
1705 {
1706         set_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state);
1707 }
1708
1709 static inline void btrfs_remount_begin(struct btrfs_fs_info *fs_info,
1710                                        unsigned long old_opts, int flags)
1711 {
1712         if (btrfs_raw_test_opt(old_opts, AUTO_DEFRAG) &&
1713             (!btrfs_raw_test_opt(fs_info->mount_opt, AUTO_DEFRAG) ||
1714              (flags & SB_RDONLY))) {
1715                 /* wait for any defraggers to finish */
1716                 wait_event(fs_info->transaction_wait,
1717                            (atomic_read(&fs_info->defrag_running) == 0));
1718                 if (flags & SB_RDONLY)
1719                         sync_filesystem(fs_info->sb);
1720         }
1721 }
1722
1723 static inline void btrfs_remount_cleanup(struct btrfs_fs_info *fs_info,
1724                                          unsigned long old_opts)
1725 {
1726         /*
1727          * We need to cleanup all defragable inodes if the autodefragment is
1728          * close or the filesystem is read only.
1729          */
1730         if (btrfs_raw_test_opt(old_opts, AUTO_DEFRAG) &&
1731             (!btrfs_raw_test_opt(fs_info->mount_opt, AUTO_DEFRAG) || sb_rdonly(fs_info->sb))) {
1732                 btrfs_cleanup_defrag_inodes(fs_info);
1733         }
1734
1735         clear_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state);
1736 }
1737
1738 static int btrfs_remount(struct super_block *sb, int *flags, char *data)
1739 {
1740         struct btrfs_fs_info *fs_info = btrfs_sb(sb);
1741         struct btrfs_root *root = fs_info->tree_root;
1742         unsigned old_flags = sb->s_flags;
1743         unsigned long old_opts = fs_info->mount_opt;
1744         unsigned long old_compress_type = fs_info->compress_type;
1745         u64 old_max_inline = fs_info->max_inline;
1746         int old_thread_pool_size = fs_info->thread_pool_size;
1747         unsigned int old_metadata_ratio = fs_info->metadata_ratio;
1748         int ret;
1749
1750         sync_filesystem(sb);
1751         btrfs_remount_prepare(fs_info);
1752
1753         if (data) {
1754                 struct security_mnt_opts new_sec_opts;
1755
1756                 security_init_mnt_opts(&new_sec_opts);
1757                 ret = parse_security_options(data, &new_sec_opts);
1758                 if (ret)
1759                         goto restore;
1760                 ret = setup_security_options(fs_info, sb,
1761                                              &new_sec_opts);
1762                 if (ret) {
1763                         security_free_mnt_opts(&new_sec_opts);
1764                         goto restore;
1765                 }
1766         }
1767
1768         ret = btrfs_parse_options(fs_info, data, *flags);
1769         if (ret) {
1770                 ret = -EINVAL;
1771                 goto restore;
1772         }
1773
1774         btrfs_remount_begin(fs_info, old_opts, *flags);
1775         btrfs_resize_thread_pool(fs_info,
1776                 fs_info->thread_pool_size, old_thread_pool_size);
1777
1778         if ((bool)(*flags & SB_RDONLY) == sb_rdonly(sb))
1779                 goto out;
1780
1781         if (*flags & SB_RDONLY) {
1782                 /*
1783                  * this also happens on 'umount -rf' or on shutdown, when
1784                  * the filesystem is busy.
1785                  */
1786                 cancel_work_sync(&fs_info->async_reclaim_work);
1787
1788                 /* wait for the uuid_scan task to finish */
1789                 down(&fs_info->uuid_tree_rescan_sem);
1790                 /* avoid complains from lockdep et al. */
1791                 up(&fs_info->uuid_tree_rescan_sem);
1792
1793                 sb->s_flags |= SB_RDONLY;
1794
1795                 /*
1796                  * Setting SB_RDONLY will put the cleaner thread to
1797                  * sleep at the next loop if it's already active.
1798                  * If it's already asleep, we'll leave unused block
1799                  * groups on disk until we're mounted read-write again
1800                  * unless we clean them up here.
1801                  */
1802                 btrfs_delete_unused_bgs(fs_info);
1803
1804                 btrfs_dev_replace_suspend_for_unmount(fs_info);
1805                 btrfs_scrub_cancel(fs_info);
1806                 btrfs_pause_balance(fs_info);
1807
1808                 ret = btrfs_commit_super(fs_info);
1809                 if (ret)
1810                         goto restore;
1811         } else {
1812                 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
1813                         btrfs_err(fs_info,
1814                                 "Remounting read-write after error is not allowed");
1815                         ret = -EINVAL;
1816                         goto restore;
1817                 }
1818                 if (fs_info->fs_devices->rw_devices == 0) {
1819                         ret = -EACCES;
1820                         goto restore;
1821                 }
1822
1823                 if (!btrfs_check_rw_degradable(fs_info)) {
1824                         btrfs_warn(fs_info,
1825                                 "too many missing devices, writeable remount is not allowed");
1826                         ret = -EACCES;
1827                         goto restore;
1828                 }
1829
1830                 if (btrfs_super_log_root(fs_info->super_copy) != 0) {
1831                         ret = -EINVAL;
1832                         goto restore;
1833                 }
1834
1835                 ret = btrfs_cleanup_fs_roots(fs_info);
1836                 if (ret)
1837                         goto restore;
1838
1839                 /* recover relocation */
1840                 mutex_lock(&fs_info->cleaner_mutex);
1841                 ret = btrfs_recover_relocation(root);
1842                 mutex_unlock(&fs_info->cleaner_mutex);
1843                 if (ret)
1844                         goto restore;
1845
1846                 ret = btrfs_resume_balance_async(fs_info);
1847                 if (ret)
1848                         goto restore;
1849
1850                 ret = btrfs_resume_dev_replace_async(fs_info);
1851                 if (ret) {
1852                         btrfs_warn(fs_info, "failed to resume dev_replace");
1853                         goto restore;
1854                 }
1855
1856                 btrfs_qgroup_rescan_resume(fs_info);
1857
1858                 if (!fs_info->uuid_root) {
1859                         btrfs_info(fs_info, "creating UUID tree");
1860                         ret = btrfs_create_uuid_tree(fs_info);
1861                         if (ret) {
1862                                 btrfs_warn(fs_info,
1863                                            "failed to create the UUID tree %d",
1864                                            ret);
1865                                 goto restore;
1866                         }
1867                 }
1868                 sb->s_flags &= ~SB_RDONLY;
1869
1870                 set_bit(BTRFS_FS_OPEN, &fs_info->flags);
1871         }
1872 out:
1873         wake_up_process(fs_info->transaction_kthread);
1874         btrfs_remount_cleanup(fs_info, old_opts);
1875         return 0;
1876
1877 restore:
1878         /* We've hit an error - don't reset SB_RDONLY */
1879         if (sb_rdonly(sb))
1880                 old_flags |= SB_RDONLY;
1881         sb->s_flags = old_flags;
1882         fs_info->mount_opt = old_opts;
1883         fs_info->compress_type = old_compress_type;
1884         fs_info->max_inline = old_max_inline;
1885         btrfs_resize_thread_pool(fs_info,
1886                 old_thread_pool_size, fs_info->thread_pool_size);
1887         fs_info->metadata_ratio = old_metadata_ratio;
1888         btrfs_remount_cleanup(fs_info, old_opts);
1889         return ret;
1890 }
1891
1892 /* Used to sort the devices by max_avail(descending sort) */
1893 static int btrfs_cmp_device_free_bytes(const void *dev_info1,
1894                                        const void *dev_info2)
1895 {
1896         if (((struct btrfs_device_info *)dev_info1)->max_avail >
1897             ((struct btrfs_device_info *)dev_info2)->max_avail)
1898                 return -1;
1899         else if (((struct btrfs_device_info *)dev_info1)->max_avail <
1900                  ((struct btrfs_device_info *)dev_info2)->max_avail)
1901                 return 1;
1902         else
1903         return 0;
1904 }
1905
1906 /*
1907  * sort the devices by max_avail, in which max free extent size of each device
1908  * is stored.(Descending Sort)
1909  */
1910 static inline void btrfs_descending_sort_devices(
1911                                         struct btrfs_device_info *devices,
1912                                         size_t nr_devices)
1913 {
1914         sort(devices, nr_devices, sizeof(struct btrfs_device_info),
1915              btrfs_cmp_device_free_bytes, NULL);
1916 }
1917
1918 /*
1919  * The helper to calc the free space on the devices that can be used to store
1920  * file data.
1921  */
1922 static int btrfs_calc_avail_data_space(struct btrfs_fs_info *fs_info,
1923                                        u64 *free_bytes)
1924 {
1925         struct btrfs_device_info *devices_info;
1926         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
1927         struct btrfs_device *device;
1928         u64 skip_space;
1929         u64 type;
1930         u64 avail_space;
1931         u64 min_stripe_size;
1932         int min_stripes = 1, num_stripes = 1;
1933         int i = 0, nr_devices;
1934
1935         /*
1936          * We aren't under the device list lock, so this is racy-ish, but good
1937          * enough for our purposes.
1938          */
1939         nr_devices = fs_info->fs_devices->open_devices;
1940         if (!nr_devices) {
1941                 smp_mb();
1942                 nr_devices = fs_info->fs_devices->open_devices;
1943                 ASSERT(nr_devices);
1944                 if (!nr_devices) {
1945                         *free_bytes = 0;
1946                         return 0;
1947                 }
1948         }
1949
1950         devices_info = kmalloc_array(nr_devices, sizeof(*devices_info),
1951                                GFP_KERNEL);
1952         if (!devices_info)
1953                 return -ENOMEM;
1954
1955         /* calc min stripe number for data space allocation */
1956         type = btrfs_data_alloc_profile(fs_info);
1957         if (type & BTRFS_BLOCK_GROUP_RAID0) {
1958                 min_stripes = 2;
1959                 num_stripes = nr_devices;
1960         } else if (type & BTRFS_BLOCK_GROUP_RAID1) {
1961                 min_stripes = 2;
1962                 num_stripes = 2;
1963         } else if (type & BTRFS_BLOCK_GROUP_RAID10) {
1964                 min_stripes = 4;
1965                 num_stripes = 4;
1966         }
1967
1968         if (type & BTRFS_BLOCK_GROUP_DUP)
1969                 min_stripe_size = 2 * BTRFS_STRIPE_LEN;
1970         else
1971                 min_stripe_size = BTRFS_STRIPE_LEN;
1972
1973         rcu_read_lock();
1974         list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
1975                 if (!device->in_fs_metadata || !device->bdev ||
1976                     device->is_tgtdev_for_dev_replace)
1977                         continue;
1978
1979                 if (i >= nr_devices)
1980                         break;
1981
1982                 avail_space = device->total_bytes - device->bytes_used;
1983
1984                 /* align with stripe_len */
1985                 avail_space = div_u64(avail_space, BTRFS_STRIPE_LEN);
1986                 avail_space *= BTRFS_STRIPE_LEN;
1987
1988                 /*
1989                  * In order to avoid overwriting the superblock on the drive,
1990                  * btrfs starts at an offset of at least 1MB when doing chunk
1991                  * allocation.
1992                  */
1993                 skip_space = SZ_1M;
1994
1995                 /*
1996                  * we can use the free space in [0, skip_space - 1], subtract
1997                  * it from the total.
1998                  */
1999                 if (avail_space && avail_space >= skip_space)
2000                         avail_space -= skip_space;
2001                 else
2002                         avail_space = 0;
2003
2004                 if (avail_space < min_stripe_size)
2005                         continue;
2006
2007                 devices_info[i].dev = device;
2008                 devices_info[i].max_avail = avail_space;
2009
2010                 i++;
2011         }
2012         rcu_read_unlock();
2013
2014         nr_devices = i;
2015
2016         btrfs_descending_sort_devices(devices_info, nr_devices);
2017
2018         i = nr_devices - 1;
2019         avail_space = 0;
2020         while (nr_devices >= min_stripes) {
2021                 if (num_stripes > nr_devices)
2022                         num_stripes = nr_devices;
2023
2024                 if (devices_info[i].max_avail >= min_stripe_size) {
2025                         int j;
2026                         u64 alloc_size;
2027
2028                         avail_space += devices_info[i].max_avail * num_stripes;
2029                         alloc_size = devices_info[i].max_avail;
2030                         for (j = i + 1 - num_stripes; j <= i; j++)
2031                                 devices_info[j].max_avail -= alloc_size;
2032                 }
2033                 i--;
2034                 nr_devices--;
2035         }
2036
2037         kfree(devices_info);
2038         *free_bytes = avail_space;
2039         return 0;
2040 }
2041
2042 /*
2043  * Calculate numbers for 'df', pessimistic in case of mixed raid profiles.
2044  *
2045  * If there's a redundant raid level at DATA block groups, use the respective
2046  * multiplier to scale the sizes.
2047  *
2048  * Unused device space usage is based on simulating the chunk allocator
2049  * algorithm that respects the device sizes and order of allocations.  This is
2050  * a close approximation of the actual use but there are other factors that may
2051  * change the result (like a new metadata chunk).
2052  *
2053  * If metadata is exhausted, f_bavail will be 0.
2054  */
2055 static int btrfs_statfs(struct dentry *dentry, struct kstatfs *buf)
2056 {
2057         struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
2058         struct btrfs_super_block *disk_super = fs_info->super_copy;
2059         struct list_head *head = &fs_info->space_info;
2060         struct btrfs_space_info *found;
2061         u64 total_used = 0;
2062         u64 total_free_data = 0;
2063         u64 total_free_meta = 0;
2064         int bits = dentry->d_sb->s_blocksize_bits;
2065         __be32 *fsid = (__be32 *)fs_info->fsid;
2066         unsigned factor = 1;
2067         struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
2068         int ret;
2069         u64 thresh = 0;
2070         int mixed = 0;
2071
2072         rcu_read_lock();
2073         list_for_each_entry_rcu(found, head, list) {
2074                 if (found->flags & BTRFS_BLOCK_GROUP_DATA) {
2075                         int i;
2076
2077                         total_free_data += found->disk_total - found->disk_used;
2078                         total_free_data -=
2079                                 btrfs_account_ro_block_groups_free_space(found);
2080
2081                         for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
2082                                 if (!list_empty(&found->block_groups[i])) {
2083                                         switch (i) {
2084                                         case BTRFS_RAID_DUP:
2085                                         case BTRFS_RAID_RAID1:
2086                                         case BTRFS_RAID_RAID10:
2087                                                 factor = 2;
2088                                         }
2089                                 }
2090                         }
2091                 }
2092
2093                 /*
2094                  * Metadata in mixed block goup profiles are accounted in data
2095                  */
2096                 if (!mixed && found->flags & BTRFS_BLOCK_GROUP_METADATA) {
2097                         if (found->flags & BTRFS_BLOCK_GROUP_DATA)
2098                                 mixed = 1;
2099                         else
2100                                 total_free_meta += found->disk_total -
2101                                         found->disk_used;
2102                 }
2103
2104                 total_used += found->disk_used;
2105         }
2106
2107         rcu_read_unlock();
2108
2109         buf->f_blocks = div_u64(btrfs_super_total_bytes(disk_super), factor);
2110         buf->f_blocks >>= bits;
2111         buf->f_bfree = buf->f_blocks - (div_u64(total_used, factor) >> bits);
2112
2113         /* Account global block reserve as used, it's in logical size already */
2114         spin_lock(&block_rsv->lock);
2115         /* Mixed block groups accounting is not byte-accurate, avoid overflow */
2116         if (buf->f_bfree >= block_rsv->size >> bits)
2117                 buf->f_bfree -= block_rsv->size >> bits;
2118         else
2119                 buf->f_bfree = 0;
2120         spin_unlock(&block_rsv->lock);
2121
2122         buf->f_bavail = div_u64(total_free_data, factor);
2123         ret = btrfs_calc_avail_data_space(fs_info, &total_free_data);
2124         if (ret)
2125                 return ret;
2126         buf->f_bavail += div_u64(total_free_data, factor);
2127         buf->f_bavail = buf->f_bavail >> bits;
2128
2129         /*
2130          * We calculate the remaining metadata space minus global reserve. If
2131          * this is (supposedly) smaller than zero, there's no space. But this
2132          * does not hold in practice, the exhausted state happens where's still
2133          * some positive delta. So we apply some guesswork and compare the
2134          * delta to a 4M threshold.  (Practically observed delta was ~2M.)
2135          *
2136          * We probably cannot calculate the exact threshold value because this
2137          * depends on the internal reservations requested by various
2138          * operations, so some operations that consume a few metadata will
2139          * succeed even if the Avail is zero. But this is better than the other
2140          * way around.
2141          */
2142         thresh = SZ_4M;
2143
2144         if (!mixed && total_free_meta - thresh < block_rsv->size)
2145                 buf->f_bavail = 0;
2146
2147         buf->f_type = BTRFS_SUPER_MAGIC;
2148         buf->f_bsize = dentry->d_sb->s_blocksize;
2149         buf->f_namelen = BTRFS_NAME_LEN;
2150
2151         /* We treat it as constant endianness (it doesn't matter _which_)
2152            because we want the fsid to come out the same whether mounted
2153            on a big-endian or little-endian host */
2154         buf->f_fsid.val[0] = be32_to_cpu(fsid[0]) ^ be32_to_cpu(fsid[2]);
2155         buf->f_fsid.val[1] = be32_to_cpu(fsid[1]) ^ be32_to_cpu(fsid[3]);
2156         /* Mask in the root object ID too, to disambiguate subvols */
2157         buf->f_fsid.val[0] ^= BTRFS_I(d_inode(dentry))->root->objectid >> 32;
2158         buf->f_fsid.val[1] ^= BTRFS_I(d_inode(dentry))->root->objectid;
2159
2160         return 0;
2161 }
2162
2163 static void btrfs_kill_super(struct super_block *sb)
2164 {
2165         struct btrfs_fs_info *fs_info = btrfs_sb(sb);
2166         kill_anon_super(sb);
2167         free_fs_info(fs_info);
2168 }
2169
2170 static struct file_system_type btrfs_fs_type = {
2171         .owner          = THIS_MODULE,
2172         .name           = "btrfs",
2173         .mount          = btrfs_mount,
2174         .kill_sb        = btrfs_kill_super,
2175         .fs_flags       = FS_REQUIRES_DEV | FS_BINARY_MOUNTDATA,
2176 };
2177 MODULE_ALIAS_FS("btrfs");
2178
2179 static int btrfs_control_open(struct inode *inode, struct file *file)
2180 {
2181         /*
2182          * The control file's private_data is used to hold the
2183          * transaction when it is started and is used to keep
2184          * track of whether a transaction is already in progress.
2185          */
2186         file->private_data = NULL;
2187         return 0;
2188 }
2189
2190 /*
2191  * used by btrfsctl to scan devices when no FS is mounted
2192  */
2193 static long btrfs_control_ioctl(struct file *file, unsigned int cmd,
2194                                 unsigned long arg)
2195 {
2196         struct btrfs_ioctl_vol_args *vol;
2197         struct btrfs_fs_devices *fs_devices;
2198         int ret = -ENOTTY;
2199
2200         if (!capable(CAP_SYS_ADMIN))
2201                 return -EPERM;
2202
2203         vol = memdup_user((void __user *)arg, sizeof(*vol));
2204         if (IS_ERR(vol))
2205                 return PTR_ERR(vol);
2206
2207         switch (cmd) {
2208         case BTRFS_IOC_SCAN_DEV:
2209                 ret = btrfs_scan_one_device(vol->name, FMODE_READ,
2210                                             &btrfs_fs_type, &fs_devices);
2211                 break;
2212         case BTRFS_IOC_DEVICES_READY:
2213                 ret = btrfs_scan_one_device(vol->name, FMODE_READ,
2214                                             &btrfs_fs_type, &fs_devices);
2215                 if (ret)
2216                         break;
2217                 ret = !(fs_devices->num_devices == fs_devices->total_devices);
2218                 break;
2219         case BTRFS_IOC_GET_SUPPORTED_FEATURES:
2220                 ret = btrfs_ioctl_get_supported_features((void __user*)arg);
2221                 break;
2222         }
2223
2224         kfree(vol);
2225         return ret;
2226 }
2227
2228 static int btrfs_freeze(struct super_block *sb)
2229 {
2230         struct btrfs_trans_handle *trans;
2231         struct btrfs_fs_info *fs_info = btrfs_sb(sb);
2232         struct btrfs_root *root = fs_info->tree_root;
2233
2234         set_bit(BTRFS_FS_FROZEN, &fs_info->flags);
2235         /*
2236          * We don't need a barrier here, we'll wait for any transaction that
2237          * could be in progress on other threads (and do delayed iputs that
2238          * we want to avoid on a frozen filesystem), or do the commit
2239          * ourselves.
2240          */
2241         trans = btrfs_attach_transaction_barrier(root);
2242         if (IS_ERR(trans)) {
2243                 /* no transaction, don't bother */
2244                 if (PTR_ERR(trans) == -ENOENT)
2245                         return 0;
2246                 return PTR_ERR(trans);
2247         }
2248         return btrfs_commit_transaction(trans);
2249 }
2250
2251 static int btrfs_unfreeze(struct super_block *sb)
2252 {
2253         struct btrfs_fs_info *fs_info = btrfs_sb(sb);
2254
2255         clear_bit(BTRFS_FS_FROZEN, &fs_info->flags);
2256         return 0;
2257 }
2258
2259 static int btrfs_show_devname(struct seq_file *m, struct dentry *root)
2260 {
2261         struct btrfs_fs_info *fs_info = btrfs_sb(root->d_sb);
2262         struct btrfs_fs_devices *cur_devices;
2263         struct btrfs_device *dev, *first_dev = NULL;
2264         struct list_head *head;
2265         struct rcu_string *name;
2266
2267         mutex_lock(&fs_info->fs_devices->device_list_mutex);
2268         cur_devices = fs_info->fs_devices;
2269         while (cur_devices) {
2270                 head = &cur_devices->devices;
2271                 list_for_each_entry(dev, head, dev_list) {
2272                         if (dev->missing)
2273                                 continue;
2274                         if (!dev->name)
2275                                 continue;
2276                         if (!first_dev || dev->devid < first_dev->devid)
2277                                 first_dev = dev;
2278                 }
2279                 cur_devices = cur_devices->seed;
2280         }
2281
2282         if (first_dev) {
2283                 rcu_read_lock();
2284                 name = rcu_dereference(first_dev->name);
2285                 seq_escape(m, name->str, " \t\n\\");
2286                 rcu_read_unlock();
2287         } else {
2288                 WARN_ON(1);
2289         }
2290         mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2291         return 0;
2292 }
2293
2294 static const struct super_operations btrfs_super_ops = {
2295         .drop_inode     = btrfs_drop_inode,
2296         .evict_inode    = btrfs_evict_inode,
2297         .put_super      = btrfs_put_super,
2298         .sync_fs        = btrfs_sync_fs,
2299         .show_options   = btrfs_show_options,
2300         .show_devname   = btrfs_show_devname,
2301         .write_inode    = btrfs_write_inode,
2302         .alloc_inode    = btrfs_alloc_inode,
2303         .destroy_inode  = btrfs_destroy_inode,
2304         .statfs         = btrfs_statfs,
2305         .remount_fs     = btrfs_remount,
2306         .freeze_fs      = btrfs_freeze,
2307         .unfreeze_fs    = btrfs_unfreeze,
2308 };
2309
2310 static const struct file_operations btrfs_ctl_fops = {
2311         .open = btrfs_control_open,
2312         .unlocked_ioctl  = btrfs_control_ioctl,
2313         .compat_ioctl = btrfs_control_ioctl,
2314         .owner   = THIS_MODULE,
2315         .llseek = noop_llseek,
2316 };
2317
2318 static struct miscdevice btrfs_misc = {
2319         .minor          = BTRFS_MINOR,
2320         .name           = "btrfs-control",
2321         .fops           = &btrfs_ctl_fops
2322 };
2323
2324 MODULE_ALIAS_MISCDEV(BTRFS_MINOR);
2325 MODULE_ALIAS("devname:btrfs-control");
2326
2327 static int btrfs_interface_init(void)
2328 {
2329         return misc_register(&btrfs_misc);
2330 }
2331
2332 static void btrfs_interface_exit(void)
2333 {
2334         misc_deregister(&btrfs_misc);
2335 }
2336
2337 static void btrfs_print_mod_info(void)
2338 {
2339         pr_info("Btrfs loaded, crc32c=%s"
2340 #ifdef CONFIG_BTRFS_DEBUG
2341                         ", debug=on"
2342 #endif
2343 #ifdef CONFIG_BTRFS_ASSERT
2344                         ", assert=on"
2345 #endif
2346 #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
2347                         ", integrity-checker=on"
2348 #endif
2349 #ifdef CONFIG_BTRFS_FS_REF_VERIFY
2350                         ", ref-verify=on"
2351 #endif
2352                         "\n",
2353                         btrfs_crc32c_impl());
2354 }
2355
2356 static int __init init_btrfs_fs(void)
2357 {
2358         int err;
2359
2360         err = btrfs_hash_init();
2361         if (err)
2362                 return err;
2363
2364         btrfs_props_init();
2365
2366         err = btrfs_init_sysfs();
2367         if (err)
2368                 goto free_hash;
2369
2370         btrfs_init_compress();
2371
2372         err = btrfs_init_cachep();
2373         if (err)
2374                 goto free_compress;
2375
2376         err = extent_io_init();
2377         if (err)
2378                 goto free_cachep;
2379
2380         err = extent_map_init();
2381         if (err)
2382                 goto free_extent_io;
2383
2384         err = ordered_data_init();
2385         if (err)
2386                 goto free_extent_map;
2387
2388         err = btrfs_delayed_inode_init();
2389         if (err)
2390                 goto free_ordered_data;
2391
2392         err = btrfs_auto_defrag_init();
2393         if (err)
2394                 goto free_delayed_inode;
2395
2396         err = btrfs_delayed_ref_init();
2397         if (err)
2398                 goto free_auto_defrag;
2399
2400         err = btrfs_prelim_ref_init();
2401         if (err)
2402                 goto free_delayed_ref;
2403
2404         err = btrfs_end_io_wq_init();
2405         if (err)
2406                 goto free_prelim_ref;
2407
2408         err = btrfs_interface_init();
2409         if (err)
2410                 goto free_end_io_wq;
2411
2412         btrfs_init_lockdep();
2413
2414         btrfs_print_mod_info();
2415
2416         err = btrfs_run_sanity_tests();
2417         if (err)
2418                 goto unregister_ioctl;
2419
2420         err = register_filesystem(&btrfs_fs_type);
2421         if (err)
2422                 goto unregister_ioctl;
2423
2424         return 0;
2425
2426 unregister_ioctl:
2427         btrfs_interface_exit();
2428 free_end_io_wq:
2429         btrfs_end_io_wq_exit();
2430 free_prelim_ref:
2431         btrfs_prelim_ref_exit();
2432 free_delayed_ref:
2433         btrfs_delayed_ref_exit();
2434 free_auto_defrag:
2435         btrfs_auto_defrag_exit();
2436 free_delayed_inode:
2437         btrfs_delayed_inode_exit();
2438 free_ordered_data:
2439         ordered_data_exit();
2440 free_extent_map:
2441         extent_map_exit();
2442 free_extent_io:
2443         extent_io_exit();
2444 free_cachep:
2445         btrfs_destroy_cachep();
2446 free_compress:
2447         btrfs_exit_compress();
2448         btrfs_exit_sysfs();
2449 free_hash:
2450         btrfs_hash_exit();
2451         return err;
2452 }
2453
2454 static void __exit exit_btrfs_fs(void)
2455 {
2456         btrfs_destroy_cachep();
2457         btrfs_delayed_ref_exit();
2458         btrfs_auto_defrag_exit();
2459         btrfs_delayed_inode_exit();
2460         btrfs_prelim_ref_exit();
2461         ordered_data_exit();
2462         extent_map_exit();
2463         extent_io_exit();
2464         btrfs_interface_exit();
2465         btrfs_end_io_wq_exit();
2466         unregister_filesystem(&btrfs_fs_type);
2467         btrfs_exit_sysfs();
2468         btrfs_cleanup_fs_uuids();
2469         btrfs_exit_compress();
2470         btrfs_hash_exit();
2471 }
2472
2473 late_initcall(init_btrfs_fs);
2474 module_exit(exit_btrfs_fs)
2475
2476 MODULE_LICENSE("GPL");