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