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