Bring in the entire FreeBSD-5 USB infrastructure. As of this commit my
[dragonfly.git] / sys / dev / usbmisc / ums / ums.c
1 /*
2  * $FreeBSD: src/sys/dev/usb/ums.c,v 1.64 2003/11/09 09:17:22 tanimura Exp $
3  * $DragonFly: src/sys/dev/usbmisc/ums/ums.c,v 1.6 2003/12/30 01:01:47 dillon Exp $
4  */
5
6 /*
7  * Copyright (c) 1998 The NetBSD Foundation, Inc.
8  * All rights reserved.
9  *
10  * This code is derived from software contributed to The NetBSD Foundation
11  * by Lennart Augustsson (lennart@augustsson.net) at
12  * Carlstedt Research & Technology.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions and the following disclaimer.
19  * 2. Redistributions in binary form must reproduce the above copyright
20  *    notice, this list of conditions and the following disclaimer in the
21  *    documentation and/or other materials provided with the distribution.
22  * 3. All advertising materials mentioning features or use of this software
23  *    must display the following acknowledgement:
24  *        This product includes software developed by the NetBSD
25  *        Foundation, Inc. and its contributors.
26  * 4. Neither the name of The NetBSD Foundation nor the names of its
27  *    contributors may be used to endorse or promote products derived
28  *    from this software without specific prior written permission.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
31  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
32  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
33  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
34  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
35  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
36  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
37  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
38  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
39  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
40  * POSSIBILITY OF SUCH DAMAGE.
41  */
42
43 /*
44  * HID spec: http://www.usb.org/developers/data/devclass/hid1_1.pdf
45  */
46
47 #include <sys/param.h>
48 #include <sys/systm.h>
49 #include <sys/kernel.h>
50 #include <sys/malloc.h>
51 #include <sys/module.h>
52 #include <sys/bus.h>
53 #include <sys/ioccom.h>
54 #include <sys/conf.h>
55 #include <sys/tty.h>
56 #include <sys/file.h>
57 #if __FreeBSD_version >= 500014
58 #include <sys/selinfo.h>
59 #else
60 #include <sys/select.h>
61 #endif
62 #include <sys/vnode.h>
63 #include <sys/poll.h>
64 #include <sys/sysctl.h>
65
66 #include <bus/usb/usb.h>
67 #include <bus/usb/usbhid.h>
68
69 #include <bus/usb/usbdi.h>
70 #include <bus/usb/usbdi_util.h>
71 #include <bus/usb/usbdevs.h>
72 #include <bus/usb/usb_quirks.h>
73 #include <bus/usb/hid.h>
74
75 #if __FreeBSD_version >= 500000
76 #include <sys/mouse.h>
77 #else
78 #include <machine/mouse.h>
79 #endif
80
81 #ifdef USB_DEBUG
82 #define DPRINTF(x)      if (umsdebug) logprintf x
83 #define DPRINTFN(n,x)   if (umsdebug>(n)) logprintf x
84 int     umsdebug = 0;
85 SYSCTL_NODE(_hw_usb, OID_AUTO, ums, CTLFLAG_RW, 0, "USB ums");
86 SYSCTL_INT(_hw_usb_ums, OID_AUTO, debug, CTLFLAG_RW,
87            &umsdebug, 0, "ums debug level");
88 #else
89 #define DPRINTF(x)
90 #define DPRINTFN(n,x)
91 #endif
92
93 #define UMSUNIT(s)      (minor(s)&0x1f)
94
95 #define MS_TO_TICKS(ms) ((ms) * hz / 1000)
96
97 #define QUEUE_BUFSIZE   400     /* MUST be divisible by 5 _and_ 8 */
98
99 struct ums_softc {
100         device_t sc_dev;                /* base device */
101         usbd_interface_handle sc_iface; /* interface */
102         usbd_pipe_handle sc_intrpipe;   /* interrupt pipe */
103         int sc_ep_addr;
104
105         u_char *sc_ibuf;
106         u_int8_t sc_iid;
107         int sc_isize;
108         struct hid_location sc_loc_x, sc_loc_y, sc_loc_z;
109         struct hid_location *sc_loc_btn;
110
111         usb_callout_t callout_handle;   /* for spurious button ups */
112
113         int sc_enabled;
114         int sc_disconnected;    /* device is gone */
115
116         int flags;              /* device configuration */
117 #define UMS_Z           0x01    /* z direction available */
118 #define UMS_SPUR_BUT_UP 0x02    /* spurious button up events */
119         int nbuttons;
120 #define MAX_BUTTONS     7       /* chosen because sc_buttons is u_char */
121
122         u_char          qbuf[QUEUE_BUFSIZE];    /* must be divisable by 3&4 */
123         u_char          dummy[100];     /* XXX just for safety and for now */
124         int             qcount, qhead, qtail;
125         mousehw_t       hw;
126         mousemode_t     mode;
127         mousestatus_t   status;
128
129         int             state;
130 #         define        UMS_ASLEEP      0x01    /* readFromDevice is waiting */
131 #         define        UMS_SELECT      0x02    /* select is waiting */
132         struct selinfo  rsel;           /* process waiting in select */
133
134         dev_t           dev;            /* specfs */
135 };
136
137 #define MOUSE_FLAGS_MASK (HIO_CONST|HIO_RELATIVE)
138 #define MOUSE_FLAGS (HIO_RELATIVE)
139
140 Static void ums_intr(usbd_xfer_handle xfer,
141                           usbd_private_handle priv, usbd_status status);
142
143 Static void ums_add_to_queue(struct ums_softc *sc,
144                                 int dx, int dy, int dz, int buttons);
145 Static void ums_add_to_queue_timeout(void *priv);
146
147 Static int  ums_enable(void *);
148 Static void ums_disable(void *);
149
150 Static d_open_t  ums_open;
151 Static d_close_t ums_close;
152 Static d_read_t  ums_read;
153 Static d_ioctl_t ums_ioctl;
154 Static d_poll_t  ums_poll;
155
156 #define UMS_CDEV_MAJOR  111
157
158 Static struct cdevsw ums_cdevsw = {
159         /* name */      "ums",
160         /* maj */       UMS_CDEV_MAJOR,
161         /* flags */     0,
162         /* port */      NULL,
163         /* autoq */     0,
164
165         /* open */      ums_open,
166         /* close */     ums_close,
167         /* read */      ums_read,
168         /* write */     nowrite,
169         /* ioctl */     ums_ioctl,
170         /* poll */      ums_poll,
171         /* mmap */      nommap,
172         /* strategy */  nostrategy,
173         /* dump */      nodump,
174         /* psize */     nopsize
175 };
176
177 USB_DECLARE_DRIVER(ums);
178
179 USB_MATCH(ums)
180 {
181         USB_MATCH_START(ums, uaa);
182         usb_interface_descriptor_t *id;
183         int size, ret;
184         void *desc;
185         usbd_status err;
186
187         if (!uaa->iface)
188                 return (UMATCH_NONE);
189         id = usbd_get_interface_descriptor(uaa->iface);
190         if (!id || id->bInterfaceClass != UICLASS_HID)
191                 return (UMATCH_NONE);
192
193         err = usbd_read_report_desc(uaa->iface, &desc, &size, M_TEMP);
194         if (err)
195                 return (UMATCH_NONE);
196
197         if (hid_is_collection(desc, size,
198                               HID_USAGE2(HUP_GENERIC_DESKTOP, HUG_MOUSE)))
199                 ret = UMATCH_IFACECLASS;
200         else
201                 ret = UMATCH_NONE;
202
203         free(desc, M_TEMP);
204         return (ret);
205 }
206
207 USB_ATTACH(ums)
208 {
209         USB_ATTACH_START(ums, sc, uaa);
210         usbd_interface_handle iface = uaa->iface;
211         usb_interface_descriptor_t *id;
212         usb_endpoint_descriptor_t *ed;
213         int size;
214         void *desc;
215         usbd_status err;
216         char devinfo[1024];
217         u_int32_t flags;
218         int i;
219         struct hid_location loc_btn;
220
221         sc->sc_disconnected = 1;
222         sc->sc_iface = iface;
223         id = usbd_get_interface_descriptor(iface);
224         usbd_devinfo(uaa->device, 0, devinfo);
225         USB_ATTACH_SETUP;
226         printf("%s: %s, iclass %d/%d\n", USBDEVNAME(sc->sc_dev),
227                devinfo, id->bInterfaceClass, id->bInterfaceSubClass);
228         ed = usbd_interface2endpoint_descriptor(iface, 0);
229         if (!ed) {
230                 printf("%s: could not read endpoint descriptor\n",
231                        USBDEVNAME(sc->sc_dev));
232                 USB_ATTACH_ERROR_RETURN;
233         }
234
235         DPRINTFN(10,("ums_attach: bLength=%d bDescriptorType=%d "
236                      "bEndpointAddress=%d-%s bmAttributes=%d wMaxPacketSize=%d"
237                      " bInterval=%d\n",
238                      ed->bLength, ed->bDescriptorType,
239                      UE_GET_ADDR(ed->bEndpointAddress),
240                      UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN ? "in":"out",
241                      UE_GET_XFERTYPE(ed->bmAttributes),
242                      UGETW(ed->wMaxPacketSize), ed->bInterval));
243
244         if (UE_GET_DIR(ed->bEndpointAddress) != UE_DIR_IN ||
245             UE_GET_XFERTYPE(ed->bmAttributes) != UE_INTERRUPT) {
246                 printf("%s: unexpected endpoint\n",
247                        USBDEVNAME(sc->sc_dev));
248                 USB_ATTACH_ERROR_RETURN;
249         }
250
251         err = usbd_read_report_desc(uaa->iface, &desc, &size, M_TEMP);
252         if (err)
253                 USB_ATTACH_ERROR_RETURN;
254
255         if (!hid_locate(desc, size, HID_USAGE2(HUP_GENERIC_DESKTOP, HUG_X),
256                        hid_input, &sc->sc_loc_x, &flags)) {
257                 printf("%s: mouse has no X report\n", USBDEVNAME(sc->sc_dev));
258                 USB_ATTACH_ERROR_RETURN;
259         }
260         if ((flags & MOUSE_FLAGS_MASK) != MOUSE_FLAGS) {
261                 printf("%s: X report 0x%04x not supported\n",
262                        USBDEVNAME(sc->sc_dev), flags);
263                 USB_ATTACH_ERROR_RETURN;
264         }
265
266         if (!hid_locate(desc, size, HID_USAGE2(HUP_GENERIC_DESKTOP, HUG_Y),
267                        hid_input, &sc->sc_loc_y, &flags)) {
268                 printf("%s: mouse has no Y report\n", USBDEVNAME(sc->sc_dev));
269                 USB_ATTACH_ERROR_RETURN;
270         }
271         if ((flags & MOUSE_FLAGS_MASK) != MOUSE_FLAGS) {
272                 printf("%s: Y report 0x%04x not supported\n",
273                        USBDEVNAME(sc->sc_dev), flags);
274                 USB_ATTACH_ERROR_RETURN;
275         }
276
277         /* try to guess the Z activator: first check Z, then WHEEL */
278         if (hid_locate(desc, size, HID_USAGE2(HUP_GENERIC_DESKTOP, HUG_Z),
279                        hid_input, &sc->sc_loc_z, &flags) ||
280             hid_locate(desc, size, HID_USAGE2(HUP_GENERIC_DESKTOP, HUG_WHEEL),
281                        hid_input, &sc->sc_loc_z, &flags)) {
282                 if ((flags & MOUSE_FLAGS_MASK) != MOUSE_FLAGS) {
283                         sc->sc_loc_z.size = 0;  /* Bad Z coord, ignore it */
284                 } else {
285                         sc->flags |= UMS_Z;
286                 }
287         }
288
289         /* figure out the number of buttons */
290         for (i = 1; i <= MAX_BUTTONS; i++)
291                 if (!hid_locate(desc, size, HID_USAGE2(HUP_BUTTON, i),
292                                 hid_input, &loc_btn, 0))
293                         break;
294         sc->nbuttons = i - 1;
295         sc->sc_loc_btn = malloc(sizeof(struct hid_location)*sc->nbuttons,
296                                 M_USBDEV, M_NOWAIT);
297         if (!sc->sc_loc_btn) {
298                 printf("%s: no memory\n", USBDEVNAME(sc->sc_dev));
299                 USB_ATTACH_ERROR_RETURN;
300         }
301
302         printf("%s: %d buttons%s\n", USBDEVNAME(sc->sc_dev),
303                sc->nbuttons, sc->flags & UMS_Z? " and Z dir." : "");
304
305         for (i = 1; i <= sc->nbuttons; i++)
306                 hid_locate(desc, size, HID_USAGE2(HUP_BUTTON, i),
307                                 hid_input, &sc->sc_loc_btn[i-1], 0);
308
309         sc->sc_isize = hid_report_size(desc, size, hid_input, &sc->sc_iid);
310         sc->sc_ibuf = malloc(sc->sc_isize, M_USB, M_NOWAIT);
311         if (!sc->sc_ibuf) {
312                 printf("%s: no memory\n", USBDEVNAME(sc->sc_dev));
313                 free(sc->sc_loc_btn, M_USB);
314                 USB_ATTACH_ERROR_RETURN;
315         }
316
317         sc->sc_ep_addr = ed->bEndpointAddress;
318         sc->sc_disconnected = 0;
319         free(desc, M_TEMP);
320
321 #ifdef USB_DEBUG
322         DPRINTF(("ums_attach: sc=%p\n", sc));
323         DPRINTF(("ums_attach: X\t%d/%d\n",
324                  sc->sc_loc_x.pos, sc->sc_loc_x.size));
325         DPRINTF(("ums_attach: Y\t%d/%d\n",
326                  sc->sc_loc_y.pos, sc->sc_loc_y.size));
327         if (sc->flags & UMS_Z)
328                 DPRINTF(("ums_attach: Z\t%d/%d\n",
329                          sc->sc_loc_z.pos, sc->sc_loc_z.size));
330         for (i = 1; i <= sc->nbuttons; i++) {
331                 DPRINTF(("ums_attach: B%d\t%d/%d\n",
332                          i, sc->sc_loc_btn[i-1].pos,sc->sc_loc_btn[i-1].size));
333         }
334         DPRINTF(("ums_attach: size=%d, id=%d\n", sc->sc_isize, sc->sc_iid));
335 #endif
336
337         if (sc->nbuttons > MOUSE_MSC_MAXBUTTON)
338                 sc->hw.buttons = MOUSE_MSC_MAXBUTTON;
339         else
340                 sc->hw.buttons = sc->nbuttons;
341         sc->hw.iftype = MOUSE_IF_USB;
342         sc->hw.type = MOUSE_MOUSE;
343         sc->hw.model = MOUSE_MODEL_GENERIC;
344         sc->hw.hwid = 0;
345         sc->mode.protocol = MOUSE_PROTO_MSC;
346         sc->mode.rate = -1;
347         sc->mode.resolution = MOUSE_RES_UNKNOWN;
348         sc->mode.accelfactor = 0;
349         sc->mode.level = 0;
350         sc->mode.packetsize = MOUSE_MSC_PACKETSIZE;
351         sc->mode.syncmask[0] = MOUSE_MSC_SYNCMASK;
352         sc->mode.syncmask[1] = MOUSE_MSC_SYNC;
353
354         sc->status.flags = 0;
355         sc->status.button = sc->status.obutton = 0;
356         sc->status.dx = sc->status.dy = sc->status.dz = 0;
357
358 #ifndef __FreeBSD__
359         sc->rsel.si_flags = 0;
360         sc->rsel.si_pid = 0;
361 #endif
362
363         sc->dev = make_dev(&ums_cdevsw, device_get_unit(self),
364                         UID_ROOT, GID_OPERATOR,
365                         0644, "ums%d", device_get_unit(self));
366
367         if (usbd_get_quirks(uaa->device)->uq_flags & UQ_SPUR_BUT_UP) {
368                 DPRINTF(("%s: Spurious button up events\n",
369                         USBDEVNAME(sc->sc_dev)));
370                 sc->flags |= UMS_SPUR_BUT_UP;
371         }
372
373         USB_ATTACH_SUCCESS_RETURN;
374 }
375
376
377 Static int
378 ums_detach(device_t self)
379 {
380         struct ums_softc *sc = device_get_softc(self);
381
382         if (sc->sc_enabled)
383                 ums_disable(sc);
384
385         DPRINTF(("%s: disconnected\n", USBDEVNAME(self)));
386
387         free(sc->sc_loc_btn, M_USB);
388         free(sc->sc_ibuf, M_USB);
389
390         /* someone waiting for data */
391         /*
392          * XXX If we wakeup the process here, the device will be gone by
393          * the time the process gets a chance to notice. *_close and friends
394          * should be fixed to handle this case.
395          * Or we should do a delayed detach for this.
396          * Does this delay now force tsleep to exit with an error?
397          */
398         if (sc->state & UMS_ASLEEP) {
399                 sc->state &= ~UMS_ASLEEP;
400                 wakeup(sc);
401         }
402         if (sc->state & UMS_SELECT) {
403                 sc->state &= ~UMS_SELECT;
404                 selwakeuppri(&sc->rsel, PZERO);
405         }
406
407         destroy_dev(sc->dev);
408
409         return 0;
410 }
411
412 void
413 ums_intr(xfer, addr, status)
414         usbd_xfer_handle xfer;
415         usbd_private_handle addr;
416         usbd_status status;
417 {
418         struct ums_softc *sc = addr;
419         u_char *ibuf;
420         int dx, dy, dz;
421         u_char buttons = 0;
422         int i;
423
424 #define UMS_BUT(i) ((i) < 3 ? (((i) + 2) % 3) : (i))
425
426         DPRINTFN(5, ("ums_intr: sc=%p status=%d\n", sc, status));
427         DPRINTFN(5, ("ums_intr: data = %02x %02x %02x\n",
428                      sc->sc_ibuf[0], sc->sc_ibuf[1], sc->sc_ibuf[2]));
429
430         if (status == USBD_CANCELLED)
431                 return;
432
433         if (status != USBD_NORMAL_COMPLETION) {
434                 DPRINTF(("ums_intr: status=%d\n", status));
435                 if (status == USBD_STALLED)
436                     usbd_clear_endpoint_stall_async(sc->sc_intrpipe);
437                 return;
438         }
439
440         ibuf = sc->sc_ibuf;
441         if (sc->sc_iid) {
442                 if (*ibuf++ != sc->sc_iid)
443                         return;
444         }
445
446         dx =  hid_get_data(ibuf, &sc->sc_loc_x);
447         dy = -hid_get_data(ibuf, &sc->sc_loc_y);
448         dz = -hid_get_data(ibuf, &sc->sc_loc_z);
449         for (i = 0; i < sc->nbuttons; i++)
450                 if (hid_get_data(ibuf, &sc->sc_loc_btn[i]))
451                         buttons |= (1 << UMS_BUT(i));
452
453         if (dx || dy || dz || (sc->flags & UMS_Z)
454             || buttons != sc->status.button) {
455                 DPRINTFN(5, ("ums_intr: x:%d y:%d z:%d buttons:0x%x\n",
456                         dx, dy, dz, buttons));
457
458                 sc->status.button = buttons;
459                 sc->status.dx += dx;
460                 sc->status.dy += dy;
461                 sc->status.dz += dz;
462
463                 /* Discard data in case of full buffer */
464                 if (sc->qcount == sizeof(sc->qbuf)) {
465                         DPRINTF(("Buffer full, discarded packet"));
466                         return;
467                 }
468
469                 /*
470                  * The Qtronix keyboard has a built in PS/2 port for a mouse.
471                  * The firmware once in a while posts a spurious button up
472                  * event. This event we ignore by doing a timeout for 50 msecs.
473                  * If we receive dx=dy=dz=buttons=0 before we add the event to
474                  * the queue.
475                  * In any other case we delete the timeout event.
476                  */
477                 if (sc->flags & UMS_SPUR_BUT_UP &&
478                     dx == 0 && dy == 0 && dz == 0 && buttons == 0) {
479                         usb_callout(sc->callout_handle, MS_TO_TICKS(50 /*msecs*/),
480                                     ums_add_to_queue_timeout, (void *) sc);
481                 } else {
482                         usb_uncallout(sc->callout_handle,
483                                       ums_add_to_queue_timeout, (void *) sc);
484                         ums_add_to_queue(sc, dx, dy, dz, buttons);
485                 }
486         }
487 }
488
489 Static void
490 ums_add_to_queue_timeout(void *priv)
491 {
492         struct ums_softc *sc = priv;
493         int s;
494
495         s = splusb();
496         ums_add_to_queue(sc, 0, 0, 0, 0);
497         splx(s);
498 }
499
500 Static void
501 ums_add_to_queue(struct ums_softc *sc, int dx, int dy, int dz, int buttons)
502 {
503         /* Discard data in case of full buffer */
504         if (sc->qhead+sc->mode.packetsize > sizeof(sc->qbuf)) {
505                 DPRINTF(("Buffer full, discarded packet"));
506                 return;
507         }
508
509         if (dx >  254)          dx =  254;
510         if (dx < -256)          dx = -256;
511         if (dy >  254)          dy =  254;
512         if (dy < -256)          dy = -256;
513         if (dz >  126)          dz =  126;
514         if (dz < -128)          dz = -128;
515
516         sc->qbuf[sc->qhead] = sc->mode.syncmask[1];
517         sc->qbuf[sc->qhead] |= ~buttons & MOUSE_MSC_BUTTONS;
518         sc->qbuf[sc->qhead+1] = dx >> 1;
519         sc->qbuf[sc->qhead+2] = dy >> 1;
520         sc->qbuf[sc->qhead+3] = dx - (dx >> 1);
521         sc->qbuf[sc->qhead+4] = dy - (dy >> 1);
522
523         if (sc->mode.level == 1) {
524                 sc->qbuf[sc->qhead+5] = dz >> 1;
525                 sc->qbuf[sc->qhead+6] = dz - (dz >> 1);
526                 sc->qbuf[sc->qhead+7] = ((~buttons >> 3)
527                                          & MOUSE_SYS_EXTBUTTONS);
528         }
529
530         sc->qhead += sc->mode.packetsize;
531         sc->qcount += sc->mode.packetsize;
532         /* wrap round at end of buffer */
533         if (sc->qhead >= sizeof(sc->qbuf))
534                 sc->qhead = 0;
535
536         /* someone waiting for data */
537         if (sc->state & UMS_ASLEEP) {
538                 sc->state &= ~UMS_ASLEEP;
539                 wakeup(sc);
540         }
541         if (sc->state & UMS_SELECT) {
542                 sc->state &= ~UMS_SELECT;
543                 selwakeuppri(&sc->rsel, PZERO);
544         }
545 }
546 Static int
547 ums_enable(v)
548         void *v;
549 {
550         struct ums_softc *sc = v;
551
552         usbd_status err;
553
554         if (sc->sc_enabled)
555                 return EBUSY;
556
557         sc->sc_enabled = 1;
558         sc->qcount = 0;
559         sc->qhead = sc->qtail = 0;
560         sc->status.flags = 0;
561         sc->status.button = sc->status.obutton = 0;
562         sc->status.dx = sc->status.dy = sc->status.dz = 0;
563
564         callout_handle_init((struct callout_handle *)&sc->callout_handle);
565
566         /* Set up interrupt pipe. */
567         err = usbd_open_pipe_intr(sc->sc_iface, sc->sc_ep_addr,
568                                 USBD_SHORT_XFER_OK, &sc->sc_intrpipe, sc,
569                                 sc->sc_ibuf, sc->sc_isize, ums_intr,
570                                 USBD_DEFAULT_INTERVAL);
571         if (err) {
572                 DPRINTF(("ums_enable: usbd_open_pipe_intr failed, error=%d\n",
573                          err));
574                 sc->sc_enabled = 0;
575                 return (EIO);
576         }
577         return (0);
578 }
579
580 Static void
581 ums_disable(priv)
582         void *priv;
583 {
584         struct ums_softc *sc = priv;
585
586         usb_uncallout(sc->callout_handle, ums_add_to_queue_timeout, sc);
587
588         /* Disable interrupts. */
589         usbd_abort_pipe(sc->sc_intrpipe);
590         usbd_close_pipe(sc->sc_intrpipe);
591
592         sc->sc_enabled = 0;
593
594         if (sc->qcount != 0)
595                 DPRINTF(("Discarded %d bytes in queue\n", sc->qcount));
596 }
597
598 Static int
599 ums_open(dev_t dev, int flag, int fmt, usb_proc_ptr p)
600 {
601         struct ums_softc *sc;
602
603         USB_GET_SC_OPEN(ums, UMSUNIT(dev), sc);
604
605         return ums_enable(sc);
606 }
607
608 Static int
609 ums_close(dev_t dev, int flag, int fmt, usb_proc_ptr p)
610 {
611         struct ums_softc *sc;
612
613         USB_GET_SC(ums, UMSUNIT(dev), sc);
614
615         if (!sc)
616                 return 0;
617
618         if (sc->sc_enabled)
619                 ums_disable(sc);
620
621         return 0;
622 }
623
624 Static int
625 ums_read(dev_t dev, struct uio *uio, int flag)
626 {
627         struct ums_softc *sc;
628         int s;
629         char buf[sizeof(sc->qbuf)];
630         int l = 0;
631         int error;
632
633         USB_GET_SC(ums, UMSUNIT(dev), sc);
634
635         s = splusb();
636         if (!sc) {
637                 splx(s);
638                 return EIO;
639         }
640
641         while (sc->qcount == 0 )  {
642                 if (flag & IO_NDELAY) {         /* non-blocking I/O */
643                         splx(s);
644                         return EWOULDBLOCK;
645                 }
646
647                 sc->state |= UMS_ASLEEP;        /* blocking I/O */
648                 error = tsleep(sc, PCATCH, "umsrea", 0);
649                 if (error) {
650                         splx(s);
651                         return error;
652                 } else if (!sc->sc_enabled) {
653                         splx(s);
654                         return EINTR;
655                 }
656                 /* check whether the device is still there */
657
658                 sc = devclass_get_softc(ums_devclass, UMSUNIT(dev));
659                 if (!sc) {
660                         splx(s);
661                         return EIO;
662                 }
663         }
664
665         /*
666          * XXX we could optimise the use of splx/splusb somewhat. The writer
667          * process only extends qcount and qtail. We could copy them and use the copies
668          * to do the copying out of the queue.
669          */
670
671         while ((sc->qcount > 0) && (uio->uio_resid > 0)) {
672                 l = (sc->qcount < uio->uio_resid? sc->qcount:uio->uio_resid);
673                 if (l > sizeof(buf))
674                         l = sizeof(buf);
675                 if (l > sizeof(sc->qbuf) - sc->qtail)           /* transfer till end of buf */
676                         l = sizeof(sc->qbuf) - sc->qtail;
677
678                 splx(s);
679                 uiomove(&sc->qbuf[sc->qtail], l, uio);
680                 s = splusb();
681
682                 if ( sc->qcount - l < 0 ) {
683                         DPRINTF(("qcount below 0, count=%d l=%d\n", sc->qcount, l));
684                         sc->qcount = l;
685                 }
686                 sc->qcount -= l;        /* remove the bytes from the buffer */
687                 sc->qtail = (sc->qtail + l) % sizeof(sc->qbuf);
688         }
689         splx(s);
690
691         return 0;
692 }
693
694 Static int
695 ums_poll(dev_t dev, int events, usb_proc_ptr p)
696 {
697         struct ums_softc *sc;
698         int revents = 0;
699         int s;
700
701         USB_GET_SC(ums, UMSUNIT(dev), sc);
702
703         if (!sc)
704                 return 0;
705
706         s = splusb();
707         if (events & (POLLIN | POLLRDNORM)) {
708                 if (sc->qcount) {
709                         revents = events & (POLLIN | POLLRDNORM);
710                 } else {
711                         sc->state |= UMS_SELECT;
712                         selrecord(p, &sc->rsel);
713                 }
714         }
715         splx(s);
716
717         return revents;
718 }
719
720 int
721 ums_ioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, usb_proc_ptr p)
722 {
723         struct ums_softc *sc;
724         int error = 0;
725         int s;
726         mousemode_t mode;
727
728         USB_GET_SC(ums, UMSUNIT(dev), sc);
729
730         if (!sc)
731                 return EIO;
732
733         switch(cmd) {
734         case MOUSE_GETHWINFO:
735                 *(mousehw_t *)addr = sc->hw;
736                 break;
737         case MOUSE_GETMODE:
738                 *(mousemode_t *)addr = sc->mode;
739                 break;
740         case MOUSE_SETMODE:
741                 mode = *(mousemode_t *)addr;
742
743                 if (mode.level == -1)
744                         /* don't change the current setting */
745                         ;
746                 else if ((mode.level < 0) || (mode.level > 1))
747                         return (EINVAL);
748
749                 s = splusb();
750                 sc->mode.level = mode.level;
751
752                 if (sc->mode.level == 0) {
753                         if (sc->nbuttons > MOUSE_MSC_MAXBUTTON)
754                                 sc->hw.buttons = MOUSE_MSC_MAXBUTTON;
755                         else
756                                 sc->hw.buttons = sc->nbuttons;
757                         sc->mode.protocol = MOUSE_PROTO_MSC;
758                         sc->mode.packetsize = MOUSE_MSC_PACKETSIZE;
759                         sc->mode.syncmask[0] = MOUSE_MSC_SYNCMASK;
760                         sc->mode.syncmask[1] = MOUSE_MSC_SYNC;
761                 } else if (sc->mode.level == 1) {
762                         if (sc->nbuttons > MOUSE_SYS_MAXBUTTON)
763                                 sc->hw.buttons = MOUSE_SYS_MAXBUTTON;
764                         else
765                                 sc->hw.buttons = sc->nbuttons;
766                         sc->mode.protocol = MOUSE_PROTO_SYSMOUSE;
767                         sc->mode.packetsize = MOUSE_SYS_PACKETSIZE;
768                         sc->mode.syncmask[0] = MOUSE_SYS_SYNCMASK;
769                         sc->mode.syncmask[1] = MOUSE_SYS_SYNC;
770                 }
771
772                 bzero(sc->qbuf, sizeof(sc->qbuf));
773                 sc->qhead = sc->qtail = sc->qcount = 0;
774                 splx(s);
775
776                 break;
777         case MOUSE_GETLEVEL:
778                 *(int *)addr = sc->mode.level;
779                 break;
780         case MOUSE_SETLEVEL:
781                 if (*(int *)addr < 0 || *(int *)addr > 1)
782                         return (EINVAL);
783
784                 s = splusb();
785                 sc->mode.level = *(int *)addr;
786
787                 if (sc->mode.level == 0) {
788                         if (sc->nbuttons > MOUSE_MSC_MAXBUTTON)
789                                 sc->hw.buttons = MOUSE_MSC_MAXBUTTON;
790                         else
791                                 sc->hw.buttons = sc->nbuttons;
792                         sc->mode.protocol = MOUSE_PROTO_MSC;
793                         sc->mode.packetsize = MOUSE_MSC_PACKETSIZE;
794                         sc->mode.syncmask[0] = MOUSE_MSC_SYNCMASK;
795                         sc->mode.syncmask[1] = MOUSE_MSC_SYNC;
796                 } else if (sc->mode.level == 1) {
797                         if (sc->nbuttons > MOUSE_SYS_MAXBUTTON)
798                                 sc->hw.buttons = MOUSE_SYS_MAXBUTTON;
799                         else
800                                 sc->hw.buttons = sc->nbuttons;
801                         sc->mode.protocol = MOUSE_PROTO_SYSMOUSE;
802                         sc->mode.packetsize = MOUSE_SYS_PACKETSIZE;
803                         sc->mode.syncmask[0] = MOUSE_SYS_SYNCMASK;
804                         sc->mode.syncmask[1] = MOUSE_SYS_SYNC;
805                 }
806
807                 bzero(sc->qbuf, sizeof(sc->qbuf));
808                 sc->qhead = sc->qtail = sc->qcount = 0;
809                 splx(s);
810
811                 break;
812         case MOUSE_GETSTATUS: {
813                 mousestatus_t *status = (mousestatus_t *) addr;
814
815                 s = splusb();
816                 *status = sc->status;
817                 sc->status.obutton = sc->status.button;
818                 sc->status.button = 0;
819                 sc->status.dx = sc->status.dy = sc->status.dz = 0;
820                 splx(s);
821
822                 if (status->dx || status->dy || status->dz)
823                         status->flags |= MOUSE_POSCHANGED;
824                 if (status->button != status->obutton)
825                         status->flags |= MOUSE_BUTTONSCHANGED;
826                 break;
827                 }
828         default:
829                 error = ENOTTY;
830         }
831
832         return error;
833 }
834
835 DRIVER_MODULE(ums, uhub, ums_driver, ums_devclass, usbd_driver_load, 0);