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