Construir un Kernel Personalizado

John Soros, Alessio, Brandon Nielsen Version unspecified Last review: 2023-12-23
Este documento proporciona instrucciones para usuarios avanzados que desean reconstruir el kernel desde alguna fuente.

Cuando compila o ejecuta un kernel personalizado, no se debe esperar soporte del equipo de kernel de Fedora.

Algunas razones comunes para compilar un kernel personalizado son:

  • Aplicar parches para pruebas que se generaron o se obtuvieron de otra fuente

  • Para reconfigurar un kernel existente

  • Para obtener más información sobre el kernel y el desarrollo del kernel

Obtener las Dependencias

La manera más fácil de instalar todas las dependencias compiladas para el kernel es usar el archivo de especificaciones del kernel Fedora:

sudo dnf install fedpkg
fedpkg clone -a kernel
cd kernel
sudo dnf builddep kernel.spec

Si usted desea usar make xconfig, necesitará algunos paquetes adicionales:

sudo dnf install qt3-devel libXi-devel gcc-c++

Arranque Seguro

Asegúrese de agregar el usuario que realiza la compilación a /etc/pesign/users y ejecute el script de autorización del usuario:

sudo /usr/libexec/pesign/pesign-authorize

Cree una nueva Machine Owner Key (Clave de Propietario de la Máquina) (MOK) para importar a UEFI:

openssl req -new -x509 -newkey rsa:2048 -keyout "key.pem" \
        -outform DER -out "cert.der" -nodes -days 36500 \
        -subj "/CN=<your name>/"

Importe el nuevo certificado a su base de datos UEFI:

Se le pedirá que autorice la importación en el próximo arranque.
mokutil --import "cert.der"

Cree un archivo de clave PKCS #12:

openssl pkcs12 -export -out key.p12 -inkey key.pem -in cert.der

Usted puede después importar el certificado y la clave a la base de datos nss:

certutil -A -i cert.der -n "<MOK certificate nickname>" -d /etc/pki/pesign/ -t "Pu,Pu,Pu"
pk12util -i key.p12 -d /etc/pki/pesign

Una vez que el certificado y la clave están importados en su base de datos nss, usted puede compilar el kernel con la clave seleccionada añadiendo %define pe_signing_cert <MOK certificate nickname> al archivo kernel.spec o llamando a rpmbuild directamente con la bandera --define "pe_signing_cert <MOK certificate nickname>".

Mientras el bugzilla bug #1651020 esté abierto usted podría necesitar editar la línea que empieza con %pesign en el archivo de especificaciones del kernel y sustituirla con pesign -c %{pe_signing_cert} --certdir /etc/pki/pesign/ -s -i $KernelImage -o vmlinuz.signed.

Está también recomendado que instale ccache, que puede ayudar a acelerar las reconstrucciones:

sudo dnf install ccache

Compilar un Kernel desde el dist-git de Fedora

First, a checkout from the Fedora kernel dist-git is required:

git clone https://src.fedoraproject.org/rpms/kernel.git

The kernel, like any other Fedora package, has a branch per Fedora release. rawhide corresponds to Rawhide and each version of Fedora has a branch called f<version>.

  1. For example, to build a Fedora 28 kernel, you would first need to switch to that branch with:

    git switch f28
  2. Para evitar conflictos con los kernels existentes, puede establecer un buildid personalizado cambiando # define buildid .local a %define buildid .<your_custom_id_here> en kernel.spec.

  3. Make whatever changes or customizations you need:

    1. Kernel configuration options can be overriden by modifying the kernel-local file.

    2. Existing patches can be added to linux-kernel-test.patch, they will be picked up during the build automatically.

    3. Patches can also be kept in seperate files and added to kernel.spec with Patch2: foo.patch, Patch3: bar.patch, etc. They should be applied automatically during the build process.

    4. To make your own modifications to the kernel source, retrieve the kernel sources for your current dist-git branch with fedpkg sources, then make your desired changes to the kernel source and generate a patch, e.g. with diff -rupN kernel_src_folder kernel_src_folder_patched > mypatch.patch. The patch can then be added to linux-kernel-test.patch or the specfile.

  4. Construya los RPMs:

    fedpkg local
  5. Instale el nuevo kernel:

    sudo dnf install --nogpgcheck ./x86_64/kernel-$version.rpm

Construyendo un kernel vanilla upstream

Algunas veces un desarrollador de Fedora le puede pedir que intente compilar e instalar un kernel upstream (posiblemente con un parche añadido) para probarlo. Si hay varias iteraciones, puede ser más rápido para usted hacer esto que para el desarrollador cambiar varios RPMs.

Se está realizando un esfuerzo para empaquetar los kernels vanilla. Vea si esto se ajusta a sus necesidades primero

Obtener las Fuentes

Clone el árbol del kernel desde kernel.org. Si usted no sabe que árbol necesita, debería obtener el árbol de Linus:

git clone git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
cd linux

También puede que desee el árbol estable (versiones 4.y.z), que se pueden añadir con:

git remote add -f stable git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable.git

Aplicar parches

Para aplicar archivos de parche, puede usar git-am:

git am -3 <patch file>

Configurar el kernel

Si el desarrollador le ha apuntado un archivo de configuración específico para utilizar, guárdelo en el directorio linux con el nombre de archivo .config

De lo contrario, deberá elegir un archivo de configuración para empezar. El kernel Linux tiene miles de opciones de configuración, por lo que no querrá empezar desde cero a menos que sepa lo que está haciendo.

Starting from an installed kernel configuration

If you want to tweak the configuration of a kernel you already have installed, you can start with its configuration which is stored in /boot/. For example, to start with the configuration of the currently running kernel:

cp /boot/config-`uname -r`* .config

Starting from dist-git

If you want to use the configuration for a kernel you do not have installed, you can get the configuration from the Fedora dist-git repository. For example, to start with the latest Rawhide configuration:

cd <dist-git directory>
git checkout rawhide
./generate_all_configs.sh # Ensure the latest configuration files are generated
cp kernel-<arch>.config <linux kernel directory>.config

The debug versions of the configuration files are in kernel-<arch>-debug.config if you would like to build a kernel with debugging options enabled.

Changing the configuration

There are several ways to change the configuration. You can run make help and look at the Configuration targets for the full list, but make menuconfig is a good place to start. You can also just edit the .config file directly.

One configuration option you may want to set is CONFIG_MODULE_COMPRESS, which compresses the modules (with gzip by default) when installing them. Without this setting, the modules can be very large.

Building the kernel

Once you’ve configured the kernel, you’re ready to build it. Before you do so, you’ll want to change the EXTRAVERSION in the Makefile to something you’ll recognize later. For example, if it reads EXTRAVERSION = -rc5 change it to EXTRAVERSION = -rc5-dave:

$EDITOR Makefile

Now you’re ready to build the kernel:

make oldconfig
make bzImage
make modules

Installing the kernel

Installing the kernel is as simple as:

sudo make modules_install
sudo make install

Rebuilding

If you have been asked to try several different things, the procedure once you have already built the tree once is mostly the same. Running make clean is recommended between builds. This will leave the .config in place, so you can skip that step above and proceed straight to the make bzImage part of the steps above. Because we installed ccache in the first step, subsequent builds may go a lot faster as the compiler hits files that haven’t changed since the last time it built them.

Cleaning up

Once you have tested the kernel, and you’ve booted back to one of your kernels installed from an RPM, you can clean up the files that the above procedure installed.

When running the following commands, be sure to get the kernel version correct!

Because you changed EXTRAVERSION in the Makefile to add a 'tag', all the files it installed will have this as part of the filename. So you should be able to use wildcards to delete them safely using commands similar to those below (just replace 'dave' with whatever tag you chose):

rm -f /boot/config-*dave* /boot/initramfs-*dave* /boot/vmlinuz-*dave* /boot/System.map-*dave*
rm -rf /lib/modules/*dave*

Finally, you will need to remove the kernel as an option in your bootloader. Assuming your system is running grub2, this can be done by removing the bootloader specification entries and rebuilding the grub config:

rm -f /boot/loader/entries/*dave*
grub2-mkconfig -o /boot/grub2/grub.cfg