- Как загружать и выгружать модули ядра в Linux
- Список всех загруженных модулей ядра в Linux
- Как загрузить или выгрузить (удалить) модули ядра в Linux
- Управление модулями ядра с помощью команды modprobe
- Howto: Linux Add or Remove a Linux Kernel Modules / Drivers
- Task: Add a Module (driver) Called foo
- Find out info about loaded module
- Task: List all loaded modules
- Task: Remove a module called foo
- Linux: How to load a kernel module automatically at boot time
Как загружать и выгружать модули ядра в Linux
Оригинал: How to Load and Unload Kernel Modules in Linux
Автор: Aaron Kili
Дата публикации: 13 июня 2017 года
Перевод: А. Кривошей
Дата перевода: июль 2017 г.
Модуль ядра — это программа, которая может быть загружена в ядро операционной системы, или выгружена из него по запросу без перекомпиляции ядра или перезагрузки системы. Модули предназначены для расширения функциональности ядра. Другими словами можно сказать, что модули похожи на плагины к программам, например к WordPress. Плагины расширяют функциональность программы без включения их в исходный код.
Аналогично, без модулей ядро должно быть собрано с включением всей необходимой функциональности непосредственно в образ ядра. Это приводит к увеличению его размеров, кроме того, для добавления любой новой функциональности системным администраторам необходимо перекомпилировать ядро.
Простой пример модуля — драйвер, который предоставляет ядру доступ к аппаратному устройству, подключенному к компьютеру.
Список всех загруженных модулей ядра в Linux
В Linux названия всех модулей заканчиваются расширением .ko, и обычно они загружаются автоматически при обнаружении оборудования во время загрузки системы. Однако системный администратор может управлять модулями с помощью специальных команд.
Для вывода списка всех загруженных модулей в Linux может использоваться команда lsmod (list modules), которая читает содержимое /proc/modules.
Как загрузить или выгрузить (удалить) модули ядра в Linux
Для загрузки модуля ядра мы можем использовать команду insmod (insert module). Здесь необходимо задать полный путь к модулю. Приведенная ниже команда загружает модуль speedstep-lib.ko.
Для выгрузки модуля ядра мы будем использовать команду rmmod (remove module). Следующая команда выгрузит модуль speedstep-lib.ko.
Управление модулями ядра с помощью команды modprobe
modprobe — это интеллектуальная команда для чтения списка, загрузки и выгрузки модулей ядра. Она производит поиск всех модулей и соответствующих файлов в директории /lib/modules/$(uname -r), но не включает в поиск альтернативные конфигурационные файлы в директории /etc/modprobe.d. Таким образом, здесь вам не нужно вводить полный путь к модулю — в этом преимущество modprobe по сравнению с ранее описанными командами.
Для загрузки модуля просто введите его имя.
Для выгрузки модуля используется флаг -r.
Замечание: в modprobe выполняется автоматическое преобразование подчеркивания, поэтому при вводе названий модулей нет никакой разницы между _ и -.
Более подробно ознакомиться с опциями можно на man-странице modprobe.
Источник
Howto: Linux Add or Remove a Linux Kernel Modules / Drivers
=> Under MS-Windows you use term device driver for modules.
=> Under Linux you use term modules for device drivers.
Tutorial details | |
---|---|
Difficulty level | Advanced |
Root privileges | Yes |
Requirements | modprobe/lsmod/modinfo utilities |
Est. reading time | N/A |
=> The Linux kernel has a modular design.
=> At boot time, only a minimal resident kernel is loaded into memory.
=> If you add new hardware you need to add driver i.e. modules.
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
=> The modprobe command intelligently adds or removes a module from the Linux kernel
=> Usually, all Linux kernel modules (drivers) are stored in the module directory located that /lib/modules/$(uname -r) directory. To see current modules, type:
$ ls /lib/modules/$(uname -r)
Output:
Use the following command to list all drivers for various devices:
$ ls /lib/modules/$(uname -r)/kernel/drivers/
Sample outputs:
Fig.01: Device drivers on my Linux based system
Task: Add a Module (driver) Called foo
Type the following command as root user:
# modprobe foo
In this example, I am loading a module called i8k, enter:
# modprobe -v i8k
Sample outputs:
Find out info about loaded module
You need to use the modinfo command to see information about a Linux Kernel module. The syntax is:
# modinfo -v
# modinfo i8k
Sample outputs:
Fig.02: Displaying information about a Linux Kernel module called i8k
Task: List all loaded modules
Use the lsmod command to show the status of modules in the Linux Kernel:
# lsmod
Sample outputs:
Task: Remove a module called foo
Pass the -r option to modprobe command to remove a module, type:
# modprobe -r foo
You can also use the rmmod command, which is simple program to remove a module from the Linux Kernel:
# rmmod foo
Recommended readings
- man pages – modinfo, lsmod, insmod, and modprobe
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Category | List of Unix and Linux commands |
---|---|
Documentation | help • mandb • man • pinfo |
Disk space analyzers | df • duf • ncdu • pydf |
File Management | cat • cp • less • mkdir • more • tree |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Linux Desktop Apps | Skype • Spotify • VLC 3 |
Modern utilities | bat • exa |
Network Utilities | NetHogs • dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop |
Searching | ag • grep • whereis • which |
Shell builtins | compgen • echo • printf |
Text processing | cut • rev |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Comments on this entry are closed.
when the system is rebooted the module inside the kernel will not be present.But i want the modules to be seen permenently.what should i do.
Thanks alot for this, very helpful for teh newbz.
Thank’s first for the helpfull command , where can i get the new modules other then my OS,
how to build linux kernel module with new device driver module during build
Thanks a lot for the info…:) 🙂
Hi there…
I am trying to remove TCP IP from a linux kernel, and want to recompile the LINUX kernel. But being a novice with the administrations of the linux (UBUNTU 10.4), I know a little about it. Agter recompilation can I again design mu own TCPIP using the C language code?
Guys please help me out…waiting for the reply .
Regards…
Thanks for this very short but very clear information. That helps me to understand the concept (of add or remove module on Linux) very much.
One question remain: how do we check to know what modules are available to add on a existing system?
Thank you in advance!
One question remain: how do we check to know what modules are available to add on a existing system?
cd to /lib/modules/$(uname -r) directory and you can see the list of available modules (run as root):
The following will list all drives
To find out more info about a module called foo:
Hope this helps!
Hi
thanks for your comments, I am trying to write a printer driver for linux, what should I do?
Please help me on this task.
Does anyone knows step by step guide for how to install ip_conntrack support into kernel Linux linux 2.6.35.14-106.fc14.i686 #1 SMP Wed Nov 23 13:57:33 UTC 2011 i686 i686 i386 GNU/Linux
I am unable to remove the following modules after issuing the commands.
$ rmmod usbhid and
$rmmod hid..
After issuing the commands the modules are not shown in “lsmod” but as soon as a device is added they again get loaded.
thanks, very clear article.
Hello there. I have an old computer Celeron, 128MB RAM and 28MB of VGA. What I want to do is keep the drivers that are needed for my system. Like if I use the Realtek Chipset for Network Card why should the Atheros driver be present on the system? Is there any way to accomplish this task?
Regards.
I have a serious problem, my Linux does not have these comands:
apt-get
uname
modprobe
mknod
man
…etc… and also has not a lot of typical commands
And there is no /dev/loop*
And mount -o loop blablabla bleble say incorrect option, does not undertand loop.
Of course, all problem seem that Kernel has no loop device support.
How can i fix it?
Please have in mind Kernel is on ROM (a chip not writteable), it is not a flasheable chip, i can not modify it on any way, … read only memory chip!!
I wish if it could be possible to add loop device support at run time as a module…
But it does not have modprobe command… neither a lot of clasic Linux commands… so i got to fail.
Need some help, i am not an expert.
Step 1: try to create /dev/loop0 (it does not exists) with mknod but mknod command not found
Try to add such coomands with apt-get, wget, etc… all says such commands not exists
I am getting mad…
Please note it is an ARM processor based, and Kernel is on a ReadOnly chip not flashable.
Thanks in advance for any help… i am getting really mad…
If I were you, rather than finding Linux Kernel modulos to have “uname”, “modprobe”, “man” recovered (maybe you have played around some kernel rebuild and screwed up some basic binaries?), I will re-install the entire Linux OS from scratch. You can download CentOS (Red Hat) or SUSE, Fedora or whatever Linux to have all these basic utilities included.
trying to add slcan module to kernel 2.6.32-504.30.3.el6.i686 but having problems with the following response … question is how to get it added
FATAL: Module slcan not found.
Thank you so much…
i want to know how many mouldes in linus and brief explanation of them.i will glad if my question is been answered.
hi all,
iam unable to remove nvme module in primary drive(ssd) by using
following comment:
rmmod nvme
Источник
Linux: How to load a kernel module automatically at boot time
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Category | List of Unix and Linux commands |
---|---|
Documentation | help • mandb • man • pinfo |
Disk space analyzers | df • duf • ncdu • pydf |
File Management | cat • cp • less • mkdir • more • tree |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Linux Desktop Apps | Skype • Spotify • VLC 3 |
Modern utilities | bat • exa |
Network Utilities | NetHogs • dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop |
Searching | ag • grep • whereis • which |
Shell builtins | compgen • echo • printf |
Text processing | cut • rev |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Comments on this entry are closed.
Try this method to load module at boot time
#echo module_name >> /etc/rc.modules
#chmod +x /etc/rc.modules
Hello,
I use Ubuntu 11.4 (Linux 2.6.38)
I tried both the files modules.conf and rc.modules.
Unfortunately the modules is not loaded.
Do you have any idea?
Thanks,
Yacob.
/etc/modules is the file you’re looking for Yacob
Thank you.
I tried this file also but the modules are not loaded.
Do you have another idea?
Thanks,
Yacob.
Try this:
echo “modprobe module_name” >> /etc/modprobe.d/modeprobe.conf
My understanding is that modprobe.conf and modules.conf are only configuration files. They do not invoke modprobe. All they do is provide modprobe with information about what it should do when it is invoked.
Scripts that are run immediately after the boot (in the start up sequence) are called rc scripts. Many systems have a script called rc.local. This script is arranged in such a way (normally with symlinks) that it is executed as the last script in the start up sequence. This is a good place to put additional commands that are required and which have not been invoked already. The normal location of this script is /etc/rc.d/rc.local.
Therefore if the modprobe command is added to that script it will be executed at the end, and before a login shell prompt is provided. Determine the location of modprobe. If, for example, it is /sbin/modprobe, then the end of the rc.local file should look something like this:
# Put your required modprobe command here:
/sbin/modprobe name-of-module
Note that if the module in question requires options, then a place to put these is in /etc/modprobe.conf, because when modprobe runs it will read that configuration file and pick up any required options from there.
Your steps helped me. It works.
I wanted to bring 8021q after every reboot.
I added it in /etc/rc.local file.
For me /etc/rc.d/rc.local doesn’t exist, I have Ubuntu 14.04 platform.
I am glad that helped you.
I use “linux from scratch”. That is a system in which the operating system is built step by step, not simply installed from some disk or web site. It takes a long time but can give some improvements in understanding and control.
Different distributions tend to store files (including configuration files) in different places. It appears that with Ubuntu there is a configuration file called /etc/modules which lists the names of modules to be loaded at boot time. If so then that might be a better place to put the 8021q module name. rc.local tends to be used for “local” after thoughts – anything unusual that needs to be done for that one host. There is a web page that describes Ubuntu’s /etc/modules here:
https://help.ubuntu.com/community/Loadable_Modules
The use of the 8021q module for vlan’s in Ubuntu is described here:
https://wiki.ubuntu.com/vlan
The section “Making it permanent”, which comes at the end of the article, seems to be relevant in your case. If that’s right then it might be tidier to do it that way than to use rc.local (even though it does work).
Hi all,
i am new buddy to Linux module programming.I am facing same problem in loading a module at boot time in Ubuntu 11.04. Can any one tell me the perfect steps to load the module at the boot time.
same problem here. I did change /etc/modules, but where do I put the module object itself so moprob can find it?
To put the question in another way, what are the default lcoation that modprobe look for modules?
i i tried to put the .KO file with the all drivers .KO file.But that doesn’t worked.
The other way to do this is configuring the Kconfig file and recompile the kernel.
But i am not getting proper documentation.
I figured that out.
add a line to /etc/modules for your module (without .ko)
copy the module file to /lib/modules/
do
sudo depmod -a
reboot and it worked for me on Ubuntu 12.04
error. copy the module file to /lib/modules/
This solution worked for me too on 12.04 . Thanks redjupiter.
Thanks redjupiter. It worked with ubuntu 11.04.
Glad it worked. one correction for others:
copy the module file to /lib/modules/
there is no /etc/modules…rather /etc/modprobe.conf is there…
please suggest
quite often there is no need for a modprobe configuration file. As I said before (see previous remark from November, 2011), modprobe is not invoked by that configuration file. Its just that if you need to provide it with additional information, then that can be done from the configuration file. The name used for the configuration file has changed a bit between different versions, and sometimes it is given as a file in a directory, modprobe.d. On my workstation (built from scratch) there is no modprobe configuration file. Its not needed.
The critical thing usually is making the kernel aware of modules. To do this you have to put the module in the right place, and run depmod to update the module dependencies.
Perhaps if you explained what you were trying to do, then it would be possible to provide a more specific explanation.
I would like to add that some systems have the modules file in /etc/sysconfig/modules
To load a module by filename (i.e. one that is not installed in /lib/modules/$(uname -r)/):
# insmod filename [args]
To unload a module:
# modprobe -r module_name
Or, alternatively:
# rmmod module_name
Check this link for more info on how to work with modules:
https://wiki.archlinux.org/index.php/kernel_modules
You forgot to mention about unsupported modules file.
Источник