Handbook:X86/Installation/Kernel

From Gentoo Wiki
Jump to:navigation Jump to:search
This page is a translated version of the page Handbook:X86/Installation/Kernel and the translation is 100% complete.
X86 Handbook
Установка
Об установке
Выбор подходящего источника для установки
Настройка сети
Подготовка дисков
Установка файла stage
Установка базовой системы
Настройка ядра
Настройка системы
Установка системных утилит
Настройка загрузчика
Завершение
Работа с Gentoo
Введение в Portage
USE-флаги
Возможности Portage
Система сценариев инициализации
Переменные окружения
Работа с Portage
Файлы и каталоги
Переменные
Смешение ветвей программного обеспечения
Дополнительные утилиты
Дополнительные репозитории пакетов
Расширенные возможности
Настройка сети OpenRC
Начальная настройка
Расширенная настройка
Модульное построение сети
Беспроводная сеть
Добавляем функциональность
Динамическое управление


Необязательно: Установка файлов прошивки и/или микрокода

Файлы прошивки

Suggested: Linux Firmware

On many systems, non-FOSS firmware is required for certain hardware to function. The sys-kernel/linux-firmware package contains firmware for many, but not all, devices.

Совет
Most wireless cards and GPUs require firmware to function.
root #emerge --ask sys-kernel/linux-firmware
Заметка
Установка определённых пакетов прошивок часто требует принятия соответствующих лицензий на прошивку. При необходимости посетите раздел руководства о принятии лицензии для получения помощи.
Firmware Loading

Firmware files are typically loaded when the associated kernel module is loaded. This means the firmware must be built into the kernel using CONFIG_EXTRA_FIRMWARE if the kernel module is set to Y instead of M. In most cases, building-in a module which required firmware can complicate or break loading.

Микрокод

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

Обновления микрокода для процессоров AMD распространяются в вышеупомянутом пакете sys-kernel/linux-firmware. Обновления микрокода для процессоров Intel находятся в пакете sys-firmware/intel-microcode, который необходимо установить отдельно. См. статью Микрокод для получения дополнительной информации о том, как применять обновления микрокода.

sys-kernel/installkernel

Installkernel may be used to automate the kernel installation, initramfs generation, unified kernel image generation and/or bootloader configuration among other things. sys-kernel/installkernel implements two paths of achieving this: the traditional installkernel originating from Debian and systemd's kernel-install. Which one to choose depends, among other things, on the system's bootloader. By default, systemd's kernel-install is used on systemd profiles, while the traditional installkernel is the default for other profiles.

Bootloader

Now is the time to think about which bootloader the user wants for the system, if unsure, follow the 'Traditional layout' subsection below.

GRUB

Users of GRUB can use either systemd's kernel-install or the traditional Debian installkernel. The systemd USE flag switches between these implementations. To automatically run grub-mkconfig when installing the kernel, enable the grub USE flag.

ФАЙЛ /etc/portage/package.use/installkernel
sys-kernel/installkernel grub
root #emerge --ask sys-kernel/installkernel

systemd-boot

When using systemd-boot (formerly gummiboot) as the bootloader, systemd's kernel-install must be used. Therefore ensure the systemd and the systemd-boot USE flags are enabled on sys-kernel/installkernel, and then install the relevant package for systemd-boot.

On OpenRC systems:

ФАЙЛ /etc/portage/package.use/systemd-boot
sys-apps/systemd-utils boot kernel-install
sys-kernel/installkernel systemd systemd-boot
root #emerge --ask sys-apps/systemd-utils sys-kernel/installkernel

On systemd systems:

ФАЙЛ /etc/portage/package.use/systemd
sys-apps/systemd boot
sys-kernel/installkernel systemd-boot
root #emerge --ask sys-apps/systemd sys-kernel/installkernel

The kernel command line to use for new kernels should be specified in /etc/kernel/cmdline, for example:

ФАЙЛ /etc/kernel/cmdline
quiet splash

EFI stub

UEFI-based computer systems technically do not need secondary bootloaders in order to boot kernels. Secondary bootloaders exist to extend the functionality of UEFI firmware during the boot process. That being said, using a secondary bootloader is typically easier and more robust because it offers a more flexible approach for quickly modifying kernel parameters at boot time. Note also that UEFI implentations strongly differ between vendors and between models and there is no guarantee that a given firmware follows the UEFI specification. Therefore, EFI Stub booting is not guaranteed to work on every UEFI-based system, and hence the USE flag is stable masked and testing keywords must be accepted for installkernel to use this feature.

ФАЙЛ /etc/portage/package.accept_keywords/installkernel
sys-kernel/installkernel
sys-boot/uefi-mkconfig
app-emulation/virt-firmware
ФАЙЛ /etc/portage/package.use/installkernel
sys-kernel/installkernel efistub
root #emerge --ask sys-kernel/installkernel
root #mkdir -p /efi

Traditional layout, other bootloaders (e.g. (e)lilo, syslinux, etc.)

The traditional /boot layout (for e.g. (e)LILO, syslinux, etc.) is used by default if the grub, systemd-boot, efistub and uki USE flags are not enabled. No further action is required.

Initramfs

An initial ram-based file system, or initramfs, may be required for a system to boot. A wide of variety of cases may necessitate one, but common cases include:

  • Kernels where storage/filesystem drivers are modules.
  • Layouts with /usr/ or /var/ on separate partitions.
  • Encrypted root filesystems.
Совет
Distribution kernels are designed to be used with an initramfs, as many storage and filesystem drivers are built as modules.

In addition to mounting the root filesystem, an initramfs may also perform other tasks such as:

  • Running file system consistency check fsck, a tool to check and repair consistency of a file system in such events of uncleanly shutdown a system.
  • Providing a recovery environment in the event of late-boot failures.

Installkernel can automatically generate an initramfs when installing the kernel if the dracut or ugrd USE flag is enabled:

ФАЙЛ /etc/portage/package.use/installkernel
sys-kernel/installkernel dracut
root #emerge --ask sys-kernel/installkernel

Optional: Unified Kernel Image

A Unified Kernel Image (UKI) combines, among other things, the kernel, the initramfs and the kernel command line into a single executable. Since the kernel command line is embedded into the unified kernel image, it should be specified before generating the unified kernel image (see below). Note that any kernel command line arguments supplied by the bootloader or firmware at boot are ignored when booting with secure boot enabled.

A unified kernel image requires a stub loader. Currently, the only one available is systemd-stub. To enable it:

For systemd systems:

ФАЙЛ /etc/portage/package.use/uki
sys-apps/systemd boot
root #emerge --ask sys-apps/systemd

For OpenRC systems:

ФАЙЛ /etc/portage/package.use/uki
sys-apps/systemd-utils boot kernel-install
root #emerge --ask sys-apps/systemd-utils

Installkernel can automatically generate a unified kernel image using either dracut or ukify by enabling the respective flag and the uki USE flag.

For dracut:

ФАЙЛ /etc/portage/package.use/uki
sys-kernel/installkernel dracut uki
ФАЙЛ /etc/dracut.conf.d/uki.conf
uefi="yes"
kernel_cmdline="some-kernel-command-line-arguments"
root #emerge --ask sys-kernel/installkernel

For ukify:

ФАЙЛ /etc/portage/package.use/uki
sys-apps/systemd boot ukify                         # Для систем systemd
sys-apps/systemd-utils kernel-install boot ukify    # Для систем OpenRC
sys-kernel/installkernel dracut ukify uki
ФАЙЛ /etc/kernel/cmdline
some-kernel-command-line-arguments
root #emerge --ask sys-kernel/installkernel

Note that while dracut can generate both an initramfs and a unified kernel image, ukify can only generate the latter and therefore the initramfs must be generated separately with dracut.

Важно
In the above configuration examples (for both Dracut and ukify) it is important to specify at least an appropriate root= parameter for the kernel command line to ensure that the Unified Kernel Image can find the root partition. This is not required for systemd based systems following the Discoverable Partitions Specification (DPS), in that case the embedded initramfs will be able to dynamically find the root partition.

Generic Unified Kernel Image (systemd only)

The prebuilt sys-kernel/gentoo-kernel-bin can optionally install a prebuilt generic unified kernel image containing a generic initramfs that is able to boot most systemd based systems. It can be installed by enabling the generic-uki USE flag, and configuring installkernel to not generate a custom initramfs or unified kernel image:

ФАЙЛ /etc/portage/package.use/uki
sys-kernel/gentoo-kernel-bin generic-uki
sys-kernel/installkernel -dracut -ukify -ugrd uki

Secure Boot

Предупреждение
If following this section and manually compiling your own kernel, then make sure to follow the steps outlined in Signing the kernel

The generic Unified Kernel Image optionally distributed by sys-kernel/gentoo-kernel-bin is already pre-signed. How to sign a locally generated unified kernel image depends on whether dracut or ukify is used. Note that the location of the key and certificate should be the same as the SECUREBOOT_SIGN_KEY and SECUREBOOT_SIGN_CERT as specified in /etc/portage/make.conf.

For dracut:

ФАЙЛ /etc/dracut.conf.d/uki.conf
uefi="yes"
kernel_cmdline="some-kernel-command-line-arguments"
uefi_secureboot_key="/path/to/kernel_key.pem"
uefi_secureboot_cert="/path/to/kernel_key.pem"

For ukify:

ФАЙЛ /etc/kernel/uki.conf
[UKI]
SecureBootPrivateKey=/path/to/kernel_key.pem
SecureBootCertificate=/path/to/kernel_key.pem

Конфигурация и компиляция ядра

Совет
It can be a wise move to use the dist-kernel on the first boot as it provides a very simple method to rule out system issues and kernel config issues. Always having a known working kernel to fallback on can speed up debugging and alleviate anxiety when updating that your system will no longer boot.

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

Заметка
During the installation phase of Gentoo, only one kernel type should be installed i.e. either the sys-kernel/gentoo-kernel-bin or sys-kernel/gentoo-sources.

От наименьшего вмешательства к наибольшему:

Полностью автоматический подход: Distribution-ядра
Проект Distribution Kernel используется для конфигурации, автоматической сборки и установки ядра Linux, связанных с ним модулей и (опционально, но по умолчанию включено) файла initramfs. Новые обновления ядра полностью автоматизированы, поскольку они обрабатываются через менеджер пакетов, как и любой другой системный пакет. В случае необходимости можно предоставить пользовательский конфигурационный файл ядра. Это наименее сложный процесс и идеально подходит для новых пользователей Gentoo, так как работает "из коробки" и требует минимального участия системного администратора.
Гибридный подход: Genkernel
Новые обновления ядра устанавливаются через системный менеджер пакетов. Системные администраторы могут использовать инструмент Gentoo genkernel для общей конфигурации, автоматической сборки и установки ядра Linux, связанных с ним модулей и (опционально, но не включено по умолчанию) файла initramfs. Можно предоставить пользовательский файл конфигурации ядра, если необходима кастомизация. Будущая конфигурация, сборка и установка ядра требуют участия системного администратора в виде выполнения eselect kernel, genkernel и, возможно, других команд для каждого обновления.
Полностью ручная настройка
Новые исходные тексты ядра устанавливаются с помощью системного менеджера пакетов. Ядро конфигурируется, собирается и устанавливается вручную с помощью команды eselect kernel и множества команд make. С новыми обновлениями ядра повторяется ручной процесс конфигурирования, сборки и установки файлов ядра. Это самый сложный процесс, но он обеспечивает максимальный контроль над процессом обновления ядра.

Основой, вокруг которой строятся все дистрибутивы, является ядро Linux. Оно является прослойкой между пользовательскими программами и аппаратным обеспечением системы. Хотя руководство предоставляет своим пользователям несколько возможных источников ядра, более подробная информация с более детальным описанием доступна на странице {{|Link|Kernel/Overview|Общие сведения о ядре}}.

Совет
Kernel installation tasks such as copying the kernel image to /boot or the EFI System Partition, generating an initramfs and/or Unified Kernel Image, updating bootloader configuration, can be automated with installkernel. Users may wish to configure and install sys-kernel/installkernel before proceeding. See the Kernel installation section below for more more information.

Distribution-ядра

Distribution-ядра — это ebuild-файлы, которые охватывают полный процесс распаковки, конфигурирования, компиляции и установки ядра. Основным преимуществом этого метода является то, что ядра обновляются до новых версий менеджером пакетов во время обновления @world. Для этого используется только команда emerge. Distribution-ядра по умолчанию сконфигурированы для поддержки большинства оборудования, для более тонкой настройки предлагаются два механизма: saveconfig и сниппеты конфигурации. Смотрите страницу проекта для более подробной информации о конфигурации.

Optional: Signed kernel modules

The kernel modules in the prebuilt distribution kernel (sys-kernel/gentoo-kernel-bin) are already signed. To sign the modules of kernels built from source enable the modules-sign USE flag, and optionally specify which key to use for signing in /etc/portage/make.conf:

ФАЙЛ /etc/portage/make.confEnable module signing
USE="modules-sign"
</div>

<div lang="en" dir="ltr" class="mw-content-ltr">
# Optionally, to use custom signing keys.
MODULES_SIGN_KEY="/path/to/kernel_key.pem"
MODULES_SIGN_CERT="/path/to/kernel_key.pem" # Only required if the MODULES_SIGN_KEY does not also contain the certificate.
MODULES_SIGN_HASH="sha512" # Defaults to sha512.

If MODULES_SIGN_KEY is not specified the kernel build system will generate a key, it will be stored in /usr/src/linux-x.y.z/certs. It is recommended to manually generate a key to ensure that it will be the same for each kernel release. A key may be generated with:

root #openssl req -new -nodes -utf8 -sha256 -x509 -outform PEM -out kernel_key.pem -keyout kernel_key.pem
Заметка
The MODULES_SIGN_KEY and MODULES_SIGN_CERT may be different files. For this example the pem file generated by OpenSSL includes both the key and the accompanying certificate, and thus both variables are set to the same value.

OpenSSL will ask some questions about the user generating the key, it is recommended to fill in these questions as detailed as possible.

Store the key in a safe location, at the very least the key should be readable only by the root user. Verify this with:

root #ls -l kernel_key.pem
 -r-------- 1 root root 3164 Jan  4 10:38 kernel_key.pem 

If this outputs anything other then the above, correct the permissions with:

root #chown root:root kernel_key.pem
root #chmod 400 kernel_key.pem
Optional: Signing the kernel image (Secure Boot)

The kernel image in the prebuilt distribution kernel (sys-kernel/gentoo-kernel-bin) is already signed for use with Secure Boot. To sign the kernel image of kernels built from source enable the secureboot USE flag, and optionally specify which key to use for signing in /etc/portage/make.conf. Note that signing the kernel image for use with secureboot requires that the kernel modules are also signed, the same key may be used to sign both the kernel image and the kernel modules:

ФАЙЛ /etc/portage/make.confEnable custom signing keys
USE="modules-sign secureboot"
</div>

<div lang="en" dir="ltr" class="mw-content-ltr">
# Optionally, to use custom signing keys.
MODULES_SIGN_KEY="/path/to/kernel_key.pem"
MODULES_SIGN_CERT="/path/to/kernel_key.pem" # Only required if the MODULES_SIGN_KEY does not also contain the certificate.
MODULES_SIGN_HASH="sha512" # Defaults to sha512.
</div>

<div lang="en" dir="ltr" class="mw-content-ltr">
# Optionally, to boot with secureboot enabled, may be the same or different signing key.
SECUREBOOT_SIGN_KEY="/path/to/kernel_key.pem"
SECUREBOOT_SIGN_CERT="/path/to/kernel_key.pem"
Заметка
The SECUREBOOT_SIGN_KEY and SECUREBOOT_SIGN_CERT may be different files. For this example the pem file generated by OpenSSL includes both the key and the accompanying certificate, and thus both variables are set to the same value.
Заметка
For this example the same key that was generated to sign the modules is used to sign the kernel image. It is also possible to generate and use a second separate key for signing the kernel image. The same OpenSSL command as in the previous section may be used again.

See the above section for instructions on generating a new key, the steps may be repeated if a separate key should be used to sign the kernel image.

To successfully boot with Secure Boot enabled, the used bootloader must also be signed and the certificate must be accepted by the UEFI firmware or Shim. This will be explained later in the handbook.

Установка distribution-ядра

Чтобы собрать ядро из исходного кода с патчами Gentoo, введите:

root #emerge --ask sys-kernel/gentoo-kernel

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

root #emerge --ask sys-kernel/gentoo-kernel-bin
Важно
Distribution Kernels, such as sys-kernel/gentoo-kernel and sys-kernel/gentoo-kernel-bin, by default, expect to be installed alongside an initramfs. Before running emerge to install the kernel users should ensure that sys-kernel/installkernel has been configured to utilize an initramfs generator (for example Dracut) as described in the installkernel section.

Обновление и очистка

После установки ядра менеджер пакетов будет автоматически обновлять его до более новых версий. Предыдущие версии будут храниться до тех пор, пока менеджер пакетов не получит запрос на очистку устаревших пакетов. Чтобы освободить место на диске, устаревшие пакеты можно удалить, периодически запуская emerge с опцией --depclean:

root #emerge --depclean

Также можно удалить именно устаревшие ядра:

root #emerge --prune sys-kernel/gentoo-kernel sys-kernel/gentoo-kernel-bin
Совет
By design, emerge only removes the kernel build directory. It does not actually remove the kernel modules, nor the installed kernel image. To completely clean-up old kernels, the app-admin/eclean-kernel tool may be used.

Задачи после установки/обновления

An upgrade of a distribution kernel is capable of triggering an automatic rebuild for external kernel modules installed by other packages (for example: sys-fs/zfs-kmod or x11-drivers/nvidia-drivers). This automated behaviour is enabled by enabling the dist-kernel USE flag. When required, this same flag will also trigger re-generation of the initramfs.

Включение этого USE-флага для таких пакетов, как sys-fs/zfs и sys-fs/zfs-kmod позволит им автоматически пересобираться в соответствии с обновленным ядром и, в случае необходимости, пересобирать initramfs.

ФАЙЛ /etc/portage/make.confEnabling USE=dist-kernel
USE="dist-kernel"
Ручная пересборка initramfs или Unified Kernel Image

Если понадобится, вручную запустите перестройку, выполнив после обновления ядра команду:

root #emerge --ask @module-rebuild

Если какой-то модуль ядра (например, ZFS) необходим при ранней загрузке, пересоберите initramfs при помощи:

root #emerge --config sys-kernel/gentoo-kernel
root #emerge --config sys-kernel/gentoo-kernel-bin

After installing the Distribution Kernel successfully, it is now time to proceed to the next section: Configuring the system.

Установка исходного кода ядра

При установке и компиляции ядра для систем на базе x86 Gentoo рекомендует использовать пакет sys-kernel/gentoo-sources.

Выберите подходящий исходный код ядра и установите его с помощью emerge:

root #emerge --ask sys-kernel/gentoo-sources

Данная команда установит исходный код ядра Linux в /usr/src/, используя в названии версию ядра. Эта команда не установит автоматически символьную ссылку, пока вы не укажете USE-флаг symlink для выбранного исходного кода ядра.

Обычно, символьная ссылка /usr/src/linux указывает на исходный код текущего работающего ядра. Однако, эта символьная ссылка не создаётся по умолчанию. Создать её поможет kernel модуль для eselect.

Чтобы подробнее узнать, зачем нужна эта символьная ссылка и как ею управлять, смотрите Kernel/Upgrade.

Для начала, просмотрите список установленных ядер (в виде исходного кода):

root #eselect kernel list
Available kernel symlink targets:
  [1]   linux-6.6.21-gentoo

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

root #eselect kernel set 1
root #ls -l /usr/src/linux
lrwxrwxrwx    1 root   root    20 мар  3 22:44 /usr/src/linux -> linux-6.6.21-gentoo

Альтернатива: Ручная настройка

Заметка
In case it was missed, this section requires the kernel sources to be installed. Be sure to obtain the relevant kernel sources, then return here for the rest of section.

Manually configuring a kernel is commonly seen as one of the most difficult procedures a system administrator has to perform. Nothing is less true - after configuring a few kernels no one remembers that it was difficult! There are two ways for a Gentoo user to manage a manual kernel system, both of which are listed below:

Modprobed-db process

A very easy way to manage the kernel is to first install sys-kernel/gentoo-kernel-bin and use the sys-kernel/modprobed-db to collect information about what the system requires. modprobed-db is a tool which monitors the system via crontab to add all modules of all devices over the system's life to make sure it everything a user needs is supported. For example, if an Xbox controller is added after installation, then modprobed-db will add the modules to be built next time the kernel is rebuilt. More on this topic can be found in the Modprobed-db article.

Manual process

This method allows a user to have full control of how their kernel is built with as minimal help from outside tools as they wish. Some could consider this as making it hard for the sake of it.

Однако одна вещь является истиной: при ручной конфигурации ядра очень важно понимать свою систему. Большую часть сведений можно почерпнуть, установив пакет sys-apps/pciutils, который содержит в команду lspci:

root #emerge --ask sys-apps/pciutils
Заметка
Находясь внутри изолированного окружения chroot, можно спокойно игнорировать любые предупреждения pcilib (например, pcilib: cannot open /sys/bus/pci/devices), которые могут появляться в выводе lspci.

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

Остаётся перейти в каталог с ядром и выполнить make menuconfig, который запустит экран меню конфигурации.

root #cd /usr/src/linux

The kernel has a method of autodetecting the modules currently being used on the installcd which will give a great starting point to allow a user to configure their own. This can be called by using:

root #make localmodconfig

It's now time to configure using nconfig:

root #make nconfig

В конфигурации ядра Linux есть много-много разделов. Сначала пройдёмся по пунктам, которые должны быть обязательно включены (иначе Gentoo будет работать неправильно или же вовсе не запустится). Также в вики есть Руководство по настройке ядра Gentoo, которое поможет понять более тонкие детали.

Enabling required options

При использовании sys-kernel/gentoo-sources, строго рекомендуется включить Gentoo-специфичные настройки. С помощью них включается необходимый минимум настроек ядра для корректной работы:

ЯДРО Включение Gentoo-специфичных настроек
Gentoo Linux --->
    [*] Gentoo Linux support
    [*]   Linux dynamic and persistent device naming (userspace devfs) support
    [*]   Select options required by Portage features
        Support for init systems, system and service managers  --->
          [*] OpenRC, runit and other script based systems and managers
          [*] systemd

Выбор в последних двух строках зависит от того, какую систему инициализации вы выбрали — OpenRC или systemd. Ничего страшного не случится, если вы включите поддержку обоих систем.

При использовании sys-kernel/vanilla-sources, этих вспомогательных настроек не будет. Вы можете включить нужные настройки вручную, но это выходит за рамки данного руководства.

Enabling support for typical system components

Убедитесь, что все драйверы, необходимые для загрузки системы (такие как контроллер SATA, поддержка блочных устройств NVMe, поддержка файловой системы и другие) собраны прямо в ядре, а не в виде модуля. В противном случае, система может не загрузиться.

Далее следует выбрать тип процессора. Также рекомендуется включить возможности MCE (если они доступны), чтобы пользователи системы могли получать оповещение о любых проблемах с оборудованием. На некоторых архитектурах (например, x86_64) подобные ошибки выводятся не в dmesg, а в /dev/mcelog. А для него понадобится пакет app-admin/mcelog.

Также включите Maintain a devtmpfs file system to mount at /dev, чтобы критически важные файлы устройств были доступны на самом раннем этапе загрузки (CONFIG_DEVTMPFS и CONFIG_DEVTMPFS_MOUNT):

ЯДРО Включение поддержки devtmpfs (CONFIG_DEVTMPFS)
Device Drivers --->
  Generic Driver Options --->
    [*] Maintain a devtmpfs filesystem to mount at /dev
    [*]   Automount devtmpfs at /dev, after the kernel mounted the rootfs

Убедитесь, что поддержка SCSI-дисков включена (CONFIG_BLK_DEV_SD):

ЯДРО Включение поддержки SCSI-дисков (CONFIG_SCSI, CONFIG_BLK_DEV_SD)
Device Drivers --->
  SCSI device support  ---> 
    <*> SCSI device support
    <*> SCSI disk support
ЯДРО Включение базовой поддержки SATA и PATA (CONFIG_ATA_ACPI, CONFIG_SATA_PMP, CONFIG_SATA_AHCI, CONFIG_ATA_BMDMA, CONFIG_ATA_SFF, CONFIG_ATA_PIIX)
Device Drivers --->
  <*> Serial ATA and Parallel ATA drivers (libata)  --->
    [*] ATA ACPI Support
    [*] SATA Port Multiplier support
    <*> AHCI SATA support (ahci)
    [*] ATA BMDMA support
    [*] ATA SFF support (for legacy IDE and PATA)
    <*> Intel ESB, ICH, PIIX3, PIIX4 PATA/SATA support (ata_piix)

Убедитесь, что включена базовая поддержка NVMe:

ЯДРО Включение базовой поддержки NVMe для Linux 4.4.x (CONFIG_BLK_DEV_NVME)
Device Drivers  --->
  <*> NVM Express block device
ЯДРО Включение базовой поддержки NVMe для Linux 5.x.x (CONFIG_DEVTMPFS)
Device Drivers --->
  NVME Support --->
    <*> NVM Express block device

Не помешает включить следующую дополнительную поддержку NVMe:

ЯДРО Включение дополнительной поддержки NVMe (CONFIG_NVME_MULTIPATH, CONFIG_NVME_MULTIPATH, CONFIG_NVME_HWMON, CONFIG_NVME_FC, CONFIG_NVME_TCP, CONFIG_NVME_TARGET, CONFIG_NVME_TARGET_PASSTHRU, CONFIG_NVME_TARGET_LOOP, CONFIG_NVME_TARGET_FC, CONFIG_NVME_TARGET_FCLOOP, CONFIG_NVME_TARGET_TCP
[*] NVMe multipath support
[*] NVMe hardware monitoring
<M> NVM Express over Fabrics FC host driver
<M> NVM Express over Fabrics TCP host driver
<M> NVMe Target support
  [*]   NVMe Target Passthrough support
  <M>   NVMe loopback device support
  <M>   NVMe over Fabrics FC target driver
  < >     NVMe over Fabrics FC Transport Loopback Test driver (NEW)
  <M>   NVMe over Fabrics TCP target support

Теперь перейдите в раздел File Systems и выберите те файловые системы, которые планируете использовать. Файловая система, используемая в качестве корневой, должна быть включена в ядро (не модулем), иначе система не сможет подключить раздел при загрузке. Также включите Virtual memory и /proc file system. При необходимости выберите один или несколько параметров, необходимых системе:

ЯДРО Включение поддержки файловой системы (CONFIG_EXT2_FS, CONFIG_EXT3_FS, CONFIG_EXT4_FS, CONFIG_BTRFS_FS, CONFIG_XFS_FS, CONFIG_MSDOS_FS, CONFIG_VFAT_FS, CONFIG_PROC_FS, и CONFIG_TMPFS)
File systems --->
  <*> Second extended fs support
  <*> The Extended 3 (ext3) filesystem
  <*> The Extended 4 (ext4) filesystem
  <*> Btrfs filesystem support
  <*> XFS filesystem support
  DOS/FAT/NT Filesystems  --->
    <*> MSDOS fs support
    <*> VFAT (Windows-95) fs support
  Pseudo Filesystems --->
    [*] /proc file system support
    [*] Tmpfs virtual memory file system support (former shm fs)

Если для подключения к Интернету используется PPPoE или модемное соединение, то включите следующие параметры (CONFIG_PPP, CONFIG_PPP_ASYNC и CONFIG_PPP_SYNC_TTY):

ЯДРО Включение поддержки PPPoE (PPPoE, CONFIG_PPPOE, CONFIG_PPP_ASYNC, CONFIG_PPP_SYNC_TTY
Device Drivers --->
  Network device support --->
    <*> PPP (point-to-point protocol) support
    <*> PPP over Ethernet
    <*> PPP support for async serial ports
    <*> PPP support for sync tty ports

Два параметра сжатия не повредят, но и не являются обязательными, как и PPP over Ethernet. Фактически, последний используется в случае, если ppp сконфигурирован на использование ядерный PPPoE режим.

Не забудьте настроить поддержку сетевых карт (Ethernet или беспроводных).

Поскольку большинство современных систем являются многоядерными, важно включить Symmetric multi-processing support (CONFIG_SMP):

ЯДРО Включение поддержки SMP (CONFIG_SMP)
Processor type and features  --->
  [*] Symmetric multi-processing support
Заметка
Во многоядерных системах каждое ядро считается за один процессор.

Если используются USB-устройства ввода (например, клавиатура и мышь) или другие устройства, то не забудьте включить и эти параметры:

ЯДРО Включение поддержки USB и HID(CONFIG_HID_GENERIC, CONFIG_USB_HID, CONFIG_USB_SUPPORT, CONFIG_USB_XHCI_HCD, CONFIG_USB_EHCI_HCD, CONFIG_USB_OHCI_HCD, (CONFIG_HID_GENERIC, CONFIG_USB_HID, CONFIG_USB_SUPPORT, CONFIG_USB_XHCI_HCD, CONFIG_USB_EHCI_HCD, CONFIG_USB_OHCI_HCD, CONFIG_USB4)
Device Drivers --->
  HID support  --->
    -*- HID bus support
    <*>   Generic HID driver
    [*]   Battery level reporting for HID devices
      USB HID support  --->
        <*> USB HID transport layer
  [*] USB support  --->
    <*>     xHCI HCD (USB 3.0) support
    <*>     EHCI HCD (USB 2.0) support
    <*>     OHCI HCD (USB 1.1) support
  <*> Unified support for USB4 and Thunderbolt  --->

Optional: Signed kernel modules

To automatically sign the kernel modules enable CONFIG_MODULE_SIG_ALL:

ЯДРО Sign kernel modules CONFIG_MODULE_SIG_ALL
[*] Enable loadable module support  
  -*-   Module signature verification    
    [*]     Automatically sign all modules    
    Which hash algorithm should modules be signed with? (Sign modules with SHA-512) --->

Optionally change the hash algorithm if desired.

To enforce that all modules are signed with a valid signature, enable CONFIG_MODULE_SIG_FORCE as well:

ЯДРО Enforce signed kernel modules CONFIG_MODULE_SIG_FORCE
[*] Enable loadable module support  
  -*-   Module signature verification    
    [*]     Require modules to be validly signed
    [*]     Automatically sign all modules
    Which hash algorithm should modules be signed with? (Sign modules with SHA-512) --->

To use a custom key, specify the location of this key in CONFIG_MODULE_SIG_KEY. If unspecified, the kernel build system will generate a key. It is recommended to generate one manually instead. This can be done with:

root #openssl req -new -nodes -utf8 -sha256 -x509 -outform PEM -out kernel_key.pem -keyout kernel_key.pem

OpenSSL will ask some questions about the user generating the key, it is recommended to fill in these questions as detailed as possible.

Store the key in a safe location, at the very least the key should be readable only by the root user. Verify this with:

root #ls -l kernel_key.pem
 -r-------- 1 root root 3164 Jan  4 10:38 kernel_key.pem 

If this outputs anything other then the above, correct the permissions with:

root #chown root:root kernel_key.pem
root #chmod 400 kernel_key.pem
ЯДРО Specify signing key CONFIG_MODULE_SIG_KEY
-*- Cryptographic API  ---> 
  Certificates for signature checking  --->  
    (/path/to/kernel_key.pem) File name or PKCS#11 URI of module signing key

To also sign external kernel modules installed by other packages via linux-mod-r1.eclass, enable the modules-sign USE flag globally:

ФАЙЛ /etc/portage/make.confEnable module signing
USE="modules-sign"
</div>

<div lang="en" dir="ltr" class="mw-content-ltr">
# Optionally, when using custom signing keys.
MODULES_SIGN_KEY="/path/to/kernel_key.pem"
MODULES_SIGN_CERT="/path/to/kernel_key.pem" # Only required if the MODULES_SIGN_KEY does not also contain the certificate
MODULES_SIGN_HASH="sha512" # Defaults to sha512
Заметка
MODULES_SIGN_KEY and MODULES_SIGN_CERT may point to different files. For this example, the pem file generated by OpenSSL includes both the key and the accompanying certificate, and thus both variables are set to the same value.

Optional: Signing the kernel image (Secure Boot)

When signing the kernel image (for use on systems with Secure Boot enabled) it is recommended to set the following kernel config options:

ЯДРО Lockdown for secureboot
General setup  --->
  Kexec and crash features  --->   
    [*] Enable kexec system call                                                                                          
    [*] Enable kexec file based system call                                                                               
    [*]   Verify kernel signature during kexec_file_load() syscall                                                        
    [*]     Require a valid signature in kexec_file_load() syscall                                                        
    [*]     Enable ""image"" signature verification support
</div>  

[*] Enable loadable module support  
  -*-   Module signature verification    
    [*]     Require modules to be validly signed
    [*]     Automatically sign all modules
    Which hash algorithm should modules be signed with? (Sign modules with SHA-512) --->  

Security options  ---> 
[*] Integrity subsystem   
  [*] Basic module for enforcing kernel lockdown                                                                       
  [*]   Enable lockdown LSM early in init                                                                       
        Kernel default lockdown mode (Integrity)  --->            

  [*]   Digital signature verification using multiple keyrings                                                            
  [*]     Enable asymmetric keys support                                                                                     
  -*-       Require all keys on the integrity keyrings be signed                                                              
  [*]       Provide keyring for platform/firmware trusted keys                                                                
  [*]       Provide a keyring to which Machine Owner Keys may be added                                                        
  [ ]         Enforce Machine Keyring CA Restrictions

Where ""image"" is a placeholder for the architecture specific image name. These options, from the top to the bottom: enforces that the kernel image in a kexec call must be signed (kexec allows replacing the kernel in-place), enforces that kernel modules are signed, enables lockdown integrity mode (prevents modifying the kernel at runtime), and enables various keychains.

On arches that do not natively support decompressing the kernel (e.g. arm64 and riscv), the kernel must be built with its own decompressor (zboot):

ЯДРО zboot CONFIG_EFI_ZBOOT
Device Drivers --->                                                                                                                           
  Firmware Drivers --->                                                                                                                       
    EFI (Extensible Firmware Interface) Support --->                                                                                               
      [*] Enable the generic EFI decompressor

After compilation of the kernel, as explained in the next section, the kernel image must be signed. First install app-crypt/sbsigntools and then sign the kernel image:

root #emerge --ask app-crypt/sbsigntools
root #sbsign /usr/src/linux-x.y.z/path/to/kernel-image --cert /path/to/kernel_key.pem --key /path/to/kernel_key.pem --out /usr/src/linux-x.y.z/path/to/kernel-image
Заметка
For this example, the same key that was generated to sign the modules is used to sign the kernel image. It is also possible to generate and use a second separate key for signing the kernel image. The same OpenSSL command as in the previous section may be used again.

Then proceed with the installation.

To automatically sign EFI executables installed by other packages, enable the secureboot USE flag globally:

ФАЙЛ /etc/portage/make.confEnable Secure Boot
USE="modules-sign secureboot"
</div>

<div lang="en" dir="ltr" class="mw-content-ltr">
# Optionally, to use custom signing keys.
MODULES_SIGN_KEY="/path/to/kernel_key.pem"
MODULES_SIGN_CERT="/path/to/kernel_key.pem" # Only required if the MODULES_SIGN_KEY does not also contain the certificate.
MODULES_SIGN_HASH="sha512" # Defaults to sha512
</div>

<div lang="en" dir="ltr" class="mw-content-ltr">
# Optionally, to boot with secureboot enabled, may be the same or different signing key.
SECUREBOOT_SIGN_KEY="/path/to/kernel_key.pem"
SECUREBOOT_SIGN_CERT="/path/to/kernel_key.pem"
Заметка
SECUREBOOT_SIGN_KEY and SECUREBOOT_SIGN_CERT may point to different files. For this example, the pem file generated by OpenSSL includes both the key and the accompanying certificate, and thus both variables are set to the same value.
Заметка
When generating an Unified Kernel Image with systemd's ukify the kernel image will be signed automatically before inclusion in the unified kernel image and it is not necessary to sign it manually.


Для архитектур x86, удостоверьтесь, что параметр 64-bit kernel отключён (CONFIG_64BIT=N), после чего установите семейство процессоров, подходящее для процессора системы..

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

user $cat /proc/cpuinfo | grep -i vendor | uniq
user $cat /proc/cpuinfo | grep -i 'model name' | uniq
ЯДРО Выключите 64-bit kernel и выберите семейство процессоров
[ ] 64-bit kernel
Processor type and features  --->
    Processor family (Core 2/newer Xeon)  --->
        ( ) 486
        ( ) 586/K5/5x86/6x86/6x86MX
        ( ) Pentium-Classic
        ( ) Pentium-MMX
        ( ) Pentium-Pro
        ( ) Pentium-II/Celeron(pre-Coppermine)
        ( ) Pentium-III/Celeron(Coppermine)/Pentium-III Xeon
        ( ) Pentium M
        ( ) Pentium-4/Celeron(P4-based)/Pentium-4 M/Xeon
        ( ) K6/K6-II/K6-III
        ( ) Athlon/Duron/K7
        ( ) Opteron/Athlon64/Hammer/K8
        ( ) Crusoe
        ( ) Efficeon
        ( ) Winchip-C6
        ( ) Winchip-2/Winchip-2A/Winchip-3
        ( ) AMD Elan
        ( ) GeodeGX1
        ( ) Geode GX/LX
        ( ) CyrixIII/VIA-C3
        ( ) VIA C3-2 (Nehemiah)
        ( ) VIA C7
        (*) Core 2/newer Xeon
        ( ) Intel Atom

Компиляция и установка

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

root #make && make modules_install
Заметка
Можно включить параллельную сборку, используя make -jN, где N — это число параллельных задач, которые может запустить процесс сборки. Это похоже на инструкции, которые были даны ранее относительно файла /etc/portage/make.conf в части переменной MAKEOPTS

По завершении компиляции, скопируйте образ ядра в каталог /boot/. Это делается командой make install:

root #make install

Данная команда скопирует образ ядра в каталог /boot/ вместе с файлом System.map и файлом настройки ядра.


Deprecated: Genkernel

Genkernel should only be considered by users with a required need that only Genkernel can meet. For others, it is recommended to use the Distribution kernel or manually compile their own as it will make maintaining a Gentoo system a lot more simple. An example of why genkernel is more difficult to manage is the lack of integration with sys-kernel/installkernel. This means a user will not get the same level of automation as provided by the other methods; for example, Unified Kernel Images will need to be created manually when using Genkernel.

Users still wishing to use Genkernel should see the Genkernel article for more information.

Модули ядра

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

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

Модули, которые должны загружаться при каждой загрузке, могут быть добавлены в файлы /etc/modules-load.d/*.conf, по одному модулю в строке. Если для модулей необходимы дополнительные параметры, их следует указывать в файлах /etc/modprobe.d/*.conf.

Чтобы просмотреть все модули, доступные для определённой версии ядра, выполните следующую команду find. Не забудьте заменить "<kernel version>" на соответствующую версию ядра для поиска:

root #find /lib/modules/<kernel version>/ -type f -iname '*.o' -or -iname '*.ko' | less

Принудительная загрузка отдельных модулей ядра

Чтобы принудительно загрузить в систему модуль 3c59x.ko (драйвер для определённого семейства сетевых карт от 3Com), отредактируйте файл /etc/modules-load.d/network.conf и добавьте туда имя модуля.

root #mkdir -p /etc/modules-load.d
root #nano -w /etc/modules-load.d/network.conf

Обратите внимание, что суффикс в имени файла модуля .ko несущественен для механизма загрузки и не включается в файл:

ФАЙЛ /etc/modules-load.d/network.confПринудительная загрузка модуля 3c59x
3c59x

Продолжите установку с раздела Настройка системы.