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