環境與準備
# 1. 安裝編譯依賴
sudo apt-get install build-essential libncurses5-dev libssl-dev bison flex
# 2. 下載內核源碼 (kernel.org)
wget https://cdn.kernel.org/pub/linux/kernel/v3.x/linux-3.10.108.tar.xz
# 或舊版
wget https://cdn.kernel.org/pub/linux/kernel/v2.6/linux-2.6.30.3.tar.bz2
# 3. 解壓至 /usr/src
sudo tar xf linux-*.tar.* -C /usr/src/
cd /usr/src/linux-*
配置內核
# 1. 複製當前運行內核配置為基礎 (推薦)
sudo cp /boot/config-$(uname -r) .config
# 2. 圖形化配置菜單 (需 root 權限)
sudo make menuconfig
# 關鍵選項檢查:
# [*] Enable loadable module support
# [*] Module unloading
# [*] Enable the block layer
# Processor type and features → 選擇正確 CPU 型號
# Device Drivers → 確保磁盤控制器、文件系統、網卡驅動為 [*] 或 [M]
# Firmware Drivers → 相關固件加載
編譯內核與模塊
# 並行編譯 (核心數 × 2 或核心數)
make -j$(($(nproc)*2))
# 僅編譯模塊 (修改驅動後)
make -j$(nproc) modules
安裝內核
# 1. 安裝模塊至 /lib/modules/$(KERNELRELEASE)
sudo make modules_install
# 2. 安裝內核映像、System.map、config 至 /boot
sudo make install
# 相當於:
# cp arch/x86/boot/bzImage /boot/vmlinuz-
# cp System.map /boot/System.map-
# cp .config /boot/config-
# 3. 更新 initramfs (關鍵!包含根文件系統驅動)
sudo update-initramfs -c -k
# 例如:sudo update-initramfs -c -k 3.10.108
# 4. 更新 GRUB2
sudo update-grub2
# 或
sudo grub-mkconfig -o /boot/grub/grub.cfg
驗證與啟動
# 重啟
sudo reboot
# 進入 GRUB 菜單選擇 "Advanced options for Ubuntu" → 新內核
# 進入系統後確認
uname -r
常見問題與解決
| 問題 | 原因 | 解決 |
| 啟動卡在 "Waiting for root device" | initramfs 缺少 SATA/RAID/SCSI 驅動 | make menuconfig 將對應驅動設為 [*] 內建,重新 make install + update-initramfs |
| 鍵盤/鼠標無響應 | USB HID 驅動未內建 | Device Drivers → HID → USB HID 設為 [*] |
| 模塊版本魔數不匹配 | 模塊編譯內核版本與運行內核不一致 | 確保 make modules_install 對應正確版本,depmod -a |
| 編譯報錯 "openssl/bio.h not found" | 缺少 libssl-dev | apt-get install libssl-dev |
加速編譯技巧
ccache:apt-get install ccache,設置 export CC="ccache gcc"。
make localmodconfig:根據當前加載模塊精簡配置 (嵌入式/精簡內核適用)。
- 模塊化驅動:非啟動必需驅動設為
[M],減小內核體積、加快啟動。