1 /*
2  * Elan Microelectronics touch panels with I2C interface
3  *
4  * Copyright (C) 2014 Elan Microelectronics Corporation.
5  * Scott Liu <scott.liu@emc.com.tw>
6  *
7  * This code is partly based on hid-multitouch.c:
8  *
9  *  Copyright (c) 2010-2012 Stephane Chatty <chatty@enac.fr>
10  *  Copyright (c) 2010-2012 Benjamin Tissoires <benjamin.tissoires@gmail.com>
11  *  Copyright (c) 2010-2012 Ecole Nationale de l'Aviation Civile, France
12  *
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  * This software is licensed under the terms of the GNU General Public
23  * License version 2, as published by the Free Software Foundation, and
24  * may be copied, distributed, and modified under those terms.
25  */
26 
27 #include <linux/module.h>
28 #include <linux/input.h>
29 #include <linux/interrupt.h>
30 #include <linux/platform_device.h>
31 #include <linux/async.h>
32 #include <linux/i2c.h>
33 #include <linux/delay.h>
34 #include <linux/uaccess.h>
35 #include <linux/buffer_head.h>
36 #include <linux/slab.h>
37 #include <linux/firmware.h>
38 #include <linux/input/mt.h>
39 #include <linux/acpi.h>
40 #include <linux/of.h>
41 #include <asm/unaligned.h>
42 
43 /* Device, Driver information */
44 #define DEVICE_NAME	"elants_i2c"
45 #define DRV_VERSION	"1.0.9"
46 
47 /* Convert from rows or columns into resolution */
48 #define ELAN_TS_RESOLUTION(n, m)   (((n) - 1) * (m))
49 
50 /* FW header data */
51 #define HEADER_SIZE		4
52 #define FW_HDR_TYPE		0
53 #define FW_HDR_COUNT		1
54 #define FW_HDR_LENGTH		2
55 
56 /* Buffer mode Queue Header information */
57 #define QUEUE_HEADER_SINGLE	0x62
58 #define QUEUE_HEADER_NORMAL	0X63
59 #define QUEUE_HEADER_WAIT	0x64
60 
61 /* Command header definition */
62 #define CMD_HEADER_WRITE	0x54
63 #define CMD_HEADER_READ		0x53
64 #define CMD_HEADER_6B_READ	0x5B
65 #define CMD_HEADER_RESP		0x52
66 #define CMD_HEADER_6B_RESP	0x9B
67 #define CMD_HEADER_HELLO	0x55
68 #define CMD_HEADER_REK		0x66
69 
70 /* FW position data */
71 #define PACKET_SIZE		55
72 #define MAX_CONTACT_NUM		10
73 #define FW_POS_HEADER		0
74 #define FW_POS_STATE		1
75 #define FW_POS_TOTAL		2
76 #define FW_POS_XY		3
77 #define FW_POS_CHECKSUM		34
78 #define FW_POS_WIDTH		35
79 #define FW_POS_PRESSURE		45
80 
81 #define HEADER_REPORT_10_FINGER	0x62
82 
83 /* Header (4 bytes) plus 3 fill 10-finger packets */
84 #define MAX_PACKET_SIZE		169
85 
86 #define BOOT_TIME_DELAY_MS	50
87 
88 /* FW read command, 0x53 0x?? 0x0, 0x01 */
89 #define E_ELAN_INFO_FW_VER	0x00
90 #define E_ELAN_INFO_BC_VER	0x10
91 #define E_ELAN_INFO_TEST_VER	0xE0
92 #define E_ELAN_INFO_FW_ID	0xF0
93 #define E_INFO_OSR		0xD6
94 #define E_INFO_PHY_SCAN		0xD7
95 #define E_INFO_PHY_DRIVER	0xD8
96 
97 #define MAX_RETRIES		3
98 #define MAX_FW_UPDATE_RETRIES	30
99 
100 #define ELAN_FW_PAGESIZE	132
101 
102 /* calibration timeout definition */
103 #define ELAN_CALI_TIMEOUT_MSEC	10000
104 
105 enum elants_state {
106 	ELAN_STATE_NORMAL,
107 	ELAN_WAIT_QUEUE_HEADER,
108 	ELAN_WAIT_RECALIBRATION,
109 };
110 
111 enum elants_iap_mode {
112 	ELAN_IAP_OPERATIONAL,
113 	ELAN_IAP_RECOVERY,
114 };
115 
116 /* struct elants_data - represents state of Elan touchscreen device */
117 struct elants_data {
118 	struct i2c_client *client;
119 	struct input_dev *input;
120 
121 	u16 fw_version;
122 	u8 test_version;
123 	u8 solution_version;
124 	u8 bc_version;
125 	u8 iap_version;
126 	u16 hw_version;
127 	unsigned int x_res;	/* resolution in units/mm */
128 	unsigned int y_res;
129 	unsigned int x_max;
130 	unsigned int y_max;
131 
132 	enum elants_state state;
133 	enum elants_iap_mode iap_mode;
134 
135 	/* Guards against concurrent access to the device via sysfs */
136 	struct mutex sysfs_mutex;
137 
138 	u8 cmd_resp[HEADER_SIZE];
139 	struct completion cmd_done;
140 
141 	u8 buf[MAX_PACKET_SIZE];
142 
143 	bool wake_irq_enabled;
144 };
145 
146 static int elants_i2c_send(struct i2c_client *client,
147 			   const void *data, size_t size)
148 {
149 	int ret;
150 
151 	ret = i2c_master_send(client, data, size);
152 	if (ret == size)
153 		return 0;
154 
155 	if (ret >= 0)
156 		ret = -EIO;
157 
158 	dev_err(&client->dev, "%s failed (%*ph): %d\n",
159 		__func__, (int)size, data, ret);
160 
161 	return ret;
162 }
163 
164 static int elants_i2c_read(struct i2c_client *client, void *data, size_t size)
165 {
166 	int ret;
167 
168 	ret = i2c_master_recv(client, data, size);
169 	if (ret == size)
170 		return 0;
171 
172 	if (ret >= 0)
173 		ret = -EIO;
174 
175 	dev_err(&client->dev, "%s failed: %d\n", __func__, ret);
176 
177 	return ret;
178 }
179 
180 static int elants_i2c_execute_command(struct i2c_client *client,
181 				      const u8 *cmd, size_t cmd_size,
182 				      u8 *resp, size_t resp_size)
183 {
184 	struct i2c_msg msgs[2];
185 	int ret;
186 	u8 expected_response;
187 
188 	switch (cmd[0]) {
189 	case CMD_HEADER_READ:
190 		expected_response = CMD_HEADER_RESP;
191 		break;
192 
193 	case CMD_HEADER_6B_READ:
194 		expected_response = CMD_HEADER_6B_RESP;
195 		break;
196 
197 	default:
198 		dev_err(&client->dev, "%s: invalid command %*ph\n",
199 			__func__, (int)cmd_size, cmd);
200 		return -EINVAL;
201 	}
202 
203 	msgs[0].addr = client->addr;
204 	msgs[0].flags = client->flags & I2C_M_TEN;
205 	msgs[0].len = cmd_size;
206 	msgs[0].buf = (u8 *)cmd;
207 
208 	msgs[1].addr = client->addr;
209 	msgs[1].flags = client->flags & I2C_M_TEN;
210 	msgs[1].flags |= I2C_M_RD;
211 	msgs[1].len = resp_size;
212 	msgs[1].buf = resp;
213 
214 	ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs));
215 	if (ret < 0)
216 		return ret;
217 
218 	if (ret != ARRAY_SIZE(msgs) || resp[FW_HDR_TYPE] != expected_response)
219 		return -EIO;
220 
221 	return 0;
222 }
223 
224 static int elants_i2c_calibrate(struct elants_data *ts)
225 {
226 	struct i2c_client *client = ts->client;
227 	int ret, error;
228 	static const u8 w_flashkey[] = { 0x54, 0xC0, 0xE1, 0x5A };
229 	static const u8 rek[] = { 0x54, 0x29, 0x00, 0x01 };
230 	static const u8 rek_resp[] = { CMD_HEADER_REK, 0x66, 0x66, 0x66 };
231 
232 	disable_irq(client->irq);
233 
234 	ts->state = ELAN_WAIT_RECALIBRATION;
235 	reinit_completion(&ts->cmd_done);
236 
237 	elants_i2c_send(client, w_flashkey, sizeof(w_flashkey));
238 	elants_i2c_send(client, rek, sizeof(rek));
239 
240 	enable_irq(client->irq);
241 
242 	ret = wait_for_completion_interruptible_timeout(&ts->cmd_done,
243 				msecs_to_jiffies(ELAN_CALI_TIMEOUT_MSEC));
244 
245 	ts->state = ELAN_STATE_NORMAL;
246 
247 	if (ret <= 0) {
248 		error = ret < 0 ? ret : -ETIMEDOUT;
249 		dev_err(&client->dev,
250 			"error while waiting for calibration to complete: %d\n",
251 			error);
252 		return error;
253 	}
254 
255 	if (memcmp(rek_resp, ts->cmd_resp, sizeof(rek_resp))) {
256 		dev_err(&client->dev,
257 			"unexpected calibration response: %*ph\n",
258 			(int)sizeof(ts->cmd_resp), ts->cmd_resp);
259 		return -EINVAL;
260 	}
261 
262 	return 0;
263 }
264 
265 static int elants_i2c_sw_reset(struct i2c_client *client)
266 {
267 	const u8 soft_rst_cmd[] = { 0x77, 0x77, 0x77, 0x77 };
268 	int error;
269 
270 	error = elants_i2c_send(client, soft_rst_cmd,
271 				sizeof(soft_rst_cmd));
272 	if (error) {
273 		dev_err(&client->dev, "software reset failed: %d\n", error);
274 		return error;
275 	}
276 
277 	/*
278 	 * We should wait at least 10 msec (but no more than 40) before
279 	 * sending fastboot or IAP command to the device.
280 	 */
281 	msleep(30);
282 
283 	return 0;
284 }
285 
286 static u16 elants_i2c_parse_version(u8 *buf)
287 {
288 	return get_unaligned_be32(buf) >> 4;
289 }
290 
291 static int elants_i2c_query_fw_id(struct elants_data *ts)
292 {
293 	struct i2c_client *client = ts->client;
294 	int error, retry_cnt;
295 	const u8 cmd[] = { CMD_HEADER_READ, E_ELAN_INFO_FW_ID, 0x00, 0x01 };
296 	u8 resp[HEADER_SIZE];
297 
298 	for (retry_cnt = 0; retry_cnt < MAX_RETRIES; retry_cnt++) {
299 		error = elants_i2c_execute_command(client, cmd, sizeof(cmd),
300 						   resp, sizeof(resp));
301 		if (!error) {
302 			ts->hw_version = elants_i2c_parse_version(resp);
303 			if (ts->hw_version != 0xffff)
304 				return 0;
305 		}
306 
307 		dev_dbg(&client->dev, "read fw id error=%d, buf=%*phC\n",
308 			error, (int)sizeof(resp), resp);
309 	}
310 
311 	dev_err(&client->dev,
312 		"Failed to read fw id or fw id is invalid\n");
313 
314 	return -EINVAL;
315 }
316 
317 static int elants_i2c_query_fw_version(struct elants_data *ts)
318 {
319 	struct i2c_client *client = ts->client;
320 	int error, retry_cnt;
321 	const u8 cmd[] = { CMD_HEADER_READ, E_ELAN_INFO_FW_VER, 0x00, 0x01 };
322 	u8 resp[HEADER_SIZE];
323 
324 	for (retry_cnt = 0; retry_cnt < MAX_RETRIES; retry_cnt++) {
325 		error = elants_i2c_execute_command(client, cmd, sizeof(cmd),
326 						   resp, sizeof(resp));
327 		if (!error) {
328 			ts->fw_version = elants_i2c_parse_version(resp);
329 			if (ts->fw_version != 0x0000 &&
330 			    ts->fw_version != 0xffff)
331 				return 0;
332 		}
333 
334 		dev_dbg(&client->dev, "read fw version error=%d, buf=%*phC\n",
335 			error, (int)sizeof(resp), resp);
336 	}
337 
338 	dev_err(&client->dev,
339 		"Failed to read fw version or fw version is invalid\n");
340 
341 	return -EINVAL;
342 }
343 
344 static int elants_i2c_query_test_version(struct elants_data *ts)
345 {
346 	struct i2c_client *client = ts->client;
347 	int error, retry_cnt;
348 	u16 version;
349 	const u8 cmd[] = { CMD_HEADER_READ, E_ELAN_INFO_TEST_VER, 0x00, 0x01 };
350 	u8 resp[HEADER_SIZE];
351 
352 	for (retry_cnt = 0; retry_cnt < MAX_RETRIES; retry_cnt++) {
353 		error = elants_i2c_execute_command(client, cmd, sizeof(cmd),
354 						   resp, sizeof(resp));
355 		if (!error) {
356 			version = elants_i2c_parse_version(resp);
357 			ts->test_version = version >> 8;
358 			ts->solution_version = version & 0xff;
359 
360 			return 0;
361 		}
362 
363 		dev_dbg(&client->dev,
364 			"read test version error rc=%d, buf=%*phC\n",
365 			error, (int)sizeof(resp), resp);
366 	}
367 
368 	dev_err(&client->dev, "Failed to read test version\n");
369 
370 	return -EINVAL;
371 }
372 
373 static int elants_i2c_query_bc_version(struct elants_data *ts)
374 {
375 	struct i2c_client *client = ts->client;
376 	const u8 cmd[] = { CMD_HEADER_READ, E_ELAN_INFO_BC_VER, 0x00, 0x01 };
377 	u8 resp[HEADER_SIZE];
378 	u16 version;
379 	int error;
380 
381 	error = elants_i2c_execute_command(client, cmd, sizeof(cmd),
382 					   resp, sizeof(resp));
383 	if (error) {
384 		dev_err(&client->dev,
385 			"read BC version error=%d, buf=%*phC\n",
386 			error, (int)sizeof(resp), resp);
387 		return error;
388 	}
389 
390 	version = elants_i2c_parse_version(resp);
391 	ts->bc_version = version >> 8;
392 	ts->iap_version = version & 0xff;
393 
394 	return 0;
395 }
396 
397 static int elants_i2c_query_ts_info(struct elants_data *ts)
398 {
399 	struct i2c_client *client = ts->client;
400 	int error;
401 	u8 resp[17];
402 	u16 phy_x, phy_y, rows, cols, osr;
403 	const u8 get_resolution_cmd[] = {
404 		CMD_HEADER_6B_READ, 0x00, 0x00, 0x00, 0x00, 0x00
405 	};
406 	const u8 get_osr_cmd[] = {
407 		CMD_HEADER_READ, E_INFO_OSR, 0x00, 0x01
408 	};
409 	const u8 get_physical_scan_cmd[] = {
410 		CMD_HEADER_READ, E_INFO_PHY_SCAN, 0x00, 0x01
411 	};
412 	const u8 get_physical_drive_cmd[] = {
413 		CMD_HEADER_READ, E_INFO_PHY_DRIVER, 0x00, 0x01
414 	};
415 
416 	/* Get trace number */
417 	error = elants_i2c_execute_command(client,
418 					   get_resolution_cmd,
419 					   sizeof(get_resolution_cmd),
420 					   resp, sizeof(resp));
421 	if (error) {
422 		dev_err(&client->dev, "get resolution command failed: %d\n",
423 			error);
424 		return error;
425 	}
426 
427 	rows = resp[2] + resp[6] + resp[10];
428 	cols = resp[3] + resp[7] + resp[11];
429 
430 	/* Process mm_to_pixel information */
431 	error = elants_i2c_execute_command(client,
432 					   get_osr_cmd, sizeof(get_osr_cmd),
433 					   resp, sizeof(resp));
434 	if (error) {
435 		dev_err(&client->dev, "get osr command failed: %d\n",
436 			error);
437 		return error;
438 	}
439 
440 	osr = resp[3];
441 
442 	error = elants_i2c_execute_command(client,
443 					   get_physical_scan_cmd,
444 					   sizeof(get_physical_scan_cmd),
445 					   resp, sizeof(resp));
446 	if (error) {
447 		dev_err(&client->dev, "get physical scan command failed: %d\n",
448 			error);
449 		return error;
450 	}
451 
452 	phy_x = get_unaligned_be16(&resp[2]);
453 
454 	error = elants_i2c_execute_command(client,
455 					   get_physical_drive_cmd,
456 					   sizeof(get_physical_drive_cmd),
457 					   resp, sizeof(resp));
458 	if (error) {
459 		dev_err(&client->dev, "get physical drive command failed: %d\n",
460 			error);
461 		return error;
462 	}
463 
464 	phy_y = get_unaligned_be16(&resp[2]);
465 
466 	dev_dbg(&client->dev, "phy_x=%d, phy_y=%d\n", phy_x, phy_y);
467 
468 	if (rows == 0 || cols == 0 || osr == 0) {
469 		dev_warn(&client->dev,
470 			 "invalid trace number data: %d, %d, %d\n",
471 			 rows, cols, osr);
472 	} else {
473 		/* translate trace number to TS resolution */
474 		ts->x_max = ELAN_TS_RESOLUTION(rows, osr);
475 		ts->x_res = DIV_ROUND_CLOSEST(ts->x_max, phy_x);
476 		ts->y_max = ELAN_TS_RESOLUTION(cols, osr);
477 		ts->y_res = DIV_ROUND_CLOSEST(ts->y_max, phy_y);
478 	}
479 
480 	return 0;
481 }
482 
483 static int elants_i2c_fastboot(struct i2c_client *client)
484 {
485 	const u8 boot_cmd[] = { 0x4D, 0x61, 0x69, 0x6E };
486 	int error;
487 
488 	error = elants_i2c_send(client, boot_cmd, sizeof(boot_cmd));
489 	if (error) {
490 		dev_err(&client->dev, "boot failed: %d\n", error);
491 		return error;
492 	}
493 
494 	dev_dbg(&client->dev, "boot success -- 0x%x\n", client->addr);
495 	return 0;
496 }
497 
498 static int elants_i2c_initialize(struct elants_data *ts)
499 {
500 	struct i2c_client *client = ts->client;
501 	int error, retry_cnt;
502 	const u8 hello_packet[] = { 0x55, 0x55, 0x55, 0x55 };
503 	const u8 recov_packet[] = { 0x55, 0x55, 0x80, 0x80 };
504 	u8 buf[HEADER_SIZE];
505 
506 	for (retry_cnt = 0; retry_cnt < MAX_RETRIES; retry_cnt++) {
507 		error = elants_i2c_sw_reset(client);
508 		if (error) {
509 			/* Continue initializing if it's the last try */
510 			if (retry_cnt < MAX_RETRIES - 1)
511 				continue;
512 		}
513 
514 		error = elants_i2c_fastboot(client);
515 		if (error) {
516 			/* Continue initializing if it's the last try */
517 			if (retry_cnt < MAX_RETRIES - 1)
518 				continue;
519 		}
520 
521 		/* Wait for Hello packet */
522 		msleep(BOOT_TIME_DELAY_MS);
523 
524 		error = elants_i2c_read(client, buf, sizeof(buf));
525 		if (error) {
526 			dev_err(&client->dev,
527 				"failed to read 'hello' packet: %d\n", error);
528 		} else if (!memcmp(buf, hello_packet, sizeof(hello_packet))) {
529 			ts->iap_mode = ELAN_IAP_OPERATIONAL;
530 			break;
531 		} else if (!memcmp(buf, recov_packet, sizeof(recov_packet))) {
532 			/*
533 			 * Setting error code will mark device
534 			 * in recovery mode below.
535 			 */
536 			error = -EIO;
537 			break;
538 		} else {
539 			error = -EINVAL;
540 			dev_err(&client->dev,
541 				"invalid 'hello' packet: %*ph\n",
542 				(int)sizeof(buf), buf);
543 		}
544 	}
545 
546 	if (!error)
547 		error = elants_i2c_query_fw_id(ts);
548 	if (!error)
549 		error = elants_i2c_query_fw_version(ts);
550 
551 	if (error) {
552 		ts->iap_mode = ELAN_IAP_RECOVERY;
553 	} else {
554 		elants_i2c_query_test_version(ts);
555 		elants_i2c_query_bc_version(ts);
556 		elants_i2c_query_ts_info(ts);
557 	}
558 
559 	return 0;
560 }
561 
562 /*
563  * Firmware update interface.
564  */
565 
566 static int elants_i2c_fw_write_page(struct i2c_client *client,
567 				    const void *page)
568 {
569 	const u8 ack_ok[] = { 0xaa, 0xaa };
570 	u8 buf[2];
571 	int retry;
572 	int error;
573 
574 	for (retry = 0; retry < MAX_FW_UPDATE_RETRIES; retry++) {
575 		error = elants_i2c_send(client, page, ELAN_FW_PAGESIZE);
576 		if (error) {
577 			dev_err(&client->dev,
578 				"IAP Write Page failed: %d\n", error);
579 			continue;
580 		}
581 
582 		error = elants_i2c_read(client, buf, 2);
583 		if (error) {
584 			dev_err(&client->dev,
585 				"IAP Ack read failed: %d\n", error);
586 			return error;
587 		}
588 
589 		if (!memcmp(buf, ack_ok, sizeof(ack_ok)))
590 			return 0;
591 
592 		error = -EIO;
593 		dev_err(&client->dev,
594 			"IAP Get Ack Error [%02x:%02x]\n",
595 			buf[0], buf[1]);
596 	}
597 
598 	return error;
599 }
600 
601 static int elants_i2c_do_update_firmware(struct i2c_client *client,
602 					 const struct firmware *fw,
603 					 bool force)
604 {
605 	const u8 enter_iap[] = { 0x45, 0x49, 0x41, 0x50 };
606 	const u8 enter_iap2[] = { 0x54, 0x00, 0x12, 0x34 };
607 	const u8 iap_ack[] = { 0x55, 0xaa, 0x33, 0xcc };
608 	u8 buf[HEADER_SIZE];
609 	u16 send_id;
610 	int page, n_fw_pages;
611 	int error;
612 
613 	/* Recovery mode detection! */
614 	if (force) {
615 		dev_dbg(&client->dev, "Recovery mode procedure\n");
616 		error = elants_i2c_send(client, enter_iap2, sizeof(enter_iap2));
617 	} else {
618 		/* Start IAP Procedure */
619 		dev_dbg(&client->dev, "Normal IAP procedure\n");
620 		elants_i2c_sw_reset(client);
621 
622 		error = elants_i2c_send(client, enter_iap, sizeof(enter_iap));
623 	}
624 
625 	if (error) {
626 		dev_err(&client->dev, "failed to enter IAP mode: %d\n", error);
627 		return error;
628 	}
629 
630 	msleep(20);
631 
632 	/* check IAP state */
633 	error = elants_i2c_read(client, buf, 4);
634 	if (error) {
635 		dev_err(&client->dev,
636 			"failed to read IAP acknowledgement: %d\n",
637 			error);
638 		return error;
639 	}
640 
641 	if (memcmp(buf, iap_ack, sizeof(iap_ack))) {
642 		dev_err(&client->dev,
643 			"failed to enter IAP: %*ph (expected %*ph)\n",
644 			(int)sizeof(buf), buf, (int)sizeof(iap_ack), iap_ack);
645 		return -EIO;
646 	}
647 
648 	dev_info(&client->dev, "successfully entered IAP mode");
649 
650 	send_id = client->addr;
651 	error = elants_i2c_send(client, &send_id, 1);
652 	if (error) {
653 		dev_err(&client->dev, "sending dummy byte failed: %d\n",
654 			error);
655 		return error;
656 	}
657 
658 	/* Clear the last page of Master */
659 	error = elants_i2c_send(client, fw->data, ELAN_FW_PAGESIZE);
660 	if (error) {
661 		dev_err(&client->dev, "clearing of the last page failed: %d\n",
662 			error);
663 		return error;
664 	}
665 
666 	error = elants_i2c_read(client, buf, 2);
667 	if (error) {
668 		dev_err(&client->dev,
669 			"failed to read ACK for clearing the last page: %d\n",
670 			error);
671 		return error;
672 	}
673 
674 	n_fw_pages = fw->size / ELAN_FW_PAGESIZE;
675 	dev_dbg(&client->dev, "IAP Pages = %d\n", n_fw_pages);
676 
677 	for (page = 0; page < n_fw_pages; page++) {
678 		error = elants_i2c_fw_write_page(client,
679 					fw->data + page * ELAN_FW_PAGESIZE);
680 		if (error) {
681 			dev_err(&client->dev,
682 				"failed to write FW page %d: %d\n",
683 				page, error);
684 			return error;
685 		}
686 	}
687 
688 	/* Old iap needs to wait 200ms for WDT and rest is for hello packets */
689 	msleep(300);
690 
691 	dev_info(&client->dev, "firmware update completed\n");
692 	return 0;
693 }
694 
695 static int elants_i2c_fw_update(struct elants_data *ts)
696 {
697 	struct i2c_client *client = ts->client;
698 	const struct firmware *fw;
699 	char *fw_name;
700 	int error;
701 
702 	fw_name = kasprintf(GFP_KERNEL, "elants_i2c_%04x.bin", ts->hw_version);
703 	if (!fw_name)
704 		return -ENOMEM;
705 
706 	dev_info(&client->dev, "requesting fw name = %s\n", fw_name);
707 	error = request_firmware(&fw, fw_name, &client->dev);
708 	kfree(fw_name);
709 	if (error) {
710 		dev_err(&client->dev, "failed to request firmware: %d\n",
711 			error);
712 		return error;
713 	}
714 
715 	if (fw->size % ELAN_FW_PAGESIZE) {
716 		dev_err(&client->dev, "invalid firmware length: %zu\n",
717 			fw->size);
718 		error = -EINVAL;
719 		goto out;
720 	}
721 
722 	disable_irq(client->irq);
723 
724 	error = elants_i2c_do_update_firmware(client, fw,
725 					ts->iap_mode == ELAN_IAP_RECOVERY);
726 	if (error) {
727 		dev_err(&client->dev, "firmware update failed: %d\n", error);
728 		ts->iap_mode = ELAN_IAP_RECOVERY;
729 		goto out_enable_irq;
730 	}
731 
732 	error = elants_i2c_initialize(ts);
733 	if (error) {
734 		dev_err(&client->dev,
735 			"failed to initialize device after firmware update: %d\n",
736 			error);
737 		ts->iap_mode = ELAN_IAP_RECOVERY;
738 		goto out_enable_irq;
739 	}
740 
741 	ts->iap_mode = ELAN_IAP_OPERATIONAL;
742 
743 out_enable_irq:
744 	ts->state = ELAN_STATE_NORMAL;
745 	enable_irq(client->irq);
746 	msleep(100);
747 
748 	if (!error)
749 		elants_i2c_calibrate(ts);
750 out:
751 	release_firmware(fw);
752 	return error;
753 }
754 
755 /*
756  * Event reporting.
757  */
758 
759 static void elants_i2c_mt_event(struct elants_data *ts, u8 *buf)
760 {
761 	struct input_dev *input = ts->input;
762 	unsigned int n_fingers;
763 	u16 finger_state;
764 	int i;
765 
766 	n_fingers = buf[FW_POS_STATE + 1] & 0x0f;
767 	finger_state = ((buf[FW_POS_STATE + 1] & 0x30) << 4) |
768 			buf[FW_POS_STATE];
769 
770 	dev_dbg(&ts->client->dev,
771 		"n_fingers: %u, state: %04x\n",  n_fingers, finger_state);
772 
773 	for (i = 0; i < MAX_CONTACT_NUM && n_fingers; i++) {
774 		if (finger_state & 1) {
775 			unsigned int x, y, p, w;
776 			u8 *pos;
777 
778 			pos = &buf[FW_POS_XY + i * 3];
779 			x = (((u16)pos[0] & 0xf0) << 4) | pos[1];
780 			y = (((u16)pos[0] & 0x0f) << 8) | pos[2];
781 			p = buf[FW_POS_PRESSURE + i];
782 			w = buf[FW_POS_WIDTH + i];
783 
784 			dev_dbg(&ts->client->dev, "i=%d x=%d y=%d p=%d w=%d\n",
785 				i, x, y, p, w);
786 
787 			input_mt_slot(input, i);
788 			input_mt_report_slot_state(input, MT_TOOL_FINGER, true);
789 			input_event(input, EV_ABS, ABS_MT_POSITION_X, x);
790 			input_event(input, EV_ABS, ABS_MT_POSITION_Y, y);
791 			input_event(input, EV_ABS, ABS_MT_PRESSURE, p);
792 			input_event(input, EV_ABS, ABS_MT_TOUCH_MAJOR, w);
793 
794 			n_fingers--;
795 		}
796 
797 		finger_state >>= 1;
798 	}
799 
800 	input_mt_sync_frame(input);
801 	input_sync(input);
802 }
803 
804 static u8 elants_i2c_calculate_checksum(u8 *buf)
805 {
806 	u8 checksum = 0;
807 	u8 i;
808 
809 	for (i = 0; i < FW_POS_CHECKSUM; i++)
810 		checksum += buf[i];
811 
812 	return checksum;
813 }
814 
815 static void elants_i2c_event(struct elants_data *ts, u8 *buf)
816 {
817 	u8 checksum = elants_i2c_calculate_checksum(buf);
818 
819 	if (unlikely(buf[FW_POS_CHECKSUM] != checksum))
820 		dev_warn(&ts->client->dev,
821 			 "%s: invalid checksum for packet %02x: %02x vs. %02x\n",
822 			 __func__, buf[FW_POS_HEADER],
823 			 checksum, buf[FW_POS_CHECKSUM]);
824 	else if (unlikely(buf[FW_POS_HEADER] != HEADER_REPORT_10_FINGER))
825 		dev_warn(&ts->client->dev,
826 			 "%s: unknown packet type: %02x\n",
827 			 __func__, buf[FW_POS_HEADER]);
828 	else
829 		elants_i2c_mt_event(ts, buf);
830 }
831 
832 static irqreturn_t elants_i2c_irq(int irq, void *_dev)
833 {
834 	const u8 wait_packet[] = { 0x64, 0x64, 0x64, 0x64 };
835 	struct elants_data *ts = _dev;
836 	struct i2c_client *client = ts->client;
837 	int report_count, report_len;
838 	int i;
839 	int len;
840 
841 	len = i2c_master_recv(client, ts->buf, sizeof(ts->buf));
842 	if (len < 0) {
843 		dev_err(&client->dev, "%s: failed to read data: %d\n",
844 			__func__, len);
845 		goto out;
846 	}
847 
848 	dev_dbg(&client->dev, "%s: packet %*ph\n",
849 		__func__, HEADER_SIZE, ts->buf);
850 
851 	switch (ts->state) {
852 	case ELAN_WAIT_RECALIBRATION:
853 		if (ts->buf[FW_HDR_TYPE] == CMD_HEADER_REK) {
854 			memcpy(ts->cmd_resp, ts->buf, sizeof(ts->cmd_resp));
855 			complete(&ts->cmd_done);
856 			ts->state = ELAN_STATE_NORMAL;
857 		}
858 		break;
859 
860 	case ELAN_WAIT_QUEUE_HEADER:
861 		if (ts->buf[FW_HDR_TYPE] != QUEUE_HEADER_NORMAL)
862 			break;
863 
864 		ts->state = ELAN_STATE_NORMAL;
865 		/* fall through */
866 
867 	case ELAN_STATE_NORMAL:
868 
869 		switch (ts->buf[FW_HDR_TYPE]) {
870 		case CMD_HEADER_HELLO:
871 		case CMD_HEADER_RESP:
872 		case CMD_HEADER_REK:
873 			break;
874 
875 		case QUEUE_HEADER_WAIT:
876 			if (memcmp(ts->buf, wait_packet, sizeof(wait_packet))) {
877 				dev_err(&client->dev,
878 					"invalid wait packet %*ph\n",
879 					HEADER_SIZE, ts->buf);
880 			} else {
881 				ts->state = ELAN_WAIT_QUEUE_HEADER;
882 				udelay(30);
883 			}
884 			break;
885 
886 		case QUEUE_HEADER_SINGLE:
887 			elants_i2c_event(ts, &ts->buf[HEADER_SIZE]);
888 			break;
889 
890 		case QUEUE_HEADER_NORMAL:
891 			report_count = ts->buf[FW_HDR_COUNT];
892 			if (report_count > 3) {
893 				dev_err(&client->dev,
894 					"too large report count: %*ph\n",
895 					HEADER_SIZE, ts->buf);
896 				break;
897 			}
898 
899 			report_len = ts->buf[FW_HDR_LENGTH] / report_count;
900 			if (report_len != PACKET_SIZE) {
901 				dev_err(&client->dev,
902 					"mismatching report length: %*ph\n",
903 					HEADER_SIZE, ts->buf);
904 				break;
905 			}
906 
907 			for (i = 0; i < report_count; i++) {
908 				u8 *buf = ts->buf + HEADER_SIZE +
909 							i * PACKET_SIZE;
910 				elants_i2c_event(ts, buf);
911 			}
912 			break;
913 
914 		default:
915 			dev_err(&client->dev, "unknown packet %*ph\n",
916 				HEADER_SIZE, ts->buf);
917 			break;
918 		}
919 		break;
920 	}
921 
922 out:
923 	return IRQ_HANDLED;
924 }
925 
926 /*
927  * sysfs interface
928  */
929 static ssize_t calibrate_store(struct device *dev,
930 			       struct device_attribute *attr,
931 			      const char *buf, size_t count)
932 {
933 	struct i2c_client *client = to_i2c_client(dev);
934 	struct elants_data *ts = i2c_get_clientdata(client);
935 	int error;
936 
937 	error = mutex_lock_interruptible(&ts->sysfs_mutex);
938 	if (error)
939 		return error;
940 
941 	error = elants_i2c_calibrate(ts);
942 
943 	mutex_unlock(&ts->sysfs_mutex);
944 	return error ?: count;
945 }
946 
947 static ssize_t write_update_fw(struct device *dev,
948 			       struct device_attribute *attr,
949 			       const char *buf, size_t count)
950 {
951 	struct i2c_client *client = to_i2c_client(dev);
952 	struct elants_data *ts = i2c_get_clientdata(client);
953 	int error;
954 
955 	error = mutex_lock_interruptible(&ts->sysfs_mutex);
956 	if (error)
957 		return error;
958 
959 	error = elants_i2c_fw_update(ts);
960 	dev_dbg(dev, "firmware update result: %d\n", error);
961 
962 	mutex_unlock(&ts->sysfs_mutex);
963 	return error ?: count;
964 }
965 
966 static ssize_t show_iap_mode(struct device *dev,
967 			     struct device_attribute *attr, char *buf)
968 {
969 	struct i2c_client *client = to_i2c_client(dev);
970 	struct elants_data *ts = i2c_get_clientdata(client);
971 
972 	return sprintf(buf, "%s\n",
973 		       ts->iap_mode == ELAN_IAP_OPERATIONAL ?
974 				"Normal" : "Recovery");
975 }
976 
977 static DEVICE_ATTR(calibrate, S_IWUSR, NULL, calibrate_store);
978 static DEVICE_ATTR(iap_mode, S_IRUGO, show_iap_mode, NULL);
979 static DEVICE_ATTR(update_fw, S_IWUSR, NULL, write_update_fw);
980 
981 struct elants_version_attribute {
982 	struct device_attribute dattr;
983 	size_t field_offset;
984 	size_t field_size;
985 };
986 
987 #define __ELANTS_FIELD_SIZE(_field)					\
988 	sizeof(((struct elants_data *)NULL)->_field)
989 #define __ELANTS_VERIFY_SIZE(_field)					\
990 	(BUILD_BUG_ON_ZERO(__ELANTS_FIELD_SIZE(_field) > 2) +		\
991 	 __ELANTS_FIELD_SIZE(_field))
992 #define ELANTS_VERSION_ATTR(_field)					\
993 	struct elants_version_attribute elants_ver_attr_##_field = {	\
994 		.dattr = __ATTR(_field, S_IRUGO,			\
995 				elants_version_attribute_show, NULL),	\
996 		.field_offset = offsetof(struct elants_data, _field),	\
997 		.field_size = __ELANTS_VERIFY_SIZE(_field),		\
998 	}
999 
1000 static ssize_t elants_version_attribute_show(struct device *dev,
1001 					     struct device_attribute *dattr,
1002 					     char *buf)
1003 {
1004 	struct i2c_client *client = to_i2c_client(dev);
1005 	struct elants_data *ts = i2c_get_clientdata(client);
1006 	struct elants_version_attribute *attr =
1007 		container_of(dattr, struct elants_version_attribute, dattr);
1008 	u8 *field = (u8 *)((char *)ts + attr->field_offset);
1009 	unsigned int fmt_size;
1010 	unsigned int val;
1011 
1012 	if (attr->field_size == 1) {
1013 		val = *field;
1014 		fmt_size = 2; /* 2 HEX digits */
1015 	} else {
1016 		val = *(u16 *)field;
1017 		fmt_size = 4; /* 4 HEX digits */
1018 	}
1019 
1020 	return sprintf(buf, "%0*x\n", fmt_size, val);
1021 }
1022 
1023 static ELANTS_VERSION_ATTR(fw_version);
1024 static ELANTS_VERSION_ATTR(hw_version);
1025 static ELANTS_VERSION_ATTR(test_version);
1026 static ELANTS_VERSION_ATTR(solution_version);
1027 static ELANTS_VERSION_ATTR(bc_version);
1028 static ELANTS_VERSION_ATTR(iap_version);
1029 
1030 static struct attribute *elants_attributes[] = {
1031 	&dev_attr_calibrate.attr,
1032 	&dev_attr_update_fw.attr,
1033 	&dev_attr_iap_mode.attr,
1034 
1035 	&elants_ver_attr_fw_version.dattr.attr,
1036 	&elants_ver_attr_hw_version.dattr.attr,
1037 	&elants_ver_attr_test_version.dattr.attr,
1038 	&elants_ver_attr_solution_version.dattr.attr,
1039 	&elants_ver_attr_bc_version.dattr.attr,
1040 	&elants_ver_attr_iap_version.dattr.attr,
1041 	NULL
1042 };
1043 
1044 static struct attribute_group elants_attribute_group = {
1045 	.attrs = elants_attributes,
1046 };
1047 
1048 static void elants_i2c_remove_sysfs_group(void *_data)
1049 {
1050 	struct elants_data *ts = _data;
1051 
1052 	sysfs_remove_group(&ts->client->dev.kobj, &elants_attribute_group);
1053 }
1054 
1055 static int elants_i2c_probe(struct i2c_client *client,
1056 			    const struct i2c_device_id *id)
1057 {
1058 	union i2c_smbus_data dummy;
1059 	struct elants_data *ts;
1060 	unsigned long irqflags;
1061 	int error;
1062 
1063 	if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) {
1064 		dev_err(&client->dev,
1065 			"%s: i2c check functionality error\n", DEVICE_NAME);
1066 		return -ENXIO;
1067 	}
1068 
1069 	/* Make sure there is something at this address */
1070 	if (i2c_smbus_xfer(client->adapter, client->addr, 0,
1071 			I2C_SMBUS_READ, 0, I2C_SMBUS_BYTE, &dummy) < 0) {
1072 		dev_err(&client->dev, "nothing at this address\n");
1073 		return -ENXIO;
1074 	}
1075 
1076 	ts = devm_kzalloc(&client->dev, sizeof(struct elants_data), GFP_KERNEL);
1077 	if (!ts)
1078 		return -ENOMEM;
1079 
1080 	mutex_init(&ts->sysfs_mutex);
1081 	init_completion(&ts->cmd_done);
1082 
1083 	ts->client = client;
1084 	i2c_set_clientdata(client, ts);
1085 
1086 	error = elants_i2c_initialize(ts);
1087 	if (error) {
1088 		dev_err(&client->dev, "failed to initialize: %d\n", error);
1089 		return error;
1090 	}
1091 
1092 	ts->input = devm_input_allocate_device(&client->dev);
1093 	if (!ts->input) {
1094 		dev_err(&client->dev, "Failed to allocate input device\n");
1095 		return -ENOMEM;
1096 	}
1097 
1098 	ts->input->name = "Elan Touchscreen";
1099 	ts->input->id.bustype = BUS_I2C;
1100 
1101 	__set_bit(BTN_TOUCH, ts->input->keybit);
1102 	__set_bit(EV_ABS, ts->input->evbit);
1103 	__set_bit(EV_KEY, ts->input->evbit);
1104 
1105 	/* Single touch input params setup */
1106 	input_set_abs_params(ts->input, ABS_X, 0, ts->x_max, 0, 0);
1107 	input_set_abs_params(ts->input, ABS_Y, 0, ts->y_max, 0, 0);
1108 	input_set_abs_params(ts->input, ABS_PRESSURE, 0, 255, 0, 0);
1109 	input_abs_set_res(ts->input, ABS_X, ts->x_res);
1110 	input_abs_set_res(ts->input, ABS_Y, ts->y_res);
1111 
1112 	/* Multitouch input params setup */
1113 	error = input_mt_init_slots(ts->input, MAX_CONTACT_NUM,
1114 				    INPUT_MT_DIRECT | INPUT_MT_DROP_UNUSED);
1115 	if (error) {
1116 		dev_err(&client->dev,
1117 			"failed to initialize MT slots: %d\n", error);
1118 		return error;
1119 	}
1120 
1121 	input_set_abs_params(ts->input, ABS_MT_POSITION_X, 0, ts->x_max, 0, 0);
1122 	input_set_abs_params(ts->input, ABS_MT_POSITION_Y, 0, ts->y_max, 0, 0);
1123 	input_set_abs_params(ts->input, ABS_MT_TOUCH_MAJOR, 0, 255, 0, 0);
1124 	input_set_abs_params(ts->input, ABS_MT_PRESSURE, 0, 255, 0, 0);
1125 	input_abs_set_res(ts->input, ABS_MT_POSITION_X, ts->x_res);
1126 	input_abs_set_res(ts->input, ABS_MT_POSITION_Y, ts->y_res);
1127 
1128 	input_set_drvdata(ts->input, ts);
1129 
1130 	error = input_register_device(ts->input);
1131 	if (error) {
1132 		dev_err(&client->dev,
1133 			"unable to register input device: %d\n", error);
1134 		return error;
1135 	}
1136 
1137 	/*
1138 	 * Systems using device tree should set up interrupt via DTS,
1139 	 * the rest will use the default falling edge interrupts.
1140 	 */
1141 	irqflags = client->dev.of_node ? 0 : IRQF_TRIGGER_FALLING;
1142 
1143 	error = devm_request_threaded_irq(&client->dev, client->irq,
1144 					  NULL, elants_i2c_irq,
1145 					  irqflags | IRQF_ONESHOT,
1146 					  client->name, ts);
1147 	if (error) {
1148 		dev_err(&client->dev, "Failed to register interrupt\n");
1149 		return error;
1150 	}
1151 
1152 	/*
1153 	 * Systems using device tree should set up wakeup via DTS,
1154 	 * the rest will configure device as wakeup source by default.
1155 	 */
1156 	if (!client->dev.of_node)
1157 		device_init_wakeup(&client->dev, true);
1158 
1159 	error = sysfs_create_group(&client->dev.kobj, &elants_attribute_group);
1160 	if (error) {
1161 		dev_err(&client->dev, "failed to create sysfs attributes: %d\n",
1162 			error);
1163 		return error;
1164 	}
1165 
1166 	error = devm_add_action(&client->dev,
1167 				elants_i2c_remove_sysfs_group, ts);
1168 	if (error) {
1169 		elants_i2c_remove_sysfs_group(ts);
1170 		dev_err(&client->dev,
1171 			"Failed to add sysfs cleanup action: %d\n",
1172 			error);
1173 		return error;
1174 	}
1175 
1176 	return 0;
1177 }
1178 
1179 static int __maybe_unused elants_i2c_suspend(struct device *dev)
1180 {
1181 	struct i2c_client *client = to_i2c_client(dev);
1182 	struct elants_data *ts = i2c_get_clientdata(client);
1183 	const u8 set_sleep_cmd[] = { 0x54, 0x50, 0x00, 0x01 };
1184 	int retry_cnt;
1185 	int error;
1186 
1187 	/* Command not support in IAP recovery mode */
1188 	if (ts->iap_mode != ELAN_IAP_OPERATIONAL)
1189 		return -EBUSY;
1190 
1191 	disable_irq(client->irq);
1192 
1193 	for (retry_cnt = 0; retry_cnt < MAX_RETRIES; retry_cnt++) {
1194 		error = elants_i2c_send(client, set_sleep_cmd,
1195 					sizeof(set_sleep_cmd));
1196 		if (!error)
1197 			break;
1198 
1199 		dev_err(&client->dev, "suspend command failed: %d\n", error);
1200 	}
1201 
1202 	if (device_may_wakeup(dev))
1203 		ts->wake_irq_enabled = (enable_irq_wake(client->irq) == 0);
1204 
1205 	return 0;
1206 }
1207 
1208 static int __maybe_unused elants_i2c_resume(struct device *dev)
1209 {
1210 	struct i2c_client *client = to_i2c_client(dev);
1211 	struct elants_data *ts = i2c_get_clientdata(client);
1212 	const u8 set_active_cmd[] = { 0x54, 0x58, 0x00, 0x01 };
1213 	int retry_cnt;
1214 	int error;
1215 
1216 	if (device_may_wakeup(dev) && ts->wake_irq_enabled)
1217 		disable_irq_wake(client->irq);
1218 
1219 	for (retry_cnt = 0; retry_cnt < MAX_RETRIES; retry_cnt++) {
1220 		error = elants_i2c_send(client, set_active_cmd,
1221 					sizeof(set_active_cmd));
1222 		if (!error)
1223 			break;
1224 
1225 		dev_err(&client->dev, "resume command failed: %d\n", error);
1226 	}
1227 
1228 	ts->state = ELAN_STATE_NORMAL;
1229 	enable_irq(client->irq);
1230 
1231 	return 0;
1232 }
1233 
1234 static SIMPLE_DEV_PM_OPS(elants_i2c_pm_ops,
1235 			 elants_i2c_suspend, elants_i2c_resume);
1236 
1237 static const struct i2c_device_id elants_i2c_id[] = {
1238 	{ DEVICE_NAME, 0 },
1239 	{ }
1240 };
1241 MODULE_DEVICE_TABLE(i2c, elants_i2c_id);
1242 
1243 #ifdef CONFIG_ACPI
1244 static const struct acpi_device_id elants_acpi_id[] = {
1245 	{ "ELAN0001", 0 },
1246 	{ }
1247 };
1248 MODULE_DEVICE_TABLE(acpi, elants_acpi_id);
1249 #endif
1250 
1251 #ifdef CONFIG_OF
1252 static const struct of_device_id elants_of_match[] = {
1253 	{ .compatible = "elan,ekth3500" },
1254 	{ /* sentinel */ }
1255 };
1256 MODULE_DEVICE_TABLE(of, elants_of_match);
1257 #endif
1258 
1259 static struct i2c_driver elants_i2c_driver = {
1260 	.probe = elants_i2c_probe,
1261 	.id_table = elants_i2c_id,
1262 	.driver = {
1263 		.name = DEVICE_NAME,
1264 		.owner = THIS_MODULE,
1265 		.pm = &elants_i2c_pm_ops,
1266 		.acpi_match_table = ACPI_PTR(elants_acpi_id),
1267 		.of_match_table = of_match_ptr(elants_of_match),
1268 	},
1269 };
1270 module_i2c_driver(elants_i2c_driver);
1271 
1272 MODULE_AUTHOR("Scott Liu <scott.liu@emc.com.tw>");
1273 MODULE_DESCRIPTION("Elan I2c Touchscreen driver");
1274 MODULE_VERSION(DRV_VERSION);
1275 MODULE_LICENSE("GPL");
1276