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