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