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/ratelimit.h>
27 #include <linux/crc32c.h>
28 #include <linux/btrfs.h>
29 #include <linux/security.h>
30 #include <linux/fs_parser.h>
31 #include "messages.h"
32 #include "delayed-inode.h"
33 #include "ctree.h"
34 #include "disk-io.h"
35 #include "transaction.h"
36 #include "btrfs_inode.h"
37 #include "direct-io.h"
38 #include "props.h"
39 #include "xattr.h"
40 #include "bio.h"
41 #include "export.h"
42 #include "compression.h"
43 #include "dev-replace.h"
44 #include "free-space-cache.h"
45 #include "backref.h"
46 #include "space-info.h"
47 #include "sysfs.h"
48 #include "zoned.h"
49 #include "tests/btrfs-tests.h"
50 #include "block-group.h"
51 #include "discard.h"
52 #include "qgroup.h"
53 #include "raid56.h"
54 #include "fs.h"
55 #include "accessors.h"
56 #include "defrag.h"
57 #include "dir-item.h"
58 #include "ioctl.h"
59 #include "scrub.h"
60 #include "verity.h"
61 #include "super.h"
62 #include "extent-tree.h"
63 #define CREATE_TRACE_POINTS
64 #include <trace/events/btrfs.h>
65
66 static const struct super_operations btrfs_super_ops;
67 static struct file_system_type btrfs_fs_type;
68
btrfs_put_super(struct super_block * sb)69 static void btrfs_put_super(struct super_block *sb)
70 {
71 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
72
73 btrfs_info(fs_info, "last unmount of filesystem %pU", fs_info->fs_devices->fsid);
74 close_ctree(fs_info);
75 }
76
77 /* Store the mount options related information. */
78 struct btrfs_fs_context {
79 char *subvol_name;
80 u64 subvol_objectid;
81 u64 max_inline;
82 u32 commit_interval;
83 u32 metadata_ratio;
84 u32 thread_pool_size;
85 unsigned long long mount_opt;
86 unsigned long compress_type:4;
87 int compress_level;
88 refcount_t refs;
89 };
90
91 enum {
92 Opt_acl,
93 Opt_clear_cache,
94 Opt_commit_interval,
95 Opt_compress,
96 Opt_compress_force,
97 Opt_compress_force_type,
98 Opt_compress_type,
99 Opt_degraded,
100 Opt_device,
101 Opt_fatal_errors,
102 Opt_flushoncommit,
103 Opt_max_inline,
104 Opt_barrier,
105 Opt_datacow,
106 Opt_datasum,
107 Opt_defrag,
108 Opt_discard,
109 Opt_discard_mode,
110 Opt_ratio,
111 Opt_rescan_uuid_tree,
112 Opt_skip_balance,
113 Opt_space_cache,
114 Opt_space_cache_version,
115 Opt_ssd,
116 Opt_ssd_spread,
117 Opt_subvol,
118 Opt_subvol_empty,
119 Opt_subvolid,
120 Opt_thread_pool,
121 Opt_treelog,
122 Opt_user_subvol_rm_allowed,
123 Opt_norecovery,
124
125 /* Rescue options */
126 Opt_rescue,
127 Opt_usebackuproot,
128
129 /* Debugging options */
130 Opt_enospc_debug,
131 #ifdef CONFIG_BTRFS_DEBUG
132 Opt_fragment, Opt_fragment_data, Opt_fragment_metadata, Opt_fragment_all,
133 #endif
134 #ifdef CONFIG_BTRFS_FS_REF_VERIFY
135 Opt_ref_verify,
136 #endif
137 Opt_err,
138 };
139
140 enum {
141 Opt_fatal_errors_panic,
142 Opt_fatal_errors_bug,
143 };
144
145 static const struct constant_table btrfs_parameter_fatal_errors[] = {
146 { "panic", Opt_fatal_errors_panic },
147 { "bug", Opt_fatal_errors_bug },
148 {}
149 };
150
151 enum {
152 Opt_discard_sync,
153 Opt_discard_async,
154 };
155
156 static const struct constant_table btrfs_parameter_discard[] = {
157 { "sync", Opt_discard_sync },
158 { "async", Opt_discard_async },
159 {}
160 };
161
162 enum {
163 Opt_space_cache_v1,
164 Opt_space_cache_v2,
165 };
166
167 static const struct constant_table btrfs_parameter_space_cache[] = {
168 { "v1", Opt_space_cache_v1 },
169 { "v2", Opt_space_cache_v2 },
170 {}
171 };
172
173 enum {
174 Opt_rescue_usebackuproot,
175 Opt_rescue_nologreplay,
176 Opt_rescue_ignorebadroots,
177 Opt_rescue_ignoredatacsums,
178 Opt_rescue_ignoremetacsums,
179 Opt_rescue_ignoresuperflags,
180 Opt_rescue_parameter_all,
181 };
182
183 static const struct constant_table btrfs_parameter_rescue[] = {
184 { "usebackuproot", Opt_rescue_usebackuproot },
185 { "nologreplay", Opt_rescue_nologreplay },
186 { "ignorebadroots", Opt_rescue_ignorebadroots },
187 { "ibadroots", Opt_rescue_ignorebadroots },
188 { "ignoredatacsums", Opt_rescue_ignoredatacsums },
189 { "ignoremetacsums", Opt_rescue_ignoremetacsums},
190 { "ignoresuperflags", Opt_rescue_ignoresuperflags},
191 { "idatacsums", Opt_rescue_ignoredatacsums },
192 { "imetacsums", Opt_rescue_ignoremetacsums},
193 { "isuperflags", Opt_rescue_ignoresuperflags},
194 { "all", Opt_rescue_parameter_all },
195 {}
196 };
197
198 #ifdef CONFIG_BTRFS_DEBUG
199 enum {
200 Opt_fragment_parameter_data,
201 Opt_fragment_parameter_metadata,
202 Opt_fragment_parameter_all,
203 };
204
205 static const struct constant_table btrfs_parameter_fragment[] = {
206 { "data", Opt_fragment_parameter_data },
207 { "metadata", Opt_fragment_parameter_metadata },
208 { "all", Opt_fragment_parameter_all },
209 {}
210 };
211 #endif
212
213 static const struct fs_parameter_spec btrfs_fs_parameters[] = {
214 fsparam_flag_no("acl", Opt_acl),
215 fsparam_flag_no("autodefrag", Opt_defrag),
216 fsparam_flag_no("barrier", Opt_barrier),
217 fsparam_flag("clear_cache", Opt_clear_cache),
218 fsparam_u32("commit", Opt_commit_interval),
219 fsparam_flag("compress", Opt_compress),
220 fsparam_string("compress", Opt_compress_type),
221 fsparam_flag("compress-force", Opt_compress_force),
222 fsparam_string("compress-force", Opt_compress_force_type),
223 fsparam_flag_no("datacow", Opt_datacow),
224 fsparam_flag_no("datasum", Opt_datasum),
225 fsparam_flag("degraded", Opt_degraded),
226 fsparam_string("device", Opt_device),
227 fsparam_flag_no("discard", Opt_discard),
228 fsparam_enum("discard", Opt_discard_mode, btrfs_parameter_discard),
229 fsparam_enum("fatal_errors", Opt_fatal_errors, btrfs_parameter_fatal_errors),
230 fsparam_flag_no("flushoncommit", Opt_flushoncommit),
231 fsparam_string("max_inline", Opt_max_inline),
232 fsparam_u32("metadata_ratio", Opt_ratio),
233 fsparam_flag("rescan_uuid_tree", Opt_rescan_uuid_tree),
234 fsparam_flag("skip_balance", Opt_skip_balance),
235 fsparam_flag_no("space_cache", Opt_space_cache),
236 fsparam_enum("space_cache", Opt_space_cache_version, btrfs_parameter_space_cache),
237 fsparam_flag_no("ssd", Opt_ssd),
238 fsparam_flag_no("ssd_spread", Opt_ssd_spread),
239 fsparam_string("subvol", Opt_subvol),
240 fsparam_flag("subvol=", Opt_subvol_empty),
241 fsparam_u64("subvolid", Opt_subvolid),
242 fsparam_u32("thread_pool", Opt_thread_pool),
243 fsparam_flag_no("treelog", Opt_treelog),
244 fsparam_flag("user_subvol_rm_allowed", Opt_user_subvol_rm_allowed),
245
246 /* Rescue options. */
247 fsparam_enum("rescue", Opt_rescue, btrfs_parameter_rescue),
248 /* Deprecated, with alias rescue=usebackuproot */
249 __fsparam(NULL, "usebackuproot", Opt_usebackuproot, fs_param_deprecated, NULL),
250 /* For compatibility only, alias for "rescue=nologreplay". */
251 fsparam_flag("norecovery", Opt_norecovery),
252
253 /* Debugging options. */
254 fsparam_flag_no("enospc_debug", Opt_enospc_debug),
255 #ifdef CONFIG_BTRFS_DEBUG
256 fsparam_enum("fragment", Opt_fragment, btrfs_parameter_fragment),
257 #endif
258 #ifdef CONFIG_BTRFS_FS_REF_VERIFY
259 fsparam_flag("ref_verify", Opt_ref_verify),
260 #endif
261 {}
262 };
263
btrfs_match_compress_type(const char * string,const char * type,bool may_have_level)264 static bool btrfs_match_compress_type(const char *string, const char *type, bool may_have_level)
265 {
266 const int len = strlen(type);
267
268 return (strncmp(string, type, len) == 0) &&
269 ((may_have_level && string[len] == ':') || string[len] == '\0');
270 }
271
btrfs_parse_compress(struct btrfs_fs_context * ctx,const struct fs_parameter * param,int opt)272 static int btrfs_parse_compress(struct btrfs_fs_context *ctx,
273 const struct fs_parameter *param, int opt)
274 {
275 const char *string = param->string;
276
277 /*
278 * Provide the same semantics as older kernels that don't use fs
279 * context, specifying the "compress" option clears "force-compress"
280 * without the need to pass "compress-force=[no|none]" before
281 * specifying "compress".
282 */
283 if (opt != Opt_compress_force && opt != Opt_compress_force_type)
284 btrfs_clear_opt(ctx->mount_opt, FORCE_COMPRESS);
285
286 if (opt == Opt_compress || opt == Opt_compress_force) {
287 ctx->compress_type = BTRFS_COMPRESS_ZLIB;
288 ctx->compress_level = BTRFS_ZLIB_DEFAULT_LEVEL;
289 btrfs_set_opt(ctx->mount_opt, COMPRESS);
290 btrfs_clear_opt(ctx->mount_opt, NODATACOW);
291 btrfs_clear_opt(ctx->mount_opt, NODATASUM);
292 } else if (btrfs_match_compress_type(string, "zlib", true)) {
293 ctx->compress_type = BTRFS_COMPRESS_ZLIB;
294 ctx->compress_level = btrfs_compress_str2level(BTRFS_COMPRESS_ZLIB,
295 string + 4);
296 btrfs_set_opt(ctx->mount_opt, COMPRESS);
297 btrfs_clear_opt(ctx->mount_opt, NODATACOW);
298 btrfs_clear_opt(ctx->mount_opt, NODATASUM);
299 } else if (btrfs_match_compress_type(string, "lzo", false)) {
300 ctx->compress_type = BTRFS_COMPRESS_LZO;
301 ctx->compress_level = 0;
302 btrfs_set_opt(ctx->mount_opt, COMPRESS);
303 btrfs_clear_opt(ctx->mount_opt, NODATACOW);
304 btrfs_clear_opt(ctx->mount_opt, NODATASUM);
305 } else if (btrfs_match_compress_type(string, "zstd", true)) {
306 ctx->compress_type = BTRFS_COMPRESS_ZSTD;
307 ctx->compress_level = btrfs_compress_str2level(BTRFS_COMPRESS_ZSTD,
308 string + 4);
309 btrfs_set_opt(ctx->mount_opt, COMPRESS);
310 btrfs_clear_opt(ctx->mount_opt, NODATACOW);
311 btrfs_clear_opt(ctx->mount_opt, NODATASUM);
312 } else if (btrfs_match_compress_type(string, "no", false) ||
313 btrfs_match_compress_type(string, "none", false)) {
314 ctx->compress_level = 0;
315 ctx->compress_type = 0;
316 btrfs_clear_opt(ctx->mount_opt, COMPRESS);
317 btrfs_clear_opt(ctx->mount_opt, FORCE_COMPRESS);
318 } else {
319 btrfs_err(NULL, "unrecognized compression value %s", string);
320 return -EINVAL;
321 }
322 return 0;
323 }
324
btrfs_parse_param(struct fs_context * fc,struct fs_parameter * param)325 static int btrfs_parse_param(struct fs_context *fc, struct fs_parameter *param)
326 {
327 struct btrfs_fs_context *ctx = fc->fs_private;
328 struct fs_parse_result result;
329 int opt;
330
331 opt = fs_parse(fc, btrfs_fs_parameters, param, &result);
332 if (opt < 0)
333 return opt;
334
335 switch (opt) {
336 case Opt_degraded:
337 btrfs_set_opt(ctx->mount_opt, DEGRADED);
338 break;
339 case Opt_subvol_empty:
340 /*
341 * This exists because we used to allow it on accident, so we're
342 * keeping it to maintain ABI. See 37becec95ac3 ("Btrfs: allow
343 * empty subvol= again").
344 */
345 break;
346 case Opt_subvol:
347 kfree(ctx->subvol_name);
348 ctx->subvol_name = kstrdup(param->string, GFP_KERNEL);
349 if (!ctx->subvol_name)
350 return -ENOMEM;
351 break;
352 case Opt_subvolid:
353 ctx->subvol_objectid = result.uint_64;
354
355 /* subvolid=0 means give me the original fs_tree. */
356 if (!ctx->subvol_objectid)
357 ctx->subvol_objectid = BTRFS_FS_TREE_OBJECTID;
358 break;
359 case Opt_device: {
360 struct btrfs_device *device;
361
362 mutex_lock(&uuid_mutex);
363 device = btrfs_scan_one_device(param->string, false);
364 mutex_unlock(&uuid_mutex);
365 if (IS_ERR(device))
366 return PTR_ERR(device);
367 break;
368 }
369 case Opt_datasum:
370 if (result.negated) {
371 btrfs_set_opt(ctx->mount_opt, NODATASUM);
372 } else {
373 btrfs_clear_opt(ctx->mount_opt, NODATACOW);
374 btrfs_clear_opt(ctx->mount_opt, NODATASUM);
375 }
376 break;
377 case Opt_datacow:
378 if (result.negated) {
379 btrfs_clear_opt(ctx->mount_opt, COMPRESS);
380 btrfs_clear_opt(ctx->mount_opt, FORCE_COMPRESS);
381 btrfs_set_opt(ctx->mount_opt, NODATACOW);
382 btrfs_set_opt(ctx->mount_opt, NODATASUM);
383 } else {
384 btrfs_clear_opt(ctx->mount_opt, NODATACOW);
385 }
386 break;
387 case Opt_compress_force:
388 case Opt_compress_force_type:
389 btrfs_set_opt(ctx->mount_opt, FORCE_COMPRESS);
390 fallthrough;
391 case Opt_compress:
392 case Opt_compress_type:
393 if (btrfs_parse_compress(ctx, param, opt))
394 return -EINVAL;
395 break;
396 case Opt_ssd:
397 if (result.negated) {
398 btrfs_set_opt(ctx->mount_opt, NOSSD);
399 btrfs_clear_opt(ctx->mount_opt, SSD);
400 btrfs_clear_opt(ctx->mount_opt, SSD_SPREAD);
401 } else {
402 btrfs_set_opt(ctx->mount_opt, SSD);
403 btrfs_clear_opt(ctx->mount_opt, NOSSD);
404 }
405 break;
406 case Opt_ssd_spread:
407 if (result.negated) {
408 btrfs_clear_opt(ctx->mount_opt, SSD_SPREAD);
409 } else {
410 btrfs_set_opt(ctx->mount_opt, SSD);
411 btrfs_set_opt(ctx->mount_opt, SSD_SPREAD);
412 btrfs_clear_opt(ctx->mount_opt, NOSSD);
413 }
414 break;
415 case Opt_barrier:
416 if (result.negated)
417 btrfs_set_opt(ctx->mount_opt, NOBARRIER);
418 else
419 btrfs_clear_opt(ctx->mount_opt, NOBARRIER);
420 break;
421 case Opt_thread_pool:
422 if (result.uint_32 == 0) {
423 btrfs_err(NULL, "invalid value 0 for thread_pool");
424 return -EINVAL;
425 }
426 ctx->thread_pool_size = result.uint_32;
427 break;
428 case Opt_max_inline:
429 ctx->max_inline = memparse(param->string, NULL);
430 break;
431 case Opt_acl:
432 if (result.negated) {
433 fc->sb_flags &= ~SB_POSIXACL;
434 } else {
435 #ifdef CONFIG_BTRFS_FS_POSIX_ACL
436 fc->sb_flags |= SB_POSIXACL;
437 #else
438 btrfs_err(NULL, "support for ACL not compiled in");
439 return -EINVAL;
440 #endif
441 }
442 /*
443 * VFS limits the ability to toggle ACL on and off via remount,
444 * despite every file system allowing this. This seems to be
445 * an oversight since we all do, but it'll fail if we're
446 * remounting. So don't set the mask here, we'll check it in
447 * btrfs_reconfigure and do the toggling ourselves.
448 */
449 if (fc->purpose != FS_CONTEXT_FOR_RECONFIGURE)
450 fc->sb_flags_mask |= SB_POSIXACL;
451 break;
452 case Opt_treelog:
453 if (result.negated)
454 btrfs_set_opt(ctx->mount_opt, NOTREELOG);
455 else
456 btrfs_clear_opt(ctx->mount_opt, NOTREELOG);
457 break;
458 case Opt_norecovery:
459 btrfs_info(NULL,
460 "'norecovery' is for compatibility only, recommended to use 'rescue=nologreplay'");
461 btrfs_set_opt(ctx->mount_opt, NOLOGREPLAY);
462 break;
463 case Opt_flushoncommit:
464 if (result.negated)
465 btrfs_clear_opt(ctx->mount_opt, FLUSHONCOMMIT);
466 else
467 btrfs_set_opt(ctx->mount_opt, FLUSHONCOMMIT);
468 break;
469 case Opt_ratio:
470 ctx->metadata_ratio = result.uint_32;
471 break;
472 case Opt_discard:
473 if (result.negated) {
474 btrfs_clear_opt(ctx->mount_opt, DISCARD_SYNC);
475 btrfs_clear_opt(ctx->mount_opt, DISCARD_ASYNC);
476 btrfs_set_opt(ctx->mount_opt, NODISCARD);
477 } else {
478 btrfs_set_opt(ctx->mount_opt, DISCARD_SYNC);
479 btrfs_clear_opt(ctx->mount_opt, DISCARD_ASYNC);
480 }
481 break;
482 case Opt_discard_mode:
483 switch (result.uint_32) {
484 case Opt_discard_sync:
485 btrfs_clear_opt(ctx->mount_opt, DISCARD_ASYNC);
486 btrfs_set_opt(ctx->mount_opt, DISCARD_SYNC);
487 break;
488 case Opt_discard_async:
489 btrfs_clear_opt(ctx->mount_opt, DISCARD_SYNC);
490 btrfs_set_opt(ctx->mount_opt, DISCARD_ASYNC);
491 break;
492 default:
493 btrfs_err(NULL, "unrecognized discard mode value %s",
494 param->key);
495 return -EINVAL;
496 }
497 btrfs_clear_opt(ctx->mount_opt, NODISCARD);
498 break;
499 case Opt_space_cache:
500 if (result.negated) {
501 btrfs_set_opt(ctx->mount_opt, NOSPACECACHE);
502 btrfs_clear_opt(ctx->mount_opt, SPACE_CACHE);
503 btrfs_clear_opt(ctx->mount_opt, FREE_SPACE_TREE);
504 } else {
505 btrfs_clear_opt(ctx->mount_opt, FREE_SPACE_TREE);
506 btrfs_set_opt(ctx->mount_opt, SPACE_CACHE);
507 }
508 break;
509 case Opt_space_cache_version:
510 switch (result.uint_32) {
511 case Opt_space_cache_v1:
512 btrfs_set_opt(ctx->mount_opt, SPACE_CACHE);
513 btrfs_clear_opt(ctx->mount_opt, FREE_SPACE_TREE);
514 break;
515 case Opt_space_cache_v2:
516 btrfs_clear_opt(ctx->mount_opt, SPACE_CACHE);
517 btrfs_set_opt(ctx->mount_opt, FREE_SPACE_TREE);
518 break;
519 default:
520 btrfs_err(NULL, "unrecognized space_cache value %s",
521 param->key);
522 return -EINVAL;
523 }
524 break;
525 case Opt_rescan_uuid_tree:
526 btrfs_set_opt(ctx->mount_opt, RESCAN_UUID_TREE);
527 break;
528 case Opt_clear_cache:
529 btrfs_set_opt(ctx->mount_opt, CLEAR_CACHE);
530 break;
531 case Opt_user_subvol_rm_allowed:
532 btrfs_set_opt(ctx->mount_opt, USER_SUBVOL_RM_ALLOWED);
533 break;
534 case Opt_enospc_debug:
535 if (result.negated)
536 btrfs_clear_opt(ctx->mount_opt, ENOSPC_DEBUG);
537 else
538 btrfs_set_opt(ctx->mount_opt, ENOSPC_DEBUG);
539 break;
540 case Opt_defrag:
541 if (result.negated)
542 btrfs_clear_opt(ctx->mount_opt, AUTO_DEFRAG);
543 else
544 btrfs_set_opt(ctx->mount_opt, AUTO_DEFRAG);
545 break;
546 case Opt_usebackuproot:
547 btrfs_warn(NULL,
548 "'usebackuproot' is deprecated, use 'rescue=usebackuproot' instead");
549 btrfs_set_opt(ctx->mount_opt, USEBACKUPROOT);
550
551 /* If we're loading the backup roots we can't trust the space cache. */
552 btrfs_set_opt(ctx->mount_opt, CLEAR_CACHE);
553 break;
554 case Opt_skip_balance:
555 btrfs_set_opt(ctx->mount_opt, SKIP_BALANCE);
556 break;
557 case Opt_fatal_errors:
558 switch (result.uint_32) {
559 case Opt_fatal_errors_panic:
560 btrfs_set_opt(ctx->mount_opt, PANIC_ON_FATAL_ERROR);
561 break;
562 case Opt_fatal_errors_bug:
563 btrfs_clear_opt(ctx->mount_opt, PANIC_ON_FATAL_ERROR);
564 break;
565 default:
566 btrfs_err(NULL, "unrecognized fatal_errors value %s",
567 param->key);
568 return -EINVAL;
569 }
570 break;
571 case Opt_commit_interval:
572 ctx->commit_interval = result.uint_32;
573 if (ctx->commit_interval > BTRFS_WARNING_COMMIT_INTERVAL) {
574 btrfs_warn(NULL, "excessive commit interval %u, use with care",
575 ctx->commit_interval);
576 }
577 if (ctx->commit_interval == 0)
578 ctx->commit_interval = BTRFS_DEFAULT_COMMIT_INTERVAL;
579 break;
580 case Opt_rescue:
581 switch (result.uint_32) {
582 case Opt_rescue_usebackuproot:
583 btrfs_set_opt(ctx->mount_opt, USEBACKUPROOT);
584 break;
585 case Opt_rescue_nologreplay:
586 btrfs_set_opt(ctx->mount_opt, NOLOGREPLAY);
587 break;
588 case Opt_rescue_ignorebadroots:
589 btrfs_set_opt(ctx->mount_opt, IGNOREBADROOTS);
590 break;
591 case Opt_rescue_ignoredatacsums:
592 btrfs_set_opt(ctx->mount_opt, IGNOREDATACSUMS);
593 break;
594 case Opt_rescue_ignoremetacsums:
595 btrfs_set_opt(ctx->mount_opt, IGNOREMETACSUMS);
596 break;
597 case Opt_rescue_ignoresuperflags:
598 btrfs_set_opt(ctx->mount_opt, IGNORESUPERFLAGS);
599 break;
600 case Opt_rescue_parameter_all:
601 btrfs_set_opt(ctx->mount_opt, IGNOREDATACSUMS);
602 btrfs_set_opt(ctx->mount_opt, IGNOREMETACSUMS);
603 btrfs_set_opt(ctx->mount_opt, IGNORESUPERFLAGS);
604 btrfs_set_opt(ctx->mount_opt, IGNOREBADROOTS);
605 btrfs_set_opt(ctx->mount_opt, NOLOGREPLAY);
606 break;
607 default:
608 btrfs_info(NULL, "unrecognized rescue option '%s'",
609 param->key);
610 return -EINVAL;
611 }
612 break;
613 #ifdef CONFIG_BTRFS_DEBUG
614 case Opt_fragment:
615 switch (result.uint_32) {
616 case Opt_fragment_parameter_all:
617 btrfs_set_opt(ctx->mount_opt, FRAGMENT_DATA);
618 btrfs_set_opt(ctx->mount_opt, FRAGMENT_METADATA);
619 break;
620 case Opt_fragment_parameter_metadata:
621 btrfs_set_opt(ctx->mount_opt, FRAGMENT_METADATA);
622 break;
623 case Opt_fragment_parameter_data:
624 btrfs_set_opt(ctx->mount_opt, FRAGMENT_DATA);
625 break;
626 default:
627 btrfs_info(NULL, "unrecognized fragment option '%s'",
628 param->key);
629 return -EINVAL;
630 }
631 break;
632 #endif
633 #ifdef CONFIG_BTRFS_FS_REF_VERIFY
634 case Opt_ref_verify:
635 btrfs_set_opt(ctx->mount_opt, REF_VERIFY);
636 break;
637 #endif
638 default:
639 btrfs_err(NULL, "unrecognized mount option '%s'", param->key);
640 return -EINVAL;
641 }
642
643 return 0;
644 }
645
646 /*
647 * Some options only have meaning at mount time and shouldn't persist across
648 * remounts, or be displayed. Clear these at the end of mount and remount code
649 * paths.
650 */
btrfs_clear_oneshot_options(struct btrfs_fs_info * fs_info)651 static void btrfs_clear_oneshot_options(struct btrfs_fs_info *fs_info)
652 {
653 btrfs_clear_opt(fs_info->mount_opt, USEBACKUPROOT);
654 btrfs_clear_opt(fs_info->mount_opt, CLEAR_CACHE);
655 btrfs_clear_opt(fs_info->mount_opt, NOSPACECACHE);
656 }
657
check_ro_option(const struct btrfs_fs_info * fs_info,unsigned long long mount_opt,unsigned long long opt,const char * opt_name)658 static bool check_ro_option(const struct btrfs_fs_info *fs_info,
659 unsigned long long mount_opt, unsigned long long opt,
660 const char *opt_name)
661 {
662 if (mount_opt & opt) {
663 btrfs_err(fs_info, "%s must be used with ro mount option",
664 opt_name);
665 return true;
666 }
667 return false;
668 }
669
btrfs_check_options(const struct btrfs_fs_info * info,unsigned long long * mount_opt,unsigned long flags)670 bool btrfs_check_options(const struct btrfs_fs_info *info,
671 unsigned long long *mount_opt,
672 unsigned long flags)
673 {
674 bool ret = true;
675
676 if (!(flags & SB_RDONLY) &&
677 (check_ro_option(info, *mount_opt, BTRFS_MOUNT_NOLOGREPLAY, "nologreplay") ||
678 check_ro_option(info, *mount_opt, BTRFS_MOUNT_IGNOREBADROOTS, "ignorebadroots") ||
679 check_ro_option(info, *mount_opt, BTRFS_MOUNT_IGNOREDATACSUMS, "ignoredatacsums") ||
680 check_ro_option(info, *mount_opt, BTRFS_MOUNT_IGNOREMETACSUMS, "ignoremetacsums") ||
681 check_ro_option(info, *mount_opt, BTRFS_MOUNT_IGNORESUPERFLAGS, "ignoresuperflags")))
682 ret = false;
683
684 if (btrfs_fs_compat_ro(info, FREE_SPACE_TREE) &&
685 !btrfs_raw_test_opt(*mount_opt, FREE_SPACE_TREE) &&
686 !btrfs_raw_test_opt(*mount_opt, CLEAR_CACHE)) {
687 btrfs_err(info, "cannot disable free-space-tree");
688 ret = false;
689 }
690 if (btrfs_fs_compat_ro(info, BLOCK_GROUP_TREE) &&
691 !btrfs_raw_test_opt(*mount_opt, FREE_SPACE_TREE)) {
692 btrfs_err(info, "cannot disable free-space-tree with block-group-tree feature");
693 ret = false;
694 }
695
696 if (btrfs_check_mountopts_zoned(info, mount_opt))
697 ret = false;
698
699 if (!test_bit(BTRFS_FS_STATE_REMOUNTING, &info->fs_state)) {
700 if (btrfs_raw_test_opt(*mount_opt, SPACE_CACHE)) {
701 btrfs_info(info, "disk space caching is enabled");
702 btrfs_warn(info,
703 "space cache v1 is being deprecated and will be removed in a future release, please use -o space_cache=v2");
704 }
705 if (btrfs_raw_test_opt(*mount_opt, FREE_SPACE_TREE))
706 btrfs_info(info, "using free-space-tree");
707 }
708
709 return ret;
710 }
711
712 /*
713 * This is subtle, we only call this during open_ctree(). We need to pre-load
714 * the mount options with the on-disk settings. Before the new mount API took
715 * effect we would do this on mount and remount. With the new mount API we'll
716 * only do this on the initial mount.
717 *
718 * This isn't a change in behavior, because we're using the current state of the
719 * file system to set the current mount options. If you mounted with special
720 * options to disable these features and then remounted we wouldn't revert the
721 * settings, because mounting without these features cleared the on-disk
722 * settings, so this being called on re-mount is not needed.
723 */
btrfs_set_free_space_cache_settings(struct btrfs_fs_info * fs_info)724 void btrfs_set_free_space_cache_settings(struct btrfs_fs_info *fs_info)
725 {
726 if (fs_info->sectorsize < PAGE_SIZE) {
727 btrfs_clear_opt(fs_info->mount_opt, SPACE_CACHE);
728 if (!btrfs_test_opt(fs_info, FREE_SPACE_TREE)) {
729 btrfs_info(fs_info,
730 "forcing free space tree for sector size %u with page size %lu",
731 fs_info->sectorsize, PAGE_SIZE);
732 btrfs_set_opt(fs_info->mount_opt, FREE_SPACE_TREE);
733 }
734 }
735
736 /*
737 * At this point our mount options are populated, so we only mess with
738 * these settings if we don't have any settings already.
739 */
740 if (btrfs_test_opt(fs_info, FREE_SPACE_TREE))
741 return;
742
743 if (btrfs_is_zoned(fs_info) &&
744 btrfs_free_space_cache_v1_active(fs_info)) {
745 btrfs_info(fs_info, "zoned: clearing existing space cache");
746 btrfs_set_super_cache_generation(fs_info->super_copy, 0);
747 return;
748 }
749
750 if (btrfs_test_opt(fs_info, SPACE_CACHE))
751 return;
752
753 if (btrfs_test_opt(fs_info, NOSPACECACHE))
754 return;
755
756 /*
757 * At this point we don't have explicit options set by the user, set
758 * them ourselves based on the state of the file system.
759 */
760 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE))
761 btrfs_set_opt(fs_info->mount_opt, FREE_SPACE_TREE);
762 else if (btrfs_free_space_cache_v1_active(fs_info))
763 btrfs_set_opt(fs_info->mount_opt, SPACE_CACHE);
764 }
765
set_device_specific_options(struct btrfs_fs_info * fs_info)766 static void set_device_specific_options(struct btrfs_fs_info *fs_info)
767 {
768 if (!btrfs_test_opt(fs_info, NOSSD) &&
769 !fs_info->fs_devices->rotating)
770 btrfs_set_opt(fs_info->mount_opt, SSD);
771
772 /*
773 * For devices supporting discard turn on discard=async automatically,
774 * unless it's already set or disabled. This could be turned off by
775 * nodiscard for the same mount.
776 *
777 * The zoned mode piggy backs on the discard functionality for
778 * resetting a zone. There is no reason to delay the zone reset as it is
779 * fast enough. So, do not enable async discard for zoned mode.
780 */
781 if (!(btrfs_test_opt(fs_info, DISCARD_SYNC) ||
782 btrfs_test_opt(fs_info, DISCARD_ASYNC) ||
783 btrfs_test_opt(fs_info, NODISCARD)) &&
784 fs_info->fs_devices->discardable &&
785 !btrfs_is_zoned(fs_info))
786 btrfs_set_opt(fs_info->mount_opt, DISCARD_ASYNC);
787 }
788
btrfs_get_subvol_name_from_objectid(struct btrfs_fs_info * fs_info,u64 subvol_objectid)789 char *btrfs_get_subvol_name_from_objectid(struct btrfs_fs_info *fs_info,
790 u64 subvol_objectid)
791 {
792 struct btrfs_root *root = fs_info->tree_root;
793 struct btrfs_root *fs_root = NULL;
794 struct btrfs_root_ref *root_ref;
795 struct btrfs_inode_ref *inode_ref;
796 struct btrfs_key key;
797 struct btrfs_path *path = NULL;
798 char *name = NULL, *ptr;
799 u64 dirid;
800 int len;
801 int ret;
802
803 path = btrfs_alloc_path();
804 if (!path) {
805 ret = -ENOMEM;
806 goto err;
807 }
808
809 name = kmalloc(PATH_MAX, GFP_KERNEL);
810 if (!name) {
811 ret = -ENOMEM;
812 goto err;
813 }
814 ptr = name + PATH_MAX - 1;
815 ptr[0] = '\0';
816
817 /*
818 * Walk up the subvolume trees in the tree of tree roots by root
819 * backrefs until we hit the top-level subvolume.
820 */
821 while (subvol_objectid != BTRFS_FS_TREE_OBJECTID) {
822 key.objectid = subvol_objectid;
823 key.type = BTRFS_ROOT_BACKREF_KEY;
824 key.offset = (u64)-1;
825
826 ret = btrfs_search_backwards(root, &key, path);
827 if (ret < 0) {
828 goto err;
829 } else if (ret > 0) {
830 ret = -ENOENT;
831 goto err;
832 }
833
834 subvol_objectid = key.offset;
835
836 root_ref = btrfs_item_ptr(path->nodes[0], path->slots[0],
837 struct btrfs_root_ref);
838 len = btrfs_root_ref_name_len(path->nodes[0], root_ref);
839 ptr -= len + 1;
840 if (ptr < name) {
841 ret = -ENAMETOOLONG;
842 goto err;
843 }
844 read_extent_buffer(path->nodes[0], ptr + 1,
845 (unsigned long)(root_ref + 1), len);
846 ptr[0] = '/';
847 dirid = btrfs_root_ref_dirid(path->nodes[0], root_ref);
848 btrfs_release_path(path);
849
850 fs_root = btrfs_get_fs_root(fs_info, subvol_objectid, true);
851 if (IS_ERR(fs_root)) {
852 ret = PTR_ERR(fs_root);
853 fs_root = NULL;
854 goto err;
855 }
856
857 /*
858 * Walk up the filesystem tree by inode refs until we hit the
859 * root directory.
860 */
861 while (dirid != BTRFS_FIRST_FREE_OBJECTID) {
862 key.objectid = dirid;
863 key.type = BTRFS_INODE_REF_KEY;
864 key.offset = (u64)-1;
865
866 ret = btrfs_search_backwards(fs_root, &key, path);
867 if (ret < 0) {
868 goto err;
869 } else if (ret > 0) {
870 ret = -ENOENT;
871 goto err;
872 }
873
874 dirid = key.offset;
875
876 inode_ref = btrfs_item_ptr(path->nodes[0],
877 path->slots[0],
878 struct btrfs_inode_ref);
879 len = btrfs_inode_ref_name_len(path->nodes[0],
880 inode_ref);
881 ptr -= len + 1;
882 if (ptr < name) {
883 ret = -ENAMETOOLONG;
884 goto err;
885 }
886 read_extent_buffer(path->nodes[0], ptr + 1,
887 (unsigned long)(inode_ref + 1), len);
888 ptr[0] = '/';
889 btrfs_release_path(path);
890 }
891 btrfs_put_root(fs_root);
892 fs_root = NULL;
893 }
894
895 btrfs_free_path(path);
896 if (ptr == name + PATH_MAX - 1) {
897 name[0] = '/';
898 name[1] = '\0';
899 } else {
900 memmove(name, ptr, name + PATH_MAX - ptr);
901 }
902 return name;
903
904 err:
905 btrfs_put_root(fs_root);
906 btrfs_free_path(path);
907 kfree(name);
908 return ERR_PTR(ret);
909 }
910
get_default_subvol_objectid(struct btrfs_fs_info * fs_info,u64 * objectid)911 static int get_default_subvol_objectid(struct btrfs_fs_info *fs_info, u64 *objectid)
912 {
913 struct btrfs_root *root = fs_info->tree_root;
914 struct btrfs_dir_item *di;
915 struct btrfs_path *path;
916 struct btrfs_key location;
917 struct fscrypt_str name = FSTR_INIT("default", 7);
918 u64 dir_id;
919
920 path = btrfs_alloc_path();
921 if (!path)
922 return -ENOMEM;
923
924 /*
925 * Find the "default" dir item which points to the root item that we
926 * will mount by default if we haven't been given a specific subvolume
927 * to mount.
928 */
929 dir_id = btrfs_super_root_dir(fs_info->super_copy);
930 di = btrfs_lookup_dir_item(NULL, root, path, dir_id, &name, 0);
931 if (IS_ERR(di)) {
932 btrfs_free_path(path);
933 return PTR_ERR(di);
934 }
935 if (!di) {
936 /*
937 * Ok the default dir item isn't there. This is weird since
938 * it's always been there, but don't freak out, just try and
939 * mount the top-level subvolume.
940 */
941 btrfs_free_path(path);
942 *objectid = BTRFS_FS_TREE_OBJECTID;
943 return 0;
944 }
945
946 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &location);
947 btrfs_free_path(path);
948 *objectid = location.objectid;
949 return 0;
950 }
951
btrfs_fill_super(struct super_block * sb,struct btrfs_fs_devices * fs_devices)952 static int btrfs_fill_super(struct super_block *sb,
953 struct btrfs_fs_devices *fs_devices)
954 {
955 struct btrfs_inode *inode;
956 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
957 int ret;
958
959 sb->s_maxbytes = MAX_LFS_FILESIZE;
960 sb->s_magic = BTRFS_SUPER_MAGIC;
961 sb->s_op = &btrfs_super_ops;
962 set_default_d_op(sb, &btrfs_dentry_operations);
963 sb->s_export_op = &btrfs_export_ops;
964 #ifdef CONFIG_FS_VERITY
965 sb->s_vop = &btrfs_verityops;
966 #endif
967 sb->s_xattr = btrfs_xattr_handlers;
968 sb->s_time_gran = 1;
969 sb->s_iflags |= SB_I_CGROUPWB | SB_I_ALLOW_HSM;
970
971 ret = super_setup_bdi(sb);
972 if (ret) {
973 btrfs_err(fs_info, "super_setup_bdi failed");
974 return ret;
975 }
976
977 ret = open_ctree(sb, fs_devices);
978 if (ret) {
979 btrfs_err(fs_info, "open_ctree failed: %d", ret);
980 return ret;
981 }
982
983 inode = btrfs_iget(BTRFS_FIRST_FREE_OBJECTID, fs_info->fs_root);
984 if (IS_ERR(inode)) {
985 ret = PTR_ERR(inode);
986 btrfs_handle_fs_error(fs_info, ret, NULL);
987 goto fail_close;
988 }
989
990 sb->s_root = d_make_root(&inode->vfs_inode);
991 if (!sb->s_root) {
992 ret = -ENOMEM;
993 goto fail_close;
994 }
995
996 sb->s_flags |= SB_ACTIVE;
997 return 0;
998
999 fail_close:
1000 close_ctree(fs_info);
1001 return ret;
1002 }
1003
btrfs_sync_fs(struct super_block * sb,int wait)1004 int btrfs_sync_fs(struct super_block *sb, int wait)
1005 {
1006 struct btrfs_trans_handle *trans;
1007 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
1008 struct btrfs_root *root = fs_info->tree_root;
1009
1010 trace_btrfs_sync_fs(fs_info, wait);
1011
1012 if (!wait) {
1013 filemap_flush(fs_info->btree_inode->i_mapping);
1014 return 0;
1015 }
1016
1017 btrfs_wait_ordered_roots(fs_info, U64_MAX, NULL);
1018
1019 trans = btrfs_attach_transaction_barrier(root);
1020 if (IS_ERR(trans)) {
1021 /* no transaction, don't bother */
1022 if (PTR_ERR(trans) == -ENOENT) {
1023 /*
1024 * Exit unless we have some pending changes
1025 * that need to go through commit
1026 */
1027 if (!test_bit(BTRFS_FS_NEED_TRANS_COMMIT,
1028 &fs_info->flags))
1029 return 0;
1030 /*
1031 * A non-blocking test if the fs is frozen. We must not
1032 * start a new transaction here otherwise a deadlock
1033 * happens. The pending operations are delayed to the
1034 * next commit after thawing.
1035 */
1036 if (sb_start_write_trylock(sb))
1037 sb_end_write(sb);
1038 else
1039 return 0;
1040 trans = btrfs_start_transaction(root, 0);
1041 }
1042 if (IS_ERR(trans))
1043 return PTR_ERR(trans);
1044 }
1045 return btrfs_commit_transaction(trans);
1046 }
1047
print_rescue_option(struct seq_file * seq,const char * s,bool * printed)1048 static void print_rescue_option(struct seq_file *seq, const char *s, bool *printed)
1049 {
1050 seq_printf(seq, "%s%s", (*printed) ? ":" : ",rescue=", s);
1051 *printed = true;
1052 }
1053
btrfs_show_options(struct seq_file * seq,struct dentry * dentry)1054 static int btrfs_show_options(struct seq_file *seq, struct dentry *dentry)
1055 {
1056 struct btrfs_fs_info *info = btrfs_sb(dentry->d_sb);
1057 const char *compress_type;
1058 const char *subvol_name;
1059 bool printed = false;
1060
1061 if (btrfs_test_opt(info, DEGRADED))
1062 seq_puts(seq, ",degraded");
1063 if (btrfs_test_opt(info, NODATASUM))
1064 seq_puts(seq, ",nodatasum");
1065 if (btrfs_test_opt(info, NODATACOW))
1066 seq_puts(seq, ",nodatacow");
1067 if (btrfs_test_opt(info, NOBARRIER))
1068 seq_puts(seq, ",nobarrier");
1069 if (info->max_inline != BTRFS_DEFAULT_MAX_INLINE)
1070 seq_printf(seq, ",max_inline=%llu", info->max_inline);
1071 if (info->thread_pool_size != min_t(unsigned long,
1072 num_online_cpus() + 2, 8))
1073 seq_printf(seq, ",thread_pool=%u", info->thread_pool_size);
1074 if (btrfs_test_opt(info, COMPRESS)) {
1075 compress_type = btrfs_compress_type2str(info->compress_type);
1076 if (btrfs_test_opt(info, FORCE_COMPRESS))
1077 seq_printf(seq, ",compress-force=%s", compress_type);
1078 else
1079 seq_printf(seq, ",compress=%s", compress_type);
1080 if (info->compress_level)
1081 seq_printf(seq, ":%d", info->compress_level);
1082 }
1083 if (btrfs_test_opt(info, NOSSD))
1084 seq_puts(seq, ",nossd");
1085 if (btrfs_test_opt(info, SSD_SPREAD))
1086 seq_puts(seq, ",ssd_spread");
1087 else if (btrfs_test_opt(info, SSD))
1088 seq_puts(seq, ",ssd");
1089 if (btrfs_test_opt(info, NOTREELOG))
1090 seq_puts(seq, ",notreelog");
1091 if (btrfs_test_opt(info, NOLOGREPLAY))
1092 print_rescue_option(seq, "nologreplay", &printed);
1093 if (btrfs_test_opt(info, USEBACKUPROOT))
1094 print_rescue_option(seq, "usebackuproot", &printed);
1095 if (btrfs_test_opt(info, IGNOREBADROOTS))
1096 print_rescue_option(seq, "ignorebadroots", &printed);
1097 if (btrfs_test_opt(info, IGNOREDATACSUMS))
1098 print_rescue_option(seq, "ignoredatacsums", &printed);
1099 if (btrfs_test_opt(info, IGNOREMETACSUMS))
1100 print_rescue_option(seq, "ignoremetacsums", &printed);
1101 if (btrfs_test_opt(info, IGNORESUPERFLAGS))
1102 print_rescue_option(seq, "ignoresuperflags", &printed);
1103 if (btrfs_test_opt(info, FLUSHONCOMMIT))
1104 seq_puts(seq, ",flushoncommit");
1105 if (btrfs_test_opt(info, DISCARD_SYNC))
1106 seq_puts(seq, ",discard");
1107 if (btrfs_test_opt(info, DISCARD_ASYNC))
1108 seq_puts(seq, ",discard=async");
1109 if (!(info->sb->s_flags & SB_POSIXACL))
1110 seq_puts(seq, ",noacl");
1111 if (btrfs_free_space_cache_v1_active(info))
1112 seq_puts(seq, ",space_cache");
1113 else if (btrfs_fs_compat_ro(info, FREE_SPACE_TREE))
1114 seq_puts(seq, ",space_cache=v2");
1115 else
1116 seq_puts(seq, ",nospace_cache");
1117 if (btrfs_test_opt(info, RESCAN_UUID_TREE))
1118 seq_puts(seq, ",rescan_uuid_tree");
1119 if (btrfs_test_opt(info, CLEAR_CACHE))
1120 seq_puts(seq, ",clear_cache");
1121 if (btrfs_test_opt(info, USER_SUBVOL_RM_ALLOWED))
1122 seq_puts(seq, ",user_subvol_rm_allowed");
1123 if (btrfs_test_opt(info, ENOSPC_DEBUG))
1124 seq_puts(seq, ",enospc_debug");
1125 if (btrfs_test_opt(info, AUTO_DEFRAG))
1126 seq_puts(seq, ",autodefrag");
1127 if (btrfs_test_opt(info, SKIP_BALANCE))
1128 seq_puts(seq, ",skip_balance");
1129 if (info->metadata_ratio)
1130 seq_printf(seq, ",metadata_ratio=%u", info->metadata_ratio);
1131 if (btrfs_test_opt(info, PANIC_ON_FATAL_ERROR))
1132 seq_puts(seq, ",fatal_errors=panic");
1133 if (info->commit_interval != BTRFS_DEFAULT_COMMIT_INTERVAL)
1134 seq_printf(seq, ",commit=%u", info->commit_interval);
1135 #ifdef CONFIG_BTRFS_DEBUG
1136 if (btrfs_test_opt(info, FRAGMENT_DATA))
1137 seq_puts(seq, ",fragment=data");
1138 if (btrfs_test_opt(info, FRAGMENT_METADATA))
1139 seq_puts(seq, ",fragment=metadata");
1140 #endif
1141 if (btrfs_test_opt(info, REF_VERIFY))
1142 seq_puts(seq, ",ref_verify");
1143 seq_printf(seq, ",subvolid=%llu", btrfs_root_id(BTRFS_I(d_inode(dentry))->root));
1144 subvol_name = btrfs_get_subvol_name_from_objectid(info,
1145 btrfs_root_id(BTRFS_I(d_inode(dentry))->root));
1146 if (!IS_ERR(subvol_name)) {
1147 seq_show_option(seq, "subvol", subvol_name);
1148 kfree(subvol_name);
1149 }
1150 return 0;
1151 }
1152
1153 /*
1154 * subvolumes are identified by ino 256
1155 */
is_subvolume_inode(struct inode * inode)1156 static inline bool is_subvolume_inode(struct inode *inode)
1157 {
1158 if (inode && inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)
1159 return true;
1160 return false;
1161 }
1162
mount_subvol(const char * subvol_name,u64 subvol_objectid,struct vfsmount * mnt)1163 static struct dentry *mount_subvol(const char *subvol_name, u64 subvol_objectid,
1164 struct vfsmount *mnt)
1165 {
1166 struct dentry *root;
1167 int ret;
1168
1169 if (!subvol_name) {
1170 if (!subvol_objectid) {
1171 ret = get_default_subvol_objectid(btrfs_sb(mnt->mnt_sb),
1172 &subvol_objectid);
1173 if (ret) {
1174 root = ERR_PTR(ret);
1175 goto out;
1176 }
1177 }
1178 subvol_name = btrfs_get_subvol_name_from_objectid(
1179 btrfs_sb(mnt->mnt_sb), subvol_objectid);
1180 if (IS_ERR(subvol_name)) {
1181 root = ERR_CAST(subvol_name);
1182 subvol_name = NULL;
1183 goto out;
1184 }
1185
1186 }
1187
1188 root = mount_subtree(mnt, subvol_name);
1189 /* mount_subtree() drops our reference on the vfsmount. */
1190 mnt = NULL;
1191
1192 if (!IS_ERR(root)) {
1193 struct super_block *s = root->d_sb;
1194 struct btrfs_fs_info *fs_info = btrfs_sb(s);
1195 struct inode *root_inode = d_inode(root);
1196 u64 root_objectid = btrfs_root_id(BTRFS_I(root_inode)->root);
1197
1198 ret = 0;
1199 if (!is_subvolume_inode(root_inode)) {
1200 btrfs_err(fs_info, "'%s' is not a valid subvolume",
1201 subvol_name);
1202 ret = -EINVAL;
1203 }
1204 if (subvol_objectid && root_objectid != subvol_objectid) {
1205 /*
1206 * This will also catch a race condition where a
1207 * subvolume which was passed by ID is renamed and
1208 * another subvolume is renamed over the old location.
1209 */
1210 btrfs_err(fs_info,
1211 "subvol '%s' does not match subvolid %llu",
1212 subvol_name, subvol_objectid);
1213 ret = -EINVAL;
1214 }
1215 if (ret) {
1216 dput(root);
1217 root = ERR_PTR(ret);
1218 deactivate_locked_super(s);
1219 }
1220 }
1221
1222 out:
1223 mntput(mnt);
1224 kfree(subvol_name);
1225 return root;
1226 }
1227
btrfs_resize_thread_pool(struct btrfs_fs_info * fs_info,u32 new_pool_size,u32 old_pool_size)1228 static void btrfs_resize_thread_pool(struct btrfs_fs_info *fs_info,
1229 u32 new_pool_size, u32 old_pool_size)
1230 {
1231 if (new_pool_size == old_pool_size)
1232 return;
1233
1234 fs_info->thread_pool_size = new_pool_size;
1235
1236 btrfs_info(fs_info, "resize thread pool %d -> %d",
1237 old_pool_size, new_pool_size);
1238
1239 btrfs_workqueue_set_max(fs_info->workers, new_pool_size);
1240 btrfs_workqueue_set_max(fs_info->delalloc_workers, new_pool_size);
1241 btrfs_workqueue_set_max(fs_info->caching_workers, new_pool_size);
1242 workqueue_set_max_active(fs_info->endio_workers, new_pool_size);
1243 workqueue_set_max_active(fs_info->endio_meta_workers, new_pool_size);
1244 btrfs_workqueue_set_max(fs_info->endio_write_workers, new_pool_size);
1245 btrfs_workqueue_set_max(fs_info->endio_freespace_worker, new_pool_size);
1246 btrfs_workqueue_set_max(fs_info->delayed_workers, new_pool_size);
1247 }
1248
btrfs_remount_begin(struct btrfs_fs_info * fs_info,unsigned long long old_opts,int flags)1249 static inline void btrfs_remount_begin(struct btrfs_fs_info *fs_info,
1250 unsigned long long old_opts, int flags)
1251 {
1252 if (btrfs_raw_test_opt(old_opts, AUTO_DEFRAG) &&
1253 (!btrfs_raw_test_opt(fs_info->mount_opt, AUTO_DEFRAG) ||
1254 (flags & SB_RDONLY))) {
1255 /* wait for any defraggers to finish */
1256 wait_event(fs_info->transaction_wait,
1257 (atomic_read(&fs_info->defrag_running) == 0));
1258 if (flags & SB_RDONLY)
1259 sync_filesystem(fs_info->sb);
1260 }
1261 }
1262
btrfs_remount_cleanup(struct btrfs_fs_info * fs_info,unsigned long long old_opts)1263 static inline void btrfs_remount_cleanup(struct btrfs_fs_info *fs_info,
1264 unsigned long long old_opts)
1265 {
1266 const bool cache_opt = btrfs_test_opt(fs_info, SPACE_CACHE);
1267
1268 /*
1269 * We need to cleanup all defragable inodes if the autodefragment is
1270 * close or the filesystem is read only.
1271 */
1272 if (btrfs_raw_test_opt(old_opts, AUTO_DEFRAG) &&
1273 (!btrfs_raw_test_opt(fs_info->mount_opt, AUTO_DEFRAG) || sb_rdonly(fs_info->sb))) {
1274 btrfs_cleanup_defrag_inodes(fs_info);
1275 }
1276
1277 /* If we toggled discard async */
1278 if (!btrfs_raw_test_opt(old_opts, DISCARD_ASYNC) &&
1279 btrfs_test_opt(fs_info, DISCARD_ASYNC))
1280 btrfs_discard_resume(fs_info);
1281 else if (btrfs_raw_test_opt(old_opts, DISCARD_ASYNC) &&
1282 !btrfs_test_opt(fs_info, DISCARD_ASYNC))
1283 btrfs_discard_cleanup(fs_info);
1284
1285 /* If we toggled space cache */
1286 if (cache_opt != btrfs_free_space_cache_v1_active(fs_info))
1287 btrfs_set_free_space_cache_v1_active(fs_info, cache_opt);
1288 }
1289
btrfs_remount_rw(struct btrfs_fs_info * fs_info)1290 static int btrfs_remount_rw(struct btrfs_fs_info *fs_info)
1291 {
1292 int ret;
1293
1294 if (BTRFS_FS_ERROR(fs_info)) {
1295 btrfs_err(fs_info,
1296 "remounting read-write after error is not allowed");
1297 return -EINVAL;
1298 }
1299
1300 if (fs_info->fs_devices->rw_devices == 0)
1301 return -EACCES;
1302
1303 if (!btrfs_check_rw_degradable(fs_info, NULL)) {
1304 btrfs_warn(fs_info,
1305 "too many missing devices, writable remount is not allowed");
1306 return -EACCES;
1307 }
1308
1309 if (btrfs_super_log_root(fs_info->super_copy) != 0) {
1310 btrfs_warn(fs_info,
1311 "mount required to replay tree-log, cannot remount read-write");
1312 return -EINVAL;
1313 }
1314
1315 /*
1316 * NOTE: when remounting with a change that does writes, don't put it
1317 * anywhere above this point, as we are not sure to be safe to write
1318 * until we pass the above checks.
1319 */
1320 ret = btrfs_start_pre_rw_mount(fs_info);
1321 if (ret)
1322 return ret;
1323
1324 btrfs_clear_sb_rdonly(fs_info->sb);
1325
1326 set_bit(BTRFS_FS_OPEN, &fs_info->flags);
1327
1328 /*
1329 * If we've gone from readonly -> read-write, we need to get our
1330 * sync/async discard lists in the right state.
1331 */
1332 btrfs_discard_resume(fs_info);
1333
1334 return 0;
1335 }
1336
btrfs_remount_ro(struct btrfs_fs_info * fs_info)1337 static int btrfs_remount_ro(struct btrfs_fs_info *fs_info)
1338 {
1339 /*
1340 * This also happens on 'umount -rf' or on shutdown, when the
1341 * filesystem is busy.
1342 */
1343 cancel_work_sync(&fs_info->async_reclaim_work);
1344 cancel_work_sync(&fs_info->async_data_reclaim_work);
1345
1346 btrfs_discard_cleanup(fs_info);
1347
1348 /* Wait for the uuid_scan task to finish */
1349 down(&fs_info->uuid_tree_rescan_sem);
1350 /* Avoid complains from lockdep et al. */
1351 up(&fs_info->uuid_tree_rescan_sem);
1352
1353 btrfs_set_sb_rdonly(fs_info->sb);
1354
1355 /*
1356 * Setting SB_RDONLY will put the cleaner thread to sleep at the next
1357 * loop if it's already active. If it's already asleep, we'll leave
1358 * unused block groups on disk until we're mounted read-write again
1359 * unless we clean them up here.
1360 */
1361 btrfs_delete_unused_bgs(fs_info);
1362
1363 /*
1364 * The cleaner task could be already running before we set the flag
1365 * BTRFS_FS_STATE_RO (and SB_RDONLY in the superblock). We must make
1366 * sure that after we finish the remount, i.e. after we call
1367 * btrfs_commit_super(), the cleaner can no longer start a transaction
1368 * - either because it was dropping a dead root, running delayed iputs
1369 * or deleting an unused block group (the cleaner picked a block
1370 * group from the list of unused block groups before we were able to
1371 * in the previous call to btrfs_delete_unused_bgs()).
1372 */
1373 wait_on_bit(&fs_info->flags, BTRFS_FS_CLEANER_RUNNING, TASK_UNINTERRUPTIBLE);
1374
1375 /*
1376 * We've set the superblock to RO mode, so we might have made the
1377 * cleaner task sleep without running all pending delayed iputs. Go
1378 * through all the delayed iputs here, so that if an unmount happens
1379 * without remounting RW we don't end up at finishing close_ctree()
1380 * with a non-empty list of delayed iputs.
1381 */
1382 btrfs_run_delayed_iputs(fs_info);
1383
1384 btrfs_dev_replace_suspend_for_unmount(fs_info);
1385 btrfs_scrub_cancel(fs_info);
1386 btrfs_pause_balance(fs_info);
1387
1388 /*
1389 * Pause the qgroup rescan worker if it is running. We don't want it to
1390 * be still running after we are in RO mode, as after that, by the time
1391 * we unmount, it might have left a transaction open, so we would leak
1392 * the transaction and/or crash.
1393 */
1394 btrfs_qgroup_wait_for_completion(fs_info, false);
1395
1396 return btrfs_commit_super(fs_info);
1397 }
1398
btrfs_ctx_to_info(struct btrfs_fs_info * fs_info,struct btrfs_fs_context * ctx)1399 static void btrfs_ctx_to_info(struct btrfs_fs_info *fs_info, struct btrfs_fs_context *ctx)
1400 {
1401 fs_info->max_inline = ctx->max_inline;
1402 fs_info->commit_interval = ctx->commit_interval;
1403 fs_info->metadata_ratio = ctx->metadata_ratio;
1404 fs_info->thread_pool_size = ctx->thread_pool_size;
1405 fs_info->mount_opt = ctx->mount_opt;
1406 fs_info->compress_type = ctx->compress_type;
1407 fs_info->compress_level = ctx->compress_level;
1408 }
1409
btrfs_info_to_ctx(struct btrfs_fs_info * fs_info,struct btrfs_fs_context * ctx)1410 static void btrfs_info_to_ctx(struct btrfs_fs_info *fs_info, struct btrfs_fs_context *ctx)
1411 {
1412 ctx->max_inline = fs_info->max_inline;
1413 ctx->commit_interval = fs_info->commit_interval;
1414 ctx->metadata_ratio = fs_info->metadata_ratio;
1415 ctx->thread_pool_size = fs_info->thread_pool_size;
1416 ctx->mount_opt = fs_info->mount_opt;
1417 ctx->compress_type = fs_info->compress_type;
1418 ctx->compress_level = fs_info->compress_level;
1419 }
1420
1421 #define btrfs_info_if_set(fs_info, old_ctx, opt, fmt, args...) \
1422 do { \
1423 if ((!old_ctx || !btrfs_raw_test_opt(old_ctx->mount_opt, opt)) && \
1424 btrfs_raw_test_opt(fs_info->mount_opt, opt)) \
1425 btrfs_info(fs_info, fmt, ##args); \
1426 } while (0)
1427
1428 #define btrfs_info_if_unset(fs_info, old_ctx, opt, fmt, args...) \
1429 do { \
1430 if ((old_ctx && btrfs_raw_test_opt(old_ctx->mount_opt, opt)) && \
1431 !btrfs_raw_test_opt(fs_info->mount_opt, opt)) \
1432 btrfs_info(fs_info, fmt, ##args); \
1433 } while (0)
1434
btrfs_emit_options(struct btrfs_fs_info * info,struct btrfs_fs_context * old)1435 static void btrfs_emit_options(struct btrfs_fs_info *info,
1436 struct btrfs_fs_context *old)
1437 {
1438 btrfs_info_if_set(info, old, NODATASUM, "setting nodatasum");
1439 btrfs_info_if_set(info, old, DEGRADED, "allowing degraded mounts");
1440 btrfs_info_if_set(info, old, NODATASUM, "setting nodatasum");
1441 btrfs_info_if_set(info, old, SSD, "enabling ssd optimizations");
1442 btrfs_info_if_set(info, old, SSD_SPREAD, "using spread ssd allocation scheme");
1443 btrfs_info_if_set(info, old, NOBARRIER, "turning off barriers");
1444 btrfs_info_if_set(info, old, NOTREELOG, "disabling tree log");
1445 btrfs_info_if_set(info, old, NOLOGREPLAY, "disabling log replay at mount time");
1446 btrfs_info_if_set(info, old, FLUSHONCOMMIT, "turning on flush-on-commit");
1447 btrfs_info_if_set(info, old, DISCARD_SYNC, "turning on sync discard");
1448 btrfs_info_if_set(info, old, DISCARD_ASYNC, "turning on async discard");
1449 btrfs_info_if_set(info, old, FREE_SPACE_TREE, "enabling free space tree");
1450 btrfs_info_if_set(info, old, SPACE_CACHE, "enabling disk space caching");
1451 btrfs_info_if_set(info, old, CLEAR_CACHE, "force clearing of disk cache");
1452 btrfs_info_if_set(info, old, AUTO_DEFRAG, "enabling auto defrag");
1453 btrfs_info_if_set(info, old, FRAGMENT_DATA, "fragmenting data");
1454 btrfs_info_if_set(info, old, FRAGMENT_METADATA, "fragmenting metadata");
1455 btrfs_info_if_set(info, old, REF_VERIFY, "doing ref verification");
1456 btrfs_info_if_set(info, old, USEBACKUPROOT, "trying to use backup root at mount time");
1457 btrfs_info_if_set(info, old, IGNOREBADROOTS, "ignoring bad roots");
1458 btrfs_info_if_set(info, old, IGNOREDATACSUMS, "ignoring data csums");
1459 btrfs_info_if_set(info, old, IGNOREMETACSUMS, "ignoring meta csums");
1460 btrfs_info_if_set(info, old, IGNORESUPERFLAGS, "ignoring unknown super block flags");
1461
1462 btrfs_info_if_unset(info, old, NODATACOW, "setting datacow");
1463 btrfs_info_if_unset(info, old, SSD, "not using ssd optimizations");
1464 btrfs_info_if_unset(info, old, SSD_SPREAD, "not using spread ssd allocation scheme");
1465 btrfs_info_if_unset(info, old, NOBARRIER, "turning off barriers");
1466 btrfs_info_if_unset(info, old, NOTREELOG, "enabling tree log");
1467 btrfs_info_if_unset(info, old, SPACE_CACHE, "disabling disk space caching");
1468 btrfs_info_if_unset(info, old, FREE_SPACE_TREE, "disabling free space tree");
1469 btrfs_info_if_unset(info, old, AUTO_DEFRAG, "disabling auto defrag");
1470 btrfs_info_if_unset(info, old, COMPRESS, "use no compression");
1471
1472 /* Did the compression settings change? */
1473 if (btrfs_test_opt(info, COMPRESS) &&
1474 (!old ||
1475 old->compress_type != info->compress_type ||
1476 old->compress_level != info->compress_level ||
1477 (!btrfs_raw_test_opt(old->mount_opt, FORCE_COMPRESS) &&
1478 btrfs_raw_test_opt(info->mount_opt, FORCE_COMPRESS)))) {
1479 const char *compress_type = btrfs_compress_type2str(info->compress_type);
1480
1481 btrfs_info(info, "%s %s compression, level %d",
1482 btrfs_test_opt(info, FORCE_COMPRESS) ? "force" : "use",
1483 compress_type, info->compress_level);
1484 }
1485
1486 if (info->max_inline != BTRFS_DEFAULT_MAX_INLINE)
1487 btrfs_info(info, "max_inline set to %llu", info->max_inline);
1488 }
1489
btrfs_reconfigure(struct fs_context * fc)1490 static int btrfs_reconfigure(struct fs_context *fc)
1491 {
1492 struct super_block *sb = fc->root->d_sb;
1493 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
1494 struct btrfs_fs_context *ctx = fc->fs_private;
1495 struct btrfs_fs_context old_ctx;
1496 int ret = 0;
1497 bool mount_reconfigure = (fc->s_fs_info != NULL);
1498
1499 btrfs_info_to_ctx(fs_info, &old_ctx);
1500
1501 /*
1502 * This is our "bind mount" trick, we don't want to allow the user to do
1503 * anything other than mount a different ro/rw and a different subvol,
1504 * all of the mount options should be maintained.
1505 */
1506 if (mount_reconfigure)
1507 ctx->mount_opt = old_ctx.mount_opt;
1508
1509 sync_filesystem(sb);
1510 set_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state);
1511
1512 if (!btrfs_check_options(fs_info, &ctx->mount_opt, fc->sb_flags))
1513 return -EINVAL;
1514
1515 ret = btrfs_check_features(fs_info, !(fc->sb_flags & SB_RDONLY));
1516 if (ret < 0)
1517 return ret;
1518
1519 btrfs_ctx_to_info(fs_info, ctx);
1520 btrfs_remount_begin(fs_info, old_ctx.mount_opt, fc->sb_flags);
1521 btrfs_resize_thread_pool(fs_info, fs_info->thread_pool_size,
1522 old_ctx.thread_pool_size);
1523
1524 if ((bool)btrfs_test_opt(fs_info, FREE_SPACE_TREE) !=
1525 (bool)btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
1526 (!sb_rdonly(sb) || (fc->sb_flags & SB_RDONLY))) {
1527 btrfs_warn(fs_info,
1528 "remount supports changing free space tree only from RO to RW");
1529 /* Make sure free space cache options match the state on disk. */
1530 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
1531 btrfs_set_opt(fs_info->mount_opt, FREE_SPACE_TREE);
1532 btrfs_clear_opt(fs_info->mount_opt, SPACE_CACHE);
1533 }
1534 if (btrfs_free_space_cache_v1_active(fs_info)) {
1535 btrfs_clear_opt(fs_info->mount_opt, FREE_SPACE_TREE);
1536 btrfs_set_opt(fs_info->mount_opt, SPACE_CACHE);
1537 }
1538 }
1539
1540 ret = 0;
1541 if (!sb_rdonly(sb) && (fc->sb_flags & SB_RDONLY))
1542 ret = btrfs_remount_ro(fs_info);
1543 else if (sb_rdonly(sb) && !(fc->sb_flags & SB_RDONLY))
1544 ret = btrfs_remount_rw(fs_info);
1545 if (ret)
1546 goto restore;
1547
1548 /*
1549 * If we set the mask during the parameter parsing VFS would reject the
1550 * remount. Here we can set the mask and the value will be updated
1551 * appropriately.
1552 */
1553 if ((fc->sb_flags & SB_POSIXACL) != (sb->s_flags & SB_POSIXACL))
1554 fc->sb_flags_mask |= SB_POSIXACL;
1555
1556 btrfs_emit_options(fs_info, &old_ctx);
1557 wake_up_process(fs_info->transaction_kthread);
1558 btrfs_remount_cleanup(fs_info, old_ctx.mount_opt);
1559 btrfs_clear_oneshot_options(fs_info);
1560 clear_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state);
1561
1562 return 0;
1563 restore:
1564 btrfs_ctx_to_info(fs_info, &old_ctx);
1565 btrfs_remount_cleanup(fs_info, old_ctx.mount_opt);
1566 clear_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state);
1567 return ret;
1568 }
1569
1570 /* Used to sort the devices by max_avail(descending sort) */
btrfs_cmp_device_free_bytes(const void * a,const void * b)1571 static int btrfs_cmp_device_free_bytes(const void *a, const void *b)
1572 {
1573 const struct btrfs_device_info *dev_info1 = a;
1574 const struct btrfs_device_info *dev_info2 = b;
1575
1576 if (dev_info1->max_avail > dev_info2->max_avail)
1577 return -1;
1578 else if (dev_info1->max_avail < dev_info2->max_avail)
1579 return 1;
1580 return 0;
1581 }
1582
1583 /*
1584 * sort the devices by max_avail, in which max free extent size of each device
1585 * is stored.(Descending Sort)
1586 */
btrfs_descending_sort_devices(struct btrfs_device_info * devices,size_t nr_devices)1587 static inline void btrfs_descending_sort_devices(
1588 struct btrfs_device_info *devices,
1589 size_t nr_devices)
1590 {
1591 sort(devices, nr_devices, sizeof(struct btrfs_device_info),
1592 btrfs_cmp_device_free_bytes, NULL);
1593 }
1594
1595 /*
1596 * The helper to calc the free space on the devices that can be used to store
1597 * file data.
1598 */
btrfs_calc_avail_data_space(struct btrfs_fs_info * fs_info,u64 * free_bytes)1599 static inline int btrfs_calc_avail_data_space(struct btrfs_fs_info *fs_info,
1600 u64 *free_bytes)
1601 {
1602 struct btrfs_device_info *devices_info;
1603 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
1604 struct btrfs_device *device;
1605 u64 type;
1606 u64 avail_space;
1607 u64 min_stripe_size;
1608 int num_stripes = 1;
1609 int i = 0, nr_devices;
1610 const struct btrfs_raid_attr *rattr;
1611
1612 /*
1613 * We aren't under the device list lock, so this is racy-ish, but good
1614 * enough for our purposes.
1615 */
1616 nr_devices = fs_info->fs_devices->open_devices;
1617 if (!nr_devices) {
1618 smp_mb();
1619 nr_devices = fs_info->fs_devices->open_devices;
1620 ASSERT(nr_devices);
1621 if (!nr_devices) {
1622 *free_bytes = 0;
1623 return 0;
1624 }
1625 }
1626
1627 devices_info = kmalloc_array(nr_devices, sizeof(*devices_info),
1628 GFP_KERNEL);
1629 if (!devices_info)
1630 return -ENOMEM;
1631
1632 /* calc min stripe number for data space allocation */
1633 type = btrfs_data_alloc_profile(fs_info);
1634 rattr = &btrfs_raid_array[btrfs_bg_flags_to_raid_index(type)];
1635
1636 if (type & BTRFS_BLOCK_GROUP_RAID0)
1637 num_stripes = nr_devices;
1638 else if (type & BTRFS_BLOCK_GROUP_RAID1_MASK)
1639 num_stripes = rattr->ncopies;
1640 else if (type & BTRFS_BLOCK_GROUP_RAID10)
1641 num_stripes = 4;
1642
1643 /* Adjust for more than 1 stripe per device */
1644 min_stripe_size = rattr->dev_stripes * BTRFS_STRIPE_LEN;
1645
1646 rcu_read_lock();
1647 list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
1648 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
1649 &device->dev_state) ||
1650 !device->bdev ||
1651 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
1652 continue;
1653
1654 if (i >= nr_devices)
1655 break;
1656
1657 avail_space = device->total_bytes - device->bytes_used;
1658
1659 /* align with stripe_len */
1660 avail_space = rounddown(avail_space, BTRFS_STRIPE_LEN);
1661
1662 /*
1663 * Ensure we have at least min_stripe_size on top of the
1664 * reserved space on the device.
1665 */
1666 if (avail_space <= BTRFS_DEVICE_RANGE_RESERVED + min_stripe_size)
1667 continue;
1668
1669 avail_space -= BTRFS_DEVICE_RANGE_RESERVED;
1670
1671 devices_info[i].dev = device;
1672 devices_info[i].max_avail = avail_space;
1673
1674 i++;
1675 }
1676 rcu_read_unlock();
1677
1678 nr_devices = i;
1679
1680 btrfs_descending_sort_devices(devices_info, nr_devices);
1681
1682 i = nr_devices - 1;
1683 avail_space = 0;
1684 while (nr_devices >= rattr->devs_min) {
1685 num_stripes = min(num_stripes, nr_devices);
1686
1687 if (devices_info[i].max_avail >= min_stripe_size) {
1688 int j;
1689 u64 alloc_size;
1690
1691 avail_space += devices_info[i].max_avail * num_stripes;
1692 alloc_size = devices_info[i].max_avail;
1693 for (j = i + 1 - num_stripes; j <= i; j++)
1694 devices_info[j].max_avail -= alloc_size;
1695 }
1696 i--;
1697 nr_devices--;
1698 }
1699
1700 kfree(devices_info);
1701 *free_bytes = avail_space;
1702 return 0;
1703 }
1704
1705 /*
1706 * Calculate numbers for 'df', pessimistic in case of mixed raid profiles.
1707 *
1708 * If there's a redundant raid level at DATA block groups, use the respective
1709 * multiplier to scale the sizes.
1710 *
1711 * Unused device space usage is based on simulating the chunk allocator
1712 * algorithm that respects the device sizes and order of allocations. This is
1713 * a close approximation of the actual use but there are other factors that may
1714 * change the result (like a new metadata chunk).
1715 *
1716 * If metadata is exhausted, f_bavail will be 0.
1717 */
btrfs_statfs(struct dentry * dentry,struct kstatfs * buf)1718 static int btrfs_statfs(struct dentry *dentry, struct kstatfs *buf)
1719 {
1720 struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
1721 struct btrfs_super_block *disk_super = fs_info->super_copy;
1722 struct btrfs_space_info *found;
1723 u64 total_used = 0;
1724 u64 total_free_data = 0;
1725 u64 total_free_meta = 0;
1726 u32 bits = fs_info->sectorsize_bits;
1727 __be32 *fsid = (__be32 *)fs_info->fs_devices->fsid;
1728 unsigned factor = 1;
1729 struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
1730 int ret;
1731 u64 thresh = 0;
1732 int mixed = 0;
1733
1734 list_for_each_entry(found, &fs_info->space_info, list) {
1735 if (found->flags & BTRFS_BLOCK_GROUP_DATA) {
1736 int i;
1737
1738 total_free_data += found->disk_total - found->disk_used;
1739 total_free_data -=
1740 btrfs_account_ro_block_groups_free_space(found);
1741
1742 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
1743 if (!list_empty(&found->block_groups[i]))
1744 factor = btrfs_bg_type_to_factor(
1745 btrfs_raid_array[i].bg_flag);
1746 }
1747 }
1748
1749 /*
1750 * Metadata in mixed block group profiles are accounted in data
1751 */
1752 if (!mixed && found->flags & BTRFS_BLOCK_GROUP_METADATA) {
1753 if (found->flags & BTRFS_BLOCK_GROUP_DATA)
1754 mixed = 1;
1755 else
1756 total_free_meta += found->disk_total -
1757 found->disk_used;
1758 }
1759
1760 total_used += found->disk_used;
1761 }
1762
1763 buf->f_blocks = div_u64(btrfs_super_total_bytes(disk_super), factor);
1764 buf->f_blocks >>= bits;
1765 buf->f_bfree = buf->f_blocks - (div_u64(total_used, factor) >> bits);
1766
1767 /* Account global block reserve as used, it's in logical size already */
1768 spin_lock(&block_rsv->lock);
1769 /* Mixed block groups accounting is not byte-accurate, avoid overflow */
1770 if (buf->f_bfree >= block_rsv->size >> bits)
1771 buf->f_bfree -= block_rsv->size >> bits;
1772 else
1773 buf->f_bfree = 0;
1774 spin_unlock(&block_rsv->lock);
1775
1776 buf->f_bavail = div_u64(total_free_data, factor);
1777 ret = btrfs_calc_avail_data_space(fs_info, &total_free_data);
1778 if (ret)
1779 return ret;
1780 buf->f_bavail += div_u64(total_free_data, factor);
1781 buf->f_bavail = buf->f_bavail >> bits;
1782
1783 /*
1784 * We calculate the remaining metadata space minus global reserve. If
1785 * this is (supposedly) smaller than zero, there's no space. But this
1786 * does not hold in practice, the exhausted state happens where's still
1787 * some positive delta. So we apply some guesswork and compare the
1788 * delta to a 4M threshold. (Practically observed delta was ~2M.)
1789 *
1790 * We probably cannot calculate the exact threshold value because this
1791 * depends on the internal reservations requested by various
1792 * operations, so some operations that consume a few metadata will
1793 * succeed even if the Avail is zero. But this is better than the other
1794 * way around.
1795 */
1796 thresh = SZ_4M;
1797
1798 /*
1799 * We only want to claim there's no available space if we can no longer
1800 * allocate chunks for our metadata profile and our global reserve will
1801 * not fit in the free metadata space. If we aren't ->full then we
1802 * still can allocate chunks and thus are fine using the currently
1803 * calculated f_bavail.
1804 */
1805 if (!mixed && block_rsv->space_info->full &&
1806 (total_free_meta < thresh || total_free_meta - thresh < block_rsv->size))
1807 buf->f_bavail = 0;
1808
1809 buf->f_type = BTRFS_SUPER_MAGIC;
1810 buf->f_bsize = fs_info->sectorsize;
1811 buf->f_namelen = BTRFS_NAME_LEN;
1812
1813 /* We treat it as constant endianness (it doesn't matter _which_)
1814 because we want the fsid to come out the same whether mounted
1815 on a big-endian or little-endian host */
1816 buf->f_fsid.val[0] = be32_to_cpu(fsid[0]) ^ be32_to_cpu(fsid[2]);
1817 buf->f_fsid.val[1] = be32_to_cpu(fsid[1]) ^ be32_to_cpu(fsid[3]);
1818 /* Mask in the root object ID too, to disambiguate subvols */
1819 buf->f_fsid.val[0] ^= btrfs_root_id(BTRFS_I(d_inode(dentry))->root) >> 32;
1820 buf->f_fsid.val[1] ^= btrfs_root_id(BTRFS_I(d_inode(dentry))->root);
1821
1822 return 0;
1823 }
1824
btrfs_fc_test_super(struct super_block * sb,struct fs_context * fc)1825 static int btrfs_fc_test_super(struct super_block *sb, struct fs_context *fc)
1826 {
1827 struct btrfs_fs_info *p = fc->s_fs_info;
1828 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
1829
1830 return fs_info->fs_devices == p->fs_devices;
1831 }
1832
btrfs_get_tree_super(struct fs_context * fc)1833 static int btrfs_get_tree_super(struct fs_context *fc)
1834 {
1835 struct btrfs_fs_info *fs_info = fc->s_fs_info;
1836 struct btrfs_fs_context *ctx = fc->fs_private;
1837 struct btrfs_fs_devices *fs_devices = NULL;
1838 struct btrfs_device *device;
1839 struct super_block *sb;
1840 blk_mode_t mode = sb_open_mode(fc->sb_flags);
1841 int ret;
1842
1843 btrfs_ctx_to_info(fs_info, ctx);
1844 mutex_lock(&uuid_mutex);
1845
1846 /*
1847 * With 'true' passed to btrfs_scan_one_device() (mount time) we expect
1848 * either a valid device or an error.
1849 */
1850 device = btrfs_scan_one_device(fc->source, true);
1851 ASSERT(device != NULL);
1852 if (IS_ERR(device)) {
1853 mutex_unlock(&uuid_mutex);
1854 return PTR_ERR(device);
1855 }
1856 fs_devices = device->fs_devices;
1857 /*
1858 * We cannot hold uuid_mutex calling sget_fc(), it will lead to a
1859 * locking order reversal with s_umount.
1860 *
1861 * So here we increase the holding number of fs_devices, this will ensure
1862 * the fs_devices itself won't be freed.
1863 */
1864 btrfs_fs_devices_inc_holding(fs_devices);
1865 fs_info->fs_devices = fs_devices;
1866 mutex_unlock(&uuid_mutex);
1867
1868
1869 sb = sget_fc(fc, btrfs_fc_test_super, set_anon_super_fc);
1870 if (IS_ERR(sb)) {
1871 mutex_lock(&uuid_mutex);
1872 btrfs_fs_devices_dec_holding(fs_devices);
1873 /*
1874 * Since the fs_devices is not opened, it can be freed at any
1875 * time after unlocking uuid_mutex. We need to avoid double
1876 * free through put_fs_context()->btrfs_free_fs_info().
1877 * So here we reset fs_info->fs_devices to NULL, and let the
1878 * regular fs_devices reclaim path to handle it.
1879 *
1880 * This applies to all later branches where no fs_devices is
1881 * opened.
1882 */
1883 fs_info->fs_devices = NULL;
1884 mutex_unlock(&uuid_mutex);
1885 return PTR_ERR(sb);
1886 }
1887
1888 set_device_specific_options(fs_info);
1889
1890 if (sb->s_root) {
1891 /*
1892 * Not the first mount of the fs thus got an existing super block.
1893 * Will reuse the returned super block, fs_info and fs_devices.
1894 *
1895 * fc->s_fs_info is not touched and will be later freed by
1896 * put_fs_context() through btrfs_free_fs_context().
1897 */
1898 ASSERT(fc->s_fs_info == fs_info);
1899
1900 mutex_lock(&uuid_mutex);
1901 btrfs_fs_devices_dec_holding(fs_devices);
1902 fs_info->fs_devices = NULL;
1903 mutex_unlock(&uuid_mutex);
1904 /*
1905 * At this stage we may have RO flag mismatch between
1906 * fc->sb_flags and sb->s_flags. Caller should detect such
1907 * mismatch and reconfigure with sb->s_umount rwsem held if
1908 * needed.
1909 */
1910 } else {
1911 struct block_device *bdev;
1912
1913 /*
1914 * The first mount of the fs thus a new superblock, fc->s_fs_info
1915 * must be NULL, and the ownership of our fs_info and fs_devices is
1916 * transferred to the super block.
1917 */
1918 ASSERT(fc->s_fs_info == NULL);
1919
1920 mutex_lock(&uuid_mutex);
1921 btrfs_fs_devices_dec_holding(fs_devices);
1922 ret = btrfs_open_devices(fs_devices, mode, sb);
1923 if (ret < 0)
1924 fs_info->fs_devices = NULL;
1925 mutex_unlock(&uuid_mutex);
1926 if (ret < 0) {
1927 deactivate_locked_super(sb);
1928 return ret;
1929 }
1930 if (!(fc->sb_flags & SB_RDONLY) && fs_devices->rw_devices == 0) {
1931 deactivate_locked_super(sb);
1932 return -EACCES;
1933 }
1934 bdev = fs_devices->latest_dev->bdev;
1935 snprintf(sb->s_id, sizeof(sb->s_id), "%pg", bdev);
1936 shrinker_debugfs_rename(sb->s_shrink, "sb-btrfs:%s", sb->s_id);
1937 ret = btrfs_fill_super(sb, fs_devices);
1938 if (ret) {
1939 deactivate_locked_super(sb);
1940 return ret;
1941 }
1942 }
1943
1944 btrfs_clear_oneshot_options(fs_info);
1945
1946 fc->root = dget(sb->s_root);
1947 return 0;
1948 }
1949
1950 /*
1951 * Ever since commit 0723a0473fb4 ("btrfs: allow mounting btrfs subvolumes
1952 * with different ro/rw options") the following works:
1953 *
1954 * (i) mount /dev/sda3 -o subvol=foo,ro /mnt/foo
1955 * (ii) mount /dev/sda3 -o subvol=bar,rw /mnt/bar
1956 *
1957 * which looks nice and innocent but is actually pretty intricate and deserves
1958 * a long comment.
1959 *
1960 * On another filesystem a subvolume mount is close to something like:
1961 *
1962 * (iii) # create rw superblock + initial mount
1963 * mount -t xfs /dev/sdb /opt/
1964 *
1965 * # create ro bind mount
1966 * mount --bind -o ro /opt/foo /mnt/foo
1967 *
1968 * # unmount initial mount
1969 * umount /opt
1970 *
1971 * Of course, there's some special subvolume sauce and there's the fact that the
1972 * sb->s_root dentry is really swapped after mount_subtree(). But conceptually
1973 * it's very close and will help us understand the issue.
1974 *
1975 * The old mount API didn't cleanly distinguish between a mount being made ro
1976 * and a superblock being made ro. The only way to change the ro state of
1977 * either object was by passing ms_rdonly. If a new mount was created via
1978 * mount(2) such as:
1979 *
1980 * mount("/dev/sdb", "/mnt", "xfs", ms_rdonly, null);
1981 *
1982 * the MS_RDONLY flag being specified had two effects:
1983 *
1984 * (1) MNT_READONLY was raised -> the resulting mount got
1985 * @mnt->mnt_flags |= MNT_READONLY raised.
1986 *
1987 * (2) MS_RDONLY was passed to the filesystem's mount method and the filesystems
1988 * made the superblock ro. Note, how SB_RDONLY has the same value as
1989 * ms_rdonly and is raised whenever MS_RDONLY is passed through mount(2).
1990 *
1991 * Creating a subtree mount via (iii) ends up leaving a rw superblock with a
1992 * subtree mounted ro.
1993 *
1994 * But consider the effect on the old mount API on btrfs subvolume mounting
1995 * which combines the distinct step in (iii) into a single step.
1996 *
1997 * By issuing (i) both the mount and the superblock are turned ro. Now when (ii)
1998 * is issued the superblock is ro and thus even if the mount created for (ii) is
1999 * rw it wouldn't help. Hence, btrfs needed to transition the superblock from ro
2000 * to rw for (ii) which it did using an internal remount call.
2001 *
2002 * IOW, subvolume mounting was inherently complicated due to the ambiguity of
2003 * MS_RDONLY in mount(2). Note, this ambiguity has mount(8) always translate
2004 * "ro" to MS_RDONLY. IOW, in both (i) and (ii) "ro" becomes MS_RDONLY when
2005 * passed by mount(8) to mount(2).
2006 *
2007 * Enter the new mount API. The new mount API disambiguates making a mount ro
2008 * and making a superblock ro.
2009 *
2010 * (3) To turn a mount ro the MOUNT_ATTR_ONLY flag can be used with either
2011 * fsmount() or mount_setattr() this is a pure VFS level change for a
2012 * specific mount or mount tree that is never seen by the filesystem itself.
2013 *
2014 * (4) To turn a superblock ro the "ro" flag must be used with
2015 * fsconfig(FSCONFIG_SET_FLAG, "ro"). This option is seen by the filesystem
2016 * in fc->sb_flags.
2017 *
2018 * But, currently the util-linux mount command already utilizes the new mount
2019 * API and is still setting fsconfig(FSCONFIG_SET_FLAG, "ro") no matter if it's
2020 * btrfs or not, setting the whole super block RO. To make per-subvolume mounting
2021 * work with different options work we need to keep backward compatibility.
2022 */
btrfs_reconfigure_for_mount(struct fs_context * fc)2023 static int btrfs_reconfigure_for_mount(struct fs_context *fc)
2024 {
2025 int ret = 0;
2026
2027 if (!(fc->sb_flags & SB_RDONLY) && (fc->root->d_sb->s_flags & SB_RDONLY))
2028 ret = btrfs_reconfigure(fc);
2029
2030 return ret;
2031 }
2032
btrfs_get_tree_subvol(struct fs_context * fc)2033 static int btrfs_get_tree_subvol(struct fs_context *fc)
2034 {
2035 struct btrfs_fs_info *fs_info = NULL;
2036 struct btrfs_fs_context *ctx = fc->fs_private;
2037 struct fs_context *dup_fc;
2038 struct dentry *dentry;
2039 struct vfsmount *mnt;
2040 int ret = 0;
2041
2042 /*
2043 * Setup a dummy root and fs_info for test/set super. This is because
2044 * we don't actually fill this stuff out until open_ctree, but we need
2045 * then open_ctree will properly initialize the file system specific
2046 * settings later. btrfs_init_fs_info initializes the static elements
2047 * of the fs_info (locks and such) to make cleanup easier if we find a
2048 * superblock with our given fs_devices later on at sget() time.
2049 */
2050 fs_info = kvzalloc(sizeof(struct btrfs_fs_info), GFP_KERNEL);
2051 if (!fs_info)
2052 return -ENOMEM;
2053
2054 fs_info->super_copy = kzalloc(BTRFS_SUPER_INFO_SIZE, GFP_KERNEL);
2055 fs_info->super_for_commit = kzalloc(BTRFS_SUPER_INFO_SIZE, GFP_KERNEL);
2056 if (!fs_info->super_copy || !fs_info->super_for_commit) {
2057 btrfs_free_fs_info(fs_info);
2058 return -ENOMEM;
2059 }
2060 btrfs_init_fs_info(fs_info);
2061
2062 dup_fc = vfs_dup_fs_context(fc);
2063 if (IS_ERR(dup_fc)) {
2064 btrfs_free_fs_info(fs_info);
2065 return PTR_ERR(dup_fc);
2066 }
2067
2068 /*
2069 * When we do the sget_fc this gets transferred to the sb, so we only
2070 * need to set it on the dup_fc as this is what creates the super block.
2071 */
2072 dup_fc->s_fs_info = fs_info;
2073
2074 ret = btrfs_get_tree_super(dup_fc);
2075 if (ret)
2076 goto error;
2077
2078 ret = btrfs_reconfigure_for_mount(dup_fc);
2079 up_write(&dup_fc->root->d_sb->s_umount);
2080 if (ret)
2081 goto error;
2082 mnt = vfs_create_mount(dup_fc);
2083 put_fs_context(dup_fc);
2084 if (IS_ERR(mnt))
2085 return PTR_ERR(mnt);
2086
2087 /*
2088 * This free's ->subvol_name, because if it isn't set we have to
2089 * allocate a buffer to hold the subvol_name, so we just drop our
2090 * reference to it here.
2091 */
2092 dentry = mount_subvol(ctx->subvol_name, ctx->subvol_objectid, mnt);
2093 ctx->subvol_name = NULL;
2094 if (IS_ERR(dentry))
2095 return PTR_ERR(dentry);
2096
2097 fc->root = dentry;
2098 return 0;
2099 error:
2100 put_fs_context(dup_fc);
2101 return ret;
2102 }
2103
btrfs_get_tree(struct fs_context * fc)2104 static int btrfs_get_tree(struct fs_context *fc)
2105 {
2106 ASSERT(fc->s_fs_info == NULL);
2107
2108 return btrfs_get_tree_subvol(fc);
2109 }
2110
btrfs_kill_super(struct super_block * sb)2111 static void btrfs_kill_super(struct super_block *sb)
2112 {
2113 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
2114 kill_anon_super(sb);
2115 btrfs_free_fs_info(fs_info);
2116 }
2117
btrfs_free_fs_context(struct fs_context * fc)2118 static void btrfs_free_fs_context(struct fs_context *fc)
2119 {
2120 struct btrfs_fs_context *ctx = fc->fs_private;
2121 struct btrfs_fs_info *fs_info = fc->s_fs_info;
2122
2123 if (fs_info)
2124 btrfs_free_fs_info(fs_info);
2125
2126 if (ctx && refcount_dec_and_test(&ctx->refs)) {
2127 kfree(ctx->subvol_name);
2128 kfree(ctx);
2129 }
2130 }
2131
btrfs_dup_fs_context(struct fs_context * fc,struct fs_context * src_fc)2132 static int btrfs_dup_fs_context(struct fs_context *fc, struct fs_context *src_fc)
2133 {
2134 struct btrfs_fs_context *ctx = src_fc->fs_private;
2135
2136 /*
2137 * Give a ref to our ctx to this dup, as we want to keep it around for
2138 * our original fc so we can have the subvolume name or objectid.
2139 *
2140 * We unset ->source in the original fc because the dup needs it for
2141 * mounting, and then once we free the dup it'll free ->source, so we
2142 * need to make sure we're only pointing to it in one fc.
2143 */
2144 refcount_inc(&ctx->refs);
2145 fc->fs_private = ctx;
2146 fc->source = src_fc->source;
2147 src_fc->source = NULL;
2148 return 0;
2149 }
2150
2151 static const struct fs_context_operations btrfs_fs_context_ops = {
2152 .parse_param = btrfs_parse_param,
2153 .reconfigure = btrfs_reconfigure,
2154 .get_tree = btrfs_get_tree,
2155 .dup = btrfs_dup_fs_context,
2156 .free = btrfs_free_fs_context,
2157 };
2158
btrfs_init_fs_context(struct fs_context * fc)2159 static int btrfs_init_fs_context(struct fs_context *fc)
2160 {
2161 struct btrfs_fs_context *ctx;
2162
2163 ctx = kzalloc(sizeof(struct btrfs_fs_context), GFP_KERNEL);
2164 if (!ctx)
2165 return -ENOMEM;
2166
2167 refcount_set(&ctx->refs, 1);
2168 fc->fs_private = ctx;
2169 fc->ops = &btrfs_fs_context_ops;
2170
2171 if (fc->purpose == FS_CONTEXT_FOR_RECONFIGURE) {
2172 btrfs_info_to_ctx(btrfs_sb(fc->root->d_sb), ctx);
2173 } else {
2174 ctx->thread_pool_size =
2175 min_t(unsigned long, num_online_cpus() + 2, 8);
2176 ctx->max_inline = BTRFS_DEFAULT_MAX_INLINE;
2177 ctx->commit_interval = BTRFS_DEFAULT_COMMIT_INTERVAL;
2178 }
2179
2180 #ifdef CONFIG_BTRFS_FS_POSIX_ACL
2181 fc->sb_flags |= SB_POSIXACL;
2182 #endif
2183 fc->sb_flags |= SB_I_VERSION;
2184
2185 return 0;
2186 }
2187
2188 static struct file_system_type btrfs_fs_type = {
2189 .owner = THIS_MODULE,
2190 .name = "btrfs",
2191 .init_fs_context = btrfs_init_fs_context,
2192 .parameters = btrfs_fs_parameters,
2193 .kill_sb = btrfs_kill_super,
2194 .fs_flags = FS_REQUIRES_DEV | FS_BINARY_MOUNTDATA |
2195 FS_ALLOW_IDMAP | FS_MGTIME,
2196 };
2197
2198 MODULE_ALIAS_FS("btrfs");
2199
btrfs_control_open(struct inode * inode,struct file * file)2200 static int btrfs_control_open(struct inode *inode, struct file *file)
2201 {
2202 /*
2203 * The control file's private_data is used to hold the
2204 * transaction when it is started and is used to keep
2205 * track of whether a transaction is already in progress.
2206 */
2207 file->private_data = NULL;
2208 return 0;
2209 }
2210
2211 /*
2212 * Used by /dev/btrfs-control for devices ioctls.
2213 */
btrfs_control_ioctl(struct file * file,unsigned int cmd,unsigned long arg)2214 static long btrfs_control_ioctl(struct file *file, unsigned int cmd,
2215 unsigned long arg)
2216 {
2217 struct btrfs_ioctl_vol_args *vol;
2218 struct btrfs_device *device = NULL;
2219 dev_t devt = 0;
2220 int ret = -ENOTTY;
2221
2222 if (!capable(CAP_SYS_ADMIN))
2223 return -EPERM;
2224
2225 vol = memdup_user((void __user *)arg, sizeof(*vol));
2226 if (IS_ERR(vol))
2227 return PTR_ERR(vol);
2228 ret = btrfs_check_ioctl_vol_args_path(vol);
2229 if (ret < 0)
2230 goto out;
2231
2232 switch (cmd) {
2233 case BTRFS_IOC_SCAN_DEV:
2234 mutex_lock(&uuid_mutex);
2235 /*
2236 * Scanning outside of mount can return NULL which would turn
2237 * into 0 error code.
2238 */
2239 device = btrfs_scan_one_device(vol->name, false);
2240 ret = PTR_ERR_OR_ZERO(device);
2241 mutex_unlock(&uuid_mutex);
2242 break;
2243 case BTRFS_IOC_FORGET_DEV:
2244 if (vol->name[0] != 0) {
2245 ret = lookup_bdev(vol->name, &devt);
2246 if (ret)
2247 break;
2248 }
2249 ret = btrfs_forget_devices(devt);
2250 break;
2251 case BTRFS_IOC_DEVICES_READY:
2252 mutex_lock(&uuid_mutex);
2253 /*
2254 * Scanning outside of mount can return NULL which would turn
2255 * into 0 error code.
2256 */
2257 device = btrfs_scan_one_device(vol->name, false);
2258 if (IS_ERR_OR_NULL(device)) {
2259 mutex_unlock(&uuid_mutex);
2260 if (IS_ERR(device))
2261 ret = PTR_ERR(device);
2262 else
2263 ret = 0;
2264 break;
2265 }
2266 ret = !(device->fs_devices->num_devices ==
2267 device->fs_devices->total_devices);
2268 mutex_unlock(&uuid_mutex);
2269 break;
2270 case BTRFS_IOC_GET_SUPPORTED_FEATURES:
2271 ret = btrfs_ioctl_get_supported_features((void __user*)arg);
2272 break;
2273 }
2274
2275 out:
2276 kfree(vol);
2277 return ret;
2278 }
2279
btrfs_freeze(struct super_block * sb)2280 static int btrfs_freeze(struct super_block *sb)
2281 {
2282 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
2283
2284 set_bit(BTRFS_FS_FROZEN, &fs_info->flags);
2285 /*
2286 * We don't need a barrier here, we'll wait for any transaction that
2287 * could be in progress on other threads (and do delayed iputs that
2288 * we want to avoid on a frozen filesystem), or do the commit
2289 * ourselves.
2290 */
2291 return btrfs_commit_current_transaction(fs_info->tree_root);
2292 }
2293
check_dev_super(struct btrfs_device * dev)2294 static int check_dev_super(struct btrfs_device *dev)
2295 {
2296 struct btrfs_fs_info *fs_info = dev->fs_info;
2297 struct btrfs_super_block *sb;
2298 u64 last_trans;
2299 u16 csum_type;
2300 int ret = 0;
2301
2302 /* This should be called with fs still frozen. */
2303 ASSERT(test_bit(BTRFS_FS_FROZEN, &fs_info->flags));
2304
2305 /* Missing dev, no need to check. */
2306 if (!dev->bdev)
2307 return 0;
2308
2309 /* Only need to check the primary super block. */
2310 sb = btrfs_read_disk_super(dev->bdev, 0, true);
2311 if (IS_ERR(sb))
2312 return PTR_ERR(sb);
2313
2314 /* Verify the checksum. */
2315 csum_type = btrfs_super_csum_type(sb);
2316 if (csum_type != btrfs_super_csum_type(fs_info->super_copy)) {
2317 btrfs_err(fs_info, "csum type changed, has %u expect %u",
2318 csum_type, btrfs_super_csum_type(fs_info->super_copy));
2319 ret = -EUCLEAN;
2320 goto out;
2321 }
2322
2323 if (btrfs_check_super_csum(fs_info, sb)) {
2324 btrfs_err(fs_info, "csum for on-disk super block no longer matches");
2325 ret = -EUCLEAN;
2326 goto out;
2327 }
2328
2329 /* Btrfs_validate_super() includes fsid check against super->fsid. */
2330 ret = btrfs_validate_super(fs_info, sb, 0);
2331 if (ret < 0)
2332 goto out;
2333
2334 last_trans = btrfs_get_last_trans_committed(fs_info);
2335 if (btrfs_super_generation(sb) != last_trans) {
2336 btrfs_err(fs_info, "transid mismatch, has %llu expect %llu",
2337 btrfs_super_generation(sb), last_trans);
2338 ret = -EUCLEAN;
2339 goto out;
2340 }
2341 out:
2342 btrfs_release_disk_super(sb);
2343 return ret;
2344 }
2345
btrfs_unfreeze(struct super_block * sb)2346 static int btrfs_unfreeze(struct super_block *sb)
2347 {
2348 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
2349 struct btrfs_device *device;
2350 int ret = 0;
2351
2352 /*
2353 * Make sure the fs is not changed by accident (like hibernation then
2354 * modified by other OS).
2355 * If we found anything wrong, we mark the fs error immediately.
2356 *
2357 * And since the fs is frozen, no one can modify the fs yet, thus
2358 * we don't need to hold device_list_mutex.
2359 */
2360 list_for_each_entry(device, &fs_info->fs_devices->devices, dev_list) {
2361 ret = check_dev_super(device);
2362 if (ret < 0) {
2363 btrfs_handle_fs_error(fs_info, ret,
2364 "super block on devid %llu got modified unexpectedly",
2365 device->devid);
2366 break;
2367 }
2368 }
2369 clear_bit(BTRFS_FS_FROZEN, &fs_info->flags);
2370
2371 /*
2372 * We still return 0, to allow VFS layer to unfreeze the fs even the
2373 * above checks failed. Since the fs is either fine or read-only, we're
2374 * safe to continue, without causing further damage.
2375 */
2376 return 0;
2377 }
2378
btrfs_show_devname(struct seq_file * m,struct dentry * root)2379 static int btrfs_show_devname(struct seq_file *m, struct dentry *root)
2380 {
2381 struct btrfs_fs_info *fs_info = btrfs_sb(root->d_sb);
2382
2383 /*
2384 * There should be always a valid pointer in latest_dev, it may be stale
2385 * for a short moment in case it's being deleted but still valid until
2386 * the end of RCU grace period.
2387 */
2388 rcu_read_lock();
2389 seq_escape(m, btrfs_dev_name(fs_info->fs_devices->latest_dev), " \t\n\\");
2390 rcu_read_unlock();
2391
2392 return 0;
2393 }
2394
btrfs_nr_cached_objects(struct super_block * sb,struct shrink_control * sc)2395 static long btrfs_nr_cached_objects(struct super_block *sb, struct shrink_control *sc)
2396 {
2397 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
2398 const s64 nr = percpu_counter_sum_positive(&fs_info->evictable_extent_maps);
2399
2400 trace_btrfs_extent_map_shrinker_count(fs_info, nr);
2401
2402 return nr;
2403 }
2404
btrfs_free_cached_objects(struct super_block * sb,struct shrink_control * sc)2405 static long btrfs_free_cached_objects(struct super_block *sb, struct shrink_control *sc)
2406 {
2407 const long nr_to_scan = min_t(unsigned long, LONG_MAX, sc->nr_to_scan);
2408 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
2409
2410 btrfs_free_extent_maps(fs_info, nr_to_scan);
2411
2412 /* The extent map shrinker runs asynchronously, so always return 0. */
2413 return 0;
2414 }
2415
2416 static const struct super_operations btrfs_super_ops = {
2417 .drop_inode = btrfs_drop_inode,
2418 .evict_inode = btrfs_evict_inode,
2419 .put_super = btrfs_put_super,
2420 .sync_fs = btrfs_sync_fs,
2421 .show_options = btrfs_show_options,
2422 .show_devname = btrfs_show_devname,
2423 .alloc_inode = btrfs_alloc_inode,
2424 .destroy_inode = btrfs_destroy_inode,
2425 .free_inode = btrfs_free_inode,
2426 .statfs = btrfs_statfs,
2427 .freeze_fs = btrfs_freeze,
2428 .unfreeze_fs = btrfs_unfreeze,
2429 .nr_cached_objects = btrfs_nr_cached_objects,
2430 .free_cached_objects = btrfs_free_cached_objects,
2431 };
2432
2433 static const struct file_operations btrfs_ctl_fops = {
2434 .open = btrfs_control_open,
2435 .unlocked_ioctl = btrfs_control_ioctl,
2436 .compat_ioctl = compat_ptr_ioctl,
2437 .owner = THIS_MODULE,
2438 .llseek = noop_llseek,
2439 };
2440
2441 static struct miscdevice btrfs_misc = {
2442 .minor = BTRFS_MINOR,
2443 .name = "btrfs-control",
2444 .fops = &btrfs_ctl_fops
2445 };
2446
2447 MODULE_ALIAS_MISCDEV(BTRFS_MINOR);
2448 MODULE_ALIAS("devname:btrfs-control");
2449
btrfs_interface_init(void)2450 static int __init btrfs_interface_init(void)
2451 {
2452 return misc_register(&btrfs_misc);
2453 }
2454
btrfs_interface_exit(void)2455 static __cold void btrfs_interface_exit(void)
2456 {
2457 misc_deregister(&btrfs_misc);
2458 }
2459
btrfs_print_mod_info(void)2460 static int __init btrfs_print_mod_info(void)
2461 {
2462 static const char options[] = ""
2463 #ifdef CONFIG_BTRFS_EXPERIMENTAL
2464 ", experimental=on"
2465 #endif
2466 #ifdef CONFIG_BTRFS_DEBUG
2467 ", debug=on"
2468 #endif
2469 #ifdef CONFIG_BTRFS_ASSERT
2470 ", assert=on"
2471 #endif
2472 #ifdef CONFIG_BTRFS_FS_REF_VERIFY
2473 ", ref-verify=on"
2474 #endif
2475 #ifdef CONFIG_BLK_DEV_ZONED
2476 ", zoned=yes"
2477 #else
2478 ", zoned=no"
2479 #endif
2480 #ifdef CONFIG_FS_VERITY
2481 ", fsverity=yes"
2482 #else
2483 ", fsverity=no"
2484 #endif
2485 ;
2486
2487 #ifdef CONFIG_BTRFS_EXPERIMENTAL
2488 if (btrfs_get_mod_read_policy() == NULL)
2489 pr_info("Btrfs loaded%s\n", options);
2490 else
2491 pr_info("Btrfs loaded%s, read_policy=%s\n",
2492 options, btrfs_get_mod_read_policy());
2493 #else
2494 pr_info("Btrfs loaded%s\n", options);
2495 #endif
2496
2497 return 0;
2498 }
2499
register_btrfs(void)2500 static int register_btrfs(void)
2501 {
2502 return register_filesystem(&btrfs_fs_type);
2503 }
2504
unregister_btrfs(void)2505 static void unregister_btrfs(void)
2506 {
2507 unregister_filesystem(&btrfs_fs_type);
2508 }
2509
2510 /* Helper structure for long init/exit functions. */
2511 struct init_sequence {
2512 int (*init_func)(void);
2513 /* Can be NULL if the init_func doesn't need cleanup. */
2514 void (*exit_func)(void);
2515 };
2516
2517 static const struct init_sequence mod_init_seq[] = {
2518 {
2519 .init_func = btrfs_props_init,
2520 .exit_func = NULL,
2521 }, {
2522 .init_func = btrfs_init_sysfs,
2523 .exit_func = btrfs_exit_sysfs,
2524 }, {
2525 .init_func = btrfs_init_compress,
2526 .exit_func = btrfs_exit_compress,
2527 }, {
2528 .init_func = btrfs_init_cachep,
2529 .exit_func = btrfs_destroy_cachep,
2530 }, {
2531 .init_func = btrfs_init_dio,
2532 .exit_func = btrfs_destroy_dio,
2533 }, {
2534 .init_func = btrfs_transaction_init,
2535 .exit_func = btrfs_transaction_exit,
2536 }, {
2537 .init_func = btrfs_ctree_init,
2538 .exit_func = btrfs_ctree_exit,
2539 }, {
2540 .init_func = btrfs_free_space_init,
2541 .exit_func = btrfs_free_space_exit,
2542 }, {
2543 .init_func = btrfs_extent_state_init_cachep,
2544 .exit_func = btrfs_extent_state_free_cachep,
2545 }, {
2546 .init_func = extent_buffer_init_cachep,
2547 .exit_func = extent_buffer_free_cachep,
2548 }, {
2549 .init_func = btrfs_bioset_init,
2550 .exit_func = btrfs_bioset_exit,
2551 }, {
2552 .init_func = btrfs_extent_map_init,
2553 .exit_func = btrfs_extent_map_exit,
2554 #ifdef CONFIG_BTRFS_EXPERIMENTAL
2555 }, {
2556 .init_func = btrfs_read_policy_init,
2557 .exit_func = NULL,
2558 #endif
2559 }, {
2560 .init_func = ordered_data_init,
2561 .exit_func = ordered_data_exit,
2562 }, {
2563 .init_func = btrfs_delayed_inode_init,
2564 .exit_func = btrfs_delayed_inode_exit,
2565 }, {
2566 .init_func = btrfs_auto_defrag_init,
2567 .exit_func = btrfs_auto_defrag_exit,
2568 }, {
2569 .init_func = btrfs_delayed_ref_init,
2570 .exit_func = btrfs_delayed_ref_exit,
2571 }, {
2572 .init_func = btrfs_prelim_ref_init,
2573 .exit_func = btrfs_prelim_ref_exit,
2574 }, {
2575 .init_func = btrfs_interface_init,
2576 .exit_func = btrfs_interface_exit,
2577 }, {
2578 .init_func = btrfs_print_mod_info,
2579 .exit_func = NULL,
2580 }, {
2581 .init_func = btrfs_run_sanity_tests,
2582 .exit_func = NULL,
2583 }, {
2584 .init_func = register_btrfs,
2585 .exit_func = unregister_btrfs,
2586 }
2587 };
2588
2589 static bool mod_init_result[ARRAY_SIZE(mod_init_seq)];
2590
btrfs_exit_btrfs_fs(void)2591 static __always_inline void btrfs_exit_btrfs_fs(void)
2592 {
2593 int i;
2594
2595 for (i = ARRAY_SIZE(mod_init_seq) - 1; i >= 0; i--) {
2596 if (!mod_init_result[i])
2597 continue;
2598 if (mod_init_seq[i].exit_func)
2599 mod_init_seq[i].exit_func();
2600 mod_init_result[i] = false;
2601 }
2602 }
2603
exit_btrfs_fs(void)2604 static void __exit exit_btrfs_fs(void)
2605 {
2606 btrfs_exit_btrfs_fs();
2607 btrfs_cleanup_fs_uuids();
2608 }
2609
init_btrfs_fs(void)2610 static int __init init_btrfs_fs(void)
2611 {
2612 int ret;
2613 int i;
2614
2615 for (i = 0; i < ARRAY_SIZE(mod_init_seq); i++) {
2616 ASSERT(!mod_init_result[i]);
2617 ret = mod_init_seq[i].init_func();
2618 if (ret < 0) {
2619 btrfs_exit_btrfs_fs();
2620 return ret;
2621 }
2622 mod_init_result[i] = true;
2623 }
2624 return 0;
2625 }
2626
2627 late_initcall(init_btrfs_fs);
2628 module_exit(exit_btrfs_fs)
2629
2630 MODULE_DESCRIPTION("B-Tree File System (BTRFS)");
2631 MODULE_LICENSE("GPL");
2632 MODULE_SOFTDEP("pre: crc32c");
2633 MODULE_SOFTDEP("pre: xxhash64");
2634 MODULE_SOFTDEP("pre: sha256");
2635 MODULE_SOFTDEP("pre: blake2b-256");
2636