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