Building the 6.x Linux Kernel from Source – Part 2
local graph
Chapter 3 — Building the 6.x Linux Kernel from Source – Part 2
Section titled “Chapter 3 — Building the 6.x Linux Kernel from Source – Part 2”This chapter continues from where the previous chapter left off. In the previous chapter, in the Steps to build the kernel from source section, we covered the first three steps of building our kernel. There, you learned how to download and extract the kernel source tree or even use git clone to get one (steps 1 and 2). We then proceeded to understand the kernel source tree layout, and, very importantly, the various approaches to correctly arrive at a starting point to configure the kernel (step 3). We even added a custom menu item to the kernel configuration menu.
In this chapter, we will continue our quest to build the kernel by covering the remaining four steps to build it. First, of course, we will build it (step 4). You will then learn how to properly install the kernel modules that get generated as part of the build (step 5). Next, we will run a simple command that sets up the GRUB (Grand Unified Bootloader) bootloader and generates the initramfs (or initrd) image (step 6). The motivation for using an initramfs image and how it’s generated are discussed as well. Some details on configuring the GRUB bootloader (for x86) are then covered (step 7).
By the end of the chapter, we’ll boot the system with our new kernel image and verify that it’s built as expected. We’ll then finish off by learning how to cross-compile a Linux kernel for a foreign architecture (for the AArch 32/64, the board in question is the well-known Raspberry Pi).
Briefly, these are the areas that will be covered in this chapter:
- Step 4 – building the kernel image and modules
- Step 5 – installing the kernel modules
- Step 6 – generating the initramfs image and bootloader setup
- Understanding the initramfs framework
- Step 7 – customizing the GRUB bootloader
- Verifying our new kernel’s configuration
- Kernel build for the Raspberry Pi
- Miscellaneous tips on the kernel build
Technical requirements
Section titled “Technical requirements”Before we begin, I assume that you have downloaded, extracted (if required), and configured the kernel, thus having a .config file ready. If you haven’t already, please refer to Chapter 2, Building the 6.x Linux Kernel from Source – Part 1, for the details on how exactly this is done. We can now proceed to build it.
Step 4 – building the kernel image and modules
Section titled “Step 4 – building the kernel image and modules”Performing the build from the end user’s point of view is straightforward. In its simplest form, just ensure you’re at the root of the configured kernel source tree and type make. That’s it – the kernel image and any kernel modules (and, on an embedded system, possibly a Device Tree Blob (DTB) binary) will get built. Grab a coffee! The first time around, it could take a while.
Of course, there are various Makefile targets we can pass to make. A quick make help command issued on the command line reveals quite a bit. Remember, we used this earlier, in fact, to see all possible configuration targets (revisit Chapter 2, Building the 6.x Kernel from Source – Part 1, and particularly the Seeing all available config options section if you’d like). Here, we use it to see what gets built by default with the all target:
$ cd ${LKP_KSRC} # recall that the env var LKP_KSRC holds the pathname to # the 'root' directory of our 6.1 LTS kernel source tree$ make help [...]Other generic targets: all - Build all targets marked with [*]* vmlinux - Build the bare kernel* modules - Build all modules [...]Architecture specific targets (x86): * bzImage - Compressed kernel image (arch/x86/boot/bzImage) [...]$Okay, so here’s what to notice: performing make all will get us the preceding three targets (the ones prefixed with the * symbol) built; what do they mean? Let’s see:
vmlinuxmatches the name of the uncompressed kernel image file.- The
modulestarget implies that all kernel config options marked asm(for module) will be built as kernel modules (.kofiles) within the kernel source tree (details on what exactly a kernel module is and how to program one are the subject matter of the following two chapters). bzImageis an architecture-specific kernel image file. On an x86[_64] system, this is the name of the compressed kernel image – the one the bootloader will actually load into RAM, uncompress in memory, and boot into; in effect, it’s the (compressed) kernel image file.
So, an FAQ: if bzImage is the actual kernel image file that we use to boot and initialize the system, then what’s vmlinux for? Notice that vmlinux is the uncompressed kernel image file. It can be large (even very large, in the presence of kernel symbols generated during a debug build). While we never boot via vmlinux, it’s nevertheless important – priceless, in fact. Do keep it around for kernel debugging purposes (my Linux Kernel Debugging book has you covered in this respect!).
Now, with the kbuild system (that the kernel uses), just running make equates to make all.
The modern Linux kernel code base is enormous. Current estimates are that recent kernels have in the region of 25 to 30 million source lines of code (SLOC)! Thus, building the kernel is indeed a very memory- and CPU-intensive job. Indeed, some folks use the kernel build as a stress test! (You should also realize that not all lines of code are going to be compiled during a particular build run). The modern make utility is powerful and multi-process capable. We can request it to spawn multiple processes to handle different (unrelated) parts of the build in parallel, leading to higher throughput and thus shorter build times. The relevant option is -jn, where n is the upper limit on the number of tasks to spawn and run in parallel. A heuristic (rule of thumb) used to determine this is as follows:
n = number-of-CPU-cores * factor;Here, factor is 2 (or 1.5 on very high-end systems with hundreds or thousands of CPU cores). Also, technically, we require the cores to be internally “threaded” or using Simultaneous Multi-Threading (SMT) – what Intel calls hyper-threading – for this heuristic to be useful.
More details on parallelized make and how it works can be found on the man page of make (invoked with man 1 make) in the PARALLEL MAKE AND THE JOBSERVER section.
Another FAQ: how many CPU cores are there on my system? There are several ways to determine this, an easy way being to use the nproc utility:
$ nproc4A quick word regarding nproc and related utilities:
Performing strace on nproc reveals that it works by essentially using the sched_getaffinity() system call. We shall mention more on this and related system calls in Chapter 10, The CPU Scheduler – Part 1, and Chapter 11, The CPU Scheduler – Part 2, on CPU scheduling.
FYI, the lscpu utility yields the number of cores as well as additional useful CPU info. Try them out on your Linux system.
Clearly, my guest VM has been configured with four CPU cores, so let’s keep n=4*2=8. So, off we go and build the kernel. The following output is from our trusty x86_64 Ubuntu 22.04 LTS guest system configured to have 2 GB of RAM and four CPU cores.
Remember, prior to building it, the kernel must first be correctly configured. For details, refer to Chapter 2, Building the 6.x Linux Kernel from Source – Part 1.
Again, when you begin, the kernel build may emit a warning, although non-fatal in this case:
$ make -j8scripts/kconfig/conf --syncconfig Kconfig UPD include/config/kernel.releasewarning: Cannot use CONFIG_STACK_VALIDATION=y, please install libelf-dev, libelf-devel or elfutils-libelf-devel [...]So, to address this, we break off the build with Ctrl + C, then follow the output’s advice and install the libelf-dev package. On our Ubuntu box, sudo apt install libelf-dev is sufficient. Do realize that if you followed the detailed setup in Online Chapter, Kernel Workspace Setup (or ran our ch1/pkg_install4ubuntu_lkp.sh script), this will not happen.
Precisely because the kernel build is very CPU- and RAM-intensive, carrying this out on a guest VM is going to be a lot slower than on a native Linux system. It helps to conserve RAM by at least booting your guest at run level 3 (multiuser with networking, no GUI): https://www.if-not-true-then-false.com/2012/howto-change-runlevel-on-grub2/.
Right, let’s run it with a few quick but very useful tips:
- Due to the sheer high CPU and RAM usage during kernel build, I sometimes find that when running the build in a VM in graphical mode, errors can occur; the system can run short on memory, triggering weird failures, and even logging one out at times! To mitigate this, I recommend you boot into your VM at run level 3 – or what
systemdtypically callsmulti-user.target– multi-user mode with networking but no graphics. To do so, you can edit the kernel command line from the GRUB menu and append 3 to it (we cover stuff like this in the Step 7 – customizing the GRUB section). Alternatively, if already in graphical mode (whatsystemdcallsgraphical.target), you can switch tomulti-user.targetwith the commandsudo systemctl isolate multi-user.target. - Then again, with the cost of RAM being low (and possibly dropping), just getting more RAM is a great and quick performance hack!
- Especially when it’s running in console mode, I personally definitely prefer to ssh into the VM and work from there.
- When building, by leveraging the
teeutility, we can easily save both the standard output and standard error into a file (teelets us simultaneously see the output on the console as well):$ sudo systemctl isolate multi-user.target[...]$ cd ${LKP_KSRC}$ make –j8 2>&1 | tee out.txtSYNC include/config/auto.conf.cmdHOSTCC scripts/basic/fixdepHOSTCC scripts/kconfig/conf.oHOSTCC scripts/kconfig/confdata.oHOSTCC scripts/kconfig/expr.oLEX scripts/kconfig/lexer.lex.cYACC scripts/kconfig/parser.tab.[ch]HOSTCC scripts/kconfig/preprocess.o[...]
Good, the kbuild system should now ensure that our new kernel – and the components we’ve configured as modules – get built. Of course, at times, things can and do go wrong. We’ll look at several of these circumstances as we progress through this chapter and, as far as possible, look at how to fix them, starting with the following section.
Getting over a cert config issue on Ubuntu
Section titled “Getting over a cert config issue on Ubuntu”Particularly on recent Ubuntu systems, we run make and all seems well with the kernel build, until we (often) hit this issue:
$ make ...[...] EXTRACT_CERTS certs/signing_key.pem CC certs/system_keyring.o CC arch/x86/entry/vdso/vclock_gettime.o EXTRACT_CERTS CC certs/common.o CC arch/x86/entry/vdso/vgetcpu.omake[1]: *** No rule to make target 'debian/canonical-revoked-certs.pem', needed by 'certs/x509_revocation_list'. Stop.make[1]: *** Waiting for unfinished jobs.... CC certs/blacklist.o[...]However, you’ll notice that make continues to execute the other parallel tasks – at least until it figures it’s quite useless – and the build then terminates (it can take a while though), ultimately unsuccessfully; no kernel is actually built.
So, what’s the problem? Here, it turns out to be a kernel config named CONFIG_SYSTEM_REVOCATION_KEYS that has been added to recent 5.x kernels; check it out:
$ grep CONFIG_SYSTEM_REVOCATION_KEYS .configCONFIG_SYSTEM_REVOCATION_KEYS="debian/canonical-revoked-certs.pem"At least on Ubuntu systems, this particular config setting seems to cause the build to fail; the quick and simple fix is to simply turn it off. You can do so with:
scripts/config --disable SYSTEM_REVOCATION_KEYSRecheck with grep; you’ll find that it’s now unset.
FYI, this Q&A on the Ask Ubuntu forum covers it: https://askubuntu.com/a/1329625/245524. For the curious, the config seems to have made its way into the 5.13 kernel; here’s the actual commit: https://github.com/torvalds/linux/commit/d1f044103dad70c1cec0a8f3abdf00834fec8b98.
Run the make command again (you might need to respond via Enter to a prompt or two); it should now succeed!
[...]KSYMS .tmp_vmlinux.kallsyms2.SAS .tmp_vmlinux.kallsyms2.SLD vmlinuxBTFIDS vmlinuxSORTTAB vmlinuxSYSMAP System.mapMODPOST modules-only.symversCC arch/x86/boot/a20.oAS arch/x86/boot/bioscall.oCC arch/x86/boot/cmdline.o[...]GEN Module.symversLDS arch/x86/boot/compressed/vmlinux.ldsAS arch/x86/boot/compressed/kernel_info.oCC [M] arch/x86/crypto/aesni-intel.mod.oCC [M] arch/x86/crypto/crc32-pclmul.mod.o[...]LD arch/x86/boot/setup.elfOBJCOPY arch/x86/boot/setup.binBUILD arch/x86/boot/bzImageKernel: arch/x86/boot/bzImage is ready (#3)Ah, it’s done!
An aside: in general, what to check if the build fails?
- Check, then recheck, that you’ve done everything correctly; do blame yourself and not the kernel (community/code)!
- Have all the required and up-to-date packages been installed? For example, if the kernel config has
CONFIG_DEBUG_INFO_BTF=y(mine does), it requirespahole1.16 or later to be installed. - Is the kernel config sane?
- Is it a hardware issue? Errors like internal compiler error: Segmentation fault usually indicate this; is there sufficient RAM and swap space allocated? Try the build on another VM, or better, on a native Linux system.
- Start (or restart) from scratch; in the root of the kernel source tree, do a
make mrproper(careful: it will clean everything, even deleting any.configfile), and perform all the steps carefully. - Hey, when all else fails, Google the error message!
The build should run cleanly, without any errors or warnings. Well, at times, compiler warnings are seen, but we shall blithely ignore them. What if you encounter compiler errors and thus a failed build during this step? How can we put this politely? Oh well, we cannot – it’s very likely your fault, not the kernel community’s. As just mentioned, please check and recheck every step, redoing it from scratch with a make mrproper command if all else fails! Very often, a failure to build the kernel implies either kernel configuration errors (randomly selected configs that might conflict), outdated versions of the toolchain, or incorrect patching, among other things. (FYI, we cover more, quite specific tips in the Miscellaneous tips on the kernel build section).
Okay, we shall assume that the kernel build step worked. The compressed kernel image (here, for the x86[_64], it’s called bzImage) and the uncompressed one, the vmlinux file, have successfully been built by stitching together the various object files generated, as can be seen in the preceding output – the last line in the preceding block confirms this fact (the #3 implies that, for me, this is the third time the kernel was built). As part of the build process, the kbuild system also proceeds to finish building all kernel modules.
A quick tip: if you’d like to time how long a command takes to execute, prefix the time command to it (so, here: time make -j8 2>&1 | tee out.txt). It works but the time(1) utility provides only a (very) coarse-grained idea of the time taken by the command that follows it.
If you’d like accurate CPU profiling and time stats, learn how to use the powerful perf utility. Here, you can try it out with the perf stat make -j8 ... command. I suggest you try this out on a distro kernel as, otherwise, perf itself will have to be manually built for your custom kernel.
Also, in the previous output, as we’re doing a parallelized build (via make -j8, implying up to eight processes performing the build in parallel), all the build processes write to the same stdout location – the console or terminal window. Hence, the output may be out of order or mixed up.
Assuming it goes off well, as indeed it should, by the time this step terminates, three key files (among many) have been generated by the kbuild system. In the root of the kernel source tree, we will now have the following files:
- The uncompressed kernel image file,
vmlinux(used for debugging purposes) - The symbol-address mapping file,
System.map - The compressed bootable kernel image file,
bzImage(see the following output)
Let’s check them out! We make the output (specifically the file size) more human-readable by passing the -h option to ls:
$ ls -lh vmlinux System.map-rw-rw-r-- 1 c2kp c2kp 4.8M May 16 16:12 System.map-rwxrwxr-x 1 c2kp c2kp 704M May 16 16:12 vmlinux$ file vmlinuxvmlinux: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, BuildID[sha1]=e4<...>, with debug_info, not strippedAs you can see, the vmlinux file is huge. This is because it contains all the kernel symbols as well as extra debug information encoded into it. (FYI, the vmlinux and System.map files are used in the kernel debug context; keep them around.) The useful file utility shows us more detail regarding this image file.
The actual kernel image file that the bootloader loads up and boots into will always be in the generic location arch/<arch>/boot/; hence, for the x86 architecture, we have the following:
$ ls -lh arch/x86/boot/bzImage-rw-rw-r-- 1 c2kp c2kp 12M May 16 16:12 arch/x86/boot/bzImage$ file arch/x86/boot/bzImagearch/x86/boot/bzImage: Linux kernel x86 boot executable bzImage, version 6.1.25-lkp-kernel (c2kp@osboxes) #3 SMP PREEMPT_DYNAMIC Tue [...], RO-rootFS, swap_dev 0XB, Normal VGASo, here, our compressed kernel image version 6.1.25-lkp-kernel for the x86_64 is approximately 12 MB in size. The file utility again clearly reveals that indeed it is a Linux kernel boot image for the x86 architecture.
By the way, the kernel’s top-level Makefile has a few simple (yet useful) targets to verify stuff like the kernel version string, and so on; let’s take a peek (it’s toward the end of the large Makefile):
cd ${LKP_KSRC}cat Makefile[ … ]kernelrelease: @echo "$(KERNELVERSION)$$($(CONFIG_SHELL) $(srctree)/scripts/setlocalversion $(srctree))"kernelversion: @echo $(KERNELVERSION)image_name: @echo $(KBUILD_IMAGE)[ … ]Let’s try out these targets:
$ make kernelrelease kernelversion image_name6.1.25-lkp-kernel6.1.25arch/x86/boot/bzImage$Nice.
The kernel documents several tweaks and switches that can be performed during the kernel build by setting various environment variables. This documentation can be found within the kernel source tree at Documentation/kbuild/kbuild.rst. We shall in fact use the INSTALL_MOD_PATH, ARCH, and CROSS_COMPILE environment variables in the material that follows.
Great! Our kernel image and modules are ready! Read on as we install the kernel modules as part of our next step.
Step 5 – installing the kernel modules
Section titled “Step 5 – installing the kernel modules”In the previous step, all the kernel config options that were marked as m – in effect, all the kernel modules, the *.ko files – have by now been built within the source tree. As you shall learn, that’s not quite enough: they must now be installed into a known location on the system. This section covers these details.
Locating the kernel modules within the kernel source
Section titled “Locating the kernel modules within the kernel source”As you just learned, the previous step – building the kernel image and modules – resulted in the compressed and uncompressed kernel images being generated, as well as all the kernel modules (as specified by our kernel config). Kernel modules are identified as files that always have a .ko (for kernel object) suffix. These modules are very useful; they give us kernel functionality in a modular manner (we can decide to plug them in or out of kernel memory at will; the following two chapters will go into great detail on the topic).
For now, knowing that the previous step generated all the kernel module files as well, let’s locate them within the kernel source tree. To that end, we use the find command to locate them within the kernel source folder:
$ cd ${LKP_KSRC}$ find . -name "*.ko"./crypto/crypto_simd.ko./crypto/cryptd.ko[...]./fs/binfmt_misc.ko./fs/vboxsf/vboxsf.koBut merely building the kernel modules is not enough; why? They need to be installed into a well-known location within the root filesystem so that, at boot, the system can actually find and load them into kernel memory. This is why we need the following step, module installation (see the following Getting the kernel modules installed section). The “well-known location within the root filesystem” where they get installed is /lib/modules/$(uname -r)/, where $(uname -r) yields the kernel version number, of course.
Getting the kernel modules installed
Section titled “Getting the kernel modules installed”Performing the kernel module installation is simple; after the build step, just invoke the modules_install Makefile target. Let’s do so:
$ cd ${LKP_KSRC}$ sudo make modules_install[sudo] password for c2kp: INSTALL /lib/modules/6.1.25-lkp-kernel/kernel/arch/x86/crypto/aesni-intel.ko SIGN /lib/modules/6.1.25-lkp-kernel/kernel/arch/x86/crypto/aesni-intel.ko[ … ] INSTALL /lib/modules/6.1.25-lkp-kernel/kernel/sound/soundcore.ko SIGN /lib/modules/6.1.25-lkp-kernel/kernel/sound/soundcore.ko DEPMOD /lib/modules/6.1.25-lkp-kernel$A few points to notice:
- Notice that we use
sudoto perform the module installation process as root (superuser). This is required as the default install location (under/lib/modules/) is only root-writable. Themodules_installtarget causes the kernel modules to be copied across to the correct installation location under/lib/modules/(the work that shows up in the preceding output block asINSTALL /lib/modules/6.1.25-lkp-kernel/<...>). - Next, the module is possibly “signed.” On systems configured with cryptographic signing of kernel modules (
CONFIG_MODULE_SIG: a useful security feature, as is the case here), theSIGNstep has the kernel “sign” the modules.
Briefly, when the config option CONFIG_MODULE_SIG_FORCE is turned on (it’s off by default), only correctly signed modules will be allowed to be loaded into kernel memory at runtime.
- Next, after all modules are copied across (and possibly signed), the
kbuildsystem runs a utility calleddepmod. Its job essentially is to resolve dependencies between kernel modules and encode them (if they exist) into some metafiles.
Now let’s see the result of the module installation step:
$ ls /lib/modules5.19.0-40-generic/ 5.19.0-41-generic/ 5.19.0-42-generic/ 6.1.25-lkp-kernel/In the preceding output, we can see that for each (Linux) kernel installed on the system, there will be a folder under /lib/modules/ whose name is the kernel release, as expected. Let’s look within the folder of interest – that of our new kernel (6.1.25-lkp-kernel). There, under the kernel/ sub-directory – within various directories – live the just-installed kernel modules:
$ ls /lib/modules/6.1.25-lkp-kernel/kernel/arch/ crypto/ drivers/ fs/ lib/ net/ sound/Incidentally, the /lib/modules/<kernel-ver>/modules.builtin file has the list of all installed kernel modules (that live under /lib/modules/<kernel-ver>/kernel/).
Overriding the default module installation location
Section titled “Overriding the default module installation location”A final key point: during the kernel build, we can install the kernel modules into a location that we specify, overriding the (default) /lib/modules/<kernel-ver> location. This is done by setting the environment variable INSTALL_MOD_PATH to the required location. As an example, here, we set up an environment variable, STG_MYKMODS, to hold the location where we want our kernel modules installed, and then run the modules_install command:
export STG_MYKMODS=../staging/rootfs/my_kernel_modulesmake INSTALL_MOD_PATH=${STG_MYKMODS} modules_installWith this, all our kernel modules will get installed into the ${STG_MYKMODS}/ folder. Note how, perhaps, sudo is not required if INSTALL_MOD_PATH refers to a location that does not require root for writing.
This technique – overriding the kernel modules’ install location – can be especially useful when building a Linux kernel and kernel modules for an embedded target. We must not overwrite the host system’s kernel modules with that of the embedded target; that would be disastrous! The reality, of course, is that we can all make mistakes like this once in a while (I know I have!); the usefulness of VMs – especially one that’s checkpointed so that we can quickly revert to a good state – becomes readily apparent!
The next step is to generate the so-called initramfs (or initrd) image and set up the bootloader. We also need to clearly understand what exactly this initramfs image is and the motivation behind using it. The section after the following one delves into these details.
Step 6 – generating the initramfs image and bootloader setup
Section titled “Step 6 – generating the initramfs image and bootloader setup”Firstly, please note that this discussion is highly biased toward the x86[_64] architecture, perhaps the most common one in use. Nevertheless, the concepts learned here can be directly applied to other architectures (like ARM), though the precise commands may vary. Typically, unlike on the x86, and at least for ARM-based Linux, there’s no direct command to generate the initramfs image; it has to be done manually, “by hand.” Embedded builder projects like Yocto and Buildroot do provide ways to automate this.
For the typical x86 desktop or server kernel build procedure, this step is internally divided into two distinct parts:
- Generating the
initramfs(formerly calledinitrd) image - GRUB setup for the new kernel image
The reason it’s encapsulated in a single step here is that, on the x86 architecture, convenience scripts perform both tasks, giving the appearance of a single step.
Are you wondering what exactly this initramfs (or initrd) image file is? Please see the Understanding the initramfs framework section for details. We’ll get there soon.
For now, let’s just go ahead and generate the initramfs (short for initial RAM filesystem) image file as well as update the bootloader. By the way, now might also be a good time to checkpoint your VM (or take a backup) so that, worst case, even if the root filesystem is corrupted (it shouldn’t be), you have a means to revert to a good state and continue working. Performing this on x86[_64] Ubuntu is easily done in one simple step:
$ sudo make install INSTALL /bootrun-parts: executing /etc/kernel/postinst.d/dkms 6.1.25-lkp-kernel /boot/vmlinuz-6.1.25-lkp-kernel * dkms: running auto installation service for kernel 6.1.25-lkp-kernel [ OK ]run-parts: executing /etc/kernel/postinst.d/initramfs-tools 6.1.25-lkp-kernel /boot/vmlinuz-6.1.25-lkp-kernelupdate-initramfs: Generating /boot/initrd.img-6.1.25-lkp-kernel[ … ]run-parts: executing /etc/kernel/postinst.d/xx-update-initrd-links 6.1.25-lkp-kernel /boot/vmlinuz-6.1.25-lkp-kernelI: /boot/initrd.img.old is now a symlink to initrd.img-5.19.0-42-genericI: /boot/initrd.img is now a symlink to initrd.img-6.1.25-lkp-kernelrun-parts: executing /etc/kernel/postinst.d/zz-update-grub 6.1.25-lkp-kernel /boot/vmlinuz-6.1.25-lkp-kernelSourcing file \`/etc/default/grub'Sourcing file \`/etc/default/grub.d/init-select.cfg'Generating grub configuration file ...Found linux image: /boot/vmlinuz-6.1.25-lkp-kernelFound initrd image: /boot/initrd.img-6.1.25-lkp-kernel[ … ]Found linux image: /boot/vmlinuz-5.19.0-42-genericFound initrd image: /boot/initrd.img-5.19.0-42-generic[ … ]doneNotice that, again, we prefix the make install command with sudo. Quite obviously, this is because we require root permission to write the concerned files and folders; they’re written into the /boot directory (which may be set up as part of the root filesystem or as a separate partition).
What if we don’t want to save the output artifacts – the initamfs image and the bootloader files – in /boot? You can always override the destination directory via the INSTALL_PATH environment variable; this is often the case when building Linux for an embedded system. The kernel documentation mentions this here: https://docs.kernel.org/kbuild/kbuild.html#install-path.
So that’s it, we are done: a brand new 6.1 kernel, along with all requested kernel modules and the initramfs image have been generated and installed, and GRUB has been updated to reflect the presence of the new kernel and initramfs images. All that remains is to reboot the system, select the new kernel image on boot (from the bootloader menu screen), boot up, log in, and verify that all is okay.
In this step, we had the initramfs image generated. The question is, what did the kbuild system perform under the hood when we did this? Read on to find out.
Generating the initramfs image – under the hood
Section titled “Generating the initramfs image – under the hood”When you ran the sudo make install command on the x86, under the hood, the kernel Makefile invoked this script: scripts/install.sh. It’s a wrapper script that loops over all possible arch-specific install scripts that may or may not be present, running them (with appropriate parameters) if they exist. To be more precise, these are the locations of the possible arch-specific scripts that will be executed if they exist (in this order):
${HOME}/bin/${INSTALLKERNEL}/sbin/${INSTALLKERNEL}${srctree}/arch/${SRCARCH}/install.sh${srctree}/arch/${SRCARCH}/boot/install.sh
Again, focusing on the x86[_64] here, the arch/x86/boot/install.sh script internally, as part of its work, copies the following files into the /boot folder, with the name format typically being <filename>-$(uname -r)-kernel:
/boot/config-6.1.25-lkp-kernel/boot/System.map-6.1.25-lkp-kernel/boot/initrd.img-6.1.25-lkp-kernel/boot/vmlinuz-6.1.25-lkp-kernelThe initramfs image is built as well. On x86 Ubuntu Linux, a shell script named update-initramfs performs this task (which is itself a convenience wrapper over another script called mkinitramfs that performs the actual work).
But how exactly is the image built? Simplistically, the initramfs image is nothing but a cpio file built using the so-called newc format. The cpio utility (copy-in, copy-out) is an old one, used in creating an archive – a simple collection of files; tar is a well-known user of cpio internally. A simplistic way to build the initramfs image, from the content of a given directory (let’s call it my_initramfs), is to do this:
find my_initramfs/ | sudo cpio -o --format=newc -R root:root | gzip -9 > initramfs.imgNote how the image is typically compressed using gzip.
Once built, the initramfs image is also copied into the /boot directory, seen as the /boot/initrd.img-6.1.25-lkp-kernel file in the preceding output snippet.
If a file being copied into /boot already exists, it is backed up as <filename>-$(uname -r).old. The file named vmlinuz-<kernel-ver>-kernel is a copy of the arch/x86/boot/bzImage file. In other words, it is the compressed kernel image – the image file that the bootloader will be configured to load into RAM, uncompress, and jump to its entry point, thus handing over control to the kernel!
Why do they have the names vmlinux (recall, this is the uncompressed kernel image file stored in the root of the kernel source tree) and vmlinuz? It’s an old Unix convention that the Linux OS is quite happy to follow: on many Unix flavors, the kernel was called vmunix, so Linux calls it vmlinux and the compressed one vmlinuz; the z in vmlinuz is to hint at the (by default) gzip compression it endures. By the way, using gzip for compressing modern kernels is quite outdated; the default on modern x86 is to use the superior (and faster) ZSTD compression, though the file naming conventions remain..
Also, the GRUB configuration file located at /boot/grub/grub.cfg is updated to reflect the fact that a new kernel is now available for boot.
Again, it’s worth emphasizing the fact that all this is very architecture-specific. The preceding discussion concerns building the kernel on an Ubuntu Linux x86_64 system. While conceptually similar, the details of the kernel image filenames, their locations, and especially the bootloader, vary on different architectures and even on different distros.
You can skip ahead to the Step 7 – customizing the GRUB section if you wish. If you are curious (I’m hoping so), read on. In the following section, we describe in some more detail the hows and whys of the initramfs (earlier called initrd) framework.
Understanding the initramfs framework
Section titled “Understanding the initramfs framework”A bit of a mystery remains! What exactly is this initramfs (initial RAM filesystem) or initrd (initial RAM disk) image for? Why is it there?
Firstly, using this feature is a choice – the kernel config directive is called CONFIG_BLK_DEV_INITRD. It’s set to y and hence on by default. In brief, for systems that do not know in advance certain things such as the boot disk host adapter or controller type (SCSI, RAID, and so on), the exact filesystem type that the root filesystem is formatted as (is it ext2, ext4, btrfs, f2fs, or something else?), or for those systems where these functionalities are always built as kernel modules, we require the initramfs capability. Exactly why will become clear in a moment. Also, as mentioned earlier, initrd is now considered an older term. Nowadays, we more often use the term initramfs in its place.
But what exactly is the difference between the older initrd and newer initramfs? The key difference is in how they’re generated. To build an (older) initrd image with the current directory content, we can do:
find . | sudo cpio -R root:root | gzip -9 > initrd.imgWhereas to build the (newer) initramfs image with the current directory content, we do it like this (using the newc format):
find . | sudo cpio -o --format=newc -R root:root | gzip -9 > initramfs.img(Tip: these details will become clearer once you read the following section.)
Why the initramfs framework?
Section titled “Why the initramfs framework?”The initramfs framework is essentially a kind of middle-man between the early kernel boot and user mode. It allows us to run user space applications (or scripts) before the actual (real) root filesystem has been mounted, before the kernel has finished initializing the system. This is useful in many circumstances, a few of which are detailed in the following list. The key point here is that initramfs allows us to run user-mode apps that the kernel cannot normally run during boot time.
Practically speaking, among various uses, this framework allows us to do some interesting things, including the following:
- Set up a console font.
- Customize keyboard layout settings.
- Print a custom welcome message on the console device.
- Accept a password (required for encrypted disks).
- Load up kernel modules as required.
- Spawn a “rescue” shell if something fails.
- And many more!
Imagine for a moment that you are in the business of building and maintaining a new Linux distribution. Now, at installation time, the end user of your distribution might decide to format their SSD disk with, say, the f2fs (fast flash filesystem) filesystem. The thing is, you cannot know in advance exactly what choice the end user will make – it could be one of any number of filesystems. So, you decide to pre-build and supply a large variety of kernel modules that will fulfill almost every possibility. Fine, when the installation is complete and the user’s system boots up, the kernel will, in this scenario, require the f2fs.ko kernel module to successfully mount the (f2fs) root filesystem and proceed further.

Figure 3.1: The kernel image is in RAM, and the root filesystem is on the disk and yet to be mounted
When the bootloader finishes its work, the Linux kernel takes over, running its code to initialize and prepare the system. So, think about this: the kernel is now running in RAM (conceptually seen at the upper left of Figure 3.1), but the modules it will soon require are still on secondary storage, the disk (or flash chip) conceptually seen at the lower right of Figure 3.1; more importantly, they’re not accessible, as the root filesystem is yet to be mounted.
But wait, think about this, we now have a classic chicken-and-egg problem: in order for the kernel to mount the root filesystem (and thus gain access to required modules on it), it requires the f2fs.ko kernel module file to be loaded into RAM (as it contains the necessary code to be able to mount and then work with the filesystem). But that file is embedded inside the f2fs root filesystem itself – to be precise, here: /lib/modules/<kernel-ver>/kernel/fs/f2fs/f2fs.ko (see Figure 3.1).
One of the primary purposes of the initramfs framework is to solve this chicken-and-egg problem. The initramfs image file is a compressed cpio archive (cpio is a flat-file format used by tar). As we mentioned in the previous section, the update-initramfs script internally invokes the mkinitramfs script (on x86 Ubuntu at least, this is the case). These scripts build a minimal temporary root filesystem containing the kernel modules as well as supporting infrastructure such as the /etc and /lib folders in a simple cpio file format, which is then usually gzip-compressed. This now forms the so-called initramfs (or initrd) image file; it will be placed in a file named /boot/initrd.img-<kernel-ver>. Well, how does that help?
At boot, and, of course, assuming the initramfs feature is enabled, the bootloader will, as part of its work, perform an extra step: after uncompressing and loading the kernel image in RAM, it will also load the specified initramfs image file into RAM. Now, when the kernel runs and detects the presence of the initramfs image, it uncompresses it, and using its content (via scripts), it loads up the required kernel modules into RAM (see Figure 3.2):

Figure 3.2: The initramfs image serves as a middleman between early kernel and actual root filesystem availability
Now that the required modules are available within the main memory (RAM, in a format called a “RAM disk”), the kernel can load the required modules (here, f2fs.ko), getting their functionality, and thus actually be able to mount the “real” root filesystem and proceed forward! Some more details on both the boot process (on x86) and the initramfs image can be found in the following sections.
Understanding the basics of the boot process on the x86
Section titled “Understanding the basics of the boot process on the x86”In the following list, we provide a brief overview of the typical boot process on an x86[_64] desktop (or laptop), workstation, or server:
- Firstly, there are broadly two ways in which systems boot. First, the legacy way (specific to the x86) is via the BIOS (short for Basic Input Output System – essentially, the firmware on the x86). After carrying out basic system initialization and diagnostics (POST – Power On Self Test), it loads up the first sector of the first bootable disk into RAM and jumps to its entry point. This forms what is often referred to as the stage one bootloader, which is very small (typically just 1 sector, 512 bytes); its primary job is to load the stage two (larger) bootloader code – also present on the bootable disk – into memory and jump to it.
The modern, more powerful way to boot is via the newer UEFI (Unified Extensible Firmware Interface) standard: on many modern systems, the UEFI framework is used as a superior and more secure way to boot the system.
So what’s the difference between the legacy BIOS and newer UEFI? Very briefly:
- UEFI is a modern framework not limited to the x86 (the BIOS is x86-only); for example, ARM-based systems leverage UEFI as part of their famed Secure Boot capabilities.
- UEFI is much more secure; it will only allow “signed” operating systems (what it calls “apps”) to be booted via it (this can cause issues with dual-booting at times).
- UEFI requires a separate special partition called the ESP (EFI System Partition); this holds a
.efifile that contains the initialization code and data, unlike the BIOS, where it’s written in firmware (typically in an EEPROM chip). Thus, updating UEFI is straightforward. - UEFI boot time is faster than that of legacy BIOS.
- UEFI lets you run modern 32- or 64-bit code, thus attractive GUIs can be used for the interface; the BIOS works with 16-bit code only.
- Drive size: the BIOS supports only up to 2.2 TB disks, whereas UEFI can support disks up to 9 ZB (zettabytes) in size!
- Regardless of UEFI/BIOS, once the kernel image is loaded in RAM, the stage two bootloader code takes control. Its main job is to load the actual (stage three) bootloader from the filesystem into memory and jump to its entry point. On the x86, GRUB is typically the bootloader employed (an older one is LILO (Linux Loader)).
- GRUB will be passed both the compressed kernel image file (
/boot/vmlinuz-<kernel-ver>) as well as the compressedinitramfsimage file (/boot/initrd.img-<kernel-ver>) as parameters (via its config file, which we’ll see in coming sections). The bootloader will (simplistically) do the following:- Perform low-level hardware initialization.
- Load these images into RAM, uncompressing the kernel image to a certain extent.
- It will then jump to the kernel entry point.
- Perform low-level hardware initialization.
- The Linux kernel, now having full control of the machine, will initialize the hardware and software environment. It typically makes no assumptions regarding the earlier work performed by the bootloader. Well, it does depend upon the BIOS or UEFI to set up things like PCI addressing and interrupt line assignment via ACPI tables (or, on ARM/PPC, via the Device Tree).
- Upon completing most of the hardware and software initialization, if it notices that the
initramfsfeature is turned on (CONFIG_BLK_DEV_INITRD=y), it will locate (and if required, uncompress) theinitramfs(initrd) image in RAM (see Figure 3.2). - It will then mount it as a temporary root filesystem in RAM itself, within a RAM disk.
- We now have a base, minimal, and temporary root filesystem set up in memory. Thus, the
initramfs-basedstartup scripts now run, performing, among other tasks, the loading of the required kernel modules into RAM (in effect, loading the root filesystem drivers, including, in our scenario, thef2fs.kokernel module; again, see Figure 3.2). - When initramfs runs, it first invokes
/sbin/init(this could be a binary executable or a script); besides other housekeeping tasks, it performs a key job: a pivot-root, unmounting the temporary initramfs root filesystem, freeing its memory, and mounting the real root filesystem. It’s now possible because the kernel module providing that filesystem support is indeed available (in RAM). - Once the (actual disk or flash-based) root filesystem is successfully mounted, system initialization can proceed. The kernel continues, ultimately invoking the first user space process (PID 1), typically
/sbin/init(when using the older SysV init framework), or, more likely these days, via the more powerfulsystemdinit framework. - The
initframework now proceeds to initialize the system, bringing up system services as configured.
A few things to note:
On modern Linux systems, the traditional (read: old/legacy) SysV (read as System Five) init framework has largely been replaced with a modern optimized framework called systemd (system daemon). Thus, on many (if not most) modern Linux systems, including embedded ones, the traditional /sbin/init has been replaced with systemd (or is simply a symbolic link to its executable file). The systemd framework is considered superior, with the ability to fine-tune the boot process and optimize boot time, along with many, many more features. Find out more about systemd in the Further reading section.
The generation of the initramfs root filesystem itself is not covered in detail in this book; the official kernel documentation does cover some of it – Using the initial RAM disk (initrd): https://docs.kernel.org/admin-guide/initrd.html.
Also, as a simple example of generating a root filesystem, you could look at the code of the SEALS project (at https://github.com/kaiwan/seals) that I mentioned in Online Chapter, Kernel Workspace Setup; it has a Bash script that generates a very minimal, or skeleton, root filesystem from scratch.
Now that you understand the motivation behind initramfs, we’ll complete this section by providing a bit of a deeper look into initramfs in the following section. Do read on!
More on the initramfs framework
Section titled “More on the initramfs framework”Another place where the initramfs framework helps is in bringing up computers whose disks are encrypted.
Are you working on a laptop with unencrypted disks? That’s not a great idea; if your device is ever lost or stolen, hackers can easily gain access to your data by simply booting into it using a Linux-based USB pen drive and can then typically access all its disk partitions. Your login credentials don’t help here. Modern distros can certainly and painlessly encrypt disk partitions; this is now a routine part of the installation. Besides volume-based encryption (provided by LUKS, dm-crypt, eCryptfs, and so on), several tools exist to individually encrypt and decrypt files. See these links for more:
Top 10 file and disk encryption tools for Linux, January 2022: https://www.fosslinux.com/50005/top-10-file-and-disk-encryption-tools-for-linux.htm, and Best File & Disk Encryption Tools for Linux, Day, May 2022: https://linuxsecurity.com/features/top-8-file-and-disk-encryption-tools-for-linux.
Assuming a system with encrypted filesystems, quite early in the boot process, the kernel will have to query the user for the password, and if correct, proceed with decrypting and mounting the disks, and so on.
But think about this: how can we run a C program executable that is, say, requesting a password, without having a C runtime environment in place – a root filesystem containing libraries, the loader program (ld-linux…), required kernel modules (for the crypto support perhaps), and so on?
Remember, the kernel itself hasn’t yet completed initialization; how can user space apps run? Again, the initramfs framework solves this issue by setting up a pretty complete, though temporary, userspace runtime environment complete with the required root filesystem containing libraries, the loader, kernel modules, some scripts, and so on, in primary memory.
Peeking into the initramfs image
Section titled “Peeking into the initramfs image”So, we just stated that the initramfs image is a temporary yet pretty complete one, containing system libraries, the loader program, minimally required kernel modules, some scripts, and so on. Can we verify this? Yes, indeed we can! Let’s take a peek into the initramfs image file. The lsinitramfs script on Ubuntu serves exactly this purpose (on Fedora, the equivalent is called lsinitrd instead):
$ ls -lh /boot/initrd.img-6.1.25-lkp-kernel-rw-r--r-- 1 root root 26M Jun 13 11:08 /boot/initrd.img-6.1.25-lkp-kernel$ lsinitramfs /boot/initrd.img-6.1.25-lkp-kernel|wc -l364$ lsinitramfs /boot/initrd.img-6.1.25-lkd-kernel.kernel[ ... ]bin[ ... ]conf/initramfs.confetcetc/console-setup[ ... ]etc/default/console-setupetc/default/keyboardetc/dhcp[ ... ]etc/modprobe.detc/modprobe.d/alsa-base.conf[ ... ]etc/udev/udev.conf[ ... ]lib64libx32runsbinscriptsscripts/functionsscripts/init-bottom[ ... ]usrusr/binusr/bin/cpiousr/bin/ddusr/bin/dmesg[ ... ]usr/lib/initramfs-toolsusr/lib/initramfs-tools/bin[ ... ]usr/lib/modprobe.d/systemd.confusr/lib/modules[ ... ]usr/lib/modules/6.1.25-lkp-kernel/kernel/crypto/crc32_generic.ko[ ... ]usr/lib/modules/6.1.25-lkp-kernel/kernel/drivers/net/ethernet/intel/e1000/e1000.ko[ ... ]usr/lib/modules/6.1.25-lkp-kernel/kernel/fs/f2fs/f2fs.ko[ ... ]usr/sbin/modprobe[ ... ]var/lib/dhcpThere’s quite a bit in there: we truncate the output to show a few select snippets. We can see a minimal root filesystem with support for the required runtime libraries, kernel modules, the /etc, /bin, /sbin, /usr, and more directories, along with their utilities.
The details of constructing the initramfs (or initrd) image go beyond what we wish to cover here. We did mention the basics; you can generate an initramfs image like this: find my_initramfs/ | sudo cpio -o --format=newc -R root:root | gzip -9 > initramfs.img. I suggest you peek into these scripts to reveal their inner workings (on Ubuntu): /usr/sbin/update-initramfs, a wrapper script over the /usr/sbin/mkinitramfs shell script. See the Further reading section for more.
Also, modern systems feature what is sometimes referred to as a hybrid initramfs: an initramfs image that consists of an early ramfs image prepended to the regular or main ramfs image. The reality is that we require special tools to unpack/pack (uncompress/compress) these images. Ubuntu provides the unmkinitramfs and mkinitramfs scripts, respectively, to perform these operations.
As a quick experiment, let’s unpack our brand-new initramfs image (the one generated in the previous section) into a temporary directory. Again, recall that this has been performed on our x86_64 Ubuntu 22.04 LTS guest VM. We view its output, truncated for readability, with tree:

Figure 3.3: Screenshot showing the partial directory tree of our 6.1 initramfs image
We’ve truncated the screenshot to show just a bit; plenty of output follows… I urge you to try this out and see for yourself.
This concludes our (rather lengthy!) discussion on the initramfs framework and the basics of the boot process on the x86[_64]. The good news is that now, armed with this knowledge, you can further customize your product by tweaking the initramfs image as required – an important skill! You’ll find more on how exactly you can customize the initramfs image in the Further reading section.
Exercise
Take your existing initamfs image, extract it, and customize it to include a new app or script (which you can run via one of the startup scripts).
As an example (and as mentioned earlier), with security being a key factor on modern systems, being able to encrypt a disk at the block level is a powerful security feature; doing this very much involves tweaking the initramfs image. (Again, the Further reading section has links on how to go about disk encryption).
Now, let’s finally complete the x86_64 kernel build procedure with some simple customization of the (x86) GRUB bootloader’s boot script.
Step 7 – customizing the GRUB bootloader
Section titled “Step 7 – customizing the GRUB bootloader”We have now completed steps 1 to 6 as outlined in Chapter 2, Building the 6.x Linux Kernel from Source – Part 1, in the Steps to build the kernel from source section. You can now reboot the system; of course, do first save and close all your apps and files. By default, though, the modern GRUB does not even show us any menu on reboot; it will by default boot into the newly built kernel (do remember that, here, we’re describing this process only for x86[_64] systems running Ubuntu; the default kernel booted into can also vary with the distro).
On x86[_64] you can always get to the GRUB menu during early system boot. Just ensure you keep the Shift key pressed down during boot. Again, this behavior does depend on other factors – on systems with newer UEFI/BIOS firmware enabled, or when running within a nested VM, you may require other ways to force-see the GRUB menu at boot (try pressing Esc too).
What if we would like to see and customize the GRUB menu every time we boot the system, thus allowing us to possibly select an alternate kernel/OS to boot from (or even pass some kernel parameters along)? This is often very useful during development and debugging, so let’s find out how we can do this.
Customizing GRUB – the basics
Section titled “Customizing GRUB – the basics”Customizing GRUB is quite easy to do; we can always, as root, edit its config file: /etc/default/grub. Do note the following:
- The following steps are to be carried out on the “target” system itself (not on the host) – in our case, within the x86_64 Ubuntu 22.04 guest VM. Of course, if working on Linux natively, you can go ahead on the same system.
- This procedure has been tested and verified on our x86_64 Ubuntu 22.04 LTS guest system only.
So what exactly are we setting out to do here? We want GRUB to show us its menu at boot, before running our favorite OS, allowing us to customize it further. Here’s a quick series of steps to do this:
- First, let’s be safe and keep a backup copy of the GRUB bootloader config file:
sudo cp /etc/default/grub /etc/default/grub.orig
- Edit it. You can use
vior your editor of choice:sudo vi /etc/default/grub - To always show the GRUB prompt at boot, insert this line:
GRUB_HIDDEN_TIMEOUT_QUIET=false
On some Linux distros, you might instead have the GRUB_TIMEOUT_STYLE=hidden directive; simply change it to GRUB_TIMEOUT_STYLE=menu to achieve the same effect. Always showing the bootloader menu at boot is good during development and testing and is typically turned off in production for both speed and security.
Talking about security, always ensure that access to the firmware (BIOS/UEFI) and bootloader is password-protected.
- Set the timeout to boot the default OS (in seconds) as required. The default is
10seconds; here, we set it to 3 seconds:GRUB_TIMEOUT=3
Setting the preceding timeout value to the following values will produce the following outcomes:
0: Boot the system immediately without displaying the menu.-1: Wait indefinitely.
Furthermore, if a GRUB_HIDDEN_TIMEOUT directive is present in the config file, just comment it out:
#GRUB_HIDDEN_TIMEOUT=1- Finally, run the
update-grubprogram as root to have your changes take effect:sudo update-grub
The preceding command will typically cause the initramfs image to be refreshed (regenerated). Once done, you’re ready to reboot the system. Hang on a second, though! The following section shows you how you can modify GRUB’s configuration to boot by default into a kernel of your choice.
Selecting the default kernel to boot into
Section titled “Selecting the default kernel to boot into”The GRUB default kernel is preset to be the number zero (via the GRUB_DEFAULT=0 directive). This will ensure that the “first kernel” – the most recently added one – boots by default (upon timeout).
This may not be what we want; as a real example, on our x86 Ubuntu 22.04 LTS guest VM, we can set it to the default Ubuntu distro kernel by, as earlier, editing the /etc/default/grub file (as root, of course), like so:
GRUB_DEFAULT="Advanced options for Ubuntu>Ubuntu, with Linux 5.19.0-43-generic"Of course, this implies that if your distro is updated or upgraded, you must again manually change the preceding line to reflect the new distro kernel that you wish to boot into by default, and then run sudo update-grub.
Right, our freshly edited GRUB configuration file is shown as follows:
$ cat /etc/default/grub [...]#GRUB_DEFAULT=0GRUB_DEFAULT="Advanced options for Ubuntu>Ubuntu, with Linux 5.19.0-43-generic" #GRUB_TIMEOUT_STYLE=hiddenGRUB_HIDDEN_TIMEOUT_QUIET=falseGRUB_TIMEOUT=3GRUB_DISTRIBUTOR=\`lsb_release -i -s 2> /dev/null || echo Debian\`GRUB_CMDLINE_LINUX_DEFAULT="quiet splash" GRUB_CMDLINE_LINUX="quiet splash" [...]As in the previous section, don’t forget: if you make any changes here, run the sudo update-grub command to have your changes take effect.
Additional points to note:
In addition, you can add “pretty” tweaks, such as changing the background image (or color) via the BACKGROUND_IMAGE="<img_file>" directive.
On Fedora, the GRUB bootloader config file is a bit different; run this command to show the GRUB menu at every boot:
sudo grub2-editenv - unset menu_auto_hideThe details can be found in the Fedora wiki – Changes/HiddenGrubMenu: https://fedoraproject.org/wiki/Changes/HiddenGrubMenu.
Unfortunately, GRUB2 (the latest version is now 2) seems to be implemented differently on pretty much every Linux distro, leading to incompatibilities when trying to tune it in one given manner.
All done! Let’s (finally!) reboot the system, get into the GRUB menu, and boot our new kernel:
$ sudo reboot [sudo] password for c2kp:Once the system completes its shutdown procedure and reboots, you should soon see the GRUB bootloader menu (the following section shows several screenshots too). Be sure to interrupt it by pressing any keyboard key!
Though always possible, I recommend you don’t delete the original distro kernel image(s) (and associated initrd, System.map files, and so on). What if your brand-new kernel fails to boot? (If it can happen to the Titanic…!) By keeping our original images, we thus have a fallback option: boot from the original distro kernel, fix our issue(s), and retry. Note that there’s almost always automatically a Recovery… menu option as well, which will try and at least log you into a root shell. Close to worst case, you usually get logged in to an initramfs-based shell (working from RAM).
As a worst-case scenario, what if all other kernels /initrd images have been deleted (or are corrupt) and your single new kernel fails to boot successfully? Ahem. Well, you can always boot into a recovery mode Linux via a USB pen drive; a bit of googling regarding this will yield many links and video tutorials. (FYI, here’s Ubuntu’s link to do precisely this, via a neat GUI app that’s typically preinstalled: https://ubuntu.com/tutorials/create-a-usb-stick-on-ubuntu#1-overview.)
Booting our VM via the GNU GRUB bootloader
Section titled “Booting our VM via the GNU GRUB bootloader”Now our guest VM (here, using the Oracle VirtualBox hypervisor) is about to come up; once its (emulated) BIOS / UEFI routines are done, the GNU GRUB screen shows up first. (Note that the procedures explained here will work as well on a native Linux system.) This happens because we quite intentionally changed the GRUB_HIDDEN_TIMEOUT_QUIET GRUB configuration directive to the value of false (as explained in the previous section). See the following screenshot (Figure 3.4).
The particular styling seen in the screenshot is how it’s customized to appear for the Ubuntu distro:

Figure 3.4: The GRUB2 menu – paused on system startup
Now let’s go straight into booting our VM:
- Press any keyboard key (except Enter) to ensure the default kernel is not booted once the timeout expires (recall, we set it to 3 seconds).
- If not already there, scroll to the
Advanced options for Ubuntumenu, highlighting it (as seen in Figure 3.4), and press Enter. - Now you’ll see a menu similar, but likely not identical, to the following screenshot (Figure 3.5). For each kernel that GRUB has detected and can boot into, there are two lines shown – one for the kernel itself and one for the special recovery mode boot option for that kernel:

Figure 3.5: The GRUB2 Advanced options… menu showing available kernels to boot from
Notice how the kernel that will boot by default – in our case, 6.1.25-lkp-kernel – is highlighted by default with an asterisk (*).
The preceding screenshot shows a few “extra” line items. This is because, at the time of taking this screenshot, I had built my 6.1.25 kernel a few times (resulting in the previous one being saved as the “.old ” item; also, keeping Ubuntu updated results in newer distro kernels getting installed as well. We can spot the 5.19.0-43-generic kernel and its predecessor. No matter; we ignore them here.
An aside: for some variety, here’s a screenshot of a UEFI-based system’s boot selection menu screen (in this particular case, on an x86_64 (Dell) PC to show the boot menu, the UEFI hotkey happens to be F12); notice the rich GUI as well as mouse pointer support:

Figure 3.6: The boot selection menu on a UEFI-based x86_64 PC
- Okay, back to our x86 Ubuntu VM with the GRUB: whatever the case, simply scroll to and highlight the entry of interest – here, our shiny new 6.1 LTS kernel, the menu entry labeled
*Ubuntu, with Linux 6.1.25-lkp-kernel(as seen in Figure 3.5). Here, it’s the very first line of the GRUB menu (as it’s the most recent addition to the GRUB menu of bootable OSs). - Once you have highlighted the preceding menu item, press Enter and voilà! The bootloader will proceed to do its job, uncompressing and loading the kernel and initramfs (or
initrd) images into RAM, and jumping to the Linux kernel’s entry point, thus handing over control to Linux!
Right, if all goes well, as it should, you will have booted into your brand-new freshly baked 6.1.25 LTS Linux kernel! Congratulations on a task well done!
Then again, you could always do more – the following section shows you how you can further edit and customize GRUB’s config at runtime (boot time). Again, this skill comes in handy now and then – for example, forgot the root password? Yes, indeed, you can actually bypass it using this technique! Read on to find out how.
Experimenting with the GRUB prompt
Section titled “Experimenting with the GRUB prompt”You could experiment further; instead of merely pressing Enter while on the Ubuntu, with Linux 6.1.25-lkp-kernel menu entry, ensure that this line is highlighted and press the e (for edit) key. We shall now enter GRUB’s edit screen, wherein we are free to edit any value we like. Here’s a screenshot after pressing the e key:

Figure 3.7: The GRUB2 bootloader: editing our custom 6.1.25-lkp-kernel kernel menu entry
This screenshot was taken after scrolling down a few lines; look carefully – you can spot the cursor (an underscore-type one: “_”) at the very beginning of the fourth line from the bottom of the edit box. (I put this key line into a box, just for emphasis. Also, the disk UUID value has been partially hidden.) This is the crucial line; it starts with the suitably indented keyword linux.
It specifies the path to the (compressed) kernel image, followed by the storage device ID where the image is present, and then the list of kernel parameters being passed via the GRUB bootloader to the Linux kernel. Here, the pathname to the kernel image is /vmlinuz-6.1.25-lkp-kernel; it starts at / as /boot is a separate partition.
Try experimenting a bit here:
- Exercise 1: As a simple exercise, after highlighting the key menu line beginning with
linux, scroll to the right and delete the wordsquietandsplashfrom this entry, then press Ctrl + X or F10 to boot. This time, the pretty Ubuntu splash screen does not appear; you are directly in the console seeing all kernel messages (emitted via the ubiquitousprintk()-related APIs, as you’ll soon learn) as they flash past, and later, systemd’s console messages and so on.
Next, a common question: what if we forget our password and thus cannot log in? Well, there are several approaches to tackle this. One is to attempt to reset it via the bootloader’s help; here’s how, let’s do it as a small learning exercise.
- Exercise 2: Boot into the GRUB menu as we have done, go to the relevant kernel menu entry, press e to edit it, scroll down to the line beginning with
linux, and append the wordsingle(or just the number1) at the end of this entry, such that it looks like this:linux /vmlinuz-6.1.25-lkp-kernel root=UUID=<...> ro quiet splash $vt_handoff single
Now, when you boot, the kernel boots into single-user mode and gives you, the eternally grateful user, a shell with root access. It might prompt you to Press Enter for maintenance; please do so. Just run the passwd <username> command to change/reset your password. Exiting this root shell has the normal boot procedure continue.
The precise procedure to boot into single-user mode varies with the distro. Exactly what to edit in the GRUB2 menu is a bit different on Red Hat/Fedora/CentOS. See the Further reading section for a link on how to set it for these systems.
This teaches us something regarding security, doesn’t it? A system is considered insecure when access to the bootloader menu (and even to the BIOS/UEFI) is possible without a password! In fact, in highly secured environments, even physical access to the console device must be restricted.
Great, by now, you have learned how to customize the GRUB and, I expect, have booted into your fresh 6.1 Linux kernel! Let’s not just assume things; let’s verify that the kernel is indeed the right one and configured as per our plan.
Verifying our new kernel’s configuration
Section titled “Verifying our new kernel’s configuration”Okay, so back to our discussion. We have now booted into our newly built kernel. But hang on, please don’t blindly assume that everything’s just fine; let’s actually verify that.
The empirical approach is always best; in this section, let’s verify that we are indeed running the (6.1.25) kernel we just built and that it has indeed been configured as we intended. We start by examining the kernel version:
$ uname -r6.1.25-lkp-kernelIndeed, we are now running Ubuntu 22.04 LTS on our just-custom-built 6.1.25 LTS kernel! Further variations of the uname utility show us the machine hardware name and the OS is as planned: we’re on the x86_64 running GNU/Linux:
$ uname -m ; uname -ox86_64GNU/LinuxMoving along, recall our discussion in Chapter 2, Building the 6.x Linux Kernel from Source – Part 1, in the Sample usage of the make menuconfig UI section, where we performed a couple of small changes to the kernel config as an exercise.
Now, we check that each configuration items we changed then has taken effect. Let’s list them here, starting with the concerned CONFIG_'FOO' name, as follows:
CONFIG_LOCALVERSION: The preceding output ofuname -rclearly shows thelocalversion(or-EXTRAVERSION) part of the kernel version has been set to what we wanted: the-lkp-kernelstring.CONFIG_IKCONFIG: This should have been enabled (see the previous chapter); it allows us to query the current kernel’s config via the/proc/config.gzpseudo-file.CONFIG_HZ: We set this option to 300 as an experiment.
So, let’s now check via the kernel extract-ikconfig script (also, recall that you are to set the LKP_KSRC environment variable to the root location of your 6.1 kernel source tree directory):
$ ${LKP_KSRC}/scripts/extract-ikconfig /boot/vmlinuz-6.1.25-lkp-kernel## Automatically generated file; DO NOT EDIT. # Linux/x86 6.1.25 Kernel Configuration [...]CONFIG_HZ_300=y [...]It works! We can see the entire kernel configuration via the scripts/extract-ikconfig script (we can do so as the CONFIG_IKCONFIG[_PROC] configs are enabled). We shall use this very script to grep the remainder of the config directives that we changed in the previous chapter (Chapter 2, Building the 6.x Linux Kernel from Source – Part 1, in the Sample usage of the make menuconfig UI section):
$ scripts/extract-ikconfig /boot/vmlinuz-6.1.25-lkp-kernel | grep -E "LOCALVERSION|CONFIG_HZ"CONFIG_LOCALVERSION="-lkp-kernel"# CONFIG_LOCALVERSION_AUTO is not set# CONFIG_HZ_PERIODIC is not set# CONFIG_HZ_100 is not set# CONFIG_HZ_250 is not setCONFIG_HZ_300=y# CONFIG_HZ_1000 is not setCONFIG_HZ=300Carefully looking through the preceding output, we can see that we got precisely what we wanted. Our new kernel’s configuration settings match precisely the settings expected in Chapter 2, Building the 6.x Linux Kernel from Source – Part 1, in the Sample usage of the make menuconfig UI section. Perfect.
Alternatively, as we have enabled the CONFIG_IKCONFIG_PROC option, we could have achieved the same verification by looking up the kernel config via the (compressed) proc filesystem entry, /proc/config.gz, like this:
gunzip -c /proc/config.gz | grep -E "LOCALVERSION|CONFIG_HZ"So, the kernel build is done! Fantastic. I urge you to refer back to Chapter 2, Building the 6.x Linux Kernel from Source – Part 1, in the Steps to build the kernel from source section, to again see the high-level overview of the steps for the entire process. Right, onto something quite interesting: in the next section, we will learn how to cross-compile the Raspberry Pi board kernel.
Kernel build for the Raspberry Pi
Section titled “Kernel build for the Raspberry Pi”A popular and relatively inexpensive Single-Board Computer (SBC) to experiment and prototype with is the ARM-based Raspberry Pi. Hobbyists, tinkerers, and, to some extent, even pros find it very useful to try out and learn how to work with embedded Linux, especially as it has a strong community backing (with many Q&A forums) and excellent support. (You’ll find a brief discussion and picture of a Raspberry Pi board in Online Chapter, Kernel Workspace Setup, in the Experimenting with the Raspberry Pi section. By the way, there are several well-known Raspberry Pi clones – like the Orange Pi – that work very well; the discussions should apply equally to them.)
There are two typical ways in which you can build a kernel for the target device or Device Under Test (DUT) that we’ll use here, the Raspberry Pi 4 Model B (64-bit):
- Build the kernel on a powerful host system, typically an x86_64 (or Mac) desktop or laptop running a Linux distro.
- Perform the build on the target device itself.
We shall follow the first method – it’s a lot faster and is considered the right way to perform embedded Linux development. (FYI, building the kernel on the target device is explained here: https://www.raspberrypi.com/documentation/computers/linux_kernel.html#building-the-kernel-locally.)
We shall assume (as usual) that we are running on our x86_64 Ubuntu 22.04 LTS guest VM. So, think about it; now, the host system is a guest Linux VM! Also, we’re targeting building the kernel for the AArch64 architecture, to take full advantage of it (not for 32-bit).
Performing large downloads and kernel build operations on a guest VM isn’t really ideal. Depending on the power and RAM of the host and guest, it will take a while. It could end up being twice as slow as building on a native Linux box. Nevertheless, assuming you have set aside sufficient disk space in the guest VM (and, of course, the host actually has this space available), this procedure works.
We will have to use an x86_64-to-AArch64 (64-bit) cross-compiler to build the kernel, or any component for that matter, for the DUT, the AArch64 Raspberry Pi 4 target. This implies installing an appropriate cross-toolchain as well to perform the build.
In the following few sections, we divide the work into three discrete steps:
- Step 1 – cloning the Raspberry Pi kernel source tree
- Step 2 – installing an x86_64-to-AArch64 cross-toolchain
- Step 3 – configuring and building the Raspberry Pi AArch64 kernel.
So, let’s begin!
Step 1 – cloning the Raspberry Pi kernel source tree
Section titled “Step 1 – cloning the Raspberry Pi kernel source tree”We arbitrarily select a staging folder (the place where the build happens) for the Raspberry Pi kernel source tree and the cross-toolchain, and assign it to an environment variable (to avoid hardcoding it):
- Set up your workspace. We set an environment variable as
RPI_STG(it’s not required to use exactly this name for the environment variable; just pick a reasonable-sounding name and stick to it) to the staging folder’s location – the place where we shall perform the work. Feel free to use a value appropriate to your system (I’m using~/rpi_work):export RPI_STG=~/rpi_workmkdir -p ${RPI_STG}/kernel_rpi
Do ensure you have sufficient disk space available: the Raspberry Pi Git kernel source tree takes approximately 1.7 GB, and the (simpler) toolchain is just a little over 40 MB. You’ll require at least 3 to 4 GB for working space. Further, if you build the images as Deb packages (we cover this shortly), it will require at least 1 GB of disk space (it’s really best to keep around 7 to 8 GB free disk space to be safe).
- Download the Raspberry Pi-specific kernel source tree (we clone it from the official source, the Raspberry Pi GitHub repository for the kernel tree, here: https://github.com/raspberrypi/linux/):
cd ${RPI_STG}/kernel_rpigit clone --depth=1 --branch=rpi-6.1.y \https://github.com/raspberrypi/linux.git
The kernel source tree gets cloned under a directory called linux/ (that is, under ${RPI_STG}/kernel_rpi/linux). It can take a while. Notice how, in the preceding command, we have the following:
- The particular Raspberry Pi kernel tree branch we have selected is not the very latest one (at the time of writing, the very latest is the rpi-6.8.y series), it’s the 6.1 kernel; that’s perfectly okay (6.1.y is an LTS kernel and matches our x86 one as well!).
- We pass the
--depthparameter set to1togit cloneto reduce the download and uncompress loads.
Now the Raspberry Pi kernel source tree is installed. Let’s briefly verify this:
$ cd ${RPI_STG}/kernel_rpi/linux ; head -n5 MakefileVERSION = 6PATCHLEVEL = 1SUBLEVEL = 34EXTRAVERSION =Okay, it’s the 6.1.34 Raspberry Pi kernel port. (The kernel version we use on the x86_64 is the 6.1.25 one; the slight variation is fine. Also, the release version (y=34) could change by the time you try it out, which again is fine.)
Step 2 – installing an x86_64-to-AArch64 cross-toolchain
Section titled “Step 2 – installing an x86_64-to-AArch64 cross-toolchain”Now it’s time to install a cross-toolchain on your host system (recall, it’s our x86 Ubuntu VM) that’s appropriate for performing the actual build. The thing is, there are several working toolchains available. Here, I shall employ the easiest and best way of obtaining and installing an appropriate toolchain for the task at hand. (FYI, the first edition of this book specified a second more complex way, via the Raspberry Pi “tools” GitHub repo; that is now considered deprecated, thus we won’t delve into it.)
Modern distros typically provide ready-to-use cross-build (or cross-compile) packages! To see a subset of them (just the GCC compiler packages for various arch’s) on (x86) Debian/Ubuntu, type in the following and press the Tab key twice (to auto-complete):
sudo apt install gcc-<TAB><TAB>Display all 398 possibilities? (y or n) ygcc-10 gcc-12-plugin-dev-alpha-linux-gnugcc-10-aarch64-linux-gnu gcc-12-plugin-dev-arm-linux-gnueabigcc-10-aarch64-linux-gnu-base gcc-12-plugin-dev-arm-linux-gnueabihfgcc-10-alpha-linux-gnu gcc-12-plugin-dev-hppa-linux-gnugcc-10-alpha-linux-gnu-base gcc-12-plugin-dev-i686-linux-gnugcc-10-arm-linux-gnueabi gcc-12-plugin-dev-m68k-linux-gnu[ … ]Nice! So many toys to play with. We’ll also require the binutils package; so, let’s install both the relevant ones:
$ sudo apt install gcc-aarch64-linux-gnu binutils-aarch64-linux-gnuThe cross tools are typically installed under /usr/bin/ and are, therefore, already part of your PATH; you now can simply use them. For example, check out the AArch64 GCC compiler’s location and version info, as follows:

Figure 3.8: Screenshot showing the AArch64 cross-compiler packages have been successfully installed (in /usr/bin)
Figure 3.8 shows us the tools in the toolchain! Notice how they’re all installed under /usr/bin/ and, more importantly, all of them are prefixed with aarch64-linux-gnu-. This is called the cross-compiler or toolchain prefix and is typically placed in the environment variable named CROSS_COMPILE (we’ll get to this shortly).
Does the cross-compiler prefix mean anything? Yes, there is a naming convention followed, and it’s of the following form:
MACHINE-VENDOR-OS-
or
<CPU>-<MANUFACTURER>[-<KERNEL>]-<OS>-
The first form is called the “target triplet” and it’s the one our cross-toolchain prefix (aarch64-linux-gnu-) is using (as it has three components in the prefix, not four). So, here, we have MACHINE as aarch64 (which, of course, implies that the target CPU is an ARM 64-bit), the VENDOR is simply set to linux, and the OS field is set to gnu (it’s not perfect; you can think of the VENDOR field as being empty and the OS field as the value linux-gnu).
Also, do keep in mind that this toolchain is appropriate for building the kernel for the AArch64 (ARM 64-bit) architecture, not for 32-bit. If that’s your intention, you will need to install an x86_64-to-AArch32 toolchain with sudo apt install gcc-arm-linux-gnueabihf binutils-arm-linux-gnueabihf (the hf suffix in the toolchain package name is for “hard float,” as the Raspberry Pi target processor uses one).
As mentioned earlier, alternate toolchains can be used as well. For example, several toolchains for ARM development (for GNU/Linux, Windows, and macOS hosts) are available on the ARM developer site at https://developer.arm.com/downloads/-/arm-gnu-toolchain-downloads.
Step 3 – configuring and building the Raspberry Pi AArch64 kernel
Section titled “Step 3 – configuring and building the Raspberry Pi AArch64 kernel”Right, let’s now configure the kernel (for the Raspberry Pi 4). Before we begin, it’s very important to keep the following in mind:
- The
ARCHenvironment variable must be set to the CPU – the architecture – for which the software is to be cross-compiled (that is, the compiled code will run on that CPU). The precise value to setARCHto is the name of the directory under thearch/directory in the kernel source tree. So, for example, you’d setARCHtoarmfor ARM-32, toarm64for the AArch64, topowerpcfor the PowerPC, and toopenriscfor the OpenRISC processor. - The
CROSS_COMPILEenvironment variable must be set to the cross-compiler (toolchain) prefix. Essentially, it’s the first few common letters that precede every utility in the toolchain. In our example, all the toolchain utilities (the C compilergcc, linker, C++,objdump, and so on) begin withaarch64-linux-gnu-(see Figure 3.8), so that’s what we setCROSS_COMPILEto. Also note that theMakefilewill always invoke the utilities as${CROSS_COMPILE}<utility>, hence invoking the correct toolchain executable. This does imply that the toolchain directory should be within thePATHvariable.
Lets go through the necessary steps now:
- Okay, let’s proceed by setting up the default kernel configuration:
cd ${RPI_STG}/kernel_rpi/linuxmake mrproperKERNEL=kernel8make ARCH=arm64 bcm2711_defconfig
The result of the above is a default kernel config, saved of course as the file .config. A quick explanation regarding the configuration target, bcm2711_defconfig: this key point was mentioned in Chapter 2, Building the 6.x Linux Kernel from Source – Part 1, in the Kernel config for typical embedded Linux systems section. We must ensure that we use an appropriate board-specific kernel config file as a starting point. Here, this – bcm2711_defconfig – is the correct kernel config file for the Broadcom SoC (System on Chip) on the Raspberry Pi 3, 3+, 4, 400, Zero 2 W, and Raspberry Pi compute modules 3, 3+, and 4, in order to generate the default 64-bit build configuration.
(Important: if you are building the kernel for another type of Raspberry Pi device, please see https://www.raspberrypi.org/documentation/linux/kernel/building.md.)
FYI, the kernel8 value is as such because the processor is ARMv8-based (64-bit).
The variety of SoCs, their packaging, and their resulting naming creates a good deal of confusion; this link might help: https://raspberrypi.stackexchange.com/questions/840/why-is-the-cpu-sometimes-referred-to-as-bcm2708-sometimes-bcm2835.
- If any further customization of the board’s kernel config is required, you could always do so with the following:
make ARCH=arm64 menuconfig
If not, just skip this step and proceed. Also, remember, if you want to fine-tune the kernel config, first generate it correctly via Step 1, and only then perform this step.
- Build (cross-compile) the kernel, the kernel modules, and the DTBs with the following:
make -j8 ARCH=arm64 CROSS_COMPILE=aarch64-linux-gnu- all
- Adjust the
-jnappropriately for your build host. What targets will thealltarget result in? The answer is that it’s all targets prefixed with the*symbol in the kernel ‘s top-level Makefile’shelptarget:$ make ARCH=arm64 help |grep "^\*"* vmlinux - Build the bare kernel* modules - Build all modules* dtbs - Build device tree blobs for enabled boards* Image.gz - Compressed kernel image (arch/arm64/boot/Image.gz)
Once the build is successfully completed, among the many files generated, we can see the following relevant ones:
$ ls -lh vmlinux System.map arch/arm64/boot/Image* arch/arm64/boot/dts/broadcom/bcm2711-rpi-4-b.dtb-rw-rw-r-- 1 c2kp c2kp 54K Jun 21 13:02 arch/arm64/boot/dts/broadcom/bcm2711-rpi-4-b.dtb-rw-rw-r-- 1 c2kp c2kp 22M Jun 21 13:24 arch/arm64/boot/Image-rw-rw-r-- 1 c2kp c2kp 7.9M Jun 21 13:24 arch/arm64/boot/Image.gz-rw-rw-r-- 1 c2kp c2kp 3.6M Jun 21 13:24 System.map-rwxrwxr-x 1 c2kp c2kp 237M Jun 21 13:24 vmlinux- Great! FYI, the file named
Imageis an uncompressed version ofImage.gz, the compressed kernel image, the latter being the one you can boot with. Thevmlinuxfile is the actual uncompressed kernel image; keep it around for kernel debugging! Also, thearch/arm64/boot/dts/broadcom/bcm2711-rpi-4-b.dtbfile is the DTB for this target platform. Thefilecommand further verifies thevmlinuximage:$ file ./vmlinux./vmlinux: ELF 64-bit LSB pie executable, ARM aarch64, version 1 (SYSV), statically linked, BuildID[sha1]=03b7<...>, with debug_info, not stripped
Here, our purpose has been to show how a Linux kernel can be configured and built for an architecture other than the host system it’s compiled upon, or, in other words, cross-compiled. The details of placing the kernel image, modules, and DTBs (including overlays) on the microSD card and so on aren’t delved into here. I refer you to the complete documentation for the Raspberry Pi kernel build, which can be found here: https://www.raspberrypi.com/documentation/computers/linux_kernel.html#cross-compiling-the-kernel.
This completes our coverage on experimenting with a kernel cross-compilation for the Raspberry Pi. We’ll end this chapter with a few miscellaneous but useful tips.
Miscellaneous tips on the kernel build
Section titled “Miscellaneous tips on the kernel build”We complete this chapter on building the Linux kernel from source with a few tips. The reason, of course, is that everything may not always go as smoothly as we’d wish it to. Each of the following subsections encapsulates a tip for you to take note of.
Often a point of confusion for folks new to this: once we configure, build, and boot from a new Linux kernel, we notice that the root filesystem and any other mounted filesystems remain identical to what was on the original (distro or custom) system. Only the kernel (and the initramfs image) has changed.
This is entirely intentional, due to the Unix paradigm of having loose coupling between the kernel and the (real) root filesystem. Since it’s the root filesystem that holds all the applications, system tools, and utilities, including libraries, in effect, we can have several kernels (to suit different product flavors, perhaps) for the same base system.
Minimum version requirements
Section titled “Minimum version requirements”To successfully build the kernel, you must ensure that your build system has the documented bare minimum versions of the various software pieces of the toolchain (and other miscellaneous tools and utilities). This information is clearly within the kernel documentation in the Minimal requirements to compile the kernel section, available at https://github.com/torvalds/linux/blob/master/Documentation/process/changes.rst#minimal-requirements-to-compile-the-kernel.
For example, as of the time of writing, the recommended minimum version of gcc is 5.1, Clang (an alternate and powerful compiler for Linux!) is 11.0.0, and that of make is 3.82 (there are many others specified, so take a look).
Building a kernel for another site
Section titled “Building a kernel for another site”In our kernel build walk-through in this book, we built a Linux kernel on a certain system (here, it was an x86_64 guest) and booted the newly built kernel off the very same system. What if this isn’t the case, as will often happen when you are building a kernel for another site or customer premises? While it’s always possible to manually put the pieces in place on the remote system, there’s a far easier and more correct way to do it – package the kernel and associated artifacts bundled along with it (the initrd image, the kernel modules collection, the kernel headers, and so on) into a well-known package format (Debian’s deb, Red Hat’s rpm, and so on)! A quick help command on the kernel’s top-level Makefile reveals these package targets (we only show the relevant ones below):
$ make ARCH=arm64 help [ ... ]Kernel packaging: rpm-pkg - Build both source and binary RPM kernel packages binrpm-pkg - Build only the binary kernel RPM package deb-pkg - Build both source and binary deb kernel packages bindeb-pkg - Build only the binary kernel deb package snap-pkg - Build only the binary kernel snap package (will connect to external hosts) dir-pkg - Build the kernel as a plain directory structure tar-pkg - Build the kernel as an uncompressed tarball targz-pkg - Build the kernel as a gzip compressed tarball[ ... ]So, for example, with the same setup just covered (building for the AArch64 Raspberry Pi 4 target), to build and package the kernel and its associated files as Debian packages, simply do the following:
$ make -j8 ARCH=arm64 CROSS_COMPILE=aarch64-linux-gnu- bindeb-pkgsh ./scripts/package/mkdebiandpkg-buildpackage -r"fakeroot -u" -a$(cat debian/arch) -b -nc -ucdpkg-buildpackage: info: source package linux-upstreamdpkg-buildpackage: info: source version 6.1.34-v8+-2dpkg-buildpackage: info: source distribution jammy[ … ]make KERNELRELEASE=6.1.34-v8+ ARCH=arm64 KBUILD_BUILD_VERSION=2 -f ./Makefile CALL scripts/checksyscalls.sh UPD init/utsversion-tmp.h CC init/version.o[ … ] GZIP arch/arm64/boot/Image.gzmake KERNELRELEASE=6.1.34-v8+ ARCH=arm64 KBUILD_BUILD_VERSION=2 -f ./Makefile intdeb-pkgsh ./scripts/package/builddeb INSTALL debian/linux-image/usr/lib/linux-image-6.1.34-v8+/broadcom/bcm2711-rpi-400.dtb INSTALL debian/linux-image/usr/lib/linux-image-6.1.34-v8+/broadcom/bcm2711-rpi-4-b.dtb[ … ] INSTALL debian/linux-image/usr/lib/linux-image-6.1.34-v8+/overlays/wm8960-soundcard.dtbo INSTALL debian/linux-image/lib/modules/6.1.34-v8+/kernel/arch/arm64/crypto/aes-arm64.ko INSTALL debian/linux-image/lib/modules/6.1.34-v8+/kernel/arch/arm64/crypto/aes-neon-blk.ko[ … ] XZ debian/linux-image/lib/modules/6.1.34-v8+/kernel/arch/arm64/crypto/aes-arm64.ko.xz XZ debian/linux-image/lib/modules/6.1.34-v8+/kernel/arch/arm64/crypto/aes-neon-bs.ko.xz[ … ] DEPMOD debian/linux-image/lib/modules/6.1.34-v8+dpkg-deb: building package 'linux-headers-6.1.34-v8+' in '../linux-headers-6.1.34-v8+_6.1.34-v8+-2_arm64.deb'. HOSTCC scripts/unifdef HDRINST usr/include/asm-generic/stat.h[ … ] INSTALL debian/linux-libc-dev/usr/includedpkg-deb: building package 'linux-libc-dev' in '../linux-libc-dev_6.1.34-v8+-2_arm64.deb'.dpkg-deb: building package 'linux-image-6.1.34-v8+' in '../linux-image-6.1.34-v8+_6.1.34-v8+-2_arm64.deb'.dpkg-deb: building package 'linux-image-6.1.34-v8+-dbg' in '../linux-image-6.1.34-v8+-dbg_6.1.34-v8+-2_arm64.deb'. dpkg-genbuildinfo --build=binary -O../linux-upstream_6.1.34-v8+-2_arm64.buildinfo dpkg-genchanges --build=binary -O../linux-upstream_6.1.34-v8+-2_arm64.changesdpkg-genchanges: info: binary-only upload (no source code included) dpkg-source --after-build .dpkg-buildpackage: info: binary-only upload (no source included)$A folder named debian is created and comprehensively populated within the kernel tree (use the tree command to see its content). The actual package files are written into the directory immediately above the kernel source directory. For example, from the command we just ran, here are the deb packages that were generated:

Figure 3.9: The Debian package files generated via our make … bindeb-pkg command
This is indeed very convenient! Now, you can install the packages – and thus the new kernel along with its headers and associated artifacts – on any other matching (in terms of CPU and Linux flavor) system with a simple sudo dpkg -i <package-name> command.
Watching the kernel build run
Section titled “Watching the kernel build run”To see details – the commands and scripts that execute, the detailed GCC compiler flags, and so on – while the kernel build runs, pass the V=1 verbose option switch to make. The following is a fragment of the output when building the Raspberry Pi 4 kernel with the verbose switch set to on (I’ve taken the liberty of adding newlines and continuation characters to make the output more readable):
$ make -j8 V=1 ARCH=arm64 CROSS_COMPILE=aarch64-linux-gnu- all[ … ]aarch64-linux-gnu-gcc -Wp,-MMD,drivers/net/ethernet/realtek/.r8169_main.o.d-nostdinc \-I./arch/arm64/include -I./arch/arm64/include/generated -I./include -I./arch/arm64/include/uapi -I./arch/arm64/include/generated/uapi -I./include/uapi-I./include/generated/uapi -include ./include/linux/compiler-version.h -include ./include/linux/kconfig.h -include ./include/linux/compiler_types.h \-D__KERNEL__ -mlittle-endian -DCC_USING_PATCHABLE_FUNCTION_ENTRY-DKASAN_SHADOW_SCALE_SHIFT= -fmacro-prefix-map=./= \-Wall -Wundef -Werror=strict-prototypes -Wno-trigraphs -fno-strict-aliasing-fno-common -fshort-wchar -fno-PIE -Werror=implicit-function-declaration-Werror=implicit-int -Werror=return-type -Wno-format-security \-std=gnu11 -mgeneral-regs-only -DCONFIG_CC_HAS_K_CONSTRAINT=1 -Wno-psabi-mabi=lp64 -fno-asynchronous-unwind-tables -fno-unwind-tables -mbranch-protection=pac-ret+leaf \-Wa,-march=armv8.5-a -DARM64_ASM_ARCH='"armv8.5-a"'-DKASAN_SHADOW_SCALE_SHIFT= -fno-delete-null-pointer-checks -Wno-frame-address -Wno-format-truncation -Wno-format-overflow -Wno-address-of-packed-member -O2-fno-allow-store-data-races -Wframe-larger-than=2048 -fstack-protector-strong-Wno-main -Wno-unused-but-set-variable -Wno-unused-const-variable-fno-omit-frame-pointer -fno-optimize-sibling-calls -fno-stack-clash-protection-fpatchable-function-entry=2 \-Wdeclaration-after-statement -Wvla -Wno-pointer-sign-Wcast-function-type -Wno-stringop-truncation -Wno-stringop-overflow -Wno-restrict-Wno-maybe-uninitialized -Wno-array-bounds -Wno-alloc-size-larger-than-Wimplicit-fallthrough=5 -fno-strict-overflow -fno-stack-check -fconserve-stack-Werror=date-time -Werror=incompatible-pointer-types -Werror=designated-init-Wno-packed-not-aligned \-g -mstack-protector-guard=sysreg -mstack-protector-guard-reg=sp_el0-mstack-protector-guard-offset=1432 -DMODULE-DKBUILD_BASENAME='"r8169_main"' -DKBUILD_MODNAME='"r8169"'-D__KBUILD_MODNAME=kmod_r8169 \-c -o drivers/net/ethernet/realtek/r8169_main.o drivers/net/ethernet/realtek/r8169_main.c[ … ]This level of detail can help debug situations where the build fails, or to learn what compiler options are being leveraged! (The GCC man page comes in use now!)
Also, of course, the output can be simultaneously seen on the terminal window and redirected to a file by leveraging the shell and tee; for example, you can do this to save it into a file named out.txt while seeing the output as well:
make -j8 V=1 ARCH=arm64 CROSS_COMPILE=aarch64-linux-gnu- all 2>&1 | tee out.txtFurthermore, and FYI, using tee -a <filename> ensures the output is appended to the file specified and doesn’t overwrite it.
A shortcut shell syntax to the build procedure
Section titled “A shortcut shell syntax to the build procedure”A shortcut shell (Bash, typically) syntax to the build procedure – assuming the required packages are installed and the kernel configuration step is done (and assuming we’re on the x86) – could be something like the following example, to be used in non-interactive build scripts, perhaps:
time make -j8 [ARCH=<...> CROSS_COMPILE=<...>] all && \ sudo make modules_install && \ sudo make installIn the preceding code, the && and || elements are the shell’s (Bash’s) convenience conditional list syntax:
cmd1 && cmd2implies: runcmd2only ifcmd1succeeds.cmd1 || cmd2implies: runcmd2only ifcmd1fails.
In any case, a simple minimally-tested Bash script to perform the x86_64 kernel build is provided in the book repo here: https://github.com/PacktPublishing/Linux-Kernel-Programming_2E/blob/main/ch3/kbuild.sh. Check it out.
Dealing with missing OpenSSL development headers
Section titled “Dealing with missing OpenSSL development headers”In one instance, the kernel build on x86_64 on an Ubuntu box failed with the following error:
[...] fatal error: openssl/opensslv.h: No such file or directoryThis is simply a case of missing OpenSSL development headers; this is mentioned in the Minimal requirements to compile the kernel document here: https://github.com/torvalds/linux/blob/master/Documentation/process/changes.rst#openssl. Specifically, it mentions that from v4.3 (and 3.7 if module signing is enabled) and higher, the openssl development packages are required. Thus, our ch1/pkg_install4ubuntu_lkp.sh installs the libssl-dev package; FYI, the equivalent package for the Fedora-type distros is openssl-devel.
FYI, this Q&A also shows how the installation of the libssl-dev package (or equivalent package that needs to be installed) solves the issue: OpenSSL missing during./configure. How to fix, available at https://superuser.com/questions/371901/openssl-missing-during-configure-how-to-fix.
How can I check which distro kernels are installed?
Section titled “How can I check which distro kernels are installed?”Sometimes it’s important to know which kernel packages (typically installed by the distro being used) are installed. This could be because, sometimes, you want to uninstall older kernels to recover disk space, in the /boot partition perhaps, as it’s running short (as often happens on my OSBoxes install!). On Debian/Ubuntu, this is one way to look them up:
dpkg --list | grep linux-imageOn Red Hat/Fedora/CentOS, you could use:
dnf list installed kernelThese are package-based kernels; they won’t include manually built ones of course!
Several Linux “builder” projects exist, which are elaborate frameworks for building a Linux system or distribution in its entirety (typically used for embedded Linux projects). As of the time of writing, Yocto (https://www.yoctoproject.org/) is considered the industry standard Linux-builder project, with Buildroot (https://buildroot.org/) being an older but very much supported one; they are indeed well worth checking out.
Next, what if the kernel build, initramfs generation, and everything else goes well but the kernel fails to complete booting, ending with kernel panic and a (well-known to the initiated!) message like [ end Kernel panic - not syncing: Attempted to kill init! …] or [Kernel panic - not syncing: No working init found. …]. The root cause of such mishaps is often a misconfiguration of the kernel config, the kernel command-line parameters (especially that of the root device), or an inability (for whatever reason) to mount the actual root filesystem. The official kernel documentation does have some tips here: https://www.kernel.org/doc/Documentation/admin-guide/init.rst.
Finally, remember an almost guaranteed way to succeed: when you get those build and/or boot errors that you just cannot fix, copy the exact error message into the clipboard, go to Google (or another search engine), and type something akin to linux kernel build <ver ...> fails with <paste-your-error-message-here>. You might be surprised at how often this helps. If not, diligently do your research, and if you really cannot find any relevant/correct answers, post your well-thought-out-with-all-relevant-details question on an appropriate forum.
Well, with this, we conclude our kernel build chapters!
Summary
Section titled “Summary”This chapter, along with the previous one, covered in a lot of detail the necessary preliminaries and how exactly to configure and build the Linux kernel from source.
In this chapter, we began with the actual kernel (and kernel modules’) build process. Once built, we showed how the kernel modules are to be installed onto the system. We then moved on to the practicalities of generating the initramfs (or initrd) image and went on to explain the motivation behind it.
The final step in the kernel build was the (simple) customization of the bootloader (here, we focused only on x86 GRUB). We then showed how to boot the system via the newly baked kernel and verify that its configuration is as we expected. As a useful add-on, we then showed how we can even cross-compile the Linux kernel for another processor (AArch64, in this instance). Finally, we shared some additional tips to help you with the kernel build.
Again, if you haven’t done so already, we urge you to carefully review and try out the procedures mentioned here and build your own custom Linux kernel.
So, congratulations on completing a Linux kernel build from scratch! You might well find that for an actual project (or product), you may not have to carry out each and every step of the kernel build procedure as we have tried hard to carefully show. Why? Well, one reason is that there might be a separate platform/BSP team that works on this aspect; another reason – increasingly likely, especially on embedded Linux projects – is that a Linux-builder framework such as Yocto (or Buildroot) is being used (or SoC vendor-supplied custom kernels are what you use). Yocto will typically take care of the mechanical aspects of the build (Yocto doesn’t exactly have the gentlest learning curve, though). However, you need to be able to configure the kernel as required by the project; that still requires the knowledge and understanding gained here.
The next two chapters will take you squarely into the world of Linux kernel development, showing you how to write your first kernel module.
Questions
Section titled “Questions”As we conclude, here is a list of questions for you to test your knowledge regarding this chapter’s material: https://github.com/PacktPublishing/Linux-Kernel-Programming_2E/blob/main/questions/ch3_qs_assignments.txt. You will find some of the questions answered in the book’s GitHub repo: https://github.com/PacktPublishing/Linux-Kernel-Programming/tree/master/solutions_to_assgn.
Further reading
Section titled “Further reading”To help you delve deeper into the subject with useful materials, we provide a rather detailed list of online references and links (and at times, even books) in a Further reading document in this book’s GitHub repository. The Further reading document is available here: https://github.com/PacktPublishing/Linux-Kernel-Programming/blob/master/Further_Reading.md.
Get This Book’s PDF Version and Exclusive Extras
|