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