xref: /netbsd-src/sys/dev/i2c/ihidev.c (revision 4d342c046e3288fb5a1edcd33cfec48c41c80664)
1 /* $NetBSD: ihidev.c,v 1.12 2020/01/09 04:04:01 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.12 2020/01/09 04:04:01 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 const struct device_compatible_entry compat_data[] = {
129 	{ "hid-over-i2c",		0 },
130 	{ NULL,				0 }
131 };
132 
133 static int
134 ihidev_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 
145 static void
146 ihidev_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 
251 static int
252 ihidev_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 
274 static bool
275 ihidev_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 
290 static bool
291 ihidev_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 
304 static int
305 ihidev_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 
558 static int
559 ihidev_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  */
591 static int
592 ihidev_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 
643 static bool
644 ihiddev_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 
694 static void
695 ihiddev_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 
707 static void
708 ihidev_intr_mask(struct ihidev_softc * const sc)
709 {
710 
711 	if (sc->sc_intr_type == IST_LEVEL) {
712 #if NACPICA > 0
713 		acpi_intr_mask(sc->sc_ih);
714 #endif
715 	}
716 }
717 
718 static void
719 ihidev_intr_unmask(struct ihidev_softc * const sc)
720 {
721 
722 	if (sc->sc_intr_type == IST_LEVEL) {
723 #if NACPICA > 0
724 		acpi_intr_unmask(sc->sc_ih);
725 #endif
726 	}
727 }
728 
729 static int
730 ihidev_intr(void *arg)
731 {
732 	struct ihidev_softc * const sc = arg;
733 
734 	mutex_enter(&sc->sc_intr_lock);
735 
736 	/*
737 	 * Schedule our soft interrupt handler.  If we're using a level-
738 	 * triggered interrupt, we have to mask it off while we wait
739 	 * for service.
740 	 */
741 	softint_schedule(sc->sc_sih);
742 	ihidev_intr_mask(sc);
743 
744 	mutex_exit(&sc->sc_intr_lock);
745 
746 	return 1;
747 }
748 
749 static void
750 ihidev_softintr(void *arg)
751 {
752 	struct ihidev_softc * const sc = arg;
753 	struct ihidev *scd;
754 	u_int psize;
755 	int res, i;
756 	u_char *p;
757 	u_int rep = 0;
758 
759 	mutex_enter(&sc->sc_intr_lock);
760 	iic_acquire_bus(sc->sc_tag, 0);
761 	res = iic_exec(sc->sc_tag, I2C_OP_READ_WITH_STOP, sc->sc_addr, NULL, 0,
762 	    sc->sc_ibuf, sc->sc_isize, 0);
763 	iic_release_bus(sc->sc_tag, 0);
764 	mutex_exit(&sc->sc_intr_lock);
765 
766 	if (res != 0)
767 		goto out;
768 
769 	/*
770 	 * 6.1.1 - First two bytes are the packet length, which must be less
771 	 * than or equal to wMaxInputLength
772 	 */
773 	psize = sc->sc_ibuf[0] | sc->sc_ibuf[1] << 8;
774 	if (!psize || psize > sc->sc_isize) {
775 		DPRINTF(("%s: %s: invalid packet size (%d vs. %d)\n",
776 		    sc->sc_dev.dv_xname, __func__, psize, sc->sc_isize));
777 		goto out;
778 	}
779 
780 	/* 3rd byte is the report id */
781 	p = sc->sc_ibuf + 2;
782 	psize -= 2;
783 	if (sc->sc_nrepid != 1)
784 		rep = *p++, psize--;
785 
786 	if (rep >= sc->sc_nrepid) {
787 		aprint_error_dev(sc->sc_dev, "%s: bad report id %d\n",
788 		    __func__, rep);
789 		goto out;
790 	}
791 
792 	DPRINTF(("%s: %s: hid input (rep %d):", sc->sc_dev.dv_xname,
793 	    __func__, rep));
794 	for (i = 0; i < sc->sc_isize; i++)
795 		DPRINTF((" %.2x", sc->sc_ibuf[i]));
796 	DPRINTF(("\n"));
797 
798 	scd = sc->sc_subdevs[rep];
799 	if (scd == NULL || !(scd->sc_state & IHIDEV_OPEN))
800 		goto out;
801 
802 	scd->sc_intr(scd, p, psize);
803 
804  out:
805 	/*
806 	 * If our interrupt is level-triggered, re-enable it now.
807 	 */
808 	ihidev_intr_unmask(sc);
809 }
810 
811 static int
812 ihidev_maxrepid(void *buf, int len)
813 {
814 	struct hid_data *d;
815 	struct hid_item h;
816 	int maxid;
817 
818 	maxid = -1;
819 	h.report_ID = 0;
820 	for (d = hid_start_parse(buf, len, hid_none); hid_get_item(d, &h); )
821 		if ((int)h.report_ID > maxid)
822 			maxid = h.report_ID;
823 	hid_end_parse(d);
824 
825 	return (maxid);
826 }
827 
828 static int
829 ihidev_print(void *aux, const char *pnp)
830 {
831 	struct ihidev_attach_arg *iha = aux;
832 
833 	if (iha->reportid == IHIDEV_CLAIM_ALLREPORTID)
834 		return (QUIET);
835 
836 	if (pnp)
837 		aprint_normal("hid at %s", pnp);
838 
839 	if (iha->reportid != 0)
840 		aprint_normal(" reportid %d", iha->reportid);
841 
842 	return (UNCONF);
843 }
844 
845 static int
846 ihidev_submatch(device_t parent, cfdata_t cf, const int *locs, void *aux)
847 {
848 	struct ihidev_attach_arg *iha = aux;
849 
850 	if (cf->ihidevcf_reportid != IHIDEV_UNK_REPORTID &&
851 	    cf->ihidevcf_reportid != iha->reportid)
852 		return (0);
853 
854 	return config_match(parent, cf, aux);
855 }
856 
857 int
858 ihidev_open(struct ihidev *scd)
859 {
860 	struct ihidev_softc *sc = scd->sc_parent;
861 
862 	DPRINTF(("%s: %s: state=%d refcnt=%d\n", sc->sc_dev.dv_xname,
863 	    __func__, scd->sc_state, sc->sc_refcnt));
864 
865 	if (scd->sc_state & IHIDEV_OPEN)
866 		return (EBUSY);
867 
868 	scd->sc_state |= IHIDEV_OPEN;
869 
870 	if (sc->sc_refcnt++ || sc->sc_isize == 0)
871 		return (0);
872 
873 	/* power on */
874 	ihidev_reset(sc, false);
875 
876 	return (0);
877 }
878 
879 void
880 ihidev_close(struct ihidev *scd)
881 {
882 	struct ihidev_softc *sc = scd->sc_parent;
883 
884 	DPRINTF(("%s: %s: state=%d refcnt=%d\n", sc->sc_dev.dv_xname,
885 	    __func__, scd->sc_state, sc->sc_refcnt));
886 
887 	if (!(scd->sc_state & IHIDEV_OPEN))
888 		return;
889 
890 	scd->sc_state &= ~IHIDEV_OPEN;
891 
892 	if (--sc->sc_refcnt)
893 		return;
894 
895 	if (ihidev_hid_command(sc, I2C_HID_CMD_SET_POWER,
896 	    &I2C_HID_POWER_OFF, false))
897 		aprint_error_dev(sc->sc_dev, "failed to power down\n");
898 }
899 
900 void
901 ihidev_get_report_desc(struct ihidev_softc *sc, void **desc, int *size)
902 {
903 	*desc = sc->sc_report;
904 	*size = sc->sc_reportlen;
905 }
906 
907 /* convert hid_* constants used throughout HID code to i2c HID equivalents */
908 int
909 ihidev_report_type_conv(int hid_type_id)
910 {
911 	switch (hid_type_id) {
912 	case hid_input:
913 		return I2C_HID_REPORT_TYPE_INPUT;
914 	case hid_output:
915 		return I2C_HID_REPORT_TYPE_OUTPUT;
916 	case hid_feature:
917 		return I2C_HID_REPORT_TYPE_FEATURE;
918 	default:
919 		return -1;
920 	}
921 }
922 
923 int
924 ihidev_get_report(struct device *dev, int type, int id, void *data, int len)
925 {
926 	struct ihidev_softc *sc = (struct ihidev_softc *)dev;
927 	struct i2c_hid_report_request rreq;
928 	int ctype;
929 
930 	if ((ctype = ihidev_report_type_conv(type)) < 0)
931 		return (1);
932 
933 	rreq.type = ctype;
934 	rreq.id = id;
935 	rreq.data = data;
936 	rreq.len = len;
937 
938 	if (ihidev_hid_command(sc, I2C_HID_CMD_GET_REPORT, &rreq, false)) {
939 		aprint_error_dev(sc->sc_dev, "failed fetching report\n");
940 		return (1);
941 	}
942 
943 	return 0;
944 }
945 
946 int
947 ihidev_set_report(struct device *dev, int type, int id, void *data,
948     int len)
949 {
950 	struct ihidev_softc *sc = (struct ihidev_softc *)dev;
951 	struct i2c_hid_report_request rreq;
952 	int ctype;
953 
954 	if ((ctype = ihidev_report_type_conv(type)) < 0)
955 		return (1);
956 
957 	rreq.type = ctype;
958 	rreq.id = id;
959 	rreq.data = data;
960 	rreq.len = len;
961 
962 	if (ihidev_hid_command(sc, I2C_HID_CMD_SET_REPORT, &rreq, false)) {
963 		aprint_error_dev(sc->sc_dev, "failed setting report\n");
964 		return (1);
965 	}
966 
967 	return 0;
968 }
969