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