Product SiteDocumentation Site

8.10. Compilació d'un nucli

Els nuclis proporcionats per Debian inclouen el major nombre possible de característiques, així com el màxim de controladors, per tal de cobrir l'espectre més ample de les configuracions de maquinari existents. Per això alguns usuaris prefereixen recompilar el nucli per tal d'incloure només el que necessiten específicament. Hi ha dues raons per a aquesta elecció. En primer lloc, pot ser per optimitzar el consum de memòria, ja que el codi del nucli, encara que mai s'utilitzi, ocupa memòria per no res (i mai es “baixa” a l'espai d'intercanvi, ja que és RAM real que utilitza), que pot disminuir el rendiment global del sistema. Un nucli compilat localment també pot limitar el risc de problemes de seguretat, ja que només una fracció del codi del nucli està compilat i executat.
La recompilació del nucli també és necessària si voleu utilitzar certes característiques que només estan disponibles com a pedaços (i no estan incloses a la versió estàndard del nucli).

8.10.1. Introducció i prerequisits

No és sorpresa que Debian gestioni el nucli en forma de paquet, fet que no és com els nuclis han estat tradicionalment compilats i instal·lats. Atès que el nucli roman sota el control del sistema d'empaquetament, es pot eliminar de manera neta, o desplegar en diverses màquines. A més, els «scripts» associats amb aquests paquets automatitzen la interacció amb el carregador d'arrencada i el generador initrd.
The upstream Linux sources contain everything needed to build a Debian package of the kernel. But you still need to install build-essential to ensure that you have the tools required to build a Debian package. Furthermore, the configuration step for the kernel requires the libncurses-dev package (formerly libncurses5-dev, which is now a transitional package). Finally, the fakeroot package will enable creation of the Debian package without using administrator's rights.

8.10.2. Obtenir les fonts

Com qualsevol cosa que pugui ser útil en un sistema Debian, les fonts del nucli Linux estan disponibles en un paquet. Per obtennir-les, només cal instal·lar el paquet linux-source-versió. L'ordre apt search ^linux-source llista les diverses versions del nucli empaquetades per Debian. L'última versió està disponible a la distribució Unstable: podeu obtenir-la sense gaire risc (especialment si el vostre APT està configurat d'acord amb les instruccions de Secció 6.2.6, «Treballar amb diverses distribucions»). Tingueu en compte que el codi font contingut en aquests paquets no es correspon exactament amb el publicat per Linus Torvalds i els desenvolupadors del nucli; com totes les distribucions, Debian aplica una sèrie de pedaços que podrien (o no) trobar el seu destí a la versió original de Linux. Aquestes modificacions inclouen retroadaptacions de correccions/característiques/controladors de versions del nucli més recents, noves característiques que encara no s'han fusionat (totalment) a l'arbre Linux principal, i de vegades fins i tot canvis específics de Debian.
The remainder of this section focuses on the 5.10 version of the Linux kernel, but the examples can, of course, be adapted to the particular version of the kernel that you want.
We assume the linux-source-5.10 package has been installed. It contains /usr/src/linux-source-5.10.tar.xz, a compressed archive of the kernel sources. You must extract these files in a new directory (not directly under /usr/src/, since there is no need for special permissions to compile a Linux kernel): ~/kernel/ is appropriate.
$ mkdir ~/kernel; cd ~/kernel
$ tar -xaf /usr/src/linux-source-5.10.tar.xz
To build a kernel from the pristine sources, just download the tarball of the version of your choice from kernel.org, verify the integrity after importing the kernel maintainers key, and then proceed as described in the following chapters.

$ wget https://kernel.org/pub/linux/kernel/v5.x/linux-5.10.62.tar.xz
[..]
$ wget https://kernel.org/pub/linux/kernel/v5.x/linux-5.10.62.tar.sign
[..]
$ unxz -c linux-5.10.62.tar.xz | gpg --verify linux-5.10.62.tar.sign -
gpg: Signature made Fri 03 Sep 2021 10:11:35 AM CEST
gpg:                using RSA key 647F28654894E3BD457199BE38DBBDC86092693E
gpg: Good signature from "Greg Kroah-Hartman <gregkh@linuxfoundation.org>" [unknown]
gpg:                 aka "Greg Kroah-Hartman (Linux kernel stable release signing key) <greg@kroah.com>" [unknown]
gpg:                 aka "Greg Kroah-Hartman <gregkh@kernel.org>" [unknown]
gpg: WARNING: This key is not certified with a trusted signature!
gpg:          There is no indication that the signature belongs to the owner.
Primary key fingerprint: 647F 2865 4894 E3BD 4571  99BE 38DB BDC8 6092 693E

8.10.3. Configurar el nucli

El següent pas consisteix a configurar el nucli segons les vostres necessitats. El procediment exacte depèn dels objectius.
When recompiling a more recent version of the kernel (possibly with an additional patch), the configuration will most likely be kept as close as possible to that proposed by Debian. In this case, and rather than reconfiguring everything from scratch, it is sufficient to copy the /boot/config-version file (the version is that of the kernel currently used, which can be found with the uname -r command) into a .config file in the directory containing the kernel sources. Make sure to read sidebar TIP Missing debian/certs/debian-uefi-certs.pem in this case.
$ cp /boot/config-5.10.0-8-amd64 ~/kernel/linux-source-5.10/.config
Tret que calgui canviar la configuració, podeu parar aquí i saltar a Secció 8.10.4, «Compilació i creació del paquet». Si cal canviar-la, d'altra banda, o si decidiu reconfigurar-ho tot des de zero, haureu de dedicar temps per configurar el vostre nucli. Hi ha diverses interfícies dedicades al directori de codi font del nucli que es poden utilitzar cridant l'ordre make objectiu, on objectiu és un dels valors descrits tot seguit.
make menuconfig compiles and executes a text-mode interface (this is where the libncurses-dev package is required) which allows navigating the options available in a hierarchical structure. Pressing the Space key changes the value of the selected option, and Enter validates the button selected at the bottom of the screen; Select returns to the selected sub-menu; Exit closes the current screen and moves back up in the hierarchy; Help will display more detailed information on the role of the selected option. The arrow keys allow moving within the list of options and buttons. To exit the configuration program, choose Exit from the main menu. The program then offers to save the changes you've made; accept if you are satisfied with your choices.
Other interfaces have similar features, but they work within more modern graphical interfaces; such as make xconfig which uses a Qt graphical interface, and make gconfig which uses GTK+. The former requires qtbase5-dev, while the latter depends on libglade2-dev and libgtk2.0-dev.
Quan s'utilitza una d'aquestes interfícies de configuració, sempre és una bona idea començar des d'una configuració predeterminada raonable. El nucli proporciona aquestes configuracions a arch/arquitectura/configs/*_defconfig i podeu posar la configuració seleccionada al lloc amb una ordre com make x86_64_defconfig (en el cas d'un PC de 64 bits) o make i386_defconfig (en el cas d'un PC de 32 bits).

8.10.4. Compilació i creació del paquet

Once the kernel configuration is ready, a simple make deb-pkg will generate up to 5 Debian packages:
linux-image-version
contains the kernel image and the associated modules,
linux-headers-version
contains the header files required to build external modules,
linux-firmware-image-version
contains the firmware files needed by some drivers (this package might be missing when you build from the kernel sources provided by Debian),
linux-image-version-dbg
contains the debugging symbols for the kernel image and its modules (only created if CONFIG_DEBUG_INFO=y), and
linux-libc-dev
contains headers relevant to some user-space libraries like GNU glibc.
The version is defined by the concatenation of the upstream version (as defined by the variables VERSION, PATCHLEVEL, SUBLEVEL, and EXTRAVERSION in the Makefile), of the LOCALVERSION configuration parameter, and of the LOCALVERSION environment variable. The package version reuses the same version string with an appended revision that is regularly incremented (and stored in .version), except if you override it with the KDEB_PKGVERSION environment variable.
$ make deb-pkg LOCALVERSION=-falcot KDEB_PKGVERSION=$(make kernelversion)-1
[...]
$ ls ../*.deb
../linux-headers-5.10.46-falcot_5.10.46-1_amd64.deb
../linux-image-5.10.46-falcot_5.10.46-1_amd64.deb
../linux-image-5.10.46-falcot-dbg_5.10.46-1_amd64.deb
../linux-libc-dev_5.10.46-1_amd64.deb
The whole process requires around 20 GB of free space, at least 8 GB of RAM, and several hours of compilation (utilizing one core) for a standard amd64 Debian kernel. These requirements can be drastically reduced by disabling the debug information using CONFIG_DEBUG_INFO=n, but this will make it impossible to trace kernel errors (“oops”) using gdb and also stop the creation of the linux-image-version-dbg package.

8.10.5. Compilació de mòduls externs

Some modules are maintained outside of the official Linux kernel. To use them, they must be compiled alongside the matching kernel. A number of common third party modules are provided by Debian in dedicated packages, such as vpb-driver-source (extra modules for Voicetronix telephony hardware) or leds-alix-source (driver of PCEngines ALIX 2/3 boards).
Aquests paquets són molts i variats, l'ordre apt-cache rdepends module-assistant pot mostrar la llista proporcionada per Debian. No obstant això, una llista completa no és particularment útil, ja que no hi ha cap raó particular per compilar mòduls externs excepte quan se sap que es necessita. En aquests casos, la documentació del dispositiu típicament detallarà els mòduls específics que necessita per funcionar amb Linux.
For example, let's look at the dahdi-source package: after installation, a .tar.bz2 of the module's sources is stored in /usr/src/. While we could manually extract the tarball and build the module, in practice we prefer to automate all this using the DKMS framework (Dynamic Kernel Module Support). Most modules offer the required DKMS integration in a package ending with a -dkms suffix. In our case, installing dahdi-dkms is all that is needed to compile the kernel module for the current kernel provided that we have the linux-headers-* package matching the installed kernel. For instance, if you use linux-image-amd64, you would also install linux-headers-amd64.
$ sudo apt install dahdi-dkms
[...]
Setting up dkms (2.8.4-3) ...
Setting up linux-headers-5.10.0-8-amd64 (5.10.46-4) ...
/etc/kernel/header_postinst.d/dkms:
dkms: running auto installation service for kernel 5.10.0-8-amd64:.
Setting up dahdi-dkms (1:2.11.1.0.20170917~dfsg-7.4) ...
Loading new dahdi-2.11.1.0.20170917~dfsg-7.4 DKMS files...
Building for 5.10.0-8-amd64
Building initial module for 5.10.0-8-amd64
Done.

dahdi_dummy.ko:
Running module version sanity check.
 - Original module
   - No original module exists within this kernel
 - Installation
   - Installing to /lib/modules/5.10.0-8-amd64/updates/dkms/

dahdi_dynamic_eth.ko:
Running module version sanity check.
 - Original module
   - No original module exists within this kernel
 - Installation
   - Installing to /lib/modules/5.10.0-8-amd64/updates/dkms/

[...]
DKMS: install completed.
$ sudo dkms status
dahdi, 2.11.1.0.20170917~dfsg-7.4, 5.10.0-8-amd64, x86_64: installed
$ sudo modinfo dahdi_dummy
filename:       /lib/modules/5.10.0-8-amd64/updates/dkms/dahdi_dummy.ko
license:        GPL v2
author:         Robert Pleh <robert.pleh@hermes.si>
description:    Timing-Only Driver
depends:        dahdi
retpoline:      Y
name:           dahdi_dummy
vermagic:       5.10.0-8-amd64 SMP mod_unload modversions 
parm:           debug:int

8.10.6. Aplicar pedaços al nucli

Algunes característiques no s'inclouen en el nucli estàndard a causa de falta de maduresa o a algun desacord amb els mantenidors del nucli. Aquestes característiques es poden distribuir com a pedaços que després qualsevol persona és lliure d'aplicar a les fonts del nucli.
Debian de vegades proporciona alguns d'aquests pedaços en els paquets linux-patch-*, però sovint no es fa en llançaments estables (de vegades per les mateixes raons que no estan fusionats en el nucli oficial original). Aquests paquets instal·len fitxers al directori /usr/src/kernel-patches/.
To apply one or more of these installed patches, use the patch command in the sources directory then start compilation of the kernel as described above. The following shows an old example using linux-patch-grsecurity2 and linux-source-4.9.
$ cd ~/kernel/linux-source-4.9
$ make clean
$ zcat /usr/src/kernel-patches/diffs/grsecurity2/grsecurity-3.1-4.9.11-201702181444.patch.gz | patch -p1
Tingueu en compte que un pedaç concret no necessàriament funciona amb qualsevol versió del nucli; és possible que patch falli quan s'aplica a les fonts del nucli. Es mostrarà un missatge d'error i es donaran alguns detalls sobre la fallada; en aquest cas, consulteu la documentació disponible al paquet Debian del pedaç (al directori /usr/share/doc/linux-patch-*/). En la majoria dels casos, el mantenidor indica per a quines versions del nucli està pensat el pedaç.