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