Linux add module to kernel

Как загружать и выгружать модули ядра в 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: Linux Add or Remove a Linux Kernel Modules / Drivers

=> Under MS-Windows you use term device driver for modules.

=> Under Linux you use term modules for device drivers.

Tutorial details
Difficulty level Advanced
Root privileges Yes
Requirements modprobe/lsmod/modinfo utilities
Est. reading time N/A

=> The Linux kernel has a modular design.

=> At boot time, only a minimal resident kernel is loaded into memory.

=> If you add new hardware you need to add driver i.e. 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

=> The modprobe command intelligently adds or removes a module from the Linux kernel

=> Usually, all Linux kernel modules (drivers) are stored in the module directory located that /lib/modules/$(uname -r) directory. To see current modules, type:
$ ls /lib/modules/$(uname -r)
Output:

Use the following command to list all drivers for various devices:
$ ls /lib/modules/$(uname -r)/kernel/drivers/
Sample outputs:

Fig.01: Device drivers on my Linux based system

Task: Add a Module (driver) Called foo

Type the following command as root user:
# modprobe foo
In this example, I am loading a module called i8k, enter:
# modprobe -v i8k
Sample outputs:

Find out info about loaded module

You need to use the modinfo command to see information about a Linux Kernel module. The syntax is:
# modinfo -v
# modinfo i8k
Sample outputs:

Fig.02: Displaying information about a Linux Kernel module called i8k

Task: List all loaded modules

Use the lsmod command to show the status of modules in the Linux Kernel:
# lsmod
Sample outputs:

Task: Remove a module called foo

Pass the -r option to modprobe command to remove a module, type:
# modprobe -r foo
You can also use the rmmod command, which is simple program to remove a module from the Linux Kernel:
# rmmod foo

Recommended readings
  • man pages – modinfo, lsmod, insmod, and modprobe

🐧 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.

when the system is rebooted the module inside the kernel will not be present.But i want the modules to be seen permenently.what should i do.

Thanks alot for this, very helpful for teh newbz.

Thank’s first for the helpfull command , where can i get the new modules other then my OS,

how to build linux kernel module with new device driver module during build

Thanks a lot for the info…:) 🙂

Hi there…
I am trying to remove TCP IP from a linux kernel, and want to recompile the LINUX kernel. But being a novice with the administrations of the linux (UBUNTU 10.4), I know a little about it. Agter recompilation can I again design mu own TCPIP using the C language code?
Guys please help me out…waiting for the reply .
Regards…

Thanks for this very short but very clear information. That helps me to understand the concept (of add or remove module on Linux) very much.

One question remain: how do we check to know what modules are available to add on a existing system?

Thank you in advance!

One question remain: how do we check to know what modules are available to add on a existing system?

cd to /lib/modules/$(uname -r) directory and you can see the list of available modules (run as root):

The following will list all drives

To find out more info about a module called foo:

Hope this helps!

Hi
thanks for your comments, I am trying to write a printer driver for linux, what should I do?

Please help me on this task.

Does anyone knows step by step guide for how to install ip_conntrack support into kernel Linux linux 2.6.35.14-106.fc14.i686 #1 SMP Wed Nov 23 13:57:33 UTC 2011 i686 i686 i386 GNU/Linux

I am unable to remove the following modules after issuing the commands.
$ rmmod usbhid and
$rmmod hid..

After issuing the commands the modules are not shown in “lsmod” but as soon as a device is added they again get loaded.

thanks, very clear article.

Hello there. I have an old computer Celeron, 128MB RAM and 28MB of VGA. What I want to do is keep the drivers that are needed for my system. Like if I use the Realtek Chipset for Network Card why should the Atheros driver be present on the system? Is there any way to accomplish this task?
Regards.

I have a serious problem, my Linux does not have these comands:
apt-get
uname
modprobe
mknod
man
…etc… and also has not a lot of typical commands

And there is no /dev/loop*

And mount -o loop blablabla bleble say incorrect option, does not undertand loop.

Of course, all problem seem that Kernel has no loop device support.

How can i fix it?

Please have in mind Kernel is on ROM (a chip not writteable), it is not a flasheable chip, i can not modify it on any way, … read only memory chip!!

I wish if it could be possible to add loop device support at run time as a module…

But it does not have modprobe command… neither a lot of clasic Linux commands… so i got to fail.

Need some help, i am not an expert.

Step 1: try to create /dev/loop0 (it does not exists) with mknod but mknod command not found

Try to add such coomands with apt-get, wget, etc… all says such commands not exists

I am getting mad…

Please note it is an ARM processor based, and Kernel is on a ReadOnly chip not flashable.

Thanks in advance for any help… i am getting really mad…

If I were you, rather than finding Linux Kernel modulos to have “uname”, “modprobe”, “man” recovered (maybe you have played around some kernel rebuild and screwed up some basic binaries?), I will re-install the entire Linux OS from scratch. You can download CentOS (Red Hat) or SUSE, Fedora or whatever Linux to have all these basic utilities included.

trying to add slcan module to kernel 2.6.32-504.30.3.el6.i686 but having problems with the following response … question is how to get it added

FATAL: Module slcan not found.

Thank you so much…

i want to know how many mouldes in linus and brief explanation of them.i will glad if my question is been answered.

hi all,
iam unable to remove nvme module in primary drive(ssd) by using
following comment:
rmmod nvme

Источник

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.

Источник

Читайте также:  Как удалить vst плагины mac os
Оцените статью