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