前言

由于我需要使用bcache,但是我们安装的centos系统的内核比较老默认不包含bcache, Bcache内核模块仅在Linux 3.10及以上版本支持

我就想自己编译一个稍微版本高点的Linux内核替换下现在的内核,也顺便学习一下内核编译,当然这篇文章是比较简单的记录

不涉及编译内核参数的解释

环境

系统: CentOS7.6

内核:4.19.307

安装编译依赖软件包

1
yum install -y gcc make git ctags ncurses-devel openssl-develyum install -y bison flex elfutils-libelf-devel bc

创建内核编译目录

使用 home 下的 kernelbuild 目录

1
mkdir ~/kernelbuild

获取内核源码

[清华大学镜像])站:Index of /kernel/v4.x/ | 清华大学开源软件镜像站 | Tsinghua Open Source Mirror

  • linux-4.xx.xx.tar.xz
  • linux-4.xx.xx.tar.gz

这两个格式都可以的,tar.xz压缩率更高,文件更小。

1
wget https://mirror.tuna.tsinghua.edu.cn/kernel/v4.x/linux-4.17.11.tar.xz

解压内核代码

将其解压后进入源码目录:

1
tar -xvJf linux-4.17.11.tar.xz

为确保内核树绝对干净,进入内核目录并执行 make mrproper 命令:

1
cd linux-4.17.11make clean && make mrproper

内核配置

复制当前的内核配置文件

config-3.10.0-862.el7.x86_64是我当前环境的内核配置文件,根据实际情况修改

1
cp /boot/config-3.10.0-862.el7.x86_64 .config
高级配置

y 是启用, n 是禁用, m 是需要时启用.
make menuconfig: 老的 ncurses 界面,被 nconfig 取代
make nconfig: 新的命令行 ncurses 界面

添加bcache

选择Device Drivers,回车

选择Multiple devices driver support(RAID and LVM),回车

用空格将方框中的全部选中

编译和安装

编译内核
1
make -j x

如果你是四核的机器,x可以是8

你也可以自动获取 $(nproc)

1
make -j $(nproc)

如何执行的时候出现警告

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
[root@master linux-4.19.307]# make -j 15
Makefile:613: include/config/auto.conf: No such file or directory
Makefile:644: include/config/auto.conf.cmd: No such file or directory
scripts/kconfig/conf --syncconfig Kconfig
.config:698:warning: symbol value 'm' invalid for CPU_FREQ_STAT
.config:970:warning: symbol value 'm' invalid for NF_NAT_REDIRECT
.config:973:warning: symbol value 'm' invalid for NF_TABLES_INET
.config:1140:warning: symbol value 'm' invalid for NF_TABLES_IPV4
.config:1144:warning: symbol value 'm' invalid for NF_TABLES_ARP
.config:1150:warning: symbol value 'm' invalid for NF_NAT_MASQUERADE_IPV4
.config:1185:warning: symbol value 'm' invalid for NF_TABLES_IPV6
.config:1194:warning: symbol value 'm' invalid for NF_NAT_MASQUERADE_IPV6
.config:1217:warning: symbol value 'm' invalid for NF_TABLES_BRIDGE
.config:3665:warning: symbol value 'm' invalid for LIRC
*
* Restart config...
*
*
* General setup
*
Compile also drivers which will not load (COMPILE_TEST) [N/y/?] (NEW)

 是由于内核配置文件中的一些选项的值无效导致的

解决方法

  1. 进入内核源码目录,执行以下命令清除之前的配置和编译文件:

    1
    make distclean
  2. 然后执行以下命令重新配置内核:

    1
    make menuconfig
安装内核

Warning: 从这里开始,需要 root 权限执行命令,否则会失败.

编译完内核后安装:

1
make modules_install install

设置启动

1
2
3
4
5
6
7
8
9
10
11
12
# 查看启动顺序
[root@master kernel]# awk -F\' '$1=="menuentry " {print $2}' /etc/grub2.cfg
CentOS Linux (4.19.307) 7 (Core)
CentOS Linux (3.10.0-957.el7.x86_64) 7 (Core)
CentOS Linux (0-rescue-911633810ca5492cbd9a6add237169e7) 7 (Core)


# 设置启动顺序
[root@localhost ~]# grub2-set-default 0

# 重启生效
[root@localhost ~]# reboot

关于Bcache的介绍和使用

Linux使用bcache让SSD加速硬盘