Configurar el núcleo Linux
Opcional: Instalar firmware y/o microcódigo
Firmware
Linux Firmware
Antes de comenzar a configurar las secciones del núcleo, es conveniente tener en cuenta que algunos dispositivos físicos requieren la instalación de firmware adicional, a veces no compatible con FOSS, en el sistema antes de que funcionen correctamente. Este suele ser el caso de las interfaces de red inalámbrica que se encuentran comúnmente en las computadoras de escritorio y portátiles. Los chips de video modernos de proveedores como AMD, Nvidia e Intel, a menudo también requieren archivos de firmware externos para ser completamente funcionales. La mayoría del firmware para dispositivos hardware modernos se puede encontrar en el paquete sys-kernel/linux-firmware.
Se recomienda tener instalado el paquete sys-kernel/linux-firmware antes del reinicio inicial del sistema para tener el firmware disponible en caso de que sea necesario:
root #
emerge --ask sys-kernel/linux-firmware
La instalación de determinados paquetes de firmware suele requerir la aceptación de las licencias de firmware asociadas. Si es necesario, visite la sección de manejo de licencias del Manual para obtener ayuda sobre cómo aceptar licencias.
Es importante tener en cuenta que los símbolos del núcleo que se construyen como módulos (M) cargarán sus archivos de firmware asociados desde el sistema de archivos cuando el núcleo los cargue. No es necesario incluir los archivos de firmware del dispositivo dentro de la imagen binaria del núcleo para los símbolos cargados como módulos.
SOF Firmware
Sound Open Firmware (SOF) is a new open source audio driver meant to replace the proprietary Smart Sound Technology (SST) audio driver from Intel. 10th gen+ and Apollo Lake (Atom E3900, Celeron N3350, and Pentium N4200) Intel CPUs require this firmware for certain features and certain AMD APUs also have support for this firmware. SOF's supported platforms matrix can be found here for more information.
root #
emerge --ask sys-firmware/sof-firmware
Microcódigo
Además del específico para el hardware de gráficos y las interfaces de red, las CPUs también pueden requerir actualizaciones de firmware. Normalmente, este tipo de firmware se conoce como microcódigo. A veces se necesitan revisiones más recientes del microcódigo para parchear la inestabilidad, los problemas de seguridad u otros errores diversos en el hardware de la CPU.
Las actualizaciones de microcódigo para las CPUs de AMD se distribuyen dentro del paquete sys-kernel/linux-firmware mencionado anteriormente. El microcódigo para CPUs Intel se puede encontrar dentro del paquete sys-firmware/intel-microcode, que deberá instalarse por separado. Consulte el artículo sobre microcódigo para obtener más información sobre cómo aplicar actualizaciones de microcódigo.
Configuración y compilación del núcleo
Ahora es el momento de configurar y compilar las fuentes del núcleo. A efectos de instalación, se presentarán tres estrategias para la gestión del núcleo; sin embargo, en cualquier momento posterior a la instalación, se puede cambiar de estrategia.
Clasificadas de menor a mayor complicación:
- Estrategia de automatización total: Núcleos de distribución
- Un Núcleo de distribución se usa para configurar, compilar e instalar automáticamente el núcleo Linux, sus módulos asociados y (opcionalmente, pero habilitado por defecto) un archivo initramfs. Las actualizaciones futuras del núcleo están completamente automatizadas, ya que se manejan a través del administrador de paquetes, como cualquier otro paquete del sistema. Es posible proporcionar un archivo de configuración del núcleo personalizado si es necesaria la personalización. Este es el proceso menos complicado y es perfecto para los nuevos usuarios de Gentoo debido a que funciona de forma inmediata y ofrece una participación mínima por parte del administrador del sistema.
- Estrategia híbrida: Genkernel
- Las nuevas fuentes del núcleo se instalan a través del administrador de paquetes del sistema. Los administradores del sistema usan la herramienta genkernel de Gentoo para configurar, compilar e instalar automáticamente el kernel de Linux, sus módulos asociados y (opcionalmente, pero no habilitado por defecto) un archivo initramfs archivo. Es posible proporcionar un archivo de configuración del núcleo personalizado si es necesaria la personalización. La configuración, compilación e instalación futuras del núcleo requieren la participación del administrador del sistema en la forma de ejecutar eselect kernel, genkernel y potencialmente otros comandos para cada actualización.
- Estrategia completamente manual
- Las nuevas fuentes del núcleo se instalan a través del administrador de paquetes del sistema. El núcleo se configura, construye e instala manualmente usando eselect kernel y una serie de comandos make. Las futuras actualizaciones del núcleo repiten el proceso manual de configuración, creación e instalación de los archivos del núcleo. Este es el proceso más complicado, pero ofrece el máximo control sobre el proceso de actualización del núcleo.
El eje alrededor del cual se construyen todas las distribuciones es el núcleo Linux. Es la capa entre los programas del usuario y el hardware del sistema. Aunque el manual proporciona a sus usuarios varias fuentes posibles del núcleo, hay disponible una lista más completa y con descripciones más detalladas en la página de descripción general del núcleo.
Kernel installation tasks such as, copying the kernel image to /boot or the EFI System Partition, generating an initramfs and/or Unified Kernel Image, updating bootloader configuration, can be automated with installkernel. Users may wish to configure and install sys-kernel/installkernel before proceeding. See the Kernel installation section below for more more information.
Alternativa: Usar núcleos de distribución
Núcleos de distribución son ebuilds que cubren el proceso completo de desempaquetar, configurar, compilar e instalar el núcleo. La principal ventaja de este método es que los núcleos se actualizan a nuevas versiones como parte de la actualización de @world sin necesidad de una acción manual. Los núcleos de distribución tienen una configuración predeterminada que dan soporte a la mayoría del hardware, pero se pueden personalizar mediante /etc/portage/savedconfig.
Instalando un núcleo de distribución
Before installing the kernel package the dracut USE flag needs to be added for the package sys-kernel/installkernel in /etc/portage/package.use:
sys-kernel/installkernel dracut
Users may also wish to enable additional sys-kernel/installkernel USE flags at this stage. See the Installation/Kernel#Installkernel section for details.
Para construir un núcleo con parches de Gentoo desde el código fuente, escriba:
root #
emerge --ask sys-kernel/gentoo-kernel
Los administradores de sistema que quieran evitar compilar las fuentes del núcleo localmente pueden utilizar imágenes del núcleo precompiladas:
root #
emerge --ask sys-kernel/gentoo-kernel-bin
Optional: Signed kernel modules
The kernel modules in the prebuilt distribution kernel (sys-kernel/gentoo-kernel-bin) are already signed. To sign the modules of kernels built from source enable the modules-sign USE flag, and optionally specify which key to use for signing in /etc/portage/make.conf:
USE="modules-sign"
</div>
<div lang="en" dir="ltr" class="mw-content-ltr">
# Optionally, to use custom signing keys.
MODULES_SIGN_KEY="/path/to/kernel_key.pem"
MODULES_SIGN_CERT="/path/to/kernel_key.pem" # Only required if the MODULES_SIGN_KEY does not also contain the certificate.
MODULES_SIGN_HASH="sha512" # Defaults to sha512.
If MODULES_SIGN_KEY is not specified the kernel build system will generate a key, it will be stored in /usr/src/linux-x.y.z/certs. It is recommended to manually generate a key to ensure that it will be the same for each kernel release. A key may be generated with:
root #
openssl req -new -nodes -utf8 -sha256 -x509 -outform PEM -out kernel_key.pem -keyout kernel_key.pem
The MODULES_SIGN_KEY and MODULES_SIGN_CERT may be different files. For this example the pem file generated by OpenSSL includes both the key and the accompanying certificate, and thus both variables are set to the same value.
OpenSSL will ask some questions about the user generating the key, it is recommended to fill in these questions as detailed as possible.
Store the key in a safe location, at the very least the key should be readable only by the root user. Verify this with:
root #
ls -l kernel_key.pem
-r-------- 1 root root 3164 Jan 4 10:38 kernel_key.pem
If this outputs anything other then the above, correct the permissions with:
root #
chown root:root kernel_key.pem
root #
chmod 400 kernel_key.pem
Optional: Signing the kernel image (Secure Boot)
The kernel image in the prebuilt distribution kernel (sys-kernel/gentoo-kernel-bin) is already signed for use with Secure Boot. To sign the kernel image of kernels built from source enable the secureboot USE flag, and optionally specify which key to use for signing in /etc/portage/make.conf. Note that signing the kernel image for use with secureboot requires that the kernel modules are also signed, the same key may be used to sign both the kernel image and the kernel modules:
USE="modules-sign secureboot"
</div>
<div lang="en" dir="ltr" class="mw-content-ltr">
# Optionally, to use custom signing keys.
MODULES_SIGN_KEY="/path/to/kernel_key.pem"
MODULES_SIGN_CERT="/path/to/kernel_key.pem" # Only required if the MODULES_SIGN_KEY does not also contain the certificate.
MODULES_SIGN_HASH="sha512" # Defaults to sha512.
</div>
<div lang="en" dir="ltr" class="mw-content-ltr">
# Optionally, to boot with secureboot enabled, may be the same or different signing key.
SECUREBOOT_SIGN_KEY="/path/to/kernel_key.pem"
SECUREBOOT_SIGN_CERT="/path/to/kernel_key.pem"
The SECUREBOOT_SIGN_KEY and SECUREBOOT_SIGN_CERT may be different files. For this example the pem file generated by OpenSSL includes both the key and the accompanying certificate, and thus both variables are set to the same value.
For this example the same key that was generated to sign the modules is used to sign the kernel image. It is also possible to generate and use a second separate key for signing the kernel image. The same OpenSSL command as in the previous section may be used again.
See the above section for instructions on generating a new key, the steps may be repeated if a separate key should be used to sign the kernel image.
To successfully boot with Secure Boot enabled, the used bootloader must also be signed and the certificate must be accepted by the UEFI firmware or Shim. This will be explained later in the handbook.
Actualización y limpieza
Una vez que el núcleo está instalado, el administrador de paquetes lo actualizará automáticamente a versiones más nuevas. Las versiones anteriores se conservarán hasta que se solicite al administrador de paquetes que limpie los paquetes obsoletos. Recuerde ejecutar periódicamente:
root #
emerge --depclean
para ahorrar espacio. Alternativamente, para limpiar específicamente versiones antiguas del núcleo:
root #
emerge --prune sys-kernel/gentoo-kernel sys-kernel/gentoo-kernel-bin
Tareas posteriores a la instalación/actualización
Los núcleos de distribución ahora son capaces de reconstruir los módulos del núcleo instalados por otros paquetes. linux-mod.eclass
proporciona USE=dist-kernel
que controla una dependencia de subslot en virtual/dist-kernel.
Habilitar esto en paquetes como sys-fs/zfs y sys-fs/zfs-kmod les permite ser reconstruidos automáticamente contra el nuevo núcleo y volver a generar el initramfs si corresponde.
Reconstrucción manual de initramfs
Si es necesario, active manualmente tales reconstrucciones, después de una actualización del núcleo, ejecutando:
root #
emerge --ask @module-rebuild
Si se necesita alguno de estos módulos (por ejemplo, ZFS) en el arranque temprano, reconstruya el initramfs después:
root #
emerge --config sys-kernel/gentoo-kernel
root #
emerge --config sys-kernel/gentoo-kernel-bin
Instalar las fuentes del núcleo
Esta sección solo es relevante cuando se usa lo siguiente genkernel (híbrido) o configuración manual de la gestión del núcleo.
The use of sys-kernel/installkernel is not strictly required, but highly recommended. When this package is installed, the kernel installation process will be delegated to installkernel. This allows for installing several different kernel versions side-by-side as well as managing and automating several tasks relating to kernel installation described later in the handbook. Install it now with:
root #
emerge --ask sys-kernel/installkernel
Al instalar y compilar el núcleo para sistemas basados en amd64, Gentoo recomienda el paquete sys-kernel/gentoo-sources.
Elija una fuente del núcleo adecuada e instálela usando emerge:
root #
emerge --ask sys-kernel/gentoo-sources
Esto instalará las fuentes del núcleo Linux en /usr/src/ usando la versión específica del kernel en el nombre de la ruta. No creará un enlace simbólico de forma automática a no ser que la USE=symlink
esté habilitada en el paquete de fuentes del núcleo elegido.
Es una convencion que se mantenga el enlace simbólico /usr/src/linux, de modo que se refiera a las fuentes que correspondan con el núcleo que se está ejecutando actualmente. Sin embargo, este enlace simbólico no se creará por defecto. Una manera fácil de crear el enlace simbólico es utilizar el módulo kernel de eselect.
Para obtener más información sobre la finalidad del enlace simbólico y cómo administrarlo, consulte Kernel/Upgrade/es.
Primero, enumere todos los núcleos instalados:
root #
eselect kernel list
Available kernel symlink targets: [1] linux-6.1.38-gentoo
Para crear un enlace simbólico llamado linux, use:
root #
eselect kernel set 1
root #
ls -l /usr/src/linux
lrwxrwxrwx 1 root root 12 Oct 13 11:04 /usr/src/linux -> linux-6.1.38-gentoo
Alternativa: Genkernel
In case it was missed, this section requires the kernel sources to be installed. Be sure to obtain the relevant kernel sources, then return here for the rest of section.
Si una configuración completamente manual parece demasiado desafiante, los administradores del sistema deberían considerar usar genkernel como un enfoque híbrido para el mantenimiento del núcleo.
Genkernel proporciona un archivo de configuración de núcleo genérico, automáticamente genera el kernel (núcleo), initramfs y los módulos asociados, y luego instala los archivos binarios resultantes en las ubicaciones apropiadas . Esto da como resultado una compatibilidad con el hardware mínima y genérica para el primer arranque del sistema y permite un control adicional de actualizaciones y personalización de la configuración del núcleo en el futuro.
Queda avisado: si bien el uso de genkernel para mantener el núcleo brinda a los administradores del sistema un mayor control de actualización sobre el núcleo del sistema, initramfs y otras opciones, "requerirán" un compromiso de tiempo y esfuerzo para materializar las futuras actualizaciones del núcleo a medida que se lanzan nuevas fuentes. Aquellos que busquen un enfoque de no intervención para el mantenimiento del núcleo deberían usar un núcleo de distribución.
Para mayor claridad, es un "concepto erróneo" creer que genkernel genera automáticamente una configuración del núcleo "personalizada" para el hardware en el que se ejecuta; utiliza una configuración del núcleo determinada que admite la mayoría del hardware genérico y maneja automáticamente los comandos make necesarios para ensamblar e instalar el núcleo, los módulos asociados y el archivo initramfs.
Grupo de licencias de software binario redistribuible
Si el paquete de firmware de linux se instaló previamente, salte a la sección de instalación.
Como requisito previo, debido a que el valor USE firwmare
está habilitado de forma predeterminada para el paquete sys-kernel/genkernel, el administrador de paquetes también intentará instalar el paquete sys-kernel/linux-firmware. Las licencias de software binario redistribuible deben aceptarse antes de que se instale el linux-firmware.
Este grupo de licencias se puede aceptar de forma global para cualquier paquete agregando @BINARY-REDISTRIBUTABLE
como un valor ACCEPT_LICENSE en el archivo /etc/portage/make. conf. Se puede aceptar exclusivamente para el paquete de linux-firmware agregando una inclusión específica a través de un archivo /etc/portage/package.license/linux-firmware.
Si es necesario, revise los métodos para aceptar licencias de software disponibles en el capítulo Instalando el sistema base del manual, luego realice algunos cambios para las licencias de software aceptables.
Si no sabe qué decidir sobre este tema, lo siguiente funcionará:
root #
mkdir /etc/portage/package.license
sys-kernel/linux-firmware @BINARY-REDISTRIBUTABLE
Instalación
Además de las explicaciones y los requisitos previos, instale el paquete sys-kernel/genkernel:
root #
emerge --ask sys-kernel/genkernel
Generación
Compile las fuentes del núcleo ejecutando genkernel all. Sin embargo, tenga en cuenta que genkernel compila un núcleo que admite una amplia gama de hardware para diferentes arquitecturas de computadoras, por lo que esta compilación puede tardar bastante en finalizar.
Si la partición/volumen raíz usa un sistema de archivos que no sea ext4, puede ser necesario configurar manualmente el núcleo usando genkernel --menuconfig all para agregar soporte integrado en el núcleo para el sistema de archivos en particular (es decir, no construir el soporte al sistema de archivos como un módulo).
Los usuarios de LVM2 deben añadir
--lvm
como argumento a la siguiente orden genkernel.root #
genkernel --mountboot --install all
Una vez finalice genkernel, se generarán e instalarán un núcleo y un sistema de archivos de inicio en ram (initramfs) en el directorio /boot. Los módulos asociados se instalarán en el directorio /lib/modules. El initramfs se iniciará inmediatamente después de cargar el núcleo para realizar la detección automática de hardware (al igual que en los entornos de imagen de disco vivo).
root #
ls /boot/vmlinu* /boot/initramfs*
root #
ls /lib/modules
Alternativa: Configuración manual
Introducción
In case it was missed, this section requires the kernel sources to be installed. Be sure to obtain the relevant kernel sources, then return here for the rest of section.
La configuración manual de un núcleo a menudo se considera el procedimiento más difícil que un usuario de Linux debe realizar. Nada mas falso - ¡después de configurar un par de núcleos, nadie recuerda que fuera difícil!
Sin embargo, una cosa sí es cierta: es vital conocer el sistema para configurar manualmente un núcleo. La mayor cantidad de información se puede obtener instalando sys-apps/pciutils que contiene la orden lspci:
root #
emerge --ask sys-apps/pciutils
Dentro de la jaula chroot, se pueden ignorar con tranquilidad las advertencias sobre pcilib (como pcilib: cannot open /sys/bus/pci/devices) que pudiera mostrar lspci.
Otra fuente de información sobre nuestro sistema consiste en ejecutar lsmod para ver los módulos del nucleo que ha usado el CD de instalación y tener así buenas indicaciones sobre qué habilitar.
Ahora vaya al directorio de las fuentes del núcleo y ejecute make menuconfig. Esto generará una pantalla de configuración basada en menús.
root #
cd /usr/src/linux
root #
make menuconfig
La configuración del núcleo Linux tiene muchas, muchas secciones. Veamos primero una lista con algunas opciones que deben ser activadas (en caso contrario Gentoo no funcionará o no funcionará adecuadamente sin ajustes adicionales). También tenemos la Guía de configuración del núcleo Gentoo en la wiki de Gentoo que también podría ayudar.
Habilitar las opciones esenciales
Al usar sys-kernel/gentoo-sources, se recomienda encarecidamente que se habiliten las opciones de configuración específicas de Gentoo. Ésto asegura que estén disponibles un mínimo de características del núcleo requeridas para el funcionamiento adecuado:
Gentoo Linux --->
Generic Driver Options --->
[*] Gentoo Linux support
[*] Linux dynamic and persistent device naming (userspace devfs) support
[*] Select options required by Portage features
Support for init systems, system and service managers --->
[*] OpenRC, runit and other script based systems and managers
[*] systemd
Naturalmente, la elección en las últimas dos líneas depende del sistema de inicio seleccionado (OpenRC vs. systemd). No está de más tener habilitado el soporte para ambos sistemas de inicio.
Al usar sys-kernel/vanilla-sources, las selecciones adicionales para los sistemas de inicio no estarán disponibles. Es posible habilitar el soporte, pero va más allá del alcance del manual.
Habilitar soporte para componentes típicos del sistema
Asegúrese de que todos los controladores que son vitales para el arranque del sistema (como los controladores SATA, la compatibilidad con dispositivos de bloque NVMe, la compatibilidad con sistemas de archivos, etc.) estén compilados dentro del núcleo y no como un módulos; de lo contrario, es posible que el sistema no pueda arranque por completo.
A continuación seleccione con exactitud el tipo de procesador. Se recomienda habilitar las funcionalidades MCE (si están disponibles) de manera que los usuarios puedan ser informados de cualquier problema en este hardware. En algunas arquitecturas (como x86_64) estos errores no son presentados a través de dmesg sino de /dev/mcelog. Para ello se requiere el paquete app-admin/mcelog.
A continuación seleccione Maintain a devtmpfs file system to mount at /dev de modo que los archivos de dispositivo críticos estén disponibles cuanto antes en el proceso de inicio (CONFIG_DEVTMPFS y CONFIG_DEVTMPFS_MOUNT):
Device Drivers --->
Generic Driver Options --->
[*] Maintain a devtmpfs filesystem to mount at /dev
[*] Automount devtmpfs at /dev, after the kernel mounted the rootfs
Verificar que se ha activado el soporte de disco SCSI (CONFIG_BLK_DEV_SD):
Device Drivers --->
SCSI device support --->
<*> SCSI device support
<*> SCSI disk support
Device Drivers --->
<*> Serial ATA and Parallel ATA drivers (libata) --->
[*] ATA ACPI Support
[*] SATA Port Multiplier support
<*> AHCI SATA support (ahci)
[*] ATA BMDMA support
[*] ATA SFF support (for legacy IDE and PATA)
<*> Intel ESB, ICH, PIIX3, PIIX4 PATA/SATA support (ata_piix)
Verifique que se haya habilitado el soporte básico para NVMe:
Device Drivers --->
<*> NVM Express block device
Device Drivers --->
NVME Support --->
<*> NVM Express block device
No está de más habilitar el siguiente soporte NVMe adicional:
[*] NVMe multipath support
[*] NVMe hardware monitoring
<M> NVM Express over Fabrics FC host driver
<M> NVM Express over Fabrics TCP host driver
<M> NVMe Target support
[*] NVMe Target Passthrough support
<M> NVMe loopback device support
<M> NVMe over Fabrics FC target driver
< > NVMe over Fabrics FC Transport Loopback Test driver (NEW)
<M> NVMe over Fabrics TCP target support
Vaya ahora a File Systems y seleccione el soporte para los sistemas de archivos que se vayan a usar en el sistema. No compile como módulo el sistema de archivos que vaya a utilizar para el sistema de archivos raíz, de lo contrario su sistema Gentoo podría no conseguir montar la partición raíz. También deberá seleccionar Virtual memory y /proc file system. Selecionar una o más de las siguientes opciones según las necesidades del sistema:
File systems --->
<*> Second extended fs support
<*> The Extended 3 (ext3) filesystem
<*> The Extended 4 (ext4) filesystem
<*> Btrfs filesystem support
DOS/FAT/NT Filesystems --->
<*> MSDOS fs support
<*> VFAT (Windows-95) fs support
Pseudo Filesystems --->
[*] /proc file system support
[*] Tmpfs virtual memory file system support (former shm fs)
Si está usando PPPoE para conectarse a Internet, o está usando un módem telefónico, habilite las siguientes opciones (CONFIG_PPP, CONFIG_PPP_ASYNC y CONFIG_PPP_SYNC_TTY):
Device Drivers --->
Network device support --->
<*> PPP (point-to-point protocol) support
<*> PPP over Ethernet
<*> PPP support for async serial ports
<*> PPP support for sync tty ports
Las dos opciones de compresión no están de más aunque no son necesarias, como tampoco lo es la opción PPP sobre Ethernet, que sólo podría utilizarse cuando se configure un núcleo en modo PPPoE.
No olvide incluir el soporte en el núcleo para su tarjeta de red (Ethernet o inalámbrica).
Muchos sistemas también tienen varios núcleos de microprocesador a su disposición, así que es importánte activar Symmetric multi-processing support (CONFIG_SMP):
Processor type and features --->
[*] Symmetric multi-processing support
En sistemas multi-núcleo, cada núcleo cuenta como un procesador.
Si utiliza dispositivos de entrada USB (como un teclado o un ratón) u otros, no olvide activarlos también:
Device Drivers --->
HID support --->
-*- HID bus support
<*> Generic HID driver
[*] Battery level reporting for HID devices
USB HID support --->
<*> USB HID transport layer
[*] USB support --->
<*> xHCI HCD (USB 3.0) support
<*> EHCI HCD (USB 2.0) support
<*> OHCI HCD (USB 1.1) support
<*> Unified support for USB4 and Thunderbolt --->
Optional: Signed kernel modules
To automatically sign the kernel modules enable CONFIG_MODULE_SIG_ALL:
[*] Enable loadable module support
-*- Module signature verification
[*] Automatically sign all modules
Which hash algorithm should modules be signed with? (Sign modules with SHA-512) --->
Optionally change the hash algorithm if desired.
To enforce that all modules are signed with a valid signature, enable CONFIG_MODULE_SIG_FORCE as well:
[*] Enable loadable module support
-*- Module signature verification
[*] Require modules to be validly signed
[*] Automatically sign all modules
Which hash algorithm should modules be signed with? (Sign modules with SHA-512) --->
To use a custom key, specify the location of this key in CONFIG_MODULE_SIG_KEY, if unspecified the kernel build system will generate a key. It is recommended to generate one manually instead. This can be done with:
root #
openssl req -new -nodes -utf8 -sha256 -x509 -outform PEM -out kernel_key.pem -keyout kernel_key.pem
OpenSSL will ask some questions about the user generating the key, it is recommended to fill in these questions as detailed as possible.
Store the key in a safe location, at the very least the key should be readable only by the root user. Verify this with:
root #
ls -l kernel_key.pem
-r-------- 1 root root 3164 Jan 4 10:38 kernel_key.pem
If this outputs anything other then the above, correct the permissions with:
root #
chown root:root kernel_key.pem
root #
chmod 400 kernel_key.pem
-*- Cryptographic API --->
Certificates for signature checking --->
(/path/to/kernel_key.pem) File name or PKCS#11 URI of module signing key
To also sign external kernel modules installed by other packages via linux-mod-r1.eclass
, enable the modules-sign USE flag globally:
USE="modules-sign"
</div>
<div lang="en" dir="ltr" class="mw-content-ltr">
# Optionally, when using custom signing keys.
MODULES_SIGN_KEY="/path/to/kernel_key.pem"
MODULES_SIGN_CERT="/path/to/kernel_key.pem" # Only required if the MODULES_SIGN_KEY does not also contain the certificate
MODULES_SIGN_HASH="sha512" # Defaults to sha512
The MODULES_SIGN_KEY and MODULES_SIGN_CERT may be different files. For this example the pem file generated by OpenSSL includes both the key and the accompanying certificate, and thus both variables are set to the same value.
Optional: Signing the kernel image (Secure Boot)
When signing the kernel image (for use on systems with Secure Boot enabled) it is recommended to set the following kernel config options:
General setup --->
Kexec and crash features --->
[*] Enable kexec system call
[*] Enable kexec file based system call
[*] Verify kernel signature during kexec_file_load() syscall
[*] Require a valid signature in kexec_file_load() syscall
[*] Enable ""image"" signature verification support
</div>
<div lang="en" dir="ltr" class="mw-content-ltr">
[*] Enable loadable module support
-*- Module signature verification
[*] Require modules to be validly signed
[*] Automatically sign all modules
Which hash algorithm should modules be signed with? (Sign modules with SHA-512) --->
</div>
<div lang="en" dir="ltr" class="mw-content-ltr">
Security options --->
[*] Integrity subsystem
[*] Basic module for enforcing kernel lockdown
[*] Enable lockdown LSM early in init
Kernel default lockdown mode (Integrity) --->
</div>
<div lang="en" dir="ltr" class="mw-content-ltr">
[*] Digital signature verification using multiple keyrings
[*] Enable asymmetric keys support
-*- Require all keys on the integrity keyrings be signed
[*] Provide keyring for platform/firmware trusted keys
[*] Provide a keyring to which Machine Owner Keys may be added
[ ] Enforce Machine Keyring CA Restrictions
Where ""image"" is a placeholder for the architecture specific image name. These options, from the top to the bottom: enforces that the kernel image in a kexec call must be signed (kexec allows replacing the kernel in-place), enforces that kernel modules are signed, enables lockdown integrity mode (prevents modifying the kernel at runtime), and enables various keychains.
On arches that do not natively support decompressing the kernel (e.g. arm64 and riscv), the kernel must be built with its own decompressor (zboot):
Device Drivers --->
Firmware Drivers --->
EFI (Extensible Firmware Interface) Support --->
[*] Enable the generic EFI decompressor
After compilation of the kernel, as explained in the next section, the kernel image must be signed. First install app-crypt/sbsigntools and then sign the kernel image:
root #
emerge --ask app-crypt/sbsigntools
root #
sbsign /usr/src/linux-x.y.z/path/to/kernel-image --cert /path/to/kernel_key.pem --key /path/to/kernel_key.pem --out /usr/src/linux-x.y.z/path/to/kernel-image
For this example the same key that was generated to sign the modules is used to sign the kernel image. It is also possible to generate and use a second sperate key for signing the kernel image. The same OpenSSL command as in the previous section may be used again.
Then proceed with the installation.
To automatically sign EFI executables installed by other packages, enable the secureboot USE flag globally:
USE="modules-sign secureboot"
</div>
<div lang="en" dir="ltr" class="mw-content-ltr">
# Optionally, to use custom signing keys.
MODULES_SIGN_KEY="/path/to/kernel_key.pem"
MODULES_SIGN_CERT="/path/to/kernel_key.pem" # Only required if the MODULES_SIGN_KEY does not also contain the certificate.
MODULES_SIGN_HASH="sha512" # Defaults to sha512
</div>
<div lang="en" dir="ltr" class="mw-content-ltr">
# Optionally, to boot with secureboot enabled, may be the same or different signing key.
SECUREBOOT_SIGN_KEY="/path/to/kernel_key.pem"
SECUREBOOT_SIGN_CERT="/path/to/kernel_key.pem"
The SECUREBOOT_SIGN_KEY and SECUREBOOT_SIGN_CERT may be different files. For this example the pem file generated by OpenSSL includes both the key and the accompanying certificate, and thus both variables are set to the same value.
When generating an Unified Kernel Image with systemd's
ukify
the kernel image will be signed automatically before inclusion in the unified kernel image and it is not necessary to sign it manually.
Configuración del núcleo específica para la arquitectura
Asegúrese de seleccionar la emulación IA32 si desea ejecutar programas de 32 bits (CONFIG_IA32_EMULATION). Gentoo instala por defecto un sistema multilib (procesado indistinto 32 bits/64 bits) de modo que, a no ser que se use un perfil no-multilib, está opción es necesaria.
Processor type and features --->
[ ] Machine Check / overheating reporting
[ ] Intel MCE Features
[ ] AMD MCE Features
Processor family (AMD-Opteron/Athlon64) --->
( ) Opteron/Athlon64/Hammer/K8
( ) Intel P4 / older Netburst based Xeon
( ) Core 2/newer Xeon
( ) Intel Atom
( ) Generic-x86-64
Binary Emulations --->
[*] IA32 Emulation
Habilite el soporte de etiquetado de particiones GPT si se utilizó previamente durante el particionado del disco (CONFIG_PARTITION_ADVANCED and CONFIG_EFI_PARTITION):
-*- Enable the block layer --->
Partition Types --->
[*] Advanced partition selection
[*] EFI GUID Partition support
Habilitar el soporte EFI stub, variables EFI y el EFI Framebuffer en el núcleo Linux si se va a usar UEFI para arrancar el sistema (CONFIG_EFI, CONFIG_EFI_STUB, CONFIG_EFI_MIXED, CONFIG_EFI_VARS, y CONFIG_EFI_FB):
Processor type and features --->
[*] EFI runtime service support
[*] EFI stub support
[*] EFI mixed-mode support
Device Drivers
Firmware Drivers --->
EFI (Extensible Firmware Interface) Support --->
<*> EFI Variable Support via sysfs
Graphics support --->
Frame buffer Devices --->
<*> Support for frame buffer devices --->
[*] EFI-based Framebuffer Support
Device Drivers --->
Sound card support --->
Advanced Linux Sound Architecture --->
<M> ALSA for SoC audio support --->
[*] Sound Open Firmware Support --->
<M> SOF PCI enumeration support
<M> SOF ACPI enumeration support
<M> SOF support for AMD audio DSPs
[*] SOF support for Intel audio DSPs
Compilar e instalar
Una vez hecha la configuración, es hora de compilar e instalar el núcleo. Salga del configurador e inicie el proceso de compilación:
root #
make && make modules_install
Es posible permitir compilaciones paralelas usando make -jX siendo
X
un número entero de compilaciones paralelas que se le permiten lanzar al proceso de construcción. Esto es similar a las instrucciones anteriores sobre /etc/portage/make.conf con la variable MAKEOPTS.Cuando finalice la compilación del núcleo copie su archivo imagen a /boot/. Se hará con la orden make install:
root #
make install
Esto copiará la imagen del núcleo en /boot/ junto con el archivo System.map y el archivo de configuración del núcleo.
Kernel installation
Installkernel
Installkernel may be used to automate, the kernel installation, initramfs generation, unified kernel image generation and/or bootloader configuration among other things. sys-kernel/installkernel implements two paths of achieving this: the traditional installkernel originating from Debian and systemd's kernel-install. Which one to choose depends, among other things, on the system's bootloader. By default systemd's kernel-install is used on systemd profiles, while the traditional installkernel is the default for other profiles.
If unsure, follow the 'Traditional layout' subsection below.
systemd-boot
When using systemd-boot (formerly gummiboot) as the bootloader, systemd's kernel-install must be used. Therefore ensure the systemd and the systemd-boot USE flags are enabled on sys-kernel/installkernel, and then install the relevant package for systemd-boot.
On OpenRC systems:
sys-apps/systemd-utils boot kernel-install
sys-kernel/installkernel systemd systemd-boot
root #
emerge --ask sys-apps/systemd-utils
On systemd systems:
sys-apps/systemd boot
sys-kernel/installkernel systemd-boot
root #
emerge --ask sys-apps/systemd
GRUB
Users of GRUB can use either systemd's kernel-install or the traditional Debian installkernel. The systemd USE flag switches between these implementations. To automatically run grub-mkconfig when installing the kernel, enable the grub USE flag.
sys-kernel/installkernel grub
root #
emerge --ask sys-kernel/installkernel
Traditional layout, other bootloaders (e.g. lilo, etc.)
The traditional /boot layout (for e.g. LILO, etc.) is used by default if the grub, systemd-boot and uki USE flags are not enabled. No further action is required.
Building an initramfs
In certain cases it is necessary to build an initramfs - an initial ram-based file system. The most common reason is when important file system locations (like /usr/ or /var/) are on separate partitions. With an initramfs, these partitions can be mounted using the tools available inside the initramfs. The default configuration of the Project:Distribution Kernel requires an initramfs.
Without an initramfs, there is a risk that the system will not boot properly as the tools that are responsible for mounting the file systems require information that resides on unmounted file systems. An initramfs will pull in the necessary files into an archive which is used right after the kernel boots, but before the control is handed over to the init tool. Scripts on the initramfs will then make sure that the partitions are properly mounted before the system continues booting.
If using genkernel, it should be used for both building the kernel and the initramfs. When using genkernel only for generating an initramfs, it is crucial to pass
--kernel-config=/path/to/kernel.config
to genkernel or the generated initramfs may not work with a manually built kernel. Note that manually built kernels go beyond the scope of support for the handbook. See the kernel configuration article for more information.Installkernel can automatically generate an initramfs when installing the kernel if the dracut USE flag is enabled:
sys-kernel/installkernel dracut
Alternatively, dracut may be called manually to generate an initramfs. Install sys-kernel/dracut first, then have it generate an initramfs:
root #
emerge --ask sys-kernel/dracut
root #
dracut --kver=6.1.38-gentoo
The initramfs will be stored in /boot/. The resulting file can be found by simply listing the files starting with initramfs:
root #
ls /boot/initramfs*
Optional: Building an Unified Kernel Image
An Unified Kernel Image (UKI) combines, among other things, the kernel, the initramfs and the kernel command line into a single executable. Since the kernel command line is embedded into the unified kernel image it should be specified before generating the unified kernel image (see below). Note that any kernel command line arguments supplied by the bootloader or firmware at boot are ignored when booting with secure boot enabled.
An unified kernel image requires a stub loader, currently the only one available is systemd-stub. To enable it:
For systemd systems:
sys-apps/systemd boot
For OpenRC systems:
sys-apps/systemd-utils boot kernel-install
Installkernel can automatically generate an unified kernel image using either dracut or ukify, by enabling the respective flag. The uki USE flag should be enabled as well to install the generated unified kernel image to the $ESP/EFI/Linux directory on the EFI system partition (ESP).
For dracut:
sys-kernel/installkernel dracut uki
uefi="yes"
kernel_cmdline="some-kernel-command-line-arguments"
For ukify:
sys-apps/systemd ukify # For systemd systems
sys-apps/systemd-utils ukify # For OpenRC systems
sys-kernel/installkernel dracut ukify uki
some-kernel-command-line-arguments
Note that while dracut can generate both an initramfs and an unified kernel image, ukify can only generate the latter and therefore the initramfs must be generated separately with dracut.
Generic Unified Kernel Image
The prebuilt sys-kernel/gentoo-kernel-bin can optionally install a prebuilt generic unified kernel image containing a generic initramfs that is able to boot most systemd based systems. It can be installed by enabling the generic-uki USE flag, and configuring installkernel to not generate a custom initramfs or unified kernel image:
sys-kernel/gentoo-kernel-bin generic-uki
sys-kernel/installkernel -dracut -ukify uki
Secure Boot
The generic Unified Kernel Image optionally distributed by sys-kernel/gentoo-kernel-bin is already pre-signed. How to sign a locally generated unified kernel image depends on whether dracut or ukify is used. Note that the location of the key and certificate should be the same as the SECUREBOOT_SIGN_KEY and SECUREBOOT_SIGN_CERT as specified in /etc/portage/make.conf.
For dracut:
uefi="yes"
kernel_cmdline="some-kernel-command-line-arguments"
uefi_secureboot_key="/path/to/kernel_key.pem"
uefi_secureboot_cert="/path/to/kernel_key.pem"
For ukify:
[UKI]
SecureBootPrivateKey=/path/to/kernel_key.pem
SecureBootCertificate=/path/to/kernel_key.pem
Rebuilding external kernel modules
External kernel modules installed by other packages via linux-mod-r1.eclass
must be rebuilt for each new kernel version. When the distribution kernels are used this may be automated by enabling the dist-kernel flag globally.
*/* dist-kernel
External kernel modules may also be rebuilt manually with:
root #
emerge --ask @module-rebuild
Módulos del núcleo
Listado de módulos del núcleo disponibles
Es opcional el hacer un listado manual de los módulos que se necesitan para el hardware. udev normalmente cargará todos los módulos para el hardware que se detecte al ser conectado, en la mayoría de los casos. Sin embargo, no es perjudicial que se enumeren los módulos que se cargarán automáticamente. Los módulos no se pueden cargar dos veces; se cargan o se descargan. A veces, el hardware exótico requiere ayuda para cargar sus controladores.
Los módulos que deben cargarse durante cada arranque se pueden agregar a los archivos /etc/modules-load.d/*.conf en el formato de un módulo por línea. En cambio cuando se necesitan opciones adicionales para los módulos, deben indicarse en los archivos /etc/modprobe.d/*.conf.
Para ver todos los módulos disponibles para una versión de núcleo en concreto, lance la siguiente orden find. No olvide sustituir "<versión del núcleo>" con la versión apropiada del núcleo a buscar:
root #
find /lib/modules/<versión del núcleo>/ -type f -iname '*.o' -or -iname '*.ko' | less
Forzar la carga de módulos concretos del núcleo
Para forzar la carga del núcleo para que cargue el módulo 3c59x.ko (que es el controlador para una familia de tarjetas de red 3Com específica), edite /etc/modules-load.d/network.conf e ingrese el nombre del módulo dentro de él.
root #
mkdir -p /etc/modules-load.d
root #
nano -w /etc/modules-load.d/network.conf
Tenga en cuenta que el sufijo del archivo .ko del módulo es insignificante para el mecanismo de carga y no se incluye en el archivo de configuración:
3c59x
Continúe la instalación con Configurar el sistema.