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