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