I believe you cannot do that directly, but I could be wrong.
I would suggest to write some data which goes into some user-space application (perhaps systemd
, or your own daemon) thru some file descriptor (maybe some socket(7), probably of netlink(7) family).
I don't know well all the details, but I do question the approach of loading a kernel module directly from kernel code, because kernel modules have been invented to "increase" the kernel from user-land applications. If you know what exact kernel code you need, consider linking all of it together. See also modprobe(8)
(your question needs a concrete use case and some motivation; I don't understand why you need to avoid going to userspace; and I would like to understand what actual kernel modules you are thinking of, and what is their exact roles)
BTW, kernel modules should not be loaded frequently. If you have to do that (e.g. loading a kernel module every few milliseconds) it means that you have a design error. A kernel module (or several of them) is generally loaded once and should not disturb the kernel when it is useless. So you should improve your overall design to avoid the need of unloading and reloading frequently your kernel modules. Conceptually at least, you should think of loading all your kernel modules at boot time and unloading them (in the appropriate order) at shutdown time.
The case is that I have two kernel modules that I should load and unload dynamically.
This is probably a symptom of a huge architecture design mistake. These are the most costly bugs. You should consider budgeting several months of efforts to avoid it.
Probably you should describe more the dependencies between [your particular] kernel modules. AFAIK, the modprobe
command manages such dependencies (e.g. won't unload a module without having first unloaded the required dependencies)
If you are designing & developing both kernel modules, you should consider merging them into a single kernel module (and budget several months of effort for that task). Of course, you may need to change its "API", e.g. some device drivers or ioctl
to be able to enable or disable some part of it.