код, работающий до того, как в системе вообще есть операционная системаthe code running before there's any operating system at all
Единственная задача загрузчика — найти образ ядра на диске, загрузить его в память и передать управление вместе с параметрами. На 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.
Загрузчик — код, которому прошивка материнской платы (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 / MBR | UEFI / 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.
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.
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.
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.
Да, это рабочий и распространённый сценарий: 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.
Практические нюансы, которые определяют, заработает ли это с первого раза:The practical details that decide whether this works on the first try:
| на что влияетwhat it affects | |
|---|---|
| порядок установкиinstall order | Windows, поставленная последней, самоуверенно делает свою 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 Boot | GRUB на популярных дистрибутивах подписан не напрямую, а через 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 -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)
# Debian/Ubuntu — сканирует диски, пишет grub.cfg заново
sudo update-grub
# на дистрибутивах без этого алиаса — то же самое действие
sudo grub-mkconfig -o /boot/grub/grub.cfg
Установщик 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.
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 и прописывать пункты меню вручную.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.
\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).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.