GRUB2

From Gentoo Wiki
Jump to:navigation Jump to:search
This page is a translated version of the page GRUB and the translation is 37% complete.
Outdated translations are marked like this.

GRUB2 (GRand Unified Bootloader versión 2) a veces nombrado como ""GRUB2"" y comúnmente referido como ""GRUB"", es un cargador múltiple secundario capaz de cargar kernels desde una variedad de sistemas de archivos en la mayoría de las arquitecturas de sistema. GRUBS soporta PC BIOS, PC EFI, IEEE 1275 (Firmware Abierto), SPARC, y MIPS Lemote Yeeloong.

GRUB2 tiene una base de código totalmente independiente respecto a GRUB Legacy y presenta una nueva sintaxis tipo intérprete de órdenes para características avanzadas similar al de las consolas.

Para una primera aproximación, vea GRUB2 Quick Start.

Si se va a realizar la migración desde GRUB Legacy a GRUB2, leer la migración de GRUB2.

Instalación

Requisitos previos

Para controlar en qué plataformas se instalará GRUB, definir la variable GRUB_PLATFORMS en make.conf. La arquitectura amd64 incluye un perfil por defecto que funciona en la mayoría de sistemas.

ARCHIVO /etc/portage/make.confEjemplo de configuración de la variable GRUB_PLATFORMS para plataformas EMU, EFI y PC
GRUB_PLATFORMS="emu efi-32 efi-64 pc"

Las siguientes plataformas son compatibles dependiendo de la CPU de destino:

Platform Target
i386 ia64 mips mipsel powerpc sparc64 x86_64
ARC No No No Yes No No No
Coreboot Yes No No No No No 32-bit
EFI Yes Yes No No No No Yes
EMU Yes Yes Yes Yes Yes Yes Yes
IEEE 1275 (Open Firmware) Yes No No No Yes Yes 32-bit
Loongson No No No Yes No No No
Multiboot Yes No No No No No 32-bit
QEMU Yes No No No No No 32-bit
QEMU-MIPS No No Yes No No No No
PC Yes No No No No No 32-bit
Nota
Cada vez que se ajusten los valores de la variable GRUB_PLATFORMS, se necesita hacer emerge de nuevo de GRUB para construir el binario modificado. Asegúrese de utilizar las opciones --newuse --deep tal y como se muestra en la sección sobre emerge más abajo.

Los perfiles amd64 habilitan el soporte por defecto para la funcionalidad (U)EFI. Cuando se utiliza un sistema basado en BIOS, definir la variable GRUB_PLATFORMS a pc para evitar dependencias no necesarias.

Ajustes USE

USE flags for sys-boot/grub GNU GRUB boot loader

device-mapper Enable support for device-mapper from sys-fs/lvm2
doc Add extra documentation (API, Javadoc, etc). It is recommended to enable per package instead of globally
efiemu Build and install the efiemu runtimes
fonts Build and install fonts for the gfxterm module
libzfs Enable support for sys-fs/zfs
mount Build and install the grub-mount utility
nls Add Native Language Support (using gettext - GNU locale utilities)
sdl Add support for Simple Direct Layer (media library)
test Enable dependencies and/or preparations necessary to run tests (usually controlled by FEATURES=test but can be toggled independently)
themes Build and install GRUB themes (starfield)
truetype Build and install grub-mkfont conversion utility
verify-sig Verify upstream signatures on distfiles

Emerge

Para instalar GRUB utilice la sintaxis normal de emerge:

root #emerge --ask --newuse --deep sys-boot/grub:2

Software adicional

Opcionalmente, puede instalar la utilidad os-prober (proporcionada por el paquete sys-boot/os-prober) para que GRUB2 explore la presencia de otros sistemas operativos al ejecutar la orden grub-mkconfig. En la mayoría de los casos, esto permitirá a GRUB2 detectar automáticamente otros sistemas operativos incluyendo Windows 7, 8.1, 10, otras distribuciones de Linux, etc.

root #emerge --ask --newuse sys-boot/os-prober

Las instalaciones de GRUB (y opcionalmente sys-boot/os-prober) no "activan" automáticamente la operación del cargador de arranque. Esta acción solo instala el cargador del "software" en el sistema operativo. Para instalar el cargador de arranque para el propio sistema (para usarlo para arrancar el sistema), deben realizarse algunos pasos adicionales, que se tratan en la sección Configuración.

Instalar el cargador de arranque

La instalación de GRUB2 como cargador de arranque del sistema dependerá de cómo se pretende arrancar el sistema (a través de BIOS o UEFI) y de cómo está particionado el disco en el que se va a instalar el cargador (con un esquema de particionado MBR o GPT).

Este artículo trata las siguientes situaciones:

Seleccione las instrucciones de instalación adecuadas para su sistema.

UEFI con GPT

Advertencia
Even though 64-bit x86 processors ("x86-64" or "x64") support running legacy 32-bit software, it is not possible for an EFI implementation to do the same. A 64-bit EFI will not be able to run 32-bit .efi loaders! It should be noted that some early 64-bit-capable systems, i.e. systems with an x64 processor (an x86 processor featuring AMD64 or Intel 64), used a 32-bit implementation of EFI, like some early MacBooks (Intel Core 2) and some pre-2010 Windows computers. In such cases, even though the processor is 64-bit, (U)EFI is implemented as 32-bit software making efi-32 the proper EFI target because, likewise, a 32-bit EFI cannot run 64-bit .efi loaders.
Nota
If the UEFI-CSM is used, refer to BIOS with MBR or BIOS with GPT instead. CSM stands for "Compatibility Support Module" and is a BIOS emulation, making the UEFI behave like a BIOS. In the firmware setup it is often called "Legacy Mode" or "Compatibility Mode". UEFI-CSM has always been optional and was phased out on mainstream systems (such as PCs) in 2020.

Particionar para UEFI con GPT

Para arrancar UEFI GPT con GRUB2, el sistema debe tener una partición EFI dedicada que contenga un sistema de ficheros FAT.

UEFI systems boot from efi files on their EFI System Partition (ESP). The EFI System Partition can be just about any size, with implementation considerations in mind.

The EFI System Partition can contain just the bootloader, or the bootloader along with support files. Typically, /boot contains the kernel along with additional EFI support files, while /boot/efi contains the actual EFI files, which tend to be small.

Nota
The EFI System Partition can be made at either /boot or /boot/efi but it tends to be simpler to just use /boot. Using /boot/efi allows files like the kernel and bootloader support files to be stored on a separate partition and filesystem or the root filesystem itself; the later requires that GRUB can access the root filesystem and read the required files, which may not always be possible (like with root filesystem encryption).

If generating a standalone EFI System Partition, under /boot/efi, a size of 128MB is reasonable, this allows multiple efi files to be stored.

Nota
There is little harm in keeping backups of working efi files, which could still be booted if a new one is installed.

Cree la partición utilizando la herramienta elegida de particionado. Las herramientas gdisk (sys-apps/gptfdisk) y parted (sys-block/parted) encajan muy bien para este propósito. Cuando se utiliza la utilidad gdisk, asegúrese de marcar la partición con el tipo EF00.

Partitioning with fdisk
Nota
As described in Preparing the disks Handbook section, /boot partition is used for ESP, which is formatted as FAT32. Depending on the preferred system configuration, a separate partition for /boot may be desirable, e.g. in the case of filesystem encryption.

If using fdisk to partition the boot partition, start by opening the disk for modification, in this example /dev/sda is used:

root #fdisk /dev/sda
Welcome to fdisk (util-linux 2.38.1).
Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.

A new partition table can be created using "g":

Command (m for help):g
Created a new GPT disklabel (GUID: 4AB36B49-BAAD-D544-AC45-E3154565018D).

A new partition can be created using "n":

Command (m for help):n
 
Partition number (1-128, default 1): 1
First sector (2048-121012190, default 2048): 
Last sector, +/-sectors or +/-size{K,M,G,T,P} (2048-121012190, default 121010175): +128M
 
Created a new partition 1 of type 'Linux filesystem' and of size 128 MiB.

Once the partition is created, the ESP and Boot flags must be set, this can be done by setting the partition type to EFI System Partition. This can be accomplished with the t option, to change the partition type, and then selecting 1, which corresponds to the EFI System Partition type:

Command (m for help):t
 
Selected partition 1
Partition type or alias (type L to list all): 1
Changed type of partition 'Linux filesystem' to 'EFI System'.

Finally, the changes can be saved by running w:

Command (m for help):w
 
The partition table has been altered.
Calling ioctl() to re-read partition table.
Syncing disks.

With the partition created, it must be formatted to use the FAT32 filesystem, this can be done with:

root #mkfs.fat -F 32 -n efi-boot /dev/sda1
root #mkdir /boot/efi

To determine the partition uuid, or PARTUUID of the new partition, the following command can be use:

user $lsblk -o name,partuuid
lsblk -o name,partuuid
NAME         PARTUUID
sdd          
└─sd1       20f3d6cc-9781-3640-9232-0f5a8c662a60

To create a fstab entry for this partition:

ARCHIVO /etc/fstabAñadir entrada de montaje de /boot/efi
/dev/sda1		/boot/efi	vfat		noauto,noatime	1 2
root #mount /boot/efi
Nota
La siguiente opción es útil para establecer la variable GRUB_PLATFORMS en /etc/portage/make.conf. Ayudará a GRUB2 a determinar qué opciones utilizar a la hora de detectar el objetivo EFI adecuado. Para los sistemas UEFI de 32 bits utilice efi-32. Para 64-bit utilice efi-64.
Importante
Con el fin de realizar una correcta instalación de GRUB2, el directorio EFI debe estar montado y el módulo del núcleo efivars debe estar cargado antes de ejecutar la orden grub-install para que esta se complete con éxito.

Installing GRUB for EFI

Asegúrese de que la ubicación del directorio /boot está disponible —si este directorio utiliza una partición separada, asegúrese de que se monta—:

root #mount /boot

Ejecute la orden grub-install para copiar los ficheros relevantes a /boot/grub. Esto debería instalar GRUB en /boot/grub, copiar la imagen del núcleo a /boot/efi/EFI/gentoo/grubx64.efi, y llamar a efibootmgr para añadir una entrada de arranque.

root #grub-install --efi-directory=/boot/efi
Installation finished. No error reported.

La órden anterior asume que una Partición EFI del sistema (ESP) vfat está montada en /boot/efi. Si la ESP está montada directamente en /boot, use --efi-directory=/boot.

Nota
By default, GRUB installs targeting the type of system which the command is executed on. If another system type is used, the --target option can be used to specify it.
Nota
The --removable option can be used to install GRUB to /boot/EFI/BOOT/BOOTX64.EFI, potentially enhancing compatibility, as this location is often checked by default.

BIOS con MBR

Nota
Cuando se tiene pensado configurar el sistema para un arranque dual con Microsoft Windows, asegúrese de que el propio sistema no tenga un firmware UEFI. En estos casos, aún cuando dichos sistemas se inicien en la modalidad 'legacy BIOS' , Microsoft Windows se negará a arrancar.

Asegúrese de que la ubicación del directorio /boot está disponible —si este directorio utiliza una partición separada, asegúrese de que se monta—:

root #mount /boot

Ejecute la orden grub-install para copiar los ficheros relevantes a /boot/grub. En la plataforma PC, esta orden también instala una imagen de arranque en el Master Boot Record (MBR) o en el sector de arranque de una partición. Si todo va bien, después de ejecutar la orden grub-install se obtendrá una salida como esta:

root #grub-install /dev/sda
Installation finished. No error reported.

grub-install acepta una opción --target para definir la arquitectura de la CPU y la plataforma del sistema. Si no se especifica, grub-install intentará adivinar los valores adecuados; en un sistema amd64/x86 usará i386-pc por defecto. grub-install también acepta una opción --boot-directory que le dice al instalador de GRUB2 en qué directorio debe buscar los ficheros de arranque de grub2. Por defecto, será el directorio /boot presente, pero dicha opción es útil cuando se está tratando de mover una partición root.

Particionar para BIOS con MBR

Asegúrese de dejar suficiente espacio libre antes de la primera partición. Inicie la primera partición en el sector 2048, dejando, al menos, 1 MiB de espacio en el disco para el registro de arranque maestro (MBR). Se recomienda (aunque no es obligatorio) crear una partición adicional para GRUB llamada BIOS boot partition. Esta partición solo necesita ser definida, pero no formateada. Esto es necesario solamente si el sistema es posteriormente migrado a una tabla de particiones GPT. Cuando nos mantenemos con MBR, no es necesario.

Si el usuario está siguiendo las instrucciones de instalación de Gentoo, esta partición BIOS boot partition ya estará disponible.

BIOS con GPT

Advertencia
GPT was not designed for the legacy BIOS, yet with the protective MBR it includes a provision for it. Also, dual-boot with legacy operating systems designed to be booted from MBR, which is the de facto standard on computers with a BIOS, will need to access their partitions through the MBR, which can be accomplished by creating GPT/MBR hybrid partitions. This technique, however, has specific constraints.

On a BIOS system with GPT partitioning, GRUB relies on a partition called "BIOS boot partition". This partition is not formatted with a file system, instead grub-install will copy parts of the boot loader to it. The "BIOS boot partition" is not the same partition as a /boot partition.

Nota
See also What is the BIOS boot partition? in the x86 Handbook.

Si una partición /boot es necesaria, comience por el montaje de la partición /boot:

root #mount /boot

Si todo va bien, después de ejecutar la orden grub-install se obtendrá una salida como esta:

root #grub-install /dev/sda
Installation finished. No error reported.

grub-install acepta una opción --target para definir la arquitectura de la CPU y la plataforma del sistema. Si no se especifica, grub-install intentará adivinar los valores adecuados; en un sistema amd64/x86 usará i386-pc por defecto. grub-install también acepta una opción --boot-directory que le dice al instalador de GRUB2 en qué directorio debe buscar los ficheros de arranque del GRUB2. Por defecto, será el directorio /boot presente, pero es útil cuando se trata de mover una partición root.

grub-install also accepts a --boot-directory option to tell the GRUB installer which directory to look in for the boot files. This defaults to the current /boot but is useful when trying to move a root partition.

Dual-boot con Windows

Nota
Cuando se tiene pensado configurar el sistema para un arranque dual con Microsoft Windows, asegúrese de que el propio sistema no tenga un firmware UEFI. Aún cuando dichos sistemas se inicien en la modalidad 'legacy BIOS' , Microsoft Windows se negará a arrancar. Además, los sistemas Microsoft Windows anteriores no tienen soporte para GPT. En estos casos es posible utilizar un enfoque MBR-GPT híbrido, ver Hybrid partition table.
Nota
Traditionally x86-PCs used a BIOS as firmware. After the switch to (U)EFI on PCs (around 2005) there used to be a BIOS emulation called 'Compatibility Support Module' (CSM), PCs were therefore still compatible with existing operating systems. On mainstream PCs the EFI-CSM has been phased out since 2020. Even before 2020 some (U)EFI implementations, such as servers, lacked the CSM completely. 'Legacy BIOS mode' is therefore no longer available on modern UEFI systems. UEFI in its native boot mode demands the GUID Partition Table (GPT), a pre-installed operating system will therefore already be using a GPT partitioning scheme.

An already installed Windows will refuse to boot when the boot mode or the partitioning scheme is changed. Also, older Windows systems don't support GPT (or EFI) at all, demanding that a BIOS or the EFI-CSM along with an MBR must be used. If Windows supports EFI it can be re-installed in the native UEFI mode and the GPT partitioning scheme, as well as Linux; see section UEFI with GPT.

Hybrid partitioning between GPT and MBR creates both a valid GPT partition table and a valid MBR partition table at the same time, but limits the total number of hybrid partitions to four because of the four primary partition limit of the MBR. Since the ESP (the EFI System Partition holding the EFI bootloaders) takes up one partition this leaves only three shared partitions between MBR and GPT. When one partition is used for Windows and one for Linux, there is only one additional hybrid partition possible, like a separate Linux /boot partition or a shared data partition between the two operating systems.

Advertencia
Normally, a GPT partition table will always also create an MBR partition table which holds only one partition spanning over the whole disk. This will ensure that older software doesn't mistake the disk as 'empty'. The MBR with its protective partition is therefore called a 'protecive MBR' and is part of the GPT specification. By defining hybrid partitions, this protective feature of the GPT is sacrificed! Legacy software will no longer see used space when analyzing the hybrid MBR. Software that is unaware of the GPT and only sees the MBR may mistake undefined disk space as unused and empty space. Data written outside the defined MBR partitions may cause data loss to the underlying GPT partitions!

If there are two physical disks available to the system, a great solution is to have one disk use the GPT and the other the MBR partitioning scheme. Normally, the Windows installation uses only one partition as 'system partition' and 'boot partition', called 'drive C:'. When in BIOS mode the initial partition for booting, the 'system partition', must be an MBR partition. This applies to every Windows version since Windows XP and includes Windows 10. Since Windows Vista (actually Windows XP x64 Edition) the Microsoft operating system supports accessing GPT partitions. The solution is to relocate the 'system partition' part of an installation to the MBR partitioned disk, and convert the 'boot partition' (the one containing \WINDOWS) into a GPT partitioned disk. Windows can thereafter access all the GPT partitions on the one disk, and will continue to use the MBR partitions (or hybrid partitions) on the disk containing the 'system partition'. The Windows installation (containing \WINDOWS) would be a GPT partition, even when booted in BIOS mode. Windows 11 no longer supports BIOS/CSM/MBR mode.

Particionar para BIOS con GPT

Cuando una tabla de particiones GPT está presente en el sistema, una pequeña partición llamada BIOS boot partition (con tipo EF02, que es diferente de la partición EFI System Partition (ESP) que tiene el tipo EF00) tendrá que estar disponible. 1 MiB será suficiente para que funcione, pero 2-4 MiB es una opción segura. Esta partición BIOS boot partition sostendrá la etapa 2 del cargador de arranque. BIOS boot partition no necesita ser formateada con un sistema de ficheros; la orden grub2-install sobrescribe cualquier sistema de ficheros preexistente con el suyo propio.

Importante
La partición de arranque de la BIOS («BIOS boot partition») no es la misma partición que se monta, comúnmente, en /boot. La partición /boot y la partición de arranque de la BIOS son diferentes particiones y deben manejarse por separado. La partición de arranque de la BIOS no se monta con regularidad en el sistema (es decir, no debe ser definida en /etc/fstab). La partición /boot se puede montar con regularidad, sin problemas, por lo que puede estar presente en el fichero /etc/fstab.

Para configurar una partición como BIOS boot partition utilice la herramienta de línea de órdenes parted (sys-block/parted) escribiendo lo que sigue (cambie 1 por el número que corresponda a su partición, la cual se marcará como BIOS boot partition):

(parted)set 1 bios_grub on

Con la utilidad cgdisk del paquete sys-apps/gptfdisk, esto se logra estableciendo el tipo de partición como 0xEF02 y etiquetándola como gptbios.

No se necesita una partición del sistema EFI, pero sería prudente asegurarse de que la partición de arranque BIOS es lo suficientemente grande como para ser convertida en una de ellas, dado que la placa base del sistema puede actualizarse posteriormente a una placa UEFI.

La salida de abajo resulta de pulsar la tecla p con la utilidad gdisk en un disco particionado con GPT, válido tanto para una BIOS boot partition [0xEF02], como para una partición EFI [0xEF00]:

root #gdisk /dev/sdc
GPT fdisk (gdisk) version 0.8.1
 
Partition table scan:
  MBR: protective
  BSD: not present
  APM: not present
  GPT: present
 
Found valid GPT with protective MBR; using GPT.
 
Command (? for help): p
Disk /dev/sdc: 976773168 sectors, 465.8 GiB
Logical sector size: 512 bytes
Disk identifier (GUID): AA369F4D-37A4-4C0D-A357-DC24B99A6337
Partition table holds up to 128 entries
First usable sector is 34, last usable sector is 976773134
Partitions will be aligned on 2048-sector boundaries
Total free space is 2014 sectors (1007.0 KiB)
 
Number  Start (sector)    End (sector)  Size       Code  Name
   1            2048       828377087   395.0 GiB   8E00  Linux LVM
   2       828377088       891291647   30.0 GiB    0700  Microsoft basic data
   3       891291648       975177727   40.0 GiB    0700  Microsoft basic data
   4       975177728       976754687   770.0 MiB   8300  Linux filesystem
   5       976754688       976756735   1024.0 KiB  EF02  BIOS boot partition
   6       976756736       976773134   8.0 MiB     EF00  EFI System
 
Command (? for help): 
Nota
El prefijo hexadecimal 0x no necesita ser introducido para GPT cuando se utiliza fdisk.

Utilizando la misma configuración, la utilidad parted proporciona una salida con una sintaxis un poco diferente:

root #parted /dev/sdc
GNU Parted 3.0
Using /dev/sdc
(parted) print
...
Sector size (logical/physical): 512B/512B
Partition Table: gpt
  
Number  Start   End    Size    File system  Name                  Flags
 1      1049kB  424GB  424GB                Linux LVM             lvm
 2      424GB   456GB  32.2GB               Microsoft basic data
 3      456GB   499GB  42.9GB               Microsoft basic data
 4      499GB   500GB  807MB   ext2         Linux filesystem
 5      500GB   500GB  1049kB               BIOS boot partition   bios_grub
 6      500GB   500GB  8396kB               EFI System            boot
  
(parted)

Crear particiones con gdisk es sencillo para los usuarios que ya están familiarizados con la utilidad de particionado fdisk. Después de iniciar gdisk, escriba n (para nueva) en el menú principal, proporcione los sectores de inicio y fin (si es necesario) y, a continuación, establezca el tipo de partición EF00 para una EFI system partition.

Los usuarios que han seguido las instrucciones de instalación de Gentoo ya tendrán el diseño de las particiones adecuado para este propósito.

Firmware abierto (IEEE 1275) en PowerPC

Véase aquí.

Install on encrypted partition

If the whole disk is encrypted, including /boot, extra steps need to be taken, to allow GRUB to decrypt and mount the device.

The device-mapper USE flag needs to be set when emerging thee GRUB package. Then the sys-fs/cryptsetup package needs to be installed. The partition needs to be encrypted as luks1 partition type.

After installing GRUB on the device, depending on the way the kernel is setup, initramfs might need to be modified in order for the system to boot completely. If a distribution kernel is installed, Dracut will be installed on the system as well and can be used to finish the configuration.

Configuración

Hay dos aspectos importantes ha tener en cuenta en la configuración de GRUB:

Fichero principal de configuración

El guión grub-mkconfig se utiliza para generar un fichero de configuración de grub. Este utiliza los guiones contenidos en /etc/grub.d/* junto con el fichero de configuración /etc/default/grub para generar el fichero /boot/grub/grub.cfg final —el único fichero de configuración utilizado por el propio GRUB2—.

Fichero Formato ¿Recomendada su edición? Descripción
/usr/sbin/grub-mkconfig Guión de intérprete de órdenes POSIX No Se instala como parte del paquete sys-boot/grub:2. Lance este guión para generar /boot/grub/grub.cfg una vez se hayan configurados los ficheros descritos abajo.
/boot/grub/grub.cfg Guión de intérprete de órdenes GRUB2 No El fichero generado por grub-mkconfig. El guión intérprete incluido en GRUB2 evalúa este fichero y no soporta necesariamente todas las órdenes o sintaxis POSIX. Lea la referencia sobre los guiones en el manual de GRUB para conocer las características soportadas. Tenga en cuenta que las modificaciones a este fichero no serán persistentes hasta la próxima vez que se lance grub-mkconfig.
/etc/grub.d/* Guiones de intérprete de órdenes POSIX Tal vez Cada guión en /etc/grub.d/* con el bit de ejecución activado se evalúa en secuencia y su salida estándar se concatena para formar el fichero final /boot/grub/grub.cfg (o el fichero que se haya indicado a grub-mkconfig a través de la opción -o). Estos guiones utilizan el intérprete de órdenes actual del sistema y por tanto puede utilizar cualquier sintaxis soportada. Idealmente deberían ser guiones compatibles POSIX y el guión de salida debe ser compatible con el intérprete GRUB2. Puede ser necesario deshabilitar o añadir guiones. Por ejemplo, para añadir entradas de menú que no se pueden generar de forma automática.
/boot/grub/custom.cfg Guión de GRUB2 shell Tal vez El guión /etc/grub.d/41_custom referenciará a este fichero para su lectura en el inicio si éste existe. Este fichero ofrece un lugar en el que se pueden añadir entradas adicionales u órdenes y no requiere la regeneración del fichero principal grub.cfg.
/etc/default/grub Guión de intérprete de órdenes POSIX En la mayoría de los casos, este es el único fichero que se debe modificar de forma directa. Se utiliza principalmente para asignar variables utilizadas en los guiones de /etc/grub.d para generar un fichero de configuración que funcione. Lea el artículo sobre GRUB variables de configuración o la referencia oficial para conocer las variables soportadas.

| /usr/sbin/grub-mkconfig || POSIX shell script || style="background-color: #F2DEDE; color: black; vertical-align: middle; text-align: left; " class="cell-no" | No || Installed as part of the sys-boot/grub:2 package. Run this script to generate /boot/grub/grub.cfg after configuring the files described below. |-

| /boot/grub/grub.cfg || GRUB shell script || style="background-color: #F2DEDE; color: black; vertical-align: middle; text-align: left; " class="cell-no" | No || The file generated by grub-mkconfig. This file is evaluated by GRUB's built-in script interpreter and doesn't necessarily support all POSIX commands or syntax. See the scripting reference in the GRUB manual for supported features. Be aware that modifications to this file won't persist to the next time grub-mkconfig is run. |-

| /etc/grub.d/* || POSIX shell scripts || style="background: #FFF176; color: black; vertical-align: middle; text-align: left; " class="cell-partial" | Maybe || Each script under /etc/grub.d/* that has its execute bit set is evaluated in sequence, and the stdout is concatenated to form the final /boot/grub/grub.cfg (or whatever file is given to the grub-mkconfig -o option). These scripts use the current system shell and therefore can use any supported syntax. Ideally they should be POSIX-compatible scripts, and the output script must be compatible with the GRUB interpreter. It may be necessary to disable or add scripts. For instance, to add menu items that couldn't be automatically generated. |-

| /boot/grub/custom.cfg || GRUB shell script || style="background: #FFF176; color: black; vertical-align: middle; text-align: left; " class="cell-partial" | Maybe || The /etc/grub.d/41_custom script will reference this file to be read in at boot time if it exists. This file provides a place to add additional entries or commands and does not require regeneration of the main grub.cfg file. |-

| /etc/default/grub || POSIX shell script || style="background-color: #DFF0D8; color: black; vertical-align: middle; text-align: left; " class="cell-yes" | Yes || In most cases this is the only file that should be modified directly. It is mainly used to assign variables used by the scripts in /etc/grub.d to generate a working configuration file. See GRUB configuration variables or the official reference for supported variables. |-

|}

GRUB no requiere, a priori, intervención manual para configurar las opciones de arranque (como es el caso de cargadores de arranque tales como GRUB Legacy y LILO). En su lugar, puede generar su fichero de configuración (/boot/grub/grub.cfg) utilizando la orden grub2-mkconfig. Esta utilidad usa los guiones que residen en el directorio /etc/grub.d/ y los ajustes realizados en el fichero /etc/default/grub.

Advertencia
La utilidad grub-mkconfig no funciona correctamente cuando se utiliza RAID por software. Es necesaria una configuración manual de los guiones ubicados en /etc/grub.d/, ya que, de lo contrario, después de la instalación, el sistema queda en un estado tal que no puede arrancar.

Después de realizar uno o varios ajustes en la configuración, debe ejecutar la utilidad grub-mkconfig con la opción -o para que apunte al fichero de salida situado en /boot/grub/grub.cfg (esta es la ubicación de salida por defecto de GRUB2):

root #grub-mkconfig -o /boot/grub/grub.cfg
Generating grub.cfg ...
Found linux image: /boot/vmlinuz-3.3.0-gentoo
done

Cada vez que la utilidad grub-mkconfig es invocada, se genera una nueva configuración del fichero.

Advertencia
Si grub-mkconfig no informa haber encontrado alguna entrada, entonces no habrá entradas en el menú. En este caso, GRUB ofrecerá selecciones sin arranque cuando reinicie el sistema, que puede abocar a una situación difícil de resolver. Por tanto, asegúrese de que la salida es satisfactoria antes de reiniciar el sistema.

Definir los parámetros de la configuración

Las siguientes variables en /etc/default/grub son algunas de las más comunes de definir para controlar cómo funcionará GRUB:

Variable Explicación Valor por defecto
GRUB_DEFAULT Define la entrada del menú seleccionada por defecto en el arranque. Puede ser un índice numérico, un título de menú, o «rescatar». Predeterminado para detectar la primera entrada.
GRUB_TIMEOUT Indica la demora (en segundos) antes de arrancar la entrada predeterminada del menú. Establezca 0 para arrancar inmediatamente o -1 para esperar indefinidamente. El valor por defecto es 5 segundos.
GRUB_CMDLINE_LINUX Parámetros que se pasan a la línea de órdenes del núcleo para todas las entradas del menú de Linux. Por ejemplo, para dar soporte a la hibernación, los usuarios tendrán que añadir GRUB_CMDLINE_LINUX="resume=/dev/sdXY" donde /dev/sdXY será la partición swap.
GRUB_CMDLINE_LINUX_DEFAULT Parámetros que se pasan a la línea de órdenes del núcleo para las entradas del menú de Linux no recuperables.
GRUB_DEVICE Es el dispositivo root de inicio (es decir, el parámetro root= del núcleo). Ajuste esta opción para anular la detección automática del dispositivo root realizada por la orden grub-mkconfig. Por ejemplo, GRUB_DEVICE=/dev/ram0 obligará a que root=/dev/ram0 sea utilizado en la línea de órdenes del núcleo.

| GRUB_DEFAULT | Defines the default menu entry selected on boot. May be a numeric index, a menu title, or "saved". | Defaults to first detected entry. |-

| GRUB_TIMEOUT | Delay (in seconds) before booting default menu entry. Set to 0 to boot immediately or -1 to wait indefinitely. | The default is 5 seconds. |-

| GRUB_CMDLINE_LINUX | Parameters to be passed on the kernel command line for all Linux menu entries. For instance, to support hibernation, users will need to add GRUB_CMDLINE_LINUX="resume=/dev/sdXY" with /dev/sdXY being the swap partition. | |-

| GRUB_CMDLINE_LINUX_DEFAULT | Parameters to be passed on the kernel command line for non-recovery Linux menu entries. | |-

| GRUB_DEVICE | The initial root device (i.e. the kernel's root= parameter). Set this to override the grub-mkconfig command's root device auto-detection. For example, GRUB_DEVICE=/dev/ram0 will force root=/dev/ram0 to be used in the kernel command line. | |-

|}

Para obtener una lista más completa, consulte la subpágina de las variables de configuración de GRUB así como la página info de grub-mkconfig.

Después de modificar los parámetros, genere el fichero de configuración de GRUB2 con grub-mkconfig.

Activar o desactivar los guiones de configuración

El directorio /etc/grub.d/ contiene los guiones que grub-mkconfig utiliza para generar un fichero grub.cfg. Por defecto, el contenido de este directorio debe ser similar al siguiente:

user $ls /etc/grub.d/
00_header  10_linux  20_linux_xen  30_os-prober  40_custom  41_custom README

GRUB utilizará todos los guiones instalados que estén marcados como ejecutables (que, por defecto, lo están todos). Para desactivar cualquiera de los scripts, simplemente quite el bit de ejecución de los permisos del fichero del script, utilizando la orden chmod. En el siguiente ejemplo, cada script, salvo 00_header y 10_linux, serán desactivados:

root #chmod -x /etc/grub.d/{20_linux_xen,30_os-prober,40_custom,41_custom}

Después de modificar los guiones (o quitar el bit de ejecución), genere el fichero de configuración GRUB utilizando grub-mkconfig.

Manipular los guiones de configuración

Algunas de las características o funcionalidades de GRUB solo es posible desarrollarlas mediante la modificación de los guiones de configuración. Por ejemplo, para permitir el arranque dual con FreeBSD, es necesario realizar las siguientes modificaciones.

Cambiar el guión /etc/grub.d/40_custom como sigue:

ARCHIVO /etc/grub.d/40_customAñadir una entrada para arranque dual
menuentry "FreeBSD" --class freebsd --class bsd --class os {
 insmod ufs2
 insmod bsd
 set root=(hd0,1)
 kfreebsd /boot/kernel/kernel
 kfreebsd_loadenv /boot/device.hints
 set kFreeBSD.vfs.root.mountfrom=ufs:/dev/ada0s1a
 set kFreeBSD.vfs.root.mountfrom.options=rw
 set kFreeBSD.hw.psm.synaptics_support=1
}

/dev/sda1 o (hd0,1) es la partición en la que reside FreeBSD. Si se utilizó la instalación normal de UFS para la partición de FreeBSD, entonces /dev/sda1 será un contenedor (algo así como una partición lógica). Este comprende la partición de intercambio y la raíz. Verifique con ls -la /etc/grub.d/40_custom que el guión 40_custom es ejecutable. Si el bit de ejecución no está establecido, entonces, configúrelo con la orden chmod u+x 40_custom.

Nota
Los usuarios familiarizados con la numeración de particiones que realiza GRUB Legacy deberían tener en cuenta que los números de particiones comienzan por 1 no por 0 con GRUB2.

A continuación, instale GRUB y actualice el fichero de configuración:

root #grub-install /dev/sda
root #grub-mkconfig -o /boot/grub/grub.cfg

Características extendidas

GRUB 2 tiene muchas características que lo convierten en un poderoso cargador de arranque. Es compatible con:

  • Arranque desde plataformas UEFI.
  • Arranque desde unidades particionadas con GPT sin necesidad de un MBR híbrido (el MBR híbrido puede activarse, según sea necesario, para proporcionar compatibilidad o portabilidad).
  • Arranque desde una partición /boot formateada con btrfs.
  • Arranque desde un grupo ZFS.
  • Arranque directamente desde un conjunto RAID btrfs sin necesitar un initramfs para configurar montaje temprano.
  • Arranque directamente desde volúmenes lógicos (como LVM2).
  • Arranque con soporte para DM-RAID (RAID 0, 1, 4, 5, 6, 9 y 10).
  • Arranque desde dispositivos cifrados (LUKS).

Algunas características se explican con más detalle a continuación.

Cargar en cadena

GRUB 2 fue construido con un modo de carga en cadena (chainload) verdaderamente mejorado en comparación con su predecesor GRUB Legacy. Para enlazar con otro cargador de arranque, utilice la opción chainloader.

ARCHIVO /etc/grub.d/40_customEncadenar la carga de otro gestor de arranque
menuentry "Ejemplo de Super Cargador de Arranque Personalizado" {
     insmod part_msdos
     insmod chain
     chainloader (hd1,1)+1
}

Para obtener más información sobre la carga en cadena, consulte la subpágina Chainloading.

Menu de GRUB protegido con contraseña

To secure GRUB so it is not possible for anyone to change boot parameters or use the command line, add a user/password combination to GRUB's configuration files. The program grub-mkpasswd-pbkdf2 generates password hashes for GRUBː

user $grub-mkpasswd-pbkdf2
Password:
Reenter password:
</div>

<div lang="en" dir="ltr" class="mw-content-ltr">
PBKDF2 hash of your password is grub.pbkdf2.sha512.10000.9CA4611006FE96BC77A...

Después, añada lo siguiente a:

ARCHIVO /etc/grub.d/35_auth:
# Grub user
echo 'set superusers="username"'
# Grub password
echo 'password_pbkdf2 <username> <password>'

The above may lock all Grub menu entries, even the default entry. In that case, to allow users to boot some menu entries without a password, see Securing the grub boot loader.

The permissions for the file need to be properly set before doing grub-mkconfig:

root #chmod 755 /etc/grub.d/35_auth

Utilizar framebuffer de pantalla

Para que GRUB2 utilice un framebuffer de pantalla gráfica, vuelva a ejecutar emerge de GRUB con el ajuste truetype de USE activado. Esto instalará una tipografía True Type por defecto, así como una utilidad de conversión del tipo de letra.

root #emerge --ask --newuse sys-boot/grub:2

Proceda a configurar el fichero de configuración por defecto de GRUB2 ubicado en /etc/default/grub. Por ejemplo:

ARCHIVO /etc/default/grubAjustes relacionados con framebuffer
# Ajustar resolución y profundidad del color
GRUB_GFXMODE=1366x768x32
 
# Mantener resolución cuando se carga el núcleo
GRUB_GFXPAYLOAD_LINUX=keep
 
# Definir una imagen de fondo
GRUB_BACKGROUND="/boot/grub/bg.png"
 
# Utilizar una tipografía personalizada, convertida con la utilidad grub-mkfont
GRUB_FONT="/boot/grub/fonts/roboto.pf2"

HiDPI displays

On modern displays with high DPI ("HiDPI"), e.g. UHD (3840x2160), the standard font will look very small. If you like to have the same font as the kernel, Terminus can be used, which resembles a BIOS built-in textmode font.

To select this font in-kernel, CONFIG_FONT_TER16x32 has to be enabled.

KERNEL Kernel compiled-in fonts
Library routines  --->
      [*] Select compiled-in fonts
      [*] Terminus 16x32 font (not supported by all drivers)

The same font is available as media-fonts/terminus-font, which can then be used for GRUB as well.

root #emerge --ask media-fonts/terminus-font
root #grub-mkfont -s 32 -o /boot/grub/fonts/terminus32b.pf2 /usr/share/fonts/terminus/ter-u32b.otb

In the above example the filename chosen for grub-mkfont output is terminus32b.pf2. The font's path has to be accessible to GRUB during boot, so it should reside in the same mount point as GRUB does; this example uses /boot/grub/fonts. The font then has to be set as GRUB_FONT in /etc/default/grub in order to be used.

ARCHIVO /etc/default/grubFramebuffer related settings
# Use a custom font, converted using grub-mkfont utility
GRUB_FONT="/boot/grub/fonts/terminus32b.pf2"

Updating the GRUB configuration file grub.cfg will then activate the configuration with the new font.

root #grub-mkconfig -o /boot/grub/grub.cfg

Solución de problemas

Nota
Para obtener más información sobre soluciones de problemas de GRUB, consulte el articulo Troubleshooting.

La mayoría de los problemas se pueden resolver al asegurar un esquema de particionado correcto. Mantenga suficiente espacio disponible antes de la primera partición del disco, u, opcionalmente, asegúrese de que la BIOS boot partition está disponible. Compruebe también que /boot/grub/grub.cfg se generó correctamente con grub-mkconfig, o genere uno con una entrada de menú personalizada.

os-prober se ejecuta

When running the grub-mkconfig command, os-prober is not running as expected, even though it is installed:

root #grub-mkconfig -o /boot/grub/grub.cfg
Generating grub configuration file ...
Found linux image: /boot/vmlinuz-5.11.14-gentoo-x86_64
Found initrd image: /boot/amd-uc.img /boot/initramfs-5.11.14-gentoo-x86_64.img
Warning: os-prober will not be executed to detect other bootable partitions.
Systems on them will not be added to the GRUB boot configuration.
Check GRUB_DISABLE_OS_PROBER documentation entry.
Adding boot menu entry for UEFI Firmware Settings ...
done

This can be corrected by setting the GRUB_DISABLE_OS_PROBER variable to false in /etc/default/grub file.

ARCHIVO /etc/default/grub
GRUB_DISABLE_OS_PROBER=false

Upon the next run, grub-mkconfig should find additional bootable partitions:

root #grub-mkconfig -o /boot/grub/grub.cfg
Generating grub configuration file ...
Found linux image: /boot/vmlinuz-5.11.14-gentoo-x86_64
Found initrd image: /boot/amd-uc.img /boot/initramfs-5.11.14-gentoo-x86_64.img
Warning: os-prober will be executed to detect other bootable partitions.
It's output will be used to detect bootable binaries on them and create new boot entries.
Found Windows Boot Manager on /dev/nvme0n1p2@/efi/Microsoft/Boot/bootmgfw.efi
Adding boot menu entry for UEFI Firmware Settings ...
done

Firmware de la placa base que no encuentra el fichero .EFI

Algunos fabricantes de placas base parece que soportan únicamente una localización para el fichero .EFI en el sistema de particiones EFI (ESP). Si este es el caso, simplemente mueva el fichero por defecto de GRUB a la localización /efi/boot/. En primer lugar, asegúrese de que el ESP está montado. Suponiendo que el ESP está montado en /boot/efi (tal y como se sugiere en el manual), lance:

root #mkdir -p /boot/efi/efi/boot
root #cp /boot/efi/efi/gentoo/grubx64.efi /boot/efi/efi/boot/bootx64.efi

On a 32-bit EFI implementation use bootia32.efi instead:

root #cp /boot/efi/efi/gentoo/grubia32.efi /boot/efi/efi/boot/bootia32.efi

The removable parameter can be used with grub-install command to generate this file automatically:

root #grub-install --efi-directory=/boot/efi --removable
Installation finished. No error reported.

Esto debería ayudar al firmware de la placa base a cargar el ejecutable de GRUB. Reinicie el sistema para ver si ahora el firmware carga GRUB correctamente.

os-prober y UEFI en una jaula chroot

La utilidad sys-boot/os-prober se utiliza para descubrir instalaciones alternativas como Microsoft Windows. Para que funcione correctamente necesita acceso a la información desde el entorno vivo de udev para comprobar la existencia de una partición de sistema EFI.

Lanzar estas órdenes en el entorno del anfitrión para ofrecer los ficheros necesarios (el ejemplo muestra Gentoo montado en /mnt/gentoo al igula que en el manual):

root #mkdir -p /mnt/gentoo/run/udev
root #mount -o bind /run/udev /mnt/gentoo/run/udev
root #mount --make-rslave /mnt/gentoo/run/udev

Instalar un nuevo núcleo

Cada vez que se instala un nuevo núcleo se debe reconfigurar GRUB2 para que lo reconozca. Esto se puede realizar utilizando grub-mkconfig tal y como se muestra abajo o se puede realizar de forma manual.

Nota
Asegúrese de que la partición /boot está montada antes de abordar este paso.
root #grub-mkconfig -o /boot/grub/grub.cfg
Generating grub.cfg ...
Found linux image: /boot/kernel-3.3.8-gentoo
Found initrd image: /boot/initramfs-genkernel-x86_64-3.3.8-gentoo
Found linux image: /boot/kernel-3.2.12-gentoo
Found initrd image: /boot/initramfs-genkernel-x86_64-3.2.12-gentoo
done

Se debe recordar que GRUB2 únicamente necesita ser reconfigurado no reinstalado en el Registro Principal de Arranque (Master Boot Record o MBR). Por el contrario, cuando se actualiza el propio GRUB2 se debe reinstalar en el disco de arranque sin embargo normalmente no necesita ser reconfigurado.

Automatic GRUB reconfiguration

If the package sys-kernel/installkernel-gentoo is installed and the USE flag grub is set, then on every installation of a kernel, grub-mkconfig will run automatically.

Véase también

  • En Chainloading se describe el uso de GRUB2 para arrancar otros cargadores de arranque. Es importante leer esto para los sistemas de arranque dual, o cuando GRUB2 necesita ser configurado para arrancar ficheros ISO.
  • En Advanced storage están documentados los pasos necesarios sobre cómo instalar y utilizar GRUB en situaciones de almacenamiento más avanzados, tales como RAID por software, volúmenes lógicos o sistemas de ficheros cifrados.
  • En Configuration variables se documenta una lista exhaustiva de las variables de configuración de GRUB, como las usadas por /etc/default/grub.
  • En Troubleshooting se presenta una lista de errores comunes de GRUB (con sus soluciones).
  • En Hybrid partition table se documenta el uso de una configuración mixta MBR/GPT, así como la forma de utilizar dicho esquema de partición híbrida con GRUB.

Recursos externos

Para más información, vea:

References