8.input设备(input子系统)驱动

  • Post author:
  • Post category:其他



8.1 Linux的input子系统的驱动框架

说起输入设备,想必大家并不陌生,按键、鼠标、键盘、触摸屏等一系列需要用户“动手”产生信息并且将生成的信息交由处理器完成处理的设备都可以称之为输入设备。而在Linux的内核驱动的实现上也将这些设备进行了专门的分类,即input设备,也叫做输入子系统。对于这些设备,Linux中有其对应的一套驱动模型。

说到这里读者可能产生了疑问,在Linux中不是仅仅将设备分成了字符设备、块设备和网络设备吗?的确是这样,input设备或input子系统和以上3中设备并不是并行的关系,只是将有特定属性的一类设备采用了另一种划分模式而已。那么,读者可能又有疑问了,对于一个字符设备而言,如只需要实现其驱动必须实现结构体file_operations中的接口函数,然后在应用程序中使用open、write、read等函数来调用就可以了,那么对于input子系统而言呢?

在这里必须重点指出,input子系统已经完成了字符驱动的文件操作接口,所以编写input类设备驱动的核心工作是完成input系统留出的接口

。input子系统的框架如图所示:

由此可以看出,

输入子系统由input驱动层(input driver)、input核心层(input core)和事件处理层(event handler)3部分组成

。一个输入事件,如触摸屏按下、按键按下、鼠标移动等动作信息传输路劲:input设备驱动(input driver)->input核心层(input core)->事件处理层(event handler)->用户空间(userspace)传递到用户空间的应用程序。


8.2 input驱动层

input驱动的编写一般只需要修改这一层,驱动核心层和事件处理层一般无需作代码修改。具体方法如下:

(1)输入事件驱动层和输入核心层不需要动,只需要编写设备驱动层(input驱动层)

(2)设备驱动层编写的接口和调用模式已定义好,驱动工程师的核心工作量是对具体输入设备硬件的操作和性能调优。

(3)input子系统不算复杂,学习时要注意“标准模式”四个字。


8.3 驱动核心层

虽然input驱动编写一般无需修改这一层的代码但是这里还是作一下介绍。驱动核心层的最关键信息集中在两个文件即input.h和input.c中。打开目录include/linux/input.h可以看到input_dev结构体的定义,这个结构体是input设备在linux内核中的模拟,即里面记录了一个input设备的所有信息。

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)];成员进行补充说明。该成员就是用于设置支持事件的,而所支持的事件种类定义如下:

#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        //电源事件

#define EV_FF_STATUS   0x17        //受力状态事件

在input.h文件中还能看到input设备的分配、注册、注销函数,函数结构如下:

int __must_check input_register_device(struct input_dev *);

void input_unregister_device(struct input_dev *);

struct input_dev __must_check *devm_input_allocate_device(struct device *);

其它重要函数:

void input_set_abs_params(struct input_dev *dev, unsigned int axis,

int min, int max, int fuzz, int flat);//设个函数是设定相应的位来支持某一类的绝对值坐标的

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_rel(struct input_dev *dev, unsigned int code, int value)

{//发送相对坐标事件时向子系统报告

input_event(dev, EV_REL, code, value);

}

static inline void input_report_abs(struct input_dev *dev, unsigned int code, int value)

{//发送绝对坐标事件时向子系统报告

input_event(dev, EV_ABS, code, value);

}


8.4 input子系统事件处理层

虽然input驱动编写一般无需修改这一层的代码但是这里还是作一下介绍。事件处理层主要功能是完成相应的input设备所传递事件的处理功能。对于事件处理层的分析,可以从两个基本结构即input_handler和input_handle开始,然后沿着input字符设备的注册和打开过程一直进入到drivers/input/evdev.c文件中的evdev_fops结构结束。接下来就按照这条主线首先分析两个重要的结构体。input_handler和input_handle结构体在include/linux/input.h头文件可以找到。

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;

};

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;

};

从名称就可以看出,input_handler是用来处理input设备的一个结构体,每一个input设备在注册时都会遍历input_handler_list链表上的每一个input_handler,去寻找与之对应的那个input_handler;同理,每一个input_handler在注册时,也会去input_dev_list上寻找那个属于它的input_dev。

input_handle并不难理解,它就是input_dev和input_handler的黏合剂,通过input_handle的联系,input_dev和input_handler就能够产生对应关系。

以下将要分析input设备的打开和注册过程用以了解事件处理层的工作过程。在drivers/input/input.c中可以看到input字符设备的注册过程为

static int __init input_init(void)

{

int err;

……..

err = class_register(&input_class);

err = input_proc_init();    //

注册file_operations

err = register_chrdev(INPUT_MAJOR, “input”, &input_fops);

……..

}

input设备注册中又调用了inptu_fops结构体。从drivers/input/input.c文件中可以看到其定义:

static const struct file_operations input_fops = {

.owner = THIS_MODULE,

.open  = input_open_file,

};

在注册过程中会完成input_dev和input_handler的匹配过程,在完成匹配后就会调用相应input_handler的connect。以input字符设备为例,就会调用evdev_handler,evdev_handler位于drivers/input/evdev.c中读者可以自行查阅。

注册完input字符设备后,接着看设备是如何打开的。之前已经提到,input子系统已经将file_operations的接口函数完成,但针对不同类型的input设备,对应的file_operations中的实现函数也是不一样的。这个不一样是由evdev_handler中的evdev_fops方法决定,其位于drivers\input\evdev.c。

static const 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,

#ifdef CONFIG_COMPAT

.compat_ioctl    = evdev_ioctl_compat,

#endif

.fasync        = evdev_fasync,

.flush        = evdev_flush,

.llseek        = no_llseek,

};

input信息如何传递给GUI的呢?通过事件传递,事件驱动型GUI框架,如QT、VC等。


8.5.input设备应用层编程实践1

8.5.1、确定设备文件名


(

1)应用层操作驱动有2条路:/dev目录下的设备文件,/sys目录下的属性文件


(2)input子系统用的/dev目录下的设备文件,具体一般是 /dev/input/eventn

(3)用cat命令来确认某个设备文件名对应哪个具体设备。我在自己的ubuntu中实测的键盘是event1,而鼠标是event3.

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <linux/input.h>
#include <string.h>


#define DEVICE_KEY			"/dev/input/event1"
#define DEVICE_MOUSE		"/dev/input/event3"


int main(void)
{
	int fd = -1, ret = -1;
	struct input_event ev;
	
	// 第1步:打开设备文件
	fd = open(DEVICE_KEY, O_RDONLY);
	if (fd < 0)
	{
		perror("open");
		return -1;
	}
	
	while (1)
	{
		// 第2步:读取一个event事件包
		memset(&ev, 0, sizeof(struct input_event));
		ret = read(fd, &ev, sizeof(struct input_event));
		if (ret != sizeof(struct input_event))
		{
			perror("read");
			close(fd);
			return -1;
		}
		
		// 第3步:解析event包,才知道发生了什么样的输入事件
		printf("%s.\n", (unsigned char *)&ev);	
	}
	
	
	// 第4步:关闭设备
	close(fd);
	
	return 0;
}

解析键盘事件数据

解析鼠标事件数据

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <linux/input.h>
#include <string.h>


#define DEVICE_KEY			"/dev/input/event1"
#define DEVICE_MOUSE		"/dev/input/event3"

#define X210_KEY			"/dev/input/event1"


int main(void)
{
	int fd = -1, ret = -1;
	struct input_event ev;
	
	// 第1步:打开设备文件
	fd = open(X210_KEY, O_RDONLY);
	if (fd < 0)
	{
		perror("open");
		return -1;
	}
	
	while (1)
	{
		// 第2步:读取一个event事件包
		memset(&ev, 0, sizeof(struct input_event));
		ret = read(fd, &ev, sizeof(struct input_event));
		if (ret != sizeof(struct input_event))
		{
			perror("read");
			close(fd);
			return -1;
		}
		
		// 第3步:解析event包,才知道发生了什么样的输入事件
		printf("-------------------------\n");
		printf("type: %hd\n", ev.type);
		printf("code: %hd\n", ev.code);
		printf("value: %d\n", ev.value);
		printf("\n");
	}
	
	
	// 第4步:关闭设备
	close(fd);
	
	return 0;
}


8.6.中断方式按键驱动实战


(1)input类设备驱动模式非常固定,用参考模版修改即可

(2)新建驱动项目并粘贴模版内容

#include <linux/input.h> 
#include <linux/module.h> 
#include <linux/init.h>
#include <asm/irq.h> 
#include <asm/io.h>

#include <mach/irqs.h>			// arch/arm/mach-s5pv210/include/mach/irqs.h
#include <linux/interrupt.h>
#include <linux/gpio.h>

/*
 * X210:
 *
 * POWER  -> EINT1   -> GPH0_1
 * LEFT   -> EINT2   -> GPH0_2
 * DOWN   -> EINT3   -> GPH0_3
 * UP     -> KP_COL0 -> GPH2_0
 * RIGHT  -> KP_COL1 -> GPH2_1
 * MENU   -> KP_COL3 -> GPH2_3 (KEY_A)
 * BACK   -> KP_COL2 -> GPH2_2 (KEY_B)
 */

#define BUTTON_IRQ	IRQ_EINT2

static struct input_dev *button_dev;

static irqreturn_t button_interrupt(int irq, void *dummy) 
{ 
	int flag;

	s3c_gpio_cfgpin(S5PV210_GPH0(2), S3C_GPIO_SFN(0x0));		// input模式
	flag = gpio_get_value(S5PV210_GPH0(2));
	s3c_gpio_cfgpin(S5PV210_GPH0(2), S3C_GPIO_SFN(0x0f));		// eint2模式
    //报告按键事件,键值为!flag
	input_report_key(button_dev, KEY_LEFT, !flag);
    //等待接受方收到数据后回复确认,用于同步
	input_sync(button_dev);
	return IRQ_HANDLED; 
}

static int __init button_init(void) 
{ 
	int error;
	
	error = gpio_request(S5PV210_GPH0(2), "GPH0_2");
	if(error)
		printk("key-s5pv210: request gpio GPH0(2) fail");
	s3c_gpio_cfgpin(S5PV210_GPH0(2), S3C_GPIO_SFN(0x0f));		// eint2模式

	//申请按键中断,按下和抬起边沿触发
	if (request_irq(BUTTON_IRQ, button_interrupt, IRQF_TRIGGER_FALLING | IRQF_TRIGGER_RISING, "button-x210", NULL)) 
	{ 
		printk(KERN_ERR "key-s5pv210.c: Can't allocate irq %d\n", BUTTON_IRQ);
		return -EBUSY; 
	}
    //给输入设备申请空间,该函数定义在input.h
	button_dev = input_allocate_device();
	if (!button_dev) 
	{ 
		printk(KERN_ERR "key-s5pv210.c: Not enough memory\n");
		error = -ENOMEM;
		goto err_free_irq; 
	}
	
    //evbit字段用于描述支持的事件,这里支持按键事件
	button_dev->evbit[0] = BIT_MASK(EV_KEY);
    //keybit字段用于描述按键的类型,在input.h中定义了很多
	button_dev->keybit[BIT_WORD(KEY_LEFT)] = BIT_MASK(KEY_LEFT);
	
    //把按键设备注册到输入子系统中
	error = input_register_device(button_dev);
	if (error) 
	{ 
		printk(KERN_ERR "key-s5pv210.c: Failed to register device\n");
		goto err_free_dev; 
	}
	return 0;
	
err_free_dev:
	input_free_device(button_dev);
err_free_irq:
	free_irq(BUTTON_IRQ, button_interrupt);
	return error; 
}

static void __exit button_exit(void) 
{ 
	input_unregister_device(button_dev); 
	free_irq(BUTTON_IRQ, button_interrupt); 
}

module_init(button_init); 
module_exit(button_exit); 

MODULE_LICENSE("GPL");
MODULE_AUTHOR("aston <1264671872@qq.com>");
MODULE_DESCRIPTION("key driver for x210 button.");






8.7 IIC触摸屏驱动例子

源码目录:drivers\input\touchscreen\goodix.c

以汇顶的IIC触摸屏为例,该例子使用IIC驱动总线注册驱动的同时注册实现了input设备驱动,具体见goodix_configure_dev

static int goodix_configure_dev(struct goodix_ts_data *ts)

{


int error;

……..

//实现并注册input设备驱动

error = goodix_request_input_dev(ts);

if (error)

return error;

//注册触摸屏点击中断,里面有input事件上报,见goodix_process_events的input_report_key

ts->irq_flags = goodix_irq_flags[ts->int_trigger_type] | IRQF_ONESHOT;

error = goodix_request_irq(ts);

……..

return 0;

}

/**

* goodix_process_events – Process incoming events

*

* @ts: our goodix_ts_data pointer

*

* Called when the IRQ is triggered. Read the current device state, and push

* the input events to the user space.

*/

static void goodix_process_events(struct goodix_ts_data *ts)

{


u8  point_data[1 + GOODIX_CONTACT_SIZE * GOODIX_MAX_CONTACTS];

int touch_num;

int i;

touch_num = goodix_ts_read_input_report(ts, point_data);

if (touch_num < 0)

return;

/*

* Bit 4 of the first byte reports the status of the capacitive

* Windows/Home button.

*/

input_report_key(ts->input_dev, KEY_LEFTMETA, point_data[0] & BIT(4));

for (i = 0; i < touch_num; i++)

goodix_ts_report_touch(ts,

&point_data[1 + GOODIX_CONTACT_SIZE * i]);

input_mt_sync_frame(ts->input_dev);

input_sync(ts->input_dev);

}

完整代码如下:

/*
 *  Driver for Goodix Touchscreens
 *
 *  Copyright (c) 2014 Red Hat Inc.
 *  Copyright (c) 2015 K. Merker <merker@debian.org>
 *
 *  This code is based on gt9xx.c authored by andrew@goodix.com:
 *
 *  2010 - 2012 Goodix Technology.
 */

/*
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; version 2 of the License.
 */

#include <linux/kernel.h>
#include <linux/dmi.h>
#include <linux/firmware.h>
#include <linux/gpio/consumer.h>
#include <linux/i2c.h>
#include <linux/input.h>
#include <linux/input/mt.h>
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/irq.h>
#include <linux/interrupt.h>
#include <linux/slab.h>
#include <linux/acpi.h>
#include <linux/of.h>
#include <asm/unaligned.h>
#include "../../gpio/gpiolib.h"

struct goodix_ts_data {
    struct i2c_client *client;
    struct input_dev *input_dev;
    int abs_x_max;
    int abs_y_max;
    bool swapped_x_y;
    bool inverted_x;
    bool inverted_y;
    unsigned int max_touch_num;
    unsigned int int_trigger_type;
    int cfg_len;
    struct gpio_desc *gpiod_int;
    struct gpio_desc *gpiod_rst;
    u16 id;
    u16 version;
    const char *cfg_name;
    struct completion firmware_loading_complete;
    unsigned long irq_flags;
};

#define GOODIX_GPIO_INT_NAME        "irq"
//#define GOODIX_GPIO_RST_NAME        "reset"
#define GOODIX_GPIO_RST_NAME        "rst"


#define GOODIX_MAX_HEIGHT        854
#define GOODIX_MAX_WIDTH        480
#define GOODIX_INT_TRIGGER        1
#define GOODIX_CONTACT_SIZE        8
#define GOODIX_MAX_CONTACTS        10

#define GOODIX_CONFIG_MAX_LENGTH    240
#define GOODIX_CONFIG_911_LENGTH    186
#define GOODIX_CONFIG_967_LENGTH    228

/* Register defines */
#define GOODIX_REG_COMMAND        0x8040
#define GOODIX_CMD_SCREEN_OFF        0x05

#define GOODIX_READ_COOR_ADDR        0x814E
#define GOODIX_REG_CONFIG_DATA        0x8047
#define GOODIX_REG_ID            0x8140

#define GOODIX_BUFFER_STATUS_READY    BIT(7)
#define GOODIX_BUFFER_STATUS_TIMEOUT    20

#define RESOLUTION_LOC        1
#define MAX_CONTACTS_LOC    5
#define TRIGGER_LOC        6

static const unsigned long goodix_irq_flags[] = {
    IRQ_TYPE_EDGE_RISING,
    IRQ_TYPE_EDGE_FALLING,
    IRQ_TYPE_LEVEL_LOW,
    IRQ_TYPE_LEVEL_HIGH,
};

/*
 * Those tablets have their coordinates origin at the bottom right
 * of the tablet, as if rotated 180 degrees
 */
static const struct dmi_system_id rotated_screen[] = {
#if defined(CONFIG_DMI) && defined(CONFIG_X86)
    {
        .ident = "WinBook TW100",
        .matches = {
            DMI_MATCH(DMI_SYS_VENDOR, "WinBook"),
            DMI_MATCH(DMI_PRODUCT_NAME, "TW100")
        }
    },
    {
        .ident = "WinBook TW700",
        .matches = {
            DMI_MATCH(DMI_SYS_VENDOR, "WinBook"),
            DMI_MATCH(DMI_PRODUCT_NAME, "TW700")
        },
    },
#endif
    {}
};

/**
 * goodix_i2c_read - read data from a register of the i2c slave device.
 *
 * @client: i2c device.
 * @reg: the register to read from.
 * @buf: raw write data buffer.
 * @len: length of the buffer to write
 */
static int goodix_i2c_read(struct i2c_client *client,
               u16 reg, u8 *buf, int len)
{
    struct i2c_msg msgs[2];
    u16 wbuf = cpu_to_be16(reg);
    int ret;

    msgs[0].flags = 0;
    msgs[0].addr  = client->addr;
    msgs[0].len   = 2;
    msgs[0].buf   = (u8 *)&wbuf;

    msgs[1].flags = I2C_M_RD;
    msgs[1].addr  = client->addr;
    msgs[1].len   = len;
    msgs[1].buf   = buf;

    ret = i2c_transfer(client->adapter, msgs, 2);
    return ret < 0 ? ret : (ret != ARRAY_SIZE(msgs) ? -EIO : 0);
}

/**
 * goodix_i2c_write - write data to a register of the i2c slave device.
 *
 * @client: i2c device.
 * @reg: the register to write to.
 * @buf: raw data buffer to write.
 * @len: length of the buffer to write
 */
static int goodix_i2c_write(struct i2c_client *client, u16 reg, const u8 *buf,
                unsigned len)
{
    u8 *addr_buf;
    struct i2c_msg msg;
    int ret;

    addr_buf = kmalloc(len + 2, GFP_KERNEL);
    if (!addr_buf)
        return -ENOMEM;

    addr_buf[0] = reg >> 8;
    addr_buf[1] = reg & 0xFF;
    memcpy(&addr_buf[2], buf, len);

    msg.flags = 0;
    msg.addr = client->addr;
    msg.buf = addr_buf;
    msg.len = len + 2;

    ret = i2c_transfer(client->adapter, &msg, 1);
    kfree(addr_buf);
    return ret < 0 ? ret : (ret != 1 ? -EIO : 0);
}

static int goodix_i2c_write_u8(struct i2c_client *client, u16 reg, u8 value)
{
    return goodix_i2c_write(client, reg, &value, sizeof(value));
}

static int goodix_get_cfg_len(u16 id)
{
    switch (id) {
    case 911:
    case 9271:
    case 9110:
    case 927:
    case 928:
        return GOODIX_CONFIG_911_LENGTH;

    case 912:
    case 967:
        return GOODIX_CONFIG_967_LENGTH;

    default:
        return GOODIX_CONFIG_MAX_LENGTH;
    }
}

static int goodix_ts_read_input_report(struct goodix_ts_data *ts, u8 *data)
{
    unsigned long max_timeout;
    int touch_num;
    int error;

    /*
     * The 'buffer status' bit, which indicates that the data is valid, is
     * not set as soon as the interrupt is raised, but slightly after.
     * This takes around 10 ms to happen, so we poll for 20 ms.
     */
    max_timeout = jiffies + msecs_to_jiffies(GOODIX_BUFFER_STATUS_TIMEOUT);
    do {
        error = goodix_i2c_read(ts->client, GOODIX_READ_COOR_ADDR,
                    data, GOODIX_CONTACT_SIZE + 1);
        if (error) {
            dev_err(&ts->client->dev, "I2C transfer error: %d\n",
                    error);
            return error;
        }

        if (data[0] & GOODIX_BUFFER_STATUS_READY) {
            touch_num = data[0] & 0x0f;
            if (touch_num > ts->max_touch_num)
                return -EPROTO;
            if((data[0]&0x80)==0)//坐标未就绪,数据无效
                return -EPROTO;
            if (touch_num > 1) {
                data += 1 + GOODIX_CONTACT_SIZE;
                error = goodix_i2c_read(ts->client,
                        GOODIX_READ_COOR_ADDR +
                            1 + GOODIX_CONTACT_SIZE,
                        data,
                        GOODIX_CONTACT_SIZE *
                            (touch_num - 1));
                if (error)
                    return error;
            }

            return touch_num;
        }

        usleep_range(1000, 2000); /* Poll every 1 - 2 ms */
    } while (time_before(jiffies, max_timeout));

    /*
     * The Goodix panel will send spurious interrupts after a
     * 'finger up' event, which will always cause a timeout.
     */
    return 0;
}

static void goodix_ts_report_touch(struct goodix_ts_data *ts, u8 *coor_data)
{
    int id = coor_data[0] & 0x0F;
    int input_x = get_unaligned_le16(&coor_data[1]);
    int input_y = get_unaligned_le16(&coor_data[3]);
    int input_w = get_unaligned_le16(&coor_data[5]);

    /* Inversions have to happen before axis swapping */
    if (ts->inverted_x)
        input_x = ts->abs_x_max - input_x;
    if (ts->inverted_y)
        input_y = ts->abs_y_max - input_y;
    if (ts->swapped_x_y)
        swap(input_x, input_y);

    input_mt_slot(ts->input_dev, id);
    input_mt_report_slot_state(ts->input_dev, MT_TOOL_FINGER, true);
    input_report_abs(ts->input_dev, ABS_MT_POSITION_X, input_x);
    input_report_abs(ts->input_dev, ABS_MT_POSITION_Y, input_y);
    input_report_abs(ts->input_dev, ABS_MT_TOUCH_MAJOR, input_w);
    input_report_abs(ts->input_dev, ABS_MT_WIDTH_MAJOR, input_w);
}

/**
 * goodix_process_events - Process incoming events
 *
 * @ts: our goodix_ts_data pointer
 *
 * Called when the IRQ is triggered. Read the current device state, and push
 * the input events to the user space.
 */
static void goodix_process_events(struct goodix_ts_data *ts)
{
    u8  point_data[1 + GOODIX_CONTACT_SIZE * GOODIX_MAX_CONTACTS];
    int touch_num;
    int i;

    touch_num = goodix_ts_read_input_report(ts, point_data);
    if (touch_num < 0)
        return;

    /*
     * Bit 4 of the first byte reports the status of the capacitive
     * Windows/Home button.
     */
    input_report_key(ts->input_dev, KEY_LEFTMETA, point_data[0] & BIT(4));

    for (i = 0; i < touch_num; i++)
        goodix_ts_report_touch(ts,
                &point_data[1 + GOODIX_CONTACT_SIZE * i]);

    input_mt_sync_frame(ts->input_dev);
    input_sync(ts->input_dev);
}

/**
 * goodix_ts_irq_handler - The IRQ handler
 *
 * @irq: interrupt number.
 * @dev_id: private data pointer.
 */
static irqreturn_t goodix_ts_irq_handler(int irq, void *dev_id)
{
    struct goodix_ts_data *ts = dev_id;

    goodix_process_events(ts);

    if (goodix_i2c_write_u8(ts->client, GOODIX_READ_COOR_ADDR, 0) < 0)
        dev_err(&ts->client->dev, "I2C write end_cmd error\n");

    return IRQ_HANDLED;
}

static void goodix_free_irq(struct goodix_ts_data *ts)
{
    devm_free_irq(&ts->client->dev, ts->client->irq, ts);
}

static int goodix_request_irq(struct goodix_ts_data *ts)
{
    return devm_request_threaded_irq(&ts->client->dev, ts->client->irq,
                     NULL, goodix_ts_irq_handler,
                     ts->irq_flags, ts->client->name, ts);
}

/**
 * goodix_check_cfg - Checks if config fw is valid
 *
 * @ts: goodix_ts_data pointer
 * @cfg: firmware config data
 */
static int goodix_check_cfg(struct goodix_ts_data *ts,
                const struct firmware *cfg)
{
    int i, raw_cfg_len;
    u8 check_sum = 0;

    if (cfg->size > GOODIX_CONFIG_MAX_LENGTH) {
        dev_err(&ts->client->dev,
            "The length of the config fw is not correct");
        return -EINVAL;
    }

    raw_cfg_len = cfg->size - 2;
    for (i = 0; i < raw_cfg_len; i++)
        check_sum += cfg->data[i];
    check_sum = (~check_sum) + 1;
    if (check_sum != cfg->data[raw_cfg_len]) {
        dev_err(&ts->client->dev,
            "The checksum of the config fw is not correct");
        return -EINVAL;
    }

    if (cfg->data[raw_cfg_len + 1] != 1) {
        dev_err(&ts->client->dev,
            "Config fw must have Config_Fresh register set");
        return -EINVAL;
    }

    return 0;
}

/**
 * goodix_send_cfg - Write fw config to device
 *
 * @ts: goodix_ts_data pointer
 * @cfg: config firmware to write to device
 */
static int goodix_send_cfg(struct goodix_ts_data *ts,
               const struct firmware *cfg)
{
    int error;

    error = goodix_check_cfg(ts, cfg);
    if (error)
        return error;

    error = goodix_i2c_write(ts->client, GOODIX_REG_CONFIG_DATA, cfg->data,
                 cfg->size);
    if (error) {
        dev_err(&ts->client->dev, "Failed to write config data: %d",
            error);
        return error;
    }
    dev_dbg(&ts->client->dev, "Config sent successfully.");

    /* Let the firmware reconfigure itself, so sleep for 10ms */
    usleep_range(10000, 11000);

    return 0;
}

static int goodix_int_sync(struct goodix_ts_data *ts)
{
    int error;

    error = gpiod_direction_output(ts->gpiod_int, 0);
    if (error)
        return error;

    msleep(50);                /* T5: 50ms */

    error = gpiod_direction_input(ts->gpiod_int);
    if (error)
        return error;

    return 0;
}

/**
 * goodix_reset - Reset device during power on
 *
 * @ts: goodix_ts_data pointer
 */
static int goodix_reset(struct goodix_ts_data *ts)
{
    int error;

    /* begin select I2C slave addr */
    error = gpiod_direction_output(ts->gpiod_rst, 0);    
    if (error)
        return error;

    msleep(15);    

    /* HIGH: 0x28/0x29, LOW: 0xBA/0xBB */
    error = gpiod_direction_output(ts->gpiod_int, ts->client->addr == 0x14);
    if (error)
    {
        printk("[log]gpiod_direction_output int 1 err\r\n");
        return error;
    }
        
    usleep_range(100, 2000);        /* T3: > 100us */

    error = gpiod_direction_output(ts->gpiod_rst, 1);    
    if (error)
    {
        printk("[log]gpiod_direction_output rst 1 err\r\n");
        return error;
    }
        

    usleep_range(6000, 10000);        /* T4: > 5ms */

    
    /* end select I2C slave addr */
    //error = gpiod_direction_input(ts->gpiod_rst);
    //if (error)
    //    return error;
    
    //msleep(50);                /* T5: 50ms */

    error = goodix_int_sync(ts);
    if (error)
        return error;

    return 0;
}

/**
 * goodix_get_gpio_config - Get GPIO config from ACPI/DT
 *
 * @ts: goodix_ts_data pointer
 */
static int goodix_get_gpio_config(struct goodix_ts_data *ts)
{
    int error;
    struct device *dev;
    struct gpio_desc *gpiod;

    if (!ts->client)
        return -EINVAL;
    dev = &ts->client->dev;

    /* Get the interrupt GPIO pin number */
    gpiod = devm_gpiod_get_optional(dev, GOODIX_GPIO_INT_NAME, GPIOD_IN);
    
    if (IS_ERR(gpiod)) {
        error = PTR_ERR(gpiod);
        if (error != -EPROBE_DEFER)
            dev_dbg(dev, "Failed to get %s GPIO: %d\n",
                GOODIX_GPIO_INT_NAME, error);
        return error;
    }

    ts->gpiod_int = gpiod;

    /* Get the reset line GPIO pin number */
    gpiod = devm_gpiod_get_optional(dev, GOODIX_GPIO_RST_NAME, GPIOD_IN);
    if (IS_ERR(gpiod)) {
        error = PTR_ERR(gpiod);
        if (error != -EPROBE_DEFER)
            dev_dbg(dev, "Failed to get %s GPIO: %d\n",
                GOODIX_GPIO_RST_NAME, error);
        return error;
    }

    ts->gpiod_rst = gpiod;

    return 0;
}

/**
 * goodix_read_config - Read the embedded configuration of the panel
 *
 * @ts: our goodix_ts_data pointer
 *
 * Must be called during probe
 */
static void goodix_read_config(struct goodix_ts_data *ts)
{
    u8 config[GOODIX_CONFIG_MAX_LENGTH];
    int error;

    error = goodix_i2c_read(ts->client, GOODIX_REG_CONFIG_DATA,
                config, ts->cfg_len);
    if (error) {
        dev_warn(&ts->client->dev,
             "Error reading config (%d), using defaults\n",
             error);
        ts->abs_x_max = GOODIX_MAX_WIDTH;
        ts->abs_y_max = GOODIX_MAX_HEIGHT;
        if (ts->swapped_x_y)
            swap(ts->abs_x_max, ts->abs_y_max);
        ts->int_trigger_type = GOODIX_INT_TRIGGER;
        ts->max_touch_num = GOODIX_MAX_CONTACTS;
        return;
    }

    ts->abs_x_max = get_unaligned_le16(&config[RESOLUTION_LOC]);
    ts->abs_y_max = get_unaligned_le16(&config[RESOLUTION_LOC + 2]);
    if (ts->swapped_x_y)
        swap(ts->abs_x_max, ts->abs_y_max);
    ts->int_trigger_type = config[TRIGGER_LOC] & 0x03;
    ts->max_touch_num = config[MAX_CONTACTS_LOC] & 0x0f;
    if (!ts->abs_x_max || !ts->abs_y_max || !ts->max_touch_num) {
        dev_err(&ts->client->dev,
            "Invalid config, using defaults\n");
        ts->abs_x_max = GOODIX_MAX_WIDTH;
        ts->abs_y_max = GOODIX_MAX_HEIGHT;
        if (ts->swapped_x_y)
            swap(ts->abs_x_max, ts->abs_y_max);
        ts->max_touch_num = GOODIX_MAX_CONTACTS;
    }

    if (dmi_check_system(rotated_screen)) {
        ts->inverted_x = true;
        ts->inverted_y = true;
        dev_dbg(&ts->client->dev,
             "Applying '180 degrees rotated screen' quirk\n");
    }
}

/**
 * goodix_read_version - Read goodix touchscreen version
 *
 * @ts: our goodix_ts_data pointer
 */
static int goodix_read_version(struct goodix_ts_data *ts)
{
    int error;
    u8 buf[6];
    char id_str[5];

    error = goodix_i2c_read(ts->client, GOODIX_REG_ID, buf, sizeof(buf));
    if (error) {
        dev_err(&ts->client->dev, "read version failed: %d\n", error);
        return error;
    }

    memcpy(id_str, buf, 4);
    id_str[4] = 0;
    if (kstrtou16(id_str, 10, &ts->id))
        ts->id = 0x1001;

    ts->version = get_unaligned_le16(&buf[4]);

    dev_info(&ts->client->dev, "ID %d, version: %04x\n", ts->id,
         ts->version);

    return 0;
}

/**
 * goodix_i2c_test - I2C test function to check if the device answers.
 *
 * @client: the i2c client
 */
static int goodix_i2c_test(struct i2c_client *client)
{
    int retry = 0;
    int error;
    u8 test;

    while (retry++ < 2) {
        error = goodix_i2c_read(client, GOODIX_REG_CONFIG_DATA,
                    &test, 1);
        if (!error)
            return 0;

        dev_err(&client->dev, "i2c test failed attempt %d: %d\n",
            retry, error);
        msleep(20);
    }

    return error;
}

/**
 * goodix_request_input_dev - Allocate, populate and register the input device
 *
 * @ts: our goodix_ts_data pointer
 *
 * Must be called during probe
 */
static int goodix_request_input_dev(struct goodix_ts_data *ts)
{
    int error;

    ts->input_dev = devm_input_allocate_device(&ts->client->dev);
    if (!ts->input_dev) {
        dev_err(&ts->client->dev, "Failed to allocate input device.");
        return -ENOMEM;
    }

    input_set_abs_params(ts->input_dev, ABS_MT_POSITION_X,
                 0, ts->abs_x_max, 0, 0);
    input_set_abs_params(ts->input_dev, ABS_MT_POSITION_Y,
                 0, ts->abs_y_max, 0, 0);
    input_set_abs_params(ts->input_dev, ABS_MT_WIDTH_MAJOR, 0, 255, 0, 0);
    input_set_abs_params(ts->input_dev, ABS_MT_TOUCH_MAJOR, 0, 255, 0, 0);

    input_mt_init_slots(ts->input_dev, ts->max_touch_num,
                INPUT_MT_DIRECT | INPUT_MT_DROP_UNUSED);

    ts->input_dev->name = "Goodix Capacitive TouchScreen";
    ts->input_dev->phys = "input/ts";
    ts->input_dev->id.bustype = BUS_I2C;
    ts->input_dev->id.vendor = 0x0416;
    ts->input_dev->id.product = ts->id;
    ts->input_dev->id.version = ts->version;

    /* Capacitive Windows/Home button on some devices */
    input_set_capability(ts->input_dev, EV_KEY, KEY_LEFTMETA);

    error = input_register_device(ts->input_dev);
    if (error) {
        dev_err(&ts->client->dev,
            "Failed to register input device: %d", error);
        return error;
    }

    return 0;
}

/**
 * goodix_configure_dev - Finish device initialization
 *
 * @ts: our goodix_ts_data pointer
 *
 * Must be called from probe to finish initialization of the device.
 * Contains the common initialization code for both devices that
 * declare gpio pins and devices that do not. It is either called
 * directly from probe or from request_firmware_wait callback.
 */
static int goodix_configure_dev(struct goodix_ts_data *ts)
{
    int error;

    ts->swapped_x_y = device_property_read_bool(&ts->client->dev,
                            "touchscreen-swapped-x-y");
    ts->inverted_x = device_property_read_bool(&ts->client->dev,
                           "touchscreen-inverted-x");
    ts->inverted_y = device_property_read_bool(&ts->client->dev,
                           "touchscreen-inverted-y");

    goodix_read_config(ts);

    error = goodix_request_input_dev(ts);
    if (error)
        return error;

    ts->irq_flags = goodix_irq_flags[ts->int_trigger_type] | IRQF_ONESHOT;
    error = goodix_request_irq(ts);
    if (error) {
        dev_err(&ts->client->dev, "request IRQ failed: %d\n", error);
        return error;
    }

    return 0;
}

/**
 * goodix_config_cb - Callback to finish device init
 *
 * @ts: our goodix_ts_data pointer
 *
 * request_firmware_wait callback that finishes
 * initialization of the device.
 */
static void goodix_config_cb(const struct firmware *cfg, void *ctx)
{
    struct goodix_ts_data *ts = ctx;
    int error;

    if (cfg) {
        /* send device configuration to the firmware */
        error = goodix_send_cfg(ts, cfg);
        if (error)
            goto err_release_cfg;
    }

    goodix_configure_dev(ts);

err_release_cfg:
    release_firmware(cfg);
    complete_all(&ts->firmware_loading_complete);
}

static int goodix_ts_probe(struct i2c_client *client,
               const struct i2c_device_id *id)
{
    struct goodix_ts_data *ts;
    int error;

    dev_dbg(&client->dev, "I2C Address: 0x%02x\n", client->addr);

    if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) {
        dev_err(&client->dev, "I2C check functionality failed.\n");
        return -ENXIO;
    }

    ts = devm_kzalloc(&client->dev, sizeof(*ts), GFP_KERNEL);
    if (!ts)
        return -ENOMEM;

    ts->client = client;
    i2c_set_clientdata(client, ts);
    init_completion(&ts->firmware_loading_complete);

    error = goodix_get_gpio_config(ts);
    if (error)
    {
        printk("[log]goodix_get_gpio_config\r\n");
        return error;
    }
        

    if (ts->gpiod_int && ts->gpiod_rst) {
        /* reset the controller */
        error = goodix_reset(ts);
        if (error) {
            dev_err(&client->dev, "Controller reset failed.\n");
            return error;
        }
    }

    error = goodix_i2c_test(client);
    if (error) {
        printk("[log]I2C communication failure: %d\n",error);
        dev_err(&client->dev, "I2C communication failure: %d\n", error);
        return error;
    }

    error = goodix_read_version(ts);
    if (error) {
        printk("[log]Read version failed.\n");
        dev_err(&client->dev, "Read version failed.\n");
        return error;
    }

    ts->cfg_len = goodix_get_cfg_len(ts->id);

    if (ts->gpiod_int && ts->gpiod_rst) {
        /* update device config */
        ts->cfg_name = devm_kasprintf(&client->dev, GFP_KERNEL,
                          "goodix_%d_cfg.bin", ts->id);
        if (!ts->cfg_name)
            return -ENOMEM;

        error = request_firmware_nowait(THIS_MODULE, true, ts->cfg_name,
                        &client->dev, GFP_KERNEL, ts,
                        goodix_config_cb);
        if (error) {
            dev_err(&client->dev,
                "Failed to invoke firmware loader: %d\n",
                error);
            return error;
        }

        return 0;
    } else {
        error = goodix_configure_dev(ts);
        if (error)
            return error;
    }

    return 0;
}

static int goodix_ts_remove(struct i2c_client *client)
{
    struct goodix_ts_data *ts = i2c_get_clientdata(client);

    if (ts->gpiod_int && ts->gpiod_rst)
        wait_for_completion(&ts->firmware_loading_complete);

    return 0;
}

static int __maybe_unused goodix_suspend(struct device *dev)
{
    struct i2c_client *client = to_i2c_client(dev);
    struct goodix_ts_data *ts = i2c_get_clientdata(client);
    int error;

    /* We need gpio pins to suspend/resume */
    if (!ts->gpiod_int || !ts->gpiod_rst) {
        disable_irq(client->irq);
        return 0;
    }

    wait_for_completion(&ts->firmware_loading_complete);

    /* Free IRQ as IRQ pin is used as output in the suspend sequence */
    goodix_free_irq(ts);

    /* Output LOW on the INT pin for 5 ms */
    error = gpiod_direction_output(ts->gpiod_int, 0);
    if (error) {
        goodix_request_irq(ts);
        return error;
    }

    usleep_range(5000, 6000);

    error = goodix_i2c_write_u8(ts->client, GOODIX_REG_COMMAND,
                    GOODIX_CMD_SCREEN_OFF);
    if (error) {
        dev_err(&ts->client->dev, "Screen off command failed\n");
        gpiod_direction_input(ts->gpiod_int);
        goodix_request_irq(ts);
        return -EAGAIN;
    }

    /*
     * The datasheet specifies that the interval between sending screen-off
     * command and wake-up should be longer than 58 ms. To avoid waking up
     * sooner, delay 58ms here.
     */
    msleep(58);
    return 0;
}

static int __maybe_unused goodix_resume(struct device *dev)
{
    struct i2c_client *client = to_i2c_client(dev);
    struct goodix_ts_data *ts = i2c_get_clientdata(client);
    int error;

    if (!ts->gpiod_int || !ts->gpiod_rst) {
        enable_irq(client->irq);
        return 0;
    }

    /*
     * Exit sleep mode by outputting HIGH level to INT pin
     * for 2ms~5ms.
     */
    error = gpiod_direction_output(ts->gpiod_int, 1);
    if (error)
        return error;

    usleep_range(2000, 5000);

    error = goodix_int_sync(ts);
    if (error)
        return error;

    error = goodix_request_irq(ts);
    if (error)
        return error;

    return 0;
}

static SIMPLE_DEV_PM_OPS(goodix_pm_ops, goodix_suspend, goodix_resume);

static const struct i2c_device_id goodix_ts_id[] = {
    { "GDIX1001:00", 0 },
    { }
};
MODULE_DEVICE_TABLE(i2c, goodix_ts_id);

#ifdef CONFIG_ACPI
static const struct acpi_device_id goodix_acpi_match[] = {
    { "GDIX1001", 0 },
    { "GDIX1002", 0 },
    { }
};
MODULE_DEVICE_TABLE(acpi, goodix_acpi_match);
#endif

#ifdef CONFIG_OF
static const struct of_device_id goodix_of_match[] = {
    { .compatible = "goodix,gt911" },
    { .compatible = "goodix,gt9110" },
    { .compatible = "goodix,gt912" },
    { .compatible = "goodix,gt927" },
    { .compatible = "goodix,gt9271" },
    { .compatible = "goodix,gt928" },
    { .compatible = "goodix,gt967" },
    { }
};
MODULE_DEVICE_TABLE(of, goodix_of_match);
#endif

static struct i2c_driver goodix_ts_driver = {
    .probe = goodix_ts_probe,
    .remove = goodix_ts_remove,
    .id_table = goodix_ts_id,
    .driver = {
        .name = "Goodix-TS",
        .acpi_match_table = ACPI_PTR(goodix_acpi_match),
        .of_match_table = of_match_ptr(goodix_of_match),
        .pm = &goodix_pm_ops,
    },
};
module_i2c_driver(goodix_ts_driver);

MODULE_AUTHOR("Benjamin Tissoires <benjamin.tissoires@gmail.com>");
MODULE_AUTHOR("Bastien Nocera <hadess@hadess.net>");
MODULE_DESCRIPTION("Goodix touchscreen driver");
MODULE_LICENSE("GPL v2");



版权声明:本文为luoguoxian12原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。