Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

x86 平台上手動編譯 Linux 內核並設定開機選項

最近在 x86 平台上把 Linux 內核從設定、編譯一路走到開機引導,整套流程都在虛擬機裡完成,安全又方便,做壞了重來一次就好。

先理清整體思路

動手之前,先把編譯內核需要經歷的幾個階段記下來,後面照著走就不容易亂:

  1. 取得原始碼:到 www.kernel.org 下載自己需要的版本。建議一律抓官方版本,不要拿別人裁剪過的內核,否則出問題很難查。
  2. 解壓縮:官方提供 gzip 與 bzip2 兩種打包格式。gzip 用 tar -xvzf,bzip2 用 tar -xvjf。
  3. 清理:解開之後先清一次,避免舊的產物干擾。三個常用命令:
    • make clean:刪除產生的檔案,但保留設定檔。
    • make mrproper:連設定檔一起刪。
    • make distclean:在 mrproper 的基礎上,再清掉編輯器備份檔與 patch 檔。
  4. 設定:有四種方式。make config 是逐題問答的純文字模式;make menuconfig 是菜單式,最常用;make xconfig 需要 X Window,純命令列環境用不了;另外還有圖形化的 gconfig。設定完成後會在原始碼根目錄產生 .config,也可以直接拿一份現成的設定檔來改,省下大量時間。
  5. 編譯核心:make zImage 在 x86 上只能產生 512K 以內的內核;make bzImage 則沒有大小限制。
  6. 編譯模組:make modules。設定時選「M」的項目只編譯不連結,選「*」的會直接連結進內核,兩者最後都以模組形式載入。
  7. 安裝模組:make modules_install。
  8. 建立 init ramdisk:mkinitrd initrd-$Version $Version,第二個參數填實際的內核版本。它的作用是讓內核具備掛載 ramdisk 的能力,包含格式化 ramdisk、把檔案系統載入 ramdisk,以及把 ramdisk 當成根檔案系統。
  9. 安裝內核:Linux 開機時會到 /boot 找內核與 init ramdisk,所以要把兩者都複製過去,再修改 grub 設定,讓開機選單多出一項自己編的內核。

實際操作

以下是我這次在 Fedora 9 上編譯 2.6.29 的完整過程。

1. 建立目錄存放原始碼

[root@localhost /]# mkdir linux_kernel

2. 進入目錄並解壓

[root@localhost linux_kernel]# ls
linux-2.6.29.tar.gz
[root@localhost linux_kernel]# tar -xvzf linux-2.6.29.tar.gz

3. 進入原始碼根目錄並清理

[root@localhost linux_kernel]# cd linux-2.6.29
[root@localhost linux-2.6.29]# make distclean

4. 設定內核:直接沿用目前系統的設定檔當起點,再進菜單微調。

[root@localhost linux-2.6.29]# cp /boot/config-2.6.25-14.fc9.i686 .config
[root@localhost linux-2.6.29]# make menuconfig

接著依需求逐項調整設定,存檔退出即可。

5. 編譯內核:完成後產物在 /arch/x86/boot 下。

[root@localhost linux-2.6.29]# make bzImage

6. 編譯模組

[root@localhost linux-2.6.29]# make modules

7. 安裝模組:模組會從原始碼目錄被複製到 /lib/modules 底下。

[root@localhost linux-2.6.29]# make modules_install

8. 建立 init ramdisk

[root@localhost linux_kernel]# mkinitrd initrd-2.6.29 2.6.29

9. 複製內核與 ramdisk 到 /boot

[root@localhost linux_kernel]# cp /linux_kernel/linux-2.6.29/arch/x86/boot/bzImage /boot/vmlinuz-2.6.29
[root@localhost linux_kernel]# cp /linux_kernel/initrd-2.6.29 /boot/

檔名可以自取,但後面寫 grub 設定時名稱必須對得上。

10. 修改 grub 開機項

[root@localhost linux_kernel]# vi /etc/grub.conf

在檔案中加入一段:

title xgg's Linux (2.6.29)
    root (hd0,0)
    kernel /vmlinuz-2.6.29 ro root=UUID=3f0b3cdc-c7e6-4649-a214-124f469262f4 rhgb quiet
    initrd /initrd-2.6.29

其中 root=UUID= 要換成自己根分區的 UUID,硬碟與分區編號也要對應實際環境。

到這裡內核就算編好了。下次開機,選單上就會多出這一個自製的核心項目,整個流程其實並不複雜。

Copyright © Linux教程網 All Rights Reserved