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