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