Configurar el cargador de arranque

From Gentoo Wiki
Jump to:navigation Jump to:search
This page is a translated version of the page Handbook:AMD64/Installation/Bootloader and the translation is 100% complete.
AMD64 Handbook
Installation
About the installation
Choosing the media
Configuring the network
Preparing the disks
The stage file
Installing base system
Configuring the kernel
Configuring the system
Installing tools
Configuring the bootloader
Finalizing
Working with Gentoo
Portage introduction
USE flags
Portage features
Initscript system
Environment variables
Working with Portage
Files and directories
Variables
Mixing software branches
Additional tools
Custom package repository
Advanced features
OpenRC network configuration
Getting started
Advanced configuration
Modular networking
Wireless
Adding functionality
Dynamic management



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 DOS/BIOS obsoleto 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 ahora se ha instalado en el sistema, pero aún no se ha instalado como un gestor de arranque secundario.

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á:

Sistemas DOS/BIOS obsoleto

Para sistemas DOS/BIOS obsoleto:

root #grub-install /dev/sda

Sistemas 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.

Para sistemas UEFI:

root #grub-install --efi-directory=/efi
Installing for x86_64-efi platform.
Installation finished. No error reported.

Tras una instalación exitosa, el resultado debe coincidir con el resultado del comando anterior. Si la salida no coincide exactamente, entonces siga con Depurar GRUB, en caso contrario siga con el paso Configurar.

Opcional: Arranque Seguro

To successfully boot with secure boot enabled the signing 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. Here it is assumed that the user has already followed the instructions in the previous sections to generate a signing key and to configure portage to use it. If this is not the case please return first to the Kernel installation section.

The package sys-boot/grub installs a prebuilt and signed stand-alone EFI executable if the secureboot USE flag is enabled. Install the required packages and copy the stand-alone grub, Shim, and the MokManager to the same directory on the EFI System Partition. For example:

root #emerge sys-boot/grub sys-boot/shim sys-boot/mokutil sys-boot/efibootmgr
root #cp /usr/share/shim/BOOTX64.EFI /efi/EFI/Gentoo/shimx64.efi
root #cp /usr/share/shim/mmx64.efi /efi/EFI/Gentoo/mmx64.efi
root #cp /usr/lib/grub/grub-x86_64.efi.signed /efi/EFI/Gentoo/grubx64.efi

La MOKlist Shim requiere claves en el formato DER, dado que la clave OpenSSL generada en el ejemplo actual está en el formato PEM, la clave debe convertirse primero:

root #openssl x509 -in /rura/a/kernel_key.pem -inform PEM -out /ruta/a/kernel_key.der -outform DER
Nota
La ruta utilizada aquí debe ser la ruta al archivo pem que contiene el certificado que pertenece a la clave generada. En este ejemplo, tanto la clave como el certificado están en el mismo archivo pem.

Después, el certificado convertido se puede importar a la MOKlist Shim:

root #mokutil --import /ruta/a/kernel_key.der
Nota
When the currently booted kernel already trusts the certificate being imported, the message "Already in kernel trusted keyring." will be returned here. If this happens, re-run the above command with the argument --ignore-keyring added.

Y finalmente registramos Shim en el firmware UEFI. En el siguiente comando, boot-disk y boot-partition-id deben reemplazarse con el disco y el identificador de partición de la partición del sistema EFI:

root #efibootmgr --create --disk /dev/boot-disk --part boot-partition-id --loader '\EFI\GRUB\shimx64.efi' --label 'shim' --unicode

Note that this prebuilt and signed stand-alone version of grub reads the grub.cfg from a different location then usual. Instead of the default /boot/grub/grub.cfg the config file should be in the same directory that the grub EFI executable is in, e.g. /efi/EFI/Gentoo/grub.cfg. When sys-kernel/installkernel is used to install the kernel and update the grub configuration then the GRUB_CFG environment variable may be used to override the usual location of the grub config file.

For example:

root #grub-mkconfig -o /efi/EFI/Gentoo/grub.cfg

Or, via installkernel:

ARCHIVO /etc/env.d/99grub
GRUB_CFG=/efi/EFI/Gentoo/grub.cfg
root #env-update
Nota
The import process will not be completed until the system is rebooted. After completing all steps in the handbook, restart the system and Shim will load, it will find the import request registered by mokutil. The MokManager application will start and ask for the password that was set when creating the import request. Follow the on-screen instructions to complete the import of the certificate, then reboot the system into the UEFI menu and enable the Secure Boot setting.
Depurar GRUB

Al depurar GRUB, hay un par de correcciones rápidas que pueden funcionar en una instalación de arranque sin tener que reiniciar en un nuevo entorno de imagen live.

En el caso de que se muestre "EFI variables are not supported on this system" en algún lugar de la pantalla, es probable que la imagen live no se haya iniciado en modo EFI y se encuentre actualmente en modo de inicio BIOS obsoleto. La solución es probar la opción removible de GRUB que se menciona a continuación. Esto sobrescribirá el archivo EFI ejecutable ubicado en /EFI/BOOT/BOOTX64.EFI. Al reiniciar en modo EFI, el firmware de la placa base puede ejecutar esta entrada de inicio predeterminada y ejecutar GRUB.

Si grub-install devuelve un error que dice "Could not prepare Boot variable: Read-only file system" y el entorno live se inició correctamente en modo UEFI, entonces debería ser posible volver a montar el sistema especial efivar como lectura-escritura y luego vuelva a ejecutar el comando antes mencionado grub-install:

root #mount -o remount,rw,nosuid,nodev,noexec --types efivarfs efivarfs /sys/firmware/efi/efivars

Esto se debe a que ciertos entornos Gentoo no oficiales no montan el sistema de archivos especial EFI de forma predeterminada. Si el comando anterior no se ejecuta, reinicie usando un entorno de imagen live oficial de Gentoo en modo EFI.

Algunos fabricantes de placas base con implementaciones UEFI deficientes parecen admitir sólo la ubicación del directorio /EFI/BOOT para el archivo .EFI en la partición del sistema EFI (ESP). El instalador de GRUB puede crear el archivo .EFI en esta ubicación automáticamente agregando la opción --removable al comando de instalación. Asegúrese de que el ESP haya sido montado antes de ejecutar el siguiente comando; suponiendo que está montado en /efi (como se definió anteriormente), ejecute:

root #grub-install --target=x86_64-efi --efi-directory=/efi --removable

Esto crea el directorio 'predeterminado' definido por la especificación UEFI y luego crea un archivo con el nombre predeterminado: BOOTX64.EFI.

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.6.21-gentoo
Found initrd image: /boot/initramfs-genkernel-amd64-6.6.21-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.

Consejo
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 4: systemd-boot

Otra opción es systemd-boot, que funciona tanto en equipos OpenRC como systemd. Es un cargador en cadena ligero y funciona bien con el arranque seguro.

Emerge

Para instalar system-boot:

root #bootctl install
root #emerge --ask sys-apps/systemd

Or

root #emerge --ask sys-apps/systemd-utils

Installation

Now, install the systemd-boot loader to the EFI System Partition:

root #bootctl install
Importante
Asegúrese de que la partición del sistema EFI se haya montado antes de ejecutar bootctl install.

Cuando utilice este gestor de arranque, antes de reiniciar, verifique que exista una nueva entrada de arranque usando:

root #bootctl list
Advertencia
The kernel command line for new systemd-boot entries is read from /etc/kernel/cmdline or /usr/lib/kernel/cmdline. If neither file is present, then the kernel command line of the currently booted kernel is re-used (/proc/cmdline). On new installs it might therefore happen that the kernel command line of the live CD is accidentally used to boot the new kernel. The kernel command line for registered entries can be checked with:
root #bootctl list
If this does not show the desired kernel command line then create /etc/kernel/cmdline containing the correct kernel command line and re-install the kernel.

Si no existe ninguna entrada nueva, asegúrese de que el paquete sys-kernel/installkernel se haya instalado con el indicador USE systemd-boot habilitado y vuelva a ejecutar la instalación del núcleo.

Para núcleos de distribución:

root #emerge --ask --config sys-kernel/gentoo-kernel

Para un núcleo configurado y compilado de forma manual:

root #make install
Importante
Al instalar núcleos para systemd-boot, no se agrega ningún argumento de línea de comandos del núcleo root= de forma predeterminada. En los sistemas systemd que utilizan initramfs, los usuarios pueden confiar en systemd-gpt-auto-generator para encontrar automáticamente la partición raíz en el arranque. De lo contrario, los usuarios deben especificar manualmente la ubicación de la partición raíz configurando root= en /etc/kernel/cmdline así como cualquier otro argumento de la línea de comandos del núcleo que deba ser usado. Y luego reinstalar el núcleo como se describe arriba.

Opcional: Arranque Seguro

Cuando el indicador USE secureboot está habilitado, el ejecutable EFI systemd-boot se firmará automáticamente. bootctl install instalará automáticamente la versión firmada.

Para iniciar correctamente con el arranque seguro habilitado, el certificado utilizado debe ser aceptado por el firmware UEFI o se debe utilizar shim como precargador. Shim está prefirmado con el certificado Microsoft de terceros, aceptado de forma predeterminada por la mayoría de las placas base UEFI.

La forma de configurar el firmware UEFI para aceptar claves personalizadas depende del proveedor del firmware, lo cual está fuera del alcance de este manual. En la página wiki systemd-boot se proporciona un hook postinst para actualizar automáticamente systemd-boot y configurarlo con shim. Sin embargo, la primera vez esto debe hacerse manualmente siguiendo los pasos a continuación:

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

La MOKlist de Shim requiere claves en formato DER, dado que la clave OpenSSL generada en el ejemplo está en formato PEM, la clave debe convertirse antes:

root #openssl x509 -in /ruta/a/kernel_key.pem -inform PEM -out /ruta/a/kernel_key.der -outform DER
Nota
La ruta utilizada aquí debe ser la ruta al archivo pem que contiene el certificado que pertenece a la clave generada. En este ejemplo, tanto la clave como el certificado están en el mismo archivo pem.

Luego, el certificado convertido se puede importar a la MOKlist de Shim:

root #mokutil --import /ruta/a/kernel_key.der
Nota
When the currently booted kernel already trusts the certificate being imported, the message "Already in kernel trusted keyring." will be returned here. If this happens, re-run the above command with the argument --ignore-keyring added.

Y finalmente registramos Shim con el firmware UEFI. En el siguiente comando, boot-disk y boot-partition-id deben reemplazarse con el disco y el identificador de partición de la partición del sistema EFI:

root #efibootmgr --create --disk /dev/boot-disk --part boot-partition-id --loader '\EFI\BOOT\BOOTX64.EFI' --label 'shim' --unicode
Nota
The import process will not be completed until the system is rebooted. After completing all steps in the handbook, restart the system and Shim will load, it will find the import request registered by mokutil. The MokManager application will start and ask for the password that was set when creating the import request. Follow the on-screen instructions to complete the import of the certificate, then reboot the system into the UEFI menu and enable the Secure Boot setting.

Alternativa 2: efibootmgr

Los sistemas informáticos con firmware basado en UEFI técnicamente no necesitan cargadores de arranque secundarios (como por ejemplo, GRUB) para arrancar los núcleos. Los cargadores de arranque secundarios existen para extender la funcionalidad del firmware UEFI durante el proceso de arranque. Usar GRUB (consulte la sección anterior) suele ser más fácil y seguro porque ofrece una manera más flexible para modificar rápidamente los parámetros del kernel en el momento del arranque.

Los administradores de sistemas que deseen adoptar un enfoque minimalista, aunque más rígido, para iniciar el sistema pueden evitar los cargadores de arranque secundarios e iniciar el núcleo Linux como un código auxiliar EFI.

La aplicación sys-boot/efibootmgr es una herramienta que se utiliza para interactuar con el firmware UEFI - gestor de arranque principal del sistema. Normalmente, se usa para agregar o eliminar entradas de inicio a la lista de entradas de inicio del firmware. También puede actualizar la configuración del firmware para que los núcleos Linux que se agregaron previamente como entradas de arranque puedan ejecutarse con opciones adicionales. Estas interacciones se realizan a través de estructuras de datos especiales llamadas variables EFI (de ahí la necesidad de soporte en ele núcleo para las variables EFI).

Asegúrese de revisar el artículo del EFI stub del núcleo antes de continuar. El núcleo debe tener opciones específicas habilitadas para que el firmware UEFI pueda iniciarlo directamente. Puede que sea necesario recompilar el kernel para poder incorporar este soporte.

También es una buena idea consultar el artículo efibootmgr para obtener información adicional.

Nota
Para reiterar, efibootmgr no es un requisito para iniciar un sistema UEFI; simplemente es necesario agregar una entrada para un EFI stub para el núcleo en el firmware UEFI. Cuando se construye apropiadamente con soporte EFI stub, el propio núcleo Linux se puede iniciar directamente. Se pueden incorporar opciones adicionales para la línea de comandos del núcleo Linux (hay una opción de configuración del núcleo llamada CONFIG_CMDLINE. De manera similar, el soporte para initramfs también se puede 'integrar' en el núcleo. Estas decisiones deben tomarse antes de la compilación del kernel, lo que da como resultado una configuración de arranque más estática.

Instale el software efibootmgr:

ARCHIVO /etc/portage/package.accept_keywords/installkernel
sys-kernel/installkernel
sys-boot/uefi-mkconfig
app-emulation/virt-firmware
ARCHIVO /etc/portage/package.use/installkernel
sys-kernel/installkernel efistub

Then reinstall installkernel, create the /efi/EFI/Gentoo directory and reinstall the kernel:

root #emerge --ask sys-kernel/installkernel
root #mkdir -p /efi/EFI/Gentoo

For distribution kernels:

root #emerge --ask --config sys-kernel/gentoo-kernel{,-bin}

For manually managed kernels:

root #make install

Cree la ubicación /efi/EFI/Gentoo y copie el núcleo en esa ubicación, llamándolo bzImage.efi:

root #mkdir -p /efi/EFI/Gentoo
root #cp /boot/vmlinuz-* /efi/EFI/Gentoo/bzImage.efi

Install the efibootmgr package:

root #emerge --ask sys-boot/efibootmgr

Cree una entrada de inicio llamada "gentoo" para el EFI stub para el núcleo recién compilado dentro del firmware UEFI:

root #efibootmgr --create --disk /dev/sda --part 1 --label "gentoo" --loader "\EFI\Gentoo\bzImage.efi"
Nota
El uso de una barra invertida (\) como separador de ruta de directorio es obligatorio cuando se utilizan definiciones UEFI.

Si se utiliza un sistema de ficheros de inicio en RAM (initramfs), entonces añadir la opción de arranque apropiada:

root #efibootmgr --create --disk /dev/sda --part 1 --label "gentoo" --loader "\EFI\Gentoo\bzImage.efi" --unicode "initrd=\efi\initramfs-genkernel-amd64-6.6.21-gentoo"
Consejo
Additional kernel command line options may be parsed by the firmware to the kernel by specifying them along with the initrd=... option as shown above.

Una vez realizados estos cambios, cuando el sistema se reinicie, aparecerá una entrada en el menú de inicio llamada "gentoo".

Imagen del Núcleo Unificada

Si installkernel se configuró para crear e instalar imágenes del núcleo unificadas. La imagen del núcleo unificada ya debería estar instalada en el directorio EFI/Linux en la partición del sistema EFI; si este no es el caso, asegúrese de que el directorio exista y luego ejecute la instalación del núcleo nuevamente como se describe anteriormente en el manual.

Para agregar una entrada de inicio directo para la imagen del núcleo unificado instalada:

root #efibootmgr --create --disk /dev/sda --part 1 --label "gentoo" --loader /efi/EFI/Linux/gentoo-x.y.z.efi


Other Alternatives

For other options that are not covered in the Handbook, see the full list of available bootloaders.


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.

(chroot) livecd #exit
livecd~#cd
livecd~#umount -l /mnt/gentoo/dev{/shm,/pts,}
livecd~#umount -R /mnt/gentoo
livecd~#reboot

¡No olvide retirar la imagen live, de lo contrario puede ser arrancada de nuevo en lugar del sistema Gentoo recién instalado!

Una vez reiniciado en el nuevo entorno Gentoo, es aconsejable finalizar con Finalizando la instalación de Gentoo.