xref: /freebsd/sys/dev/usb/input/ums.c (revision e39e854e27f53a784c3982cbeb68f4ad1cfd9162)
1 /*-
2  * Copyright (c) 1998 The NetBSD Foundation, Inc.
3  * All rights reserved.
4  *
5  * This code is derived from software contributed to The NetBSD Foundation
6  * by Lennart Augustsson (lennart@augustsson.net) at
7  * Carlstedt Research & Technology.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
19  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
20  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
21  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
22  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28  * POSSIBILITY OF SUCH DAMAGE.
29  */
30 
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33 
34 /*
35  * HID spec: http://www.usb.org/developers/devclass_docs/HID1_11.pdf
36  */
37 
38 #include <sys/stdint.h>
39 #include <sys/stddef.h>
40 #include <sys/param.h>
41 #include <sys/queue.h>
42 #include <sys/types.h>
43 #include <sys/systm.h>
44 #include <sys/kernel.h>
45 #include <sys/bus.h>
46 #include <sys/module.h>
47 #include <sys/lock.h>
48 #include <sys/mutex.h>
49 #include <sys/condvar.h>
50 #include <sys/sysctl.h>
51 #include <sys/sx.h>
52 #include <sys/unistd.h>
53 #include <sys/callout.h>
54 #include <sys/malloc.h>
55 #include <sys/priv.h>
56 #include <sys/conf.h>
57 #include <sys/fcntl.h>
58 #include <sys/sbuf.h>
59 
60 #include <dev/usb/usb.h>
61 #include <dev/usb/usbdi.h>
62 #include <dev/usb/usbdi_util.h>
63 #include <dev/usb/usbhid.h>
64 #include "usbdevs.h"
65 
66 #define	USB_DEBUG_VAR ums_debug
67 #include <dev/usb/usb_debug.h>
68 
69 #include <dev/usb/quirk/usb_quirk.h>
70 
71 #include <sys/ioccom.h>
72 #include <sys/filio.h>
73 #include <sys/tty.h>
74 #include <sys/mouse.h>
75 
76 #ifdef USB_DEBUG
77 static int ums_debug = 0;
78 
79 static SYSCTL_NODE(_hw_usb, OID_AUTO, ums, CTLFLAG_RW, 0, "USB ums");
80 SYSCTL_INT(_hw_usb_ums, OID_AUTO, debug, CTLFLAG_RW,
81     &ums_debug, 0, "Debug level");
82 #endif
83 
84 #define	MOUSE_FLAGS_MASK (HIO_CONST|HIO_RELATIVE)
85 #define	MOUSE_FLAGS (HIO_RELATIVE)
86 
87 #define	UMS_BUF_SIZE      8		/* bytes */
88 #define	UMS_IFQ_MAXLEN   50		/* units */
89 #define	UMS_BUTTON_MAX   31		/* exclusive, must be less than 32 */
90 #define	UMS_BUT(i) ((i) < 3 ? (((i) + 2) % 3) : (i))
91 #define	UMS_INFO_MAX	  2		/* maximum number of HID sets */
92 
93 enum {
94 	UMS_INTR_DT,
95 	UMS_N_TRANSFER,
96 };
97 
98 struct ums_info {
99 	struct hid_location sc_loc_w;
100 	struct hid_location sc_loc_x;
101 	struct hid_location sc_loc_y;
102 	struct hid_location sc_loc_z;
103 	struct hid_location sc_loc_t;
104 	struct hid_location sc_loc_btn[UMS_BUTTON_MAX];
105 
106 	uint32_t sc_flags;
107 #define	UMS_FLAG_X_AXIS     0x0001
108 #define	UMS_FLAG_Y_AXIS     0x0002
109 #define	UMS_FLAG_Z_AXIS     0x0004
110 #define	UMS_FLAG_T_AXIS     0x0008
111 #define	UMS_FLAG_SBU        0x0010	/* spurious button up events */
112 #define	UMS_FLAG_REVZ	    0x0020	/* Z-axis is reversed */
113 #define	UMS_FLAG_W_AXIS     0x0040
114 
115 	uint8_t	sc_iid_w;
116 	uint8_t	sc_iid_x;
117 	uint8_t	sc_iid_y;
118 	uint8_t	sc_iid_z;
119 	uint8_t	sc_iid_t;
120 	uint8_t	sc_iid_btn[UMS_BUTTON_MAX];
121 	uint8_t	sc_buttons;
122 };
123 
124 struct ums_softc {
125 	struct usb_fifo_sc sc_fifo;
126 	struct mtx sc_mtx;
127 	struct usb_callout sc_callout;
128 	struct ums_info sc_info[UMS_INFO_MAX];
129 
130 	mousehw_t sc_hw;
131 	mousemode_t sc_mode;
132 	mousestatus_t sc_status;
133 
134 	struct usb_xfer *sc_xfer[UMS_N_TRANSFER];
135 
136 	int sc_pollrate;
137 	int sc_fflags;
138 
139 	uint8_t	sc_buttons;
140 	uint8_t	sc_iid;
141 	uint8_t	sc_temp[64];
142 };
143 
144 static void ums_put_queue_timeout(void *__sc);
145 
146 static usb_callback_t ums_intr_callback;
147 
148 static device_probe_t ums_probe;
149 static device_attach_t ums_attach;
150 static device_detach_t ums_detach;
151 
152 static usb_fifo_cmd_t ums_start_read;
153 static usb_fifo_cmd_t ums_stop_read;
154 static usb_fifo_open_t ums_open;
155 static usb_fifo_close_t ums_close;
156 static usb_fifo_ioctl_t ums_ioctl;
157 
158 static void	ums_put_queue(struct ums_softc *, int32_t, int32_t,
159 		    int32_t, int32_t, int32_t);
160 static int	ums_sysctl_handler_parseinfo(SYSCTL_HANDLER_ARGS);
161 
162 static struct usb_fifo_methods ums_fifo_methods = {
163 	.f_open = &ums_open,
164 	.f_close = &ums_close,
165 	.f_ioctl = &ums_ioctl,
166 	.f_start_read = &ums_start_read,
167 	.f_stop_read = &ums_stop_read,
168 	.basename[0] = "ums",
169 };
170 
171 static void
172 ums_put_queue_timeout(void *__sc)
173 {
174 	struct ums_softc *sc = __sc;
175 
176 	mtx_assert(&sc->sc_mtx, MA_OWNED);
177 
178 	ums_put_queue(sc, 0, 0, 0, 0, 0);
179 }
180 
181 static void
182 ums_intr_callback(struct usb_xfer *xfer, usb_error_t error)
183 {
184 	struct ums_softc *sc = usbd_xfer_softc(xfer);
185 	struct ums_info *info = &sc->sc_info[0];
186 	struct usb_page_cache *pc;
187 	uint8_t *buf = sc->sc_temp;
188 	int32_t buttons = 0;
189 	int32_t buttons_found = 0;
190 	int32_t dw = 0;
191 	int32_t dx = 0;
192 	int32_t dy = 0;
193 	int32_t dz = 0;
194 	int32_t dt = 0;
195 	uint8_t i;
196 	uint8_t id;
197 	int len;
198 
199 	usbd_xfer_status(xfer, &len, NULL, NULL, NULL);
200 
201 	switch (USB_GET_STATE(xfer)) {
202 	case USB_ST_TRANSFERRED:
203 		DPRINTFN(6, "sc=%p actlen=%d\n", sc, len);
204 
205 		if (len > (int)sizeof(sc->sc_temp)) {
206 			DPRINTFN(6, "truncating large packet to %zu bytes\n",
207 			    sizeof(sc->sc_temp));
208 			len = sizeof(sc->sc_temp);
209 		}
210 		if (len == 0)
211 			goto tr_setup;
212 
213 		pc = usbd_xfer_get_frame(xfer, 0);
214 		usbd_copy_out(pc, 0, buf, len);
215 
216 		DPRINTFN(6, "data = %02x %02x %02x %02x "
217 		    "%02x %02x %02x %02x\n",
218 		    (len > 0) ? buf[0] : 0, (len > 1) ? buf[1] : 0,
219 		    (len > 2) ? buf[2] : 0, (len > 3) ? buf[3] : 0,
220 		    (len > 4) ? buf[4] : 0, (len > 5) ? buf[5] : 0,
221 		    (len > 6) ? buf[6] : 0, (len > 7) ? buf[7] : 0);
222 
223 		if (sc->sc_iid) {
224 			id = *buf;
225 
226 			len--;
227 			buf++;
228 
229 		} else {
230 			id = 0;
231 			if (sc->sc_info[0].sc_flags & UMS_FLAG_SBU) {
232 				if ((*buf == 0x14) || (*buf == 0x15)) {
233 					goto tr_setup;
234 				}
235 			}
236 		}
237 
238 	repeat:
239 		if ((info->sc_flags & UMS_FLAG_W_AXIS) &&
240 		    (id == info->sc_iid_w))
241 			dw += hid_get_data(buf, len, &info->sc_loc_w);
242 
243 		if ((info->sc_flags & UMS_FLAG_X_AXIS) &&
244 		    (id == info->sc_iid_x))
245 			dx += hid_get_data(buf, len, &info->sc_loc_x);
246 
247 		if ((info->sc_flags & UMS_FLAG_Y_AXIS) &&
248 		    (id == info->sc_iid_y))
249 			dy = -hid_get_data(buf, len, &info->sc_loc_y);
250 
251 		if ((info->sc_flags & UMS_FLAG_Z_AXIS) &&
252 		    (id == info->sc_iid_z)) {
253 			int32_t temp;
254 			temp = hid_get_data(buf, len, &info->sc_loc_z);
255 			if (info->sc_flags & UMS_FLAG_REVZ)
256 				temp = -temp;
257 			dz -= temp;
258 		}
259 
260 		if ((info->sc_flags & UMS_FLAG_T_AXIS) &&
261 		    (id == info->sc_iid_t))
262 			dt -= hid_get_data(buf, len, &info->sc_loc_t);
263 
264 		for (i = 0; i < info->sc_buttons; i++) {
265 			uint32_t mask;
266 			mask = 1UL << UMS_BUT(i);
267 			/* check for correct button ID */
268 			if (id != info->sc_iid_btn[i])
269 				continue;
270 			/* check for button pressed */
271 			if (hid_get_data(buf, len, &info->sc_loc_btn[i]))
272 				buttons |= mask;
273 			/* register button mask */
274 			buttons_found |= mask;
275 		}
276 
277 		if (++info != &sc->sc_info[UMS_INFO_MAX])
278 			goto repeat;
279 
280 		/* keep old button value(s) for non-detected buttons */
281 		buttons |= sc->sc_status.button & ~buttons_found;
282 
283 		if (dx || dy || dz || dt || dw ||
284 		    (buttons != sc->sc_status.button)) {
285 
286 			DPRINTFN(6, "x:%d y:%d z:%d t:%d w:%d buttons:0x%08x\n",
287 			    dx, dy, dz, dt, dw, buttons);
288 
289 			/* translate T-axis into button presses until further */
290 			if (dt > 0)
291 				buttons |= 1UL << 3;
292 			else if (dt < 0)
293 				buttons |= 1UL << 4;
294 
295 			sc->sc_status.button = buttons;
296 			sc->sc_status.dx += dx;
297 			sc->sc_status.dy += dy;
298 			sc->sc_status.dz += dz;
299 			/*
300 			 * sc->sc_status.dt += dt;
301 			 * no way to export this yet
302 			 */
303 
304 			/*
305 		         * The Qtronix keyboard has a built in PS/2
306 		         * port for a mouse.  The firmware once in a
307 		         * while posts a spurious button up
308 		         * event. This event we ignore by doing a
309 		         * timeout for 50 msecs.  If we receive
310 		         * dx=dy=dz=buttons=0 before we add the event
311 		         * to the queue.  In any other case we delete
312 		         * the timeout event.
313 		         */
314 			if ((sc->sc_info[0].sc_flags & UMS_FLAG_SBU) &&
315 			    (dx == 0) && (dy == 0) && (dz == 0) && (dt == 0) &&
316 			    (dw == 0) && (buttons == 0)) {
317 
318 				usb_callout_reset(&sc->sc_callout, hz / 20,
319 				    &ums_put_queue_timeout, sc);
320 			} else {
321 
322 				usb_callout_stop(&sc->sc_callout);
323 
324 				ums_put_queue(sc, dx, dy, dz, dt, buttons);
325 			}
326 		}
327 	case USB_ST_SETUP:
328 tr_setup:
329 		/* check if we can put more data into the FIFO */
330 		if (usb_fifo_put_bytes_max(
331 		    sc->sc_fifo.fp[USB_FIFO_RX]) != 0) {
332 			usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
333 			usbd_transfer_submit(xfer);
334 		}
335 		break;
336 
337 	default:			/* Error */
338 		if (error != USB_ERR_CANCELLED) {
339 			/* try clear stall first */
340 			usbd_xfer_set_stall(xfer);
341 			goto tr_setup;
342 		}
343 		break;
344 	}
345 }
346 
347 static const struct usb_config ums_config[UMS_N_TRANSFER] = {
348 
349 	[UMS_INTR_DT] = {
350 		.type = UE_INTERRUPT,
351 		.endpoint = UE_ADDR_ANY,
352 		.direction = UE_DIR_IN,
353 		.flags = {.pipe_bof = 1,.short_xfer_ok = 1,},
354 		.bufsize = 0,	/* use wMaxPacketSize */
355 		.callback = &ums_intr_callback,
356 	},
357 };
358 
359 /* A match on these entries will load ums */
360 static const STRUCT_USB_HOST_ID __used ums_devs[] = {
361 	{USB_IFACE_CLASS(UICLASS_HID),
362 	 USB_IFACE_SUBCLASS(UISUBCLASS_BOOT),
363 	 USB_IFACE_PROTOCOL(UIPROTO_MOUSE),},
364 };
365 
366 static int
367 ums_probe(device_t dev)
368 {
369 	struct usb_attach_arg *uaa = device_get_ivars(dev);
370 	void *d_ptr;
371 	struct hid_data *hd;
372 	struct hid_item hi;
373 	int error, mdepth, found;
374 	uint16_t d_len;
375 
376 	DPRINTFN(11, "\n");
377 
378 	if (uaa->usb_mode != USB_MODE_HOST)
379 		return (ENXIO);
380 
381 	if (uaa->info.bInterfaceClass != UICLASS_HID)
382 		return (ENXIO);
383 
384 	if ((uaa->info.bInterfaceSubClass == UISUBCLASS_BOOT) &&
385 	    (uaa->info.bInterfaceProtocol == UIPROTO_MOUSE))
386 		return (BUS_PROBE_DEFAULT);
387 
388 	error = usbd_req_get_hid_desc(uaa->device, NULL,
389 	    &d_ptr, &d_len, M_TEMP, uaa->info.bIfaceIndex);
390 
391 	if (error)
392 		return (ENXIO);
393 
394 	hd = hid_start_parse(d_ptr, d_len, 1 << hid_input);
395 	if (hd == NULL)
396 		return (0);
397 	mdepth = 0;
398 	found = 0;
399 	while (hid_get_item(hd, &hi)) {
400 		switch (hi.kind) {
401 		case hid_collection:
402 			if (mdepth != 0)
403 				mdepth++;
404 			else if (hi.collection == 1 &&
405 			     hi.usage ==
406 			      HID_USAGE2(HUP_GENERIC_DESKTOP, HUG_MOUSE))
407 				mdepth++;
408 			break;
409 		case hid_endcollection:
410 			if (mdepth != 0)
411 				mdepth--;
412 			break;
413 		case hid_input:
414 			if (mdepth == 0)
415 				break;
416 			if (hi.usage ==
417 			     HID_USAGE2(HUP_GENERIC_DESKTOP, HUG_X) &&
418 			    (hi.flags & MOUSE_FLAGS_MASK) == MOUSE_FLAGS)
419 				found++;
420 			if (hi.usage ==
421 			     HID_USAGE2(HUP_GENERIC_DESKTOP, HUG_Y) &&
422 			    (hi.flags & MOUSE_FLAGS_MASK) == MOUSE_FLAGS)
423 				found++;
424 			break;
425 		default:
426 			break;
427 		}
428 	}
429 	hid_end_parse(hd);
430 	free(d_ptr, M_TEMP);
431 	return (found ? BUS_PROBE_DEFAULT : ENXIO);
432 }
433 
434 static void
435 ums_hid_parse(struct ums_softc *sc, device_t dev, const uint8_t *buf,
436     uint16_t len, uint8_t index)
437 {
438 	struct ums_info *info = &sc->sc_info[index];
439 	uint32_t flags;
440 	uint8_t i;
441 	uint8_t j;
442 
443 	if (hid_locate(buf, len, HID_USAGE2(HUP_GENERIC_DESKTOP, HUG_X),
444 	    hid_input, index, &info->sc_loc_x, &flags, &info->sc_iid_x)) {
445 
446 		if ((flags & MOUSE_FLAGS_MASK) == MOUSE_FLAGS) {
447 			info->sc_flags |= UMS_FLAG_X_AXIS;
448 		}
449 	}
450 	if (hid_locate(buf, len, HID_USAGE2(HUP_GENERIC_DESKTOP, HUG_Y),
451 	    hid_input, index, &info->sc_loc_y, &flags, &info->sc_iid_y)) {
452 
453 		if ((flags & MOUSE_FLAGS_MASK) == MOUSE_FLAGS) {
454 			info->sc_flags |= UMS_FLAG_Y_AXIS;
455 		}
456 	}
457 	/* Try the wheel first as the Z activator since it's tradition. */
458 	if (hid_locate(buf, len, HID_USAGE2(HUP_GENERIC_DESKTOP,
459 	    HUG_WHEEL), hid_input, index, &info->sc_loc_z, &flags,
460 	    &info->sc_iid_z) ||
461 	    hid_locate(buf, len, HID_USAGE2(HUP_GENERIC_DESKTOP,
462 	    HUG_TWHEEL), hid_input, index, &info->sc_loc_z, &flags,
463 	    &info->sc_iid_z)) {
464 		if ((flags & MOUSE_FLAGS_MASK) == MOUSE_FLAGS) {
465 			info->sc_flags |= UMS_FLAG_Z_AXIS;
466 		}
467 		/*
468 		 * We might have both a wheel and Z direction, if so put
469 		 * put the Z on the W coordinate.
470 		 */
471 		if (hid_locate(buf, len, HID_USAGE2(HUP_GENERIC_DESKTOP,
472 		    HUG_Z), hid_input, index, &info->sc_loc_w, &flags,
473 		    &info->sc_iid_w)) {
474 
475 			if ((flags & MOUSE_FLAGS_MASK) == MOUSE_FLAGS) {
476 				info->sc_flags |= UMS_FLAG_W_AXIS;
477 			}
478 		}
479 	} else if (hid_locate(buf, len, HID_USAGE2(HUP_GENERIC_DESKTOP,
480 	    HUG_Z), hid_input, index, &info->sc_loc_z, &flags,
481 	    &info->sc_iid_z)) {
482 
483 		if ((flags & MOUSE_FLAGS_MASK) == MOUSE_FLAGS) {
484 			info->sc_flags |= UMS_FLAG_Z_AXIS;
485 		}
486 	}
487 	/*
488 	 * The Microsoft Wireless Intellimouse 2.0 reports it's wheel
489 	 * using 0x0048, which is HUG_TWHEEL, and seems to expect you
490 	 * to know that the byte after the wheel is the tilt axis.
491 	 * There are no other HID axis descriptors other than X,Y and
492 	 * TWHEEL
493 	 */
494 	if (hid_locate(buf, len, HID_USAGE2(HUP_GENERIC_DESKTOP,
495 	    HUG_TWHEEL), hid_input, index, &info->sc_loc_t,
496 	    &flags, &info->sc_iid_t)) {
497 
498 		info->sc_loc_t.pos += 8;
499 
500 		if ((flags & MOUSE_FLAGS_MASK) == MOUSE_FLAGS) {
501 			info->sc_flags |= UMS_FLAG_T_AXIS;
502 		}
503 	} else if (hid_locate(buf, len, HID_USAGE2(HUP_CONSUMER,
504 		HUC_AC_PAN), hid_input, index, &info->sc_loc_t,
505 		&flags, &info->sc_iid_t)) {
506 
507 		if ((flags & MOUSE_FLAGS_MASK) == MOUSE_FLAGS)
508 			info->sc_flags |= UMS_FLAG_T_AXIS;
509 	}
510 	/* figure out the number of buttons */
511 
512 	for (i = 0; i < UMS_BUTTON_MAX; i++) {
513 		if (!hid_locate(buf, len, HID_USAGE2(HUP_BUTTON, (i + 1)),
514 		    hid_input, index, &info->sc_loc_btn[i], NULL,
515 		    &info->sc_iid_btn[i])) {
516 			break;
517 		}
518 	}
519 
520 	/* detect other buttons */
521 
522 	for (j = 0; (i < UMS_BUTTON_MAX) && (j < 2); i++, j++) {
523 		if (!hid_locate(buf, len, HID_USAGE2(HUP_MICROSOFT, (j + 1)),
524 		    hid_input, index, &info->sc_loc_btn[i], NULL,
525 		    &info->sc_iid_btn[i])) {
526 			break;
527 		}
528 	}
529 
530 	info->sc_buttons = i;
531 
532 	if (i > sc->sc_buttons)
533 		sc->sc_buttons = i;
534 
535 	if (info->sc_flags == 0)
536 		return;
537 
538 	/* announce information about the mouse */
539 	device_printf(dev, "%d buttons and [%s%s%s%s%s] coordinates ID=%u\n",
540 	    (info->sc_buttons),
541 	    (info->sc_flags & UMS_FLAG_X_AXIS) ? "X" : "",
542 	    (info->sc_flags & UMS_FLAG_Y_AXIS) ? "Y" : "",
543 	    (info->sc_flags & UMS_FLAG_Z_AXIS) ? "Z" : "",
544 	    (info->sc_flags & UMS_FLAG_T_AXIS) ? "T" : "",
545 	    (info->sc_flags & UMS_FLAG_W_AXIS) ? "W" : "",
546 	    info->sc_iid_x);
547 }
548 
549 static int
550 ums_attach(device_t dev)
551 {
552 	struct usb_attach_arg *uaa = device_get_ivars(dev);
553 	struct ums_softc *sc = device_get_softc(dev);
554 	struct ums_info *info;
555 	void *d_ptr = NULL;
556 	int isize;
557 	int err;
558 	uint16_t d_len;
559 	uint8_t i;
560 #ifdef USB_DEBUG
561 	uint8_t j;
562 #endif
563 
564 	DPRINTFN(11, "sc=%p\n", sc);
565 
566 	device_set_usb_desc(dev);
567 
568 	mtx_init(&sc->sc_mtx, "ums lock", NULL, MTX_DEF | MTX_RECURSE);
569 
570 	usb_callout_init_mtx(&sc->sc_callout, &sc->sc_mtx, 0);
571 
572 	/*
573          * Force the report (non-boot) protocol.
574          *
575          * Mice without boot protocol support may choose not to implement
576          * Set_Protocol at all; Ignore any error.
577          */
578 	err = usbd_req_set_protocol(uaa->device, NULL,
579 	    uaa->info.bIfaceIndex, 1);
580 
581 	err = usbd_transfer_setup(uaa->device,
582 	    &uaa->info.bIfaceIndex, sc->sc_xfer, ums_config,
583 	    UMS_N_TRANSFER, sc, &sc->sc_mtx);
584 
585 	if (err) {
586 		DPRINTF("error=%s\n", usbd_errstr(err));
587 		goto detach;
588 	}
589 
590 	/* Get HID descriptor */
591 	err = usbd_req_get_hid_desc(uaa->device, NULL, &d_ptr,
592 	    &d_len, M_TEMP, uaa->info.bIfaceIndex);
593 
594 	if (err) {
595 		device_printf(dev, "error reading report description\n");
596 		goto detach;
597 	}
598 
599 	isize = hid_report_size(d_ptr, d_len, hid_input, &sc->sc_iid);
600 
601 	/*
602 	 * The Microsoft Wireless Notebook Optical Mouse seems to be in worse
603 	 * shape than the Wireless Intellimouse 2.0, as its X, Y, wheel, and
604 	 * all of its other button positions are all off. It also reports that
605 	 * it has two addional buttons and a tilt wheel.
606 	 */
607 	if (usb_test_quirk(uaa, UQ_MS_BAD_CLASS)) {
608 
609 		sc->sc_iid = 0;
610 
611 		info = &sc->sc_info[0];
612 		info->sc_flags = (UMS_FLAG_X_AXIS |
613 		    UMS_FLAG_Y_AXIS |
614 		    UMS_FLAG_Z_AXIS |
615 		    UMS_FLAG_SBU);
616 		info->sc_buttons = 3;
617 		isize = 5;
618 		/* 1st byte of descriptor report contains garbage */
619 		info->sc_loc_x.pos = 16;
620 		info->sc_loc_x.size = 8;
621 		info->sc_loc_y.pos = 24;
622 		info->sc_loc_y.size = 8;
623 		info->sc_loc_z.pos = 32;
624 		info->sc_loc_z.size = 8;
625 		info->sc_loc_btn[0].pos = 8;
626 		info->sc_loc_btn[0].size = 1;
627 		info->sc_loc_btn[1].pos = 9;
628 		info->sc_loc_btn[1].size = 1;
629 		info->sc_loc_btn[2].pos = 10;
630 		info->sc_loc_btn[2].size = 1;
631 
632 		/* Announce device */
633 		device_printf(dev, "3 buttons and [XYZ] "
634 		    "coordinates ID=0\n");
635 
636 	} else {
637 		/* Search the HID descriptor and announce device */
638 		for (i = 0; i < UMS_INFO_MAX; i++) {
639 			ums_hid_parse(sc, dev, d_ptr, d_len, i);
640 		}
641 	}
642 
643 	if (usb_test_quirk(uaa, UQ_MS_REVZ)) {
644 		info = &sc->sc_info[0];
645 		/* Some wheels need the Z axis reversed. */
646 		info->sc_flags |= UMS_FLAG_REVZ;
647 	}
648 	if (isize > (int)usbd_xfer_max_framelen(sc->sc_xfer[UMS_INTR_DT])) {
649 		DPRINTF("WARNING: report size, %d bytes, is larger "
650 		    "than interrupt size, %d bytes!\n", isize,
651 		    usbd_xfer_max_framelen(sc->sc_xfer[UMS_INTR_DT]));
652 	}
653 	free(d_ptr, M_TEMP);
654 	d_ptr = NULL;
655 
656 #ifdef USB_DEBUG
657 	for (j = 0; j < UMS_INFO_MAX; j++) {
658 		info = &sc->sc_info[j];
659 
660 		DPRINTF("sc=%p, index=%d\n", sc, j);
661 		DPRINTF("X\t%d/%d id=%d\n", info->sc_loc_x.pos,
662 		    info->sc_loc_x.size, info->sc_iid_x);
663 		DPRINTF("Y\t%d/%d id=%d\n", info->sc_loc_y.pos,
664 		    info->sc_loc_y.size, info->sc_iid_y);
665 		DPRINTF("Z\t%d/%d id=%d\n", info->sc_loc_z.pos,
666 		    info->sc_loc_z.size, info->sc_iid_z);
667 		DPRINTF("T\t%d/%d id=%d\n", info->sc_loc_t.pos,
668 		    info->sc_loc_t.size, info->sc_iid_t);
669 		DPRINTF("W\t%d/%d id=%d\n", info->sc_loc_w.pos,
670 		    info->sc_loc_w.size, info->sc_iid_w);
671 
672 		for (i = 0; i < info->sc_buttons; i++) {
673 			DPRINTF("B%d\t%d/%d id=%d\n",
674 			    i + 1, info->sc_loc_btn[i].pos,
675 			    info->sc_loc_btn[i].size, info->sc_iid_btn[i]);
676 		}
677 	}
678 	DPRINTF("size=%d, id=%d\n", isize, sc->sc_iid);
679 #endif
680 
681 	err = usb_fifo_attach(uaa->device, sc, &sc->sc_mtx,
682 	    &ums_fifo_methods, &sc->sc_fifo,
683 	    device_get_unit(dev), -1, uaa->info.bIfaceIndex,
684   	    UID_ROOT, GID_OPERATOR, 0644);
685 	if (err)
686 		goto detach;
687 
688 	SYSCTL_ADD_PROC(device_get_sysctl_ctx(dev),
689 	    SYSCTL_CHILDREN(device_get_sysctl_tree(dev)),
690 	    OID_AUTO, "parseinfo", CTLTYPE_STRING|CTLFLAG_RD,
691 	    sc, 0, ums_sysctl_handler_parseinfo,
692 	    "", "Dump of parsed HID report descriptor");
693 
694 	return (0);
695 
696 detach:
697 	if (d_ptr) {
698 		free(d_ptr, M_TEMP);
699 	}
700 	ums_detach(dev);
701 	return (ENOMEM);
702 }
703 
704 static int
705 ums_detach(device_t self)
706 {
707 	struct ums_softc *sc = device_get_softc(self);
708 
709 	DPRINTF("sc=%p\n", sc);
710 
711 	usb_fifo_detach(&sc->sc_fifo);
712 
713 	usbd_transfer_unsetup(sc->sc_xfer, UMS_N_TRANSFER);
714 
715 	usb_callout_drain(&sc->sc_callout);
716 
717 	mtx_destroy(&sc->sc_mtx);
718 
719 	return (0);
720 }
721 
722 static void
723 ums_start_read(struct usb_fifo *fifo)
724 {
725 	struct ums_softc *sc = usb_fifo_softc(fifo);
726 	int rate;
727 
728 	/* Check if we should override the default polling interval */
729 	rate = sc->sc_pollrate;
730 	/* Range check rate */
731 	if (rate > 1000)
732 		rate = 1000;
733 	/* Check for set rate */
734 	if ((rate > 0) && (sc->sc_xfer[UMS_INTR_DT] != NULL)) {
735 		DPRINTF("Setting pollrate = %d\n", rate);
736 		/* Stop current transfer, if any */
737 		usbd_transfer_stop(sc->sc_xfer[UMS_INTR_DT]);
738 		/* Set new interval */
739 		usbd_xfer_set_interval(sc->sc_xfer[UMS_INTR_DT], 1000 / rate);
740 		/* Only set pollrate once */
741 		sc->sc_pollrate = 0;
742 	}
743 
744 	usbd_transfer_start(sc->sc_xfer[UMS_INTR_DT]);
745 }
746 
747 static void
748 ums_stop_read(struct usb_fifo *fifo)
749 {
750 	struct ums_softc *sc = usb_fifo_softc(fifo);
751 
752 	usbd_transfer_stop(sc->sc_xfer[UMS_INTR_DT]);
753 	usb_callout_stop(&sc->sc_callout);
754 }
755 
756 
757 #if ((MOUSE_SYS_PACKETSIZE != 8) || \
758      (MOUSE_MSC_PACKETSIZE != 5))
759 #error "Software assumptions are not met. Please update code."
760 #endif
761 
762 static void
763 ums_put_queue(struct ums_softc *sc, int32_t dx, int32_t dy,
764     int32_t dz, int32_t dt, int32_t buttons)
765 {
766 	uint8_t buf[8];
767 
768 	if (1) {
769 
770 		if (dx > 254)
771 			dx = 254;
772 		if (dx < -256)
773 			dx = -256;
774 		if (dy > 254)
775 			dy = 254;
776 		if (dy < -256)
777 			dy = -256;
778 		if (dz > 126)
779 			dz = 126;
780 		if (dz < -128)
781 			dz = -128;
782 		if (dt > 126)
783 			dt = 126;
784 		if (dt < -128)
785 			dt = -128;
786 
787 		buf[0] = sc->sc_mode.syncmask[1];
788 		buf[0] |= (~buttons) & MOUSE_MSC_BUTTONS;
789 		buf[1] = dx >> 1;
790 		buf[2] = dy >> 1;
791 		buf[3] = dx - (dx >> 1);
792 		buf[4] = dy - (dy >> 1);
793 
794 		if (sc->sc_mode.level == 1) {
795 			buf[5] = dz >> 1;
796 			buf[6] = dz - (dz >> 1);
797 			buf[7] = (((~buttons) >> 3) & MOUSE_SYS_EXTBUTTONS);
798 		}
799 		usb_fifo_put_data_linear(sc->sc_fifo.fp[USB_FIFO_RX], buf,
800 		    sc->sc_mode.packetsize, 1);
801 
802 	} else {
803 		DPRINTF("Buffer full, discarded packet\n");
804 	}
805 }
806 
807 static void
808 ums_reset_buf(struct ums_softc *sc)
809 {
810 	/* reset read queue, must be called locked */
811 	usb_fifo_reset(sc->sc_fifo.fp[USB_FIFO_RX]);
812 }
813 
814 static int
815 ums_open(struct usb_fifo *fifo, int fflags)
816 {
817 	struct ums_softc *sc = usb_fifo_softc(fifo);
818 
819 	DPRINTFN(2, "\n");
820 
821 	/* check for duplicate open, should not happen */
822 	if (sc->sc_fflags & fflags)
823 		return (EBUSY);
824 
825 	/* check for first open */
826 	if (sc->sc_fflags == 0) {
827 
828 		/* reset all USB mouse parameters */
829 
830 		if (sc->sc_buttons > MOUSE_MSC_MAXBUTTON)
831 			sc->sc_hw.buttons = MOUSE_MSC_MAXBUTTON;
832 		else
833 			sc->sc_hw.buttons = sc->sc_buttons;
834 
835 		sc->sc_hw.iftype = MOUSE_IF_USB;
836 		sc->sc_hw.type = MOUSE_MOUSE;
837 		sc->sc_hw.model = MOUSE_MODEL_GENERIC;
838 		sc->sc_hw.hwid = 0;
839 
840 		sc->sc_mode.protocol = MOUSE_PROTO_MSC;
841 		sc->sc_mode.rate = -1;
842 		sc->sc_mode.resolution = MOUSE_RES_UNKNOWN;
843 		sc->sc_mode.accelfactor = 0;
844 		sc->sc_mode.level = 0;
845 		sc->sc_mode.packetsize = MOUSE_MSC_PACKETSIZE;
846 		sc->sc_mode.syncmask[0] = MOUSE_MSC_SYNCMASK;
847 		sc->sc_mode.syncmask[1] = MOUSE_MSC_SYNC;
848 
849 		/* reset status */
850 
851 		sc->sc_status.flags = 0;
852 		sc->sc_status.button = 0;
853 		sc->sc_status.obutton = 0;
854 		sc->sc_status.dx = 0;
855 		sc->sc_status.dy = 0;
856 		sc->sc_status.dz = 0;
857 		/* sc->sc_status.dt = 0; */
858 	}
859 
860 	if (fflags & FREAD) {
861 		/* allocate RX buffer */
862 		if (usb_fifo_alloc_buffer(fifo,
863 		    UMS_BUF_SIZE, UMS_IFQ_MAXLEN)) {
864 			return (ENOMEM);
865 		}
866 	}
867 
868 	sc->sc_fflags |= fflags & (FREAD | FWRITE);
869 	return (0);
870 }
871 
872 static void
873 ums_close(struct usb_fifo *fifo, int fflags)
874 {
875 	struct ums_softc *sc = usb_fifo_softc(fifo);
876 
877 	DPRINTFN(2, "\n");
878 
879 	if (fflags & FREAD)
880 		usb_fifo_free_buffer(fifo);
881 
882 	sc->sc_fflags &= ~(fflags & (FREAD | FWRITE));
883 }
884 
885 static int
886 ums_ioctl(struct usb_fifo *fifo, u_long cmd, void *addr, int fflags)
887 {
888 	struct ums_softc *sc = usb_fifo_softc(fifo);
889 	mousemode_t mode;
890 	int error = 0;
891 
892 	DPRINTFN(2, "\n");
893 
894 	mtx_lock(&sc->sc_mtx);
895 
896 	switch (cmd) {
897 	case MOUSE_GETHWINFO:
898 		*(mousehw_t *)addr = sc->sc_hw;
899 		break;
900 
901 	case MOUSE_GETMODE:
902 		*(mousemode_t *)addr = sc->sc_mode;
903 		break;
904 
905 	case MOUSE_SETMODE:
906 		mode = *(mousemode_t *)addr;
907 
908 		if (mode.level == -1) {
909 			/* don't change the current setting */
910 		} else if ((mode.level < 0) || (mode.level > 1)) {
911 			error = EINVAL;
912 			break;
913 		} else {
914 			sc->sc_mode.level = mode.level;
915 		}
916 
917 		/* store polling rate */
918 		sc->sc_pollrate = mode.rate;
919 
920 		if (sc->sc_mode.level == 0) {
921 			if (sc->sc_buttons > MOUSE_MSC_MAXBUTTON)
922 				sc->sc_hw.buttons = MOUSE_MSC_MAXBUTTON;
923 			else
924 				sc->sc_hw.buttons = sc->sc_buttons;
925 			sc->sc_mode.protocol = MOUSE_PROTO_MSC;
926 			sc->sc_mode.packetsize = MOUSE_MSC_PACKETSIZE;
927 			sc->sc_mode.syncmask[0] = MOUSE_MSC_SYNCMASK;
928 			sc->sc_mode.syncmask[1] = MOUSE_MSC_SYNC;
929 		} else if (sc->sc_mode.level == 1) {
930 			if (sc->sc_buttons > MOUSE_SYS_MAXBUTTON)
931 				sc->sc_hw.buttons = MOUSE_SYS_MAXBUTTON;
932 			else
933 				sc->sc_hw.buttons = sc->sc_buttons;
934 			sc->sc_mode.protocol = MOUSE_PROTO_SYSMOUSE;
935 			sc->sc_mode.packetsize = MOUSE_SYS_PACKETSIZE;
936 			sc->sc_mode.syncmask[0] = MOUSE_SYS_SYNCMASK;
937 			sc->sc_mode.syncmask[1] = MOUSE_SYS_SYNC;
938 		}
939 		ums_reset_buf(sc);
940 		break;
941 
942 	case MOUSE_GETLEVEL:
943 		*(int *)addr = sc->sc_mode.level;
944 		break;
945 
946 	case MOUSE_SETLEVEL:
947 		if (*(int *)addr < 0 || *(int *)addr > 1) {
948 			error = EINVAL;
949 			break;
950 		}
951 		sc->sc_mode.level = *(int *)addr;
952 
953 		if (sc->sc_mode.level == 0) {
954 			if (sc->sc_buttons > MOUSE_MSC_MAXBUTTON)
955 				sc->sc_hw.buttons = MOUSE_MSC_MAXBUTTON;
956 			else
957 				sc->sc_hw.buttons = sc->sc_buttons;
958 			sc->sc_mode.protocol = MOUSE_PROTO_MSC;
959 			sc->sc_mode.packetsize = MOUSE_MSC_PACKETSIZE;
960 			sc->sc_mode.syncmask[0] = MOUSE_MSC_SYNCMASK;
961 			sc->sc_mode.syncmask[1] = MOUSE_MSC_SYNC;
962 		} else if (sc->sc_mode.level == 1) {
963 			if (sc->sc_buttons > MOUSE_SYS_MAXBUTTON)
964 				sc->sc_hw.buttons = MOUSE_SYS_MAXBUTTON;
965 			else
966 				sc->sc_hw.buttons = sc->sc_buttons;
967 			sc->sc_mode.protocol = MOUSE_PROTO_SYSMOUSE;
968 			sc->sc_mode.packetsize = MOUSE_SYS_PACKETSIZE;
969 			sc->sc_mode.syncmask[0] = MOUSE_SYS_SYNCMASK;
970 			sc->sc_mode.syncmask[1] = MOUSE_SYS_SYNC;
971 		}
972 		ums_reset_buf(sc);
973 		break;
974 
975 	case MOUSE_GETSTATUS:{
976 			mousestatus_t *status = (mousestatus_t *)addr;
977 
978 			*status = sc->sc_status;
979 			sc->sc_status.obutton = sc->sc_status.button;
980 			sc->sc_status.button = 0;
981 			sc->sc_status.dx = 0;
982 			sc->sc_status.dy = 0;
983 			sc->sc_status.dz = 0;
984 			/* sc->sc_status.dt = 0; */
985 
986 			if (status->dx || status->dy || status->dz /* || status->dt */ ) {
987 				status->flags |= MOUSE_POSCHANGED;
988 			}
989 			if (status->button != status->obutton) {
990 				status->flags |= MOUSE_BUTTONSCHANGED;
991 			}
992 			break;
993 		}
994 	default:
995 		error = ENOTTY;
996 		break;
997 	}
998 
999 	mtx_unlock(&sc->sc_mtx);
1000 	return (error);
1001 }
1002 
1003 static int
1004 ums_sysctl_handler_parseinfo(SYSCTL_HANDLER_ARGS)
1005 {
1006 	struct ums_softc *sc = arg1;
1007 	struct ums_info *info;
1008 	struct sbuf *sb;
1009 	int i, j, err, had_output;
1010 
1011 	sb = sbuf_new_auto();
1012 	for (i = 0, had_output = 0; i < UMS_INFO_MAX; i++) {
1013 		info = &sc->sc_info[i];
1014 
1015 		/* Don't emit empty info */
1016 		if ((info->sc_flags &
1017 		    (UMS_FLAG_X_AXIS | UMS_FLAG_Y_AXIS | UMS_FLAG_Z_AXIS |
1018 		     UMS_FLAG_T_AXIS | UMS_FLAG_W_AXIS)) == 0 &&
1019 		    info->sc_buttons == 0)
1020 			continue;
1021 
1022 		if (had_output)
1023 			sbuf_printf(sb, "\n");
1024 		had_output = 1;
1025 		sbuf_printf(sb, "i%d:", i + 1);
1026 		if (info->sc_flags & UMS_FLAG_X_AXIS)
1027 			sbuf_printf(sb, " X:r%d, p%d, s%d;",
1028 			    (int)info->sc_iid_x,
1029 			    (int)info->sc_loc_x.pos,
1030 			    (int)info->sc_loc_x.size);
1031 		if (info->sc_flags & UMS_FLAG_Y_AXIS)
1032 			sbuf_printf(sb, " Y:r%d, p%d, s%d;",
1033 			    (int)info->sc_iid_y,
1034 			    (int)info->sc_loc_y.pos,
1035 			    (int)info->sc_loc_y.size);
1036 		if (info->sc_flags & UMS_FLAG_Z_AXIS)
1037 			sbuf_printf(sb, " Z:r%d, p%d, s%d;",
1038 			    (int)info->sc_iid_z,
1039 			    (int)info->sc_loc_z.pos,
1040 			    (int)info->sc_loc_z.size);
1041 		if (info->sc_flags & UMS_FLAG_T_AXIS)
1042 			sbuf_printf(sb, " T:r%d, p%d, s%d;",
1043 			    (int)info->sc_iid_t,
1044 			    (int)info->sc_loc_t.pos,
1045 			    (int)info->sc_loc_t.size);
1046 		if (info->sc_flags & UMS_FLAG_W_AXIS)
1047 			sbuf_printf(sb, " W:r%d, p%d, s%d;",
1048 			    (int)info->sc_iid_w,
1049 			    (int)info->sc_loc_w.pos,
1050 			    (int)info->sc_loc_w.size);
1051 
1052 		for (j = 0; j < info->sc_buttons; j++) {
1053 			sbuf_printf(sb, " B%d:r%d, p%d, s%d;", j + 1,
1054 			    (int)info->sc_iid_btn[j],
1055 			    (int)info->sc_loc_btn[j].pos,
1056 			    (int)info->sc_loc_btn[j].size);
1057 		}
1058 	}
1059 	sbuf_finish(sb);
1060 	err = SYSCTL_OUT(req, sbuf_data(sb), sbuf_len(sb) + 1);
1061 	sbuf_delete(sb);
1062 
1063 	return (err);
1064 }
1065 
1066 static devclass_t ums_devclass;
1067 
1068 static device_method_t ums_methods[] = {
1069 	DEVMETHOD(device_probe, ums_probe),
1070 	DEVMETHOD(device_attach, ums_attach),
1071 	DEVMETHOD(device_detach, ums_detach),
1072 	{0, 0}
1073 };
1074 
1075 static driver_t ums_driver = {
1076 	.name = "ums",
1077 	.methods = ums_methods,
1078 	.size = sizeof(struct ums_softc),
1079 };
1080 
1081 DRIVER_MODULE(ums, uhub, ums_driver, ums_devclass, NULL, 0);
1082 MODULE_DEPEND(ums, usb, 1, 1, 1);
1083 MODULE_VERSION(ums, 1);
1084