xref: /netbsd-src/sys/dev/i2c/ihidev.c (revision 53b02e147d4ed531c0d2a5ca9b3e8026ba3e99b5)
1 /* $NetBSD: ihidev.c,v 1.20 2021/08/07 16:19:11 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.20 2021/08/07 16:19:11 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 */
89 enum {
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 
104 static int I2C_HID_POWER_ON	= 0x0;
105 static int I2C_HID_POWER_OFF	= 0x1;
106 
107 static int	ihidev_match(device_t, cfdata_t, void *);
108 static void	ihidev_attach(device_t, device_t, void *);
109 static int	ihidev_detach(device_t, int);
110 CFATTACH_DECL_NEW(ihidev, sizeof(struct ihidev_softc),
111     ihidev_match, ihidev_attach, ihidev_detach, NULL);
112 
113 static bool	ihiddev_intr_init(struct ihidev_softc *);
114 static void	ihiddev_intr_fini(struct ihidev_softc *);
115 
116 static bool	ihidev_suspend(device_t, const pmf_qual_t *);
117 static bool	ihidev_resume(device_t, const pmf_qual_t *);
118 static int	ihidev_hid_command(struct ihidev_softc *, int, void *, bool);
119 static int	ihidev_intr(void *);
120 static void	ihidev_softintr(void *);
121 static int	ihidev_reset(struct ihidev_softc *, bool);
122 static int	ihidev_hid_desc_parse(struct ihidev_softc *);
123 
124 static int	ihidev_maxrepid(void *, int);
125 static int	ihidev_print(void *, const char *);
126 static int	ihidev_submatch(device_t, cfdata_t, const int *, void *);
127 
128 static bool	ihidev_acpi_get_info(struct ihidev_softc *);
129 
130 static const struct device_compatible_entry compat_data[] = {
131 	{ .compat = "PNP0C50" },
132 	{ .compat = "ACPI0C50" },
133 	{ .compat = "hid-over-i2c" },
134 	DEVICE_COMPAT_EOL
135 };
136 
137 static int
138 ihidev_match(device_t parent, cfdata_t match, void *aux)
139 {
140 	struct i2c_attach_args * const ia = aux;
141 	int match_result;
142 
143 	if (iic_use_direct_match(ia, match, compat_data, &match_result))
144 		return I2C_MATCH_DIRECT_COMPATIBLE;
145 
146 	return 0;
147 }
148 
149 static void
150 ihidev_attach(device_t parent, device_t self, void *aux)
151 {
152 	struct ihidev_softc *sc = device_private(self);
153 	struct i2c_attach_args *ia = aux;
154 	struct ihidev_attach_arg iha;
155 	device_t dev;
156 	int repid, repsz;
157 	int isize;
158 	int locs[IHIDBUSCF_NLOCS];
159 
160 	sc->sc_dev = self;
161 	sc->sc_tag = ia->ia_tag;
162 	sc->sc_addr = ia->ia_addr;
163 	mutex_init(&sc->sc_intr_lock, MUTEX_DEFAULT, IPL_VM);
164 
165 	sc->sc_phandle = ia->ia_cookie;
166 	if (ia->ia_cookietype != I2C_COOKIE_ACPI) {
167 		aprint_error(": unsupported device tree type\n");
168 		return;
169 	}
170 	if (! ihidev_acpi_get_info(sc)) {
171 		return;
172 	}
173 
174 	if (ihidev_hid_command(sc, I2C_HID_CMD_DESCR, NULL, false) ||
175 	    ihidev_hid_desc_parse(sc)) {
176 		aprint_error(": failed fetching initial HID descriptor\n");
177 		return;
178 	}
179 
180 	aprint_naive("\n");
181 	aprint_normal(": vendor 0x%x product 0x%x, %s\n",
182 	    le16toh(sc->hid_desc.wVendorID), le16toh(sc->hid_desc.wProductID),
183 	    ia->ia_name);
184 
185 	sc->sc_nrepid = ihidev_maxrepid(sc->sc_report, sc->sc_reportlen);
186 	if (sc->sc_nrepid < 0)
187 		return;
188 
189 	aprint_normal_dev(self, "%d report id%s\n", sc->sc_nrepid,
190 	    sc->sc_nrepid > 1 ? "s" : "");
191 
192 	sc->sc_nrepid++;
193 	sc->sc_subdevs = kmem_zalloc(sc->sc_nrepid * sizeof(struct ihidev *),
194 	    KM_SLEEP);
195 
196 	/* find largest report size and allocate memory for input buffer */
197 	sc->sc_isize = le16toh(sc->hid_desc.wMaxInputLength);
198 	for (repid = 0; repid < sc->sc_nrepid; repid++) {
199 		repsz = hid_report_size(sc->sc_report, sc->sc_reportlen,
200 		    hid_input, repid);
201 
202 		isize = repsz + 2; /* two bytes for the length */
203 		isize += (sc->sc_nrepid != 1); /* one byte for the report ID */
204 		if (isize > sc->sc_isize)
205 			sc->sc_isize = isize;
206 
207 		DPRINTF(("%s: repid %d size %d\n", sc->sc_dev.dv_xname, repid,
208 		    repsz));
209 	}
210 	sc->sc_ibuf = kmem_zalloc(sc->sc_isize, KM_SLEEP);
211 	if (! ihiddev_intr_init(sc)) {
212 		return;
213 	}
214 
215 	iha.iaa = ia;
216 	iha.parent = sc;
217 
218 	/* Look for a driver claiming all report IDs first. */
219 	iha.reportid = IHIDEV_CLAIM_ALLREPORTID;
220 	locs[IHIDBUSCF_REPORTID] = IHIDEV_CLAIM_ALLREPORTID;
221 	dev = config_found(self, &iha, ihidev_print,
222 	    CFARGS(.submatch = ihidev_submatch,
223 		   .locators = locs));
224 	if (dev != NULL) {
225 		for (repid = 0; repid < sc->sc_nrepid; repid++)
226 			sc->sc_subdevs[repid] = device_private(dev);
227 		return;
228 	}
229 
230 	for (repid = 0; repid < sc->sc_nrepid; repid++) {
231 		if (hid_report_size(sc->sc_report, sc->sc_reportlen, hid_input,
232 		    repid) == 0 &&
233 		    hid_report_size(sc->sc_report, sc->sc_reportlen,
234 		    hid_output, repid) == 0 &&
235 		    hid_report_size(sc->sc_report, sc->sc_reportlen,
236 		    hid_feature, repid) == 0)
237 			continue;
238 
239 		iha.reportid = repid;
240 		locs[IHIDBUSCF_REPORTID] = repid;
241 		dev = config_found(self, &iha, ihidev_print,
242 		    CFARGS(.submatch = ihidev_submatch,
243 			   .locators = locs));
244 		sc->sc_subdevs[repid] = device_private(dev);
245 	}
246 
247 	/* power down until we're opened */
248 	if (ihidev_hid_command(sc, I2C_HID_CMD_SET_POWER, &I2C_HID_POWER_OFF, false)) {
249 		aprint_error_dev(sc->sc_dev, "failed to power down\n");
250 		return;
251 	}
252 	if (!pmf_device_register(self, ihidev_suspend, ihidev_resume))
253 		aprint_error_dev(self, "couldn't establish power handler\n");
254 }
255 
256 static int
257 ihidev_detach(device_t self, int flags)
258 {
259 	struct ihidev_softc *sc = device_private(self);
260 
261 	mutex_enter(&sc->sc_intr_lock);
262 	ihiddev_intr_fini(sc);
263 	if (ihidev_hid_command(sc, I2C_HID_CMD_SET_POWER,
264 	    &I2C_HID_POWER_OFF, true))
265 	aprint_error_dev(sc->sc_dev, "failed to power down\n");
266 	mutex_exit(&sc->sc_intr_lock);
267 	if (sc->sc_ibuf != NULL) {
268 		kmem_free(sc->sc_ibuf, sc->sc_isize);
269 		sc->sc_ibuf = NULL;
270 	}
271 
272 	if (sc->sc_report != NULL)
273 		kmem_free(sc->sc_report, sc->sc_reportlen);
274 
275 	pmf_device_deregister(self);
276 	return (0);
277 }
278 
279 static bool
280 ihidev_suspend(device_t self, const pmf_qual_t *q)
281 {
282 	struct ihidev_softc *sc = device_private(self);
283 
284 	mutex_enter(&sc->sc_intr_lock);
285 	if (sc->sc_refcnt > 0) {
286 		printf("ihidev power off\n");
287 		if (ihidev_hid_command(sc, I2C_HID_CMD_SET_POWER,
288 		    &I2C_HID_POWER_OFF, true))
289 		aprint_error_dev(sc->sc_dev, "failed to power down\n");
290 	}
291 	mutex_exit(&sc->sc_intr_lock);
292 	return true;
293 }
294 
295 static bool
296 ihidev_resume(device_t self, const pmf_qual_t *q)
297 {
298 	struct ihidev_softc *sc = device_private(self);
299 
300 	mutex_enter(&sc->sc_intr_lock);
301 	if (sc->sc_refcnt > 0) {
302 		printf("ihidev power reset\n");
303 		ihidev_reset(sc, true);
304 	}
305 	mutex_exit(&sc->sc_intr_lock);
306 	return true;
307 }
308 
309 static int
310 ihidev_hid_command(struct ihidev_softc *sc, int hidcmd, void *arg, bool poll)
311 {
312 	int i, res = 1;
313 	int flags = poll ? I2C_F_POLL : 0;
314 
315 	iic_acquire_bus(sc->sc_tag, flags);
316 
317 	switch (hidcmd) {
318 	case I2C_HID_CMD_DESCR: {
319 		/*
320 		 * 5.2.2 - HID Descriptor Retrieval
321 		 * register is passed from the controller
322 		 */
323 		uint8_t cmd[] = {
324 			htole16(sc->sc_hid_desc_addr) & 0xff,
325 			htole16(sc->sc_hid_desc_addr) >> 8,
326 		};
327 
328 		DPRINTF(("%s: HID command I2C_HID_CMD_DESCR at 0x%x\n",
329 		    sc->sc_dev.dv_xname, htole16(sc->sc_hid_desc_addr)));
330 
331 		/* 20 00 */
332 		res = iic_exec(sc->sc_tag, I2C_OP_READ_WITH_STOP, sc->sc_addr,
333 		    &cmd, sizeof(cmd), &sc->hid_desc_buf,
334 		    sizeof(struct i2c_hid_desc), flags);
335 
336 		DPRINTF(("%s: HID descriptor:", sc->sc_dev.dv_xname));
337 		for (i = 0; i < sizeof(struct i2c_hid_desc); i++)
338 			DPRINTF((" %.2x", sc->hid_desc_buf[i]));
339 		DPRINTF(("\n"));
340 
341 		break;
342 	}
343 	case I2C_HID_CMD_RESET: {
344 		uint8_t cmd[] = {
345 			htole16(sc->hid_desc.wCommandRegister) & 0xff,
346 			htole16(sc->hid_desc.wCommandRegister) >> 8,
347 			0,
348 			I2C_HID_CMD_RESET,
349 		};
350 
351 		DPRINTF(("%s: HID command I2C_HID_CMD_RESET\n",
352 		    sc->sc_dev.dv_xname));
353 
354 		/* 22 00 00 01 */
355 		res = iic_exec(sc->sc_tag, I2C_OP_WRITE_WITH_STOP, sc->sc_addr,
356 		    &cmd, sizeof(cmd), NULL, 0, flags);
357 
358 		break;
359 	}
360 	case I2C_HID_CMD_GET_REPORT: {
361 		struct i2c_hid_report_request *rreq =
362 		    (struct i2c_hid_report_request *)arg;
363 
364 		uint8_t cmd[] = {
365 			htole16(sc->hid_desc.wCommandRegister) & 0xff,
366 			htole16(sc->hid_desc.wCommandRegister) >> 8,
367 			0,
368 			I2C_HID_CMD_GET_REPORT,
369 			0, 0, 0,
370 		};
371 		int cmdlen = 7;
372 		int dataoff = 4;
373 		int report_id = rreq->id;
374 		int report_id_len = 1;
375 		int report_len = rreq->len + 2;
376 		int d;
377 		uint8_t *tmprep;
378 
379 		DPRINTF(("%s: HID command I2C_HID_CMD_GET_REPORT %d "
380 		    "(type %d, len %d)\n", sc->sc_dev.dv_xname, report_id,
381 		    rreq->type, rreq->len));
382 
383 		/*
384 		 * 7.2.2.4 - "The protocol is optimized for Report < 15.  If a
385 		 * report ID >= 15 is necessary, then the Report ID in the Low
386 		 * Byte must be set to 1111 and a Third Byte is appended to the
387 		 * protocol.  This Third Byte contains the entire/actual report
388 		 * ID."
389 		 */
390 		if (report_id >= 15) {
391 			cmd[dataoff++] = report_id;
392 			report_id = 15;
393 			report_id_len = 2;
394 		} else
395 			cmdlen--;
396 
397 		cmd[2] = report_id | rreq->type << 4;
398 
399 		cmd[dataoff++] = sc->hid_desc.wDataRegister & 0xff;
400 		cmd[dataoff] = sc->hid_desc.wDataRegister >> 8;
401 
402 		/*
403 		 * 7.2.2.2 - Response will be a 2-byte length value, the report
404 		 * id with length determined above, and then the report.
405 		 * Allocate rreq->len + 2 + 2 bytes, read into that temporary
406 		 * buffer, and then copy only the report back out to
407 		 * rreq->data.
408 		 */
409 		report_len += report_id_len;
410 		tmprep = kmem_zalloc(report_len, KM_NOSLEEP);
411 
412 		/* type 3 id 8: 22 00 38 02 23 00 */
413 		res = iic_exec(sc->sc_tag, I2C_OP_READ_WITH_STOP, sc->sc_addr,
414 		    &cmd, cmdlen, tmprep, report_len, flags);
415 
416 		d = tmprep[0] | tmprep[1] << 8;
417 		if (d != report_len) {
418 			DPRINTF(("%s: response size %d != expected length %d\n",
419 			    sc->sc_dev.dv_xname, d, report_len));
420 		}
421 
422 		if (report_id_len == 2)
423 			d = tmprep[2] | tmprep[3] << 8;
424 		else
425 			d = tmprep[2];
426 
427 		if (d != rreq->id) {
428 			DPRINTF(("%s: response report id %d != %d\n",
429 			    sc->sc_dev.dv_xname, d, rreq->id));
430 			iic_release_bus(sc->sc_tag, 0);
431 			kmem_free(tmprep, report_len);
432 			return (1);
433 		}
434 
435 		DPRINTF(("%s: response:", sc->sc_dev.dv_xname));
436 		for (i = 0; i < report_len; i++)
437 			DPRINTF((" %.2x", tmprep[i]));
438 		DPRINTF(("\n"));
439 
440 		memcpy(rreq->data, tmprep + 2 + report_id_len, rreq->len);
441 		kmem_free(tmprep, report_len);
442 
443 		break;
444 	}
445 	case I2C_HID_CMD_SET_REPORT: {
446 		struct i2c_hid_report_request *rreq =
447 		    (struct i2c_hid_report_request *)arg;
448 
449 		uint8_t cmd[] = {
450 			htole16(sc->hid_desc.wCommandRegister) & 0xff,
451 			htole16(sc->hid_desc.wCommandRegister) >> 8,
452 			0,
453 			I2C_HID_CMD_SET_REPORT,
454 			0, 0, 0, 0, 0, 0,
455 		};
456 		int cmdlen = 10;
457 		int report_id = rreq->id;
458 		int report_len = 2 + (report_id ? 1 : 0) + rreq->len;
459 		int dataoff;
460 		uint8_t *finalcmd;
461 
462 		DPRINTF(("%s: HID command I2C_HID_CMD_SET_REPORT %d "
463 		    "(type %d, len %d):", sc->sc_dev.dv_xname, report_id,
464 		    rreq->type, rreq->len));
465 		for (i = 0; i < rreq->len; i++)
466 			DPRINTF((" %.2x", ((uint8_t *)rreq->data)[i]));
467 		DPRINTF(("\n"));
468 
469 		/*
470 		 * 7.2.2.4 - "The protocol is optimized for Report < 15.  If a
471 		 * report ID >= 15 is necessary, then the Report ID in the Low
472 		 * Byte must be set to 1111 and a Third Byte is appended to the
473 		 * protocol.  This Third Byte contains the entire/actual report
474 		 * ID."
475 		 */
476 		dataoff = 4;
477 		if (report_id >= 15) {
478 			cmd[dataoff++] = report_id;
479 			report_id = 15;
480 		} else
481 			cmdlen--;
482 
483 		cmd[2] = report_id | rreq->type << 4;
484 
485 		if (rreq->type == I2C_HID_REPORT_TYPE_FEATURE) {
486 			cmd[dataoff++] = htole16(sc->hid_desc.wDataRegister)
487 			    & 0xff;
488 			cmd[dataoff++] = htole16(sc->hid_desc.wDataRegister)
489 			    >> 8;
490 		} else {
491 			cmd[dataoff++] = htole16(sc->hid_desc.wOutputRegister)
492 			    & 0xff;
493 			cmd[dataoff++] = htole16(sc->hid_desc.wOutputRegister)
494 			    >> 8;
495 		}
496 
497 		cmd[dataoff++] = report_len & 0xff;
498 		cmd[dataoff++] = report_len >> 8;
499 		cmd[dataoff] = rreq->id;
500 
501 		finalcmd = kmem_zalloc(cmdlen + rreq->len, KM_NOSLEEP);
502 
503 		memcpy(finalcmd, cmd, cmdlen);
504 		memcpy(finalcmd + cmdlen, rreq->data, rreq->len);
505 
506 		/* type 3 id 4: 22 00 34 03 23 00 04 00 04 03 */
507 		res = iic_exec(sc->sc_tag, I2C_OP_WRITE_WITH_STOP, sc->sc_addr,
508 		    finalcmd, cmdlen + rreq->len, NULL, 0, flags);
509 		kmem_free(finalcmd, cmdlen + rreq->len);
510 
511  		break;
512  	}
513 
514 	case I2C_HID_CMD_SET_POWER: {
515 		int power = *(int *)arg;
516 		uint8_t cmd[] = {
517 			htole16(sc->hid_desc.wCommandRegister) & 0xff,
518 			htole16(sc->hid_desc.wCommandRegister) >> 8,
519 			power,
520 			I2C_HID_CMD_SET_POWER,
521 		};
522 
523 		DPRINTF(("%s: HID command I2C_HID_CMD_SET_POWER(%d)\n",
524 		    sc->sc_dev.dv_xname, power));
525 
526 		/* 22 00 00 08 */
527 		res = iic_exec(sc->sc_tag, I2C_OP_WRITE_WITH_STOP, sc->sc_addr,
528 		    &cmd, sizeof(cmd), NULL, 0, flags);
529 
530 		break;
531 	}
532 	case I2C_HID_REPORT_DESCR: {
533 		uint8_t cmd[] = {
534 			htole16(sc->hid_desc.wReportDescRegister) & 0xff,
535 			htole16(sc->hid_desc.wReportDescRegister) >> 8,
536 		};
537 
538 		DPRINTF(("%s: HID command I2C_HID_REPORT_DESCR at 0x%x with "
539 		    "size %d\n", sc->sc_dev.dv_xname, cmd[0],
540 		    sc->sc_reportlen));
541 
542 		/* 20 00 */
543 		res = iic_exec(sc->sc_tag, I2C_OP_READ_WITH_STOP, sc->sc_addr,
544 		    &cmd, sizeof(cmd), sc->sc_report, sc->sc_reportlen, flags);
545 
546 		DPRINTF(("%s: HID report descriptor:", sc->sc_dev.dv_xname));
547 		for (i = 0; i < sc->sc_reportlen; i++)
548 			DPRINTF((" %.2x", sc->sc_report[i]));
549 		DPRINTF(("\n"));
550 
551 		break;
552 	}
553 	default:
554 		aprint_error_dev(sc->sc_dev, "unknown command %d\n",
555 		    hidcmd);
556 	}
557 
558 	iic_release_bus(sc->sc_tag, flags);
559 
560 	return (res);
561 }
562 
563 static int
564 ihidev_reset(struct ihidev_softc *sc, bool poll)
565 {
566 	DPRINTF(("%s: resetting\n", sc->sc_dev.dv_xname));
567 
568 	if (ihidev_hid_command(sc, I2C_HID_CMD_SET_POWER,
569 	    &I2C_HID_POWER_ON, poll)) {
570 		aprint_error_dev(sc->sc_dev, "failed to power on\n");
571 		return (1);
572 	}
573 
574 	DELAY(1000);
575 
576 	if (ihidev_hid_command(sc, I2C_HID_CMD_RESET, 0, poll)) {
577 		aprint_error_dev(sc->sc_dev, "failed to reset hardware\n");
578 
579 		ihidev_hid_command(sc, I2C_HID_CMD_SET_POWER,
580 		    &I2C_HID_POWER_OFF, poll);
581 
582 		return (1);
583 	}
584 
585 	DELAY(1000);
586 
587 	return (0);
588 }
589 
590 /*
591  * 5.2.2 - HID Descriptor Retrieval
592  *
593  * parse HID Descriptor that has already been read into hid_desc with
594  * I2C_HID_CMD_DESCR
595  */
596 static int
597 ihidev_hid_desc_parse(struct ihidev_softc *sc)
598 {
599 	int retries = 3;
600 
601 	/* must be v01.00 */
602 	if (le16toh(sc->hid_desc.bcdVersion) != 0x0100) {
603 		aprint_error_dev(sc->sc_dev,
604 		    "bad HID descriptor bcdVersion (0x%x)\n",
605 		    le16toh(sc->hid_desc.bcdVersion));
606 		return (1);
607 	}
608 
609 	/* must be 30 bytes for v1.00 */
610 	if (le16toh(sc->hid_desc.wHIDDescLength !=
611 	    sizeof(struct i2c_hid_desc))) {
612 		aprint_error_dev(sc->sc_dev,
613 		    "bad HID descriptor size (%d != %zu)\n",
614 		    le16toh(sc->hid_desc.wHIDDescLength),
615 		    sizeof(struct i2c_hid_desc));
616 		return (1);
617 	}
618 
619 	if (le16toh(sc->hid_desc.wReportDescLength) <= 0) {
620 		aprint_error_dev(sc->sc_dev,
621 		    "bad HID report descriptor size (%d)\n",
622 		    le16toh(sc->hid_desc.wReportDescLength));
623 		return (1);
624 	}
625 
626 	while (retries-- > 0) {
627 		if (ihidev_reset(sc, false)) {
628 			if (retries == 0)
629 				return(1);
630 
631 			DELAY(1000);
632 		}
633 		else
634 			break;
635 	}
636 
637 	sc->sc_reportlen = le16toh(sc->hid_desc.wReportDescLength);
638 	sc->sc_report = kmem_zalloc(sc->sc_reportlen, KM_NOSLEEP);
639 
640 	if (ihidev_hid_command(sc, I2C_HID_REPORT_DESCR, 0, false)) {
641 		aprint_error_dev(sc->sc_dev, "failed fetching HID report\n");
642 		return (1);
643 	}
644 
645 	return (0);
646 }
647 
648 static bool
649 ihiddev_intr_init(struct ihidev_softc *sc)
650 {
651 #if NACPICA > 0
652 	ACPI_HANDLE hdl = (void *)(uintptr_t)sc->sc_phandle;
653 	struct acpi_resources res;
654 	ACPI_STATUS rv;
655 	char buf[100];
656 
657 	rv = acpi_resource_parse(sc->sc_dev, hdl, "_CRS", &res,
658 	    &acpi_resource_parse_ops_quiet);
659 	if (ACPI_FAILURE(rv)) {
660 		aprint_error_dev(sc->sc_dev, "can't parse '_CRS'\n");
661 		return false;
662 	}
663 
664 	const struct acpi_irq * const irq = acpi_res_irq(&res, 0);
665 	if (irq == NULL) {
666 		aprint_error_dev(sc->sc_dev, "no IRQ resource\n");
667 		acpi_resource_cleanup(&res);
668 		return false;
669 	}
670 
671 	sc->sc_intr_type =
672 	    irq->ar_type == ACPI_EDGE_SENSITIVE ? IST_EDGE : IST_LEVEL;
673 
674 	acpi_resource_cleanup(&res);
675 
676 	sc->sc_ih = acpi_intr_establish(sc->sc_dev, sc->sc_phandle, IPL_TTY,
677 	    false, ihidev_intr, sc, device_xname(sc->sc_dev));
678 	if (sc->sc_ih == NULL) {
679 		aprint_error_dev(sc->sc_dev, "can't establish interrupt\n");
680 		return false;
681 	}
682 	aprint_normal_dev(sc->sc_dev, "interrupting at %s\n",
683 	    acpi_intr_string(sc->sc_ih, buf, sizeof(buf)));
684 
685 	sc->sc_sih = softint_establish(SOFTINT_SERIAL, ihidev_softintr, sc);
686 	if (sc->sc_sih == NULL) {
687 		aprint_error_dev(sc->sc_dev,
688 		    "can't establish soft interrupt\n");
689 		return false;
690 	}
691 
692 	return true;
693 #else
694 	aprint_error_dev(sc->sc_dev, "can't establish interrupt\n");
695 	return false;
696 #endif
697 }
698 
699 static void
700 ihiddev_intr_fini(struct ihidev_softc *sc)
701 {
702 #if NACPICA > 0
703 	if (sc->sc_ih != NULL) {
704 		acpi_intr_disestablish(sc->sc_ih);
705 	}
706 	if (sc->sc_sih != NULL) {
707 		softint_disestablish(sc->sc_sih);
708 	}
709 #endif
710 }
711 
712 static void
713 ihidev_intr_mask(struct ihidev_softc * const sc)
714 {
715 
716 	if (sc->sc_intr_type == IST_LEVEL) {
717 #if NACPICA > 0
718 		acpi_intr_mask(sc->sc_ih);
719 #endif
720 	}
721 }
722 
723 static void
724 ihidev_intr_unmask(struct ihidev_softc * const sc)
725 {
726 
727 	if (sc->sc_intr_type == IST_LEVEL) {
728 #if NACPICA > 0
729 		acpi_intr_unmask(sc->sc_ih);
730 #endif
731 	}
732 }
733 
734 static int
735 ihidev_intr(void *arg)
736 {
737 	struct ihidev_softc * const sc = arg;
738 
739 	mutex_enter(&sc->sc_intr_lock);
740 
741 	/*
742 	 * Schedule our soft interrupt handler.  If we're using a level-
743 	 * triggered interrupt, we have to mask it off while we wait
744 	 * for service.
745 	 */
746 	softint_schedule(sc->sc_sih);
747 	ihidev_intr_mask(sc);
748 
749 	mutex_exit(&sc->sc_intr_lock);
750 
751 	return 1;
752 }
753 
754 static void
755 ihidev_softintr(void *arg)
756 {
757 	struct ihidev_softc * const sc = arg;
758 	struct ihidev *scd;
759 	u_int psize;
760 	int res, i;
761 	u_char *p;
762 	u_int rep = 0;
763 
764 	mutex_enter(&sc->sc_intr_lock);
765 	iic_acquire_bus(sc->sc_tag, 0);
766 	res = iic_exec(sc->sc_tag, I2C_OP_READ_WITH_STOP, sc->sc_addr, NULL, 0,
767 	    sc->sc_ibuf, sc->sc_isize, 0);
768 	iic_release_bus(sc->sc_tag, 0);
769 	mutex_exit(&sc->sc_intr_lock);
770 
771 	if (res != 0)
772 		goto out;
773 
774 	/*
775 	 * 6.1.1 - First two bytes are the packet length, which must be less
776 	 * than or equal to wMaxInputLength
777 	 */
778 	psize = sc->sc_ibuf[0] | sc->sc_ibuf[1] << 8;
779 	if (!psize || psize > sc->sc_isize) {
780 		DPRINTF(("%s: %s: invalid packet size (%d vs. %d)\n",
781 		    sc->sc_dev.dv_xname, __func__, psize, sc->sc_isize));
782 		goto out;
783 	}
784 
785 	/* 3rd byte is the report id */
786 	p = sc->sc_ibuf + 2;
787 	psize -= 2;
788 	if (sc->sc_nrepid != 1)
789 		rep = *p++, psize--;
790 
791 	if (rep >= sc->sc_nrepid) {
792 		aprint_error_dev(sc->sc_dev, "%s: bad report id %d\n",
793 		    __func__, rep);
794 		goto out;
795 	}
796 
797 	DPRINTF(("%s: %s: hid input (rep %d):", sc->sc_dev.dv_xname,
798 	    __func__, rep));
799 	for (i = 0; i < sc->sc_isize; i++)
800 		DPRINTF((" %.2x", sc->sc_ibuf[i]));
801 	DPRINTF(("\n"));
802 
803 	scd = sc->sc_subdevs[rep];
804 	if (scd == NULL || !(scd->sc_state & IHIDEV_OPEN))
805 		goto out;
806 
807 	scd->sc_intr(scd, p, psize);
808 
809  out:
810 	/*
811 	 * If our interrupt is level-triggered, re-enable it now.
812 	 */
813 	ihidev_intr_unmask(sc);
814 }
815 
816 static int
817 ihidev_maxrepid(void *buf, int len)
818 {
819 	struct hid_data *d;
820 	struct hid_item h;
821 	int maxid;
822 
823 	maxid = -1;
824 	h.report_ID = 0;
825 	for (d = hid_start_parse(buf, len, hid_none); hid_get_item(d, &h); )
826 		if ((int)h.report_ID > maxid)
827 			maxid = h.report_ID;
828 	hid_end_parse(d);
829 
830 	return (maxid);
831 }
832 
833 static int
834 ihidev_print(void *aux, const char *pnp)
835 {
836 	struct ihidev_attach_arg *iha = aux;
837 
838 	if (iha->reportid == IHIDEV_CLAIM_ALLREPORTID)
839 		return (QUIET);
840 
841 	if (pnp)
842 		aprint_normal("hid at %s", pnp);
843 
844 	if (iha->reportid != 0)
845 		aprint_normal(" reportid %d", iha->reportid);
846 
847 	return (UNCONF);
848 }
849 
850 static int
851 ihidev_submatch(device_t parent, cfdata_t cf, const int *locs, void *aux)
852 {
853 	struct ihidev_attach_arg *iha = aux;
854 
855 	if (cf->ihidevcf_reportid != IHIDEV_UNK_REPORTID &&
856 	    cf->ihidevcf_reportid != iha->reportid)
857 		return (0);
858 
859 	return config_match(parent, cf, aux);
860 }
861 
862 int
863 ihidev_open(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 (EBUSY);
872 
873 	scd->sc_state |= IHIDEV_OPEN;
874 
875 	if (sc->sc_refcnt++ || sc->sc_isize == 0)
876 		return (0);
877 
878 	/* power on */
879 	ihidev_reset(sc, false);
880 
881 	return (0);
882 }
883 
884 void
885 ihidev_close(struct ihidev *scd)
886 {
887 	struct ihidev_softc *sc = scd->sc_parent;
888 
889 	DPRINTF(("%s: %s: state=%d refcnt=%d\n", sc->sc_dev.dv_xname,
890 	    __func__, scd->sc_state, sc->sc_refcnt));
891 
892 	if (!(scd->sc_state & IHIDEV_OPEN))
893 		return;
894 
895 	scd->sc_state &= ~IHIDEV_OPEN;
896 
897 	if (--sc->sc_refcnt)
898 		return;
899 
900 	if (ihidev_hid_command(sc, I2C_HID_CMD_SET_POWER,
901 	    &I2C_HID_POWER_OFF, false))
902 		aprint_error_dev(sc->sc_dev, "failed to power down\n");
903 }
904 
905 void
906 ihidev_get_report_desc(struct ihidev_softc *sc, void **desc, int *size)
907 {
908 	*desc = sc->sc_report;
909 	*size = sc->sc_reportlen;
910 }
911 
912 /* convert hid_* constants used throughout HID code to i2c HID equivalents */
913 int
914 ihidev_report_type_conv(int hid_type_id)
915 {
916 	switch (hid_type_id) {
917 	case hid_input:
918 		return I2C_HID_REPORT_TYPE_INPUT;
919 	case hid_output:
920 		return I2C_HID_REPORT_TYPE_OUTPUT;
921 	case hid_feature:
922 		return I2C_HID_REPORT_TYPE_FEATURE;
923 	default:
924 		return -1;
925 	}
926 }
927 
928 int
929 ihidev_get_report(struct device *dev, int type, int id, void *data, int len)
930 {
931 	struct ihidev_softc *sc = (struct ihidev_softc *)dev;
932 	struct i2c_hid_report_request rreq;
933 	int ctype;
934 
935 	if ((ctype = ihidev_report_type_conv(type)) < 0)
936 		return (1);
937 
938 	rreq.type = ctype;
939 	rreq.id = id;
940 	rreq.data = data;
941 	rreq.len = len;
942 
943 	if (ihidev_hid_command(sc, I2C_HID_CMD_GET_REPORT, &rreq, false)) {
944 		aprint_error_dev(sc->sc_dev, "failed fetching report\n");
945 		return (1);
946 	}
947 
948 	return 0;
949 }
950 
951 int
952 ihidev_set_report(struct device *dev, int type, int id, void *data,
953     int len)
954 {
955 	struct ihidev_softc *sc = (struct ihidev_softc *)dev;
956 	struct i2c_hid_report_request rreq;
957 	int ctype;
958 
959 	if ((ctype = ihidev_report_type_conv(type)) < 0)
960 		return (1);
961 
962 	rreq.type = ctype;
963 	rreq.id = id;
964 	rreq.data = data;
965 	rreq.len = len;
966 
967 	if (ihidev_hid_command(sc, I2C_HID_CMD_SET_REPORT, &rreq, false)) {
968 		aprint_error_dev(sc->sc_dev, "failed setting report\n");
969 		return (1);
970 	}
971 
972 	return 0;
973 }
974 
975 static bool
976 ihidev_acpi_get_info(struct ihidev_softc *sc)
977 {
978 	ACPI_HANDLE hdl = (void *)(uintptr_t)sc->sc_phandle;
979 	ACPI_STATUS status;
980 	ACPI_INTEGER val;
981 
982 	/* 3cdff6f7-4267-4555-ad05-b30a3d8938de */
983 	uint8_t i2c_hid_guid[] = {
984 		0xF7, 0xF6, 0xDF, 0x3C,
985 		0x67, 0x42,
986 		0x55, 0x45,
987 		0xAD, 0x05,
988 		0xB3, 0x0A, 0x3D, 0x89, 0x38, 0xDE,
989 	};
990 
991 	status = acpi_dsm_integer(hdl, i2c_hid_guid, 1, 1, NULL, &val);
992 	if (ACPI_FAILURE(status)) {
993 		aprint_error_dev(sc->sc_dev,
994 		    "failed to get HidDescriptorAddress: %s\n",
995 		    AcpiFormatException(status));
996 		return false;
997 	}
998 
999 	sc->sc_hid_desc_addr = (u_int)val;
1000 
1001 	return true;
1002 }
1003