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