Linux驱动之Input子系统基础知识
1、Linux Input子系统概述
Linux系统的Input子系统处理输入事务,输入设备的驱动程序通过Input输入子系统提供的接口注册到内核,利用子系统提供的功能与用户空间或系统中的其它程序进行交互。整个Input子系统的实现可以看作三层,如下:
- 输入驱动层(input driver):针对各个具体输入设备的驱动功能程序;
- 输入核心层(input core):Linux内核统一管理各输入设备及其驱动程序;
- 事件处理层(event handler):将底层输入硬件事件翻译成用户空间所认知的软事件。
Linux内核Input子系统的框架如下所示:
从上图可以知道,Linux系统中一般的输入设备都是字符类设备,Input子系统的所有输入设备的主设备号都是13。
2、Input数据结构
(1)input_dev结构体
在Linux Input子系统框架中可以看到,input_dev结构体是Input子系统中最重要的数据结构,它代表了一类输入设备,每个具体的input驱动程序,都必须分配并初始化这样的一个结构体,该结构体的定义如下所示:
/** * struct input_dev - represents an input device * @name: name of the device * @phys: physical path to the device in the system hierarchy * @uniq: unique identification code for the device (if device has it) * @id: id of the device (struct input_id) * @propbit: bitmap of device properties and quirks * @evbit: bitmap of types of events supported by the device (EV_KEY, * EV_REL, etc.) * @keybit: bitmap of keys/buttons this device has * @relbit: bitmap of relative axes for the device * @absbit: bitmap of absolute axes for the device * @mscbit: bitmap of miscellaneous events supported by the device * @ledbit: bitmap of leds present on the device * @sndbit: bitmap of sound effects supported by the device * @ffbit: bitmap of force feedback effects supported by the device * @swbit: bitmap of switches present on the device * @hint_events_per_packet: average number of events generated by the * device in a packet (between EV_SYN/SYN_REPORT events). Used by * event handlers to estimate size of the buffer needed to hold * events. * @keycodemax: size of keycode table * @keycodesize: size of elements in keycode table * @keycode: map of scancodes to keycodes for this device * @getkeycode: optional legacy method to retrieve current keymap. * @setkeycode: optional method to alter current keymap, used to implement * sparse keymaps. If not supplied default mechanism will be used. * The method is being called while holding event_lock and thus must * not sleep * @ff: force feedback structure associated with the device if device * supports force feedback effects * @repeat_key: stores key code of the last key pressed; used to implement * software autorepeat * @timer: timer for software autorepeat * @rep: current values for autorepeat parameters (delay, rate) * @mt: pointer to multitouch state * @absinfo: array of &struct input_absinfo elements holding information * about absolute axes (current value, min, max, flat, fuzz, * resolution) * @key: reflects current state of device's keys/buttons * @led: reflects current state of device's LEDs * @snd: reflects current state of sound effects * @sw: reflects current state of device's switches * @open: this method is called when the very first user calls * input_open_device(). The driver must prepare the device * to start generating events (start polling thread, * request an IRQ, submit URB, etc.) * @close: this method is called when the very last user calls * input_close_device(). * @flush: purges the device. Most commonly used to get rid of force * feedback effects loaded into the device when disconnecting * from it * @event: event handler for events sent _to_ the device, like EV_LED * or EV_SND. The device is expected to carry out the requested * action (turn on a LED, play sound, etc.) The call is protected * by @event_lock and must not sleep * @grab: input handle that currently has the device grabbed (via * EVIOCGRAB ioctl). When a handle grabs a device it becomes sole * recipient for all input events coming from the device * @event_lock: this spinlock is taken when input core receives * and processes a new event for the device (in input_event()). * Code that accesses and/or modifies parameters of a device * (such as keymap or absmin, absmax, absfuzz, etc.) after device * has been registered with input core must take this lock. * @mutex: serializes calls to open(), close() and flush() methods * @users: stores number of users (input handlers) that opened this * device. It is used by input_open_device() and input_close_device() * to make sure that dev->open() is only called when the first * user opens device and dev->close() is called when the very * last user closes the device * @going_away: marks devices that are in a middle of unregistering and * causes input_open_device*() fail with -ENODEV. * @dev: driver model's view of this device * @h_list: list of input handles associated with the device. When * accessing the list dev->mutex must be held * @node: used to place the device onto input_dev_list * @num_vals: number of values queued in the current frame * @max_vals: maximum number of values queued in a frame * @vals: array of values queued in the current frame * @devres_managed: indicates that devices is managed with devres framework * and needs not be explicitly unregistered or freed. */ struct input_dev { const char *name; const char *phys; const char *uniq; struct input_id id; unsigned long propbit[BITS_TO_LONGS(INPUT_PROP_CNT)]; unsigned long evbit[BITS_TO_LONGS(EV_CNT)]; unsigned long keybit[BITS_TO_LONGS(KEY_CNT)]; unsigned long relbit[BITS_TO_LONGS(REL_CNT)]; unsigned long absbit[BITS_TO_LONGS(ABS_CNT)]; unsigned long mscbit[BITS_TO_LONGS(MSC_CNT)]; unsigned long ledbit[BITS_TO_LONGS(LED_CNT)]; unsigned long sndbit[BITS_TO_LONGS(SND_CNT)]; unsigned long ffbit[BITS_TO_LONGS(FF_CNT)]; unsigned long swbit[BITS_TO_LONGS(SW_CNT)]; unsigned int hint_events_per_packet; unsigned int keycodemax; unsigned int keycodesize; void *keycode; int (*setkeycode)(struct input_dev *dev, const struct input_keymap_entry *ke, unsigned int *old_keycode); int (*getkeycode)(struct input_dev *dev, struct input_keymap_entry *ke); struct ff_device *ff; unsigned int repeat_key; struct timer_list timer; int rep[REP_CNT]; struct input_mt *mt; struct input_absinfo *absinfo; unsigned long key[BITS_TO_LONGS(KEY_CNT)]; unsigned long led[BITS_TO_LONGS(LED_CNT)]; unsigned long snd[BITS_TO_LONGS(SND_CNT)]; unsigned long sw[BITS_TO_LONGS(SW_CNT)]; int (*open)(struct input_dev *dev); void (*close)(struct input_dev *dev); int (*flush)(struct input_dev *dev, struct file *file); int (*event)(struct input_dev *dev, unsigned int type, unsigned int code, int value); struct input_handle __rcu *grab; spinlock_t event_lock; struct mutex mutex; unsigned int users; bool going_away; struct device dev; struct list_head h_list; struct list_head node; unsigned int num_vals; unsigned int max_vals; struct input_value *vals; bool devres_managed; };
该结构体的成员比较多,简单描述一些核心关键成员:
首先是若干个数组成员,如下:
unsigned long evbit[BITS_TO_LONGS(EV_CNT)]; //事件支持的类型 //每种类型支持的编码 unsigned long keybit[BITS_TO_LONGS(KEY_CNT)]; //按键事件 unsigned long relbit[BITS_TO_LONGS(REL_CNT)]; unsigned long absbit[BITS_TO_LONGS(ABS_CNT)]; //绝对坐标,触摸屏上使用 unsigned long mscbit[BITS_TO_LONGS(MSC_CNT)]; unsigned long ledbit[BITS_TO_LONGS(LED_CNT)]; unsigned long sndbit[BITS_TO_LONGS(SND_CNT)]; unsigned long ffbit[BITS_TO_LONGS(FF_CNT)]; unsigned long swbit[BITS_TO_LONGS(SW_CNT)];
evbit[BITS_TO_LONGS(EV_CNT)]这个数组以位掩码的形式代表了这个设备支持的事件的类型,设置的方式如下:
dev->evbit[0] = BIT(EV_SYN) | BIT(EV_KEY) | BIT(EV_ABS);
absbit[BITS_TO_LONGS(ABS_CNT)]这个数组以位掩码的形式代表这个类型的事件支持的编码,触摸屏驱动支持EV_ABS,所以需要设置这个数组,有一个专门设置这个数组的函数input_set_abs_params,代码如下所示:
void input_set_abs_params(struct input_dev *dev, unsigned int axis, int min, int max, int fuzz, int flat) { struct input_absinfo *absinfo; input_alloc_absinfo(dev); if (!dev->absinfo) return; absinfo = &dev->absinfo[axis]; absinfo->minimum = min; absinfo->maximum = max; absinfo->fuzz = fuzz; absinfo->flat = flat; __set_bit(EV_ABS, dev->evbit); __set_bit(axis, dev->absbit); }
对于触摸屏驱动程序可以类似下面这样使用:
input_set_abs_params(dev, ABS_X, 0, 0x3FF, 0, 0); //设置AD转换的x坐标 input_set_abs_params(dev, ABS_Y, 0, 0x3FF, 0, 0); //设置AD转换的y坐标 input_set_abs_params(dev, ABS_PRESSURE, 0, 1, 0, 0); //设置触摸屏是否按下的标志
其中,表示设置ABS_X/ABS_Y编码值范围为0~0x3FF,该值的范围是由CPU或者其它硬件的ADC限制,ADC的位数为10位,所以不会超过0x3FF。
struct input_id结构体用来标识设备驱动的特征,该结构体定义如下所示:
struct input_id { __u16 bustype; //总线类型 __u16 vendor; //生产厂商 __u16 product; //产品类型 __u16 version; //版本 };
如果需要特定的事件处理器来处理这个设备的话,input_id结构体就非常重要,因为Input子系统核心要通过它们将设备驱动与事件处理层联系起来,常见的输入设备驱动所用的事件处理器一般为通用型,因此该初始化也无关紧要。
(2)input_handler结构体
该结构体是事件处理器数据结构,代表了一个事件处理器,该结构的定义如下:
/** * struct input_handler - implements one of interfaces for input devices * @private: driver-specific data * @event: event handler. This method is being called by input core with * interrupts disabled and dev->event_lock spinlock held and so * it may not sleep * @events: event sequence handler. This method is being called by * input core with interrupts disabled and dev->event_lock * spinlock held and so it may not sleep * @filter: similar to @event; separates normal event handlers from * "filters". * @match: called after comparing device's id with handler's id_table * to perform fine-grained matching between device and handler * @connect: called when attaching a handler to an input device * @disconnect: disconnects a handler from input device * @start: starts handler for given handle. This function is called by * input core right after connect() method and also when a process * that "grabbed" a device releases it * @legacy_minors: set to %true by drivers using legacy minor ranges * @minor: beginning of range of 32 legacy minors for devices this driver * can provide * @name: name of the handler, to be shown in /proc/bus/input/handlers * @id_table: pointer to a table of input_device_ids this driver can * handle * @h_list: list of input handles associated with the handler * @node: for placing the driver onto input_handler_list * * Input handlers attach to input devices and create input handles. There * are likely several handlers attached to any given input device at the * same time. All of them will get their copy of input event generated by * the device. * * The very same structure is used to implement input filters. Input core * allows filters to run first and will not pass event to regular handlers * if any of the filters indicate that the event should be filtered (by * returning %true from their filter() method). * * Note that input core serializes calls to connect() and disconnect() * methods. */ struct input_handler { void *private; void (*event)(struct input_handle *handle, unsigned int type, unsigned int code, int value); void (*events)(struct input_handle *handle, const struct input_value *vals, unsigned int count); bool (*filter)(struct input_handle *handle, unsigned int type, unsigned int code, int value); bool (*match)(struct input_handler *handler, struct input_dev *dev); int (*connect)(struct input_handler *handler, struct input_dev *dev, const struct input_device_id *id); void (*disconnect)(struct input_handle *handle); void (*start)(struct input_handle *handle); bool legacy_minors; int minor; const char *name; const struct input_device_id *id_table; struct list_head h_list; struct list_head node; };
简单描述该结构体的一些重要成员:
首先是几个操作函数指针,如下:
void (*event)(struct input_handle *handle, unsigned int type, unsigned int code, int value); void (*events)(struct input_handle *handle, const struct input_value *vals, unsigned int count); bool (*filter)(struct input_handle *handle, unsigned int type, unsigned int code, int value); bool (*match)(struct input_handler *handler, struct input_dev *dev); int (*connect)(struct input_handler *handler, struct input_dev *dev, const struct input_device_id *id); void (*disconnect)(struct input_handle *handle); void (*start)(struct input_handle *handle);
event函数是当事件处理器接收到来自input设备传来的事件时调用的处理函数,负责处理事件,该函数非常重要。
connect函数是当一个input设备模块注册到内核的时候调用的,将事件处理器与输入设备联系起来,是将input_dev和input_handler配对的函数。
disconnect函数则实现与connect函数相反的功能。
start函数用来启动给定的input_handler,该函数一般由input核心层在调用input_handler的connect()函数之后被调用。
const struct input_device_id *id_table;//事件处理器所支持的input设备
该成员会用在connect函数中,input_device_id结构与input_id结构类似。
还有两个链表,如下:
struct list_head h_list; struct list_head node;
h_list链表用来链接它所支持的input_handle结构,input_dev与input_handler配对之后会生成一个input_handle结构。
node为链表节点,用来链接到input_handler_list,该链表链接了所有注册到内核的事件处理器。
(3)input_handle结构体
struct input_handle结构体代表一个成功配对的input_dev和input_handler,该结构体的定义如下所示:
/** * struct input_handle - links input device with an input handler * @private: handler-specific data * @open: counter showing whether the handle is 'open', i.e. should deliver * events from its device * @name: name given to the handle by handler that created it * @dev: input device the handle is attached to * @handler: handler that works with the device through this handle * @d_node: used to put the handle on device's list of attached handles * @h_node: used to put the handle on handler's list of handles from which * it gets events */ struct input_handle { void *private; int open; const char *name; struct input_dev *dev; struct input_handler *handler; struct list_head d_node; struct list_head h_node; };
private成员用来保存一些私有数据,每个配对的事件处理器都会分配一个对应的设备结构,如evdev事件处理器的evdev结构,注意这个结构与设备驱动层的input_dev不同,初始化handle时,需要保存到该成员。
open为打开的标志,每个input_handle打开后才能操作,这个一般通过事件处理器的open方法间接设置。
dev为关联的input_dev结构体。
handler为关联的input_handler结构体。
d_node用来将input_handle链接到input_dev的h_list链表上。
h_node用来将input_handle链接到input_handler的h_list链表上。
总的来说,input_dev就是硬件驱动层,代表一个input设备,input_handler是事件处理层,代表一个事件处理器,input_handle则属于Input子系统核心层,代表一个配对的input设备与input事件处理器,input_dev通过全局的input_dev_list链接在一起,设备注册的时候会执行这个操作,input_handler通过全局的input_handler_list链接在一起,事件处理器注册的时候会执行这个操作,input_handle没有全局的链表,注册的时候将自己链接到input_dev和input_handler的链表上,通过input_dev和input_handler就可以找到input_handle。
3、Input内核模块
因为用户需要的输入方式是多种多样的,Linux Input子系统所能支持的输入设备,可以说是千差万别的,Input子系统的三层内核模块如下所示:
在上图的Input三层内核模块中,主要完成3件事情:
- 完成形形色色input设备在Linux内核的注册;
- 完成事件处理器input_handler在Linux内核的注册;
- 完成Linux input事件的上报。
(1)input设备的注册
在Linux驱动中描述一个input设备可以使用input_dev来表示,在编写一个具体的input设备驱动时,需要先分配一个input_dev结构体,并初始化该结构体,该操作可以使用input_allocate_device()函数去实现,该函数代码的实现如下:
/** * input_allocate_device - allocate memory for new input device * * Returns prepared struct input_dev or %NULL. * * NOTE: Use input_free_device() to free devices that have not been * registered; input_unregister_device() should be used for already * registered devices. */ struct input_dev *input_allocate_device(void) { static atomic_t input_no = ATOMIC_INIT(-1); struct input_dev *dev; dev = kzalloc(sizeof(struct input_dev), GFP_KERNEL); if (dev) { dev->dev.type = &input_dev_type; dev->dev.class = &input_class; device_initialize(&dev->dev); mutex_init(&dev->mutex); spin_lock_init(&dev->event_lock); init_timer(&dev->timer); INIT_LIST_HEAD(&dev->h_list); INIT_LIST_HEAD(&dev->node); dev_set_name(&dev->dev, "input%lu", (unsigned long)atomic_inc_return(&input_no)); __module_get(THIS_MODULE); } return dev; }
分配input_dev结构体所需要的内存后,并将input_dev的成员赋值初始化后,然后就可以调用函数input_register_device()来向input子系统完成注册,该函数的代码实现如下:
int input_register_device(struct input_dev *dev) { struct input_devres *devres = NULL; struct input_handler *handler; unsigned int packet_size; const char *path; int error; if (dev->devres_managed) { devres = devres_alloc(devm_input_device_unregister, sizeof(struct input_devres), GFP_KERNEL); if (!devres) return -ENOMEM; devres->input = dev; } /* Every input device generates EV_SYN/SYN_REPORT events. */ __set_bit(EV_SYN, dev->evbit); /* KEY_RESERVED is not supposed to be transmitted to userspace. */ __clear_bit(KEY_RESERVED, dev->keybit); /* Make sure that bitmasks not mentioned in dev->evbit are clean. */ input_cleanse_bitmasks(dev); packet_size = input_estimate_events_per_packet(dev); if (dev->hint_events_per_packet < packet_size) dev->hint_events_per_packet = packet_size; dev->max_vals = dev->hint_events_per_packet + 2; dev->vals = kcalloc(dev->max_vals, sizeof(*dev->vals), GFP_KERNEL); if (!dev->vals) { error = -ENOMEM; goto err_devres_free; } /* * If delay and period are pre-set by the driver, then autorepeating * is handled by the driver itself and we don't do it in input.c. */ if (!dev->rep[REP_DELAY] && !dev->rep[REP_PERIOD]) input_enable_softrepeat(dev, 250, 33); if (!dev->getkeycode) dev->getkeycode = input_default_getkeycode; if (!dev->setkeycode) dev->setkeycode = input_default_setkeycode; error = device_add(&dev->dev); if (error) goto err_free_vals; path = kobject_get_path(&dev->dev.kobj, GFP_KERNEL); pr_info("%s as %s\n", dev->name ? dev->name : "Unspecified device", path ? path : "N/A"); kfree(path); error = mutex_lock_interruptible(&input_mutex); if (error) goto err_device_del; list_add_tail(&dev->node, &input_dev_list); list_for_each_entry(handler, &input_handler_list, node) input_attach_handler(dev, handler); input_wakeup_procfs_readers(); mutex_unlock(&input_mutex); if (dev->devres_managed) { dev_dbg(dev->dev.parent, "%s: registering %s with devres.\n", __func__, dev_name(&dev->dev)); devres_add(dev->dev.parent, devres); } return 0; err_device_del: device_del(&dev->dev); err_free_vals: kfree(dev->vals); dev->vals = NULL; err_devres_free: devres_free(devres); return error; }
从上面的代码可以看到,input设备的注册还是与所有的Linux设备注册一样调用device_add()函数将设备注册为Linux设备,同时,通过list_add_tail()将设备添加到Linux内核全局链表input_dev_list,然后通过list_for_each_entry()为设备找到属于自己的input_handler。
(2)input_handler的注册
一般来说input_handler的注册会在input_dev之前,常见的input_handler有:
- mousedev_handler处理来自鼠标类的input事件;
- joydev_handler处理来自游戏杠类的事件;
- kdev_handler处理来自键盘类的事件;
- evdev_handler响应绝大部分的事件,默认的input处理事件。
input_handler的注册是由API函数input_register_handler()去完成的,该函数的定义如下:
/** * input_register_handler - register a new input handler * @handler: handler to be registered * * This function registers a new input handler (interface) for input * devices in the system and attaches it to all input devices that * are compatible with the handler. */ int input_register_handler(struct input_handler *handler) { struct input_dev *dev; int error; error = mutex_lock_interruptible(&input_mutex); if (error) return error; INIT_LIST_HEAD(&handler->h_list); list_add_tail(&handler->node, &input_handler_list); list_for_each_entry(dev, &input_dev_list, node) input_attach_handler(dev, handler); input_wakeup_procfs_readers(); mutex_unlock(&input_mutex); return 0; }
函数会先初始化input_handler的h_list链表,并且使用list_add_tail()将handler加入到全局的input_handler_list链表中。
无论是设备的注册还是handler的注册都会调用函数input_attach_handler(),该函数的定义如下:
static int input_attach_handler(struct input_dev *dev, struct input_handler *handler) { const struct input_device_id *id; int error; id = input_match_device(handler, dev); if (!id) return -ENODEV; error = handler->connect(handler, dev, id); if (error && error != -ENODEV) pr_err("failed to attach handler %s to device %s, error: %d\n", handler->name, kobject_name(&dev->dev.kobj), error); return error; }
每个handler在注册的时候都有自己的id_table,如果设备与input_handler能够匹配成功的话,就会调用input_handler的connect函数。
(3)input事件的上报
一般input事件在底层上报都是通过中断方式,比如说,常用的按键和触摸屏就是采用中断的方式,触摸屏的事件的上报过程如下:
input_report_abs(dev, ABS_X, x); input_report_abs(dev, ABS_X, y); input_report_key(dev, BTN_TOUCH, 1); input_sync(dev);
上面就是一个具体触摸屏接收到中断信号后,调用中断处理函数来处理事件时所调用的方法来完成一次上报事件,它以input_sync()来表示一次完成的事件上报,input事件会被存放到指定的buffer中,由上层读取并做出相应的响应。
4、Android系统对Input的使用
Android系统对Input子系统的集成和使用也沿袭Android的HAL架构,以便上层应用对底层的Input内核模块进行调用,对Input事件进行响应,Android输入子系统的基本架构如下所示:
上面图中显示的EventHub就是Android输入子系统的HAL层,它负责与底层Input子系统内核模块的交互,事实上,Android中EventHub没有独立的库,它是libui的一部分,EventHub在初始化会调用功能函数scanDeviceLocked(),扫描打开底层Input子系统中的输入设备。
Android输入子系统也没有独立的服务线程,它通过系统的WindowManagerService向上层应用提供相应的输入服务,负责Android input子系统的InputManager就是WindowManagerService的有机组成部分之一,InputManager会通过EventHub去读取Input事件,并分发这些事件,EventHub会用到inboundqueue和outboundqueue两个事件队列处理输入事件,而驱动中的input_sync()函数就是这两个队列元素生成源,EventHub会启动InputDispatcherThread线程来处理输入事件,先是从inboundqueue中取出新的input event处理,处理完成再生成另一新的input event放进outboundqueue,接着从outboundqueue中取出新的input event,处理完成则生成新的input message,最后调用::send()函数向上层应用发送inputmessage,EventHub主要负责完成从input event到input message的转化。
Android子系统的事件传递流程如下图所示:
在Android系统中,为了加快输入事件的响应,在WindowManagerService进程与Android其它进程之间的通信没有采用Binder方式,而是采用了共享内存+管道的IPC通信方式,其中管道用来告诉其它进程有新事件到达以及其它进程已完成事件的处理,而共享内存则是用来存放相应的事件信息。
参考:
《Android驱动开发权威指南》