Uefi boot manager linux

EFISTUB

The Linux kernel supports EFISTUB booting which allows EFI firmware to load the kernel as an EFI executable. The option is enabled by default on Arch Linux kernels, or if compiling the kernel one can activate it by setting CONFIG_EFI_STUB=y in the Kernel configuration. See The EFI Boot Stub for more information.

With EFISTUB a kernel can be booted directly by a UEFI motherboard or indirectly using a boot loader. Using a boot loader is recommended if you have multiple kernel/initramfs pairs and your motherboard’s UEFI boot menu is not easy to use.

Contents

Preparing for EFISTUB

First, you must create an EFI system partition and choose how it is mounted. See EFI system partition#Mount the partition for all available ESP mounting options.

Booting EFISTUB

Using a boot manager

This article or section needs language, wiki syntax or style improvements. See Help:Style for reference.

There are several UEFI boot managers which can provide additional options or simplify the process of UEFI booting — especially if you have multiple kernels/operating systems. See Arch boot process#Boot loader for more information.

Using UEFI directly

UEFI is designed to remove the need for an intermediate bootloader such as GRUB. If your motherboard has a good UEFI implementation, it is possible to embed the kernel parameters within a UEFI boot entry and for the motherboard to boot Arch directly. You can use efibootmgr or UEFI Shell v2 to modify your motherboard’s boot entries.

efibootmgr

To create a boot entry with efibootmgr that will load the kernel:

or create a boot entry with efibootmgr and hibernation on swap partition:

Where /dev/sdX and Y are the drive and partition number where the ESP is located. Change the root= and resume= parameters to reflect your Linux root and swap partitions, see kernel parameters for supported device name formats, and persistent block device naming for how to obtain the corresponding value. If omitted, then the first partition on /dev/sda is used as the ESP.

Note that the -u / —unicode argument in quotes is just the list of kernel parameters, so you may need to add additional parameters (e.g. for suspend to disk or microcode).

After adding the boot entry, you can verify the entry was added properly with:

To set the boot order:

Where XXXX is the number that appears in the output of efibootmgr command against each entry.

efibootmgr with .efi file

This article or section is a candidate for merging with systemd-boot#Preparing a unified kernel image.

If using cryptboot AUR and sbupdate-git AUR to generate your own keys for Secure Boot and sign the initramfs and kernel then create a bootable .efi image, efibootmgr can be used directly to boot the .efi file:

See efibootmgr(8) for an explanation of the options. To include microcode in a unified kernel image, concatenate it with the initramfs and use the resultant image with objtool.

Some UEFI implementations make it difficult to modify the NVRAM successfully using efibootmgr. If efibootmgr cannot successfully create an entry, you can use the bcfg command in UEFI Shell v2 (i.e., from the Arch Linux live iso).

Читайте также:  Windows language pack language interface pack

First, find out the device number where your ESP resides with:

In this example, 1 is used as the device number. To list the contents of the ESP:

To view the current boot entries:

To add an entry for your kernel, use:

Where N is the location where the entry will be added in the boot menu. 0 is the first menu item. Menu items already existing will be shifted in the menu without being discarded.

Add the necessary kernel options by creating a file on your ESP:

In the file, add the boot line. For example:

Press F2 to save and then F3 to exit.

Add these options to your previous entry:

Repeat this process for any additional entries.

To remove a previously added item do:

kesboot

You can also simplify and automate the work with EFISTUB using a script from the kesboot-git AUR package. It also contains a pacman hook that can add and remove EFI variables during actions with packages.

First, install the package, and then configure the /etc/kesboot.conf file:

The package also contains a program for the initial configuration of the EFI boot. After mounting the ESP directory, run

More tools

This section is being considered for removal.

Some of the tools above, and more, are briefly discussed in rEFInd#Tools.

Using UEFI Shell

If you do not want to create a permanent boot entry it is possible to launch the kernel from UEFI Shell as if it is a normal UEFI application:

In this case, the kernel parameters are passed as normal parameters to the launched EFISTUB kernel file.

To avoid needing to remember all of your kernel parameters every time, you can save the executable command to a shell script such as archlinux.nsh on your UEFI System Partition, then run it with:

Using a startup.nsh script

Some UEFI implementations do not retain EFI variables between cold boots (e.g. VirtualBox before version 6.1) and anything set through the UEFI firmware interface is lost on poweroff.

The UEFI Shell Specification 2.0 establishes that a script called startup.nsh at the root of the ESP partition will always be interpreted and can contain arbitrary instructions; among those you can set a bootloading line. Make sure you mount the ESP partition on /boot and create a startup.nsh script that contains a kernel bootloading line. For example:

This method will work with almost all UEFI firmware versions you may encounter in real hardware, you can use it as last resort. The script must be a single long line. Sections in brackets are optional and given only as a guide. Shell style linebreaks are for visual clarification only. FAT filesystems use the backslash as path separator and in this case, the backslash declares the initramfs is located in the root of the ESP partition. Only Intel microcode is loaded in the booting parameters line; AMD microcode is read from disk later during the boot process; this is done automatically by the kernel.

Troubleshooting

Cannot create a new boot entry with efibootmgr

This article or section is a candidate for moving to Unified Extensible Firmware Interface#Troubleshooting.

Some kernel and efibootmgr version combinations might refuse to create new boot entries. This could be due to lack of free space in the NVRAM. You can try deleting any EFI dump files:

Or, as a last resort, boot with the efi_no_storage_paranoia kernel parameter. You can also try to downgrade your efibootmgr install to version 0.11.0. This version works with Linux version 4.0.6. See the bug discussion FS#34641, in particular the closing comment, for more information.

Читайте также:  Средства windows обеспечения безопасности информации

Newly created boot entries are removed

The factual accuracy of this article or section is disputed.

Some motherboards may remove boot entries after a couple of boots. This could be due to lack of free space in the NVRAM. To prevent this from occurring, it may help to reduce the amount of Linux boot entries being added by efibootmgr by minimizing your entry creation process, as well as reducing the amount of automatic drive boot entries by the Compatibility Support Module (CSM) by disabling it from your UEFI settings.

EFISTUB does not work on some Dell systems

Several generation Dell BIOSes are wrongly passing the arguments to the bootloader, thus making EFISTUB parse a null command line which normally means unbootable system (see the complete linux-efi thread).

A workaround has been found since Linux 5.10 to correct this behavior (see this commit ). For Linux See also

Источник

systemd-boot (Русский)

systemd-boot, ранее известный как gummiboot — это простой UEFI менеджер загрузки, который исполняет настроенные EFI образы. Запись по умолчанию выбирается с помощью настроенного шаблона (glob) или меню на экране. Включен в пакет systemd , который устанавливается на системе Arch по умолчанию.

Прост в настройке, но способен только на запуск исполняемых EFI файлов, таких как ядро Linux EFISTUB, UEFI Shell, GRUB, Windows Boot Manager.

Contents

Установка

Загрузка в режиме EFI

  1. Убедитесь, что вы загружены в режиме UEFI.
  2. Проверьте доступны ли EFI переменные.
  3. Корректно примонтируйте Системный Раздел EFI (ESP). В этой статье esp используется для обозначения точки монтирования.

Загрузка в режиме BIOS

Вы с таким же успехом можете установить systemd-boot, если загружаетесь в режиме BIOS. Тем не менее, от вас всё равно требуется сообщить прошивке запускать EFI файл systemd-boot при загрузке:

  • у вас есть работающий EFI shell где-нибудь.
  • ваш интерфейс прошивки предоставляет вам соответствующий способ настройки EFI файла, который будет загружен во время загрузки.

Если вы имеете такую возможность, процесс установки будет проще: перейдите в ваш EFI shell или интерфейс настройки вашей прошивки и измените EFI файл по умолчанию вашей машины на esp/EFI/systemd/systemd-bootx64.efi ( или systemd-bootia32.efi если у вас 32 битная системная прошивка).

Обновлениe

В отличие от предыдущего отдельного пакета gummiboot, который автоматически обновляется с помощью post_install скрипта, обновления systemd-boot теперь должны производиться пользователем вручную. Однако, эта процедура может быть автоматизирована с использованием pacman hooks.

Вручную

systemd-boot (bootctl(1)) предполагает, что ваш Системный Раздел EFI примонтирован в /boot .

Если ESP не примонтирован в /boot , опцией —path= можно явно указать точку монтирования, например:

Автоматически

AUR (Русский) пакет systemd-boot-pacman-hook AUR предоставляет хук Pacman для автоматизации процесса обновления. Установка этого пакета добавит hook, который будет выполняться при каждом обновлении пакета systemd .

В качестве альтернативы, вы можете разместить следующий pacman hook в каталоге /etc/pacman.d/hooks/:

Настройка

Базовая настройка

Базовая конфигурация хранится в файле esp/loader/loader.conf и состоит из трех опций:

  • default – выбираемая по умолчанию запись (без суффикса .conf ); можно использовать подстановку, например arch-*
  • timeout – задержка меню в секундах. Если таймаут не задан, то меню будет отображаться, только если удерживать клавишу Space (другие клавиши тоже могут работать) при загрузке.
  • editor — следует ли включить редактор параметров ядра. 1 (по умолчанию) — включить, 0 — отключить; Поскольку пользователь может добавить init=/bin/bash для обхода пароля администратора и получить полный доступ, настоятельно рекомендуется установить эту опцию в 0 .

Добавление загрузочных записей

bootctl ищет элементы для загрузочного меню в esp/loader/entries/*.conf – каждый найденный файл должен содержать точно одну загрузочную запись. Возможными опциями являются:

  • title – название операционной системы. Обязательная.
  • version – версия ядра, отображаемая только если существуют несколько записей с одинаковым названием. Не обязательная.
  • machine-id – идентификатор машины из /etc/machine-id , отображаемый только если существуют несколько записей с одинаковым названием и одинаковой версией. Не обязательная.
  • efi – EFI программа для запуска, относительно вашего ESP ( $esp ); например, /vmlinuz-linux . Либо это, либо linux (смотрите ниже) является обязательным.
  • options – опции командной строки для передачи EFI приложению. Не обязательная, но вам нужно будет передать как минимум initrd=efipath и root=dev если загружаете Linux.
Читайте также:  Как устранить ошибку windows script host

Для Linux вы можете задать linux path-to-vmlinuz и initrd path-to-initramfs ; это автоматически преобразуется в efi path и options initrd=path – этот синтаксис поддерживается только для удобства и не имеет различий по функциональности.

Установки со стандартной корневой директорией

Вот пример записи для корневого раздела без LVM или LUKS:

Пожалуйста, обратите внимание, что в вышеприведённом примере PARTUUID / PARTLABEL идентифицируют GPT раздел, а это не то же самое, что UUID / LABEL , которые идентифицируют файловую систему. Использование PARTUUID / PARTLABEL бывает полезным, потому что они инвариантны (то есть неизменяемы), если вы переформатируете раздел в другую файловую систему или если по какой-то причине изменятся обозначения /dev/sd*. Также оно может быть полезно, если у вас нет файловой системы на разделе (или вы используете LUKS, который не поддерживает метки LABEL ).

Установки с LVM корневой директорией

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

Замените на актуальные названия VG и LV (например, root=/dev/mapper/volgroup00-lvolroot ). Кроме того, вместо них можно использовать UUID:

Обратите внимание, что root=UUID= используется вместо root=PARTUUID= , который используется для корневых разделов без LVM или LUKS.

Установки с зашифрованной корневой директорией

Ниже приведен пример конфигурационного файла для зашифрованного корневого раздела (DM-Crypt / LUKS) с использованием encrypt mkinitcpio (Русский) hook:

В этом примере используется UUID; если хотите, можете заменить UUID на PARTUUID . Вы можете также заменить /dev путь на регулярный UUID. mapped-name — название, которое вы желаете использовать. Смотрите Dm-crypt/System configuration#Boot loader.

Если вы используете LVM, ваша опция cryptdevice будет выглядеть следующим образом:

Вы также можете добавить другие EFI приложения, такие как \EFI\arch\grub.efi .

Установка корневого подраздела btrfs

При загрузке с подраздела Btrfs (Русский) в роли корневого, добавьте к строке options rootflags=subvol= . В примере ниже, корневой раздел монтируется как btrfs подраздел с именем ‘ROOT’ (например, mount -o subvol=ROOT /dev/sdxY /mnt ):

Если это невозможно сделать, то это приведет к ошибке: ERROR: Root device mounted successfully, but /sbin/init does not exist.

Установки с ZFS корневой директорией

В случае загрузки из ZFS dataset, добавьте zfs= к строке options . Здесь в корневом dataset установлено значение ‘zroot/ROOT/default’:

When booting off of a ZFS dataset ensure that it has had the bootfs property set with zpool set bootfs= .

EFI Shells или другие EFI приложения

В случае, если вы установили EFI Shells или другие EFI приложения в ESP, вы можете использовать следующие фрагменты:

Поддержка гибернации

Редактор параметров ядра с защитой паролем

В качестве альтернативы можете установить systemd-boot-password AUR который поддерживает password опцию базовой конфигурации. Используйте sbpctl generate для генерации значения для этой опции.

Установка systemd-boot-password следующей командой:

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

Клавиши в загрузочном меню

В меню используются следующие клавиши:

  • Вверх/Вниз — выбор записи
  • Enter — загрузить выбранную запись
  • d — выбрать загрузочную запись по умолчанию (хранится в энергонезависимой EFI переменной)
  • -/T — уменьшить таймаут (хранится в энергонезависимой EFI переменной)
  • +/t — увеличить таймаут (хранится в энергонезависимой EFI переменной)
  • e — редактировать командную строку ядра. Не имеет эффекта, если опция конфигурации editor установлена в 0 .
  • v — показать версию gummiboot и UEFI
  • Q — выйти
  • P — отобразить текущую конфигурацию
  • h/? — помощь

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

  • l — Linux
  • w — Windows
  • a — OS X
  • s — EFI Shell
  • 1-9 — порядковый номер записи

Решение проблем

Создание записи вручную с помощью efibootmgr

Если команда bootctl install не сработала, вы можете создать загрузочную EFI запись самостоятельно с помощью утилиты efibootmgr :

Источник

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