1 /*
2  * HID over I2C protocol implementation
3  *
4  * Copyright (c) 2012 Benjamin Tissoires <benjamin.tissoires@gmail.com>
5  * Copyright (c) 2012 Ecole Nationale de l'Aviation Civile, France
6  * Copyright (c) 2012 Red Hat, Inc
7  *
8  * This code is partly based on "USB HID support for Linux":
9  *
10  *  Copyright (c) 1999 Andreas Gal
11  *  Copyright (c) 2000-2005 Vojtech Pavlik <vojtech@suse.cz>
12  *  Copyright (c) 2005 Michael Haboustak <mike-@cinci.rr.com> for Concept2, Inc
13  *  Copyright (c) 2007-2008 Oliver Neukum
14  *  Copyright (c) 2006-2010 Jiri Kosina
15  *
16  * This file is subject to the terms and conditions of the GNU General Public
17  * License.  See the file COPYING in the main directory of this archive for
18  * more details.
19  */
20 
21 #include <linux/module.h>
22 #include <linux/i2c.h>
23 #include <linux/interrupt.h>
24 #include <linux/input.h>
25 #include <linux/irq.h>
26 #include <linux/delay.h>
27 #include <linux/slab.h>
28 #include <linux/pm.h>
29 #include <linux/device.h>
30 #include <linux/wait.h>
31 #include <linux/err.h>
32 #include <linux/string.h>
33 #include <linux/list.h>
34 #include <linux/jiffies.h>
35 #include <linux/kernel.h>
36 #include <linux/hid.h>
37 #include <linux/mutex.h>
38 #include <linux/acpi.h>
39 #include <linux/of.h>
40 #include <linux/regulator/consumer.h>
41 
42 #include <linux/platform_data/i2c-hid.h>
43 
44 #include "../hid-ids.h"
45 #include "i2c-hid.h"
46 
47 /* quirks to control the device */
48 #define I2C_HID_QUIRK_SET_PWR_WAKEUP_DEV	BIT(0)
49 #define I2C_HID_QUIRK_NO_IRQ_AFTER_RESET	BIT(1)
50 #define I2C_HID_QUIRK_BOGUS_IRQ			BIT(4)
51 
52 /* flags */
53 #define I2C_HID_STARTED		0
54 #define I2C_HID_RESET_PENDING	1
55 #define I2C_HID_READ_PENDING	2
56 
57 #define I2C_HID_PWR_ON		0x00
58 #define I2C_HID_PWR_SLEEP	0x01
59 
60 /* debug option */
61 static bool debug;
62 module_param(debug, bool, 0444);
63 MODULE_PARM_DESC(debug, "print a lot of debug information");
64 
65 #define i2c_hid_dbg(ihid, fmt, arg...)					  \
66 do {									  \
67 	if (debug)							  \
68 		dev_printk(KERN_DEBUG, &(ihid)->client->dev, fmt, ##arg); \
69 } while (0)
70 
71 struct i2c_hid_desc {
72 	__le16 wHIDDescLength;
73 	__le16 bcdVersion;
74 	__le16 wReportDescLength;
75 	__le16 wReportDescRegister;
76 	__le16 wInputRegister;
77 	__le16 wMaxInputLength;
78 	__le16 wOutputRegister;
79 	__le16 wMaxOutputLength;
80 	__le16 wCommandRegister;
81 	__le16 wDataRegister;
82 	__le16 wVendorID;
83 	__le16 wProductID;
84 	__le16 wVersionID;
85 	__le32 reserved;
86 } __packed;
87 
88 struct i2c_hid_cmd {
89 	unsigned int registerIndex;
90 	__u8 opcode;
91 	unsigned int length;
92 	bool wait;
93 };
94 
95 union command {
96 	u8 data[0];
97 	struct cmd {
98 		__le16 reg;
99 		__u8 reportTypeID;
100 		__u8 opcode;
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 	struct i2c_hid_platform_data pdata;
157 
158 	bool			irq_wake_enabled;
159 	struct mutex		reset_lock;
160 
161 	unsigned long		sleep_delay;
162 };
163 
164 static const struct i2c_hid_quirks {
165 	__u16 idVendor;
166 	__u16 idProduct;
167 	__u32 quirks;
168 } i2c_hid_quirks[] = {
169 	{ USB_VENDOR_ID_WEIDA, HID_ANY_ID,
170 		I2C_HID_QUIRK_SET_PWR_WAKEUP_DEV },
171 	{ I2C_VENDOR_ID_HANTICK, I2C_PRODUCT_ID_HANTICK_5288,
172 		I2C_HID_QUIRK_NO_IRQ_AFTER_RESET },
173 	{ USB_VENDOR_ID_ELAN, HID_ANY_ID,
174 		 I2C_HID_QUIRK_BOGUS_IRQ },
175 	{ 0, 0 }
176 };
177 
178 /*
179  * i2c_hid_lookup_quirk: return any quirks associated with a I2C HID device
180  * @idVendor: the 16-bit vendor ID
181  * @idProduct: the 16-bit product ID
182  *
183  * Returns: a u32 quirks value.
184  */
185 static u32 i2c_hid_lookup_quirk(const u16 idVendor, const u16 idProduct)
186 {
187 	u32 quirks = 0;
188 	int n;
189 
190 	for (n = 0; i2c_hid_quirks[n].idVendor; n++)
191 		if (i2c_hid_quirks[n].idVendor == idVendor &&
192 		    (i2c_hid_quirks[n].idProduct == (__u16)HID_ANY_ID ||
193 		     i2c_hid_quirks[n].idProduct == idProduct))
194 			quirks = i2c_hid_quirks[n].quirks;
195 
196 	return quirks;
197 }
198 
199 static int __i2c_hid_command(struct i2c_client *client,
200 		const struct i2c_hid_cmd *command, u8 reportID,
201 		u8 reportType, u8 *args, int args_len,
202 		unsigned char *buf_recv, int data_len)
203 {
204 	struct i2c_hid *ihid = i2c_get_clientdata(client);
205 	union command *cmd = (union command *)ihid->cmdbuf;
206 	int ret;
207 	struct i2c_msg msg[2];
208 	int msg_num = 1;
209 
210 	int length = command->length;
211 	bool wait = command->wait;
212 	unsigned int registerIndex = command->registerIndex;
213 
214 	/* special case for hid_descr_cmd */
215 	if (command == &hid_descr_cmd) {
216 		cmd->c.reg = ihid->wHIDDescRegister;
217 	} else {
218 		cmd->data[0] = ihid->hdesc_buffer[registerIndex];
219 		cmd->data[1] = ihid->hdesc_buffer[registerIndex + 1];
220 	}
221 
222 	if (length > 2) {
223 		cmd->c.opcode = command->opcode;
224 		cmd->c.reportTypeID = reportID | reportType << 4;
225 	}
226 
227 	memcpy(cmd->data + length, args, args_len);
228 	length += args_len;
229 
230 	i2c_hid_dbg(ihid, "%s: cmd=%*ph\n", __func__, length, cmd->data);
231 
232 	msg[0].addr = client->addr;
233 	msg[0].flags = client->flags & I2C_M_TEN;
234 	msg[0].len = length;
235 	msg[0].buf = cmd->data;
236 	if (data_len > 0) {
237 		msg[1].addr = client->addr;
238 		msg[1].flags = client->flags & I2C_M_TEN;
239 		msg[1].flags |= I2C_M_RD;
240 		msg[1].len = data_len;
241 		msg[1].buf = buf_recv;
242 		msg_num = 2;
243 		set_bit(I2C_HID_READ_PENDING, &ihid->flags);
244 	}
245 
246 	if (wait)
247 		set_bit(I2C_HID_RESET_PENDING, &ihid->flags);
248 
249 	ret = i2c_transfer(client->adapter, msg, msg_num);
250 
251 	if (data_len > 0)
252 		clear_bit(I2C_HID_READ_PENDING, &ihid->flags);
253 
254 	if (ret != msg_num)
255 		return ret < 0 ? ret : -EIO;
256 
257 	ret = 0;
258 
259 	if (wait && (ihid->quirks & I2C_HID_QUIRK_NO_IRQ_AFTER_RESET)) {
260 		msleep(100);
261 	} else if (wait) {
262 		i2c_hid_dbg(ihid, "%s: waiting...\n", __func__);
263 		if (!wait_event_timeout(ihid->wait,
264 				!test_bit(I2C_HID_RESET_PENDING, &ihid->flags),
265 				msecs_to_jiffies(5000)))
266 			ret = -ENODATA;
267 		i2c_hid_dbg(ihid, "%s: finished.\n", __func__);
268 	}
269 
270 	return ret;
271 }
272 
273 static int i2c_hid_command(struct i2c_client *client,
274 		const struct i2c_hid_cmd *command,
275 		unsigned char *buf_recv, int data_len)
276 {
277 	return __i2c_hid_command(client, command, 0, 0, NULL, 0,
278 				buf_recv, data_len);
279 }
280 
281 static int i2c_hid_get_report(struct i2c_client *client, u8 reportType,
282 		u8 reportID, unsigned char *buf_recv, int data_len)
283 {
284 	struct i2c_hid *ihid = i2c_get_clientdata(client);
285 	u8 args[3];
286 	int ret;
287 	int args_len = 0;
288 	u16 readRegister = le16_to_cpu(ihid->hdesc.wDataRegister);
289 
290 	i2c_hid_dbg(ihid, "%s\n", __func__);
291 
292 	if (reportID >= 0x0F) {
293 		args[args_len++] = reportID;
294 		reportID = 0x0F;
295 	}
296 
297 	args[args_len++] = readRegister & 0xFF;
298 	args[args_len++] = readRegister >> 8;
299 
300 	ret = __i2c_hid_command(client, &hid_get_report_cmd, reportID,
301 		reportType, args, args_len, buf_recv, data_len);
302 	if (ret) {
303 		dev_err(&client->dev,
304 			"failed to retrieve report from device.\n");
305 		return ret;
306 	}
307 
308 	return 0;
309 }
310 
311 /**
312  * i2c_hid_set_or_send_report: forward an incoming report to the device
313  * @client: the i2c_client of the device
314  * @reportType: 0x03 for HID_FEATURE_REPORT ; 0x02 for HID_OUTPUT_REPORT
315  * @reportID: the report ID
316  * @buf: the actual data to transfer, without the report ID
317  * @len: size of buf
318  * @use_data: true: use SET_REPORT HID command, false: send plain OUTPUT report
319  */
320 static int i2c_hid_set_or_send_report(struct i2c_client *client, u8 reportType,
321 		u8 reportID, unsigned char *buf, size_t data_len, bool use_data)
322 {
323 	struct i2c_hid *ihid = i2c_get_clientdata(client);
324 	u8 *args = ihid->argsbuf;
325 	const struct i2c_hid_cmd *hidcmd;
326 	int ret;
327 	u16 dataRegister = le16_to_cpu(ihid->hdesc.wDataRegister);
328 	u16 outputRegister = le16_to_cpu(ihid->hdesc.wOutputRegister);
329 	u16 maxOutputLength = le16_to_cpu(ihid->hdesc.wMaxOutputLength);
330 	u16 size;
331 	int args_len;
332 	int index = 0;
333 
334 	i2c_hid_dbg(ihid, "%s\n", __func__);
335 
336 	if (data_len > ihid->bufsize)
337 		return -EINVAL;
338 
339 	size =		2			/* size */ +
340 			(reportID ? 1 : 0)	/* reportID */ +
341 			data_len		/* buf */;
342 	args_len =	(reportID >= 0x0F ? 1 : 0) /* optional third byte */ +
343 			2			/* dataRegister */ +
344 			size			/* args */;
345 
346 	if (!use_data && maxOutputLength == 0)
347 		return -ENOSYS;
348 
349 	if (reportID >= 0x0F) {
350 		args[index++] = reportID;
351 		reportID = 0x0F;
352 	}
353 
354 	/*
355 	 * use the data register for feature reports or if the device does not
356 	 * support the output register
357 	 */
358 	if (use_data) {
359 		args[index++] = dataRegister & 0xFF;
360 		args[index++] = dataRegister >> 8;
361 		hidcmd = &hid_set_report_cmd;
362 	} else {
363 		args[index++] = outputRegister & 0xFF;
364 		args[index++] = outputRegister >> 8;
365 		hidcmd = &hid_no_cmd;
366 	}
367 
368 	args[index++] = size & 0xFF;
369 	args[index++] = size >> 8;
370 
371 	if (reportID)
372 		args[index++] = reportID;
373 
374 	memcpy(&args[index], buf, data_len);
375 
376 	ret = __i2c_hid_command(client, hidcmd, reportID,
377 		reportType, args, args_len, NULL, 0);
378 	if (ret) {
379 		dev_err(&client->dev, "failed to set a report to device.\n");
380 		return ret;
381 	}
382 
383 	return data_len;
384 }
385 
386 static int i2c_hid_set_power(struct i2c_client *client, int power_state)
387 {
388 	struct i2c_hid *ihid = i2c_get_clientdata(client);
389 	int ret;
390 
391 	i2c_hid_dbg(ihid, "%s\n", __func__);
392 
393 	/*
394 	 * Some devices require to send a command to wakeup before power on.
395 	 * The call will get a return value (EREMOTEIO) but device will be
396 	 * triggered and activated. After that, it goes like a normal device.
397 	 */
398 	if (power_state == I2C_HID_PWR_ON &&
399 	    ihid->quirks & I2C_HID_QUIRK_SET_PWR_WAKEUP_DEV) {
400 		ret = i2c_hid_command(client, &hid_set_power_cmd, NULL, 0);
401 
402 		/* Device was already activated */
403 		if (!ret)
404 			goto set_pwr_exit;
405 	}
406 
407 	ret = __i2c_hid_command(client, &hid_set_power_cmd, power_state,
408 		0, NULL, 0, NULL, 0);
409 
410 	if (ret)
411 		dev_err(&client->dev, "failed to change power setting.\n");
412 
413 set_pwr_exit:
414 	return ret;
415 }
416 
417 static int i2c_hid_hwreset(struct i2c_client *client)
418 {
419 	struct i2c_hid *ihid = i2c_get_clientdata(client);
420 	int ret;
421 
422 	i2c_hid_dbg(ihid, "%s\n", __func__);
423 
424 	/*
425 	 * This prevents sending feature reports while the device is
426 	 * being reset. Otherwise we may lose the reset complete
427 	 * interrupt.
428 	 */
429 	mutex_lock(&ihid->reset_lock);
430 
431 	ret = i2c_hid_set_power(client, I2C_HID_PWR_ON);
432 	if (ret)
433 		goto out_unlock;
434 
435 	/*
436 	 * The HID over I2C specification states that if a DEVICE needs time
437 	 * after the PWR_ON request, it should utilise CLOCK stretching.
438 	 * However, it has been observered that the Windows driver provides a
439 	 * 1ms sleep between the PWR_ON and RESET requests and that some devices
440 	 * rely on this.
441 	 */
442 	usleep_range(1000, 5000);
443 
444 	i2c_hid_dbg(ihid, "resetting...\n");
445 
446 	ret = i2c_hid_command(client, &hid_reset_cmd, NULL, 0);
447 	if (ret) {
448 		dev_err(&client->dev, "failed to reset device.\n");
449 		i2c_hid_set_power(client, I2C_HID_PWR_SLEEP);
450 	}
451 
452 out_unlock:
453 	mutex_unlock(&ihid->reset_lock);
454 	return ret;
455 }
456 
457 static void i2c_hid_get_input(struct i2c_hid *ihid)
458 {
459 	int ret;
460 	u32 ret_size;
461 	int size = le16_to_cpu(ihid->hdesc.wMaxInputLength);
462 
463 	if (size > ihid->bufsize)
464 		size = ihid->bufsize;
465 
466 	ret = i2c_master_recv(ihid->client, ihid->inbuf, size);
467 	if (ret != size) {
468 		if (ret < 0)
469 			return;
470 
471 		dev_err(&ihid->client->dev, "%s: got %d data instead of %d\n",
472 			__func__, ret, size);
473 		return;
474 	}
475 
476 	ret_size = ihid->inbuf[0] | ihid->inbuf[1] << 8;
477 
478 	if (!ret_size) {
479 		/* host or device initiated RESET completed */
480 		if (test_and_clear_bit(I2C_HID_RESET_PENDING, &ihid->flags))
481 			wake_up(&ihid->wait);
482 		return;
483 	}
484 
485 	if (ihid->quirks & I2C_HID_QUIRK_BOGUS_IRQ && ret_size == 0xffff) {
486 		dev_warn_once(&ihid->client->dev, "%s: IRQ triggered but "
487 			      "there's no data\n", __func__);
488 		return;
489 	}
490 
491 	if ((ret_size > size) || (ret_size < 2)) {
492 		dev_err(&ihid->client->dev, "%s: incomplete report (%d/%d)\n",
493 			__func__, size, ret_size);
494 		return;
495 	}
496 
497 	i2c_hid_dbg(ihid, "input: %*ph\n", ret_size, ihid->inbuf);
498 
499 	if (test_bit(I2C_HID_STARTED, &ihid->flags))
500 		hid_input_report(ihid->hid, HID_INPUT_REPORT, ihid->inbuf + 2,
501 				ret_size - 2, 1);
502 
503 	return;
504 }
505 
506 static irqreturn_t i2c_hid_irq(int irq, void *dev_id)
507 {
508 	struct i2c_hid *ihid = dev_id;
509 
510 	if (test_bit(I2C_HID_READ_PENDING, &ihid->flags))
511 		return IRQ_HANDLED;
512 
513 	i2c_hid_get_input(ihid);
514 
515 	return IRQ_HANDLED;
516 }
517 
518 static int i2c_hid_get_report_length(struct hid_report *report)
519 {
520 	return ((report->size - 1) >> 3) + 1 +
521 		report->device->report_enum[report->type].numbered + 2;
522 }
523 
524 /*
525  * Traverse the supplied list of reports and find the longest
526  */
527 static void i2c_hid_find_max_report(struct hid_device *hid, unsigned int type,
528 		unsigned int *max)
529 {
530 	struct hid_report *report;
531 	unsigned int size;
532 
533 	/* We should not rely on wMaxInputLength, as some devices may set it to
534 	 * a wrong length. */
535 	list_for_each_entry(report, &hid->report_enum[type].report_list, list) {
536 		size = i2c_hid_get_report_length(report);
537 		if (*max < size)
538 			*max = size;
539 	}
540 }
541 
542 static void i2c_hid_free_buffers(struct i2c_hid *ihid)
543 {
544 	kfree(ihid->inbuf);
545 	kfree(ihid->rawbuf);
546 	kfree(ihid->argsbuf);
547 	kfree(ihid->cmdbuf);
548 	ihid->inbuf = NULL;
549 	ihid->rawbuf = NULL;
550 	ihid->cmdbuf = NULL;
551 	ihid->argsbuf = NULL;
552 	ihid->bufsize = 0;
553 }
554 
555 static int i2c_hid_alloc_buffers(struct i2c_hid *ihid, size_t report_size)
556 {
557 	/* the worst case is computed from the set_report command with a
558 	 * reportID > 15 and the maximum report length */
559 	int args_len = sizeof(__u8) + /* ReportID */
560 		       sizeof(__u8) + /* optional ReportID byte */
561 		       sizeof(__u16) + /* data register */
562 		       sizeof(__u16) + /* size of the report */
563 		       report_size; /* report */
564 
565 	ihid->inbuf = kzalloc(report_size, GFP_KERNEL);
566 	ihid->rawbuf = kzalloc(report_size, GFP_KERNEL);
567 	ihid->argsbuf = kzalloc(args_len, GFP_KERNEL);
568 	ihid->cmdbuf = kzalloc(sizeof(union command) + args_len, GFP_KERNEL);
569 
570 	if (!ihid->inbuf || !ihid->rawbuf || !ihid->argsbuf || !ihid->cmdbuf) {
571 		i2c_hid_free_buffers(ihid);
572 		return -ENOMEM;
573 	}
574 
575 	ihid->bufsize = report_size;
576 
577 	return 0;
578 }
579 
580 static int i2c_hid_get_raw_report(struct hid_device *hid,
581 		unsigned char report_number, __u8 *buf, size_t count,
582 		unsigned char report_type)
583 {
584 	struct i2c_client *client = hid->driver_data;
585 	struct i2c_hid *ihid = i2c_get_clientdata(client);
586 	size_t ret_count, ask_count;
587 	int ret;
588 
589 	if (report_type == HID_OUTPUT_REPORT)
590 		return -EINVAL;
591 
592 	/* +2 bytes to include the size of the reply in the query buffer */
593 	ask_count = min(count + 2, (size_t)ihid->bufsize);
594 
595 	ret = i2c_hid_get_report(client,
596 			report_type == HID_FEATURE_REPORT ? 0x03 : 0x01,
597 			report_number, ihid->rawbuf, ask_count);
598 
599 	if (ret < 0)
600 		return ret;
601 
602 	ret_count = ihid->rawbuf[0] | (ihid->rawbuf[1] << 8);
603 
604 	if (ret_count <= 2)
605 		return 0;
606 
607 	ret_count = min(ret_count, ask_count);
608 
609 	/* The query buffer contains the size, dropping it in the reply */
610 	count = min(count, ret_count - 2);
611 	memcpy(buf, ihid->rawbuf + 2, count);
612 
613 	return count;
614 }
615 
616 static int i2c_hid_output_raw_report(struct hid_device *hid, __u8 *buf,
617 		size_t count, unsigned char report_type, bool use_data)
618 {
619 	struct i2c_client *client = hid->driver_data;
620 	struct i2c_hid *ihid = i2c_get_clientdata(client);
621 	int report_id = buf[0];
622 	int ret;
623 
624 	if (report_type == HID_INPUT_REPORT)
625 		return -EINVAL;
626 
627 	mutex_lock(&ihid->reset_lock);
628 
629 	if (report_id) {
630 		buf++;
631 		count--;
632 	}
633 
634 	ret = i2c_hid_set_or_send_report(client,
635 				report_type == HID_FEATURE_REPORT ? 0x03 : 0x02,
636 				report_id, buf, count, use_data);
637 
638 	if (report_id && ret >= 0)
639 		ret++; /* add report_id to the number of transfered bytes */
640 
641 	mutex_unlock(&ihid->reset_lock);
642 
643 	return ret;
644 }
645 
646 static int i2c_hid_output_report(struct hid_device *hid, __u8 *buf,
647 		size_t count)
648 {
649 	return i2c_hid_output_raw_report(hid, buf, count, HID_OUTPUT_REPORT,
650 			false);
651 }
652 
653 static int i2c_hid_raw_request(struct hid_device *hid, unsigned char reportnum,
654 			       __u8 *buf, size_t len, unsigned char rtype,
655 			       int reqtype)
656 {
657 	switch (reqtype) {
658 	case HID_REQ_GET_REPORT:
659 		return i2c_hid_get_raw_report(hid, reportnum, buf, len, rtype);
660 	case HID_REQ_SET_REPORT:
661 		if (buf[0] != reportnum)
662 			return -EINVAL;
663 		return i2c_hid_output_raw_report(hid, buf, len, rtype, true);
664 	default:
665 		return -EIO;
666 	}
667 }
668 
669 static int i2c_hid_parse(struct hid_device *hid)
670 {
671 	struct i2c_client *client = hid->driver_data;
672 	struct i2c_hid *ihid = i2c_get_clientdata(client);
673 	struct i2c_hid_desc *hdesc = &ihid->hdesc;
674 	unsigned int rsize;
675 	char *rdesc;
676 	int ret;
677 	int tries = 3;
678 	char *use_override;
679 
680 	i2c_hid_dbg(ihid, "entering %s\n", __func__);
681 
682 	rsize = le16_to_cpu(hdesc->wReportDescLength);
683 	if (!rsize || rsize > HID_MAX_DESCRIPTOR_SIZE) {
684 		dbg_hid("weird size of report descriptor (%u)\n", rsize);
685 		return -EINVAL;
686 	}
687 
688 	do {
689 		ret = i2c_hid_hwreset(client);
690 		if (ret)
691 			msleep(1000);
692 	} while (tries-- > 0 && ret);
693 
694 	if (ret)
695 		return ret;
696 
697 	use_override = i2c_hid_get_dmi_hid_report_desc_override(client->name,
698 								&rsize);
699 
700 	if (use_override) {
701 		rdesc = use_override;
702 		i2c_hid_dbg(ihid, "Using a HID report descriptor override\n");
703 	} else {
704 		rdesc = kzalloc(rsize, GFP_KERNEL);
705 
706 		if (!rdesc) {
707 			dbg_hid("couldn't allocate rdesc memory\n");
708 			return -ENOMEM;
709 		}
710 
711 		i2c_hid_dbg(ihid, "asking HID report descriptor\n");
712 
713 		ret = i2c_hid_command(client, &hid_report_descr_cmd,
714 				      rdesc, rsize);
715 		if (ret) {
716 			hid_err(hid, "reading report descriptor failed\n");
717 			kfree(rdesc);
718 			return -EIO;
719 		}
720 	}
721 
722 	i2c_hid_dbg(ihid, "Report Descriptor: %*ph\n", rsize, rdesc);
723 
724 	ret = hid_parse_report(hid, rdesc, rsize);
725 	if (!use_override)
726 		kfree(rdesc);
727 
728 	if (ret) {
729 		dbg_hid("parsing report descriptor failed\n");
730 		return ret;
731 	}
732 
733 	return 0;
734 }
735 
736 static int i2c_hid_start(struct hid_device *hid)
737 {
738 	struct i2c_client *client = hid->driver_data;
739 	struct i2c_hid *ihid = i2c_get_clientdata(client);
740 	int ret;
741 	unsigned int bufsize = HID_MIN_BUFFER_SIZE;
742 
743 	i2c_hid_find_max_report(hid, HID_INPUT_REPORT, &bufsize);
744 	i2c_hid_find_max_report(hid, HID_OUTPUT_REPORT, &bufsize);
745 	i2c_hid_find_max_report(hid, HID_FEATURE_REPORT, &bufsize);
746 
747 	if (bufsize > ihid->bufsize) {
748 		disable_irq(client->irq);
749 		i2c_hid_free_buffers(ihid);
750 
751 		ret = i2c_hid_alloc_buffers(ihid, bufsize);
752 		enable_irq(client->irq);
753 
754 		if (ret)
755 			return ret;
756 	}
757 
758 	return 0;
759 }
760 
761 static void i2c_hid_stop(struct hid_device *hid)
762 {
763 	hid->claimed = 0;
764 }
765 
766 static int i2c_hid_open(struct hid_device *hid)
767 {
768 	struct i2c_client *client = hid->driver_data;
769 	struct i2c_hid *ihid = i2c_get_clientdata(client);
770 
771 	set_bit(I2C_HID_STARTED, &ihid->flags);
772 	return 0;
773 }
774 
775 static void i2c_hid_close(struct hid_device *hid)
776 {
777 	struct i2c_client *client = hid->driver_data;
778 	struct i2c_hid *ihid = i2c_get_clientdata(client);
779 
780 	clear_bit(I2C_HID_STARTED, &ihid->flags);
781 }
782 
783 struct hid_ll_driver i2c_hid_ll_driver = {
784 	.parse = i2c_hid_parse,
785 	.start = i2c_hid_start,
786 	.stop = i2c_hid_stop,
787 	.open = i2c_hid_open,
788 	.close = i2c_hid_close,
789 	.output_report = i2c_hid_output_report,
790 	.raw_request = i2c_hid_raw_request,
791 };
792 EXPORT_SYMBOL_GPL(i2c_hid_ll_driver);
793 
794 static int i2c_hid_init_irq(struct i2c_client *client)
795 {
796 	struct i2c_hid *ihid = i2c_get_clientdata(client);
797 	unsigned long irqflags = 0;
798 	int ret;
799 
800 	dev_dbg(&client->dev, "Requesting IRQ: %d\n", client->irq);
801 
802 	if (!irq_get_trigger_type(client->irq))
803 		irqflags = IRQF_TRIGGER_LOW;
804 
805 	ret = request_threaded_irq(client->irq, NULL, i2c_hid_irq,
806 				   irqflags | IRQF_ONESHOT, client->name, ihid);
807 	if (ret < 0) {
808 		dev_warn(&client->dev,
809 			"Could not register for %s interrupt, irq = %d,"
810 			" ret = %d\n",
811 			client->name, client->irq, ret);
812 
813 		return ret;
814 	}
815 
816 	return 0;
817 }
818 
819 static int i2c_hid_fetch_hid_descriptor(struct i2c_hid *ihid)
820 {
821 	struct i2c_client *client = ihid->client;
822 	struct i2c_hid_desc *hdesc = &ihid->hdesc;
823 	unsigned int dsize;
824 	int ret;
825 
826 	/* i2c hid fetch using a fixed descriptor size (30 bytes) */
827 	if (i2c_hid_get_dmi_i2c_hid_desc_override(client->name)) {
828 		i2c_hid_dbg(ihid, "Using a HID descriptor override\n");
829 		ihid->hdesc =
830 			*i2c_hid_get_dmi_i2c_hid_desc_override(client->name);
831 	} else {
832 		i2c_hid_dbg(ihid, "Fetching the HID descriptor\n");
833 		ret = i2c_hid_command(client, &hid_descr_cmd,
834 				      ihid->hdesc_buffer,
835 				      sizeof(struct i2c_hid_desc));
836 		if (ret) {
837 			dev_err(&client->dev, "hid_descr_cmd failed\n");
838 			return -ENODEV;
839 		}
840 	}
841 
842 	/* Validate the length of HID descriptor, the 4 first bytes:
843 	 * bytes 0-1 -> length
844 	 * bytes 2-3 -> bcdVersion (has to be 1.00) */
845 	/* check bcdVersion == 1.0 */
846 	if (le16_to_cpu(hdesc->bcdVersion) != 0x0100) {
847 		dev_err(&client->dev,
848 			"unexpected HID descriptor bcdVersion (0x%04hx)\n",
849 			le16_to_cpu(hdesc->bcdVersion));
850 		return -ENODEV;
851 	}
852 
853 	/* Descriptor length should be 30 bytes as per the specification */
854 	dsize = le16_to_cpu(hdesc->wHIDDescLength);
855 	if (dsize != sizeof(struct i2c_hid_desc)) {
856 		dev_err(&client->dev, "weird size of HID descriptor (%u)\n",
857 			dsize);
858 		return -ENODEV;
859 	}
860 	i2c_hid_dbg(ihid, "HID Descriptor: %*ph\n", dsize, ihid->hdesc_buffer);
861 	return 0;
862 }
863 
864 #ifdef CONFIG_ACPI
865 static const struct acpi_device_id i2c_hid_acpi_blacklist[] = {
866 	/*
867 	 * The CHPN0001 ACPI device, which is used to describe the Chipone
868 	 * ICN8505 controller, has a _CID of PNP0C50 but is not HID compatible.
869 	 */
870 	{"CHPN0001", 0 },
871 	{ },
872 };
873 
874 static int i2c_hid_acpi_pdata(struct i2c_client *client,
875 		struct i2c_hid_platform_data *pdata)
876 {
877 	static guid_t i2c_hid_guid =
878 		GUID_INIT(0x3CDFF6F7, 0x4267, 0x4555,
879 			  0xAD, 0x05, 0xB3, 0x0A, 0x3D, 0x89, 0x38, 0xDE);
880 	union acpi_object *obj;
881 	struct acpi_device *adev;
882 	acpi_handle handle;
883 
884 	handle = ACPI_HANDLE(&client->dev);
885 	if (!handle || acpi_bus_get_device(handle, &adev)) {
886 		dev_err(&client->dev, "Error could not get ACPI device\n");
887 		return -ENODEV;
888 	}
889 
890 	if (acpi_match_device_ids(adev, i2c_hid_acpi_blacklist) == 0)
891 		return -ENODEV;
892 
893 	obj = acpi_evaluate_dsm_typed(handle, &i2c_hid_guid, 1, 1, NULL,
894 				      ACPI_TYPE_INTEGER);
895 	if (!obj) {
896 		dev_err(&client->dev, "Error _DSM call to get HID descriptor address failed\n");
897 		return -ENODEV;
898 	}
899 
900 	pdata->hid_descriptor_address = obj->integer.value;
901 	ACPI_FREE(obj);
902 
903 	return 0;
904 }
905 
906 static void i2c_hid_acpi_fix_up_power(struct device *dev)
907 {
908 	struct acpi_device *adev;
909 
910 	adev = ACPI_COMPANION(dev);
911 	if (adev)
912 		acpi_device_fix_up_power(adev);
913 }
914 
915 static const struct acpi_device_id i2c_hid_acpi_match[] = {
916 	{"ACPI0C50", 0 },
917 	{"PNP0C50", 0 },
918 	{ },
919 };
920 MODULE_DEVICE_TABLE(acpi, i2c_hid_acpi_match);
921 #else
922 static inline int i2c_hid_acpi_pdata(struct i2c_client *client,
923 		struct i2c_hid_platform_data *pdata)
924 {
925 	return -ENODEV;
926 }
927 
928 static inline void i2c_hid_acpi_fix_up_power(struct device *dev) {}
929 #endif
930 
931 #ifdef CONFIG_OF
932 static int i2c_hid_of_probe(struct i2c_client *client,
933 		struct i2c_hid_platform_data *pdata)
934 {
935 	struct device *dev = &client->dev;
936 	u32 val;
937 	int ret;
938 
939 	ret = of_property_read_u32(dev->of_node, "hid-descr-addr", &val);
940 	if (ret) {
941 		dev_err(&client->dev, "HID register address not provided\n");
942 		return -ENODEV;
943 	}
944 	if (val >> 16) {
945 		dev_err(&client->dev, "Bad HID register address: 0x%08x\n",
946 			val);
947 		return -EINVAL;
948 	}
949 	pdata->hid_descriptor_address = val;
950 
951 	return 0;
952 }
953 
954 static const struct of_device_id i2c_hid_of_match[] = {
955 	{ .compatible = "hid-over-i2c" },
956 	{},
957 };
958 MODULE_DEVICE_TABLE(of, i2c_hid_of_match);
959 #else
960 static inline int i2c_hid_of_probe(struct i2c_client *client,
961 		struct i2c_hid_platform_data *pdata)
962 {
963 	return -ENODEV;
964 }
965 #endif
966 
967 static void i2c_hid_fwnode_probe(struct i2c_client *client,
968 				 struct i2c_hid_platform_data *pdata)
969 {
970 	u32 val;
971 
972 	if (!device_property_read_u32(&client->dev, "post-power-on-delay-ms",
973 				      &val))
974 		pdata->post_power_delay_ms = val;
975 }
976 
977 static int i2c_hid_probe(struct i2c_client *client,
978 			 const struct i2c_device_id *dev_id)
979 {
980 	int ret;
981 	struct i2c_hid *ihid;
982 	struct hid_device *hid;
983 	__u16 hidRegister;
984 	struct i2c_hid_platform_data *platform_data = client->dev.platform_data;
985 
986 	dbg_hid("HID probe called for i2c 0x%02x\n", client->addr);
987 
988 	if (!client->irq) {
989 		dev_err(&client->dev,
990 			"HID over i2c has not been provided an Int IRQ\n");
991 		return -EINVAL;
992 	}
993 
994 	if (client->irq < 0) {
995 		if (client->irq != -EPROBE_DEFER)
996 			dev_err(&client->dev,
997 				"HID over i2c doesn't have a valid IRQ\n");
998 		return client->irq;
999 	}
1000 
1001 	ihid = devm_kzalloc(&client->dev, sizeof(*ihid), GFP_KERNEL);
1002 	if (!ihid)
1003 		return -ENOMEM;
1004 
1005 	if (client->dev.of_node) {
1006 		ret = i2c_hid_of_probe(client, &ihid->pdata);
1007 		if (ret)
1008 			return ret;
1009 	} else if (!platform_data) {
1010 		ret = i2c_hid_acpi_pdata(client, &ihid->pdata);
1011 		if (ret)
1012 			return ret;
1013 	} else {
1014 		ihid->pdata = *platform_data;
1015 	}
1016 
1017 	/* Parse platform agnostic common properties from ACPI / device tree */
1018 	i2c_hid_fwnode_probe(client, &ihid->pdata);
1019 
1020 	ihid->pdata.supplies[0].supply = "vdd";
1021 	ihid->pdata.supplies[1].supply = "vddl";
1022 
1023 	ret = devm_regulator_bulk_get(&client->dev,
1024 				      ARRAY_SIZE(ihid->pdata.supplies),
1025 				      ihid->pdata.supplies);
1026 	if (ret)
1027 		return ret;
1028 
1029 	ret = regulator_bulk_enable(ARRAY_SIZE(ihid->pdata.supplies),
1030 				    ihid->pdata.supplies);
1031 	if (ret < 0)
1032 		return ret;
1033 
1034 	if (ihid->pdata.post_power_delay_ms)
1035 		msleep(ihid->pdata.post_power_delay_ms);
1036 
1037 	i2c_set_clientdata(client, ihid);
1038 
1039 	ihid->client = client;
1040 
1041 	hidRegister = ihid->pdata.hid_descriptor_address;
1042 	ihid->wHIDDescRegister = cpu_to_le16(hidRegister);
1043 
1044 	init_waitqueue_head(&ihid->wait);
1045 	mutex_init(&ihid->reset_lock);
1046 
1047 	/* we need to allocate the command buffer without knowing the maximum
1048 	 * size of the reports. Let's use HID_MIN_BUFFER_SIZE, then we do the
1049 	 * real computation later. */
1050 	ret = i2c_hid_alloc_buffers(ihid, HID_MIN_BUFFER_SIZE);
1051 	if (ret < 0)
1052 		goto err_regulator;
1053 
1054 	i2c_hid_acpi_fix_up_power(&client->dev);
1055 
1056 	device_enable_async_suspend(&client->dev);
1057 
1058 	/* Make sure there is something at this address */
1059 	ret = i2c_smbus_read_byte(client);
1060 	if (ret < 0) {
1061 		dev_dbg(&client->dev, "nothing at this address: %d\n", ret);
1062 		ret = -ENXIO;
1063 		goto err_regulator;
1064 	}
1065 
1066 	ret = i2c_hid_fetch_hid_descriptor(ihid);
1067 	if (ret < 0)
1068 		goto err_regulator;
1069 
1070 	ret = i2c_hid_init_irq(client);
1071 	if (ret < 0)
1072 		goto err_regulator;
1073 
1074 	hid = hid_allocate_device();
1075 	if (IS_ERR(hid)) {
1076 		ret = PTR_ERR(hid);
1077 		goto err_irq;
1078 	}
1079 
1080 	ihid->hid = hid;
1081 
1082 	hid->driver_data = client;
1083 	hid->ll_driver = &i2c_hid_ll_driver;
1084 	hid->dev.parent = &client->dev;
1085 	hid->bus = BUS_I2C;
1086 	hid->version = le16_to_cpu(ihid->hdesc.bcdVersion);
1087 	hid->vendor = le16_to_cpu(ihid->hdesc.wVendorID);
1088 	hid->product = le16_to_cpu(ihid->hdesc.wProductID);
1089 
1090 	snprintf(hid->name, sizeof(hid->name), "%s %04hX:%04hX",
1091 		 client->name, hid->vendor, hid->product);
1092 	strlcpy(hid->phys, dev_name(&client->dev), sizeof(hid->phys));
1093 
1094 	ihid->quirks = i2c_hid_lookup_quirk(hid->vendor, hid->product);
1095 
1096 	ret = hid_add_device(hid);
1097 	if (ret) {
1098 		if (ret != -ENODEV)
1099 			hid_err(client, "can't add hid device: %d\n", ret);
1100 		goto err_mem_free;
1101 	}
1102 
1103 	return 0;
1104 
1105 err_mem_free:
1106 	hid_destroy_device(hid);
1107 
1108 err_irq:
1109 	free_irq(client->irq, ihid);
1110 
1111 err_regulator:
1112 	regulator_bulk_disable(ARRAY_SIZE(ihid->pdata.supplies),
1113 			       ihid->pdata.supplies);
1114 	i2c_hid_free_buffers(ihid);
1115 	return ret;
1116 }
1117 
1118 static int i2c_hid_remove(struct i2c_client *client)
1119 {
1120 	struct i2c_hid *ihid = i2c_get_clientdata(client);
1121 	struct hid_device *hid;
1122 
1123 	hid = ihid->hid;
1124 	hid_destroy_device(hid);
1125 
1126 	free_irq(client->irq, ihid);
1127 
1128 	if (ihid->bufsize)
1129 		i2c_hid_free_buffers(ihid);
1130 
1131 	regulator_bulk_disable(ARRAY_SIZE(ihid->pdata.supplies),
1132 			       ihid->pdata.supplies);
1133 
1134 	return 0;
1135 }
1136 
1137 static void i2c_hid_shutdown(struct i2c_client *client)
1138 {
1139 	struct i2c_hid *ihid = i2c_get_clientdata(client);
1140 
1141 	i2c_hid_set_power(client, I2C_HID_PWR_SLEEP);
1142 	free_irq(client->irq, ihid);
1143 }
1144 
1145 #ifdef CONFIG_PM_SLEEP
1146 static int i2c_hid_suspend(struct device *dev)
1147 {
1148 	struct i2c_client *client = to_i2c_client(dev);
1149 	struct i2c_hid *ihid = i2c_get_clientdata(client);
1150 	struct hid_device *hid = ihid->hid;
1151 	int ret;
1152 	int wake_status;
1153 
1154 	if (hid->driver && hid->driver->suspend) {
1155 		ret = hid->driver->suspend(hid, PMSG_SUSPEND);
1156 		if (ret < 0)
1157 			return ret;
1158 	}
1159 
1160 	/* Save some power */
1161 	i2c_hid_set_power(client, I2C_HID_PWR_SLEEP);
1162 
1163 	disable_irq(client->irq);
1164 
1165 	if (device_may_wakeup(&client->dev)) {
1166 		wake_status = enable_irq_wake(client->irq);
1167 		if (!wake_status)
1168 			ihid->irq_wake_enabled = true;
1169 		else
1170 			hid_warn(hid, "Failed to enable irq wake: %d\n",
1171 				wake_status);
1172 	} else {
1173 		regulator_bulk_disable(ARRAY_SIZE(ihid->pdata.supplies),
1174 				       ihid->pdata.supplies);
1175 	}
1176 
1177 	return 0;
1178 }
1179 
1180 static int i2c_hid_resume(struct device *dev)
1181 {
1182 	int ret;
1183 	struct i2c_client *client = to_i2c_client(dev);
1184 	struct i2c_hid *ihid = i2c_get_clientdata(client);
1185 	struct hid_device *hid = ihid->hid;
1186 	int wake_status;
1187 
1188 	if (!device_may_wakeup(&client->dev)) {
1189 		ret = regulator_bulk_enable(ARRAY_SIZE(ihid->pdata.supplies),
1190 					    ihid->pdata.supplies);
1191 		if (ret)
1192 			hid_warn(hid, "Failed to enable supplies: %d\n", ret);
1193 
1194 		if (ihid->pdata.post_power_delay_ms)
1195 			msleep(ihid->pdata.post_power_delay_ms);
1196 	} else if (ihid->irq_wake_enabled) {
1197 		wake_status = disable_irq_wake(client->irq);
1198 		if (!wake_status)
1199 			ihid->irq_wake_enabled = false;
1200 		else
1201 			hid_warn(hid, "Failed to disable irq wake: %d\n",
1202 				wake_status);
1203 	}
1204 
1205 	enable_irq(client->irq);
1206 
1207 	/* Instead of resetting device, simply powers the device on. This
1208 	 * solves "incomplete reports" on Raydium devices 2386:3118 and
1209 	 * 2386:4B33 and fixes various SIS touchscreens no longer sending
1210 	 * data after a suspend/resume.
1211 	 */
1212 	ret = i2c_hid_set_power(client, I2C_HID_PWR_ON);
1213 	if (ret)
1214 		return ret;
1215 
1216 	if (hid->driver && hid->driver->reset_resume) {
1217 		ret = hid->driver->reset_resume(hid);
1218 		return ret;
1219 	}
1220 
1221 	return 0;
1222 }
1223 #endif
1224 
1225 static const struct dev_pm_ops i2c_hid_pm = {
1226 	SET_SYSTEM_SLEEP_PM_OPS(i2c_hid_suspend, i2c_hid_resume)
1227 };
1228 
1229 static const struct i2c_device_id i2c_hid_id_table[] = {
1230 	{ "hid", 0 },
1231 	{ "hid-over-i2c", 0 },
1232 	{ },
1233 };
1234 MODULE_DEVICE_TABLE(i2c, i2c_hid_id_table);
1235 
1236 
1237 static struct i2c_driver i2c_hid_driver = {
1238 	.driver = {
1239 		.name	= "i2c_hid",
1240 		.pm	= &i2c_hid_pm,
1241 		.acpi_match_table = ACPI_PTR(i2c_hid_acpi_match),
1242 		.of_match_table = of_match_ptr(i2c_hid_of_match),
1243 	},
1244 
1245 	.probe		= i2c_hid_probe,
1246 	.remove		= i2c_hid_remove,
1247 	.shutdown	= i2c_hid_shutdown,
1248 	.id_table	= i2c_hid_id_table,
1249 };
1250 
1251 module_i2c_driver(i2c_hid_driver);
1252 
1253 MODULE_DESCRIPTION("HID over I2C core driver");
1254 MODULE_AUTHOR("Benjamin Tissoires <benjamin.tissoires@gmail.com>");
1255 MODULE_LICENSE("GPL");
1256