1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Elan Microelectronics touch panels with I2C interface
4  *
5  * Copyright (C) 2014 Elan Microelectronics Corporation.
6  * Scott Liu <scott.liu@emc.com.tw>
7  *
8  * This code is partly based on hid-multitouch.c:
9  *
10  *  Copyright (c) 2010-2012 Stephane Chatty <chatty@enac.fr>
11  *  Copyright (c) 2010-2012 Benjamin Tissoires <benjamin.tissoires@gmail.com>
12  *  Copyright (c) 2010-2012 Ecole Nationale de l'Aviation Civile, France
13  *
14  * This code is partly based on i2c-hid.c:
15  *
16  * Copyright (c) 2012 Benjamin Tissoires <benjamin.tissoires@gmail.com>
17  * Copyright (c) 2012 Ecole Nationale de l'Aviation Civile, France
18  * Copyright (c) 2012 Red Hat, Inc
19  */
20 
21 
22 #include <linux/bits.h>
23 #include <linux/module.h>
24 #include <linux/input.h>
25 #include <linux/interrupt.h>
26 #include <linux/irq.h>
27 #include <linux/platform_device.h>
28 #include <linux/async.h>
29 #include <linux/i2c.h>
30 #include <linux/delay.h>
31 #include <linux/uaccess.h>
32 #include <linux/buffer_head.h>
33 #include <linux/slab.h>
34 #include <linux/firmware.h>
35 #include <linux/input/mt.h>
36 #include <linux/input/touchscreen.h>
37 #include <linux/acpi.h>
38 #include <linux/of.h>
39 #include <linux/pm_wakeirq.h>
40 #include <linux/gpio/consumer.h>
41 #include <linux/regulator/consumer.h>
42 #include <linux/uuid.h>
43 #include <asm/unaligned.h>
44 
45 /* Device, Driver information */
46 #define DEVICE_NAME	"elants_i2c"
47 
48 /* Convert from rows or columns into resolution */
49 #define ELAN_TS_RESOLUTION(n, m)   (((n) - 1) * (m))
50 
51 /* FW header data */
52 #define HEADER_SIZE		4
53 #define FW_HDR_TYPE		0
54 #define FW_HDR_COUNT		1
55 #define FW_HDR_LENGTH		2
56 
57 /* Buffer mode Queue Header information */
58 #define QUEUE_HEADER_SINGLE	0x62
59 #define QUEUE_HEADER_NORMAL	0X63
60 #define QUEUE_HEADER_WAIT	0x64
61 #define QUEUE_HEADER_NORMAL2	0x66
62 
63 /* Command header definition */
64 #define CMD_HEADER_WRITE	0x54
65 #define CMD_HEADER_READ		0x53
66 #define CMD_HEADER_6B_READ	0x5B
67 #define CMD_HEADER_ROM_READ	0x96
68 #define CMD_HEADER_RESP		0x52
69 #define CMD_HEADER_6B_RESP	0x9B
70 #define CMD_HEADER_ROM_RESP	0x95
71 #define CMD_HEADER_HELLO	0x55
72 #define CMD_HEADER_REK		0x66
73 
74 /* FW position data */
75 #define PACKET_SIZE_OLD		40
76 #define PACKET_SIZE		55
77 #define MAX_CONTACT_NUM		10
78 #define FW_POS_HEADER		0
79 #define FW_POS_STATE		1
80 #define FW_POS_TOTAL		2
81 #define FW_POS_XY		3
82 #define FW_POS_TOOL_TYPE	33
83 #define FW_POS_CHECKSUM		34
84 #define FW_POS_WIDTH		35
85 #define FW_POS_PRESSURE		45
86 
87 #define HEADER_REPORT_10_FINGER	0x62
88 
89 /* Header (4 bytes) plus 3 full 10-finger packets */
90 #define MAX_PACKET_SIZE		169
91 
92 #define BOOT_TIME_DELAY_MS	50
93 
94 /* FW read command, 0x53 0x?? 0x0, 0x01 */
95 #define E_ELAN_INFO_FW_VER	0x00
96 #define E_ELAN_INFO_BC_VER	0x10
97 #define E_ELAN_INFO_X_RES	0x60
98 #define E_ELAN_INFO_Y_RES	0x63
99 #define E_ELAN_INFO_REK		0xD0
100 #define E_ELAN_INFO_TEST_VER	0xE0
101 #define E_ELAN_INFO_FW_ID	0xF0
102 #define E_INFO_OSR		0xD6
103 #define E_INFO_PHY_SCAN		0xD7
104 #define E_INFO_PHY_DRIVER	0xD8
105 
106 /* FW write command, 0x54 0x?? 0x0, 0x01 */
107 #define E_POWER_STATE_SLEEP	0x50
108 #define E_POWER_STATE_RESUME	0x58
109 
110 #define MAX_RETRIES		3
111 #define MAX_FW_UPDATE_RETRIES	30
112 
113 #define ELAN_FW_PAGESIZE	132
114 
115 /* calibration timeout definition */
116 #define ELAN_CALI_TIMEOUT_MSEC	12000
117 
118 #define ELAN_POWERON_DELAY_USEC	5000
119 #define ELAN_RESET_DELAY_MSEC	20
120 
121 /* FW boot code version */
122 #define BC_VER_H_BYTE_FOR_EKTH3900x1_I2C        0x72
123 #define BC_VER_H_BYTE_FOR_EKTH3900x2_I2C        0x82
124 #define BC_VER_H_BYTE_FOR_EKTH3900x3_I2C        0x92
125 #define BC_VER_H_BYTE_FOR_EKTH5312x1_I2C        0x6D
126 #define BC_VER_H_BYTE_FOR_EKTH5312x2_I2C        0x6E
127 #define BC_VER_H_BYTE_FOR_EKTH5312cx1_I2C       0x77
128 #define BC_VER_H_BYTE_FOR_EKTH5312cx2_I2C       0x78
129 #define BC_VER_H_BYTE_FOR_EKTH5312x1_I2C_USB    0x67
130 #define BC_VER_H_BYTE_FOR_EKTH5312x2_I2C_USB    0x68
131 #define BC_VER_H_BYTE_FOR_EKTH5312cx1_I2C_USB   0x74
132 #define BC_VER_H_BYTE_FOR_EKTH5312cx2_I2C_USB   0x75
133 
134 enum elants_chip_id {
135 	EKTH3500,
136 	EKTF3624,
137 };
138 
139 enum elants_state {
140 	ELAN_STATE_NORMAL,
141 	ELAN_WAIT_QUEUE_HEADER,
142 	ELAN_WAIT_RECALIBRATION,
143 };
144 
145 enum elants_iap_mode {
146 	ELAN_IAP_OPERATIONAL,
147 	ELAN_IAP_RECOVERY,
148 };
149 
150 /* struct elants_data - represents state of Elan touchscreen device */
151 struct elants_data {
152 	struct i2c_client *client;
153 	struct input_dev *input;
154 
155 	struct regulator *vcc33;
156 	struct regulator *vccio;
157 	struct gpio_desc *reset_gpio;
158 
159 	u16 fw_version;
160 	u8 test_version;
161 	u8 solution_version;
162 	u8 bc_version;
163 	u8 iap_version;
164 	u16 hw_version;
165 	u8 major_res;
166 	unsigned int x_res;	/* resolution in units/mm */
167 	unsigned int y_res;
168 	unsigned int x_max;
169 	unsigned int y_max;
170 	unsigned int phy_x;
171 	unsigned int phy_y;
172 	struct touchscreen_properties prop;
173 
174 	enum elants_state state;
175 	enum elants_chip_id chip_id;
176 	enum elants_iap_mode iap_mode;
177 
178 	/* Guards against concurrent access to the device via sysfs */
179 	struct mutex sysfs_mutex;
180 
181 	u8 cmd_resp[HEADER_SIZE];
182 	struct completion cmd_done;
183 
184 	bool keep_power_in_suspend;
185 
186 	/* Must be last to be used for DMA operations */
187 	u8 buf[MAX_PACKET_SIZE] ____cacheline_aligned;
188 };
189 
190 static int elants_i2c_send(struct i2c_client *client,
191 			   const void *data, size_t size)
192 {
193 	int ret;
194 
195 	ret = i2c_master_send(client, data, size);
196 	if (ret == size)
197 		return 0;
198 
199 	if (ret >= 0)
200 		ret = -EIO;
201 
202 	dev_err(&client->dev, "%s failed (%*ph): %d\n",
203 		__func__, (int)size, data, ret);
204 
205 	return ret;
206 }
207 
208 static int elants_i2c_read(struct i2c_client *client, void *data, size_t size)
209 {
210 	int ret;
211 
212 	ret = i2c_master_recv(client, data, size);
213 	if (ret == size)
214 		return 0;
215 
216 	if (ret >= 0)
217 		ret = -EIO;
218 
219 	dev_err(&client->dev, "%s failed: %d\n", __func__, ret);
220 
221 	return ret;
222 }
223 
224 static int elants_i2c_execute_command(struct i2c_client *client,
225 				      const u8 *cmd, size_t cmd_size,
226 				      u8 *resp, size_t resp_size,
227 				      int retries, const char *cmd_name)
228 {
229 	struct i2c_msg msgs[2];
230 	int ret;
231 	u8 expected_response;
232 
233 	switch (cmd[0]) {
234 	case CMD_HEADER_READ:
235 		expected_response = CMD_HEADER_RESP;
236 		break;
237 
238 	case CMD_HEADER_6B_READ:
239 		expected_response = CMD_HEADER_6B_RESP;
240 		break;
241 
242 	case CMD_HEADER_ROM_READ:
243 		expected_response = CMD_HEADER_ROM_RESP;
244 		break;
245 
246 	default:
247 		dev_err(&client->dev, "(%s): invalid command: %*ph\n",
248 			cmd_name, (int)cmd_size, cmd);
249 		return -EINVAL;
250 	}
251 
252 	for (;;) {
253 		msgs[0].addr = client->addr;
254 		msgs[0].flags = client->flags & I2C_M_TEN;
255 		msgs[0].len = cmd_size;
256 		msgs[0].buf = (u8 *)cmd;
257 
258 		msgs[1].addr = client->addr;
259 		msgs[1].flags = (client->flags & I2C_M_TEN) | I2C_M_RD;
260 		msgs[1].flags |= I2C_M_RD;
261 		msgs[1].len = resp_size;
262 		msgs[1].buf = resp;
263 
264 		ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs));
265 		if (ret < 0) {
266 			if (--retries > 0) {
267 				dev_dbg(&client->dev,
268 					"(%s) I2C transfer failed: %pe (retrying)\n",
269 					cmd_name, ERR_PTR(ret));
270 				continue;
271 			}
272 
273 			dev_err(&client->dev,
274 				"(%s) I2C transfer failed: %pe\n",
275 				cmd_name, ERR_PTR(ret));
276 			return ret;
277 		}
278 
279 		if (ret != ARRAY_SIZE(msgs) ||
280 		    resp[FW_HDR_TYPE] != expected_response) {
281 			if (--retries > 0) {
282 				dev_dbg(&client->dev,
283 					"(%s) unexpected response: %*ph (retrying)\n",
284 					cmd_name, ret, resp);
285 				continue;
286 			}
287 
288 			dev_err(&client->dev,
289 				"(%s) unexpected response: %*ph\n",
290 				cmd_name, ret, resp);
291 			return -EIO;
292 		}
293 
294 		return 0;
295 	}
296 }
297 
298 static int elants_i2c_calibrate(struct elants_data *ts)
299 {
300 	struct i2c_client *client = ts->client;
301 	int ret, error;
302 	static const u8 w_flashkey[] = { CMD_HEADER_WRITE, 0xC0, 0xE1, 0x5A };
303 	static const u8 rek[] = { CMD_HEADER_WRITE, 0x29, 0x00, 0x01 };
304 	static const u8 rek_resp[] = { CMD_HEADER_REK, 0x66, 0x66, 0x66 };
305 
306 	disable_irq(client->irq);
307 
308 	ts->state = ELAN_WAIT_RECALIBRATION;
309 	reinit_completion(&ts->cmd_done);
310 
311 	elants_i2c_send(client, w_flashkey, sizeof(w_flashkey));
312 	elants_i2c_send(client, rek, sizeof(rek));
313 
314 	enable_irq(client->irq);
315 
316 	ret = wait_for_completion_interruptible_timeout(&ts->cmd_done,
317 				msecs_to_jiffies(ELAN_CALI_TIMEOUT_MSEC));
318 
319 	ts->state = ELAN_STATE_NORMAL;
320 
321 	if (ret <= 0) {
322 		error = ret < 0 ? ret : -ETIMEDOUT;
323 		dev_err(&client->dev,
324 			"error while waiting for calibration to complete: %d\n",
325 			error);
326 		return error;
327 	}
328 
329 	if (memcmp(rek_resp, ts->cmd_resp, sizeof(rek_resp))) {
330 		dev_err(&client->dev,
331 			"unexpected calibration response: %*ph\n",
332 			(int)sizeof(ts->cmd_resp), ts->cmd_resp);
333 		return -EINVAL;
334 	}
335 
336 	return 0;
337 }
338 
339 static int elants_i2c_sw_reset(struct i2c_client *client)
340 {
341 	const u8 soft_rst_cmd[] = { 0x77, 0x77, 0x77, 0x77 };
342 	int error;
343 
344 	error = elants_i2c_send(client, soft_rst_cmd,
345 				sizeof(soft_rst_cmd));
346 	if (error) {
347 		dev_err(&client->dev, "software reset failed: %d\n", error);
348 		return error;
349 	}
350 
351 	/*
352 	 * We should wait at least 10 msec (but no more than 40) before
353 	 * sending fastboot or IAP command to the device.
354 	 */
355 	msleep(30);
356 
357 	return 0;
358 }
359 
360 static u16 elants_i2c_parse_version(u8 *buf)
361 {
362 	return get_unaligned_be32(buf) >> 4;
363 }
364 
365 static int elants_i2c_query_hw_version(struct elants_data *ts)
366 {
367 	struct i2c_client *client = ts->client;
368 	int retry_cnt = MAX_RETRIES;
369 	const u8 cmd[] = { CMD_HEADER_READ, E_ELAN_INFO_FW_ID, 0x00, 0x01 };
370 	u8 resp[HEADER_SIZE];
371 	int error;
372 
373 	while (retry_cnt--) {
374 		error = elants_i2c_execute_command(client, cmd, sizeof(cmd),
375 						   resp, sizeof(resp), 1,
376 						   "read fw id");
377 		if (error)
378 			return error;
379 
380 		ts->hw_version = elants_i2c_parse_version(resp);
381 		if (ts->hw_version != 0xffff)
382 			return 0;
383 	}
384 
385 	dev_err(&client->dev, "Invalid fw id: %#04x\n", ts->hw_version);
386 
387 	return -EINVAL;
388 }
389 
390 static int elants_i2c_query_fw_version(struct elants_data *ts)
391 {
392 	struct i2c_client *client = ts->client;
393 	int retry_cnt = MAX_RETRIES;
394 	const u8 cmd[] = { CMD_HEADER_READ, E_ELAN_INFO_FW_VER, 0x00, 0x01 };
395 	u8 resp[HEADER_SIZE];
396 	int error;
397 
398 	while (retry_cnt--) {
399 		error = elants_i2c_execute_command(client, cmd, sizeof(cmd),
400 						   resp, sizeof(resp), 1,
401 						   "read fw version");
402 		if (error)
403 			return error;
404 
405 		ts->fw_version = elants_i2c_parse_version(resp);
406 		if (ts->fw_version != 0x0000 && ts->fw_version != 0xffff)
407 			return 0;
408 
409 		dev_dbg(&client->dev, "(read fw version) resp %*phC\n",
410 			(int)sizeof(resp), resp);
411 	}
412 
413 	dev_err(&client->dev, "Invalid fw ver: %#04x\n", ts->fw_version);
414 
415 	return -EINVAL;
416 }
417 
418 static int elants_i2c_query_test_version(struct elants_data *ts)
419 {
420 	struct i2c_client *client = ts->client;
421 	int error;
422 	u16 version;
423 	const u8 cmd[] = { CMD_HEADER_READ, E_ELAN_INFO_TEST_VER, 0x00, 0x01 };
424 	u8 resp[HEADER_SIZE];
425 
426 	error = elants_i2c_execute_command(client, cmd, sizeof(cmd),
427 					   resp, sizeof(resp), MAX_RETRIES,
428 					   "read test version");
429 	if (error) {
430 		dev_err(&client->dev, "Failed to read test version\n");
431 		return error;
432 	}
433 
434 	version = elants_i2c_parse_version(resp);
435 	ts->test_version = version >> 8;
436 	ts->solution_version = version & 0xff;
437 
438 	return 0;
439 }
440 
441 static int elants_i2c_query_bc_version(struct elants_data *ts)
442 {
443 	struct i2c_client *client = ts->client;
444 	const u8 cmd[] = { CMD_HEADER_READ, E_ELAN_INFO_BC_VER, 0x00, 0x01 };
445 	u8 resp[HEADER_SIZE];
446 	u16 version;
447 	int error;
448 
449 	error = elants_i2c_execute_command(client, cmd, sizeof(cmd),
450 					   resp, sizeof(resp), 1,
451 					   "read BC version");
452 	if (error)
453 		return error;
454 
455 	version = elants_i2c_parse_version(resp);
456 	ts->bc_version = version >> 8;
457 	ts->iap_version = version & 0xff;
458 
459 	return 0;
460 }
461 
462 static int elants_i2c_query_ts_info_ektf(struct elants_data *ts)
463 {
464 	struct i2c_client *client = ts->client;
465 	int error;
466 	u8 resp[4];
467 	u16 phy_x, phy_y;
468 	const u8 get_xres_cmd[] = {
469 		CMD_HEADER_READ, E_ELAN_INFO_X_RES, 0x00, 0x00
470 	};
471 	const u8 get_yres_cmd[] = {
472 		CMD_HEADER_READ, E_ELAN_INFO_Y_RES, 0x00, 0x00
473 	};
474 
475 	/* Get X/Y size in mm */
476 	error = elants_i2c_execute_command(client, get_xres_cmd,
477 					   sizeof(get_xres_cmd),
478 					   resp, sizeof(resp), 1,
479 					   "get X size");
480 	if (error)
481 		return error;
482 
483 	phy_x = resp[2] | ((resp[3] & 0xF0) << 4);
484 
485 	error = elants_i2c_execute_command(client, get_yres_cmd,
486 					   sizeof(get_yres_cmd),
487 					   resp, sizeof(resp), 1,
488 					   "get Y size");
489 	if (error)
490 		return error;
491 
492 	phy_y = resp[2] | ((resp[3] & 0xF0) << 4);
493 
494 	dev_dbg(&client->dev, "phy_x=%d, phy_y=%d\n", phy_x, phy_y);
495 
496 	ts->phy_x = phy_x;
497 	ts->phy_y = phy_y;
498 
499 	/* eKTF doesn't report max size, set it to default values */
500 	ts->x_max = 2240 - 1;
501 	ts->y_max = 1408 - 1;
502 
503 	return 0;
504 }
505 
506 static int elants_i2c_query_ts_info_ekth(struct elants_data *ts)
507 {
508 	struct i2c_client *client = ts->client;
509 	int error;
510 	u8 resp[17];
511 	u16 phy_x, phy_y, rows, cols, osr;
512 	const u8 get_resolution_cmd[] = {
513 		CMD_HEADER_6B_READ, 0x00, 0x00, 0x00, 0x00, 0x00
514 	};
515 	const u8 get_osr_cmd[] = {
516 		CMD_HEADER_READ, E_INFO_OSR, 0x00, 0x01
517 	};
518 	const u8 get_physical_scan_cmd[] = {
519 		CMD_HEADER_READ, E_INFO_PHY_SCAN, 0x00, 0x01
520 	};
521 	const u8 get_physical_drive_cmd[] = {
522 		CMD_HEADER_READ, E_INFO_PHY_DRIVER, 0x00, 0x01
523 	};
524 
525 	/* Get trace number */
526 	error = elants_i2c_execute_command(client,
527 					   get_resolution_cmd,
528 					   sizeof(get_resolution_cmd),
529 					   resp, sizeof(resp), 1,
530 					   "get resolution");
531 	if (error)
532 		return error;
533 
534 	rows = resp[2] + resp[6] + resp[10];
535 	cols = resp[3] + resp[7] + resp[11];
536 
537 	/* Get report resolution value of ABS_MT_TOUCH_MAJOR */
538 	ts->major_res = resp[16];
539 
540 	/* Process mm_to_pixel information */
541 	error = elants_i2c_execute_command(client,
542 					   get_osr_cmd, sizeof(get_osr_cmd),
543 					   resp, sizeof(resp), 1, "get osr");
544 	if (error)
545 		return error;
546 
547 	osr = resp[3];
548 
549 	error = elants_i2c_execute_command(client,
550 					   get_physical_scan_cmd,
551 					   sizeof(get_physical_scan_cmd),
552 					   resp, sizeof(resp), 1,
553 					   "get physical scan");
554 	if (error)
555 		return error;
556 
557 	phy_x = get_unaligned_be16(&resp[2]);
558 
559 	error = elants_i2c_execute_command(client,
560 					   get_physical_drive_cmd,
561 					   sizeof(get_physical_drive_cmd),
562 					   resp, sizeof(resp), 1,
563 					   "get physical drive");
564 	if (error)
565 		return error;
566 
567 	phy_y = get_unaligned_be16(&resp[2]);
568 
569 	dev_dbg(&client->dev, "phy_x=%d, phy_y=%d\n", phy_x, phy_y);
570 
571 	if (rows == 0 || cols == 0 || osr == 0) {
572 		dev_warn(&client->dev,
573 			 "invalid trace number data: %d, %d, %d\n",
574 			 rows, cols, osr);
575 	} else {
576 		/* translate trace number to TS resolution */
577 		ts->x_max = ELAN_TS_RESOLUTION(rows, osr);
578 		ts->x_res = DIV_ROUND_CLOSEST(ts->x_max, phy_x);
579 		ts->y_max = ELAN_TS_RESOLUTION(cols, osr);
580 		ts->y_res = DIV_ROUND_CLOSEST(ts->y_max, phy_y);
581 		ts->phy_x = phy_x;
582 		ts->phy_y = phy_y;
583 	}
584 
585 	return 0;
586 }
587 
588 static int elants_i2c_fastboot(struct i2c_client *client)
589 {
590 	const u8 boot_cmd[] = { 0x4D, 0x61, 0x69, 0x6E };
591 	int error;
592 
593 	error = elants_i2c_send(client, boot_cmd, sizeof(boot_cmd));
594 	if (error) {
595 		dev_err(&client->dev, "boot failed: %d\n", error);
596 		return error;
597 	}
598 
599 	dev_dbg(&client->dev, "boot success -- 0x%x\n", client->addr);
600 	return 0;
601 }
602 
603 static int elants_i2c_initialize(struct elants_data *ts)
604 {
605 	struct i2c_client *client = ts->client;
606 	int error, error2, retry_cnt;
607 	const u8 hello_packet[] = { 0x55, 0x55, 0x55, 0x55 };
608 	const u8 recov_packet[] = { 0x55, 0x55, 0x80, 0x80 };
609 	u8 buf[HEADER_SIZE];
610 
611 	for (retry_cnt = 0; retry_cnt < MAX_RETRIES; retry_cnt++) {
612 		error = elants_i2c_sw_reset(client);
613 		if (error) {
614 			/* Continue initializing if it's the last try */
615 			if (retry_cnt < MAX_RETRIES - 1)
616 				continue;
617 		}
618 
619 		error = elants_i2c_fastboot(client);
620 		if (error) {
621 			/* Continue initializing if it's the last try */
622 			if (retry_cnt < MAX_RETRIES - 1)
623 				continue;
624 		}
625 
626 		/* Wait for Hello packet */
627 		msleep(BOOT_TIME_DELAY_MS);
628 
629 		error = elants_i2c_read(client, buf, sizeof(buf));
630 		if (error) {
631 			dev_err(&client->dev,
632 				"failed to read 'hello' packet: %d\n", error);
633 		} else if (!memcmp(buf, hello_packet, sizeof(hello_packet))) {
634 			ts->iap_mode = ELAN_IAP_OPERATIONAL;
635 			break;
636 		} else if (!memcmp(buf, recov_packet, sizeof(recov_packet))) {
637 			/*
638 			 * Setting error code will mark device
639 			 * in recovery mode below.
640 			 */
641 			error = -EIO;
642 			break;
643 		} else {
644 			error = -EINVAL;
645 			dev_err(&client->dev,
646 				"invalid 'hello' packet: %*ph\n",
647 				(int)sizeof(buf), buf);
648 		}
649 	}
650 
651 	/* hw version is available even if device in recovery state */
652 	error2 = elants_i2c_query_hw_version(ts);
653 	if (!error2)
654 		error2 = elants_i2c_query_bc_version(ts);
655 	if (!error)
656 		error = error2;
657 
658 	if (!error)
659 		error = elants_i2c_query_fw_version(ts);
660 	if (!error)
661 		error = elants_i2c_query_test_version(ts);
662 
663 	switch (ts->chip_id) {
664 	case EKTH3500:
665 		if (!error)
666 			error = elants_i2c_query_ts_info_ekth(ts);
667 		break;
668 	case EKTF3624:
669 		if (!error)
670 			error = elants_i2c_query_ts_info_ektf(ts);
671 		break;
672 	default:
673 		BUG();
674 	}
675 
676 	if (error)
677 		ts->iap_mode = ELAN_IAP_RECOVERY;
678 
679 	return 0;
680 }
681 
682 /*
683  * Firmware update interface.
684  */
685 
686 static int elants_i2c_fw_write_page(struct i2c_client *client,
687 				    const void *page)
688 {
689 	const u8 ack_ok[] = { 0xaa, 0xaa };
690 	u8 buf[2];
691 	int retry;
692 	int error;
693 
694 	for (retry = 0; retry < MAX_FW_UPDATE_RETRIES; retry++) {
695 		error = elants_i2c_send(client, page, ELAN_FW_PAGESIZE);
696 		if (error) {
697 			dev_err(&client->dev,
698 				"IAP Write Page failed: %d\n", error);
699 			continue;
700 		}
701 
702 		error = elants_i2c_read(client, buf, 2);
703 		if (error) {
704 			dev_err(&client->dev,
705 				"IAP Ack read failed: %d\n", error);
706 			return error;
707 		}
708 
709 		if (!memcmp(buf, ack_ok, sizeof(ack_ok)))
710 			return 0;
711 
712 		error = -EIO;
713 		dev_err(&client->dev,
714 			"IAP Get Ack Error [%02x:%02x]\n",
715 			buf[0], buf[1]);
716 	}
717 
718 	return error;
719 }
720 
721 static int elants_i2c_validate_remark_id(struct elants_data *ts,
722 					 const struct firmware *fw)
723 {
724 	struct i2c_client *client = ts->client;
725 	int error;
726 	const u8 cmd[] = { CMD_HEADER_ROM_READ, 0x80, 0x1F, 0x00, 0x00, 0x21 };
727 	u8 resp[6] = { 0 };
728 	u16 ts_remark_id = 0;
729 	u16 fw_remark_id = 0;
730 
731 	/* Compare TS Remark ID and FW Remark ID */
732 	error = elants_i2c_execute_command(client, cmd, sizeof(cmd),
733 					   resp, sizeof(resp),
734 					   1, "read Remark ID");
735 	if (error)
736 		return error;
737 
738 	ts_remark_id = get_unaligned_be16(&resp[3]);
739 
740 	fw_remark_id = get_unaligned_le16(&fw->data[fw->size - 4]);
741 
742 	if (fw_remark_id != ts_remark_id) {
743 		dev_err(&client->dev,
744 			"Remark ID Mismatched: ts_remark_id=0x%04x, fw_remark_id=0x%04x.\n",
745 			ts_remark_id, fw_remark_id);
746 		return -EINVAL;
747 	}
748 
749 	return 0;
750 }
751 
752 static bool elants_i2c_should_check_remark_id(struct elants_data *ts)
753 {
754 	struct i2c_client *client = ts->client;
755 	const u8 bootcode_version = ts->iap_version;
756 	bool check;
757 
758 	/* I2C eKTH3900 and eKTH5312 are NOT support Remark ID */
759 	if ((bootcode_version == BC_VER_H_BYTE_FOR_EKTH3900x1_I2C) ||
760 	    (bootcode_version == BC_VER_H_BYTE_FOR_EKTH3900x2_I2C) ||
761 	    (bootcode_version == BC_VER_H_BYTE_FOR_EKTH3900x3_I2C) ||
762 	    (bootcode_version == BC_VER_H_BYTE_FOR_EKTH5312x1_I2C) ||
763 	    (bootcode_version == BC_VER_H_BYTE_FOR_EKTH5312x2_I2C) ||
764 	    (bootcode_version == BC_VER_H_BYTE_FOR_EKTH5312cx1_I2C) ||
765 	    (bootcode_version == BC_VER_H_BYTE_FOR_EKTH5312cx2_I2C) ||
766 	    (bootcode_version == BC_VER_H_BYTE_FOR_EKTH5312x1_I2C_USB) ||
767 	    (bootcode_version == BC_VER_H_BYTE_FOR_EKTH5312x2_I2C_USB) ||
768 	    (bootcode_version == BC_VER_H_BYTE_FOR_EKTH5312cx1_I2C_USB) ||
769 	    (bootcode_version == BC_VER_H_BYTE_FOR_EKTH5312cx2_I2C_USB)) {
770 		dev_dbg(&client->dev,
771 			"eKTH3900/eKTH5312(0x%02x) are not support remark id\n",
772 			bootcode_version);
773 		check = false;
774 	} else if (bootcode_version >= 0x60) {
775 		check = true;
776 	} else {
777 		check = false;
778 	}
779 
780 	return check;
781 }
782 
783 static int elants_i2c_do_update_firmware(struct i2c_client *client,
784 					 const struct firmware *fw,
785 					 bool force)
786 {
787 	struct elants_data *ts = i2c_get_clientdata(client);
788 	const u8 enter_iap[] = { 0x45, 0x49, 0x41, 0x50 };
789 	const u8 enter_iap2[] = { 0x54, 0x00, 0x12, 0x34 };
790 	const u8 iap_ack[] = { 0x55, 0xaa, 0x33, 0xcc };
791 	const u8 close_idle[] = { 0x54, 0x2c, 0x01, 0x01 };
792 	u8 buf[HEADER_SIZE];
793 	u16 send_id;
794 	int page, n_fw_pages;
795 	int error;
796 	bool check_remark_id = elants_i2c_should_check_remark_id(ts);
797 
798 	/* Recovery mode detection! */
799 	if (force) {
800 		dev_dbg(&client->dev, "Recovery mode procedure\n");
801 
802 		if (check_remark_id) {
803 			error = elants_i2c_validate_remark_id(ts, fw);
804 			if (error)
805 				return error;
806 		}
807 
808 		error = elants_i2c_send(client, enter_iap2, sizeof(enter_iap2));
809 		if (error) {
810 			dev_err(&client->dev, "failed to enter IAP mode: %d\n",
811 				error);
812 			return error;
813 		}
814 	} else {
815 		/* Start IAP Procedure */
816 		dev_dbg(&client->dev, "Normal IAP procedure\n");
817 
818 		/* Close idle mode */
819 		error = elants_i2c_send(client, close_idle, sizeof(close_idle));
820 		if (error)
821 			dev_err(&client->dev, "Failed close idle: %d\n", error);
822 		msleep(60);
823 
824 		elants_i2c_sw_reset(client);
825 		msleep(20);
826 
827 		if (check_remark_id) {
828 			error = elants_i2c_validate_remark_id(ts, fw);
829 			if (error)
830 				return error;
831 		}
832 
833 		error = elants_i2c_send(client, enter_iap, sizeof(enter_iap));
834 		if (error) {
835 			dev_err(&client->dev, "failed to enter IAP mode: %d\n",
836 				error);
837 			return error;
838 		}
839 	}
840 
841 	msleep(20);
842 
843 	/* check IAP state */
844 	error = elants_i2c_read(client, buf, 4);
845 	if (error) {
846 		dev_err(&client->dev,
847 			"failed to read IAP acknowledgement: %d\n",
848 			error);
849 		return error;
850 	}
851 
852 	if (memcmp(buf, iap_ack, sizeof(iap_ack))) {
853 		dev_err(&client->dev,
854 			"failed to enter IAP: %*ph (expected %*ph)\n",
855 			(int)sizeof(buf), buf, (int)sizeof(iap_ack), iap_ack);
856 		return -EIO;
857 	}
858 
859 	dev_info(&client->dev, "successfully entered IAP mode");
860 
861 	send_id = client->addr;
862 	error = elants_i2c_send(client, &send_id, 1);
863 	if (error) {
864 		dev_err(&client->dev, "sending dummy byte failed: %d\n",
865 			error);
866 		return error;
867 	}
868 
869 	/* Clear the last page of Master */
870 	error = elants_i2c_send(client, fw->data, ELAN_FW_PAGESIZE);
871 	if (error) {
872 		dev_err(&client->dev, "clearing of the last page failed: %d\n",
873 			error);
874 		return error;
875 	}
876 
877 	error = elants_i2c_read(client, buf, 2);
878 	if (error) {
879 		dev_err(&client->dev,
880 			"failed to read ACK for clearing the last page: %d\n",
881 			error);
882 		return error;
883 	}
884 
885 	n_fw_pages = fw->size / ELAN_FW_PAGESIZE;
886 	dev_dbg(&client->dev, "IAP Pages = %d\n", n_fw_pages);
887 
888 	for (page = 0; page < n_fw_pages; page++) {
889 		error = elants_i2c_fw_write_page(client,
890 					fw->data + page * ELAN_FW_PAGESIZE);
891 		if (error) {
892 			dev_err(&client->dev,
893 				"failed to write FW page %d: %d\n",
894 				page, error);
895 			return error;
896 		}
897 	}
898 
899 	/* Old iap needs to wait 200ms for WDT and rest is for hello packets */
900 	msleep(300);
901 
902 	dev_info(&client->dev, "firmware update completed\n");
903 	return 0;
904 }
905 
906 static int elants_i2c_fw_update(struct elants_data *ts)
907 {
908 	struct i2c_client *client = ts->client;
909 	const struct firmware *fw;
910 	char *fw_name;
911 	int error;
912 
913 	fw_name = kasprintf(GFP_KERNEL, "elants_i2c_%04x.bin", ts->hw_version);
914 	if (!fw_name)
915 		return -ENOMEM;
916 
917 	dev_info(&client->dev, "requesting fw name = %s\n", fw_name);
918 	error = request_firmware(&fw, fw_name, &client->dev);
919 	kfree(fw_name);
920 	if (error) {
921 		dev_err(&client->dev, "failed to request firmware: %d\n",
922 			error);
923 		return error;
924 	}
925 
926 	if (fw->size % ELAN_FW_PAGESIZE) {
927 		dev_err(&client->dev, "invalid firmware length: %zu\n",
928 			fw->size);
929 		error = -EINVAL;
930 		goto out;
931 	}
932 
933 	disable_irq(client->irq);
934 
935 	error = elants_i2c_do_update_firmware(client, fw,
936 					ts->iap_mode == ELAN_IAP_RECOVERY);
937 	if (error) {
938 		dev_err(&client->dev, "firmware update failed: %d\n", error);
939 		ts->iap_mode = ELAN_IAP_RECOVERY;
940 		goto out_enable_irq;
941 	}
942 
943 	error = elants_i2c_initialize(ts);
944 	if (error) {
945 		dev_err(&client->dev,
946 			"failed to initialize device after firmware update: %d\n",
947 			error);
948 		ts->iap_mode = ELAN_IAP_RECOVERY;
949 		goto out_enable_irq;
950 	}
951 
952 	ts->iap_mode = ELAN_IAP_OPERATIONAL;
953 
954 out_enable_irq:
955 	ts->state = ELAN_STATE_NORMAL;
956 	enable_irq(client->irq);
957 	msleep(100);
958 
959 	if (!error)
960 		elants_i2c_calibrate(ts);
961 out:
962 	release_firmware(fw);
963 	return error;
964 }
965 
966 /*
967  * Event reporting.
968  */
969 
970 static void elants_i2c_mt_event(struct elants_data *ts, u8 *buf,
971 				size_t packet_size)
972 {
973 	struct input_dev *input = ts->input;
974 	unsigned int n_fingers;
975 	unsigned int tool_type;
976 	u16 finger_state;
977 	int i;
978 
979 	n_fingers = buf[FW_POS_STATE + 1] & 0x0f;
980 	finger_state = ((buf[FW_POS_STATE + 1] & 0x30) << 4) |
981 			buf[FW_POS_STATE];
982 
983 	dev_dbg(&ts->client->dev,
984 		"n_fingers: %u, state: %04x\n",  n_fingers, finger_state);
985 
986 	/* Note: all fingers have the same tool type */
987 	tool_type = buf[FW_POS_TOOL_TYPE] & BIT(0) ?
988 			MT_TOOL_FINGER : MT_TOOL_PALM;
989 
990 	for (i = 0; i < MAX_CONTACT_NUM && n_fingers; i++) {
991 		if (finger_state & 1) {
992 			unsigned int x, y, p, w;
993 			u8 *pos;
994 
995 			pos = &buf[FW_POS_XY + i * 3];
996 			x = (((u16)pos[0] & 0xf0) << 4) | pos[1];
997 			y = (((u16)pos[0] & 0x0f) << 8) | pos[2];
998 
999 			/*
1000 			 * eKTF3624 may have use "old" touch-report format,
1001 			 * depending on a device and TS firmware version.
1002 			 * For example, ASUS Transformer devices use the "old"
1003 			 * format, while ASUS Nexus 7 uses the "new" formant.
1004 			 */
1005 			if (packet_size == PACKET_SIZE_OLD &&
1006 			    ts->chip_id == EKTF3624) {
1007 				w = buf[FW_POS_WIDTH + i / 2];
1008 				w >>= 4 * (~i & 1);
1009 				w |= w << 4;
1010 				w |= !w;
1011 				p = w;
1012 			} else {
1013 				p = buf[FW_POS_PRESSURE + i];
1014 				w = buf[FW_POS_WIDTH + i];
1015 			}
1016 
1017 			dev_dbg(&ts->client->dev, "i=%d x=%d y=%d p=%d w=%d\n",
1018 				i, x, y, p, w);
1019 
1020 			input_mt_slot(input, i);
1021 			input_mt_report_slot_state(input, tool_type, true);
1022 			touchscreen_report_pos(input, &ts->prop, x, y, true);
1023 			input_event(input, EV_ABS, ABS_MT_PRESSURE, p);
1024 			input_event(input, EV_ABS, ABS_MT_TOUCH_MAJOR, w);
1025 
1026 			n_fingers--;
1027 		}
1028 
1029 		finger_state >>= 1;
1030 	}
1031 
1032 	input_mt_sync_frame(input);
1033 	input_sync(input);
1034 }
1035 
1036 static u8 elants_i2c_calculate_checksum(u8 *buf)
1037 {
1038 	u8 checksum = 0;
1039 	u8 i;
1040 
1041 	for (i = 0; i < FW_POS_CHECKSUM; i++)
1042 		checksum += buf[i];
1043 
1044 	return checksum;
1045 }
1046 
1047 static void elants_i2c_event(struct elants_data *ts, u8 *buf,
1048 			     size_t packet_size)
1049 {
1050 	u8 checksum = elants_i2c_calculate_checksum(buf);
1051 
1052 	if (unlikely(buf[FW_POS_CHECKSUM] != checksum))
1053 		dev_warn(&ts->client->dev,
1054 			 "%s: invalid checksum for packet %02x: %02x vs. %02x\n",
1055 			 __func__, buf[FW_POS_HEADER],
1056 			 checksum, buf[FW_POS_CHECKSUM]);
1057 	else if (unlikely(buf[FW_POS_HEADER] != HEADER_REPORT_10_FINGER))
1058 		dev_warn(&ts->client->dev,
1059 			 "%s: unknown packet type: %02x\n",
1060 			 __func__, buf[FW_POS_HEADER]);
1061 	else
1062 		elants_i2c_mt_event(ts, buf, packet_size);
1063 }
1064 
1065 static irqreturn_t elants_i2c_irq(int irq, void *_dev)
1066 {
1067 	const u8 wait_packet[] = { 0x64, 0x64, 0x64, 0x64 };
1068 	struct elants_data *ts = _dev;
1069 	struct i2c_client *client = ts->client;
1070 	int report_count, report_len;
1071 	int i;
1072 	int len;
1073 
1074 	len = i2c_master_recv_dmasafe(client, ts->buf, sizeof(ts->buf));
1075 	if (len < 0) {
1076 		dev_err(&client->dev, "%s: failed to read data: %d\n",
1077 			__func__, len);
1078 		goto out;
1079 	}
1080 
1081 	dev_dbg(&client->dev, "%s: packet %*ph\n",
1082 		__func__, HEADER_SIZE, ts->buf);
1083 
1084 	switch (ts->state) {
1085 	case ELAN_WAIT_RECALIBRATION:
1086 		if (ts->buf[FW_HDR_TYPE] == CMD_HEADER_REK) {
1087 			memcpy(ts->cmd_resp, ts->buf, sizeof(ts->cmd_resp));
1088 			complete(&ts->cmd_done);
1089 			ts->state = ELAN_STATE_NORMAL;
1090 		}
1091 		break;
1092 
1093 	case ELAN_WAIT_QUEUE_HEADER:
1094 		if (ts->buf[FW_HDR_TYPE] != QUEUE_HEADER_NORMAL)
1095 			break;
1096 
1097 		ts->state = ELAN_STATE_NORMAL;
1098 		fallthrough;
1099 
1100 	case ELAN_STATE_NORMAL:
1101 
1102 		switch (ts->buf[FW_HDR_TYPE]) {
1103 		case CMD_HEADER_HELLO:
1104 		case CMD_HEADER_RESP:
1105 			break;
1106 
1107 		case QUEUE_HEADER_WAIT:
1108 			if (memcmp(ts->buf, wait_packet, sizeof(wait_packet))) {
1109 				dev_err(&client->dev,
1110 					"invalid wait packet %*ph\n",
1111 					HEADER_SIZE, ts->buf);
1112 			} else {
1113 				ts->state = ELAN_WAIT_QUEUE_HEADER;
1114 				udelay(30);
1115 			}
1116 			break;
1117 
1118 		case QUEUE_HEADER_SINGLE:
1119 			elants_i2c_event(ts, &ts->buf[HEADER_SIZE],
1120 					 ts->buf[FW_HDR_LENGTH]);
1121 			break;
1122 
1123 		case QUEUE_HEADER_NORMAL2: /* CMD_HEADER_REK */
1124 			/*
1125 			 * Depending on firmware version, eKTF3624 touchscreens
1126 			 * may utilize one of these opcodes for the touch events:
1127 			 * 0x63 (NORMAL) and 0x66 (NORMAL2).  The 0x63 is used by
1128 			 * older firmware version and differs from 0x66 such that
1129 			 * touch pressure value needs to be adjusted.  The 0x66
1130 			 * opcode of newer firmware is equal to 0x63 of eKTH3500.
1131 			 */
1132 			if (ts->chip_id != EKTF3624)
1133 				break;
1134 
1135 			fallthrough;
1136 
1137 		case QUEUE_HEADER_NORMAL:
1138 			report_count = ts->buf[FW_HDR_COUNT];
1139 			if (report_count == 0 || report_count > 3) {
1140 				dev_err(&client->dev,
1141 					"bad report count: %*ph\n",
1142 					HEADER_SIZE, ts->buf);
1143 				break;
1144 			}
1145 
1146 			report_len = ts->buf[FW_HDR_LENGTH] / report_count;
1147 
1148 			if (report_len == PACKET_SIZE_OLD &&
1149 			    ts->chip_id == EKTF3624) {
1150 				dev_dbg_once(&client->dev,
1151 					     "using old report format\n");
1152 			} else if (report_len != PACKET_SIZE) {
1153 				dev_err(&client->dev,
1154 					"mismatching report length: %*ph\n",
1155 					HEADER_SIZE, ts->buf);
1156 				break;
1157 			}
1158 
1159 			for (i = 0; i < report_count; i++) {
1160 				u8 *buf = ts->buf + HEADER_SIZE +
1161 							i * report_len;
1162 				elants_i2c_event(ts, buf, report_len);
1163 			}
1164 			break;
1165 
1166 		default:
1167 			dev_err(&client->dev, "unknown packet %*ph\n",
1168 				HEADER_SIZE, ts->buf);
1169 			break;
1170 		}
1171 		break;
1172 	}
1173 
1174 out:
1175 	return IRQ_HANDLED;
1176 }
1177 
1178 /*
1179  * sysfs interface
1180  */
1181 static ssize_t calibrate_store(struct device *dev,
1182 			       struct device_attribute *attr,
1183 			       const char *buf, size_t count)
1184 {
1185 	struct i2c_client *client = to_i2c_client(dev);
1186 	struct elants_data *ts = i2c_get_clientdata(client);
1187 	int error;
1188 
1189 	error = mutex_lock_interruptible(&ts->sysfs_mutex);
1190 	if (error)
1191 		return error;
1192 
1193 	error = elants_i2c_calibrate(ts);
1194 
1195 	mutex_unlock(&ts->sysfs_mutex);
1196 	return error ?: count;
1197 }
1198 
1199 static ssize_t write_update_fw(struct device *dev,
1200 			       struct device_attribute *attr,
1201 			       const char *buf, size_t count)
1202 {
1203 	struct i2c_client *client = to_i2c_client(dev);
1204 	struct elants_data *ts = i2c_get_clientdata(client);
1205 	int error;
1206 
1207 	error = mutex_lock_interruptible(&ts->sysfs_mutex);
1208 	if (error)
1209 		return error;
1210 
1211 	error = elants_i2c_fw_update(ts);
1212 	dev_dbg(dev, "firmware update result: %d\n", error);
1213 
1214 	mutex_unlock(&ts->sysfs_mutex);
1215 	return error ?: count;
1216 }
1217 
1218 static ssize_t show_iap_mode(struct device *dev,
1219 			     struct device_attribute *attr, char *buf)
1220 {
1221 	struct i2c_client *client = to_i2c_client(dev);
1222 	struct elants_data *ts = i2c_get_clientdata(client);
1223 
1224 	return sprintf(buf, "%s\n",
1225 		       ts->iap_mode == ELAN_IAP_OPERATIONAL ?
1226 				"Normal" : "Recovery");
1227 }
1228 
1229 static ssize_t show_calibration_count(struct device *dev,
1230 				      struct device_attribute *attr, char *buf)
1231 {
1232 	struct i2c_client *client = to_i2c_client(dev);
1233 	const u8 cmd[] = { CMD_HEADER_READ, E_ELAN_INFO_REK, 0x00, 0x01 };
1234 	u8 resp[HEADER_SIZE];
1235 	u16 rek_count;
1236 	int error;
1237 
1238 	error = elants_i2c_execute_command(client, cmd, sizeof(cmd),
1239 					   resp, sizeof(resp), 1,
1240 					   "read ReK status");
1241 	if (error)
1242 		return sprintf(buf, "%d\n", error);
1243 
1244 	rek_count = get_unaligned_be16(&resp[2]);
1245 	return sprintf(buf, "0x%04x\n", rek_count);
1246 }
1247 
1248 static DEVICE_ATTR_WO(calibrate);
1249 static DEVICE_ATTR(iap_mode, S_IRUGO, show_iap_mode, NULL);
1250 static DEVICE_ATTR(calibration_count, S_IRUGO, show_calibration_count, NULL);
1251 static DEVICE_ATTR(update_fw, S_IWUSR, NULL, write_update_fw);
1252 
1253 struct elants_version_attribute {
1254 	struct device_attribute dattr;
1255 	size_t field_offset;
1256 	size_t field_size;
1257 };
1258 
1259 #define __ELANTS_FIELD_SIZE(_field)					\
1260 	sizeof(((struct elants_data *)NULL)->_field)
1261 #define __ELANTS_VERIFY_SIZE(_field)					\
1262 	(BUILD_BUG_ON_ZERO(__ELANTS_FIELD_SIZE(_field) > 2) +		\
1263 	 __ELANTS_FIELD_SIZE(_field))
1264 #define ELANTS_VERSION_ATTR(_field)					\
1265 	struct elants_version_attribute elants_ver_attr_##_field = {	\
1266 		.dattr = __ATTR(_field, S_IRUGO,			\
1267 				elants_version_attribute_show, NULL),	\
1268 		.field_offset = offsetof(struct elants_data, _field),	\
1269 		.field_size = __ELANTS_VERIFY_SIZE(_field),		\
1270 	}
1271 
1272 static ssize_t elants_version_attribute_show(struct device *dev,
1273 					     struct device_attribute *dattr,
1274 					     char *buf)
1275 {
1276 	struct i2c_client *client = to_i2c_client(dev);
1277 	struct elants_data *ts = i2c_get_clientdata(client);
1278 	struct elants_version_attribute *attr =
1279 		container_of(dattr, struct elants_version_attribute, dattr);
1280 	u8 *field = (u8 *)((char *)ts + attr->field_offset);
1281 	unsigned int fmt_size;
1282 	unsigned int val;
1283 
1284 	if (attr->field_size == 1) {
1285 		val = *field;
1286 		fmt_size = 2; /* 2 HEX digits */
1287 	} else {
1288 		val = *(u16 *)field;
1289 		fmt_size = 4; /* 4 HEX digits */
1290 	}
1291 
1292 	return sprintf(buf, "%0*x\n", fmt_size, val);
1293 }
1294 
1295 static ELANTS_VERSION_ATTR(fw_version);
1296 static ELANTS_VERSION_ATTR(hw_version);
1297 static ELANTS_VERSION_ATTR(test_version);
1298 static ELANTS_VERSION_ATTR(solution_version);
1299 static ELANTS_VERSION_ATTR(bc_version);
1300 static ELANTS_VERSION_ATTR(iap_version);
1301 
1302 static struct attribute *elants_attributes[] = {
1303 	&dev_attr_calibrate.attr,
1304 	&dev_attr_update_fw.attr,
1305 	&dev_attr_iap_mode.attr,
1306 	&dev_attr_calibration_count.attr,
1307 
1308 	&elants_ver_attr_fw_version.dattr.attr,
1309 	&elants_ver_attr_hw_version.dattr.attr,
1310 	&elants_ver_attr_test_version.dattr.attr,
1311 	&elants_ver_attr_solution_version.dattr.attr,
1312 	&elants_ver_attr_bc_version.dattr.attr,
1313 	&elants_ver_attr_iap_version.dattr.attr,
1314 	NULL
1315 };
1316 
1317 static const struct attribute_group elants_attribute_group = {
1318 	.attrs = elants_attributes,
1319 };
1320 
1321 static int elants_i2c_power_on(struct elants_data *ts)
1322 {
1323 	int error;
1324 
1325 	/*
1326 	 * If we do not have reset gpio assume platform firmware
1327 	 * controls regulators and does power them on for us.
1328 	 */
1329 	if (IS_ERR_OR_NULL(ts->reset_gpio))
1330 		return 0;
1331 
1332 	error = regulator_enable(ts->vcc33);
1333 	if (error) {
1334 		dev_err(&ts->client->dev,
1335 			"failed to enable vcc33 regulator: %d\n",
1336 			error);
1337 		return error;
1338 	}
1339 
1340 	error = regulator_enable(ts->vccio);
1341 	if (error) {
1342 		dev_err(&ts->client->dev,
1343 			"failed to enable vccio regulator: %d\n",
1344 			error);
1345 		regulator_disable(ts->vcc33);
1346 		return error;
1347 	}
1348 
1349 	/*
1350 	 * We need to wait a bit after powering on controller before
1351 	 * we are allowed to release reset GPIO.
1352 	 */
1353 	usleep_range(ELAN_POWERON_DELAY_USEC, ELAN_POWERON_DELAY_USEC + 100);
1354 
1355 	gpiod_set_value_cansleep(ts->reset_gpio, 0);
1356 
1357 	msleep(ELAN_RESET_DELAY_MSEC);
1358 
1359 	return 0;
1360 }
1361 
1362 static void elants_i2c_power_off(void *_data)
1363 {
1364 	struct elants_data *ts = _data;
1365 
1366 	if (!IS_ERR_OR_NULL(ts->reset_gpio)) {
1367 		/*
1368 		 * Activate reset gpio to prevent leakage through the
1369 		 * pin once we shut off power to the controller.
1370 		 */
1371 		gpiod_set_value_cansleep(ts->reset_gpio, 1);
1372 		regulator_disable(ts->vccio);
1373 		regulator_disable(ts->vcc33);
1374 	}
1375 }
1376 
1377 #ifdef CONFIG_ACPI
1378 static const struct acpi_device_id i2c_hid_ids[] = {
1379 	{"ACPI0C50", 0 },
1380 	{"PNP0C50", 0 },
1381 	{ },
1382 };
1383 
1384 static const guid_t i2c_hid_guid =
1385 	GUID_INIT(0x3CDFF6F7, 0x4267, 0x4555,
1386 		  0xAD, 0x05, 0xB3, 0x0A, 0x3D, 0x89, 0x38, 0xDE);
1387 
1388 static bool elants_acpi_is_hid_device(struct device *dev)
1389 {
1390 	acpi_handle handle = ACPI_HANDLE(dev);
1391 	union acpi_object *obj;
1392 
1393 	if (acpi_match_device_ids(ACPI_COMPANION(dev), i2c_hid_ids))
1394 		return false;
1395 
1396 	obj = acpi_evaluate_dsm_typed(handle, &i2c_hid_guid, 1, 1, NULL, ACPI_TYPE_INTEGER);
1397 	if (obj) {
1398 		ACPI_FREE(obj);
1399 		return true;
1400 	}
1401 
1402 	return false;
1403 }
1404 #else
1405 static bool elants_acpi_is_hid_device(struct device *dev)
1406 {
1407 	return false;
1408 }
1409 #endif
1410 
1411 static int elants_i2c_probe(struct i2c_client *client)
1412 {
1413 	union i2c_smbus_data dummy;
1414 	struct elants_data *ts;
1415 	unsigned long irqflags;
1416 	int error;
1417 
1418 	/* Don't bind to i2c-hid compatible devices, these are handled by the i2c-hid drv. */
1419 	if (elants_acpi_is_hid_device(&client->dev)) {
1420 		dev_warn(&client->dev, "This device appears to be an I2C-HID device, not binding\n");
1421 		return -ENODEV;
1422 	}
1423 
1424 	if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) {
1425 		dev_err(&client->dev, "I2C check functionality error\n");
1426 		return -ENXIO;
1427 	}
1428 
1429 	ts = devm_kzalloc(&client->dev, sizeof(struct elants_data), GFP_KERNEL);
1430 	if (!ts)
1431 		return -ENOMEM;
1432 
1433 	mutex_init(&ts->sysfs_mutex);
1434 	init_completion(&ts->cmd_done);
1435 
1436 	ts->client = client;
1437 	ts->chip_id = (enum elants_chip_id)(uintptr_t)device_get_match_data(&client->dev);
1438 	i2c_set_clientdata(client, ts);
1439 
1440 	ts->vcc33 = devm_regulator_get(&client->dev, "vcc33");
1441 	if (IS_ERR(ts->vcc33))
1442 		return dev_err_probe(&client->dev, PTR_ERR(ts->vcc33),
1443 				     "Failed to get 'vcc33' regulator\n");
1444 
1445 	ts->vccio = devm_regulator_get(&client->dev, "vccio");
1446 	if (IS_ERR(ts->vccio))
1447 		return dev_err_probe(&client->dev, PTR_ERR(ts->vccio),
1448 				     "Failed to get 'vccio' regulator\n");
1449 
1450 	ts->reset_gpio = devm_gpiod_get(&client->dev, "reset", GPIOD_OUT_HIGH);
1451 	if (IS_ERR(ts->reset_gpio)) {
1452 		error = PTR_ERR(ts->reset_gpio);
1453 
1454 		if (error == -EPROBE_DEFER)
1455 			return error;
1456 
1457 		if (error != -ENOENT && error != -ENOSYS) {
1458 			dev_err(&client->dev,
1459 				"failed to get reset gpio: %d\n",
1460 				error);
1461 			return error;
1462 		}
1463 
1464 		ts->keep_power_in_suspend = true;
1465 	}
1466 
1467 	error = elants_i2c_power_on(ts);
1468 	if (error)
1469 		return error;
1470 
1471 	error = devm_add_action_or_reset(&client->dev,
1472 					 elants_i2c_power_off, ts);
1473 	if (error) {
1474 		dev_err(&client->dev,
1475 			"failed to install power off action: %d\n", error);
1476 		return error;
1477 	}
1478 
1479 	/* Make sure there is something at this address */
1480 	if (i2c_smbus_xfer(client->adapter, client->addr, 0,
1481 			   I2C_SMBUS_READ, 0, I2C_SMBUS_BYTE, &dummy) < 0) {
1482 		dev_err(&client->dev, "nothing at this address\n");
1483 		return -ENXIO;
1484 	}
1485 
1486 	error = elants_i2c_initialize(ts);
1487 	if (error) {
1488 		dev_err(&client->dev, "failed to initialize: %d\n", error);
1489 		return error;
1490 	}
1491 
1492 	ts->input = devm_input_allocate_device(&client->dev);
1493 	if (!ts->input) {
1494 		dev_err(&client->dev, "Failed to allocate input device\n");
1495 		return -ENOMEM;
1496 	}
1497 
1498 	ts->input->name = "Elan Touchscreen";
1499 	ts->input->id.bustype = BUS_I2C;
1500 
1501 	/* Multitouch input params setup */
1502 
1503 	input_set_abs_params(ts->input, ABS_MT_POSITION_X, 0, ts->x_max, 0, 0);
1504 	input_set_abs_params(ts->input, ABS_MT_POSITION_Y, 0, ts->y_max, 0, 0);
1505 	input_set_abs_params(ts->input, ABS_MT_TOUCH_MAJOR, 0, 255, 0, 0);
1506 	input_set_abs_params(ts->input, ABS_MT_PRESSURE, 0, 255, 0, 0);
1507 	input_set_abs_params(ts->input, ABS_MT_TOOL_TYPE,
1508 			     0, MT_TOOL_PALM, 0, 0);
1509 
1510 	touchscreen_parse_properties(ts->input, true, &ts->prop);
1511 
1512 	if (ts->chip_id == EKTF3624 && ts->phy_x && ts->phy_y) {
1513 		/* calculate resolution from size */
1514 		ts->x_res = DIV_ROUND_CLOSEST(ts->prop.max_x, ts->phy_x);
1515 		ts->y_res = DIV_ROUND_CLOSEST(ts->prop.max_y, ts->phy_y);
1516 	}
1517 
1518 	input_abs_set_res(ts->input, ABS_MT_POSITION_X, ts->x_res);
1519 	input_abs_set_res(ts->input, ABS_MT_POSITION_Y, ts->y_res);
1520 	input_abs_set_res(ts->input, ABS_MT_TOUCH_MAJOR, ts->major_res);
1521 
1522 	error = input_mt_init_slots(ts->input, MAX_CONTACT_NUM,
1523 				    INPUT_MT_DIRECT | INPUT_MT_DROP_UNUSED);
1524 	if (error) {
1525 		dev_err(&client->dev,
1526 			"failed to initialize MT slots: %d\n", error);
1527 		return error;
1528 	}
1529 
1530 	error = input_register_device(ts->input);
1531 	if (error) {
1532 		dev_err(&client->dev,
1533 			"unable to register input device: %d\n", error);
1534 		return error;
1535 	}
1536 
1537 	/*
1538 	 * Platform code (ACPI, DTS) should normally set up interrupt
1539 	 * for us, but in case it did not let's fall back to using falling
1540 	 * edge to be compatible with older Chromebooks.
1541 	 */
1542 	irqflags = irq_get_trigger_type(client->irq);
1543 	if (!irqflags)
1544 		irqflags = IRQF_TRIGGER_FALLING;
1545 
1546 	error = devm_request_threaded_irq(&client->dev, client->irq,
1547 					  NULL, elants_i2c_irq,
1548 					  irqflags | IRQF_ONESHOT,
1549 					  client->name, ts);
1550 	if (error) {
1551 		dev_err(&client->dev, "Failed to register interrupt\n");
1552 		return error;
1553 	}
1554 
1555 	error = devm_device_add_group(&client->dev, &elants_attribute_group);
1556 	if (error) {
1557 		dev_err(&client->dev, "failed to create sysfs attributes: %d\n",
1558 			error);
1559 		return error;
1560 	}
1561 
1562 	return 0;
1563 }
1564 
1565 static int elants_i2c_suspend(struct device *dev)
1566 {
1567 	struct i2c_client *client = to_i2c_client(dev);
1568 	struct elants_data *ts = i2c_get_clientdata(client);
1569 	const u8 set_sleep_cmd[] = {
1570 		CMD_HEADER_WRITE, E_POWER_STATE_SLEEP, 0x00, 0x01
1571 	};
1572 	int retry_cnt;
1573 	int error;
1574 
1575 	/* Command not support in IAP recovery mode */
1576 	if (ts->iap_mode != ELAN_IAP_OPERATIONAL)
1577 		return -EBUSY;
1578 
1579 	disable_irq(client->irq);
1580 
1581 	if (device_may_wakeup(dev)) {
1582 		/*
1583 		 * The device will automatically enter idle mode
1584 		 * that has reduced power consumption.
1585 		 */
1586 		return 0;
1587 	} else if (ts->keep_power_in_suspend) {
1588 		for (retry_cnt = 0; retry_cnt < MAX_RETRIES; retry_cnt++) {
1589 			error = elants_i2c_send(client, set_sleep_cmd,
1590 						sizeof(set_sleep_cmd));
1591 			if (!error)
1592 				break;
1593 
1594 			dev_err(&client->dev,
1595 				"suspend command failed: %d\n", error);
1596 		}
1597 	} else {
1598 		elants_i2c_power_off(ts);
1599 	}
1600 
1601 	return 0;
1602 }
1603 
1604 static int elants_i2c_resume(struct device *dev)
1605 {
1606 	struct i2c_client *client = to_i2c_client(dev);
1607 	struct elants_data *ts = i2c_get_clientdata(client);
1608 	const u8 set_active_cmd[] = {
1609 		CMD_HEADER_WRITE, E_POWER_STATE_RESUME, 0x00, 0x01
1610 	};
1611 	int retry_cnt;
1612 	int error;
1613 
1614 	if (device_may_wakeup(dev)) {
1615 		elants_i2c_sw_reset(client);
1616 	} else if (ts->keep_power_in_suspend) {
1617 		for (retry_cnt = 0; retry_cnt < MAX_RETRIES; retry_cnt++) {
1618 			error = elants_i2c_send(client, set_active_cmd,
1619 						sizeof(set_active_cmd));
1620 			if (!error)
1621 				break;
1622 
1623 			dev_err(&client->dev,
1624 				"resume command failed: %d\n", error);
1625 		}
1626 	} else {
1627 		elants_i2c_power_on(ts);
1628 		elants_i2c_initialize(ts);
1629 	}
1630 
1631 	ts->state = ELAN_STATE_NORMAL;
1632 	enable_irq(client->irq);
1633 
1634 	return 0;
1635 }
1636 
1637 static DEFINE_SIMPLE_DEV_PM_OPS(elants_i2c_pm_ops,
1638 				elants_i2c_suspend, elants_i2c_resume);
1639 
1640 static const struct i2c_device_id elants_i2c_id[] = {
1641 	{ DEVICE_NAME, EKTH3500 },
1642 	{ "ekth3500", EKTH3500 },
1643 	{ "ektf3624", EKTF3624 },
1644 	{ }
1645 };
1646 MODULE_DEVICE_TABLE(i2c, elants_i2c_id);
1647 
1648 #ifdef CONFIG_ACPI
1649 static const struct acpi_device_id elants_acpi_id[] = {
1650 	{ "ELAN0001", EKTH3500 },
1651 	{ }
1652 };
1653 MODULE_DEVICE_TABLE(acpi, elants_acpi_id);
1654 #endif
1655 
1656 #ifdef CONFIG_OF
1657 static const struct of_device_id elants_of_match[] = {
1658 	{ .compatible = "elan,ekth3500", .data = (void *)EKTH3500 },
1659 	{ .compatible = "elan,ektf3624", .data = (void *)EKTF3624 },
1660 	{ /* sentinel */ }
1661 };
1662 MODULE_DEVICE_TABLE(of, elants_of_match);
1663 #endif
1664 
1665 static struct i2c_driver elants_i2c_driver = {
1666 	.probe = elants_i2c_probe,
1667 	.id_table = elants_i2c_id,
1668 	.driver = {
1669 		.name = DEVICE_NAME,
1670 		.pm = pm_sleep_ptr(&elants_i2c_pm_ops),
1671 		.acpi_match_table = ACPI_PTR(elants_acpi_id),
1672 		.of_match_table = of_match_ptr(elants_of_match),
1673 		.probe_type = PROBE_PREFER_ASYNCHRONOUS,
1674 	},
1675 };
1676 module_i2c_driver(elants_i2c_driver);
1677 
1678 MODULE_AUTHOR("Scott Liu <scott.liu@emc.com.tw>");
1679 MODULE_DESCRIPTION("Elan I2c Touchscreen driver");
1680 MODULE_LICENSE("GPL");
1681