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