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