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