Translations:Handbook:X86/Blocks/Bootloader/2/ru
Есть несколько очень небольших исключений из этого стандарта 64-битной прошивки UEFI, а именно: несколько ранних моделей Apple Mac и некоторые планшеты Dell на базе Intel Atom имели поддержку 32-битной прошивки UEFI. Подавляющее большинство читателей никогда не столкнется с 32–битной прошивкой UEFI в природе. По этой причине 32–битная прошивка UEFI не рассматривается в Руководстве.
Выбор загрузчика
Когда ядро Linux настроено, системные утилиты установлены и конфигурационные файлы отредактированы, настало время для установки последней важной части системы Linux: загрузчика.
Загрузчик отвечает за запуск ядра Linux во время загрузки — без него система не будет знать, как действовать после нажатия кнопки питания.
Для , мы описали настройку либо GRUB, либо LILO для систем на базе DOS/Legacy BIOS, и GRUB или efibootmgr для UEFI-систем.
В этом разделе Руководства было сделано разделение между установкой пакета (emerge) загрузчика и установкой загрузчика на системный диск. Термин установка пакета (emerge) будет использоваться для установки пакета в систему с помощью пакетного менеджера Portage. Термин установка загрузчика на системный диск будет означать копирование файлов загрузчика или физическое изменение соответствующих разделов диска для того, чтобы активировать и подготовить к работе загрузчик для следующей перезагрузки.
По умолчанию: GRUB
По умолчанию, большинство систем Gentoo на данный момент используют GRUB (из пакета sys-boot/grub), который является прямым продолжателем GRUB Legacy. Без дополнительных настроек GRUB поддерживает старые системы BIOS ("pc"). С небольшими настройкам, которые нужно выполнить до сборки, GRUB может поддерживать более чем полутора десятка дополнительных платформ. Для получения более подробной информации смотрите раздел Предварительные требования статьи GRUB.
Emerge
Если используется старая материнская плата, BIOS которой поддерживает только таблицу разделов MBR, для установки GRUB не нужно никаких дополнительных настроек:
root #
emerge --ask --verbose sys-boot/grub
Заметка для пользователей UEFI: запущенная команда выведет включенные значения в переменной GRUB_PLATFORMS, перед компиляцией. Если используется более новая UEFI-совместимая материнская плата, пользователям сперва нужно убедиться, что GRUB_PLATFORMS=""
включено (обычно это уже сделано по умолчанию). Если это не так, добавьте GRUB_PLATFORMS=""
в файл /etc/portage/make.conf до компиляции GRUB, что позволит собрать пакет с поддержкой EFI:
root #
echo 'GRUB_PLATFORMS=""' >> /etc/portage/make.conf
root #
emerge --ask sys-boot/grub
Если GRUB был каким-то образом был установлен до включения GRUB_PLATFORMS=""
, то добавьте строку (из примера выше) в make.conf, после чего повторно переопределите зависимости для для набора пакетов world с помощью emerge --update --newuse
:
root #
emerge --ask --update --newuse --verbose sys-boot/grub
GRUB теперь установлен в системе, но еще не активирован.
Установка
Далее установим необходимые для GRUB файлы в каталог /boot/grub/ с помощью команды grub-install. Если предположить, что первый диском (тот, с которого будет загружаться система) является /dev/sda, то одна из следующих команд сделает это:
DOS/Устаревшие BIOS системы
При использовании BIOS:
root #
grub-install /dev/sda
При использовании UEFI
Убедитесь, что системный раздел EFI был смонтирован перед запуском grub-install. grub-install может установить файл GRUB EFI () в неправильном каталоге без каких-либо сообщений, о том, что использовался неправильный каталог.
For UEFI systems:
root #
grub-install --efi-directory=
Installing for x86_64-efi platform. Installation finished. No error reported.
Upon successful installation, the output should match the output of the previous command. If the output does not match exactly, then proceed to Debugging GRUB, otherwise jump to the Configure step.
Optional: Secure Boot
To successfully boot with secure boot enabled the signing certificate must either be accepted by the UEFI firmware, or shim must be used as a pre-loader. Shim is pre-signed with the third-party Microsoft Certificate, accepted by default by most UEFI motherboards.
How to configure the UEFI firmware to accept custom keys depends on the firmware vendor, which is beyond the scope of the handbook. Below is shown how to setup shim instead. Here it is assumed that the user has already followed the instructions in the previous sections to generate a signing key and to configure portage to use it. If this is not the case please return first to the Kernel installation section.
The package sys-boot/grub installs a prebuilt and signed stand-alone EFI executable if the secureboot USE flag is enabled. Install the required packages and copy the stand-alone grub, Shim, and the MokManager to the same directory on the EFI System Partition. For example:
root #
emerge sys-boot/grub sys-boot/shim sys-boot/mokutil sys-boot/efibootmgr
root #
cp /usr/share/shim/BOOTX64.EFI /EFI/Gentoo/shimx64.efi
root #
cp /usr/share/shim/mmx64.efi /EFI/Gentoo/mmx64.efi
root #
cp /usr/lib/grub/grub-x86_64.efi.signed /EFI/Gentoo/grubx64.efi
Next register the signing key in shims MOKlist, this requires keys in the DER format, whereas sbsign and the kernel build system expect keys in the PEM format. In the previous sections of the handbook an example was shown to generate such a signing PEM key, this key must now be converted to the DER format:
root #
openssl x509 -in /path/to/kernel_key.pem -inform PEM -out /path/to/kernel_key.der -outform DER
The path used here must be the path to the pem file containing the certificate belonging to the generated key. In this example both key and certificate are in the same pem file.
Then the converted certificate can be imported into Shims MOKlist, this command will ask to set some password for the import request:
root #
mokutil --import /path/to/kernel_key.der
When the currently booted kernel already trusts the certificate being imported, the message "Already in kernel trusted keyring." will be returned here. If this happens, re-run the above command with the argument --ignore-keyring added.
Next, register Shim with the UEFI firmware. In the following command, boot-disk
and boot-partition-id
must be replaced with the disk and partition identifier of the EFI system partition:
root #
efibootmgr --create --disk /dev/boot-disk --part boot-partition-id --loader '\EFI\Gentoo\shimx64.efi' --label 'GRUB via Shim' --unicode
Note that this prebuilt and signed stand-alone version of grub reads the grub.cfg from a different location then usual. Instead of the default /boot/grub/grub.cfg the config file should be in the same directory that the grub EFI executable is in, e.g. /EFI/Gentoo/grub.cfg. When sys-kernel/installkernel is used to install the kernel and update the grub configuration then the GRUB_CFG environment variable may be used to override the usual location of the grub config file.
For example:
root #
grub-mkconfig -o /EFI/Gentoo/grub.cfg
Or, via installkernel:
/etc/env.d/99grub
GRUB_CFG=/EFI/Gentoo/grub.cfg
root #
env-update
The import process will not be completed until the system is rebooted. After completing all steps in the handbook, restart the system and Shim will load, it will find the import request registered by mokutil. The MokManager application will start and ask for the password that was set when creating the import request. Follow the on-screen instructions to complete the import of the certificate, then reboot the system into the UEFI menu and enable the Secure Boot setting.
Отладка GRUB
When debugging GRUB, there are a couple of quick fixes that may result in a bootable installation without having to reboot to a new live image environment.
In the event that "EFI variables are not supported on this system" is displayed somewhere in the output, it is likely the live image was not booted in EFI mode and is presently in Legacy BIOS boot mode. The solution is to try the removable GRUB step mentioned below. This will overwrite the executable EFI file located at /EFI/BOOT/BOOTX64.EFI. Upon rebooting in EFI mode, the motherboard firmware may execute this default boot entry and execute GRUB.
- Important
Если grub-install возвращает ошибку наподобииCould not prepare Boot variable: Read-only file system
, необходимо перемонтировать специальную точку монтирования efivars в режим чтения-записи:root #
mount -o remount,rw,nosuid,nodev,noexec --types efivarfs efivarfs /sys/firmware/efi/efivars
root #
mount -o remount,rw,nosuid,nodev,noexec --types efivarfs efivarfs /sys/firmware/efi/efivars
This is caused by certain non-official Gentoo environments not mounting the special EFI filesystem by default. If the previous command does not run, then reboot using an official Gentoo live image environment in EFI mode.
Некоторые производители материнских плат поддерживают только каталог /efi/boot/ для расположения файла .EFI в системном разделе EFI (ESP). Установщик GRUB может выполнить эту операцию автоматически, если использовать параметр --removable
. Убедитесь, что ESP смонтирован до запуска следующих команд. Предполагая, что ESP смонтирован в /boot (как было предложено ранее), выполните:
root #
grub-install --target= --efi-directory= --removable
Это создает каталог по умолчанию, определенный спецификацией UEFI, а затем скопирует файл в каталог EFI «по умолчанию», определенный той же спецификацией.
Настройка
Далее, нужно сгенерировать конфигурационный файл GRUB на основе настроек пользователя, указанных в файле /etc/default/grub и сценариях /etc/grub.d. В большинстве случаев ничего не нужно настраивать, так как GRUB автоматически определяет, какое ядро есть для загрузки (самый высокий приоритет у /boot/) и какая файловая система у rootfs. Здесь также можно добавить параметры ядра в /etc/default/grub, используя переменную GRUB_CMDLINE_LINUX.
Для создания окончательной конфигурации GRUB, запустите команду grub-mkconfig:
root #
grub-mkconfig -o /boot/grub/grub.cfg
Generating grub.cfg ... Found linux image: /boot/vmlinuz- Found initrd image: /boot/initramfs-genkernel-- done
Вывод команды должен содержать по крайней мере один образ Linux, так как он необходим для загрузки системы. Если используется initramfs или ядро создавалось с помощью genkernel, также должен быть указан правильный образ initrd. Если это не так, перейдите в /boot/ и проверьте содержимое, используя команду ls. Если файлы действительно отсутствуют, вернитесь к инструкции по настройке и установке ядра.
Для обнаружения других операционных систем на других диска можно использовать утилиту os-prober. Она может обнаруживать Windows 7, 8.1, 10, и другие дистрибутивы Linux. Для таких систем с двойной загрузкой необходимо установить пакет sys-boot/os-prober и затем перезапустить команду grub-mkconfig (как было показано выше). Если появятся проблемы, полностью перечитайте статью GRUB до того, как спрашивать у сообщества Gentoo поддержки.
Alternative 1: systemd-boot
Another option is systemd-boot, which works on both OpenRC and systemd machines. It is a thin chainloader and works well with secure boot.
Emerge
To install systemd-boot, enable the boot USE flag and re-install sys-apps/systemd (for systemd systems) or sys-apps/systemd-utils (for OpenRC systems):
/etc/portage/package.use/systemd-boot
sys-apps/systemd boot
sys-apps/systemd-utils boot
root #
emerge --ask sys-apps/systemd
Or
root #
emerge --ask sys-apps/systemd-utils
Installation
Now, install the systemd-boot loader to the EFI System Partition:
root #
bootctl install
Make sure the EFI system partition has been mounted before running bootctl install.
When using this bootloader, before rebooting, verify that a new bootable entry exists using:
root #
bootctl list
The kernel command line for new systemd-boot entries is read from /etc/kernel/cmdline or /usr/lib/kernel/cmdline. If neither file is present, then the kernel command line of the currently booted kernel is re-used (/proc/cmdline). On new installs it might therefore happen that the kernel command line of the live CD is accidentally used to boot the new kernel. The kernel command line for registered entries can be checked with:
root #
bootctl list
If no new entry exists, ensure the sys-kernel/installkernel package has been installed with the systemd and systemd-boot USE flags enabled, and re-run the kernel installation.
For the distribution kernels:
root #
emerge --ask --config sys-kernel/gentoo-kernel
For a manually configured and compiled kernel:
root #
make install
When installing kernels for systemd-boot, no root= kernel command line argument is added by default. On systemd systems that are using an initramfs users may rely instead on systemd-gpt-auto-generator to automatically find the root partition at boot. Otherwise users should manually specify the location of the root partition by setting root= in /etc/kernel/cmdline as well as any other kernel command line arguments that should be used. And then reinstalling the kernel as described above.
Optional: Secure Boot
When the secureboot USE flag is enabled, the systemd-boot EFI executable will be signed by portage automatically. Furthermore, bootctl install will automatically install the signed version.
To successfully boot with secure boot enabled the used certificate must either be accepted by the UEFI firmware, or shim must be used as a pre-loader. Shim is pre-signed with the third-party Microsoft Certificate, accepted by default by most UEFI motherboards.
How to configure the UEFI firmware to accept custom keys depends on the firmware vendor, which is beyond the scope of the handbook. Below is shown how to setup shim instead. Here it is assumed that the user has already followed the instructions in the previous sections to generate a signing key and to configure portage to use it. If this is not the case please return first to the Kernel installation section.
root #
emerge --ask sys-boot/shim sys-boot/mokutil sys-boot/efibootmgr
root #
bootctl install --no-variables
root #
cp /usr/share/shim/BOOTX64.EFI /EFI/systemd/shimx64.efi
root #
cp /usr/share/shim/mmx64.efi /EFI/systemd/mmx64.efi
Shims MOKlist requires keys in the DER format, whereas sbsign and the kernel build system expect keys in the PEM format. In the previous sections of the handbook an example was shown to generate such a signing PEM key, this key must now be converted to the DER format:
root #
openssl x509 -in /path/to/kernel_key.pem -inform PEM -out /path/to/kernel_key.der -outform DER
The path used here must be the path to the pem file containing the certificate belonging to the generated key. In this example both key and certificate are in the same pem file.
Then the converted certificate can be imported into Shims MOKlist:
root #
mokutil --import /path/to/kernel_key.der
When the currently booted kernel already trusts the certificate being imported, the message "Already in kernel trusted keyring." will be returned here. If this happens, re-run the above command with the argument --ignore-keyring added.
And finally we register Shim with the UEFI firmware. In the following command, boot-disk
and boot-partition-id
must be replaced with the disk and partition identifier of the EFI system partition:
root #
efibootmgr --create --disk /dev/boot-disk --part boot-partition-id --loader '\EFI\systemd\shimx64.efi' --label 'Systemd-boot via Shim' --unicode '\EFI\systemd\systemd-bootx64.efi'
The import process will not be completed until the system is rebooted. After completing all steps in the handbook, restart the system and Shim will load, it will find the import request registered by mokutil. The MokManager application will start and ask for the password that was set when creating the import request. Follow the on-screen instructions to complete the import of the certificate, then reboot the system into the UEFI menu and enable the Secure Boot setting.
Альтернатива 2: efibootmgr
На UEFI-системах, с прошивкой UEFI (другими словами, основным загрузчиком), можно напрямую управлять загрузочными записями UEFI. Таким системам не требуется дополнительный (также известный как вторичный) загрузчик, такой как GRUB, который помогает загрузить систему. Учитывая сказанное, использование дополнительного EFI-загрузчика типа GRUB имеет смысл лишь в том, чтобы расширить функциональность UEFI во время загрузки. Использование efibootmgr подойдёт больше для тех, кто хочет получить больше минимализма (хотя это сложнее) при загрузке системы; использование GRUB проще для большинства пользователей, так как он предлагает более гибкий подход для загрузки UEFI-систем.
System administrators who desire to take a minimalist, although more rigid, approach to booting the system can avoid secondary bootloaders and boot the Linux kernel as an EFI stub.
Помните, sys-boot/efibootmgr — это не загрузчик; это средство для взаимодействия с прошивкой UEFI и обновления её настроек, для того, чтобы можно было загрузить установленное ядро Linux с дополнительными параметрами (если необходимо) или организовать несколько загрузочных записей. Это взаимодействие осуществляется через переменные EFI (что требует поддержки переменных EFI со стороны ядра).
Перед тем, как продолжить, обязательно прочитайте всю статью EFI stub. В ядре должны быть включены определенные параметр, чтобы ядро могло загрузится напрямую с системной прошивкой UEFI. Это может потребовать пересборки ядра. Также взгляните на статью efibootmgr.
It is also a good idea to take a look at the efibootmgr article for additional information.
Повторим еще раз, efibootmgr не является обязательным требованием для загрузки из UEFI. Ядро Linux может загружаться сразу же, а дополнительные параметры ядра могут быть встроены в само ядра (в конфигурации ядра есть параметр CONFIG_CMDLINE, который позволяет пользователю определить параметры загрузки). Даже initramfs может быть встроен в ядро.
Установите efibootmgr:
/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
Then reinstall installkernel, create the directory and reinstall the kernel:
root #
emerge --ask sys-kernel/installkernel
root #
mkdir -p
For distribution kernels:
root #
emerge --ask --config sys-kernel/gentoo-kernel{,-bin}
For manually managed kernels:
root #
make install
Создайте каталог и затем скопируйте в него ядро, назвав его :
root #
mkdir -p
root #
cp /boot/vmlinuz-* /
Install the efibootmgr package:
root #
emerge --ask sys-boot/efibootmgr
Далее, сообщите прошивке UEFI создать загрузочную запись и называть её "Gentoo", в которой будет свежее ядро с EFI stub:
root #
efibootmgr --create --disk /dev/sda --part 1 --label "gentoo" --loader "\"
Символ обратной косой черты (\), применяемый для разделения каталогов, является обязательным при использовании определений UEFI.
Если используется файловая система инициализации, размещаемая в оперативной памяти (initramfs), добавьте соответствующий загрузочный параметр:
root #
efibootmgr --create --disk /dev/sda --part 1 --label "gentoo" --loader "\" --unicode "initrd=\initramfs.img"
Additional kernel command line options may be parsed by the firmware to the kernel by specifying them along with the initrd=... option as shown above.
После внесения изменений и перезагрузки системы появится загрузочная запись под именем «gentoo».
Unified Kernel Image
If installkernel was configured to build and install unified kernel images. The unified kernel image should already be installed to the EFI/Linux directory on the EFI system partition, if this is not the case ensure the directory exists and then run the kernel installation again as described earlier in the handbook.
To add a direct boot entry for the installed unified kernel image:
root #
efibootmgr --create --disk /dev/sda --part 1 --label "gentoo" --loader "\EFI\Linux\gentoo-x.y.z.efi"
Other Alternatives
For other options that are not covered in the Handbook, see the full list of available bootloaders.