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