Merge tag 'trace-v4.20-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt...
[muen/linux.git] / drivers / hid / i2c-hid / i2c-hid-core.c
1 /*
2  * HID over I2C protocol implementation
3  *
4  * Copyright (c) 2012 Benjamin Tissoires <benjamin.tissoires@gmail.com>
5  * Copyright (c) 2012 Ecole Nationale de l'Aviation Civile, France
6  * Copyright (c) 2012 Red Hat, Inc
7  *
8  * This code is partly based on "USB HID support for Linux":
9  *
10  *  Copyright (c) 1999 Andreas Gal
11  *  Copyright (c) 2000-2005 Vojtech Pavlik <vojtech@suse.cz>
12  *  Copyright (c) 2005 Michael Haboustak <mike-@cinci.rr.com> for Concept2, Inc
13  *  Copyright (c) 2007-2008 Oliver Neukum
14  *  Copyright (c) 2006-2010 Jiri Kosina
15  *
16  * This file is subject to the terms and conditions of the GNU General Public
17  * License.  See the file COPYING in the main directory of this archive for
18  * more details.
19  */
20
21 #include <linux/module.h>
22 #include <linux/i2c.h>
23 #include <linux/interrupt.h>
24 #include <linux/input.h>
25 #include <linux/irq.h>
26 #include <linux/delay.h>
27 #include <linux/slab.h>
28 #include <linux/pm.h>
29 #include <linux/pm_runtime.h>
30 #include <linux/device.h>
31 #include <linux/wait.h>
32 #include <linux/err.h>
33 #include <linux/string.h>
34 #include <linux/list.h>
35 #include <linux/jiffies.h>
36 #include <linux/kernel.h>
37 #include <linux/hid.h>
38 #include <linux/mutex.h>
39 #include <linux/acpi.h>
40 #include <linux/of.h>
41 #include <linux/regulator/consumer.h>
42
43 #include <linux/platform_data/i2c-hid.h>
44
45 #include "../hid-ids.h"
46 #include "i2c-hid.h"
47
48 /* quirks to control the device */
49 #define I2C_HID_QUIRK_SET_PWR_WAKEUP_DEV        BIT(0)
50 #define I2C_HID_QUIRK_NO_IRQ_AFTER_RESET        BIT(1)
51 #define I2C_HID_QUIRK_NO_RUNTIME_PM             BIT(2)
52
53 /* flags */
54 #define I2C_HID_STARTED         0
55 #define I2C_HID_RESET_PENDING   1
56 #define I2C_HID_READ_PENDING    2
57
58 #define I2C_HID_PWR_ON          0x00
59 #define I2C_HID_PWR_SLEEP       0x01
60
61 /* debug option */
62 static bool debug;
63 module_param(debug, bool, 0444);
64 MODULE_PARM_DESC(debug, "print a lot of debug information");
65
66 #define i2c_hid_dbg(ihid, fmt, arg...)                                    \
67 do {                                                                      \
68         if (debug)                                                        \
69                 dev_printk(KERN_DEBUG, &(ihid)->client->dev, fmt, ##arg); \
70 } while (0)
71
72 struct i2c_hid_desc {
73         __le16 wHIDDescLength;
74         __le16 bcdVersion;
75         __le16 wReportDescLength;
76         __le16 wReportDescRegister;
77         __le16 wInputRegister;
78         __le16 wMaxInputLength;
79         __le16 wOutputRegister;
80         __le16 wMaxOutputLength;
81         __le16 wCommandRegister;
82         __le16 wDataRegister;
83         __le16 wVendorID;
84         __le16 wProductID;
85         __le16 wVersionID;
86         __le32 reserved;
87 } __packed;
88
89 struct i2c_hid_cmd {
90         unsigned int registerIndex;
91         __u8 opcode;
92         unsigned int length;
93         bool wait;
94 };
95
96 union command {
97         u8 data[0];
98         struct cmd {
99                 __le16 reg;
100                 __u8 reportTypeID;
101                 __u8 opcode;
102         } __packed c;
103 };
104
105 #define I2C_HID_CMD(opcode_) \
106         .opcode = opcode_, .length = 4, \
107         .registerIndex = offsetof(struct i2c_hid_desc, wCommandRegister)
108
109 /* fetch HID descriptor */
110 static const struct i2c_hid_cmd hid_descr_cmd = { .length = 2 };
111 /* fetch report descriptors */
112 static const struct i2c_hid_cmd hid_report_descr_cmd = {
113                 .registerIndex = offsetof(struct i2c_hid_desc,
114                         wReportDescRegister),
115                 .opcode = 0x00,
116                 .length = 2 };
117 /* commands */
118 static const struct i2c_hid_cmd hid_reset_cmd =         { I2C_HID_CMD(0x01),
119                                                           .wait = true };
120 static const struct i2c_hid_cmd hid_get_report_cmd =    { I2C_HID_CMD(0x02) };
121 static const struct i2c_hid_cmd hid_set_report_cmd =    { I2C_HID_CMD(0x03) };
122 static const struct i2c_hid_cmd hid_set_power_cmd =     { I2C_HID_CMD(0x08) };
123 static const struct i2c_hid_cmd hid_no_cmd =            { .length = 0 };
124
125 /*
126  * These definitions are not used here, but are defined by the spec.
127  * Keeping them here for documentation purposes.
128  *
129  * static const struct i2c_hid_cmd hid_get_idle_cmd = { I2C_HID_CMD(0x04) };
130  * static const struct i2c_hid_cmd hid_set_idle_cmd = { I2C_HID_CMD(0x05) };
131  * static const struct i2c_hid_cmd hid_get_protocol_cmd = { I2C_HID_CMD(0x06) };
132  * static const struct i2c_hid_cmd hid_set_protocol_cmd = { I2C_HID_CMD(0x07) };
133  */
134
135 /* The main device structure */
136 struct i2c_hid {
137         struct i2c_client       *client;        /* i2c client */
138         struct hid_device       *hid;   /* pointer to corresponding HID dev */
139         union {
140                 __u8 hdesc_buffer[sizeof(struct i2c_hid_desc)];
141                 struct i2c_hid_desc hdesc;      /* the HID Descriptor */
142         };
143         __le16                  wHIDDescRegister; /* location of the i2c
144                                                    * register of the HID
145                                                    * descriptor. */
146         unsigned int            bufsize;        /* i2c buffer size */
147         u8                      *inbuf;         /* Input buffer */
148         u8                      *rawbuf;        /* Raw Input buffer */
149         u8                      *cmdbuf;        /* Command buffer */
150         u8                      *argsbuf;       /* Command arguments buffer */
151
152         unsigned long           flags;          /* device flags */
153         unsigned long           quirks;         /* Various quirks */
154
155         wait_queue_head_t       wait;           /* For waiting the interrupt */
156
157         struct i2c_hid_platform_data pdata;
158
159         bool                    irq_wake_enabled;
160         struct mutex            reset_lock;
161 };
162
163 static const struct i2c_hid_quirks {
164         __u16 idVendor;
165         __u16 idProduct;
166         __u32 quirks;
167 } i2c_hid_quirks[] = {
168         { USB_VENDOR_ID_WEIDA, USB_DEVICE_ID_WEIDA_8752,
169                 I2C_HID_QUIRK_SET_PWR_WAKEUP_DEV },
170         { USB_VENDOR_ID_WEIDA, USB_DEVICE_ID_WEIDA_8755,
171                 I2C_HID_QUIRK_SET_PWR_WAKEUP_DEV },
172         { I2C_VENDOR_ID_HANTICK, I2C_PRODUCT_ID_HANTICK_5288,
173                 I2C_HID_QUIRK_NO_IRQ_AFTER_RESET |
174                 I2C_HID_QUIRK_NO_RUNTIME_PM },
175         { 0, 0 }
176 };
177
178 /*
179  * i2c_hid_lookup_quirk: return any quirks associated with a I2C HID device
180  * @idVendor: the 16-bit vendor ID
181  * @idProduct: the 16-bit product ID
182  *
183  * Returns: a u32 quirks value.
184  */
185 static u32 i2c_hid_lookup_quirk(const u16 idVendor, const u16 idProduct)
186 {
187         u32 quirks = 0;
188         int n;
189
190         for (n = 0; i2c_hid_quirks[n].idVendor; n++)
191                 if (i2c_hid_quirks[n].idVendor == idVendor &&
192                     (i2c_hid_quirks[n].idProduct == (__u16)HID_ANY_ID ||
193                      i2c_hid_quirks[n].idProduct == idProduct))
194                         quirks = i2c_hid_quirks[n].quirks;
195
196         return quirks;
197 }
198
199 static int __i2c_hid_command(struct i2c_client *client,
200                 const struct i2c_hid_cmd *command, u8 reportID,
201                 u8 reportType, u8 *args, int args_len,
202                 unsigned char *buf_recv, int data_len)
203 {
204         struct i2c_hid *ihid = i2c_get_clientdata(client);
205         union command *cmd = (union command *)ihid->cmdbuf;
206         int ret;
207         struct i2c_msg msg[2];
208         int msg_num = 1;
209
210         int length = command->length;
211         bool wait = command->wait;
212         unsigned int registerIndex = command->registerIndex;
213
214         /* special case for hid_descr_cmd */
215         if (command == &hid_descr_cmd) {
216                 cmd->c.reg = ihid->wHIDDescRegister;
217         } else {
218                 cmd->data[0] = ihid->hdesc_buffer[registerIndex];
219                 cmd->data[1] = ihid->hdesc_buffer[registerIndex + 1];
220         }
221
222         if (length > 2) {
223                 cmd->c.opcode = command->opcode;
224                 cmd->c.reportTypeID = reportID | reportType << 4;
225         }
226
227         memcpy(cmd->data + length, args, args_len);
228         length += args_len;
229
230         i2c_hid_dbg(ihid, "%s: cmd=%*ph\n", __func__, length, cmd->data);
231
232         msg[0].addr = client->addr;
233         msg[0].flags = client->flags & I2C_M_TEN;
234         msg[0].len = length;
235         msg[0].buf = cmd->data;
236         if (data_len > 0) {
237                 msg[1].addr = client->addr;
238                 msg[1].flags = client->flags & I2C_M_TEN;
239                 msg[1].flags |= I2C_M_RD;
240                 msg[1].len = data_len;
241                 msg[1].buf = buf_recv;
242                 msg_num = 2;
243                 set_bit(I2C_HID_READ_PENDING, &ihid->flags);
244         }
245
246         if (wait)
247                 set_bit(I2C_HID_RESET_PENDING, &ihid->flags);
248
249         ret = i2c_transfer(client->adapter, msg, msg_num);
250
251         if (data_len > 0)
252                 clear_bit(I2C_HID_READ_PENDING, &ihid->flags);
253
254         if (ret != msg_num)
255                 return ret < 0 ? ret : -EIO;
256
257         ret = 0;
258
259         if (wait && (ihid->quirks & I2C_HID_QUIRK_NO_IRQ_AFTER_RESET)) {
260                 msleep(100);
261         } else if (wait) {
262                 i2c_hid_dbg(ihid, "%s: waiting...\n", __func__);
263                 if (!wait_event_timeout(ihid->wait,
264                                 !test_bit(I2C_HID_RESET_PENDING, &ihid->flags),
265                                 msecs_to_jiffies(5000)))
266                         ret = -ENODATA;
267                 i2c_hid_dbg(ihid, "%s: finished.\n", __func__);
268         }
269
270         return ret;
271 }
272
273 static int i2c_hid_command(struct i2c_client *client,
274                 const struct i2c_hid_cmd *command,
275                 unsigned char *buf_recv, int data_len)
276 {
277         return __i2c_hid_command(client, command, 0, 0, NULL, 0,
278                                 buf_recv, data_len);
279 }
280
281 static int i2c_hid_get_report(struct i2c_client *client, u8 reportType,
282                 u8 reportID, unsigned char *buf_recv, int data_len)
283 {
284         struct i2c_hid *ihid = i2c_get_clientdata(client);
285         u8 args[3];
286         int ret;
287         int args_len = 0;
288         u16 readRegister = le16_to_cpu(ihid->hdesc.wDataRegister);
289
290         i2c_hid_dbg(ihid, "%s\n", __func__);
291
292         if (reportID >= 0x0F) {
293                 args[args_len++] = reportID;
294                 reportID = 0x0F;
295         }
296
297         args[args_len++] = readRegister & 0xFF;
298         args[args_len++] = readRegister >> 8;
299
300         ret = __i2c_hid_command(client, &hid_get_report_cmd, reportID,
301                 reportType, args, args_len, buf_recv, data_len);
302         if (ret) {
303                 dev_err(&client->dev,
304                         "failed to retrieve report from device.\n");
305                 return ret;
306         }
307
308         return 0;
309 }
310
311 /**
312  * i2c_hid_set_or_send_report: forward an incoming report to the device
313  * @client: the i2c_client of the device
314  * @reportType: 0x03 for HID_FEATURE_REPORT ; 0x02 for HID_OUTPUT_REPORT
315  * @reportID: the report ID
316  * @buf: the actual data to transfer, without the report ID
317  * @len: size of buf
318  * @use_data: true: use SET_REPORT HID command, false: send plain OUTPUT report
319  */
320 static int i2c_hid_set_or_send_report(struct i2c_client *client, u8 reportType,
321                 u8 reportID, unsigned char *buf, size_t data_len, bool use_data)
322 {
323         struct i2c_hid *ihid = i2c_get_clientdata(client);
324         u8 *args = ihid->argsbuf;
325         const struct i2c_hid_cmd *hidcmd;
326         int ret;
327         u16 dataRegister = le16_to_cpu(ihid->hdesc.wDataRegister);
328         u16 outputRegister = le16_to_cpu(ihid->hdesc.wOutputRegister);
329         u16 maxOutputLength = le16_to_cpu(ihid->hdesc.wMaxOutputLength);
330         u16 size;
331         int args_len;
332         int index = 0;
333
334         i2c_hid_dbg(ihid, "%s\n", __func__);
335
336         if (data_len > ihid->bufsize)
337                 return -EINVAL;
338
339         size =          2                       /* size */ +
340                         (reportID ? 1 : 0)      /* reportID */ +
341                         data_len                /* buf */;
342         args_len =      (reportID >= 0x0F ? 1 : 0) /* optional third byte */ +
343                         2                       /* dataRegister */ +
344                         size                    /* args */;
345
346         if (!use_data && maxOutputLength == 0)
347                 return -ENOSYS;
348
349         if (reportID >= 0x0F) {
350                 args[index++] = reportID;
351                 reportID = 0x0F;
352         }
353
354         /*
355          * use the data register for feature reports or if the device does not
356          * support the output register
357          */
358         if (use_data) {
359                 args[index++] = dataRegister & 0xFF;
360                 args[index++] = dataRegister >> 8;
361                 hidcmd = &hid_set_report_cmd;
362         } else {
363                 args[index++] = outputRegister & 0xFF;
364                 args[index++] = outputRegister >> 8;
365                 hidcmd = &hid_no_cmd;
366         }
367
368         args[index++] = size & 0xFF;
369         args[index++] = size >> 8;
370
371         if (reportID)
372                 args[index++] = reportID;
373
374         memcpy(&args[index], buf, data_len);
375
376         ret = __i2c_hid_command(client, hidcmd, reportID,
377                 reportType, args, args_len, NULL, 0);
378         if (ret) {
379                 dev_err(&client->dev, "failed to set a report to device.\n");
380                 return ret;
381         }
382
383         return data_len;
384 }
385
386 static int i2c_hid_set_power(struct i2c_client *client, int power_state)
387 {
388         struct i2c_hid *ihid = i2c_get_clientdata(client);
389         int ret;
390
391         i2c_hid_dbg(ihid, "%s\n", __func__);
392
393         /*
394          * Some devices require to send a command to wakeup before power on.
395          * The call will get a return value (EREMOTEIO) but device will be
396          * triggered and activated. After that, it goes like a normal device.
397          */
398         if (power_state == I2C_HID_PWR_ON &&
399             ihid->quirks & I2C_HID_QUIRK_SET_PWR_WAKEUP_DEV) {
400                 ret = i2c_hid_command(client, &hid_set_power_cmd, NULL, 0);
401
402                 /* Device was already activated */
403                 if (!ret)
404                         goto set_pwr_exit;
405         }
406
407         ret = __i2c_hid_command(client, &hid_set_power_cmd, power_state,
408                 0, NULL, 0, NULL, 0);
409
410         if (ret)
411                 dev_err(&client->dev, "failed to change power setting.\n");
412
413 set_pwr_exit:
414         return ret;
415 }
416
417 static int i2c_hid_hwreset(struct i2c_client *client)
418 {
419         struct i2c_hid *ihid = i2c_get_clientdata(client);
420         int ret;
421
422         i2c_hid_dbg(ihid, "%s\n", __func__);
423
424         /*
425          * This prevents sending feature reports while the device is
426          * being reset. Otherwise we may lose the reset complete
427          * interrupt.
428          */
429         mutex_lock(&ihid->reset_lock);
430
431         ret = i2c_hid_set_power(client, I2C_HID_PWR_ON);
432         if (ret)
433                 goto out_unlock;
434
435         /*
436          * The HID over I2C specification states that if a DEVICE needs time
437          * after the PWR_ON request, it should utilise CLOCK stretching.
438          * However, it has been observered that the Windows driver provides a
439          * 1ms sleep between the PWR_ON and RESET requests and that some devices
440          * rely on this.
441          */
442         usleep_range(1000, 5000);
443
444         i2c_hid_dbg(ihid, "resetting...\n");
445
446         ret = i2c_hid_command(client, &hid_reset_cmd, NULL, 0);
447         if (ret) {
448                 dev_err(&client->dev, "failed to reset device.\n");
449                 i2c_hid_set_power(client, I2C_HID_PWR_SLEEP);
450         }
451
452 out_unlock:
453         mutex_unlock(&ihid->reset_lock);
454         return ret;
455 }
456
457 static void i2c_hid_get_input(struct i2c_hid *ihid)
458 {
459         int ret;
460         u32 ret_size;
461         int size = le16_to_cpu(ihid->hdesc.wMaxInputLength);
462
463         if (size > ihid->bufsize)
464                 size = ihid->bufsize;
465
466         ret = i2c_master_recv(ihid->client, ihid->inbuf, size);
467         if (ret != size) {
468                 if (ret < 0)
469                         return;
470
471                 dev_err(&ihid->client->dev, "%s: got %d data instead of %d\n",
472                         __func__, ret, size);
473                 return;
474         }
475
476         ret_size = ihid->inbuf[0] | ihid->inbuf[1] << 8;
477
478         if (!ret_size) {
479                 /* host or device initiated RESET completed */
480                 if (test_and_clear_bit(I2C_HID_RESET_PENDING, &ihid->flags))
481                         wake_up(&ihid->wait);
482                 return;
483         }
484
485         if ((ret_size > size) || (ret_size < 2)) {
486                 dev_err(&ihid->client->dev, "%s: incomplete report (%d/%d)\n",
487                         __func__, size, ret_size);
488                 return;
489         }
490
491         i2c_hid_dbg(ihid, "input: %*ph\n", ret_size, ihid->inbuf);
492
493         if (test_bit(I2C_HID_STARTED, &ihid->flags))
494                 hid_input_report(ihid->hid, HID_INPUT_REPORT, ihid->inbuf + 2,
495                                 ret_size - 2, 1);
496
497         return;
498 }
499
500 static irqreturn_t i2c_hid_irq(int irq, void *dev_id)
501 {
502         struct i2c_hid *ihid = dev_id;
503
504         if (test_bit(I2C_HID_READ_PENDING, &ihid->flags))
505                 return IRQ_HANDLED;
506
507         i2c_hid_get_input(ihid);
508
509         return IRQ_HANDLED;
510 }
511
512 static int i2c_hid_get_report_length(struct hid_report *report)
513 {
514         return ((report->size - 1) >> 3) + 1 +
515                 report->device->report_enum[report->type].numbered + 2;
516 }
517
518 /*
519  * Traverse the supplied list of reports and find the longest
520  */
521 static void i2c_hid_find_max_report(struct hid_device *hid, unsigned int type,
522                 unsigned int *max)
523 {
524         struct hid_report *report;
525         unsigned int size;
526
527         /* We should not rely on wMaxInputLength, as some devices may set it to
528          * a wrong length. */
529         list_for_each_entry(report, &hid->report_enum[type].report_list, list) {
530                 size = i2c_hid_get_report_length(report);
531                 if (*max < size)
532                         *max = size;
533         }
534 }
535
536 static void i2c_hid_free_buffers(struct i2c_hid *ihid)
537 {
538         kfree(ihid->inbuf);
539         kfree(ihid->rawbuf);
540         kfree(ihid->argsbuf);
541         kfree(ihid->cmdbuf);
542         ihid->inbuf = NULL;
543         ihid->rawbuf = NULL;
544         ihid->cmdbuf = NULL;
545         ihid->argsbuf = NULL;
546         ihid->bufsize = 0;
547 }
548
549 static int i2c_hid_alloc_buffers(struct i2c_hid *ihid, size_t report_size)
550 {
551         /* the worst case is computed from the set_report command with a
552          * reportID > 15 and the maximum report length */
553         int args_len = sizeof(__u8) + /* ReportID */
554                        sizeof(__u8) + /* optional ReportID byte */
555                        sizeof(__u16) + /* data register */
556                        sizeof(__u16) + /* size of the report */
557                        report_size; /* report */
558
559         ihid->inbuf = kzalloc(report_size, GFP_KERNEL);
560         ihid->rawbuf = kzalloc(report_size, GFP_KERNEL);
561         ihid->argsbuf = kzalloc(args_len, GFP_KERNEL);
562         ihid->cmdbuf = kzalloc(sizeof(union command) + args_len, GFP_KERNEL);
563
564         if (!ihid->inbuf || !ihid->rawbuf || !ihid->argsbuf || !ihid->cmdbuf) {
565                 i2c_hid_free_buffers(ihid);
566                 return -ENOMEM;
567         }
568
569         ihid->bufsize = report_size;
570
571         return 0;
572 }
573
574 static int i2c_hid_get_raw_report(struct hid_device *hid,
575                 unsigned char report_number, __u8 *buf, size_t count,
576                 unsigned char report_type)
577 {
578         struct i2c_client *client = hid->driver_data;
579         struct i2c_hid *ihid = i2c_get_clientdata(client);
580         size_t ret_count, ask_count;
581         int ret;
582
583         if (report_type == HID_OUTPUT_REPORT)
584                 return -EINVAL;
585
586         /* +2 bytes to include the size of the reply in the query buffer */
587         ask_count = min(count + 2, (size_t)ihid->bufsize);
588
589         ret = i2c_hid_get_report(client,
590                         report_type == HID_FEATURE_REPORT ? 0x03 : 0x01,
591                         report_number, ihid->rawbuf, ask_count);
592
593         if (ret < 0)
594                 return ret;
595
596         ret_count = ihid->rawbuf[0] | (ihid->rawbuf[1] << 8);
597
598         if (ret_count <= 2)
599                 return 0;
600
601         ret_count = min(ret_count, ask_count);
602
603         /* The query buffer contains the size, dropping it in the reply */
604         count = min(count, ret_count - 2);
605         memcpy(buf, ihid->rawbuf + 2, count);
606
607         return count;
608 }
609
610 static int i2c_hid_output_raw_report(struct hid_device *hid, __u8 *buf,
611                 size_t count, unsigned char report_type, bool use_data)
612 {
613         struct i2c_client *client = hid->driver_data;
614         struct i2c_hid *ihid = i2c_get_clientdata(client);
615         int report_id = buf[0];
616         int ret;
617
618         if (report_type == HID_INPUT_REPORT)
619                 return -EINVAL;
620
621         mutex_lock(&ihid->reset_lock);
622
623         if (report_id) {
624                 buf++;
625                 count--;
626         }
627
628         ret = i2c_hid_set_or_send_report(client,
629                                 report_type == HID_FEATURE_REPORT ? 0x03 : 0x02,
630                                 report_id, buf, count, use_data);
631
632         if (report_id && ret >= 0)
633                 ret++; /* add report_id to the number of transfered bytes */
634
635         mutex_unlock(&ihid->reset_lock);
636
637         return ret;
638 }
639
640 static int i2c_hid_output_report(struct hid_device *hid, __u8 *buf,
641                 size_t count)
642 {
643         return i2c_hid_output_raw_report(hid, buf, count, HID_OUTPUT_REPORT,
644                         false);
645 }
646
647 static int i2c_hid_raw_request(struct hid_device *hid, unsigned char reportnum,
648                                __u8 *buf, size_t len, unsigned char rtype,
649                                int reqtype)
650 {
651         switch (reqtype) {
652         case HID_REQ_GET_REPORT:
653                 return i2c_hid_get_raw_report(hid, reportnum, buf, len, rtype);
654         case HID_REQ_SET_REPORT:
655                 if (buf[0] != reportnum)
656                         return -EINVAL;
657                 return i2c_hid_output_raw_report(hid, buf, len, rtype, true);
658         default:
659                 return -EIO;
660         }
661 }
662
663 static int i2c_hid_parse(struct hid_device *hid)
664 {
665         struct i2c_client *client = hid->driver_data;
666         struct i2c_hid *ihid = i2c_get_clientdata(client);
667         struct i2c_hid_desc *hdesc = &ihid->hdesc;
668         unsigned int rsize;
669         char *rdesc;
670         int ret;
671         int tries = 3;
672         char *use_override;
673
674         i2c_hid_dbg(ihid, "entering %s\n", __func__);
675
676         rsize = le16_to_cpu(hdesc->wReportDescLength);
677         if (!rsize || rsize > HID_MAX_DESCRIPTOR_SIZE) {
678                 dbg_hid("weird size of report descriptor (%u)\n", rsize);
679                 return -EINVAL;
680         }
681
682         do {
683                 ret = i2c_hid_hwreset(client);
684                 if (ret)
685                         msleep(1000);
686         } while (tries-- > 0 && ret);
687
688         if (ret)
689                 return ret;
690
691         use_override = i2c_hid_get_dmi_hid_report_desc_override(client->name,
692                                                                 &rsize);
693
694         if (use_override) {
695                 rdesc = use_override;
696                 i2c_hid_dbg(ihid, "Using a HID report descriptor override\n");
697         } else {
698                 rdesc = kzalloc(rsize, GFP_KERNEL);
699
700                 if (!rdesc) {
701                         dbg_hid("couldn't allocate rdesc memory\n");
702                         return -ENOMEM;
703                 }
704
705                 i2c_hid_dbg(ihid, "asking HID report descriptor\n");
706
707                 ret = i2c_hid_command(client, &hid_report_descr_cmd,
708                                       rdesc, rsize);
709                 if (ret) {
710                         hid_err(hid, "reading report descriptor failed\n");
711                         kfree(rdesc);
712                         return -EIO;
713                 }
714         }
715
716         i2c_hid_dbg(ihid, "Report Descriptor: %*ph\n", rsize, rdesc);
717
718         ret = hid_parse_report(hid, rdesc, rsize);
719         if (!use_override)
720                 kfree(rdesc);
721
722         if (ret) {
723                 dbg_hid("parsing report descriptor failed\n");
724                 return ret;
725         }
726
727         return 0;
728 }
729
730 static int i2c_hid_start(struct hid_device *hid)
731 {
732         struct i2c_client *client = hid->driver_data;
733         struct i2c_hid *ihid = i2c_get_clientdata(client);
734         int ret;
735         unsigned int bufsize = HID_MIN_BUFFER_SIZE;
736
737         i2c_hid_find_max_report(hid, HID_INPUT_REPORT, &bufsize);
738         i2c_hid_find_max_report(hid, HID_OUTPUT_REPORT, &bufsize);
739         i2c_hid_find_max_report(hid, HID_FEATURE_REPORT, &bufsize);
740
741         if (bufsize > ihid->bufsize) {
742                 disable_irq(client->irq);
743                 i2c_hid_free_buffers(ihid);
744
745                 ret = i2c_hid_alloc_buffers(ihid, bufsize);
746                 enable_irq(client->irq);
747
748                 if (ret)
749                         return ret;
750         }
751
752         return 0;
753 }
754
755 static void i2c_hid_stop(struct hid_device *hid)
756 {
757         hid->claimed = 0;
758 }
759
760 static int i2c_hid_open(struct hid_device *hid)
761 {
762         struct i2c_client *client = hid->driver_data;
763         struct i2c_hid *ihid = i2c_get_clientdata(client);
764         int ret = 0;
765
766         ret = pm_runtime_get_sync(&client->dev);
767         if (ret < 0)
768                 return ret;
769
770         set_bit(I2C_HID_STARTED, &ihid->flags);
771         return 0;
772 }
773
774 static void i2c_hid_close(struct hid_device *hid)
775 {
776         struct i2c_client *client = hid->driver_data;
777         struct i2c_hid *ihid = i2c_get_clientdata(client);
778
779         clear_bit(I2C_HID_STARTED, &ihid->flags);
780
781         /* Save some power */
782         pm_runtime_put(&client->dev);
783 }
784
785 static int i2c_hid_power(struct hid_device *hid, int lvl)
786 {
787         struct i2c_client *client = hid->driver_data;
788         struct i2c_hid *ihid = i2c_get_clientdata(client);
789
790         i2c_hid_dbg(ihid, "%s lvl:%d\n", __func__, lvl);
791
792         switch (lvl) {
793         case PM_HINT_FULLON:
794                 pm_runtime_get_sync(&client->dev);
795                 break;
796         case PM_HINT_NORMAL:
797                 pm_runtime_put(&client->dev);
798                 break;
799         }
800         return 0;
801 }
802
803 struct hid_ll_driver i2c_hid_ll_driver = {
804         .parse = i2c_hid_parse,
805         .start = i2c_hid_start,
806         .stop = i2c_hid_stop,
807         .open = i2c_hid_open,
808         .close = i2c_hid_close,
809         .power = i2c_hid_power,
810         .output_report = i2c_hid_output_report,
811         .raw_request = i2c_hid_raw_request,
812 };
813 EXPORT_SYMBOL_GPL(i2c_hid_ll_driver);
814
815 static int i2c_hid_init_irq(struct i2c_client *client)
816 {
817         struct i2c_hid *ihid = i2c_get_clientdata(client);
818         unsigned long irqflags = 0;
819         int ret;
820
821         dev_dbg(&client->dev, "Requesting IRQ: %d\n", client->irq);
822
823         if (!irq_get_trigger_type(client->irq))
824                 irqflags = IRQF_TRIGGER_LOW;
825
826         ret = request_threaded_irq(client->irq, NULL, i2c_hid_irq,
827                                    irqflags | IRQF_ONESHOT, client->name, ihid);
828         if (ret < 0) {
829                 dev_warn(&client->dev,
830                         "Could not register for %s interrupt, irq = %d,"
831                         " ret = %d\n",
832                         client->name, client->irq, ret);
833
834                 return ret;
835         }
836
837         return 0;
838 }
839
840 static int i2c_hid_fetch_hid_descriptor(struct i2c_hid *ihid)
841 {
842         struct i2c_client *client = ihid->client;
843         struct i2c_hid_desc *hdesc = &ihid->hdesc;
844         unsigned int dsize;
845         int ret;
846
847         /* i2c hid fetch using a fixed descriptor size (30 bytes) */
848         if (i2c_hid_get_dmi_i2c_hid_desc_override(client->name)) {
849                 i2c_hid_dbg(ihid, "Using a HID descriptor override\n");
850                 ihid->hdesc =
851                         *i2c_hid_get_dmi_i2c_hid_desc_override(client->name);
852         } else {
853                 i2c_hid_dbg(ihid, "Fetching the HID descriptor\n");
854                 ret = i2c_hid_command(client, &hid_descr_cmd,
855                                       ihid->hdesc_buffer,
856                                       sizeof(struct i2c_hid_desc));
857                 if (ret) {
858                         dev_err(&client->dev, "hid_descr_cmd failed\n");
859                         return -ENODEV;
860                 }
861         }
862
863         /* Validate the length of HID descriptor, the 4 first bytes:
864          * bytes 0-1 -> length
865          * bytes 2-3 -> bcdVersion (has to be 1.00) */
866         /* check bcdVersion == 1.0 */
867         if (le16_to_cpu(hdesc->bcdVersion) != 0x0100) {
868                 dev_err(&client->dev,
869                         "unexpected HID descriptor bcdVersion (0x%04hx)\n",
870                         le16_to_cpu(hdesc->bcdVersion));
871                 return -ENODEV;
872         }
873
874         /* Descriptor length should be 30 bytes as per the specification */
875         dsize = le16_to_cpu(hdesc->wHIDDescLength);
876         if (dsize != sizeof(struct i2c_hid_desc)) {
877                 dev_err(&client->dev, "weird size of HID descriptor (%u)\n",
878                         dsize);
879                 return -ENODEV;
880         }
881         i2c_hid_dbg(ihid, "HID Descriptor: %*ph\n", dsize, ihid->hdesc_buffer);
882         return 0;
883 }
884
885 #ifdef CONFIG_ACPI
886 static const struct acpi_device_id i2c_hid_acpi_blacklist[] = {
887         /*
888          * The CHPN0001 ACPI device, which is used to describe the Chipone
889          * ICN8505 controller, has a _CID of PNP0C50 but is not HID compatible.
890          */
891         {"CHPN0001", 0 },
892         { },
893 };
894
895 static int i2c_hid_acpi_pdata(struct i2c_client *client,
896                 struct i2c_hid_platform_data *pdata)
897 {
898         static guid_t i2c_hid_guid =
899                 GUID_INIT(0x3CDFF6F7, 0x4267, 0x4555,
900                           0xAD, 0x05, 0xB3, 0x0A, 0x3D, 0x89, 0x38, 0xDE);
901         union acpi_object *obj;
902         struct acpi_device *adev;
903         acpi_handle handle;
904
905         handle = ACPI_HANDLE(&client->dev);
906         if (!handle || acpi_bus_get_device(handle, &adev)) {
907                 dev_err(&client->dev, "Error could not get ACPI device\n");
908                 return -ENODEV;
909         }
910
911         if (acpi_match_device_ids(adev, i2c_hid_acpi_blacklist) == 0)
912                 return -ENODEV;
913
914         obj = acpi_evaluate_dsm_typed(handle, &i2c_hid_guid, 1, 1, NULL,
915                                       ACPI_TYPE_INTEGER);
916         if (!obj) {
917                 dev_err(&client->dev, "Error _DSM call to get HID descriptor address failed\n");
918                 return -ENODEV;
919         }
920
921         pdata->hid_descriptor_address = obj->integer.value;
922         ACPI_FREE(obj);
923
924         return 0;
925 }
926
927 static void i2c_hid_acpi_fix_up_power(struct device *dev)
928 {
929         struct acpi_device *adev;
930
931         adev = ACPI_COMPANION(dev);
932         if (adev)
933                 acpi_device_fix_up_power(adev);
934 }
935
936 static const struct acpi_device_id i2c_hid_acpi_match[] = {
937         {"ACPI0C50", 0 },
938         {"PNP0C50", 0 },
939         { },
940 };
941 MODULE_DEVICE_TABLE(acpi, i2c_hid_acpi_match);
942 #else
943 static inline int i2c_hid_acpi_pdata(struct i2c_client *client,
944                 struct i2c_hid_platform_data *pdata)
945 {
946         return -ENODEV;
947 }
948
949 static inline void i2c_hid_acpi_fix_up_power(struct device *dev) {}
950 #endif
951
952 #ifdef CONFIG_OF
953 static int i2c_hid_of_probe(struct i2c_client *client,
954                 struct i2c_hid_platform_data *pdata)
955 {
956         struct device *dev = &client->dev;
957         u32 val;
958         int ret;
959
960         ret = of_property_read_u32(dev->of_node, "hid-descr-addr", &val);
961         if (ret) {
962                 dev_err(&client->dev, "HID register address not provided\n");
963                 return -ENODEV;
964         }
965         if (val >> 16) {
966                 dev_err(&client->dev, "Bad HID register address: 0x%08x\n",
967                         val);
968                 return -EINVAL;
969         }
970         pdata->hid_descriptor_address = val;
971
972         return 0;
973 }
974
975 static const struct of_device_id i2c_hid_of_match[] = {
976         { .compatible = "hid-over-i2c" },
977         {},
978 };
979 MODULE_DEVICE_TABLE(of, i2c_hid_of_match);
980 #else
981 static inline int i2c_hid_of_probe(struct i2c_client *client,
982                 struct i2c_hid_platform_data *pdata)
983 {
984         return -ENODEV;
985 }
986 #endif
987
988 static void i2c_hid_fwnode_probe(struct i2c_client *client,
989                                  struct i2c_hid_platform_data *pdata)
990 {
991         u32 val;
992
993         if (!device_property_read_u32(&client->dev, "post-power-on-delay-ms",
994                                       &val))
995                 pdata->post_power_delay_ms = val;
996 }
997
998 static int i2c_hid_probe(struct i2c_client *client,
999                          const struct i2c_device_id *dev_id)
1000 {
1001         int ret;
1002         struct i2c_hid *ihid;
1003         struct hid_device *hid;
1004         __u16 hidRegister;
1005         struct i2c_hid_platform_data *platform_data = client->dev.platform_data;
1006
1007         dbg_hid("HID probe called for i2c 0x%02x\n", client->addr);
1008
1009         if (!client->irq) {
1010                 dev_err(&client->dev,
1011                         "HID over i2c has not been provided an Int IRQ\n");
1012                 return -EINVAL;
1013         }
1014
1015         if (client->irq < 0) {
1016                 if (client->irq != -EPROBE_DEFER)
1017                         dev_err(&client->dev,
1018                                 "HID over i2c doesn't have a valid IRQ\n");
1019                 return client->irq;
1020         }
1021
1022         ihid = devm_kzalloc(&client->dev, sizeof(*ihid), GFP_KERNEL);
1023         if (!ihid)
1024                 return -ENOMEM;
1025
1026         if (client->dev.of_node) {
1027                 ret = i2c_hid_of_probe(client, &ihid->pdata);
1028                 if (ret)
1029                         return ret;
1030         } else if (!platform_data) {
1031                 ret = i2c_hid_acpi_pdata(client, &ihid->pdata);
1032                 if (ret)
1033                         return ret;
1034         } else {
1035                 ihid->pdata = *platform_data;
1036         }
1037
1038         /* Parse platform agnostic common properties from ACPI / device tree */
1039         i2c_hid_fwnode_probe(client, &ihid->pdata);
1040
1041         ihid->pdata.supplies[0].supply = "vdd";
1042         ihid->pdata.supplies[1].supply = "vddl";
1043
1044         ret = devm_regulator_bulk_get(&client->dev,
1045                                       ARRAY_SIZE(ihid->pdata.supplies),
1046                                       ihid->pdata.supplies);
1047         if (ret)
1048                 return ret;
1049
1050         ret = regulator_bulk_enable(ARRAY_SIZE(ihid->pdata.supplies),
1051                                     ihid->pdata.supplies);
1052         if (ret < 0)
1053                 return ret;
1054
1055         if (ihid->pdata.post_power_delay_ms)
1056                 msleep(ihid->pdata.post_power_delay_ms);
1057
1058         i2c_set_clientdata(client, ihid);
1059
1060         ihid->client = client;
1061
1062         hidRegister = ihid->pdata.hid_descriptor_address;
1063         ihid->wHIDDescRegister = cpu_to_le16(hidRegister);
1064
1065         init_waitqueue_head(&ihid->wait);
1066         mutex_init(&ihid->reset_lock);
1067
1068         /* we need to allocate the command buffer without knowing the maximum
1069          * size of the reports. Let's use HID_MIN_BUFFER_SIZE, then we do the
1070          * real computation later. */
1071         ret = i2c_hid_alloc_buffers(ihid, HID_MIN_BUFFER_SIZE);
1072         if (ret < 0)
1073                 goto err_regulator;
1074
1075         i2c_hid_acpi_fix_up_power(&client->dev);
1076
1077         pm_runtime_get_noresume(&client->dev);
1078         pm_runtime_set_active(&client->dev);
1079         pm_runtime_enable(&client->dev);
1080         device_enable_async_suspend(&client->dev);
1081
1082         /* Make sure there is something at this address */
1083         ret = i2c_smbus_read_byte(client);
1084         if (ret < 0) {
1085                 dev_dbg(&client->dev, "nothing at this address: %d\n", ret);
1086                 ret = -ENXIO;
1087                 goto err_pm;
1088         }
1089
1090         ret = i2c_hid_fetch_hid_descriptor(ihid);
1091         if (ret < 0)
1092                 goto err_pm;
1093
1094         ret = i2c_hid_init_irq(client);
1095         if (ret < 0)
1096                 goto err_pm;
1097
1098         hid = hid_allocate_device();
1099         if (IS_ERR(hid)) {
1100                 ret = PTR_ERR(hid);
1101                 goto err_irq;
1102         }
1103
1104         ihid->hid = hid;
1105
1106         hid->driver_data = client;
1107         hid->ll_driver = &i2c_hid_ll_driver;
1108         hid->dev.parent = &client->dev;
1109         hid->bus = BUS_I2C;
1110         hid->version = le16_to_cpu(ihid->hdesc.bcdVersion);
1111         hid->vendor = le16_to_cpu(ihid->hdesc.wVendorID);
1112         hid->product = le16_to_cpu(ihid->hdesc.wProductID);
1113
1114         snprintf(hid->name, sizeof(hid->name), "%s %04hX:%04hX",
1115                  client->name, hid->vendor, hid->product);
1116         strlcpy(hid->phys, dev_name(&client->dev), sizeof(hid->phys));
1117
1118         ihid->quirks = i2c_hid_lookup_quirk(hid->vendor, hid->product);
1119
1120         ret = hid_add_device(hid);
1121         if (ret) {
1122                 if (ret != -ENODEV)
1123                         hid_err(client, "can't add hid device: %d\n", ret);
1124                 goto err_mem_free;
1125         }
1126
1127         if (!(ihid->quirks & I2C_HID_QUIRK_NO_RUNTIME_PM))
1128                 pm_runtime_put(&client->dev);
1129
1130         return 0;
1131
1132 err_mem_free:
1133         hid_destroy_device(hid);
1134
1135 err_irq:
1136         free_irq(client->irq, ihid);
1137
1138 err_pm:
1139         pm_runtime_put_noidle(&client->dev);
1140         pm_runtime_disable(&client->dev);
1141
1142 err_regulator:
1143         regulator_bulk_disable(ARRAY_SIZE(ihid->pdata.supplies),
1144                                ihid->pdata.supplies);
1145         i2c_hid_free_buffers(ihid);
1146         return ret;
1147 }
1148
1149 static int i2c_hid_remove(struct i2c_client *client)
1150 {
1151         struct i2c_hid *ihid = i2c_get_clientdata(client);
1152         struct hid_device *hid;
1153
1154         if (!(ihid->quirks & I2C_HID_QUIRK_NO_RUNTIME_PM))
1155                 pm_runtime_get_sync(&client->dev);
1156         pm_runtime_disable(&client->dev);
1157         pm_runtime_set_suspended(&client->dev);
1158         pm_runtime_put_noidle(&client->dev);
1159
1160         hid = ihid->hid;
1161         hid_destroy_device(hid);
1162
1163         free_irq(client->irq, ihid);
1164
1165         if (ihid->bufsize)
1166                 i2c_hid_free_buffers(ihid);
1167
1168         regulator_bulk_disable(ARRAY_SIZE(ihid->pdata.supplies),
1169                                ihid->pdata.supplies);
1170
1171         return 0;
1172 }
1173
1174 static void i2c_hid_shutdown(struct i2c_client *client)
1175 {
1176         struct i2c_hid *ihid = i2c_get_clientdata(client);
1177
1178         i2c_hid_set_power(client, I2C_HID_PWR_SLEEP);
1179         free_irq(client->irq, ihid);
1180 }
1181
1182 #ifdef CONFIG_PM_SLEEP
1183 static int i2c_hid_suspend(struct device *dev)
1184 {
1185         struct i2c_client *client = to_i2c_client(dev);
1186         struct i2c_hid *ihid = i2c_get_clientdata(client);
1187         struct hid_device *hid = ihid->hid;
1188         int ret;
1189         int wake_status;
1190
1191         if (hid->driver && hid->driver->suspend) {
1192                 /*
1193                  * Wake up the device so that IO issues in
1194                  * HID driver's suspend code can succeed.
1195                  */
1196                 ret = pm_runtime_resume(dev);
1197                 if (ret < 0)
1198                         return ret;
1199
1200                 ret = hid->driver->suspend(hid, PMSG_SUSPEND);
1201                 if (ret < 0)
1202                         return ret;
1203         }
1204
1205         if (!pm_runtime_suspended(dev)) {
1206                 /* Save some power */
1207                 i2c_hid_set_power(client, I2C_HID_PWR_SLEEP);
1208
1209                 disable_irq(client->irq);
1210         }
1211
1212         if (device_may_wakeup(&client->dev)) {
1213                 wake_status = enable_irq_wake(client->irq);
1214                 if (!wake_status)
1215                         ihid->irq_wake_enabled = true;
1216                 else
1217                         hid_warn(hid, "Failed to enable irq wake: %d\n",
1218                                 wake_status);
1219         } else {
1220                 regulator_bulk_disable(ARRAY_SIZE(ihid->pdata.supplies),
1221                                        ihid->pdata.supplies);
1222         }
1223
1224         return 0;
1225 }
1226
1227 static int i2c_hid_resume(struct device *dev)
1228 {
1229         int ret;
1230         struct i2c_client *client = to_i2c_client(dev);
1231         struct i2c_hid *ihid = i2c_get_clientdata(client);
1232         struct hid_device *hid = ihid->hid;
1233         int wake_status;
1234
1235         if (!device_may_wakeup(&client->dev)) {
1236                 ret = regulator_bulk_enable(ARRAY_SIZE(ihid->pdata.supplies),
1237                                             ihid->pdata.supplies);
1238                 if (ret)
1239                         hid_warn(hid, "Failed to enable supplies: %d\n", ret);
1240
1241                 if (ihid->pdata.post_power_delay_ms)
1242                         msleep(ihid->pdata.post_power_delay_ms);
1243         } else if (ihid->irq_wake_enabled) {
1244                 wake_status = disable_irq_wake(client->irq);
1245                 if (!wake_status)
1246                         ihid->irq_wake_enabled = false;
1247                 else
1248                         hid_warn(hid, "Failed to disable irq wake: %d\n",
1249                                 wake_status);
1250         }
1251
1252         /* We'll resume to full power */
1253         pm_runtime_disable(dev);
1254         pm_runtime_set_active(dev);
1255         pm_runtime_enable(dev);
1256
1257         enable_irq(client->irq);
1258
1259         /* Instead of resetting device, simply powers the device on. This
1260          * solves "incomplete reports" on Raydium devices 2386:3118 and
1261          * 2386:4B33 and fixes various SIS touchscreens no longer sending
1262          * data after a suspend/resume.
1263          */
1264         ret = i2c_hid_set_power(client, I2C_HID_PWR_ON);
1265         if (ret)
1266                 return ret;
1267
1268         if (hid->driver && hid->driver->reset_resume) {
1269                 ret = hid->driver->reset_resume(hid);
1270                 return ret;
1271         }
1272
1273         return 0;
1274 }
1275 #endif
1276
1277 #ifdef CONFIG_PM
1278 static int i2c_hid_runtime_suspend(struct device *dev)
1279 {
1280         struct i2c_client *client = to_i2c_client(dev);
1281
1282         i2c_hid_set_power(client, I2C_HID_PWR_SLEEP);
1283         disable_irq(client->irq);
1284         return 0;
1285 }
1286
1287 static int i2c_hid_runtime_resume(struct device *dev)
1288 {
1289         struct i2c_client *client = to_i2c_client(dev);
1290
1291         enable_irq(client->irq);
1292         i2c_hid_set_power(client, I2C_HID_PWR_ON);
1293         return 0;
1294 }
1295 #endif
1296
1297 static const struct dev_pm_ops i2c_hid_pm = {
1298         SET_SYSTEM_SLEEP_PM_OPS(i2c_hid_suspend, i2c_hid_resume)
1299         SET_RUNTIME_PM_OPS(i2c_hid_runtime_suspend, i2c_hid_runtime_resume,
1300                            NULL)
1301 };
1302
1303 static const struct i2c_device_id i2c_hid_id_table[] = {
1304         { "hid", 0 },
1305         { "hid-over-i2c", 0 },
1306         { },
1307 };
1308 MODULE_DEVICE_TABLE(i2c, i2c_hid_id_table);
1309
1310
1311 static struct i2c_driver i2c_hid_driver = {
1312         .driver = {
1313                 .name   = "i2c_hid",
1314                 .pm     = &i2c_hid_pm,
1315                 .acpi_match_table = ACPI_PTR(i2c_hid_acpi_match),
1316                 .of_match_table = of_match_ptr(i2c_hid_of_match),
1317         },
1318
1319         .probe          = i2c_hid_probe,
1320         .remove         = i2c_hid_remove,
1321         .shutdown       = i2c_hid_shutdown,
1322         .id_table       = i2c_hid_id_table,
1323 };
1324
1325 module_i2c_driver(i2c_hid_driver);
1326
1327 MODULE_DESCRIPTION("HID over I2C core driver");
1328 MODULE_AUTHOR("Benjamin Tissoires <benjamin.tissoires@gmail.com>");
1329 MODULE_LICENSE("GPL");