Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux 內核定製指南:依硬體精簡編譯、提升開機速度與釋放記憶體

編輯:Linux 教學

為什麼要定製內核?

發行版預設內核為了相容性包含大量驅動與功能,導致體積龐大、開機慢、佔用記憶體。依實際硬體精簡內核可:

  • 移除無用驅動(無線網卡、SCSI、舊式音效晶片等)。
  • 針對 CPU 型號啟用最佳化(如 CONFIG_MCORE2、CONFIG_MK8)。
  • 將低頻功能模組化 (M),按需載入。
  • 縮減內核映像大小,加快載入與解壓縮。

前置準備:備份與啟動盤

  1. 備份重要資料。
  2. 製作啟動救援媒體(USB/光碟),確保編譯失誤時可救援。
    Red Hat 系:mkbootdisk --verbose --device /dev/sdX $(uname -r)。
  3. 以 root 登入文字模式(Runlevel 3)。

內核源碼獲取與配置介面

cd /usr/src/linux          # 或解壓內核源碼至任意目錄
make mrproper              # 清理舊配置

兩種配置介面:

  • make menuconfig:文字介面(NCurses),適合 SSH/終端機。
  • make xconfig:圖形介面 (Qt),需 X Window,操作直觀。

本文以 xconfig 為例。

關鍵配置選單逐項說明

Processor type and features

  • Processor family:選擇精確 CPU 型號(Core 2/Nehalem/AMD K8/Zen 等),啟用對應指令集最佳化。
  • Preemption Model:桌面選 Preemptible Kernel (Low Latency Desktop);伺服器選 Voluntary Kernel Preemption 或 No Forced Preemption。
  • Timer frequency:1000Hz (桌面/多媒體) / 250Hz/300Hz (伺服器/省電)。

Device Drivers → 僅保留實體硬體對應驅動

  • 網路:僅勾選實際網卡驅動(e1000e, igb, r8169 等),其餘設 M 或 N。
  • 儲存:AHCI/SATA/NVMe 控制器設 *(內建),RAID 卡、SCSI 若無硬體設 N。
  • 圖形:Intel/AMD/NVIDIA 驅動依顯示卡選擇,桌面建議內建 KMS 驅動。
  • USB、音效、輸入裝置:按需啟用。

File systems

  • 根分區檔案系統 (ext4/xfs/btrfs) 必須設 * 內建。
  • 其他檔案系統 (vfat, ntfs, nfs, cifs) 設 M 模組化。

Kernel hacking / Debugging

生產環境建議關閉 DEBUG_KERNEL、DEBUG_INFO 等除錯選項,減少體積與效能損耗。

模組化策略

選項三態:Y(*)=內建、M=模組、N=不編譯。
原則:開機必須(根檔案系統、啟動裝置驅動、CPU 核心)設 Y;其餘盡量 M。

編譯與安裝

make bzImage               # 編譯內核映像 (約 10-30 分鐘視 CPU)
make modules               # 編譯模組
make modules_install       # 安裝模組至 /lib/modules/$(uname -r)

若報錯,回頭檢查相依選項(xconfig 會自動提示相依)。

部署新內核

cp arch/x86/boot/bzImage /boot/vmlinuz-$(uname -r)-custom
cp System.map /boot/System.map-$(uname -r)-custom
cp .config /boot/config-$(uname -r)-custom

更新引導載入器 (GRUB 2)

grub2-mkconfig -o /boot/grub2/grub.cfg
# 或手動編輯 /etc/grub.d/40_custom 加入新選單項

舊版 GRUB (Legacy) 編輯 /boot/grub/grub.conf 新增 title/kernel/initrd 項。

建立初始虛擬檔案系統 (initramfs/initrd)

若根分區驅動、檔案系統模組化,必須重建 initramfs:

dracut -f /boot/initramfs-$(uname -r)-custom.img $(uname -r)-custom
# 或 mkinitrd (舊版)

驗證與回滾

  1. 重啟,GRUB 選單選擇新內核啟動。
  2. uname -r 確認版本;dmesg | grep -i error 檢查錯誤。
  3. 若失敗,重啟選舊內核,檢查配置、重建 initramfs、修正相依後再試。

常見陷阱與避坑指南

現象可能原因對策
Kernel panic: VFS: Unable to mount root fs根分區驅動/檔案系統未內建,或 initramfs 缺失設為 Y 內建,或重建 initramfs 包含對應模組
鍵盤/滑鼠無反應USB HID / 輸入子系統未啟用Device Drivers → Input device support → Keyboard/Mouse 設 Y
網卡不見對應驅動未編譯lspci -k 確認驅動名稱,設 Y 或 M 並載入
模組載入失敗: Unknown symbol內核配置改變導致符號不匹配完整重新編譯 make clean && make

總結

內核定製是 Linux 系統調優的核心技能。建議流程:硬體清單 → 最小配置 → 測試 → 逐步加入功能。保留舊內核作為回滾基準,善用 make olddefconfig 升級新版源碼時保留既有配置。

Copyright © Windows教程網 All Rights Reserved