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