код, работающий до того, как в системе вообще есть операционная системаthe code running before there's any operating system at all

Загрузчик: механика и практикаBootloader: mechanics and practice

Единственная задача загрузчика — найти образ ядра на диске, загрузить его в память и передать управление вместе с параметрами. На UEFI-системах это не «один загрузчик на диск», а список записей в энергонезависимой памяти материнской платы — отсюда и то, что Windows, и два разных дистрибутива Linux на разных физических дисках вполне уживаются в одном меню GRUB.A bootloader's only job is to find the kernel image on disk, load it into memory, and hand off control along with its parameters. On UEFI systems this isn't "one bootloader per disk" — it's a list of entries in the motherboard's non-volatile memory, which is exactly why Windows and two different Linux distros on separate physical disks can coexist in one GRUB menu just fine.

Что этоWhat it is

Загрузчик — код, которому прошивка материнской платы (BIOS или UEFI) передаёт управление первым, до появления ядра и вообще любого userspace. Его работа сводится к трём шагам: найти на диске образ ядра (и, как правило, initramfs — временный корневой образ с драйверами, нужными до монтирования настоящего корня), загрузить их в память, передать ядру управление вместе с параметрами командной строки. Всё, что происходит после этого — уже работа самого ядра и init-системы, не загрузчика.A bootloader is the code the motherboard's firmware (BIOS or UEFI) hands control to first, before the kernel or any userspace exists. Its job boils down to three steps: find the kernel image on disk (and usually initramfs — a temporary root image with the drivers needed before the real root gets mounted), load them into memory, and hand off control to the kernel along with its command-line parameters. Everything after that is the kernel's and the init system's job, not the bootloader's.

Два принципиально разных механизма поиска загрузчика существуют в зависимости от того, что за прошивка стоит на плате:Two fundamentally different bootloader-discovery mechanisms exist, depending on what firmware the board runs:

BIOS / MBRUEFI / GPT
где ищет загрузчикwhere it looks for the loaderпервые 446 байт первого диска (MBR) — сигнатура, а не файловая системаthe first 446 bytes of the first disk (the MBR) — a signature, not a filesystemфайл .efi на EFI System Partition (ESP), путь записан в NVRAM платыa .efi file on the EFI System Partition (ESP), the path is stored in the board's NVRAM
сколько загрузчиков одновременноhow many loaders at onceфактически один активный на диск — MBR крошечный, места под несколько нетeffectively one active per disk — the MBR is tiny, no room for more than oneсколько угодно — каждая запись в NVRAM независима и указывает на свой .efi-файлas many as you like — each NVRAM entry is independent and points to its own .efi file
Secure Bootне существует как концепция — BIOS не проверяет подписиdoesn't exist as a concept — BIOS doesn't check signaturesпрошивка проверяет цифровую подпись .efi-файла перед запускомthe firmware checks the .efi file's digital signature before running it

Windows 11 официально требует UEFI и включённый Secure Boot — это сразу задаёт контекст для мультизагрузки: на современном железе разговор идёт почти всегда именно про UEFI-сценарий.Windows 11 officially requires UEFI with Secure Boot enabled — which immediately frames the multiboot conversation: on modern hardware, this is almost always a UEFI scenario.

Как это устроено внутриHow it's built internally

01

NVRAM: список загрузчиков, а не один загрузчикNVRAM: a list of loaders, not one loader

UEFI хранит в NVRAM материнской платы упорядоченный список записей загрузки. Каждая запись — это метка, идентификатор диска и ESP-раздела на нём, и путь к конкретному .efi-файлу (например, \EFI\ubuntu\shimx64.efi или \EFI\Microsoft\Boot\bootmgfw.efi). Переменная BootOrder задаёт приоритет между записями. При включении прошивка читает BootOrder, берёт первую запись, монтирует указанный ESP и запускает найденный там .efi-файл. Именно поэтому «загрузчик» на UEFI-системе — это не физический объект на конкретном диске, а запись в энергонезависимой памяти самой платы, независимая от того, на каком физическом накопителе лежит фактический файл.UEFI stores an ordered list of boot entries in the motherboard's NVRAM. Each entry is a label, the disk and ESP identifier on it, and the path to a specific .efi file (say, \EFI\ubuntu\shimx64.efi or \EFI\Microsoft\Boot\bootmgfw.efi). The BootOrder variable sets priority among entries. On power-up, the firmware reads BootOrder, takes the first entry, mounts the referenced ESP, and runs the .efi file found there. This is exactly why a "bootloader" on a UEFI system isn't a physical object on one specific disk — it's an entry in the board's own non-volatile memory, independent of which physical drive the actual file happens to live on.

02

GRUB: две стадии, конфиг и менюtwo stages, a config, a menu

GRUB, установленный как .efi-файл на ESP, при запуске читает свой конфигурационный файл (/boot/grub/grub.cfg) — список пунктов меню, каждый со своим путём к ядру, initramfs и параметрами командной строки. Этот файл не редактируют руками напрямую: grub-mkconfig (он же update-grub в Debian/Ubuntu) генерирует его заново из скриптов в /etc/grub.d/ и настроек в /etc/default/grub — поэтому обновление ядра само по себе не появляется в меню GRUB без повторного запуска этой генерации. grub-install — отдельная, более редкая операция: она копирует сами файлы GRUB на ESP и создаёт (или обновляет) NVRAM-запись через efibootmgr — нужна один раз при установке или при восстановлении сломанной загрузки, а не при каждом обновлении ядра.GRUB, installed as a .efi file on the ESP, reads its config file (/boot/grub/grub.cfg) on startup — a list of menu entries, each with its own path to a kernel, an initramfs, and command-line parameters. This file isn't hand-edited directly: grub-mkconfig (aka update-grub on Debian/Ubuntu) regenerates it from scripts in /etc/grub.d/ and settings in /etc/default/grub — which is why a kernel update doesn't show up in the GRUB menu on its own without re-running that generation step. grub-install is a separate, rarer operation: it copies GRUB's own files onto the ESP and creates (or updates) the NVRAM entry via efibootmgr — needed once at install time or when recovering a broken boot, not on every kernel update.

03

chainloading: GRUB не грузит Windows сам — он передаёт эстафетуGRUB doesn't boot Windows itself — it hands off the baton

Windows не понимает формат меню GRUB и не умеет грузиться «через» него в обычном смысле. Вместо этого GRUB использует chainloading: находит на диске чужой .efi-файл (например, bootmgfw.efi — собственный загрузчик Windows) и просто передаёт ему управление, как если бы прошивка запустила его напрямую. С точки зрения Windows ничего необычного не произошло — она стартовала как обычно, просто на шаг раньше был GRUB, а не сразу прошивка. Это и есть механизм, которым один загрузчик может предложить в меню сразу несколько независимых, ничего не знающих друг о друге ОС.Windows doesn't understand GRUB's menu format and can't be booted "through" it in the usual sense. Instead, GRUB uses chainloading: it finds someone else's .efi file on disk (say, bootmgfw.efi — Windows's own loader) and simply hands it control, as if the firmware had launched it directly. From Windows's point of view nothing unusual happened — it started up as normal, just with GRUB running one step earlier instead of the firmware going straight there. This is exactly the mechanism that lets one bootloader offer several independent OSes in its menu that know nothing about each other.

Мультизагрузка: несколько ОС на разных дискахMultiboot: several OSes on separate disks

Да, это рабочий и распространённый сценарий: Windows 11 на одном физическом диске и два разных дистрибутива Linux на двух других — все три видны в одном меню GRUB. Механика опирается ровно на то, что описано выше: NVRAM хранит независимые записи, каждая указывает на свой .efi-файл на своей ESP, а GRUB одного из дистрибутивов становится «главным входом», из которого остальные системы либо запускаются напрямую (второй Linux — тоже через chainload на его загрузчик или прямую загрузку его ядра), либо через собственный chainloading на Windows.Yes, this is a working and common setup: Windows 11 on one physical disk and two different Linux distros on two others — all three showing up in one GRUB menu. The mechanics rest on exactly what's described above: NVRAM holds independent entries, each pointing to its own .efi file on its own ESP, and one distro's GRUB becomes the "main entry point," from which the other systems either boot directly (the second Linux — also via chainload to its loader, or a direct kernel boot) or via chainloading to Windows.

UEFI firmware — читает NVRAM BootOrder boot GRUB — disk 1 / ESP chainload chainload свой пункт bootmgfw.efi disk 2 / ESP — Windows 11 vmlinuz + initrd disk 1 — тот же дистрибутив grubx64.efi disk 3 / ESP — второй дистрибутив os-prober находит записи на disk 2 и disk 3 при update-grub
GRUB на диске 1 становится главным входом: часть пунктов меню запускает его же ядро, часть — chainload на найденные os-prober загрузчики Windows и второго дистрибутива на других дисках.GRUB on disk 1 becomes the main entry point: some menu items boot its own kernel, others chainload to the Windows and second-distro loaders that os-prober found on the other disks.

Практические нюансы, которые определяют, заработает ли это с первого раза:The practical details that decide whether this works on the first try:

на что влияетwhat it affects
порядок установкиinstall orderWindows, поставленная последней, самоуверенно делает свою NVRAM-запись приоритетной (иногда стирая чужие) — правильный порядок: сначала Windows, потом дистрибутивы Linux, тогда GRUB ставится последним и остаётся главным входомWindows installed last self-confidently makes its own NVRAM entry the priority (sometimes wiping others) — the correct order is Windows first, then the Linux distros, so GRUB installs last and stays the main entry point
os-proberутилита, которую update-grub запускает для сканирования всех примонтированных разделов на других дисках в поисках других ОС — без неё найденные вручную загрузчики придётся прописывать в grub.cfg самостоятельноthe utility update-grub runs to scan every mounted partition on other disks for other OSes — without it, discovered loaders have to be added to grub.cfg by hand
Secure BootGRUB на популярных дистрибутивах подписан не напрямую, а через shim — маленький загрузчик, подписанный Microsoft, который прошивка доверяет и который затем сам проверяет подпись GRUB своим встроенным ключом дистрибутиваGRUB on popular distros isn't signed directly, but via shim — a small loader signed by Microsoft, which the firmware trusts, and which then checks GRUB's signature itself using the distro's own embedded key
efibootmgr — посмотреть реальные NVRAM-записи и их порядок — see the actual NVRAM entries and their order
efibootmgr -v

# типичный вывод:
# BootOrder: 0000,0001,0002
# Boot0000* ubuntu       HD(1,GPT,...)/File(\EFI\ubuntu\shimx64.efi)
# Boot0001* fedora       HD(1,GPT,...)/File(\EFI\fedora\shimx64.efi)
# Boot0002* Windows Boot Manager  HD(1,GPT,...)/File(\EFI\Microsoft\Boot\bootmgfw.efi)
update-grub — пересобрать меню, включая найденные os-prober системы — rebuild the menu, including the systems os-prober found
# Debian/Ubuntu — сканирует диски, пишет grub.cfg заново
sudo update-grub

# на дистрибутивах без этого алиаса — то же самое действие
sudo grub-mkconfig -o /boot/grub/grub.cfg

Грабли и мифыGotchas & myths

«GRUB исчез после установки Windows» — не баг, а ожидаемое поведение установщика Windows"GRUB disappeared after installing Windows" — not a bug, it's the Windows installer's expected behavior

Установщик Windows не церемонится с чужими загрузчиками: он делает свою NVRAM-запись приоритетной, а иногда переписывает и саму ESP. Восстановление обычно сводится к загрузке с live-USB Linux и повторному grub-install — сами данные на дисках при этом не теряются, страдает только запись в NVRAM/ESP.Windows's installer doesn't play nice with other bootloaders: it makes its own NVRAM entry the priority, and sometimes overwrites the ESP itself. Recovery usually means booting a Linux live USB and re-running grub-install — the data on the disks itself isn't lost, only the NVRAM/ESP entry gets clobbered.

Обновил ядро — новая версия не появилась в меню GRUBUpdated the kernel — the new version doesn't show up in the GRUB menu

grub.cfg — сгенерированный файл, а не источник истины: он не обновляется автоматически при появлении нового образа ядра в /boot. На большинстве дистрибутивов пакетный менеджер сам вызывает update-grub при установке пакета ядра, но при ручной сборке ядра или нестандартной настройке этот шаг легко забыть — тогда в меню годами остаётся только старая версия.grub.cfg is a generated file, not a source of truth — it doesn't auto-update when a new kernel image appears in /boot. On most distros the package manager calls update-grub itself when installing a kernel package, but with a hand-built kernel or a nonstandard setup, this step is easy to forget — leaving only the old version in the menu for years.

os-prober монтирует все разделы диска как root — это осознанный компромисс безопасностиos-prober mounts every disk partition as root — a deliberate security trade-off

Чтобы найти чужие ОС, os-prober временно монтирует каждый обнаруженный раздел с правами root, включая разделы, чьё содержимое системе заранее неизвестно и не проверено. На системах, где на диске могут физически оказаться недоверенные или подменённые разделы (например, при работе с чужим или публичным железом), это осознанная причина отключать os-prober и прописывать пункты меню вручную.To find other OSes, os-prober temporarily mounts every discovered partition with root privileges, including partitions whose contents the system knows nothing about and hasn't vetted. On systems where an untrusted or tampered-with partition could physically end up on the disk (say, on shared or public hardware), that's a deliberate reason to disable os-prober and add menu entries by hand instead.

ТерминыTerms

MBR (Master Boot Record)
первые 446 байт диска на старой схеме разметки BIOS — не файловая система, а фиксированное место, где размещается первая стадия загрузчика. Ограниченный размер — причина, по которой полноценный GRUB на BIOS-системах ставится в две стадии.the first 446 bytes of a disk under the older BIOS partitioning scheme — not a filesystem, but a fixed spot where the bootloader's first stage lives. Its tiny size is why a full GRUB install on BIOS systems happens in two stages.
GPT (GUID Partition Table)
современная схема разметки диска, используемая вместе с UEFI — в отличие от MBR, поддерживает диски произвольного размера и произвольное число разделов, и именно на ней размещается ESP.the modern disk partitioning scheme used alongside UEFI — unlike MBR, it supports disks of any size and an arbitrary number of partitions, and it's what the ESP lives on.
ESP (EFI System Partition)
небольшой раздел, отформатированный в FAT32, где UEFI хранит .efi-файлы загрузчиков — общий для всех ОС на конкретном диске, но у каждой ОС там своя подпапка (\EFI\Microsoft\, \EFI\ubuntu\ и т.д.).a small FAT32-formatted partition where UEFI stores bootloaders' .efi files — shared by every OS on a given disk, but each OS gets its own subfolder there (\EFI\Microsoft\, \EFI\ubuntu\, and so on).
NVRAM
энергонезависимая память самой материнской платы, где UEFI хранит упорядоченный список записей загрузки (не на диске!) — именно здесь физически живёт информация о том, какие ОС видны в загрузочном меню и в каком порядке.the motherboard's own non-volatile memory, where UEFI keeps its ordered list of boot entries (not on any disk!) — this is exactly where the information about which OSes appear in the boot menu, and in what order, physically lives.
chainloading
передача управления от одного загрузчика к другому, независимому и ничего не знающему о первом — механизм, которым GRUB запускает загрузчик Windows или GRUB другого дистрибутива, не переписывая и не эмулируя его.handing control from one bootloader to another, independent one that knows nothing about the first — the mechanism GRUB uses to launch Windows's loader or another distro's GRUB, without rewriting or emulating it.
os-prober
утилита, сканирующая все обнаруженные разделы на предмет других ОС и автоматически добавляющая найденное в меню GRUB при update-grub. Монтирует разделы с правами root для проверки — источник компромисса между удобством и безопасностью.a utility that scans every discovered partition for other OSes and automatically adds what it finds to the GRUB menu during update-grub. It mounts partitions with root privileges to check them — the source of a convenience-vs-security trade-off.
Secure Boot
функция UEFI, проверяющая цифровую подпись каждого .efi-файла перед его запуском, чтобы не дать выполниться неподписанному или подменённому загрузочному коду. Windows 11 требует её включённой.a UEFI feature checking every .efi file's digital signature before running it, to stop unsigned or tampered boot code from executing. Windows 11 requires it enabled.
shim
маленький промежуточный загрузчик, подписанный Microsoft и потому доверенный прошивкой напрямую — сам проверяет подпись GRUB встроенным ключом конкретного дистрибутива, решая проблему «UEFI не доверяет GRUB напрямую» без необходимости каждому дистрибутиву договариваться с производителями железа отдельно.a small intermediate loader signed by Microsoft and therefore trusted directly by the firmware — it checks GRUB's own signature using a specific distro's embedded key, solving "UEFI doesn't trust GRUB directly" without every distro having to individually negotiate with hardware vendors.
initramfs
временный корневой файловый образ, загружаемый в память вместе с ядром — содержит драйверы и утилиты, нужные до того, как станет доступен настоящий корневой раздел (например, драйвер контроллера диска или модуль для расшифровки зашифрованного раздела).a temporary root filesystem image loaded into memory alongside the kernel — holds the drivers and tools needed before the real root partition becomes available (say, a disk controller driver or a module for decrypting an encrypted partition).