OSDN Git Service

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