xref: /freebsd/sys/dev/hid/hmt.c (revision bc5304a006238115291e7568583632889dffbab9)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2014-2020 Vladimir Kondratyev <wulf@FreeBSD.org>
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27 
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30 
31 /*
32  * MS Windows 7/8/10 compatible HID Multi-touch Device driver.
33  * https://msdn.microsoft.com/en-us/library/windows/hardware/jj151569(v=vs.85).aspx
34  * http://download.microsoft.com/download/7/d/d/7dd44bb7-2a7a-4505-ac1c-7227d3d96d5b/hid-over-i2c-protocol-spec-v1-0.docx
35  * https://www.kernel.org/doc/Documentation/input/multi-touch-protocol.txt
36  */
37 
38 #include "opt_hid.h"
39 
40 #include <sys/param.h>
41 #include <sys/bus.h>
42 #include <sys/kernel.h>
43 #include <sys/lock.h>
44 #include <sys/malloc.h>
45 #include <sys/module.h>
46 #include <sys/mutex.h>
47 #include <sys/sysctl.h>
48 #include <sys/systm.h>
49 
50 #include <dev/evdev/evdev.h>
51 #include <dev/evdev/input.h>
52 
53 #define	HID_DEBUG_VAR	hmt_debug
54 #include <dev/hid/hid.h>
55 #include <dev/hid/hidbus.h>
56 #include <dev/hid/hidquirk.h>
57 
58 #include <dev/hid/hconf.h>
59 
60 static SYSCTL_NODE(_hw_hid, OID_AUTO, hmt, CTLFLAG_RW, 0,
61     "MSWindows 7/8/10 compatible HID Multi-touch Device");
62 #ifdef HID_DEBUG
63 static int hmt_debug = 0;
64 SYSCTL_INT(_hw_hid_hmt, OID_AUTO, debug, CTLFLAG_RWTUN,
65     &hmt_debug, 1, "Debug level");
66 #endif
67 static bool hmt_timestamps = 0;
68 SYSCTL_BOOL(_hw_hid_hmt, OID_AUTO, timestamps, CTLFLAG_RDTUN,
69     &hmt_timestamps, 1, "Enable hardware timestamp reporting");
70 
71 #define	HMT_BTN_MAX	8	/* Number of buttons supported */
72 
73 enum hmt_type {
74 	HMT_TYPE_UNKNOWN = 0,	/* HID report descriptor is not probed */
75 	HMT_TYPE_UNSUPPORTED,	/* Repdescr does not belong to MT device */
76 	HMT_TYPE_TOUCHPAD,
77 	HMT_TYPE_TOUCHSCREEN,
78 };
79 
80 enum {
81 	HMT_TIP_SWITCH,
82 #define	HMT_SLOT	HMT_TIP_SWITCH
83 	HMT_WIDTH,
84 #define	HMT_MAJOR	HMT_WIDTH
85 	HMT_HEIGHT,
86 #define HMT_MINOR	HMT_HEIGHT
87 	HMT_ORIENTATION,
88 	HMT_X,
89 	HMT_Y,
90 	HMT_CONTACTID,
91 	HMT_PRESSURE,
92 	HMT_IN_RANGE,
93 	HMT_CONFIDENCE,
94 	HMT_TOOL_X,
95 	HMT_TOOL_Y,
96 	HMT_N_USAGES,
97 };
98 
99 #define	HMT_NO_CODE	(ABS_MAX + 10)
100 #define	HMT_NO_USAGE	-1
101 
102 struct hmt_hid_map_item {
103 	char		name[5];
104 	int32_t 	usage;		/* HID usage */
105 	uint32_t	code;		/* Evdev event code */
106 	bool		required;	/* Required for MT Digitizers */
107 };
108 
109 static const struct hmt_hid_map_item hmt_hid_map[HMT_N_USAGES] = {
110 	[HMT_TIP_SWITCH] = {	/* HMT_SLOT */
111 		.name = "TIP",
112 		.usage = HID_USAGE2(HUP_DIGITIZERS, HUD_TIP_SWITCH),
113 		.code = ABS_MT_SLOT,
114 		.required = true,
115 	},
116 	[HMT_WIDTH] = {		/* HMT_MAJOR */
117 		.name = "WDTH",
118 		.usage = HID_USAGE2(HUP_DIGITIZERS, HUD_WIDTH),
119 		.code = ABS_MT_TOUCH_MAJOR,
120 		.required = false,
121 	},
122 	[HMT_HEIGHT] = {	/* HMT_MINOR */
123 		.name = "HGHT",
124 		.usage = HID_USAGE2(HUP_DIGITIZERS, HUD_HEIGHT),
125 		.code = ABS_MT_TOUCH_MINOR,
126 		.required = false,
127 	},
128 	[HMT_ORIENTATION] = {
129 		.name = "ORIE",
130 		.usage = HMT_NO_USAGE,
131 		.code = ABS_MT_ORIENTATION,
132 		.required = false,
133 	},
134 	[HMT_X] = {
135 		.name = "X",
136 		.usage = HID_USAGE2(HUP_GENERIC_DESKTOP, HUG_X),
137 		.code = ABS_MT_POSITION_X,
138 		.required = true,
139 	},
140 	[HMT_Y] = {
141 		.name = "Y",
142 		.usage = HID_USAGE2(HUP_GENERIC_DESKTOP, HUG_Y),
143 		.code = ABS_MT_POSITION_Y,
144 		.required = true,
145 	},
146 	[HMT_CONTACTID] = {
147 		.name = "C_ID",
148 		.usage = HID_USAGE2(HUP_DIGITIZERS, HUD_CONTACTID),
149 		.code = ABS_MT_TRACKING_ID,
150 		.required = true,
151 	},
152 	[HMT_PRESSURE] = {
153 		.name = "PRES",
154 		.usage = HID_USAGE2(HUP_DIGITIZERS, HUD_TIP_PRESSURE),
155 		.code = ABS_MT_PRESSURE,
156 		.required = false,
157 	},
158 	[HMT_IN_RANGE] = {
159 		.name = "RANG",
160 		.usage = HID_USAGE2(HUP_DIGITIZERS, HUD_IN_RANGE),
161 		.code = ABS_MT_DISTANCE,
162 		.required = false,
163 	},
164 	[HMT_CONFIDENCE] = {
165 		.name = "CONF",
166 		.usage = HID_USAGE2(HUP_DIGITIZERS, HUD_CONFIDENCE),
167 		.code = HMT_NO_CODE,
168 		.required = false,
169 	},
170 	[HMT_TOOL_X] = {	/* Shares HID usage with HMT_X */
171 		.name = "TL_X",
172 		.usage = HID_USAGE2(HUP_GENERIC_DESKTOP, HUG_X),
173 		.code = ABS_MT_TOOL_X,
174 		.required = false,
175 	},
176 	[HMT_TOOL_Y] = {	/* Shares HID usage with HMT_Y */
177 		.name = "TL_Y",
178 		.usage = HID_USAGE2(HUP_GENERIC_DESKTOP, HUG_Y),
179 		.code = ABS_MT_TOOL_Y,
180 		.required = false,
181 	},
182 };
183 
184 struct hmt_softc {
185 	device_t		dev;
186 	enum hmt_type		type;
187 
188 	int32_t			cont_count_max;
189 	struct hid_absinfo	ai[HMT_N_USAGES];
190 	struct hid_location	locs[MAX_MT_SLOTS][HMT_N_USAGES];
191 	struct hid_location	cont_count_loc;
192 	struct hid_location	btn_loc[HMT_BTN_MAX];
193 	struct hid_location	int_btn_loc;
194 	struct hid_location	scan_time_loc;
195 	int32_t			scan_time_max;
196 	int32_t			scan_time;
197 	int32_t			timestamp;
198 	bool			touch;
199 	bool			prev_touch;
200 
201 	struct evdev_dev	*evdev;
202 
203 	uint32_t		slot_data[HMT_N_USAGES];
204 	uint8_t			caps[howmany(HMT_N_USAGES, 8)];
205 	uint8_t			buttons[howmany(HMT_BTN_MAX, 8)];
206 	uint32_t		nconts_per_report;
207 	uint32_t		nconts_todo;
208 	uint8_t			report_id;
209 	uint32_t		max_button;
210 	bool			has_int_button;
211 	bool			is_clickpad;
212 	bool			do_timestamps;
213 #ifdef IICHID_SAMPLING
214 	bool			iichid_sampling;
215 #endif
216 
217 	struct hid_location	cont_max_loc;
218 	uint32_t		cont_max_rlen;
219 	uint8_t			cont_max_rid;
220 	struct hid_location	btn_type_loc;
221 	uint32_t		btn_type_rlen;
222 	uint8_t			btn_type_rid;
223 	uint32_t		thqa_cert_rlen;
224 	uint8_t			thqa_cert_rid;
225 };
226 
227 #define	HMT_FOREACH_USAGE(caps, usage)			\
228 	for ((usage) = 0; (usage) < HMT_N_USAGES; ++(usage))	\
229 		if (isset((caps), (usage)))
230 
231 static enum hmt_type hmt_hid_parse(struct hmt_softc *, const void *,
232     hid_size_t, uint32_t, uint8_t);
233 static int hmt_set_input_mode(struct hmt_softc *, enum hconf_input_mode);
234 
235 static hid_intr_t	hmt_intr;
236 
237 static device_probe_t	hmt_probe;
238 static device_attach_t	hmt_attach;
239 static device_detach_t	hmt_detach;
240 
241 static evdev_open_t	hmt_ev_open;
242 static evdev_close_t	hmt_ev_close;
243 
244 static const struct evdev_methods hmt_evdev_methods = {
245 	.ev_open = &hmt_ev_open,
246 	.ev_close = &hmt_ev_close,
247 };
248 
249 static const struct hid_device_id hmt_devs[] = {
250 	{ HID_TLC(HUP_DIGITIZERS, HUD_TOUCHSCREEN) },
251 	{ HID_TLC(HUP_DIGITIZERS, HUD_TOUCHPAD) },
252 };
253 
254 static int
255 hmt_ev_close(struct evdev_dev *evdev)
256 {
257 	return (hidbus_intr_stop(evdev_get_softc(evdev)));
258 }
259 
260 static int
261 hmt_ev_open(struct evdev_dev *evdev)
262 {
263 	return (hidbus_intr_start(evdev_get_softc(evdev)));
264 }
265 
266 static int
267 hmt_probe(device_t dev)
268 {
269 	struct hmt_softc *sc = device_get_softc(dev);
270 	void *d_ptr;
271 	hid_size_t d_len;
272 	int err;
273 
274 	err = HIDBUS_LOOKUP_DRIVER_INFO(dev, hmt_devs);
275 	if (err != 0)
276 		return (err);
277 
278 	err = hid_get_report_descr(dev, &d_ptr, &d_len);
279 	if (err != 0) {
280 		device_printf(dev, "could not retrieve report descriptor from "
281 		     "device: %d\n", err);
282 		return (ENXIO);
283 	}
284 
285 	/* Check if report descriptor belongs to a HID multitouch device */
286 	if (sc->type == HMT_TYPE_UNKNOWN)
287 		sc->type = hmt_hid_parse(sc, d_ptr, d_len,
288 		    hidbus_get_usage(dev), hidbus_get_index(dev));
289 	if (sc->type == HMT_TYPE_UNSUPPORTED)
290 		return (ENXIO);
291 
292 	hidbus_set_desc(dev,
293 	    sc->type == HMT_TYPE_TOUCHPAD ? "TouchPad" : "TouchScreen");
294 
295 	return (BUS_PROBE_DEFAULT);
296 }
297 
298 static int
299 hmt_attach(device_t dev)
300 {
301 	struct hmt_softc *sc = device_get_softc(dev);
302 	const struct hid_device_info *hw = hid_get_device_info(dev);
303 	void *d_ptr;
304 	uint8_t *fbuf = NULL;
305 	hid_size_t d_len, fsize;
306 	uint32_t cont_count_max;
307 	int nbuttons, btn;
308 	size_t i;
309 	int err;
310 
311 	err = hid_get_report_descr(dev, &d_ptr, &d_len);
312 	if (err != 0) {
313 		device_printf(dev, "could not retrieve report descriptor from "
314 		    "device: %d\n", err);
315 		return (ENXIO);
316 	}
317 
318 	sc->dev = dev;
319 
320 	fsize = hid_report_size_max(d_ptr, d_len, hid_feature, NULL);
321 	if (fsize != 0)
322 		fbuf = malloc(fsize, M_TEMP, M_WAITOK | M_ZERO);
323 
324 	/* Fetch and parse "Contact count maximum" feature report */
325 	if (sc->cont_max_rlen > 1) {
326 		err = hid_get_report(dev, fbuf, sc->cont_max_rlen, NULL,
327 		    HID_FEATURE_REPORT, sc->cont_max_rid);
328 		if (err == 0) {
329 			cont_count_max = hid_get_udata(fbuf + 1,
330 			    sc->cont_max_rlen - 1, &sc->cont_max_loc);
331 			/*
332 			 * Feature report is a primary source of
333 			 * 'Contact Count Maximum'
334 			 */
335 			if (cont_count_max > 0)
336 				sc->cont_count_max = cont_count_max;
337 		} else
338 			DPRINTF("hid_get_report error=%d\n", err);
339 	} else
340 		DPRINTF("Feature report %hhu size invalid: %u\n",
341 		    sc->cont_max_rid, sc->cont_max_rlen);
342 
343 	/* Fetch and parse "Button type" feature report */
344 	if (sc->btn_type_rlen > 1 && sc->btn_type_rid != sc->cont_max_rid) {
345 		bzero(fbuf, fsize);
346 		err = hid_get_report(dev, fbuf, sc->btn_type_rlen, NULL,
347 		    HID_FEATURE_REPORT, sc->btn_type_rid);
348 	}
349 	if (sc->btn_type_rlen > 1) {
350 		if (err == 0)
351 			sc->is_clickpad = hid_get_udata(fbuf + 1,
352 			    sc->btn_type_rlen - 1, &sc->btn_type_loc) == 0;
353 		else
354 			DPRINTF("hid_get_report error=%d\n", err);
355 	}
356 
357 	/* Fetch THQA certificate to enable some devices like WaveShare */
358 	if (sc->thqa_cert_rlen > 1 && sc->thqa_cert_rid != sc->cont_max_rid)
359 		(void)hid_get_report(dev, fbuf, sc->thqa_cert_rlen, NULL,
360 		    HID_FEATURE_REPORT, sc->thqa_cert_rid);
361 
362 	free(fbuf, M_TEMP);
363 
364 	/* Switch touchpad in to absolute multitouch mode */
365 	if (sc->type == HMT_TYPE_TOUCHPAD) {
366 		err = hmt_set_input_mode(sc, HCONF_INPUT_MODE_MT_TOUCHPAD);
367 		if (err != 0)
368 			DPRINTF("Failed to set input mode: %d\n", err);
369 	}
370 
371 	/* Cap contact count maximum to MAX_MT_SLOTS */
372 	if (sc->cont_count_max > MAX_MT_SLOTS) {
373 		DPRINTF("Hardware reported %d contacts while only %d is "
374 		    "supported\n", sc->cont_count_max, MAX_MT_SLOTS);
375 		sc->cont_count_max = MAX_MT_SLOTS;
376 	}
377 
378 	/* Set number of MT protocol type B slots */
379 	sc->ai[HMT_SLOT] = (struct hid_absinfo) {
380 		.min = 0,
381 		.max = sc->cont_count_max - 1,
382 		.res = 0,
383 	};
384 
385 	if (hid_test_quirk(hw, HQ_MT_TIMESTAMP) || hmt_timestamps)
386 		sc->do_timestamps = true;
387 #ifdef IICHID_SAMPLING
388 	if (hid_test_quirk(hw, HQ_IICHID_SAMPLING))
389 		sc->iichid_sampling = true;
390 #endif
391 
392 	hidbus_set_intr(dev, hmt_intr, sc);
393 
394 	sc->evdev = evdev_alloc();
395 	evdev_set_name(sc->evdev, device_get_desc(dev));
396 	evdev_set_phys(sc->evdev, device_get_nameunit(dev));
397 	evdev_set_id(sc->evdev, hw->idBus, hw->idVendor, hw->idProduct,
398 	    hw->idVersion);
399 	evdev_set_serial(sc->evdev, hw->serial);
400 	evdev_set_methods(sc->evdev, dev, &hmt_evdev_methods);
401 	evdev_set_flag(sc->evdev, EVDEV_FLAG_MT_STCOMPAT);
402 	evdev_set_flag(sc->evdev, EVDEV_FLAG_EXT_EPOCH); /* hidbus child */
403 	switch (sc->type) {
404 	case HMT_TYPE_TOUCHSCREEN:
405 		evdev_support_prop(sc->evdev, INPUT_PROP_DIRECT);
406 		break;
407 	case HMT_TYPE_TOUCHPAD:
408 		evdev_support_prop(sc->evdev, INPUT_PROP_POINTER);
409 		if (sc->is_clickpad)
410 			evdev_support_prop(sc->evdev, INPUT_PROP_BUTTONPAD);
411 		break;
412 	default:
413 		KASSERT(0, ("hmt_attach: unsupported touch device type"));
414 	}
415 	evdev_support_event(sc->evdev, EV_SYN);
416 	evdev_support_event(sc->evdev, EV_ABS);
417 	if (sc->do_timestamps) {
418 		evdev_support_event(sc->evdev, EV_MSC);
419 		evdev_support_msc(sc->evdev, MSC_TIMESTAMP);
420 	}
421 #ifdef IICHID_SAMPLING
422 	if (sc->iichid_sampling)
423 		evdev_set_flag(sc->evdev, EVDEV_FLAG_MT_AUTOREL);
424 #endif
425 	nbuttons = 0;
426 	if (sc->max_button != 0 || sc->has_int_button) {
427 		evdev_support_event(sc->evdev, EV_KEY);
428 		if (sc->has_int_button)
429 			evdev_support_key(sc->evdev, BTN_LEFT);
430 		for (btn = 0; btn < sc->max_button; ++btn) {
431 			if (isset(sc->buttons, btn)) {
432 				evdev_support_key(sc->evdev, BTN_MOUSE + btn);
433 				nbuttons++;
434 			}
435 		}
436 	}
437 	HMT_FOREACH_USAGE(sc->caps, i) {
438 		if (hmt_hid_map[i].code != HMT_NO_CODE)
439 			evdev_support_abs(sc->evdev, hmt_hid_map[i].code,
440 			    sc->ai[i].min, sc->ai[i].max, 0, 0, sc->ai[i].res);
441 	}
442 
443 	err = evdev_register(sc->evdev);
444 	if (err) {
445 		hmt_detach(dev);
446 		return (ENXIO);
447 	}
448 
449 	/* Announce information about the touch device */
450 	device_printf(sc->dev, "Multitouch %s with %d external button%s%s\n",
451 	    sc->type == HMT_TYPE_TOUCHSCREEN ? "touchscreen" : "touchpad",
452 	    nbuttons, nbuttons != 1 ? "s" : "",
453 	    sc->is_clickpad ? ", click-pad" : "");
454 	device_printf(sc->dev,
455 	    "%d contacts with [%s%s%s%s%s] properties. Report range [%d:%d] - [%d:%d]\n",
456 	    (int)sc->cont_count_max,
457 	    isset(sc->caps, HMT_IN_RANGE) ? "R" : "",
458 	    isset(sc->caps, HMT_CONFIDENCE) ? "C" : "",
459 	    isset(sc->caps, HMT_WIDTH) ? "W" : "",
460 	    isset(sc->caps, HMT_HEIGHT) ? "H" : "",
461 	    isset(sc->caps, HMT_PRESSURE) ? "P" : "",
462 	    (int)sc->ai[HMT_X].min, (int)sc->ai[HMT_Y].min,
463 	    (int)sc->ai[HMT_X].max, (int)sc->ai[HMT_Y].max);
464 
465 	return (0);
466 }
467 
468 static int
469 hmt_detach(device_t dev)
470 {
471 	struct hmt_softc *sc = device_get_softc(dev);
472 
473 	evdev_free(sc->evdev);
474 
475 	return (0);
476 }
477 
478 static void
479 hmt_intr(void *context, void *buf, hid_size_t len)
480 {
481 	struct hmt_softc *sc = context;
482 	size_t usage;
483 	uint32_t *slot_data = sc->slot_data;
484 	uint32_t cont, btn;
485 	uint32_t cont_count;
486 	uint32_t width;
487 	uint32_t height;
488 	uint32_t int_btn = 0;
489 	uint32_t left_btn = 0;
490 	int32_t slot;
491 	uint32_t scan_time;
492 	int32_t delta;
493 	uint8_t id;
494 
495 #ifdef IICHID_SAMPLING
496 	/*
497 	 * Special packet of zero length is generated by iichid driver running
498 	 * in polling mode at the start of inactivity period to workaround
499 	 * "stuck touch" problem caused by miss of finger release events.
500 	 * This snippet is to be removed after GPIO interrupt support is added.
501 	 */
502 	if (sc->iichid_sampling && len == 0) {
503 		sc->prev_touch = false;
504 		sc->timestamp = 0;
505 		for (slot = 0; slot <= sc->ai[HMT_SLOT].max; slot++) {
506 			evdev_push_abs(sc->evdev, ABS_MT_SLOT, slot);
507 			evdev_push_abs(sc->evdev, ABS_MT_TRACKING_ID, -1);
508 		}
509 		evdev_sync(sc->evdev);
510 		return;
511 	}
512 #endif
513 
514 	/* Ignore irrelevant reports */
515 	id = sc->report_id != 0 ? *(uint8_t *)buf : 0;
516 	if (sc->report_id != id) {
517 		DPRINTF("Skip report with unexpected ID: %hhu\n", id);
518 		return;
519 	}
520 
521 	/* Strip leading "report ID" byte */
522 	if (sc->report_id != 0) {
523 		len--;
524 		buf = (uint8_t *)buf + 1;
525 	}
526 
527 	/*
528 	 * "In Parallel mode, devices report all contact information in a
529 	 * single packet. Each physical contact is represented by a logical
530 	 * collection that is embedded in the top-level collection."
531 	 *
532 	 * Since additional contacts that were not present will still be in the
533 	 * report with contactid=0 but contactids are zero-based, find
534 	 * contactcount first.
535 	 */
536 	cont_count = hid_get_udata(buf, len, &sc->cont_count_loc);
537 	/*
538 	 * "In Hybrid mode, the number of contacts that can be reported in one
539 	 * report is less than the maximum number of contacts that the device
540 	 * supports. For example, a device that supports a maximum of
541 	 * 4 concurrent physical contacts, can set up its top-level collection
542 	 * to deliver a maximum of two contacts in one report. If four contact
543 	 * points are present, the device can break these up into two serial
544 	 * reports that deliver two contacts each.
545 	 *
546 	 * "When a device delivers data in this manner, the Contact Count usage
547 	 * value in the first report should reflect the total number of
548 	 * contacts that are being delivered in the hybrid reports. The other
549 	 * serial reports should have a contact count of zero (0)."
550 	 */
551 	if (cont_count != 0)
552 		sc->nconts_todo = cont_count;
553 
554 #ifdef HID_DEBUG
555 	DPRINTFN(6, "cont_count:%2u", (unsigned)cont_count);
556 	if (hmt_debug >= 6) {
557 		HMT_FOREACH_USAGE(sc->caps, usage) {
558 			if (hmt_hid_map[usage].usage != HMT_NO_USAGE)
559 				printf(" %-4s", hmt_hid_map[usage].name);
560 		}
561 		printf("\n");
562 	}
563 #endif
564 
565 	/* Find the number of contacts reported in current report */
566 	cont_count = MIN(sc->nconts_todo, sc->nconts_per_report);
567 
568 	/* Use protocol Type B for reporting events */
569 	for (cont = 0; cont < cont_count; cont++) {
570 		bzero(slot_data, sizeof(sc->slot_data));
571 		HMT_FOREACH_USAGE(sc->caps, usage) {
572 			if (sc->locs[cont][usage].size > 0)
573 				slot_data[usage] = hid_get_udata(
574 				    buf, len, &sc->locs[cont][usage]);
575 		}
576 
577 		slot = evdev_get_mt_slot_by_tracking_id(sc->evdev,
578 		    slot_data[HMT_CONTACTID]);
579 
580 #ifdef HID_DEBUG
581 		DPRINTFN(6, "cont%01x: data = ", cont);
582 		if (hmt_debug >= 6) {
583 			HMT_FOREACH_USAGE(sc->caps, usage) {
584 				if (hmt_hid_map[usage].usage != HMT_NO_USAGE)
585 					printf("%04x ", slot_data[usage]);
586 			}
587 			printf("slot = %d\n", (int)slot);
588 		}
589 #endif
590 
591 		if (slot == -1) {
592 			DPRINTF("Slot overflow for contact_id %u\n",
593 			    (unsigned)slot_data[HMT_CONTACTID]);
594 			continue;
595 		}
596 
597 		if (slot_data[HMT_TIP_SWITCH] != 0 &&
598 		    !(isset(sc->caps, HMT_CONFIDENCE) &&
599 		      slot_data[HMT_CONFIDENCE] == 0)) {
600 			/* This finger is in proximity of the sensor */
601 			sc->touch = true;
602 			slot_data[HMT_SLOT] = slot;
603 			slot_data[HMT_IN_RANGE] = !slot_data[HMT_IN_RANGE];
604 			/* Divided by two to match visual scale of touch */
605 			width = slot_data[HMT_WIDTH] >> 1;
606 			height = slot_data[HMT_HEIGHT] >> 1;
607 			slot_data[HMT_ORIENTATION] = width > height;
608 			slot_data[HMT_MAJOR] = MAX(width, height);
609 			slot_data[HMT_MINOR] = MIN(width, height);
610 
611 			HMT_FOREACH_USAGE(sc->caps, usage)
612 				if (hmt_hid_map[usage].code != HMT_NO_CODE)
613 					evdev_push_abs(sc->evdev,
614 					    hmt_hid_map[usage].code,
615 					    slot_data[usage]);
616 		} else {
617 			evdev_push_abs(sc->evdev, ABS_MT_SLOT, slot);
618 			evdev_push_abs(sc->evdev, ABS_MT_TRACKING_ID, -1);
619 		}
620 	}
621 
622 	sc->nconts_todo -= cont_count;
623 	if (sc->do_timestamps && sc->nconts_todo == 0) {
624 		/* HUD_SCAN_TIME is measured in 100us, convert to us. */
625 		scan_time = hid_get_udata(buf, len, &sc->scan_time_loc);
626 		if (sc->prev_touch) {
627 			delta = scan_time - sc->scan_time;
628 			if (delta < 0)
629 				delta += sc->scan_time_max;
630 		} else
631 			delta = 0;
632 		sc->scan_time = scan_time;
633 		sc->timestamp += delta * 100;
634 		evdev_push_msc(sc->evdev, MSC_TIMESTAMP, sc->timestamp);
635 		sc->prev_touch = sc->touch;
636 		sc->touch = false;
637 		if (!sc->prev_touch)
638 			sc->timestamp = 0;
639 	}
640 	if (sc->nconts_todo == 0) {
641 		/* Report both the click and external left btns as BTN_LEFT */
642 		if (sc->has_int_button)
643 			int_btn = hid_get_data(buf, len, &sc->int_btn_loc);
644 		if (isset(sc->buttons, 0))
645 			left_btn = hid_get_data(buf, len, &sc->btn_loc[0]);
646 		if (sc->has_int_button || isset(sc->buttons, 0))
647 			evdev_push_key(sc->evdev, BTN_LEFT,
648 			    (int_btn != 0) | (left_btn != 0));
649 		for (btn = 1; btn < sc->max_button; ++btn) {
650 			if (isset(sc->buttons, btn))
651 				evdev_push_key(sc->evdev, BTN_MOUSE + btn,
652 				    hid_get_data(buf,
653 						 len,
654 						 &sc->btn_loc[btn]) != 0);
655 		}
656 		evdev_sync(sc->evdev);
657 	}
658 }
659 
660 static enum hmt_type
661 hmt_hid_parse(struct hmt_softc *sc, const void *d_ptr, hid_size_t d_len,
662     uint32_t tlc_usage, uint8_t tlc_index)
663 {
664 	struct hid_absinfo ai;
665 	struct hid_item hi;
666 	struct hid_data *hd;
667 	uint32_t flags;
668 	size_t i;
669 	size_t cont = 0;
670 	enum hmt_type type;
671 	uint32_t left_btn, btn;
672 	int32_t cont_count_max = 0;
673 	uint8_t report_id = 0;
674 	bool finger_coll = false;
675 	bool cont_count_found = false;
676 	bool scan_time_found = false;
677 	bool has_int_button = false;
678 
679 #define HMT_HI_ABSOLUTE(hi)	((hi).nusages != 0 &&	\
680 	((hi).flags & (HIO_VARIABLE | HIO_RELATIVE)) == HIO_VARIABLE)
681 #define	HUMS_THQA_CERT	0xC5
682 
683 	/*
684 	 * Get left button usage taking in account MS Precision Touchpad specs.
685 	 * For Windows PTP report descriptor assigns buttons in following way:
686 	 * Button 1 - Indicates Button State for touchpad button integrated
687 	 *            with digitizer.
688 	 * Button 2 - Indicates Button State for external button for primary
689 	 *            (default left) clicking.
690 	 * Button 3 - Indicates Button State for external button for secondary
691 	 *            (default right) clicking.
692 	 * If a device only supports external buttons, it must still use
693 	 * Button 2 and Button 3 to reference the external buttons.
694 	 */
695 	switch (tlc_usage) {
696 	case HID_USAGE2(HUP_DIGITIZERS, HUD_TOUCHSCREEN):
697 		type = HMT_TYPE_TOUCHSCREEN;
698 		left_btn = 1;
699 		break;
700 	case HID_USAGE2(HUP_DIGITIZERS, HUD_TOUCHPAD):
701 		type = HMT_TYPE_TOUCHPAD;
702 		left_btn = 2;
703 		break;
704 	default:
705 		return (HMT_TYPE_UNSUPPORTED);
706 	}
707 
708 	/* Parse features for mandatory maximum contact count usage */
709 	if (!hidbus_locate(d_ptr, d_len,
710 	    HID_USAGE2(HUP_DIGITIZERS, HUD_CONTACT_MAX), hid_feature,
711 	    tlc_index, 0, &sc->cont_max_loc, &flags, &sc->cont_max_rid, &ai) ||
712 	    (flags & (HIO_VARIABLE | HIO_RELATIVE)) != HIO_VARIABLE)
713 		return (HMT_TYPE_UNSUPPORTED);
714 
715 	cont_count_max = ai.max;
716 
717 	/* Parse features for button type usage */
718 	if (hidbus_locate(d_ptr, d_len,
719 	    HID_USAGE2(HUP_DIGITIZERS, HUD_BUTTON_TYPE), hid_feature,
720 	    tlc_index, 0, &sc->btn_type_loc, &flags, &sc->btn_type_rid, NULL)
721 	    && (flags & (HIO_VARIABLE | HIO_RELATIVE)) != HIO_VARIABLE)
722 		sc->btn_type_rid = 0;
723 
724 	/* Parse features for THQA certificate report ID */
725 	hidbus_locate(d_ptr, d_len, HID_USAGE2(HUP_MICROSOFT, HUMS_THQA_CERT),
726 	    hid_feature, tlc_index, 0, NULL, NULL, &sc->thqa_cert_rid, NULL);
727 
728 	/* Parse input for other parameters */
729 	hd = hid_start_parse(d_ptr, d_len, 1 << hid_input);
730 	HIDBUS_FOREACH_ITEM(hd, &hi, tlc_index) {
731 		switch (hi.kind) {
732 		case hid_collection:
733 			if (hi.collevel == 2 &&
734 			    hi.usage == HID_USAGE2(HUP_DIGITIZERS, HUD_FINGER))
735 				finger_coll = true;
736 			break;
737 		case hid_endcollection:
738 			if (hi.collevel == 1 && finger_coll) {
739 				finger_coll = false;
740 				cont++;
741 			}
742 			break;
743 		case hid_input:
744 			/*
745 			 * Ensure that all usages belong to the same report
746 			 */
747 			if (HMT_HI_ABSOLUTE(hi) &&
748 			    (report_id == 0 || report_id == hi.report_ID))
749 				report_id = hi.report_ID;
750 			else
751 				break;
752 
753 			if (hi.collevel == 1 && left_btn == 2 &&
754 			    hi.usage == HID_USAGE2(HUP_BUTTON, 1)) {
755 				has_int_button = true;
756 				sc->int_btn_loc = hi.loc;
757 				break;
758 			}
759 			if (hi.collevel == 1 &&
760 			    hi.usage >= HID_USAGE2(HUP_BUTTON, left_btn) &&
761 			    hi.usage <= HID_USAGE2(HUP_BUTTON, HMT_BTN_MAX)) {
762 				btn = (hi.usage & 0xFFFF) - left_btn;
763 				setbit(sc->buttons, btn);
764 				sc->btn_loc[btn] = hi.loc;
765 				if (btn >= sc->max_button)
766 					sc->max_button = btn + 1;
767 				break;
768 			}
769 			if (hi.collevel == 1 && hi.usage ==
770 			    HID_USAGE2(HUP_DIGITIZERS, HUD_CONTACTCOUNT)) {
771 				cont_count_found = true;
772 				sc->cont_count_loc = hi.loc;
773 				break;
774 			}
775 			/* Scan time is required but clobbered by evdev */
776 			if (hi.collevel == 1 && hi.usage ==
777 			    HID_USAGE2(HUP_DIGITIZERS, HUD_SCAN_TIME)) {
778 				scan_time_found = true;
779 				sc->scan_time_loc = hi.loc;
780 				sc->scan_time_max = hi.logical_maximum;
781 				break;
782 			}
783 
784 			if (!finger_coll || hi.collevel != 2)
785 				break;
786 			if (cont >= MAX_MT_SLOTS) {
787 				DPRINTF("Finger %zu ignored\n", cont);
788 				break;
789 			}
790 
791 			for (i = 0; i < HMT_N_USAGES; i++) {
792 				if (hi.usage == hmt_hid_map[i].usage) {
793 					/*
794 					 * HUG_X usage is an array mapped to
795 					 * both ABS_MT_POSITION and ABS_MT_TOOL
796 					 * events. So don`t stop search if we
797 					 * already have HUG_X mapping done.
798 					 */
799 					if (sc->locs[cont][i].size)
800 						continue;
801 					sc->locs[cont][i] = hi.loc;
802 					/*
803 					 * Hid parser returns valid logical and
804 					 * physical sizes for first finger only
805 					 * at least on ElanTS 0x04f3:0x0012.
806 					 */
807 					if (cont > 0)
808 						break;
809 					setbit(sc->caps, i);
810 					sc->ai[i] = (struct hid_absinfo) {
811 					    .max = hi.logical_maximum,
812 					    .min = hi.logical_minimum,
813 					    .res = hid_item_resolution(&hi),
814 					};
815 					break;
816 				}
817 			}
818 			break;
819 		default:
820 			break;
821 		}
822 	}
823 	hid_end_parse(hd);
824 
825 	/* Check for required HID Usages */
826 	if (!cont_count_found || !scan_time_found || cont == 0)
827 		return (HMT_TYPE_UNSUPPORTED);
828 	for (i = 0; i < HMT_N_USAGES; i++) {
829 		if (hmt_hid_map[i].required && isclr(sc->caps, i))
830 			return (HMT_TYPE_UNSUPPORTED);
831 	}
832 
833 	/* Touchpads must have at least one button */
834 	if (type == HMT_TYPE_TOUCHPAD && !sc->max_button && !has_int_button)
835 		return (HMT_TYPE_UNSUPPORTED);
836 
837 	/*
838 	 * According to specifications 'Contact Count Maximum' should be read
839 	 * from Feature Report rather than from HID descriptor. Set sane
840 	 * default value now to handle the case of 'Get Report' request failure
841 	 */
842 	if (cont_count_max < 1)
843 		cont_count_max = cont;
844 
845 	/* Report touch orientation if both width and height are supported */
846 	if (isset(sc->caps, HMT_WIDTH) && isset(sc->caps, HMT_HEIGHT)) {
847 		setbit(sc->caps, HMT_ORIENTATION);
848 		sc->ai[HMT_ORIENTATION].max = 1;
849 	}
850 
851 	sc->cont_max_rlen = hid_report_size(d_ptr, d_len, hid_feature,
852 	    sc->cont_max_rid);
853 	if (sc->btn_type_rid > 0)
854 		sc->btn_type_rlen = hid_report_size(d_ptr, d_len,
855 		    hid_feature, sc->btn_type_rid);
856 	if (sc->thqa_cert_rid > 0)
857 		sc->thqa_cert_rlen = hid_report_size(d_ptr, d_len,
858 		    hid_feature, sc->thqa_cert_rid);
859 
860 	sc->report_id = report_id;
861 	sc->cont_count_max = cont_count_max;
862 	sc->nconts_per_report = cont;
863 	sc->has_int_button = has_int_button;
864 
865 	return (type);
866 }
867 
868 static int
869 hmt_set_input_mode(struct hmt_softc *sc, enum hconf_input_mode mode)
870 {
871 	devclass_t hconf_devclass;
872 	device_t hconf;
873 	int  err;
874 
875 	GIANT_REQUIRED;
876 
877 	/* Find touchpad's configuration TLC */
878 	hconf = hidbus_find_child(device_get_parent(sc->dev),
879 	    HID_USAGE2(HUP_DIGITIZERS, HUD_CONFIG));
880 	if (hconf == NULL)
881 		return (ENXIO);
882 
883 	/* Ensure that hconf driver is attached to configuration TLC */
884 	if (device_is_alive(hconf) == 0)
885 		device_probe_and_attach(hconf);
886 	if (device_is_attached(hconf) == 0)
887 		return (ENXIO);
888 	hconf_devclass = devclass_find("hconf");
889 	if (device_get_devclass(hconf) != hconf_devclass)
890 		return (ENXIO);
891 
892 	/* hconf_set_input_mode can drop the Giant while sleeping */
893 	device_busy(hconf);
894 	err = hconf_set_input_mode(hconf, mode);
895 	device_unbusy(hconf);
896 
897 	return (err);
898 }
899 
900 static devclass_t hmt_devclass;
901 
902 static device_method_t hmt_methods[] = {
903 	DEVMETHOD(device_probe,		hmt_probe),
904 	DEVMETHOD(device_attach,	hmt_attach),
905 	DEVMETHOD(device_detach,	hmt_detach),
906 
907 	DEVMETHOD_END
908 };
909 
910 static driver_t hmt_driver = {
911 	.name = "hmt",
912 	.methods = hmt_methods,
913 	.size = sizeof(struct hmt_softc),
914 };
915 
916 DRIVER_MODULE(hmt, hidbus, hmt_driver, hmt_devclass, NULL, 0);
917 MODULE_DEPEND(hmt, hidbus, 1, 1, 1);
918 MODULE_DEPEND(hmt, hid, 1, 1, 1);
919 MODULE_DEPEND(hmt, hconf, 1, 1, 1);
920 MODULE_DEPEND(hmt, evdev, 1, 1, 1);
921 MODULE_VERSION(hmt, 1);
922 HID_PNP_INFO(hmt_devs);
923