Linux kernel load drivers

Как загружать и выгружать модули ядра в 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: Display List of Modules or Device Drivers In the Linux Kernel

H ow do I display the list of loaded Linux Kernel modules or device drivers on Linux operating systems?

You need to use lsmod program which show the status of loaded modules in the Linux Kernel. Linux kernel use a term modules for all hardware device drivers.

Tutorial details
Difficulty level Easy
Root privileges Yes
Requirements lsmod
Est. reading time Less than a one minute

Please note hat lsmod is a trivial program which nicely formats the contents of the /proc/modules , showing what kernel modules are currently loaded.

This is an important task. With lsmod you can verify that device driver is loaded for particular hardware. Any hardware device will only work if device driver is loaded.

Task: List or display loaded modules

Open a terminal or login over the ssh session and type the following command
$ less /proc/modules
Sample outputs:

To see nicely formatted output, type:
$ lsmod
Sample outputs:

First column is Module name and second column is the size of the modules i..e the output format is module name, size, use count, list of referring 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

Finding more info about any module or driver

Type the following command:
# modinfo driver-Name-Here
# modinfo thermal_sys
# modinfo e1000e
Sample outputs:

Источник

How to Load and Unload Kernel Modules in Linux

A kernel module is a program which can loaded into or unloaded from the kernel upon demand, without necessarily recompiling it (the kernel) or rebooting the system, and is intended to enhance the functionality of the kernel.

In general software terms, modules are more or less like plugins to a software such as WordPress. Plugins provide means to extend software functionality, without them, developers would have to build a single massive software with all functionalities integrated in a package. If new functionalities are needed, they would have to be added in new versions of a software.

Likewise without modules, the kernel would have to be built with all functionalities integrated directly into the kernel image. This would mean having bigger kernels, and system administrators would need to recompile the kernel every time a new functionality is needed.

A simple example of a module is a device driver – which enables the kernel to access a hardware component/device connected to the system.

List All Loaded Kernel Modules in Linux

In Linux, all modules end with the .ko extension, and they are normally loaded automatically as the hardware is detected at system boot. However a system administrator can manage the modules using certain commands.

To list all currently loaded modules in Linux, we can use the lsmod (list modules) command which reads the contents of /proc/modules like this.

How to Load and Unload (Remove) Kernel Modules in Linux

To load a kernel module, we can use the insmod (insert module) command. Here, we have to specify the full path of the module. The command below will insert the speedstep-lib.ko module.

To unload a kernel module, we use the rmmod (remove module) command. The following example will unload or remove the speedstep-lib.ko module.

How to Manage Kernel Modules Using modprobe Command

modprobe is an intelligent command for listing, inserting as well as removing modules from the kernel. It searches in the module directory /lib/modules/$(uname -r) for all the modules and related files, but excludes alternative configuration files in the /etc/modprobe.d directory.

Here, you don’t need the absolute path of a module; this is the advantage of using modprobe over the previous commands.

To insert a module, simply provide its name as follows.

To remove a module, use the -r flag like this.

Note: Under modprobe, automatic underscore conversion is performed, so there is no difference between _ and – while entering module names.

For more usage info and options, read through the modprobe man page.

Do not forget to check out:

That’s all for now! Do you have any useful ideas, that you wanted us to add to this guide or queries, use the feedback form below to drop them to us.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

Linux: Find out what kernel drivers (modules) are loaded

lsmod command

You need to use lsmod command to show the status of modules in the Linux Kernel. Simply type the lsmod at a shell prompt to list all loaded modules:
$ lsmod
Sample outputs:

Get more information about the driver

To get more information about specific driver use modinfo command. The syntax is:
modinfo < driver-name >
To see information about a Linux Kernel module called e1000, enter:
$ modinfo e1000
Sample outputs:

  • 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

See modinfo and lsmod man pages for more info.

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

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.

Источник

Читайте также:  Чем закреплять окна windows
Оцените статью