Configurar el cargador de arranque
Seleccionar un gestor de arranque
Una vez se haya configurado el núcleo Linux configurado, instalado las herramientas del sistema y editado los ficheros de configuración, es el momento de instalar la última pieza importante de una instalación Linux: cargador de arranque.
El cargador de arranque es el responsable de arrancar el núcleo Linux en el momento del inicio. Sin él, el sistema no sabría cómo proceder cuando se pulsa el botón de encendido.
Para amd64, documentamos cómo configurar bien GRUB o LILO para sistemas basados en BIOS y GRUB o efibootmgr para sistemas UEFI.
En esta sección del Manual se realizó una delimitación entre realizar un emerge del paquete del gestor de arranque e instalar un gestor de arranque en un disco del sistema. Aquí el término emerge será utilizado para pedirle a Portage que instale el paquete para que esté disponible en el sistema. El término install significará la copia de los ficheros del gestor de arranque o la modificación física de las secciones del disco apropiadas para dejar al gestor de arranque activado y listo para operar en el próximo reinicio.
Predeterminado: GRUB
De manera predeterminada, la mayoría de los sistemas Gentoo utilizan GRUB (disponible en el paquete sys-boot/grub), que es el sucesor directo de GRUB Legacy. Sin ninguna configuración adicional, GRUB soporta antiguos sistemas BIOS ("pc"). Con una pequeña configuración, necesaria antes de construir, GRUB puede soportar más de media docena de plataformas adicionales. Para obtener más información, consulte la sección de prerequisitos del artículo sobre GRUB.
Emerge
Cuando se utilice un antiguo sistema con BIOS que soporte solo tablas de particiones MBR, no son necesarias configuraciones extra para realizar un emerge de GRUB:
root #
emerge --ask --verbose sys-boot/grub
Una nota para los usuarios de UEFI: Al lanzar la orden de arriba, se mostrarán los valores habilitados de GRUB_PLATFORMS antes de hacer emerge. Cuando se utilicen sistemas con UEFI, los usuarios necesitarán asegurarse de que GRUB_PLATFORMS="efi-64"
está habilitado (ya que es el caso por defecto). Si ese no es el caso para la configuración, se necesitará añadir GRUB_PLATFORMS="efi-64"
al fichero /etc/portage/make.conf antes de hacer emerge de GRUB de modo que el paquete se construya con funcionalidad EFI:
root #
echo 'GRUB_PLATFORMS="efi-64"' >> /etc/portage/make.conf
root #
emerge --ask sys-boot/grub
- Si se realizó emerge de GRUB sin habilitar previamente
GRUB_PLATFORMS="efi-64"
, se puede añadir esta línea la línea (tal y como se muestra arriba) a make.conf y se pueden recalcular las dependencias para el conjunto de paquetes world pasando las opciones--update --newuse
a emerge:
root #
emerge --ask --update --newuse --verbose sys-boot/grub
El software GRUB está ahora disponible en el sistema, pero no se ha instalado aún.
Instalación
A continuación, instalar los archivos necesarios de GRUB en el directorio /boot/grub/ mediante la orden grub-install. Se supone que el primer disco (desde el que se inicia el sistema) es /dev/sda alguna de las órdenes siguientes lo hará:
- Cuando se utiliza BIOS:
root #
grub-install /dev/sda
For DOS/Legacy BIOS systems:
root #
grub-install /dev/sda
- Cuando se utilice UEFI:
- Importante
Asegúrese de que la partición EFI de sistema está montada antes de lanzar grub-install. Es posible que grub-install instale el fichero GRUB para EFI (grubx64.efi) en el directorio incorrecto sin ofrecer ningún tipo de indicación de que se ha utilizado el directorio incorrecto.
For UEFI systems:
root #
grub-install --target=x86_64-efi --efi-directory=/boot
Upon successful installation, the output should match the output of the previous command. If the output does not match exactly, then proceed to Debugging GRUB, otherwise jump to the Configure step.
Optional: Secure Boot
The sys-boot/grub package does not recognize the secureboot USE flag, this is because the GRUB EFI executable is not installed by the package but is instead built and installed by the grub-install command. GRUB must therefore be manually signed after installation to the boot partition. Additionally, GRUB is a modular bootloader but loading modules is prohibited when Secure Boot is enabled. Therefore all necessary modules must be compiled into the GRUB EFI executable, below an example is shown including some basic modules, this may have to be adjusted for more advanced configurations:
root #
emerge --noreplace sbsigntools
root #
export GRUB_MODULES="all_video boot btrfs cat chain configfile echo efifwsetup efinet ext2 fat font gettext gfxmenu gfxterm gfxterm_background gzio halt help hfsplus iso9660 jpeg keystatus loadenv loopback linux ls lsefi lsefimmap lsefisystab lssal memdisk minicmd normal ntfs part_apple part_msdos part_gpt password_pbkdf2 png probe reboot regexp search search_fs_uuid search_fs_file search_label sleep smbios squash4 test true video xfs zfs zfscrypt zfsinfo"
root #
grub-install --target=x86_64-efi --efi-directory=/efi --modules=${GRUB_MODULES} --sbat /usr/share/grub/sbat.csv
root #
sbsign /efi/EFI/GRUB/grubx64.efi --key /path/to/kernel_key.pem --cert /path/to/kernel_key.pem --out /efi/EFI/GRUB/grubx64.efi
To successfully boot with secure boot enabled the used certificate must either be accepted by the UEFI firmware, or shim must be used as a pre-loader. Shim is pre-signed with the third-party Microsoft Certificate, accepted by default by most UEFI motherboards.
How to configure the UEFI firmware to accept custom keys depends on the firmware vendor, which is beyond the scope of the handbook. Below is shown how to setup shim instead:
root #
emerge sys-boot/shim sys-boot/mokutil sys-boot/efibootmgr
root #
cp /usr/share/shim/BOOTX64.EFI /efi/EFI/GRUB/shimx64.efi
root #
cp /usr/share/shim/mmx64.efi /efi/EFI/GRUB/mmx64.efi
Shims MOKlist requires keys in the DER format, since the OpenSSL key generated in the example here is in the PEM format, the key must be converted first:
root #
openssl x509 -in /path/to/kernel_key.pem -inform PEM -out /path/to/kernel_key.der -outform DER
The path used here must be the path to the pem file containing the certificate belonging to the generated key. In this example both key and certificate are in the same pem file.
Then the converted certificate can be imported into Shims MOKlist:
root #
mokutil --import /path/to/kernel_key.der
And finally we register Shim with the UEFI firmware. In the following command, boot-disk
and boot-partition-id
must be replaced with the disk and partition identifier of the EFI system partition:
root #
efibootmgr --create --disk /dev/boot-disk --part boot-partition-id --loader '\EFI\GRUB\shimx64.efi' --label 'shim' --unicode
Debugging GRUB
When debugging GRUB, there are a couple of quick fixes that may result in a bootable installation without having to reboot to a new live image environment.
In the event that "EFI variables are not supported on this system" is displayed somewhere in the output, it is likely the live image was not booted in EFI mode and is presently in Legacy BIOS boot mode. The solution is to try the removable GRUB step mentioned below. This will overwrite the executable EFI file located at /EFI/BOOT/BOOTX64.EFI. Upon rebooting in EFI mode, the motherboard firmware may execute this default boot entry and execute GRUB.
- Importante
Si grub-install devuelve un error comoCould not prepare Boot variable: Read-only file system
, puede que sea necesario montar de nuevo el punto de montaje especial efivars en modo lectura y escritura para poder continuar:root #
mount -o remount,rw /sys/firmware/efi/efivars
root #
mount -o remount,rw,nosuid,nodev,noexec --types efivarfs efivarfs /sys/firmware/efi/efivars
This is caused by certain non-official Gentoo environments not mounting the special EFI filesystem by default. If the previous command does not run, then reboot using an official Gentoo live image environment in EFI mode.
Algunos fabricantes de placas base, ofrecen soporte úncamente a localizar el fichero .EFI en el directorio /efi/boot/ dentro de la partición de sistema EFI (ESP). El instalador GRUB puede hacer esta operación de forma automática si se utiliza la opción --removable
. Verificar que la ESP está montada antes de lanzar las siguientes órdenes. Asumiendo que la ESP está montada en /boot/efi (como se sugirió antes), lanzar:
root #
grub-install --target=x86_64-efi --efi-directory=/boot --removable
Esto crea el directorio por defecto definido por la especificación UEFI y a continuación copia el fichero grubx64.efi a la localización EFI 'por defecto' definida en la misma especificación.
Configuración
A continuación, generar la configuración de GRUB basada en la configuración de usuario especificado en el archivo /etc/default/grub y en los guiones /etc/grub.d. En la mayoría de los casos, no se necesita ninguna configuración por parte de los usuarios ya que GRUB detectará automáticamente el núcleo que debe iniciar (la versión más alta disponible en /boot/) y cuál es el sistema de ficheros raíz. También es posible añadir argumentos del núcleo en /etc/default/grub mediante la variable GRUB_CMDLINE_LINUX.
Para generar la configuración final de GRUB, lance la orden grub-mkconfig:
root #
grub-mkconfig -o /boot/grub/grub.cfg
Generating grub.cfg ... Found linux image: /boot/vmlinuz-6.1.38-gentoo Found initrd image: /boot/initramfs-genkernel-amd64-6.1.38-gentoo done
La salida de la orden debe mostrar que se ha encontrado al menos una imagen de Linux, como las que son necesarias para arrancar el sistema. Si se utiliza un initramfs o se utilizó genkernel para construir el núcleo, la imagen correcta initrd debería poder detectarse de esta forma. Si no es el caso, hay que ir a /boot/ y comprobar los contenidos mediante la orden ls. Si los archivos no están, se debe regresar a la configuración del núcleo y a las instrucciones de instalación.
La utilidad os-prober en conjunto con GRUB para detectar otros sistemas operativos en los discos conectados. Windows 7, 8.1, 10 y otras distribuciones de Linux son detectables. Para esto escenarios de doble booteo debes hacer un emerge del paquete sys-boot/os-prober y luego volver a ejecutar grub-mkconfig (como se muestra arriba). Si se encuentran problemas en la detección, asegúrate de leer el artículo de GRUB entero antes de pedir soporte a la comunidad de Gentoo.
Alternativa 1: LILO
Emerge
LILO, el LInuxLOader (Cargador de Linux), está de sobra probado y es el verdadero caballo de batalla de los cargadores de arranque de Linux. Sin embargo, carece de algunas características que posee GRUB. La razón por la que LILO aún se utiliza es que, en algunos sistemas, GRUB no funciona y LILO sí. Por supuesto, también se sigue utilizando debido a que algunas personas lo conocen bien y quieren seguir utilizándolo. De cualquier formar, Gentoo ofrece soporte a ambos.
Instalar LILO es muy fácil, sencillamente utilice emerge.
root #
emerge --ask sys-boot/lilo
Configurar
Para configurar LILO, en primer lugar se debe crear /etc/lilo.conf:
root #
nano -w /etc/lilo.conf
En el archivo de configuración, las secciones se utilizan para referirse al núcleo arrancable. Asegúrese de que conoce los archivos del núcleo (incluyendo su versión) y los archivos initramfs, ya que se necesita hacer referencia a ellos es el fichero de configuración.
Si el sistema de fichero raíz es JFS, agregue una línea
append="ro"
después de cada elemento de arranque ya que JFS necesita reproducir su registro antes de permitir el montaje en modo lectura y escritura.'"`UNIQ--pre-00000006-QINU`"'
Si se utiliza un esquema de particionamiento diferente o se utiliza una imagen del núcleo, se deberá ajustar adecuadamente..
Si se necesita un initramfs, se debe cambiar la configuración haciendo referencia al fichero initramfs e indicar al initramfs donde se encuentra el dispositivo raíz:
'"`UNIQ--pre-00000009-QINU`"'
Si se necesitan pasar opciones adicionales al núcleo, utilice una sentencia append
. Por ejemplo, añada la sentencia video
para habilitar el framebuffer:
'"`UNIQ--pre-0000000C-QINU`"'
Los usuarios que utilizan genkernel deberían saber que sus núcleos utilizan las mismas opciones de arranque que el CD de instalación. Por ejemplo, si se necesita ofrecer soporte para dispositivos SCSI añada doscsi
como opción del núcleo.
Ahora, guarde el archivo y salga.
Instalación
Para terminar, lance /sbin/lilo de modo que LILO pueda aplicar los ajustes definidos en /etc/lilo.conf al sistema (esto es, instalarse a sí mismo en el disco). Recuerde que se necesita lanzar /sbin/lilo cada vez que se ha instalado un nuevo núcleo o se ha realizado un cambio al fichero lilo.conf para reiniciar el sistema si se ha cambiado el nombre del fichero que contiene el núcleo.
root #
/sbin/lilo
Alternativa 2: efibootmgr
En los sistemas basados en UEFI, el firmware UEFI del sistema (en otras palabras, el cargador de arranque primario) de puede manipular directamente para que busque entradas de arranque UEFI. Estos sistemas no necesitan tener cargadores de arranque (también conocidos como secundarios) como GRUB para ayudar a iniciar el sistema. Una vez dicho esto, la razón por la que existen cargadores basados en EFI como GRUB es para extender la funcionalidad de los sistemas UEFI durante el proceso de arranque. El uso de efibootmgr está realmente enfocado en aquéllos que desean mantener un enfoque minimalista (aunque más rígido) en el arranque de sus sistemas. El uso de GRUB2 (ver arriba) es más fácil para la mayoría de los usuarios ya que ofrece un enfoque flexible cuando se inician sistemas UEFI.
System administrators who desire to take a minimalist, although more rigid, approach to booting the system can avoid secondary bootloaders and boot the Linux kernel as an EFI stub.
Recuerde que la aplicación sys-boot/efibootmgr no es un cargador de arranque, es una herramienta para interactuar con el firmware UEFI y actualizar su configuración, de modo que núcleo Linux que se instaló previamente se puede arrancar con opciones adicionales (si es necesario) o también para permitir múltiples entradas de arranque. Esta interacción se realiza a través de variables EFI (de ahí la necesidad de soporte para el núcleo de variables EFI).
Asegúrese de leer el artículo del núcleo EFI stub antes de continuar. El núcleo debe tener opciones específicas habilitadas para que pueda ser iniciado directamente por el firmware UEFI del sistema firmware. Puede que sea necesario recompilar el núcleo. También es buena idea echar un vistazo al artículo efibootmgr/es.
It is also a good idea to take a look at the efibootmgr article for additional information.
Insisitimos en que efibootmgr no es un requisito para arrancar un sistema UEFI. Se puede arrancar el núcleo Linux de forma inmediata y se pueden construir opciones de línea de órdenes del núcleo en el propio núcleo Linux (hay una opción de configuración del núcleo llamada CONFIG_CMDLINE que permite al usuario especificar los parámetros de arranque como opciones de la línea de órdenes). Incluso se puede 'construir' un sistema de ficheros initramfs en el propio núcleo.
Los que opten por este enfoque deben instalar el software:
root #
emerge --ask sys-boot/efibootmgr
A continuación crear la localización /boot/efi/boot/ y copiar el núcleo en esta localización llamándolo bzImage.efi:
root #
mkdir -p /boot/efi/boot
root #
cp /boot/vmlinuz-* /boot/efi/boot/bzImage.efi
El uso de \ como separador de directorios es obligatorio cuando se utilizan las definiciones UEFI.
A continuación, indíquele al firmware UEFI que se va a crear una entrada en el menú de inicio llamada "Gentoo" que tiene el nuevo núcleo compilado para EFI:
root #
efibootmgr --create --disk /dev/sda --part 2 --label "Gentoo" --loader "\efi\boot\bzImage.efi"
Si se utiliza un sistema de ficheros de inicio en RAM (initramfs), añadir la opción de arranque apropiada:
root #
efibootmgr -c -d /dev/sda -p 2 -L "Gentoo" -l "\efi\boot\bzImage.efi" initrd='\initramfs-genkernel-amd64-6.1.38-gentoo'
Note that the above command presumes an initramfs file was copied into the ESP inside the same directory as the bzImage.efi file.
Una vez realizados estos cambios, cuando el sistema se reinicie, aparecerá una entrada en el menú de inicio llamada "Gentoo".
Unified Kernel Image
If installkernel was configured to build and install unified kernel images. The unified kernel image should already be installed to the EFI/Linux directory on the EFI system partition, if this is not the case ensure the directory exists and then run the kernel installation again as described earlier in the handbook.
To add a direct boot entry for the installed unified kernel image:
root #
efibootmgr --create --disk /dev/sda --part 1 --label "gentoo" --loader /efi/EFI/Linux/gentoo-x.y.z.efi
Alternativa 3: Syslinux
Syslinux es otro cargador de arranque alternativo para la arquitectura amd64. Ofrece soporte para MBR y en su versión 6.00 también ofrece soporte para arranque EFI. El arranque PXE (a través de la red) y otras opciones menos conocidas también están soportadas. Aunque Syslinux es un cargador de arranque popular para muchos, en el manual no se ofrece soporte para él. Los lectores pueden encontrar información acerca de cómo hacer emerge del paquete e instalarlo a continuación en el artículo de Syslinux.
Alternative 4: systemd-boot
Another option is systemd-boot, which works on both OpenRC and systemd machines. It is a thin chainloader and works well with secure boot.
To install systemd-boot:
root #
bootctl install
Make sure the EFI system partition has been mounted before running bootctl install.
When using this bootloader, before rebooting, verify that a new bootable entry exists using:
root #
bootctl list
If no new entry exists, ensure the sys-kernel/installkernel package has been installed with the systemd-boot USE flag enabled, and re-run the kernel installation.
For the distribution kernels:
root #
emerge --ask --config sys-kernel/gentoo-kernel
For a manually configured and compiled kernel:
root #
make install
When installing kernels for systemd-boot, no root= kernel command line argument is added by default. On systemd systems that are using an initramfs users may rely instead on systemd-gpt-auto-generator to automatically find the root partition at boot. Otherwise users should manually specify the location of the root partition by setting root= in /etc/kernel/cmdline as well as any other kernel command line arguments that should be used. And then reinstalling the kernel as described above.
Optional: Secure Boot
When the secureboot USE flag is enabled, the systemd-boot EFI executable will be signed automatically. bootctl install will automatically install the signed version.
To successfully boot with secure boot enabled the used certificate must either be accepted by the UEFI firmware, or shim must be used as a pre-loader. Shim is pre-signed with the third-party Microsoft Certificate, accepted by default by most UEFI motherboards.
How to configure the UEFI firmware to accept custom keys depends on the firmware vendor, which is beyond the scope of the handbook. A postinst hook to automatically update systemd-boot and set it up with shim instead is provided on the systemd-boot wiki page. However the first time this should be done manually by following the steps below:
root #
emerge --ask sys-boot/shim sys-boot/mokutil sys-boot/efibootmgr
root #
cp /usr/share/shim/BOOTX64.EFI /efi/EFI/BOOT/BOOTX64.EFI
root #
cp /usr/share/shim/mmx64.efi /efi/EFI/BOOT/mmx64.efi
root #
cp /efi/EFI/systemd/systemd-bootx64.efi /efi/EFI/BOOT/grubx64.efi
Shim is hardcoded to load grubx64.efi. As such the systemd-boot bootloader must be named as if it were GRUB.
Shims MOKlist requires keys in the DER format, since the OpenSSL key generated in the example here is in the PEM format, the key must be converted first:
root #
openssl x509 -in /path/to/kernel_key.pem -inform PEM -out /path/to/kernel_key.der -outform DER
The path used here must be the path to the pem file containing the certificate belonging to the generated key. In this example both key and certificate are in the same pem file.
Then the converted certificate can be imported into Shims MOKlist:
root #
mokutil --import /path/to/kernel_key.der
And finally we register Shim with the UEFI firmware. In the following command, boot-disk
and boot-partition-id
must be replaced with the disk and partition identifier of the EFI system partition:
root #
efibootmgr --create --disk /dev/boot-disk --part boot-partition-id --loader '\EFI\BOOT\BOOTX64.EFI' --label 'shim' --unicode
Reiniciar el sistema
Salga del entorno chroot y desmonte todas las particiones que continúen montadas. Luego escriba la orden mágica da inicio a la auténtica prueba final: reboot.
root #
exit
cdimage ~#
cd
cdimage ~#
umount -l /mnt/gentoo/dev{/shm,/pts,}
cdimage ~#
umount -R /mnt/gentoo
cdimage ~#
reboot
Por supuesto, no olvide quitar el CD arrancable, o podría arrancar de nuevo el CD en lugar de su nuevo sistema Gentoo.
Una haya reiniciado en su recien instalado entorno Gentoo, termine con Finalizar la instalación de Gentoo.