xref: /linux/drivers/base/module.c (revision e5f0e38e7ece5b35577faa9bfbe5ec56091ec76b)
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_remove_kobj;
70 	}
71 
72 	module_create_drivers_dir(mk);
73 	if (!mk->drivers_dir) {
74 		ret = -EINVAL;
75 		goto out_free_driver_name;
76 	}
77 
78 	ret = sysfs_create_link(mk->drivers_dir, &drv->p->kobj, driver_name);
79 	if (ret)
80 		goto out_remove_drivers_dir;
81 
82 	kfree(driver_name);
83 
84 	return 0;
85 
86 out_remove_drivers_dir:
87 	sysfs_remove_link(mk->drivers_dir, driver_name);
88 
89 out_free_driver_name:
90 	kfree(driver_name);
91 
92 out_remove_kobj:
93 	sysfs_remove_link(&drv->p->kobj, "module");
94 	return ret;
95 }
96 
97 void module_remove_driver(const struct device_driver *drv)
98 {
99 	struct module_kobject *mk = NULL;
100 	char *driver_name;
101 
102 	if (!drv)
103 		return;
104 
105 	/* Synchronize with dev_uevent() */
106 	synchronize_rcu();
107 
108 	sysfs_remove_link(&drv->p->kobj, "module");
109 
110 	if (drv->owner)
111 		mk = &drv->owner->mkobj;
112 	else if (drv->p->mkobj)
113 		mk = drv->p->mkobj;
114 	if (mk && mk->drivers_dir) {
115 		driver_name = make_driver_name(drv);
116 		if (driver_name) {
117 			sysfs_remove_link(mk->drivers_dir, driver_name);
118 			kfree(driver_name);
119 		}
120 	}
121 }
122