Manual de Gentoo: PPC64/Instalación/Núcleo
Opcional: Instalar firmware y/o microcódigo
Firmware
Firmware para Linux
On many systems, non-FOSS firmware is required for certain hardware to function. The sys-kernel/linux-firmware package contains firmware for many, but not all, devices.
Most wireless cards and GPUs require firmware to function.
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.
Firmware Loading
Firmware files are typically loaded when the associated kernel module is loaded. This means the firmware must be built into the kernel using CONFIG_EXTRA_FIRMWARE if the kernel module is set to Y instead of M. In most cases, building-in a module which required firmware can complicate or break loading.
{{#switch: ppc64 | amd64 | x86 =
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.
sys-kernel/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.
Bootloader
Now is the time to think about which bootloader the user wants for the system, if unsure, follow the 'Traditional layout' subsection below.
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.
/etc/portage/package.use/installkernel
sys-kernel/installkernel grub
root #
emerge --ask sys-kernel/installkernel
Traditional layout, other bootloaders (e.g. (e)lilo, syslinux, etc.)
The traditional /boot layout (for e.g. (e)LILO, syslinux, etc.) is used by default if the grub, systemd-boot, efistub and uki USE flags are not enabled. No further action is required.
Construir un initramfs
An initial ram-based file system, or initramfs, may be required for a system to boot. A wide of variety of cases may necessitate one, but common cases include:
- Kernels where storage/filesystem drivers are modules.
- Layouts with /usr/ or /var/ on separate partitions.
- Encrypted root filesystems.
Distribution kernels are designed to be used with an initramfs, as many storage and filesystem drivers are built as modules.
In addition to mounting the root filesystem, an initramfs may also perform other tasks such as:
- Running file system consistency check fsck, a tool to check and repair consistency of a file system in such events of uncleanly shutdown a system.
- Providing a recovery environment in the event of late-boot failures.
Installkernel puede generar automáticamente un initramfs al instalar el núcleo si el indicador USE dracut está habilitado:
/etc/portage/package.use/installkernel
sys-kernel/installkernel dracut
root #
emerge --ask sys-kernel/installkernel
{{#switch: ppc64 | amd64 | arm64 | x86 =
Opcional: Creación de una imagen de núcleo unificada
Una Imagen de Núcleo Unificada (UKI) combina, entre otras cosas, el núcleo, el initramfs y la línea de comandos del núcleo en un único ejecutable. Dado que la línea de comandos del núcleo está integrada en la imagen del núcleo unificada, se debe especificar antes de generar la imagen del núcleo unificada (ver más abajo). Tenga en cuenta que cualquier argumento de la línea de comandos del núcleo proporcionado por el gestor de arranque o el firmware durante el arranque se ignora cuando se inicia con el arranque seguro habilitado.
Una imagen de núcleo unificada requiere un cargador de código auxiliar; actualmente el único disponible es systemd-stub. Para habilitarlo:
En sistemas systemd:
/etc/portage/package.use/systemd
sys-apps/systemd boot
root #
emerge --ask sys-apps/systemd
En sistemas OpenRC:
/etc/portage/package.use/systemd-utils
sys-apps/systemd-utils boot kernel-install
root #
emerge --ask sys-apps/systemd-utils
Installkernel puede generar automáticamente una imagen de núcleo unificada usando dracut o ukify, habilitando el indicador respectivo. El indicador USE uki también debe estar habilitado para instalar la imagen del núcleo unificada generada en el directorio $ESP/EFI/Linux en la partición del sistema EFI (ESP).
Para dracut:
/etc/portage/package.use/installkernel
sys-kernel/installkernel dracut uki
/etc/dracut.conf
uefi="yes"
kernel_cmdline="argumentos-para-la-linea-comandos-del-núcleo"
root #
emerge --ask sys-kernel/installkernel
Para ukify:
/etc/portage/package.use/installkernel
sys-apps/systemd ukify # Para sistemas systemd
sys-apps/systemd-utils ukify # Para sistemas OpenRC
sys-kernel/installkernel dracut ukify uki
/etc/kernel/cmdline
argumentos-para-la-linea-comandos-del-núcleo
root #
emerge --ask sys-kernel/installkernel
Tenga en cuenta que, si bien dracut puede generar tanto initramfs como una imagen de núcleo unificada, ukify solo puede generar esta última y, por lo tanto, el initramfs debe generarse por separado con dracut.
In the above configuration examples (for both Dracut and ukify) it is important to specify at least an appropriate root= parameter for the kernel command line to ensure that the Unified Kernel Image can find the root partition. This is not required for systemd based systems following the Discoverable Partitions Specification (DPS), in that case the embedded initramfs will be able to dynamically find the root partition.
Imagen del Núcleo Unificada Genérica
El Template:Paquete preconstruido puede instalar opcionalmente una imagen del núcleo unificada genérica preconstruida que contiene un initramfs genérico que puede arrancar la mayoría de los sistemas basados en systemd. Se puede instalar habilitando el indicador USE generic-uki y configurando installkernel para no generar un initramfs personalizado o una imagen del núcleo unificada:
/etc/portage/package.use/generic-uki
sys-kernel/gentoo-kernel-bin generic-uki
sys-kernel/installkernel -dracut -ukify uki
Arranque Seguro
If following this section and manually compiling your own kernel, then make sure to follow the steps outlined in Signing the kernel
La imagen genérica del núcleo unificada distribuida opcionalmente por sys-kernel/gentoo-kernel-bin ya está prefirmada. La forma de firmar una imagen del núcleo unificada generada localmente depende de si se utiliza dracut o ukify. Tenga en cuenta que la ubicación de la clave y el certificado debe ser la misma que SECUREBOOT_SIGN_KEY y SECUREBOOT_SIGN_CERT como se especifica en /etc/portage/make.conf.
Para dracut:
/etc/dracut.conf
uefi="yes"
kernel_cmdline="argumentos-para-la-linea-comandos-del-núcleo"
uefi_secureboot_key="/ruta/a/kernel_key.pem"
uefi_secureboot_cert="/ruta/a/kernel_key.pem"
Para ukify:
/etc/kernel/uki.conf
[UKI]
SecureBootPrivateKey=/ruta/a/kernel_key.pem
SecureBootCertificate=/ruta/a/kernel_key.pem
Configuración y compilación del núcleo
It can be a wise move to use the dist-kernel on the first boot as it provides a very simple method to rule out system issues and kernel config issues. Always having a known working kernel to fallback on can speed up debugging and alleviate anxiety when updating that your system will no longer boot.
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.
During the installation phase of Gentoo, only one kernel type should be installed i.e. either the sys-kernel/gentoo-kernel-bin or sys-kernel/gentoo-sources.
Clasificadas de menor a mayor complicación:
- Propuesta de automatización total: núcleos de la distribución
- Un Núcleo de la 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.
- La manera completamente manual
- Las nuevas fuentes del núcleo se instalan a través del administrador de paquetes del sistema. El núcleo se configura, compila e instala manualmente utilizando eselect kernel y una serie de comandos make. Las futuras actualizaciones del núcleo repiten el proceso manual de configuración, compilación e instalación de los archivos del núcleo. Este es el proceso más complejo, pero ofrece el máximo control sobre el proceso de actualización del núcleo.
- 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 pueden usar la herramienta genkernel de Gentoo para configurar, compilar, e instalar automáticamente el núcleo 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.
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.
Tareas de instalación del núcleo como, por ejemplo, copiar la imagen del núcleo a /boot o la Partición del Sistema EFI, generar un initramfs y/o Imagen unificada del núcleo, que actualiza la configuración del gestor de arranque, se puede automatizar con installkernel. Es posible que los usuarios deseen configurar e instalar sys-kernel/installkernel antes de continuar. Consulte la Sección de instalación del núcleo a continuación para obtener más información.
Núcleos de la distrubución
Núcleos de la Distribución son ebuilds que cubren el proceso completo de descomprimir, configurar, compilar e instalar el kernel. La principal ventaja de este método es que el administrador de paquetes actualiza los kernels a nuevas versiones como parte de la actualización de @world. Esto no requiere más participación que ejecutar un comando emerge. Los núcleos de la distribución tienen de forma predeterminada una configuración que admite la mayoría del hardware; sin embargo, se ofrecen dos mecanismos para la personalización: savedconfig y fragmentos de configuración. Consulte la página del proyecto para más detalles sobre la configuración.
Opcional: Módulos del núcleo firmados
Los módulos del núcleo en el núcleo de distribución preconstruido (sys-kernel/gentoo-kernel-bin) ya están firmados. Para firmar los módulos de núcleos creados a partir del código fuente, habilite el indicador USE modules-sign y, opcionalmente, especifique qué clave usar para la firma en /etc/portage/make.conf:
/etc/portage/make.conf
Habilitar módulos firmadosUSE="modules-sign"
# Opcionalmente, para utilizar claves de firma personalizadas.
MODULES_SIGN_KEY="/ruta/a/clave_núcleo.pem"
MODULES_SIGN_CERT="/ruta/a/clave_núcleo.pem" # Solo es necesario si MODULES_SIGN_KEY no contiene también el certificado.
MODULES_SIGN_HASH="sha512" # sha512 por defecto.
Si no se especifica MODULES_SIGN_KEY, el sistema de compilación del kernel generará una clave, que se almacenará en /usr/src/linux-x.y.z/certs. Se recomienda generar manualmente una clave para garantizar que sea la misma para cada versión del kernel. Se puede generar una clave con:
root #
openssl req -new -nodes -utf8 -sha256 -x509 -outform PEM -out kernel_key.pem -keyout kernel_key.pem
MODULES_SIGN_KEY y MODULES_SIGN_CERT pueden ser archivos diferentes. Para este ejemplo, el archivo pem generado por OpenSSL incluye tanto la clave como el certificado adjunto y, por lo tanto, ambas variables se establecen al mismo valor.
OpenSSL hará algunas preguntas sobre el usuario para el que se genera la clave, se recomienda responderlas lo más detalladamente posible.
Guarde la clave en un lugar seguro, como mínimo, que solo el usuario root pueda leerla. Verifiquelo con:
root #
ls -l kernel_key.pem
-r-------- 1 root root 3164 Jan 4 10:38 kernel_key.pem
Si la salida es algo distinta a lo anterior, corrija los permisos con:
root #
chown root:root kernel_key.pem
root #
chmod 400 kernel_key.pem
Instalando un núcleo de distribución
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
Los
Distribution Kernel | |
---|---|
Description | Dist-kernel project maintains packages providing for zero-effort kernel install and upgrades |
Project email | dist-kernel@gentoo.org |
Packages | p.g.o/dist-kernel@gentoo.org
|
IRC channel | #gentoo-dist-kernel (webchat) |
Bugs | Related bugs |
Lead(s) | "Yes" is not recognized as a Boolean (true/false) value. none No lead election date set |
Member(s) |
|
Subproject(s) (and inherited member(s)) |
(none) |
Parent Project | Gentoo |
Project listing |
The Distribution Kernel project aims to maintain sys-kernel/*-kernel packages. These kernel packages have three goals:
- Covering kernel maintenance wholly within packages (install via emerge, upgrade as part of @world upgrade), without requiring additional actions from the user or resorting to non-portable hacks.
- Providing a default configuration that works for most of diverse systems, for users who are not interested in configuring their own kernel from scratch.
- Supporting different bootloaders and /boot layouts (LILO, GRUB, systemd-boot, EFI stub…) with minimal effort, including deploying self-built kernel binary packages over a fleet of heterogeneous systems.
Current packages
The following packages are provided:
- sys-kernel/vanilla-kernel (built from source, customizable)
- sys-kernel/gentoo-kernel (built from source, customizable)
- sys-kernel/gentoo-kernel-bin (prebuilt)
The project currently maintains two LTS branches (5.4 and 5.10), plus newer branches that are marked stable at the time. Usually, the last EOL version is also kept for a short time.
Trying it out
If using out-of-source kernel modules like x11-drivers/nvidia-drivers or sys-fs/zfs, add
USE="dist-kernel"
to /etc/portage/make.conf for automatic rebuilds!Simply, either run
root #
emerge -av sys-kernel/gentoo-kernel
or
root #
emerge -av sys-kernel/gentoo-kernel-bin
depending on your preference for from-source builds or prebuilt binaries. You need to use the non-bin if you wish to customise your config.
For updating the bootloader's configuration files:
- Users of systemd-boot should have the kernel installed automatically into /boot.
- Users of GRUB can enable the grub USE flag on sys-kernel/installkernel to automatically run grub-mkconfig after upgrades
It is possible to use a hook in /etc/kernel/install.d/ to automatically update other bootloaders or run arbitrary commands at the point of kernel installation.
See the AMD64 Handbook for more details.
Signed kernel modules
The modules-sign
global USE flag can be used to automatically sign the compiled kernel modules. When the flag is enabled the MODULES_SIGN_HASH, MODULES_SIGN_KEY (and optionally MODULES_SIGN_CERT) environment variables can be set to control the used key (or pkcs11 URI) and hashing algorithm (default: SHA512). When MODULES_SIGN_KEY is unset the kernel build system will automatically generate a new key.
/etc/portage/make.conf
make.confMODULES_SIGN_KEY="..."
MODULES_SIGN_HASH="..."
As of version 6.4.13 the modules in the pre-built kernel packages (e.g. sys-kernel/gentoo-kernel-bin) are pre-signed though enforcing of valid module signatures is not enabled by default for these kernels. Enforcing can be enabled with the module.sig_enforce=1
kernel command line argument, or by enabling Secure Boot. For these kernels the key that was used to sign the in-tree modules is not available to sign out-of-tree modules. In this case, if module signature enforcing is enabled, any out-of-tree modules must be signed with a different key, and the certificate belonging to this key must be inserted into the kernel's keychain using Shim, see the Signed kernel module support and Shim article for more details.
Secure Boot
The secureboot
global USE flag can be used to automatically sign the generated kernel images for use with Secure Boot. When the flag is enabled the SECUREBOOT_SIGN_KEY and SECUREBOOT_SIGN_CERT must be used to specify which key (or pkcs11 URI) and certificate should be used. When using Secure Boot it is required that the kernel modules are also signed, see the above section for more information on this.
/etc/portage/make.conf
make.confSECUREBOOT_SIGN_KEY="..."
SECUREBOOT_SIGN_CERT="..."
As of version 6.4.13 the kernel image in the pre-built kernel packages (e.g. sys-kernel/gentoo-kernel-bin) is pre-signed. The certificate belonging to this signature can be found in /usr/src/linux-x.y.z-gentoo-dist/certs/signing_key.x509
. As with other kernel packages, this certificate must be accepted by the UEFI firmware or Shim in order to boot with Secure Boot enabled.
To successfully boot with Secure Boot enabled any bootloaders involved in the boot-chain must also be signed. Additionally the firmware must be configured to accept the used certificate, or alternatively Shim can be used as pre-loader.
Generic UKI
As of version 6.6.9 it is possible to install a generic Unified Kernel Image alongside the kernel with the generic-uki
USE flag on amd64 and arm64 systems. As with the plain kernel images and kernel modules, this UKI is pre-signed in sys-kernel/gentoo-kernel-bin.
To use the generic UKI ensure that the used implementation of installkernel does not overwrite the pre-generated initramfs or UKI.
Debian's installkernel
For sys-kernel/installkernel[-systemd] this means that no initramfs or UKI generating plugins should be installed in /etc/kernel/preinst.d, this will be the case unless custom plugins were installed.
Systemd's kernel-install
sys-kernel/installkernel[systemd] should be configured to a) use the uki layout and b) not call any initrd_generator or uki_generator. These variables should be set to none, or any other value that is not an installed initramfs or uki generator. This is the case by default unless /etc/kernel/install.conf has been manually altered.
For example, to use the generic UKI:
/etc/kernel/install.conf
layout=uki
initrd_generator=none
uki_generator=none
To use only the generic initramfs, and generate a custom UKI with, for example, ukify:
/etc/kernel/install.conf
layout=uki
initrd_generator=none
uki_generator=ukify
This is an experimental feature! It is know to work on systemd systems via systemd-boot or EFI Stub booting. It will likely not work on systems using openrc and/or musl due to the inclusion of systemd and other executables built against glibc in the prebuilt initramfs. Issues have also been observed trying to boot this generic UKI with GRUB. Additionally, the generic UKI requires that the systems UEFI implementation is 64 bit, which may not be the case on older systems despite the system having a 64 bit CPU, on these systems the generic initramfs image may still be used but a custom UKI must be built as described above. When trying the generic UKI or initramfs for the first time, always ensure that an alternative method of booting the system is available.
Using custom initramfs and UKI generators
To use initramfs generators other then the default dracut, disable the initramfs
USE flag. Then install an appropriate plugin for the used installkernel implementation:
Debian's installkernel
For sys-kernel/installkernel[-systemd] initramfs and UKI plugins are installed in /etc/kernel/preinst.d. The plugin must place the generated initramfs and/or UKI as an initrd
or uki.efi
file respectively, in the same location as the kernel image.
Systemd's kernel-install
For sys-kernel/installkernel[systemd] initramfs and UKI plugins are installed in /etc/kernel/install.d, the file name must have the suffix .install
. The plugin must place the generated initramfs and/or UKI as an initrd
or uki.efi
file respectively, in ${KERNEL_INSTALL_STAGING_AREA}
. Additionally it should respect the ${KERNEL_INSTALL_INITRD_GENERATOR}
and/or ${KERNEL_INSTALL_UKI_GENERATOR}
variables.
Modifying kernel configuration
By default, a rather full-featured config is used. These steps are only necessary if a customized configuration is required.
To customize, use the from-source packages sys-kernel/gentoo-kernel or sys-kernel/vanilla-kernel, and not the the
-bin
variant(s).The modern versions of Distribution Kernels support two mechanisms for changing the kernel configuration: savedconfig and/or config snippets.
- savedconfig
- Replaces the entire package-provided config with an administrator-supplied config file. This approach is probably a better choice for those desiring to build an entirely custom kernel.
- config snippets
- Uses the /etc/kernel/config.d directory to hold configuration file "snippets" that will be merged on top of the package-provided configuration file. This approach offers a convenient method for use-cases that change some specific config options (I.E. enable or disable a certain feature entirely), but would like to continue receiving new changes from the package-provided config file.
Preparing a modified kernel config
The easiest way to modify the current kernel configuration is to run one the configuration UIs in the kernel build tree. To do that, select a kernel ebuild and run it up to the configure phase. For example:
root #
ebuild /var/db/repos/gentoo/sys-kernel/gentoo-kernel/gentoo-kernel-5.9.8.ebuild configure
* linux-5.9.tar.xz BLAKE2B SHA512 size ;-) ... [ ok ] * genpatches-5.9-8.base.tar.xz BLAKE2B SHA512 size ;-) ... [ ok ] * genpatches-5.9-8.extras.tar.xz BLAKE2B SHA512 size ;-) ... [ ok ] * kernel-x86_64-fedora.config.5.9.2 BLAKE2B SHA512 size ;-) ... [ ok ] * Starting with 5.7.9, Distribution Kernels are switching from Arch * Linux configs to Fedora. Please keep a backup kernel just in case. >>> Unpacking source... >>> Unpacking linux-5.9.tar.xz to /tmp/portage/sys-kernel/gentoo-kernel-5.9.8/work [...] make[1]: Leaving directory '/tmp/portage/sys-kernel/gentoo-kernel-5.9.8/work/modprep' >>> Source configured.
Note the directory used by make. Enter it and run a kernel configuration tool such as nconfig or menuconfig:
root #
cd /var/tmp/portage/sys-kernel/gentoo-kernel-5.9.8/work/modprep
root #
make nconfig
After saving changes, the new config will be written to the .config file (in the modprep directory).
Using savedconfig
To use savedconfig, put the kernel config into an appropriate /etc/portage/savedconfig directory. The filename can either match the package name, or name with version. For example, creating the following file will apply the same configuration anytime a version of the gentoo-kernel
package is emerged:
root #
cp /var/tmp/portage/sys-kernel/gentoo-kernel-5.9.8/work/modprep/.config /etc/portage/savedconfig/sys-kernel/gentoo-kernel
Afterward, enable the savedconfig
USE flag on the relevant kernel package, then re-emerge the package:
root #
echo "sys-kernel/gentoo-kernel savedconfig" >> /etc/portage/package.use
root #
emerge --ask sys-kernel/gentoo-kernel
Note that the default Gentoo kernel configuration will not used if savedconfig has been enabled. When using an outdated configuration file, unset symbols (a.k.a newly added symbols) will take the upstream kernel's default values rather than Gentoo's default configuration. It is important to note there could be differences between the two.
Using /etc/kernel/config.d
To easily generate .config snippets, run diff --changed-group-format="%>" --unchanged-group-format="" .config.old .config | tee -a /etc/kernel/config.d/my-kernel.config in /var/tmp/portage/sys-kernel/gentoo-kernel-5.9.8/work/modprep.
To use the config.d approach, put a config override file into /etc/kernel/config.d directory. Make sure that the file has .config suffix. All files present in that directory will be merged in lexical order to the default Gentoo config.
For example:
/etc/kernel/config.d/50test.config
# CONFIG_HZ_300 is not set
CONFIG_HZ_1000=y
CONFIG_HZ=1000
Note that the 'is not set' comments unset options.
Using different option files for different kernel versions or variants is not supported via the config.d configuration method at the moment.
Project docs
- Bumping kernels — describes the ebuild revision bumping process.
See also
- Savedconfig — a USE flag that preserves the saved configuration files upon package updates.
- News item, así como sys-kernel/gentoo-kernel y sys-kernel/gentoo-kernel-bin, se instalan de forma predeterminada junto con un initramfs. Antes de ejecutar emerge para instalar el núcleo, los usuarios deben asegurarse de que sys-kernel/installkernel esté configurado para utilizar un generador de initramfs (por ejemplo, Dracut), como se describe en la sección installkernel.
Actualización y limpieza
Una vez instalado el núcleo, el administrador de paquetes lo actualizará automáticamente a versiones más recientes. Las versiones anteriores se conservarán hasta que se solicite al administrador de paquetes que limpie los paquetes obsoletos. Para recuperar espacio en disco, los paquetes obsoletos se pueden eliminar ejecutando periódicamente emerge con la opción --depclean
:
root #
emerge --depclean
Alternativamente, para limpiar específicamente versiones antiguas del núcleo:
root #
emerge --prune sys-kernel/gentoo-kernel sys-kernel/gentoo-kernel-bin
Por diseño, emerge solo elimina el directorio de compilación del núcleo. No elimina los módulos del núcleo ni la imagen del núcleo instalada. Para limpiar completamente los núcleos antiguos, se puede usar la herramienta app-admin/eclean-kernel.
Tareas posteriores a la instalación/actualización
Una actualización de un núcleo de distribución puede activar la reconstrucción automática de los módulos externos del núcleo instalados por otros paquetes (por ejemplo: sys-fs/zfs-kmod o x11-drivers/nvidia-drivers). Este comportamiento automatizado se activa con el indicador USE dist-kernel. Cuando sea necesario, este mismo indicador también activará la regeneración de initramfs.
Se recomienda encarecidamente activar este indicador globalmente a través de /etc/portage/make.conf cuando se utiliza un nucleo de distribución:
/etc/portage/make.conf
Activar USE=dist-kernelUSE="dist-kernel"
Reconstrucción manual de initramfs o de la Imagen de Núcleo Unificada
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 algún módulo del núcleo (por ejemplo, ZFS) en el inicio temprano, reconstruya el initramfs también a través de:
root #
emerge --config sys-kernel/gentoo-kernel
root #
emerge --config sys-kernel/gentoo-kernel-bin
Después de instalar con éxito un núcleo de distribución, es momento de pasar a la siguiente sección: Configuración del sistema.
Instalar las fuentes del núcleo
Al instalar y compilar el núcleo para sistemas basados en ppc64, 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 el indicador USE symlink esté habilitado 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.
Primero, enumere todos los núcleos instalados:
root #
eselect kernel list
Available kernel symlink targets: [1] linux-6.6.21-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.6.21-gentoo
Alternativa: Configuración manual
En caso de que se lo haya perdido, esta sección requiere las fuentes del núcleo estén instalafas. Asegúrese de obtener las fuentes del núcleo relevantes, luego regrese aquí para el resto de la sección.
Manually configuring a kernel is commonly seen as one of the most difficult procedures a system administrator has to perform. Nothing is less true - after configuring a few kernels no one remembers that it was difficult! There are two ways for a Gentoo user to manage a manual kernel system, both of which are listed below:
Modprobed-db process
A very easy way to manage the kernel is to first install sys-kernel/gentoo-kernel-bin and use the sys-kernel/modprobed-db to collect information about what the system requires. modprobed-db is a tool which monitors the system via crontab to add all modules of all devices over the system's life to make sure it everything a user needs is supported. For example, if an Xbox controller is added after installation, then modprobed-db will add the modules to be built next time the kernel is rebuilt. More on this topic can be found in the Modprobed-db article.
Manual process
This method allows a user to have full control of how their kernel is built with as minimal help from outside tools as they wish. Some could consider this as making it hard for the sake of it.
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
The kernel has a method of autodetecting the modules currently being used on the installcd which will give a great starting point to allow a user to configure their own. This can be called by using:
root #
make localmodconfig
It's now time to configure using nconfig:
root #
make nconfig
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 Gentoo de configuración del núcleo en la wiki de Gentoo que también podría ayudar.
Enabling required options
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.
Enabling support for typical system components
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
<*> XFS 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 --->
Opcional: módulos del núcleo firmados
Para firmar automáticamente los módulos del núcleo, habilite 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) --->
Opcionalmente, cambie el algoritmo hash si lo desea.
Para exigir que todos los módulos estén firmados con una firma válida, habilite CONFIG_MODULE_SIG_FORCE también:
[*] 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) --->
Para usar una clave personalizada, especifique la ubicación de esta clave en CONFIG_MODULE_SIG_KEY; si no se especifica, el sistema de compilación del núcleo generará una clave. Se recomienda generar uno manualmente. Esto se puede hacer con:
root #
openssl req -new -nodes -utf8 -sha256 -x509 -outform PEM -out kernel_key.pem -keyout kernel_key.pem
OpenSSL hará algunas preguntas sobre el usuario para el que se genera la clave; se recomienda completar estas preguntas lo más detalladamente posible.
Guarde la clave en un lugar seguro; como mínimo, solo el usuario root debe poder leerla. Verifique esto con:
root #
ls -l kernel_key.pem
-r-------- 1 root root 3164 Jan 4 10:38 kernel_key.pem
Si esto genera algo distinto a lo anterior, corrija los permisos con:
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
Para firmar también módulos del núcleo externos instalados por otros paquetes a través de linux-mod-r1.eclass
, habilite el indicador USE modules-sign globalmente:
/etc/portage/make.conf
Habilitar el firmado de módulosUSE="modules-sign"
# Opcional, cuando se usen claves personalizadas.
MODULES_SIGN_KEY="/ruta/a/kernel_key.pem"
MODULES_SIGN_CERT="/ruta/a/kernel_key.pem" # Solo es necesario si MODULES_SIGN_KEY no contiene también el certificado
MODULES_SIGN_HASH="sha512" # sha512 es el predeterminado
MODULES_SIGN_KEY y MODULES_SIGN_CERT pueden ser archivos diferentes. Para este ejemplo, el archivo pem generado por OpenSSL incluye tanto la clave como el certificado adjunto y, por lo tanto, ambas variables se configuran con el mismo valor.
Opcional: firmar la imagen del núcleo (Arranque Seguro)
Al firmar la imagen del núcleo (para usar en sistemas con Secure Boot habilitado), se recomienda configurar las siguientes opciones de configuración del núcleo:
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
[*] 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) --->
Security options --->
[*] Integrity subsystem
[*] Basic module for enforcing kernel lockdown
[*] Enable lockdown LSM early in init
Kernel default lockdown mode (Integrity) --->
[*] 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
Donde ""imagen"" es un marcador de posición para el nombre de la imagen específica de la arquitectura. Estas opciones, de arriba a abajo: exige que la imagen del núcleo en una llamada kexec deba estar firmada (kexec permite reemplazar el núcleo in situ), exige que los módulos del núcleo estén firmados, habilita el bloqueo modo integridad (evita la modificación del núcleo en tiempo de ejecución) y habilita varios claveros.
En arquitecturas que no admiten de forma nativa la descompresión del núcleo (por ejemplo, arm64 y riscv), el núcleo debe construirse con su propio descompresor (zboot):
Device Drivers --->
Firmware Drivers --->
EFI (Extensible Firmware Interface) Support --->
[*] Enable the generic EFI decompressor
Después de la compilación del núcleo, como se explica en la siguiente sección, se debe firmar la imagen del núcleo. Primero instale app-crypt/sbsigntools y luego firme la imagen del núcleo:
root #
emerge --ask app-crypt/sbsigntools
root #
sbsign /usr/src/linux-x.y.z/ruta/a/kernel-image --cert /ruta/a/kernel_key.pem --key /ruta/a/kernel_key.pem --out /usr/src/linux-x.y.z/ruta/a/kernel-image
Para este ejemplo, la misma clave que se generó para firmar los módulos se utiliza para firmar la imagen del núcleo. También es posible generar y utilizar una segunda clave especial para firmar la imagen del núcleo. Se puede volver a utilizar el mismo comando OpenSSL que en la sección anterior.
Luego proceda con la instalación.
Para firmar automáticamente los ejecutables EFI instalados por otros paquetes, habilite el indicador USE secureboot globalmente:
/etc/portage/make.conf
Habilitar el Arranque SeguroUSE="modules-sign secureboot"
# Opcionalmente, para usar claves personalizadas.
MODULES_SIGN_KEY="/ruta/a/kernel_key.pem"
MODULES_SIGN_CERT="/ruta/a/kernel_key.pem" # Solo es necesario si MODULES_SIGN_KEY no contiene también el certificado.
MODULES_SIGN_HASH="sha512" # El predeterminado es sha512
# Opcionalmente, para iniciar con el arranque seguro habilitado, puede ser la misma clave de firma o una diferente.
SECUREBOOT_SIGN_KEY="/ruta/a/kernel_key.pem"
SECUREBOOT_SIGN_CERT="/ruta/a/kernel_key.pem"
SECUREBOOT_SIGN_KEY y SECUREBOOT_SIGN_CERT pueden ser archivos diferentes. Para este ejemplo, el archivo pem generado por OpenSSL incluye tanto la clave como el certificado adjunto y, por lo tanto, ambas variables se configuran con el mismo valor.
Al generar una Imagen del núcleo unificada con
ukify
de systemd, la imagen del núcleo se firmará automáticamente antes de incluirla en la imagen del núcleo unificada y no es necesario firmarla manualmente.
Compilar e Instalar
Ahora que el núcleo está configurado, es hora de compilarlo e instalarlo. Salga de la configuración e inicie el proceso de compilación:
root #
make && make modules_install
Es posible habilitar construcciones en paralelo usando
make -jX
siendo X el número de compilaciones paralelas que se permite que lance el proceso de construcción. Es similar a las instrucciones anteriores sobre /etc/portage/make.conf con la variable MAKEOPTS
.When the kernel has finished compiling, copy the kernel image to /boot/. This is handled by the make install command:
root #
make install
This command will copy the kernel image to /boot. If sys-kernel/installkernel is installed it will call /sbin/installkernel instead and delegate the kernel installation. Instead of simply copying the kernel to /boot, Installkernel installs each kernel with its version number in the file name. Additionally, installkernel provides a framework for automatically accomplishing various tasks relating to kernel installation, such as: generating an initramfs, building an Unified Kernel Image, and updating the bootloader configuration.
Deprecated: Genkernel
Genkernel should only be considered by users with a required need that only Genkernel can meet. For others, it is recommended to use the Distribution kernel or manually compile their own as it will make maintaining a Gentoo system a lot more simple. An example of why genkernel is more difficult to manage is the lack of integration with sys-kernel/installkernel. This means a user will not get the same level of automation as provided by the other methods; for example, Unified Kernel Images will need to be created manually when using Genkernel.
Users still wishing to use Genkernel should see the Genkernel article for more information.
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:
/etc/modules-load.d/network.conf
Forzar la carga del módulo 3c59x3c59x
Continúe la instalación con Configuring the system.