Unload kernel module что это windows

Kernelmoduleunloader.exe - это программа, разработанная Dark Byte.

Содержание

  • 1. Что такое Kernelmoduleunloader.exe?
  • 2. Kernelmoduleunloader.exe безопасный или это вирус или вредоносное ПО?
  • 3. Могу ли я удалить или удалить Kernelmoduleunloader.exe?
  • 4. Распространенные сообщения об ошибках в Kernelmoduleunloader.exe
  • 5. Как исправить Kernelmoduleunloader.exe
  • 6. Обновление за февраль 2023
  • 7. Загрузите или переустановите Kernelmoduleunloader.exe


Обновлено февраль 2023: Вот три шага к использованию инструмента восстановления для устранения проблем с exe на вашем компьютере: Получите его по адресу эту ссылку

  1. Скачайте и установите это программное обеспечение.
  2. Просканируйте свой компьютер на наличие проблем с exe.
  3. Исправьте ошибки exe с помощью программного инструмента

Kernelmoduleunloader.exe это исполняемый файл, который является частью Чит двигателя 5.5 Программа, разработанная Темный байт, Программное обеспечение обычно о 9.36 MB по размеру.

Расширение .exe имени файла отображает исполняемый файл. В некоторых случаях исполняемые файлы могут повредить ваш компьютер. Пожалуйста, прочитайте следующее, чтобы решить для себя, является ли Kernelmoduleunloader.exe Файл на вашем компьютере — это вирус или троянский конь, который вы должны удалить, или это действительный файл операционной системы Windows или надежное приложение.

Рекомендуется: Выявление ошибок, связанных с Kernelmoduleunloader.exe.
(опциональное предложение для Reimage — Cайт | Лицензионное соглашение | Персональные данные | Удалить)

Kernelmoduleunloader.exe является вирусом или вредоносным ПО?

Kernelmoduleunloader.exe безопасный или это вирус или вредоносное ПО?

Первое, что поможет вам определить, является ли тот или иной файл законным процессом Windows или вирусом, это местоположение самого исполняемого файла. Например, такой процесс, как Kernelmoduleunloader.exe, должен запускаться из C: Program Files Cheat Engine Cheat Engine.exe, а не в другом месте.

Для подтверждения откройте диспетчер задач, выберите «Просмотр» -> «Выбрать столбцы» и выберите «Имя пути к изображению», чтобы добавить столбец местоположения в диспетчер задач. Если вы обнаружите здесь подозрительный каталог, возможно, стоит дополнительно изучить этот процесс.

Еще один инструмент, который иногда может помочь вам обнаружить плохие процессы, — это Microsoft Process Explorer. Запустите программу (не требует установки) и активируйте «Проверить легенды» в разделе «Параметры». Теперь перейдите в View -> Select Columns и добавьте «Verified Signer» в качестве одного из столбцов.

Если статус процесса «Проверенная подписывающая сторона» указан как «Невозможно проверить», вам следует взглянуть на процесс. Не все хорошие процессы Windows имеют метку проверенной подписи, но ни один из плохих.

Наиболее важные факты о Kernelmoduleunloader.exe:

  • Находится в C: Program Files Cheat Engine вложенная;
  • Издатель: Темный байт
  • Полный путь: C: Program Files Cheat Engine Cheat Engine.exe
  • Файл справки:
  • URL издателя: www.cheatengine.org
  • Известно, что до 9.36 MB по размеру на большинстве окон;

Если у вас возникли какие-либо трудности с этим исполняемым файлом, перед удалением Kernelmoduleunloader.exe необходимо определить, заслуживает ли он доверия. Для этого найдите этот процесс в диспетчере задач.

Найдите его местоположение (оно должно быть в C: Program Files Cheat Engine ) и сравните его размер с приведенными выше фактами.

Если вы подозреваете, что можете быть заражены вирусом, вы должны немедленно попытаться это исправить. Чтобы удалить вирус Kernelmoduleunloader.exe, необходимо Загрузите и установите приложение полной безопасности, например Malwarebytes., Обратите внимание, что не все инструменты могут обнаружить все типы вредоносных программ, поэтому вам может потребоваться попробовать несколько вариантов, прежде чем вы добьетесь успеха.

Кроме того, функциональность вируса может сама влиять на удаление Kernelmoduleunloader.exe. В этом случае вы должны включить Безопасный режим с загрузкой сетевых драйверов — безопасная среда, которая отключает большинство процессов и загружает только самые необходимые службы и драйверы. Когда вы можете запустить программу безопасности и полный анализ системы.

Могу ли я удалить или удалить Kernelmoduleunloader.exe?

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

Согласно различным источникам онлайн,
8% людей удаляют этот файл, поэтому он может быть безвредным, но рекомендуется проверить надежность этого исполняемого файла самостоятельно, чтобы определить, является ли он безопасным или вирусом. Лучшая диагностика для этих подозрительных файлов — полный системный анализ с Reimage, Если файл классифицирован как вредоносный, эти приложения также удалят Kernelmoduleunloader.exe и избавятся от связанных вредоносных программ.

Однако, если это не вирус и вам необходимо удалить Kernelmoduleunloader.exe, вы можете удалить Cheat Engine 5.5 со своего компьютера с помощью программы удаления, которая должна находиться по адресу: «C: Program Files Cheat Engine unins000.exe. «. Если вы не можете найти его деинсталлятор, возможно, вам придется удалить Cheat Engine 5.5, чтобы полностью удалить Kernelmoduleunloader.exe. Вы можете использовать функцию «Добавить / удалить программу» в Панели управления Windows.

  • 1. в Меню Пуск (для Windows 8 щелкните правой кнопкой мыши в нижнем левом углу экрана), нажмите Панель управления, а затем под Программы:
    o Windows Vista / 7 / 8.1 / 10: нажмите Удаление программы.
    o Windows XP: нажмите Установка и удаление программ.
  • 2. Когда вы найдете программу Чит двигателя 5.5щелкните по нему, а затем:
    o Windows Vista / 7 / 8.1 / 10: нажмите Удалить.
    o Windows XP: нажмите Удалить or Изменить / Удалить вкладка (справа от программы).
  • 3. Следуйте инструкциям по удалению Чит двигателя 5.5.

Распространенные сообщения об ошибках в Kernelmoduleunloader.exe

Наиболее распространенные ошибки Kernelmoduleunloader.exe, которые могут возникнуть:

• «Ошибка приложения Kernelmoduleunloader.exe».
• «Ошибка Kernelmoduleunloader.exe».
• «Возникла ошибка в приложении Kernelmoduleunloader.exe. Приложение будет закрыто. Приносим извинения за неудобства».
• «Kernelmoduleunloader.exe не является допустимым приложением Win32».
• «Kernelmoduleunloader.exe не запущен».
• «Kernelmoduleunloader.exe не найден».
• «Не удается найти Kernelmoduleunloader.exe».
• «Ошибка запуска программы: Kernelmoduleunloader.exe».
• «Неверный путь к приложению: Kernelmoduleunloader.exe».

Эти сообщения об ошибках .exe могут появляться во время установки программы, во время выполнения связанной с ней программы Cheat Engine 5.5, при запуске или завершении работы Windows, или даже при установке операционной системы Windows. Отслеживание момента появления ошибки Kernelmoduleunloader.exe является важной информацией при устранении неполадок.

Как исправить Kernelmoduleunloader.exe

Аккуратный и опрятный компьютер — это один из лучших способов избежать проблем с Cheat Engine 5.5. Это означает выполнение сканирования на наличие вредоносных программ, очистку жесткого диска cleanmgr и ПФС / SCANNOWудаление ненужных программ, мониторинг любых автозапускаемых программ (с помощью msconfig) и включение автоматических обновлений Windows. Не забывайте всегда делать регулярные резервные копии или хотя бы определять точки восстановления.

Если у вас возникла более серьезная проблема, постарайтесь запомнить последнее, что вы сделали, или последнее, что вы установили перед проблемой. Использовать resmon Команда для определения процессов, вызывающих вашу проблему. Даже в случае серьезных проблем вместо переустановки Windows вы должны попытаться восстановить вашу установку или, в случае Windows 8, выполнив команду DISM.exe / Online / Очистка-изображение / Восстановить здоровье, Это позволяет восстановить операционную систему без потери данных.

Чтобы помочь вам проанализировать процесс Kernelmoduleunloader.exe на вашем компьютере, вам могут пригодиться следующие программы: Менеджер задач безопасности отображает все запущенные задачи Windows, включая встроенные скрытые процессы, такие как мониторинг клавиатуры и браузера или записи автозапуска. Единый рейтинг риска безопасности указывает на вероятность того, что это шпионское ПО, вредоносное ПО или потенциальный троянский конь. Это антивирус обнаруживает и удаляет со своего жесткого диска шпионское и рекламное ПО, трояны, кейлоггеры, вредоносное ПО и трекеры.

Обновлено февраль 2023:

Мы рекомендуем вам попробовать это новое программное обеспечение, которое исправляет компьютерные ошибки, защищает их от вредоносных программ и оптимизирует производительность вашего ПК. Этот новый инструмент исправляет широкий спектр компьютерных ошибок, защищает от таких вещей, как потеря файлов, вредоносное ПО и сбои оборудования.

  • Шаг 1: Скачать PC Repair & Optimizer Tool (Windows 10, 8, 7, XP, Vista — Microsoft Gold Certified).
  • Шаг 2: Нажмите «Начать сканирование”, Чтобы найти проблемы реестра Windows, которые могут вызывать проблемы с ПК.
  • Шаг 3: Нажмите «Починить все», Чтобы исправить все проблемы.

скачать
(опциональное предложение для Reimage — Cайт | Лицензионное соглашение | Персональные данные | Удалить)

Загрузите или переустановите Kernelmoduleunloader.exe

Вход в музей Мадам Тюссо не рекомендуется загружать замещающие exe-файлы с любых сайтов загрузки, так как они могут сами содержать вирусы и т. д. Если вам нужно скачать или переустановить Kernelmoduleunloader.exe, то мы рекомендуем переустановить основное приложение, связанное с ним Чит двигателя 5.5.

Информация об операционной системе

Ошибки Kernelmoduleunloader.exe могут появляться в любых из нижеперечисленных операционных систем Microsoft Windows:

  • Windows 10
  • Windows 8.1
  • Windows 7
  • Windows Vista
  • Windows XP
  • Windows ME
  • Windows 2000

Почему пользовательское приложение работает некорректно? Существует не так много способов, которые бы помогали выявить проблему. В большинстве случаев для поддержания высокой доступности требуется стороннее программное обеспечение. В статье рассказываем, как настроить мониторинг пользовательского приложения через модуль ядра Linux, а также разбираем, как установить связь с сокетом.

Введение

Двустороннее взаимодействие между пользовательским приложением и модулем ядра:

Application: любое приложение, запущенное на уровне пользователя, которое может взаимодействовать с модулем ядра.

Kernel Module: содержит определение системных вызовов, которые могут использоваться API-интерфейсами приложений и ядра для мониторинга работоспособности.

«Администрирование Linux. Мега»

Проверка состояния модуля ядра

Разберём команды, которые полезны при написании и использовании расширений ядра.

Загрузка модуля ядра

insmod: используется для вставки модуля в ядро.

пример: insmod ‘kernel_ext_binary’

# insmod helloWorld.ko
Welcome to Hello world Module.

Выгрузка модуля ядра

пример: rmmod ‘kernel_ext_binary’

# rmmod helloWorld.ko
Goodbye, from Hello world.

Список всех запущенных модулей ядра

lsmod: выводит список всех загруженных модулей ядра. 

пример: lsmod | grep ‘kernel_ext_binary’

# lsmod | grep hello
helloWorld 12189  1

Подробная информация о модуле ядра

modinfo: отображает дополнительную информацию о модуле. 

пример: modinfo hello*.ko

# modinfo helloWorld.ko
filename:       /root/helloWorld.ko
description:    Basic Hello World KE
author:         helloWorld
license:        GPL
rhelversion:    7.3
srcversion:     5F60F86F84D8477986C3A50
depends:
vermagic:       3.10.0-514.el7.ppc64le SMP mod_unload modversions

Перечисленные команды можно запускать на консоли и через бинарное приложение с помощью вызова system().

Связь с пользовательским пространством

Пользовательское пространство должно открыть файл по указанному пути с помощью open() API. Этот файл используется пользовательским приложением и модулем ядра для взаимодействия друг с другом. Все команды и данные из пользовательского приложения записываются в этот файл, из которого модуль ядра считывает и выполняет действия. Возможно и обратное.

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int open(const char *pathname, int flags);

Пример:

int fd;
#define DEVICE_FILE_NAME "/dev/char_dev"
fd = open(DEVICE_FILE_NAME, 0);

Возвращаемое значение open() — дескриптор файла, небольшое неотрицательное целое число, которое используется в последующих системных вызовах (в данном случае ioctl).

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

Системный вызов ioctl() может быть вызван из пользовательского пространства для управления базовыми параметрами устройства.

#include <sys/ioctl.h>

int ioctl(int fd, int cmd, ...);

fd — это файловый дескриптор, возвращаемый из open(), а cmd — то же самое, что реализовано в ioctl() модуля ядра.

Пример:

#define IOCTL_SEND_MSG _IOR(MAJOR_NUM, 0, char *)
int ret_val;
char message[100];
ret_val = ioctl(file_desc, IOCTL_SEND_MSG, message);
if (ret_val < 0) {
printf("ioctl_send_msg failed:%dn", ret_val);
exit(−1);
}

В приведенном примере IOCTL_SEND_MSG — команда, которая отправляется модулю.

_IOR означает, что приложение создаёт номер команды ioctl для передачи информации из пользовательского приложения в модуль ядра. 

Первый аргумент, MAJOR_NUM, — основной номер используемого нами устройства.

Второй аргумент — номер команды (их может быть несколько с разным значением).

Третий аргумент — тип, который мы хотим передать от процесса к ядру.

Точно так же пользовательское приложение может получить сообщение от ядра с небольшим изменением аргументов ioctl.

Обработка потоков в модуле ядра

В следующих разделах рассмотрим способы обработки многопоточности в контексте ядра. 

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

Мы можем создать несколько потоков в модуле, используя следующие вызовы:

#include <linux/kthread.h>
static struct task_struct * sampleThread = NULL;
sampleThread = kthread_run(threadfn, data, namefmt, …)

kthread_run() создаёт новый поток и сообщает ему о запуске.

threadfn — имя функции для запуска. 

data * — указатель на аргументы функции.

namefmt — имя потока (в выводе команды ps)

Остановка потока

Мы можем остановить запущенные потоки, используя вызов:

kthread_stop(sampleThread)

Установка связи с сокетом

Можно создать необработанный сокет с помощью функции sock_create(). Через этот сокет модуль ядра будет взаимодействовать с другими приложениями пользовательского уровня внутри или вне хоста.

struct socket *sock;
struct sockaddr_ll *s1 = kmalloc(sizeof(struct sockaddr_ll),GFP_KERNEL);
result = sock_create(PF_PACKET, SOCK_RAW, htons(ETH_P_IP), &sock);
if(result < 0)
{
printk(KERN_INFO "[vmmKE] unable to create socket");
    return -1;
}

//copy the interface name to ifr.name  and other required information.
strcpy((char *)ifr.ifr_name, InfName);
s1->sll_family = AF_PACKET;
s1->sll_ifindex = ifindex;
s1->sll_halen = ETH_ALEN;
s1->sll_protocol = htons(ETH_P_IP);

result = sock->ops->bind(sock, (struct sockaddr *)s1, sizeof(struct sockaddr_ll));
if(result < 0)
{
printk(KERN_INFO "[vmmKE] unable to bind socket");
    return -1;
}

С помощью sock_sendmsg() модуль ядра может отправлять данные, используя структуру сообщения.

struct msghdr message;
int ret= sock_sendmsg(sock, (struct msghdr *)&message);

Генерация сигналов процессу пользовательского пространства

Сигналы тоже можно сгенерировать из модуля ядра в пользовательское приложение. Если идентификатор процесса (PID) известен ядру, используя этот pid, модуль может заполнить требуемую структуру pid и передать ее в send_sig_info() для запуска сигнала.

struct pid *pid_struct = find_get_pid(pid);
struct task_struct *task = pid_task(pid_struct,PIDTYPE_PID);
int signum = SIGKILL, sig_ret;
struct siginfo info;
memset(&info, '', sizeof(struct siginfo));
info.si_signo = signum;
//send a SIGKILL to the daemon
sig_ret = send_sig_info(signum, &info, task);
if (sig_ret < 0)
{
printk(KERN_INFO "error sending signaln");
return -1;
}

Ротация логов 

Если пользователь хочет перенаправить все логи, связанные с модулем ядра, в определённый файл, необходимо добавить запись в rsyslog (/etc/rsyslog.conf) следующим образом:

:msg,startswith,"[HelloModule]" /var/log/helloModule.log 

Это позволяет rsyslog перенаправлять все логи ядра, начинающиеся с [Hello Module], в модуль /var/log/helloModule.log file. 

Пример: пользователи могут написать собственный сценарий ротации и поместить его в /etc/logrotate.d.

"/var/log/helloModule.log" {
daily
rotate 4
maxsize 2M
create 0600 root
postrotate
    service rsyslog restart > /dev/null
endscript
}

Сценарий ежедневно проверяет, не превышает ли размер файла логов 2 МБ, и поддерживает 4 ротации этого файла. Если размер логов превышает 2 МБ, будет создан новый файл с тем же именем и правами доступа к файлу 0600, а к старому файлу будет добавлена отметка даты и времени.

После ротации он перезапустит службу rsyslog.

Создание файла

Обратитесь к содержимому makefile, чтобы сгенерировать двоичные файлы для сэмпла программы:

obj−m += helloWorld.o
all:
make −C /lib/modules/$(shell uname −r)/build M=$(PWD) modules
clean:
make −C /lib/modules/$(shell uname −r)/build M=$(PWD) clean

Примечание: пример основан на варианте RHEL. Другие варианты реализации makefile могут отличаться.

Интеграция модуля ядра с пользовательским приложением 

Пользовательское приложение использует вызовы ioctl для отправки данных в модуль ядра. В приведённом ниже примере эти вызовы ioctl можно использовать для отправки сведений о приложении или отправки обновлений в более поздний момент времени.

Пример пользовательского приложения

Пример включает в себя все концепции, описанные ранее.

# cat helloWorld.h

#ifndef HELLOWORLD_H
#define HELLOWORLD_H
#include <linux/ioctl.h>

// cmd ‘KE_DATA_VAR’ to send the integer type data
#define KE_DATA_VAR _IOR('q', 1, int *)

#endif

# cat helloWorld.c

#include <stdio.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/ioctl.h>
#include <stdlib.h>
#include "helloWorld.h"

/* @brief: function to load the kernel module */
void load_KE()
{
    printf ("loading KEn");
    if (system ("insmod /root/helloWorld.ko") == 0)
    {
        printf ("KE loaded successfully");
    }
}

/* @brief: function to unload the kernel module */
void unload_KE()
{
    printf ("unloading KEn");
    if (system ("rmmod /root/helloWorld.ko") == 0)
    {
        printf ("KE unloaded successfully");
    }
}

/* @brief: method to send data to kernel module */
void send_data(int fd)
{
    int v;

    printf("Enter value: ");
    scanf("%d", &v);
    getchar();
    if (ioctl(fd, KE_DATA_VAR, &v) == -1)
    {
        perror("send data error at ioctl");
    }
}

int main(int argc, char *argv[])
{
    const char *file_name = "/dev/char_device"; //used by ioctl
    int fd;
    enum
    {
        e_load, //load the kernel module
        e_unload, //unload the kernel module
        e_send, //send a HB from test binary to kernel module
    } option;

    if (argc == 2)
    {
        if (strcmp(argv[1], "-l") == 0)
        {
            option = e_load;
        }
        else if (strcmp(argv[1], "-u") == 0)
        {
            option = e_unload;
        }
                }
        else if (strcmp(argv[1], "-s") == 0)
        {
            option = e_send;
        }
        else
        {
            fprintf(stderr, "Usage: %s [-l | -u | -s ]n", argv[0]);
            return 1;
        }
    }
    else
    {
        fprintf(stderr, "Usage: %s [-l | -u | -s ]n", argv[0]);
        return 1;
    }

    if ((option != e_load) && (option != e_unload))
    {
        fd = open(file_name, O_RDWR);
        if (fd == -1)
        {
            perror("KE ioctl file open");
            return 2;
        }
    }
    switch (option)
    {
        case e_load:
            load_KE();
            break;
        case e_unload:
            unload_KE();
            break;
        case e_send:
            send_data(fd);
            break;
        default:
            break;
    }

    if ((option != e_load) && (option != e_unload))
    {
        close (fd);
    }
return 0;
}

Sample kernel module
# cat helloWorld.c
#include <linux/slab.h>
#include <linux/kthread.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/version.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <linux/device.h>
#include <linux/errno.h>
#include <asm/uaccess.h>
#include <linux/time.h>
#include <linux/mutex.h>
#include <linux/socket.h>
#include <linux/ioctl.h>
#include <linux/notifier.h>
#include <linux/reboot.h>
#include <linux/sched.h>
#include <linux/pid.h>
#include <linux/kmod.h>
#include <linux/if.h>
#include <linux/net.h>
#include <linux/if_ether.h>
#include <linux/if_packet.h>
#include <linux/unistd.h>
#include <linux/types.h>
#include <linux/time.h>
#include <linux/delay.h>

typedef struct
{
    char ethInfName[8];
    char srcMacAdr[15];
    char destMacAdr[15];
    int ifindex;
}KEConfig_t;

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Owner Name");
MODULE_DESCRIPTION("Sample Hello world");
MODULE_VERSION("0.1");

static char *name = "world";
static struct task_struct *ke_thread;
static struct KEConfig_t KECfg;
module_param(name, charp, S_IRUGO);
MODULE_PARM_DESC(name, "The name to display in /var/log/kern.log");


/* @brief: create socket and send required data to HM
 * creates the socket and binds on to it.
 * This method will also send event notification
 * to HM.
 * */
static int createSocketandSendData(char *data)
{
    int ret_l =0;
    mm_segment_t oldfs;
    struct msghdr message;
    struct iovec ioVector;

    int result;
    struct ifreq ifr;
    struct socket *sock;
    struct sockaddr_ll *s1 = kmalloc(sizeof(struct sockaddr_ll),GFP_KERNEL);
    if (!s1)
    {
       printk(KERN_INFO "failed to allocate memory");
       return -1;
    }
    printk(KERN_INFO "inside configureSocket");
    memset(s1, '', sizeof(struct sockaddr_ll));
    memset(픦, '', sizeof(ifr));

    result = sock_create(PF_PACKET, SOCK_RAW, htons(ETH_P_IP), &sock);
    if(result < 0)
    {
        printk(KERN_INFO "unable to create socket");
        return -1;
    }
    printk(KERN_INFO "interface: %s", KECfg.ethInfName);
    printk(KERN_INFO "ifr index: %d", KECfg.ifindex);
    strcpy((char *)ifr.ifr_name, KECfg.ethInfName);

    s1->sll_family = AF_PACKET;
    s1->sll_ifindex = KECfg.ifindex;
    s1->sll_halen = ETH_ALEN;
    s1->sll_protocol = htons(ETH_P_IP);
result = sock->ops->bind(sock, (struct sockaddr *)s1, sizeof(struct sockaddr_ll));
    if(result < 0)
    {
        printk(KERN_INFO "Unable to bind socket");
        return -1;
    }

    //create the message header
    memset(&message, 0, sizeof(message));
    message.msg_name = sockData->sock_ll;
    message.msg_namelen = sizeof(*(sock_ll));

    ioVector.iov_base = data;
    ioVector.iov_len  = sizeof(data);
    message.msg_iov = &ioVector;
    message.msg_iovlen = 1;
    message.msg_control = NULL;
    message.msg_controllen = 0;
    oldfs = get_fs();
    set_fs(KERNEL_DS);
    ret_l = sock_sendmsg(sockData->sock, &message, sizeof(data));


    return 0;
}

static long ke_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
{
    int b;

    switch (cmd)
    {
        case KE_DATA_VAR:
        if (get_user(b, (int *)arg))
        {
        return -EACCES;
        }
        //set the time of HB here
        mutex_lock(&dataLock);
        do_gettimeofday(&hbTv);
        printk(KERN_INFO "time of day is %ld:%lu n", hbTv.tv_sec, hbTv.tv_usec);
        printk(KERN_INFO "data %dn", b);
        //send data out
        createSocketandSendData(&b);
        mutex_unlock(&dataLock);
        break;
        default:
            return -EINVAL;
    }

    return 0;
}

/* @brief: method to register the ioctl call */
static struct file_operations ke_fops =
{
    .owner = THIS_MODULE,
#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,35))
    .ioctl = ke_ioctl
#else
    .unlocked_ioctl = ke_ioctl
#endif
};

/* @brief The thread function */
int ke_init()
{
    printk(KERN_INFO "Inside function");
    return 0;
}

/* @brief The LKM initialization function */
static int __init module_init(void)
{
   printk(KERN_INFO "module_init initializedn");
   if ((ret = alloc_chrdev_region(&dev, FIRST_MINOR, MINOR_CNT, "KE_ioctl")) < 0)
   {
       return ret;
   }

   cdev_init(&c_dev, &ke_fops);

   if ((ret = cdev_add(&c_dev, dev, MINOR_CNT)) < 0)
   {
       return ret;
   }

   if (IS_ERR(cl = class_create(THIS_MODULE, "char")))
   {
       cdev_del(&c_dev);
       unregister_chrdev_region(dev, MINOR_CNT);
       return PTR_ERR(cl);
   }
   if (IS_ERR(dev_ret = device_create(cl, NULL, dev, NULL, "KEDevice")))
   {
       class_destroy(cl);
       cdev_del(&c_dev);
       unregister_chrdev_region(dev, MINOR_CNT);
       return PTR_ERR(dev_ret);
   }

   //create related threads
   mutex_init(&dataLock); //initialize the lock
   KEThread = kthread_run(ke_init,"KE thread","KEThread");

  return 0;
}

void thread_cleanup(void)
{
    int ret = 0;

    if (ke_thread)
    ret = kthread_stop(ke_thread);
    if (!ret)
        printk(KERN_INFO "Kernel thread stopped");
}

/* @brief The LKM cleanup function */
static void __exit module_exit(void)
{
   device_destroy(cl, dev);
   class_destroy(cl);
   cdev_del(&c_dev);
   unregister_chrdev_region(dev, MINOR_CNT);

   thread_cleanup();
   printk(KERN_INFO "Exit %s from the Hello world!n", name);
}

module_init(module_init);
module_exit(module_exit);

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

Все модули заканчиваются вызовом либо cleanup_module(), либо функции, которую вы указываете с помощью вызова module_exit(). Это функция выхода для модулей — она отменяет всё, что сделала функция ввода.

Примечание: предположим, файл открыт в пользовательском пространстве с помощью функции open(), которая используется для связи с модулем ядра. 

Если какой-либо вызов execve() выполняется пользовательским процессом, нужно установить параметр сокета FD_CLOEXEC в fd (файловый дескриптор).

fd = open(“/dev/char_device”, O_RDWR);
fcntl(fd, F_SETFD, FD_CLOEXEC);

Если параметр FD_CLOEXEC не установлен для этого fd, дескриптор файла должен оставаться открытым при вызове execve(). 

Коротко о главном

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

«Администрирование Linux. Мега»

Содержание

  1. Kernel module
  2. Contents
  3. Obtaining information
  4. Automatic module loading with systemd
  5. Manual module handling
  6. Setting module options
  7. Manually at load time using modprobe
  8. Using files in /etc/modprobe.d/
  9. Using kernel command line
  10. Aliasing
  11. Blacklisting
  12. Using files in /etc/modprobe.d/
  13. Using kernel command line
  14. Troubleshooting
  15. Modules do not load
  16. Kernel module (Русский)
  17. Contents
  18. Обзор
  19. Получение информации
  20. Автоматическое управление модулями
  21. Управление модулями вручную
  22. Настройка параметров модуля
  23. С помощью файлов в /etc/modprobe.d/
  24. С помощью командной строки ядра
  25. Создание псевдонимов
  26. Запрет загрузки
  27. С помощью файлов в /etc/modprobe.d/
  28. С помощью командной строки ядра
  29. How to Load and Unload Kernel Modules in Linux
  30. List All Loaded Kernel Modules in Linux
  31. How to Load and Unload (Remove) Kernel Modules in Linux
  32. How to Manage Kernel Modules Using modprobe Command
  33. If You Appreciate What We Do Here On TecMint, You Should Consider:
  34. How to load or unload a Linux kernel module
  35. Fix problem peripherals by finding and loading kernel modules.
  36. Subscribe now
  37. kernels.png
  38. Finding kernel modules
  39. Manually loading kernel modules
  40. Модули ядра Linux
  41. Модули ядра Linux
  42. Все модули
  43. Что загружено?
  44. Запуск модулей ядра
  45. Удаление модулей ядра
  46. Блокирование загрузки модулей
  47. Автозагрузка модулей
  48. Установка модулей ядра Linux
  49. Выводы

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

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.

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

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.

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

Источник

Kernel module (Русский)

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

Contents

Обзор

Чтобы создать модуль ядра, вы можете прочитать The Linux Kernel Module Programming Guide. Модуль можно сконфигурировать как вкомпилированный, а можно как загружаемый. Чтобы иметь возможность динамически загружать или выгружать модуль, его необходимо сконфигурировать как загружаемый модуль в настройке ядра (в этом случае строка, относящаяся к модулю должна быть отмечена буквой M ).

Получение информации

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

Чтобы показать информацию о модуле:

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

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

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

Чтобы узнать зависимости модуля (или его псевдонима), включая сам модуль:

Автоматическое управление модулями

Сегодня все необходимые загрузки модулей делаются автоматически с помощью udev, поэтому если вам не нужно загружать какие-либо модули, не входящие в стандартное ядро, вам не придётся прописывать модули, требующиеся для загрузки в каком-либо конфигурационном файле. Однако, бывают случаи, когда вам необходимо загружать свой модуль в процессе загрузки или наоборот не загружать какой-то стандартный модуль, чтобы ваш компьютер правильно функционировал.

Смотрите modules-load.d(5) для дополнительной информации.

Управление модулями вручную

Альтернативный вариант выгрузки модуля:

Настройка параметров модуля

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

С помощью файлов в /etc/modprobe.d/

С помощью командной строки ядра

Если модуль вкомпилирован в ядро, вы также можете передать параметры модулю с помощью командной строки ядра. Для всех стандартных загрузчиков, подойдёт следующий синтаксис:

Просто добавьте это в загрузчике в строку с ядром, как описано в параметрах ядра.

Создание псевдонимов

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

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

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

С помощью файлов в /etc/modprobe.d/

Можно изменить такое поведение. Команда install заставляет modprobe запускать вашу собственную команду вместо вставки модуля в ядро как обычно. Поэтому вы можете насильно сделать так, чтобы модуль никогда не загружался:

Это запретит данный модуль и все модули, зависящие от него.

С помощью командной строки ядра

Вы также можете запрещать модули из загрузчика.

Источник

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

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

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.

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.

coffee

We are thankful for your never ending support.

Источник

How to load or unload a Linux kernel module

Fix problem peripherals by finding and loading kernel modules.

code computer development programming

Subscribe now

Get the highlights in your inbox every week.

This article is excerpted from chapter 15 of Linux in Action, published by Manning.

Linux manages hardware peripherals using kernel modules. Here’s how that works.

A running Linux kernel is one of those things you don’t want to upset. After all, the kernel is the software that drives everything your computer does. Considering how many details have to be simultaneously managed on a live system, it’s better to leave the kernel to do its job with as few distractions as possible. But if it’s impossible to make even small changes to the compute environment without rebooting the whole system, then plugging in a new webcam or printer could cause a painful disruption to your workflow. Having to reboot each time you add a device to get the system to recognize it is hardly efficient.

To create an effective balance between the opposing virtues of stability and usability, Linux isolates the kernel, but lets you add specific functionality on the fly through loadable kernel modules (LKMs). As shown in the figure below, you can think of a module as a piece of software that tells the kernel where to find a device and what to do with it. In turn, the kernel makes the device available to users and processes and oversees its operation.

kernels.png

kernels

Kernel modules act as translators between devices and the Linux kernel.

There’s nothing stopping you from writing your own module to support a device exactly the way you’d like it, but why bother? The Linux module library is already so robust that there’s usually no need to roll your own. And the vast majority of the time, Linux will automatically load a new device’s module without you even knowing it.

Still, there are times when, for some reason, it doesn’t happen by itself. (You don’t want to leave that hiring manager impatiently waiting for your smiling face to join the video conference job interview for too long.) To help things along, you’ll want to understand a bit more about kernel modules and, in particular, how to find the actual module that will run your peripheral and then how to manually activate it.

Finding kernel modules

In my case, the active kernel is the version with the highest release number (4.4.0-104-generic), but there’s no guarantee that that’ll be the same for you (kernels are frequently updated). If you’re going to be doing some work with modules that you’d like to use on a live system, you need to be sure you’ve got the right directory tree.

You’ll find most of the modules organized within their subdirectories beneath the kernel/ directory. Take a few minutes to browse through those directories to get an idea of how things are arranged and what’s available. The filenames usually give you a good idea of what you’re looking at.

There are 33,350 available modules. It looks like someone’s been working hard over the years to provide us with the software to run our physical devices.

That’s how you find modules. Your next job is to figure out how to manually load an inactive module if, for some reason, it didn’t happen on its own.

Manually loading kernel modules

Before you can load a kernel module, logic dictates that you’ll have to confirm it exists. And before you can do that, you’ll need to know what it’s called. Getting that part sometimes requires equal parts magic and luck and some help from of the hard work of online documentation authors.

Linux recognized the interface (the Atheros AR9485) but listed it as unclaimed. Well, as they say, «When the going gets tough, the tough search the internet.» I ran a search for atheros ar9 linux module and, after sifting through pages and pages of five- and even 10-year-old results advising me to either write my own module or just give up, I finally discovered that (with Ubuntu 16.04, at least) a working module existed. Its name is ath9k.

Just one more step, load the module:

That’s it. No reboots. No fuss.

Here’s one more example to show you how to work with active modules that have become corrupted. There was a time when using my Logitech webcam with a particular piece of software would make the camera inaccessible to any other programs until the next system boot. Sometimes I needed to open the camera in a different application but didn’t have the time to shut down and start up again. (I run a lot of applications, and getting them all in place after booting takes some time.)

Because this module is presumably active, using lsmod to search for the word video should give me a hint about the name of the relevant module. In fact, it’s better than a hint: The only module described with the word video is uvcvideo (as you can see in the following):

There was probably something I could have controlled for that was causing the crash, and I guess I could have dug a bit deeper to see if I could fix things the right way. But you know how it is; sometimes you don’t care about the theory and just want your device working. So I used rmmod to kill the uvcvideo module and modprobe to start it up again all nice and fresh:

Again: no reboots. No stubborn blood stains.

Источник

Модули ядра Linux

Как вы знаете из статьи что такое ядро Linux, ядро является монолитным. Это значит, что весь исполняемый код сосредоточен в одном файле. Такая архитектура имеет некоторые недостатки, например, невозможность установки новых драйверов без пересборки ядра. Но разработчики нашли решение и этой проблеме, добавив систему модулей.

Модули ядра Linux

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

Модули ядра Linux собираются только под определенную версию ядра, есть способ запуска модуля независимо от версии ядра, если они совместимы с помощью dkms, но об этом мы поговорим позже.

Находятся все модули в папке /lib/modules/. Учитывая, что модули рассчитаны только для определенной версии ядра, то в этой папке создается отдельная подпапка, для каждой установленной в системе версии ядра. В этой папке находятся сами модули и дополнительные конфигурационные файлы, модули отсортированы по категориям, в зависимости от назначения например:

Snimok ekrana ot 2020 09 04 17 55 37

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

Работа с модулями ядра Linux выполняется, в основном, с помощью этих команд, но могут использовать и другие.

Все модули

Такая задача возникает нечасто, но если вы хотите посмотреть все установленные модули ядра Linux в системе, делается очень просто. Все модули расположены в папке /lib/modules, а поэтому очень просто вычислить их все одной командой, или даже просто зайти в папку файловым менеджером и посмотреть.

В Ubuntu команда будет выглядеть вот так:

Snimok ekrana ot 2020 09 04 17 57 22

Можно смастерить такую конструкцию с помощью find:

Можем искать только для текущего ядра:

Snimok ekrana ot 2020 09 04 17 57 37

Также, все модули записаны в конфигурационном файле /lib/modules/modules.aliases, поэтому мы можем просто посмотреть его содержимое:

Snimok ekrana ot 2020 09 04 17 58 05

Если хотим проверить установлен ли определенный модуль ядра Linux, отфильтруем вывод любой из команд с помощью grep:

Snimok ekrana ot 2020 09 04 17 59 01

Что загружено?

Все информация о загруженных модулях хранится в файле /proc/modules, мы можем ее вывести командой:

Snimok ekrana ot 2020 09 04 17 59 40

Но для этого дела есть более цивилизованные методы. Это утилита lsmod и modinfo. Чтобы посмотреть загруженные модули ядра linux выполните:

Snimok ekrana ot 2020 09 04 18 00 20

Удобно проверять загружен ли модуль с помощью grep:

sudo lsmod | grep vbox

А более подробную информацию о каждом модуле можно получить с помощью утилиты modinfo:

Snimok ekrana ot 2020 09 04 18 00 55

Запуск модулей ядра

Загрузить модуль ядра Linux можно с помощью команд modprobe или insmod. Например, загрузим модуль vboxdrv

sudo modprobe vboxdrv

Чтобы загрузить модуль ядра linux с помощью insmod необходимо передать адрес файла модуля:

sudo insmod /lib/modules/4.1.20-11-default/weak-updates/misc/vboxdrv.ko

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

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

Другая команда в этом случае выглядит немного проще:

sudo rmmod vboxdrv

Snimok ekrana ot 2020 09 04 18 02 51

Если вы получили ошибку во время выгрузки модуля, например: rmmod: ERROR: Module vboxdrv is in use by: vboxnetadp vboxnetflt, значит он еще используется другими модулями, и сначала нужно выгрузить их. В данном случае это vboxnetadp и vboxnetflt. Правильно отработавшая команда не должна ничего возвращать.

rmmod vboxnetadp vboxnetflt

Блокирование загрузки модулей

Иногда, во время загрузки системы для используемых нами устройств, загружаются не те модули ядра Linux, они либо не поддерживают нужную функциональность либо конфликтуют с другими модулями. Ярким примером можно назвать загрузку драйвера b43 вместо brcmsmac для беспроводных адаптеров Broadcom. Чтобы решить эту проблему вы можете добавлять модули в черный список. Для этого достаточно добавить одну строчку в файл /etc/modprobe.d/blacklist.conf:

sudo vi /etc/modprobe.d/blacklist.conf

Snimok ekrana ot 2020 09 04 18 04 56

Этот код добавит в черный список модуль b43.

Автозагрузка модулей

Кроме чёрного списка существует отдельный каталог, в котором можно настроить автоматическую загрузку модулей при старте системы. Это /etc/modules.load.d/. Этот каталог тоже содержит конфигурационные файлы с расширением *.conf, в которых перечислены все модули, которые надо загружать при старте системы. Для добавления своего модуля можно воспользоваться файлом /etc/modules.load.d/modules.conf. Например, добавим brcmsmac:

sudo vi /etc/modules.load.d/modules.conf

Snimok ekrana ot 2020 09 04 18 15 34

Установка модулей ядра Linux

Выводы

Скорее всего, вам редко придется возиться с этими модулями. Но работа с модулями ядра будет необходима, если ваш дистрибутив не поддерживает аппаратное обеспечение вашего устройства из коробки, а также когда вы работаете со сторонним программным обеспечением, таким как VirtualBox, Vmware и т д. Но очень полезно знать как обращаться с модулями, когда вам нужно добавить или удалить их. Даже если у вас нет необходимости в этом сейчас, вы можете протестировать, как все работает, чтобы быть вооруженным потом.

Источник

Оригинал: How to Load and Unload Kernel Modules in Linux

Автор: Aaron Kili

Дата публикации: 13 июня 2017 года

Перевод: А. Кривошей

Дата перевода: июль 2017 г.

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

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

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

Список всех загруженных модулей ядра в Linux

В Linux названия всех модулей заканчиваются расширением .ko, и обычно они загружаются автоматически при обнаружении оборудования во время загрузки системы. Однако системный администратор может управлять модулями с помощью специальных команд.

Для вывода списка всех загруженных модулей в Linux может использоваться команда lsmod (list modules), которая читает содержимое /proc/modules.

# lsmod
List Kernel Modules in Linux
Module                  Size  Used by
rfcomm                 69632  2
pci_stub               16384  1
vboxpci                24576  0
vboxnetadp             28672  0
vboxnetflt             28672  0
vboxdrv               454656  3 vboxnetadp,vboxnetflt,vboxpci
bnep                   20480  2
rtsx_usb_ms            20480  0
memstick               20480  1 rtsx_usb_ms
btusb                  45056  0
uvcvideo               90112  0
btrtl                  16384  1 btusb
btbcm                  16384  1 btusb
videobuf2_vmalloc      16384  1 uvcvideo
btintel                16384  1 btusb
videobuf2_memops       16384  1 videobuf2_vmalloc
bluetooth             520192  29 bnep,btbcm,btrtl,btusb,rfcomm,btintel
videobuf2_v4l2         28672  1 uvcvideo
videobuf2_core         36864  2 uvcvideo,videobuf2_v4l2
v4l2_common            16384  1 videobuf2_v4l2
videodev              176128  4 uvcvideo,v4l2_common,videobuf2_core,videobuf2_v4l2
intel_rapl             20480  0
x86_pkg_temp_thermal    16384  0
media                  24576  2 uvcvideo,videodev
....

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

Для загрузки модуля ядра мы можем использовать команду insmod (insert module). Здесь необходимо задать полный путь к модулю. Приведенная ниже команда загружает модуль speedstep-lib.ko.

# insmod /lib/modules/4.4.0-21-generic/kernel/drivers/cpufreq/speedstep-lib.ko 

Для выгрузки модуля ядра мы будем использовать команду rmmod (remove module). Следующая команда выгрузит модуль speedstep-lib.ko.

# rmmod /lib/modules/4.4.0-21-generic/kernel/drivers/cpufreq/speedstep-lib.ko 

Управление модулями ядра с помощью команды modprobe

modprobe — это интеллектуальная команда для чтения списка, загрузки и выгрузки модулей ядра. Она производит поиск всех модулей и соответствующих файлов в директории /lib/modules/$(uname -r), но не включает в поиск альтернативные конфигурационные файлы в директории /etc/modprobe.d. Таким образом, здесь вам не нужно вводить полный путь к модулю — в этом преимущество modprobe по сравнению с ранее описанными командами.

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

# modprobe speedstep-lib

Для выгрузки модуля используется флаг -r.

# modprobe -r speedstep-lib

Замечание: в modprobe выполняется автоматическое преобразование подчеркивания, поэтому при вводе названий модулей нет никакой разницы между _ и -.

Более подробно ознакомиться с опциями можно на man-странице modprobe.

# man modprobe

Если вам понравилась статья, поделитесь ею с друзьями:


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.

Suggested Read: How to Find Out What Version of Linux You Are Running

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.

# lsmod

List Kernel Modules in Linux

Module                  Size  Used by
rfcomm                 69632  2
pci_stub               16384  1
vboxpci                24576  0
vboxnetadp             28672  0
vboxnetflt             28672  0
vboxdrv               454656  3 vboxnetadp,vboxnetflt,vboxpci
bnep                   20480  2
rtsx_usb_ms            20480  0
memstick               20480  1 rtsx_usb_ms
btusb                  45056  0
uvcvideo               90112  0
btrtl                  16384  1 btusb
btbcm                  16384  1 btusb
videobuf2_vmalloc      16384  1 uvcvideo
btintel                16384  1 btusb
videobuf2_memops       16384  1 videobuf2_vmalloc
bluetooth             520192  29 bnep,btbcm,btrtl,btusb,rfcomm,btintel
videobuf2_v4l2         28672  1 uvcvideo
videobuf2_core         36864  2 uvcvideo,videobuf2_v4l2
v4l2_common            16384  1 videobuf2_v4l2
videodev              176128  4 uvcvideo,v4l2_common,videobuf2_core,videobuf2_v4l2
intel_rapl             20480  0
x86_pkg_temp_thermal    16384  0
media                  24576  2 uvcvideo,videodev
....

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.

# insmod /lib/modules/4.4.0-21-generic/kernel/drivers/cpufreq/speedstep-lib.ko 

To unload a kernel module, we use the rmmod (remove module) command. The following example will unload or remove the speedstep-lib.ko module.

# rmmod /lib/modules/4.4.0-21-generic/kernel/drivers/cpufreq/speedstep-lib.ko 

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.

# modprobe speedstep-lib

To remove a module, use the -r flag like this.

# modprobe -r speedstep-lib

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.

# man modprobe

Do not forget to check out:

  1. How to Change Kernel Runtime Parameters in a Persistent and Non-Persistent Way
  2. How to Install or Upgrade to Latest Kernel Version in CentOS 7
  3. How to Upgrade Kernel to Latest Version in Ubuntu

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.

Support Us

We are thankful for your never ending support.

Sometimes knowing which kernel modules recently unloaded can be as valuable as knowing which ones loaded. Windows keeps a record of drivers that unload for debugging purposes — in particular to help analyze failures in the attempt to call unloaded code. If you’ve ever used the lm command in Windbg, you’re probably somewhat familiar with seeing the list of unloaded modules. Today we’ll discuss a new Volatility plugin for Windows called unloadedmodules and walk though an example of how it can be useful in your memory forensic efforts.

Windbg’s Unloaded Module List

As previously described, near the bottom of the lm output in Windbg, you’ll see the unloaded modules:

kd> lm
start    end        module name
00b70000 00c07000   windbg     (deferred)             
68cf0000 6908b000   dbgeng     (deferred)             
69090000 690d8000   symsrv     (deferred)             
690e0000 69221000   dbghelp    (deferred)             
6f9c0000 6fa54000   MSFTEDIT   (deferred)      
[snip]

Unloaded modules:
94352000 943bc000   spsys.sys
942df000 94349000   spsys.sys
88bf1000 88bfe000   crashdmp.sys
88800000 8880a000   dump_storport.sys
82e00000 82e18000   dump_LSI_SAS.sys
8d41d000 8d42e000   dump_dumpfve.sys
69090000 690d8000   symsrv.dll

Kernel Internals

Before building this functionality into Volatility, we have to understand where the data is kept and what functions in the kernel are responsible for tracking it.

Kernel modules are typically represented as _LDR_DATA_TABLE_ENTRY structures. The list head is located in the _KDDEBUGGER_DATA64 block named PsLoadedModuleList — this is how the modules plugin enumerates modules. An example of the data structure is shown below (for an x86 system).

>>> dt("_LDR_DATA_TABLE_ENTRY")
'_LDR_DATA_TABLE_ENTRY' (80 bytes)
0x0   : InLoadOrderLinks               ['_LIST_ENTRY']
0x8   : InMemoryOrderLinks             ['_LIST_ENTRY']
0x10  : InInitializationOrderLinks     ['_LIST_ENTRY']
0x18  : DllBase                        ['pointer', ['void']]
0x1c  : EntryPoint                     ['pointer', ['void']]
0x20  : SizeOfImage                    ['unsigned long']
0x24  : FullDllName                    ['_UNICODE_STRING']
0x2c  : BaseDllName                    ['_UNICODE_STRING']
0x34  : Flags                          ['unsigned long']
0x38  : LoadCount                      ['unsigned short']
0x3a  : TlsIndex                       ['unsigned short']
0x3c  : HashLinks                      ['_LIST_ENTRY']
0x3c  : SectionPointer                 ['pointer', ['void']]
0x40  : CheckSum                       ['unsigned long']
0x44  : LoadedImports                  ['pointer', ['void']]
0x44  : TimeDateStamp                  ['UnixTimeStamp', {'is_utc': True}]
0x48  : EntryPointActivationContext    ['pointer', ['void']]
0x4c  : PatchInformation               ['pointer', ['void']]

Similarly, for unloaded modules, there are two members in the _KDDEBUGGER_DATA64 structure — MmUnloadedDrivers and MmLastUnloadedDriver. The MmUnloadedDrivers member is a pointer to an array of _UNLOADED_DRIVER structures and MmLastUnloadedDriver is an integer that specifies the size of the array. Here is a look at the structure for an x86 system:

>>> dt("_UNLOADED_DRIVER")
'_UNLOADED_DRIVER' (24 bytes)
0x0   : Name                           ['_UNICODE_STRING']
0x8   : StartAddress                   ['address']
0xc   : EndAddress                     ['address']
0x10  : CurrentTime                    ['WinTimeStamp', {}]

As you can see, the kernel not only tracks the unloaded driver’s name, but the address range it used to occupy and the precise time it unloaded. Posts by Alex Ionescu on the OSR list archives and later by  EP_XOFF on the KernelMode.info forums fills in a few other details. Specifically, these structures are created and filled in by code downstream from MmUnloadSystemImage(). This function internally calls _MiUnloadSystemImage() which leads to _MiRememberUnloadedDriver(). The code below shows the relevant decompiled source code:

void MiRememberUnloadedDriver(_UNICODE_STRING *SourceDriverName, int StartAddress, int a3)
{
  _UNLOADED_DRIVER *pArray[50]; 
  int dwLastDriver; 
  _UNLOADED_DRIVER *UnloadedDriver; 
  LSA_UNICODE_STRING *CopyDriverName; 

  if ( SourceDriverName->Length )
  {
    ExAcquireResourceExclusiveLite(&PsLoadedModuleResource, 1);
    if ( MmUnloadedDrivers )
    {
      dwLastDriver = MmLastUnloadedDriver;
      if ( MmLastUnloadedDriver < 50 )
        goto extend_list;
    }
    else
    {
      pArray = ExAllocatePoolWithTag(0, 50 * sizeof(_UNLOADED_DRIVER), 'TDmM');
      MmUnloadedDrivers = pArray;
      if ( !pArray )
      {
finished:
        ExReleaseResourceLite(&PsLoadedModuleResource);
        return;
      }
      memset(pArray, 0, 50 * sizeof(_UNLOADED_DRIVER));
    }
    dwLastDriver = 0;
    MmLastUnloadedDriver = 0;
extend_list:
    UnloadedDriver = &MmUnloadedDrivers[dwLastDriver];
    RtlFreeAnsiString(UnloadedDriver);
    CopyDriverName = ExAllocatePoolWithTag(NonPagedPool, SourceDriverName->Length, 'TDmM');
    UnloadedDriver->Name.Buffer = CopyDriverName;
    if ( CopyDriverName )
    {
      memcpy(CopyDriverName, SourceDriverName->Buffer, SourceDriverName->Length);
      UnloadedDriver->Name.Length = SourceDriverName->Length;
      UnloadedDriver->Name.MaximumLength = SourceDriverName->MaximumLength;
      *&UnloadedDriver->StartAddress = StartAddress;
      KeQuerySystemTime(&UnloadedDriver->CurrentTime);
      ++MiTotalUnloads;
      ++MmLastUnloadedDriver;
    }
    else
    {
      ++MiUnloadsSkipped;
      UnloadedDriver->Name.MaximumLength = 0;
      UnloadedDriver->Name.Length = 0;
    }
    goto finished;
  }
}

You can take away a few importact facts from browsing the source code:

  •  The system remembers a maximum of 50 drivers 
  •  Once the max is reached, everything is erased, and it starts over with 50 blank slots
  •  The pool tag associated with unloaded drivers is MmDT 

Its also important to note that MmUnloadSystemImage() is called from numerous other functions in the kernel, as shown by the list of cross-references below.

I didn’t do exhaustive code analysis to see if there’s a way to unload a driver without it being remembered, but at first glance it looks like most of the well known paths are accounted for.

Analyzing a Memory Dump

While scanning through some old malware-infected memory dumps, I noticed a strange artifact left by a Rustock variant. A module named xxx.sys apparently occupied the range 0x00f6f88000 — 0xf6fc2000 of kernel memory just before it unloaded at 2010-12-31 18:47:57.

$ python vol.py -f rustock-c.vmem unloadedmodules 
Volatile Systems Volatility Framework 2.3_beta
Name                 StartAddress EndAddress Time
-------------------- ------------ ---------- ----
Sfloppy.SYS          0x00f8b92000 0xf8b95000 2010-12-31 18:46:04 
Cdaudio.SYS          0x00f89d2000 0xf89d7000 2010-12-31 18:46:04 
splitter.sys         0x00f8c1c000 0xf8c1e000 2010-12-31 18:46:40 
swmidi.sys           0x00f871a000 0xf8728000 2010-12-31 18:46:41 
aec.sys              0x00f75d8000 0xf75fb000 2010-12-31 18:46:41 
DMusic.sys           0x00f78d0000 0xf78dd000 2010-12-31 18:46:41 
drmkaud.sys          0x00f8d9c000 0xf8d9d000 2010-12-31 18:46:41 
kmixer.sys           0x00f75ae000 0xf75d8000 2010-12-31 18:46:46 
xxx.sys              0x00f6f88000 0xf6fc2000 2010-12-31 18:47:57 

The most interesting aspect is that neither the modules plugin (walks the linked list of active modules) nor the modscan plugin (scans for _LDR_DATA_TABLE_ENTRY pools) has any record of xxx.sys:

$ python vol.py -f rustock-c.vmem modules | grep -i xxx
Volatile Systems Volatility Framework 2.3_beta
$ python vol.py -f rustock-c.vmem modscan | grep -i xxx
Volatile Systems Volatility Framework 2.3_beta

In this case, unloadedmodules was the only plugin to show evidence that a driver named xxx.sys was loaded. You can take this information and run with it. In what direction, you ask? Well, that depends — every analyst is different. Let your curiosity lead you in the right path.

My first step was to see if a file named xxx.sys in fact existed on the victim machine’s disk. For that I used @gleeda’s mftparser (which she’ll explain in more detail in a future MoVP post).

$ python vol.py -f rustock-c.vmem mftparser 
[snip]
MFT entry found at offset 0xc6d49f8
Attribute: In Use & File
Record Number: 20507
Link count: 1

$STANDARD_INFORMATION
Creation                       Modified                       MFT Altered                    Access Date                    Type
------------------------------ ------------------------------ ------------------------------ ------------------------------ ----
2010-12-31 18:46:44 UTC+0000 2010-12-31 18:46:44 UTC+0000   2010-12-31 18:46:44 UTC+0000   2010-12-31 18:46:44 UTC+0000   Archive

$FILE_NAME
Creation                       Modified                       MFT Altered                    Access Date                    Name/Path
------------------------------ ------------------------------ ------------------------------ ------------------------------ ---------
2010-12-31 18:46:44 UTC+0000 2010-12-31 18:46:44 UTC+0000   2010-12-31 18:46:44 UTC+0000   2010-12-31 18:46:44 UTC+0000   WINDOWSsystem32xxx.sys
[snip]

The output confirms that xxx.sys indeed existed and it was in the system32 directory. It was created at 2010-12-31 18:46:44, which is just over a minute before the driver was unloaded. So you can imagine the whole infection was pretty quick — from the driver being dropped to disk, to being loaded, to finishing its tasks, and then unloading.

The next direction I went in was to scan memory for references to xxx.sys. This may help identify the initial dropper component and/or explain how the driver got loaded in the first place. I used yarascan for this purpose.

$ python vol.py -f rustock-c.vmem yarascan -Y "xxx.sys" --wide 
Volatile Systems Volatility Framework 2.3_beta
Rule: r1
Owner: Process csrss.exe Pid 600
0x004e95b0  78 00 78 00 78 00 2e 00 73 00 79 00 73 00 31 00   x.x.x...s.y.s.1.
0x004e95c0  20 00 44 00 61 00 74 00 65 00 69 00 28 00 65 00   ..D.a.t.e.i.(.e.
0x004e95d0  6e 00 29 00 20 00 6b 00 6f 00 70 00 69 00 65 00   n.)...k.o.p.i.e.
0x004e95e0  72 00 74 00 2e 00 43 00 3a 00 5c 00 6d 00 61 00   r.t...C.:..m.a.
Rule: r1
Owner: Process csrss.exe Pid 600
0x004e99bc  78 00 78 00 78 00 2e 00 73 00 79 00 73 00 44 00   x.x.x...s.y.s.D.
0x004e99cc  72 00 69 00 76 00 65 00 72 00 20 00 49 00 6e 00   r.i.v.e.r...I.n.
0x004e99dc  73 00 74 00 61 00 6c 00 6c 00 65 00 72 00 20 00   s.t.a.l.l.e.r...
0x004e99ec  31 00 2e 00 30 00 20 00 42 00 79 00 20 00 57 00   1...0...B.y...W.
Rule: r1
Owner: Process csrss.exe Pid 600
0x0085777c  78 00 78 00 78 00 2e 00 73 00 79 00 73 00 00 00   x.x.x...s.y.s...
0x0085778c  78 00 2e 00 73 00 79 00 73 00 00 00 c3 01 61 06   x...s.y.s.....a.
0x0085779c  00 00 0b 00 b0 c1 64 bc 78 af 64 bc 74 61 74 75   ......d.x.d.tatu
0x008577ac  73 62 61 72 33 32 00 00 00 00 00 00 00 00 00 00   sbar32..........
Rule: r1
Owner: Process csrss.exe Pid 600
0x010233b0  78 00 78 00 78 00 2e 00 73 00 79 00 73 00 00 00   x.x.x...s.y.s...
0x010233c0  02 00 10 00 74 01 08 01 38 33 02 01 64 00 5c 00   ....t...83..d..
0x010233d0  04 00 02 00 76 01 08 01 18 33 02 01 6e 00 73 00   ....v....3..n.s.
0x010233e0  74 00 64 00 72 00 69 00 76 00 65 00 72 00 20 00   t.d.r.i.v.e.r...

In this output you can see fragments of strings, but undeniably ones that contain xxx.sys. The target process is csrss.exe. Could it be that malware injected code into csrss.exe? Although that’s a good guess, csrss.exe is also the host process, on XP/2003, for command shell history (commands entered via cmd.exe). That led me to scan with cmdscan:

$ python vol.py -f rustock-c.vmem cmdscan
Volatile Systems Volatility Framework 2.3_beta
**************************************************
CommandProcess: csrss.exe Pid: 600
CommandHistory: 0x4e4d68 Application: ?Nd.exe Flags: 
CommandCount: 13 LastAdded: 12 LastDisplayed: 12
FirstCommand: 0 CommandCountMax: 50
ProcessHandle: 0x0
Cmd #1 @ 0x1023318: ?d files
Cmd #2 @ 0x1023338: Nir??
Cmd #3 @ 0x4e1eb8: ??Nkit t
Cmd #5 @ 0x10233c8: ?d????nstdriver r??N?N start xxx
Cmd #6 @ 0x10233d8: ?nstdriver r??N?N start xxx
Cmd #7 @ 0x10235b0: ?d WINDOWS
Cmd #8 @ 0x10235d0: N?Nsystem32 ????nstdriver -Install xxx xxx.sys ??
Cmd #9 @ 0x10235f0: ?nstdriver -Install xxx xxx.sys ??
Cmd #10 @ 0x4ecef8: Negedit?
Cmd #11 @ 0x10233f8: N?N start xxx
Cmd #12 @ 0x1023ba0: ?d]

As you can see, the «xxx.sys» strings we found in csrss.exe really belonged to someone’s cmd.exe session. The attacker installed the driver via command-line using a utility called instdriver.exe. You may notice some unprintable characters in the output — that’s because the cmd.exe session is no longer valid. In fact, cmd.exe is not even running anymore according to the process list. Thus the data we’re analyzing is truly volatile — its no longer in use by the OS…just lingering around until its re-used or overwritten with other data.

Conclusion

If it wasn’t for the unloadedmodules plugin, we would have missed the malicious xxx.sys (or we would have found it much later than we did). Armed with the file name, the address(es) it occupied when loaded, and the unload time stamp, we had enough to begin an investigation and stay on the right track. 

cheat-enginekernelmoduleunloaderlpr-at-master-github image

Webcheat-engine/Cheat Engine/dbk32/Kernelmodule unloader/Kernelmoduleunloader.lpr Go to file Cannot retrieve contributors at this time executable file 491 lines (398 sloc) 15.2 KB Raw Blame …
From github.com
See details »


HOW TO LOAD AND UNLOAD KERNEL MODULES IN LINUX

how-to-load-and-unload-kernel-modules-in-linux image

WebJun 13, 2017 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. … How to Load and Unload …
From tecmint.com
See details »


CE 7.2 DBVM WON’T WORK DUE TO KERNEL MODULE · ISSUE …

ce-72-dbvm-wont-work-due-to-kernel-module-issue image

WebNov 12, 2020 I’ve tried to unload kernel module, uninstall, reboot, and reinstall but nothing works. Any help would be appreciated. Thanks! Specs: AMD Ryzen 5 5600x Windows 10 20H2 build 19042.572 Cheat Engine …
From github.com
See details »


UNLOAD KERNEL MODULE.LNK — VIRUS TRACKER®

WebSep 14, 2012 Path: C:ProgramDataMicrosoftWindowsStart MenuProgramsCheat Engine 6.1Kernel stuff Size: 1157 MD5: 46CB3B06F52971E456A158188E39C86E …
From virustracker.net
See details »


IS IT POSSIBLE TO UNLOAD A KERNEL MODULE WITHOUT INVOKING ITS …

WebJun 20, 2016 In theory, you can use a kind of a hack: find struct module corresponding to your module in the kernel memory and set both ‘init’ and ‘exit’ fields to NULL there. This …
From stackoverflow.com
See details »


HOW TO LOAD OR UNLOAD A LINUX KERNEL MODULE | OPENSOURCE.COM

WebMay 30, 2018 To help things along, you’ll want to understand a bit more about kernel modules and, in particular, how to find the actual module that will run your peripheral …
From opensource.com
See details »


HOW TO BYPASS KERNEL ANTICHEAT & DEVELOP DRIVERS — GUIDED …

WebAug 26, 2020 If you are dealing with a strong usermode anticheat, you can write a kernel mode driver to bypass it. Because you are in the kernel and the anticheat is not, you can …
From guidedhacking.com
See details »


HELP DELETING CHEAT ENGINE SO I DO NOT GET BANNED FROM R6

WebHelp deleting cheat engine so I do not get banned from R6 Title says it all, i think i uninstalled it completely and i ran the kernel unloader thing but not in administrator (if …
From reddit.com
See details »


I’M SCARED OF CHEAT ENGINE, PLZ HELP! : R/CHEATENGINE

WebYou have to unload the kernel module from registry if you want to use CE (Cheat Engine) and completely stop using it and remove traces after closing. Firstly close CE and then …
From reddit.com
See details »


LINUX — SAFE UNLOADING OF KERNEL MODULE — STACK OVERFLOW

WebJun 4, 2015 Solution is to: Find address of sys_call_table symbol, check if address is correct (checking for example that sys_call_table [__NR_close] points to address of …
From stackoverflow.com
See details »


CAN’T START THE GAME. «CLOSE CHEAT ENGINE». — STEAM COMMUNITY

WebJan 7, 2022 Unload your kernel module through kernelmoduleunloader.exe from cheat engine directory let’s rewrite this post of mine did some digging and this is probably …
From steamcommunity.com
See details »


HOW TO FORCEFULLY REMOVE A LOADABLE MODULE FROM KERNEL

WebJan 31, 2020 1. man rmmod: NAME rmmod — Simple program to remove a module from the Linux Kernel SYNOPSIS rmmod [-f] [-s] [-v] [modulename] DESCRIPTION rmmod is …
From unix.stackexchange.com
See details »


CHEAT ENGINE :: VIEW TOPIC — BUG IN CE KERNEL MODULE …

WebDec 28, 2011 Bug in CE kernel module unloader. I’ve tested this various times, and even once after a clean restart of the system. If CE traces an external API (I have tested it on …
From forum.cheatengine.org
See details »


CHEAT ENGINE :: VIEW TOPIC — USING THE KERNEL MODE API

WebAug 31, 2017 I’ve noticed before that if the CE exe has been modified, loading the driver will bluescreen your system (which makes sense because being able to use the DBK …
From cheatengine.org
See details »


DISABLE DBK64 AFTER LOADING? — FEARLESS CHEAT ENGINE

WebMar 10, 2017 by Eric » Fri Mar 10, 2017 12:17 am. run the kernelmodule unloader. it’s in start->programs->cheat engine 6.x->kernel stuff->kernelmodule unloader. if you’re on …
From fearlessrevolution.com
See details »


Related Search


Сейчас каждая операционная система имеет разделение на пользовательский режим и режим ядра, в этой статье разбирается ядро Linux и его модули.

Ядро операционной системы

Все процессы, работающие в системе, работают либо в режиме ядра, либо в пользовательском режиме. Процессы, работающие в режиме ядра получают больше прав, чем в пользовательском режиме. В режиме ядра работает само ядро и могут работать другие подсистемы.

Ядро является самой главной частью операционной системы, так как в него закладываются важнейшие функции:

  • связь с оборудованием, и предоставление ресурсов компьютера всем процессам в системе;
  • управление всеми процессами в системе;
  • в зависимости от типа ядра, у него могут быть и другие функции. Либо эти функции могут быть вынесены из ядра, но работать в режиме ядра. Или могут вообще быть вынесены из режима ядра в пользовательский режим.

Вообще, ядро можно рассматривать как главную программу, которая устанавливает правила, по которым работают остальные программы. Все в системе должно работать по правилам ядра. А ядро подчиняется правилам, которые диктует оборудование (архитектура процессора, оперативная память, системная плата).

Типы ядер

Существуют следующие типы ядер:

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

Особенность ядра Linux

В Linux все является файлом (файл, каталог, сокет, оборудование). Об этом я уже писал здесь.

Ядро написано на языке C и является переносимым. Оно реализует многозадачность и многопоточность, виртуальную память и многое другое. Также оно соответствует стандартам POSIX, это означает что программа написанная по стандартам POSIX будет работать на всех дистрибутивах Linux.

Официальный сайт ядра Linux: https://www.kernel.org/. Здесь можно найти исходники и списки изменений разных версий ядра.

Создатель и основной руководитель ядра Linux – Линус Торвальдс:

Линус Торвальдс

Линус Торвальдс

Файлы ядра

Файл ядра находится в каталоге /boot и начинается со слова vmlinuz, а дальше идет версия:

alex@deb-11:~$ ls -l /boot/vmlinuz*
-rw-r--r-- 1 root root 6962816 авг 13 16:25 /boot/vmlinuz-5.10.0-17-amd64
-rw-r--r-- 1 root root 6962016 сен  2 16:54 /boot/vmlinuz-5.10.0-18-amd64

alex@ubu-22:~$ ls -l /boot/vmlinuz*
lrwxrwxrwx 1 root root       25 ноя 16 07:00 /boot/vmlinuz -> vmlinuz-5.15.0-53-generic
-rw------- 1 root root 11543392 окт 13 07:49 /boot/vmlinuz-5.15.0-52-generic
-rw------- 1 root root 11548224 окт 17 18:41 /boot/vmlinuz-5.15.0-53-generic
lrwxrwxrwx 1 root root       25 ноя 16 07:00 /boot/vmlinuz.old -> vmlinuz-5.15.0-52-generic

По умолчанию Debian и Ubuntu хранят старые ядра после обновления, поэтому здесь находятся несколько файлов.

Посмотрим что лежит еще в каталоге /boot:

alex@deb-11:~$ ls -l /boot/
итого 70660
-rw-r--r-- 1 root root   236286 авг 13 16:25 config-5.10.0-17-amd64
-rw-r--r-- 1 root root   236286 сен  2 16:54 config-5.10.0-18-amd64
drwxr-xr-x 5 root root     4096 сен 13 12:23 grub
-rw-r--r-- 1 root root 28960621 сен  9 10:49 initrd.img-5.10.0-17-amd64
-rw-r--r-- 1 root root 28979132 сен 12 15:00 initrd.img-5.10.0-18-amd64
-rw-r--r-- 1 root root       83 авг 13 16:25 System.map-5.10.0-17-amd64
-rw-r--r-- 1 root root       83 сен  2 16:54 System.map-5.10.0-18-amd64
-rw-r--r-- 1 root root  6962816 авг 13 16:25 vmlinuz-5.10.0-17-amd64
-rw-r--r-- 1 root root  6962016 сен  2 16:54 vmlinuz-5.10.0-18-amd64

alex@ubu-22:~$ ls -l /boot/
total 244772
-rw-r--r-- 1 root root    261861 окт 13 07:40 config-5.15.0-52-generic
-rw-r--r-- 1 root root    261837 окт 17 18:36 config-5.15.0-53-generic
drwxr-xr-x 5 root root      4096 ноя 16 07:00 grub
lrwxrwxrwx 1 root root        28 ноя 16 07:00 initrd.img -> initrd.img-5.15.0-53-generic
-rw-r--r-- 1 root root 107247090 ноя  9 06:19 initrd.img-5.15.0-52-generic
-rw-r--r-- 1 root root 107269841 ноя 16 07:00 initrd.img-5.15.0-53-generic
lrwxrwxrwx 1 root root        28 ноя 16 07:00 initrd.img.old -> initrd.img-5.15.0-52-generic
-rw------- 1 root root   6249017 окт 13 07:40 System.map-5.15.0-52-generic
-rw------- 1 root root   6250186 окт 17 18:36 System.map-5.15.0-53-generic
lrwxrwxrwx 1 root root        25 ноя 16 07:00 vmlinuz -> vmlinuz-5.15.0-53-generic
-rw------- 1 root root  11543392 окт 13 07:49 vmlinuz-5.15.0-52-generic
-rw------- 1 root root  11548224 окт 17 18:41 vmlinuz-5.15.0-53-generic
lrwxrwxrwx 1 root root        25 ноя 16 07:00 vmlinuz.old -> vmlinuz-5.15.0-52-generic
  • vmlinuz – ядро;
  • initrd.img – образ стартовой файловой системы, которая необходима чтобы запустить ядро;
  • System.map – файл для управления памятью;
  • config – файл параметров с которыми собрано текущее ядро;
  • Каталог grub – файлы загрузчика grub, про него я рассказывал здесь.

Модули ядра

Так как ядро в Linux – монолитное. То все драйвера должны быть включены в ядро. Вначале так и было, но когда возможного оборудования стало слишком много, и всё многообразие драйверов не могли поместить в одно ядро, придумали динамически подгружаемые модули ядра.

Сегодня ядро является минимальным, и поддержка устройства осуществляется с помощью динамически подгружаемых модулей ядра.

Вот размер ядра:

alex@deb-11:~$ du -h /boot/vmlinuz-5.10.0-18-amd64
6,7M    /boot/vmlinuz-5.10.0-18-amd64

alex@ubu-22:~$ du -h /boot/vmlinuz-5.15.0-53-generic
12M     /boot/vmlinuz-5.15.0-53-generic

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

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

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

Команда lsmod берет информацию из /proc/modules чтобы вывести список уже загруженных модулей:

$ lsmod | head -n 20
Module                        Size  Used by
binfmt_misc                   24576  1
snd_hda_codec_generic         98304  2
ledtrig_audio                 16384  1 snd_hda_codec_generic
snd_hda_intel                 57344  0
snd_intel_dspcfg              28672  1 snd_hda_intel
soundwire_intel               45056  1 snd_intel_dspcfg
soundwire_generic_allocation  16384  1 soundwire_intel
snd_soc_core                  319488  1 soundwire_intel
snd_compress                  32768  1 snd_soc_core
soundwire_cadence             36864  1 soundwire_intel
snd_hda_codec                176128  2 snd_hda_codec_generic,snd_hda_intel
snd_hda_core                 110592  3 snd_hda_codec_generic,snd_hda_intel,snd_hda_codec
qxl                           77824  0
snd_hwdep                     16384  1 snd_hda_codec
drm_ttm_helper                16384  1 qxl
soundwire_bus                 94208  3 soundwire_intel,soundwire_generic_allocation,soundwire_cadence
joydev                        28672  0
ttm                          114688  2 qxl,drm_ttm_helper
snd_pcm                      143360  6 snd_hda_intel,snd_hda_codec,soundwire_intel,snd_compress,snd_soc_core,snd_hda_core

А если вам нужно получить список всех модулей ядра, а не только загруженных, то можете воспользоваться следующей командой:

$ find /lib/modules/$(uname -r) -name *.ko

Вывод предыдущей команды будет очень большим, например в Ubuntu сейчас более 6040 подгружаемых модулей.

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

Команда modinfo нужна для получения информации о модуле. Вы можете указать полное имя файла или имя модуля.

Для выполнения этой команды в Ubuntu не обязательно использовать sudo, а в Debian нужно:

alex@ubu-22:~$ modinfo vfat
name:           vfat
filename:       (builtin)
author:         Gordon Chaffee
description:    VFAT filesystem support
license:        GPL
file:           fs/fat/vfat
alias:          fs-vfat

alex@deb-11:~$ sudo modinfo vfat
filename:       /lib/modules/5.10.0-18-amd64/kernel/fs/fat/vfat.ko
author:         Gordon Chaffee
description:    VFAT filesystem support
license:        GPL
alias:          fs-vfat
depends:        fat
retpoline:      Y
intree:         Y
name:           vfat
vermagic:       5.10.0-18-amd64 SMP mod_unload modversions
sig_id:         PKCS#7
signer:         Debian Secure Boot CA
sig_key:        32:A0:28:7F:84:1A:03:6F:A3:93:C1:E0:65:C4:3A:E6:B2:42:26:43
sig_hashalgo:   sha256
signature:      A0:1A:81:0B:41:A4:6C:82:1A:2F:85:91:BD:E3:51:69:CA:95:4E:EF:
                BB:29:9E:D5:DF:79:26:EC:85:2E:B7:2E:53:E7:4F:16:F5:00:C3:F2:
                C2:F0:85:51:8F:C3:2A:51:EF:0E:85:32:6F:7D:8D:59:6D:37:5F:7B:
                76:71:8A:C4:D3:96:39:3E:F7:EE:E5:59:ED:79:65:65:51:4C:3F:F4:
                F6:05:C7:61:D6:0D:91:B3:71:19:CA:81:B8:D6:90:CA:21:44:6A:FC:
                B0:B2:AE:11:7D:D9:EA:E5:E9:93:6B:A0:30:F2:20:95:97:84:E4:81:
                CA:26:09:3E:78:1A:B6:BB:21:7B:DC:B2:18:C6:2B:C9:1B:8F:60:7A:
                D3:8B:CB:21:15:C1:E5:88:75:06:07:DC:DC:B0:E9:5F:DF:C5:6F:20:
                DE:39:EA:7D:13:83:D1:92:7A:3A:0C:34:27:F2:50:43:5B:EA:68:E8:
                25:B2:A7:81:49:38:E7:8A:1C:25:74:B0:00:DC:CB:5A:52:D7:07:E0:
                32:12:D6:ED:0B:CC:90:49:00:5B:DB:7C:5B:5C:9F:44:C1:DF:51:EC:
                19:A7:96:2F:5A:7C:BF:E5:C9:9E:AB:08:2D:05:83:18:B8:F0:87:7E:
                03:C3:53:64:21:0D:35:54:B4:04:EF:39:32:71:0E:19

Выше вы можете заметить разницу. В Ubuntu вместо имени файла написано – (builtin). А в Debian/lib/modules/5.10.0-18-amd64/kernel/fs/fat/vfat.ko. Если вы вместо имени видите (builtin), значит этот модуль встроен в ядро.

Утилита modinfo показывает следующую информацию:

  • filename – полный путь к файлу (если это не встроенный в ядро модуль);
  • author – информация о создателе;
  • description – описание;
  • license – лицензия;
  • alias – псевдоним (их может быть несколько);
  • depends – зависимость, то есть без этого модуля, он не загрузится. Зависимостей может быть несколько. (не бывает для встроенных в ядро модулей);
  • retpoline – указывает, что модуль построен с поддержкой защиты от Spectre;
  • intree – все модули ядра начинают разработку как out-of-tree. Как только модуль принимается для включения в ядро, он становится модулем in-tree. Модули без этого флага (установленного в N) могут испортить ядро;
  • name – имя модуля;
  • vermagic – это строка используется для проверки, был ли модуль ядра скомпилирован для конкретной версии ядра или нет (не бывает для встроенных в ядро модулей);
  • parm – если у модуля есть параметры, то они записываются сюда.

Вы можете использовать опцию -F для ограничения вывода по конкретному полю:

alex@ubu-22:~$ modinfo -F description vfat
VFAT filesystem support

Если вы не укажете полное имя файла, modinfo ищет модуль в /lib/modules/<версия_ядра>/kernel

Версию вашего ядра можно получить командой uname -r:

alex@deb-11:~$ uname -r
5.10.0-18-amd64

alex@ubu-22:~$ uname -r
5.15.0-52-generic

Для поиска модулей ядра можно воспользоваться такой командой:

alex@deb-11:~$ ls /lib/modules/`uname -r`/kernel
arch  block  crypto  drivers  fs  lib  mm  net  sound  virt

alex@ubu-22:~$ ls /lib/modules/`uname -r`/kernel
arch   crypto   fs      lib  net      sound   v4l2loopback
block  drivers  kernel  mm   samples  ubuntu  zfs

Вы можете найти некоторые простые текстовые файлы в каталоге:

$ ls /lib/modules/`uname -r`
build          modules.alias.bin          modules.builtin.modinfo  modules.order        vdso
initrd         modules.builtin            modules.dep              modules.softdep
kernel         modules.builtin.alias.bin  modules.dep.bin          modules.symbols
modules.alias  modules.builtin.bin        modules.devname          modules.symbols.bin
  • modules.dep – перечислены зависимости;
  • modules.alias – перечислены псевдонимы;
  • modules.builtin – содержит модули, которые встроены в ядро. К ним относятся драйверы необходимые для основных функциональных возможностей в большинстве систем.

Если вы заходите получить имя файла модуля с помощью modinfo а модуль окажется встроенным, то попробуйте поискать информацию в файле modules.builtin:

alex@deb-11:~$ sudo modinfo processor -F filename
(builtin)

alex@deb-11:~$ grep processor /lib/modules/`uname -r`/modules.builtin
kernel/drivers/acpi/processor.ko

alex@ubu-22:~$ modinfo processor -F filename
(builtin)
(builtin)

alex@ubu-22:~$ grep processor /lib/modules/`uname -r`/modules.builtin
kernel/drivers/acpi/processor.ko
kernel/drivers/xen/xen-acpi-processor.ko

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

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

Раньше использовались команды: insmod – для загрузки модуля, и rmmod – для извлечения модуля.

Команда modprobe заменила insmod и rmmod, при этом modprobe следит за зависимостями и выгружает или загружает модули с их учётом.

Я буду использовать модуль uhci_hcd для этого примера. Используйте modinfo, чтобы увидеть зависимости этого модуля:

alex@ubu-22:~$ modinfo uhci_hcd
name:           uhci_hcd
filename:       (builtin)
license:        GPL
file:           drivers/usb/host/uhci-hcd
description:    USB Universal Host Controller Interface driver
author:         Linus 'Frodo Rabbit' Torvalds, Johannes Erdfelt, Randy Dunlap, Georg Acher, Deti Fliegl, Thomas Sailer, Roman Weissgaerber, Alan Stern
softdep:        pre: ehci_pci
parm:           ignore_oc:ignore hardware overcurrent indications (bool)
parm:           debug:Debug level (int)


alex@deb-11:~$ sudo modinfo uhci_hcd
filename:       /lib/modules/5.10.0-18-amd64/kernel/drivers/usb/host/uhci-hcd.ko
license:        GPL
description:    USB Universal Host Controller Interface driver
author:         Linus 'Frodo Rabbit' Torvalds, Johannes Erdfelt, Randy Dunlap, Georg Acher, Deti Fliegl, Thomas Sailer, Roman Weissgaerber, Alan Stern
softdep:        pre: ehci_pci
alias:          pci:v*d*sv*sd*bc0Csc03i00*
depends:        usbcore,usb-common
retpoline:      Y
intree:         Y
name:           uhci_hcd
vermagic:       5.10.0-18-amd64 SMP mod_unload modversions
sig_id:         PKCS#7
signer:         Debian Secure Boot CA
sig_key:        32:A0:28:7F:84:1A:03:6F:A3:93:C1:E0:65:C4:3A:E6:B2:42:26:43
sig_hashalgo:   sha256
signature:      0A:D2:BF:AF:B5:35:14:B4:7D:BC:73:6F:06:66:9A:F1:5D:94:67:99:
                CA:72:89:45:7C:3E:95:B1:00:19:F3:59:D6:D2:74:82:E8:AA:85:F8:
                60:A0:AB:CB:98:E1:A5:E4:7F:A6:3D:48:29:9B:4C:01:33:61:61:C0:
                A3:E5:80:B3:E6:3A:78:B0:F1:DB:D0:AF:A6:CA:41:EA:B2:59:EB:E6:
                4B:0C:80:69:3E:06:7A:BB:E9:DD:16:C6:B4:D2:78:10:68:D2:F0:0F:
                93:62:18:80:71:D3:42:3D:81:D6:3E:48:B5:85:FE:FB:77:C0:03:68:
                23:50:9B:99:F1:F8:8C:AF:9F:93:2D:28:16:AF:36:75:1E:72:54:AF:
                A6:3A:DD:43:32:6C:4C:39:1C:66:B9:77:B2:E2:9C:76:45:D7:0D:85:
                AE:38:9B:4A:69:00:B1:AA:92:5A:85:86:89:04:82:F7:DA:40:D4:2E:
                9D:D6:B9:AE:5C:44:01:6C:B6:95:8E:3C:02:06:18:D0:E1:D2:6A:18:
                E4:39:FF:0C:1D:62:C5:2D:16:C6:51:2F:24:B8:3E:DB:3A:8D:11:C6:
                48:F9:AC:A7:C2:83:95:88:D3:28:EC:C1:E9:6A:B0:B1:54:5E:76:E6:
                A6:00:1A:79:44:66:61:BB:9B:8C:7B:B4:B3:F6:EA:8C
parm:           ignore_oc:ignore hardware overcurrent indications (bool)
parm:           debug:Debug level (int)

Как видите, в Ubuntu этот модуль встроен в ядро. А в Debian это подгружаемый модуль ядра. Поэтому дальнейшие действия я буду выполнять в Debian.

Найдём зависимости для uhci_hcd:

$ sudo modinfo -F depends uhci_hcd
usbcore,usb-common

Как вы видите, этот модуль имеет зависимость от usbcore. А он зависит от usb-common:

$ sudo modinfo -F depends usbcore
usb-common

На этом зависимости кончаются:

$ sudo modinfo -F depends usb-common

Если вы хотите, вручную загрузить или выгрузить драйвер, используйте modprobe с опцией:

  • -i, чтобы загрузить модуль;
  • -r, чтобы выгрузить модуль;
  • -n чтобы показать, что будет сделано, не делая это;
  • а опция -v покажет подробную информацию.

Например:

$ sudo modprobe -nrv uhci_hcd
rmmod uhci_hcd
rmmod ehci_hcd

То есть, при выгрузке uhci_hcd выгрузится еще и ehci_hcd. Мы можем выполнить эти две команды (rmmod uhci_hcdrmmod ehci_hcd), или выполнить одну modprobe.

Давайте выгрузим этот модуль:

$ sudo modprobe -rv uhci_hcd
rmmod uhci_hcd
rmmod ehci_hcd
rmmod usbcore
rmmod usb_common

И загрузим модули обратно:

$ sudo modprobe -iv uhci_hcd
insmod /lib/modules/5.10.0-18-amd64/kernel/drivers/usb/common/usb-common.ko
insmod /lib/modules/5.10.0-18-amd64/kernel/drivers/usb/core/usbcore.ko
insmod /lib/modules/5.10.0-18-amd64/kernel/drivers/usb/host/uhci-hcd.ko

$ sudo modprobe -iv ehci-hcd
insmod /lib/modules/5.10.0-18-amd64/kernel/drivers/usb/host/ehci-hcd.ko

Вы не можете выгрузить модуль если он используется или если этот модуль встроен в ядро. Именно поэтому я не стал приводить пример на Ubuntu:

$ sudo modprobe -rv uhci_hcd
modprobe: FATAL: Module uhci_hcd is builtin

Параметры модулей

Некоторые модули имеют параметры. Например, драйвер устройства должен знать, какие IRQ или порт I/O использовать. Следующий пример показывает информацию о модуле usbhid, который имеет несколько таких параметров:

$ modinfo -F parm usbhid
mousepoll:Polling interval of mice (uint)
jspoll:Polling interval of joysticks (uint)
kbpoll:Polling interval of keyboards (uint)
ignoreled:Autosuspend with active leds (uint)
quirks:Add/modify USB HID quirks by specifying  quirks=vendorID:productID:quirks where vendorID, productID, and quirks are all in 0x-prefixed hex (array of charp)

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

Автозагрузка модулей ядра

Бывает ситуация, когда модуль ядра не загружается при подключении устройства. И его нужно загрузить вручную, например:

$ sudo modprobe 8021q

Проверить, загружен модуль или нет можно так:

$ sudo lsmod | grep 8021q
8021q                  40960  0
garp                   16384  1 8021q
mrp                    20480  1 8021q

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

$ sudo nano /etc/modules-load.d/8021q.conf
8021q

После этого можно перезагрузиться и проверить, что модуль загружен автоматически.

Также в Debian и Ubuntu для автозагрузки модуля ядра, можно добавить имя модуля в файл /etc/modules.

Итог

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

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

Узнали как получить информацию о модуле ядра используя команду modinfo, а также как получить список модулей в системе используя lsmod.


Сводка

Ядро Linux и модули ядра

Имя статьи

Ядро Linux и модули ядра

Описание

Сейчас каждая операционная система имеет разделение на пользовательский режим и режим ядра, в этой статье разбирается ядро Linux и его модули

In this tutorial, you will learn how to load and unload kernel modules in Linux. When you install a Linux-like operating system, the kernel automatically installs the majority of device driver modules. It also allows you to install additional device drivers as modules using the commands modprobe and insmod once the installation is complete.

Normally, kernel modules are loaded automatically, but you may need to manually install new modules on occasion.

From time to time, you may want to unload/uninstall some modules are well.

The two major commands that can be used to load and unload kernel modules in Linux include:

  • modprobe
  • insmod

While the two commands are used to achieve the same thing, most users will want to use modprobe instead, which is more clever and can handle module dependencies.

Modprobe can also be used to unload/remove loaded kernel modules.

How to load kernel modules in Linux

Load Kernel Modules using INSMOD command

The insmod (insert module) command can be used to load a kernel module. The whole path of the module must be specified here.

Kernel module files usually have .ko extensions, for example you can use the command bellow to insert bluetooth.ko module.

insmod /lib/modules/4.4.0-21-generic/kernel/drivers/cpufreq/bluetooth.ko

Load Kernel Modules using MODPROBE command

Using the modprobe command and the module name, you can add the module to the Linux kernel.

sudo modprobe bluetooth

List Loaded Kernel Modules

Using the lsmod command, you can see what kernel modules are currently loaded.

sudo lsmod | grep bluetooth

Except for the additional configuration file in /etc/modprobe.d/, Linux maintains a kernel module directory and configuration files under /lib/modules/'uname -r' /kernel/drivers/.

To list kernel drivers run the following command

ls /lib/modules/'uname -r'/kernel/drivers/

For my case when I run uname -r I get the following sample output;

5.11.0-38-generic

Now I can run the full command with value of the command uname -r used;

ls /lib/modules/5.11.0-38-generic/kernel/drivers/
accessibility  crypto    hwmon       md        parport    scsi         vdpa
acpi           dax       hwtracing   media     pci        siox         vfio
android        dca       i2c         memstick  pcmcia     slimbus      vhost
ata            dma       i3c         message   phy        soc          video
atm            edac      iio         mfd       pinctrl    soundwire    virt
auxdisplay     extcon    infiniband  misc      platform   spi          virtio
base           firewire  input       mmc       power      spmi         visorbus
bcma           firmware  iommu       most      powercap   ssb          vme
block          fpga      ipack       mtd       pps        staging      w1
bluetooth      gnss      irqchip     mux       ptp        target       watchdog
bus            gpio      isdn        net       pwm        tee          xen
char           gpu       leds        nfc       rapidio    thermal
clk            greybus   lightnvm    ntb       regulator  thunderbolt
counter        hid       macintosh   nvdimm    reset      tty
cpufreq        hsi       mailbox     nvme      rpmsg      uio
cpuidle        hv        mcb         nvmem     rtc        usb

You may encounter problems loading modules at times, or modules that are not loaded properly.

You can aggressively install or load modules to avoid these issues by using the '–force' option (-f) in the modprobe command.

modprobe -f floppy

If you continue to have issues or difficulties while loading the modules, you will need to debug this time.

You can determine the exact error or issue before or after installing the modules by activating debugging. To put it another way, debugging is the same as a dry-run of loading modules.

This form of debugging is enabled by the '-n' option in the modprobe command. This option forces the modprobe command to complete all module loading steps except the last.

modprobe -vn module_name

The ‘--show-depends‘ option in the modprobe command can also be used to display the module’s dependencies.

An example is shown below.

modprobe --show-depends e1000
insmod /lib/modules/5.11.0-38-generic/kernel/drivers/net/ethernet/intel/e1000/e1000.ko

How to unload kernel modules in Linux

You can unload loaded kernel modules in Linux using the commands:

  • rmmod
  • modprobe

Just like insmod does not a module with its dependencies, rmmod does not remove a module with its dependencies. You may want to use modprobe with -r option instead.

Unload kernel modules using rmmod command

The rmmod (remove module) command is used to unload a kernel module. The bluetooth.ko module will be unloaded or removed using the following example.

rmmod /lib/modules/4.4.0-21-generic/kernel/drivers/cpufreq/bluetooth.ko

Unload kernel modules using modprobe command

Use the modprobe command with the -r option and the module name to remove a module. e.g.

sudo modprobe -r bluetooth

To remove a kernel module, use the -r option in the modprobe command. Assume we wish to get rid of the floppy module.

modprobe -r floppy

After removing the floppy module from the kernel, type

lsmod | grep floppy

You should not be able to see anything. If you want to re-insert this module, refer to loading kernel module section above.

That concludes our guide on how to load and unload kernel modules in Linux.

Further Reading

man modprobe

man insmod

man rmmod

Other Tutorials

How to set and unset environment variables in Linux

How to list hardware information in Linux

How to Use uname Command on Linux

Понравилась статья? Поделить с друзьями:
  • Unknown modules in qt multimedia windows
  • Unknown lan id ewa windows 10
  • Unknown hard error что делать windows 10 при включении
  • Unknown hard error при установке windows
  • Unknown hard error при запуске windows 10