cd /usr/src
wget https://cdn.kernel.org/pub/linux/kernel/v5.x/linux-5.15.100.tar.xz
tar -xvf linux-5.15.100.tar.xz
cd linux-5.15.100
建議: 使用長期支援 (LTS) 版本,避免 RC 版。
cp /boot/config-$(uname -r) .config
make olddefconfig # 自動回答新選項為預設值
# CentOS/RHEL
make defconfig
# 或下載官方配置
wget -O .config https://raw.githubusercontent.com/torvalds/linux/master/arch/x86/configs/x86_64_defconfig
# 透過 make menuconfig 圖形化介面勾選
General setup --->
[*] Enable deprecated sysfs features to support old userspace tools
[*] Enable deprecated sysfs features by default (CONFIG_SYSFS_DEPRECATED_V2=y)
Device Drivers --->
Generic Driver Options --->
[*] Maintain a devtmpfs filesystem to mount at /dev
Block devices --->
<*> Loopback device support
<*> Cryptoloop Support
關鍵修正: 若 .config 中 CONFIG_SYSFS_DEPRECATED_V2 被註解,需手動設為 y,否則舊版 mkinitrd/nash 會導致 mount: could not find filesystem '/dev/root' 錯誤。
# 編譯核心映像 (bzImage)
make -j$(nproc) bzImage
# 編譯模組
make -j$(nproc) modules
# 安裝模組到 /lib/modules/$(uname -r)/
make modules_install
# 安裝核心到 /boot、更新 grub
make install
並行編譯: -j$(nproc) 使用所有 CPU 核心,大幅縮短時間。
# CentOS/RHEL 7+ (dracut)
dracut --force /boot/initramfs-5.15.100.img 5.15.100
# Debian/Ubuntu (update-initramfs)
update-initramfs -c -k 5.15.100
# 手動打包 (舊版/特殊需求)
cd /boot
cp initramfs-5.15.100.img /tmp/
cd /tmp
mkdir newinitrd && cd newinitrd
zcat ../initramfs-5.15.100.img | cpio -idmv
# 修復重複模組載入 (如 dm-region-hash.ko)
vi init
# 找到並刪除重複的 insmod 行
find . | cpio -c -o > ../initramfs-new.img
cd ..
gzip -9 < initramfs-new.img > initramfs-5.15.100.img
cp initramfs-5.15.100.img /boot/
# 檢查可用核心項目
grep ^menuentry /boot/grub2/grub.cfg
# 或
grubby --info=ALL
# 設定預設啟動項 (以最新核心為例)
grubby --set-default /boot/vmlinuz-5.15.100
# 或手動編輯 /etc/default/grub
GRUB_DEFAULT=saved
GRUB_SAVEDEFAULT=true
# 然後
grub2-mkconfig -o /boot/grub2/grub.cfg
vi /boot/grub/grub.conf
# 修改 default=0 (指向新核心條目)
reboot
uname -r # 確認新核心版本
dmesg | head -20 # 檢查啟動日誌
lsmod # 確認模組載入正常
| 錯誤現象 | 原因 | 解決 |
|---|---|---|
| Kernel panic: VFS: Unable to mount root fs | initramfs 缺少磁碟/檔案系統驅動 | 確認 .config 包含根裝置驅動 (SATA/NVMe/RAID)、重建 initramfs |
| mount: could not find filesystem '/dev/root' | SYSFS_DEPRECATED_V2 未啟用 | 設定 CONFIG_SYSFS_DEPRECATED_V2=y 重編 |
| 模組載入失敗 | 模組版本不匹配 (vermagic) | 確認編譯環境一致、重新 make modules_install |
| 開機卡在 GRUB | grub.cfg 未正確更新 | 重新執行 grub2-mkconfig、檢查裝置映射 |
tar czf /backup/boot-$(date +%F).tar.gz /bootyum update kernel / apt install linux-image-generic 更安全make localmodconfig 僅編譯目前載入模組,大幅縮減體積與時間