How to build a Linux kernel

This article shows you how to build a Linux kernel, which is useful for using features supported only in the latest kernels from the Linux community or for creating your own Linux OS. The commands listed here have been verified to run on Debian 11, but are basically the same for other Linux operating systems (except for how to install packages).

Preparation to build

Install the following packages.
sudo apt install gcc make flex bison bc libncurses-dev libelf-dev libssl-dev

Get a kernel source code

Linux kernel source code can be downloaded from the following site.

The latest stable version on the day this post was written was6.2.7. The following shows an example of downloading it to a working directory on a build machine.
wget https://cdn.kernel.org/pub/linux/kernel/v6.x/linux-6.2.7.tar.xz

Build

Extract the source code

tar xf linux-6.2.7.tar.xz

Configuration

ここではデフォルト設定を行います。
cd linux-6.2.7
make defconfig

When more configuration is required

make menuconfig
After entering the above, the following TUI-based configuration screen will appear. This can be used to add/remove the required CONFIGs.

Compile

make -j32

The above -j32 is an option to compile in 32 parallel. It should be changed accordingly to the actual number of CPUs.

If the following message appears, the build was successful. The following bzImage is the same as the named like vmlinuz-6.1.0-5-amd64 in many Linux OS.

Kernel: arch/x86/boot/bzImage is ready  (#1)

Launch test

Here we will use a Debian 11 drive image as a rootfs and boot with QEMU.

Download of a rootfs drive image

Download the rootfs image as follows.
wget https://cloud.debian.org/images/cloud/bullseye/20230124-1270/debian-11-nocloud-amd64-20230124-1270.qcow2

Launch

Run QEMU as follows. --nographic option is given so that a serial device is created in the virtual machine. The kernel option console=ttyS0 makes the serial device become a console. These make the terminal running QEMU the input/output terminal to the serial device as it is.

Note that when configured with defconfig, the virtio storage functionality is built into the kernel. The kernel can mount rootfs directly without initrd.

sudo qemu-system-x86_64 \
-cpu host \
--enable-kvm \
-m 1024 \
-nographic \
-drive id=drive0,format=qcow2,file=debian-11-nocloud-amd64-20230124-1270.qcow2,if=virtio \
-kernel arch/x86_64/boot/bzImage \
-append "root=/dev/vda1 console=ttyS0"
If the following login prompt appears, you have succeeded.
(abbr.)
Debian GNU/Linux 11 debian ttyS0

debian login:
This image allows to log in without password by use root as a user name.
Linux debian 6.2.7 #1 SMP PREEMPT_DYNAMIC Sun Mar 19 02:39:21 UTC 2023 x86_64
(abbr.)
root@debian:~#

How to force terminate QEMU when a launch fails

While QEMU is running, enter Ctrl-a followed by c to go to the QEMU monitor screen. Enter q here.
(Enter Ctrl-a, c)
QEMU 7.2.0 monitor - type 'help' for more information
(qemu) q

No comments:

Post a Comment