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