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