Linux kernel build header

Linux kernel build header

Product SiteDocumentation Site

8.10. Компиляция Ядра

Включаемые в дистибутивы Debian ядра содержат в себе максимально количество функциональных возможностей, а также максимум драйверов. В результате этого становится возможным с помощью ядра настроить как можно больше аппаратных устройств уже на стадии установки, загрузки и дальнейшей эксплуатации системы (которые могут быть установлены на компьютерах пользователей. Большинство их такая ситуация устраивает — максимально опознаются аппаратные средства, а расточительное использование ресурсов компьютера для них не критично). Но некоторые предпочитают перекомпилировать (пересобрать) ядро, включив в них только то, что им действительно нужно. Для такого подхода имеются две причины. Первая — возможность оптимизации использования физической памяти (RAM) поскольку код ядра постоянно находится в ней (и никогда не “выгружается”, даже часть его, на файл подкачки). Избыточное использование ядром физической памяти (а она недёшева, и её часто не хватает на компьютерах пользователей) может уменьшить общую производительность системы. Вторая причина — локально скомпилированные ядра помогут снизить риск проблем безопасности. За счёт исключения ненужного (только незначительное количество кода ядра будет включено в состав ядра, скомпилировано и в дальнейшем выполняться) в конечном итоге повысится защищённость и производительность системы.

ЗАМЕТКА Обновления Системы Безопасности

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

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

УГЛУБЛЯЕМСЯ Настольная Книга по Ядру Debian

The Debian kernel team maintains the “Debian Kernel Handbook” (also available in the debian-kernel-handbook package) with comprehensive documentation about most kernel related tasks and about how official Debian kernel packages are handled. This is the first place you should look into if you need more information than what is provided in this section.

8.10.1. Введение и предпосылки

Неудивительно, что в Debian управление ядром организовано в виде готового пакета, а не как ранее — традиционная компиляция и устанавка вручную. Поскольку ядро (в составе пакета) всегда остается под контролем системы управления пакетами, то удаление или установка ядра на одной, или на нескольких машинах сразу, выполняется чисто. Кроме того, в пакетах кроме ядра имеются ещё и сценарии, автоматизирующие процесс подключения устанавливаемого ядра в загрузчик и создающие образ initrd для загрузки.

Читайте также:  Винда линукс одном компе

The upstream Linux sources contain everything needed to build a Debian package of the kernel. But you still need to install build-essential to ensure that you have the tools required to build a Debian package. Furthermore, the configuration step for the kernel requires the libncurses-dev package (formerly libncurses5-dev , which is now a transitional package). Finally, the fakeroot package will enable creation of the Debian package without using administrator’s rights.

КУЛЬТУРА Старые добрые времена пакета kernel-package

Ранее рекомендованным способом сборки пакетов было использование программы make-kpkg из пакета kernel-package . В настоящее время у системы построения пакетов Linux уже появилась возможность создания пакетов Debian надлежащего качества.

8.10.2. Получение исходного кода

Like anything that can be useful on a Debian system, the Linux kernel sources are available in a package. To retrieve them, just install the linux-source-version package. The apt search ^linux-source command lists the various kernel versions packaged by Debian. The latest version is available in the Unstable distribution: you can retrieve them without much risk (especially if your APT is configured according to the instructions of Раздел 6.2.6, «Работа с отдельными дистрибутивами»). Note that the source code contained in these packages does not correspond precisely with that published by Linus Torvalds and the kernel developers; like all distributions, Debian applies a number of patches, which might (or might not) find their way into the upstream version of Linux. These modifications include backports of fixes/features/drivers from newer kernel versions, new features not yet (entirely) merged in the upstream Linux tree, and sometimes even Debian specific changes.

The remainder of this section focuses on the 5.10 version of the Linux kernel, but the examples can, of course, be adapted to the particular version of the kernel that you want.

We assume the linux-source-5.10 package has been installed. It contains /usr/src/linux-source-5.10.tar.xz , a compressed archive of the kernel sources. You must extract these files in a new directory (not directly under /usr/src/ , since there is no need for special permissions to compile a Linux kernel): ~/kernel/ is appropriate.

$ mkdir ~/kernel; cd ~/kernel $ tar -xaf /usr/src/linux-source-5.10.tar.xz

КУЛЬТУРА Месторасположение исходных кодов ядра

Читайте также:  Ft232r usb uart драйвер linux

Traditionally, Linux kernel sources would be placed in /usr/src/linux/ thus requiring root permissions for compilation. However, working with administrator rights should be avoided when not needed. There is a src group that allows members to work in this directory, but working in /usr/src/ should be avoided, nevertheless. By keeping the kernel sources in a personal directory, you get security on all counts: no files in /usr/ unknown to the packaging system, and no risk of misleading programs that read /usr/src/linux when trying to gather information on the used kernel.

To build a kernel from the pristine sources, just download the tarball of the version of your choice from kernel.org , verify the integrity after importing the kernel maintainers key, and then proceed as described in the following chapters.

 $ wget https://kernel.org/pub/linux/kernel/v5.x/linux-5.10.62.tar.xz [..] $ wget https://kernel.org/pub/linux/kernel/v5.x/linux-5.10.62.tar.sign [..] $ unxz -c linux-5.10.62.tar.xz | gpg --verify linux-5.10.62.tar.sign - gpg: Signature made Fri 03 Sep 2021 10:11:35 AM CEST gpg: using RSA key 647F28654894E3BD457199BE38DBBDC86092693E gpg: Good signature from "Greg Kroah-Hartman " [unknown] gpg: aka "Greg Kroah-Hartman (Linux kernel stable release signing key) " [unknown] gpg: aka "Greg Kroah-Hartman " [unknown] gpg: WARNING: This key is not certified with a trusted signature! gpg: There is no indication that the signature belongs to the owner. Primary key fingerprint: 647F 2865 4894 E3BD 4571 99BE 38DB BDC8 6092 693E 

8.10.3. Настройка ядра

Следующий шаг содержит настройку ядра в соответствии с вашими потребностями. Более точный алгоритм работы зависит от ваших целей.

When recompiling a more recent version of the kernel (possibly with an additional patch), the configuration will most likely be kept as close as possible to that proposed by Debian. In this case, and rather than reconfiguring everything from scratch, it is sufficient to copy the /boot/config-version file (the version is that of the kernel currently used, which can be found with the uname -r command) into a .config file in the directory containing the kernel sources. Make sure to read sidebar TIP Missing debian/certs/debian-uefi-certs.pem in this case.

$ cp /boot/config-5.10.0-8-amd64 ~/kernel/linux-source-5.10/.config

Если вам не нужно изменять конфигурацию ядра, вы можете остановиться здесь и пропустить раздел Раздел 8.10.4, «Компиляция и Сборка Пакета». В противном случае, если необходимо внести изменения в конфигурацию ядра или вы решили сами всё настроить с нуля, то необходимо выделить достаточно время на эту работу. В каталоге с исходными кодами ядра присутствуют и различные специальные интерфейсы, которые могут быть использованы посредством вызова команды make target , где в качестве target выступает одно из значений, описанных ниже.

Читайте также:  Linux ограничение загрузки процессора

make menuconfig compiles and executes a text-mode interface (this is where the libncurses-dev package is required) which allows navigating the options available in a hierarchical structure. Pressing the Space key changes the value of the selected option, and Enter validates the button selected at the bottom of the screen; Select returns to the selected sub-menu; Exit closes the current screen and moves back up in the hierarchy; Help will display more detailed information on the role of the selected option. The arrow keys allow moving within the list of options and buttons. To exit the configuration program, choose Exit from the main menu. The program then offers to save the changes you’ve made; accept if you are satisfied with your choices.

Other interfaces have similar features, but they work within more modern graphical interfaces; such as make xconfig which uses a Qt graphical interface, and make gconfig which uses GTK+. The former requires qtbase5-dev , while the latter depends on libglade2-dev and libgtk2.0-dev .

Хорошей идеей было бы использовать совместно с теми интерфейсами одну из конфигураций по умолчанию, имеющиеся в комплекте с исходным кодом ядра. Они спроектированы оптимальным образом и расположены в arch/arch/configs/*_defconfig . Вы можете взять выбранную вами оттуда конфигурацию поместив её в новое место командой похожей на make x86_64_defconfig (в случае 64-битного ПК) или make i386_defconfig (в случае 32-разрядный ПК). Программа возьмёт .config из заготовленных разработчиками оптимальных конфигураций и сохраняет его в каталог, где будет компилироваться ядро, то есть по сути копирует этот файл.

СОВЕТ Применение устаревших файлов .config

Если вы хотите использовать старый файл .config , который был создан ранее в другой (обычно старой) версии ядра, вам необходимо будет его обновить. Для этого имеются три варианта. Первый — при запуске make oldconfig программа в интерактивной форме задаст вам вопросы, касающиеся вновь введённых в ядро опций или изменений, которые возможно имели место быть в новой версии ядра (длительный по времени процесс). Второй — запуск make olddefconfig уведомит программу о том, что вы, как бы, ответили на все задаваемые ею вопросы положительно. Третий — команда make oldnoconfig даст понять команде, что на все вопросы вы дали отрицательные ответы.

Источник

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