xref: /linux/drivers/base/module.c (revision b615b9c36cae0468491547206406a909a9a37f26)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * module.c - module sysfs fun for drivers
4  */
5 #include <linux/device.h>
6 #include <linux/module.h>
7 #include <linux/errno.h>
8 #include <linux/slab.h>
9 #include <linux/string.h>
10 #include <linux/rcupdate.h>
11 #include "base.h"
12 
13 static char *make_driver_name(const struct device_driver *drv)
14 {
15 	char *driver_name;
16 
17 	driver_name = kasprintf(GFP_KERNEL, "%s:%s", drv->bus->name, drv->name);
18 	if (!driver_name)
19 		return NULL;
20 
21 	return driver_name;
22 }
23 
24 static void module_create_drivers_dir(struct module_kobject *mk)
25 {
26 	static DEFINE_MUTEX(drivers_dir_mutex);
27 
28 	mutex_lock(&drivers_dir_mutex);
29 	if (mk && !mk->drivers_dir)
30 		mk->drivers_dir = kobject_create_and_add("drivers", &mk->kobj);
31 	mutex_unlock(&drivers_dir_mutex);
32 }
33 
34 int module_add_driver(struct module *mod, const struct device_driver *drv)
35 {
36 	char *driver_name;
37 	struct module_kobject *mk = NULL;
38 	int ret;
39 
40 	if (!drv)
41 		return 0;
42 
43 	if (mod)
44 		mk = &mod->mkobj;
45 	else if (drv->mod_name) {
46 		struct kobject *mkobj;
47 
48 		/* Lookup built-in module entry in /sys/modules */
49 		mkobj = kset_find_obj(module_kset, drv->mod_name);
50 		if (mkobj) {
51 			mk = container_of(mkobj, struct module_kobject, kobj);
52 			/* remember our module structure */
53 			drv->p->mkobj = mk;
54 			/* kset_find_obj took a reference */
55 			kobject_put(mkobj);
56 		}
57 	}
58 
59 	if (!mk)
60 		return 0;
61 
62 	ret = sysfs_create_link(&drv->p->kobj, &mk->kobj, "module");
63 	if (ret)
64 		return ret;
65 
66 	driver_name = make_driver_name(drv);
67 	if (!driver_name) {
68 		ret = -ENOMEM;
69 		goto out;
70 	}
71 
72 	module_create_drivers_dir(mk);
73 	if (!mk->drivers_dir) {
74 		ret = -EINVAL;
75 		goto out;
76 	}
77 
78 	ret = sysfs_create_link(mk->drivers_dir, &drv->p->kobj, driver_name);
79 	if (ret)
80 		goto out;
81 
82 	kfree(driver_name);
83 
84 	return 0;
85 out:
86 	sysfs_remove_link(&drv->p->kobj, "module");
87 	sysfs_remove_link(mk->drivers_dir, driver_name);
88 	kfree(driver_name);
89 
90 	return ret;
91 }
92 
93 void module_remove_driver(const struct device_driver *drv)
94 {
95 	struct module_kobject *mk = NULL;
96 	char *driver_name;
97 
98 	if (!drv)
99 		return;
100 
101 	/* Synchronize with dev_uevent() */
102 	synchronize_rcu();
103 
104 	sysfs_remove_link(&drv->p->kobj, "module");
105 
106 	if (drv->owner)
107 		mk = &drv->owner->mkobj;
108 	else if (drv->p->mkobj)
109 		mk = drv->p->mkobj;
110 	if (mk && mk->drivers_dir) {
111 		driver_name = make_driver_name(drv);
112 		if (driver_name) {
113 			sysfs_remove_link(mk->drivers_dir, driver_name);
114 			kfree(driver_name);
115 		}
116 	}
117 }
118