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