57f109bc8ec96a7d248ee148ce2fcdc5f4058257
[platform/kernel/linux-rpi.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/device.h>
30 #include <linux/wait.h>
31 #include <linux/err.h>
32 #include <linux/string.h>
33 #include <linux/list.h>
34 #include <linux/jiffies.h>
35 #include <linux/kernel.h>
36 #include <linux/hid.h>
37 #include <linux/mutex.h>
38
39 #include "../hid-ids.h"
40 #include "i2c-hid.h"
41
42 /* quirks to control the device */
43 #define I2C_HID_QUIRK_SET_PWR_WAKEUP_DEV        BIT(0)
44 #define I2C_HID_QUIRK_NO_IRQ_AFTER_RESET        BIT(1)
45 #define I2C_HID_QUIRK_BOGUS_IRQ                 BIT(4)
46 #define I2C_HID_QUIRK_RESET_ON_RESUME           BIT(5)
47 #define I2C_HID_QUIRK_BAD_INPUT_SIZE            BIT(6)
48 #define I2C_HID_QUIRK_NO_WAKEUP_AFTER_RESET     BIT(7)
49
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 };
92
93 union command {
94         u8 data[0];
95         struct cmd {
96                 __le16 reg;
97                 __u8 reportTypeID;
98                 __u8 opcode;
99                 __u8 reportID;
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 static const struct i2c_hid_cmd hid_get_report_cmd =    { I2C_HID_CMD(0x02) };
118 static const struct i2c_hid_cmd hid_set_report_cmd =    { I2C_HID_CMD(0x03) };
119 static const struct i2c_hid_cmd hid_set_power_cmd =     { I2C_HID_CMD(0x08) };
120 static const struct i2c_hid_cmd hid_no_cmd =            { .length = 0 };
121
122 /*
123  * These definitions are not used here, but are defined by the spec.
124  * Keeping them here for documentation purposes.
125  *
126  * static const struct i2c_hid_cmd hid_get_idle_cmd = { I2C_HID_CMD(0x04) };
127  * static const struct i2c_hid_cmd hid_set_idle_cmd = { I2C_HID_CMD(0x05) };
128  * static const struct i2c_hid_cmd hid_get_protocol_cmd = { I2C_HID_CMD(0x06) };
129  * static const struct i2c_hid_cmd hid_set_protocol_cmd = { I2C_HID_CMD(0x07) };
130  */
131
132 /* The main device structure */
133 struct i2c_hid {
134         struct i2c_client       *client;        /* i2c client */
135         struct hid_device       *hid;   /* pointer to corresponding HID dev */
136         union {
137                 __u8 hdesc_buffer[sizeof(struct i2c_hid_desc)];
138                 struct i2c_hid_desc hdesc;      /* the HID Descriptor */
139         };
140         __le16                  wHIDDescRegister; /* location of the i2c
141                                                    * register of the HID
142                                                    * descriptor. */
143         unsigned int            bufsize;        /* i2c buffer size */
144         u8                      *inbuf;         /* Input buffer */
145         u8                      *rawbuf;        /* Raw Input buffer */
146         u8                      *cmdbuf;        /* Command buffer */
147         u8                      *argsbuf;       /* Command arguments buffer */
148
149         unsigned long           flags;          /* device flags */
150         unsigned long           quirks;         /* Various quirks */
151
152         wait_queue_head_t       wait;           /* For waiting the interrupt */
153
154         bool                    irq_wake_enabled;
155         struct mutex            reset_lock;
156
157         struct i2chid_ops       *ops;
158 };
159
160 static const struct i2c_hid_quirks {
161         __u16 idVendor;
162         __u16 idProduct;
163         __u32 quirks;
164 } i2c_hid_quirks[] = {
165         { USB_VENDOR_ID_WEIDA, HID_ANY_ID,
166                 I2C_HID_QUIRK_SET_PWR_WAKEUP_DEV },
167         { I2C_VENDOR_ID_HANTICK, I2C_PRODUCT_ID_HANTICK_5288,
168                 I2C_HID_QUIRK_NO_IRQ_AFTER_RESET },
169         { I2C_VENDOR_ID_ITE, I2C_DEVICE_ID_ITE_VOYO_WINPAD_A15,
170                 I2C_HID_QUIRK_NO_IRQ_AFTER_RESET },
171         { I2C_VENDOR_ID_RAYDIUM, I2C_PRODUCT_ID_RAYDIUM_3118,
172                 I2C_HID_QUIRK_NO_IRQ_AFTER_RESET },
173         { USB_VENDOR_ID_ALPS_JP, HID_ANY_ID,
174                  I2C_HID_QUIRK_RESET_ON_RESUME },
175         { I2C_VENDOR_ID_SYNAPTICS, I2C_PRODUCT_ID_SYNAPTICS_SYNA2393,
176                  I2C_HID_QUIRK_RESET_ON_RESUME },
177         { USB_VENDOR_ID_ITE, I2C_DEVICE_ID_ITE_LENOVO_LEGION_Y720,
178                 I2C_HID_QUIRK_BAD_INPUT_SIZE },
179         /*
180          * Sending the wakeup after reset actually break ELAN touchscreen controller
181          */
182         { USB_VENDOR_ID_ELAN, HID_ANY_ID,
183                  I2C_HID_QUIRK_NO_WAKEUP_AFTER_RESET |
184                  I2C_HID_QUIRK_BOGUS_IRQ },
185         { 0, 0 }
186 };
187
188 /*
189  * i2c_hid_lookup_quirk: return any quirks associated with a I2C HID device
190  * @idVendor: the 16-bit vendor ID
191  * @idProduct: the 16-bit product ID
192  *
193  * Returns: a u32 quirks value.
194  */
195 static u32 i2c_hid_lookup_quirk(const u16 idVendor, const u16 idProduct)
196 {
197         u32 quirks = 0;
198         int n;
199
200         for (n = 0; i2c_hid_quirks[n].idVendor; n++)
201                 if (i2c_hid_quirks[n].idVendor == idVendor &&
202                     (i2c_hid_quirks[n].idProduct == (__u16)HID_ANY_ID ||
203                      i2c_hid_quirks[n].idProduct == idProduct))
204                         quirks = i2c_hid_quirks[n].quirks;
205
206         return quirks;
207 }
208
209 static int __i2c_hid_command(struct i2c_hid *ihid,
210                 const struct i2c_hid_cmd *command, u8 reportID,
211                 u8 reportType, u8 *args, int args_len,
212                 unsigned char *buf_recv, int data_len)
213 {
214         struct i2c_client *client = ihid->client;
215         union command *cmd = (union command *)ihid->cmdbuf;
216         int ret;
217         struct i2c_msg msg[2];
218         int msg_num = 1;
219
220         int length = command->length;
221         unsigned int registerIndex = command->registerIndex;
222
223         /* special case for hid_descr_cmd */
224         if (command == &hid_descr_cmd) {
225                 cmd->c.reg = ihid->wHIDDescRegister;
226         } else {
227                 cmd->data[0] = ihid->hdesc_buffer[registerIndex];
228                 cmd->data[1] = ihid->hdesc_buffer[registerIndex + 1];
229         }
230
231         if (length > 2) {
232                 cmd->c.opcode = command->opcode;
233                 if (reportID < 0x0F) {
234                         cmd->c.reportTypeID = reportType << 4 | reportID;
235                 } else {
236                         cmd->c.reportTypeID = reportType << 4 | 0x0F;
237                         cmd->c.reportID = reportID;
238                         length++;
239                 }
240         }
241
242         memcpy(cmd->data + length, args, args_len);
243         length += args_len;
244
245         i2c_hid_dbg(ihid, "%s: cmd=%*ph\n", __func__, length, cmd->data);
246
247         msg[0].addr = client->addr;
248         msg[0].flags = client->flags & I2C_M_TEN;
249         msg[0].len = length;
250         msg[0].buf = cmd->data;
251         if (data_len > 0) {
252                 msg[1].addr = client->addr;
253                 msg[1].flags = client->flags & I2C_M_TEN;
254                 msg[1].flags |= I2C_M_RD;
255                 msg[1].len = data_len;
256                 msg[1].buf = buf_recv;
257                 msg_num = 2;
258                 set_bit(I2C_HID_READ_PENDING, &ihid->flags);
259         }
260
261         ret = i2c_transfer(client->adapter, msg, msg_num);
262
263         if (data_len > 0)
264                 clear_bit(I2C_HID_READ_PENDING, &ihid->flags);
265
266         if (ret != msg_num)
267                 return ret < 0 ? ret : -EIO;
268
269         return 0;
270 }
271
272 static int i2c_hid_command(struct i2c_hid *ihid,
273                 const struct i2c_hid_cmd *command,
274                 unsigned char *buf_recv, int data_len)
275 {
276         return __i2c_hid_command(ihid, command, 0, 0, NULL, 0,
277                                 buf_recv, data_len);
278 }
279
280 static int i2c_hid_get_report(struct i2c_hid *ihid, u8 reportType,
281                 u8 reportID, unsigned char *buf_recv, int data_len)
282 {
283         u8 args[2];
284         int ret;
285         int args_len = 0;
286         u16 readRegister = le16_to_cpu(ihid->hdesc.wDataRegister);
287
288         i2c_hid_dbg(ihid, "%s\n", __func__);
289
290         args[args_len++] = readRegister & 0xFF;
291         args[args_len++] = readRegister >> 8;
292
293         ret = __i2c_hid_command(ihid, &hid_get_report_cmd, reportID,
294                 reportType, args, args_len, buf_recv, data_len);
295         if (ret) {
296                 dev_err(&ihid->client->dev,
297                         "failed to retrieve report from device.\n");
298                 return ret;
299         }
300
301         return 0;
302 }
303
304 /**
305  * i2c_hid_set_or_send_report: forward an incoming report to the device
306  * @ihid: the i2c hid device
307  * @reportType: 0x03 for HID_FEATURE_REPORT ; 0x02 for HID_OUTPUT_REPORT
308  * @reportID: the report ID
309  * @buf: the actual data to transfer, without the report ID
310  * @data_len: size of buf
311  * @use_data: true: use SET_REPORT HID command, false: send plain OUTPUT report
312  */
313 static int i2c_hid_set_or_send_report(struct i2c_hid *ihid, u8 reportType,
314                 u8 reportID, unsigned char *buf, size_t data_len, bool use_data)
315 {
316         u8 *args = ihid->argsbuf;
317         const struct i2c_hid_cmd *hidcmd;
318         int ret;
319         u16 dataRegister = le16_to_cpu(ihid->hdesc.wDataRegister);
320         u16 outputRegister = le16_to_cpu(ihid->hdesc.wOutputRegister);
321         u16 maxOutputLength = le16_to_cpu(ihid->hdesc.wMaxOutputLength);
322         u16 size;
323         int args_len;
324         int index = 0;
325
326         i2c_hid_dbg(ihid, "%s\n", __func__);
327
328         if (data_len > ihid->bufsize)
329                 return -EINVAL;
330
331         size =          2                       /* size */ +
332                         (reportID ? 1 : 0)      /* reportID */ +
333                         data_len                /* buf */;
334         args_len =      2                       /* dataRegister */ +
335                         size                    /* args */;
336
337         if (!use_data && maxOutputLength == 0)
338                 return -ENOSYS;
339
340         /*
341          * use the data register for feature reports or if the device does not
342          * support the output register
343          */
344         if (use_data) {
345                 args[index++] = dataRegister & 0xFF;
346                 args[index++] = dataRegister >> 8;
347                 hidcmd = &hid_set_report_cmd;
348         } else {
349                 args[index++] = outputRegister & 0xFF;
350                 args[index++] = outputRegister >> 8;
351                 hidcmd = &hid_no_cmd;
352         }
353
354         args[index++] = size & 0xFF;
355         args[index++] = size >> 8;
356
357         if (reportID)
358                 args[index++] = reportID;
359
360         memcpy(&args[index], buf, data_len);
361
362         ret = __i2c_hid_command(ihid, hidcmd, reportID,
363                 reportType, args, args_len, NULL, 0);
364         if (ret) {
365                 dev_err(&ihid->client->dev,
366                         "failed to set a report to device.\n");
367                 return ret;
368         }
369
370         return data_len;
371 }
372
373 static int i2c_hid_set_power(struct i2c_hid *ihid, int power_state)
374 {
375         int ret;
376
377         i2c_hid_dbg(ihid, "%s\n", __func__);
378
379         /*
380          * Some devices require to send a command to wakeup before power on.
381          * The call will get a return value (EREMOTEIO) but device will be
382          * triggered and activated. After that, it goes like a normal device.
383          */
384         if (power_state == I2C_HID_PWR_ON &&
385             ihid->quirks & I2C_HID_QUIRK_SET_PWR_WAKEUP_DEV) {
386                 ret = i2c_hid_command(ihid, &hid_set_power_cmd, NULL, 0);
387
388                 /* Device was already activated */
389                 if (!ret)
390                         goto set_pwr_exit;
391         }
392
393         ret = __i2c_hid_command(ihid, &hid_set_power_cmd, power_state,
394                 0, NULL, 0, NULL, 0);
395         if (ret)
396                 dev_err(&ihid->client->dev,
397                         "failed to change power setting.\n");
398
399 set_pwr_exit:
400
401         /*
402          * The HID over I2C specification states that if a DEVICE needs time
403          * after the PWR_ON request, it should utilise CLOCK stretching.
404          * However, it has been observered that the Windows driver provides a
405          * 1ms sleep between the PWR_ON and RESET requests.
406          * According to Goodix Windows even waits 60 ms after (other?)
407          * PWR_ON requests. Testing has confirmed that several devices
408          * will not work properly without a delay after a PWR_ON request.
409          */
410         if (!ret && power_state == I2C_HID_PWR_ON)
411                 msleep(60);
412
413         return ret;
414 }
415
416 static int i2c_hid_execute_reset(struct i2c_hid *ihid)
417 {
418         int ret;
419
420         i2c_hid_dbg(ihid, "resetting...\n");
421
422         set_bit(I2C_HID_RESET_PENDING, &ihid->flags);
423
424         ret = i2c_hid_command(ihid, &hid_reset_cmd, NULL, 0);
425         if (ret) {
426                 dev_err(&ihid->client->dev, "failed to reset device.\n");
427                 goto out;
428         }
429
430         if (ihid->quirks & I2C_HID_QUIRK_NO_IRQ_AFTER_RESET) {
431                 msleep(100);
432                 goto out;
433         }
434
435         i2c_hid_dbg(ihid, "%s: waiting...\n", __func__);
436         if (!wait_event_timeout(ihid->wait,
437                                 !test_bit(I2C_HID_RESET_PENDING, &ihid->flags),
438                                 msecs_to_jiffies(5000))) {
439                 ret = -ENODATA;
440                 goto out;
441         }
442         i2c_hid_dbg(ihid, "%s: finished.\n", __func__);
443
444 out:
445         clear_bit(I2C_HID_RESET_PENDING, &ihid->flags);
446         return ret;
447 }
448
449 static int i2c_hid_hwreset(struct i2c_hid *ihid)
450 {
451         int ret;
452
453         i2c_hid_dbg(ihid, "%s\n", __func__);
454
455         /*
456          * This prevents sending feature reports while the device is
457          * being reset. Otherwise we may lose the reset complete
458          * interrupt.
459          */
460         mutex_lock(&ihid->reset_lock);
461
462         ret = i2c_hid_set_power(ihid, I2C_HID_PWR_ON);
463         if (ret)
464                 goto out_unlock;
465
466         ret = i2c_hid_execute_reset(ihid);
467         if (ret) {
468                 dev_err(&ihid->client->dev,
469                         "failed to reset device: %d\n", ret);
470                 i2c_hid_set_power(ihid, I2C_HID_PWR_SLEEP);
471                 goto out_unlock;
472         }
473
474         /* At least some SIS devices need this after reset */
475         if (!(ihid->quirks & I2C_HID_QUIRK_NO_WAKEUP_AFTER_RESET))
476                 ret = i2c_hid_set_power(ihid, I2C_HID_PWR_ON);
477
478 out_unlock:
479         mutex_unlock(&ihid->reset_lock);
480         return ret;
481 }
482
483 static void i2c_hid_get_input(struct i2c_hid *ihid)
484 {
485         int ret;
486         u32 ret_size;
487         int size = le16_to_cpu(ihid->hdesc.wMaxInputLength);
488
489         if (size > ihid->bufsize)
490                 size = ihid->bufsize;
491
492         ret = i2c_master_recv(ihid->client, ihid->inbuf, size);
493         if (ret != size) {
494                 if (ret < 0)
495                         return;
496
497                 dev_err(&ihid->client->dev, "%s: got %d data instead of %d\n",
498                         __func__, ret, size);
499                 return;
500         }
501
502         ret_size = ihid->inbuf[0] | ihid->inbuf[1] << 8;
503
504         if (!ret_size) {
505                 /* host or device initiated RESET completed */
506                 if (test_and_clear_bit(I2C_HID_RESET_PENDING, &ihid->flags))
507                         wake_up(&ihid->wait);
508                 return;
509         }
510
511         if (ihid->quirks & I2C_HID_QUIRK_BOGUS_IRQ && ret_size == 0xffff) {
512                 dev_warn_once(&ihid->client->dev, "%s: IRQ triggered but "
513                               "there's no data\n", __func__);
514                 return;
515         }
516
517         if ((ret_size > size) || (ret_size < 2)) {
518                 if (ihid->quirks & I2C_HID_QUIRK_BAD_INPUT_SIZE) {
519                         ihid->inbuf[0] = size & 0xff;
520                         ihid->inbuf[1] = size >> 8;
521                         ret_size = size;
522                 } else {
523                         dev_err(&ihid->client->dev, "%s: incomplete report (%d/%d)\n",
524                                 __func__, size, ret_size);
525                         return;
526                 }
527         }
528
529         i2c_hid_dbg(ihid, "input: %*ph\n", ret_size, ihid->inbuf);
530
531         if (test_bit(I2C_HID_STARTED, &ihid->flags)) {
532                 pm_wakeup_event(&ihid->client->dev, 0);
533
534                 hid_input_report(ihid->hid, HID_INPUT_REPORT, ihid->inbuf + 2,
535                                 ret_size - 2, 1);
536         }
537
538         return;
539 }
540
541 static irqreturn_t i2c_hid_irq(int irq, void *dev_id)
542 {
543         struct i2c_hid *ihid = dev_id;
544
545         if (test_bit(I2C_HID_READ_PENDING, &ihid->flags))
546                 return IRQ_HANDLED;
547
548         i2c_hid_get_input(ihid);
549
550         return IRQ_HANDLED;
551 }
552
553 static int i2c_hid_get_report_length(struct hid_report *report)
554 {
555         return ((report->size - 1) >> 3) + 1 +
556                 report->device->report_enum[report->type].numbered + 2;
557 }
558
559 /*
560  * Traverse the supplied list of reports and find the longest
561  */
562 static void i2c_hid_find_max_report(struct hid_device *hid, unsigned int type,
563                 unsigned int *max)
564 {
565         struct hid_report *report;
566         unsigned int size;
567
568         /* We should not rely on wMaxInputLength, as some devices may set it to
569          * a wrong length. */
570         list_for_each_entry(report, &hid->report_enum[type].report_list, list) {
571                 size = i2c_hid_get_report_length(report);
572                 if (*max < size)
573                         *max = size;
574         }
575 }
576
577 static void i2c_hid_free_buffers(struct i2c_hid *ihid)
578 {
579         kfree(ihid->inbuf);
580         kfree(ihid->rawbuf);
581         kfree(ihid->argsbuf);
582         kfree(ihid->cmdbuf);
583         ihid->inbuf = NULL;
584         ihid->rawbuf = NULL;
585         ihid->cmdbuf = NULL;
586         ihid->argsbuf = NULL;
587         ihid->bufsize = 0;
588 }
589
590 static int i2c_hid_alloc_buffers(struct i2c_hid *ihid, size_t report_size)
591 {
592         /* the worst case is computed from the set_report command with a
593          * reportID > 15 and the maximum report length */
594         int args_len = sizeof(__u8) + /* ReportID */
595                        sizeof(__u8) + /* optional ReportID byte */
596                        sizeof(__u16) + /* data register */
597                        sizeof(__u16) + /* size of the report */
598                        report_size; /* report */
599
600         ihid->inbuf = kzalloc(report_size, GFP_KERNEL);
601         ihid->rawbuf = kzalloc(report_size, GFP_KERNEL);
602         ihid->argsbuf = kzalloc(args_len, GFP_KERNEL);
603         ihid->cmdbuf = kzalloc(sizeof(union command) + args_len, GFP_KERNEL);
604
605         if (!ihid->inbuf || !ihid->rawbuf || !ihid->argsbuf || !ihid->cmdbuf) {
606                 i2c_hid_free_buffers(ihid);
607                 return -ENOMEM;
608         }
609
610         ihid->bufsize = report_size;
611
612         return 0;
613 }
614
615 static int i2c_hid_get_raw_report(struct hid_device *hid,
616                 unsigned char report_number, __u8 *buf, size_t count,
617                 unsigned char report_type)
618 {
619         struct i2c_client *client = hid->driver_data;
620         struct i2c_hid *ihid = i2c_get_clientdata(client);
621         size_t ret_count, ask_count;
622         int ret;
623
624         if (report_type == HID_OUTPUT_REPORT)
625                 return -EINVAL;
626
627         /*
628          * In case of unnumbered reports the response from the device will
629          * not have the report ID that the upper layers expect, so we need
630          * to stash it the buffer ourselves and adjust the data size.
631          */
632         if (!report_number) {
633                 buf[0] = 0;
634                 buf++;
635                 count--;
636         }
637
638         /* +2 bytes to include the size of the reply in the query buffer */
639         ask_count = min(count + 2, (size_t)ihid->bufsize);
640
641         ret = i2c_hid_get_report(ihid,
642                         report_type == HID_FEATURE_REPORT ? 0x03 : 0x01,
643                         report_number, ihid->rawbuf, ask_count);
644
645         if (ret < 0)
646                 return ret;
647
648         ret_count = ihid->rawbuf[0] | (ihid->rawbuf[1] << 8);
649
650         if (ret_count <= 2)
651                 return 0;
652
653         ret_count = min(ret_count, ask_count);
654
655         /* The query buffer contains the size, dropping it in the reply */
656         count = min(count, ret_count - 2);
657         memcpy(buf, ihid->rawbuf + 2, count);
658
659         if (!report_number)
660                 count++;
661
662         return count;
663 }
664
665 static int i2c_hid_output_raw_report(struct hid_device *hid, __u8 *buf,
666                 size_t count, unsigned char report_type, bool use_data)
667 {
668         struct i2c_client *client = hid->driver_data;
669         struct i2c_hid *ihid = i2c_get_clientdata(client);
670         int report_id = buf[0];
671         int ret;
672
673         if (report_type == HID_INPUT_REPORT)
674                 return -EINVAL;
675
676         mutex_lock(&ihid->reset_lock);
677
678         /*
679          * Note that both numbered and unnumbered reports passed here
680          * are supposed to have report ID stored in the 1st byte of the
681          * buffer, so we strip it off unconditionally before passing payload
682          * to i2c_hid_set_or_send_report which takes care of encoding
683          * everything properly.
684          */
685         ret = i2c_hid_set_or_send_report(ihid,
686                                 report_type == HID_FEATURE_REPORT ? 0x03 : 0x02,
687                                 report_id, buf + 1, count - 1, use_data);
688
689         if (ret >= 0)
690                 ret++; /* add report_id to the number of transferred bytes */
691
692         mutex_unlock(&ihid->reset_lock);
693
694         return ret;
695 }
696
697 static int i2c_hid_output_report(struct hid_device *hid, __u8 *buf,
698                 size_t count)
699 {
700         return i2c_hid_output_raw_report(hid, buf, count, HID_OUTPUT_REPORT,
701                         false);
702 }
703
704 static int i2c_hid_raw_request(struct hid_device *hid, unsigned char reportnum,
705                                __u8 *buf, size_t len, unsigned char rtype,
706                                int reqtype)
707 {
708         switch (reqtype) {
709         case HID_REQ_GET_REPORT:
710                 return i2c_hid_get_raw_report(hid, reportnum, buf, len, rtype);
711         case HID_REQ_SET_REPORT:
712                 if (buf[0] != reportnum)
713                         return -EINVAL;
714                 return i2c_hid_output_raw_report(hid, buf, len, rtype, true);
715         default:
716                 return -EIO;
717         }
718 }
719
720 static int i2c_hid_parse(struct hid_device *hid)
721 {
722         struct i2c_client *client = hid->driver_data;
723         struct i2c_hid *ihid = i2c_get_clientdata(client);
724         struct i2c_hid_desc *hdesc = &ihid->hdesc;
725         unsigned int rsize;
726         char *rdesc;
727         int ret;
728         int tries = 3;
729         char *use_override;
730
731         i2c_hid_dbg(ihid, "entering %s\n", __func__);
732
733         rsize = le16_to_cpu(hdesc->wReportDescLength);
734         if (!rsize || rsize > HID_MAX_DESCRIPTOR_SIZE) {
735                 dbg_hid("weird size of report descriptor (%u)\n", rsize);
736                 return -EINVAL;
737         }
738
739         do {
740                 ret = i2c_hid_hwreset(ihid);
741                 if (ret)
742                         msleep(1000);
743         } while (tries-- > 0 && ret);
744
745         if (ret)
746                 return ret;
747
748         use_override = i2c_hid_get_dmi_hid_report_desc_override(client->name,
749                                                                 &rsize);
750
751         if (use_override) {
752                 rdesc = use_override;
753                 i2c_hid_dbg(ihid, "Using a HID report descriptor override\n");
754         } else {
755                 rdesc = kzalloc(rsize, GFP_KERNEL);
756
757                 if (!rdesc) {
758                         dbg_hid("couldn't allocate rdesc memory\n");
759                         return -ENOMEM;
760                 }
761
762                 i2c_hid_dbg(ihid, "asking HID report descriptor\n");
763
764                 ret = i2c_hid_command(ihid, &hid_report_descr_cmd,
765                                       rdesc, rsize);
766                 if (ret) {
767                         hid_err(hid, "reading report descriptor failed\n");
768                         kfree(rdesc);
769                         return -EIO;
770                 }
771         }
772
773         i2c_hid_dbg(ihid, "Report Descriptor: %*ph\n", rsize, rdesc);
774
775         ret = hid_parse_report(hid, rdesc, rsize);
776         if (!use_override)
777                 kfree(rdesc);
778
779         if (ret) {
780                 dbg_hid("parsing report descriptor failed\n");
781                 return ret;
782         }
783
784         return 0;
785 }
786
787 static int i2c_hid_start(struct hid_device *hid)
788 {
789         struct i2c_client *client = hid->driver_data;
790         struct i2c_hid *ihid = i2c_get_clientdata(client);
791         int ret;
792         unsigned int bufsize = HID_MIN_BUFFER_SIZE;
793
794         i2c_hid_find_max_report(hid, HID_INPUT_REPORT, &bufsize);
795         i2c_hid_find_max_report(hid, HID_OUTPUT_REPORT, &bufsize);
796         i2c_hid_find_max_report(hid, HID_FEATURE_REPORT, &bufsize);
797
798         if (bufsize > ihid->bufsize) {
799                 disable_irq(client->irq);
800                 i2c_hid_free_buffers(ihid);
801
802                 ret = i2c_hid_alloc_buffers(ihid, bufsize);
803                 enable_irq(client->irq);
804
805                 if (ret)
806                         return ret;
807         }
808
809         return 0;
810 }
811
812 static void i2c_hid_stop(struct hid_device *hid)
813 {
814         hid->claimed = 0;
815 }
816
817 static int i2c_hid_open(struct hid_device *hid)
818 {
819         struct i2c_client *client = hid->driver_data;
820         struct i2c_hid *ihid = i2c_get_clientdata(client);
821
822         set_bit(I2C_HID_STARTED, &ihid->flags);
823         return 0;
824 }
825
826 static void i2c_hid_close(struct hid_device *hid)
827 {
828         struct i2c_client *client = hid->driver_data;
829         struct i2c_hid *ihid = i2c_get_clientdata(client);
830
831         clear_bit(I2C_HID_STARTED, &ihid->flags);
832 }
833
834 struct hid_ll_driver i2c_hid_ll_driver = {
835         .parse = i2c_hid_parse,
836         .start = i2c_hid_start,
837         .stop = i2c_hid_stop,
838         .open = i2c_hid_open,
839         .close = i2c_hid_close,
840         .output_report = i2c_hid_output_report,
841         .raw_request = i2c_hid_raw_request,
842 };
843 EXPORT_SYMBOL_GPL(i2c_hid_ll_driver);
844
845 static int i2c_hid_init_irq(struct i2c_client *client)
846 {
847         struct i2c_hid *ihid = i2c_get_clientdata(client);
848         unsigned long irqflags = 0;
849         int ret;
850
851         dev_dbg(&client->dev, "Requesting IRQ: %d\n", client->irq);
852
853         if (!irq_get_trigger_type(client->irq))
854                 irqflags = IRQF_TRIGGER_LOW;
855
856         ret = request_threaded_irq(client->irq, NULL, i2c_hid_irq,
857                                    irqflags | IRQF_ONESHOT, client->name, ihid);
858         if (ret < 0) {
859                 dev_warn(&client->dev,
860                         "Could not register for %s interrupt, irq = %d,"
861                         " ret = %d\n",
862                         client->name, client->irq, ret);
863
864                 return ret;
865         }
866
867         return 0;
868 }
869
870 static int i2c_hid_fetch_hid_descriptor(struct i2c_hid *ihid)
871 {
872         struct i2c_client *client = ihid->client;
873         struct i2c_hid_desc *hdesc = &ihid->hdesc;
874         unsigned int dsize;
875         int ret;
876
877         /* i2c hid fetch using a fixed descriptor size (30 bytes) */
878         if (i2c_hid_get_dmi_i2c_hid_desc_override(client->name)) {
879                 i2c_hid_dbg(ihid, "Using a HID descriptor override\n");
880                 ihid->hdesc =
881                         *i2c_hid_get_dmi_i2c_hid_desc_override(client->name);
882         } else {
883                 i2c_hid_dbg(ihid, "Fetching the HID descriptor\n");
884                 ret = i2c_hid_command(ihid, &hid_descr_cmd,
885                                       ihid->hdesc_buffer,
886                                       sizeof(struct i2c_hid_desc));
887                 if (ret) {
888                         dev_err(&ihid->client->dev, "hid_descr_cmd failed\n");
889                         return -ENODEV;
890                 }
891         }
892
893         /* Validate the length of HID descriptor, the 4 first bytes:
894          * bytes 0-1 -> length
895          * bytes 2-3 -> bcdVersion (has to be 1.00) */
896         /* check bcdVersion == 1.0 */
897         if (le16_to_cpu(hdesc->bcdVersion) != 0x0100) {
898                 dev_err(&ihid->client->dev,
899                         "unexpected HID descriptor bcdVersion (0x%04hx)\n",
900                         le16_to_cpu(hdesc->bcdVersion));
901                 return -ENODEV;
902         }
903
904         /* Descriptor length should be 30 bytes as per the specification */
905         dsize = le16_to_cpu(hdesc->wHIDDescLength);
906         if (dsize != sizeof(struct i2c_hid_desc)) {
907                 dev_err(&ihid->client->dev,
908                         "weird size of HID descriptor (%u)\n", dsize);
909                 return -ENODEV;
910         }
911         i2c_hid_dbg(ihid, "HID Descriptor: %*ph\n", dsize, ihid->hdesc_buffer);
912         return 0;
913 }
914
915 static int i2c_hid_core_power_up(struct i2c_hid *ihid)
916 {
917         if (!ihid->ops->power_up)
918                 return 0;
919
920         return ihid->ops->power_up(ihid->ops);
921 }
922
923 static void i2c_hid_core_power_down(struct i2c_hid *ihid)
924 {
925         if (!ihid->ops->power_down)
926                 return;
927
928         ihid->ops->power_down(ihid->ops);
929 }
930
931 static void i2c_hid_core_shutdown_tail(struct i2c_hid *ihid)
932 {
933         if (!ihid->ops->shutdown_tail)
934                 return;
935
936         ihid->ops->shutdown_tail(ihid->ops);
937 }
938
939 int i2c_hid_core_probe(struct i2c_client *client, struct i2chid_ops *ops,
940                        u16 hid_descriptor_address, u32 quirks)
941 {
942         int ret;
943         struct i2c_hid *ihid;
944         struct hid_device *hid;
945
946         dbg_hid("HID probe called for i2c 0x%02x\n", client->addr);
947
948         if (!client->irq) {
949                 dev_err(&client->dev,
950                         "HID over i2c has not been provided an Int IRQ\n");
951                 return -EINVAL;
952         }
953
954         if (client->irq < 0) {
955                 if (client->irq != -EPROBE_DEFER)
956                         dev_err(&client->dev,
957                                 "HID over i2c doesn't have a valid IRQ\n");
958                 return client->irq;
959         }
960
961         ihid = devm_kzalloc(&client->dev, sizeof(*ihid), GFP_KERNEL);
962         if (!ihid)
963                 return -ENOMEM;
964
965         ihid->ops = ops;
966
967         ret = i2c_hid_core_power_up(ihid);
968         if (ret)
969                 return ret;
970
971         i2c_set_clientdata(client, ihid);
972
973         ihid->client = client;
974
975         ihid->wHIDDescRegister = cpu_to_le16(hid_descriptor_address);
976
977         init_waitqueue_head(&ihid->wait);
978         mutex_init(&ihid->reset_lock);
979
980         /* we need to allocate the command buffer without knowing the maximum
981          * size of the reports. Let's use HID_MIN_BUFFER_SIZE, then we do the
982          * real computation later. */
983         ret = i2c_hid_alloc_buffers(ihid, HID_MIN_BUFFER_SIZE);
984         if (ret < 0)
985                 goto err_powered;
986
987         device_enable_async_suspend(&client->dev);
988
989         /* Make sure there is something at this address */
990         ret = i2c_smbus_read_byte(client);
991         if (ret < 0) {
992                 dev_dbg(&client->dev, "nothing at this address: %d\n", ret);
993                 ret = -ENXIO;
994                 goto err_powered;
995         }
996
997         ret = i2c_hid_fetch_hid_descriptor(ihid);
998         if (ret < 0) {
999                 dev_err(&client->dev,
1000                         "Failed to fetch the HID Descriptor\n");
1001                 goto err_powered;
1002         }
1003
1004         ret = i2c_hid_init_irq(client);
1005         if (ret < 0)
1006                 goto err_powered;
1007
1008         hid = hid_allocate_device();
1009         if (IS_ERR(hid)) {
1010                 ret = PTR_ERR(hid);
1011                 goto err_irq;
1012         }
1013
1014         ihid->hid = hid;
1015
1016         hid->driver_data = client;
1017         hid->ll_driver = &i2c_hid_ll_driver;
1018         hid->dev.parent = &client->dev;
1019         hid->bus = BUS_I2C;
1020         hid->version = le16_to_cpu(ihid->hdesc.bcdVersion);
1021         hid->vendor = le16_to_cpu(ihid->hdesc.wVendorID);
1022         hid->product = le16_to_cpu(ihid->hdesc.wProductID);
1023
1024         snprintf(hid->name, sizeof(hid->name), "%s %04X:%04X",
1025                  client->name, (u16)hid->vendor, (u16)hid->product);
1026         strlcpy(hid->phys, dev_name(&client->dev), sizeof(hid->phys));
1027
1028         ihid->quirks = i2c_hid_lookup_quirk(hid->vendor, hid->product);
1029
1030         ret = hid_add_device(hid);
1031         if (ret) {
1032                 if (ret != -ENODEV)
1033                         hid_err(client, "can't add hid device: %d\n", ret);
1034                 goto err_mem_free;
1035         }
1036
1037         hid->quirks |= quirks;
1038
1039         return 0;
1040
1041 err_mem_free:
1042         hid_destroy_device(hid);
1043
1044 err_irq:
1045         free_irq(client->irq, ihid);
1046
1047 err_powered:
1048         i2c_hid_core_power_down(ihid);
1049         i2c_hid_free_buffers(ihid);
1050         return ret;
1051 }
1052 EXPORT_SYMBOL_GPL(i2c_hid_core_probe);
1053
1054 int i2c_hid_core_remove(struct i2c_client *client)
1055 {
1056         struct i2c_hid *ihid = i2c_get_clientdata(client);
1057         struct hid_device *hid;
1058
1059         hid = ihid->hid;
1060         hid_destroy_device(hid);
1061
1062         free_irq(client->irq, ihid);
1063
1064         if (ihid->bufsize)
1065                 i2c_hid_free_buffers(ihid);
1066
1067         i2c_hid_core_power_down(ihid);
1068
1069         return 0;
1070 }
1071 EXPORT_SYMBOL_GPL(i2c_hid_core_remove);
1072
1073 void i2c_hid_core_shutdown(struct i2c_client *client)
1074 {
1075         struct i2c_hid *ihid = i2c_get_clientdata(client);
1076
1077         i2c_hid_set_power(ihid, I2C_HID_PWR_SLEEP);
1078         free_irq(client->irq, ihid);
1079
1080         i2c_hid_core_shutdown_tail(ihid);
1081 }
1082 EXPORT_SYMBOL_GPL(i2c_hid_core_shutdown);
1083
1084 #ifdef CONFIG_PM_SLEEP
1085 static int i2c_hid_core_suspend(struct device *dev)
1086 {
1087         struct i2c_client *client = to_i2c_client(dev);
1088         struct i2c_hid *ihid = i2c_get_clientdata(client);
1089         struct hid_device *hid = ihid->hid;
1090         int ret;
1091         int wake_status;
1092
1093         ret = hid_driver_suspend(hid, PMSG_SUSPEND);
1094         if (ret < 0)
1095                 return ret;
1096
1097         /* Save some power */
1098         i2c_hid_set_power(ihid, I2C_HID_PWR_SLEEP);
1099
1100         disable_irq(client->irq);
1101
1102         if (device_may_wakeup(&client->dev)) {
1103                 wake_status = enable_irq_wake(client->irq);
1104                 if (!wake_status)
1105                         ihid->irq_wake_enabled = true;
1106                 else
1107                         hid_warn(hid, "Failed to enable irq wake: %d\n",
1108                                 wake_status);
1109         } else {
1110                 i2c_hid_core_power_down(ihid);
1111         }
1112
1113         return 0;
1114 }
1115
1116 static int i2c_hid_core_resume(struct device *dev)
1117 {
1118         int ret;
1119         struct i2c_client *client = to_i2c_client(dev);
1120         struct i2c_hid *ihid = i2c_get_clientdata(client);
1121         struct hid_device *hid = ihid->hid;
1122         int wake_status;
1123
1124         if (!device_may_wakeup(&client->dev)) {
1125                 i2c_hid_core_power_up(ihid);
1126         } else if (ihid->irq_wake_enabled) {
1127                 wake_status = disable_irq_wake(client->irq);
1128                 if (!wake_status)
1129                         ihid->irq_wake_enabled = false;
1130                 else
1131                         hid_warn(hid, "Failed to disable irq wake: %d\n",
1132                                 wake_status);
1133         }
1134
1135         enable_irq(client->irq);
1136
1137         /* Instead of resetting device, simply powers the device on. This
1138          * solves "incomplete reports" on Raydium devices 2386:3118 and
1139          * 2386:4B33 and fixes various SIS touchscreens no longer sending
1140          * data after a suspend/resume.
1141          *
1142          * However some ALPS touchpads generate IRQ storm without reset, so
1143          * let's still reset them here.
1144          */
1145         if (ihid->quirks & I2C_HID_QUIRK_RESET_ON_RESUME)
1146                 ret = i2c_hid_hwreset(ihid);
1147         else
1148                 ret = i2c_hid_set_power(ihid, I2C_HID_PWR_ON);
1149
1150         if (ret)
1151                 return ret;
1152
1153         return hid_driver_reset_resume(hid);
1154 }
1155 #endif
1156
1157 const struct dev_pm_ops i2c_hid_core_pm = {
1158         SET_SYSTEM_SLEEP_PM_OPS(i2c_hid_core_suspend, i2c_hid_core_resume)
1159 };
1160 EXPORT_SYMBOL_GPL(i2c_hid_core_pm);
1161
1162 MODULE_DESCRIPTION("HID over I2C core driver");
1163 MODULE_AUTHOR("Benjamin Tissoires <benjamin.tissoires@gmail.com>");
1164 MODULE_LICENSE("GPL");