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