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