轉自:https://www.cnblogs.com/yiru/archive/2012/11/26/2789681.html(博主:勒達與天鵝),僅供學習參考。
要讀 LDD 就得先有可用的驅動開發環境,網路上找到的文章照著做會遇到不少坑,經過近兩天的摸索與修改後終於成功,以下為修正後的版本。
《Linux Device Driver Third Edition》提到 Setting Up Your Test System 時指出:為 2.6.X 撰寫模組,首先要求在 Linux 上建置並配置核心原始碼樹。對 2.6 核心來說,現有的標頭檔已經足夠,但模組連結的是原始碼樹中的目的檔,這樣模組載入器會更穩健,但也要求這些目的檔必須存在。所以驅動開發的第一件事就是建核心原始碼樹。
書裡沒說怎麼建,以下是我整理的流程。環境是安裝在虛擬機裡的 Ubuntu 10.10,建議虛擬硬碟容量至少 15G(我配 10G 時仍有容量不足的提示,但還是完成了)。
先查核心版本:在終端輸入 uname -r,我的版本是 2.6.32-35-generic。
接著到 /usr/src/ 看有沒有 linux-source,通常沒有。用 apt-cache search linux-source 搜尋,會列出 linux-source 與 linux-source-2.6.35 等選項,挑對應自己核心的版本安裝:
sudo apt-get install linux-source-2.6.35
下載完畢後 /usr/src/ 下會出現 linux-source-2.6.35 目錄,裡面有 linux-source-2.6.35.tar.bz2,解壓到該目錄下。解壓方式:先 sudo -i 切換到根用戶,定位到 /usr/src/linux-source-2.6.35/,執行 tar jxvf linux-source-2.6.35.tar.bz2,得到原始碼目錄 linux-source-2.6.35。
進入該目錄開始配置核心,選最快的原版預設方式:make oldconfig。
完成後,先去修改 /usr/src/linux-source-2.6.35/ubuntu/omnibook/Makefile,否則會出現 ld: /ubuntu/omnibook/sections.lds: No such file 的錯誤。以根用戶開啟該 Makefile,把其中的 PWD=$(shell pwd) 剪貼到 ifeq ($(KERNELRELEASE),) 前面,存檔。
然後編譯模組,定位到原始碼目錄執行 make modules,約等一個小時。完成後安裝模組:make modules_install。至此原始碼樹建置完成,重啟系統。
接著試跑書中第一個範例。程式碼 helloworld.c:
#include <linux/init.h>
#include <linux/module.h>
MODULE_LICENSE("GPL");
static int hello_init(void){
printk(KERN_ALERT "hello world!\n");
return 0;
}
static int hello_exit(void){
printk(KERN_ALERT "Goodbye cruel world!\n");
return 0;
}
module_init(hello_init);
module_exit(hello_exit);
Makefile:
ifneq ($(KERNELRELEASE),)
obj-m := hello.o
else
PWD := $(shell pwd)
KVER ?= $(shell uname -r)
KDIR := /lib/modules/$(KVER)/build
all:
$(MAKE) -C $(KDIR) M=$(PWD)
clean:
rm -rf .*.cmd *.o *.mod.c *.ko .tmp_versions *.symvers *.order
endif
編譯:執行 make,輸出如下:
make -C /lib/modules/2.6.32-35-generic/build M=/source/test/ldd
make[1]: Entering directory `/usr/src/linux-headers-2.6.32-35-generic'
LD /source/test/ldd/built-in.o
CC [M] /source/test/ldd/hello.o
Building modules, stage 2.
MODPOST 1 modules
CC /source/test/ldd/hello.mod.o
LD [M] /source/test/ldd/hello.ko
make[1]: Leaving directory '/usr/src/linux-headers-2.6.32-35-generic'
用 modinfo hello.ko 查看模組資訊,insmod hello.ko 載入(沒有錯誤訊息即成功),lsmod 確認已載入,rmmod hello.ko 移除。
為什麼載入與移除時沒看到 printk 的輸出?書中說明,如果不出現在終端,就會寫進 syslog:
cat /var/log/syslog | grep world
Nov 28 11:07:47 ubuntu64 kernel: [ 6942.233442] hello world!
Nov 28 11:08:00 ubuntu64 kernel: [ 6955.202296] Goodbye cruel world!
驅動開發實驗環境建置完成。