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