Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux綜合 >> Linux 核心

Linux 內核 Input 子系統入門:以觸控螢幕為例看資料怎麼從硬體走到使用者

Linux 的輸入設備五花八門:按鍵、鍵盤、觸控螢幕、滑鼠、搖桿……但它們本質上都是字元設備。內核把這些共通性抽象出來,做成了 input 子系統,讓驅動開發不必每個都從零開始。本文以觸控螢幕為例,把「註冊 → 配對 → 上報 → 讀取」這條鏈路走一遍。

第一章、三層架構與三個核心結構

Linux 內核 Input 子系統入門:以觸控螢幕為例看資料怎麼從硬體走到使用者

圖 1 input 輸入子系統

子系統分為三層:

  • 驅動層:與硬體直接相關,負責捕捉觸控被按下、按下的座標、滑鼠移動、按鍵輸入等原始資料,然後往核心層上報。
  • 核心層:扮演橋樑。device driver 與 handler 的註冊都經由它完成;它接收驅動層的資料,挑選對應的 handler 去處理。
  • 事件處理層:最終把資料複製到使用者空間,供應用程式讀取。

先認識三個定義在 linux/input.h 的重要結構。

input_dev:描述一個輸入設備

struct input_dev {
    void *private;
    const char *name;
    const char *phys;
    const char *uniq;
    struct input_id id;              // 與 input_handler 配對用的 id
    unsigned long evbit[NBITS(EV_MAX)];   // 設備支援的事件類型
    unsigned long keybit[NBITS(KEY_MAX)]; // 按鍵事件的子類型
    unsigned long relbit[NBITS(REL_MAX)];
    unsigned long absbit[NBITS(ABS_MAX)]; // 絕對座標事件的子類型
    unsigned long mscbit[NBITS(MSC_MAX)];
    unsigned long ledbit[NBITS(LED_MAX)];
    unsigned long sndbit[NBITS(SND_MAX)];
    unsigned long ffbit[NBITS(FF_MAX)];
    unsigned long swbit[NBITS(SW_MAX)];
    ...
    int absmax[ABS_MAX + 1];         // 絕對座標事件的最大值
    int absmin[ABS_MAX + 1];         // 絕對座標事件的最小值
    int absfuzz[ABS_MAX + 1];
    int absflat[ABS_MAX + 1];
    int (*open)(struct input_dev *dev);
    void (*close)(struct input_dev *dev);
    int (*event)(struct input_dev *dev, unsigned int type, unsigned int code, int value);
    struct input_handle *grab;       // 目前佔用該設備的 handle
    struct mutex mutex;
    unsigned int users;              // 開啟該設備的使用者數
    struct class_device cdev;
    struct device *dev;
    int dynalloc;
    struct list_head h_list;         // 串接該設備關聯的 input_handle
    struct list_head node;           // 把設備串入 input_dev_list
};

這是個相當「全能」的結構,觸控螢幕、鍵盤、滑鼠的資訊它都想到了;對觸控螢幕而言只會用到其中一部分。特別注意最後兩個 list_head:

struct list_head {
    struct list_head *next, *prev;
};

它內部不存資料,只有兩個指向自身型別的指標。所有 input device 註冊後會掛進 input_dev_list,所有 handler 註冊後會掛進 input_handler_list,list_head 就是這兩條鏈表上的節點。而兩條鏈表之間的對應關係,由 input_handle 負責橋接。

input_handler:處理設備的人

struct input_handler {
    void *private;
    void (*event)(struct input_handle *handle, unsigned int type, unsigned int code, int value);
    struct input_handle* (*connect)(struct input_handler *handler, struct input_dev *dev, struct input_device_id *id);
    void (*disconnect)(struct input_handle *handle);
    const struct file_operations *fops;   // 提供給使用者操作設備的函式指標
    int minor;
    char *name;
    struct input_device_id *id_table;     // 與 input_dev 配對用的 id
    struct input_device_id *blacklist;
    struct list_head h_list;              // 串接與該 handler 相關的 handle
    struct list_head node;                // 把 handler 串入 input_handler_list
};

input_handle:把兩者牽在一起

struct input_handle {
    void *private;
    int open;                            // 記錄設備開啟次數
    char *name;
    struct input_dev *dev;               // 指向所屬的 input_dev
    struct input_handler *handler;       // 指向所屬的 input_handler
    struct list_head d_node;             // 串入 input_dev 的 handle 鏈表
    struct list_head h_node;             // 串入 input_handler 的 handle 鏈表
};

為什麼要多一層 handle,不讓 input_dev 與 input_handler 直接對應?因為關係是多對多:一個 device 可以對應多個 handler,一個 handler 也會處理多個 device。同一塊觸控螢幕,可能同時掛上 event handler 與 tsdev handler。

Linux 內核 Input 子系統入門:以觸控螢幕為例看資料怎麼從硬體走到使用者

圖 2 input_dev、input_handler、input_handle 關係圖

第二章、input device 的註冊

註冊本身只有幾行,因為 input.c 已經把重活封裝好了。在驅動 xxx_ts.c 裡先宣告全域變數,再於 probe 中初始化:

static int __init xxx_probe(struct platform_device *pdev)
{
    ...
    if (!(tsdev = input_allocate_device())) {
        printk(KERN_ERR "tsdev: not enough memory\n");
        err = -ENOMEM;
        goto fail;
    }
    tsdev->name = "xxx TouchScreen";
    tsdev->phys = "xxx/event0";
    tsdev->id.bustype = BUS_HOST;      // 用於匹配 handler 的 id
    tsdev->id.vendor  = 0x0005;
    tsdev->id.product = 0x0001;
    tsdev->id.version = 0x0100;
    tsdev->open  = xxx_open;
    tsdev->close = xxx_close;
    tsdev->evbit[0] = BIT(EV_KEY) | BIT(EV_ABS) | BIT(EV_SYN);
    tsdev->keybit[BIT(BTN_TOUCH)] = BIT(BTN_TOUCH);
    input_set_abs_params(tsdev, ABS_X, 0, 0x400, 0, 0);
    input_set_abs_params(tsdev, ABS_Y, 0, 0x400, 0, 0);
    input_set_abs_params(tsdev, ABS_PRESSURE, 0, 1000, 0, 0);
    ...
    if (input_register_device(tsdev))
        goto fail;
    ...
}

input_allocate_device() 做的事很單純——用 kzalloc 配置一塊 input_dev 記憶體,初始化 class device 與兩個鏈表頭:

struct input_dev *input_allocate_device(void)
{
    struct input_dev *dev;
    dev = kzalloc(sizeof(struct input_dev), GFP_KERNEL);
    if (dev) {
        dev->dynalloc = 1;
        dev->cdev.class = &input_class;
        class_device_initialize(&dev->cdev);
        INIT_LIST_HEAD(&dev->h_list);
        INIT_LIST_HEAD(&dev->node);
    }
    return dev;
}

kzalloc 相當於核心空間的 malloc,GFP_KERNEL 表示一般記憶體配置。

接著進入主題 input_register_device(),關鍵片段如下:

mutex_init(&dev->mutex);              // 互斥鎖,保護臨界區
set_bit(EV_SYN, dev->evbit);           // 所有 input 設備預設支援同步事件
INIT_LIST_HEAD(&dev->h_list);          // 初始化 handle 鏈表頭
list_add_tail(&dev->node, &input_dev_list);   // 掛入設備鏈表
...
/* 遍歷 input_handler_list,尋找能匹配的 handler */
list_for_each_entry(handler, &input_handler_list, node)
    if (!handler->blacklist || !input_match_device(handler->blacklist, dev))
        if ((id = input_match_device(handler->id_table, dev)))
            if ((handle = handler->connect(handler, dev, id)))
                input_link_handle(handle);

鏈表操作定義在 linux/list.h:INIT_LIST_HEAD 讓節點的 next/prev 都指向自己,list_add_tail 則把新節點插入鏈表頭之前。而 input_dev_list 與 input_handler_list 早在 input.c 開頭就以 LIST_HEAD 靜態定義好了,初始只有一個「哨兵」節點。

配對的關鍵是 input_match_device():它逐一比對 id 的 flags 所指定的欄位(bustype、vendor、product、version),再用 MATCH_BIT 比對 evbit、keybit、relbit、absbit 等能力位圖,任何一項不符即失敗——條件確實相當嚴苛。

配對成功後呼叫 handler 的 connect。以 evdev 為例:

static struct input_handler evdev_handler = {
    .event = evdev_event,
    .connect = evdev_connect,
    .disconnect = evdev_disconnect,
    .fops = &evdev_fops,
    .minor = EVDEV_MINOR_BASE,
    .name = "evdev",
    .id_table = evdev_ids,
};
static struct input_handle *evdev_connect(struct input_handler *handler,
                                          struct input_dev *dev,
                                          struct input_device_id *id)
{
    struct evdev *evdev;
    ...
    for (minor = 0; minor < EVDEV_MINORS && evdev_table[minor]; minor++);
    if (minor == EVDEV_MINORS) return NULL;

    if (!(evdev = kzalloc(sizeof(struct evdev), GFP_KERNEL)))
        return NULL;
    INIT_LIST_HEAD(&evdev->list);
    init_waitqueue_head(&evdev->wait);
    evdev->exist = 1;
    evdev->minor = minor;
    evdev->handle.dev = dev;
    evdev->handle.handler = handler;
    evdev->handle.private = evdev;     // 這個 private 稍後很重要
    sprintf(evdev->name, "event%d", minor);
    evdev_table[minor] = evdev;
    ...
    return &evdev->handle;
}

evdev_table[] 是一個大小為 EVDEV_MINORS(32)的全域指標陣列,用來存放該 handler 負責的多個設備實體——這正體現了「一個 handler 可處理多個 device」。最後 input_link_handle() 把 handle 的 d_node 與 h_node 分別掛進設備與 handler 的 h_list,三者關係就此成形。

第三章、input_handler 的註冊

handler 是與使用者層打交道的,因此 evdev 的 fops 就是一堆介面函式:

static struct file_operations evdev_fops = {
    .owner = THIS_MODULE,
    .read = evdev_read,
    .write = evdev_write,
    .poll = evdev_poll,
    .open = evdev_open,
    .release = evdev_release,
    .unlocked_ioctl = evdev_ioctl,
    .fasync = evdev_fasync,
    .flush = evdev_flush
};

static struct input_device_id evdev_ids[] = {
    { .driver_info = 1 },   /* Matches all devices */
    { },                    /* Terminating zero entry */
};
MODULE_DEVICE_TABLE(input, evdev_ids);

id_table 第一個條目只設了 driver_info,其餘欄位皆未定義,代表這個 handler 能匹配所有設備;第二個空條目作為結束哨兵。

static int __init evdev_init(void)
{
    input_register_handler(&evdev_handler);
    return 0;
}

input_register_handler() 的骨架與註冊設備時幾乎如出一轍:初始化 h_list、掛入 input_handler_list,然後反過來遍歷 input_dev_list 逐一嘗試配對與 connect。

第四章、資料結構全景

Linux 內核 Input 子系統入門:以觸控螢幕為例看資料怎麼從硬體走到使用者

圖 3 input 子系統資料結構圖

這裡出現了一個前面沒提的結構:

struct evdev_list {
    struct input_event buffer[EVDEV_BUFFER_SIZE];  // 存放設備資料
    int head;   // 寫入位置
    int tail;   // 讀取位置
    struct fasync_struct *fasync;
    struct evdev *evdev;
    struct list_head node;
};

struct input_event {
    struct timeval time;
    __u16 type;
    __u16 code;
    __s32 value;
};

buffer 就是使用者最終要拿到的資料。而 evdev_list 是在 open 時才配置的:

static int evdev_open(struct inode *inode, struct file *file)
{
    struct evdev_list *list;
    int i = iminor(inode) - EVDEV_MINOR_BASE;
    ...
    if (!(list = kzalloc(sizeof(struct evdev_list), GFP_KERNEL)))
        return -ENOMEM;
    list->evdev = evdev_table[i];
    list_add_tail(&list->node, &evdev_table[i]->list);
    file->private_data = list;
    if (!list->evdev->open++)
        if (list->evdev->exist)
            input_open_device(&list->evdev->handle);
    return 0;
}

input_open_device() 裡那句 handle->open++ 別小看它——後續資料傳遞時會判斷這個值是否為真,只有開過設備,資料才會被送出去。

第五章、資料怎麼從硬體走到核心

觸控螢幕的暫存器配置依各家 ARM 晶片 Datasheet 而定,這裡不展開。重點是取得座標之後如何上報。按下時:

input_report_key(tsdev, BTN_TOUCH, 1);
input_report_abs(tsdev, ABS_X, x);
input_report_abs(tsdev, ABS_Y, y);
input_report_abs(tsdev, ABS_PRESSURE, 1);
input_sync(tsdev);      // 同步事件,代表一輪資料結束

抬手時:

input_report_key(tsdev, BTN_TOUCH, 0);
input_report_abs(tsdev, ABS_PRESSURE, 0);
input_sync(tsdev);

這兩個 report 函式其實只是薄薄一層包裝:

static inline void input_report_key(struct input_dev *dev, unsigned int code, int value)
{ input_event(dev, EV_KEY, code, !!value); }

static inline void input_report_abs(struct input_dev *dev, unsigned int code, int value)
{ input_event(dev, EV_ABS, code, value); }

真正的重頭戲在 input_event()。它先確認事件類型與代碼都在設備支援的位圖內,接著針對 EV_KEY 與 EV_ABS 做去重、濾波(absfuzz 會對抖動值做加權平滑),最後是資料分發:

if (dev->grab)          // 有自訂處理函式(註冊階段通常沒有)
    dev->grab->handler->event(dev->grab, type, code, value);
else
    list_for_each_entry(handle, &dev->h_list, d_node)
        if (handle->open)   // 只有被開啟過的處理程序才收資料
            handle->handler->event(handle, type, code, value);

這裡就 answers 了上一章的伏筆:沒經過 evdev_open,handle->open 為 0,資料不會被送進去。

接著進入 evdev 的 event:

static void evdev_event(struct input_handle *handle, unsigned int type,
                        unsigned int code, int value)
{
    struct evdev *evdev = handle->private;   // connect 時已賦值
    struct evdev_list *list;
    ...
    list_for_each_entry(list, &evdev->list, node) {
        do_gettimeofday(&list->buffer[list->head].time);
        list->buffer[list->head].type  = type;
        list->buffer[list->head].code  = code;
        list->buffer[list->head].value = value;
        list->head = (list->head + 1) & (EVDEV_BUFFER_SIZE - 1);
        kill_fasync(&list->fasync, SIGIO, POLL_IN);
    }
    wake_up_interruptible(&evdev->wait);
}

資料填進 buffer、head 前進(到頭就繞回 0)、喚醒等待佇列。至此核心層的工作完成。

第六章、使用者空間怎麼讀

應用程式只要定義一個 input_event、open 設備、然後 read:

static ssize_t evdev_read(struct file *file, char __user *buffer,
                          size_t count, loff_t *ppos)
{
    struct evdev_list *list = file->private_data;
    int retval;

    if (count < evdev_event_size()) return -EINVAL;
    if (list->head == list->tail && list->evdev->exist
        && (file->f_flags & O_NONBLOCK)) return -EAGAIN;

    retval = wait_event_interruptible(list->evdev->wait,
             list->head != list->tail || (!list->evdev->exist));
    if (retval) return retval;
    if (!list->evdev->exist) return -ENODEV;

    while (list->head != list->tail && retval + evdev_event_size() < = count) {
        struct input_event *event = (struct input_event *) list->buffer + list->tail;
        if (evdev_event_to_user(buffer + retval, event))
            return -EFAULT;
        list->tail = (list->tail + 1) & (EVDEV_BUFFER_SIZE - 1);
        retval += evdev_event_size();
    }
    return retval;
}

最後一步就是 copy_to_user():把 event 指向的資料複製到使用者提供的緩衝區,回傳已讀位元組數。至於拿這些座標去做手勢還是畫線,那就是應用層的事了。

介面裡雖然也有 write、ioctl,但對觸控螢幕而言我們要的只是筆尖座標,因此很少用到,這裡不再展開。


【說明】本文僅在作者理解範圍內對 input 子系統做入門介紹,仍有許多細節未能觸及;它適合在既有框架下修改驅動,但不足以支撐從零開發一個完整驅動。

Copyright © Linux教程網 All Rights Reserved