1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Atmel maXTouch Touchscreen driver
4  *
5  * Copyright (C) 2010 Samsung Electronics Co.Ltd
6  * Copyright (C) 2011-2014 Atmel Corporation
7  * Copyright (C) 2012 Google, Inc.
8  * Copyright (C) 2016 Zodiac Inflight Innovations
9  *
10  * Author: Joonyoung Shim <jy0922.shim@samsung.com>
11  */
12 
13 #include <linux/acpi.h>
14 #include <linux/dmi.h>
15 #include <linux/module.h>
16 #include <linux/init.h>
17 #include <linux/completion.h>
18 #include <linux/delay.h>
19 #include <linux/firmware.h>
20 #include <linux/i2c.h>
21 #include <linux/input/mt.h>
22 #include <linux/interrupt.h>
23 #include <linux/irq.h>
24 #include <linux/of.h>
25 #include <linux/property.h>
26 #include <linux/slab.h>
27 #include <linux/gpio/consumer.h>
28 #include <asm/unaligned.h>
29 #include <media/v4l2-device.h>
30 #include <media/v4l2-ioctl.h>
31 #include <media/videobuf2-v4l2.h>
32 #include <media/videobuf2-vmalloc.h>
33 
34 /* Firmware files */
35 #define MXT_FW_NAME		"maxtouch.fw"
36 #define MXT_CFG_NAME		"maxtouch.cfg"
37 #define MXT_CFG_MAGIC		"OBP_RAW V1"
38 
39 /* Registers */
40 #define MXT_OBJECT_START	0x07
41 #define MXT_OBJECT_SIZE		6
42 #define MXT_INFO_CHECKSUM_SIZE	3
43 #define MXT_MAX_BLOCK_WRITE	256
44 
45 /* Object types */
46 #define MXT_DEBUG_DIAGNOSTIC_T37	37
47 #define MXT_GEN_MESSAGE_T5		5
48 #define MXT_GEN_COMMAND_T6		6
49 #define MXT_GEN_POWER_T7		7
50 #define MXT_GEN_ACQUIRE_T8		8
51 #define MXT_GEN_DATASOURCE_T53		53
52 #define MXT_TOUCH_MULTI_T9		9
53 #define MXT_TOUCH_KEYARRAY_T15		15
54 #define MXT_TOUCH_PROXIMITY_T23		23
55 #define MXT_TOUCH_PROXKEY_T52		52
56 #define MXT_PROCI_GRIPFACE_T20		20
57 #define MXT_PROCG_NOISE_T22		22
58 #define MXT_PROCI_ONETOUCH_T24		24
59 #define MXT_PROCI_TWOTOUCH_T27		27
60 #define MXT_PROCI_GRIP_T40		40
61 #define MXT_PROCI_PALM_T41		41
62 #define MXT_PROCI_TOUCHSUPPRESSION_T42	42
63 #define MXT_PROCI_STYLUS_T47		47
64 #define MXT_PROCG_NOISESUPPRESSION_T48	48
65 #define MXT_SPT_COMMSCONFIG_T18		18
66 #define MXT_SPT_GPIOPWM_T19		19
67 #define MXT_SPT_SELFTEST_T25		25
68 #define MXT_SPT_CTECONFIG_T28		28
69 #define MXT_SPT_USERDATA_T38		38
70 #define MXT_SPT_DIGITIZER_T43		43
71 #define MXT_SPT_MESSAGECOUNT_T44	44
72 #define MXT_SPT_CTECONFIG_T46		46
73 #define MXT_SPT_DYNAMICCONFIGURATIONCONTAINER_T71 71
74 #define MXT_TOUCH_MULTITOUCHSCREEN_T100 100
75 
76 /* MXT_GEN_MESSAGE_T5 object */
77 #define MXT_RPTID_NOMSG		0xff
78 
79 /* MXT_GEN_COMMAND_T6 field */
80 #define MXT_COMMAND_RESET	0
81 #define MXT_COMMAND_BACKUPNV	1
82 #define MXT_COMMAND_CALIBRATE	2
83 #define MXT_COMMAND_REPORTALL	3
84 #define MXT_COMMAND_DIAGNOSTIC	5
85 
86 /* Define for T6 status byte */
87 #define MXT_T6_STATUS_RESET	BIT(7)
88 #define MXT_T6_STATUS_OFL	BIT(6)
89 #define MXT_T6_STATUS_SIGERR	BIT(5)
90 #define MXT_T6_STATUS_CAL	BIT(4)
91 #define MXT_T6_STATUS_CFGERR	BIT(3)
92 #define MXT_T6_STATUS_COMSERR	BIT(2)
93 
94 /* MXT_GEN_POWER_T7 field */
95 struct t7_config {
96 	u8 idle;
97 	u8 active;
98 } __packed;
99 
100 #define MXT_POWER_CFG_RUN		0
101 #define MXT_POWER_CFG_DEEPSLEEP		1
102 
103 /* MXT_TOUCH_MULTI_T9 field */
104 #define MXT_T9_CTRL		0
105 #define MXT_T9_XSIZE		3
106 #define MXT_T9_YSIZE		4
107 #define MXT_T9_ORIENT		9
108 #define MXT_T9_RANGE		18
109 
110 /* MXT_TOUCH_MULTI_T9 status */
111 #define MXT_T9_UNGRIP		BIT(0)
112 #define MXT_T9_SUPPRESS		BIT(1)
113 #define MXT_T9_AMP		BIT(2)
114 #define MXT_T9_VECTOR		BIT(3)
115 #define MXT_T9_MOVE		BIT(4)
116 #define MXT_T9_RELEASE		BIT(5)
117 #define MXT_T9_PRESS		BIT(6)
118 #define MXT_T9_DETECT		BIT(7)
119 
120 struct t9_range {
121 	__le16 x;
122 	__le16 y;
123 } __packed;
124 
125 /* MXT_TOUCH_MULTI_T9 orient */
126 #define MXT_T9_ORIENT_SWITCH	BIT(0)
127 #define MXT_T9_ORIENT_INVERTX	BIT(1)
128 #define MXT_T9_ORIENT_INVERTY	BIT(2)
129 
130 /* MXT_SPT_COMMSCONFIG_T18 */
131 #define MXT_COMMS_CTRL		0
132 #define MXT_COMMS_CMD		1
133 #define MXT_COMMS_RETRIGEN	BIT(6)
134 
135 /* MXT_DEBUG_DIAGNOSTIC_T37 */
136 #define MXT_DIAGNOSTIC_PAGEUP	0x01
137 #define MXT_DIAGNOSTIC_DELTAS	0x10
138 #define MXT_DIAGNOSTIC_REFS	0x11
139 #define MXT_DIAGNOSTIC_SIZE	128
140 
141 #define MXT_FAMILY_1386			160
142 #define MXT1386_COLUMNS			3
143 #define MXT1386_PAGES_PER_COLUMN	8
144 
145 struct t37_debug {
146 #ifdef CONFIG_TOUCHSCREEN_ATMEL_MXT_T37
147 	u8 mode;
148 	u8 page;
149 	u8 data[MXT_DIAGNOSTIC_SIZE];
150 #endif
151 };
152 
153 /* Define for MXT_GEN_COMMAND_T6 */
154 #define MXT_BOOT_VALUE		0xa5
155 #define MXT_RESET_VALUE		0x01
156 #define MXT_BACKUP_VALUE	0x55
157 
158 /* T100 Multiple Touch Touchscreen */
159 #define MXT_T100_CTRL		0
160 #define MXT_T100_CFG1		1
161 #define MXT_T100_TCHAUX		3
162 #define MXT_T100_XSIZE		9
163 #define MXT_T100_XRANGE		13
164 #define MXT_T100_YSIZE		20
165 #define MXT_T100_YRANGE		24
166 
167 #define MXT_T100_CFG_SWITCHXY	BIT(5)
168 #define MXT_T100_CFG_INVERTY	BIT(6)
169 #define MXT_T100_CFG_INVERTX	BIT(7)
170 
171 #define MXT_T100_TCHAUX_VECT	BIT(0)
172 #define MXT_T100_TCHAUX_AMPL	BIT(1)
173 #define MXT_T100_TCHAUX_AREA	BIT(2)
174 
175 #define MXT_T100_DETECT		BIT(7)
176 #define MXT_T100_TYPE_MASK	0x70
177 
178 enum t100_type {
179 	MXT_T100_TYPE_FINGER		= 1,
180 	MXT_T100_TYPE_PASSIVE_STYLUS	= 2,
181 	MXT_T100_TYPE_HOVERING_FINGER	= 4,
182 	MXT_T100_TYPE_GLOVE		= 5,
183 	MXT_T100_TYPE_LARGE_TOUCH	= 6,
184 };
185 
186 #define MXT_DISTANCE_ACTIVE_TOUCH	0
187 #define MXT_DISTANCE_HOVERING		1
188 
189 #define MXT_TOUCH_MAJOR_DEFAULT		1
190 #define MXT_PRESSURE_DEFAULT		1
191 
192 /* Delay times */
193 #define MXT_BACKUP_TIME		50	/* msec */
194 #define MXT_RESET_GPIO_TIME	20	/* msec */
195 #define MXT_RESET_INVALID_CHG	100	/* msec */
196 #define MXT_RESET_TIME		200	/* msec */
197 #define MXT_RESET_TIMEOUT	3000	/* msec */
198 #define MXT_CRC_TIMEOUT		1000	/* msec */
199 #define MXT_FW_RESET_TIME	3000	/* msec */
200 #define MXT_FW_CHG_TIMEOUT	300	/* msec */
201 
202 /* Command to unlock bootloader */
203 #define MXT_UNLOCK_CMD_MSB	0xaa
204 #define MXT_UNLOCK_CMD_LSB	0xdc
205 
206 /* Bootloader mode status */
207 #define MXT_WAITING_BOOTLOAD_CMD	0xc0	/* valid 7 6 bit only */
208 #define MXT_WAITING_FRAME_DATA	0x80	/* valid 7 6 bit only */
209 #define MXT_FRAME_CRC_CHECK	0x02
210 #define MXT_FRAME_CRC_FAIL	0x03
211 #define MXT_FRAME_CRC_PASS	0x04
212 #define MXT_APP_CRC_FAIL	0x40	/* valid 7 8 bit only */
213 #define MXT_BOOT_STATUS_MASK	0x3f
214 #define MXT_BOOT_EXTENDED_ID	BIT(5)
215 #define MXT_BOOT_ID_MASK	0x1f
216 
217 /* Touchscreen absolute values */
218 #define MXT_MAX_AREA		0xff
219 
220 #define MXT_PIXELS_PER_MM	20
221 
222 struct mxt_info {
223 	u8 family_id;
224 	u8 variant_id;
225 	u8 version;
226 	u8 build;
227 	u8 matrix_xsize;
228 	u8 matrix_ysize;
229 	u8 object_num;
230 };
231 
232 struct mxt_object {
233 	u8 type;
234 	u16 start_address;
235 	u8 size_minus_one;
236 	u8 instances_minus_one;
237 	u8 num_report_ids;
238 } __packed;
239 
240 struct mxt_dbg {
241 	u16 t37_address;
242 	u16 diag_cmd_address;
243 	struct t37_debug *t37_buf;
244 	unsigned int t37_pages;
245 	unsigned int t37_nodes;
246 
247 	struct v4l2_device v4l2;
248 	struct v4l2_pix_format format;
249 	struct video_device vdev;
250 	struct vb2_queue queue;
251 	struct mutex lock;
252 	int input;
253 };
254 
255 enum v4l_dbg_inputs {
256 	MXT_V4L_INPUT_DELTAS,
257 	MXT_V4L_INPUT_REFS,
258 	MXT_V4L_INPUT_MAX,
259 };
260 
261 enum mxt_suspend_mode {
262 	MXT_SUSPEND_DEEP_SLEEP	= 0,
263 	MXT_SUSPEND_T9_CTRL	= 1,
264 };
265 
266 /* Config update context */
267 struct mxt_cfg {
268 	u8 *raw;
269 	size_t raw_size;
270 	off_t raw_pos;
271 
272 	u8 *mem;
273 	size_t mem_size;
274 	int start_ofs;
275 
276 	struct mxt_info info;
277 };
278 
279 /* Each client has this additional data */
280 struct mxt_data {
281 	struct i2c_client *client;
282 	struct input_dev *input_dev;
283 	char phys[64];		/* device physical location */
284 	struct mxt_object *object_table;
285 	struct mxt_info *info;
286 	void *raw_info_block;
287 	unsigned int irq;
288 	unsigned int max_x;
289 	unsigned int max_y;
290 	bool invertx;
291 	bool inverty;
292 	bool xy_switch;
293 	u8 xsize;
294 	u8 ysize;
295 	bool in_bootloader;
296 	u16 mem_size;
297 	u8 t100_aux_ampl;
298 	u8 t100_aux_area;
299 	u8 t100_aux_vect;
300 	u8 max_reportid;
301 	u32 config_crc;
302 	u32 info_crc;
303 	u8 bootloader_addr;
304 	u8 *msg_buf;
305 	u8 t6_status;
306 	bool update_input;
307 	u8 last_message_count;
308 	u8 num_touchids;
309 	u8 multitouch;
310 	struct t7_config t7_cfg;
311 	struct mxt_dbg dbg;
312 	struct gpio_desc *reset_gpio;
313 	bool use_retrigen_workaround;
314 
315 	/* Cached parameters from object table */
316 	u16 T5_address;
317 	u8 T5_msg_size;
318 	u8 T6_reportid;
319 	u16 T6_address;
320 	u16 T7_address;
321 	u16 T71_address;
322 	u8 T9_reportid_min;
323 	u8 T9_reportid_max;
324 	u16 T18_address;
325 	u8 T19_reportid;
326 	u16 T44_address;
327 	u8 T100_reportid_min;
328 	u8 T100_reportid_max;
329 
330 	/* for fw update in bootloader */
331 	struct completion bl_completion;
332 
333 	/* for reset handling */
334 	struct completion reset_completion;
335 
336 	/* for config update handling */
337 	struct completion crc_completion;
338 
339 	u32 *t19_keymap;
340 	unsigned int t19_num_keys;
341 
342 	enum mxt_suspend_mode suspend_mode;
343 };
344 
345 struct mxt_vb2_buffer {
346 	struct vb2_buffer	vb;
347 	struct list_head	list;
348 };
349 
350 static size_t mxt_obj_size(const struct mxt_object *obj)
351 {
352 	return obj->size_minus_one + 1;
353 }
354 
355 static size_t mxt_obj_instances(const struct mxt_object *obj)
356 {
357 	return obj->instances_minus_one + 1;
358 }
359 
360 static bool mxt_object_readable(unsigned int type)
361 {
362 	switch (type) {
363 	case MXT_GEN_COMMAND_T6:
364 	case MXT_GEN_POWER_T7:
365 	case MXT_GEN_ACQUIRE_T8:
366 	case MXT_GEN_DATASOURCE_T53:
367 	case MXT_TOUCH_MULTI_T9:
368 	case MXT_TOUCH_KEYARRAY_T15:
369 	case MXT_TOUCH_PROXIMITY_T23:
370 	case MXT_TOUCH_PROXKEY_T52:
371 	case MXT_TOUCH_MULTITOUCHSCREEN_T100:
372 	case MXT_PROCI_GRIPFACE_T20:
373 	case MXT_PROCG_NOISE_T22:
374 	case MXT_PROCI_ONETOUCH_T24:
375 	case MXT_PROCI_TWOTOUCH_T27:
376 	case MXT_PROCI_GRIP_T40:
377 	case MXT_PROCI_PALM_T41:
378 	case MXT_PROCI_TOUCHSUPPRESSION_T42:
379 	case MXT_PROCI_STYLUS_T47:
380 	case MXT_PROCG_NOISESUPPRESSION_T48:
381 	case MXT_SPT_COMMSCONFIG_T18:
382 	case MXT_SPT_GPIOPWM_T19:
383 	case MXT_SPT_SELFTEST_T25:
384 	case MXT_SPT_CTECONFIG_T28:
385 	case MXT_SPT_USERDATA_T38:
386 	case MXT_SPT_DIGITIZER_T43:
387 	case MXT_SPT_CTECONFIG_T46:
388 	case MXT_SPT_DYNAMICCONFIGURATIONCONTAINER_T71:
389 		return true;
390 	default:
391 		return false;
392 	}
393 }
394 
395 static void mxt_dump_message(struct mxt_data *data, u8 *message)
396 {
397 	dev_dbg(&data->client->dev, "message: %*ph\n",
398 		data->T5_msg_size, message);
399 }
400 
401 static int mxt_wait_for_completion(struct mxt_data *data,
402 				   struct completion *comp,
403 				   unsigned int timeout_ms)
404 {
405 	struct device *dev = &data->client->dev;
406 	unsigned long timeout = msecs_to_jiffies(timeout_ms);
407 	long ret;
408 
409 	ret = wait_for_completion_interruptible_timeout(comp, timeout);
410 	if (ret < 0) {
411 		return ret;
412 	} else if (ret == 0) {
413 		dev_err(dev, "Wait for completion timed out.\n");
414 		return -ETIMEDOUT;
415 	}
416 	return 0;
417 }
418 
419 static int mxt_bootloader_read(struct mxt_data *data,
420 			       u8 *val, unsigned int count)
421 {
422 	int ret;
423 	struct i2c_msg msg;
424 
425 	msg.addr = data->bootloader_addr;
426 	msg.flags = data->client->flags & I2C_M_TEN;
427 	msg.flags |= I2C_M_RD;
428 	msg.len = count;
429 	msg.buf = val;
430 
431 	ret = i2c_transfer(data->client->adapter, &msg, 1);
432 	if (ret == 1) {
433 		ret = 0;
434 	} else {
435 		ret = ret < 0 ? ret : -EIO;
436 		dev_err(&data->client->dev, "%s: i2c recv failed (%d)\n",
437 			__func__, ret);
438 	}
439 
440 	return ret;
441 }
442 
443 static int mxt_bootloader_write(struct mxt_data *data,
444 				const u8 * const val, unsigned int count)
445 {
446 	int ret;
447 	struct i2c_msg msg;
448 
449 	msg.addr = data->bootloader_addr;
450 	msg.flags = data->client->flags & I2C_M_TEN;
451 	msg.len = count;
452 	msg.buf = (u8 *)val;
453 
454 	ret = i2c_transfer(data->client->adapter, &msg, 1);
455 	if (ret == 1) {
456 		ret = 0;
457 	} else {
458 		ret = ret < 0 ? ret : -EIO;
459 		dev_err(&data->client->dev, "%s: i2c send failed (%d)\n",
460 			__func__, ret);
461 	}
462 
463 	return ret;
464 }
465 
466 static int mxt_lookup_bootloader_address(struct mxt_data *data, bool retry)
467 {
468 	u8 appmode = data->client->addr;
469 	u8 bootloader;
470 	u8 family_id = data->info ? data->info->family_id : 0;
471 
472 	switch (appmode) {
473 	case 0x4a:
474 	case 0x4b:
475 		/* Chips after 1664S use different scheme */
476 		if (retry || family_id >= 0xa2) {
477 			bootloader = appmode - 0x24;
478 			break;
479 		}
480 		fallthrough;	/* for normal case */
481 	case 0x4c:
482 	case 0x4d:
483 	case 0x5a:
484 	case 0x5b:
485 		bootloader = appmode - 0x26;
486 		break;
487 
488 	default:
489 		dev_err(&data->client->dev,
490 			"Appmode i2c address 0x%02x not found\n",
491 			appmode);
492 		return -EINVAL;
493 	}
494 
495 	data->bootloader_addr = bootloader;
496 	return 0;
497 }
498 
499 static int mxt_probe_bootloader(struct mxt_data *data, bool alt_address)
500 {
501 	struct device *dev = &data->client->dev;
502 	int error;
503 	u8 val;
504 	bool crc_failure;
505 
506 	error = mxt_lookup_bootloader_address(data, alt_address);
507 	if (error)
508 		return error;
509 
510 	error = mxt_bootloader_read(data, &val, 1);
511 	if (error)
512 		return error;
513 
514 	/* Check app crc fail mode */
515 	crc_failure = (val & ~MXT_BOOT_STATUS_MASK) == MXT_APP_CRC_FAIL;
516 
517 	dev_err(dev, "Detected bootloader, status:%02X%s\n",
518 			val, crc_failure ? ", APP_CRC_FAIL" : "");
519 
520 	return 0;
521 }
522 
523 static u8 mxt_get_bootloader_version(struct mxt_data *data, u8 val)
524 {
525 	struct device *dev = &data->client->dev;
526 	u8 buf[3];
527 
528 	if (val & MXT_BOOT_EXTENDED_ID) {
529 		if (mxt_bootloader_read(data, &buf[0], 3) != 0) {
530 			dev_err(dev, "%s: i2c failure\n", __func__);
531 			return val;
532 		}
533 
534 		dev_dbg(dev, "Bootloader ID:%d Version:%d\n", buf[1], buf[2]);
535 
536 		return buf[0];
537 	} else {
538 		dev_dbg(dev, "Bootloader ID:%d\n", val & MXT_BOOT_ID_MASK);
539 
540 		return val;
541 	}
542 }
543 
544 static int mxt_check_bootloader(struct mxt_data *data, unsigned int state,
545 				bool wait)
546 {
547 	struct device *dev = &data->client->dev;
548 	u8 val;
549 	int ret;
550 
551 recheck:
552 	if (wait) {
553 		/*
554 		 * In application update mode, the interrupt
555 		 * line signals state transitions. We must wait for the
556 		 * CHG assertion before reading the status byte.
557 		 * Once the status byte has been read, the line is deasserted.
558 		 */
559 		ret = mxt_wait_for_completion(data, &data->bl_completion,
560 					      MXT_FW_CHG_TIMEOUT);
561 		if (ret) {
562 			/*
563 			 * TODO: handle -ERESTARTSYS better by terminating
564 			 * fw update process before returning to userspace
565 			 * by writing length 0x000 to device (iff we are in
566 			 * WAITING_FRAME_DATA state).
567 			 */
568 			dev_err(dev, "Update wait error %d\n", ret);
569 			return ret;
570 		}
571 	}
572 
573 	ret = mxt_bootloader_read(data, &val, 1);
574 	if (ret)
575 		return ret;
576 
577 	if (state == MXT_WAITING_BOOTLOAD_CMD)
578 		val = mxt_get_bootloader_version(data, val);
579 
580 	switch (state) {
581 	case MXT_WAITING_BOOTLOAD_CMD:
582 	case MXT_WAITING_FRAME_DATA:
583 	case MXT_APP_CRC_FAIL:
584 		val &= ~MXT_BOOT_STATUS_MASK;
585 		break;
586 	case MXT_FRAME_CRC_PASS:
587 		if (val == MXT_FRAME_CRC_CHECK) {
588 			goto recheck;
589 		} else if (val == MXT_FRAME_CRC_FAIL) {
590 			dev_err(dev, "Bootloader CRC fail\n");
591 			return -EINVAL;
592 		}
593 		break;
594 	default:
595 		return -EINVAL;
596 	}
597 
598 	if (val != state) {
599 		dev_err(dev, "Invalid bootloader state %02X != %02X\n",
600 			val, state);
601 		return -EINVAL;
602 	}
603 
604 	return 0;
605 }
606 
607 static int mxt_send_bootloader_cmd(struct mxt_data *data, bool unlock)
608 {
609 	int ret;
610 	u8 buf[2];
611 
612 	if (unlock) {
613 		buf[0] = MXT_UNLOCK_CMD_LSB;
614 		buf[1] = MXT_UNLOCK_CMD_MSB;
615 	} else {
616 		buf[0] = 0x01;
617 		buf[1] = 0x01;
618 	}
619 
620 	ret = mxt_bootloader_write(data, buf, 2);
621 	if (ret)
622 		return ret;
623 
624 	return 0;
625 }
626 
627 static int __mxt_read_reg(struct i2c_client *client,
628 			       u16 reg, u16 len, void *val)
629 {
630 	struct i2c_msg xfer[2];
631 	u8 buf[2];
632 	int ret;
633 
634 	buf[0] = reg & 0xff;
635 	buf[1] = (reg >> 8) & 0xff;
636 
637 	/* Write register */
638 	xfer[0].addr = client->addr;
639 	xfer[0].flags = 0;
640 	xfer[0].len = 2;
641 	xfer[0].buf = buf;
642 
643 	/* Read data */
644 	xfer[1].addr = client->addr;
645 	xfer[1].flags = I2C_M_RD;
646 	xfer[1].len = len;
647 	xfer[1].buf = val;
648 
649 	ret = i2c_transfer(client->adapter, xfer, 2);
650 	if (ret == 2) {
651 		ret = 0;
652 	} else {
653 		if (ret >= 0)
654 			ret = -EIO;
655 		dev_err(&client->dev, "%s: i2c transfer failed (%d)\n",
656 			__func__, ret);
657 	}
658 
659 	return ret;
660 }
661 
662 static int __mxt_write_reg(struct i2c_client *client, u16 reg, u16 len,
663 			   const void *val)
664 {
665 	u8 *buf;
666 	size_t count;
667 	int ret;
668 
669 	count = len + 2;
670 	buf = kmalloc(count, GFP_KERNEL);
671 	if (!buf)
672 		return -ENOMEM;
673 
674 	buf[0] = reg & 0xff;
675 	buf[1] = (reg >> 8) & 0xff;
676 	memcpy(&buf[2], val, len);
677 
678 	ret = i2c_master_send(client, buf, count);
679 	if (ret == count) {
680 		ret = 0;
681 	} else {
682 		if (ret >= 0)
683 			ret = -EIO;
684 		dev_err(&client->dev, "%s: i2c send failed (%d)\n",
685 			__func__, ret);
686 	}
687 
688 	kfree(buf);
689 	return ret;
690 }
691 
692 static int mxt_write_reg(struct i2c_client *client, u16 reg, u8 val)
693 {
694 	return __mxt_write_reg(client, reg, 1, &val);
695 }
696 
697 static struct mxt_object *
698 mxt_get_object(struct mxt_data *data, u8 type)
699 {
700 	struct mxt_object *object;
701 	int i;
702 
703 	for (i = 0; i < data->info->object_num; i++) {
704 		object = data->object_table + i;
705 		if (object->type == type)
706 			return object;
707 	}
708 
709 	dev_warn(&data->client->dev, "Invalid object type T%u\n", type);
710 	return NULL;
711 }
712 
713 static void mxt_proc_t6_messages(struct mxt_data *data, u8 *msg)
714 {
715 	struct device *dev = &data->client->dev;
716 	u8 status = msg[1];
717 	u32 crc = msg[2] | (msg[3] << 8) | (msg[4] << 16);
718 
719 	if (crc != data->config_crc) {
720 		data->config_crc = crc;
721 		dev_dbg(dev, "T6 Config Checksum: 0x%06X\n", crc);
722 	}
723 
724 	complete(&data->crc_completion);
725 
726 	/* Detect reset */
727 	if (status & MXT_T6_STATUS_RESET)
728 		complete(&data->reset_completion);
729 
730 	/* Output debug if status has changed */
731 	if (status != data->t6_status)
732 		dev_dbg(dev, "T6 Status 0x%02X%s%s%s%s%s%s%s\n",
733 			status,
734 			status == 0 ? " OK" : "",
735 			status & MXT_T6_STATUS_RESET ? " RESET" : "",
736 			status & MXT_T6_STATUS_OFL ? " OFL" : "",
737 			status & MXT_T6_STATUS_SIGERR ? " SIGERR" : "",
738 			status & MXT_T6_STATUS_CAL ? " CAL" : "",
739 			status & MXT_T6_STATUS_CFGERR ? " CFGERR" : "",
740 			status & MXT_T6_STATUS_COMSERR ? " COMSERR" : "");
741 
742 	/* Save current status */
743 	data->t6_status = status;
744 }
745 
746 static int mxt_write_object(struct mxt_data *data,
747 				 u8 type, u8 offset, u8 val)
748 {
749 	struct mxt_object *object;
750 	u16 reg;
751 
752 	object = mxt_get_object(data, type);
753 	if (!object || offset >= mxt_obj_size(object))
754 		return -EINVAL;
755 
756 	reg = object->start_address;
757 	return mxt_write_reg(data->client, reg + offset, val);
758 }
759 
760 static void mxt_input_button(struct mxt_data *data, u8 *message)
761 {
762 	struct input_dev *input = data->input_dev;
763 	int i;
764 
765 	for (i = 0; i < data->t19_num_keys; i++) {
766 		if (data->t19_keymap[i] == KEY_RESERVED)
767 			continue;
768 
769 		/* Active-low switch */
770 		input_report_key(input, data->t19_keymap[i],
771 				 !(message[1] & BIT(i)));
772 	}
773 }
774 
775 static void mxt_input_sync(struct mxt_data *data)
776 {
777 	input_mt_report_pointer_emulation(data->input_dev,
778 					  data->t19_num_keys);
779 	input_sync(data->input_dev);
780 }
781 
782 static void mxt_proc_t9_message(struct mxt_data *data, u8 *message)
783 {
784 	struct device *dev = &data->client->dev;
785 	struct input_dev *input_dev = data->input_dev;
786 	int id;
787 	u8 status;
788 	int x;
789 	int y;
790 	int area;
791 	int amplitude;
792 
793 	id = message[0] - data->T9_reportid_min;
794 	status = message[1];
795 	x = (message[2] << 4) | ((message[4] >> 4) & 0xf);
796 	y = (message[3] << 4) | ((message[4] & 0xf));
797 
798 	/* Handle 10/12 bit switching */
799 	if (data->max_x < 1024)
800 		x >>= 2;
801 	if (data->max_y < 1024)
802 		y >>= 2;
803 
804 	area = message[5];
805 	amplitude = message[6];
806 
807 	dev_dbg(dev,
808 		"[%u] %c%c%c%c%c%c%c%c x: %5u y: %5u area: %3u amp: %3u\n",
809 		id,
810 		(status & MXT_T9_DETECT) ? 'D' : '.',
811 		(status & MXT_T9_PRESS) ? 'P' : '.',
812 		(status & MXT_T9_RELEASE) ? 'R' : '.',
813 		(status & MXT_T9_MOVE) ? 'M' : '.',
814 		(status & MXT_T9_VECTOR) ? 'V' : '.',
815 		(status & MXT_T9_AMP) ? 'A' : '.',
816 		(status & MXT_T9_SUPPRESS) ? 'S' : '.',
817 		(status & MXT_T9_UNGRIP) ? 'U' : '.',
818 		x, y, area, amplitude);
819 
820 	input_mt_slot(input_dev, id);
821 
822 	if (status & MXT_T9_DETECT) {
823 		/*
824 		 * Multiple bits may be set if the host is slow to read
825 		 * the status messages, indicating all the events that
826 		 * have happened.
827 		 */
828 		if (status & MXT_T9_RELEASE) {
829 			input_mt_report_slot_inactive(input_dev);
830 			mxt_input_sync(data);
831 		}
832 
833 		/* if active, pressure must be non-zero */
834 		if (!amplitude)
835 			amplitude = MXT_PRESSURE_DEFAULT;
836 
837 		/* Touch active */
838 		input_mt_report_slot_state(input_dev, MT_TOOL_FINGER, 1);
839 		input_report_abs(input_dev, ABS_MT_POSITION_X, x);
840 		input_report_abs(input_dev, ABS_MT_POSITION_Y, y);
841 		input_report_abs(input_dev, ABS_MT_PRESSURE, amplitude);
842 		input_report_abs(input_dev, ABS_MT_TOUCH_MAJOR, area);
843 	} else {
844 		/* Touch no longer active, close out slot */
845 		input_mt_report_slot_inactive(input_dev);
846 	}
847 
848 	data->update_input = true;
849 }
850 
851 static void mxt_proc_t100_message(struct mxt_data *data, u8 *message)
852 {
853 	struct device *dev = &data->client->dev;
854 	struct input_dev *input_dev = data->input_dev;
855 	int id;
856 	u8 status;
857 	u8 type = 0;
858 	u16 x;
859 	u16 y;
860 	int distance = 0;
861 	int tool = 0;
862 	u8 major = 0;
863 	u8 pressure = 0;
864 	u8 orientation = 0;
865 
866 	id = message[0] - data->T100_reportid_min - 2;
867 
868 	/* ignore SCRSTATUS events */
869 	if (id < 0)
870 		return;
871 
872 	status = message[1];
873 	x = get_unaligned_le16(&message[2]);
874 	y = get_unaligned_le16(&message[4]);
875 
876 	if (status & MXT_T100_DETECT) {
877 		type = (status & MXT_T100_TYPE_MASK) >> 4;
878 
879 		switch (type) {
880 		case MXT_T100_TYPE_HOVERING_FINGER:
881 			tool = MT_TOOL_FINGER;
882 			distance = MXT_DISTANCE_HOVERING;
883 
884 			if (data->t100_aux_vect)
885 				orientation = message[data->t100_aux_vect];
886 
887 			break;
888 
889 		case MXT_T100_TYPE_FINGER:
890 		case MXT_T100_TYPE_GLOVE:
891 			tool = MT_TOOL_FINGER;
892 			distance = MXT_DISTANCE_ACTIVE_TOUCH;
893 
894 			if (data->t100_aux_area)
895 				major = message[data->t100_aux_area];
896 
897 			if (data->t100_aux_ampl)
898 				pressure = message[data->t100_aux_ampl];
899 
900 			if (data->t100_aux_vect)
901 				orientation = message[data->t100_aux_vect];
902 
903 			break;
904 
905 		case MXT_T100_TYPE_PASSIVE_STYLUS:
906 			tool = MT_TOOL_PEN;
907 
908 			/*
909 			 * Passive stylus is reported with size zero so
910 			 * hardcode.
911 			 */
912 			major = MXT_TOUCH_MAJOR_DEFAULT;
913 
914 			if (data->t100_aux_ampl)
915 				pressure = message[data->t100_aux_ampl];
916 
917 			break;
918 
919 		case MXT_T100_TYPE_LARGE_TOUCH:
920 			/* Ignore suppressed touch */
921 			break;
922 
923 		default:
924 			dev_dbg(dev, "Unexpected T100 type\n");
925 			return;
926 		}
927 	}
928 
929 	/*
930 	 * Values reported should be non-zero if tool is touching the
931 	 * device
932 	 */
933 	if (!pressure && type != MXT_T100_TYPE_HOVERING_FINGER)
934 		pressure = MXT_PRESSURE_DEFAULT;
935 
936 	input_mt_slot(input_dev, id);
937 
938 	if (status & MXT_T100_DETECT) {
939 		dev_dbg(dev, "[%u] type:%u x:%u y:%u a:%02X p:%02X v:%02X\n",
940 			id, type, x, y, major, pressure, orientation);
941 
942 		input_mt_report_slot_state(input_dev, tool, 1);
943 		input_report_abs(input_dev, ABS_MT_POSITION_X, x);
944 		input_report_abs(input_dev, ABS_MT_POSITION_Y, y);
945 		input_report_abs(input_dev, ABS_MT_TOUCH_MAJOR, major);
946 		input_report_abs(input_dev, ABS_MT_PRESSURE, pressure);
947 		input_report_abs(input_dev, ABS_MT_DISTANCE, distance);
948 		input_report_abs(input_dev, ABS_MT_ORIENTATION, orientation);
949 	} else {
950 		dev_dbg(dev, "[%u] release\n", id);
951 
952 		/* close out slot */
953 		input_mt_report_slot_inactive(input_dev);
954 	}
955 
956 	data->update_input = true;
957 }
958 
959 static int mxt_proc_message(struct mxt_data *data, u8 *message)
960 {
961 	u8 report_id = message[0];
962 
963 	if (report_id == MXT_RPTID_NOMSG)
964 		return 0;
965 
966 	if (report_id == data->T6_reportid) {
967 		mxt_proc_t6_messages(data, message);
968 	} else if (!data->input_dev) {
969 		/*
970 		 * Do not report events if input device
971 		 * is not yet registered.
972 		 */
973 		mxt_dump_message(data, message);
974 	} else if (report_id >= data->T9_reportid_min &&
975 		   report_id <= data->T9_reportid_max) {
976 		mxt_proc_t9_message(data, message);
977 	} else if (report_id >= data->T100_reportid_min &&
978 		   report_id <= data->T100_reportid_max) {
979 		mxt_proc_t100_message(data, message);
980 	} else if (report_id == data->T19_reportid) {
981 		mxt_input_button(data, message);
982 		data->update_input = true;
983 	} else {
984 		mxt_dump_message(data, message);
985 	}
986 
987 	return 1;
988 }
989 
990 static int mxt_read_and_process_messages(struct mxt_data *data, u8 count)
991 {
992 	struct device *dev = &data->client->dev;
993 	int ret;
994 	int i;
995 	u8 num_valid = 0;
996 
997 	/* Safety check for msg_buf */
998 	if (count > data->max_reportid)
999 		return -EINVAL;
1000 
1001 	/* Process remaining messages if necessary */
1002 	ret = __mxt_read_reg(data->client, data->T5_address,
1003 				data->T5_msg_size * count, data->msg_buf);
1004 	if (ret) {
1005 		dev_err(dev, "Failed to read %u messages (%d)\n", count, ret);
1006 		return ret;
1007 	}
1008 
1009 	for (i = 0;  i < count; i++) {
1010 		ret = mxt_proc_message(data,
1011 			data->msg_buf + data->T5_msg_size * i);
1012 
1013 		if (ret == 1)
1014 			num_valid++;
1015 	}
1016 
1017 	/* return number of messages read */
1018 	return num_valid;
1019 }
1020 
1021 static irqreturn_t mxt_process_messages_t44(struct mxt_data *data)
1022 {
1023 	struct device *dev = &data->client->dev;
1024 	int ret;
1025 	u8 count, num_left;
1026 
1027 	/* Read T44 and T5 together */
1028 	ret = __mxt_read_reg(data->client, data->T44_address,
1029 		data->T5_msg_size + 1, data->msg_buf);
1030 	if (ret) {
1031 		dev_err(dev, "Failed to read T44 and T5 (%d)\n", ret);
1032 		return IRQ_NONE;
1033 	}
1034 
1035 	count = data->msg_buf[0];
1036 
1037 	/*
1038 	 * This condition may be caused by the CHG line being configured in
1039 	 * Mode 0. It results in unnecessary I2C operations but it is benign.
1040 	 */
1041 	if (count == 0)
1042 		return IRQ_NONE;
1043 
1044 	if (count > data->max_reportid) {
1045 		dev_warn(dev, "T44 count %d exceeded max report id\n", count);
1046 		count = data->max_reportid;
1047 	}
1048 
1049 	/* Process first message */
1050 	ret = mxt_proc_message(data, data->msg_buf + 1);
1051 	if (ret < 0) {
1052 		dev_warn(dev, "Unexpected invalid message\n");
1053 		return IRQ_NONE;
1054 	}
1055 
1056 	num_left = count - 1;
1057 
1058 	/* Process remaining messages if necessary */
1059 	if (num_left) {
1060 		ret = mxt_read_and_process_messages(data, num_left);
1061 		if (ret < 0)
1062 			goto end;
1063 		else if (ret != num_left)
1064 			dev_warn(dev, "Unexpected invalid message\n");
1065 	}
1066 
1067 end:
1068 	if (data->update_input) {
1069 		mxt_input_sync(data);
1070 		data->update_input = false;
1071 	}
1072 
1073 	return IRQ_HANDLED;
1074 }
1075 
1076 static int mxt_process_messages_until_invalid(struct mxt_data *data)
1077 {
1078 	struct device *dev = &data->client->dev;
1079 	int count, read;
1080 	u8 tries = 2;
1081 
1082 	count = data->max_reportid;
1083 
1084 	/* Read messages until we force an invalid */
1085 	do {
1086 		read = mxt_read_and_process_messages(data, count);
1087 		if (read < count)
1088 			return 0;
1089 	} while (--tries);
1090 
1091 	if (data->update_input) {
1092 		mxt_input_sync(data);
1093 		data->update_input = false;
1094 	}
1095 
1096 	dev_err(dev, "CHG pin isn't cleared\n");
1097 	return -EBUSY;
1098 }
1099 
1100 static irqreturn_t mxt_process_messages(struct mxt_data *data)
1101 {
1102 	int total_handled, num_handled;
1103 	u8 count = data->last_message_count;
1104 
1105 	if (count < 1 || count > data->max_reportid)
1106 		count = 1;
1107 
1108 	/* include final invalid message */
1109 	total_handled = mxt_read_and_process_messages(data, count + 1);
1110 	if (total_handled < 0)
1111 		return IRQ_NONE;
1112 	/* if there were invalid messages, then we are done */
1113 	else if (total_handled <= count)
1114 		goto update_count;
1115 
1116 	/* keep reading two msgs until one is invalid or reportid limit */
1117 	do {
1118 		num_handled = mxt_read_and_process_messages(data, 2);
1119 		if (num_handled < 0)
1120 			return IRQ_NONE;
1121 
1122 		total_handled += num_handled;
1123 
1124 		if (num_handled < 2)
1125 			break;
1126 	} while (total_handled < data->num_touchids);
1127 
1128 update_count:
1129 	data->last_message_count = total_handled;
1130 
1131 	if (data->update_input) {
1132 		mxt_input_sync(data);
1133 		data->update_input = false;
1134 	}
1135 
1136 	return IRQ_HANDLED;
1137 }
1138 
1139 static irqreturn_t mxt_interrupt(int irq, void *dev_id)
1140 {
1141 	struct mxt_data *data = dev_id;
1142 
1143 	if (data->in_bootloader) {
1144 		/* bootloader state transition completion */
1145 		complete(&data->bl_completion);
1146 		return IRQ_HANDLED;
1147 	}
1148 
1149 	if (!data->object_table)
1150 		return IRQ_HANDLED;
1151 
1152 	if (data->T44_address) {
1153 		return mxt_process_messages_t44(data);
1154 	} else {
1155 		return mxt_process_messages(data);
1156 	}
1157 }
1158 
1159 static int mxt_t6_command(struct mxt_data *data, u16 cmd_offset,
1160 			  u8 value, bool wait)
1161 {
1162 	u16 reg;
1163 	u8 command_register;
1164 	int timeout_counter = 0;
1165 	int ret;
1166 
1167 	reg = data->T6_address + cmd_offset;
1168 
1169 	ret = mxt_write_reg(data->client, reg, value);
1170 	if (ret)
1171 		return ret;
1172 
1173 	if (!wait)
1174 		return 0;
1175 
1176 	do {
1177 		msleep(20);
1178 		ret = __mxt_read_reg(data->client, reg, 1, &command_register);
1179 		if (ret)
1180 			return ret;
1181 	} while (command_register != 0 && timeout_counter++ <= 100);
1182 
1183 	if (timeout_counter > 100) {
1184 		dev_err(&data->client->dev, "Command failed!\n");
1185 		return -EIO;
1186 	}
1187 
1188 	return 0;
1189 }
1190 
1191 static int mxt_acquire_irq(struct mxt_data *data)
1192 {
1193 	int error;
1194 
1195 	enable_irq(data->irq);
1196 
1197 	if (data->use_retrigen_workaround) {
1198 		error = mxt_process_messages_until_invalid(data);
1199 		if (error)
1200 			return error;
1201 	}
1202 
1203 	return 0;
1204 }
1205 
1206 static int mxt_soft_reset(struct mxt_data *data)
1207 {
1208 	struct device *dev = &data->client->dev;
1209 	int ret = 0;
1210 
1211 	dev_info(dev, "Resetting device\n");
1212 
1213 	disable_irq(data->irq);
1214 
1215 	reinit_completion(&data->reset_completion);
1216 
1217 	ret = mxt_t6_command(data, MXT_COMMAND_RESET, MXT_RESET_VALUE, false);
1218 	if (ret)
1219 		return ret;
1220 
1221 	/* Ignore CHG line for 100ms after reset */
1222 	msleep(MXT_RESET_INVALID_CHG);
1223 
1224 	mxt_acquire_irq(data);
1225 
1226 	ret = mxt_wait_for_completion(data, &data->reset_completion,
1227 				      MXT_RESET_TIMEOUT);
1228 	if (ret)
1229 		return ret;
1230 
1231 	return 0;
1232 }
1233 
1234 static void mxt_update_crc(struct mxt_data *data, u8 cmd, u8 value)
1235 {
1236 	/*
1237 	 * On failure, CRC is set to 0 and config will always be
1238 	 * downloaded.
1239 	 */
1240 	data->config_crc = 0;
1241 	reinit_completion(&data->crc_completion);
1242 
1243 	mxt_t6_command(data, cmd, value, true);
1244 
1245 	/*
1246 	 * Wait for crc message. On failure, CRC is set to 0 and config will
1247 	 * always be downloaded.
1248 	 */
1249 	mxt_wait_for_completion(data, &data->crc_completion, MXT_CRC_TIMEOUT);
1250 }
1251 
1252 static void mxt_calc_crc24(u32 *crc, u8 firstbyte, u8 secondbyte)
1253 {
1254 	static const unsigned int crcpoly = 0x80001B;
1255 	u32 result;
1256 	u32 data_word;
1257 
1258 	data_word = (secondbyte << 8) | firstbyte;
1259 	result = ((*crc << 1) ^ data_word);
1260 
1261 	if (result & 0x1000000)
1262 		result ^= crcpoly;
1263 
1264 	*crc = result;
1265 }
1266 
1267 static u32 mxt_calculate_crc(u8 *base, off_t start_off, off_t end_off)
1268 {
1269 	u32 crc = 0;
1270 	u8 *ptr = base + start_off;
1271 	u8 *last_val = base + end_off - 1;
1272 
1273 	if (end_off < start_off)
1274 		return -EINVAL;
1275 
1276 	while (ptr < last_val) {
1277 		mxt_calc_crc24(&crc, *ptr, *(ptr + 1));
1278 		ptr += 2;
1279 	}
1280 
1281 	/* if len is odd, fill the last byte with 0 */
1282 	if (ptr == last_val)
1283 		mxt_calc_crc24(&crc, *ptr, 0);
1284 
1285 	/* Mask to 24-bit */
1286 	crc &= 0x00FFFFFF;
1287 
1288 	return crc;
1289 }
1290 
1291 static int mxt_check_retrigen(struct mxt_data *data)
1292 {
1293 	struct i2c_client *client = data->client;
1294 	int error;
1295 	int val;
1296 	struct irq_data *irqd;
1297 
1298 	data->use_retrigen_workaround = false;
1299 
1300 	irqd = irq_get_irq_data(data->irq);
1301 	if (!irqd)
1302 		return -EINVAL;
1303 
1304 	if (irqd_is_level_type(irqd))
1305 		return 0;
1306 
1307 	if (data->T18_address) {
1308 		error = __mxt_read_reg(client,
1309 				       data->T18_address + MXT_COMMS_CTRL,
1310 				       1, &val);
1311 		if (error)
1312 			return error;
1313 
1314 		if (val & MXT_COMMS_RETRIGEN)
1315 			return 0;
1316 	}
1317 
1318 	dev_warn(&client->dev, "Enabling RETRIGEN workaround\n");
1319 	data->use_retrigen_workaround = true;
1320 	return 0;
1321 }
1322 
1323 static int mxt_prepare_cfg_mem(struct mxt_data *data, struct mxt_cfg *cfg)
1324 {
1325 	struct device *dev = &data->client->dev;
1326 	struct mxt_object *object;
1327 	unsigned int type, instance, size, byte_offset;
1328 	int offset;
1329 	int ret;
1330 	int i;
1331 	u16 reg;
1332 	u8 val;
1333 
1334 	while (cfg->raw_pos < cfg->raw_size) {
1335 		/* Read type, instance, length */
1336 		ret = sscanf(cfg->raw + cfg->raw_pos, "%x %x %x%n",
1337 			     &type, &instance, &size, &offset);
1338 		if (ret == 0) {
1339 			/* EOF */
1340 			break;
1341 		} else if (ret != 3) {
1342 			dev_err(dev, "Bad format: failed to parse object\n");
1343 			return -EINVAL;
1344 		}
1345 		cfg->raw_pos += offset;
1346 
1347 		object = mxt_get_object(data, type);
1348 		if (!object) {
1349 			/* Skip object */
1350 			for (i = 0; i < size; i++) {
1351 				ret = sscanf(cfg->raw + cfg->raw_pos, "%hhx%n",
1352 					     &val, &offset);
1353 				if (ret != 1) {
1354 					dev_err(dev, "Bad format in T%d at %d\n",
1355 						type, i);
1356 					return -EINVAL;
1357 				}
1358 				cfg->raw_pos += offset;
1359 			}
1360 			continue;
1361 		}
1362 
1363 		if (size > mxt_obj_size(object)) {
1364 			/*
1365 			 * Either we are in fallback mode due to wrong
1366 			 * config or config from a later fw version,
1367 			 * or the file is corrupt or hand-edited.
1368 			 */
1369 			dev_warn(dev, "Discarding %zu byte(s) in T%u\n",
1370 				 size - mxt_obj_size(object), type);
1371 		} else if (mxt_obj_size(object) > size) {
1372 			/*
1373 			 * If firmware is upgraded, new bytes may be added to
1374 			 * end of objects. It is generally forward compatible
1375 			 * to zero these bytes - previous behaviour will be
1376 			 * retained. However this does invalidate the CRC and
1377 			 * will force fallback mode until the configuration is
1378 			 * updated. We warn here but do nothing else - the
1379 			 * malloc has zeroed the entire configuration.
1380 			 */
1381 			dev_warn(dev, "Zeroing %zu byte(s) in T%d\n",
1382 				 mxt_obj_size(object) - size, type);
1383 		}
1384 
1385 		if (instance >= mxt_obj_instances(object)) {
1386 			dev_err(dev, "Object instances exceeded!\n");
1387 			return -EINVAL;
1388 		}
1389 
1390 		reg = object->start_address + mxt_obj_size(object) * instance;
1391 
1392 		for (i = 0; i < size; i++) {
1393 			ret = sscanf(cfg->raw + cfg->raw_pos, "%hhx%n",
1394 				     &val,
1395 				     &offset);
1396 			if (ret != 1) {
1397 				dev_err(dev, "Bad format in T%d at %d\n",
1398 					type, i);
1399 				return -EINVAL;
1400 			}
1401 			cfg->raw_pos += offset;
1402 
1403 			if (i > mxt_obj_size(object))
1404 				continue;
1405 
1406 			byte_offset = reg + i - cfg->start_ofs;
1407 
1408 			if (byte_offset >= 0 && byte_offset < cfg->mem_size) {
1409 				*(cfg->mem + byte_offset) = val;
1410 			} else {
1411 				dev_err(dev, "Bad object: reg:%d, T%d, ofs=%d\n",
1412 					reg, object->type, byte_offset);
1413 				return -EINVAL;
1414 			}
1415 		}
1416 	}
1417 
1418 	return 0;
1419 }
1420 
1421 static int mxt_upload_cfg_mem(struct mxt_data *data, struct mxt_cfg *cfg)
1422 {
1423 	unsigned int byte_offset = 0;
1424 	int error;
1425 
1426 	/* Write configuration as blocks */
1427 	while (byte_offset < cfg->mem_size) {
1428 		unsigned int size = cfg->mem_size - byte_offset;
1429 
1430 		if (size > MXT_MAX_BLOCK_WRITE)
1431 			size = MXT_MAX_BLOCK_WRITE;
1432 
1433 		error = __mxt_write_reg(data->client,
1434 					cfg->start_ofs + byte_offset,
1435 					size, cfg->mem + byte_offset);
1436 		if (error) {
1437 			dev_err(&data->client->dev,
1438 				"Config write error, ret=%d\n", error);
1439 			return error;
1440 		}
1441 
1442 		byte_offset += size;
1443 	}
1444 
1445 	return 0;
1446 }
1447 
1448 static int mxt_init_t7_power_cfg(struct mxt_data *data);
1449 
1450 /*
1451  * mxt_update_cfg - download configuration to chip
1452  *
1453  * Atmel Raw Config File Format
1454  *
1455  * The first four lines of the raw config file contain:
1456  *  1) Version
1457  *  2) Chip ID Information (first 7 bytes of device memory)
1458  *  3) Chip Information Block 24-bit CRC Checksum
1459  *  4) Chip Configuration 24-bit CRC Checksum
1460  *
1461  * The rest of the file consists of one line per object instance:
1462  *   <TYPE> <INSTANCE> <SIZE> <CONTENTS>
1463  *
1464  *   <TYPE> - 2-byte object type as hex
1465  *   <INSTANCE> - 2-byte object instance number as hex
1466  *   <SIZE> - 2-byte object size as hex
1467  *   <CONTENTS> - array of <SIZE> 1-byte hex values
1468  */
1469 static int mxt_update_cfg(struct mxt_data *data, const struct firmware *fw)
1470 {
1471 	struct device *dev = &data->client->dev;
1472 	struct mxt_cfg cfg;
1473 	int ret;
1474 	int offset;
1475 	int i;
1476 	u32 info_crc, config_crc, calculated_crc;
1477 	u16 crc_start = 0;
1478 
1479 	/* Make zero terminated copy of the OBP_RAW file */
1480 	cfg.raw = kmemdup_nul(fw->data, fw->size, GFP_KERNEL);
1481 	if (!cfg.raw)
1482 		return -ENOMEM;
1483 
1484 	cfg.raw_size = fw->size;
1485 
1486 	mxt_update_crc(data, MXT_COMMAND_REPORTALL, 1);
1487 
1488 	if (strncmp(cfg.raw, MXT_CFG_MAGIC, strlen(MXT_CFG_MAGIC))) {
1489 		dev_err(dev, "Unrecognised config file\n");
1490 		ret = -EINVAL;
1491 		goto release_raw;
1492 	}
1493 
1494 	cfg.raw_pos = strlen(MXT_CFG_MAGIC);
1495 
1496 	/* Load information block and check */
1497 	for (i = 0; i < sizeof(struct mxt_info); i++) {
1498 		ret = sscanf(cfg.raw + cfg.raw_pos, "%hhx%n",
1499 			     (unsigned char *)&cfg.info + i,
1500 			     &offset);
1501 		if (ret != 1) {
1502 			dev_err(dev, "Bad format\n");
1503 			ret = -EINVAL;
1504 			goto release_raw;
1505 		}
1506 
1507 		cfg.raw_pos += offset;
1508 	}
1509 
1510 	if (cfg.info.family_id != data->info->family_id) {
1511 		dev_err(dev, "Family ID mismatch!\n");
1512 		ret = -EINVAL;
1513 		goto release_raw;
1514 	}
1515 
1516 	if (cfg.info.variant_id != data->info->variant_id) {
1517 		dev_err(dev, "Variant ID mismatch!\n");
1518 		ret = -EINVAL;
1519 		goto release_raw;
1520 	}
1521 
1522 	/* Read CRCs */
1523 	ret = sscanf(cfg.raw + cfg.raw_pos, "%x%n", &info_crc, &offset);
1524 	if (ret != 1) {
1525 		dev_err(dev, "Bad format: failed to parse Info CRC\n");
1526 		ret = -EINVAL;
1527 		goto release_raw;
1528 	}
1529 	cfg.raw_pos += offset;
1530 
1531 	ret = sscanf(cfg.raw + cfg.raw_pos, "%x%n", &config_crc, &offset);
1532 	if (ret != 1) {
1533 		dev_err(dev, "Bad format: failed to parse Config CRC\n");
1534 		ret = -EINVAL;
1535 		goto release_raw;
1536 	}
1537 	cfg.raw_pos += offset;
1538 
1539 	/*
1540 	 * The Info Block CRC is calculated over mxt_info and the object
1541 	 * table. If it does not match then we are trying to load the
1542 	 * configuration from a different chip or firmware version, so
1543 	 * the configuration CRC is invalid anyway.
1544 	 */
1545 	if (info_crc == data->info_crc) {
1546 		if (config_crc == 0 || data->config_crc == 0) {
1547 			dev_info(dev, "CRC zero, attempting to apply config\n");
1548 		} else if (config_crc == data->config_crc) {
1549 			dev_dbg(dev, "Config CRC 0x%06X: OK\n",
1550 				 data->config_crc);
1551 			ret = 0;
1552 			goto release_raw;
1553 		} else {
1554 			dev_info(dev, "Config CRC 0x%06X: does not match file 0x%06X\n",
1555 				 data->config_crc, config_crc);
1556 		}
1557 	} else {
1558 		dev_warn(dev,
1559 			 "Warning: Info CRC error - device=0x%06X file=0x%06X\n",
1560 			 data->info_crc, info_crc);
1561 	}
1562 
1563 	/* Malloc memory to store configuration */
1564 	cfg.start_ofs = MXT_OBJECT_START +
1565 			data->info->object_num * sizeof(struct mxt_object) +
1566 			MXT_INFO_CHECKSUM_SIZE;
1567 	cfg.mem_size = data->mem_size - cfg.start_ofs;
1568 	cfg.mem = kzalloc(cfg.mem_size, GFP_KERNEL);
1569 	if (!cfg.mem) {
1570 		ret = -ENOMEM;
1571 		goto release_raw;
1572 	}
1573 
1574 	ret = mxt_prepare_cfg_mem(data, &cfg);
1575 	if (ret)
1576 		goto release_mem;
1577 
1578 	/* Calculate crc of the received configs (not the raw config file) */
1579 	if (data->T71_address)
1580 		crc_start = data->T71_address;
1581 	else if (data->T7_address)
1582 		crc_start = data->T7_address;
1583 	else
1584 		dev_warn(dev, "Could not find CRC start\n");
1585 
1586 	if (crc_start > cfg.start_ofs) {
1587 		calculated_crc = mxt_calculate_crc(cfg.mem,
1588 						   crc_start - cfg.start_ofs,
1589 						   cfg.mem_size);
1590 
1591 		if (config_crc > 0 && config_crc != calculated_crc)
1592 			dev_warn(dev, "Config CRC in file inconsistent, calculated=%06X, file=%06X\n",
1593 				 calculated_crc, config_crc);
1594 	}
1595 
1596 	ret = mxt_upload_cfg_mem(data, &cfg);
1597 	if (ret)
1598 		goto release_mem;
1599 
1600 	mxt_update_crc(data, MXT_COMMAND_BACKUPNV, MXT_BACKUP_VALUE);
1601 
1602 	ret = mxt_check_retrigen(data);
1603 	if (ret)
1604 		goto release_mem;
1605 
1606 	ret = mxt_soft_reset(data);
1607 	if (ret)
1608 		goto release_mem;
1609 
1610 	dev_info(dev, "Config successfully updated\n");
1611 
1612 	/* T7 config may have changed */
1613 	mxt_init_t7_power_cfg(data);
1614 
1615 release_mem:
1616 	kfree(cfg.mem);
1617 release_raw:
1618 	kfree(cfg.raw);
1619 	return ret;
1620 }
1621 
1622 static void mxt_free_input_device(struct mxt_data *data)
1623 {
1624 	if (data->input_dev) {
1625 		input_unregister_device(data->input_dev);
1626 		data->input_dev = NULL;
1627 	}
1628 }
1629 
1630 static void mxt_free_object_table(struct mxt_data *data)
1631 {
1632 #ifdef CONFIG_TOUCHSCREEN_ATMEL_MXT_T37
1633 	video_unregister_device(&data->dbg.vdev);
1634 	v4l2_device_unregister(&data->dbg.v4l2);
1635 #endif
1636 	data->object_table = NULL;
1637 	data->info = NULL;
1638 	kfree(data->raw_info_block);
1639 	data->raw_info_block = NULL;
1640 	kfree(data->msg_buf);
1641 	data->msg_buf = NULL;
1642 	data->T5_address = 0;
1643 	data->T5_msg_size = 0;
1644 	data->T6_reportid = 0;
1645 	data->T7_address = 0;
1646 	data->T71_address = 0;
1647 	data->T9_reportid_min = 0;
1648 	data->T9_reportid_max = 0;
1649 	data->T18_address = 0;
1650 	data->T19_reportid = 0;
1651 	data->T44_address = 0;
1652 	data->T100_reportid_min = 0;
1653 	data->T100_reportid_max = 0;
1654 	data->max_reportid = 0;
1655 }
1656 
1657 static int mxt_parse_object_table(struct mxt_data *data,
1658 				  struct mxt_object *object_table)
1659 {
1660 	struct i2c_client *client = data->client;
1661 	int i;
1662 	u8 reportid;
1663 	u16 end_address;
1664 
1665 	/* Valid Report IDs start counting from 1 */
1666 	reportid = 1;
1667 	data->mem_size = 0;
1668 	for (i = 0; i < data->info->object_num; i++) {
1669 		struct mxt_object *object = object_table + i;
1670 		u8 min_id, max_id;
1671 
1672 		le16_to_cpus(&object->start_address);
1673 
1674 		if (object->num_report_ids) {
1675 			min_id = reportid;
1676 			reportid += object->num_report_ids *
1677 					mxt_obj_instances(object);
1678 			max_id = reportid - 1;
1679 		} else {
1680 			min_id = 0;
1681 			max_id = 0;
1682 		}
1683 
1684 		dev_dbg(&data->client->dev,
1685 			"T%u Start:%u Size:%zu Instances:%zu Report IDs:%u-%u\n",
1686 			object->type, object->start_address,
1687 			mxt_obj_size(object), mxt_obj_instances(object),
1688 			min_id, max_id);
1689 
1690 		switch (object->type) {
1691 		case MXT_GEN_MESSAGE_T5:
1692 			if (data->info->family_id == 0x80 &&
1693 			    data->info->version < 0x20) {
1694 				/*
1695 				 * On mXT224 firmware versions prior to V2.0
1696 				 * read and discard unused CRC byte otherwise
1697 				 * DMA reads are misaligned.
1698 				 */
1699 				data->T5_msg_size = mxt_obj_size(object);
1700 			} else {
1701 				/* CRC not enabled, so skip last byte */
1702 				data->T5_msg_size = mxt_obj_size(object) - 1;
1703 			}
1704 			data->T5_address = object->start_address;
1705 			break;
1706 		case MXT_GEN_COMMAND_T6:
1707 			data->T6_reportid = min_id;
1708 			data->T6_address = object->start_address;
1709 			break;
1710 		case MXT_GEN_POWER_T7:
1711 			data->T7_address = object->start_address;
1712 			break;
1713 		case MXT_SPT_DYNAMICCONFIGURATIONCONTAINER_T71:
1714 			data->T71_address = object->start_address;
1715 			break;
1716 		case MXT_TOUCH_MULTI_T9:
1717 			data->multitouch = MXT_TOUCH_MULTI_T9;
1718 			/* Only handle messages from first T9 instance */
1719 			data->T9_reportid_min = min_id;
1720 			data->T9_reportid_max = min_id +
1721 						object->num_report_ids - 1;
1722 			data->num_touchids = object->num_report_ids;
1723 			break;
1724 		case MXT_SPT_COMMSCONFIG_T18:
1725 			data->T18_address = object->start_address;
1726 			break;
1727 		case MXT_SPT_MESSAGECOUNT_T44:
1728 			data->T44_address = object->start_address;
1729 			break;
1730 		case MXT_SPT_GPIOPWM_T19:
1731 			data->T19_reportid = min_id;
1732 			break;
1733 		case MXT_TOUCH_MULTITOUCHSCREEN_T100:
1734 			data->multitouch = MXT_TOUCH_MULTITOUCHSCREEN_T100;
1735 			data->T100_reportid_min = min_id;
1736 			data->T100_reportid_max = max_id;
1737 			/* first two report IDs reserved */
1738 			data->num_touchids = object->num_report_ids - 2;
1739 			break;
1740 		}
1741 
1742 		end_address = object->start_address
1743 			+ mxt_obj_size(object) * mxt_obj_instances(object) - 1;
1744 
1745 		if (end_address >= data->mem_size)
1746 			data->mem_size = end_address + 1;
1747 	}
1748 
1749 	/* Store maximum reportid */
1750 	data->max_reportid = reportid;
1751 
1752 	/* If T44 exists, T5 position has to be directly after */
1753 	if (data->T44_address && (data->T5_address != data->T44_address + 1)) {
1754 		dev_err(&client->dev, "Invalid T44 position\n");
1755 		return -EINVAL;
1756 	}
1757 
1758 	data->msg_buf = kcalloc(data->max_reportid,
1759 				data->T5_msg_size, GFP_KERNEL);
1760 	if (!data->msg_buf)
1761 		return -ENOMEM;
1762 
1763 	return 0;
1764 }
1765 
1766 static int mxt_read_info_block(struct mxt_data *data)
1767 {
1768 	struct i2c_client *client = data->client;
1769 	int error;
1770 	size_t size;
1771 	void *id_buf, *buf;
1772 	uint8_t num_objects;
1773 	u32 calculated_crc;
1774 	u8 *crc_ptr;
1775 
1776 	/* If info block already allocated, free it */
1777 	if (data->raw_info_block)
1778 		mxt_free_object_table(data);
1779 
1780 	/* Read 7-byte ID information block starting at address 0 */
1781 	size = sizeof(struct mxt_info);
1782 	id_buf = kzalloc(size, GFP_KERNEL);
1783 	if (!id_buf)
1784 		return -ENOMEM;
1785 
1786 	error = __mxt_read_reg(client, 0, size, id_buf);
1787 	if (error)
1788 		goto err_free_mem;
1789 
1790 	/* Resize buffer to give space for rest of info block */
1791 	num_objects = ((struct mxt_info *)id_buf)->object_num;
1792 	size += (num_objects * sizeof(struct mxt_object))
1793 		+ MXT_INFO_CHECKSUM_SIZE;
1794 
1795 	buf = krealloc(id_buf, size, GFP_KERNEL);
1796 	if (!buf) {
1797 		error = -ENOMEM;
1798 		goto err_free_mem;
1799 	}
1800 	id_buf = buf;
1801 
1802 	/* Read rest of info block */
1803 	error = __mxt_read_reg(client, MXT_OBJECT_START,
1804 			       size - MXT_OBJECT_START,
1805 			       id_buf + MXT_OBJECT_START);
1806 	if (error)
1807 		goto err_free_mem;
1808 
1809 	/* Extract & calculate checksum */
1810 	crc_ptr = id_buf + size - MXT_INFO_CHECKSUM_SIZE;
1811 	data->info_crc = crc_ptr[0] | (crc_ptr[1] << 8) | (crc_ptr[2] << 16);
1812 
1813 	calculated_crc = mxt_calculate_crc(id_buf, 0,
1814 					   size - MXT_INFO_CHECKSUM_SIZE);
1815 
1816 	/*
1817 	 * CRC mismatch can be caused by data corruption due to I2C comms
1818 	 * issue or else device is not using Object Based Protocol (eg i2c-hid)
1819 	 */
1820 	if ((data->info_crc == 0) || (data->info_crc != calculated_crc)) {
1821 		dev_err(&client->dev,
1822 			"Info Block CRC error calculated=0x%06X read=0x%06X\n",
1823 			calculated_crc, data->info_crc);
1824 		error = -EIO;
1825 		goto err_free_mem;
1826 	}
1827 
1828 	data->raw_info_block = id_buf;
1829 	data->info = (struct mxt_info *)id_buf;
1830 
1831 	dev_info(&client->dev,
1832 		 "Family: %u Variant: %u Firmware V%u.%u.%02X Objects: %u\n",
1833 		 data->info->family_id, data->info->variant_id,
1834 		 data->info->version >> 4, data->info->version & 0xf,
1835 		 data->info->build, data->info->object_num);
1836 
1837 	/* Parse object table information */
1838 	error = mxt_parse_object_table(data, id_buf + MXT_OBJECT_START);
1839 	if (error) {
1840 		dev_err(&client->dev, "Error %d parsing object table\n", error);
1841 		mxt_free_object_table(data);
1842 		goto err_free_mem;
1843 	}
1844 
1845 	data->object_table = (struct mxt_object *)(id_buf + MXT_OBJECT_START);
1846 
1847 	return 0;
1848 
1849 err_free_mem:
1850 	kfree(id_buf);
1851 	return error;
1852 }
1853 
1854 static int mxt_read_t9_resolution(struct mxt_data *data)
1855 {
1856 	struct i2c_client *client = data->client;
1857 	int error;
1858 	struct t9_range range;
1859 	unsigned char orient;
1860 	struct mxt_object *object;
1861 
1862 	object = mxt_get_object(data, MXT_TOUCH_MULTI_T9);
1863 	if (!object)
1864 		return -EINVAL;
1865 
1866 	error = __mxt_read_reg(client,
1867 			       object->start_address + MXT_T9_XSIZE,
1868 			       sizeof(data->xsize), &data->xsize);
1869 	if (error)
1870 		return error;
1871 
1872 	error = __mxt_read_reg(client,
1873 			       object->start_address + MXT_T9_YSIZE,
1874 			       sizeof(data->ysize), &data->ysize);
1875 	if (error)
1876 		return error;
1877 
1878 	error = __mxt_read_reg(client,
1879 			       object->start_address + MXT_T9_RANGE,
1880 			       sizeof(range), &range);
1881 	if (error)
1882 		return error;
1883 
1884 	data->max_x = get_unaligned_le16(&range.x);
1885 	data->max_y = get_unaligned_le16(&range.y);
1886 
1887 	error =  __mxt_read_reg(client,
1888 				object->start_address + MXT_T9_ORIENT,
1889 				1, &orient);
1890 	if (error)
1891 		return error;
1892 
1893 	data->xy_switch = orient & MXT_T9_ORIENT_SWITCH;
1894 	data->invertx = orient & MXT_T9_ORIENT_INVERTX;
1895 	data->inverty = orient & MXT_T9_ORIENT_INVERTY;
1896 
1897 	return 0;
1898 }
1899 
1900 static int mxt_read_t100_config(struct mxt_data *data)
1901 {
1902 	struct i2c_client *client = data->client;
1903 	int error;
1904 	struct mxt_object *object;
1905 	u16 range_x, range_y;
1906 	u8 cfg, tchaux;
1907 	u8 aux;
1908 
1909 	object = mxt_get_object(data, MXT_TOUCH_MULTITOUCHSCREEN_T100);
1910 	if (!object)
1911 		return -EINVAL;
1912 
1913 	/* read touchscreen dimensions */
1914 	error = __mxt_read_reg(client,
1915 			       object->start_address + MXT_T100_XRANGE,
1916 			       sizeof(range_x), &range_x);
1917 	if (error)
1918 		return error;
1919 
1920 	data->max_x = get_unaligned_le16(&range_x);
1921 
1922 	error = __mxt_read_reg(client,
1923 			       object->start_address + MXT_T100_YRANGE,
1924 			       sizeof(range_y), &range_y);
1925 	if (error)
1926 		return error;
1927 
1928 	data->max_y = get_unaligned_le16(&range_y);
1929 
1930 	error = __mxt_read_reg(client,
1931 			       object->start_address + MXT_T100_XSIZE,
1932 			       sizeof(data->xsize), &data->xsize);
1933 	if (error)
1934 		return error;
1935 
1936 	error = __mxt_read_reg(client,
1937 			       object->start_address + MXT_T100_YSIZE,
1938 			       sizeof(data->ysize), &data->ysize);
1939 	if (error)
1940 		return error;
1941 
1942 	/* read orientation config */
1943 	error =  __mxt_read_reg(client,
1944 				object->start_address + MXT_T100_CFG1,
1945 				1, &cfg);
1946 	if (error)
1947 		return error;
1948 
1949 	data->xy_switch = cfg & MXT_T100_CFG_SWITCHXY;
1950 	data->invertx = cfg & MXT_T100_CFG_INVERTX;
1951 	data->inverty = cfg & MXT_T100_CFG_INVERTY;
1952 
1953 	/* allocate aux bytes */
1954 	error =  __mxt_read_reg(client,
1955 				object->start_address + MXT_T100_TCHAUX,
1956 				1, &tchaux);
1957 	if (error)
1958 		return error;
1959 
1960 	aux = 6;
1961 
1962 	if (tchaux & MXT_T100_TCHAUX_VECT)
1963 		data->t100_aux_vect = aux++;
1964 
1965 	if (tchaux & MXT_T100_TCHAUX_AMPL)
1966 		data->t100_aux_ampl = aux++;
1967 
1968 	if (tchaux & MXT_T100_TCHAUX_AREA)
1969 		data->t100_aux_area = aux++;
1970 
1971 	dev_dbg(&client->dev,
1972 		"T100 aux mappings vect:%u ampl:%u area:%u\n",
1973 		data->t100_aux_vect, data->t100_aux_ampl, data->t100_aux_area);
1974 
1975 	return 0;
1976 }
1977 
1978 static int mxt_input_open(struct input_dev *dev);
1979 static void mxt_input_close(struct input_dev *dev);
1980 
1981 static void mxt_set_up_as_touchpad(struct input_dev *input_dev,
1982 				   struct mxt_data *data)
1983 {
1984 	int i;
1985 
1986 	input_dev->name = "Atmel maXTouch Touchpad";
1987 
1988 	__set_bit(INPUT_PROP_BUTTONPAD, input_dev->propbit);
1989 
1990 	input_abs_set_res(input_dev, ABS_X, MXT_PIXELS_PER_MM);
1991 	input_abs_set_res(input_dev, ABS_Y, MXT_PIXELS_PER_MM);
1992 	input_abs_set_res(input_dev, ABS_MT_POSITION_X,
1993 			  MXT_PIXELS_PER_MM);
1994 	input_abs_set_res(input_dev, ABS_MT_POSITION_Y,
1995 			  MXT_PIXELS_PER_MM);
1996 
1997 	for (i = 0; i < data->t19_num_keys; i++)
1998 		if (data->t19_keymap[i] != KEY_RESERVED)
1999 			input_set_capability(input_dev, EV_KEY,
2000 					     data->t19_keymap[i]);
2001 }
2002 
2003 static int mxt_initialize_input_device(struct mxt_data *data)
2004 {
2005 	struct device *dev = &data->client->dev;
2006 	struct input_dev *input_dev;
2007 	int error;
2008 	unsigned int num_mt_slots;
2009 	unsigned int mt_flags = 0;
2010 
2011 	switch (data->multitouch) {
2012 	case MXT_TOUCH_MULTI_T9:
2013 		num_mt_slots = data->T9_reportid_max - data->T9_reportid_min + 1;
2014 		error = mxt_read_t9_resolution(data);
2015 		if (error)
2016 			dev_warn(dev, "Failed to initialize T9 resolution\n");
2017 		break;
2018 
2019 	case MXT_TOUCH_MULTITOUCHSCREEN_T100:
2020 		num_mt_slots = data->num_touchids;
2021 		error = mxt_read_t100_config(data);
2022 		if (error)
2023 			dev_warn(dev, "Failed to read T100 config\n");
2024 		break;
2025 
2026 	default:
2027 		dev_err(dev, "Invalid multitouch object\n");
2028 		return -EINVAL;
2029 	}
2030 
2031 	/* Handle default values and orientation switch */
2032 	if (data->max_x == 0)
2033 		data->max_x = 1023;
2034 
2035 	if (data->max_y == 0)
2036 		data->max_y = 1023;
2037 
2038 	if (data->xy_switch)
2039 		swap(data->max_x, data->max_y);
2040 
2041 	dev_info(dev, "Touchscreen size X%uY%u\n", data->max_x, data->max_y);
2042 
2043 	/* Register input device */
2044 	input_dev = input_allocate_device();
2045 	if (!input_dev)
2046 		return -ENOMEM;
2047 
2048 	input_dev->name = "Atmel maXTouch Touchscreen";
2049 	input_dev->phys = data->phys;
2050 	input_dev->id.bustype = BUS_I2C;
2051 	input_dev->dev.parent = dev;
2052 	input_dev->open = mxt_input_open;
2053 	input_dev->close = mxt_input_close;
2054 
2055 	input_set_capability(input_dev, EV_KEY, BTN_TOUCH);
2056 
2057 	/* For single touch */
2058 	input_set_abs_params(input_dev, ABS_X, 0, data->max_x, 0, 0);
2059 	input_set_abs_params(input_dev, ABS_Y, 0, data->max_y, 0, 0);
2060 
2061 	if (data->multitouch == MXT_TOUCH_MULTI_T9 ||
2062 	    (data->multitouch == MXT_TOUCH_MULTITOUCHSCREEN_T100 &&
2063 	     data->t100_aux_ampl)) {
2064 		input_set_abs_params(input_dev, ABS_PRESSURE, 0, 255, 0, 0);
2065 	}
2066 
2067 	/* If device has buttons we assume it is a touchpad */
2068 	if (data->t19_num_keys) {
2069 		mxt_set_up_as_touchpad(input_dev, data);
2070 		mt_flags |= INPUT_MT_POINTER;
2071 	} else {
2072 		mt_flags |= INPUT_MT_DIRECT;
2073 	}
2074 
2075 	/* For multi touch */
2076 	error = input_mt_init_slots(input_dev, num_mt_slots, mt_flags);
2077 	if (error) {
2078 		dev_err(dev, "Error %d initialising slots\n", error);
2079 		goto err_free_mem;
2080 	}
2081 
2082 	if (data->multitouch == MXT_TOUCH_MULTITOUCHSCREEN_T100) {
2083 		input_set_abs_params(input_dev, ABS_MT_TOOL_TYPE,
2084 				     0, MT_TOOL_MAX, 0, 0);
2085 		input_set_abs_params(input_dev, ABS_MT_DISTANCE,
2086 				     MXT_DISTANCE_ACTIVE_TOUCH,
2087 				     MXT_DISTANCE_HOVERING,
2088 				     0, 0);
2089 	}
2090 
2091 	input_set_abs_params(input_dev, ABS_MT_POSITION_X,
2092 			     0, data->max_x, 0, 0);
2093 	input_set_abs_params(input_dev, ABS_MT_POSITION_Y,
2094 			     0, data->max_y, 0, 0);
2095 
2096 	if (data->multitouch == MXT_TOUCH_MULTI_T9 ||
2097 	    (data->multitouch == MXT_TOUCH_MULTITOUCHSCREEN_T100 &&
2098 	     data->t100_aux_area)) {
2099 		input_set_abs_params(input_dev, ABS_MT_TOUCH_MAJOR,
2100 				     0, MXT_MAX_AREA, 0, 0);
2101 	}
2102 
2103 	if (data->multitouch == MXT_TOUCH_MULTI_T9 ||
2104 	    (data->multitouch == MXT_TOUCH_MULTITOUCHSCREEN_T100 &&
2105 	     data->t100_aux_ampl)) {
2106 		input_set_abs_params(input_dev, ABS_MT_PRESSURE,
2107 				     0, 255, 0, 0);
2108 	}
2109 
2110 	if (data->multitouch == MXT_TOUCH_MULTITOUCHSCREEN_T100 &&
2111 	    data->t100_aux_vect) {
2112 		input_set_abs_params(input_dev, ABS_MT_ORIENTATION,
2113 				     0, 255, 0, 0);
2114 	}
2115 
2116 	if (data->multitouch == MXT_TOUCH_MULTITOUCHSCREEN_T100 &&
2117 	    data->t100_aux_vect) {
2118 		input_set_abs_params(input_dev, ABS_MT_ORIENTATION,
2119 				     0, 255, 0, 0);
2120 	}
2121 
2122 	input_set_drvdata(input_dev, data);
2123 
2124 	error = input_register_device(input_dev);
2125 	if (error) {
2126 		dev_err(dev, "Error %d registering input device\n", error);
2127 		goto err_free_mem;
2128 	}
2129 
2130 	data->input_dev = input_dev;
2131 
2132 	return 0;
2133 
2134 err_free_mem:
2135 	input_free_device(input_dev);
2136 	return error;
2137 }
2138 
2139 static int mxt_configure_objects(struct mxt_data *data,
2140 				 const struct firmware *cfg);
2141 
2142 static void mxt_config_cb(const struct firmware *cfg, void *ctx)
2143 {
2144 	mxt_configure_objects(ctx, cfg);
2145 	release_firmware(cfg);
2146 }
2147 
2148 static int mxt_initialize(struct mxt_data *data)
2149 {
2150 	struct i2c_client *client = data->client;
2151 	int recovery_attempts = 0;
2152 	int error;
2153 
2154 	while (1) {
2155 		error = mxt_read_info_block(data);
2156 		if (!error)
2157 			break;
2158 
2159 		/* Check bootloader state */
2160 		error = mxt_probe_bootloader(data, false);
2161 		if (error) {
2162 			dev_info(&client->dev, "Trying alternate bootloader address\n");
2163 			error = mxt_probe_bootloader(data, true);
2164 			if (error) {
2165 				/* Chip is not in appmode or bootloader mode */
2166 				return error;
2167 			}
2168 		}
2169 
2170 		/* OK, we are in bootloader, see if we can recover */
2171 		if (++recovery_attempts > 1) {
2172 			dev_err(&client->dev, "Could not recover from bootloader mode\n");
2173 			/*
2174 			 * We can reflash from this state, so do not
2175 			 * abort initialization.
2176 			 */
2177 			data->in_bootloader = true;
2178 			return 0;
2179 		}
2180 
2181 		/* Attempt to exit bootloader into app mode */
2182 		mxt_send_bootloader_cmd(data, false);
2183 		msleep(MXT_FW_RESET_TIME);
2184 	}
2185 
2186 	error = mxt_acquire_irq(data);
2187 	if (error)
2188 		return error;
2189 
2190 	error = mxt_check_retrigen(data);
2191 	if (error)
2192 		return error;
2193 
2194 	error = request_firmware_nowait(THIS_MODULE, true, MXT_CFG_NAME,
2195 					&client->dev, GFP_KERNEL, data,
2196 					mxt_config_cb);
2197 	if (error) {
2198 		dev_err(&client->dev, "Failed to invoke firmware loader: %d\n",
2199 			error);
2200 		return error;
2201 	}
2202 
2203 	return 0;
2204 }
2205 
2206 static int mxt_set_t7_power_cfg(struct mxt_data *data, u8 sleep)
2207 {
2208 	struct device *dev = &data->client->dev;
2209 	int error;
2210 	struct t7_config *new_config;
2211 	struct t7_config deepsleep = { .active = 0, .idle = 0 };
2212 
2213 	if (sleep == MXT_POWER_CFG_DEEPSLEEP)
2214 		new_config = &deepsleep;
2215 	else
2216 		new_config = &data->t7_cfg;
2217 
2218 	error = __mxt_write_reg(data->client, data->T7_address,
2219 				sizeof(data->t7_cfg), new_config);
2220 	if (error)
2221 		return error;
2222 
2223 	dev_dbg(dev, "Set T7 ACTV:%d IDLE:%d\n",
2224 		new_config->active, new_config->idle);
2225 
2226 	return 0;
2227 }
2228 
2229 static int mxt_init_t7_power_cfg(struct mxt_data *data)
2230 {
2231 	struct device *dev = &data->client->dev;
2232 	int error;
2233 	bool retry = false;
2234 
2235 recheck:
2236 	error = __mxt_read_reg(data->client, data->T7_address,
2237 				sizeof(data->t7_cfg), &data->t7_cfg);
2238 	if (error)
2239 		return error;
2240 
2241 	if (data->t7_cfg.active == 0 || data->t7_cfg.idle == 0) {
2242 		if (!retry) {
2243 			dev_dbg(dev, "T7 cfg zero, resetting\n");
2244 			mxt_soft_reset(data);
2245 			retry = true;
2246 			goto recheck;
2247 		} else {
2248 			dev_dbg(dev, "T7 cfg zero after reset, overriding\n");
2249 			data->t7_cfg.active = 20;
2250 			data->t7_cfg.idle = 100;
2251 			return mxt_set_t7_power_cfg(data, MXT_POWER_CFG_RUN);
2252 		}
2253 	}
2254 
2255 	dev_dbg(dev, "Initialized power cfg: ACTV %d, IDLE %d\n",
2256 		data->t7_cfg.active, data->t7_cfg.idle);
2257 	return 0;
2258 }
2259 
2260 #ifdef CONFIG_TOUCHSCREEN_ATMEL_MXT_T37
2261 static const struct v4l2_file_operations mxt_video_fops = {
2262 	.owner = THIS_MODULE,
2263 	.open = v4l2_fh_open,
2264 	.release = vb2_fop_release,
2265 	.unlocked_ioctl = video_ioctl2,
2266 	.read = vb2_fop_read,
2267 	.mmap = vb2_fop_mmap,
2268 	.poll = vb2_fop_poll,
2269 };
2270 
2271 static u16 mxt_get_debug_value(struct mxt_data *data, unsigned int x,
2272 			       unsigned int y)
2273 {
2274 	struct mxt_info *info = data->info;
2275 	struct mxt_dbg *dbg = &data->dbg;
2276 	unsigned int ofs, page;
2277 	unsigned int col = 0;
2278 	unsigned int col_width;
2279 
2280 	if (info->family_id == MXT_FAMILY_1386) {
2281 		col_width = info->matrix_ysize / MXT1386_COLUMNS;
2282 		col = y / col_width;
2283 		y = y % col_width;
2284 	} else {
2285 		col_width = info->matrix_ysize;
2286 	}
2287 
2288 	ofs = (y + (x * col_width)) * sizeof(u16);
2289 	page = ofs / MXT_DIAGNOSTIC_SIZE;
2290 	ofs %= MXT_DIAGNOSTIC_SIZE;
2291 
2292 	if (info->family_id == MXT_FAMILY_1386)
2293 		page += col * MXT1386_PAGES_PER_COLUMN;
2294 
2295 	return get_unaligned_le16(&dbg->t37_buf[page].data[ofs]);
2296 }
2297 
2298 static int mxt_convert_debug_pages(struct mxt_data *data, u16 *outbuf)
2299 {
2300 	struct mxt_dbg *dbg = &data->dbg;
2301 	unsigned int x = 0;
2302 	unsigned int y = 0;
2303 	unsigned int i, rx, ry;
2304 
2305 	for (i = 0; i < dbg->t37_nodes; i++) {
2306 		/* Handle orientation */
2307 		rx = data->xy_switch ? y : x;
2308 		ry = data->xy_switch ? x : y;
2309 		rx = data->invertx ? (data->xsize - 1 - rx) : rx;
2310 		ry = data->inverty ? (data->ysize - 1 - ry) : ry;
2311 
2312 		outbuf[i] = mxt_get_debug_value(data, rx, ry);
2313 
2314 		/* Next value */
2315 		if (++x >= (data->xy_switch ? data->ysize : data->xsize)) {
2316 			x = 0;
2317 			y++;
2318 		}
2319 	}
2320 
2321 	return 0;
2322 }
2323 
2324 static int mxt_read_diagnostic_debug(struct mxt_data *data, u8 mode,
2325 				     u16 *outbuf)
2326 {
2327 	struct mxt_dbg *dbg = &data->dbg;
2328 	int retries = 0;
2329 	int page;
2330 	int ret;
2331 	u8 cmd = mode;
2332 	struct t37_debug *p;
2333 	u8 cmd_poll;
2334 
2335 	for (page = 0; page < dbg->t37_pages; page++) {
2336 		p = dbg->t37_buf + page;
2337 
2338 		ret = mxt_write_reg(data->client, dbg->diag_cmd_address,
2339 				    cmd);
2340 		if (ret)
2341 			return ret;
2342 
2343 		retries = 0;
2344 		msleep(20);
2345 wait_cmd:
2346 		/* Read back command byte */
2347 		ret = __mxt_read_reg(data->client, dbg->diag_cmd_address,
2348 				     sizeof(cmd_poll), &cmd_poll);
2349 		if (ret)
2350 			return ret;
2351 
2352 		/* Field is cleared once the command has been processed */
2353 		if (cmd_poll) {
2354 			if (retries++ > 100)
2355 				return -EINVAL;
2356 
2357 			msleep(20);
2358 			goto wait_cmd;
2359 		}
2360 
2361 		/* Read T37 page */
2362 		ret = __mxt_read_reg(data->client, dbg->t37_address,
2363 				     sizeof(struct t37_debug), p);
2364 		if (ret)
2365 			return ret;
2366 
2367 		if (p->mode != mode || p->page != page) {
2368 			dev_err(&data->client->dev, "T37 page mismatch\n");
2369 			return -EINVAL;
2370 		}
2371 
2372 		dev_dbg(&data->client->dev, "%s page:%d retries:%d\n",
2373 			__func__, page, retries);
2374 
2375 		/* For remaining pages, write PAGEUP rather than mode */
2376 		cmd = MXT_DIAGNOSTIC_PAGEUP;
2377 	}
2378 
2379 	return mxt_convert_debug_pages(data, outbuf);
2380 }
2381 
2382 static int mxt_queue_setup(struct vb2_queue *q,
2383 		       unsigned int *nbuffers, unsigned int *nplanes,
2384 		       unsigned int sizes[], struct device *alloc_devs[])
2385 {
2386 	struct mxt_data *data = q->drv_priv;
2387 	size_t size = data->dbg.t37_nodes * sizeof(u16);
2388 
2389 	if (*nplanes)
2390 		return sizes[0] < size ? -EINVAL : 0;
2391 
2392 	*nplanes = 1;
2393 	sizes[0] = size;
2394 
2395 	return 0;
2396 }
2397 
2398 static void mxt_buffer_queue(struct vb2_buffer *vb)
2399 {
2400 	struct mxt_data *data = vb2_get_drv_priv(vb->vb2_queue);
2401 	u16 *ptr;
2402 	int ret;
2403 	u8 mode;
2404 
2405 	ptr = vb2_plane_vaddr(vb, 0);
2406 	if (!ptr) {
2407 		dev_err(&data->client->dev, "Error acquiring frame ptr\n");
2408 		goto fault;
2409 	}
2410 
2411 	switch (data->dbg.input) {
2412 	case MXT_V4L_INPUT_DELTAS:
2413 	default:
2414 		mode = MXT_DIAGNOSTIC_DELTAS;
2415 		break;
2416 
2417 	case MXT_V4L_INPUT_REFS:
2418 		mode = MXT_DIAGNOSTIC_REFS;
2419 		break;
2420 	}
2421 
2422 	ret = mxt_read_diagnostic_debug(data, mode, ptr);
2423 	if (ret)
2424 		goto fault;
2425 
2426 	vb2_set_plane_payload(vb, 0, data->dbg.t37_nodes * sizeof(u16));
2427 	vb2_buffer_done(vb, VB2_BUF_STATE_DONE);
2428 	return;
2429 
2430 fault:
2431 	vb2_buffer_done(vb, VB2_BUF_STATE_ERROR);
2432 }
2433 
2434 /* V4L2 structures */
2435 static const struct vb2_ops mxt_queue_ops = {
2436 	.queue_setup		= mxt_queue_setup,
2437 	.buf_queue		= mxt_buffer_queue,
2438 	.wait_prepare		= vb2_ops_wait_prepare,
2439 	.wait_finish		= vb2_ops_wait_finish,
2440 };
2441 
2442 static const struct vb2_queue mxt_queue = {
2443 	.type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
2444 	.io_modes = VB2_MMAP | VB2_USERPTR | VB2_DMABUF | VB2_READ,
2445 	.buf_struct_size = sizeof(struct mxt_vb2_buffer),
2446 	.ops = &mxt_queue_ops,
2447 	.mem_ops = &vb2_vmalloc_memops,
2448 	.timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC,
2449 	.min_buffers_needed = 1,
2450 };
2451 
2452 static int mxt_vidioc_querycap(struct file *file, void *priv,
2453 				 struct v4l2_capability *cap)
2454 {
2455 	struct mxt_data *data = video_drvdata(file);
2456 
2457 	strlcpy(cap->driver, "atmel_mxt_ts", sizeof(cap->driver));
2458 	strlcpy(cap->card, "atmel_mxt_ts touch", sizeof(cap->card));
2459 	snprintf(cap->bus_info, sizeof(cap->bus_info),
2460 		 "I2C:%s", dev_name(&data->client->dev));
2461 	return 0;
2462 }
2463 
2464 static int mxt_vidioc_enum_input(struct file *file, void *priv,
2465 				   struct v4l2_input *i)
2466 {
2467 	if (i->index >= MXT_V4L_INPUT_MAX)
2468 		return -EINVAL;
2469 
2470 	i->type = V4L2_INPUT_TYPE_TOUCH;
2471 
2472 	switch (i->index) {
2473 	case MXT_V4L_INPUT_REFS:
2474 		strlcpy(i->name, "Mutual Capacitance References",
2475 			sizeof(i->name));
2476 		break;
2477 	case MXT_V4L_INPUT_DELTAS:
2478 		strlcpy(i->name, "Mutual Capacitance Deltas", sizeof(i->name));
2479 		break;
2480 	}
2481 
2482 	return 0;
2483 }
2484 
2485 static int mxt_set_input(struct mxt_data *data, unsigned int i)
2486 {
2487 	struct v4l2_pix_format *f = &data->dbg.format;
2488 
2489 	if (i >= MXT_V4L_INPUT_MAX)
2490 		return -EINVAL;
2491 
2492 	if (i == MXT_V4L_INPUT_DELTAS)
2493 		f->pixelformat = V4L2_TCH_FMT_DELTA_TD16;
2494 	else
2495 		f->pixelformat = V4L2_TCH_FMT_TU16;
2496 
2497 	f->width = data->xy_switch ? data->ysize : data->xsize;
2498 	f->height = data->xy_switch ? data->xsize : data->ysize;
2499 	f->field = V4L2_FIELD_NONE;
2500 	f->colorspace = V4L2_COLORSPACE_RAW;
2501 	f->bytesperline = f->width * sizeof(u16);
2502 	f->sizeimage = f->width * f->height * sizeof(u16);
2503 
2504 	data->dbg.input = i;
2505 
2506 	return 0;
2507 }
2508 
2509 static int mxt_vidioc_s_input(struct file *file, void *priv, unsigned int i)
2510 {
2511 	return mxt_set_input(video_drvdata(file), i);
2512 }
2513 
2514 static int mxt_vidioc_g_input(struct file *file, void *priv, unsigned int *i)
2515 {
2516 	struct mxt_data *data = video_drvdata(file);
2517 
2518 	*i = data->dbg.input;
2519 
2520 	return 0;
2521 }
2522 
2523 static int mxt_vidioc_fmt(struct file *file, void *priv, struct v4l2_format *f)
2524 {
2525 	struct mxt_data *data = video_drvdata(file);
2526 
2527 	f->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2528 	f->fmt.pix = data->dbg.format;
2529 
2530 	return 0;
2531 }
2532 
2533 static int mxt_vidioc_enum_fmt(struct file *file, void *priv,
2534 				 struct v4l2_fmtdesc *fmt)
2535 {
2536 	if (fmt->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
2537 		return -EINVAL;
2538 
2539 	switch (fmt->index) {
2540 	case 0:
2541 		fmt->pixelformat = V4L2_TCH_FMT_TU16;
2542 		break;
2543 
2544 	case 1:
2545 		fmt->pixelformat = V4L2_TCH_FMT_DELTA_TD16;
2546 		break;
2547 
2548 	default:
2549 		return -EINVAL;
2550 	}
2551 
2552 	return 0;
2553 }
2554 
2555 static int mxt_vidioc_g_parm(struct file *file, void *fh,
2556 			     struct v4l2_streamparm *a)
2557 {
2558 	if (a->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
2559 		return -EINVAL;
2560 
2561 	a->parm.capture.readbuffers = 1;
2562 	a->parm.capture.timeperframe.numerator = 1;
2563 	a->parm.capture.timeperframe.denominator = 10;
2564 	return 0;
2565 }
2566 
2567 static const struct v4l2_ioctl_ops mxt_video_ioctl_ops = {
2568 	.vidioc_querycap        = mxt_vidioc_querycap,
2569 
2570 	.vidioc_enum_fmt_vid_cap = mxt_vidioc_enum_fmt,
2571 	.vidioc_s_fmt_vid_cap   = mxt_vidioc_fmt,
2572 	.vidioc_g_fmt_vid_cap   = mxt_vidioc_fmt,
2573 	.vidioc_try_fmt_vid_cap	= mxt_vidioc_fmt,
2574 	.vidioc_g_parm		= mxt_vidioc_g_parm,
2575 
2576 	.vidioc_enum_input      = mxt_vidioc_enum_input,
2577 	.vidioc_g_input         = mxt_vidioc_g_input,
2578 	.vidioc_s_input         = mxt_vidioc_s_input,
2579 
2580 	.vidioc_reqbufs         = vb2_ioctl_reqbufs,
2581 	.vidioc_create_bufs     = vb2_ioctl_create_bufs,
2582 	.vidioc_querybuf        = vb2_ioctl_querybuf,
2583 	.vidioc_qbuf            = vb2_ioctl_qbuf,
2584 	.vidioc_dqbuf           = vb2_ioctl_dqbuf,
2585 	.vidioc_expbuf          = vb2_ioctl_expbuf,
2586 
2587 	.vidioc_streamon        = vb2_ioctl_streamon,
2588 	.vidioc_streamoff       = vb2_ioctl_streamoff,
2589 };
2590 
2591 static const struct video_device mxt_video_device = {
2592 	.name = "Atmel maxTouch",
2593 	.fops = &mxt_video_fops,
2594 	.ioctl_ops = &mxt_video_ioctl_ops,
2595 	.release = video_device_release_empty,
2596 	.device_caps = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_TOUCH |
2597 		       V4L2_CAP_READWRITE | V4L2_CAP_STREAMING,
2598 };
2599 
2600 static void mxt_debug_init(struct mxt_data *data)
2601 {
2602 	struct mxt_info *info = data->info;
2603 	struct mxt_dbg *dbg = &data->dbg;
2604 	struct mxt_object *object;
2605 	int error;
2606 
2607 	object = mxt_get_object(data, MXT_GEN_COMMAND_T6);
2608 	if (!object)
2609 		goto error;
2610 
2611 	dbg->diag_cmd_address = object->start_address + MXT_COMMAND_DIAGNOSTIC;
2612 
2613 	object = mxt_get_object(data, MXT_DEBUG_DIAGNOSTIC_T37);
2614 	if (!object)
2615 		goto error;
2616 
2617 	if (mxt_obj_size(object) != sizeof(struct t37_debug)) {
2618 		dev_warn(&data->client->dev, "Bad T37 size");
2619 		goto error;
2620 	}
2621 
2622 	dbg->t37_address = object->start_address;
2623 
2624 	/* Calculate size of data and allocate buffer */
2625 	dbg->t37_nodes = data->xsize * data->ysize;
2626 
2627 	if (info->family_id == MXT_FAMILY_1386)
2628 		dbg->t37_pages = MXT1386_COLUMNS * MXT1386_PAGES_PER_COLUMN;
2629 	else
2630 		dbg->t37_pages = DIV_ROUND_UP(data->xsize *
2631 					      info->matrix_ysize *
2632 					      sizeof(u16),
2633 					      sizeof(dbg->t37_buf->data));
2634 
2635 	dbg->t37_buf = devm_kmalloc_array(&data->client->dev, dbg->t37_pages,
2636 					  sizeof(struct t37_debug), GFP_KERNEL);
2637 	if (!dbg->t37_buf)
2638 		goto error;
2639 
2640 	/* init channel to zero */
2641 	mxt_set_input(data, 0);
2642 
2643 	/* register video device */
2644 	snprintf(dbg->v4l2.name, sizeof(dbg->v4l2.name), "%s", "atmel_mxt_ts");
2645 	error = v4l2_device_register(&data->client->dev, &dbg->v4l2);
2646 	if (error)
2647 		goto error;
2648 
2649 	/* initialize the queue */
2650 	mutex_init(&dbg->lock);
2651 	dbg->queue = mxt_queue;
2652 	dbg->queue.drv_priv = data;
2653 	dbg->queue.lock = &dbg->lock;
2654 	dbg->queue.dev = &data->client->dev;
2655 
2656 	error = vb2_queue_init(&dbg->queue);
2657 	if (error)
2658 		goto error_unreg_v4l2;
2659 
2660 	dbg->vdev = mxt_video_device;
2661 	dbg->vdev.v4l2_dev = &dbg->v4l2;
2662 	dbg->vdev.lock = &dbg->lock;
2663 	dbg->vdev.vfl_dir = VFL_DIR_RX;
2664 	dbg->vdev.queue = &dbg->queue;
2665 	video_set_drvdata(&dbg->vdev, data);
2666 
2667 	error = video_register_device(&dbg->vdev, VFL_TYPE_TOUCH, -1);
2668 	if (error)
2669 		goto error_unreg_v4l2;
2670 
2671 	return;
2672 
2673 error_unreg_v4l2:
2674 	v4l2_device_unregister(&dbg->v4l2);
2675 error:
2676 	dev_warn(&data->client->dev, "Error initializing T37\n");
2677 }
2678 #else
2679 static void mxt_debug_init(struct mxt_data *data)
2680 {
2681 }
2682 #endif
2683 
2684 static int mxt_configure_objects(struct mxt_data *data,
2685 				 const struct firmware *cfg)
2686 {
2687 	struct device *dev = &data->client->dev;
2688 	int error;
2689 
2690 	error = mxt_init_t7_power_cfg(data);
2691 	if (error) {
2692 		dev_err(dev, "Failed to initialize power cfg\n");
2693 		return error;
2694 	}
2695 
2696 	if (cfg) {
2697 		error = mxt_update_cfg(data, cfg);
2698 		if (error)
2699 			dev_warn(dev, "Error %d updating config\n", error);
2700 	}
2701 
2702 	if (data->multitouch) {
2703 		error = mxt_initialize_input_device(data);
2704 		if (error)
2705 			return error;
2706 	} else {
2707 		dev_warn(dev, "No touch object detected\n");
2708 	}
2709 
2710 	mxt_debug_init(data);
2711 
2712 	return 0;
2713 }
2714 
2715 /* Firmware Version is returned as Major.Minor.Build */
2716 static ssize_t mxt_fw_version_show(struct device *dev,
2717 				   struct device_attribute *attr, char *buf)
2718 {
2719 	struct mxt_data *data = dev_get_drvdata(dev);
2720 	struct mxt_info *info = data->info;
2721 	return scnprintf(buf, PAGE_SIZE, "%u.%u.%02X\n",
2722 			 info->version >> 4, info->version & 0xf, info->build);
2723 }
2724 
2725 /* Hardware Version is returned as FamilyID.VariantID */
2726 static ssize_t mxt_hw_version_show(struct device *dev,
2727 				   struct device_attribute *attr, char *buf)
2728 {
2729 	struct mxt_data *data = dev_get_drvdata(dev);
2730 	struct mxt_info *info = data->info;
2731 	return scnprintf(buf, PAGE_SIZE, "%u.%u\n",
2732 			 info->family_id, info->variant_id);
2733 }
2734 
2735 static ssize_t mxt_show_instance(char *buf, int count,
2736 				 struct mxt_object *object, int instance,
2737 				 const u8 *val)
2738 {
2739 	int i;
2740 
2741 	if (mxt_obj_instances(object) > 1)
2742 		count += scnprintf(buf + count, PAGE_SIZE - count,
2743 				   "Instance %u\n", instance);
2744 
2745 	for (i = 0; i < mxt_obj_size(object); i++)
2746 		count += scnprintf(buf + count, PAGE_SIZE - count,
2747 				"\t[%2u]: %02x (%d)\n", i, val[i], val[i]);
2748 	count += scnprintf(buf + count, PAGE_SIZE - count, "\n");
2749 
2750 	return count;
2751 }
2752 
2753 static ssize_t mxt_object_show(struct device *dev,
2754 				    struct device_attribute *attr, char *buf)
2755 {
2756 	struct mxt_data *data = dev_get_drvdata(dev);
2757 	struct mxt_object *object;
2758 	int count = 0;
2759 	int i, j;
2760 	int error;
2761 	u8 *obuf;
2762 
2763 	/* Pre-allocate buffer large enough to hold max sized object. */
2764 	obuf = kmalloc(256, GFP_KERNEL);
2765 	if (!obuf)
2766 		return -ENOMEM;
2767 
2768 	error = 0;
2769 	for (i = 0; i < data->info->object_num; i++) {
2770 		object = data->object_table + i;
2771 
2772 		if (!mxt_object_readable(object->type))
2773 			continue;
2774 
2775 		count += scnprintf(buf + count, PAGE_SIZE - count,
2776 				"T%u:\n", object->type);
2777 
2778 		for (j = 0; j < mxt_obj_instances(object); j++) {
2779 			u16 size = mxt_obj_size(object);
2780 			u16 addr = object->start_address + j * size;
2781 
2782 			error = __mxt_read_reg(data->client, addr, size, obuf);
2783 			if (error)
2784 				goto done;
2785 
2786 			count = mxt_show_instance(buf, count, object, j, obuf);
2787 		}
2788 	}
2789 
2790 done:
2791 	kfree(obuf);
2792 	return error ?: count;
2793 }
2794 
2795 static int mxt_check_firmware_format(struct device *dev,
2796 				     const struct firmware *fw)
2797 {
2798 	unsigned int pos = 0;
2799 	char c;
2800 
2801 	while (pos < fw->size) {
2802 		c = *(fw->data + pos);
2803 
2804 		if (c < '0' || (c > '9' && c < 'A') || c > 'F')
2805 			return 0;
2806 
2807 		pos++;
2808 	}
2809 
2810 	/*
2811 	 * To convert file try:
2812 	 * xxd -r -p mXTXXX__APP_VX-X-XX.enc > maxtouch.fw
2813 	 */
2814 	dev_err(dev, "Aborting: firmware file must be in binary format\n");
2815 
2816 	return -EINVAL;
2817 }
2818 
2819 static int mxt_load_fw(struct device *dev, const char *fn)
2820 {
2821 	struct mxt_data *data = dev_get_drvdata(dev);
2822 	const struct firmware *fw = NULL;
2823 	unsigned int frame_size;
2824 	unsigned int pos = 0;
2825 	unsigned int retry = 0;
2826 	unsigned int frame = 0;
2827 	int ret;
2828 
2829 	ret = request_firmware(&fw, fn, dev);
2830 	if (ret) {
2831 		dev_err(dev, "Unable to open firmware %s\n", fn);
2832 		return ret;
2833 	}
2834 
2835 	/* Check for incorrect enc file */
2836 	ret = mxt_check_firmware_format(dev, fw);
2837 	if (ret)
2838 		goto release_firmware;
2839 
2840 	if (!data->in_bootloader) {
2841 		/* Change to the bootloader mode */
2842 		data->in_bootloader = true;
2843 
2844 		ret = mxt_t6_command(data, MXT_COMMAND_RESET,
2845 				     MXT_BOOT_VALUE, false);
2846 		if (ret)
2847 			goto release_firmware;
2848 
2849 		msleep(MXT_RESET_TIME);
2850 
2851 		/* Do not need to scan since we know family ID */
2852 		ret = mxt_lookup_bootloader_address(data, 0);
2853 		if (ret)
2854 			goto release_firmware;
2855 
2856 		mxt_free_input_device(data);
2857 		mxt_free_object_table(data);
2858 	} else {
2859 		enable_irq(data->irq);
2860 	}
2861 
2862 	reinit_completion(&data->bl_completion);
2863 
2864 	ret = mxt_check_bootloader(data, MXT_WAITING_BOOTLOAD_CMD, false);
2865 	if (ret) {
2866 		/* Bootloader may still be unlocked from previous attempt */
2867 		ret = mxt_check_bootloader(data, MXT_WAITING_FRAME_DATA, false);
2868 		if (ret)
2869 			goto disable_irq;
2870 	} else {
2871 		dev_info(dev, "Unlocking bootloader\n");
2872 
2873 		/* Unlock bootloader */
2874 		ret = mxt_send_bootloader_cmd(data, true);
2875 		if (ret)
2876 			goto disable_irq;
2877 	}
2878 
2879 	while (pos < fw->size) {
2880 		ret = mxt_check_bootloader(data, MXT_WAITING_FRAME_DATA, true);
2881 		if (ret)
2882 			goto disable_irq;
2883 
2884 		frame_size = ((*(fw->data + pos) << 8) | *(fw->data + pos + 1));
2885 
2886 		/* Take account of CRC bytes */
2887 		frame_size += 2;
2888 
2889 		/* Write one frame to device */
2890 		ret = mxt_bootloader_write(data, fw->data + pos, frame_size);
2891 		if (ret)
2892 			goto disable_irq;
2893 
2894 		ret = mxt_check_bootloader(data, MXT_FRAME_CRC_PASS, true);
2895 		if (ret) {
2896 			retry++;
2897 
2898 			/* Back off by 20ms per retry */
2899 			msleep(retry * 20);
2900 
2901 			if (retry > 20) {
2902 				dev_err(dev, "Retry count exceeded\n");
2903 				goto disable_irq;
2904 			}
2905 		} else {
2906 			retry = 0;
2907 			pos += frame_size;
2908 			frame++;
2909 		}
2910 
2911 		if (frame % 50 == 0)
2912 			dev_dbg(dev, "Sent %d frames, %d/%zd bytes\n",
2913 				frame, pos, fw->size);
2914 	}
2915 
2916 	/* Wait for flash. */
2917 	ret = mxt_wait_for_completion(data, &data->bl_completion,
2918 				      MXT_FW_RESET_TIME);
2919 	if (ret)
2920 		goto disable_irq;
2921 
2922 	dev_dbg(dev, "Sent %d frames, %d bytes\n", frame, pos);
2923 
2924 	/*
2925 	 * Wait for device to reset. Some bootloader versions do not assert
2926 	 * the CHG line after bootloading has finished, so ignore potential
2927 	 * errors.
2928 	 */
2929 	mxt_wait_for_completion(data, &data->bl_completion, MXT_FW_RESET_TIME);
2930 
2931 	data->in_bootloader = false;
2932 
2933 disable_irq:
2934 	disable_irq(data->irq);
2935 release_firmware:
2936 	release_firmware(fw);
2937 	return ret;
2938 }
2939 
2940 static ssize_t mxt_update_fw_store(struct device *dev,
2941 					struct device_attribute *attr,
2942 					const char *buf, size_t count)
2943 {
2944 	struct mxt_data *data = dev_get_drvdata(dev);
2945 	int error;
2946 
2947 	error = mxt_load_fw(dev, MXT_FW_NAME);
2948 	if (error) {
2949 		dev_err(dev, "The firmware update failed(%d)\n", error);
2950 		count = error;
2951 	} else {
2952 		dev_info(dev, "The firmware update succeeded\n");
2953 
2954 		error = mxt_initialize(data);
2955 		if (error)
2956 			return error;
2957 	}
2958 
2959 	return count;
2960 }
2961 
2962 static DEVICE_ATTR(fw_version, S_IRUGO, mxt_fw_version_show, NULL);
2963 static DEVICE_ATTR(hw_version, S_IRUGO, mxt_hw_version_show, NULL);
2964 static DEVICE_ATTR(object, S_IRUGO, mxt_object_show, NULL);
2965 static DEVICE_ATTR(update_fw, S_IWUSR, NULL, mxt_update_fw_store);
2966 
2967 static struct attribute *mxt_attrs[] = {
2968 	&dev_attr_fw_version.attr,
2969 	&dev_attr_hw_version.attr,
2970 	&dev_attr_object.attr,
2971 	&dev_attr_update_fw.attr,
2972 	NULL
2973 };
2974 
2975 static const struct attribute_group mxt_attr_group = {
2976 	.attrs = mxt_attrs,
2977 };
2978 
2979 static void mxt_start(struct mxt_data *data)
2980 {
2981 	switch (data->suspend_mode) {
2982 	case MXT_SUSPEND_T9_CTRL:
2983 		mxt_soft_reset(data);
2984 
2985 		/* Touch enable */
2986 		/* 0x83 = SCANEN | RPTEN | ENABLE */
2987 		mxt_write_object(data,
2988 				MXT_TOUCH_MULTI_T9, MXT_T9_CTRL, 0x83);
2989 		break;
2990 
2991 	case MXT_SUSPEND_DEEP_SLEEP:
2992 	default:
2993 		mxt_set_t7_power_cfg(data, MXT_POWER_CFG_RUN);
2994 
2995 		/* Recalibrate since chip has been in deep sleep */
2996 		mxt_t6_command(data, MXT_COMMAND_CALIBRATE, 1, false);
2997 		break;
2998 	}
2999 }
3000 
3001 static void mxt_stop(struct mxt_data *data)
3002 {
3003 	switch (data->suspend_mode) {
3004 	case MXT_SUSPEND_T9_CTRL:
3005 		/* Touch disable */
3006 		mxt_write_object(data,
3007 				MXT_TOUCH_MULTI_T9, MXT_T9_CTRL, 0);
3008 		break;
3009 
3010 	case MXT_SUSPEND_DEEP_SLEEP:
3011 	default:
3012 		mxt_set_t7_power_cfg(data, MXT_POWER_CFG_DEEPSLEEP);
3013 		break;
3014 	}
3015 }
3016 
3017 static int mxt_input_open(struct input_dev *dev)
3018 {
3019 	struct mxt_data *data = input_get_drvdata(dev);
3020 
3021 	mxt_start(data);
3022 
3023 	return 0;
3024 }
3025 
3026 static void mxt_input_close(struct input_dev *dev)
3027 {
3028 	struct mxt_data *data = input_get_drvdata(dev);
3029 
3030 	mxt_stop(data);
3031 }
3032 
3033 static int mxt_parse_device_properties(struct mxt_data *data)
3034 {
3035 	static const char keymap_property[] = "linux,gpio-keymap";
3036 	struct device *dev = &data->client->dev;
3037 	u32 *keymap;
3038 	int n_keys;
3039 	int error;
3040 
3041 	if (device_property_present(dev, keymap_property)) {
3042 		n_keys = device_property_count_u32(dev, keymap_property);
3043 		if (n_keys <= 0) {
3044 			error = n_keys < 0 ? n_keys : -EINVAL;
3045 			dev_err(dev, "invalid/malformed '%s' property: %d\n",
3046 				keymap_property, error);
3047 			return error;
3048 		}
3049 
3050 		keymap = devm_kmalloc_array(dev, n_keys, sizeof(*keymap),
3051 					    GFP_KERNEL);
3052 		if (!keymap)
3053 			return -ENOMEM;
3054 
3055 		error = device_property_read_u32_array(dev, keymap_property,
3056 						       keymap, n_keys);
3057 		if (error) {
3058 			dev_err(dev, "failed to parse '%s' property: %d\n",
3059 				keymap_property, error);
3060 			return error;
3061 		}
3062 
3063 		data->t19_keymap = keymap;
3064 		data->t19_num_keys = n_keys;
3065 	}
3066 
3067 	return 0;
3068 }
3069 
3070 static const struct dmi_system_id chromebook_T9_suspend_dmi[] = {
3071 	{
3072 		.matches = {
3073 			DMI_MATCH(DMI_SYS_VENDOR, "GOOGLE"),
3074 			DMI_MATCH(DMI_PRODUCT_NAME, "Link"),
3075 		},
3076 	},
3077 	{
3078 		.matches = {
3079 			DMI_MATCH(DMI_PRODUCT_NAME, "Peppy"),
3080 		},
3081 	},
3082 	{ }
3083 };
3084 
3085 static int mxt_probe(struct i2c_client *client, const struct i2c_device_id *id)
3086 {
3087 	struct mxt_data *data;
3088 	int error;
3089 
3090 	/*
3091 	 * Ignore devices that do not have device properties attached to
3092 	 * them, as we need help determining whether we are dealing with
3093 	 * touch screen or touchpad.
3094 	 *
3095 	 * So far on x86 the only users of Atmel touch controllers are
3096 	 * Chromebooks, and chromeos_laptop driver will ensure that
3097 	 * necessary properties are provided (if firmware does not do that).
3098 	 */
3099 	if (!device_property_present(&client->dev, "compatible"))
3100 		return -ENXIO;
3101 
3102 	/*
3103 	 * Ignore ACPI devices representing bootloader mode.
3104 	 *
3105 	 * This is a bit of a hack: Google Chromebook BIOS creates ACPI
3106 	 * devices for both application and bootloader modes, but we are
3107 	 * interested in application mode only (if device is in bootloader
3108 	 * mode we'll end up switching into application anyway). So far
3109 	 * application mode addresses were all above 0x40, so we'll use it
3110 	 * as a threshold.
3111 	 */
3112 	if (ACPI_COMPANION(&client->dev) && client->addr < 0x40)
3113 		return -ENXIO;
3114 
3115 	data = devm_kzalloc(&client->dev, sizeof(struct mxt_data), GFP_KERNEL);
3116 	if (!data)
3117 		return -ENOMEM;
3118 
3119 	snprintf(data->phys, sizeof(data->phys), "i2c-%u-%04x/input0",
3120 		 client->adapter->nr, client->addr);
3121 
3122 	data->client = client;
3123 	data->irq = client->irq;
3124 	i2c_set_clientdata(client, data);
3125 
3126 	init_completion(&data->bl_completion);
3127 	init_completion(&data->reset_completion);
3128 	init_completion(&data->crc_completion);
3129 
3130 	data->suspend_mode = dmi_check_system(chromebook_T9_suspend_dmi) ?
3131 		MXT_SUSPEND_T9_CTRL : MXT_SUSPEND_DEEP_SLEEP;
3132 
3133 	error = mxt_parse_device_properties(data);
3134 	if (error)
3135 		return error;
3136 
3137 	data->reset_gpio = devm_gpiod_get_optional(&client->dev,
3138 						   "reset", GPIOD_OUT_LOW);
3139 	if (IS_ERR(data->reset_gpio)) {
3140 		error = PTR_ERR(data->reset_gpio);
3141 		dev_err(&client->dev, "Failed to get reset gpio: %d\n", error);
3142 		return error;
3143 	}
3144 
3145 	error = devm_request_threaded_irq(&client->dev, client->irq,
3146 					  NULL, mxt_interrupt, IRQF_ONESHOT,
3147 					  client->name, data);
3148 	if (error) {
3149 		dev_err(&client->dev, "Failed to register interrupt\n");
3150 		return error;
3151 	}
3152 
3153 	disable_irq(client->irq);
3154 
3155 	if (data->reset_gpio) {
3156 		msleep(MXT_RESET_GPIO_TIME);
3157 		gpiod_set_value(data->reset_gpio, 1);
3158 		msleep(MXT_RESET_INVALID_CHG);
3159 	}
3160 
3161 	error = mxt_initialize(data);
3162 	if (error)
3163 		return error;
3164 
3165 	error = sysfs_create_group(&client->dev.kobj, &mxt_attr_group);
3166 	if (error) {
3167 		dev_err(&client->dev, "Failure %d creating sysfs group\n",
3168 			error);
3169 		goto err_free_object;
3170 	}
3171 
3172 	return 0;
3173 
3174 err_free_object:
3175 	mxt_free_input_device(data);
3176 	mxt_free_object_table(data);
3177 	return error;
3178 }
3179 
3180 static int mxt_remove(struct i2c_client *client)
3181 {
3182 	struct mxt_data *data = i2c_get_clientdata(client);
3183 
3184 	disable_irq(data->irq);
3185 	sysfs_remove_group(&client->dev.kobj, &mxt_attr_group);
3186 	mxt_free_input_device(data);
3187 	mxt_free_object_table(data);
3188 
3189 	return 0;
3190 }
3191 
3192 static int __maybe_unused mxt_suspend(struct device *dev)
3193 {
3194 	struct i2c_client *client = to_i2c_client(dev);
3195 	struct mxt_data *data = i2c_get_clientdata(client);
3196 	struct input_dev *input_dev = data->input_dev;
3197 
3198 	if (!input_dev)
3199 		return 0;
3200 
3201 	mutex_lock(&input_dev->mutex);
3202 
3203 	if (input_dev->users)
3204 		mxt_stop(data);
3205 
3206 	mutex_unlock(&input_dev->mutex);
3207 
3208 	disable_irq(data->irq);
3209 
3210 	return 0;
3211 }
3212 
3213 static int __maybe_unused mxt_resume(struct device *dev)
3214 {
3215 	struct i2c_client *client = to_i2c_client(dev);
3216 	struct mxt_data *data = i2c_get_clientdata(client);
3217 	struct input_dev *input_dev = data->input_dev;
3218 
3219 	if (!input_dev)
3220 		return 0;
3221 
3222 	enable_irq(data->irq);
3223 
3224 	mutex_lock(&input_dev->mutex);
3225 
3226 	if (input_dev->users)
3227 		mxt_start(data);
3228 
3229 	mutex_unlock(&input_dev->mutex);
3230 
3231 	return 0;
3232 }
3233 
3234 static SIMPLE_DEV_PM_OPS(mxt_pm_ops, mxt_suspend, mxt_resume);
3235 
3236 static const struct of_device_id mxt_of_match[] = {
3237 	{ .compatible = "atmel,maxtouch", },
3238 	/* Compatibles listed below are deprecated */
3239 	{ .compatible = "atmel,qt602240_ts", },
3240 	{ .compatible = "atmel,atmel_mxt_ts", },
3241 	{ .compatible = "atmel,atmel_mxt_tp", },
3242 	{ .compatible = "atmel,mXT224", },
3243 	{},
3244 };
3245 MODULE_DEVICE_TABLE(of, mxt_of_match);
3246 
3247 #ifdef CONFIG_ACPI
3248 static const struct acpi_device_id mxt_acpi_id[] = {
3249 	{ "ATML0000", 0 },	/* Touchpad */
3250 	{ "ATML0001", 0 },	/* Touchscreen */
3251 	{ }
3252 };
3253 MODULE_DEVICE_TABLE(acpi, mxt_acpi_id);
3254 #endif
3255 
3256 static const struct i2c_device_id mxt_id[] = {
3257 	{ "qt602240_ts", 0 },
3258 	{ "atmel_mxt_ts", 0 },
3259 	{ "atmel_mxt_tp", 0 },
3260 	{ "maxtouch", 0 },
3261 	{ "mXT224", 0 },
3262 	{ }
3263 };
3264 MODULE_DEVICE_TABLE(i2c, mxt_id);
3265 
3266 static struct i2c_driver mxt_driver = {
3267 	.driver = {
3268 		.name	= "atmel_mxt_ts",
3269 		.of_match_table = mxt_of_match,
3270 		.acpi_match_table = ACPI_PTR(mxt_acpi_id),
3271 		.pm	= &mxt_pm_ops,
3272 	},
3273 	.probe		= mxt_probe,
3274 	.remove		= mxt_remove,
3275 	.id_table	= mxt_id,
3276 };
3277 
3278 module_i2c_driver(mxt_driver);
3279 
3280 /* Module information */
3281 MODULE_AUTHOR("Joonyoung Shim <jy0922.shim@samsung.com>");
3282 MODULE_DESCRIPTION("Atmel maXTouch Touchscreen driver");
3283 MODULE_LICENSE("GPL");
3284