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