xref: /freebsd/sys/dev/iicbus/iichid.c (revision 1e74951b6cd8132ae417177336b7180e174a5e3f)
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 
279 	memset(buf, 0xaa, 2);   // In case nothing gets read
280 	struct iic_msg msgs[] = {
281 	    { sc->addr, IIC_M_RD, maxlen, buf },
282 	};
283 	int error;
284 
285 	error = iicbus_transfer(sc->dev, msgs, nitems(msgs));
286 	if (error != 0)
287 		return (error);
288 
289 	DPRINTFN(sc, 5, "%*D\n", msgs[0].len, msgs[0].buf, " ");
290 
291 	uint16_t actlen = le16dec(buf);
292 
293 	if (actlen == 0) {
294 		if (!sc->reset_acked) {
295 			mtx_lock(&sc->mtx);
296 			sc->reset_acked = true;
297 			wakeup(&sc->reset_acked);
298 			mtx_unlock(&sc->mtx);
299 		}
300 	}
301 
302 	if (actlen <= 2 || actlen > maxlen) {
303 		actlen = 0;
304 	}
305 	if (actual_len != NULL) {
306 		*actual_len = actlen;
307 	}
308 
309 	return (error);
310 }
311 
312 static int
iichid_cmd_write(struct iichid_softc * sc,const void * buf,iichid_size_t len)313 iichid_cmd_write(struct iichid_softc *sc, const void *buf, iichid_size_t len)
314 {
315 	/* 6.2.3 - Sending Output Reports. */
316 	uint8_t *cmdreg = (uint8_t *)&sc->desc.wOutputRegister;
317 	uint16_t replen = 2 + len;
318 	uint8_t cmd[4] = { cmdreg[0], cmdreg[1], replen & 0xFF, replen >> 8 };
319 	struct iic_msg msgs[] = {
320 	    {sc->addr, IIC_M_WR | IIC_M_NOSTOP, sizeof(cmd), cmd},
321 	    {sc->addr, IIC_M_WR | IIC_M_NOSTART, len, __DECONST(void *, buf)},
322 	};
323 
324 	if (le16toh(sc->desc.wMaxOutputLength) == 0)
325 		return (IIC_ENOTSUPP);
326 	if (len < 2)
327 		return (IIC_ENOTSUPP);
328 
329 	DPRINTF(sc, "HID command I2C_HID_CMD_WRITE (len %d): "
330 	    "%*D\n", len, len, buf, " ");
331 
332 	return (iicbus_transfer(sc->dev, msgs, nitems(msgs)));
333 }
334 
335 static int
iichid_cmd_get_hid_desc(struct iichid_softc * sc,uint16_t config_reg,struct i2c_hid_desc * hid_desc)336 iichid_cmd_get_hid_desc(struct iichid_softc *sc, uint16_t config_reg,
337     struct i2c_hid_desc *hid_desc)
338 {
339 	/*
340 	 * 5.2.2 - HID Descriptor Retrieval
341 	 * register is passed from the controller.
342 	 */
343 	uint16_t cmd = htole16(config_reg);
344 	struct iic_msg msgs[] = {
345 	    { sc->addr, IIC_M_WR | IIC_M_NOSTOP, 2, (uint8_t *)&cmd },
346 	    { sc->addr, IIC_M_RD, sizeof(*hid_desc), (uint8_t *)hid_desc },
347 	};
348 	int error;
349 
350 	DPRINTF(sc, "HID command I2C_HID_CMD_DESCR at 0x%x\n", config_reg);
351 
352 	error = iicbus_transfer(sc->dev, msgs, nitems(msgs));
353 	if (error != 0)
354 		return (error);
355 
356 	DPRINTF(sc, "HID descriptor: %*D\n",
357 	    (int)sizeof(struct i2c_hid_desc), hid_desc, " ");
358 
359 	return (0);
360 }
361 
362 static int
iichid_set_power(struct iichid_softc * sc,uint8_t param)363 iichid_set_power(struct iichid_softc *sc, uint8_t param)
364 {
365 	uint8_t *cmdreg = (uint8_t *)&sc->desc.wCommandRegister;
366 	uint8_t cmd[] = { cmdreg[0], cmdreg[1], param, I2C_HID_CMD_SET_POWER };
367 	struct iic_msg msgs[] = {
368 	    { sc->addr, IIC_M_WR, sizeof(cmd), cmd },
369 	};
370 
371 	DPRINTF(sc, "HID command I2C_HID_CMD_SET_POWER(%d)\n", param);
372 
373 	return (iicbus_transfer(sc->dev, msgs, nitems(msgs)));
374 }
375 
376 static int
iichid_reset(struct iichid_softc * sc)377 iichid_reset(struct iichid_softc *sc)
378 {
379 	uint8_t *cmdreg = (uint8_t *)&sc->desc.wCommandRegister;
380 	uint8_t cmd[] = { cmdreg[0], cmdreg[1], 0, I2C_HID_CMD_RESET };
381 	struct iic_msg msgs[] = {
382 	    { sc->addr, IIC_M_WR, sizeof(cmd), cmd },
383 	};
384 
385 	DPRINTF(sc, "HID command I2C_HID_CMD_RESET\n");
386 
387 	return (iicbus_transfer(sc->dev, msgs, nitems(msgs)));
388 }
389 
390 static int
iichid_cmd_get_report_desc(struct iichid_softc * sc,void * buf,iichid_size_t len)391 iichid_cmd_get_report_desc(struct iichid_softc* sc, void *buf,
392     iichid_size_t len)
393 {
394 	uint16_t cmd = sc->desc.wReportDescRegister;
395 	struct iic_msg msgs[] = {
396 	    { sc->addr, IIC_M_WR | IIC_M_NOSTOP, 2, (uint8_t *)&cmd },
397 	    { sc->addr, IIC_M_RD, len, buf },
398 	};
399 	int error;
400 
401 	DPRINTF(sc, "HID command I2C_HID_REPORT_DESCR at 0x%x with size %d\n",
402 	    le16toh(cmd), len);
403 
404 	error = iicbus_transfer(sc->dev, msgs, nitems(msgs));
405 	if (error != 0)
406 		return (error);
407 
408 	DPRINTF(sc, "HID report descriptor: %*D\n", len, buf, " ");
409 
410 	return (0);
411 }
412 
413 static int
iichid_cmd_get_report(struct iichid_softc * sc,void * buf,iichid_size_t maxlen,iichid_size_t * actual_len,uint8_t type,uint8_t id)414 iichid_cmd_get_report(struct iichid_softc* sc, void *buf, iichid_size_t maxlen,
415     iichid_size_t *actual_len, uint8_t type, uint8_t id)
416 {
417 	/*
418 	 * 7.2.2.4 - "The protocol is optimized for Report < 15.  If a
419 	 * report ID >= 15 is necessary, then the Report ID in the Low Byte
420 	 * must be set to 1111 and a Third Byte is appended to the protocol.
421 	 * This Third Byte contains the entire/actual report ID."
422 	 */
423 	uint8_t *dtareg = (uint8_t *)&sc->desc.wDataRegister;
424 	uint8_t *cmdreg = (uint8_t *)&sc->desc.wCommandRegister;
425 	uint8_t cmd[] =	{   /*________|______id>=15_____|______id<15______*/
426 						    cmdreg[0]		   ,
427 						    cmdreg[1]		   ,
428 			    (id >= 15 ? 15 | (type << 4): id | (type << 4)),
429 					      I2C_HID_CMD_GET_REPORT	   ,
430 			    (id >= 15 ?		id	:    dtareg[0]	  ),
431 			    (id >= 15 ?	   dtareg[0]	:    dtareg[1]	  ),
432 			    (id >= 15 ?    dtareg[1]	:	0	  ),
433 			};
434 	int cmdlen    =	    (id >= 15 ?		7	:	6	  );
435 	uint8_t actbuf[2] = { 0, 0 };
436 	uint16_t actlen;
437 	int d, error;
438 	struct iic_msg msgs[] = {
439 	    { sc->addr, IIC_M_WR | IIC_M_NOSTOP, cmdlen, cmd },
440 	    { sc->addr, IIC_M_RD | IIC_M_NOSTOP, 2, actbuf },
441 	    { sc->addr, IIC_M_RD | IIC_M_NOSTART, maxlen, buf },
442 	};
443 
444 	if (maxlen == 0)
445 		return (EINVAL);
446 
447 	DPRINTF(sc, "HID command I2C_HID_CMD_GET_REPORT %d "
448 	    "(type %d, len %d)\n", id, type, maxlen);
449 
450 	/*
451 	 * 7.2.2.2 - Response will be a 2-byte length value, the report
452 	 * id (1 byte, if defined in Report Descriptor), and then the report.
453 	 */
454 	error = iicbus_transfer(sc->dev, msgs, nitems(msgs));
455 	if (error != 0)
456 		return (error);
457 
458 	actlen = actbuf[0] | actbuf[1] << 8;
459 	if (actlen != maxlen + 2)
460 		DPRINTF(sc, "response size %d != expected length %d\n",
461 		    actlen, maxlen + 2);
462 
463 	if (actlen <= 2 || actlen == 0xFFFF)
464 		return (ENOMSG);
465 
466 	d = id != 0 ? *(uint8_t *)buf : 0;
467 	if (d != id) {
468 		DPRINTF(sc, "response report id %d != %d\n", d, id);
469 		return (EBADMSG);
470 	}
471 
472 	actlen -= 2;
473 	if (actlen > maxlen)
474 		actlen = maxlen;
475 	if (actual_len != NULL)
476 		*actual_len = actlen;
477 
478 	DPRINTF(sc, "response: %*D %*D\n", 2, actbuf, " ", actlen, buf, " ");
479 
480 	return (0);
481 }
482 
483 static int
iichid_cmd_set_report(struct iichid_softc * sc,const void * buf,iichid_size_t len,uint8_t type,uint8_t id)484 iichid_cmd_set_report(struct iichid_softc* sc, const void *buf,
485     iichid_size_t len, uint8_t type, uint8_t id)
486 {
487 	/*
488 	 * 7.2.2.4 - "The protocol is optimized for Report < 15.  If a
489 	 * report ID >= 15 is necessary, then the Report ID in the Low Byte
490 	 * must be set to 1111 and a Third Byte is appended to the protocol.
491 	 * This Third Byte contains the entire/actual report ID."
492 	 */
493 	uint8_t *dtareg = (uint8_t *)&sc->desc.wDataRegister;
494 	uint8_t *cmdreg = (uint8_t *)&sc->desc.wCommandRegister;
495 	uint16_t replen = 2 + len;
496 	uint8_t cmd[] =	{   /*________|______id>=15_____|______id<15______*/
497 						    cmdreg[0]		   ,
498 						    cmdreg[1]		   ,
499 			    (id >= 15 ? 15 | (type << 4): id | (type << 4)),
500 					      I2C_HID_CMD_SET_REPORT	   ,
501 			    (id >= 15 ?		id	:    dtareg[0]    ),
502 			    (id >= 15 ?    dtareg[0]	:    dtareg[1]    ),
503 			    (id >= 15 ?    dtareg[1]	:   replen & 0xff ),
504 			    (id >= 15 ?   replen & 0xff	:   replen >> 8   ),
505 			    (id >= 15 ?   replen >> 8	:	0	  ),
506 			};
507 	int cmdlen    =	    (id >= 15 ?		9	:	8	  );
508 	struct iic_msg msgs[] = {
509 	    {sc->addr, IIC_M_WR | IIC_M_NOSTOP, cmdlen, cmd},
510 	    {sc->addr, IIC_M_WR | IIC_M_NOSTART, len, __DECONST(void *, buf)},
511 	};
512 
513 	DPRINTF(sc, "HID command I2C_HID_CMD_SET_REPORT %d (type %d, len %d): "
514 	    "%*D\n", id, type, len, len, buf, " ");
515 
516 	return (iicbus_transfer(sc->dev, msgs, nitems(msgs)));
517 }
518 
519 #ifdef IICHID_SAMPLING
520 static void
iichid_sampling_task(void * context,int pending)521 iichid_sampling_task(void *context, int pending)
522 {
523 	struct iichid_softc *sc;
524 	device_t parent;
525 	iichid_size_t actual;
526 	bool bus_requested;
527 	int error, rate;
528 
529 	sc = context;
530 	parent = device_get_parent(sc->dev);
531 
532 	bus_requested = false;
533 	if (iicbus_request_bus(parent, sc->dev, IIC_WAIT) != 0)
534 		goto rearm;
535 	bus_requested = true;
536 
537 	if (!sc->power_on)
538 		goto out;
539 
540 	error = iichid_cmd_read(sc, sc->intr_buf, sc->intr_bufsize, &actual);
541 	if (error == 0) {
542 		if (actual > 0) {
543 			sc->intr_handler(sc->intr_ctx, sc->intr_buf + 2, actual - 2);
544 			sc->missing_samples = 0;
545 			if (sc->dup_size != actual ||
546 			    memcmp(sc->dup_buf, sc->intr_buf, actual) != 0) {
547 				sc->dup_size = actual;
548 				memcpy(sc->dup_buf, sc->intr_buf, actual);
549 				sc->dup_samples = 0;
550 			} else
551 				++sc->dup_samples;
552 		} else {
553 			if (++sc->missing_samples == 1)
554 				sc->intr_handler(sc->intr_ctx, sc->intr_buf + 2, 0);
555 			sc->dup_samples = 0;
556 		}
557 	} else
558 		DPRINTF(sc, "read error occurred: %d\n", error);
559 
560 rearm:
561 	if (sc->callout_setup && sc->sampling_rate_slow > 0) {
562 		if (sc->missing_samples >= sc->sampling_hysteresis ||
563 		    sc->dup_samples >= sc->sampling_hysteresis)
564 			rate = sc->sampling_rate_slow;
565 		else
566 			rate = sc->sampling_rate_fast;
567 		taskqueue_enqueue_timeout_sbt(sc->taskqueue, &sc->sampling_task,
568 		    SBT_1S / MAX(rate, 1), 0, C_PREL(2));
569 	}
570 out:
571 	if (bus_requested)
572 		iicbus_release_bus(parent, sc->dev);
573 }
574 #endif	/* IICHID_SAMPLING */
575 
576 static void
iichid_intr(void * context)577 iichid_intr(void *context)
578 {
579 	struct iichid_softc *sc;
580 	device_t parent;
581 	iichid_size_t actual;
582 	int error;
583 
584 	sc = context;
585 	parent = device_get_parent(sc->dev);
586 
587 	/*
588 	 * Designware(IG4) driver-specific hack.
589 	 * Requesting of an I2C bus with IIC_DONTWAIT parameter enables polled
590 	 * mode in the driver, making possible iicbus_transfer execution from
591 	 * interrupt handlers and callouts.
592 	 */
593 	if (iicbus_request_bus(parent, sc->dev, IIC_DONTWAIT) != 0)
594 		return;
595 
596 	/*
597 	 * Reading of input reports of I2C devices residing in SLEEP state is
598 	 * not allowed and often returns a garbage.  If a HOST needs to
599 	 * communicate with the DEVICE it MUST issue a SET POWER command
600 	 * (to ON) before any other command. As some hardware requires reads to
601 	 * acknowledge interrupts we fetch only length header and discard it.
602 	 */
603 	THREAD_SLEEPING_OK();
604 	error = iichid_cmd_read(sc, sc->intr_buf, sc->intr_bufsize, &actual);
605 	THREAD_NO_SLEEPING();
606 	if (error == 0) {
607 		if (sc->power_on && sc->open) {
608 			if (actual != 0)
609 				sc->intr_handler(sc->intr_ctx, sc->intr_buf + 2,
610 				    actual - 2);
611 			else
612 				DPRINTF(sc, "no data received\n");
613 		}
614 	} else
615 		DPRINTF(sc, "read error occurred: %d\n", error);
616 
617 	iicbus_release_bus(parent, sc->dev);
618 }
619 
620 static int
iichid_set_power_state(struct iichid_softc * sc,enum iichid_powerstate_how how_open,enum iichid_powerstate_how how_suspend)621 iichid_set_power_state(struct iichid_softc *sc,
622      enum iichid_powerstate_how how_open,
623      enum iichid_powerstate_how how_suspend)
624 {
625 	device_t parent;
626 	int error;
627 	int how_request;
628 	bool power_on;
629 
630 	/*
631 	 * Request iicbus early as sc->suspend and sc->power_on
632 	 * are protected by iicbus internal lock.
633 	 */
634 	parent = device_get_parent(sc->dev);
635 	/* Allow to interrupt open()/close() handlers by SIGINT */
636 	how_request = how_open == IICHID_PS_NULL ? IIC_WAIT : IIC_INTRWAIT;
637 	error = iicbus_request_bus(parent, sc->dev, how_request);
638 	if (error != 0)
639 		return (error);
640 
641 	switch (how_open) {
642 	case IICHID_PS_ON:
643 		sc->open = true;
644 		break;
645 	case IICHID_PS_OFF:
646 		sc->open = false;
647 		break;
648 	case IICHID_PS_NULL:
649 	default:
650 		break;
651 	}
652 
653 	switch (how_suspend) {
654 	case IICHID_PS_ON:
655 		sc->suspend = false;
656 		break;
657 	case IICHID_PS_OFF:
658 		sc->suspend = true;
659 		break;
660 	case IICHID_PS_NULL:
661 	default:
662 		break;
663 	}
664 
665 	power_on = sc->open & !sc->suspend;
666 
667 	if (power_on != sc->power_on) {
668 		error = iichid_set_power(sc,
669 		    power_on ? I2C_HID_POWER_ON : I2C_HID_POWER_OFF);
670 
671 		sc->power_on = power_on;
672 #ifdef IICHID_SAMPLING
673 		if (sc->sampling_rate_slow >= 0 && sc->intr_handler != NULL) {
674 			if (power_on) {
675 				iichid_setup_callout(sc);
676 				iichid_reset_callout(sc);
677 			} else
678 				iichid_teardown_callout(sc);
679 		}
680 #endif
681 	}
682 
683 	iicbus_release_bus(parent, sc->dev);
684 
685 	return (error);
686 }
687 
688 static int
iichid_setup_interrupt(struct iichid_softc * sc)689 iichid_setup_interrupt(struct iichid_softc *sc)
690 {
691 	sc->irq_cookie = 0;
692 
693 	int error = bus_setup_intr(sc->dev, sc->irq_res,
694 	    INTR_TYPE_TTY|INTR_MPSAFE, NULL, iichid_intr, sc, &sc->irq_cookie);
695 	if (error != 0)
696 		DPRINTF(sc, "Could not setup interrupt handler\n");
697 	else
698 		DPRINTF(sc, "successfully setup interrupt\n");
699 
700 	return (error);
701 }
702 
703 static void
iichid_teardown_interrupt(struct iichid_softc * sc)704 iichid_teardown_interrupt(struct iichid_softc *sc)
705 {
706 	if (sc->irq_cookie)
707 		bus_teardown_intr(sc->dev, sc->irq_res, sc->irq_cookie);
708 
709 	sc->irq_cookie = 0;
710 }
711 
712 #ifdef IICHID_SAMPLING
713 static int
iichid_setup_callout(struct iichid_softc * sc)714 iichid_setup_callout(struct iichid_softc *sc)
715 {
716 
717 	if (sc->sampling_rate_slow < 0) {
718 		DPRINTF(sc, "sampling_rate is below 0, can't setup callout\n");
719 		return (EINVAL);
720 	}
721 
722 	sc->callout_setup = true;
723 	DPRINTF(sc, "successfully setup callout\n");
724 	return (0);
725 }
726 
727 static int
iichid_reset_callout(struct iichid_softc * sc)728 iichid_reset_callout(struct iichid_softc *sc)
729 {
730 
731 	if (sc->sampling_rate_slow <= 0) {
732 		DPRINTF(sc, "sampling_rate is below or equal to 0, "
733 		    "can't reset callout\n");
734 		return (EINVAL);
735 	}
736 
737 	if (!sc->callout_setup)
738 		return (EINVAL);
739 
740 	/* Start with slow sampling. */
741 	sc->missing_samples = sc->sampling_hysteresis;
742 	sc->dup_samples = 0;
743 	sc->dup_size = 0;
744 	taskqueue_enqueue_timeout(sc->taskqueue, &sc->sampling_task, 0);
745 
746 	return (0);
747 }
748 
749 static void
iichid_teardown_callout(struct iichid_softc * sc)750 iichid_teardown_callout(struct iichid_softc *sc)
751 {
752 
753 	sc->callout_setup = false;
754 	taskqueue_cancel_timeout(sc->taskqueue, &sc->sampling_task, NULL);
755 	DPRINTF(sc, "tore callout down\n");
756 }
757 
758 static int
iichid_sysctl_sampling_rate_handler(SYSCTL_HANDLER_ARGS)759 iichid_sysctl_sampling_rate_handler(SYSCTL_HANDLER_ARGS)
760 {
761 	struct iichid_softc *sc;
762 	device_t parent;
763 	int error, oldval, value;
764 
765 	sc = arg1;
766 
767 	value = sc->sampling_rate_slow;
768 	error = sysctl_handle_int(oidp, &value, 0, req);
769 
770 	if (error != 0 || req->newptr == NULL ||
771 	    value == sc->sampling_rate_slow)
772 		return (error);
773 
774 	/* Can't switch to interrupt mode if it is not supported. */
775 	if (sc->irq_res == NULL && value < 0)
776 		return (EINVAL);
777 
778 	parent = device_get_parent(sc->dev);
779 	error = iicbus_request_bus(parent, sc->dev, IIC_WAIT);
780 	if (error != 0)
781 		return (iic2errno(error));
782 
783 	oldval = sc->sampling_rate_slow;
784 	sc->sampling_rate_slow = value;
785 
786 	if (oldval < 0 && value >= 0) {
787 		iichid_teardown_interrupt(sc);
788 		if (sc->power_on)
789 			iichid_setup_callout(sc);
790 	} else if (oldval >= 0 && value < 0) {
791 		if (sc->power_on)
792 			iichid_teardown_callout(sc);
793 		iichid_setup_interrupt(sc);
794 	}
795 
796 	if (sc->power_on && value > 0)
797 		iichid_reset_callout(sc);
798 
799 	iicbus_release_bus(parent, sc->dev);
800 
801 	DPRINTF(sc, "new sampling_rate value: %d\n", value);
802 
803 	return (0);
804 }
805 #endif /* IICHID_SAMPLING */
806 
807 static void
iichid_intr_setup(device_t dev,device_t child __unused,hid_intr_t intr,void * context,struct hid_rdesc_info * rdesc)808 iichid_intr_setup(device_t dev, device_t child __unused, hid_intr_t intr,
809     void *context, struct hid_rdesc_info *rdesc)
810 {
811 	struct iichid_softc *sc;
812 	device_t parent;
813 
814 	if (intr == NULL)
815 		return;
816 
817 	sc = device_get_softc(dev);
818 	/*
819 	 * Start with wMaxInputLength to follow HID-over-I2C specs. Than if
820 	 * semi-HID device like ietp(4) requested changing of input buffer
821 	 * size with report descriptor overloading, find the longest input
822 	 * report in the descriptor, and add two for the length field.
823 	 */
824 	rdesc->rdsize = rdesc->rdsize == 0 ?
825 	    le16toh(sc->desc.wMaxInputLength) - 2 : rdesc->isize;
826 	/* Write and get/set_report sizes are limited by I2C-HID protocol. */
827 	rdesc->grsize = rdesc->srsize = IICHID_SIZE_MAX;
828 	rdesc->wrsize = IICHID_SIZE_MAX;
829 
830 	parent = device_get_parent(sc->dev);
831 	iicbus_request_bus(parent, sc->dev, IIC_WAIT);
832 
833 	sc->intr_handler = intr;
834 	sc->intr_ctx = context;
835 	sc->intr_bufsize = rdesc->rdsize + 2;
836 	sc->intr_buf = realloc(sc->intr_buf, sc->intr_bufsize,
837 	    M_DEVBUF, M_WAITOK | M_ZERO);
838 #ifdef IICHID_SAMPLING
839 	sc->dup_buf = realloc(sc->dup_buf, sc->intr_bufsize,
840 	    M_DEVBUF, M_WAITOK | M_ZERO);
841 	taskqueue_start_threads(&sc->taskqueue, 1, PI_TTY,
842 	    "%s taskq", device_get_nameunit(sc->dev));
843 #endif
844 	iicbus_release_bus(parent, sc->dev);
845 }
846 
847 static void
iichid_intr_unsetup(device_t dev,device_t child __unused)848 iichid_intr_unsetup(device_t dev, device_t child __unused)
849 {
850 #ifdef IICHID_SAMPLING
851 	struct iichid_softc *sc;
852 
853 	sc = device_get_softc(dev);
854 	taskqueue_drain_all(sc->taskqueue);
855 #endif
856 }
857 
858 static int
iichid_intr_start(device_t dev,device_t child __unused)859 iichid_intr_start(device_t dev, device_t child __unused)
860 {
861 	struct iichid_softc *sc;
862 
863 	sc = device_get_softc(dev);
864 	DPRINTF(sc, "iichid device open\n");
865 	if (!sc->open)
866 		iichid_set_power_state(sc, IICHID_PS_ON, IICHID_PS_NULL);
867 
868 	return (0);
869 }
870 
871 static int
iichid_intr_stop(device_t dev,device_t child __unused)872 iichid_intr_stop(device_t dev, device_t child __unused)
873 {
874 	struct iichid_softc *sc;
875 
876 	sc = device_get_softc(dev);
877 	DPRINTF(sc, "iichid device close\n");
878 	/*
879 	 * 8.2 - The HOST determines that there are no active applications
880 	 * that are currently using the specific HID DEVICE.  The HOST
881 	 * is recommended to issue a HIPO command to the DEVICE to force
882 	 * the DEVICE in to a lower power state.
883 	 */
884 	iichid_set_power_state(sc, IICHID_PS_OFF, IICHID_PS_NULL);
885 
886 	return (0);
887 }
888 
889 static void
iichid_intr_poll(device_t dev,device_t child __unused)890 iichid_intr_poll(device_t dev, device_t child __unused)
891 {
892 	struct iichid_softc *sc;
893 	iichid_size_t actual;
894 	int error;
895 
896 	sc = device_get_softc(dev);
897 	error = iichid_cmd_read(sc, sc->intr_buf, sc->intr_bufsize, &actual);
898 	if (error == 0 && actual != 0)
899 		sc->intr_handler(sc->intr_ctx, sc->intr_buf + 2, actual);
900 }
901 
902 /*
903  * HID interface
904  */
905 static int
iichid_get_rdesc(device_t dev,device_t child __unused,void * buf,hid_size_t len)906 iichid_get_rdesc(device_t dev, device_t child __unused, void *buf,
907     hid_size_t len)
908 {
909 	struct iichid_softc *sc;
910 	int error;
911 
912 	sc = device_get_softc(dev);
913 	error = iichid_cmd_get_report_desc(sc, buf, len);
914 	if (error)
915 		DPRINTF(sc, "failed to fetch report descriptor: %d\n", error);
916 
917 	return (iic2errno(error));
918 }
919 
920 static int
iichid_read(device_t dev,device_t child __unused,void * buf,hid_size_t maxlen,hid_size_t * actlen)921 iichid_read(device_t dev, device_t child __unused, void *buf,
922     hid_size_t maxlen, hid_size_t *actlen)
923 {
924 	struct iichid_softc *sc;
925 	device_t parent;
926 	uint8_t *tmpbuf;
927 	int error;
928 
929 	if (maxlen > IICHID_SIZE_MAX)
930 		return (EMSGSIZE);
931 	sc = device_get_softc(dev);
932 	parent = device_get_parent(sc->dev);
933 	error = iicbus_request_bus(parent, sc->dev, IIC_WAIT);
934 	if (error == 0) {
935 		tmpbuf = malloc(maxlen + 2, M_DEVBUF, M_WAITOK | M_ZERO);
936 		error = iichid_cmd_read(sc, tmpbuf, maxlen + 2, actlen);
937 		iicbus_release_bus(parent, sc->dev);
938 		if (*actlen > 0)
939 			memcpy(buf, tmpbuf + 2, *actlen);
940 		free(tmpbuf, M_DEVBUF);
941 	}
942 	return (iic2errno(error));
943 }
944 
945 static int
iichid_write(device_t dev,device_t child __unused,const void * buf,hid_size_t len)946 iichid_write(device_t dev, device_t child __unused, const void *buf,
947     hid_size_t len)
948 {
949 	struct iichid_softc *sc;
950 
951 	if (len > IICHID_SIZE_MAX)
952 		return (EMSGSIZE);
953 	sc = device_get_softc(dev);
954 	return (iic2errno(iichid_cmd_write(sc, buf, len)));
955 }
956 
957 static int
iichid_get_report(device_t dev,device_t child __unused,void * buf,hid_size_t maxlen,hid_size_t * actlen,uint8_t type,uint8_t id)958 iichid_get_report(device_t dev, device_t child __unused, void *buf,
959     hid_size_t maxlen, hid_size_t *actlen, uint8_t type, uint8_t id)
960 {
961 	struct iichid_softc *sc;
962 
963 	if (maxlen > IICHID_SIZE_MAX)
964 		return (EMSGSIZE);
965 	sc = device_get_softc(dev);
966 	return (iic2errno(
967 	    iichid_cmd_get_report(sc, buf, maxlen, actlen, type, id)));
968 }
969 
970 static int
iichid_set_report(device_t dev,device_t child __unused,const void * buf,hid_size_t len,uint8_t type,uint8_t id)971 iichid_set_report(device_t dev, device_t child __unused, const void *buf,
972     hid_size_t len, uint8_t type, uint8_t id)
973 {
974 	struct iichid_softc *sc;
975 
976 	if (len > IICHID_SIZE_MAX)
977 		return (EMSGSIZE);
978 	sc = device_get_softc(dev);
979 	return (iic2errno(iichid_cmd_set_report(sc, buf, len, type, id)));
980 }
981 
982 static int
iichid_set_idle(device_t dev,device_t child __unused,uint16_t duration,uint8_t id)983 iichid_set_idle(device_t dev, device_t child __unused,
984     uint16_t duration, uint8_t id)
985 {
986 	return (ENOTSUP);
987 }
988 
989 static int
iichid_set_protocol(device_t dev,device_t child __unused,uint16_t protocol)990 iichid_set_protocol(device_t dev, device_t child __unused, uint16_t protocol)
991 {
992 	return (ENOTSUP);
993 }
994 
995 static int
iichid_ioctl(device_t dev,device_t child __unused,unsigned long cmd,uintptr_t data)996 iichid_ioctl(device_t dev, device_t child __unused, unsigned long cmd,
997     uintptr_t data)
998 {
999 	int error;
1000 
1001 	switch (cmd) {
1002 	case I2CRDWR:
1003 		error = iic2errno(iicbus_transfer(dev,
1004 		    ((struct iic_rdwr_data *)data)->msgs,
1005 		    ((struct iic_rdwr_data *)data)->nmsgs));
1006 		break;
1007 	default:
1008 		error = EINVAL;
1009 	}
1010 
1011 	return (error);
1012 }
1013 
1014 static int
iichid_fill_device_info(struct i2c_hid_desc * desc,ACPI_HANDLE handle,struct hid_device_info * hw)1015 iichid_fill_device_info(struct i2c_hid_desc *desc, ACPI_HANDLE handle,
1016     struct hid_device_info *hw)
1017 {
1018 	ACPI_DEVICE_INFO *device_info;
1019 
1020 	hw->idBus = BUS_I2C;
1021 	hw->idVendor = le16toh(desc->wVendorID);
1022 	hw->idProduct = le16toh(desc->wProductID);
1023 	hw->idVersion = le16toh(desc->wVersionID);
1024 
1025 	/* get ACPI HID. It is a base part of the device name. */
1026 	if (ACPI_FAILURE(AcpiGetObjectInfo(handle, &device_info)))
1027 		return (ENXIO);
1028 
1029 	if (device_info->Valid & ACPI_VALID_HID)
1030 		strlcpy(hw->idPnP, device_info->HardwareId.String,
1031 		    HID_PNP_ID_SIZE);
1032 	snprintf(hw->name, sizeof(hw->name), "%s:%02lX %04X:%04X",
1033 	    (device_info->Valid & ACPI_VALID_HID) ?
1034 	    device_info->HardwareId.String : "Unknown",
1035 	    (device_info->Valid & ACPI_VALID_UID) ?
1036 	    strtoul(device_info->UniqueId.String, NULL, 10) : 0UL,
1037 	    le16toh(desc->wVendorID), le16toh(desc->wProductID));
1038 
1039 	AcpiOsFree(device_info);
1040 
1041 	strlcpy(hw->serial, "", sizeof(hw->serial));
1042 	hw->rdescsize = le16toh(desc->wReportDescLength);
1043 	if (desc->wOutputRegister == 0 || desc->wMaxOutputLength == 0)
1044 		hid_add_dynamic_quirk(hw, HQ_NOWRITE);
1045 
1046 	return (0);
1047 }
1048 
1049 static int
iichid_probe(device_t dev)1050 iichid_probe(device_t dev)
1051 {
1052 	struct iichid_softc *sc;
1053 	ACPI_HANDLE handle;
1054 	uint16_t config_reg;
1055 	int error, reg;
1056 
1057 	sc = device_get_softc(dev);
1058 	sc->dev = dev;
1059 	if (sc->probe_done)
1060 		goto done;
1061 
1062 	sc->probe_done = true;
1063 	sc->probe_result = ENXIO;
1064 
1065 	if (acpi_disabled("iichid"))
1066 		return (ENXIO);
1067 
1068 	sc->addr = iicbus_get_addr(dev) << 1;
1069 	if (sc->addr == 0)
1070 		return (ENXIO);
1071 
1072 	handle = acpi_get_handle(dev);
1073 	if (handle == NULL)
1074 		return (ENXIO);
1075 
1076 	reg = acpi_is_iichid(handle);
1077 	if (reg == IICHID_REG_NONE)
1078 		return (ENXIO);
1079 
1080 	if (reg == IICHID_REG_ACPI) {
1081 		if (ACPI_FAILURE(iichid_get_config_reg(handle, &config_reg)))
1082 			return (ENXIO);
1083 	} else
1084 		config_reg = (uint16_t)reg;
1085 
1086 	DPRINTF(sc, "  IICbus addr       : 0x%02X\n", sc->addr >> 1);
1087 	DPRINTF(sc, "  HID descriptor reg: 0x%02X\n", config_reg);
1088 
1089 	error = iichid_cmd_get_hid_desc(sc, config_reg, &sc->desc);
1090 	if (error) {
1091 		DPRINTF(sc, "could not retrieve HID descriptor from the "
1092 		    "device: %d\n", error);
1093 		return (ENXIO);
1094 	}
1095 
1096 	if (le16toh(sc->desc.wHIDDescLength) != 30 ||
1097 	    le16toh(sc->desc.bcdVersion) != 0x100 ||
1098 	    le16toh(sc->desc.wMaxInputLength) < 2) {
1099 		DPRINTF(sc, "HID descriptor is broken\n");
1100 		return (ENXIO);
1101 	}
1102 
1103 	/* Setup hid_device_info so we can figure out quirks for the device. */
1104 	if (iichid_fill_device_info(&sc->desc, handle, &sc->hw) != 0) {
1105 		DPRINTF(sc, "error evaluating AcpiGetObjectInfo\n");
1106 		return (ENXIO);
1107 	}
1108 
1109 	if (hid_test_quirk(&sc->hw, HQ_HID_IGNORE))
1110 		return (ENXIO);
1111 
1112 	sc->probe_result = BUS_PROBE_DEFAULT;
1113 done:
1114 	if (sc->probe_result <= BUS_PROBE_SPECIFIC)
1115 		device_set_descf(dev, "%s I2C HID device", sc->hw.name);
1116 	return (sc->probe_result);
1117 }
1118 
1119 static int
iichid_attach(device_t dev)1120 iichid_attach(device_t dev)
1121 {
1122 	struct iichid_softc *sc;
1123 	device_t child;
1124 	int error;
1125 
1126 	sc = device_get_softc(dev);
1127 	error = iichid_set_power(sc, I2C_HID_POWER_ON);
1128 	if (error) {
1129 		device_printf(dev, "failed to power on: %d\n", error);
1130 		return (ENXIO);
1131 	}
1132 	sc->power_on = true;
1133 
1134 	mtx_init(&sc->mtx, device_get_nameunit(dev), NULL, MTX_DEF);
1135 	sc->intr_bufsize = le16toh(sc->desc.wMaxInputLength) - 2;
1136 	sc->intr_buf = malloc(sc->intr_bufsize, M_DEVBUF, M_WAITOK | M_ZERO);
1137 	TASK_INIT(&sc->suspend_task, 0, iichid_suspend_task, sc);
1138 #ifdef IICHID_SAMPLING
1139 	sc->taskqueue = taskqueue_create_fast("iichid_tq", M_WAITOK | M_ZERO,
1140 	    taskqueue_thread_enqueue, &sc->taskqueue);
1141 	TIMEOUT_TASK_INIT(sc->taskqueue, &sc->sampling_task, 0,
1142 	    iichid_sampling_task, sc);
1143 
1144 	sc->sampling_rate_slow = -1;
1145 	sc->sampling_rate_fast = IICHID_SAMPLING_RATE_FAST;
1146 	sc->sampling_hysteresis = IICHID_SAMPLING_HYSTERESIS;
1147 	sc->dup_buf = malloc(sc->intr_bufsize, M_DEVBUF, M_WAITOK | M_ZERO);
1148 #endif
1149 
1150 	sc->irq_rid = 0;
1151 	sc->irq_res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ,
1152 	    &sc->irq_rid, RF_ACTIVE);
1153 
1154 	if (sc->irq_res != NULL) {
1155 		DPRINTF(sc, "allocated irq at %p and rid %d\n",
1156 		    sc->irq_res, sc->irq_rid);
1157 		error = iichid_setup_interrupt(sc);
1158 	}
1159 
1160 	if (sc->irq_res == NULL || error != 0) {
1161 #ifdef IICHID_SAMPLING
1162 		device_printf(sc->dev,
1163 		    "Using sampling mode\n");
1164 		sc->sampling_rate_slow = IICHID_SAMPLING_RATE_SLOW;
1165 #else
1166 		device_printf(sc->dev, "Interrupt setup failed\n");
1167 		if (sc->irq_res != NULL)
1168 			bus_release_resource(dev, SYS_RES_IRQ, sc->irq_rid,
1169 			    sc->irq_res);
1170 		iichid_detach(dev);
1171 		error = ENXIO;
1172 		goto done;
1173 #endif
1174 	}
1175 
1176 #ifdef IICHID_SAMPLING
1177 	SYSCTL_ADD_PROC(device_get_sysctl_ctx(sc->dev),
1178 		SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)),
1179 		OID_AUTO, "sampling_rate_slow", CTLTYPE_INT | CTLFLAG_RWTUN,
1180 		sc, 0, iichid_sysctl_sampling_rate_handler, "I",
1181 		"idle sampling rate in num/second");
1182 	SYSCTL_ADD_INT(device_get_sysctl_ctx(sc->dev),
1183 		SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)),
1184 		OID_AUTO, "sampling_rate_fast", CTLFLAG_RWTUN,
1185 		&sc->sampling_rate_fast, 0,
1186 		"active sampling rate in num/second");
1187 	SYSCTL_ADD_INT(device_get_sysctl_ctx(sc->dev),
1188 		SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)),
1189 		OID_AUTO, "sampling_hysteresis", CTLFLAG_RWTUN,
1190 		&sc->sampling_hysteresis, 0,
1191 		"number of missing samples before enabling of slow mode");
1192 	hid_add_dynamic_quirk(&sc->hw, HQ_IICHID_SAMPLING);
1193 #endif /* IICHID_SAMPLING */
1194 
1195 	/*
1196 	 * Windows driver sleeps for 1ms between the SET_POWER and RESET
1197 	 * commands. So we too as some devices may depend on this.
1198 	 */
1199 	pause("iichid", (hz + 999) / 1000);
1200 
1201 	error = iichid_reset(sc);
1202 	if (error) {
1203 		device_printf(dev, "failed to reset hardware: %d\n", error);
1204 		iichid_detach(dev);
1205 		error = ENXIO;
1206 		goto done;
1207 	}
1208 
1209 	/* Wait for RESET response */
1210 #ifdef IICHID_SAMPLING
1211 	if (sc->sampling_rate_slow >= 0) {
1212 		pause("iichid", (hz + 999) / 1000);
1213 		(void)iichid_cmd_read(sc, sc->intr_buf, 0, NULL);
1214 	} else
1215 #endif /* IICHID_SAMPLING */
1216 	{
1217 		mtx_lock(&sc->mtx);
1218 		if (!sc->reset_acked && !cold) {
1219 			error = mtx_sleep(&sc->reset_acked,  &sc->mtx, 0,
1220 			    "iichid_reset", hz * IICHID_RESET_TIMEOUT);
1221 			if (error != 0)
1222 				device_printf(sc->dev,
1223 				    "Reset timeout expired\n");
1224 		}
1225 		mtx_unlock(&sc->mtx);
1226 	}
1227 
1228 	child = device_add_child(dev, "hidbus", DEVICE_UNIT_ANY);
1229 	if (child == NULL) {
1230 		device_printf(sc->dev, "Could not add I2C device\n");
1231 		iichid_detach(dev);
1232 		error = ENOMEM;
1233 		goto done;
1234 	}
1235 
1236 	device_set_ivars(child, &sc->hw);
1237 	bus_attach_children(dev);
1238 	error = 0;
1239 done:
1240 	iicbus_request_bus(device_get_parent(dev), dev, IIC_WAIT);
1241 	if (!sc->open) {
1242 		(void)iichid_set_power(sc, I2C_HID_POWER_OFF);
1243 		sc->power_on = false;
1244 	}
1245 	iicbus_release_bus(device_get_parent(dev), dev);
1246 	return (error);
1247 }
1248 
1249 static int
iichid_detach(device_t dev)1250 iichid_detach(device_t dev)
1251 {
1252 	struct iichid_softc *sc;
1253 	int error;
1254 
1255 	sc = device_get_softc(dev);
1256 	error = bus_generic_detach(dev);
1257 	if (error)
1258 		return (error);
1259 	iichid_teardown_interrupt(sc);
1260 	if (sc->irq_res != NULL)
1261 		bus_release_resource(dev, SYS_RES_IRQ, sc->irq_rid,
1262 		    sc->irq_res);
1263 #ifdef IICHID_SAMPLING
1264 	if (sc->taskqueue != NULL)
1265 		taskqueue_free(sc->taskqueue);
1266 	sc->taskqueue = NULL;
1267 	free(sc->dup_buf, M_DEVBUF);
1268 #endif
1269 	free(sc->intr_buf, M_DEVBUF);
1270 	mtx_destroy(&sc->mtx);
1271 	return (0);
1272 }
1273 
1274 static void
iichid_suspend_task(void * context,int pending)1275 iichid_suspend_task(void *context, int pending)
1276 {
1277 	struct iichid_softc *sc = context;
1278 
1279 	iichid_teardown_interrupt(sc);
1280 }
1281 
1282 static int
iichid_suspend(device_t dev)1283 iichid_suspend(device_t dev)
1284 {
1285 	struct iichid_softc *sc;
1286 	int error;
1287 
1288 	sc = device_get_softc(dev);
1289 	(void)bus_generic_suspend(dev);
1290 	/*
1291 	 * 8.2 - The HOST is going into a deep power optimized state and wishes
1292 	 * to put all the devices into a low power state also.  The HOST
1293 	 * is recommended to issue a HIPO command to the DEVICE to force
1294 	 * the DEVICE in to a lower power state.
1295 	 */
1296 	DPRINTF(sc, "Suspend called, setting device to power_state 1\n");
1297 	error = iichid_set_power_state(sc, IICHID_PS_NULL, IICHID_PS_OFF);
1298 	if (error != 0)
1299 		DPRINTF(sc, "Could not set power_state, error: %d\n", error);
1300 	else
1301 		DPRINTF(sc, "Successfully set power_state\n");
1302 
1303 #ifdef IICHID_SAMPLING
1304 	if (sc->sampling_rate_slow < 0)
1305 #endif
1306 	{
1307 		/*
1308 		 * bus_teardown_intr can not be executed right here as it wants
1309 		 * to run on certain CPU to interacts with LAPIC while suspend
1310 		 * thread is bound to CPU0. So run it from taskqueue context.
1311 		 */
1312 #ifdef IICHID_SAMPLING
1313 #define	suspend_thread	sc->taskqueue
1314 #else
1315 #define	suspend_thread	taskqueue_thread
1316 #endif
1317 		taskqueue_enqueue(suspend_thread, &sc->suspend_task);
1318 		taskqueue_drain(suspend_thread, &sc->suspend_task);
1319 	}
1320 
1321 	return (0);
1322 }
1323 
1324 static int
iichid_resume(device_t dev)1325 iichid_resume(device_t dev)
1326 {
1327 	struct iichid_softc *sc;
1328 	int error;
1329 
1330 	sc = device_get_softc(dev);
1331 #ifdef IICHID_SAMPLING
1332 	if (sc->sampling_rate_slow < 0)
1333 #endif
1334 		iichid_setup_interrupt(sc);
1335 
1336 	DPRINTF(sc, "Resume called, setting device to power_state 0\n");
1337 	error = iichid_set_power_state(sc, IICHID_PS_NULL, IICHID_PS_ON);
1338 	if (error != 0)
1339 		DPRINTF(sc, "Could not set power_state, error: %d\n", error);
1340 	else
1341 		DPRINTF(sc, "Successfully set power_state\n");
1342 	(void)bus_generic_resume(dev);
1343 
1344 	return (0);
1345 }
1346 
1347 static device_method_t iichid_methods[] = {
1348 	DEVMETHOD(device_probe,		iichid_probe),
1349 	DEVMETHOD(device_attach,	iichid_attach),
1350 	DEVMETHOD(device_detach,	iichid_detach),
1351 	DEVMETHOD(device_suspend,	iichid_suspend),
1352 	DEVMETHOD(device_resume,	iichid_resume),
1353 
1354 	DEVMETHOD(hid_intr_setup,	iichid_intr_setup),
1355 	DEVMETHOD(hid_intr_unsetup,	iichid_intr_unsetup),
1356 	DEVMETHOD(hid_intr_start,	iichid_intr_start),
1357 	DEVMETHOD(hid_intr_stop,	iichid_intr_stop),
1358 	DEVMETHOD(hid_intr_poll,	iichid_intr_poll),
1359 
1360 	/* HID interface */
1361 	DEVMETHOD(hid_get_rdesc,	iichid_get_rdesc),
1362 	DEVMETHOD(hid_read,		iichid_read),
1363 	DEVMETHOD(hid_write,		iichid_write),
1364 	DEVMETHOD(hid_get_report,	iichid_get_report),
1365 	DEVMETHOD(hid_set_report,	iichid_set_report),
1366 	DEVMETHOD(hid_set_idle,		iichid_set_idle),
1367 	DEVMETHOD(hid_set_protocol,	iichid_set_protocol),
1368 	DEVMETHOD(hid_ioctl,		iichid_ioctl),
1369 
1370 	DEVMETHOD_END
1371 };
1372 
1373 static driver_t iichid_driver = {
1374 	.name = "iichid",
1375 	.methods = iichid_methods,
1376 	.size = sizeof(struct iichid_softc),
1377 };
1378 
1379 DRIVER_MODULE(iichid, iicbus, iichid_driver, NULL, NULL);
1380 MODULE_DEPEND(iichid, iicbus, IICBUS_MINVER, IICBUS_PREFVER, IICBUS_MAXVER);
1381 MODULE_DEPEND(iichid, acpi, 1, 1, 1);
1382 MODULE_DEPEND(iichid, hid, 1, 1, 1);
1383 MODULE_DEPEND(iichid, hidbus, 1, 1, 1);
1384 MODULE_VERSION(iichid, 1);
1385 IICBUS_ACPI_PNP_INFO(iichid_ids);
1386