Linux 輸入(input)子系統架構分析

 內核的輸入子系統是對分散的,多種不同類別的輸入設備(如鍵盤,鼠標,跟蹤球,操縱桿,觸摸屏,加速計和手寫板)等字符設備進行統一處理的一層抽象,就是在字符設備驅動上抽象出的一層。輸入子系統包括兩類驅動程序:事件驅動程序和設備驅動程序。事件驅動程序負責和應用程序的接口,而設備驅動程序負責和底層輸入設備的通信。鼠標事件生成文件mousedev屬於事件驅動程序,而PS/2鼠標驅動程序是設備驅動程序。事件驅動程序是標準的,對所有的輸入類都是可用的,所以要實現的是設備驅動程序而不是事件驅動程序。設備驅動程序可以利用一個已經存在的,合適的事件驅動程序通過輸入核心和用戶應用程序接口。
輸入子系統帶來了如下好處:
1.統一了物理形態各異的相似的輸入設備的處理功能
2.提供了用於分發輸入報告給用戶應用程序的簡單的事件接口
3.抽取出了輸入驅動程序的通用部分,簡化了驅動,並引入了一致性

       現在 Android、X windows、qt等衆多應用對於linux系統中鍵盤、鼠標、觸摸屏等輸入設備的支持都通過、或越來越傾向於標準的input輸入子系統。因爲input子系統已經完成了字符驅動的文件操作接口,所以編寫驅動的核心工作是完成input系統留出的接口,工作量不大。但如果你想更靈活的應用它,就需要好好的分析下input子系統了。


先來看一下輸入子系統體系架構圖:


再對照下圖(input輸入子系統框架),很清楚的知道輸入子系統是由輸入子系統核心層( Input Core ),驅動層和事件處理層(Event Handler)三部份組成。一個輸入事件,如鼠標移動,鍵盤按鍵按下,joystick的移動等等通過 input driver -> Input core -> Event handler -> userspace 到達用戶空間傳給應用程序。

注意:keyboard.c不會在/dev/input下產生節點,而是作爲ttyn終端(不包括串口終端)的輸入。

設備描述
       在linux內核中,input設備用input_dev結構體描述,使用input子系統實現輸入設備驅動的時候,驅動的核心工作是向系統報告按鍵、觸摸屏、鍵盤、鼠標等輸入事件(event,通過input_event結構體描述),一再需要關心文件操作接口,因爲input子系統已經完成了文件操作接口。驅動報告的事件經過InputCore和EventHandler最終到達用戶空間。
現在瞭解了input子系統的基本思想,下面來看一下input子系統的3個基本的數據結構:
  1. struct input_dev {  
  2.     const char *name;     //名稱                              
  3.     const char *phys;  //設備在系統中的物理路徑
  4.     const char *uniq;  //設備唯一識別符
  5.     struct input_id id; //設備ID,包含總線ID(PCI、USB)、廠商ID,與input_handler匹配的時會用到  
  6.   
  7.     unsigned long evbit[BITS_TO_LONGS(EV_CNT)];     //支持的所有事件類型  
  8.     unsigned long keybit[BITS_TO_LONGS(KEY_CNT)];   //支持的鍵盤事件  
  9.     unsigned long relbit[BITS_TO_LONGS(REL_CNT)];   //支持的鼠標相對值事件  
  10.     unsigned long absbit[BITS_TO_LONGS(ABS_CNT)];   //支持的鼠標絕對值事件  
  11.     unsigned long mscbit[BITS_TO_LONGS(MSC_CNT)];   //支持的其它事件類型  
  12.     unsigned long ledbit[BITS_TO_LONGS(LED_CNT)];   //支持的LED燈事件  
  13.     unsigned long sndbit[BITS_TO_LONGS(SND_CNT)];   //支持的聲效事件 
  14.     unsigned long ffbit[BITS_TO_LONGS(FF_CNT)];     //支持的力反饋事件  
  15.     unsigned long swbit[BITS_TO_LONGS(SW_CNT)];     //支持的開關事件  
  16.   
  17.     unsigned int keycodemax;  //keycode表的大小
  18.     unsigned int keycodesize;  //keycode表中元素個數
  19.     void *keycode;  //設備的鍵盤表
  20.     int (*setkeycode)(struct input_dev *dev, int scancode, int keycode);//配置keycode表  
  21.     int (*getkeycode)(struct input_dev *dev, int scancode, int *keycode);//獲取keycode表  
  22.   
  23.     struct ff_device *ff;  
  24.   
  25.     unsigned int repeat_key;//保存上一個鍵值  
  26.     struct timer_list timer;  
  27.   
  28.     int sync;  
  29.   
  30.     int abs[ABS_MAX + 1];             //絕對座標上報的當前值  
  31.     int rep[REP_MAX + 1];             //這個參數主要是處理重複按鍵,後面遇到再講  
  32.     unsigned long key[BITS_TO_LONGS(KEY_CNT)]; //按鍵有兩種狀態,按下和擡起,這個字段就是記錄這兩個狀態。  
  33.     unsigned long led[BITS_TO_LONGS(LED_CNT)];  
  34.     unsigned long snd[BITS_TO_LONGS(SND_CNT)];  
  35.     unsigned long sw[BITS_TO_LONGS(SW_CNT)];  
  36.   
  37.     int absmax[ABS_MAX + 1];           //絕對座標的最大值  
  38.     int absmin[ABS_MAX + 1];       //絕對座標的最小值  
  39.     int absfuzz[ABS_MAX + 1];            
  40.     int absflat[ABS_MAX + 1];            
  41.     //操作接口
  42.     int (*open)(struct input_dev *dev);  
  43.     void (*close)(struct input_dev *dev);  
  44.     int (*flush)(struct input_dev *dev, struct file *file);  
  45.     int (*event)(struct input_dev *dev, unsigned int type, unsigned int code, int value);  
  46.   
  47.     struct input_handle *grab;         //當前使用的handle  
  48.   
  49.     spinlock_t event_lock;  
  50.     struct mutex mutex;  
  51.   
  52.     unsigned int users;  
  53.     int going_away;  
  54.   
  55.     struct device dev;  
  56.   
  57.     struct list_head    h_list;    //h_list是一個鏈表頭,用來把handle掛載在這個上  
  58.     struct list_head    node;      //這個node是用來連到input_dev_list上的  
  59. };  
  60.  // input_dev->evbit表示設備支持的事件類型,可以是下列值的組合
           #define EV_SYN           0x00  //同步事件
            #define EV_KEY           0x01 //絕對二進制值,如鍵盤或按鈕
            #define EV_REL           0x02 //絕對結果,如鼠標設備
            #define EV_ABS           0x03 //絕對整數值,如操縱桿或書寫板
            #define EV_MSC          0x04 //其它類
            #define EV_SW            0x05 //開關事件
            #define EV_LED          0x11 //LED或其它指示設備
            #define EV_SND         0x12 //聲音輸出,如蜂鳴器
            #define EV_REP         0x14 //允許按鍵自重複
            #define EV_FF             0x15 //力反饋
            #define EV_PWR        0x16 //電源管理事件
    include/linux/input.h中定義了支持的類型
  61. struct input_handler {  
  62.   
  63.     void *private;  
  64.   
  65.     void (*event)(struct input_handle *handle, unsigned int type, unsigned int code, int value);  
  66.     int (*connect)(struct input_handler *handler, struct input_dev *dev, const struct input_device_id *id);  
  67.     void (*disconnect)(struct input_handle *handle);  
  68.     void (*start)(struct input_handle *handle);  
  69.   
  70.     const struct file_operations *fops;  
  71.     int minor;                               //次設備號  
  72.     const char *name;  
  73.   
  74.     const struct input_device_id *id_table;  
  75.     const struct input_device_id *blacklist;  
  76.   
  77.     struct list_head    h_list;    //h_list是一個鏈表頭,用來把handle掛載在這個上  
  78.     struct list_head    node;      //這個node是用來連到input_handler_list上的  
  79. };  
  80.   
  81. struct input_handle {  
  82.   
  83.     void *private;  
  84.   
  85.     int open;  
  86.     const char *name;  
  87.   
  88.     struct input_dev *dev;              //指向input_dev  
  89.     struct input_handler *handler;      //指向input_handler  
  90.   
  91.     struct list_head    d_node;     //連到input_dev的h_list上  
  92.     struct list_head    h_node;     //連到input_handler的h_list上  
  93. };  
如下圖代表了input_dev,input_handler,input_handle,3者之間的關係。一類handler可以和多個硬件設備相關聯,一個硬件設備可以和多個handler相關聯。例如:一個觸摸屏設備可以作爲一個event設備,作爲一個鼠標設備,也可以作爲一個觸摸設備,所以一個設備需要與多個平臺驅動進行連接。而一個平臺驅動也不只爲一個設備服務,一個觸摸平臺驅動可能要爲A,B,C3個觸摸設備提供上層驅動,所以需要這樣一對多的連接。


下面來看看input字符設備註冊過程:

  1. static int __init input_init(void)  
  2. {  
  3.     int err;  
  4.   
  5.     input_init_abs_bypass();  
  6.     /*創建一個類input_class*/  
  7.     err = class_register(&input_class);                       
  8.     if (err) {  
  9.         printk(KERN_ERR "input: unable to register input_dev class/n");  
  10.         return err;  
  11.     }  
  12.     /*在/proc下創建入口項*/  
  13.     err = input_proc_init();  
  14.     if (err)  
  15.         goto fail1;  
  16.     /*註冊設備號INPUT_MAJOR的設備,記住input子系統的設備的主設備號都是13,即INPUT_MAJOR爲13,並與input_fops相關聯*/  
  17.     err = register_chrdev(INPUT_MAJOR, "input", &input_fops);       
  18.     if (err) {  
  19.         printk(KERN_ERR "input: unable to register char major %d", INPUT_MAJOR);  
  20.         goto fail2;  
  21.     }  
  22.   
  23.     return 0;  
  24.   
  25.  fail2: input_proc_exit();  
  26.  fail1: class_unregister(&input_class);  
  27.     return err;  
  28. }  
  29. subsys_initcall(input_init);  
下面來看input子系統的file_operations,這裏只有一個打開函數input_open_file,這個在事件傳遞部分講解。
  1. static const struct file_operations input_fops = {  
  2.     .owner = THIS_MODULE,  
  3.     .open = input_open_file,  
  4. };  
下邊來看input_dev設備的註冊:
  1. int input_register_device(struct input_dev *dev)  
  2. {  
  3.     static atomic_t input_no = ATOMIC_INIT(0);  
  4.     struct input_handler *handler;  
  5.     const char *path;  
  6.     int error;  
  7.   
  8.     __set_bit(EV_SYN, dev->evbit);  
  9.   
  10.     /* 
  11.      * If delay and period are pre-set by the driver, then autorepeating 
  12.      * is handled by the driver itself and we don't do it in input.c. 
  13.      */  
  14.   
  15.     init_timer(&dev->timer);  
  16.     /*  
  17.      *rep主要是處理重複按鍵,如果沒有定義dev->rep[REP_DELAY]和dev->rep[REP_PERIOD], 
  18.      *則將其賦值爲默認值。dev->rep[REP_DELAY]是指第一次按下多久算一次,這裏是250ms, 
  19.      *dev->rep[REP_PERIOD]指如果按鍵沒有被擡起,每33ms算一次。 
  20.      */  
  21.     if (!dev->rep[REP_DELAY] && !dev->rep[REP_PERIOD]) {  
  22.         dev->timer.data = (long) dev;  
  23.         dev->timer.function = input_repeat_key;  
  24.         dev->rep[REP_DELAY] = 250;  
  25.         dev->rep[REP_PERIOD] = 33;  
  26.     }  
  27.     /*如果dev沒有定義getkeycode和setkeycode,則賦默認值。他們的作用一個是獲得鍵的掃描碼,一個是設置鍵的掃描碼*/  
  28.     if (!dev->getkeycode)  
  29.         dev->getkeycode = input_default_getkeycode;  
  30.   
  31.     if (!dev->setkeycode)  
  32.         dev->setkeycode = input_default_setkeycode;  
  33.   
  34.     dev_set_name(&dev->dev, "input%ld",  
  35.              (unsigned long) atomic_inc_return(&input_no) - 1);  
  36.     /*將input_dev封裝的dev註冊到sysfs*/  
  37.     error = device_add(&dev->dev);  
  38.     if (error)  
  39.         return error;  
  40.   
  41.     path = kobject_get_path(&dev->dev.kobj, GFP_KERNEL);  
  42.     printk(KERN_INFO "input: %s as %s/n",  
  43.         dev->name ? dev->name : "Unspecified device", path ? path : "N/A");  
  44.     kfree(path);  
  45.   
  46.     error = mutex_lock_interruptible(&input_mutex);  
  47.     if (error) {  
  48.         device_del(&dev->dev);  
  49.         return error;  
  50.     }  
  51.     /*將input_dev掛在input_dev_list上*/  
  52.     list_add_tail(&dev->node, &input_dev_list);  
  53.     /*匹配所有的input_handler,這個就是剛纔那幅圖裏的一個設備對應多個handler的由來*/  
  54.     list_for_each_entry(handler, &input_handler_list, node)  
  55.         input_attach_handler(dev, handler);  
  56.   
  57.     input_wakeup_procfs_readers();  
  58.   
  59.     mutex_unlock(&input_mutex);  
  60.   
  61.     return 0;  
  62. }  
跟蹤程序,來看看input_attach_handler的實現:
  1. static int input_attach_handler(struct input_dev *dev, struct input_handler *handler)  
  2. {  
  3.     const struct input_device_id *id;  
  4.     int error;  
  5.     /*handler有一個黑名單,如果存在黑名單,並且這個id匹配就退出*/  
  6.     if (handler->blacklist && input_match_device(handler->blacklist, dev))  
  7.         return -ENODEV;  
  8.     /*匹配id,實現在下邊可以看到*/  
  9.     id = input_match_device(handler->id_table, dev);  
  10.     if (!id)  
  11.         return -ENODEV;  
  12.     /*如果匹配,則調用具體的handler的connect函數*/  
  13.     error = handler->connect(handler, dev, id);  
  14.     if (error && error != -ENODEV)  
  15.         printk(KERN_ERR  
  16.             "input: failed to attach handler %s to device %s, "  
  17.             "error: %d/n",  
  18.             handler->name, kobject_name(&dev->dev.kobj), error);  
  19.   
  20.     return error;  
  21. }  
下邊來看看這個匹配函數:如果id->flags存在,並且相應的標誌爲被設定則進行比較。
  1. static const struct input_device_id *input_match_device(const struct input_device_id *id,  
  2.                             struct input_dev *dev)  
  3. {  
  4.     int i;  
  5.   
  6.     for (; id->flags || id->driver_info; id++) {  
  7.   
  8.         if (id->flags & INPUT_DEVICE_ID_MATCH_BUS)  
  9.             if (id->bustype != dev->id.bustype)  
  10.                 continue;  
  11.   
  12.         if (id->flags & INPUT_DEVICE_ID_MATCH_VENDOR)  
  13.             if (id->vendor != dev->id.vendor)  
  14.                 continue;  
  15.   
  16.         if (id->flags & INPUT_DEVICE_ID_MATCH_PRODUCT)  
  17.             if (id->product != dev->id.product)  
  18.                 continue;  
  19.   
  20.         if (id->flags & INPUT_DEVICE_ID_MATCH_VERSION)  
  21.             if (id->version != dev->id.version)  
  22.                 continue;  
  23.   
  24.         MATCH_BIT(evbit,  EV_MAX);  
  25.         MATCH_BIT(keybit, KEY_MAX);  
  26.         MATCH_BIT(relbit, REL_MAX);  
  27.         MATCH_BIT(absbit, ABS_MAX);  
  28.         MATCH_BIT(mscbit, MSC_MAX);  
  29.         MATCH_BIT(ledbit, LED_MAX);  
  30.         MATCH_BIT(sndbit, SND_MAX);  
  31.         MATCH_BIT(ffbit,  FF_MAX);  
  32.         MATCH_BIT(swbit,  SW_MAX);  
  33.   
  34.         return id;  
  35.     }  
  36.   
  37.     return NULL;  
  38. }  
  1. #define MATCH_BIT(bit, max) /  
  2.         for (i = 0; i < BITS_TO_LONGS(max); i++) /  
  3.             if ((id->bit[i] & dev->bit[i]) != id->bit[i]) /  
  4.                 break; /  
  5.         if (i != BITS_TO_LONGS(max)) /  
  6.             continue
Input_dev和input_handler匹配後調用input_handler的connect。以evdev_handler爲例:如果匹配上了就會創建一個evdev,它裏邊封裝了一個handle,會把input_dev和input_handler關聯到一起。
  1. /* 
  2.  * Create new evdev device. Note that input core serializes calls 
  3.  * to connect and disconnect so we don't need to lock evdev_table here. 
  4.  */  
  5. static int evdev_connect(struct input_handler *handler, struct input_dev *dev,  
  6.              const struct input_device_id *id)  
  7. {  
  8.     struct evdev *evdev;  
  9.     int minor;  
  10.     int error;  
  11.     /* 
  12.      *首先補充幾個知識點: 
  13.      *static struct input_handler *input_table[8]; 
  14.      *#define INPUT_DEVICES 256 
  15.      *一共有8個input_handler,對應256個設備,所以一個handler對應32個設備。 
  16.      *這個問題在我參加的一次linux驅動的面試中被問到,當時真是汗啊!!! 
  17.      *static struct evdev *evdev_table[EVDEV_MINORS]; 
  18.      *#define EVDEV_MINORS  32 
  19.      *evdev理論上可對應32個設備,其對應的設備節點一般位於/dev/input/event0~/dev/input/event4 
  20.      *下邊的for循環,在evdev_table數組中找一個未使用的地方  
  21.      */  
  22.     for (minor = 0; minor < EVDEV_MINORS; minor++)  
  23.         if (!evdev_table[minor])  
  24.             break;  
  25.   
  26.     if (minor == EVDEV_MINORS) {  
  27.         printk(KERN_ERR "evdev: no more free evdev devices/n");  
  28.         return -ENFILE;  
  29.     }  
  30.     /*下邊的代碼是爲每一個匹配的設備分配一個evdev結構體,並對成員進行初始化*/  
  31.     evdev = kzalloc(sizeof(struct evdev), GFP_KERNEL);  
  32.     if (!evdev)  
  33.         return -ENOMEM;  
  34.   
  35.     INIT_LIST_HEAD(&evdev->client_list);  
  36.     spin_lock_init(&evdev->client_lock);  
  37.     mutex_init(&evdev->mutex);  
  38.     init_waitqueue_head(&evdev->wait);  
  39.   
  40.     snprintf(evdev->name, sizeof(evdev->name), "event%d", minor);  
  41.     evdev->exist = 1;  
  42.     evdev->minor = minor;  
  43.   
  44.     evdev->handle.dev = input_get_device(dev);  
  45.     evdev->handle.name = evdev->name;  
  46.     evdev->handle.handler = handler;  
  47.     evdev->handle.private = evdev;  
  48.   
  49.     dev_set_name(&evdev->dev, evdev->name);  
  50.     evdev->dev.devt = MKDEV(INPUT_MAJOR, EVDEV_MINOR_BASE + minor);  
  51.     evdev->dev.class = &input_class; /*調用函數創建字符設備節點*/   
  52.     evdev->dev.parent = &dev->dev;  
  53.     evdev->dev.release = evdev_free;  
  54.     /**/  
  55.     device_initialize(&evdev->dev);  
  56.     /* 
  57.          *input_register_handle完成的主要功能是: 
  58.          *list_add_tail_rcu(&handle->d_node, &dev->h_list); 
  59.      *list_add_tail(&handle->h_node, &handler->h_list); 
  60.      */  
  61.     error = input_register_handle(&evdev->handle);  
  62.     if (error)  
  63.         goto err_free_evdev;  
  64.     /*evdev_install_chrdev完成的功能是evdev_table[evdev->minor]=evdev;*/  
  65.     error = evdev_install_chrdev(evdev);  
  66.     if (error)  
  67.         goto err_unregister_handle;  
  68.   
  69.     error = device_add(&evdev->dev);  
  70.     if (error)  
  71.         goto err_cleanup_evdev;  
  72.   
  73.     return 0;  
  74.     。。。。。。。。。。  
  75. }  
input子系統最重要的部分就是向上層report了。這裏還是先介紹幾個數據結構:
  1. struct input_event {  
  2.     struct timeval time;  //事件發生的時間  
  3.     __u16 type;           //事件類型  
  4.     __u16 code;           //子事件  
  5.     __s32 value;          //事件的value  
  6. };  

  1. struct evdev_client {  
  2.     struct input_event buffer[EVDEV_BUFFER_SIZE];        //可以同時管理EVDEV_BUFFER_SIZE(64)個事件  
  3.     int head;                                            //存儲事件從head開始  
  4.     int tail;                                            //取出事件從tail開始  
  5.     spinlock_t buffer_lock; /* protects access to buffer, head and tail */     
  6.     struct fasync_struct *fasync;                        //異步通知事件發生  
  7.     struct evdev *evdev;                                 //指向本evdev_client歸屬的evdev  
  8.     struct list_head node;                               //用於掛載到evdev的鏈表頭client_list上  
  9. };  

  1. static struct input_handler evdev_handler = {  
  2.     .event      = evdev_event,  //向系統報告input事件,系統通過read方法讀取
  3.     .connect    = evdev_connect,   //和input_dev匹配後調用connect構建
  4.     .disconnect = evdev_disconnect,  
  5.     .fops       = &evdev_fops, //event設備文件的操作方法 
  6.     .minor      = EVDEV_MINOR_BASE,//次設備號基準值  
  7.     .name       = "evdev",  
  8.     .id_table   = evdev_ids,  //匹配規則 
  9. };  
這裏的次設備號是EVDEV_MINOR_BASE(64),也就是說evdev_handler所表示的設備文件範圍(13,64)~(13,64+32)。
如下一個結構體:evdev_handler匹配所有設備。
  1. static const struct input_device_id evdev_ids[] = {  
  2.     { .driver_info = 1 },   /* Matches all devices */  
  3.     { },            /* Terminating zero entry */  
  4. };  
看一下這張圖會對上邊的結構有清楚的認知了:

這個是evdev_handler是fops,下面的講解中會用到其中的open,read函數。
  1. static const struct file_operations evdev_fops = {  
  2.     .owner      = THIS_MODULE,  
  3.     .read       = evdev_read,  
  4.     .write      = evdev_write,  
  5.     .poll       = evdev_poll,  
  6.     .open       = evdev_open,  
  7.     .release    = evdev_release,  
  8.     .unlocked_ioctl = evdev_ioctl,  
  9. #ifdef CONFIG_COMPAT  
  10.     .compat_ioctl   = evdev_ioctl_compat,  
  11. #endif  
  12.     .fasync     = evdev_fasync,  
  13.     .flush      = evdev_flush  
  14. };  
在驅動程序中我們會調用input_report_abs等函數:

設備驅動通過宏set_bit()告訴input子系統它支持哪些事件,如下所示
set_bit(EV_KEY, input_dev->keybit); //EV_KEY事件支持的事件碼
struct input_dev中有兩個成員,一個是unsigned long evbit,一個是unsigned long keybit,分別用來表示設備所支持的事件類型和按鍵類型。 

用於報告EV_KEY、EV_REL、EV_ABS、EV_FF、EV_SW等事件的函數有:

        void input_report_key(struct input_dev *dev, unsigned int code, int value)
        void input_report_rel(struct input_dev *dev, unsigned int code, int value)
        void input_report_abs(struct input_dev *dev, unsigned int code, int value)
         void input_report_ff_status(struct input_dev *dev, unsigned int code, int value)

        void input_report_switch(struct input_dev *dev, unsigned int code, int value)     

如果你覺得麻煩,你也可以只記住1個函數(因爲上述函數都是通過它實現的)

void input_event(struct input_dev *dev, unsigned int type, unsigned int code, int value)

相關參數介紹:
code:
事件的代碼。如果事件的類型是EV_KEY,該代碼code爲設備鍵盤代碼。代碼值0-127爲鍵盤上的按鍵代碼,0x110-0x116爲鼠標上按鍵代碼,其中0x110(BTN_LEFT)爲鼠標左鍵,0x111(BTN_RIGHT)爲鼠標右鍵,0x112(BTN_MIDDLE)爲鼠標中鍵。其它代碼含義請參看include/linux/input.h文件。

value:
事件的值。如果事件的類型是EV_KEY,當按鍵按下時值爲1,鬆開時值爲0.

事件報告完畢後,設備驅動需要使用input_sync函數告訴輸入子系統一個完整的報告已經發送。
void input_sync(struct input_dev *dev)
{
      input_event(dev,EV_SYN,SYN_REPORT,0);
}
這一點在鼠標移動處理中很重要,因爲鼠標座標的X分量和Y分量是分開傳送的,需要利用input_sync函數來同步。
跟蹤input_event如下:
  1. void input_event(struct input_dev *dev,  
  2.          unsigned int type, unsigned int code, int value)  
  3. {  
  4.     unsigned long flags;  
  5.   
  6.     if (is_event_supported(type, dev->evbit, EV_MAX)) {  
  7.   
  8.         spin_lock_irqsave(&dev->event_lock, flags);  
  9.         /*利用輸入值調正隨機數產生器*/  
  10.         add_input_randomness(type, code, value);  
  11.         input_handle_event(dev, type, code, value);  
  12.         spin_unlock_irqrestore(&dev->event_lock, flags);  
  13.     }  
  14. }  
跟蹤input_handle_event如下:
  1. static void input_handle_event(struct input_dev *dev,  
  2.                    unsigned int type, unsigned int code, int value)  
  3. {  
  4.     int disposition = INPUT_IGNORE_EVENT;  
  5.   
  6.     switch (type) {  
  7.     。。。。。。。。。。。。。。。。  
  8.     if (disposition != INPUT_IGNORE_EVENT && type != EV_SYN)  
  9.         dev->sync = 0;  
  10.   
  11.     if ((disposition & INPUT_PASS_TO_DEVICE) && dev->event)  
  12.         dev->event(dev, type, code, value);  
  13.   
  14.     if (disposition & INPUT_PASS_TO_HANDLERS)  
  15.         input_pass_event(dev, type, code, value);  
  16. }  
如果該事件需要input device來完成,就會將disposition設置成INPUT_PASS_TO_DEVICE,如果需要input handler來完成,就會將disposition設置成INPUT_PASS_TO_DEVICE,如果需要兩者都參與,則將disposition設置成INPUT_PASS_TO_ALL。
跟蹤input_pass_event如下:
  1. static void input_pass_event(struct input_dev *dev,  
  2.                  unsigned int type, unsigned int code, int value)  
  3. {  
  4.     struct input_handle *handle;  
  5.   
  6.     rcu_read_lock();  
  7.     /**/  
  8.     handle = rcu_dereference(dev->grab);  
  9.     if (handle)  
  10.         /*如果input_dev的grab指向了一個handle,就用這個handle關聯的handler的event,否則遍歷整個掛在input_dev的h_list上的handle關聯的handler*/  
  11.         handle->handler->event(handle, type, code, value);  
  12.     else  
  13.         list_for_each_entry_rcu(handle, &dev->h_list, d_node)  
  14.             if (handle->open)  
  15.                 handle->handler->event(handle,  
  16.                             type, code, value);  
  17.     rcu_read_unlock();  
  18. }  
比如下邊的evdev_handler的evdev_event:
  1. static void evdev_event(struct input_handle *handle,  
  2.             unsigned int type, unsigned int code, int value)  
  3. {  
  4.     struct evdev *evdev = handle->private;  
  5.     struct evdev_client *client;  
  6.     struct input_event event;  
  7.   
  8.     do_gettimeofday(&event.time);  
  9.     event.type = type;  
  10.     event.code = code;  
  11.     event.value = value;  
  12.   
  13.     rcu_read_lock();  
  14.     client = rcu_dereference(evdev->grab);  
  15.     if (client)  
  16.     /*如果evdev->grab指向一個當前使用的client就將event放到這個client的buffer中,否則放到整個client_list上的client的鏈表中*/  
  17.         evdev_pass_event(client, &event);  
  18.     else  
  19.         list_for_each_entry_rcu(client, &evdev->client_list, node)  
  20.             evdev_pass_event(client, &event);  
  21.   
  22.     rcu_read_unlock();  
  23.   
  24.     wake_up_interruptible(&evdev->wait);  
  25. }  
  1. static void evdev_pass_event(struct evdev_client *client,  
  2.                  struct input_event *event)  
  3. {  
  4.     /* 
  5.      * Interrupts are disabled, just acquire the lock 
  6.      */  
  7.     spin_lock(&client->buffer_lock);  
  8.     /*將event裝入client的buffer中,buffer是一個環形緩存區*/  
  9.     client->buffer[client->head++] = *event;  
  10.     client->head &= EVDEV_BUFFER_SIZE - 1;  
  11.     spin_unlock(&client->buffer_lock);  
  12.   
  13.     kill_fasync(&client->fasync, SIGIO, POLL_IN);  
  14. }  

這裏總結一下事件的傳遞過程:首先在驅動層中,調用inport_report_abs,然後他調用了input core層的input_event,input_event調用了input_handle_event對事件進行分派,調用input_pass_event,在這裏他會把事件傳遞給具體的handler層,然後在相應handler的event處理函數中,封裝一個event,然後把它投入evdev的那個client_list上的client的事件buffer中,等待用戶空間來讀取。

當用戶空間打開設備節點/dev/input/event0~/dev/input/event4的時候,會使用input_fops中的input_open_file()函數,input_open_file()->evdev_open()(如果handler是evdev的話)->evdev_open_device()->input_open_device()->dev->open()。也就是struct file_operations input_fops提供了通用接口,最終會調用具體input_dev的open函數。下邊看一下用戶程序打開文件時的過程,首先調用了input_open_file:

  1. static int input_open_file(struct inode *inode, struct file *file)  
  2. {  
  3.     struct input_handler *handler;  
  4.     const struct file_operations *old_fops, *new_fops = NULL;  
  5.     int err;  
  6.   
  7.     lock_kernel();  
  8.     /* No load-on-demand here? */  
  9.     /*因爲32個input_dev公共一個handler所以低5位應該是相同的*/  
  10.     handler = input_table[iminor(inode) >> 5];  
  11.     if (!handler || !(new_fops = fops_get(handler->fops))) {  
  12.         err = -ENODEV;  
  13.         goto out;  
  14.     }  
  15.   
  16.     /* 
  17.      * That's _really_ odd. Usually NULL ->open means "nothing special", 
  18.      * not "no device". Oh, well... 
  19.      */  
  20.     if (!new_fops->open) {  
  21.         fops_put(new_fops);  
  22.         err = -ENODEV;  
  23.         goto out;  
  24.     }  
  25.     /*保存以前的fops,使用相應的handler的fops*/  
  26.     old_fops = file->f_op;  
  27.     file->f_op = new_fops;  
  28.   
  29.     err = new_fops->open(inode, file);  
  30.   
  31.     if (err) {  
  32.         fops_put(file->f_op);  
  33.         file->f_op = fops_get(old_fops);  
  34.     }  
  35.     fops_put(old_fops);  
  36. out:  
  37.     unlock_kernel();  
  38.     return err;  
  39. }  

這裏還是假設handler是evdev_handler。
  1. static int evdev_open(struct inode *inode, struct file *file)  
  2. {  
  3.     struct evdev *evdev;  
  4.     struct evdev_client *client;  
  5.     /*因爲次設備號是從EVDEV_MINOR_BASE開始的*/  
  6.     int i = iminor(inode) - EVDEV_MINOR_BASE;  
  7.     int error;  
  8.       
  9.     if (i >= EVDEV_MINORS)  
  10.         return -ENODEV;  
  11.   
  12.     error = mutex_lock_interruptible(&evdev_table_mutex);  
  13.     if (error)  
  14.         return error;  
  15.     /*evdev_table一共可容納32個成員,找到次設備號對應的那個*/  
  16.     evdev = evdev_table[i];  
  17.     if (evdev)  
  18.         get_device(&evdev->dev);  
  19.     mutex_unlock(&evdev_table_mutex);  
  20.   
  21.     if (!evdev)  
  22.         return -ENODEV;  
  23.     /*打開的時候創建一個client*/  
  24.     client = kzalloc(sizeof(struct evdev_client), GFP_KERNEL);  
  25.     if (!client) {  
  26.         error = -ENOMEM;  
  27.         goto err_put_evdev;  
  28.     }  
  29.   
  30.     spin_lock_init(&client->buffer_lock);  
  31.     /*下邊兩句的作用就是將evdev和client綁定到一起*/  
  32.     client->evdev = evdev;  
  33.     evdev_attach_client(evdev, client);  
  34.   
  35.     error = evdev_open_device(evdev);  
  36.     if (error)  
  37.         goto err_free_client;  
  38.     /*將file->private_data指向剛剛建的client,後邊會用到的*/  
  39.     file->private_data = client;  
  40.     return 0;  
  41.   
  42.  err_free_client:  
  43.     evdev_detach_client(evdev, client);  
  44.     kfree(client);  
  45.  err_put_evdev:  
  46.     put_device(&evdev->dev);  
  47.     return error;  
  48. }  

  1. static int evdev_open_device(struct evdev *evdev)  
  2. {  
  3.     int retval;  
  4.   
  5.     retval = mutex_lock_interruptible(&evdev->mutex);  
  6.     if (retval)  
  7.         return retval;  
  8.     /*如果設備不存在,返回錯誤*/  
  9.     if (!evdev->exist)  
  10.         retval = -ENODEV;  
  11.     /*如果是被第一次打開,則調用input_open_device*/  
  12.     else if (!evdev->open++) {  
  13.         retval = input_open_device(&evdev->handle);  
  14.         if (retval)  
  15.             evdev->open--;  
  16.     }  
  17.   
  18.     mutex_unlock(&evdev->mutex);  
  19.     return retval;  
  20. }  

  1. int input_open_device(struct input_handle *handle)  
  2. {  
  3.     struct input_dev *dev = handle->dev;  
  4.     int retval;  
  5.   
  6.     retval = mutex_lock_interruptible(&dev->mutex);  
  7.     if (retval)  
  8.         return retval;  
  9.   
  10.     if (dev->going_away) {  
  11.         retval = -ENODEV;  
  12.         goto out;  
  13.     }  
  14.   
  15.     handle->open++;  
  16.   
  17.     if (!dev->users++ && dev->open)  
  18.         retval = dev->open(dev);  
  19.   
  20.     if (retval) {  
  21.         dev->users--;  
  22.         if (!--handle->open) {  
  23.             /* 
  24.              * Make sure we are not delivering any more events 
  25.              * through this handle 
  26.              */  
  27.             synchronize_rcu();  
  28.         }  
  29.     }  
  30.   
  31.  out:  
  32.     mutex_unlock(&dev->mutex);  
  33.     return retval;  
  34. }  
下面是用戶進程讀取event的底層實現:
  1. static ssize_t evdev_read(struct file *file, char __user *buffer,  
  2.               size_t count, loff_t *ppos)  
  3. {  
  4.     /*這個就是剛纔在open函數中*/  
  5.     struct evdev_client *client = file->private_data;  
  6.     struct evdev *evdev = client->evdev;  
  7.     struct input_event event;  
  8.     int retval;  
  9.   
  10.     if (count < input_event_size())  
  11.         return -EINVAL;  
  12.     /*如果client的環形緩衝區中沒有數據並且是非阻塞的,那麼返回-EAGAIN,也就是try again*/  
  13.     if (client->head == client->tail && evdev->exist &&  
  14.         (file->f_flags & O_NONBLOCK))  
  15.         return -EAGAIN;  
  16.     /*如果沒有數據,並且是阻塞的,則在等待隊列上等待吧*/  
  17.     retval = wait_event_interruptible(evdev->wait,  
  18.         client->head != client->tail || !evdev->exist);  
  19.     if (retval)  
  20.         return retval;  
  21.   
  22.     if (!evdev->exist)  
  23.         return -ENODEV;  
  24.     /*如果獲得了數據則取出來,調用evdev_fetch_next_event*/  
  25.     while (retval + input_event_size() <= count &&  
  26.            evdev_fetch_next_event(client, &event)) {  
  27.         /*input_event_to_user調用copy_to_user傳入用戶程序中,這樣讀取完成*/  
  28.         if (input_event_to_user(buffer + retval, &event))  
  29.             return -EFAULT;  
  30.   
  31.         retval += input_event_size();  
  32.     }  
  33.   
  34.     return retval;  
  35. }  

  1. static int evdev_fetch_next_event(struct evdev_client *client,  
  2.                   struct input_event *event)  
  3. {  
  4.     int have_event;  
  5.   
  6.     spin_lock_irq(&client->buffer_lock);  
  7.     /*先判斷一下是否有數據*/  
  8.     have_event = client->head != client->tail;  
  9.     /*如果有就從環形緩衝區的取出來,記得是從head存儲,tail取出*/  
  10.     if (have_event) {  
  11.         *event = client->buffer[client->tail++];  
  12.         client->tail &= EVDEV_BUFFER_SIZE - 1;  
  13.     }  
  14.   
  15.     spin_unlock_irq(&client->buffer_lock);  
  16.   
  17.     return have_event;  
  18. }  

  1. int input_event_to_user(char __user *buffer,  
  2.             const struct input_event *event)  
  3. {  
  4.     /*如果設置了標誌INPUT_COMPAT_TEST就將事件event包裝成結構體compat_event*/  
  5.     if (INPUT_COMPAT_TEST) {  
  6.         struct input_event_compat compat_event;  
  7.   
  8.         compat_event.time.tv_sec = event->time.tv_sec;  
  9.         compat_event.time.tv_usec = event->time.tv_usec;  
  10.         compat_event.type = event->type;  
  11.         compat_event.code = event->code;  
  12.         compat_event.value = event->value;  
  13.         /*將包裝成的compat_event拷貝到用戶空間*/  
  14.         if (copy_to_user(buffer, &compat_event,  
  15.                  sizeof(struct input_event_compat)))  
  16.             return -EFAULT;  
  17.   
  18.     } else {  
  19.         /*否則,將event拷貝到用戶空間*/  
  20.         if (copy_to_user(buffer, eventsizeof(struct input_event)))  
  21.             return -EFAULT;  
  22.     }  
  23.   
  24.     return 0;  
  25. }  
這裏總結一下:如果兩個進程打開同一個文件,每個進程在打開時都會生成一個evdev_client,evdev_client被掛在evdev的client_list,在handle收到一個事件的時候,會把事件copy到掛在client_list上的所有evdev_client的buffer中。這樣所有打開同一個設備的進程都會收到這個消息而喚醒。
發佈了7 篇原創文章 · 獲贊 2 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章