xref: /freebsd/sys/dev/usb/input/wmt.c (revision 8e9740b62e950b40dcf7dbe729855be14450d40d)
1 /*-
2  * Copyright (c) 2014-2017 Vladimir Kondratyev <wulf@FreeBSD.org>
3  * All rights reserved.
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 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 /*
31  * MS Windows 7/8/10 compatible USB HID Multi-touch Device driver.
32  * https://msdn.microsoft.com/en-us/library/windows/hardware/jj151569(v=vs.85).aspx
33  * https://www.kernel.org/doc/Documentation/input/multi-touch-protocol.txt
34  */
35 
36 #include <sys/param.h>
37 #include <sys/bus.h>
38 #include <sys/conf.h>
39 #include <sys/kernel.h>
40 #include <sys/lock.h>
41 #include <sys/malloc.h>
42 #include <sys/module.h>
43 #include <sys/mutex.h>
44 #include <sys/stddef.h>
45 #include <sys/sysctl.h>
46 #include <sys/systm.h>
47 
48 #include <dev/hid/hid.h>
49 
50 #include "usbdevs.h"
51 #include <dev/usb/usb.h>
52 #include <dev/usb/usbdi.h>
53 #include <dev/usb/usbdi_util.h>
54 #include <dev/usb/usbhid.h>
55 
56 #include <dev/usb/quirk/usb_quirk.h>
57 
58 #include <dev/evdev/evdev.h>
59 #include <dev/evdev/input.h>
60 
61 #define	USB_DEBUG_VAR wmt_debug
62 #include <dev/usb/usb_debug.h>
63 
64 static SYSCTL_NODE(_hw_usb, OID_AUTO, wmt, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
65     "USB MSWindows 7/8/10 compatible Multi-touch Device");
66 #ifdef USB_DEBUG
67 static int wmt_debug = 0;
68 SYSCTL_INT(_hw_usb_wmt, OID_AUTO, debug, CTLFLAG_RWTUN,
69     &wmt_debug, 1, "Debug level");
70 #endif
71 static bool wmt_timestamps = 0;
72 SYSCTL_BOOL(_hw_usb_wmt, OID_AUTO, timestamps, CTLFLAG_RDTUN,
73     &wmt_timestamps, 1, "Enable hardware timestamp reporting");
74 
75 #define	WMT_BSIZE	1024	/* bytes, buffer size */
76 #define	WMT_BTN_MAX	8	/* Number of buttons supported */
77 
78 enum {
79 	WMT_INTR_DT,
80 	WMT_N_TRANSFER,
81 };
82 
83 enum wmt_type {
84 	WMT_TYPE_UNKNOWN = 0,	/* HID report descriptor is not probed */
85 	WMT_TYPE_UNSUPPORTED,	/* Repdescr does not belong to MT device */
86 	WMT_TYPE_TOUCHPAD,
87 	WMT_TYPE_TOUCHSCREEN,
88 };
89 
90 enum wmt_input_mode {
91 	WMT_INPUT_MODE_MOUSE =		0x0,
92 	WMT_INPUT_MODE_MT_TOUCHSCREEN =	0x2,
93 	WMT_INPUT_MODE_MT_TOUCHPAD =	0x3,
94 };
95 
96 enum {
97 	WMT_TIP_SWITCH =	ABS_MT_INDEX(ABS_MT_TOOL_TYPE),
98 	WMT_WIDTH =		ABS_MT_INDEX(ABS_MT_TOUCH_MAJOR),
99 	WMT_HEIGHT =		ABS_MT_INDEX(ABS_MT_TOUCH_MINOR),
100 	WMT_ORIENTATION =	ABS_MT_INDEX(ABS_MT_ORIENTATION),
101 	WMT_X =			ABS_MT_INDEX(ABS_MT_POSITION_X),
102 	WMT_Y =			ABS_MT_INDEX(ABS_MT_POSITION_Y),
103 	WMT_CONTACTID =		ABS_MT_INDEX(ABS_MT_TRACKING_ID),
104 	WMT_PRESSURE =		ABS_MT_INDEX(ABS_MT_PRESSURE),
105 	WMT_IN_RANGE =		ABS_MT_INDEX(ABS_MT_DISTANCE),
106 	WMT_CONFIDENCE =	ABS_MT_INDEX(ABS_MT_BLOB_ID),
107 	WMT_TOOL_X =		ABS_MT_INDEX(ABS_MT_TOOL_X),
108 	WMT_TOOL_Y =		ABS_MT_INDEX(ABS_MT_TOOL_Y),
109 };
110 
111 #define	WMT_N_USAGES	MT_CNT
112 #define	WMT_NO_USAGE	-1
113 
114 struct wmt_hid_map_item {
115 	char		name[5];
116 	int32_t 	usage;		/* HID usage */
117 	bool		reported;	/* Item value is passed to evdev */
118 	bool		required;	/* Required for MT Digitizers */
119 };
120 
121 static const struct wmt_hid_map_item wmt_hid_map[WMT_N_USAGES] = {
122 	[WMT_TIP_SWITCH] = {
123 		.name = "TIP",
124 		.usage = HID_USAGE2(HUP_DIGITIZERS, HUD_TIP_SWITCH),
125 		.reported = false,
126 		.required = true,
127 	},
128 	[WMT_WIDTH] = {
129 		.name = "WDTH",
130 		.usage = HID_USAGE2(HUP_DIGITIZERS, HUD_WIDTH),
131 		.reported = true,
132 		.required = false,
133 	},
134 	[WMT_HEIGHT] = {
135 		.name = "HGHT",
136 		.usage = HID_USAGE2(HUP_DIGITIZERS, HUD_HEIGHT),
137 		.reported = true,
138 		.required = false,
139 	},
140 	[WMT_ORIENTATION] = {
141 		.name = "ORIE",
142 		.usage = WMT_NO_USAGE,
143 		.reported = true,
144 		.required = false,
145 	},
146 	[WMT_X] = {
147 		.name = "X",
148 		.usage = HID_USAGE2(HUP_GENERIC_DESKTOP, HUG_X),
149 		.reported = true,
150 		.required = true,
151 	},
152 	[WMT_Y] = {
153 		.name = "Y",
154 		.usage = HID_USAGE2(HUP_GENERIC_DESKTOP, HUG_Y),
155 		.reported = true,
156 		.required = true,
157 	},
158 	[WMT_CONTACTID] = {
159 		.name = "C_ID",
160 		.usage = HID_USAGE2(HUP_DIGITIZERS, HUD_CONTACTID),
161 		.reported = true,
162 		.required = true,
163 	},
164 	[WMT_PRESSURE] = {
165 		.name = "PRES",
166 		.usage = HID_USAGE2(HUP_DIGITIZERS, HUD_TIP_PRESSURE),
167 		.reported = true,
168 		.required = false,
169 	},
170 	[WMT_IN_RANGE] = {
171 		.name = "RANG",
172 		.usage = HID_USAGE2(HUP_DIGITIZERS, HUD_IN_RANGE),
173 		.reported = true,
174 		.required = false,
175 	},
176 	[WMT_CONFIDENCE] = {
177 		.name = "CONF",
178 		.usage = HID_USAGE2(HUP_DIGITIZERS, HUD_CONFIDENCE),
179 		.reported = false,
180 		.required = false,
181 	},
182 	[WMT_TOOL_X] = {	/* Shares HID usage with WMT_X */
183 		.name = "TL_X",
184 		.usage = HID_USAGE2(HUP_GENERIC_DESKTOP, HUG_X),
185 		.reported = true,
186 		.required = false,
187 	},
188 	[WMT_TOOL_Y] = {	/* Shares HID usage with WMT_Y */
189 		.name = "TL_Y",
190 		.usage = HID_USAGE2(HUP_GENERIC_DESKTOP, HUG_Y),
191 		.reported = true,
192 		.required = false,
193 	},
194 };
195 
196 struct wmt_absinfo {
197 	int32_t			min;
198 	int32_t			max;
199 	int32_t			res;
200 };
201 
202 struct wmt_softc {
203 	device_t		dev;
204 	enum wmt_type		type;
205 
206 	int32_t			cont_count_max;
207 	struct mtx		mtx;
208 	struct wmt_absinfo	ai[WMT_N_USAGES];
209 	struct hid_location	locs[MAX_MT_SLOTS][WMT_N_USAGES];
210 	struct hid_location	cont_count_loc;
211 	struct hid_location	btn_loc[WMT_BTN_MAX];
212 	struct hid_location	int_btn_loc;
213 	struct hid_location	scan_time_loc;
214 	int32_t			scan_time_max;
215 	int32_t			scan_time;
216 	int32_t			timestamp;
217 	bool			touch;
218 	bool			prev_touch;
219 
220 	struct usb_xfer		*xfer[WMT_N_TRANSFER];
221 	struct evdev_dev	*evdev;
222 
223 	union evdev_mt_slot	slot_data;
224 	uint8_t			caps[howmany(WMT_N_USAGES, 8)];
225 	uint8_t			buttons[howmany(WMT_BTN_MAX, 8)];
226 	uint32_t		isize;
227 	uint32_t		nconts_per_report;
228 	uint32_t		nconts_todo;
229 	uint32_t		report_len;
230 	uint8_t			report_id;
231 	uint32_t		max_button;
232 	bool			has_int_button;
233 	bool			is_clickpad;
234 	bool			do_timestamps;
235 
236 	struct hid_location	cont_max_loc;
237 	uint32_t		cont_max_rlen;
238 	uint8_t			cont_max_rid;
239 	struct hid_location	btn_type_loc;
240 	uint32_t		btn_type_rlen;
241 	uint8_t			btn_type_rid;
242 	uint32_t		thqa_cert_rlen;
243 	uint8_t			thqa_cert_rid;
244 	struct hid_location	input_mode_loc;
245 	uint32_t		input_mode_rlen;
246 	uint8_t			input_mode_rid;
247 
248 	uint8_t			buf[WMT_BSIZE] __aligned(4);
249 };
250 
251 #define	WMT_FOREACH_USAGE(caps, usage)			\
252 	for ((usage) = 0; (usage) < WMT_N_USAGES; ++(usage))	\
253 		if (isset((caps), (usage)))
254 
255 static enum wmt_type wmt_hid_parse(struct wmt_softc *, const void *, uint16_t);
256 static int wmt_set_input_mode(struct wmt_softc *, enum wmt_input_mode);
257 
258 static usb_callback_t	wmt_intr_callback;
259 
260 static device_probe_t	wmt_probe;
261 static device_attach_t	wmt_attach;
262 static device_detach_t	wmt_detach;
263 
264 #if __FreeBSD_version >= 1200077
265 static evdev_open_t	wmt_ev_open;
266 static evdev_close_t	wmt_ev_close;
267 #else
268 static evdev_open_t	wmt_ev_open_11;
269 static evdev_close_t	wmt_ev_close_11;
270 #endif
271 
272 static const struct evdev_methods wmt_evdev_methods = {
273 #if __FreeBSD_version >= 1200077
274 	.ev_open = &wmt_ev_open,
275 	.ev_close = &wmt_ev_close,
276 #else
277 	.ev_open = &wmt_ev_open_11,
278 	.ev_close = &wmt_ev_close_11,
279 #endif
280 };
281 
282 static const struct usb_config wmt_config[WMT_N_TRANSFER] = {
283 	[WMT_INTR_DT] = {
284 		.type = UE_INTERRUPT,
285 		.endpoint = UE_ADDR_ANY,
286 		.direction = UE_DIR_IN,
287 		.flags = { .pipe_bof = 1, .short_xfer_ok = 1 },
288 		.bufsize = WMT_BSIZE,
289 		.callback = &wmt_intr_callback,
290 	},
291 };
292 
293 static int
294 wmt_probe(device_t dev)
295 {
296 	struct usb_attach_arg *uaa = device_get_ivars(dev);
297 	struct wmt_softc *sc = device_get_softc(dev);
298 	void *d_ptr;
299 	uint16_t d_len;
300 	int err;
301 
302 	if (uaa->usb_mode != USB_MODE_HOST)
303 		return (ENXIO);
304 
305 	if (uaa->info.bInterfaceClass != UICLASS_HID)
306 		return (ENXIO);
307 
308 	if (usb_test_quirk(uaa, UQ_WMT_IGNORE))
309 		return (ENXIO);
310 
311 	err = usbd_req_get_hid_desc(uaa->device, NULL,
312 	    &d_ptr, &d_len, M_TEMP, uaa->info.bIfaceIndex);
313 	if (err)
314 		return (ENXIO);
315 
316 	/* Check if report descriptor belongs to a HID multitouch device */
317 	if (sc->type == WMT_TYPE_UNKNOWN)
318 		sc->type = wmt_hid_parse(sc, d_ptr, d_len);
319 	if (sc->type != WMT_TYPE_UNSUPPORTED)
320 		err = BUS_PROBE_DEFAULT;
321 	else
322 		err = ENXIO;
323 
324 	/* Check HID report length */
325 	if (sc->type != WMT_TYPE_UNSUPPORTED &&
326 	    (sc->isize <= 0 || sc->isize > WMT_BSIZE)) {
327 		DPRINTF("Input size invalid or too large: %d\n", sc->isize);
328 		err = ENXIO;
329 	}
330 
331 	free(d_ptr, M_TEMP);
332 	return (err);
333 }
334 
335 static int
336 wmt_attach(device_t dev)
337 {
338 	struct usb_attach_arg *uaa = device_get_ivars(dev);
339 	struct wmt_softc *sc = device_get_softc(dev);
340 	uint32_t cont_count_max;
341 	int nbuttons, btn;
342 	size_t i;
343 	int err;
344 
345 	device_set_usb_desc(dev);
346 	sc->dev = dev;
347 
348 	/* Fetch and parse "Contact count maximum" feature report */
349 	if (sc->cont_max_rlen > 0 && sc->cont_max_rlen <= WMT_BSIZE) {
350 		err = usbd_req_get_report(uaa->device, NULL, sc->buf,
351 		    sc->cont_max_rlen, uaa->info.bIfaceIndex,
352 		    UHID_FEATURE_REPORT, sc->cont_max_rid);
353 		if (err == USB_ERR_NORMAL_COMPLETION) {
354 			cont_count_max = hid_get_udata(sc->buf + 1,
355 			    sc->cont_max_rlen - 1, &sc->cont_max_loc);
356 			/*
357 			 * Feature report is a primary source of
358 			 * 'Contact Count Maximum'
359 			 */
360 			if (cont_count_max > 0)
361 				sc->cont_count_max = cont_count_max;
362 		} else
363 			DPRINTF("usbd_req_get_report error=(%s)\n",
364 			    usbd_errstr(err));
365 	} else
366 		DPRINTF("Feature report %hhu size invalid or too large: %u\n",
367 		    sc->cont_max_rid, sc->cont_max_rlen);
368 
369 	/* Fetch and parse "Button type" feature report */
370 	if (sc->btn_type_rlen > 1 && sc->btn_type_rlen <= WMT_BSIZE &&
371 	    sc->btn_type_rid != sc->cont_max_rid) {
372 		bzero(sc->buf, sc->btn_type_rlen);
373 		err = usbd_req_get_report(uaa->device, NULL, sc->buf,
374 		    sc->btn_type_rlen, uaa->info.bIfaceIndex,
375 		    UHID_FEATURE_REPORT, sc->btn_type_rid);
376 	}
377 	if (sc->btn_type_rlen > 1) {
378 		if (err == 0)
379 			sc->is_clickpad = hid_get_udata(sc->buf + 1,
380 			    sc->btn_type_rlen - 1, &sc->btn_type_loc) == 0;
381 		else
382 			DPRINTF("usbd_req_get_report error=%d\n", err);
383 	}
384 
385 	/* Fetch THQA certificate to enable some devices like WaveShare */
386 	if (sc->thqa_cert_rlen > 0 && sc->thqa_cert_rlen <= WMT_BSIZE &&
387 	    sc->thqa_cert_rid != sc->cont_max_rid)
388 		(void)usbd_req_get_report(uaa->device, NULL, sc->buf,
389 		    sc->thqa_cert_rlen, uaa->info.bIfaceIndex,
390 		    UHID_FEATURE_REPORT, sc->thqa_cert_rid);
391 
392 	/* Switch touchpad in to absolute multitouch mode */
393 	if (sc->type == WMT_TYPE_TOUCHPAD) {
394 		err = wmt_set_input_mode(sc, WMT_INPUT_MODE_MT_TOUCHPAD);
395 		if (err != 0)
396 			DPRINTF("Failed to set input mode: %d\n", err);
397 	}
398 
399 	/* Cap contact count maximum to MAX_MT_SLOTS */
400 	if (sc->cont_count_max > MAX_MT_SLOTS) {
401 		DPRINTF("Hardware reported %d contacts while only %d is "
402 		    "supported\n", (int)sc->cont_count_max, MAX_MT_SLOTS);
403 		sc->cont_count_max = MAX_MT_SLOTS;
404 	}
405 
406 	if (/*usb_test_quirk(hw, UQ_MT_TIMESTAMP) ||*/ wmt_timestamps)
407 		sc->do_timestamps = true;
408 
409 	mtx_init(&sc->mtx, "wmt lock", NULL, MTX_DEF);
410 
411 	err = usbd_transfer_setup(uaa->device, &uaa->info.bIfaceIndex,
412 	    sc->xfer, wmt_config, WMT_N_TRANSFER, sc, &sc->mtx);
413 	if (err != USB_ERR_NORMAL_COMPLETION) {
414 		DPRINTF("usbd_transfer_setup error=%s\n", usbd_errstr(err));
415 		goto detach;
416 	}
417 
418 	sc->evdev = evdev_alloc();
419 	evdev_set_name(sc->evdev, device_get_desc(dev));
420 	evdev_set_phys(sc->evdev, device_get_nameunit(dev));
421 	evdev_set_id(sc->evdev, BUS_USB, uaa->info.idVendor,
422 	    uaa->info.idProduct, 0);
423 	evdev_set_serial(sc->evdev, usb_get_serial(uaa->device));
424 	evdev_set_methods(sc->evdev, sc, &wmt_evdev_methods);
425 	evdev_set_flag(sc->evdev, EVDEV_FLAG_MT_STCOMPAT);
426 	switch (sc->type) {
427 	case WMT_TYPE_TOUCHSCREEN:
428 		evdev_support_prop(sc->evdev, INPUT_PROP_DIRECT);
429 		break;
430 	case WMT_TYPE_TOUCHPAD:
431 		evdev_support_prop(sc->evdev, INPUT_PROP_POINTER);
432 		if (sc->is_clickpad)
433 			evdev_support_prop(sc->evdev, INPUT_PROP_BUTTONPAD);
434 		break;
435 	default:
436 		KASSERT(0, ("wmt_attach: unsupported touch device type"));
437 	}
438 	evdev_support_event(sc->evdev, EV_SYN);
439 	evdev_support_event(sc->evdev, EV_ABS);
440 	if (sc->do_timestamps) {
441 		evdev_support_event(sc->evdev, EV_MSC);
442 		evdev_support_msc(sc->evdev, MSC_TIMESTAMP);
443 	}
444 	nbuttons = 0;
445 	if (sc->max_button != 0 || sc->has_int_button) {
446 		evdev_support_event(sc->evdev, EV_KEY);
447 		if (sc->has_int_button)
448 			evdev_support_key(sc->evdev, BTN_LEFT);
449 		for (btn = 0; btn < sc->max_button; ++btn) {
450 			if (isset(sc->buttons, btn)) {
451 				evdev_support_key(sc->evdev, BTN_MOUSE + btn);
452 				nbuttons++;
453 			}
454 		}
455 	}
456 	evdev_support_abs(sc->evdev,
457 	    ABS_MT_SLOT, 0, sc->cont_count_max - 1, 0, 0, 0);
458 	WMT_FOREACH_USAGE(sc->caps, i) {
459 		if (wmt_hid_map[i].reported)
460 			evdev_support_abs(sc->evdev, ABS_MT_FIRST + i,
461 			    sc->ai[i].min, sc->ai[i].max, 0, 0, sc->ai[i].res);
462 	}
463 
464 	err = evdev_register_mtx(sc->evdev, &sc->mtx);
465 	if (err)
466 		goto detach;
467 
468 	/* Announce information about the touch device */
469 	device_printf(sc->dev, "Multitouch %s with %d external button%s%s\n",
470 	    sc->type == WMT_TYPE_TOUCHSCREEN ? "touchscreen" : "touchpad",
471 	    nbuttons, nbuttons != 1 ? "s" : "",
472 	    sc->is_clickpad ? ", click-pad" : "");
473 	device_printf(sc->dev,
474 	    "%d contacts and [%s%s%s%s%s]. Report range [%d:%d] - [%d:%d]\n",
475 	    (int)sc->cont_count_max,
476 	    isset(sc->caps, WMT_IN_RANGE) ? "R" : "",
477 	    isset(sc->caps, WMT_CONFIDENCE) ? "C" : "",
478 	    isset(sc->caps, WMT_WIDTH) ? "W" : "",
479 	    isset(sc->caps, WMT_HEIGHT) ? "H" : "",
480 	    isset(sc->caps, WMT_PRESSURE) ? "P" : "",
481 	    (int)sc->ai[WMT_X].min, (int)sc->ai[WMT_Y].min,
482 	    (int)sc->ai[WMT_X].max, (int)sc->ai[WMT_Y].max);
483 
484 	return (0);
485 
486 detach:
487 	wmt_detach(dev);
488 	return (ENXIO);
489 }
490 
491 static int
492 wmt_detach(device_t dev)
493 {
494 	struct wmt_softc *sc = device_get_softc(dev);
495 
496 	evdev_free(sc->evdev);
497 	usbd_transfer_unsetup(sc->xfer, WMT_N_TRANSFER);
498 	mtx_destroy(&sc->mtx);
499 	return (0);
500 }
501 
502 static void
503 wmt_process_report(struct wmt_softc *sc, uint8_t *buf, int len)
504 {
505 	size_t usage;
506 	union evdev_mt_slot *slot_data;
507 	uint32_t cont, btn;
508 	uint32_t cont_count;
509 	uint32_t width;
510 	uint32_t height;
511 	uint32_t int_btn = 0;
512 	uint32_t left_btn = 0;
513 	int slot;
514 	uint32_t scan_time;
515 	int32_t delta;
516 
517 	/*
518 	 * "In Parallel mode, devices report all contact information in a
519 	 * single packet. Each physical contact is represented by a logical
520 	 * collection that is embedded in the top-level collection."
521 	 *
522 	 * Since additional contacts that were not present will still be in the
523 	 * report with contactid=0 but contactids are zero-based, find
524 	 * contactcount first.
525 	 */
526 	cont_count = hid_get_udata(buf, len, &sc->cont_count_loc);
527 	/*
528 	 * "In Hybrid mode, the number of contacts that can be reported in one
529 	 * report is less than the maximum number of contacts that the device
530 	 * supports. For example, a device that supports a maximum of
531 	 * 4 concurrent physical contacts, can set up its top-level collection
532 	 * to deliver a maximum of two contacts in one report. If four contact
533 	 * points are present, the device can break these up into two serial
534 	 * reports that deliver two contacts each.
535 	 *
536 	 * "When a device delivers data in this manner, the Contact Count usage
537 	 * value in the first report should reflect the total number of
538 	 * contacts that are being delivered in the hybrid reports. The other
539 	 * serial reports should have a contact count of zero (0)."
540 	 */
541 	if (cont_count != 0)
542 		sc->nconts_todo = cont_count;
543 
544 #ifdef USB_DEBUG
545 	DPRINTFN(6, "cont_count:%2u", (unsigned)cont_count);
546 	if (wmt_debug >= 6) {
547 		WMT_FOREACH_USAGE(sc->caps, usage) {
548 			if (wmt_hid_map[usage].usage != WMT_NO_USAGE)
549 				printf(" %-4s", wmt_hid_map[usage].name);
550 		}
551 		printf("\n");
552 	}
553 #endif
554 
555 	/* Find the number of contacts reported in current report */
556 	cont_count = MIN(sc->nconts_todo, sc->nconts_per_report);
557 
558 	/* Use protocol Type B for reporting events */
559 	for (cont = 0; cont < cont_count; cont++) {
560 		slot_data = &sc->slot_data;
561 		bzero(slot_data, sizeof(sc->slot_data));
562 		WMT_FOREACH_USAGE(sc->caps, usage) {
563 			if (sc->locs[cont][usage].size > 0)
564 				slot_data->val[usage] = hid_get_udata(
565 				    buf, len, &sc->locs[cont][usage]);
566 		}
567 
568 		slot = evdev_mt_id_to_slot(sc->evdev, slot_data->id);
569 
570 #ifdef USB_DEBUG
571 		DPRINTFN(6, "cont%01x: data = ", cont);
572 		if (wmt_debug >= 6) {
573 			WMT_FOREACH_USAGE(sc->caps, usage) {
574 				if (wmt_hid_map[usage].usage != WMT_NO_USAGE)
575 					printf("%04x ", slot_data->val[usage]);
576 			}
577 			printf("slot = %d\n", slot);
578 		}
579 #endif
580 
581 		if (slot == -1) {
582 			DPRINTF("Slot overflow for contact_id %u\n",
583 			    (unsigned)slot_data->id);
584 			continue;
585 		}
586 
587 		if (slot_data->val[WMT_TIP_SWITCH] != 0 &&
588 		    !(isset(sc->caps, WMT_CONFIDENCE) &&
589 		      slot_data->val[WMT_CONFIDENCE] == 0)) {
590 			/* This finger is in proximity of the sensor */
591 			sc->touch = true;
592 			slot_data->dist = !slot_data->val[WMT_IN_RANGE];
593 			/* Divided by two to match visual scale of touch */
594 			width = slot_data->val[WMT_WIDTH] >> 1;
595 			height = slot_data->val[WMT_HEIGHT] >> 1;
596 			slot_data->ori = width > height;
597 			slot_data->maj = MAX(width, height);
598 			slot_data->min = MIN(width, height);
599 		} else
600 			slot_data = NULL;
601 
602 		evdev_mt_push_slot(sc->evdev, slot, slot_data);
603 	}
604 
605 	sc->nconts_todo -= cont_count;
606 	if (sc->do_timestamps && sc->nconts_todo == 0) {
607 		/* HUD_SCAN_TIME is measured in 100us, convert to us. */
608 		scan_time = hid_get_udata(buf, len, &sc->scan_time_loc);
609 		if (sc->prev_touch) {
610 			delta = scan_time - sc->scan_time;
611 			if (delta < 0)
612 				delta += sc->scan_time_max;
613 		} else
614 			delta = 0;
615 		sc->scan_time = scan_time;
616 		sc->timestamp += delta * 100;
617 		evdev_push_msc(sc->evdev, MSC_TIMESTAMP, sc->timestamp);
618 		sc->prev_touch = sc->touch;
619 		sc->touch = false;
620 		if (!sc->prev_touch)
621 			sc->timestamp = 0;
622 	}
623 	if (sc->nconts_todo == 0) {
624 		/* Report both the click and external left btns as BTN_LEFT */
625 		if (sc->has_int_button)
626 			int_btn = hid_get_data(buf, len, &sc->int_btn_loc);
627 		if (isset(sc->buttons, 0))
628 			left_btn = hid_get_data(buf, len, &sc->btn_loc[0]);
629 		if (sc->has_int_button || isset(sc->buttons, 0))
630 			evdev_push_key(sc->evdev, BTN_LEFT,
631 			    (int_btn != 0) | (left_btn != 0));
632 		for (btn = 1; btn < sc->max_button; ++btn) {
633 			if (isset(sc->buttons, btn))
634 				evdev_push_key(sc->evdev, BTN_MOUSE + btn,
635 				    hid_get_data(buf,
636 						 len,
637 						 &sc->btn_loc[btn]) != 0);
638 		}
639 		evdev_sync(sc->evdev);
640 	}
641 }
642 
643 static void
644 wmt_intr_callback(struct usb_xfer *xfer, usb_error_t error)
645 {
646 	struct wmt_softc *sc = usbd_xfer_softc(xfer);
647 	struct usb_page_cache *pc;
648 	uint8_t *buf = sc->buf;
649 	int len;
650 
651 	usbd_xfer_status(xfer, &len, NULL, NULL, NULL);
652 
653 	switch (USB_GET_STATE(xfer)) {
654 	case USB_ST_TRANSFERRED:
655 		pc = usbd_xfer_get_frame(xfer, 0);
656 
657 		DPRINTFN(6, "sc=%p actlen=%d\n", sc, len);
658 
659 		if (len >= (int)sc->report_len ||
660 		    (len > 0 && sc->report_id != 0)) {
661 			/* Limit report length to the maximum */
662 			if (len > (int)sc->report_len)
663 				len = sc->report_len;
664 
665 			usbd_copy_out(pc, 0, buf, len);
666 
667 			/* Ignore irrelevant reports */
668 			if (sc->report_id && *buf != sc->report_id)
669 				goto tr_ignore;
670 
671 			/* Make sure we don't process old data */
672 			if (len < sc->report_len)
673 				bzero(buf + len, sc->report_len - len);
674 
675 			/* Strip leading "report ID" byte */
676 			if (sc->report_id) {
677 				len--;
678 				buf++;
679 			}
680 
681 			wmt_process_report(sc, buf, len);
682 		} else {
683 tr_ignore:
684 			DPRINTF("Ignored transfer, %d bytes\n", len);
685 		}
686 
687 	case USB_ST_SETUP:
688 tr_setup:
689 		usbd_xfer_set_frame_len(xfer, 0, sc->isize);
690 		usbd_transfer_submit(xfer);
691 		break;
692 	default:
693 		if (error != USB_ERR_CANCELLED) {
694 			/* Try clear stall first */
695 			usbd_xfer_set_stall(xfer);
696 			goto tr_setup;
697 		}
698 		break;
699 	}
700 }
701 
702 static void
703 wmt_ev_close_11(struct evdev_dev *evdev, void *ev_softc)
704 {
705 	struct wmt_softc *sc = ev_softc;
706 
707 	mtx_assert(&sc->mtx, MA_OWNED);
708 	usbd_transfer_stop(sc->xfer[WMT_INTR_DT]);
709 }
710 
711 static int
712 wmt_ev_open_11(struct evdev_dev *evdev, void *ev_softc)
713 {
714 	struct wmt_softc *sc = ev_softc;
715 
716 	mtx_assert(&sc->mtx, MA_OWNED);
717 	usbd_transfer_start(sc->xfer[WMT_INTR_DT]);
718 
719 	return (0);
720 }
721 
722 #if __FreeBSD_version >= 1200077
723 static int
724 wmt_ev_close(struct evdev_dev *evdev)
725 {
726 	struct wmt_softc *sc = evdev_get_softc(evdev);
727 
728 	wmt_ev_close_11(evdev, sc);
729 
730 	return (0);
731 }
732 
733 static int
734 wmt_ev_open(struct evdev_dev *evdev)
735 {
736 	struct wmt_softc *sc = evdev_get_softc(evdev);
737 
738 	return (wmt_ev_open_11(evdev, sc));
739 
740 }
741 #endif
742 
743 static enum wmt_type
744 wmt_hid_parse(struct wmt_softc *sc, const void *d_ptr, uint16_t d_len)
745 {
746 	struct hid_item hi;
747 	struct hid_data *hd;
748 	size_t i;
749 	size_t cont = 0;
750 	enum wmt_type type = WMT_TYPE_UNSUPPORTED;
751 	uint32_t left_btn, btn;
752 	int32_t cont_count_max = 0;
753 	uint8_t report_id = 0;
754 	bool touch_coll = false;
755 	bool finger_coll = false;
756 	bool cont_count_found = false;
757 	bool scan_time_found = false;
758 	bool has_int_button = false;
759 
760 #define WMT_HI_ABSOLUTE(hi)	\
761 	(((hi).flags & (HIO_CONST|HIO_VARIABLE|HIO_RELATIVE)) == HIO_VARIABLE)
762 #define	HUMS_THQA_CERT	0xC5
763 
764 	/* Parse features for maximum contact count */
765 	hd = hid_start_parse(d_ptr, d_len, 1 << hid_feature);
766 	while (hid_get_item(hd, &hi)) {
767 		switch (hi.kind) {
768 		case hid_collection:
769 			if (hi.collevel == 1 && hi.usage ==
770 			    HID_USAGE2(HUP_DIGITIZERS, HUD_TOUCHSCREEN)) {
771 				touch_coll = true;
772 				type = WMT_TYPE_TOUCHSCREEN;
773 				left_btn = 1;
774 				break;
775 			}
776 			if (hi.collevel == 1 && hi.usage ==
777 			    HID_USAGE2(HUP_DIGITIZERS, HUD_TOUCHPAD)) {
778 				touch_coll = true;
779 				type = WMT_TYPE_TOUCHPAD;
780 				left_btn = 2;
781 			}
782 			break;
783 		case hid_endcollection:
784 			if (hi.collevel == 0 && touch_coll)
785 				touch_coll = false;
786 			break;
787 		case hid_feature:
788 			if (hi.collevel == 1 && touch_coll && hi.usage ==
789 			      HID_USAGE2(HUP_MICROSOFT, HUMS_THQA_CERT)) {
790 				sc->thqa_cert_rid = hi.report_ID;
791 				break;
792 			}
793 			if (hi.collevel == 1 && touch_coll && hi.usage ==
794 			    HID_USAGE2(HUP_DIGITIZERS, HUD_CONTACT_MAX)) {
795 				cont_count_max = hi.logical_maximum;
796 				sc->cont_max_rid = hi.report_ID;
797 				sc->cont_max_loc = hi.loc;
798 				break;
799 			}
800 			if (hi.collevel == 1 && touch_coll && hi.usage ==
801 			    HID_USAGE2(HUP_DIGITIZERS, HUD_BUTTON_TYPE)) {
802 				sc->btn_type_rid = hi.report_ID;
803 				sc->btn_type_loc = hi.loc;
804 			}
805 			break;
806 		default:
807 			break;
808 		}
809 	}
810 	hid_end_parse(hd);
811 
812 	if (type == WMT_TYPE_UNSUPPORTED)
813 		return (WMT_TYPE_UNSUPPORTED);
814 	/* Maximum contact count is required usage */
815 	if (sc->cont_max_rid == 0)
816 		return (WMT_TYPE_UNSUPPORTED);
817 
818 	touch_coll = false;
819 
820 	/* Parse input for other parameters */
821 	hd = hid_start_parse(d_ptr, d_len, 1 << hid_input);
822 	while (hid_get_item(hd, &hi)) {
823 		switch (hi.kind) {
824 		case hid_collection:
825 			if (hi.collevel == 1 && hi.usage ==
826 			    HID_USAGE2(HUP_DIGITIZERS, HUD_TOUCHSCREEN))
827 				touch_coll = true;
828 			else if (touch_coll && hi.collevel == 2 &&
829 			    (report_id == 0 || report_id == hi.report_ID) &&
830 			    hi.usage == HID_USAGE2(HUP_DIGITIZERS, HUD_FINGER))
831 				finger_coll = true;
832 			break;
833 		case hid_endcollection:
834 			if (hi.collevel == 1 && finger_coll) {
835 				finger_coll = false;
836 				cont++;
837 			} else if (hi.collevel == 0 && touch_coll)
838 				touch_coll = false;
839 			break;
840 		case hid_input:
841 			/*
842 			 * Ensure that all usages are located within the same
843 			 * report and proper collection.
844 			 */
845 			if (WMT_HI_ABSOLUTE(hi) && touch_coll &&
846 			    (report_id == 0 || report_id == hi.report_ID))
847 				report_id = hi.report_ID;
848 			else
849 				break;
850 
851 			if (hi.collevel == 1 && left_btn == 2 &&
852 			    hi.usage == HID_USAGE2(HUP_BUTTON, 1)) {
853 				has_int_button = true;
854 				sc->int_btn_loc = hi.loc;
855 				break;
856 			}
857 			if (hi.collevel == 1 &&
858 			    hi.usage >= HID_USAGE2(HUP_BUTTON, left_btn) &&
859 			    hi.usage <= HID_USAGE2(HUP_BUTTON, WMT_BTN_MAX)) {
860 				btn = (hi.usage & 0xFFFF) - left_btn;
861 				setbit(sc->buttons, btn);
862 				sc->btn_loc[btn] = hi.loc;
863 				if (btn >= sc->max_button)
864 					sc->max_button = btn + 1;
865 				break;
866 			}
867 			if (hi.collevel == 1 && hi.usage ==
868 			    HID_USAGE2(HUP_DIGITIZERS, HUD_CONTACTCOUNT)) {
869 				cont_count_found = true;
870 				sc->cont_count_loc = hi.loc;
871 				break;
872 			}
873 			/* Scan time is required but clobbered by evdev */
874 			if (hi.collevel == 1 && hi.usage ==
875 			    HID_USAGE2(HUP_DIGITIZERS, HUD_SCAN_TIME)) {
876 				scan_time_found = true;
877 				sc->scan_time_loc = hi.loc;
878 				sc->scan_time_max = hi.logical_maximum;
879 				break;
880 			}
881 
882 			if (!finger_coll || hi.collevel != 2)
883 				break;
884 			if (cont >= MAX_MT_SLOTS) {
885 				DPRINTF("Finger %zu ignored\n", cont);
886 				break;
887 			}
888 
889 			for (i = 0; i < WMT_N_USAGES; i++) {
890 				if (hi.usage == wmt_hid_map[i].usage) {
891 					/*
892 					 * HUG_X usage is an array mapped to
893 					 * both ABS_MT_POSITION and ABS_MT_TOOL
894 					 * events. So don`t stop search if we
895 					 * already have HUG_X mapping done.
896 					 */
897 					if (sc->locs[cont][i].size)
898 						continue;
899 					sc->locs[cont][i] = hi.loc;
900 					/*
901 					 * Hid parser returns valid logical and
902 					 * physical sizes for first finger only
903 					 * at least on ElanTS 0x04f3:0x0012.
904 					 */
905 					if (cont > 0)
906 						break;
907 					setbit(sc->caps, i);
908 					sc->ai[i] = (struct wmt_absinfo) {
909 					    .max = hi.logical_maximum,
910 					    .min = hi.logical_minimum,
911 					    .res = hid_item_resolution(&hi),
912 					};
913 					break;
914 				}
915 			}
916 			break;
917 		default:
918 			break;
919 		}
920 	}
921 	hid_end_parse(hd);
922 
923 	/* Check for required HID Usages */
924 	if (!cont_count_found || !scan_time_found || cont == 0)
925 		return (WMT_TYPE_UNSUPPORTED);
926 	for (i = 0; i < WMT_N_USAGES; i++) {
927 		if (wmt_hid_map[i].required && isclr(sc->caps, i))
928 			return (WMT_TYPE_UNSUPPORTED);
929 	}
930 
931 	/* Touchpads must have at least one button */
932 	if (type == WMT_TYPE_TOUCHPAD && !sc->max_button && !has_int_button)
933 		return (WMT_TYPE_UNSUPPORTED);
934 
935 	/*
936 	 * According to specifications 'Contact Count Maximum' should be read
937 	 * from Feature Report rather than from HID descriptor. Set sane
938 	 * default value now to handle the case of 'Get Report' request failure
939 	 */
940 	if (cont_count_max < 1)
941 		cont_count_max = cont;
942 
943 	/* Report touch orientation if both width and height are supported */
944 	if (isset(sc->caps, WMT_WIDTH) && isset(sc->caps, WMT_HEIGHT)) {
945 		setbit(sc->caps, WMT_ORIENTATION);
946 		sc->ai[WMT_ORIENTATION].max = 1;
947 	}
948 
949 	sc->isize = hid_report_size_max(d_ptr, d_len, hid_input, NULL);
950 	sc->report_len = hid_report_size(d_ptr, d_len, hid_input,
951 	    report_id);
952 	sc->cont_max_rlen = hid_report_size(d_ptr, d_len, hid_feature,
953 	    sc->cont_max_rid);
954 	if (sc->btn_type_rid > 0)
955 		sc->btn_type_rlen = hid_report_size(d_ptr, d_len,
956 		    hid_feature, sc->btn_type_rid);
957 	if (sc->thqa_cert_rid > 0)
958 		sc->thqa_cert_rlen = hid_report_size(d_ptr, d_len,
959 		    hid_feature, sc->thqa_cert_rid);
960 
961 	sc->report_id = report_id;
962 	sc->nconts_per_report = cont;
963 	sc->has_int_button = has_int_button;
964 	sc->cont_count_max = cont_count_max;
965 
966 	return (type);
967 }
968 
969 static int
970 wmt_set_input_mode(struct wmt_softc *sc, enum wmt_input_mode mode)
971 {
972 	struct usb_attach_arg *uaa = device_get_ivars(sc->dev);
973 	int err;
974 
975 	if (sc->input_mode_rlen < 3 || sc->input_mode_rlen > WMT_BSIZE) {
976 		DPRINTF("Feature report %hhu size invalid or too large: %u\n",
977 		    sc->input_mode_rid, sc->input_mode_rlen);
978 		return (USB_ERR_BAD_BUFSIZE);
979 	}
980 
981 	/* Input Mode report is not strictly required to be readable */
982 	err = usbd_req_get_report(uaa->device, NULL, sc->buf,
983 	    sc->input_mode_rlen, uaa->info.bIfaceIndex,
984 	    UHID_FEATURE_REPORT, sc->input_mode_rid);
985 	if (err != USB_ERR_NORMAL_COMPLETION)
986 		bzero(sc->buf + 1, sc->input_mode_rlen - 1);
987 
988 	sc->buf[0] = sc->input_mode_rid;
989 	hid_put_udata(sc->buf + 1, sc->input_mode_rlen - 1,
990 	    &sc->input_mode_loc, mode);
991 	err = usbd_req_set_report(uaa->device, NULL, sc->buf,
992 	    sc->input_mode_rlen, uaa->info.bIfaceIndex,
993 	    UHID_FEATURE_REPORT, sc->input_mode_rid);
994 
995 	return (err);
996 }
997 
998 static const STRUCT_USB_HOST_ID wmt_devs[] = {
999 	/* generic HID class w/o boot interface */
1000 	{USB_IFACE_CLASS(UICLASS_HID),
1001 	 USB_IFACE_SUBCLASS(0),},
1002 };
1003 
1004 static devclass_t wmt_devclass;
1005 
1006 static device_method_t wmt_methods[] = {
1007 	DEVMETHOD(device_probe, wmt_probe),
1008 	DEVMETHOD(device_attach, wmt_attach),
1009 	DEVMETHOD(device_detach, wmt_detach),
1010 
1011 	DEVMETHOD_END
1012 };
1013 
1014 static driver_t wmt_driver = {
1015 	.name = "wmt",
1016 	.methods = wmt_methods,
1017 	.size = sizeof(struct wmt_softc),
1018 };
1019 
1020 DRIVER_MODULE(wmt, uhub, wmt_driver, wmt_devclass, NULL, 0);
1021 MODULE_DEPEND(wmt, usb, 1, 1, 1);
1022 MODULE_DEPEND(wmt, hid, 1, 1, 1);
1023 MODULE_DEPEND(wmt, evdev, 1, 1, 1);
1024 MODULE_VERSION(wmt, 1);
1025 USB_PNP_HOST_INFO(wmt_devs);
1026