Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux技術

ARM 平台字符驅動:異步通知與異步 I/O 完整實例

設備文件的 I/O 訪問有阻塞與非阻塞兩種方式,poll 已經提供了不錯的解決方案;如果再配上異步通知,整套機制才算完整。本文以一個 4KB 的「虛擬磁盤」字符設備 myfasync_drv 為例,把內核結構體與內核函數串起來講清楚。

一、阻塞 I/O、非阻塞 I/O 與異步 I/O

· 阻塞 I/O:掛起進程,一直等待設備可訪問後再訪問。

· 非阻塞 I/O:進程訪問設備一次,不可訪問時直接執行下一條指令。

· 異步 I/O:非常類似硬件上的「中斷」概念(硬件去 call 軟件、內核去 call 應用程序)。信號是在軟件層次上對中斷機制的一種模擬:信號是異步的,進程不必通過任何操作來等待它到達,事實上進程也不知道信號何時到達。「進程收到異步通知信號」與「處理器收到中斷請求」原理相同。

異步通知隊列(async_queue):內核通過 fasync() 函數把設備文件 fd 加入異步通知隊列(內核中的鏈表)。當該 fd 發生 I/O 時,內核調用 kill_fasync() 產生 SIGIO 信號,從而主動通知注冊過 SIGIO 的應用程序。

要特別注意:異步通知的對象必須是設備文件,而且必須注冊過 fasync()。普通文件(比如 /tmp/text.txt)不行,因為普通文件在內核中並沒有實現 fasync() 與 kill_fasync()。

二、應用程序部分

模板一:設備文件的異步通知應用程序骨架

void input_handler(int num) { /* 信號處理函數 */ }

fd = open("設備文件路徑,如 /dev/xxx", O_RDWR);
signal(SIGIO, input_handler);              //等待內核 kill_fasync() 釋放 SIGIO
fcntl(fd, F_SETOWN, getpid());             //讓當前進程成為文件的主人
oflags = fcntl(fd, F_GETFL);               //取得當前 fd 的 flag
fcntl(fd, F_SETFL, oflags | FASYNC);       //添加異步通知標志,fd 進入通知隊列

實例一:以標準輸入設備演示異步通知

#include <signal.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>

#define MAX_LEN 100

void input_handler(int num)
{
    char data[MAX_LEN];
    int len;
    len = read(STDIN_FILENO, &data, MAX_LEN);
    data[len] = 0;
    printf("input available :%s\n", data);
}

void setFdAsync(int fd)
{
    int oflags;
    fcntl(fd, F_SETOWN, getpid());            //當前進程變成文件的主人
    oflags = fcntl(fd, F_GETFL);
    /* FASYNC 在 glibc 的 fcntl.h 中定義為 #define FASYNC O_ASYNC */
    fcntl(fd, F_SETFL, oflags | FASYNC);
}

void main()
{
    int fd = STDIN_FILENO;                    //一般是鍵盤
    signal(SIGIO, input_handler);
    setFdAsync(fd);
    while (1);
}

運行後每輸入一行,就會看到 input available :...。在某些系統上,由於對 STDIN_FILENO 有特殊保護,while 循環執行兩次後進程會被掛起休眠,此時 CPU 消耗為 0。

三、驅動程序部分:一項數據結構 + 兩個函數

fasync_struct 結構體

struct fasync_struct {
    int magic;                     //FASYNC_MAGIC,設備文件鏡像標識
    int fa_fd;                     //文件描述符
    struct fasync_struct *fa_next; //異步通知單鏈表
    struct file *fa_file;          //該進程打開的文件
};

fasync_helper:把 fd 加入異步通知隊列

int fasync_helper(int fd, struct file *filp, int on, struct fasync_struct **fapp)
{
    struct fasync_struct *fa, **fp;
    struct fasync_struct *new = NULL;
    int result = 0;

    if (on) {   //第一次 on = mode = oflag | FASYNC,不為 0,分配空間
        new = kmem_cache_alloc(fasync_cache, GFP_KERNEL);
        if (!new)
            return -ENOMEM;
    }
    write_lock_irq(&fasync_lock);
    for (fp = fapp; (fa = *fp) != NULL; fp = &fa->fa_next) {
        if (fa->fa_file == filp) {
            if (on) {
                fa->fa_fd = fd;
                kmem_cache_free(fasync_cache, new);
            } else {           //釋放設備時(on = 0)摘除節點
                *fp = fa->fa_next;
                kmem_cache_free(fasync_cache, fa);
                result = 1;
            }
            goto out;
        }
    }
    if (on) {                  //首次加入鏈表
        new->magic   = FASYNC_MAGIC;
        new->fa_file = filp;
        new->fa_fd   = fd;
        new->fa_next = *fapp;
        *fapp = new;
        result = 1;
    }
out:
    write_unlock_irq(&fasync_lock);
    return result;
}
EXPORT_SYMBOL(fasync_helper);

kill_fasync:釋放異步讀信號

void __kill_fasync(struct fasync_struct *fa, int sig, int band)
{
    while (fa) {
        struct fown_struct *fown;
        if (fa->magic != FASYNC_MAGIC) {   //鏡像失效,不產生信號
            printk(KERN_ERR "kill_fasync: bad magic number in fasync_struct!\n");
            return;
        }
        fown = &fa->fa_file->f_owner;
        if (!(sig == SIGURG && fown->signum == 0))
            send_sigio(fown, fa->fa_fd, band);
        fa = fa->fa_next;
    }
}
EXPORT_SYMBOL(__kill_fasync);

參數 sig 是要發送的信號;band 一般填 POLL_IN 表示設備可讀,可寫時用 POLL_OUT。

驅動中的異步通知模板

struct VirtualDisk {
    struct cdev cdev;
    /* ...其他全局變量... */
    struct fasync_struct *async_queue;   //異步結構體指針
};

static int myfasync_drv_fasync(int fd, struct file *file, int mode)
{
    struct VirtualDisk *devp = file->private_data;
    return fasync_helper(fd, file, mode, &devp->async_queue);
}

static ssize_t myfasync_drv_write(struct file *file, const char __user *buf,
                                  size_t count, loff_t *ppos)
{
    struct VirtualDisk *devp = file->private_data;
    /* ...寫入處理... */
    if (devp->async_queue)
        kill_fasync(&devp->async_queue, SIGIO, POLL_IN);   //產生異步讀信號
    return 0;
}

static int myfasync_drv_release(struct inode *inode, struct file *file)
{
    myfasync_drv_fasync(-1, file, 0);   //關閉時從異步隊列刪除
    return 0;
}

完整驅動實例要點

設備定義為 4KB 內存(VIRTUALDISK_SIZE 0x1000),主設備號 250,file_operations 中包含 open、read、write、release、llseek、ioctl 與 fasync 七個方法:

static struct file_operations myfasync_drv_fops = {
    .owner   = THIS_MODULE,
    .open    = myfasync_drv_open,
    .read    = myfasync_drv_read,
    .write   = myfasync_drv_write,
    .release = myfasync_drv_release,
    .llseek  = myfasync_drv_llseek,
    .ioctl   = myfasync_drv_ioctl,
    .fasync  = myfasync_drv_fasync,
};

其中 llseek 支持 SEEK_SET / SEEK_CUR / SEEK_END 三種定位方式並做越界檢查;ioctl 支持 MEM_CLEAR 命令把設備內存清零,不認識的命令返回 -EINVAL;read 與 write 通過 copy_to_user / copy_from_user 在設備內存與用戶緩沖區之間搬運數據,並同步更新文件偏移;write 結束時調用 kill_fasync 發送 SIGIO。初始化流程則是 register_chrdev_region(或 alloc_chrdev_region)→ kmalloc 設備結構 → cdev_init/cdev_add → class_create/class_device_create 自動生成 /dev 節點。

Makefile

KERN_DIR = /workspacearm/linux-2.6.2.6
all:
	make -C $(KERN_DIR) M=`pwd` modules
	cp myfasync_drv.ko /opt/fsmini/
clean:
	make -C $(KERN_DIR) M=`pwd` modules clean
	rm -rf timerlists.order
obj-m += myfasync_drv.o

測試應用程序

int myfd;
int lenthe;

void input_handler(int num)
{
    char data[80];
    int len;
    lseek(myfd, -lenthe, SEEK_CUR);   //把偏移移回寫之前的位置
    len = read(myfd, data, lenthe);
    printf("myfd = %d, len = %d buffuer input available :%s\n", myfd, len, data);
}

int main()
{
    myfd = open("/dev/myfasync_drv", O_RDWR);
    printf("fd = %d, pid = %d", myfd, getpid());
    signal(SIGIO, input_handler);
    setFdAsync(myfd);
    while (1) {
        char buffer[80];
        lenthe = read(STDIN_FILENO, buffer, 80);
        write(myfd, buffer, lenthe);
    }
    return 0;
}

實驗結果

# insmod myfasync_drv.ko
# ./mybutton.bin
myfasync_drv open          //對應應用程序的 open
myfasync_drv_fasync 3      //對應 fcntl(fd, F_SETFL, oflags | FASYNC)
fd = 3, pid = 793 before while
hello                      //鍵盤輸入
myfasync_drv write
written 6 bytes(s) from 0, buffer is hello
write kill_fasync          //釋放 SIGIO
myfasync_drv read          //應用程序收到信號後執行 read
read 6 bytes(s) is 0
myfd = 3, len = 6 buffuer input available :hello
...
myfasync_drv release       //Ctrl+C 退出,執行 release
myfasync_drv_fasync -1

四、異步通知的缺陷

當多個文件同時向同一個進程發送異步通知信號時,進程無法判斷究竟是哪個文件發來的信號。這時候「設備文件」仍然要借助 poll/select 機制才能完成完整的 I/O 管理。

Copyright © Linux教程網 All Rights Reserved