Linux kernel module version

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 . Создайте алиас:

Читайте также:  Портативная ос линукс только для usb

У некоторых модулей есть алиасы, которые используются для их автоматической загрузки, когда они потребуются определённой программе. Отключение этих алиасов может предотвратить их автоматическую загрузку, при этом остаётся возможность из загрузки вручную.

Запрет загрузки

В терминах модулей ядра 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:

Читайте также:  Completely remove android studio mac os

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.

Читайте также:  Easier cap dc60 008 драйвер windows 10

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 .

Источник

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 find the version of a compiled kernel module?

I am in a situation where it would be very convenient to find the version of a loaded kernel module by querying the loaded module or .ko file.

Is there a standard way to do this without digging into the source code?

2 Answers 2

Runtime method

Tested with this setup on kernel 4.9.6.

/sys/modules/module_version/version

version is set by the MODULE_VERSION macro.

The file does not exist if the MODULE_VERSION macro is not used in the module.

/sys/module/module_version/srcversion

srcversion is an MD4 hash of the source code used to compile the kernel module. It is calculated automatically at build time from https://github.com/torvalds/linux/blob/v4.9/scripts/mod/modpost.c#L1978 using https://github.com/torvalds/linux/blob/v4.9/scripts/mod/sumversion.c#L400

To enable it, either:

  • set MODULE_VERSION for the module
  • compile with CONFIG_MODULE_SRCVERSION_ALL . srcversion then gets generated for all modules, including those without MODULE_VERSION set: modinfo srcversion: How do I generate this from my source?

The srcversion file is only present when if one of the above holds.

You can then check that the built .ko matches the insmodded one with:

This is a very useful sanity check when you are developing your own kernel modules and copying modules between machines.

From inside module code itself with THIS_MODULE

Источник

Оцените статью