How to compile linux kernel from source

How To Compile Linux Kernel From Source Code?

Hi, today we are going to compile Linux kernel. you can think that compiling kernel is very complicated and hard for you. But it is not. It is more easy to compile than a lot of other projects. Because Linux kernel has no dependency to a library or other tools. It needs just ncurses development library which is used for module configuration.

Download Linux Kernel Source Code

Linux Kernel is an open-source project which is can be used anyone without any fee and freely. Linux Kernel source code is provided by http://www.kernel.org . First we will download the latest mainline kernel source code.

Download Linux Kernel Source Code

Extract Linux Kernel

Then decompress it. The postfix of file like xz, gz is not important they are just different compression algorithms all ingredients are the same

Enter the decompress directory

Install Dependencies

Run module configuration menu for the kernel. Here you need ncurses devel library for C programming language.

Ubuntu, Debian, Mint, Kali

Fedora, CentOS, RedHat

Kernel Build Configuration

We will run the kernel configuration tool with the following command.

You can configure the file system module from here. If you have space constraint you can remove unneeded file system modules or add required file system modules

Kernel Build Configuration

Here are driver modules. As I said above you can remove unneeded modules or add drivers you need.

Virtualization modules can be configured with this menu. Say you have AMD CPU you do not have to compile Intel drivers.

After applying all settings you can save them and exit

Save Kernel Compile Configuration Kernel Config

Make Help

Now we are ready to compile process. There is a lot of compile options but I am gonna show you some of them. If you want to see all off them run make help

Make Help

Compiling Linux Kernel As ISO Image

We can compile the Linux Kernel with the isoimage option which will make ISO files to boot the kernel. This ISO can be burned into a CD too.

After compilation, you can find your image in arch/x86/boot/image.iso

Compile Linux As Binary

Linux kernel can be compiled with the make command. By providing the -j8 compilation will be done in a multi-threat way.

Compile Linux As Binary

Install Linux Kernel

We can install compiled Linux kernel like below. This will change the current kernel of the Linux distribution and boot next time with this kernel.

Источник

Kernel/Traditional compilation

This article is an introduction to building custom kernels from kernel.org sources. This method of compiling kernels is the traditional method common to all distributions. It can be, depending on your background, more complicated than using the Kernels/Arch Build System. Consider the Arch Build System tools are developed and maintained to make repeatable compilation tasks efficient and safe.

Contents

Preparation

It is not necessary (or recommended) to use the root account or root privileges (i.e. via Sudo) for kernel preparation.

Install the core packages

Install the base-devel package group, which contains necessary packages such as make and gcc . It is also recommended to install the following packages, as listed in the default Arch kernel PKGBUILD: xmlto , kmod , inetutils , bc , libelf , git , cpio , perl , tar , xz .

Create a kernel compilation directory

It is recommended to create a separate build directory for your kernel(s). In this example, the directory kernelbuild will be created in the home directory:

Download the kernel source

Download the kernel source from https://www.kernel.org. This should be the tarball ( tar.xz ) file for your chosen kernel.

It can be downloaded by simply right-clicking the tar.xz link in your browser and selecting Save Link As. , or any other number of ways via alternative graphical or command-line tools that utilise HTTP, TFTP, Rsync, or Git.

In the following command-line example, wget has been installed and is used inside the

/kernelbuild directory to obtain kernel 4.8.6:

You should also verify the correctness of the download before trusting it. First grab the signature, then use that to grab the fingerprint of the signing key, then use the fingerprint to obtain the actual signing key:

Note the signature was generated for the tar archive (i.e. extension .tar ), not the compressed .tar.xz file that you have downloaded. You need to decompress the latter without untarring it. Verify that you have xz installed, then you can proceed like so:

Do not proceed if this does not result in output that includes the string «Good signature».

If wget was not used inside the build directory, it will be necessary to move the tarball into it, e.g.

Unpack the kernel source

Within the build directory, unpack the kernel tarball:

To finalise the preparation, ensure that the kernel tree is absolutely clean; do not rely on the source tree being clean after unpacking. To do so, first change into the new kernel source directory created, and then run the make mrproper command:

Kernel configuration

This is the most crucial step in customizing the default kernel to reflect your computer’s precise specifications. Kernel configuration is set in its .config file, which includes the use of Kernel modules. By setting the options in .config properly, your kernel and computer will function most efficiently.

You can do a mixture of two things:

  • Use the default Arch settings from an official kernel (recommended)
  • Manually configure the kernel options (optional, advanced and not recommended)
Читайте также:  Не видится диск при установке windows

Default Arch configuration

This method will create a .config file for the custom kernel using the default Arch kernel settings. If a stock Arch kernel is running, you can use the following command inside the custom kernel source directory:

Otherwise, the default configuration can be found online in the official Arch Linux kernel package.

Advanced configuration

There are several tools available to fine-tune the kernel configuration, which provide an alternative to otherwise spending hours manually configuring each and every one of the options available during compilation.

Those tools are:

  • make menuconfig : Command-line ncurses interface superseded by nconfig
  • make nconfig : Newer ncurses interface for the command-line
  • make xconfig : User-friendly graphical interface that requires packagekit-qt5 to be installed as a dependency. This is the recommended method — especially for less experienced users — as it is easier to navigate, and information about each option is also displayed.
  • make gconfig : Graphical configuration similar to xconfig but using gtk. This requires gtk2 , glib2 and libgladeAUR .

The chosen method should be run inside the kernel source directory, and all will either create a new .config file, or overwrite an existing one where present. All optional configurations will be automatically enabled, although any newer configuration options (i.e. with an older kernel .config ) may not be automatically selected.

Once the changes have been made save the .config file. It is a good idea to make a backup copy outside the source directory. You may need to do this multiple times before you get all the options right.

If unsure, only change a few options between compilations. If you cannot boot your newly built kernel, see the list of necessary config items here.

Running lspci -k # from liveCD lists names of kernel modules in use. Most importantly, you must maintain cgroups support. This is necessary for systemd. For more detailed information, see Gentoo:Kernel/Gentoo Kernel Configuration Guide and Gentoo:Intel#Kernel or Gentoo:Ryzen#Kernel for Intel or AMD Ryzen processors.

Compilation

Compilation time will vary from as little as fifteen minutes to over an hour, depending on your kernel configuration and processor capability. Once the .config file has been set for the custom kernel, within the source directory run the following command to compile:

Installation

Install the modules

Once the kernel has been compiled, the modules for it must follow. First build the modules:

Then install the modules. As root or with root privileges, run the following command to do so:

This will copy the compiled modules into /lib/modules/ — . For example, for kernel version 4.8 installed above, they would be copied to /lib/modules/4.8.6-ARCH . This keeps the modules for individual kernels used separated.

Copy the kernel to /boot directory

The kernel compilation process will generate a compressed bzImage (big zImage) of that kernel, which must be copied to the /boot directory and renamed in the process. Provided the name is prefixed with vmlinuz- , you may name the kernel as you wish. In the examples below, the installed and compiled 4.8 kernel has been copied over and renamed to vmlinuz-linux48 :

Make initial RAM disk

If you do not know what making an initial RAM disk is, see Initramfs on Wikipedia and mkinitcpio.

Automated preset method

An existing mkinitcpio preset can be copied and modified so that the custom kernel initramfs images can be generated in the same way as for an official kernel. This is useful where intending to recompile the kernel (e.g. where updated). In the example below, the preset file for the stock Arch kernel will be copied and modified for kernel 4.8, installed above.

First, copy the existing preset file, renaming it to match the name of the custom kernel specified as a suffix to /boot/vmlinuz- when copying the bzImage (in this case, linux48 ):

Second, edit the file and amend for the custom kernel. Note (again) that the ALL_kver= parameter also matches the name of the custom kernel specified when copying the bzImage :

Finally, generate the initramfs images for the custom kernel in the same way as for an official kernel:

Manual method

Rather than use a preset file, mkinitcpio can also be used to generate an initramfs file manually. The syntax of the command is:

  • -k ( —kernel ): Specifies the modules to use when generating the initramfs image. The name will be the same as the name of the custom kernel source directory (and the modules directory for it, located in /usr/lib/modules/ ).
  • -g ( —generate ): Specifies the name of the initramfs file to generate in the /boot directory. Again, using the naming convention mentioned above is recommended.

For example, the command for the 4.8 custom kernel installed above would be:

Copy System.map

The System.map file is not required for booting Linux. It is a type of «phone directory» list of functions in a particular build of a kernel. The System.map contains a list of kernel symbols (i.e function names, variable names etc) and their corresponding addresses. This «symbol-name to address mapping» is used by:

  • Some processes like klogd, ksymoops, etc.
  • By OOPS handler when information has to be dumped to the screen during a kernel crash (i.e info like in which function it has crashed).

If your /boot is on a filesystem which supports symlinks (i.e., not FAT32), copy System.map to /boot , appending your kernel’s name to the destination file. Then create a symlink from /boot/System.map to point to /boot/System.map- :

After completing all steps above, you should have the following 3 files and 1 soft symlink in your /boot directory along with any other previously existing files:

  • Kernel: vmlinuz-
  • Initramfs: Initramfs- .img
  • System Map: System.map-
  • System Map kernel symlink

Bootloader configuration

Add an entry for your new kernel in your bootloader’s configuration file. See Arch boot process#Feature comparison for possible boot loaders, their wiki articles and other information.

Источник

How to Compile and Install Linux Kernel v4.9.11 Source On a Debian / Ubuntu Linux

Why build a custom kernel?

Compiling a custom Linux kernel has its advantages and disadvantages. To change the kernel’s behavior, one had to compile and then reboot into a new Linux. Most of the functionality in the Linux kernel contained in modules that can be dynamically loaded and unloaded from the kernel as necessary. Some benefits of a custom Linux kernel:

  1. Support a wide range of hardware including the latest hardware.
  2. Remove unwanted drivers from the kernel.
  3. Faster boot time due to small kernel size.
  4. Increased security due to additional or removed modules/drivers/features.
  5. You will learn about the kernel and advanced usage.
  6. Always run the cutting edge latest kernel.
  7. Lower memory usage.
Читайте также:  Download windows update utility

Note: The following instructions were tested on both Debian Linux v8.x and Ubuntu Linux v14.04.4/16.04.2 LTS.

Prerequisites

You need to install the following packages on a Debian or Ubuntu Linux to compiler the Linux kernel:

  • git : Fast, scalable, distributed revision control system. You can grab the latest source code using the git command.
  • fakeroot : Tool for simulating superuser privileges. Useful to build .deb files.
  • build-essential : Tools for building the Linux kernel such as GCC compiler and related tools on a Debian or Ubuntu Linux based system.
  • ncurses-dev : Developer’s libraries for ncurses. This is used by menuconfig while configuring the kernel options.
  • kernel-package : Utility for building Linux kernel related Debian packages.
  • xz-utils : XZ-format compression utilities to decompress the Linux kernel tar ball.
  • Disk space : 10 GB or more free disk space.
  • Time : Kernel compilation may take quite a while, depending on the power of your machine.

Install required packages

Open the terminal application. Type the following apt-get command to install the required packages for building the Linux kernel:
$ sudo apt-get install git fakeroot build-essential ncurses-dev xz-utils libssl-dev bc
Sample outputs:

Fig.01: Install gcc and friends

Fig.02: Install utility for building Linux kernel

Download the Linux kernel source code

Type the following wget command to grab both source code and pgp keys:
$ wget https://cdn.kernel.org/pub/linux/kernel/v4.x/linux-4.9.11.tar.sign
$ wget wget https://cdn.kernel.org/pub/linux/kernel/v4.x/linux-4.9.11.tar.xz
Sample outputs:

Fig.03: Use the wget to grab the latest source code from kernel.org

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Get the public key from the PGP keyserver in order to verify the signature i.e. RSA key ID 00411886 (from the above outputs):
$ gpg —keyserver hkp://keys.gnupg.net —recv-keys 00411886
Sample outputs:

Now verify again:
$ gpg —verify linux-4.9.11.tar.sign
Sample outputs:

If you do not “ BAD signature ” output from “ gpg —verify ” command, untar the Linux kernel tar ball using the tar command enter:
$ tar xvf linux-4.9.11.tar
$ ls
$ cd linux-4.9.11/
$ ls
Sample outputs

Configure the Linux kernel

First, copy your existing Linux kernel config file
$ cd linux-4.9.11
$ cp -v /boot/config-$(uname -r) .config
Sample outputs:

To configure the kernel, run:
$ make menuconfig
Sample outputs:

WARNING : It is easy to remove support for a device driver or option and end up with a broken kernel. For example, if the ext4 driver is removed from the kernel configuration file, a system may not boot. When in doubt, just leave support in the kernel.

Make sure you save the changes before exit from menuconfig.

Compile the Linux kernel

You need to clean the source tree and reset the kernel-package parameters, type:
$ make-kpkg clean
Sample outputs:

Fig.06: Run make-kpkg command

Fig.07: Start compiling the kernel

Please note that kernel compilation may take quite a while, depending on the power of your machine. On my shared 4 CORE CPU and 4GB ram it took 60 mins to build the Linux kernel. In the end you should see something as follows on screen:

Verify kernel deb files:

Installing a custom kernel

Type the following dpkg command to install a custom kernel on your system:
$ cd ..
$ sudo dpkg -i linux-headers-4.9.11_1.0.NAS_amd64.deb
$ sudo dpkg -i linux-image-4.9.11_1.0.NAS_amd64.deb
Sample outputs:

Reboot the box/server/laptop

Type the following command:
$ sudo reboot
OR
$ sudo shutdown -r now

Verify that everything is working

Type the following command to verify your new kernel and everything is working fine:
$ uname -a
$ uname -r
$ uname -mrs
$ dmesg | more
$ dmesg | egrep -i —color ‘error|critical|failed’
Sample outputs:

And, there you have it, the Linux kernel version 4.9.11 installed and working correctly.

See also
  • The Linux kernel project site.
  • Man pages – fakeroot(1)

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

New kernels will automatically come with newer updates/distro, but the learning experience of compiling kernel is priceless.

Thanks for the tutorial… Took a couple of hours to build on my machine. But it worked. Well sort of. I get missing or strange characters in text. Doesn’t matter if an icon label, in a terminal, LibreOffice, Firefox, etc. I went back to original kernel and all is well again. Using LUbuntu 3.19 kernel 64 bit.

Is there any difference between “raw” kernel and “ubuntu” kernel? Ubuntu compilated kernel 4.2 is marked like unstable, but kernel.org says 4.2 is stable. What does it mean?

4.2 is stable. Ubuntu built packages are behind the schedule and most likely built when 4.2 was in beta. Also, some propitiatory NVIDIA/ATI & others driver may not work on the latest version 4.2. YMMV.

Thanks for the tutorial. I followed the same steps you mentioned but I found one file ( abi ) is missing on my macbook (parallels + ubuntu 14.04) , here is /boot folder. Do you know which step is wrong ?

If you want to only compile the loaded modules with the current kernel use ‘make localmodconfig’. This will make the compile time shorter and include all of the currently loaded modules of you current kernel.

What does this——> ubuntu@mate:

$ dmesg | egrep -i –color ‘error|critical|failed’
[ 4.718735] systemd[1]: Failed to insert module ‘kdbus’: Function not implemented
[ 9.308305] EXT4-fs (sdc1): re-mounted. Opts: errors=remount-ro
[ 22.411061] vboxdrv: module verification failed: signature and/or required key missing – tainting kernel Andy Dec 31, 2015 @ 16:00

Try adding -j for a significant speed increase:
i.e.
fakeroot make-kpkg —initrd —revision=1.0.NAS -j 16

This sped up the process to about 10 minutes on my 8 core system. By default only a single core is used.

newer kernels directly support “make deb-pkg” instead of using”make-kpkg”

great tute, though with the unpacking “Installing custom kernel” .deb part, had to do image first then headers.. naturally.. thanx…

I have problem after :
“fakeroot make-kpkg –initrd –revision=1.0.NAS kernel_image kernel_headers”

it’s showing:
“scripts/sign-file.c:23:30: fatal error: openssl/opensslv.h: No such file or directory
compilation terminated.
scripts/Makefile.host:91: recipe for target ‘scripts/sign-file’ failed
make[2]: *** [scripts/sign-file] Error 1
Makefile:545: recipe for target ‘scripts’ failed
make[1]: *** [scripts] Error 2
make[1]: Leaving directory ‘/home/x/linux-4.4’
debian/ruleset/targets/common.mk:295: recipe for target ‘debian/stamp/build/kernel’ failed
make: *** [debian/stamp/build/kernel] Error 2”

What I’m doing wrong?

Thanks for help

Did you installed build-essential package? openssl.h means you need to install libssl-dev? Try

sudo apt-get install libssl-dev build-essential ncurses-dev xz-utils kernel-package

Edited by Vivek Gite. Reason: typo.

Reading package lists… Done
Building dependency tree
Reading state information… Done
E: Unable to locate package curses-dev

My bad. It should be ncurses-dev .

Thanks for help

After I type :
ls ../*.deb

it’ showing on red :
../linux-headers-4.4.0_1.0.NAS_amd64.deb
../linux-image-4.4.0_1.0.NAS_amd64.deb

sudo dpkg -i linux-headers-4.4.0_1.0.NAS_amd64.deb:
dpkg: error processing archive linux-headers-4.4.0_1.0.NAS_amd64.deb (–install):
cannot access archive: No such file or directory
Errors were encountered while processing:
linux-headers-4.4.0_1.0.NAS_amd64.deb

cd to .. and try:
sudo dpkg -i linux-headers-4.4.0_1.0.NAS_amd64.deb
sudo dpkg -i linux-image-4.4.0_1.0.NAS_amd64.deb
OR
sudo dpkg -i ../linux-headers-4.4.0_1.0.NAS_amd64.deb
sudo dpkg -i ../linux-image-4.4.0_1.0.NAS_amd64.deb

I have enough 🙂 I tried to run ubuntu on Yoga 900 – Wifi / touchscreen and track-pad doesn’t work.
I manage to run Wifi but with rest I have huge problem (nothing works).

Anyway BIG BIG thanks for help and all replies.

you need to compile the linux-image, and after the linux-header

I got the same error with kernel 4.10.1 , is there any way to fix that
/boot”
run-parts: executing /etc/kernel/postinst.d/apt-auto-removal 4.10.1 /home/bassem/linux-4.10.1/debian/linux-image-4.10.1//boot/vmlinuz-4.10.1
/etc/kernel/postinst.d/apt-auto-removal: 84: /etc/kernel/postinst.d/apt-auto-removal: cannot create /etc/apt/apt.conf.d//01autoremove-kernels.dpkg-new: Permission denied
run-parts: /etc/kernel/postinst.d/apt-auto-removal exited with return code 2
make[3]: *** [install] Error 1
make[2]: *** [install] Error 2
make[2]: Leaving directory `/home/bassem/linux-4.10.1′
make[1]: *** [debian/stamp/install/linux-image-4.10.1] Error 2
make[1]: Leaving directory `/home/bassem/linux-4.10.1′
make: *** [kernel_image] Error 2

Thaks so much Vivek Gite, worked for me!

Your article needs updating. All of the required packages do not exist in the cache. If someone comes to this site hoping for a guide to properly compiling and installing a new Linux kernel – not having the packages prior to coming here – they will spend quite some time trying to track down a fistful of packages that no longer exist, have been updated and/or replaced.

Please fix this ASAP. Thanks. 🙂

Can you provide your Linux distro name and other info like what packages are missing? I tested this on Debian 8 and Ubuntu Linux 14.04.3 LTS only. Everything worked perfectly.

Checked /etc/apt/sources.list all required sources are in place. Searching apt-cache returns no entries for any of the listed packages.

$ dmesg | egrep -i —color ‘error|critical|failed’
[ 7.474368] systemd[1]: Cannot add dependency job for unit display-manager.service, ignoring: Unit display-manager.service failed to load: No such file or directory.
[ 7.474377] systemd[1]: Cannot add dependency job for unit display-manager.service, ignoring: Unit display-manager.service failed to load: No such file or directory.
[ 10.513727] EXT4-fs (sda7): re-mounted. Opts: errors=remount-ro
user@PLUS:

Much easier way to compile your kernel:

Thanks for the thought but your install script causes dkms errors due to elaborate versioning. I get some extremely long build and version numbers which makes it useless. You need to allow for the user to enter EXPLICIT kernel versions and not do some crazy automate based on date/time etc……

I would suggest a prompt that shows the user WHAT you will be calling the kernel version and deb files, and allow the user to modify it at this point.

tnx a lot:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

After I select Linux kernel config options and drivers to build and I click on save and then exit, it says to “make” in the terminal but your tutorial says that I should “make-kpkg clean” so which one should I do first after I save and exit the menuconfig?

End of the configuration.
*** Execute ‘make’ to start the build or try ‘make help’. is what it says so what should I do next?

this is my output anyone can help me?

root@debian:/home/habernir/linux-4.1.18# dpkg -i linux-headers-4.1.18_1.0.NAS_amd64.deb
(Reading database … 214910 files and directories currently installed.)
Preparing to unpack linux-headers-4.1.18_1.0.NAS_amd64.deb …
Unpacking linux-headers-4.1.18 (1.0.NAS) over (1.0.NAS) …
Setting up linux-headers-4.1.18 (1.0.NAS) …
Examining /etc/kernel/header_postinst.d.
run-parts: executing /etc/kernel/header_postinst.d/dkms 4.1.18 /boot/vmlinuz-4.1.18
Error! Your kernel headers for kernel 4.1.18 cannot be found.
Please install the linux-headers-4.1.18 package,
or use the –kernelsourcedir option to tell DKMS where it’s located
root@debian:/home/habernir/linux-4.1.18#

amd debian 8.3 was installed in uefi

Hi I am trying to build linux-socfpga-3.10-ltsi kernel from rocketboards and facing the following error. Please help:
make[4]: *** No rule to make target `drivers/acpi/acpica/uteval.o’, needed by `drivers/acpi/acpica/acpi.o’. Stop.
make[3]: *** [drivers/acpi/acpica] Error 2
make[2]: *** [drivers/acpi] Error 2
make[1]: *** [drivers] Error 2
make[1]: Leaving directory `/home/mohanubuntu/Mohan/linux-socfpga-socfpga-3.10-ltsi’
make: *** [debian/stamp/build/kernel] Error 2

I ran into error when executing the following command:
$ fakeroot make-kpkg –initrd –revision=1.0.NAS kernel_image kernel_headers -j 4

Can anyone help me? The last lines of the following are the error information.

Источник

Читайте также:  Драйвер для canon lbp6020b для linux
Оцените статью