- Как загружать и выгружать модули ядра в Linux
- Список всех загруженных модулей ядра в Linux
- Как загрузить или выгрузить (удалить) модули ядра в Linux
- Управление модулями ядра с помощью команды modprobe
- Kernel module (Русский)
- Contents
- Обзор
- Получение информации
- Автоматическое управление модулями
- Управление модулями вручную
- Настройка параметров модуля
- С помощью файлов в /etc/modprobe.d/
- С помощью командной строки ядра
- Создание псевдонимов
- Запрет загрузки
- С помощью файлов в /etc/modprobe.d/
- С помощью командной строки ядра
- Kernel module
- Contents
- Obtaining information
- Automatic module loading with systemd
- Manual module handling
- Setting module options
- Manually at load time using modprobe
- Using files in /etc/modprobe.d/
- Using kernel command line
- Aliasing
- Blacklisting
- Using files in /etc/modprobe.d/
- Using kernel command line
- Troubleshooting
- Modules do not load
- 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.
Источник
Kernel module (Русский)
Модули ядра — это отдельные кусочки кода, которые могут быть загружены и выгружены из ядра по мере необходимости. Они расширяют функциональность ядра без необходимости перезагрузки системы.
Contents
Обзор
Чтобы создать модуль ядра, вы можете прочитать The Linux Kernel Module Programming Guide. Модуль можно сконфигурировать как вкомпилированный, а можно как загружаемый. Чтобы иметь возможность динамически загружать или выгружать модуль, его необходимо сконфигурировать как загружаемый модуль в настройке ядра (в этом случае строка, относящаяся к модулю должна быть отмечена буквой M ).
Модули хранятся в /usr/lib/modules/kernel_release . Чтобы узнать текущую версию вашего ядра, используйте команду uname -r .
Получение информации
Чтобы узнать, какие модули ядра загружены в настоящий момент:
Чтобы показать информацию о модуле:
Чтобы вывести список опций, с которыми загружен модуль:
Чтобы отобразить настройки для всех модулей:
Чтобы отобразить настройки для отдельного модуля:
Чтобы узнать зависимости модуля (или его псевдонима), включая сам модуль:
Автоматическое управление модулями
Сегодня все необходимые загрузки модулей делаются автоматически с помощью udev, поэтому если вам не нужно загружать какие-либо модули, не входящие в стандартное ядро, вам не придётся прописывать модули, требующиеся для загрузки в каком-либо конфигурационном файле. Однако, бывают случаи, когда вам необходимо загружать свой модуль в процессе загрузки или наоборот не загружать какой-то стандартный модуль, чтобы ваш компьютер правильно функционировал.
Чтобы дополнительные модули ядра загружались автоматически в процессе загрузки, создаются статические списки в конфигурационных файлах в директории /etc/modules-load.d/ . Каждый конфигурационный файл называется по схеме /etc/modules-load.d/
.conf . Эти конфигурационные файлы содержат список названий модулей ядра, которые необходимо грузить, разделённых переносом строки. Пустые строки и строки, в которых первым непробельным символом является # или ; , игнорируются.
Смотрите modules-load.d(5) для дополнительной информации.
Управление модулями вручную
Управление модулями ядра производится с помощью утилит, предоставляемых пакетом kmod . Вы можете использовать эти утилиты вручную.
Загрузка модуля из другого места (для тех модулей, которых нет в /lib/modules/$(uname -r)/ ):
Альтернативный вариант выгрузки модуля:
Настройка параметров модуля
Чтобы передать параметр модулю ядра, вы можете воспользоваться конфигурационным файлом в modprobe или использовать командную строку ядра.
С помощью файлов в /etc/modprobe.d/
Файлы в директории /etc/modprobe.d/ можно использовать для передачи настроек модуля в udev, который через modprobe управляет загрузкой модулей во время загрузки системы. Конфигурационные файлы в этой директории могут иметь любое имя, оканчивающееся расширением .conf . Синтаксис следующий:
С помощью командной строки ядра
Если модуль вкомпилирован в ядро, вы также можете передать параметры модулю с помощью командной строки ядра. Для всех стандартных загрузчиков, подойдёт следующий синтаксис:
Просто добавьте это в загрузчике в строку с ядром, как описано в параметрах ядра.
Создание псевдонимов
Псевдонимы (алиасы) — это альтернативные названия для модуля. Например: alias my-mod really_long_modulename означает, что вы можете использовать modprobe my-mod вместо modprobe really_long_modulename . Вы также можете использовать звёздочки в стиле shell, то есть alias my-mod* really_long_modulename будет иметь тот же эффект, что и modprobe my-mod-something . Создайте алиас:
У некоторых модулей есть алиасы, которые используются для их автоматической загрузки, когда они потребуются определённой программе. Отключение этих алиасов может предотвратить их автоматическую загрузку, при этом остаётся возможность из загрузки вручную.
Запрет загрузки
В терминах модулей ядра blacklisting означает механизм, предотвращающий загрузку какого-то модуля. Это может понадобиться, например если вам не нужна работа какого-то оборудования или если загрузка данного модуля вызывает проблемы: например, могут быть два модуля ядра, которые пытаются управлять одним и тем же оборудованием, и их совместная загрузка приводит к конфликту.
Некоторые модули загружаются как часть initramfs. Команда mkinitcpio -M напечатает все автоматически обнаруженные модули: для предотвращения initramfs от загрузки каких-то из этих модулей, занесите их в чёрный список в /etc/modprobe.d/modprobe.conf . Команда mkinitcpio -v отобразит все модули, которые необходимы некоторым хукам (например, filesystems хук, block хук и т.д.). Не забудьте добавить этот .conf файл в секцию FILES в /etc/mkinitcpio.conf , если вы этого ещё не сделали, пересоберите initramfs после того, как вы запретили загрузку модулей, а затем перезагрузитесь.
С помощью файлов в /etc/modprobe.d/
Создайте .conf файл в /etc/modprobe.d/ и добавьте строку для каждого модуля, который вы хотите запретить, используя ключевое слово blacklist . Например, если вы хотите запретить загружать модуль pcspkr :
Можно изменить такое поведение. Команда install заставляет modprobe запускать вашу собственную команду вместо вставки модуля в ядро как обычно. Поэтому вы можете насильно сделать так, чтобы модуль никогда не загружался:
Это запретит данный модуль и все модули, зависящие от него.
С помощью командной строки ядра
Вы также можете запрещать модули из загрузчика.
Источник
Kernel module
Kernel modules are pieces of code that can be loaded and unloaded into the kernel upon demand. They extend the functionality of the kernel without the need to reboot the system.
To create a kernel module, you can read The Linux Kernel Module Programming Guide. A module can be configured as built-in or loadable. To dynamically load or remove a module, it has to be configured as a loadable module in the kernel configuration (the line related to the module will therefore display the letter M ).
Contents
Obtaining information
Modules are stored in /usr/lib/modules/kernel_release . You can use the command uname -r to get your current kernel release version.
To show what kernel modules are currently loaded:
To show information about a module:
To list the options that are set for a loaded module:
To display the comprehensive configuration of all the modules:
To display the configuration of a particular module:
List the dependencies of a module (or alias), including the module itself:
Automatic module loading with systemd
Today, all necessary modules loading is handled automatically by udev, so if you do not need to use any out-of-tree kernel modules, there is no need to put modules that should be loaded at boot in any configuration file. However, there are cases where you might want to load an extra module during the boot process, or blacklist another one for your computer to function properly.
Kernel modules can be explicitly listed in files under /etc/modules-load.d/ for systemd to load them during boot. Each configuration file is named in the style of /etc/modules-load.d/program.conf . Configuration files simply contain a list of kernel modules names to load, separated by newlines. Empty lines and lines whose first non-whitespace character is # or ; are ignored.
See modules-load.d(5) for more details.
Manual module handling
Kernel modules are handled by tools provided by kmod package. You can use these tools manually.
To load a module:
To load a module by filename (i.e. one that is not installed in /usr/lib/modules/$(uname -r)/ ):
To unload a module:
Setting module options
To pass a parameter to a kernel module, you can pass them manually with modprobe or assure certain parameters are always applied using a modprobe configuration file or by using the kernel command line.
Manually at load time using modprobe
The basic way to pass parameters to a module is using the modprobe command. Parameters are specified on command line using simple key=value assignments:
Using files in /etc/modprobe.d/
Files in /etc/modprobe.d/ directory can be used to pass module settings to udev, which will use modprobe to manage the loading of the modules during system boot. Configuration files in this directory can have any name, given that they end with the .conf extension. The syntax is:
Using kernel command line
If the module is built into the kernel, you can also pass options to the module using the kernel command line. For all common bootloaders, the following syntax is correct:
Simply add this to your bootloader’s kernel-line, as described in Kernel Parameters.
Aliasing
Aliases are alternate names for a module. For example: alias my-mod really_long_modulename means you can use modprobe my-mod instead of modprobe really_long_modulename . You can also use shell-style wildcards, so alias my-mod* really_long_modulename means that modprobe my-mod-something has the same effect. Create an alias:
Some modules have aliases which are used to automatically load them when they are needed by an application. Disabling these aliases can prevent automatic loading but will still allow the modules to be manually loaded.
Blacklisting
Blacklisting, in the context of kernel modules, is a mechanism to prevent the kernel module from loading. This could be useful if, for example, the associated hardware is not needed, or if loading that module causes problems: for instance there may be two kernel modules that try to control the same piece of hardware, and loading them together would result in a conflict.
Some modules are loaded as part of the initramfs. mkinitcpio -M will print out all automatically detected modules: to prevent the initramfs from loading some of those modules, blacklist them in a .conf file under /etc/modprobe.d and it shall be added in by the modconf hook during image generation. Running mkinitcpio -v will list all modules pulled in by the various hooks (e.g. filesystems hook, block hook, etc.). Remember to add that .conf file to the FILES array in /etc/mkinitcpio.conf if you do not have the modconf hook in your HOOKS array (e.g. you have deviated from the default configuration), and once you have blacklisted the modules regenerate the initramfs, and reboot afterwards.
Using files in /etc/modprobe.d/
Create a .conf file inside /etc/modprobe.d/ and append a line for each module you want to blacklist, using the blacklist keyword. If for example you want to prevent the pcspkr module from loading:
However, there is a workaround for this behaviour; the install command instructs modprobe to run a custom command instead of inserting the module in the kernel as normal, so you can force the module to always fail loading with:
This will effectively blacklist that module and any other that depends on it.
Using kernel command line
You can also blacklist modules from the bootloader.
Simply add module_blacklist=modname1,modname2,modname3 to your bootloader’s kernel line, as described in Kernel parameters.
Troubleshooting
Modules do not load
In case a specific module does not load and the boot log (accessible by running journalctl -b as root) says that the module is blacklisted, but the directory /etc/modprobe.d/ does not show a corresponding entry, check another modprobe source folder at /usr/lib/modprobe.d/ for blacklisting entries.
A module will not be loaded if the «vermagic» string contained within the kernel module does not match the value of the currently running kernel. If it is known that the module is compatible with the current running kernel the «vermagic» check can be ignored with modprobe —force-vermagic .
Источник
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.
Источник