xref: /freebsd/sys/dev/iicbus/iichid.c (revision df6ae0577d2c966ac0db9983ae353c24b53067eb)
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);
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);
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 	 * Do not rely just on wMaxInputLength, as some devices (which?)
820 	 * may set it to a wrong length.  Also find the longest input report
821 	 * in report descriptor, and add two for the length field.
822 	 */
823 	rdesc->rdsize = 2 +
824 	    MAX(rdesc->isize, le16toh(sc->desc.wMaxInputLength));
825 	/* Write and get/set_report sizes are limited by I2C-HID protocol. */
826 	rdesc->grsize = rdesc->srsize = IICHID_SIZE_MAX;
827 	rdesc->wrsize = IICHID_SIZE_MAX;
828 
829 	parent = device_get_parent(sc->dev);
830 	iicbus_request_bus(parent, sc->dev, IIC_WAIT);
831 
832 	sc->intr_handler = intr;
833 	sc->intr_ctx = context;
834 	sc->intr_bufsize = rdesc->rdsize;
835 	sc->intr_buf = realloc(sc->intr_buf, sc->intr_bufsize,
836 	    M_DEVBUF, M_WAITOK | M_ZERO);
837 #ifdef IICHID_SAMPLING
838 	sc->dup_buf = realloc(sc->dup_buf, sc->intr_bufsize,
839 	    M_DEVBUF, M_WAITOK | M_ZERO);
840 	taskqueue_start_threads(&sc->taskqueue, 1, PI_TTY,
841 	    "%s taskq", device_get_nameunit(sc->dev));
842 #endif
843 	iicbus_release_bus(parent, sc->dev);
844 }
845 
846 static void
iichid_intr_unsetup(device_t dev,device_t child __unused)847 iichid_intr_unsetup(device_t dev, device_t child __unused)
848 {
849 #ifdef IICHID_SAMPLING
850 	struct iichid_softc *sc;
851 
852 	sc = device_get_softc(dev);
853 	taskqueue_drain_all(sc->taskqueue);
854 #endif
855 }
856 
857 static int
iichid_intr_start(device_t dev,device_t child __unused)858 iichid_intr_start(device_t dev, device_t child __unused)
859 {
860 	struct iichid_softc *sc;
861 
862 	sc = device_get_softc(dev);
863 	DPRINTF(sc, "iichid device open\n");
864 	if (!sc->open)
865 		iichid_set_power_state(sc, IICHID_PS_ON, IICHID_PS_NULL);
866 
867 	return (0);
868 }
869 
870 static int
iichid_intr_stop(device_t dev,device_t child __unused)871 iichid_intr_stop(device_t dev, device_t child __unused)
872 {
873 	struct iichid_softc *sc;
874 
875 	sc = device_get_softc(dev);
876 	DPRINTF(sc, "iichid device close\n");
877 	/*
878 	 * 8.2 - The HOST determines that there are no active applications
879 	 * that are currently using the specific HID DEVICE.  The HOST
880 	 * is recommended to issue a HIPO command to the DEVICE to force
881 	 * the DEVICE in to a lower power state.
882 	 */
883 	iichid_set_power_state(sc, IICHID_PS_OFF, IICHID_PS_NULL);
884 
885 	return (0);
886 }
887 
888 static void
iichid_intr_poll(device_t dev,device_t child __unused)889 iichid_intr_poll(device_t dev, device_t child __unused)
890 {
891 	struct iichid_softc *sc;
892 	iichid_size_t actual;
893 	int error;
894 
895 	sc = device_get_softc(dev);
896 	error = iichid_cmd_read(sc, sc->intr_buf, sc->intr_bufsize, &actual);
897 	if (error == 0 && actual != 0)
898 		sc->intr_handler(sc->intr_ctx, sc->intr_buf + 2, actual);
899 }
900 
901 /*
902  * HID interface
903  */
904 static int
iichid_get_rdesc(device_t dev,device_t child __unused,void * buf,hid_size_t len)905 iichid_get_rdesc(device_t dev, device_t child __unused, void *buf,
906     hid_size_t len)
907 {
908 	struct iichid_softc *sc;
909 	int error;
910 
911 	sc = device_get_softc(dev);
912 	error = iichid_cmd_get_report_desc(sc, buf, len);
913 	if (error)
914 		DPRINTF(sc, "failed to fetch report descriptor: %d\n", error);
915 
916 	return (iic2errno(error));
917 }
918 
919 static int
iichid_read(device_t dev,device_t child __unused,void * buf,hid_size_t maxlen,hid_size_t * actlen)920 iichid_read(device_t dev, device_t child __unused, void *buf,
921     hid_size_t maxlen, hid_size_t *actlen)
922 {
923 	struct iichid_softc *sc;
924 	device_t parent;
925 	uint8_t *tmpbuf;
926 	int error;
927 
928 	if (maxlen > IICHID_SIZE_MAX)
929 		return (EMSGSIZE);
930 	sc = device_get_softc(dev);
931 	parent = device_get_parent(sc->dev);
932 	error = iicbus_request_bus(parent, sc->dev, IIC_WAIT);
933 	if (error == 0) {
934 		tmpbuf = malloc(maxlen + 2, M_DEVBUF, M_WAITOK | M_ZERO);
935 		error = iichid_cmd_read(sc, tmpbuf, maxlen + 2, actlen);
936 		iicbus_release_bus(parent, sc->dev);
937 		if (*actlen > 0)
938 			memcpy(buf, tmpbuf + 2, *actlen);
939 		free(tmpbuf, M_DEVBUF);
940 	}
941 	return (iic2errno(error));
942 }
943 
944 static int
iichid_write(device_t dev,device_t child __unused,const void * buf,hid_size_t len)945 iichid_write(device_t dev, device_t child __unused, const void *buf,
946     hid_size_t len)
947 {
948 	struct iichid_softc *sc;
949 
950 	if (len > IICHID_SIZE_MAX)
951 		return (EMSGSIZE);
952 	sc = device_get_softc(dev);
953 	return (iic2errno(iichid_cmd_write(sc, buf, len)));
954 }
955 
956 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)957 iichid_get_report(device_t dev, device_t child __unused, void *buf,
958     hid_size_t maxlen, hid_size_t *actlen, uint8_t type, uint8_t id)
959 {
960 	struct iichid_softc *sc;
961 
962 	if (maxlen > IICHID_SIZE_MAX)
963 		return (EMSGSIZE);
964 	sc = device_get_softc(dev);
965 	return (iic2errno(
966 	    iichid_cmd_get_report(sc, buf, maxlen, actlen, type, id)));
967 }
968 
969 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)970 iichid_set_report(device_t dev, device_t child __unused, const void *buf,
971     hid_size_t len, uint8_t type, uint8_t id)
972 {
973 	struct iichid_softc *sc;
974 
975 	if (len > IICHID_SIZE_MAX)
976 		return (EMSGSIZE);
977 	sc = device_get_softc(dev);
978 	return (iic2errno(iichid_cmd_set_report(sc, buf, len, type, id)));
979 }
980 
981 static int
iichid_set_idle(device_t dev,device_t child __unused,uint16_t duration,uint8_t id)982 iichid_set_idle(device_t dev, device_t child __unused,
983     uint16_t duration, uint8_t id)
984 {
985 	return (ENOTSUP);
986 }
987 
988 static int
iichid_set_protocol(device_t dev,device_t child __unused,uint16_t protocol)989 iichid_set_protocol(device_t dev, device_t child __unused, uint16_t protocol)
990 {
991 	return (ENOTSUP);
992 }
993 
994 static int
iichid_ioctl(device_t dev,device_t child __unused,unsigned long cmd,uintptr_t data)995 iichid_ioctl(device_t dev, device_t child __unused, unsigned long cmd,
996     uintptr_t data)
997 {
998 	int error;
999 
1000 	switch (cmd) {
1001 	case I2CRDWR:
1002 		error = iic2errno(iicbus_transfer(dev,
1003 		    ((struct iic_rdwr_data *)data)->msgs,
1004 		    ((struct iic_rdwr_data *)data)->nmsgs));
1005 		break;
1006 	default:
1007 		error = EINVAL;
1008 	}
1009 
1010 	return (error);
1011 }
1012 
1013 static int
iichid_fill_device_info(struct i2c_hid_desc * desc,ACPI_HANDLE handle,struct hid_device_info * hw)1014 iichid_fill_device_info(struct i2c_hid_desc *desc, ACPI_HANDLE handle,
1015     struct hid_device_info *hw)
1016 {
1017 	ACPI_DEVICE_INFO *device_info;
1018 
1019 	hw->idBus = BUS_I2C;
1020 	hw->idVendor = le16toh(desc->wVendorID);
1021 	hw->idProduct = le16toh(desc->wProductID);
1022 	hw->idVersion = le16toh(desc->wVersionID);
1023 
1024 	/* get ACPI HID. It is a base part of the device name. */
1025 	if (ACPI_FAILURE(AcpiGetObjectInfo(handle, &device_info)))
1026 		return (ENXIO);
1027 
1028 	if (device_info->Valid & ACPI_VALID_HID)
1029 		strlcpy(hw->idPnP, device_info->HardwareId.String,
1030 		    HID_PNP_ID_SIZE);
1031 	snprintf(hw->name, sizeof(hw->name), "%s:%02lX %04X:%04X",
1032 	    (device_info->Valid & ACPI_VALID_HID) ?
1033 	    device_info->HardwareId.String : "Unknown",
1034 	    (device_info->Valid & ACPI_VALID_UID) ?
1035 	    strtoul(device_info->UniqueId.String, NULL, 10) : 0UL,
1036 	    le16toh(desc->wVendorID), le16toh(desc->wProductID));
1037 
1038 	AcpiOsFree(device_info);
1039 
1040 	strlcpy(hw->serial, "", sizeof(hw->serial));
1041 	hw->rdescsize = le16toh(desc->wReportDescLength);
1042 	if (desc->wOutputRegister == 0 || desc->wMaxOutputLength == 0)
1043 		hid_add_dynamic_quirk(hw, HQ_NOWRITE);
1044 
1045 	return (0);
1046 }
1047 
1048 static int
iichid_probe(device_t dev)1049 iichid_probe(device_t dev)
1050 {
1051 	struct iichid_softc *sc;
1052 	ACPI_HANDLE handle;
1053 	uint16_t config_reg;
1054 	int error, reg;
1055 
1056 	sc = device_get_softc(dev);
1057 	sc->dev = dev;
1058 	if (sc->probe_done)
1059 		goto done;
1060 
1061 	sc->probe_done = true;
1062 	sc->probe_result = ENXIO;
1063 
1064 	if (acpi_disabled("iichid"))
1065 		return (ENXIO);
1066 
1067 	sc->addr = iicbus_get_addr(dev) << 1;
1068 	if (sc->addr == 0)
1069 		return (ENXIO);
1070 
1071 	handle = acpi_get_handle(dev);
1072 	if (handle == NULL)
1073 		return (ENXIO);
1074 
1075 	reg = acpi_is_iichid(handle);
1076 	if (reg == IICHID_REG_NONE)
1077 		return (ENXIO);
1078 
1079 	if (reg == IICHID_REG_ACPI) {
1080 		if (ACPI_FAILURE(iichid_get_config_reg(handle, &config_reg)))
1081 			return (ENXIO);
1082 	} else
1083 		config_reg = (uint16_t)reg;
1084 
1085 	DPRINTF(sc, "  IICbus addr       : 0x%02X\n", sc->addr >> 1);
1086 	DPRINTF(sc, "  HID descriptor reg: 0x%02X\n", config_reg);
1087 
1088 	error = iichid_cmd_get_hid_desc(sc, config_reg, &sc->desc);
1089 	if (error) {
1090 		DPRINTF(sc, "could not retrieve HID descriptor from the "
1091 		    "device: %d\n", error);
1092 		return (ENXIO);
1093 	}
1094 
1095 	if (le16toh(sc->desc.wHIDDescLength) != 30 ||
1096 	    le16toh(sc->desc.bcdVersion) != 0x100) {
1097 		DPRINTF(sc, "HID descriptor is broken\n");
1098 		return (ENXIO);
1099 	}
1100 
1101 	/* Setup hid_device_info so we can figure out quirks for the device. */
1102 	if (iichid_fill_device_info(&sc->desc, handle, &sc->hw) != 0) {
1103 		DPRINTF(sc, "error evaluating AcpiGetObjectInfo\n");
1104 		return (ENXIO);
1105 	}
1106 
1107 	if (hid_test_quirk(&sc->hw, HQ_HID_IGNORE))
1108 		return (ENXIO);
1109 
1110 	sc->probe_result = BUS_PROBE_DEFAULT;
1111 done:
1112 	if (sc->probe_result <= BUS_PROBE_SPECIFIC)
1113 		device_set_descf(dev, "%s I2C HID device", sc->hw.name);
1114 	return (sc->probe_result);
1115 }
1116 
1117 static int
iichid_attach(device_t dev)1118 iichid_attach(device_t dev)
1119 {
1120 	struct iichid_softc *sc;
1121 	device_t child;
1122 	int error;
1123 
1124 	sc = device_get_softc(dev);
1125 	error = iichid_set_power(sc, I2C_HID_POWER_ON);
1126 	if (error) {
1127 		device_printf(dev, "failed to power on: %d\n", error);
1128 		return (ENXIO);
1129 	}
1130 	sc->power_on = true;
1131 
1132 	mtx_init(&sc->mtx, device_get_nameunit(dev), NULL, MTX_DEF);
1133 	sc->intr_bufsize = le16toh(sc->desc.wMaxInputLength) - 2;
1134 	sc->intr_buf = malloc(sc->intr_bufsize, M_DEVBUF, M_WAITOK | M_ZERO);
1135 	TASK_INIT(&sc->suspend_task, 0, iichid_suspend_task, sc);
1136 #ifdef IICHID_SAMPLING
1137 	sc->taskqueue = taskqueue_create_fast("iichid_tq", M_WAITOK | M_ZERO,
1138 	    taskqueue_thread_enqueue, &sc->taskqueue);
1139 	TIMEOUT_TASK_INIT(sc->taskqueue, &sc->sampling_task, 0,
1140 	    iichid_sampling_task, sc);
1141 
1142 	sc->sampling_rate_slow = -1;
1143 	sc->sampling_rate_fast = IICHID_SAMPLING_RATE_FAST;
1144 	sc->sampling_hysteresis = IICHID_SAMPLING_HYSTERESIS;
1145 	sc->dup_buf = malloc(sc->intr_bufsize, M_DEVBUF, M_WAITOK | M_ZERO);
1146 #endif
1147 
1148 	sc->irq_rid = 0;
1149 	sc->irq_res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ,
1150 	    &sc->irq_rid, RF_ACTIVE);
1151 
1152 	if (sc->irq_res != NULL) {
1153 		DPRINTF(sc, "allocated irq at %p and rid %d\n",
1154 		    sc->irq_res, sc->irq_rid);
1155 		error = iichid_setup_interrupt(sc);
1156 	}
1157 
1158 	if (sc->irq_res == NULL || error != 0) {
1159 #ifdef IICHID_SAMPLING
1160 		device_printf(sc->dev,
1161 		    "Using sampling mode\n");
1162 		sc->sampling_rate_slow = IICHID_SAMPLING_RATE_SLOW;
1163 #else
1164 		device_printf(sc->dev, "Interrupt setup failed\n");
1165 		if (sc->irq_res != NULL)
1166 			bus_release_resource(dev, SYS_RES_IRQ, sc->irq_rid,
1167 			    sc->irq_res);
1168 		iichid_detach(dev);
1169 		error = ENXIO;
1170 		goto done;
1171 #endif
1172 	}
1173 
1174 #ifdef IICHID_SAMPLING
1175 	SYSCTL_ADD_PROC(device_get_sysctl_ctx(sc->dev),
1176 		SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)),
1177 		OID_AUTO, "sampling_rate_slow", CTLTYPE_INT | CTLFLAG_RWTUN,
1178 		sc, 0, iichid_sysctl_sampling_rate_handler, "I",
1179 		"idle sampling rate in num/second");
1180 	SYSCTL_ADD_INT(device_get_sysctl_ctx(sc->dev),
1181 		SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)),
1182 		OID_AUTO, "sampling_rate_fast", CTLFLAG_RWTUN,
1183 		&sc->sampling_rate_fast, 0,
1184 		"active sampling rate in num/second");
1185 	SYSCTL_ADD_INT(device_get_sysctl_ctx(sc->dev),
1186 		SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)),
1187 		OID_AUTO, "sampling_hysteresis", CTLFLAG_RWTUN,
1188 		&sc->sampling_hysteresis, 0,
1189 		"number of missing samples before enabling of slow mode");
1190 	hid_add_dynamic_quirk(&sc->hw, HQ_IICHID_SAMPLING);
1191 #endif /* IICHID_SAMPLING */
1192 
1193 	/*
1194 	 * Windows driver sleeps for 1ms between the SET_POWER and RESET
1195 	 * commands. So we too as some devices may depend on this.
1196 	 */
1197 	pause("iichid", (hz + 999) / 1000);
1198 
1199 	error = iichid_reset(sc);
1200 	if (error) {
1201 		device_printf(dev, "failed to reset hardware: %d\n", error);
1202 		iichid_detach(dev);
1203 		error = ENXIO;
1204 		goto done;
1205 	}
1206 
1207 	/* Wait for RESET response */
1208 #ifdef IICHID_SAMPLING
1209 	if (sc->sampling_rate_slow >= 0) {
1210 		pause("iichid", (hz + 999) / 1000);
1211 		(void)iichid_cmd_read(sc, sc->intr_buf, 0, NULL);
1212 	} else
1213 #endif /* IICHID_SAMPLING */
1214 	{
1215 		mtx_lock(&sc->mtx);
1216 		if (!sc->reset_acked && !cold) {
1217 			error = mtx_sleep(&sc->reset_acked,  &sc->mtx, 0,
1218 			    "iichid_reset", hz * IICHID_RESET_TIMEOUT);
1219 			if (error != 0)
1220 				device_printf(sc->dev,
1221 				    "Reset timeout expired\n");
1222 		}
1223 		mtx_unlock(&sc->mtx);
1224 	}
1225 
1226 	child = device_add_child(dev, "hidbus", DEVICE_UNIT_ANY);
1227 	if (child == NULL) {
1228 		device_printf(sc->dev, "Could not add I2C device\n");
1229 		iichid_detach(dev);
1230 		error = ENOMEM;
1231 		goto done;
1232 	}
1233 
1234 	device_set_ivars(child, &sc->hw);
1235 	bus_attach_children(dev);
1236 	error = 0;
1237 done:
1238 	iicbus_request_bus(device_get_parent(dev), dev, IIC_WAIT);
1239 	if (!sc->open) {
1240 		(void)iichid_set_power(sc, I2C_HID_POWER_OFF);
1241 		sc->power_on = false;
1242 	}
1243 	iicbus_release_bus(device_get_parent(dev), dev);
1244 	return (error);
1245 }
1246 
1247 static int
iichid_detach(device_t dev)1248 iichid_detach(device_t dev)
1249 {
1250 	struct iichid_softc *sc;
1251 	int error;
1252 
1253 	sc = device_get_softc(dev);
1254 	error = bus_generic_detach(dev);
1255 	if (error)
1256 		return (error);
1257 	iichid_teardown_interrupt(sc);
1258 	if (sc->irq_res != NULL)
1259 		bus_release_resource(dev, SYS_RES_IRQ, sc->irq_rid,
1260 		    sc->irq_res);
1261 #ifdef IICHID_SAMPLING
1262 	if (sc->taskqueue != NULL)
1263 		taskqueue_free(sc->taskqueue);
1264 	sc->taskqueue = NULL;
1265 	free(sc->dup_buf, M_DEVBUF);
1266 #endif
1267 	free(sc->intr_buf, M_DEVBUF);
1268 	mtx_destroy(&sc->mtx);
1269 	return (0);
1270 }
1271 
1272 static void
iichid_suspend_task(void * context,int pending)1273 iichid_suspend_task(void *context, int pending)
1274 {
1275 	struct iichid_softc *sc = context;
1276 
1277 	iichid_teardown_interrupt(sc);
1278 }
1279 
1280 static int
iichid_suspend(device_t dev)1281 iichid_suspend(device_t dev)
1282 {
1283 	struct iichid_softc *sc;
1284 	int error;
1285 
1286 	sc = device_get_softc(dev);
1287 	(void)bus_generic_suspend(dev);
1288 	/*
1289 	 * 8.2 - The HOST is going into a deep power optimized state and wishes
1290 	 * to put all the devices into a low power state also.  The HOST
1291 	 * is recommended to issue a HIPO command to the DEVICE to force
1292 	 * the DEVICE in to a lower power state.
1293 	 */
1294 	DPRINTF(sc, "Suspend called, setting device to power_state 1\n");
1295 	error = iichid_set_power_state(sc, IICHID_PS_NULL, IICHID_PS_OFF);
1296 	if (error != 0)
1297 		DPRINTF(sc, "Could not set power_state, error: %d\n", error);
1298 	else
1299 		DPRINTF(sc, "Successfully set power_state\n");
1300 
1301 #ifdef IICHID_SAMPLING
1302 	if (sc->sampling_rate_slow < 0)
1303 #endif
1304 	{
1305 		/*
1306 		 * bus_teardown_intr can not be executed right here as it wants
1307 		 * to run on certain CPU to interacts with LAPIC while suspend
1308 		 * thread is bound to CPU0. So run it from taskqueue context.
1309 		 */
1310 #ifdef IICHID_SAMPLING
1311 #define	suspend_thread	sc->taskqueue
1312 #else
1313 #define	suspend_thread	taskqueue_thread
1314 #endif
1315 		taskqueue_enqueue(suspend_thread, &sc->suspend_task);
1316 		taskqueue_drain(suspend_thread, &sc->suspend_task);
1317 	}
1318 
1319 	return (0);
1320 }
1321 
1322 static int
iichid_resume(device_t dev)1323 iichid_resume(device_t dev)
1324 {
1325 	struct iichid_softc *sc;
1326 	int error;
1327 
1328 	sc = device_get_softc(dev);
1329 #ifdef IICHID_SAMPLING
1330 	if (sc->sampling_rate_slow < 0)
1331 #endif
1332 		iichid_setup_interrupt(sc);
1333 
1334 	DPRINTF(sc, "Resume called, setting device to power_state 0\n");
1335 	error = iichid_set_power_state(sc, IICHID_PS_NULL, IICHID_PS_ON);
1336 	if (error != 0)
1337 		DPRINTF(sc, "Could not set power_state, error: %d\n", error);
1338 	else
1339 		DPRINTF(sc, "Successfully set power_state\n");
1340 	(void)bus_generic_resume(dev);
1341 
1342 	return (0);
1343 }
1344 
1345 static device_method_t iichid_methods[] = {
1346 	DEVMETHOD(device_probe,		iichid_probe),
1347 	DEVMETHOD(device_attach,	iichid_attach),
1348 	DEVMETHOD(device_detach,	iichid_detach),
1349 	DEVMETHOD(device_suspend,	iichid_suspend),
1350 	DEVMETHOD(device_resume,	iichid_resume),
1351 
1352 	DEVMETHOD(hid_intr_setup,	iichid_intr_setup),
1353 	DEVMETHOD(hid_intr_unsetup,	iichid_intr_unsetup),
1354 	DEVMETHOD(hid_intr_start,	iichid_intr_start),
1355 	DEVMETHOD(hid_intr_stop,	iichid_intr_stop),
1356 	DEVMETHOD(hid_intr_poll,	iichid_intr_poll),
1357 
1358 	/* HID interface */
1359 	DEVMETHOD(hid_get_rdesc,	iichid_get_rdesc),
1360 	DEVMETHOD(hid_read,		iichid_read),
1361 	DEVMETHOD(hid_write,		iichid_write),
1362 	DEVMETHOD(hid_get_report,	iichid_get_report),
1363 	DEVMETHOD(hid_set_report,	iichid_set_report),
1364 	DEVMETHOD(hid_set_idle,		iichid_set_idle),
1365 	DEVMETHOD(hid_set_protocol,	iichid_set_protocol),
1366 	DEVMETHOD(hid_ioctl,		iichid_ioctl),
1367 
1368 	DEVMETHOD_END
1369 };
1370 
1371 static driver_t iichid_driver = {
1372 	.name = "iichid",
1373 	.methods = iichid_methods,
1374 	.size = sizeof(struct iichid_softc),
1375 };
1376 
1377 DRIVER_MODULE(iichid, iicbus, iichid_driver, NULL, NULL);
1378 MODULE_DEPEND(iichid, iicbus, IICBUS_MINVER, IICBUS_PREFVER, IICBUS_MAXVER);
1379 MODULE_DEPEND(iichid, acpi, 1, 1, 1);
1380 MODULE_DEPEND(iichid, hid, 1, 1, 1);
1381 MODULE_DEPEND(iichid, hidbus, 1, 1, 1);
1382 MODULE_VERSION(iichid, 1);
1383 IICBUS_ACPI_PNP_INFO(iichid_ids);
1384