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