ihidev.c revision 1.10
1/* $NetBSD: ihidev.c,v 1.10 2019/12/22 16:44:35 thorpej Exp $ */
2/* $OpenBSD ihidev.c,v 1.13 2017/04/08 02:57:23 deraadt Exp $ */
3
4/*-
5 * Copyright (c) 2017 The NetBSD Foundation, Inc.
6 * All rights reserved.
7 *
8 * This code is derived from software contributed to The NetBSD Foundation
9 * by Manuel Bouyer.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 *    notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 *    notice, this list of conditions and the following disclaimer in the
18 *    documentation and/or other materials provided with the distribution.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
24 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30 * POSSIBILITY OF SUCH DAMAGE.
31 */
32
33/*
34 * Copyright (c) 2015, 2016 joshua stein <jcs@openbsd.org>
35 *
36 * Permission to use, copy, modify, and distribute this software for any
37 * purpose with or without fee is hereby granted, provided that the above
38 * copyright notice and this permission notice appear in all copies.
39 *
40 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
41 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
42 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
43 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
44 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
45 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
46 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
47 */
48
49/*
50 * HID-over-i2c driver
51 *
52 * https://msdn.microsoft.com/en-us/library/windows/hardware/dn642101%28v=vs.85%29.aspx
53 *
54 */
55
56#include <sys/cdefs.h>
57__KERNEL_RCSID(0, "$NetBSD: ihidev.c,v 1.10 2019/12/22 16:44:35 thorpej Exp $");
58
59#include <sys/param.h>
60#include <sys/systm.h>
61#include <sys/device.h>
62#include <sys/kmem.h>
63
64
65#include <dev/i2c/i2cvar.h>
66#include <dev/i2c/ihidev.h>
67
68#include <dev/hid/hid.h>
69
70#if defined(__i386__) || defined(__amd64__)
71#  include "acpica.h"
72#endif
73#if NACPICA > 0
74#include <dev/acpi/acpivar.h>
75#include <dev/acpi/acpi_intr.h>
76#endif
77
78#include "locators.h"
79
80/* #define IHIDEV_DEBUG */
81
82#ifdef IHIDEV_DEBUG
83#define DPRINTF(x) printf x
84#else
85#define DPRINTF(x)
86#endif
87
88/* 7.2 */
89enum {
90	I2C_HID_CMD_DESCR	= 0x0,
91	I2C_HID_CMD_RESET	= 0x1,
92	I2C_HID_CMD_GET_REPORT	= 0x2,
93	I2C_HID_CMD_SET_REPORT	= 0x3,
94	I2C_HID_CMD_GET_IDLE	= 0x4,
95	I2C_HID_CMD_SET_IDLE	= 0x5,
96	I2C_HID_CMD_GET_PROTO	= 0x6,
97	I2C_HID_CMD_SET_PROTO	= 0x7,
98	I2C_HID_CMD_SET_POWER	= 0x8,
99
100	/* pseudo commands */
101	I2C_HID_REPORT_DESCR	= 0x100,
102};
103
104static int I2C_HID_POWER_ON	= 0x0;
105static int I2C_HID_POWER_OFF	= 0x1;
106
107static int	ihidev_match(device_t, cfdata_t, void *);
108static void	ihidev_attach(device_t, device_t, void *);
109static int	ihidev_detach(device_t, int);
110CFATTACH_DECL_NEW(ihidev, sizeof(struct ihidev_softc),
111    ihidev_match, ihidev_attach, ihidev_detach, NULL);
112
113static bool	ihiddev_intr_init(struct ihidev_softc *);
114static void	ihiddev_intr_fini(struct ihidev_softc *);
115
116static bool	ihidev_suspend(device_t, const pmf_qual_t *);
117static bool	ihidev_resume(device_t, const pmf_qual_t *);
118static int	ihidev_hid_command(struct ihidev_softc *, int, void *, bool);
119static int	ihidev_intr(void *);
120static void	ihidev_softintr(void *);
121static int	ihidev_reset(struct ihidev_softc *, bool);
122static int	ihidev_hid_desc_parse(struct ihidev_softc *);
123
124static int	ihidev_maxrepid(void *, int);
125static int	ihidev_print(void *, const char *);
126static int	ihidev_submatch(device_t, cfdata_t, const int *, void *);
127
128static const struct device_compatible_entry compat_data[] = {
129	{ "hid-over-i2c",		0 },
130	{ NULL,				0 }
131};
132
133static int
134ihidev_match(device_t parent, cfdata_t match, void *aux)
135{
136	struct i2c_attach_args * const ia = aux;
137	int match_result;
138
139	if (iic_use_direct_match(ia, match, compat_data, &match_result))
140		return I2C_MATCH_DIRECT_COMPATIBLE;
141
142	return 0;
143}
144
145static void
146ihidev_attach(device_t parent, device_t self, void *aux)
147{
148	struct ihidev_softc *sc = device_private(self);
149	struct i2c_attach_args *ia = aux;
150	struct ihidev_attach_arg iha;
151	device_t dev;
152	int repid, repsz;
153	int isize;
154	uint32_t v;
155	int locs[IHIDBUSCF_NLOCS];
156
157
158	sc->sc_dev = self;
159	sc->sc_tag = ia->ia_tag;
160	sc->sc_addr = ia->ia_addr;
161	sc->sc_phandle = ia->ia_cookie;
162	mutex_init(&sc->sc_intr_lock, MUTEX_DEFAULT, IPL_VM);
163
164	if (!prop_dictionary_get_uint32(ia->ia_prop, "hid-descr-addr", &v)) {
165		aprint_error(": no hid-descr-addr value\n");
166		return;
167	}
168
169	sc->sc_hid_desc_addr = v;
170
171	if (ihidev_hid_command(sc, I2C_HID_CMD_DESCR, NULL, false) ||
172	    ihidev_hid_desc_parse(sc)) {
173		aprint_error(": failed fetching initial HID descriptor\n");
174		return;
175	}
176
177	aprint_naive("\n");
178	aprint_normal(": vendor 0x%x product 0x%x, %s\n",
179	    le16toh(sc->hid_desc.wVendorID), le16toh(sc->hid_desc.wProductID),
180	    ia->ia_name);
181
182	sc->sc_nrepid = ihidev_maxrepid(sc->sc_report, sc->sc_reportlen);
183	if (sc->sc_nrepid < 0)
184		return;
185
186	aprint_normal_dev(self, "%d report id%s\n", sc->sc_nrepid,
187	    sc->sc_nrepid > 1 ? "s" : "");
188
189	sc->sc_nrepid++;
190	sc->sc_subdevs = kmem_zalloc(sc->sc_nrepid * sizeof(struct ihidev *),
191	    KM_SLEEP);
192
193	/* find largest report size and allocate memory for input buffer */
194	sc->sc_isize = le16toh(sc->hid_desc.wMaxInputLength);
195	for (repid = 0; repid < sc->sc_nrepid; repid++) {
196		repsz = hid_report_size(sc->sc_report, sc->sc_reportlen,
197		    hid_input, repid);
198
199		isize = repsz + 2; /* two bytes for the length */
200		isize += (sc->sc_nrepid != 1); /* one byte for the report ID */
201		if (isize > sc->sc_isize)
202			sc->sc_isize = isize;
203
204		DPRINTF(("%s: repid %d size %d\n", sc->sc_dev.dv_xname, repid,
205		    repsz));
206	}
207	sc->sc_ibuf = kmem_zalloc(sc->sc_isize, KM_SLEEP);
208	if (! ihiddev_intr_init(sc)) {
209		return;
210	}
211
212	iha.iaa = ia;
213	iha.parent = sc;
214
215	/* Look for a driver claiming all report IDs first. */
216	iha.reportid = IHIDEV_CLAIM_ALLREPORTID;
217	locs[IHIDBUSCF_REPORTID] = IHIDEV_CLAIM_ALLREPORTID;
218	dev = config_found_sm_loc(self, "ihidbus", locs, &iha,
219	    ihidev_print, ihidev_submatch);
220	if (dev != NULL) {
221		for (repid = 0; repid < sc->sc_nrepid; repid++)
222			sc->sc_subdevs[repid] = device_private(dev);
223		return;
224	}
225
226	for (repid = 0; repid < sc->sc_nrepid; repid++) {
227		if (hid_report_size(sc->sc_report, sc->sc_reportlen, hid_input,
228		    repid) == 0 &&
229		    hid_report_size(sc->sc_report, sc->sc_reportlen,
230		    hid_output, repid) == 0 &&
231		    hid_report_size(sc->sc_report, sc->sc_reportlen,
232		    hid_feature, repid) == 0)
233			continue;
234
235		iha.reportid = repid;
236		locs[IHIDBUSCF_REPORTID] = repid;
237		dev = config_found_sm_loc(self, "ihidbus", locs,
238		    &iha, ihidev_print, ihidev_submatch);
239		sc->sc_subdevs[repid] = device_private(dev);
240	}
241
242	/* power down until we're opened */
243	if (ihidev_hid_command(sc, I2C_HID_CMD_SET_POWER, &I2C_HID_POWER_OFF, false)) {
244		aprint_error_dev(sc->sc_dev, "failed to power down\n");
245		return;
246	}
247	if (!pmf_device_register(self, ihidev_suspend, ihidev_resume))
248		aprint_error_dev(self, "couldn't establish power handler\n");
249}
250
251static int
252ihidev_detach(device_t self, int flags)
253{
254	struct ihidev_softc *sc = device_private(self);
255
256	mutex_enter(&sc->sc_intr_lock);
257	ihiddev_intr_fini(sc);
258	if (ihidev_hid_command(sc, I2C_HID_CMD_SET_POWER,
259	    &I2C_HID_POWER_OFF, true))
260	aprint_error_dev(sc->sc_dev, "failed to power down\n");
261	mutex_exit(&sc->sc_intr_lock);
262	if (sc->sc_ibuf != NULL) {
263		kmem_free(sc->sc_ibuf, sc->sc_isize);
264		sc->sc_ibuf = NULL;
265	}
266
267	if (sc->sc_report != NULL)
268		kmem_free(sc->sc_report, sc->sc_reportlen);
269
270	pmf_device_deregister(self);
271	return (0);
272}
273
274static bool
275ihidev_suspend(device_t self, const pmf_qual_t *q)
276{
277	struct ihidev_softc *sc = device_private(self);
278
279	mutex_enter(&sc->sc_intr_lock);
280	if (sc->sc_refcnt > 0) {
281		printf("ihidev power off\n");
282		if (ihidev_hid_command(sc, I2C_HID_CMD_SET_POWER,
283		    &I2C_HID_POWER_OFF, true))
284		aprint_error_dev(sc->sc_dev, "failed to power down\n");
285	}
286	mutex_exit(&sc->sc_intr_lock);
287	return true;
288}
289
290static bool
291ihidev_resume(device_t self, const pmf_qual_t *q)
292{
293	struct ihidev_softc *sc = device_private(self);
294
295	mutex_enter(&sc->sc_intr_lock);
296	if (sc->sc_refcnt > 0) {
297		printf("ihidev power reset\n");
298		ihidev_reset(sc, true);
299	}
300	mutex_exit(&sc->sc_intr_lock);
301	return true;
302}
303
304static int
305ihidev_hid_command(struct ihidev_softc *sc, int hidcmd, void *arg, bool poll)
306{
307	int i, res = 1;
308	int flags = poll ? I2C_F_POLL : 0;
309
310	iic_acquire_bus(sc->sc_tag, flags);
311
312	switch (hidcmd) {
313	case I2C_HID_CMD_DESCR: {
314		/*
315		 * 5.2.2 - HID Descriptor Retrieval
316		 * register is passed from the controller
317		 */
318		uint8_t cmd[] = {
319			htole16(sc->sc_hid_desc_addr) & 0xff,
320			htole16(sc->sc_hid_desc_addr) >> 8,
321		};
322
323		DPRINTF(("%s: HID command I2C_HID_CMD_DESCR at 0x%x\n",
324		    sc->sc_dev.dv_xname, htole16(sc->sc_hid_desc_addr)));
325
326		/* 20 00 */
327		res = iic_exec(sc->sc_tag, I2C_OP_READ_WITH_STOP, sc->sc_addr,
328		    &cmd, sizeof(cmd), &sc->hid_desc_buf,
329		    sizeof(struct i2c_hid_desc), flags);
330
331		DPRINTF(("%s: HID descriptor:", sc->sc_dev.dv_xname));
332		for (i = 0; i < sizeof(struct i2c_hid_desc); i++)
333			DPRINTF((" %.2x", sc->hid_desc_buf[i]));
334		DPRINTF(("\n"));
335
336		break;
337	}
338	case I2C_HID_CMD_RESET: {
339		uint8_t cmd[] = {
340			htole16(sc->hid_desc.wCommandRegister) & 0xff,
341			htole16(sc->hid_desc.wCommandRegister) >> 8,
342			0,
343			I2C_HID_CMD_RESET,
344		};
345
346		DPRINTF(("%s: HID command I2C_HID_CMD_RESET\n",
347		    sc->sc_dev.dv_xname));
348
349		/* 22 00 00 01 */
350		res = iic_exec(sc->sc_tag, I2C_OP_WRITE_WITH_STOP, sc->sc_addr,
351		    &cmd, sizeof(cmd), NULL, 0, flags);
352
353		break;
354	}
355	case I2C_HID_CMD_GET_REPORT: {
356		struct i2c_hid_report_request *rreq =
357		    (struct i2c_hid_report_request *)arg;
358
359		uint8_t cmd[] = {
360			htole16(sc->hid_desc.wCommandRegister) & 0xff,
361			htole16(sc->hid_desc.wCommandRegister) >> 8,
362			0,
363			I2C_HID_CMD_GET_REPORT,
364			0, 0, 0,
365		};
366		int cmdlen = 7;
367		int dataoff = 4;
368		int report_id = rreq->id;
369		int report_id_len = 1;
370		int report_len = rreq->len + 2;
371		int d;
372		uint8_t *tmprep;
373
374		DPRINTF(("%s: HID command I2C_HID_CMD_GET_REPORT %d "
375		    "(type %d, len %d)\n", sc->sc_dev.dv_xname, report_id,
376		    rreq->type, rreq->len));
377
378		/*
379		 * 7.2.2.4 - "The protocol is optimized for Report < 15.  If a
380		 * report ID >= 15 is necessary, then the Report ID in the Low
381		 * Byte must be set to 1111 and a Third Byte is appended to the
382		 * protocol.  This Third Byte contains the entire/actual report
383		 * ID."
384		 */
385		if (report_id >= 15) {
386			cmd[dataoff++] = report_id;
387			report_id = 15;
388			report_id_len = 2;
389		} else
390			cmdlen--;
391
392		cmd[2] = report_id | rreq->type << 4;
393
394		cmd[dataoff++] = sc->hid_desc.wDataRegister & 0xff;
395		cmd[dataoff] = sc->hid_desc.wDataRegister >> 8;
396
397		/*
398		 * 7.2.2.2 - Response will be a 2-byte length value, the report
399		 * id with length determined above, and then the report.
400		 * Allocate rreq->len + 2 + 2 bytes, read into that temporary
401		 * buffer, and then copy only the report back out to
402		 * rreq->data.
403		 */
404		report_len += report_id_len;
405		tmprep = kmem_zalloc(report_len, KM_NOSLEEP);
406
407		/* type 3 id 8: 22 00 38 02 23 00 */
408		res = iic_exec(sc->sc_tag, I2C_OP_READ_WITH_STOP, sc->sc_addr,
409		    &cmd, cmdlen, tmprep, report_len, flags);
410
411		d = tmprep[0] | tmprep[1] << 8;
412		if (d != report_len) {
413			DPRINTF(("%s: response size %d != expected length %d\n",
414			    sc->sc_dev.dv_xname, d, report_len));
415		}
416
417		if (report_id_len == 2)
418			d = tmprep[2] | tmprep[3] << 8;
419		else
420			d = tmprep[2];
421
422		if (d != rreq->id) {
423			DPRINTF(("%s: response report id %d != %d\n",
424			    sc->sc_dev.dv_xname, d, rreq->id));
425			iic_release_bus(sc->sc_tag, 0);
426			kmem_free(tmprep, report_len);
427			return (1);
428		}
429
430		DPRINTF(("%s: response:", sc->sc_dev.dv_xname));
431		for (i = 0; i < report_len; i++)
432			DPRINTF((" %.2x", tmprep[i]));
433		DPRINTF(("\n"));
434
435		memcpy(rreq->data, tmprep + 2 + report_id_len, rreq->len);
436		kmem_free(tmprep, report_len);
437
438		break;
439	}
440	case I2C_HID_CMD_SET_REPORT: {
441		struct i2c_hid_report_request *rreq =
442		    (struct i2c_hid_report_request *)arg;
443
444		uint8_t cmd[] = {
445			htole16(sc->hid_desc.wCommandRegister) & 0xff,
446			htole16(sc->hid_desc.wCommandRegister) >> 8,
447			0,
448			I2C_HID_CMD_SET_REPORT,
449			0, 0, 0, 0, 0, 0,
450		};
451		int cmdlen = 10;
452		int report_id = rreq->id;
453		int report_len = 2 + (report_id ? 1 : 0) + rreq->len;
454		int dataoff;
455		uint8_t *finalcmd;
456
457		DPRINTF(("%s: HID command I2C_HID_CMD_SET_REPORT %d "
458		    "(type %d, len %d):", sc->sc_dev.dv_xname, report_id,
459		    rreq->type, rreq->len));
460		for (i = 0; i < rreq->len; i++)
461			DPRINTF((" %.2x", ((uint8_t *)rreq->data)[i]));
462		DPRINTF(("\n"));
463
464		/*
465		 * 7.2.2.4 - "The protocol is optimized for Report < 15.  If a
466		 * report ID >= 15 is necessary, then the Report ID in the Low
467		 * Byte must be set to 1111 and a Third Byte is appended to the
468		 * protocol.  This Third Byte contains the entire/actual report
469		 * ID."
470		 */
471		dataoff = 4;
472		if (report_id >= 15) {
473			cmd[dataoff++] = report_id;
474			report_id = 15;
475		} else
476			cmdlen--;
477
478		cmd[2] = report_id | rreq->type << 4;
479
480		if (rreq->type == I2C_HID_REPORT_TYPE_FEATURE) {
481			cmd[dataoff++] = htole16(sc->hid_desc.wDataRegister)
482			    & 0xff;
483			cmd[dataoff++] = htole16(sc->hid_desc.wDataRegister)
484			    >> 8;
485		} else {
486			cmd[dataoff++] = htole16(sc->hid_desc.wOutputRegister)
487			    & 0xff;
488			cmd[dataoff++] = htole16(sc->hid_desc.wOutputRegister)
489			    >> 8;
490		}
491
492		cmd[dataoff++] = report_len & 0xff;
493		cmd[dataoff++] = report_len >> 8;
494		cmd[dataoff] = rreq->id;
495
496		finalcmd = kmem_zalloc(cmdlen + rreq->len, KM_NOSLEEP);
497
498		memcpy(finalcmd, cmd, cmdlen);
499		memcpy(finalcmd + cmdlen, rreq->data, rreq->len);
500
501		/* type 3 id 4: 22 00 34 03 23 00 04 00 04 03 */
502		res = iic_exec(sc->sc_tag, I2C_OP_WRITE_WITH_STOP, sc->sc_addr,
503		    finalcmd, cmdlen + rreq->len, NULL, 0, flags);
504		kmem_free(finalcmd, cmdlen + rreq->len);
505
506 		break;
507 	}
508
509	case I2C_HID_CMD_SET_POWER: {
510		int power = *(int *)arg;
511		uint8_t cmd[] = {
512			htole16(sc->hid_desc.wCommandRegister) & 0xff,
513			htole16(sc->hid_desc.wCommandRegister) >> 8,
514			power,
515			I2C_HID_CMD_SET_POWER,
516		};
517
518		DPRINTF(("%s: HID command I2C_HID_CMD_SET_POWER(%d)\n",
519		    sc->sc_dev.dv_xname, power));
520
521		/* 22 00 00 08 */
522		res = iic_exec(sc->sc_tag, I2C_OP_WRITE_WITH_STOP, sc->sc_addr,
523		    &cmd, sizeof(cmd), NULL, 0, flags);
524
525		break;
526	}
527	case I2C_HID_REPORT_DESCR: {
528		uint8_t cmd[] = {
529			htole16(sc->hid_desc.wReportDescRegister) & 0xff,
530			htole16(sc->hid_desc.wReportDescRegister) >> 8,
531		};
532
533		DPRINTF(("%s: HID command I2C_HID_REPORT_DESCR at 0x%x with "
534		    "size %d\n", sc->sc_dev.dv_xname, cmd[0],
535		    sc->sc_reportlen));
536
537		/* 20 00 */
538		res = iic_exec(sc->sc_tag, I2C_OP_READ_WITH_STOP, sc->sc_addr,
539		    &cmd, sizeof(cmd), sc->sc_report, sc->sc_reportlen, flags);
540
541		DPRINTF(("%s: HID report descriptor:", sc->sc_dev.dv_xname));
542		for (i = 0; i < sc->sc_reportlen; i++)
543			DPRINTF((" %.2x", sc->sc_report[i]));
544		DPRINTF(("\n"));
545
546		break;
547	}
548	default:
549		aprint_error_dev(sc->sc_dev, "unknown command %d\n",
550		    hidcmd);
551	}
552
553	iic_release_bus(sc->sc_tag, flags);
554
555	return (res);
556}
557
558static int
559ihidev_reset(struct ihidev_softc *sc, bool poll)
560{
561	DPRINTF(("%s: resetting\n", sc->sc_dev.dv_xname));
562
563	if (ihidev_hid_command(sc, I2C_HID_CMD_SET_POWER,
564	    &I2C_HID_POWER_ON, poll)) {
565		aprint_error_dev(sc->sc_dev, "failed to power on\n");
566		return (1);
567	}
568
569	DELAY(1000);
570
571	if (ihidev_hid_command(sc, I2C_HID_CMD_RESET, 0, poll)) {
572		aprint_error_dev(sc->sc_dev, "failed to reset hardware\n");
573
574		ihidev_hid_command(sc, I2C_HID_CMD_SET_POWER,
575		    &I2C_HID_POWER_OFF, poll);
576
577		return (1);
578	}
579
580	DELAY(1000);
581
582	return (0);
583}
584
585/*
586 * 5.2.2 - HID Descriptor Retrieval
587 *
588 * parse HID Descriptor that has already been read into hid_desc with
589 * I2C_HID_CMD_DESCR
590 */
591static int
592ihidev_hid_desc_parse(struct ihidev_softc *sc)
593{
594	int retries = 3;
595
596	/* must be v01.00 */
597	if (le16toh(sc->hid_desc.bcdVersion) != 0x0100) {
598		aprint_error_dev(sc->sc_dev,
599		    "bad HID descriptor bcdVersion (0x%x)\n",
600		    le16toh(sc->hid_desc.bcdVersion));
601		return (1);
602	}
603
604	/* must be 30 bytes for v1.00 */
605	if (le16toh(sc->hid_desc.wHIDDescLength !=
606	    sizeof(struct i2c_hid_desc))) {
607		aprint_error_dev(sc->sc_dev,
608		    "bad HID descriptor size (%d != %zu)\n",
609		    le16toh(sc->hid_desc.wHIDDescLength),
610		    sizeof(struct i2c_hid_desc));
611		return (1);
612	}
613
614	if (le16toh(sc->hid_desc.wReportDescLength) <= 0) {
615		aprint_error_dev(sc->sc_dev,
616		    "bad HID report descriptor size (%d)\n",
617		    le16toh(sc->hid_desc.wReportDescLength));
618		return (1);
619	}
620
621	while (retries-- > 0) {
622		if (ihidev_reset(sc, false)) {
623			if (retries == 0)
624				return(1);
625
626			DELAY(1000);
627		}
628		else
629			break;
630	}
631
632	sc->sc_reportlen = le16toh(sc->hid_desc.wReportDescLength);
633	sc->sc_report = kmem_zalloc(sc->sc_reportlen, KM_NOSLEEP);
634
635	if (ihidev_hid_command(sc, I2C_HID_REPORT_DESCR, 0, false)) {
636		aprint_error_dev(sc->sc_dev, "failed fetching HID report\n");
637		return (1);
638	}
639
640	return (0);
641}
642
643static bool
644ihiddev_intr_init(struct ihidev_softc *sc)
645{
646#if NACPICA > 0
647	ACPI_HANDLE hdl = (void *)(uintptr_t)sc->sc_phandle;
648	struct acpi_resources res;
649	ACPI_STATUS rv;
650	char buf[100];
651
652	rv = acpi_resource_parse(sc->sc_dev, hdl, "_CRS", &res,
653	    &acpi_resource_parse_ops_quiet);
654	if (ACPI_FAILURE(rv)) {
655		aprint_error_dev(sc->sc_dev, "can't parse '_CRS'\n");
656		return false;
657	}
658
659	const struct acpi_irq * const irq = acpi_res_irq(&res, 0);
660	if (irq == NULL) {
661		aprint_error_dev(sc->sc_dev, "no IRQ resource\n");
662		acpi_resource_cleanup(&res);
663		return false;
664	}
665
666	sc->sc_intr_type =
667	    irq->ar_type == ACPI_EDGE_SENSITIVE ? IST_EDGE : IST_LEVEL;
668
669	acpi_resource_cleanup(&res);
670
671	sc->sc_ih = acpi_intr_establish(sc->sc_dev, sc->sc_phandle, IPL_TTY,
672	    false, ihidev_intr, sc, device_xname(sc->sc_dev));
673	if (sc->sc_ih == NULL) {
674		aprint_error_dev(sc->sc_dev, "can't establish interrupt\n");
675		return false;
676	}
677	aprint_normal_dev(sc->sc_dev, "interrupting at %s\n",
678	    acpi_intr_string(sc->sc_ih, buf, sizeof(buf)));
679
680	sc->sc_sih = softint_establish(SOFTINT_SERIAL, ihidev_softintr, sc);
681	if (sc->sc_sih == NULL) {
682		aprint_error_dev(sc->sc_dev,
683		    "can't establish soft interrupt\n");
684		return false;
685	}
686
687	return true;
688#else
689	aprint_error_dev(sc->sc_dev, "can't establish interrupt\n");
690	return false;
691#endif
692}
693
694static void
695ihiddev_intr_fini(struct ihidev_softc *sc)
696{
697#if NACPICA > 0
698	if (sc->sc_ih != NULL) {
699		acpi_intr_disestablish(sc->sc_ih);
700	}
701	if (sc->sc_sih != NULL) {
702		softint_disestablish(sc->sc_sih);
703	}
704#endif
705}
706
707static int
708ihidev_intr(void *arg)
709{
710	struct ihidev_softc * const sc = arg;
711
712	mutex_enter(&sc->sc_intr_lock);
713
714	/*
715	 * Schedule our soft interrupt handler.  If we're using a level-
716	 * triggered interrupt, we have to mask it off while we wait
717	 * for service.
718	 */
719	softint_schedule(sc->sc_sih);
720	if (sc->sc_intr_type == IST_LEVEL) {
721#if NACPICA > 0
722		acpi_intr_mask(sc->sc_ih);
723#endif
724	}
725
726	mutex_exit(&sc->sc_intr_lock);
727
728	return 1;
729}
730
731static void
732ihidev_softintr(void *arg)
733{
734	struct ihidev_softc * const sc = arg;
735	struct ihidev *scd;
736	u_int psize;
737	int res, i;
738	u_char *p;
739	u_int rep = 0;
740
741	iic_acquire_bus(sc->sc_tag, 0);
742	res = iic_exec(sc->sc_tag, I2C_OP_READ_WITH_STOP, sc->sc_addr, NULL, 0,
743	    sc->sc_ibuf, sc->sc_isize, 0);
744	iic_release_bus(sc->sc_tag, 0);
745	if (res != 0)
746		goto out;
747
748	/*
749	 * 6.1.1 - First two bytes are the packet length, which must be less
750	 * than or equal to wMaxInputLength
751	 */
752	psize = sc->sc_ibuf[0] | sc->sc_ibuf[1] << 8;
753	if (!psize || psize > sc->sc_isize) {
754		DPRINTF(("%s: %s: invalid packet size (%d vs. %d)\n",
755		    sc->sc_dev.dv_xname, __func__, psize, sc->sc_isize));
756		goto out;
757	}
758
759	/* 3rd byte is the report id */
760	p = sc->sc_ibuf + 2;
761	psize -= 2;
762	if (sc->sc_nrepid != 1)
763		rep = *p++, psize--;
764
765	if (rep >= sc->sc_nrepid) {
766		aprint_error_dev(sc->sc_dev, "%s: bad report id %d\n",
767		    __func__, rep);
768		goto out;
769	}
770
771	DPRINTF(("%s: %s: hid input (rep %d):", sc->sc_dev.dv_xname,
772	    __func__, rep));
773	for (i = 0; i < sc->sc_isize; i++)
774		DPRINTF((" %.2x", sc->sc_ibuf[i]));
775	DPRINTF(("\n"));
776
777	scd = sc->sc_subdevs[rep];
778	if (scd == NULL || !(scd->sc_state & IHIDEV_OPEN))
779		goto out;
780
781	scd->sc_intr(scd, p, psize);
782
783 out:
784	/*
785	 * If our interrupt is level-triggered, re-enable it now.
786	 */
787	if (sc->sc_intr_type == IST_LEVEL) {
788#if NACPICA > 0
789		acpi_intr_unmask(sc->sc_ih);
790#endif
791	}
792}
793
794static int
795ihidev_maxrepid(void *buf, int len)
796{
797	struct hid_data *d;
798	struct hid_item h;
799	int maxid;
800
801	maxid = -1;
802	h.report_ID = 0;
803	for (d = hid_start_parse(buf, len, hid_none); hid_get_item(d, &h); )
804		if ((int)h.report_ID > maxid)
805			maxid = h.report_ID;
806	hid_end_parse(d);
807
808	return (maxid);
809}
810
811static int
812ihidev_print(void *aux, const char *pnp)
813{
814	struct ihidev_attach_arg *iha = aux;
815
816	if (iha->reportid == IHIDEV_CLAIM_ALLREPORTID)
817		return (QUIET);
818
819	if (pnp)
820		aprint_normal("hid at %s", pnp);
821
822	if (iha->reportid != 0)
823		aprint_normal(" reportid %d", iha->reportid);
824
825	return (UNCONF);
826}
827
828static int
829ihidev_submatch(device_t parent, cfdata_t cf, const int *locs, void *aux)
830{
831	struct ihidev_attach_arg *iha = aux;
832
833	if (cf->ihidevcf_reportid != IHIDEV_UNK_REPORTID &&
834	    cf->ihidevcf_reportid != iha->reportid)
835		return (0);
836
837	return config_match(parent, cf, aux);
838}
839
840int
841ihidev_open(struct ihidev *scd)
842{
843	struct ihidev_softc *sc = scd->sc_parent;
844
845	DPRINTF(("%s: %s: state=%d refcnt=%d\n", sc->sc_dev.dv_xname,
846	    __func__, scd->sc_state, sc->sc_refcnt));
847
848	if (scd->sc_state & IHIDEV_OPEN)
849		return (EBUSY);
850
851	scd->sc_state |= IHIDEV_OPEN;
852
853	if (sc->sc_refcnt++ || sc->sc_isize == 0)
854		return (0);
855
856	/* power on */
857	ihidev_reset(sc, false);
858
859	return (0);
860}
861
862void
863ihidev_close(struct ihidev *scd)
864{
865	struct ihidev_softc *sc = scd->sc_parent;
866
867	DPRINTF(("%s: %s: state=%d refcnt=%d\n", sc->sc_dev.dv_xname,
868	    __func__, scd->sc_state, sc->sc_refcnt));
869
870	if (!(scd->sc_state & IHIDEV_OPEN))
871		return;
872
873	scd->sc_state &= ~IHIDEV_OPEN;
874
875	if (--sc->sc_refcnt)
876		return;
877
878	if (ihidev_hid_command(sc, I2C_HID_CMD_SET_POWER,
879	    &I2C_HID_POWER_OFF, false))
880		aprint_error_dev(sc->sc_dev, "failed to power down\n");
881}
882
883void
884ihidev_get_report_desc(struct ihidev_softc *sc, void **desc, int *size)
885{
886	*desc = sc->sc_report;
887	*size = sc->sc_reportlen;
888}
889
890/* convert hid_* constants used throughout HID code to i2c HID equivalents */
891int
892ihidev_report_type_conv(int hid_type_id)
893{
894	switch (hid_type_id) {
895	case hid_input:
896		return I2C_HID_REPORT_TYPE_INPUT;
897	case hid_output:
898		return I2C_HID_REPORT_TYPE_OUTPUT;
899	case hid_feature:
900		return I2C_HID_REPORT_TYPE_FEATURE;
901	default:
902		return -1;
903	}
904}
905
906int
907ihidev_get_report(struct device *dev, int type, int id, void *data, int len)
908{
909	struct ihidev_softc *sc = (struct ihidev_softc *)dev;
910	struct i2c_hid_report_request rreq;
911	int ctype;
912
913	if ((ctype = ihidev_report_type_conv(type)) < 0)
914		return (1);
915
916	rreq.type = ctype;
917	rreq.id = id;
918	rreq.data = data;
919	rreq.len = len;
920
921	if (ihidev_hid_command(sc, I2C_HID_CMD_GET_REPORT, &rreq, false)) {
922		aprint_error_dev(sc->sc_dev, "failed fetching report\n");
923		return (1);
924	}
925
926	return 0;
927}
928
929int
930ihidev_set_report(struct device *dev, int type, int id, void *data,
931    int len)
932{
933	struct ihidev_softc *sc = (struct ihidev_softc *)dev;
934	struct i2c_hid_report_request rreq;
935	int ctype;
936
937	if ((ctype = ihidev_report_type_conv(type)) < 0)
938		return (1);
939
940	rreq.type = ctype;
941	rreq.id = id;
942	rreq.data = data;
943	rreq.len = len;
944
945	if (ihidev_hid_command(sc, I2C_HID_CMD_SET_REPORT, &rreq, false)) {
946		aprint_error_dev(sc->sc_dev, "failed setting report\n");
947		return (1);
948	}
949
950	return 0;
951}
952