Что такое dkms в linux
Перейти к содержимому

Что такое dkms в linux

  • автор:

dkms 101

Loadable kernel module is very useful for dynamically adding functionality to the running kernel. As the free of Linux, we can often update/install new kernel easily. For some distributions, every time we install a new kernel, we need to compile the loadable module at the same time. This is very boring and in sometimes it can do some harmness. This is the Dynamic Kernel Module Support (DKMS) can play a role. DKMS is a program/framework that enables generating Linux kernel modules whose sources generally reside outside the kernel source tree. And the DKMS modules will be automatically rebuilt when a new kernel is installed.

This article will just focus how to use the dkms but not include the internals of it.

Let’s use the x710 network card VF driver as an example.

No DKMS

Firstly, Let’s see the system self-contained i40evf driver.

Here it has a low version of driver. We mannually override it with a more newer version.

It works, now let’s update the dist, this also updates the kernel.

Look at the i40evf again, it rolls back to the lower version again. If we want to use the high version i40evf, we need to compile it again.

With DKMS

Firstly, we need move the source file into the /usr/src directory. For example

Notice here i40evf-3.4.2 directory is the src directory in i40evf-3.4.2.tar.gz.

In this directory we need create a file named dkms.conf. Following is the file content.

Then install the dkms package.

Don’t forget install the linux headers package to build the module.

Now the i40evf has been updated to 3.4.2.

Updates the dist and reboot.

Notice the md5 checksum, we can make sure the i40evf module has been automatically rebuilt.

Ubuntu Documentation

This DKMS (Dynamic Kernel Module Support) package (http://linux.dell.com/dkms/) provides support for installing supplementary versions of kernel modules. The package compiles and installs into the kernel tree. Uninstalling restores the previous modules. By default, installation is into the current kernel tree, but any kernel tree can be selected with command-line options. Furthermore, DKMS is called automatically upon installation of new Ubuntu kernel-image packages, and therefore modules added to DKMS will be automatically carried across updates.

Overview

To use a module with DKMS, one places the module installation files (could be source code or binary) in /usr/src/<modulename>-<version>, along with a configuration file dkms.conf that tells DKMS how to build/configure the module and what its name is. Under more advanced scenarios, conditional build instructions and patching can be done by the dkms system, but considering on your case this may not be necessary.

Walk-through

Let’s say you want to install a module for your fancy "Awesome Adaptor." You are given a source tarball awesome-20091211-v1.1.tgz.

Without DKMS, you would unpack the module and read the README to figure out how to compile and install the module.

A typical README will have you do something like this:

With DKMS, we tell DKMS how to do that for you by creating a dkms.conf file with the appropriate entries. For example, after we’ve unpacked the tarball:

Inside dkms.conf, we might add the lines:

You can also add options to call scripts before or after build or install, provide additional (conditional) make commands, patch commands, etc. The dkms.conf is in fact sourced into a shell script, so a fair amount of trickery can be done if necessary. These options and more are described in the dkms.conf section in man dkms.

Next, we install the module into DKMS by copying the module installation files into the kernel source tree /usr/src/<modulename>-<version> and tell DKMS about the new module:

That’s it! DKMS has now added our module to its list of modules to build for future kernel installations. To make sure it works and to install the module into our current kernel, we can instruct dkms to build and install the module:

With some luck, your module will be installed and reinstalled into future kernel updates.

Examples

DKMS (последним исправлял пользователь 171 2012-03-18 11:26:44)

The material on this wiki is available under a free license, see Copyright / License for details
You can contribute to this wiki, see Wiki Guide for details

Dynamic Kernel Module Support (Русский)

Dynamic Kernel Module Support (DKMS) — это фреймворк, который используется для генерации тех модулей ядра Linux, которые в общем случае не включены в дерево исходного кода. DKMS позволяет драйверам устройств автоматически пересобираться, когда ядро уже установлено.

Это означает, что пользователь может не ждать, пока какая-то компания, проект или сопроводитель пакета выпустит новую версию модуля. После введения хуков pacman пересборка модулей осуществляется автоматически во время обновления ядра.

Установка

Установите пакет dkms и заголовочные файлы требуемого ядра/ядер. Например, для ядра по умолчанию linux соответствует linux-headers . Другие ядра имеют собственные пакеты с заголовочными файлами.

Значительное число модулей, не включенных в ядро, имеют DKMS вариант; некоторые из них размещаются в официальных репозиториях, но большинство из них можно найти только в AUR.

Обновления

Обычно пересборка модулей DKMS во время обновления ядра выполняется бесшовно, но что-то может пойти не так. Следует обратить особое внимание на вывод pacman! Это, в частности, относится к тем системам, которым требуется модуль DKMS для успешной загрузки и/или если вы используете DKMS с ядром не из официальных репозиториев.

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

Использование

Использование DKMS вручную.

Автозавершение по Tab будет доступно после выполнения команды:

Список модулей

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

Пересборка модулей

Пересборка всех модулей для текущего ядра:

или для конкретного ядра:

Сборка конкретного модуля для текущего ядра:

Сборка модуля для всех ядер:

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

Удаление модуля (старые автоматически не удаляются):

Если пакет dkms удален, то теряется информация о предыдущих файлах сборки модуля. В этом случае, перейдите в директорию /usr/lib/modules/kernel_release и /var/lib/dkms/package_name и удалите все файлы и каталоги, которые больше не используются.

Создание DKMS пакета

Initial ramdisk

В случаях для любых модулей, которые были установлены через DKMS и используются в Initrd, например zfs-dkms AUR , может быть полезно написать хук pacman для автоматической пересборки образа(ов) initramfs.

Например, когда используется linux и mkinitcpio, то для обновления модуля ZFS после каждого zfs-dkms AUR апгрейда,

Вы можете добавить больше таргетов в хук и сделать дополнительные копии хука, если в вашей система установлены другие ядра. Префикс 90- необходим для гарантированного запуска после хуков DPKMS.

What is DKMS in Linux

DKMS has many benefits for the Linux service provider communities, e.g.:

  1. From the driver developer’s point of view, it aids in adding drivers that are not already in the base kernel. Also, the driver developers who are required to make available updated device drivers for testing and common use on a large variety of kernels also benefit. Another advantage of DKMS is that the developers can test run their driver’s code on different machines. In fact, this speeds up the driver development process.
  2. From a system administrator standpoint, DKMS simplifies the process of installing device driver updates to the active kernel without adding any changes to it. Hence they do not need to wait for the arrival of a new kernel.
  3. Selected bug fixes or patches can be rolled out in between large-size updates.
  4. New hardware which requires modification in a single module can be easily integrated. Again this can be achieved without entirely testing the new kernels.

What will we cover?

This guide will discuss various kernel-related terminologies and specifically what is DKMS.

A Quick review of Terminologies

What is the Linux kernel?

It is the core part of a Linux OS. It is the main interface between the processes running on the OS and its hardware. It manages major functions like memory management, process management, CPU management, device driver management, and System calls and security management.

Kernel Space
The kernel is actually hidden from the user and works in its own area called Kernel Space. The user interacts with the kernel using the user applications like files browser, web browser, etc. These interactions use a specific programming construct called System Call.

Kernel Source Tree
It has all the source code for kernel and device drivers. It consists of many directories and subdirectories like arch, block, crypto, include, init, lib, usr, etc.

Linux kernel modules
Linux kernel modules are basically chunks of code. These can be added and removed from the kernel as per requirement. They can be built-in or loadable. The kernel module increases the functions of the kernel without requiring a system reboot. Unlike microkernels, where adding new components into the kernel requires configuring and building a new kernel, we can load and unload components or modules of the OS at runtime. These modules are device drivers, file systems, etc.

After a module is loaded, it is just like a piece of kernel code. It has the same privileges and duties as a normal kernel code.

Definition of DKMS

Here is an excerpt of the DKMS definition I found here:

“DKMS is a framework where device driver source can reside outside the kernel source tree so that it is very easy to rebuild modules as you upgrade kernels.”

Let us elaborate on the above. The DKMS system is a tree out of the base kernel tree on the ground. It contains the module source and compiled module binaries. As a result of this replication, modules are not coupled to the kernel. (Although modules are not entirely decoupled).

I myself first encountered the DKMS concept when I bought an HP laptop and installed Ubuntu 18.04 on it. Everything was working fine except for my wifi. My laptop was not able to locate any wifi adapter. In the Settings, the wifi menu displayed a message “No WiFi Adapter Found”. I started searching forums on the internet and discovered many people were experiencing the same issue. I found many solutions suggesting installing header files, drivers, and other packages.

I just blindly followed those guides without actually knowing what they actually wanted to convey. Anyway, those guides helped me out, and I got working wifi somehow. But the problem was that whenever I updated my Ubuntu system, the same problem arose, and I had to repeat the same steps of recompiling the downloaded drivers. Also, I have to fix the low signal problem every time after installing the driver. I even installed Windows OS, and to my surprise, the Wifi was actually working flawlessly. But I have to use Ubuntu for my work anyway. So I decided to live with the temporary patch I got earlier.

DKMS comes to the rescue

A recent solution that I just came across that I did not care about in the past used the DKMS way. Instead of using the make or make install command, DKMS performs three operations on the source code: add, build and install.

Using DKMS

For DKMS to work, the module source should be present on the system where we are building the module, and the location path should be like ‘/usr/src/<module>-<module-version>/’ and remember this is the very first requirement of DKMS. Another requirement is a file called ‘dkms.conf’, which will guide how to build and install a module. And just to mention, DKMS should already be installed on the system. Once everything is in place, we can add a module to the DKMS tree.

Let us see these steps by installing a demo module ‘demo-v0.1.tar.gz’ with DKMS. We are doing this sample is only for the purpose of understanding how DKMS works. After extracting the file, we need to ‘cd’ inside it:

Now create a dkms.conf file that contains the following lines:

Now that our dkms.conf file is ready, we can add our demo module as:

The beauty of the DKMS is that we can specify the kernel version against which we want to build or module as shown here:

If we do not specify the kernel, DKMS will build the module with the current kernel version.

If everything goes well, we can now install the module using:

If we upgrade our kernel or change the hardware architecture, a module must be manually rebuilt again. With the help of DKMS, this procedure becomes redundant as the DKMS dynamically builds these kernel modules for each kernel present on the system.

Conclusion

Tools like DKMS have greatly helped administrators, driver developers, and others reduce the kernel management task. While the end-users do not care about how the underlying system is working until their goals are met, DKMS lets developers and administrators focus on their work.

About the author

Ali Imran Nagori

Ali imran is a technical writer and Linux enthusiast who loves to write about Linux system administration and related technologies. You can connect with him on LinkedIn
.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *