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