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

Linux 字符驅動開發心得:從設備號到 file_operations 的最小骨架

Linux 字符驅動的框架,對初學者來說不太容易記。寫過一陣子之後,我把框架搭建濃縮成兩個關鍵動作:申請設備號與註冊字符驅動。

int alloc_chrdev_region(dev_t *, unsigned, unsigned, const char *);  // 動態申請設備號
int cdev_add(struct cdev *, dev_t, unsigned);                        // 註冊字符驅動

做完這兩步,驅動就能被加載進內核。下面從零把骨架搭起來,驅動取名 “main”。

頭檔案與模組宣告

#include <linux/fs.h>
#include <linux/module.h>
#include <linux/coda.h>
#include <linux/slab.h>
#include <linux/cdev.h>
#include <linux/uaccess.h>

#define MODULE_NAME "main"
MODULE_LICENSE("GPL");

驅動要進內核,就得宣告遵循的授權協議,否則加載時系統會發出訊息。這裡依內核慣例掛上 GPL。

兩個關鍵結構體

要把驅動註冊進內核,必須先把它抽象成 struct cdev——系統裡有各種字符驅動,透過這個統一結構,才能用同一組函數註冊。

struct cdev {
    struct kobject kobj;
    struct module *owner;
    const struct file_operations *ops;
    struct list_head list;
    dev_t dev;
    unsigned int count;
};

其中 kobj 暫可不管,owner 指向模組擁有者(通常用 THIS_MODULE 賦值),ops 才是我們真正要動手的地方——各種操作介面都在那裡。

struct cdev mydev;
struct file_operations ops;

struct file_operations 相當龐大,內部全是函數指標:

struct file_operations {
    struct module *owner;
    loff_t (*llseek) (struct file *, loff_t, int);
    ssize_t (*read) (struct file *, char __user *, size_t, loff_t *);
    ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *);
    int (*open) (struct inode *, struct file *);
    int (*release) (struct inode *, struct file *);
    long (*unlocked_ioctl) (struct file *, unsigned int, unsigned long);
    int (*mmap) (struct file *, struct vm_area_struct *);
    unsigned int (*poll) (struct file *, struct poll_table_struct *);
    /* ...其餘省略... */
};

C 語言沒有 interface 概念,用這種「全函數指標的結構體」來定義介面是一種巧妙的替代做法;而且我們不必把每個指標都實作。應用程式使用驅動時最常用 open、write、read、close,對應的就是 open、write、read、release 這四個欄位。實作時,函式的簽名必須與介面定義一致。

static int main_open(struct inode *inode, struct file *filp)
{
    return 0;
}

讀寫:使用者空間與核心空間的搬運

這個範例讓驅動只能存一個字元。我們用一個靜態字元變數當儲存空間,並透過 copy_from_user 把使用者空間的資料搬進核心空間:

static inline long copy_from_user(void *to, const void __user *from, unsigned long n)
static inline long copy_to_user(void __user *to, const void *from, unsigned long n)
static char main_buffer;

static ssize_t main_write(struct file *filp, const char __user *buffer,
                          size_t length, loff_t *l)
{
    if (length != 1) return -1;
    copy_from_user(&main_buffer, buffer, length);
    return 1;
}

static ssize_t main_read(struct file *filp, char __user *buffer,
                         size_t length, loff_t *l)
{
    if (length != 1) return -1;
    copy_to_user(buffer, &main_buffer, length);
    return 1;
}

static int main_close(struct inode *inode, struct file *filp)
{
    return 0;
}

嚴謹一點的話,copy_from_user/copy_to_user 的回傳值應該檢查:它回傳的是「未能複製的位元組數」,非零就該回傳 -EFAULT,而不是假裝成功。

初始化:申請設備號並註冊

static dev_t dev;

static int __init main_init(void)
{
    // 動態申請設備號
    int result = alloc_chrdev_region(&dev, 0, 1, MODULE_NAME);
    if (result < 0)
    {
        printk(KERN_ALERT "device load error");
        return -1;
    }

    // 組裝操作介面
    ops.owner   = THIS_MODULE;
    ops.open    = main_open;
    ops.release = main_close;
    ops.write   = main_write;
    ops.read    = main_read;

    // 用 ops 構造抽象驅動
    cdev_init(&mydev, &ops);
    mydev.owner = THIS_MODULE;

    // 向系統註冊
    cdev_add(&mydev, dev, 1);
    printk(KERN_ALERT "device load success\n");
    return 0;
}

dev_t 其實就是一個無符號 long。alloc_chrdev_region 的第二個參數是子設備號起始值,第三個是要申請幾個(連續分配,知道第一個就夠了),第四個是驅動名稱。透過 cdev_init 之後,當內核要對這個驅動執行寫入,就會沿著 mydev->ops->write 找到我們實作的函式。

printk 的訊息在動態加載時未必看得到:Ubuntu 下查 /var/log/kern.log,CentOS 下查 /var/log/messages,看最後十幾行通常就夠了。

清理與入口出口宣告

static void __exit main_exit(void)
{
    unregister_chrdev_region(dev, 1);
    cdev_del(&mydev);
}
module_init(main_init);
module_exit(main_exit);

module_init 與 module_exit 宣告驅動的入口與出口,是必須完成的一步。有了初始化,就一定要有對應的清理函式。

Makefile

ifeq ($(KERNELRELEASE),)
KERNELDIR ?= /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
modules:
    $(MAKE) -C $(KERNELDIR) M=$(PWD) modules -Wall
modules_install:
    $(MAKE) -C $(KERNELDIR) M=$(PWD) modules_install -Wall
clean:
    rm -rf *.o *~ core .depend .*.cmd
    sudo rmmod main
    sudo rm /dev/main
install:
    sudo insmod main.ko
    sudo mknod /dev/main c 250 0
message:
    tail -n 5 /var/log/kern.log
.PHONY: modules modules_install clean
else
    obj-m := main.o
endif

因為我的機器是 Ubuntu,message 目標看的是 kern.log;若該檔案不存在,換成 /var/log/messages 即可。這裡的 install 目標是照我自己的環境寫的,換機器時請在命令行手動執行:

$ make
$ sudo insmod main.ko

然後查 /proc/devices 看 main 對應的設備號(我的是 250),據此建立設備節點:

sudo mknod /dev/main c 250 0

驅動就這樣裝進內核了。執行 make message 若看到最後一行是 device load success,恭喜,一個最簡單的字符驅動完成。

延伸閱讀

Linux 字符驅動中動態分配設備號與動態生成設備節點 https://www.linuxidc.com/Linux/2014-03/97438.htm
字符驅動設計----mini2440 LED 驅動設計之路 https://www.linuxidc.com/Linux/2012-08/68706.htm
Linux 設備驅動 ====> 字符驅動 https://www.linuxidc.com/Linux/2012-03/57581.htm
如何編寫 Ubuntu 字符驅動 https://www.linuxidc.com/Linux/2010-05/25887.htm
2.4 下內核 linux 字符驅動模板 https://www.linuxidc.com/Linux/2007-06/5338.htm

Copyright © Linux教程網 All Rights Reserved