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