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