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