先乱序记录一下阅读Linux input subsystem代码的笔记。
在input device driver的入口代码部分,需要分配并初始化input device结构,内核提供的API是input_allocate_device(),代码如下:
1 struct input_dev *input_allocate_device(void) 2 { 3 struct input_dev *dev; 4 5 dev = kzalloc(sizeof(struct input_dev), GFP_KERNEL); 6 if (dev) { 7 dev->dev.type = &input_dev_type; 8 dev->dev.class = &input_class; 9 device_initialize(&dev->dev); 10 mutex_init(&dev->mutex); 11 spin_lock_init(&dev->event_lock); 12 INIT_LIST_HEAD(&dev->h_list); 13 INIT_LIST_HEAD(&dev->node); 14 15 __module_get(THIS_MODULE); 16 } 17 18 return dev; 19 }
此API的工作就是分配内存并初始化结构,这里调用了device_initialize,在input_device_register中还会调用device_add,这两个API合起来就是device_register要做的工作。有了constructor还要有destructor,就是input_free_device,代码如下:
1 void input_free_device(struct input_dev *dev) 2 { 3 if (dev) 4 input_put_device(dev); 5 }
初始化input device支持事件的时候可以使用input_set_capability(),这个函数的代码如下:
1 void input_set_capability(struct input_dev *dev, unsigned int type, unsigned int code) 2 { 3 switch (type) { 4 case EV_KEY: 5 __set_bit(code, dev->keybit); 6 break; 7 8 case EV_REL: 9 __set_bit(code, dev->relbit); 10 break; 11 12 case EV_ABS: 13 __set_bit(code, dev->absbit); 14 break; 15 16 case EV_MSC: 17 __set_bit(code, dev->mscbit); 18 break; 19 20 case EV_SW: 21 __set_bit(code, dev->swbit); 22 break; 23 24 case EV_LED: 25 __set_bit(code, dev->ledbit); 26 break; 27 28 case EV_SND: 29 __set_bit(code, dev->sndbit); 30 break; 31 32 case EV_FF: 33 __set_bit(code, dev->ffbit); 34 break; 35 36 case EV_PWR: 37 /* do nothing */ 38 break; 39 40 default: 41 pr_err("input_set_capability: unknown type %u (code %u) ", 42 type, code); 43 dump_stack(); 44 return; 45 } 46 47 __set_bit(type, dev->evbit); 48 }
通过代码可以看到,如果一个设备需要支持多种事件的话,需要多次调用该API,而不能使用按位或的形式传参。
现在input device初始化完成了,应该向系统注册了,使用的API是input_register_device(),代码如下:
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 /* Every input device generates EV_SYN/SYN_REPORT events. */ 9 __set_bit(EV_SYN, dev->evbit); 10 11 /* KEY_RESERVED is not supposed to be transmitted to userspace. */ 12 __clear_bit(KEY_RESERVED, dev->keybit); 13 14 /* Make sure that bitmasks not mentioned in dev->evbit are clean. */ 15 input_cleanse_bitmasks(dev); 16 17 if (!dev->hint_events_per_packet) 18 dev->hint_events_per_packet = 19 input_estimate_events_per_packet(dev); 20 21 /* 22 * If delay and period are pre-set by the driver, then autorepeating 23 * is handled by the driver itself and we don't do it in input.c. 24 */ 25 init_timer(&dev->timer); 26 if (!dev->rep[REP_DELAY] && !dev->rep[REP_PERIOD]) { 27 dev->timer.data = (long) dev; 28 dev->timer.function = input_repeat_key; 29 dev->rep[REP_DELAY] = 250; 30 dev->rep[REP_PERIOD] = 33; 31 } 32 33 if (!dev->getkeycode) 34 dev->getkeycode = input_default_getkeycode; 35 36 if (!dev->setkeycode) 37 dev->setkeycode = input_default_setkeycode; 38 39 dev_set_name(&dev->dev, "input%ld", 40 (unsigned long) atomic_inc_return(&input_no) - 1); 41 42 error = device_add(&dev->dev); 43 if (error) 44 return error; 45 46 path = kobject_get_path(&dev->dev.kobj, GFP_KERNEL); 47 pr_info("%s as %s ", 48 dev->name ? dev->name : "Unspecified device", 49 path ? path : "N/A"); 50 kfree(path); 51 52 error = mutex_lock_interruptible(&input_mutex); 53 if (error) { 54 device_del(&dev->dev); 55 return error; 56 } 57 58 list_add_tail(&dev->node, &input_dev_list); 59 60 list_for_each_entry(handler, &input_handler_list, node) 61 input_attach_handler(dev, handler); 62 63 input_wakeup_procfs_readers(); 64 65 mutex_unlock(&input_mutex); 66 67 return 0; 68 }
这个函数做了以下几件事:
第一,因为所有的输入设备都需要支持EV_SYN,所以有必要明确置位一下,而KEY_RESERVED事件是不被支持的,所以清除掉。而对于当前设备没有明确表示支持的事件默认不支持,要清除掉相关的bitmap,代码如下:
1 static void input_cleanse_bitmasks(struct input_dev *dev) 2 { 3 INPUT_CLEANSE_BITMASK(dev, KEY, key); 4 INPUT_CLEANSE_BITMASK(dev, REL, rel); 5 INPUT_CLEANSE_BITMASK(dev, ABS, abs); 6 INPUT_CLEANSE_BITMASK(dev, MSC, msc); 7 INPUT_CLEANSE_BITMASK(dev, LED, led); 8 INPUT_CLEANSE_BITMASK(dev, SND, snd); 9 INPUT_CLEANSE_BITMASK(dev, FF, ff); 10 INPUT_CLEANSE_BITMASK(dev, SW, sw); 11 }
1 #define INPUT_CLEANSE_BITMASK(dev, type, bits) 2 do { 3 if (!test_bit(EV_##type, dev->evbit)) 4 memset(dev->bits##bit, 0, 5 sizeof(dev->bits##bit)); 6 } while (0)
清除bitmap的时候,首先看dev->evbit[]中是否指定EV_KEY EV_REL EV_ABS EV_MSC EV_LED EV_SND EV_FF EV_SW,若不指定,就把相关的xxxbit数组中所有元素清零,逻辑很简单,但是实现的时候,注意一下宏的使用方式,dev->bits##bit,以前接触的##连接符,都是变动的部分放在最后,变动部分的前面加上##,但是这里变动部分在前面,反而在其后面加##,注意使用方式。
第二,初始化定时器,设置重复事件,可见,如果用户没有明确指定重复的延迟和周期的话,输入子系统将延迟初始化为默认值250ms,周期是33ms,目前还不知道这部分的意义,估计需要结合具体的输入设备才能理解。
第三,设置设备的名字,这里的device_add将向系统注册一个设备,如果用户空间有udev或者mdev的话,将在/dev下产生相应的设备节点。
第四,list_add_tail(&dev->node, &input_dev_list),在操作系统中所谓的注册,其实就是将某单独的数据结构,通过插入链表或者填充数组的方式让内核可以通过某链表头或者数组找到它,因此,这里的input_dev_list显然就是一个全局变量,链表头。
第五,这是十分重要的一步,list_for_each_entry(handler, &input_handler_list, node)
input_attach_handler(dev, handler);
简而言之,这一步逐一将系统中存在的struct input_handler与当前要注册的input_device进行匹配,若匹配成功,则调用handler->match(),进一步还会调用handler->connect(),显然这些函数指针指向的回调函数都是事件处理层决定的,例如evdev.c中向系统注册的evdev_handler指定的相关函数是evdev_connect,这里就不展开了,input_attach_handler代码如下:
1 static const struct input_device_id *input_match_device(struct input_handler *handler, 2 struct input_dev *dev) 3 { 4 const struct input_device_id *id; 5 int i; 6 7 for (id = handler->id_table; id->flags || id->driver_info; id++) { 8 9 if (id->flags & INPUT_DEVICE_ID_MATCH_BUS) 10 if (id->bustype != dev->id.bustype) 11 continue; 12 13 if (id->flags & INPUT_DEVICE_ID_MATCH_VENDOR) 14 if (id->vendor != dev->id.vendor) 15 continue; 16 17 if (id->flags & INPUT_DEVICE_ID_MATCH_PRODUCT) 18 if (id->product != dev->id.product) 19 continue; 20 21 if (id->flags & INPUT_DEVICE_ID_MATCH_VERSION) 22 if (id->version != dev->id.version) 23 continue; 24 25 MATCH_BIT(evbit, EV_MAX); 26 MATCH_BIT(keybit, KEY_MAX); 27 MATCH_BIT(relbit, REL_MAX); 28 MATCH_BIT(absbit, ABS_MAX); 29 MATCH_BIT(mscbit, MSC_MAX); 30 MATCH_BIT(ledbit, LED_MAX); 31 MATCH_BIT(sndbit, SND_MAX); 32 MATCH_BIT(ffbit, FF_MAX); 33 MATCH_BIT(swbit, SW_MAX); 34 35 if (!handler->match || handler->match(handler, dev)) 36 return id; 37 } 38 39 return NULL; 40 } 41 42 static int input_attach_handler(struct input_dev *dev, struct input_handler *handler) 43 { 44 const struct input_device_id *id; 45 int error; 46 47 id = input_match_device(handler, dev); 48 if (!id) 49 return -ENODEV; 50 51 error = handler->connect(handler, dev, id); 52 if (error && error != -ENODEV) 53 pr_err("failed to attach handler %s to device %s, error: %d ", 54 handler->name, kobject_name(&dev->dev.kobj), error); 55 56 return error; 57 }
匹配时,检查handler中的id_table与input_device->id,比如bustype、vendor、product以及version,除此之外,还要比较xxxbit数组,MATCH_BIT宏定义如下:
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;
BITS_TO_LONGS的定义:
1 #define BITS_TO_LONGS(nr) DIV_ROUND_UP(nr, BITS_PER_BYTE * sizeof(long))
如果当前要注册的device不能完全满足匹配条件,那么就换下一个id_table中的表项进行匹配,若当前handler->id_table中所有表项都不能与device的id匹配,那么就返回NULL,返回NULL就会使得input_attach_handler返回-ENODEV,这样在input_register_handler中会从input_handler_list中再找到下一个handler重新开始匹配。
以上API都是和input device相关的,现在看一下注册input_handler的API,input_register_handler(),代码如下:
1 int input_register_handler(struct input_handler *handler) 2 { 3 struct input_dev *dev; 4 int retval; 5 6 retval = mutex_lock_interruptible(&input_mutex); 7 if (retval) 8 return retval; 9 10 INIT_LIST_HEAD(&handler->h_list); 11 12 if (handler->fops != NULL) { 13 if (input_table[handler->minor >> 5]) { 14 retval = -EBUSY; 15 goto out; 16 } 17 input_table[handler->minor >> 5] = handler; 18 } 19 20 list_add_tail(&handler->node, &input_handler_list); 21 22 list_for_each_entry(dev, &input_dev_list, node) 23 input_attach_handler(dev, handler); 24 25 input_wakeup_procfs_readers(); 26 27 out: 28 mutex_unlock(&input_mutex); 29 return retval; 30 }
这个函数主要做三件事:
第一,将要注册的handler填充到input_table数组中,填充的时候,数组的下标取决于handler的minor,minor除以32即可得到input_table数组的下标,当然填充数组前需要检查下当前位置是否已经被占用,若占用则直接宣告注册失败。
第二,将要注册的handler加入到全局链表头input_handler_list所指向的链表。
第三,和input_register_device最后一步一样,将handler和device进行匹配,如果系统中已经存在了一些input_device,它们在注册阶段并没有匹配到合适的handler,那么注册handler的时候就又检查了一下handler和device的对应关系,这一次可能有些device就得到了匹配的handler。其实,input_device、input_handler、input_handle与设备驱动模型中的device、driver、bus的关系很类似,注册input_device、input_driver任意一方都会进行匹配检查。在设备驱动模型中,device和driver匹配成功后,device结构中会有一个成员表示自己的driver,而driver中有一链表成员,表示自己能够支持的各个设备,这一点在input subsystem中的体现为,匹配成功后,在handler->connect()函数中input_handler和input_device会同时出现在input_handle结构体中,该结构体的定义如下:
1 struct input_handle { 2 3 void *private; 4 5 int open; 6 const char *name; 7 8 struct input_dev *dev; 9 struct input_handler *handler; 10 11 struct list_head d_node; 12 struct list_head h_node; 13 };
dev成员指向配对成功的input_device,handler成员指向对应的handler,这样来看handle结构的一大重要作用就是记录匹配成功的input_device和input_handler。
以上是input subsystem的中间层,在中间层以上还有事件处理层,这一层的实现就是evdev.c、mousedev.c、joydev.c等文件构建的,接下来简单分析下evdev。
evdev.c实现了对evdev的管理,根据Docuentation/input/input.txt的描述,evdev is the generic input event interface. It passes the events generated in the kernel straight to the program, with timestamps.因此,evdev只是对输入设备这一类设备的管理,并不涉及具体如鼠标、键盘以及游戏摇杆等设备的管理,但是驱动中完全可以使用关于evdev的API直接给用户空间程序上报事件。evdev模块代码入口如下:
1 static struct input_handler evdev_handler = { 2 .event = evdev_event, 3 .connect = evdev_connect, 4 .disconnect = evdev_disconnect, 5 .fops = &evdev_fops, 6 .minor = EVDEV_MINOR_BASE, 7 .name = "evdev", 8 .id_table = evdev_ids, 9 }; 10 11 static int __init evdev_init(void) 12 { 13 return input_register_handler(&evdev_handler); 14 } 15 16 static void __exit evdev_exit(void) 17 { 18 input_unregister_handler(&evdev_handler); 19 } 20 21 module_init(evdev_init); 22 module_exit(evdev_exit);
模块入口函数evdev_init()使用上面分析过的函数input_register_handler向内核注册了自己的handler,evdev_handler,这个结构体就是evdev的核心了,以下所有内容都将围绕这个结构体展开。name成员的含义显而易见,minor成员初始化为EVDEV_MINOR_BASE,此宏的定义是64,id_table则指向了evdev_ids数组的起始地址,该数组定义如下:
1 static const struct input_device_id evdev_ids[] = { 2 { .driver_info = 1 }, /* Matches all devices */ 3 { }, /* Terminating zero entry */ 4 };
这里只初始化了driver_info,注释说匹配所有设备,结合上面的input_match_device函数看一下,在for循环中由于id->driver_info成员是1,所以这一层循环是一定能够跑完的,但是flags成员没有初始化,默认为0,那么匹配时将不会对bustype、vendor、product以及version检查,由于这里的evbit、keybit、relbit、absbit、mscbit等数组成员也都是0,那么id->xxxbit数组与dev->xxxbit数组位与后一定是全零,也就是等于id->xxxbit,这一部分的检查也会完全通过,接着就是handler->match,这个函数指针在evdev结构体中没有初始化,是NULL,所以直接返回当前id就完成了一次匹配,这样分析来看evdev确实会匹配所有设备。
匹配成功后,input_attach_handler()会调用handler->connect(),也就是这里的evdev_connect,代码如下:
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 for (minor = 0; minor < EVDEV_MINORS; minor++) 13 if (!evdev_table[minor]) 14 break; 15 16 if (minor == EVDEV_MINORS) { 17 pr_err("no more free evdev devices "); 18 return -ENFILE; 19 } 20 21 evdev = kzalloc(sizeof(struct evdev), GFP_KERNEL); 22 if (!evdev) 23 return -ENOMEM; 24 25 INIT_LIST_HEAD(&evdev->client_list); 26 spin_lock_init(&evdev->client_lock); 27 mutex_init(&evdev->mutex); 28 init_waitqueue_head(&evdev->wait); 29 30 dev_set_name(&evdev->dev, "event%d", minor); 31 evdev->exist = true; 32 evdev->minor = minor; 33 34 evdev->handle.dev = input_get_device(dev); 35 evdev->handle.name = dev_name(&evdev->dev); 36 evdev->handle.handler = handler; 37 evdev->handle.private = evdev; 38 39 evdev->dev.devt = MKDEV(INPUT_MAJOR, EVDEV_MINOR_BASE + minor); 40 evdev->dev.class = &input_class; 41 evdev->dev.parent = &dev->dev; 42 evdev->dev.release = evdev_free; 43 device_initialize(&evdev->dev); 44 45 error = input_register_handle(&evdev->handle); 46 if (error) 47 goto err_free_evdev; 48 49 error = evdev_install_chrdev(evdev); 50 if (error) 51 goto err_unregister_handle; 52 53 error = device_add(&evdev->dev); 54 if (error) 55 goto err_cleanup_evdev; 56 57 return 0; 58 59 err_cleanup_evdev: 60 evdev_cleanup(evdev); 61 err_unregister_handle: 62 input_unregister_handle(&evdev->handle); 63 err_free_evdev: 64 put_device(&evdev->dev); 65 return error; 66 }
evdev_connect()主要是创建一个新的event设备,相应的设备节点文件是/dev/input/eventX。evdev_table是全局数组,里面存放着所有的evdev的地址,它的容量是EVDEV_MINORS,也就是32。要注册一个新的evdev设备,首先要检查一下evdev数量是不是已经达到了最大值,这里采用的方式就是直接从头遍历evdev_table数组,第一个为NULL的元素就是能够存放新evdev的地方,如果数组已经满了,那么此函数即返回-ENFILE。如果有空间,那么就申请内存来存放新的evdev,接着就是初始化新的evdev了:一个evdev可以有多个client,所以初始化client_list,而操作client的时候需要互斥,所以初始化client_lock,等待队列用于实现用户空间读取时的阻塞等待,exist成员置为true表示新的evdev已经存在,minor是新的evdev在evdev_table中的索引,而设备节点文件/dev/input/eventx中的x就是这里minor决定的。
evdev_connect一项重要工作就是绑定一组匹配成功的input_device和input_handler,这个工作是跟evdev->handle成员息息相关的,handle成员handler指向了配对成功的handler,成员dev指向了配对成功的device,而private成员则指向了evdev设备本身。
接着,初始化evdev->dev,这就是设备驱动模型中的struct device了,设备号有INPUT_MAJOR, EVDEV_MINOR_BASE,minor生成,class指向了input_class,说明在class/input/目录下会出现新evdev的信息。接着,device_initialize()函数各种初始化。input_register_handle,注意这里是注册handle而不是上面已经分析过的handler,它的代码如下:
1 int input_register_handle(struct input_handle *handle) 2 { 3 struct input_handler *handler = handle->handler; 4 struct input_dev *dev = handle->dev; 5 int error; 6 7 /* 8 * We take dev->mutex here to prevent race with 9 * input_release_device(). 10 */ 11 error = mutex_lock_interruptible(&dev->mutex); 12 if (error) 13 return error; 14 15 /* 16 * Filters go to the head of the list, normal handlers 17 * to the tail. 18 */ 19 if (handler->filter) 20 list_add_rcu(&handle->d_node, &dev->h_list); 21 else 22 list_add_tail_rcu(&handle->d_node, &dev->h_list); 23 24 mutex_unlock(&dev->mutex); 25 26 /* 27 * Since we are supposed to be called from ->connect() 28 * which is mutually exclusive with ->disconnect() 29 * we can't be racing with input_unregister_handle() 30 * and so separate lock is not needed here. 31 */ 32 list_add_tail_rcu(&handle->h_node, &handler->h_list); 33 34 if (handler->start) 35 handler->start(handle); 36 37 return 0; 38 }
这个函数主要做两件事,将handle挂接到当前device的h_list上,h_list中的h就代表handle的意思,另一件事是将handle挂接到当前handler的h_list上,如果当前handler有start方法的话就调用,显然evdev_handler没有。这个函数将handle同时挂到了device和handler的链表上,那么两者都可用通过相关的数据结构成员找到它们,这一点的用意后面遇到再说吧。
接着,evdev_install_chrdev(),看名字意思是注册evdev相关的字符设备,但是struct evdev结构体中并没有struct cdev结构体,所以这里的注册并不是像cdev_init()、cdev_add()这样的注册,而是直接操作struct evdev,代码如下:
1 static int evdev_install_chrdev(struct evdev *evdev) 2 { 3 /* 4 * No need to do any locking here as calls to connect and 5 * disconnect are serialized by the input core 6 */ 7 evdev_table[evdev->minor] = evdev; 8 return 0; 9 }
evdev_disconnect函数则是释放evdev_connect所占用的资源以及创建的条目,代码如下:
1 static void evdev_disconnect(struct input_handle *handle) 2 { 3 struct evdev *evdev = handle->private; 4 5 device_del(&evdev->dev); 6 evdev_cleanup(evdev); 7 input_unregister_handle(handle); 8 put_device(&evdev->dev); 9 }
这里再展开一下evdev_cleanup()和input_unregister_handle(),代码如下:
1 /* 2 * Mark device non-existent. This disables writes, ioctls and 3 * prevents new users from opening the device. Already posted 4 * blocking reads will stay, however new ones will fail. 5 */ 6 static void evdev_mark_dead(struct evdev *evdev) 7 { 8 mutex_lock(&evdev->mutex); 9 evdev->exist = false; 10 mutex_unlock(&evdev->mutex); 11 } 12 13 static void evdev_cleanup(struct evdev *evdev) 14 { 15 struct input_handle *handle = &evdev->handle; 16 17 evdev_mark_dead(evdev); 18 evdev_hangup(evdev); 19 evdev_remove_chrdev(evdev); 20 21 /* evdev is marked dead so no one else accesses evdev->open */ 22 if (evdev->open) { 23 input_flush_device(handle, NULL); 24 input_close_device(handle); 25 } 26 }
大致过一下disconnect的流程,清除exist,既然这个设备已经失效,那么需要通知所有的evdev_client。这里插一句,后面分析evdev_open()的时候会看到,每open一次,便会新建一个struct_client,对于每个struct_client而言,它们不知道evdev已经disconnect,这是一个异步事件,所以evdev_disconnect()中使用异步信号通知机制,即kill_fasync()。evdev_disconnect()还会清掉之前注册在evdev_table[]中的元素,如果此时还有在使用endev的,就将其强行关闭。最后,把此handle从dev和handler的h_list上删除。
下面分析evdev_open,当应用程序执行open("/dev/input/eventX", O_RDWR)时,系统调用经过文件系统一系列操作后就会执行这里的evdev_open,因为它是file_operations中的成员。此函数会从事件处理层到input core层再到驱动程序的input_dev对应的open方法依次执行下去。代码如下:
1 static int evdev_open(struct inode *inode, struct file *file) 2 { 3 struct evdev *evdev; 4 struct evdev_client *client; 5 int i = iminor(inode) - EVDEV_MINOR_BASE; 6 unsigned int bufsize; 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 = evdev_table[i]; 16 if (evdev) 17 get_device(&evdev->dev); 18 mutex_unlock(&evdev_table_mutex); 19 20 if (!evdev) 21 return -ENODEV; 22 23 bufsize = evdev_compute_buffer_size(evdev->handle.dev); 24 25 client = kzalloc(sizeof(struct evdev_client) + 26 bufsize * sizeof(struct input_event), 27 GFP_KERNEL); 28 if (!client) { 29 error = -ENOMEM; 30 goto err_put_evdev; 31 } 32 33 client->bufsize = bufsize; 34 spin_lock_init(&client->buffer_lock); 35 client->evdev = evdev; 36 evdev_attach_client(evdev, client); 37 38 error = evdev_open_device(evdev); 39 if (error) 40 goto err_free_client; 41 42 file->private_data = client; 43 nonseekable_open(inode, file); 44 45 return 0; 46 47 err_free_client: 48 evdev_detach_client(evdev, client); 49 kfree(client); 50 err_put_evdev: 51 put_device(&evdev->dev); 52 return error; 53 }
evdev_open()做的第一件事,是找到evdev设备,前面evdev_install_chrdev()中将注册的evdev设备都放在了evdev_table[]数组中,所以找到evdev的关键在于找到数组下标,evdev_open是file_operations的成员,它的接口中有一个是inode,我们可以通过宏iminor获得设备的minor,然后减去EVDEV_MINOR_BASE就得到了数组索引,这样就完成了第一步。
第二步,给evdev_client结构分配内存空间。这里非常有必要说一下evdev_client结构,此结构定义如下:
1 struct evdev_client { 2 unsigned int head; 3 unsigned int tail; 4 unsigned int packet_head; /* [future] position of the first element of next packet */ 5 spinlock_t buffer_lock; /* protects access to buffer, head and tail */ 6 struct fasync_struct *fasync; 7 struct evdev *evdev; 8 struct list_head node; 9 unsigned int bufsize; 10 struct input_event buffer[]; 11 };
可以看到这个结构中多数成员都是关于buffer的,这完全可以理解,一个输入设备要上报输入事件,从代码上来说,肯定有存储事件的缓冲区,而且有时候一个设备会上报多个事件,那么我们需要能够存储多个事件的缓冲区。bufsize成员表示当前输入设备的输入事件缓冲区最多可以存放事件的个数。值的注意的是,输入事件缓冲区的大小不是固定的,这里采用的是零长数组的方式,我们可以借此学习一下变长数组在C语言中的使用方法。
由代码可以看到,client结构的内存分为两部分,一部分是client结构本身的内存空间,另一部分就是变长数组的长度。计算变长数组的长度时,需要知道当前输入设备的输入事件缓冲区能存放事件的数量,也就是bufsize,计算bufsize的方法endev_compute_buffer_size()代码如下:
1 static unsigned int evdev_compute_buffer_size(struct input_dev *dev) 2 { 3 unsigned int n_events = 4 max(dev->hint_events_per_packet * EVDEV_BUF_PACKETS, 5 EVDEV_MIN_BUFFER_SIZE); 6 7 return roundup_pow_of_two(n_events); 8 }
dev->hint_events_per_packet是在input_register_device()中确定的,如果我们没有初始化这个成员,那么它将由input_estimate_events_per_packet()决定,这块代码还没看懂,先跳过。bufsize最终会向上取整到2的幂,后面读写函数中操作client_struct时会看到这样做的好处。
第二步还没说完,变长数组的长度就是bufsize * sizeof(struct input_event),这一点显而易见。接着初始化client->bufsize。
第三步,将client的evdev指向当前evdev,并且将client挂接到evdev的链表上。既然这里有挂接链表的操作,说明一个evdev对应着多个client,这一点在evdev_disconnect()中已经体现:evdev需要遍历自己的client_list,给所有的client发信号。
第四步,调用evdev_open_device(),并且将file的private_data初始化为client。evdev_open_device()代码如下:
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 else if (!evdev->open++) { 12 retval = input_open_device(&evdev->handle); 13 if (retval) 14 evdev->open--; 15 } 16 17 mutex_unlock(&evdev->mutex); 18 return retval; 19 }
此函数比较简单,上锁、检查参数后调用input_open_device(),代码如下:
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 }
input_open_device()的核心是对handle->open和dev->users成员自增,调用dev->open()。但是我没搞懂这里的逻辑,为什么只有dev->users为零的时候才会调用dev->open()?还有,dev->open是在哪里操作的?dev->open就是我们使用input_register_device()之前自己赋值操作的方法。
到这里就分析完了evdev_open(),evdev_poll()就是调用poll_wait(),evdev_fasync()就是调用fasync_helper(),这里不多说了,这两个函数就说明我们可以在应用层使用poll()或者select()实现输入设备的异步阻塞IO以及异步非阻塞IO操作。
接下来分析evdev_read(),它的作用是从已经打开的evdev中读取输入事件,如果缓冲区中有事件则传递给用户空间,否则阻塞等待,代码如下:
1 static ssize_t evdev_read(struct file *file, char __user *buffer, 2 size_t count, loff_t *ppos) 3 { 4 struct evdev_client *client = file->private_data; 5 struct evdev *evdev = client->evdev; 6 struct input_event event; 7 int retval; 8 9 if (count < input_event_size()) 10 return -EINVAL; 11 12 if (client->packet_head == client->tail && evdev->exist && 13 (file->f_flags & O_NONBLOCK)) 14 return -EAGAIN; 15 16 retval = wait_event_interruptible(evdev->wait, 17 client->packet_head != client->tail || !evdev->exist); 18 if (retval) 19 return retval; 20 21 if (!evdev->exist) 22 return -ENODEV; 23 24 while (retval + input_event_size() <= count && 25 evdev_fetch_next_event(client, &event)) { 26 27 if (input_event_to_user(buffer + retval, &event)) 28 return -EFAULT; 29 30 retval += input_event_size(); 31 } 32 33 return retval; 34 }
第一步,从file->private_data中获取evdev_client结构,接着根据client获取当前的evdev设备。如果用户空间要读取的长度小于一个事件的长度,那么直接返回,如果当前事件缓冲区为空,并且设备存在,同时当前文件的操作为非阻塞IO方式,那么直接返回-EAGAIN即可。
第二步,调用wait_event_interruptible(),condition为输入事件缓冲区非空或者evdev设备不存在了,如果是因为设备不存在了,那么直接返回-ENODEV即可,否则读取缓冲区中的事件,传递给用户空间即可。读取输入事件缓冲区的视线内代码是一个循环,它的停止条件是已经传递给用户空间的数据长度已经不小于count或者输入事件缓冲区已经空了,这里看一下evdev_fetch_next_event()代码:
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 if (have_event) { 10 *event = client->buffer[client->tail++]; 11 client->tail &= client->bufsize - 1; 12 } 13 14 spin_unlock_irq(&client->buffer_lock); 15 16 return have_event; 17 }
此函数就是从输入事件缓冲区中取出一个事件,首先对client加锁,根据client->head与client->tail判断缓冲区是否有事件,若两者不相等那么有,否则没有。由于tail指向将要处理的事件,若要取事件,那么就根据tail就可以得到之。而input_event_to_user()就是copy_to_user(),把取出来的事件拷贝给用户空间。
evdev_read()是读取事件,读取时使用wait_event_interruptible()实现阻塞IO,如果读取操作阻塞在了wait队列上,那么我们在哪里将其唤醒呢?是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 15 client = rcu_dereference(evdev->grab); 16 if (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 if (type == EV_SYN && code == SYN_REPORT) 25 wake_up_interruptible(&evdev->wait); 26 }
简而言之,此函数就是把type code value代表的事件发送给当前evdev对应的client。首先定义一个input_event结构,把传入的事件信息一次填入,完成一个事件的描述,接着看一下当前evdev的grab成员,这个成员代表exclusice access的含义,也就是说,如果这个成员不是NULL,那么这个evdev只能被一个client访问使用,如果没有grab成员,那么此事件就需要给evdev->client_list上所有成员发消息,发消息的函数是evdev_pass_event(),最后,如果type是EV_SYN且code是SYN_REPORT,那么我们将调用wake_up_interruptible(),实现读取操作的同步,这也意味着,驱动程序中要显式调用report相关的函数才能解锁读取操作。
这里重点看evdev_pass_event(),代码如下:
1 static void evdev_pass_event(struct evdev_client *client, 2 struct input_event *event) 3 { 4 /* Interrupts are disabled, just acquire the lock. */ 5 spin_lock(&client->buffer_lock); 6 7 client->buffer[client->head++] = *event; 8 client->head &= client->bufsize - 1; 9 10 if (unlikely(client->head == client->tail)) { 11 /* 12 * This effectively "drops" all unconsumed events, leaving 13 * EV_SYN/SYN_DROPPED plus the newest event in the queue. 14 */ 15 client->tail = (client->head - 2) & (client->bufsize - 1); 16 17 client->buffer[client->tail].time = event->time; 18 client->buffer[client->tail].type = EV_SYN; 19 client->buffer[client->tail].code = SYN_DROPPED; 20 client->buffer[client->tail].value = 0; 21 22 client->packet_head = client->tail; 23 } 24 25 if (event->type == EV_SYN && event->code == SYN_REPORT) { 26 client->packet_head = client->head; 27 kill_fasync(&client->fasync, SIGIO, POLL_IN); 28 } 29 30 spin_unlock(&client->buffer_lock); 31 }
该函数备调用的时机为产生了一个输入事件以后,那么这个函数肯定要将产生的事件存储到事件队列缓冲区中,上面代码对于client->head的操作即是,存储了事件队列以后,还要确保head没超过bufsize,如果超过了bufsize,那么应该从零开始,也就是覆盖第一个,这种逻辑的实现就是通过按位与操作实现的,能够使用按位与操作实现的原因是evdev_open()时bufsize被向上取整为2的幂。如果存储了当前事件后,事件队列缓冲区满了,内核代码采用的机制是,只留下两个事件,最新的一个事件其实不是事件,它的code为SYN_DROPPED,而另一个就是newest事件,接着把packet_head成员更新为tail,代表一系列事件的头部。接着有一项很重要的操作,如果我们的事件type=EV_SYN,code=SYN_REPORT,那么通过kill_fasync()发送SIGIO,那么如果我们的输入设备文件支持异步IO操作的话,应用层应该能通过异步通知的方式接收SIGIO,从而在信号回调函数中读取到输入事件,这一点后面我需要写程序验证一下。