xref: /freebsd/sys/dev/iicbus/iichid.c (revision daa098cc37b9db36281623c00558976aea4fa90e)
1 /*-
2  * Copyright (c) 2018-2019 Marc Priggemeyer <marc.priggemeyer@gmail.com>
3  * Copyright (c) 2019-2020 Vladimir Kondratyev <wulf@FreeBSD.org>
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 /*
28  * I2C HID transport backend.
29  */
30 
31 #include <sys/cdefs.h>
32 #include "opt_hid.h"
33 
34 #include <sys/param.h>
35 #include <sys/bus.h>
36 #include <sys/callout.h>
37 #include <sys/endian.h>
38 #include <sys/kernel.h>
39 #include <sys/lock.h>
40 #include <sys/malloc.h>
41 #include <sys/module.h>
42 #include <sys/proc.h>
43 #include <sys/rman.h>
44 #include <sys/sysctl.h>
45 #include <sys/systm.h>
46 #include <sys/taskqueue.h>
47 
48 #include <machine/resource.h>
49 
50 #include <contrib/dev/acpica/include/acpi.h>
51 #include <contrib/dev/acpica/include/accommon.h>
52 #include <dev/acpica/acpivar.h>
53 
54 #include <dev/evdev/input.h>
55 
56 #include <dev/hid/hid.h>
57 #include <dev/hid/hidquirk.h>
58 
59 #include <dev/iicbus/iic.h>
60 #include <dev/iicbus/iicbus.h>
61 #include <dev/iicbus/iiconf.h>
62 
63 #include "hid_if.h"
64 
65 #ifdef IICHID_DEBUG
66 static int iichid_debug = 0;
67 
68 static SYSCTL_NODE(_hw, OID_AUTO, iichid, CTLFLAG_RW, 0, "I2C HID");
69 SYSCTL_INT(_hw_iichid, OID_AUTO, debug, CTLFLAG_RWTUN,
70     &iichid_debug, 1, "Debug level");
71 
72 #define	DPRINTFN(sc, n, ...) do {			\
73 	if (iichid_debug >= (n))			\
74 		device_printf((sc)->dev, __VA_ARGS__);	\
75 } while (0)
76 #define	DPRINTF(sc, ...)	DPRINTFN(sc, 1, __VA_ARGS__)
77 #else
78 #define	DPRINTFN(...)		do {} while (0)
79 #define	DPRINTF(...)		do {} while (0)
80 #endif
81 
82 typedef	hid_size_t	iichid_size_t;
83 #define	IICHID_SIZE_MAX	(UINT16_MAX - 2)
84 
85 /* 7.2 */
86 enum {
87 	I2C_HID_CMD_DESCR	= 0x0,
88 	I2C_HID_CMD_RESET	= 0x1,
89 	I2C_HID_CMD_GET_REPORT	= 0x2,
90 	I2C_HID_CMD_SET_REPORT	= 0x3,
91 	I2C_HID_CMD_GET_IDLE	= 0x4,
92 	I2C_HID_CMD_SET_IDLE	= 0x5,
93 	I2C_HID_CMD_GET_PROTO	= 0x6,
94 	I2C_HID_CMD_SET_PROTO	= 0x7,
95 	I2C_HID_CMD_SET_POWER	= 0x8,
96 };
97 
98 #define	I2C_HID_POWER_ON		0x0
99 #define	I2C_HID_POWER_OFF		0x1
100 
101 #define	IICHID_RESET_TIMEOUT		5	/* seconds */
102 
103 /*
104  * Since interrupt resource acquisition is not always possible (in case of GPIO
105  * interrupts) iichid now supports a sampling_mode.
106  * Set dev.iichid.<unit>.sampling_rate_slow to a value greater then 0
107  * to activate sampling. A value of 0 is possible but will not reset the
108  * callout and, thereby, disable further report requests. Do not set the
109  * sampling_rate_fast value too high as it may result in periodical lags of
110  * cursor motion.
111  */
112 #define	IICHID_SAMPLING_RATE_FAST	80
113 #define	IICHID_SAMPLING_RATE_SLOW	10
114 #define	IICHID_SAMPLING_HYSTERESIS	16	/* ~ 2x fast / slow */
115 
116 /* 5.1.1 - HID Descriptor Format */
117 struct i2c_hid_desc {
118 	uint16_t wHIDDescLength;
119 	uint16_t bcdVersion;
120 	uint16_t wReportDescLength;
121 	uint16_t wReportDescRegister;
122 	uint16_t wInputRegister;
123 	uint16_t wMaxInputLength;
124 	uint16_t wOutputRegister;
125 	uint16_t wMaxOutputLength;
126 	uint16_t wCommandRegister;
127 	uint16_t wDataRegister;
128 	uint16_t wVendorID;
129 	uint16_t wProductID;
130 	uint16_t wVersionID;
131 	uint32_t reserved;
132 } __packed;
133 
134 #define	IICHID_REG_NONE	-1
135 #define	IICHID_REG_ACPI	(UINT16_MAX + 1)
136 #define	IICHID_REG_ELAN	0x0001
137 
138 static const struct iichid_id {
139 	char *id;
140 	int reg;
141 } iichid_ids[] = {
142 	{ "ELAN0000",	IICHID_REG_ELAN },
143 	{ "PNP0C50",	IICHID_REG_ACPI },
144 	{ "ACPI0C50",	IICHID_REG_ACPI },
145 	{ NULL,		0 },
146 };
147 
148 enum iichid_powerstate_how {
149 	IICHID_PS_NULL,
150 	IICHID_PS_ON,
151 	IICHID_PS_OFF,
152 };
153 
154 /*
155  * Locking: no internal locks are used. To serialize access to shared members,
156  * external iicbus lock should be taken.  That allows to make locking greatly
157  * simple at the cost of running front interrupt handlers with locked bus.
158  */
159 struct iichid_softc {
160 	device_t		dev;
161 	struct mtx		mtx;
162 
163 	bool			probe_done;
164 	int			probe_result;
165 
166 	struct hid_device_info	hw;
167 	uint16_t		addr;	/* Shifted left by 1 */
168 	struct i2c_hid_desc	desc;
169 
170 	hid_intr_t		*intr_handler;
171 	void			*intr_ctx;
172 	uint8_t			*intr_buf;
173 	iichid_size_t		intr_bufsize;
174 
175 	int			irq_rid;
176 	struct resource		*irq_res;
177 	void			*irq_cookie;
178 
179 #ifdef IICHID_SAMPLING
180 	int			sampling_rate_slow;	/* iicbus lock */
181 	int			sampling_rate_fast;
182 	int			sampling_hysteresis;
183 	int			missing_samples;	/* iicbus lock */
184 	int			dup_samples;		/* iicbus lock */
185 	iichid_size_t		dup_size;		/* iicbus lock */
186 	bool			callout_setup;		/* iicbus lock */
187 	uint8_t			*dup_buf;
188 	struct taskqueue	*taskqueue;
189 	struct timeout_task	sampling_task;		/* iicbus lock */
190 #endif
191 
192 	struct task		suspend_task;
193 	bool			open;			/* iicbus lock */
194 	bool			suspend;		/* iicbus lock */
195 	bool			power_on;		/* iicbus lock */
196 	bool			reset_acked;		/* iichid mtx */
197 };
198 
199 static device_probe_t	iichid_probe;
200 static device_attach_t	iichid_attach;
201 static device_detach_t	iichid_detach;
202 static device_resume_t	iichid_resume;
203 static device_suspend_t	iichid_suspend;
204 
205 static void	iichid_suspend_task(void *, int);
206 
207 #ifdef IICHID_SAMPLING
208 static int	iichid_setup_callout(struct iichid_softc *);
209 static int	iichid_reset_callout(struct iichid_softc *);
210 static void	iichid_teardown_callout(struct iichid_softc *);
211 #endif
212 
213 static inline int
acpi_is_iichid(ACPI_HANDLE handle)214 acpi_is_iichid(ACPI_HANDLE handle)
215 {
216 	const struct iichid_id *ids;
217 	UINT32	sta;
218 	int reg;
219 
220 	for (ids = iichid_ids; ids->id != NULL; ids++) {
221 		if (acpi_MatchHid(handle, ids->id)) {
222 			reg = ids->reg;
223 			break;
224 		}
225 	}
226 	if (ids->id == NULL)
227 		return (IICHID_REG_NONE);
228 
229 	/*
230 	 * If no _STA method or if it failed, then assume that
231 	 * the device is present.
232 	 */
233 	if (ACPI_FAILURE(acpi_GetInteger(handle, "_STA", &sta)) ||
234 	    ACPI_DEVICE_PRESENT(sta))
235 		return (reg);
236 
237 	return (IICHID_REG_NONE);
238 }
239 
240 static ACPI_STATUS
iichid_get_config_reg(ACPI_HANDLE handle,uint16_t * config_reg)241 iichid_get_config_reg(ACPI_HANDLE handle, uint16_t *config_reg)
242 {
243 	ACPI_OBJECT *result;
244 	ACPI_BUFFER acpi_buf;
245 	ACPI_STATUS status;
246 
247 	/*
248 	 * function (_DSM) to be evaluated to retrieve the address of
249 	 * the configuration register of the HID device.
250 	 */
251 	/* 3cdff6f7-4267-4555-ad05-b30a3d8938de */
252 	static uint8_t dsm_guid[ACPI_UUID_LENGTH] = {
253 		0xF7, 0xF6, 0xDF, 0x3C, 0x67, 0x42, 0x55, 0x45,
254 		0xAD, 0x05, 0xB3, 0x0A, 0x3D, 0x89, 0x38, 0xDE,
255 	};
256 
257 	status = acpi_EvaluateDSMTyped(handle, dsm_guid, 1, 1, NULL, &acpi_buf,
258 	    ACPI_TYPE_INTEGER);
259 	if (ACPI_FAILURE(status)) {
260 		printf("%s: error evaluating _DSM\n", __func__);
261 		return (status);
262 	}
263 	result = (ACPI_OBJECT *) acpi_buf.Pointer;
264 	*config_reg = result->Integer.Value & 0xFFFF;
265 
266 	AcpiOsFree(result);
267 	return (status);
268 }
269 
270 static int
iichid_cmd_read(struct iichid_softc * sc,void * buf,iichid_size_t maxlen,iichid_size_t * actual_len)271 iichid_cmd_read(struct iichid_softc* sc, void *buf, iichid_size_t maxlen,
272     iichid_size_t *actual_len)
273 {
274 	/*
275 	 * 6.1.3 - Retrieval of Input Reports
276 	 * DEVICE returns the length (2 Bytes) and the entire Input Report.
277 	 */
278 	uint8_t actbuf[2] = { 0, 0 };
279 	/* Read actual input report length. */
280 	struct iic_msg msgs[] = {
281 	    { sc->addr, IIC_M_RD | IIC_M_NOSTOP, sizeof(actbuf), actbuf },
282 	};
283 	uint16_t actlen;
284 	int error;
285 
286 	error = iicbus_transfer(sc->dev, msgs, nitems(msgs));
287 	if (error != 0)
288 		return (error);
289 
290 	actlen = actbuf[0] | actbuf[1] << 8;
291 #ifdef IICHID_SAMPLING
292 	if ((actlen == 0 && sc->sampling_rate_slow < 0) ||
293 	    (maxlen == 0 && sc->sampling_rate_slow >= 0)) {
294 #else
295 	if (actlen == 0) {
296 #endif
297 		/* Read and discard reset command response. */
298 		msgs[0] = (struct iic_msg)
299 		    { sc->addr, IIC_M_RD | IIC_M_NOSTART,
300 		        le16toh(sc->desc.wMaxInputLength) - 2, sc->intr_buf };
301 		actlen = 0;
302 		if (!sc->reset_acked) {
303 			mtx_lock(&sc->mtx);
304 			sc->reset_acked = true;
305 			wakeup(&sc->reset_acked);
306 			mtx_unlock(&sc->mtx);
307 		}
308 #ifdef IICHID_SAMPLING
309 	} else if ((actlen <= 2 || actlen == 0xFFFF) &&
310 		    sc->sampling_rate_slow >= 0) {
311 		/* Read and discard 1 byte to send I2C STOP condition. */
312 		msgs[0] = (struct iic_msg)
313 		    { sc->addr, IIC_M_RD | IIC_M_NOSTART, 1, actbuf };
314 		actlen = 0;
315 #endif
316 	} else {
317 		actlen -= 2;
318 		if (actlen > maxlen) {
319 			DPRINTF(sc, "input report too big. requested=%d "
320 			    "received=%d\n", maxlen, actlen);
321 			actlen = maxlen;
322 		}
323 		/* Read input report itself. */
324 		msgs[0] = (struct iic_msg)
325 		    { sc->addr, IIC_M_RD | IIC_M_NOSTART, actlen, buf };
326 	}
327 
328 	error = iicbus_transfer(sc->dev, msgs, 1);
329 	if (error == 0 && actual_len != NULL)
330 		*actual_len = actlen;
331 
332 	DPRINTFN(sc, 5,
333 	    "%*D - %*D\n", 2, actbuf, " ", msgs[0].len, msgs[0].buf, " ");
334 
335 	return (error);
336 }
337 
338 static int
339 iichid_cmd_write(struct iichid_softc *sc, const void *buf, iichid_size_t len)
340 {
341 	/* 6.2.3 - Sending Output Reports. */
342 	uint8_t *cmdreg = (uint8_t *)&sc->desc.wOutputRegister;
343 	uint16_t replen = 2 + len;
344 	uint8_t cmd[4] = { cmdreg[0], cmdreg[1], replen & 0xFF, replen >> 8 };
345 	struct iic_msg msgs[] = {
346 	    {sc->addr, IIC_M_WR | IIC_M_NOSTOP, sizeof(cmd), cmd},
347 	    {sc->addr, IIC_M_WR | IIC_M_NOSTART, len, __DECONST(void *, buf)},
348 	};
349 
350 	if (le16toh(sc->desc.wMaxOutputLength) == 0)
351 		return (IIC_ENOTSUPP);
352 	if (len < 2)
353 		return (IIC_ENOTSUPP);
354 
355 	DPRINTF(sc, "HID command I2C_HID_CMD_WRITE (len %d): "
356 	    "%*D\n", len, len, buf, " ");
357 
358 	return (iicbus_transfer(sc->dev, msgs, nitems(msgs)));
359 }
360 
361 static int
362 iichid_cmd_get_hid_desc(struct iichid_softc *sc, uint16_t config_reg,
363     struct i2c_hid_desc *hid_desc)
364 {
365 	/*
366 	 * 5.2.2 - HID Descriptor Retrieval
367 	 * register is passed from the controller.
368 	 */
369 	uint16_t cmd = htole16(config_reg);
370 	struct iic_msg msgs[] = {
371 	    { sc->addr, IIC_M_WR | IIC_M_NOSTOP, 2, (uint8_t *)&cmd },
372 	    { sc->addr, IIC_M_RD, sizeof(*hid_desc), (uint8_t *)hid_desc },
373 	};
374 	int error;
375 
376 	DPRINTF(sc, "HID command I2C_HID_CMD_DESCR at 0x%x\n", config_reg);
377 
378 	error = iicbus_transfer(sc->dev, msgs, nitems(msgs));
379 	if (error != 0)
380 		return (error);
381 
382 	DPRINTF(sc, "HID descriptor: %*D\n",
383 	    (int)sizeof(struct i2c_hid_desc), hid_desc, " ");
384 
385 	return (0);
386 }
387 
388 static int
389 iichid_set_power(struct iichid_softc *sc, uint8_t param)
390 {
391 	uint8_t *cmdreg = (uint8_t *)&sc->desc.wCommandRegister;
392 	uint8_t cmd[] = { cmdreg[0], cmdreg[1], param, I2C_HID_CMD_SET_POWER };
393 	struct iic_msg msgs[] = {
394 	    { sc->addr, IIC_M_WR, sizeof(cmd), cmd },
395 	};
396 
397 	DPRINTF(sc, "HID command I2C_HID_CMD_SET_POWER(%d)\n", param);
398 
399 	return (iicbus_transfer(sc->dev, msgs, nitems(msgs)));
400 }
401 
402 static int
403 iichid_reset(struct iichid_softc *sc)
404 {
405 	uint8_t *cmdreg = (uint8_t *)&sc->desc.wCommandRegister;
406 	uint8_t cmd[] = { cmdreg[0], cmdreg[1], 0, I2C_HID_CMD_RESET };
407 	struct iic_msg msgs[] = {
408 	    { sc->addr, IIC_M_WR, sizeof(cmd), cmd },
409 	};
410 
411 	DPRINTF(sc, "HID command I2C_HID_CMD_RESET\n");
412 
413 	return (iicbus_transfer(sc->dev, msgs, nitems(msgs)));
414 }
415 
416 static int
417 iichid_cmd_get_report_desc(struct iichid_softc* sc, void *buf,
418     iichid_size_t len)
419 {
420 	uint16_t cmd = sc->desc.wReportDescRegister;
421 	struct iic_msg msgs[] = {
422 	    { sc->addr, IIC_M_WR | IIC_M_NOSTOP, 2, (uint8_t *)&cmd },
423 	    { sc->addr, IIC_M_RD, len, buf },
424 	};
425 	int error;
426 
427 	DPRINTF(sc, "HID command I2C_HID_REPORT_DESCR at 0x%x with size %d\n",
428 	    le16toh(cmd), len);
429 
430 	error = iicbus_transfer(sc->dev, msgs, nitems(msgs));
431 	if (error != 0)
432 		return (error);
433 
434 	DPRINTF(sc, "HID report descriptor: %*D\n", len, buf, " ");
435 
436 	return (0);
437 }
438 
439 static int
440 iichid_cmd_get_report(struct iichid_softc* sc, void *buf, iichid_size_t maxlen,
441     iichid_size_t *actual_len, uint8_t type, uint8_t id)
442 {
443 	/*
444 	 * 7.2.2.4 - "The protocol is optimized for Report < 15.  If a
445 	 * report ID >= 15 is necessary, then the Report ID in the Low Byte
446 	 * must be set to 1111 and a Third Byte is appended to the protocol.
447 	 * This Third Byte contains the entire/actual report ID."
448 	 */
449 	uint8_t *dtareg = (uint8_t *)&sc->desc.wDataRegister;
450 	uint8_t *cmdreg = (uint8_t *)&sc->desc.wCommandRegister;
451 	uint8_t cmd[] =	{   /*________|______id>=15_____|______id<15______*/
452 						    cmdreg[0]		   ,
453 						    cmdreg[1]		   ,
454 			    (id >= 15 ? 15 | (type << 4): id | (type << 4)),
455 					      I2C_HID_CMD_GET_REPORT	   ,
456 			    (id >= 15 ?		id	:    dtareg[0]	  ),
457 			    (id >= 15 ?	   dtareg[0]	:    dtareg[1]	  ),
458 			    (id >= 15 ?    dtareg[1]	:	0	  ),
459 			};
460 	int cmdlen    =	    (id >= 15 ?		7	:	6	  );
461 	uint8_t actbuf[2] = { 0, 0 };
462 	uint16_t actlen;
463 	int d, error;
464 	struct iic_msg msgs[] = {
465 	    { sc->addr, IIC_M_WR | IIC_M_NOSTOP, cmdlen, cmd },
466 	    { sc->addr, IIC_M_RD | IIC_M_NOSTOP, 2, actbuf },
467 	    { sc->addr, IIC_M_RD | IIC_M_NOSTART, maxlen, buf },
468 	};
469 
470 	if (maxlen == 0)
471 		return (EINVAL);
472 
473 	DPRINTF(sc, "HID command I2C_HID_CMD_GET_REPORT %d "
474 	    "(type %d, len %d)\n", id, type, maxlen);
475 
476 	/*
477 	 * 7.2.2.2 - Response will be a 2-byte length value, the report
478 	 * id (1 byte, if defined in Report Descriptor), and then the report.
479 	 */
480 	error = iicbus_transfer(sc->dev, msgs, nitems(msgs));
481 	if (error != 0)
482 		return (error);
483 
484 	actlen = actbuf[0] | actbuf[1] << 8;
485 	if (actlen != maxlen + 2)
486 		DPRINTF(sc, "response size %d != expected length %d\n",
487 		    actlen, maxlen + 2);
488 
489 	if (actlen <= 2 || actlen == 0xFFFF)
490 		return (ENOMSG);
491 
492 	d = id != 0 ? *(uint8_t *)buf : 0;
493 	if (d != id) {
494 		DPRINTF(sc, "response report id %d != %d\n", d, id);
495 		return (EBADMSG);
496 	}
497 
498 	actlen -= 2;
499 	if (actlen > maxlen)
500 		actlen = maxlen;
501 	if (actual_len != NULL)
502 		*actual_len = actlen;
503 
504 	DPRINTF(sc, "response: %*D %*D\n", 2, actbuf, " ", actlen, buf, " ");
505 
506 	return (0);
507 }
508 
509 static int
510 iichid_cmd_set_report(struct iichid_softc* sc, const void *buf,
511     iichid_size_t len, uint8_t type, uint8_t id)
512 {
513 	/*
514 	 * 7.2.2.4 - "The protocol is optimized for Report < 15.  If a
515 	 * report ID >= 15 is necessary, then the Report ID in the Low Byte
516 	 * must be set to 1111 and a Third Byte is appended to the protocol.
517 	 * This Third Byte contains the entire/actual report ID."
518 	 */
519 	uint8_t *dtareg = (uint8_t *)&sc->desc.wDataRegister;
520 	uint8_t *cmdreg = (uint8_t *)&sc->desc.wCommandRegister;
521 	uint16_t replen = 2 + len;
522 	uint8_t cmd[] =	{   /*________|______id>=15_____|______id<15______*/
523 						    cmdreg[0]		   ,
524 						    cmdreg[1]		   ,
525 			    (id >= 15 ? 15 | (type << 4): id | (type << 4)),
526 					      I2C_HID_CMD_SET_REPORT	   ,
527 			    (id >= 15 ?		id	:    dtareg[0]    ),
528 			    (id >= 15 ?    dtareg[0]	:    dtareg[1]    ),
529 			    (id >= 15 ?    dtareg[1]	:   replen & 0xff ),
530 			    (id >= 15 ?   replen & 0xff	:   replen >> 8   ),
531 			    (id >= 15 ?   replen >> 8	:	0	  ),
532 			};
533 	int cmdlen    =	    (id >= 15 ?		9	:	8	  );
534 	struct iic_msg msgs[] = {
535 	    {sc->addr, IIC_M_WR | IIC_M_NOSTOP, cmdlen, cmd},
536 	    {sc->addr, IIC_M_WR | IIC_M_NOSTART, len, __DECONST(void *, buf)},
537 	};
538 
539 	DPRINTF(sc, "HID command I2C_HID_CMD_SET_REPORT %d (type %d, len %d): "
540 	    "%*D\n", id, type, len, len, buf, " ");
541 
542 	return (iicbus_transfer(sc->dev, msgs, nitems(msgs)));
543 }
544 
545 #ifdef IICHID_SAMPLING
546 static void
547 iichid_sampling_task(void *context, int pending)
548 {
549 	struct iichid_softc *sc;
550 	device_t parent;
551 	iichid_size_t actual;
552 	bool bus_requested;
553 	int error, rate;
554 
555 	sc = context;
556 	parent = device_get_parent(sc->dev);
557 
558 	bus_requested = false;
559 	if (iicbus_request_bus(parent, sc->dev, IIC_WAIT) != 0)
560 		goto rearm;
561 	bus_requested = true;
562 
563 	if (!sc->power_on)
564 		goto out;
565 
566 	error = iichid_cmd_read(sc, sc->intr_buf, sc->intr_bufsize, &actual);
567 	if (error == 0) {
568 		if (actual > 0) {
569 			sc->intr_handler(sc->intr_ctx, sc->intr_buf, actual);
570 			sc->missing_samples = 0;
571 			if (sc->dup_size != actual ||
572 			    memcmp(sc->dup_buf, sc->intr_buf, actual) != 0) {
573 				sc->dup_size = actual;
574 				memcpy(sc->dup_buf, sc->intr_buf, actual);
575 				sc->dup_samples = 0;
576 			} else
577 				++sc->dup_samples;
578 		} else {
579 			if (++sc->missing_samples == 1)
580 				sc->intr_handler(sc->intr_ctx, sc->intr_buf, 0);
581 			sc->dup_samples = 0;
582 		}
583 	} else
584 		DPRINTF(sc, "read error occurred: %d\n", error);
585 
586 rearm:
587 	if (sc->callout_setup && sc->sampling_rate_slow > 0) {
588 		if (sc->missing_samples >= sc->sampling_hysteresis ||
589 		    sc->dup_samples >= sc->sampling_hysteresis)
590 			rate = sc->sampling_rate_slow;
591 		else
592 			rate = sc->sampling_rate_fast;
593 		taskqueue_enqueue_timeout_sbt(sc->taskqueue, &sc->sampling_task,
594 		    SBT_1S / MAX(rate, 1), 0, C_PREL(2));
595 	}
596 out:
597 	if (bus_requested)
598 		iicbus_release_bus(parent, sc->dev);
599 }
600 #endif	/* IICHID_SAMPLING */
601 
602 static void
603 iichid_intr(void *context)
604 {
605 	struct iichid_softc *sc;
606 	device_t parent;
607 	iichid_size_t actual;
608 	int error;
609 
610 	sc = context;
611 	parent = device_get_parent(sc->dev);
612 
613 	/*
614 	 * Designware(IG4) driver-specific hack.
615 	 * Requesting of an I2C bus with IIC_DONTWAIT parameter enables polled
616 	 * mode in the driver, making possible iicbus_transfer execution from
617 	 * interrupt handlers and callouts.
618 	 */
619 	if (iicbus_request_bus(parent, sc->dev, IIC_DONTWAIT) != 0)
620 		return;
621 
622 	/*
623 	 * Reading of input reports of I2C devices residing in SLEEP state is
624 	 * not allowed and often returns a garbage.  If a HOST needs to
625 	 * communicate with the DEVICE it MUST issue a SET POWER command
626 	 * (to ON) before any other command. As some hardware requires reads to
627 	 * acknowledge interrupts we fetch only length header and discard it.
628 	 */
629 	THREAD_SLEEPING_OK();
630 	error = iichid_cmd_read(sc, sc->intr_buf, sc->intr_bufsize, &actual);
631 	THREAD_NO_SLEEPING();
632 	if (error == 0) {
633 		if (sc->power_on) {
634 			if (actual != 0)
635 				sc->intr_handler(sc->intr_ctx, sc->intr_buf,
636 				    actual);
637 			else
638 				DPRINTF(sc, "no data received\n");
639 		}
640 	} else
641 		DPRINTF(sc, "read error occurred: %d\n", error);
642 
643 	iicbus_release_bus(parent, sc->dev);
644 }
645 
646 static int
647 iichid_set_power_state(struct iichid_softc *sc,
648      enum iichid_powerstate_how how_open,
649      enum iichid_powerstate_how how_suspend)
650 {
651 	device_t parent;
652 	int error;
653 	int how_request;
654 	bool power_on;
655 
656 	/*
657 	 * Request iicbus early as sc->suspend and sc->power_on
658 	 * are protected by iicbus internal lock.
659 	 */
660 	parent = device_get_parent(sc->dev);
661 	/* Allow to interrupt open()/close() handlers by SIGINT */
662 	how_request = how_open == IICHID_PS_NULL ? IIC_WAIT : IIC_INTRWAIT;
663 	error = iicbus_request_bus(parent, sc->dev, how_request);
664 	if (error != 0)
665 		return (error);
666 
667 	switch (how_open) {
668 	case IICHID_PS_ON:
669 		sc->open = true;
670 		break;
671 	case IICHID_PS_OFF:
672 		sc->open = false;
673 		break;
674 	case IICHID_PS_NULL:
675 	default:
676 		break;
677 	}
678 
679 	switch (how_suspend) {
680 	case IICHID_PS_ON:
681 		sc->suspend = false;
682 		break;
683 	case IICHID_PS_OFF:
684 		sc->suspend = true;
685 		break;
686 	case IICHID_PS_NULL:
687 	default:
688 		break;
689 	}
690 
691 	power_on = sc->open & !sc->suspend;
692 
693 	if (power_on != sc->power_on) {
694 		error = iichid_set_power(sc,
695 		    power_on ? I2C_HID_POWER_ON : I2C_HID_POWER_OFF);
696 
697 		sc->power_on = power_on;
698 #ifdef IICHID_SAMPLING
699 		if (sc->sampling_rate_slow >= 0 && sc->intr_handler != NULL) {
700 			if (power_on) {
701 				iichid_setup_callout(sc);
702 				iichid_reset_callout(sc);
703 			} else
704 				iichid_teardown_callout(sc);
705 		}
706 #endif
707 	}
708 
709 	iicbus_release_bus(parent, sc->dev);
710 
711 	return (error);
712 }
713 
714 static int
715 iichid_setup_interrupt(struct iichid_softc *sc)
716 {
717 	sc->irq_cookie = 0;
718 
719 	int error = bus_setup_intr(sc->dev, sc->irq_res,
720 	    INTR_TYPE_TTY|INTR_MPSAFE, NULL, iichid_intr, sc, &sc->irq_cookie);
721 	if (error != 0)
722 		DPRINTF(sc, "Could not setup interrupt handler\n");
723 	else
724 		DPRINTF(sc, "successfully setup interrupt\n");
725 
726 	return (error);
727 }
728 
729 static void
730 iichid_teardown_interrupt(struct iichid_softc *sc)
731 {
732 	if (sc->irq_cookie)
733 		bus_teardown_intr(sc->dev, sc->irq_res, sc->irq_cookie);
734 
735 	sc->irq_cookie = 0;
736 }
737 
738 #ifdef IICHID_SAMPLING
739 static int
740 iichid_setup_callout(struct iichid_softc *sc)
741 {
742 
743 	if (sc->sampling_rate_slow < 0) {
744 		DPRINTF(sc, "sampling_rate is below 0, can't setup callout\n");
745 		return (EINVAL);
746 	}
747 
748 	sc->callout_setup = true;
749 	DPRINTF(sc, "successfully setup callout\n");
750 	return (0);
751 }
752 
753 static int
754 iichid_reset_callout(struct iichid_softc *sc)
755 {
756 
757 	if (sc->sampling_rate_slow <= 0) {
758 		DPRINTF(sc, "sampling_rate is below or equal to 0, "
759 		    "can't reset callout\n");
760 		return (EINVAL);
761 	}
762 
763 	if (!sc->callout_setup)
764 		return (EINVAL);
765 
766 	/* Start with slow sampling. */
767 	sc->missing_samples = sc->sampling_hysteresis;
768 	sc->dup_samples = 0;
769 	sc->dup_size = 0;
770 	taskqueue_enqueue_timeout(sc->taskqueue, &sc->sampling_task, 0);
771 
772 	return (0);
773 }
774 
775 static void
776 iichid_teardown_callout(struct iichid_softc *sc)
777 {
778 
779 	sc->callout_setup = false;
780 	taskqueue_cancel_timeout(sc->taskqueue, &sc->sampling_task, NULL);
781 	DPRINTF(sc, "tore callout down\n");
782 }
783 
784 static int
785 iichid_sysctl_sampling_rate_handler(SYSCTL_HANDLER_ARGS)
786 {
787 	struct iichid_softc *sc;
788 	device_t parent;
789 	int error, oldval, value;
790 
791 	sc = arg1;
792 
793 	value = sc->sampling_rate_slow;
794 	error = sysctl_handle_int(oidp, &value, 0, req);
795 
796 	if (error != 0 || req->newptr == NULL ||
797 	    value == sc->sampling_rate_slow)
798 		return (error);
799 
800 	/* Can't switch to interrupt mode if it is not supported. */
801 	if (sc->irq_res == NULL && value < 0)
802 		return (EINVAL);
803 
804 	parent = device_get_parent(sc->dev);
805 	error = iicbus_request_bus(parent, sc->dev, IIC_WAIT);
806 	if (error != 0)
807 		return (iic2errno(error));
808 
809 	oldval = sc->sampling_rate_slow;
810 	sc->sampling_rate_slow = value;
811 
812 	if (oldval < 0 && value >= 0) {
813 		iichid_teardown_interrupt(sc);
814 		if (sc->power_on)
815 			iichid_setup_callout(sc);
816 	} else if (oldval >= 0 && value < 0) {
817 		if (sc->power_on)
818 			iichid_teardown_callout(sc);
819 		iichid_setup_interrupt(sc);
820 	}
821 
822 	if (sc->power_on && value > 0)
823 		iichid_reset_callout(sc);
824 
825 	iicbus_release_bus(parent, sc->dev);
826 
827 	DPRINTF(sc, "new sampling_rate value: %d\n", value);
828 
829 	return (0);
830 }
831 #endif /* IICHID_SAMPLING */
832 
833 static void
834 iichid_intr_setup(device_t dev, device_t child __unused, hid_intr_t intr,
835     void *context, struct hid_rdesc_info *rdesc)
836 {
837 	struct iichid_softc *sc;
838 	device_t parent;
839 
840 	if (intr == NULL)
841 		return;
842 
843 	sc = device_get_softc(dev);
844 	/*
845 	 * Do not rely on wMaxInputLength, as some devices may set it to
846 	 * a wrong length. Find the longest input report in report descriptor.
847 	 */
848 	rdesc->rdsize =
849 	    MAX(rdesc->isize, le16toh(sc->desc.wMaxInputLength) - 2);
850 	/* Write and get/set_report sizes are limited by I2C-HID protocol. */
851 	rdesc->grsize = rdesc->srsize = IICHID_SIZE_MAX;
852 	rdesc->wrsize = IICHID_SIZE_MAX;
853 
854 	parent = device_get_parent(sc->dev);
855 	iicbus_request_bus(parent, sc->dev, IIC_WAIT);
856 
857 	sc->intr_handler = intr;
858 	sc->intr_ctx = context;
859 	sc->intr_bufsize = rdesc->rdsize;
860 	sc->intr_buf = realloc(sc->intr_buf, sc->intr_bufsize,
861 	    M_DEVBUF, M_WAITOK | M_ZERO);
862 #ifdef IICHID_SAMPLING
863 	sc->dup_buf = realloc(sc->dup_buf, sc->intr_bufsize,
864 	    M_DEVBUF, M_WAITOK | M_ZERO);
865 	taskqueue_start_threads(&sc->taskqueue, 1, PI_TTY,
866 	    "%s taskq", device_get_nameunit(sc->dev));
867 #endif
868 	iicbus_release_bus(parent, sc->dev);
869 }
870 
871 static void
872 iichid_intr_unsetup(device_t dev, device_t child __unused)
873 {
874 #ifdef IICHID_SAMPLING
875 	struct iichid_softc *sc;
876 
877 	sc = device_get_softc(dev);
878 	taskqueue_drain_all(sc->taskqueue);
879 #endif
880 }
881 
882 static int
883 iichid_intr_start(device_t dev, device_t child __unused)
884 {
885 	struct iichid_softc *sc;
886 
887 	sc = device_get_softc(dev);
888 	DPRINTF(sc, "iichid device open\n");
889 	iichid_set_power_state(sc, IICHID_PS_ON, IICHID_PS_NULL);
890 
891 	return (0);
892 }
893 
894 static int
895 iichid_intr_stop(device_t dev, device_t child __unused)
896 {
897 	struct iichid_softc *sc;
898 
899 	sc = device_get_softc(dev);
900 	DPRINTF(sc, "iichid device close\n");
901 	/*
902 	 * 8.2 - The HOST determines that there are no active applications
903 	 * that are currently using the specific HID DEVICE.  The HOST
904 	 * is recommended to issue a HIPO command to the DEVICE to force
905 	 * the DEVICE in to a lower power state.
906 	 */
907 	iichid_set_power_state(sc, IICHID_PS_OFF, IICHID_PS_NULL);
908 
909 	return (0);
910 }
911 
912 static void
913 iichid_intr_poll(device_t dev, device_t child __unused)
914 {
915 	struct iichid_softc *sc;
916 	iichid_size_t actual;
917 	int error;
918 
919 	sc = device_get_softc(dev);
920 	error = iichid_cmd_read(sc, sc->intr_buf, sc->intr_bufsize, &actual);
921 	if (error == 0 && actual != 0)
922 		sc->intr_handler(sc->intr_ctx, sc->intr_buf, actual);
923 }
924 
925 /*
926  * HID interface
927  */
928 static int
929 iichid_get_rdesc(device_t dev, device_t child __unused, void *buf,
930     hid_size_t len)
931 {
932 	struct iichid_softc *sc;
933 	int error;
934 
935 	sc = device_get_softc(dev);
936 	error = iichid_cmd_get_report_desc(sc, buf, len);
937 	if (error)
938 		DPRINTF(sc, "failed to fetch report descriptor: %d\n", error);
939 
940 	return (iic2errno(error));
941 }
942 
943 static int
944 iichid_read(device_t dev, device_t child __unused, void *buf,
945     hid_size_t maxlen, hid_size_t *actlen)
946 {
947 	struct iichid_softc *sc;
948 	device_t parent;
949 	int error;
950 
951 	if (maxlen > IICHID_SIZE_MAX)
952 		return (EMSGSIZE);
953 	sc = device_get_softc(dev);
954 	parent = device_get_parent(sc->dev);
955 	error = iicbus_request_bus(parent, sc->dev, IIC_WAIT);
956 	if (error == 0) {
957 		error = iichid_cmd_read(sc, buf, maxlen, actlen);
958 		iicbus_release_bus(parent, sc->dev);
959 	}
960 	return (iic2errno(error));
961 }
962 
963 static int
964 iichid_write(device_t dev, device_t child __unused, const void *buf,
965     hid_size_t len)
966 {
967 	struct iichid_softc *sc;
968 
969 	if (len > IICHID_SIZE_MAX)
970 		return (EMSGSIZE);
971 	sc = device_get_softc(dev);
972 	return (iic2errno(iichid_cmd_write(sc, buf, len)));
973 }
974 
975 static int
976 iichid_get_report(device_t dev, device_t child __unused, void *buf,
977     hid_size_t maxlen, hid_size_t *actlen, uint8_t type, uint8_t id)
978 {
979 	struct iichid_softc *sc;
980 
981 	if (maxlen > IICHID_SIZE_MAX)
982 		return (EMSGSIZE);
983 	sc = device_get_softc(dev);
984 	return (iic2errno(
985 	    iichid_cmd_get_report(sc, buf, maxlen, actlen, type, id)));
986 }
987 
988 static int
989 iichid_set_report(device_t dev, device_t child __unused, const void *buf,
990     hid_size_t len, uint8_t type, uint8_t id)
991 {
992 	struct iichid_softc *sc;
993 
994 	if (len > IICHID_SIZE_MAX)
995 		return (EMSGSIZE);
996 	sc = device_get_softc(dev);
997 	return (iic2errno(iichid_cmd_set_report(sc, buf, len, type, id)));
998 }
999 
1000 static int
1001 iichid_set_idle(device_t dev, device_t child __unused,
1002     uint16_t duration, uint8_t id)
1003 {
1004 	return (ENOTSUP);
1005 }
1006 
1007 static int
1008 iichid_set_protocol(device_t dev, device_t child __unused, uint16_t protocol)
1009 {
1010 	return (ENOTSUP);
1011 }
1012 
1013 static int
1014 iichid_ioctl(device_t dev, device_t child __unused, unsigned long cmd,
1015     uintptr_t data)
1016 {
1017 	int error;
1018 
1019 	switch (cmd) {
1020 	case I2CRDWR:
1021 		error = iic2errno(iicbus_transfer(dev,
1022 		    ((struct iic_rdwr_data *)data)->msgs,
1023 		    ((struct iic_rdwr_data *)data)->nmsgs));
1024 		break;
1025 	default:
1026 		error = EINVAL;
1027 	}
1028 
1029 	return (error);
1030 }
1031 
1032 static int
1033 iichid_fill_device_info(struct i2c_hid_desc *desc, ACPI_HANDLE handle,
1034     struct hid_device_info *hw)
1035 {
1036 	ACPI_DEVICE_INFO *device_info;
1037 
1038 	hw->idBus = BUS_I2C;
1039 	hw->idVendor = le16toh(desc->wVendorID);
1040 	hw->idProduct = le16toh(desc->wProductID);
1041 	hw->idVersion = le16toh(desc->wVersionID);
1042 
1043 	/* get ACPI HID. It is a base part of the device name. */
1044 	if (ACPI_FAILURE(AcpiGetObjectInfo(handle, &device_info)))
1045 		return (ENXIO);
1046 
1047 	if (device_info->Valid & ACPI_VALID_HID)
1048 		strlcpy(hw->idPnP, device_info->HardwareId.String,
1049 		    HID_PNP_ID_SIZE);
1050 	snprintf(hw->name, sizeof(hw->name), "%s:%02lX %04X:%04X",
1051 	    (device_info->Valid & ACPI_VALID_HID) ?
1052 	    device_info->HardwareId.String : "Unknown",
1053 	    (device_info->Valid & ACPI_VALID_UID) ?
1054 	    strtoul(device_info->UniqueId.String, NULL, 10) : 0UL,
1055 	    le16toh(desc->wVendorID), le16toh(desc->wProductID));
1056 
1057 	AcpiOsFree(device_info);
1058 
1059 	strlcpy(hw->serial, "", sizeof(hw->serial));
1060 	hw->rdescsize = le16toh(desc->wReportDescLength);
1061 	if (desc->wOutputRegister == 0 || desc->wMaxOutputLength == 0)
1062 		hid_add_dynamic_quirk(hw, HQ_NOWRITE);
1063 
1064 	return (0);
1065 }
1066 
1067 static int
1068 iichid_probe(device_t dev)
1069 {
1070 	struct iichid_softc *sc;
1071 	ACPI_HANDLE handle;
1072 	uint16_t config_reg;
1073 	int error, reg;
1074 
1075 	sc = device_get_softc(dev);
1076 	sc->dev = dev;
1077 	if (sc->probe_done)
1078 		goto done;
1079 
1080 	sc->probe_done = true;
1081 	sc->probe_result = ENXIO;
1082 
1083 	if (acpi_disabled("iichid"))
1084 		return (ENXIO);
1085 
1086 	sc->addr = iicbus_get_addr(dev) << 1;
1087 	if (sc->addr == 0)
1088 		return (ENXIO);
1089 
1090 	handle = acpi_get_handle(dev);
1091 	if (handle == NULL)
1092 		return (ENXIO);
1093 
1094 	reg = acpi_is_iichid(handle);
1095 	if (reg == IICHID_REG_NONE)
1096 		return (ENXIO);
1097 
1098 	if (reg == IICHID_REG_ACPI) {
1099 		if (ACPI_FAILURE(iichid_get_config_reg(handle, &config_reg)))
1100 			return (ENXIO);
1101 	} else
1102 		config_reg = (uint16_t)reg;
1103 
1104 	DPRINTF(sc, "  IICbus addr       : 0x%02X\n", sc->addr >> 1);
1105 	DPRINTF(sc, "  HID descriptor reg: 0x%02X\n", config_reg);
1106 
1107 	error = iichid_cmd_get_hid_desc(sc, config_reg, &sc->desc);
1108 	if (error) {
1109 		DPRINTF(sc, "could not retrieve HID descriptor from the "
1110 		    "device: %d\n", error);
1111 		return (ENXIO);
1112 	}
1113 
1114 	if (le16toh(sc->desc.wHIDDescLength) != 30 ||
1115 	    le16toh(sc->desc.bcdVersion) != 0x100) {
1116 		DPRINTF(sc, "HID descriptor is broken\n");
1117 		return (ENXIO);
1118 	}
1119 
1120 	/* Setup hid_device_info so we can figure out quirks for the device. */
1121 	if (iichid_fill_device_info(&sc->desc, handle, &sc->hw) != 0) {
1122 		DPRINTF(sc, "error evaluating AcpiGetObjectInfo\n");
1123 		return (ENXIO);
1124 	}
1125 
1126 	if (hid_test_quirk(&sc->hw, HQ_HID_IGNORE))
1127 		return (ENXIO);
1128 
1129 	sc->probe_result = BUS_PROBE_DEFAULT;
1130 done:
1131 	if (sc->probe_result <= BUS_PROBE_SPECIFIC)
1132 		device_set_descf(dev, "%s I2C HID device", sc->hw.name);
1133 	return (sc->probe_result);
1134 }
1135 
1136 static int
1137 iichid_attach(device_t dev)
1138 {
1139 	struct iichid_softc *sc;
1140 	device_t child;
1141 	int error;
1142 
1143 	sc = device_get_softc(dev);
1144 	error = iichid_set_power(sc, I2C_HID_POWER_ON);
1145 	if (error) {
1146 		device_printf(dev, "failed to power on: %d\n", error);
1147 		return (ENXIO);
1148 	}
1149 	sc->power_on = true;
1150 
1151 	mtx_init(&sc->mtx, device_get_nameunit(dev), NULL, MTX_DEF);
1152 	sc->intr_bufsize = le16toh(sc->desc.wMaxInputLength) - 2;
1153 	sc->intr_buf = malloc(sc->intr_bufsize, M_DEVBUF, M_WAITOK | M_ZERO);
1154 	TASK_INIT(&sc->suspend_task, 0, iichid_suspend_task, sc);
1155 #ifdef IICHID_SAMPLING
1156 	sc->taskqueue = taskqueue_create_fast("iichid_tq", M_WAITOK | M_ZERO,
1157 	    taskqueue_thread_enqueue, &sc->taskqueue);
1158 	TIMEOUT_TASK_INIT(sc->taskqueue, &sc->sampling_task, 0,
1159 	    iichid_sampling_task, sc);
1160 
1161 	sc->sampling_rate_slow = -1;
1162 	sc->sampling_rate_fast = IICHID_SAMPLING_RATE_FAST;
1163 	sc->sampling_hysteresis = IICHID_SAMPLING_HYSTERESIS;
1164 	sc->dup_buf = malloc(sc->intr_bufsize, M_DEVBUF, M_WAITOK | M_ZERO);
1165 #endif
1166 
1167 	sc->irq_rid = 0;
1168 	sc->irq_res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ,
1169 	    &sc->irq_rid, RF_ACTIVE);
1170 
1171 	if (sc->irq_res != NULL) {
1172 		DPRINTF(sc, "allocated irq at %p and rid %d\n",
1173 		    sc->irq_res, sc->irq_rid);
1174 		error = iichid_setup_interrupt(sc);
1175 	}
1176 
1177 	if (sc->irq_res == NULL || error != 0) {
1178 #ifdef IICHID_SAMPLING
1179 		device_printf(sc->dev,
1180 		    "Using sampling mode\n");
1181 		sc->sampling_rate_slow = IICHID_SAMPLING_RATE_SLOW;
1182 #else
1183 		device_printf(sc->dev, "Interrupt setup failed\n");
1184 		if (sc->irq_res != NULL)
1185 			bus_release_resource(dev, SYS_RES_IRQ, sc->irq_rid,
1186 			    sc->irq_res);
1187 		iichid_detach(dev);
1188 		error = ENXIO;
1189 		goto done;
1190 #endif
1191 	}
1192 
1193 #ifdef IICHID_SAMPLING
1194 	SYSCTL_ADD_PROC(device_get_sysctl_ctx(sc->dev),
1195 		SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)),
1196 		OID_AUTO, "sampling_rate_slow", CTLTYPE_INT | CTLFLAG_RWTUN,
1197 		sc, 0, iichid_sysctl_sampling_rate_handler, "I",
1198 		"idle sampling rate in num/second");
1199 	SYSCTL_ADD_INT(device_get_sysctl_ctx(sc->dev),
1200 		SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)),
1201 		OID_AUTO, "sampling_rate_fast", CTLFLAG_RWTUN,
1202 		&sc->sampling_rate_fast, 0,
1203 		"active sampling rate in num/second");
1204 	SYSCTL_ADD_INT(device_get_sysctl_ctx(sc->dev),
1205 		SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)),
1206 		OID_AUTO, "sampling_hysteresis", CTLFLAG_RWTUN,
1207 		&sc->sampling_hysteresis, 0,
1208 		"number of missing samples before enabling of slow mode");
1209 	hid_add_dynamic_quirk(&sc->hw, HQ_IICHID_SAMPLING);
1210 #endif /* IICHID_SAMPLING */
1211 
1212 	/*
1213 	 * Windows driver sleeps for 1ms between the SET_POWER and RESET
1214 	 * commands. So we too as some devices may depend on this.
1215 	 */
1216 	pause("iichid", (hz + 999) / 1000);
1217 
1218 	error = iichid_reset(sc);
1219 	if (error) {
1220 		device_printf(dev, "failed to reset hardware: %d\n", error);
1221 		iichid_detach(dev);
1222 		error = ENXIO;
1223 		goto done;
1224 	}
1225 
1226 	/* Wait for RESET response */
1227 #ifdef IICHID_SAMPLING
1228 	if (sc->sampling_rate_slow >= 0) {
1229 		pause("iichid", (hz + 999) / 1000);
1230 		(void)iichid_cmd_read(sc, sc->intr_buf, 0, NULL);
1231 	} else
1232 #endif /* IICHID_SAMPLING */
1233 	{
1234 		mtx_lock(&sc->mtx);
1235 		if (!sc->reset_acked && !cold) {
1236 			error = mtx_sleep(&sc->reset_acked,  &sc->mtx, 0,
1237 			    "iichid_reset", hz * IICHID_RESET_TIMEOUT);
1238 			if (error != 0)
1239 				device_printf(sc->dev,
1240 				    "Reset timeout expired\n");
1241 		}
1242 		mtx_unlock(&sc->mtx);
1243 	}
1244 
1245 	child = device_add_child(dev, "hidbus", DEVICE_UNIT_ANY);
1246 	if (child == NULL) {
1247 		device_printf(sc->dev, "Could not add I2C device\n");
1248 		iichid_detach(dev);
1249 		error = ENOMEM;
1250 		goto done;
1251 	}
1252 
1253 	device_set_ivars(child, &sc->hw);
1254 	bus_attach_children(dev);
1255 	error = 0;
1256 done:
1257 	iicbus_request_bus(device_get_parent(dev), dev, IIC_WAIT);
1258 	if (!sc->open) {
1259 		(void)iichid_set_power(sc, I2C_HID_POWER_OFF);
1260 		sc->power_on = false;
1261 	}
1262 	iicbus_release_bus(device_get_parent(dev), dev);
1263 	return (error);
1264 }
1265 
1266 static int
1267 iichid_detach(device_t dev)
1268 {
1269 	struct iichid_softc *sc;
1270 	int error;
1271 
1272 	sc = device_get_softc(dev);
1273 	error = bus_generic_detach(dev);
1274 	if (error)
1275 		return (error);
1276 	iichid_teardown_interrupt(sc);
1277 	if (sc->irq_res != NULL)
1278 		bus_release_resource(dev, SYS_RES_IRQ, sc->irq_rid,
1279 		    sc->irq_res);
1280 #ifdef IICHID_SAMPLING
1281 	if (sc->taskqueue != NULL)
1282 		taskqueue_free(sc->taskqueue);
1283 	sc->taskqueue = NULL;
1284 	free(sc->dup_buf, M_DEVBUF);
1285 #endif
1286 	free(sc->intr_buf, M_DEVBUF);
1287 	mtx_destroy(&sc->mtx);
1288 	return (0);
1289 }
1290 
1291 static void
1292 iichid_suspend_task(void *context, int pending)
1293 {
1294 	struct iichid_softc *sc = context;
1295 
1296 	iichid_teardown_interrupt(sc);
1297 }
1298 
1299 static int
1300 iichid_suspend(device_t dev)
1301 {
1302 	struct iichid_softc *sc;
1303 	int error;
1304 
1305 	sc = device_get_softc(dev);
1306 	(void)bus_generic_suspend(dev);
1307 	/*
1308 	 * 8.2 - The HOST is going into a deep power optimized state and wishes
1309 	 * to put all the devices into a low power state also.  The HOST
1310 	 * is recommended to issue a HIPO command to the DEVICE to force
1311 	 * the DEVICE in to a lower power state.
1312 	 */
1313 	DPRINTF(sc, "Suspend called, setting device to power_state 1\n");
1314 	error = iichid_set_power_state(sc, IICHID_PS_NULL, IICHID_PS_OFF);
1315 	if (error != 0)
1316 		DPRINTF(sc, "Could not set power_state, error: %d\n", error);
1317 	else
1318 		DPRINTF(sc, "Successfully set power_state\n");
1319 
1320 #ifdef IICHID_SAMPLING
1321 	if (sc->sampling_rate_slow < 0)
1322 #endif
1323 	{
1324 		/*
1325 		 * bus_teardown_intr can not be executed right here as it wants
1326 		 * to run on certain CPU to interacts with LAPIC while suspend
1327 		 * thread is bound to CPU0. So run it from taskqueue context.
1328 		 */
1329 #ifdef IICHID_SAMPLING
1330 #define	suspend_thread	sc->taskqueue
1331 #else
1332 #define	suspend_thread	taskqueue_thread
1333 #endif
1334 		taskqueue_enqueue(suspend_thread, &sc->suspend_task);
1335 		taskqueue_drain(suspend_thread, &sc->suspend_task);
1336 	}
1337 
1338 	return (0);
1339 }
1340 
1341 static int
1342 iichid_resume(device_t dev)
1343 {
1344 	struct iichid_softc *sc;
1345 	int error;
1346 
1347 	sc = device_get_softc(dev);
1348 #ifdef IICHID_SAMPLING
1349 	if (sc->sampling_rate_slow < 0)
1350 #endif
1351 		iichid_setup_interrupt(sc);
1352 
1353 	DPRINTF(sc, "Resume called, setting device to power_state 0\n");
1354 	error = iichid_set_power_state(sc, IICHID_PS_NULL, IICHID_PS_ON);
1355 	if (error != 0)
1356 		DPRINTF(sc, "Could not set power_state, error: %d\n", error);
1357 	else
1358 		DPRINTF(sc, "Successfully set power_state\n");
1359 	(void)bus_generic_resume(dev);
1360 
1361 	return (0);
1362 }
1363 
1364 static device_method_t iichid_methods[] = {
1365 	DEVMETHOD(device_probe,		iichid_probe),
1366 	DEVMETHOD(device_attach,	iichid_attach),
1367 	DEVMETHOD(device_detach,	iichid_detach),
1368 	DEVMETHOD(device_suspend,	iichid_suspend),
1369 	DEVMETHOD(device_resume,	iichid_resume),
1370 
1371 	DEVMETHOD(hid_intr_setup,	iichid_intr_setup),
1372 	DEVMETHOD(hid_intr_unsetup,	iichid_intr_unsetup),
1373 	DEVMETHOD(hid_intr_start,	iichid_intr_start),
1374 	DEVMETHOD(hid_intr_stop,	iichid_intr_stop),
1375 	DEVMETHOD(hid_intr_poll,	iichid_intr_poll),
1376 
1377 	/* HID interface */
1378 	DEVMETHOD(hid_get_rdesc,	iichid_get_rdesc),
1379 	DEVMETHOD(hid_read,		iichid_read),
1380 	DEVMETHOD(hid_write,		iichid_write),
1381 	DEVMETHOD(hid_get_report,	iichid_get_report),
1382 	DEVMETHOD(hid_set_report,	iichid_set_report),
1383 	DEVMETHOD(hid_set_idle,		iichid_set_idle),
1384 	DEVMETHOD(hid_set_protocol,	iichid_set_protocol),
1385 	DEVMETHOD(hid_ioctl,		iichid_ioctl),
1386 
1387 	DEVMETHOD_END
1388 };
1389 
1390 static driver_t iichid_driver = {
1391 	.name = "iichid",
1392 	.methods = iichid_methods,
1393 	.size = sizeof(struct iichid_softc),
1394 };
1395 
1396 DRIVER_MODULE(iichid, iicbus, iichid_driver, NULL, NULL);
1397 MODULE_DEPEND(iichid, iicbus, IICBUS_MINVER, IICBUS_PREFVER, IICBUS_MAXVER);
1398 MODULE_DEPEND(iichid, acpi, 1, 1, 1);
1399 MODULE_DEPEND(iichid, hid, 1, 1, 1);
1400 MODULE_DEPEND(iichid, hidbus, 1, 1, 1);
1401 MODULE_VERSION(iichid, 1);
1402 IICBUS_ACPI_PNP_INFO(iichid_ids);
1403