Linux modprobe on boot

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.

Читайте также:  All linux iso download

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 .

Источник

Команда Modprobe в Linux

Ядро Linux — это основной компонент операционной системы Linux. Он управляет ресурсами системы и является мостом между оборудованием и программным обеспечением вашего компьютера.

Ядро Linux имеет модульную конструкцию. Модуль ядра, или часто называемый драйвером, — это фрагмент кода, расширяющий функциональность ядра. Модули либо скомпилированы как загружаемые модули, либо встроены в ядро. Загружаемые модули могут быть загружены и выгружены в работающем ядре по запросу без необходимости перезагрузки системы.

Обычно модули загружаются по запросу через udev (диспетчер устройств). Однако иногда вам может потребоваться точная настройка того, как загружаются модули. Например, вам может потребоваться загрузить модуль с дополнительными параметрами или предотвратить автоматическую загрузку модуля.

Вы можете вручную загрузить модуль в ядро с помощью команды modprobe или автоматически во время загрузки с помощью файлов /etc/modules или /etc/modules-load.d/*.conf .

В этой статье мы объясним, как использовать modprobe для добавления и удаления модулей из ядра Linux. modprobe является частью kmod , двоичного kmod , который реализует несколько программ, используемых для управления модулями ядра Linux.

Добавление модулей ядра

Модули ядра хранятся в каталоге /lib/modules/ . Вы найдете версию работающего ядра , используйте команду uname -r .

Только пользователи с правами администратора могут управлять модулями ядра.

Чтобы загрузить модуль, вызовите команду modprobe за которой следует имя модуля:

Команда modprobe загрузит данный модуль и любые дополнительные зависимости модуля. В командной строке можно указать только один модуль.

Используйте команду lsmod чтобы убедиться, что модуль загружен:

Чтобы загрузить модуль с дополнительными параметрами, используйте синтаксис parameter=value :

Команда принимает несколько пар parameter=value разделенных пробелом.

Как правило, вам необходимо загрузить модуль во время загрузки системы. Вы можете сделать это, указав модуль и его параметры в файле внутри каталога /etc/modules-load.d . Файлы должны заканчиваться на .conf и иметь любое имя:

Параметры, указанные в этих файлах, считываются программой udev , которая загружает модули при запуске системы с помощью modprobe .

Удаление модулей ядра

Чтобы удалить модуль, вызовите команду modprobe с параметром -r за которым следует имя модуля:

modprobe также удалит неиспользуемые зависимости модуля.

При вызове с -r команда принимает несколько модулей в качестве аргументов:

Если вы хотите предотвратить загрузку модуля ядра во время загрузки, создайте файл .conf с любым именем внутри /etc/modprobe.d . Синтаксис:

Если вы хотите внести в черный список дополнительные модули, укажите модули в новой строке или создайте новый файл .conf .

Выводы

Команда modprobe позволяет добавлять и удалять модули ядра Linux.

Не стесняйтесь оставлять комментарии, если у вас есть вопросы.

Источник

Как загружать и выгружать модули ядра в Linux

Оригинал: How to Load and Unload Kernel Modules in Linux
Автор: Aaron Kili
Дата публикации: 13 июня 2017 года
Перевод: А. Кривошей
Дата перевода: июль 2017 г.

Модуль ядра — это программа, которая может быть загружена в ядро операционной системы, или выгружена из него по запросу без перекомпиляции ядра или перезагрузки системы. Модули предназначены для расширения функциональности ядра. Другими словами можно сказать, что модули похожи на плагины к программам, например к WordPress. Плагины расширяют функциональность программы без включения их в исходный код.

Аналогично, без модулей ядро должно быть собрано с включением всей необходимой функциональности непосредственно в образ ядра. Это приводит к увеличению его размеров, кроме того, для добавления любой новой функциональности системным администраторам необходимо перекомпилировать ядро.

Простой пример модуля — драйвер, который предоставляет ядру доступ к аппаратному устройству, подключенному к компьютеру.

Читайте также:  Windows не обновляется nod32

Список всех загруженных модулей ядра в 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.

Источник

Linux modprobe command

On Linux operating systems, the modprobe command adds and removes modules from the Linux kernel.

Description

Modules are pieces of code which extend the functionality of the operating system kernel without the need to reboot. Once loaded, modules reside in memory, and can be instantiated multiple times; they can be thought of as analogous to a device driver.

modprobe uses the dependency lists and hardware maps generated by depmod to intelligently load or unload modules into the kernel. It performs the actual insertion and removal using the lower-level programs insmod and rmmod, respectively.

While it’s possible to call insmod and rmmod manually, we recommend to load and unload modules using depmod to ensure that any inter-module dependencies are considered before changes are made.

Technical description

modprobe searches the module directory,

for all the modules and other files, except for the optional configuration files in the /etc/modprobe.d directory. modprobe also uses module options specified on the kernel command line in the form of:

. and blacklists in the form of:

Modern versions of Linux modprobe (post-kernel version 2.4.x) do not modify modules themselves. The work of resolving symbols and understanding parameters is done inside the kernel. Module failure is therefore sometimes accompanied by a kernel message — see dmesg for more information about viewing them.

modprobe expects an up-to-date modules.dep.bin file (or fallback human readable modules.dep file), as generated by the depmod utility. This file lists what other modules each module needs (if any), and modprobe uses this to add or remove these dependencies automatically.

If any arguments are given after the modulename, they are passed to the kernel (in addition to any options listed in the configuration file).

Syntax

Options

-a, —all Insert all module names on the command line.
-b,—use-blacklist This option causes modprobe to apply the blacklist commands in the configuration files (if any) to module names as well. (Any module which has been blacklisted is not automatically loaded.)
-C, —config This option overrides the default configuration directory (/etc/modprobe.d).

This option is passed through install or remove commands to other modprobe commands in the MODPROBE_OPTIONS environment variable. -c, —showconfig Dump out the effective configuration from the config directory and exit. —dump-modversions Print out a list of module versioning information required by a module. This option is commonly used by distributions to package up a Linux kernel module using module versioning deps. -d, —dirname Directory where modules are found (/lib/modules/`uname -r` by default). —first-time Normally, modprobe succeeds (and does nothing) if told to insert a module that is already present, or remove a module which isn’t present. This is ideal for simple scripts; however, more complicated scripts often want to know whether modprobe really did something: this option makes modprobe fail in the case that it actually didn’t do anything. —force-vermagic Every module contains a small string containing important information, such as the kernel and compiler versions. If a module fails to load and the kernel complains that the «version magic» doesn’t match, you can use this option to remove it. This applies to any modules inserted: the module (or alias) on the command line and any modules on which it depends.

This check is there for your protection, so this using option is dangerous unless you know what you’re doing.

—force-modversion When modules are compiled with CONFIG_MODVERSIONS set, a section detailing the versions of every interfaced used by (or supplied by) the module is created. If a module fails to load and the kernel complains that the module disagrees about a version of some interface, you can use —force-modversion to remove the version information altogether. This applies to any modules inserted: the module (or alias) on the command line and any modules on which it depends.

This check is there for your protection, so using this option is dangerous unless you know what you’re doing. -f, —force Try to strip any versioning information from the module which might otherwise stop it from loading: this is the same as using both —force-vermagic and —force-modversion. This applies to any modules inserted: the module (or alias) on the command line and any modules it on which it depends.

These checks are there for your protection, so using this option is dangerous unless you know what you are doing. -i,
—ignore-install,
—ignore-remove This option causes modprobe to ignore install and remove commands in the configuration file (if any) for the module specified on the command line (any dependent modules are still subject to commands set for them in the configuration file). Both install and remove commands currently are ignored when this option is used regardless of whether the request was more specifically made with only one or other (and not both) of —ignore-install or —ignore-remove. -n, —dry-run, —show This option does everything but actually insert or delete the modules (or run the install or remove commands). Combined with -v, it is useful for debugging. For historical reasons both —dry-run and —show actually mean the same thing and are interchangeable. -q, —quiet With this flag, modprobe won’t print an error message if you try to remove or insert a module it can’t find (and isn’t an alias or install/remove command). However, it still returns with a non-zero exit status. The kernel uses this to opportunistically probe for modules which might exist using request_module. -R, —resolve-alias Print all module names matching an alias. This can be useful for debugging module alias problems. -r —remove This option causes modprobe to remove rather than insert a module. If the modules it depends on are also unused, modprobe tries to remove them too. Unlike insertion, more than one module can be specified on the command line (it does not make sense to specify module parameters when removing modules).

There is usually no reason to remove modules, but some buggy modules require it. Your distribution kernel may not be built to support removal of modules at all. -S, —set-version Set the kernel version, rather than using uname to decide on the kernel version (which dictates where to find the modules). —show-depends List the dependencies of a module (or alias), including the module itself. This produces a (possibly empty) set of module file names, one per line, each starting with «insmod» and is often used by distributions to determine which modules to include when generating initrd/initramfs images. Install commands which apply are shown prefixed by «install». It does not run any of the install commands. Note that modinfo can extract dependencies of a module from the module itself, but knows nothing of aliases or install commands. -s, —syslog This option causes any error messages to go through the syslog mechanism (as LOG_DAEMON with level LOG_NOTICE) rather than to standard error. This is also automatically enabled when stderr is unavailable.

This option is passed through install or remove commands to other modprobe commands in the MODPROBE_OPTIONS environment variable. -V, —version Show modprobe‘s version information and exit. -v, —verbose Verbose mode; print messages about what the program is doing. Usually modprobe only prints messages if something goes wrong.

This option is passed through install or remove commands to other modprobe commands in the MODPROBE_OPTIONS environment variable.

Examples

The following series of commands illustrate a common way to use modprobe. Each command is prefixed with sudo, as they require root permissions:

These commands perform the following operations:

  1. In the first command, we use ln to create a symbolic link to our module file in the directory /lib/modules/kernel-release. The command uname -r, enclosed in back quotes, is executed by the shell and translates to the appropriate string representing our kernel release version.
  2. In the second command, an updated dependency list is generated by depmod -a to make sure the module we’re installing is aware of all existing modules and dependencies. This dependency list is used by modprobe when installing the module in the third command.
  3. modprobe installs the kernel module.

depmod — Generate a list of kernel module dependences and associated map files.
insmod — Insert a module into the Linux kernel.
lsmod — Show the status of Linux kernel modules.
modinfo — Show information about a Linux kernel module.
rmmod — Remove a module from the Linux kernel.
uname — Print information about the current system.

Источник

Читайте также:  Что занимает место линукс
Оцените статью