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