I came across the LWN article "Manual driver binding and unbinding", where it explains how to use the sysfs
interface to dynamically bind and unbind drivers in Linux. Where exactly in the kernel code is this interface implemented? I assume this is shared across the whole kernel.
The functionality you are looking for is implemented here in drivers/base/bus.c
.
The function that gets called when you write to /sys/bus/usb/drivers/usb/bind
is bind_store()
, which gets the string passed from userspace and uses it to find the appropriate device. Then checks if the driver declares support for the device in its id table, and if so it binds it to the device. Similarly, unbind_store()
in the same file handles unbinding through /sys/bus/usb/drivers/usb/unbind
.
The functions you are interested in are probably these:
bus_find_device_by_name()
from linux/device/bus.h
bus_find_device()
from linux/device/bus.h
device_driver_attach()
from linux/device.h
device_release_driver()
from linux/device.h
You can see if a device matches a specific driver through driver->bus->match()
.
Note that device_driver_detach()
(used in drivers/base/bus.c
to implement unbinding) is not exported, use device_release_driver()
instead.