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