Linux kernel build and install

Kernel/Traditional compilation

This article is an introduction to building custom kernels from kernel.org sources. This method of compiling kernels is the traditional method common to all distributions. It can be, depending on your background, more complicated than using the Kernels/Arch Build System. Consider the Arch Build System tools are developed and maintained to make repeatable compilation tasks efficient and safe.

Contents

Preparation

It is not necessary (or recommended) to use the root account or root privileges (i.e. via Sudo) for kernel preparation.

Install the core packages

Install the base-devel package group, which contains necessary packages such as make and gcc . It is also recommended to install the following packages, as listed in the default Arch kernel PKGBUILD: xmlto , kmod , inetutils , bc , libelf , git , cpio , perl , tar , xz .

Create a kernel compilation directory

It is recommended to create a separate build directory for your kernel(s). In this example, the directory kernelbuild will be created in the home directory:

Download the kernel source

Download the kernel source from https://www.kernel.org. This should be the tarball ( tar.xz ) file for your chosen kernel.

It can be downloaded by simply right-clicking the tar.xz link in your browser and selecting Save Link As. , or any other number of ways via alternative graphical or command-line tools that utilise HTTP, TFTP, Rsync, or Git.

In the following command-line example, wget has been installed and is used inside the

/kernelbuild directory to obtain kernel 4.8.6:

You should also verify the correctness of the download before trusting it. First grab the signature, then use that to grab the fingerprint of the signing key, then use the fingerprint to obtain the actual signing key:

Note the signature was generated for the tar archive (i.e. extension .tar ), not the compressed .tar.xz file that you have downloaded. You need to decompress the latter without untarring it. Verify that you have xz installed, then you can proceed like so:

Do not proceed if this does not result in output that includes the string «Good signature».

If wget was not used inside the build directory, it will be necessary to move the tarball into it, e.g.

Unpack the kernel source

Within the build directory, unpack the kernel tarball:

To finalise the preparation, ensure that the kernel tree is absolutely clean; do not rely on the source tree being clean after unpacking. To do so, first change into the new kernel source directory created, and then run the make mrproper command:

Kernel configuration

This is the most crucial step in customizing the default kernel to reflect your computer’s precise specifications. Kernel configuration is set in its .config file, which includes the use of Kernel modules. By setting the options in .config properly, your kernel and computer will function most efficiently.

You can do a mixture of two things:

  • Use the default Arch settings from an official kernel (recommended)
  • Manually configure the kernel options (optional, advanced and not recommended)

Default Arch configuration

This method will create a .config file for the custom kernel using the default Arch kernel settings. If a stock Arch kernel is running, you can use the following command inside the custom kernel source directory:

Читайте также:  Как восстановить linux livecd

Otherwise, the default configuration can be found online in the official Arch Linux kernel package.

Advanced configuration

There are several tools available to fine-tune the kernel configuration, which provide an alternative to otherwise spending hours manually configuring each and every one of the options available during compilation.

Those tools are:

  • make menuconfig : Command-line ncurses interface superseded by nconfig
  • make nconfig : Newer ncurses interface for the command-line
  • make xconfig : User-friendly graphical interface that requires packagekit-qt5 to be installed as a dependency. This is the recommended method — especially for less experienced users — as it is easier to navigate, and information about each option is also displayed.
  • make gconfig : Graphical configuration similar to xconfig but using gtk. This requires gtk2 , glib2 and libgladeAUR .

The chosen method should be run inside the kernel source directory, and all will either create a new .config file, or overwrite an existing one where present. All optional configurations will be automatically enabled, although any newer configuration options (i.e. with an older kernel .config ) may not be automatically selected.

Once the changes have been made save the .config file. It is a good idea to make a backup copy outside the source directory. You may need to do this multiple times before you get all the options right.

If unsure, only change a few options between compilations. If you cannot boot your newly built kernel, see the list of necessary config items here.

Running lspci -k # from liveCD lists names of kernel modules in use. Most importantly, you must maintain cgroups support. This is necessary for systemd. For more detailed information, see Gentoo:Kernel/Gentoo Kernel Configuration Guide and Gentoo:Intel#Kernel or Gentoo:Ryzen#Kernel for Intel or AMD Ryzen processors.

Compilation

Compilation time will vary from as little as fifteen minutes to over an hour, depending on your kernel configuration and processor capability. Once the .config file has been set for the custom kernel, within the source directory run the following command to compile:

Installation

Install the modules

Once the kernel has been compiled, the modules for it must follow. First build the modules:

Then install the modules. As root or with root privileges, run the following command to do so:

This will copy the compiled modules into /lib/modules/ — . For example, for kernel version 4.8 installed above, they would be copied to /lib/modules/4.8.6-ARCH . This keeps the modules for individual kernels used separated.

Copy the kernel to /boot directory

The kernel compilation process will generate a compressed bzImage (big zImage) of that kernel, which must be copied to the /boot directory and renamed in the process. Provided the name is prefixed with vmlinuz- , you may name the kernel as you wish. In the examples below, the installed and compiled 4.8 kernel has been copied over and renamed to vmlinuz-linux48 :

Make initial RAM disk

If you do not know what making an initial RAM disk is, see Initramfs on Wikipedia and mkinitcpio.

Automated preset method

An existing mkinitcpio preset can be copied and modified so that the custom kernel initramfs images can be generated in the same way as for an official kernel. This is useful where intending to recompile the kernel (e.g. where updated). In the example below, the preset file for the stock Arch kernel will be copied and modified for kernel 4.8, installed above.

First, copy the existing preset file, renaming it to match the name of the custom kernel specified as a suffix to /boot/vmlinuz- when copying the bzImage (in this case, linux48 ):

Second, edit the file and amend for the custom kernel. Note (again) that the ALL_kver= parameter also matches the name of the custom kernel specified when copying the bzImage :

Читайте также:  Появилось окно безопасность windows

Finally, generate the initramfs images for the custom kernel in the same way as for an official kernel:

Manual method

Rather than use a preset file, mkinitcpio can also be used to generate an initramfs file manually. The syntax of the command is:

  • -k ( —kernel ): Specifies the modules to use when generating the initramfs image. The name will be the same as the name of the custom kernel source directory (and the modules directory for it, located in /usr/lib/modules/ ).
  • -g ( —generate ): Specifies the name of the initramfs file to generate in the /boot directory. Again, using the naming convention mentioned above is recommended.

For example, the command for the 4.8 custom kernel installed above would be:

Copy System.map

The System.map file is not required for booting Linux. It is a type of «phone directory» list of functions in a particular build of a kernel. The System.map contains a list of kernel symbols (i.e function names, variable names etc) and their corresponding addresses. This «symbol-name to address mapping» is used by:

  • Some processes like klogd, ksymoops, etc.
  • By OOPS handler when information has to be dumped to the screen during a kernel crash (i.e info like in which function it has crashed).

If your /boot is on a filesystem which supports symlinks (i.e., not FAT32), copy System.map to /boot , appending your kernel’s name to the destination file. Then create a symlink from /boot/System.map to point to /boot/System.map- :

After completing all steps above, you should have the following 3 files and 1 soft symlink in your /boot directory along with any other previously existing files:

  • Kernel: vmlinuz-
  • Initramfs: Initramfs- .img
  • System Map: System.map-
  • System Map kernel symlink

Bootloader configuration

Add an entry for your new kernel in your bootloader’s configuration file. See Arch boot process#Feature comparison for possible boot loaders, their wiki articles and other information.

Источник

Как собрать ядро Linux с нуля

Обновл. 18 Июн 2021 |

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

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

Сборка ядра Linux

Процесс сборки ядра Linux состоит из семи простых шагов. Однако для выполнения этой процедуры вам потребуется значительное количество времени (зависящее от характеристик вашего компьютера).

Примечание: Для сборки ядра Linux я выделил следующие ресурсы:

виртуальная машина — VMware Workstation 15 Pro (15.5.6);

дистрибутив — Debian Linux (ветка Testing);

ресурсы — 2 ядра CPU (Ryzen 5 1600 AF), 2GB RAM, HDD;

время компиляции — 3+ часа.

После этого я попробовал собрать ядро еще раз, перенеся образ виртуальной машины на NVMe SSD A-Data XPG SX8200 Pro (1TB), а также увеличив количество доступных для виртуальной машины ядер CPU до 6, а RAM — до 4GB. В таком варианте время компиляции составило около 1.5 часов.

Шаг №1: Загрузка исходного кода

Откройте сайт kernel.org и найдите архив с исходными кодами самой свежей версии ядра (Latest Release).

Примечание: Не пугайтесь, если версия ядра на сайте kernel.org не совпадает с той, которую я использовал на данном уроке. Все рассмотренные шаги/команды работоспособны, просто вам придется заменить цифры в версии ядра на свои.

Затем откройте терминал и с помощью команды wget скачайте архив с исходным кодом ядра Linux:

Шаг №2: Распаковка архива с исходным кодом

Распакуем архив, применив команду tar :

$ tar xvf linux-5.12.10.tar.xz

Шаг №3: Установка необходимых пакетов

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

Пользователям Debian/Ubuntu/Linux Mint:

Читайте также:  Сбербанк инвестор приложение для windows

$ sudo apt-get install git fakeroot build-essential ncurses-dev xz-utils libssl-dev bc flex libelf-dev bison

Данная команда установит следующие пакеты:

Пакет Описание
git Утилита, помогающая отслеживать изменения в файлах исходного кода. А в случае какой-либо ошибки, эти изменения можно будет откатить.
fakeroot Позволяет запускать команду в среде, имитирующей привилегии root.
build-essential Набор различных утилит для компиляции программ (компиляторы gcc, g++ и пр.).
ncurses-dev Библиотека, предоставляющая API для программирования текстовых терминалов.
xz-utils Утилита для работы с архивами в .xz-формате.
libssl-dev Библиотека для разработки и поддержки протоколов шифрования SSL и TLS.
bc (Basic Calculator) Интерактивный интерпретатор, позволяющий выполнять скрипты с различными математическими выражениями.
flex (Fast Lexical Analyzer Generator) Утилита генерации программ, которые могут распознавать в тексте шаблоны.
libelf-dev Библиотека, используемая для работы с ELF-файлами (исполняемые файлы, файлы объектного кода и дампы ядра).
bison Создает из набора правил программу анализа структуры текстовых файлов.

Пользователям CentOS/RHEL/Scientific Linux:

$ sudo yum group install «Development Tools»

$ sudo yum groupinstall «Development Tools»

Также необходимо установить дополнительные пакеты:

$ sudo yum install ncurses-devel bison flex elfutils-libelf-devel openssl-devel

Пользователям Fedora:

$ sudo dnf group install «Development Tools»
$ sudo dnf install ncurses-devel bison flex elfutils-libelf-devel openssl-devel

Шаг №4: Конфигурирование ядра

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

Для этого перейдите с помощью команды cd в каталог linux-5.12.10:

Скопируйте существующий файл конфигурации с помощью команды cp :

$ sudo cp -v /boot/config-$(uname -r) .config

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

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

Меню конфигурации включает в себя такие параметры, как:

Firmware Drivers — настройка прошивки/драйверов для различных устройств;

Virtualization — настройки виртуализации;

File systems — настройки различных файловых систем;

Для навигации по меню применяются стрелки на клавиатуре. Пункт H elp > поможет вам узнать больше о различных параметрах. Когда вы закончите вносить изменения, выберите пункт S ave > , а затем выйдите из меню с помощью пункта E xit > .

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

Примечание: Если вы использовали вариант с копированием файла конфигурации, то перед переходом к следующему шагу, откройте этот файл и проверьте, что параметр CONFIG_SYSTEM_TRUSTED_KEYS у вас определен так же, как указано на следующем скриншоте:

В противном случае вы можете получить ошибку:

make[4]: *** No rule to make target ‘debian/certs/test-signing-certs.pem’, needed by ‘certs/x509_certificate_list’. Stop.
make[4]: *** Waiting for unfinished jobs.

Шаг №5: Сборка ядра

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

Процесс сборки и компиляции ядра Linux занимает довольно продолжительное время.

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

Затем нужно будет установить модули с помощью следующей команды:

$ sudo make modules_install

Осталось произвести установку нового ядра. Для этого необходимо выполнить:

$ sudo make install

Шаг №6: Обновление загрузчика

Загрузчик GRUB — это первая программа, которая запускается при включении системы.

Пользователям Debian/Ubuntu/Linux Mint:

Команда make install автоматически обновит загрузчик.

Для того, чтобы обновить загрузчик вручную, вам необходимо сначала обновить initramfs до новой версии ядра:

$ sudo update-initramfs -c -k 5.12.10

Затем обновить загрузчик GRUB с помощью следующей команды:

Пользователям CentOS/RHEL/Scientific Linux :

$ sudo grub2-mkconfig -o /boot/grub2/grub.cfg
$ sudo grubby —set-default /boot/vmlinuz-5.6.9

Вы можете подтвердить детали с помощью следующих команд:

grubby —info=ALL | more
grubby —default-index
grubby —default-kernel

Шаг №7: Перезагрузка системы

После выполнения вышеописанных действий перезагрузите свой компьютер. Когда система загрузится, проверьте версию используемого ядра с помощью следующей команды:

Как видите, теперь в системе установлено собранное нами ядро Linux-5.12.10.

Поделиться в социальных сетях:

Источник

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