xref: /linux/fs/sysfs/mount.c (revision 78d797520f6a74ed402cb98c6bf74d96b4937965)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * fs/sysfs/symlink.c - operations for initializing and mounting sysfs
4  *
5  * Copyright (c) 2001-3 Patrick Mochel
6  * Copyright (c) 2007 SUSE Linux Products GmbH
7  * Copyright (c) 2007 Tejun Heo <teheo@suse.de>
8  *
9  * Please see Documentation/filesystems/sysfs.rst for more information.
10  */
11 
12 #include <linux/fs.h>
13 #include <linux/magic.h>
14 #include <linux/mount.h>
15 #include <linux/init.h>
16 #include <linux/slab.h>
17 #include <linux/user_namespace.h>
18 #include <linux/fs_context.h>
19 #include <net/net_namespace.h>
20 
21 #include "sysfs.h"
22 
23 static struct kernfs_root *sysfs_root;
24 struct kernfs_node *sysfs_root_kn;
25 
26 static void sysfs_fs_context_free(struct fs_context *fc)
27 {
28 	struct kernfs_fs_context *kfc = fc->fs_private;
29 
30 	if (kfc->ns_tag)
31 		kobj_ns_drop(KOBJ_NS_TYPE_NET, kfc->ns_tag);
32 	kernfs_free_fs_context(fc);
33 	kfree(kfc);
34 }
35 
36 static const struct fs_context_operations sysfs_fs_context_ops = {
37 	.free		= sysfs_fs_context_free,
38 	.get_tree	= kernfs_get_tree,
39 };
40 
41 static int sysfs_init_fs_context(struct fs_context *fc)
42 {
43 	struct kernfs_fs_context *kfc;
44 	struct ns_common *ns;
45 
46 	if (!(fc->sb_flags & SB_KERNMOUNT)) {
47 		if (!kobj_ns_current_may_mount(KOBJ_NS_TYPE_NET))
48 			return -EPERM;
49 	}
50 
51 	kfc = kzalloc_obj(struct kernfs_fs_context);
52 	if (!kfc)
53 		return -ENOMEM;
54 
55 	kfc->ns_tag = ns = kobj_ns_grab_current(KOBJ_NS_TYPE_NET);
56 	kfc->root = sysfs_root;
57 	kfc->magic = SYSFS_MAGIC;
58 	fc->fs_private = kfc;
59 	fc->ops = &sysfs_fs_context_ops;
60 	if (ns) {
61 		struct net *netns = to_net_ns(ns);
62 
63 		put_user_ns(fc->user_ns);
64 		fc->user_ns = get_user_ns(netns->user_ns);
65 	}
66 	fc->global = true;
67 	return 0;
68 }
69 
70 static void sysfs_kill_sb(struct super_block *sb)
71 {
72 	struct ns_common *ns = (struct ns_common *)kernfs_super_ns(sb);
73 
74 	kernfs_kill_sb(sb);
75 	kobj_ns_drop(KOBJ_NS_TYPE_NET, ns);
76 }
77 
78 static struct file_system_type sysfs_fs_type = {
79 	.name			= "sysfs",
80 	.init_fs_context	= sysfs_init_fs_context,
81 	.kill_sb		= sysfs_kill_sb,
82 	.fs_flags		= FS_USERNS_MOUNT | FS_USERNS_MOUNT_RESTRICTED,
83 };
84 
85 int __init sysfs_init(void)
86 {
87 	int err;
88 
89 	sysfs_root = kernfs_create_root(NULL, KERNFS_ROOT_EXTRA_OPEN_PERM_CHECK,
90 					NULL);
91 	if (IS_ERR(sysfs_root))
92 		return PTR_ERR(sysfs_root);
93 
94 	sysfs_root_kn = kernfs_root_to_node(sysfs_root);
95 
96 	err = register_filesystem(&sysfs_fs_type);
97 	if (err) {
98 		kernfs_destroy_root(sysfs_root);
99 		return err;
100 	}
101 
102 	return 0;
103 }
104