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