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