Live linux with uefi

Загрузка Linux с VHD на компьютере с UEFI

В статье о возможности загружать Linux с VHD был предложен способ загружать Linux на машине с Windows без необходимости разбивать диск на разделы. Но было одно существенное ограничение: рассматривался только вариант загрузки BIOS, т.е. legacy-загрузки. Сейчас появляется всё больше устройств без поддержки режима legacy (например, многие ноутбуки, выпущенные в 2020 году). Поэтому в этой статье будет рассмотрена загрузка Linux с VHD на компьютерах с UEFI.

В чём отличия UEFI от BIOS, в интернете описано достаточно подробно, можно посмотреть, например, в этой статье. Для нас наиболее важным будет необходимость использовать разметку GPT для загрузочного диска и при создании разделов на VHD. Эксперименты проводились при отключенном Secure Boot. Не буду подробно останавливаться на моментах, описанных в предыдущей части. Как и ранее, предполагается, что читатель имеет представление о работе с консолью в Windows и Linux, умеет работать со стандартными системными утилитами, с ПО для виртуализации и т.п.

Предварительно отмечу еще ряд моментов. Можно было бы рассмотреть загрузку системы с внутреннего жесткого диска компьютера, но мы немного усложним задачу и будем загружать систему со съемного USB-диска, на котором будет располагаться VHD-файл. Все действия применимы и для внутреннего жесткого диска, а некоторые особенности будут отмечены в отдельном разделе.

Разработчики grub4dos недавно выпустили версию своего загрузчика для UEFI. При использовании версии grub4dos-for_UEFI-2021-02-10.7z на виртуальной машине у меня не возникло особых проблем при загрузке Linux с VHD, но на реальном железе при работе с тем же самым образом VHD была получена ошибка: Error 24: Attempt to access block outside of partition. С учетом простоты, с которой UEFI позволяет заменить загрузчик (простая замена файла), было решено воспользоваться загрузчиком grub2 из дистрибутива Debian debian-10.8.0-amd64-netinst.iso.

Установка Linux на VHD

Есть два ключевых отличия от варианта для BIOS:

1) в настройках VirtualBox необходимо установить опцию «Enable EFI»;

2) при установке Debian диск был разбит на два раздела: ESP (EFI system partition) размером

100 Мб, отформатированный в FAT32, и EXT4, занимающий всё оставшееся место.

Возможны и другие варианты разбиения. Раздел ESP при желании можно вынести за пределы VHD (он нам нужен только для загрузки на виртуальной машине), но все дальнейшие настройки сделаны исходя из того, что на VHD будет два раздела.

Подготовка Linux к загрузке с VHD

Скрипт из предыдущей статьи нам подходит для загрузки на локальном компьютере, где состав дисков меняется редко и заранее известно, на каком диске хранится VHD-файл. Но мы себе поставили новую цель: иметь возможность загружаться с USB-носителя на любом компьютере с любой конфигурацией жестких дисков. Загрузчики grub4dos и grub2 умеют искать файлы на доступных разделах и работать с UUID разделов. Мы этим воспользуемся при создании конфигурационного файла загрузчика, а пока добавим обработку UUID в скрипт loop_boot_vhd.

В скрипт добавлено считывание нового параметра loop_dev_uuid . В нём ожидается UUID раздела, на котором находится VHD-файл (путь к нему передается, как и раньше, в параметре loop_file_path ). Если задан loop_dev_uuid , то значение, переданное в loop_dev_path , игнорируется и заменяется на найденный по UUID путь к устройству. Кроме того, если диск подключен по USB, то он может определяться в системе с задержкой. Поэтому добавлено ожидание (до 10 секунд), во время которого выполняется ежесекундная проверка, появилось нужное устройство или нет. Мы ищем раздел по UUID с помощью утилиты findfs. Она не входит в образ initramfs, для её добавления необходимо создать скрипт /etc/initramfs-tools/hooks/copyfindfs (не забывайте делать скрипты исполняемыми).

Скрипт loop_boot_vhd необходимо расположить, как и ранее, в /etc/initramfs-tools/scripts/local-top/. После чего пересобрать initramfs, и VHD-образ можно считать готовым.

Настройка grub.cfg

В GRUB2 можно получить UUID раздела с помощью модуля probe, поэтому он должен быть в сборке. За основу была взята сборка GRUB2 с установочного диска Debian, для загрузки нам понадобятся следующие файлы:

Их необходимо скопировать на EFI-раздел USB-диска:

Далее необходимо создать конфигурационный файл \EFI\debian\grub.cfg.

В cfg-файле всё достаточно очевидно, только обращу внимание, что VHD-файл имеет название debefi.vhd, и система будет искать его в корне всех найденных разделов. Для исключения ошибок название файла необходимо сделать уникальным для загружаемой системы. Ну и «gpt2» используется потому, что Linux установлен на втором разделе внутри VHD.

Читайте также:  Драйвера для samsung n110 windows

Особенности настройки параллельно с Windows bootloader

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

Я опишу один из вариантов реализации выбора между загрузкой Windows и Linux: с помощью замены загрузчика на GRUB2. Загрузка EFI-систем по умолчанию начинается с файла \EFI\Boot\BOOTX64.EFI, в Windows 10 используется \EFI\Microsoft\Boot\bootmgfw.efi. Заменить загрузчик Microsoft на GRUB2 можно просто заменив файл. Необходимо быть внимательным, если сомневаетесь в получении результата с первого раза, то лучше сначала поэкспериментируйте на виртуальной машине. С помощью diskpart.exe надо подключить EFI-раздел Windows, на котором необходимо:

переименовать/перенести файл \EFI\Microsoft\Boot\bootmgfw.efi в \EFI\boot\ms.efi;

файл bootx64.efi из ISO-образа Debian переименовать в \EFI\Microsoft\Boot\bootmgfw.efi;

grubx64.efi разместить в \EFI\Microsoft\Boot\grubx64.efi;

probe.mod разместить в \EFI\debian\x86_64-efi\probe.mod;

ранее созданный grub.cfg скопировать в \EFI\debian\grub.cfg и добавить пункт для передачи управления загрузчику Microsoft:

Теперь при загрузке сначала будет появляться меню GRUB2 с выбором загрузки Windows («ms») или Linux («vhdUUID»).

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

Источник

Installation: UEFI

This is an alternate version of the basic install walkthrough, with additional information specific to installation on UEFI platforms.

More advanced installation methods for various specialized installs are also available on this Wiki.

UEFI support is built into the current Void Live images and UEFI-based installation should go fairly smoothly on well-behaved platforms. So where it was once necessary to use manual installation procedures to install Linux in UEFI mode (as it was in many distributions), today it should not as often be necessary for a basic (non-specialized) install.

Contents

Getting Started

LiveCD ISOs for the various flavors of Void can be downloaded from https://alpha.de.repo.voidlinux.org/live/current/ to be burned to a CD, mounted in a VM or copied for use on a Flash drive.

For further information regarding the live images and system requirements, see Live Images.

Installation

Boot your machine using the previously-created installation medium.

You can choose to run the live image from the media, or, if you have the resources available, you can load the contents of the limage into RAM. This option takes some time at the beginning but provides a quicker-overall installation procedure.

Once the live image has booted to a login prompt, log in as root using password voidlinux and then run:

Keyboard

Select the keymap for your keyboard; standard «qwerty» keybaords will generally use the «us» keymap.

Network

Select your primary network interface. If you use DHCP on your network, select that option, otherwise the installer will prompt for IP address, netmask and gateway.

Source

Choose whether you want to install from a local source (the packages that are included on the ISO) or from the network (in which case packages are downloaded from the Void remote repositories). Installing from the network allows you to install the most up-to-date packages available from the official repositories. Note that installing from local will also install any desktop installed on the disk (e.g. xfce).

Hostname

Set a hostname for your computer remembering the best practice that hostnames should be all lower case, with no spaces.

Locale

Configure your default locale settings; this will be used to set the libc locale.

Timezone

Select your timezone from the list of standard timezone options.

RootPassword

Enter and confirm the password used for the root account on your new Void installation. The password will not be shown on screen.

UserAccount

Choose a login (default void) and a descriptive name for that login (default Void User). Then enter and confirm the password for this default user. Finally you may chose to modify the group memberships for the user or go with the defaults.

BootLoader

Determine whether you’d like to use the installer to automatically install GRUB2 to the EFI system partition, or choose none if you’d like to install/configure an EFI loader manually after completing the installation process.

Partition

If you partitioned your disk outside of the Void installer(fdisk, cfdisk), you may skip the step. You should nevertheless read through this section for information regarding specific UEFI requirements to make sure your layout is compliant.

Читайте также:  Windows 10 raspberry iso

Void does not provide an automatic/preset partition scheme, so you will need to create this manually using cfdisk. However, in the case of UEFI, there are some special considerations that need to be made.

First, while UEFI systems are supposed to support MBR-based partition tables, the reality may be less predictable and the newer GPT scheme is going to be a better choice, especially if you have one of the larger Advanced Format disks. Use GPT.

Second, you need to create an EFI system partition, generally the first one. It does not need to be large; it is common to create one between 200MB and 1GB. When you create this partition in cfdisk, you need to change the type from the default «Linux» to the type appropriate to the ESP:

  • For GPT disks, change the type to EFI System .
  • For MBR (DOS) disks, create a primary partition and change the type to ef (EFI). [Not recommended]

You can then partition up the remaining free space as you choose for your Linux installation. See Disks#Partitioning for further information.

Filesystems

Create the filesystems used to populate the partitions you just created. Choose your filesystem type, specify the mountpoint and create the filesystem, if necessary, for each partition you mean to modify.

Once finished, select Back to return to the main installer menu. For additional information, see Disks#Filesystems.

Review Settings

Before installing, its generally a good idea to review the installation settings. Arrow right from the main menu to select settings and use to review.

Install

This step of the installer creates the filesystems specified in the previous step, then downloads all of the base packages (if configured to install via Network) and copies them to the target partition/partitions configured in the previous steps. After that, the installer generates an initramfs and installs GRUB2 to the EFI System partition.

After the installation is successfully completed, you can reboot into your new Void Linux install!

Post-Installation

Once you boot into your new Void installation, continue to Post-installation for further configuration tips.

Notes/Issues

Notes on Grub2 EFI Loader installation.

Grub2 possesses the ability to install an EFI loader to the EFI System Partition, as well as to modify the BootOrder variable in the system firmware. This works on most well-behaved UEFI imlementations. However, there are reports of a couple of issues on some systems/motherboards:

  • The BootOrder variable is not updated.
  • The BootOrder is not saved/followed by the system.

If the BootOrder variable fails to be updated, then the system will not boot the newly-installed Void system without some extra configuration.

To confirm that BootOrder has been updated before your final reboot, you can run the command efibootmgr with no arguments. The output should include something like this:

See the man page for efibootmgr for more information on the capabilities and use of this program. If you see the option «void_grub» and it is listed first in BootOrder, then the variables have been successfully updated, and you can try to reboot. If not, keep reading.

In cases where BootOrder is either not updated, or not saved/followed after you reboot, then you should try copying grubx64.efi to the common default EFI loader location. You’ll need to mount your EFI partition, and we’ll assume it’s on /mnt/. (In your installed Void system, the mount point would normally be /boot/efi/)

On 32-bit firmware it should be

You may then need to set the default boot disk in your computer’s setup utility, but Void/Grub2 should boot correctly after this.

Note that you can boot your system back into the LiveCD to perform this operation if you were unable to boot to your Void Installation.

Notes on Partitioning

Cfdisk does not give me a choice of partition table type.

If the disk has already been initialized, cfdisk will continue with the partition table layout already present.

If your disk was previously partitioned with the MBR scheme, you will see the text «label: dos» near the top of the cfdisk screen. At this point, you will want to back out of the installer and run cfdisk manually with the «-z» option to start with an uninitialized disk layout, where you will then be prompted for the label type and continue with a new partition layout.

Читайте также:  Cant mount file linux

If the disk was previously using GPT, then you will see the text «Label: gpt» near the top of the cfdisk screen.

Multiple Partitions

It is common practice to put various subdirectories of / onto their own mounted partition, and there often good reasons for doing so.

However, it is important to note, because of Void’s adoption of a more modern method for laying out the file system (known as the «/usr merge»), you must not try to place /usr on a separate partition. When you attempt to do so, the installer will inform you that this is not supported in Void. For information as to the «whats» and «whys» of the /usr merge, please see https://www.freedesktop.org/wiki/Software/systemd/TheCaseForTheUsrMerge/.

Separate Boot Partition: While there are very few cases where this would be useful today, some people will opt to create a separate /boot partition, creating a nested mount scenario, where you have one partition mounted at /boot/ and a second partition mounted at /boot/efi.

This creates a problem in the installer where it may fail at grub-install, as the /boot/efi directory isn’t created on the /boot/ partition. To avoid this particular failure the options are as follows:

  • In the Filesystems stage, make sure to assign the EFI System Partition last. As long as /boot is assigned before /boot/efi, then it will be mounted before the creation of the /boot/efi/ mountpoint, and no trouble will arise.
  • Don’t use a separate /boot/ partition. One of the few cases where it might be desirable would be when having an encrypted root, but unencrypted /boot. Various ways of booting encrypted systems and the reasoning behind each is a rather large discussion of its own.
    • To the author’s knowledge, Grub is the only EFI loader that, at the time of this writing, can open LUKS/LVM containers itself, so the use of other loaders would require the kernel and initrd to be on an unencrypted filesystem.
    • Another way to deal with this would be to use the ESP as /boot/ itself, but there are issues. Grub will need to be installed manually, as the installer assumes the ESP exists at /boot/efi/ and you will have to override this.
    • Lastly, you could use your preferred EFI loader to control all boot options, but allow it to chainload Grub which can handle booting your encrypted Linux installation. Obviously this does not avoid the use of Grub, so if that is one’s goal, then this is not a satisfying option.

This can actually be an issue for any nested mount scenario, though such schemes aren’t that common, and may not need to be configured at install-time.

Platform-specific notes

Bitness — Note that UEFI loader bitness (i.e. 32-bit or 64-bit) must match that of the firmware. So 64-bit firmware only runs a 64-bit loader (bootx64.efi), while 32-bit firmware only runs a 32-bit loader (bootia32.efi).

However, the loader can switch the CPU mode, so it is possible to boot a 64-bit kernel from a 32-bit EFI loader (given support in the loader), provided the CPU is actually x86_64 architecture. The reverse is also true (32-bit EFI kernel booted by a 64-bit EFI loader).

This applies only to firmware bitness. It is still not possible, for obvious reasons, to load a 64-bit OS on a 32-bit CPU.

Working Platforms

This procedure has been tested on the following systems: (Please add any systems/motherboards where this procedure has been successfully followed)

QEMU/KVM virtual machine on 64-bit OVMF firmware image (64-bit guest, 64-bit host) — x86_64 Void Install CD. BootOrder updated successfully, BootOrder obeyed by system.

QEMU/KVM virtual machine on 32-bit OVMF firmware image (32/64-bit guests, 64-bit host) — i686 and x86_64 Void Install CD. BootOrder updated successfully, BootOrder obeyed by system.

ASROCK Z77 Extreme4 (Intel Z77 chipset, 64-bit firmware) — x86_64 Void Install CD. BootOrder updated successfully, BootOrder obeyed by system.

Less-than-working Platforms

The following platforms have had issues with this procedure: (Please add any systems/motherboards that have issues related to EFI installation, as well as workarounds, if any.)

32-bit Firmware

Current ISOs have full support for loading both 32- and 64-bit OSes on both 32- and 64-bit firmwares. Tweaking the install script or adding packages to the install environment should no longer be necessary.

Источник

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