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 /* debug option */
71 static bool debug;
72 module_param(debug, bool, 0444);
73 MODULE_PARM_DESC(debug, "print a lot of debug information");
74 
75 #define i2c_hid_dbg(ihid, fmt, arg...)					  \
76 do {									  \
77 	if (debug)							  \
78 		dev_printk(KERN_DEBUG, &(ihid)->client->dev, fmt, ##arg); \
79 } while (0)
80 
81 struct i2c_hid_desc {
82 	__le16 wHIDDescLength;
83 	__le16 bcdVersion;
84 	__le16 wReportDescLength;
85 	__le16 wReportDescRegister;
86 	__le16 wInputRegister;
87 	__le16 wMaxInputLength;
88 	__le16 wOutputRegister;
89 	__le16 wMaxOutputLength;
90 	__le16 wCommandRegister;
91 	__le16 wDataRegister;
92 	__le16 wVendorID;
93 	__le16 wProductID;
94 	__le16 wVersionID;
95 	__le32 reserved;
96 } __packed;
97 
98 /* The main device structure */
99 struct i2c_hid {
100 	struct i2c_client	*client;	/* i2c client */
101 	struct hid_device	*hid;	/* pointer to corresponding HID dev */
102 	struct i2c_hid_desc hdesc;		/* the HID Descriptor */
103 	__le16			wHIDDescRegister; /* location of the i2c
104 						   * register of the HID
105 						   * descriptor. */
106 	unsigned int		bufsize;	/* i2c buffer size */
107 	u8			*inbuf;		/* Input buffer */
108 	u8			*rawbuf;	/* Raw Input buffer */
109 	u8			*cmdbuf;	/* Command buffer */
110 
111 	unsigned long		flags;		/* device flags */
112 	unsigned long		quirks;		/* Various quirks */
113 
114 	wait_queue_head_t	wait;		/* For waiting the interrupt */
115 
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 		if (ihid->hid->group != HID_GROUP_RMI)
558 			pm_wakeup_event(&ihid->client->dev, 0);
559 
560 		hid_input_report(ihid->hid, HID_INPUT_REPORT,
561 				ihid->inbuf + sizeof(__le16),
562 				ret_size - sizeof(__le16), 1);
563 	}
564 
565 	return;
566 }
567 
568 static irqreturn_t i2c_hid_irq(int irq, void *dev_id)
569 {
570 	struct i2c_hid *ihid = dev_id;
571 
572 	if (test_bit(I2C_HID_READ_PENDING, &ihid->flags))
573 		return IRQ_HANDLED;
574 
575 	i2c_hid_get_input(ihid);
576 
577 	return IRQ_HANDLED;
578 }
579 
580 static int i2c_hid_get_report_length(struct hid_report *report)
581 {
582 	return ((report->size - 1) >> 3) + 1 +
583 		report->device->report_enum[report->type].numbered + 2;
584 }
585 
586 /*
587  * Traverse the supplied list of reports and find the longest
588  */
589 static void i2c_hid_find_max_report(struct hid_device *hid, unsigned int type,
590 		unsigned int *max)
591 {
592 	struct hid_report *report;
593 	unsigned int size;
594 
595 	/* We should not rely on wMaxInputLength, as some devices may set it to
596 	 * a wrong length. */
597 	list_for_each_entry(report, &hid->report_enum[type].report_list, list) {
598 		size = i2c_hid_get_report_length(report);
599 		if (*max < size)
600 			*max = size;
601 	}
602 }
603 
604 static void i2c_hid_free_buffers(struct i2c_hid *ihid)
605 {
606 	kfree(ihid->inbuf);
607 	kfree(ihid->rawbuf);
608 	kfree(ihid->cmdbuf);
609 	ihid->inbuf = NULL;
610 	ihid->rawbuf = NULL;
611 	ihid->cmdbuf = NULL;
612 	ihid->bufsize = 0;
613 }
614 
615 static int i2c_hid_alloc_buffers(struct i2c_hid *ihid, size_t report_size)
616 {
617 	/*
618 	 * The worst case is computed from the set_report command with a
619 	 * reportID > 15 and the maximum report length.
620 	 */
621 	int cmd_len = sizeof(__le16) +	/* command register */
622 		      sizeof(u8) +	/* encoded report type/ID */
623 		      sizeof(u8) +	/* opcode */
624 		      sizeof(u8) +	/* optional 3rd byte report ID */
625 		      sizeof(__le16) +	/* data register */
626 		      sizeof(__le16) +	/* report data size */
627 		      sizeof(u8) +	/* report ID if numbered report */
628 		      report_size;
629 
630 	ihid->inbuf = kzalloc(report_size, GFP_KERNEL);
631 	ihid->rawbuf = kzalloc(report_size, GFP_KERNEL);
632 	ihid->cmdbuf = kzalloc(cmd_len, GFP_KERNEL);
633 
634 	if (!ihid->inbuf || !ihid->rawbuf || !ihid->cmdbuf) {
635 		i2c_hid_free_buffers(ihid);
636 		return -ENOMEM;
637 	}
638 
639 	ihid->bufsize = report_size;
640 
641 	return 0;
642 }
643 
644 static int i2c_hid_get_raw_report(struct hid_device *hid,
645 				  u8 report_type, u8 report_id,
646 				  u8 *buf, size_t count)
647 {
648 	struct i2c_client *client = hid->driver_data;
649 	struct i2c_hid *ihid = i2c_get_clientdata(client);
650 	int ret_count;
651 
652 	if (report_type == HID_OUTPUT_REPORT)
653 		return -EINVAL;
654 
655 	/*
656 	 * In case of unnumbered reports the response from the device will
657 	 * not have the report ID that the upper layers expect, so we need
658 	 * to stash it the buffer ourselves and adjust the data size.
659 	 */
660 	if (!report_id) {
661 		buf[0] = 0;
662 		buf++;
663 		count--;
664 	}
665 
666 	ret_count = i2c_hid_get_report(ihid,
667 			report_type == HID_FEATURE_REPORT ? 0x03 : 0x01,
668 			report_id, buf, count);
669 
670 	if (ret_count > 0 && !report_id)
671 		ret_count++;
672 
673 	return ret_count;
674 }
675 
676 static int i2c_hid_output_raw_report(struct hid_device *hid, u8 report_type,
677 				     const u8 *buf, size_t count, bool do_set)
678 {
679 	struct i2c_client *client = hid->driver_data;
680 	struct i2c_hid *ihid = i2c_get_clientdata(client);
681 	int report_id = buf[0];
682 	int ret;
683 
684 	if (report_type == HID_INPUT_REPORT)
685 		return -EINVAL;
686 
687 	mutex_lock(&ihid->reset_lock);
688 
689 	/*
690 	 * Note that both numbered and unnumbered reports passed here
691 	 * are supposed to have report ID stored in the 1st byte of the
692 	 * buffer, so we strip it off unconditionally before passing payload
693 	 * to i2c_hid_set_or_send_report which takes care of encoding
694 	 * everything properly.
695 	 */
696 	ret = i2c_hid_set_or_send_report(ihid,
697 				report_type == HID_FEATURE_REPORT ? 0x03 : 0x02,
698 				report_id, buf + 1, count - 1, do_set);
699 
700 	if (ret >= 0)
701 		ret++; /* add report_id to the number of transferred bytes */
702 
703 	mutex_unlock(&ihid->reset_lock);
704 
705 	return ret;
706 }
707 
708 static int i2c_hid_output_report(struct hid_device *hid, u8 *buf, size_t count)
709 {
710 	return i2c_hid_output_raw_report(hid, HID_OUTPUT_REPORT, buf, count,
711 					 false);
712 }
713 
714 static int i2c_hid_raw_request(struct hid_device *hid, unsigned char reportnum,
715 			       __u8 *buf, size_t len, unsigned char rtype,
716 			       int reqtype)
717 {
718 	switch (reqtype) {
719 	case HID_REQ_GET_REPORT:
720 		return i2c_hid_get_raw_report(hid, rtype, reportnum, buf, len);
721 	case HID_REQ_SET_REPORT:
722 		if (buf[0] != reportnum)
723 			return -EINVAL;
724 		return i2c_hid_output_raw_report(hid, rtype, buf, len, true);
725 	default:
726 		return -EIO;
727 	}
728 }
729 
730 static int i2c_hid_parse(struct hid_device *hid)
731 {
732 	struct i2c_client *client = hid->driver_data;
733 	struct i2c_hid *ihid = i2c_get_clientdata(client);
734 	struct i2c_hid_desc *hdesc = &ihid->hdesc;
735 	unsigned int rsize;
736 	char *rdesc;
737 	int ret;
738 	int tries = 3;
739 	char *use_override;
740 
741 	i2c_hid_dbg(ihid, "entering %s\n", __func__);
742 
743 	rsize = le16_to_cpu(hdesc->wReportDescLength);
744 	if (!rsize || rsize > HID_MAX_DESCRIPTOR_SIZE) {
745 		dbg_hid("weird size of report descriptor (%u)\n", rsize);
746 		return -EINVAL;
747 	}
748 
749 	do {
750 		ret = i2c_hid_hwreset(ihid);
751 		if (ret)
752 			msleep(1000);
753 	} while (tries-- > 0 && ret);
754 
755 	if (ret)
756 		return ret;
757 
758 	use_override = i2c_hid_get_dmi_hid_report_desc_override(client->name,
759 								&rsize);
760 
761 	if (use_override) {
762 		rdesc = use_override;
763 		i2c_hid_dbg(ihid, "Using a HID report descriptor override\n");
764 	} else {
765 		rdesc = kzalloc(rsize, GFP_KERNEL);
766 
767 		if (!rdesc) {
768 			dbg_hid("couldn't allocate rdesc memory\n");
769 			return -ENOMEM;
770 		}
771 
772 		i2c_hid_dbg(ihid, "asking HID report descriptor\n");
773 
774 		ret = i2c_hid_read_register(ihid,
775 					    ihid->hdesc.wReportDescRegister,
776 					    rdesc, rsize);
777 		if (ret) {
778 			hid_err(hid, "reading report descriptor failed\n");
779 			kfree(rdesc);
780 			return -EIO;
781 		}
782 	}
783 
784 	i2c_hid_dbg(ihid, "Report Descriptor: %*ph\n", rsize, rdesc);
785 
786 	ret = hid_parse_report(hid, rdesc, rsize);
787 	if (!use_override)
788 		kfree(rdesc);
789 
790 	if (ret) {
791 		dbg_hid("parsing report descriptor failed\n");
792 		return ret;
793 	}
794 
795 	return 0;
796 }
797 
798 static int i2c_hid_start(struct hid_device *hid)
799 {
800 	struct i2c_client *client = hid->driver_data;
801 	struct i2c_hid *ihid = i2c_get_clientdata(client);
802 	int ret;
803 	unsigned int bufsize = HID_MIN_BUFFER_SIZE;
804 
805 	i2c_hid_find_max_report(hid, HID_INPUT_REPORT, &bufsize);
806 	i2c_hid_find_max_report(hid, HID_OUTPUT_REPORT, &bufsize);
807 	i2c_hid_find_max_report(hid, HID_FEATURE_REPORT, &bufsize);
808 
809 	if (bufsize > ihid->bufsize) {
810 		disable_irq(client->irq);
811 		i2c_hid_free_buffers(ihid);
812 
813 		ret = i2c_hid_alloc_buffers(ihid, bufsize);
814 		enable_irq(client->irq);
815 
816 		if (ret)
817 			return ret;
818 	}
819 
820 	return 0;
821 }
822 
823 static void i2c_hid_stop(struct hid_device *hid)
824 {
825 	hid->claimed = 0;
826 }
827 
828 static int i2c_hid_open(struct hid_device *hid)
829 {
830 	struct i2c_client *client = hid->driver_data;
831 	struct i2c_hid *ihid = i2c_get_clientdata(client);
832 
833 	set_bit(I2C_HID_STARTED, &ihid->flags);
834 	return 0;
835 }
836 
837 static void i2c_hid_close(struct hid_device *hid)
838 {
839 	struct i2c_client *client = hid->driver_data;
840 	struct i2c_hid *ihid = i2c_get_clientdata(client);
841 
842 	clear_bit(I2C_HID_STARTED, &ihid->flags);
843 }
844 
845 struct hid_ll_driver i2c_hid_ll_driver = {
846 	.parse = i2c_hid_parse,
847 	.start = i2c_hid_start,
848 	.stop = i2c_hid_stop,
849 	.open = i2c_hid_open,
850 	.close = i2c_hid_close,
851 	.output_report = i2c_hid_output_report,
852 	.raw_request = i2c_hid_raw_request,
853 };
854 EXPORT_SYMBOL_GPL(i2c_hid_ll_driver);
855 
856 static int i2c_hid_init_irq(struct i2c_client *client)
857 {
858 	struct i2c_hid *ihid = i2c_get_clientdata(client);
859 	unsigned long irqflags = 0;
860 	int ret;
861 
862 	dev_dbg(&client->dev, "Requesting IRQ: %d\n", client->irq);
863 
864 	if (!irq_get_trigger_type(client->irq))
865 		irqflags = IRQF_TRIGGER_LOW;
866 
867 	ret = request_threaded_irq(client->irq, NULL, i2c_hid_irq,
868 				   irqflags | IRQF_ONESHOT, client->name, ihid);
869 	if (ret < 0) {
870 		dev_warn(&client->dev,
871 			"Could not register for %s interrupt, irq = %d,"
872 			" ret = %d\n",
873 			client->name, client->irq, ret);
874 
875 		return ret;
876 	}
877 
878 	return 0;
879 }
880 
881 static int i2c_hid_fetch_hid_descriptor(struct i2c_hid *ihid)
882 {
883 	struct i2c_client *client = ihid->client;
884 	struct i2c_hid_desc *hdesc = &ihid->hdesc;
885 	unsigned int dsize;
886 	int error;
887 
888 	/* i2c hid fetch using a fixed descriptor size (30 bytes) */
889 	if (i2c_hid_get_dmi_i2c_hid_desc_override(client->name)) {
890 		i2c_hid_dbg(ihid, "Using a HID descriptor override\n");
891 		ihid->hdesc =
892 			*i2c_hid_get_dmi_i2c_hid_desc_override(client->name);
893 	} else {
894 		i2c_hid_dbg(ihid, "Fetching the HID descriptor\n");
895 		error = i2c_hid_read_register(ihid,
896 					      ihid->wHIDDescRegister,
897 					      &ihid->hdesc,
898 					      sizeof(ihid->hdesc));
899 		if (error) {
900 			dev_err(&ihid->client->dev,
901 				"failed to fetch HID descriptor: %d\n",
902 				error);
903 			return -ENODEV;
904 		}
905 	}
906 
907 	/* Validate the length of HID descriptor, the 4 first bytes:
908 	 * bytes 0-1 -> length
909 	 * bytes 2-3 -> bcdVersion (has to be 1.00) */
910 	/* check bcdVersion == 1.0 */
911 	if (le16_to_cpu(hdesc->bcdVersion) != 0x0100) {
912 		dev_err(&ihid->client->dev,
913 			"unexpected HID descriptor bcdVersion (0x%04hx)\n",
914 			le16_to_cpu(hdesc->bcdVersion));
915 		return -ENODEV;
916 	}
917 
918 	/* Descriptor length should be 30 bytes as per the specification */
919 	dsize = le16_to_cpu(hdesc->wHIDDescLength);
920 	if (dsize != sizeof(struct i2c_hid_desc)) {
921 		dev_err(&ihid->client->dev,
922 			"weird size of HID descriptor (%u)\n", dsize);
923 		return -ENODEV;
924 	}
925 	i2c_hid_dbg(ihid, "HID Descriptor: %*ph\n", dsize, &ihid->hdesc);
926 	return 0;
927 }
928 
929 static int i2c_hid_core_power_up(struct i2c_hid *ihid)
930 {
931 	if (!ihid->ops->power_up)
932 		return 0;
933 
934 	return ihid->ops->power_up(ihid->ops);
935 }
936 
937 static void i2c_hid_core_power_down(struct i2c_hid *ihid)
938 {
939 	if (!ihid->ops->power_down)
940 		return;
941 
942 	ihid->ops->power_down(ihid->ops);
943 }
944 
945 static void i2c_hid_core_shutdown_tail(struct i2c_hid *ihid)
946 {
947 	if (!ihid->ops->shutdown_tail)
948 		return;
949 
950 	ihid->ops->shutdown_tail(ihid->ops);
951 }
952 
953 int i2c_hid_core_probe(struct i2c_client *client, struct i2chid_ops *ops,
954 		       u16 hid_descriptor_address, u32 quirks)
955 {
956 	int ret;
957 	struct i2c_hid *ihid;
958 	struct hid_device *hid;
959 
960 	dbg_hid("HID probe called for i2c 0x%02x\n", client->addr);
961 
962 	if (!client->irq) {
963 		dev_err(&client->dev,
964 			"HID over i2c has not been provided an Int IRQ\n");
965 		return -EINVAL;
966 	}
967 
968 	if (client->irq < 0) {
969 		if (client->irq != -EPROBE_DEFER)
970 			dev_err(&client->dev,
971 				"HID over i2c doesn't have a valid IRQ\n");
972 		return client->irq;
973 	}
974 
975 	ihid = devm_kzalloc(&client->dev, sizeof(*ihid), GFP_KERNEL);
976 	if (!ihid)
977 		return -ENOMEM;
978 
979 	ihid->ops = ops;
980 
981 	ret = i2c_hid_core_power_up(ihid);
982 	if (ret)
983 		return ret;
984 
985 	i2c_set_clientdata(client, ihid);
986 
987 	ihid->client = client;
988 
989 	ihid->wHIDDescRegister = cpu_to_le16(hid_descriptor_address);
990 
991 	init_waitqueue_head(&ihid->wait);
992 	mutex_init(&ihid->reset_lock);
993 
994 	/* we need to allocate the command buffer without knowing the maximum
995 	 * size of the reports. Let's use HID_MIN_BUFFER_SIZE, then we do the
996 	 * real computation later. */
997 	ret = i2c_hid_alloc_buffers(ihid, HID_MIN_BUFFER_SIZE);
998 	if (ret < 0)
999 		goto err_powered;
1000 
1001 	device_enable_async_suspend(&client->dev);
1002 
1003 	/* Make sure there is something at this address */
1004 	ret = i2c_smbus_read_byte(client);
1005 	if (ret < 0) {
1006 		dev_dbg(&client->dev, "nothing at this address: %d\n", ret);
1007 		ret = -ENXIO;
1008 		goto err_powered;
1009 	}
1010 
1011 	ret = i2c_hid_fetch_hid_descriptor(ihid);
1012 	if (ret < 0) {
1013 		dev_err(&client->dev,
1014 			"Failed to fetch the HID Descriptor\n");
1015 		goto err_powered;
1016 	}
1017 
1018 	ret = i2c_hid_init_irq(client);
1019 	if (ret < 0)
1020 		goto err_powered;
1021 
1022 	hid = hid_allocate_device();
1023 	if (IS_ERR(hid)) {
1024 		ret = PTR_ERR(hid);
1025 		goto err_irq;
1026 	}
1027 
1028 	ihid->hid = hid;
1029 
1030 	hid->driver_data = client;
1031 	hid->ll_driver = &i2c_hid_ll_driver;
1032 	hid->dev.parent = &client->dev;
1033 	hid->bus = BUS_I2C;
1034 	hid->version = le16_to_cpu(ihid->hdesc.bcdVersion);
1035 	hid->vendor = le16_to_cpu(ihid->hdesc.wVendorID);
1036 	hid->product = le16_to_cpu(ihid->hdesc.wProductID);
1037 
1038 	snprintf(hid->name, sizeof(hid->name), "%s %04X:%04X",
1039 		 client->name, (u16)hid->vendor, (u16)hid->product);
1040 	strscpy(hid->phys, dev_name(&client->dev), sizeof(hid->phys));
1041 
1042 	ihid->quirks = i2c_hid_lookup_quirk(hid->vendor, hid->product);
1043 
1044 	ret = hid_add_device(hid);
1045 	if (ret) {
1046 		if (ret != -ENODEV)
1047 			hid_err(client, "can't add hid device: %d\n", ret);
1048 		goto err_mem_free;
1049 	}
1050 
1051 	hid->quirks |= quirks;
1052 
1053 	return 0;
1054 
1055 err_mem_free:
1056 	hid_destroy_device(hid);
1057 
1058 err_irq:
1059 	free_irq(client->irq, ihid);
1060 
1061 err_powered:
1062 	i2c_hid_core_power_down(ihid);
1063 	i2c_hid_free_buffers(ihid);
1064 	return ret;
1065 }
1066 EXPORT_SYMBOL_GPL(i2c_hid_core_probe);
1067 
1068 void i2c_hid_core_remove(struct i2c_client *client)
1069 {
1070 	struct i2c_hid *ihid = i2c_get_clientdata(client);
1071 	struct hid_device *hid;
1072 
1073 	hid = ihid->hid;
1074 	hid_destroy_device(hid);
1075 
1076 	free_irq(client->irq, ihid);
1077 
1078 	if (ihid->bufsize)
1079 		i2c_hid_free_buffers(ihid);
1080 
1081 	i2c_hid_core_power_down(ihid);
1082 }
1083 EXPORT_SYMBOL_GPL(i2c_hid_core_remove);
1084 
1085 void i2c_hid_core_shutdown(struct i2c_client *client)
1086 {
1087 	struct i2c_hid *ihid = i2c_get_clientdata(client);
1088 
1089 	i2c_hid_set_power(ihid, I2C_HID_PWR_SLEEP);
1090 	free_irq(client->irq, ihid);
1091 
1092 	i2c_hid_core_shutdown_tail(ihid);
1093 }
1094 EXPORT_SYMBOL_GPL(i2c_hid_core_shutdown);
1095 
1096 #ifdef CONFIG_PM_SLEEP
1097 static int i2c_hid_core_suspend(struct device *dev)
1098 {
1099 	struct i2c_client *client = to_i2c_client(dev);
1100 	struct i2c_hid *ihid = i2c_get_clientdata(client);
1101 	struct hid_device *hid = ihid->hid;
1102 	int ret;
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 		i2c_hid_core_power_down(ihid);
1115 
1116 	return 0;
1117 }
1118 
1119 static int i2c_hid_core_resume(struct device *dev)
1120 {
1121 	int ret;
1122 	struct i2c_client *client = to_i2c_client(dev);
1123 	struct i2c_hid *ihid = i2c_get_clientdata(client);
1124 	struct hid_device *hid = ihid->hid;
1125 
1126 	if (!device_may_wakeup(&client->dev))
1127 		i2c_hid_core_power_up(ihid);
1128 
1129 	enable_irq(client->irq);
1130 
1131 	/* Instead of resetting device, simply powers the device on. This
1132 	 * solves "incomplete reports" on Raydium devices 2386:3118 and
1133 	 * 2386:4B33 and fixes various SIS touchscreens no longer sending
1134 	 * data after a suspend/resume.
1135 	 *
1136 	 * However some ALPS touchpads generate IRQ storm without reset, so
1137 	 * let's still reset them here.
1138 	 */
1139 	if (ihid->quirks & I2C_HID_QUIRK_RESET_ON_RESUME)
1140 		ret = i2c_hid_hwreset(ihid);
1141 	else
1142 		ret = i2c_hid_set_power(ihid, I2C_HID_PWR_ON);
1143 
1144 	if (ret)
1145 		return ret;
1146 
1147 	return hid_driver_reset_resume(hid);
1148 }
1149 #endif
1150 
1151 const struct dev_pm_ops i2c_hid_core_pm = {
1152 	SET_SYSTEM_SLEEP_PM_OPS(i2c_hid_core_suspend, i2c_hid_core_resume)
1153 };
1154 EXPORT_SYMBOL_GPL(i2c_hid_core_pm);
1155 
1156 MODULE_DESCRIPTION("HID over I2C core driver");
1157 MODULE_AUTHOR("Benjamin Tissoires <benjamin.tissoires@gmail.com>");
1158 MODULE_LICENSE("GPL");
1159