kernel tree reorganization stage 1: Major cvs repository work (not logged as
[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.5 2003/08/07 21:17:15 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 <bus/usb/usb.h>
62 #include <bus/usb/usbhid.h>
63
64 #include <bus/usb/usbdi.h>
65 #include <bus/usb/usbdi_util.h>
66 #include <bus/usb/usbdevs.h>
67 #include <bus/usb/usb_quirks.h>
68 #include <bus/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         /* name */      "ums",
151         /* maj */       UMS_CDEV_MAJOR,
152         /* flags */     0,
153         /* port */      NULL,
154         /* autoq */     0,
155
156         /* open */      ums_open,
157         /* close */     ums_close,
158         /* read */      ums_read,
159         /* write */     nowrite,
160         /* ioctl */     ums_ioctl,
161         /* poll */      ums_poll,
162         /* mmap */      nommap,
163         /* strategy */  nostrategy,
164         /* dump */      nodump,
165         /* psize */     nopsize
166 };
167
168 USB_DECLARE_DRIVER(ums);
169
170 USB_MATCH(ums)
171 {
172         USB_MATCH_START(ums, uaa);
173         usb_interface_descriptor_t *id;
174         int size, ret;
175         void *desc;
176         usbd_status err;
177         
178         if (!uaa->iface)
179                 return (UMATCH_NONE);
180         id = usbd_get_interface_descriptor(uaa->iface);
181         if (!id || id->bInterfaceClass != UICLASS_HID)
182                 return (UMATCH_NONE);
183
184         err = usbd_alloc_report_desc(uaa->iface, &desc, &size, M_TEMP);
185         if (err)
186                 return (UMATCH_NONE);
187
188         if (hid_is_collection(desc, size, 
189                               HID_USAGE2(HUP_GENERIC_DESKTOP, HUG_MOUSE)))
190                 ret = UMATCH_IFACECLASS;
191         else
192                 ret = UMATCH_NONE;
193
194         free(desc, M_TEMP);
195         return (ret);
196 }
197
198 USB_ATTACH(ums)
199 {
200         USB_ATTACH_START(ums, sc, uaa);
201         usbd_interface_handle iface = uaa->iface;
202         usb_interface_descriptor_t *id;
203         usb_endpoint_descriptor_t *ed;
204         int size;
205         void *desc;
206         usbd_status err;
207         char devinfo[1024];
208         u_int32_t flags;
209         int i;
210         struct hid_location loc_btn;
211         
212         sc->sc_disconnected = 1;
213         sc->sc_iface = iface;
214         id = usbd_get_interface_descriptor(iface);
215         usbd_devinfo(uaa->device, 0, devinfo);
216         USB_ATTACH_SETUP;
217         printf("%s: %s, iclass %d/%d\n", USBDEVNAME(sc->sc_dev),
218                devinfo, id->bInterfaceClass, id->bInterfaceSubClass);
219         ed = usbd_interface2endpoint_descriptor(iface, 0);
220         if (!ed) {
221                 printf("%s: could not read endpoint descriptor\n",
222                        USBDEVNAME(sc->sc_dev));
223                 USB_ATTACH_ERROR_RETURN;
224         }
225
226         DPRINTFN(10,("ums_attach: bLength=%d bDescriptorType=%d "
227                      "bEndpointAddress=%d-%s bmAttributes=%d wMaxPacketSize=%d"
228                      " bInterval=%d\n",
229                      ed->bLength, ed->bDescriptorType, 
230                      UE_GET_ADDR(ed->bEndpointAddress),
231                      UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN ? "in":"out",
232                      UE_GET_XFERTYPE(ed->bmAttributes),
233                      UGETW(ed->wMaxPacketSize), ed->bInterval));
234
235         if (UE_GET_DIR(ed->bEndpointAddress) != UE_DIR_IN ||
236             UE_GET_XFERTYPE(ed->bmAttributes) != UE_INTERRUPT) {
237                 printf("%s: unexpected endpoint\n",
238                        USBDEVNAME(sc->sc_dev));
239                 USB_ATTACH_ERROR_RETURN;
240         }
241
242         err = usbd_alloc_report_desc(uaa->iface, &desc, &size, M_TEMP);
243         if (err)
244                 USB_ATTACH_ERROR_RETURN;
245
246         if (!hid_locate(desc, size, HID_USAGE2(HUP_GENERIC_DESKTOP, HUG_X),
247                        hid_input, &sc->sc_loc_x, &flags)) {
248                 printf("%s: mouse has no X report\n", USBDEVNAME(sc->sc_dev));
249                 USB_ATTACH_ERROR_RETURN;
250         }
251         if ((flags & MOUSE_FLAGS_MASK) != MOUSE_FLAGS) {
252                 printf("%s: X report 0x%04x not supported\n",
253                        USBDEVNAME(sc->sc_dev), flags);
254                 USB_ATTACH_ERROR_RETURN;
255         }
256
257         if (!hid_locate(desc, size, HID_USAGE2(HUP_GENERIC_DESKTOP, HUG_Y),
258                        hid_input, &sc->sc_loc_y, &flags)) {
259                 printf("%s: mouse has no Y report\n", USBDEVNAME(sc->sc_dev));
260                 USB_ATTACH_ERROR_RETURN;
261         }
262         if ((flags & MOUSE_FLAGS_MASK) != MOUSE_FLAGS) {
263                 printf("%s: Y report 0x%04x not supported\n",
264                        USBDEVNAME(sc->sc_dev), flags);
265                 USB_ATTACH_ERROR_RETURN;
266         }
267
268         /* try to guess the Z activator: first check Z, then WHEEL */
269         if (hid_locate(desc, size, HID_USAGE2(HUP_GENERIC_DESKTOP, HUG_Z),
270                        hid_input, &sc->sc_loc_z, &flags) ||
271             hid_locate(desc, size, HID_USAGE2(HUP_GENERIC_DESKTOP, HUG_WHEEL),
272                        hid_input, &sc->sc_loc_z, &flags)) {
273                 if ((flags & MOUSE_FLAGS_MASK) != MOUSE_FLAGS) {
274                         sc->sc_loc_z.size = 0;  /* Bad Z coord, ignore it */
275                 } else {
276                         sc->flags |= UMS_Z;
277                 }
278         }
279
280         /* figure out the number of buttons */
281         for (i = 1; i <= MAX_BUTTONS; i++)
282                 if (!hid_locate(desc, size, HID_USAGE2(HUP_BUTTON, i),
283                                 hid_input, &loc_btn, 0))
284                         break;
285         sc->nbuttons = i - 1;
286         sc->sc_loc_btn = malloc(sizeof(struct hid_location)*sc->nbuttons, 
287                                 M_USBDEV, M_NOWAIT);
288         if (!sc->sc_loc_btn) {
289                 printf("%s: no memory\n", USBDEVNAME(sc->sc_dev));
290                 USB_ATTACH_ERROR_RETURN;
291         }
292
293         printf("%s: %d buttons%s\n", USBDEVNAME(sc->sc_dev),
294                sc->nbuttons, sc->flags & UMS_Z? " and Z dir." : "");
295
296         for (i = 1; i <= sc->nbuttons; i++)
297                 hid_locate(desc, size, HID_USAGE2(HUP_BUTTON, i),
298                                 hid_input, &sc->sc_loc_btn[i-1], 0);
299
300         sc->sc_isize = hid_report_size(desc, size, hid_input, &sc->sc_iid);
301         sc->sc_ibuf = malloc(sc->sc_isize, M_USB, M_NOWAIT);
302         if (!sc->sc_ibuf) {
303                 printf("%s: no memory\n", USBDEVNAME(sc->sc_dev));
304                 free(sc->sc_loc_btn, M_USB);
305                 USB_ATTACH_ERROR_RETURN;
306         }
307
308         sc->sc_ep_addr = ed->bEndpointAddress;
309         sc->sc_disconnected = 0;
310         free(desc, M_TEMP);
311
312 #ifdef USB_DEBUG
313         DPRINTF(("ums_attach: sc=%p\n", sc));
314         DPRINTF(("ums_attach: X\t%d/%d\n", 
315                  sc->sc_loc_x.pos, sc->sc_loc_x.size));
316         DPRINTF(("ums_attach: Y\t%d/%d\n", 
317                  sc->sc_loc_y.pos, sc->sc_loc_y.size));
318         if (sc->flags & UMS_Z)
319                 DPRINTF(("ums_attach: Z\t%d/%d\n", 
320                          sc->sc_loc_z.pos, sc->sc_loc_z.size));
321         for (i = 1; i <= sc->nbuttons; i++) {
322                 DPRINTF(("ums_attach: B%d\t%d/%d\n",
323                          i, sc->sc_loc_btn[i-1].pos,sc->sc_loc_btn[i-1].size));
324         }
325         DPRINTF(("ums_attach: size=%d, id=%d\n", sc->sc_isize, sc->sc_iid));
326 #endif
327
328         if (sc->nbuttons > MOUSE_MSC_MAXBUTTON)
329                 sc->hw.buttons = MOUSE_MSC_MAXBUTTON;
330         else
331                 sc->hw.buttons = sc->nbuttons;
332         sc->hw.iftype = MOUSE_IF_USB;
333         sc->hw.type = MOUSE_MOUSE;
334         sc->hw.model = MOUSE_MODEL_GENERIC;
335         sc->hw.hwid = 0;
336         sc->mode.protocol = MOUSE_PROTO_MSC;
337         sc->mode.rate = -1;
338         sc->mode.resolution = MOUSE_RES_UNKNOWN;
339         sc->mode.accelfactor = 0;
340         sc->mode.level = 0;
341         sc->mode.packetsize = MOUSE_MSC_PACKETSIZE;
342         sc->mode.syncmask[0] = MOUSE_MSC_SYNCMASK;
343         sc->mode.syncmask[1] = MOUSE_MSC_SYNC;
344
345         sc->status.flags = 0;
346         sc->status.button = sc->status.obutton = 0;
347         sc->status.dx = sc->status.dy = sc->status.dz = 0;
348
349         sc->rsel.si_flags = 0;
350         sc->rsel.si_pid = 0;
351
352         sc->dev = make_dev(&ums_cdevsw, device_get_unit(self),
353                         UID_ROOT, GID_OPERATOR,
354                         0644, "ums%d", device_get_unit(self));
355
356         if (usbd_get_quirks(uaa->device)->uq_flags & UQ_SPUR_BUT_UP) {
357                 DPRINTF(("%s: Spurious button up events\n",
358                         USBDEVNAME(sc->sc_dev)));
359                 sc->flags |= UMS_SPUR_BUT_UP;
360         }
361
362         USB_ATTACH_SUCCESS_RETURN;
363 }
364
365
366 Static int
367 ums_detach(device_t self)
368 {
369         struct ums_softc *sc = device_get_softc(self);
370         struct vnode *vp;
371
372         if (sc->sc_enabled)
373                 ums_disable(sc);
374
375         DPRINTF(("%s: disconnected\n", USBDEVNAME(self)));
376
377         free(sc->sc_loc_btn, M_USB);
378         free(sc->sc_ibuf, M_USB);
379
380         vp = SLIST_FIRST(&sc->dev->si_hlist);
381         if (vp)
382                 VOP_REVOKE(vp, REVOKEALL);
383
384         /* someone waiting for data */
385         /*
386          * XXX If we wakeup the process here, the device will be gone by
387          * the time the process gets a chance to notice. *_close and friends
388          * should be fixed to handle this case.
389          * Or we should do a delayed detach for this.
390          * Does this delay now force tsleep to exit with an error?
391          */
392         if (sc->state & UMS_ASLEEP) {
393                 sc->state &= ~UMS_ASLEEP;
394                 wakeup(sc);
395         }
396         if (sc->state & UMS_SELECT) {
397                 sc->state &= ~UMS_SELECT;
398                 selwakeup(&sc->rsel);
399         }
400
401         destroy_dev(sc->dev);
402
403         return 0;
404 }
405
406 void
407 ums_intr(xfer, addr, status)
408         usbd_xfer_handle xfer;
409         usbd_private_handle addr;
410         usbd_status status;
411 {
412         struct ums_softc *sc = addr;
413         u_char *ibuf;
414         int dx, dy, dz;
415         u_char buttons = 0;
416         int i;
417
418 #define UMS_BUT(i) ((i) < 3 ? (((i) + 2) % 3) : (i))
419
420         DPRINTFN(5, ("ums_intr: sc=%p status=%d\n", sc, status));
421         DPRINTFN(5, ("ums_intr: data = %02x %02x %02x\n",
422                      sc->sc_ibuf[0], sc->sc_ibuf[1], sc->sc_ibuf[2]));
423
424         if (status == USBD_CANCELLED)
425                 return;
426
427         if (status != USBD_NORMAL_COMPLETION) {
428                 DPRINTF(("ums_intr: status=%d\n", status));
429                 usbd_clear_endpoint_stall_async(sc->sc_intrpipe);
430                 return;
431         }
432
433         ibuf = sc->sc_ibuf;
434         if (sc->sc_iid) {
435                 if (*ibuf++ != sc->sc_iid)
436                         return;
437         }
438
439         dx =  hid_get_data(ibuf, &sc->sc_loc_x);
440         dy = -hid_get_data(ibuf, &sc->sc_loc_y);
441         dz = -hid_get_data(ibuf, &sc->sc_loc_z);
442         for (i = 0; i < sc->nbuttons; i++)
443                 if (hid_get_data(ibuf, &sc->sc_loc_btn[i]))
444                         buttons |= (1 << UMS_BUT(i));
445
446         if (dx || dy || dz || (sc->flags & UMS_Z)
447             || buttons != sc->status.button) {
448                 DPRINTFN(5, ("ums_intr: x:%d y:%d z:%d buttons:0x%x\n",
449                         dx, dy, dz, buttons));
450
451                 sc->status.button = buttons;
452                 sc->status.dx += dx;
453                 sc->status.dy += dy;
454                 sc->status.dz += dz;
455
456                 /* Discard data in case of full buffer */
457                 if (sc->qcount == sizeof(sc->qbuf)) {
458                         DPRINTF(("Buffer full, discarded packet"));
459                         return;
460                 }
461
462                 /*
463                  * The Qtronix keyboard has a built in PS/2 port for a mouse.
464                  * The firmware once in a while posts a spurious button up
465                  * event. This event we ignore by doing a timeout for 50 msecs.
466                  * If we receive dx=dy=dz=buttons=0 before we add the event to
467                  * the queue.
468                  * In any other case we delete the timeout event.
469                  */
470                 if (sc->flags & UMS_SPUR_BUT_UP &&
471                     dx == 0 && dy == 0 && dz == 0 && buttons == 0) {
472                         usb_timeout(ums_add_to_queue_timeout, (void *) sc,
473                                 MS_TO_TICKS(50 /*msecs*/), sc->timeout_handle);
474                 } else {
475                         usb_untimeout(ums_add_to_queue_timeout, (void *) sc,
476                                 sc->timeout_handle);
477
478                         ums_add_to_queue(sc, dx, dy, dz, buttons);
479                 }
480         }
481 }
482
483 Static void
484 ums_add_to_queue_timeout(void *priv)
485 {
486         struct ums_softc *sc = priv;
487         int s;
488
489         s = splusb();
490         ums_add_to_queue(sc, 0, 0, 0, 0);
491         splx(s);
492 }
493
494 Static void
495 ums_add_to_queue(struct ums_softc *sc, int dx, int dy, int dz, int buttons)
496 {
497         /* Discard data in case of full buffer */
498         if (sc->qhead+sc->mode.packetsize > sizeof(sc->qbuf)) {
499                 DPRINTF(("Buffer full, discarded packet"));
500                 return;
501         }
502
503         if (dx >  254)          dx =  254;
504         if (dx < -256)          dx = -256;
505         if (dy >  254)          dy =  254;
506         if (dy < -256)          dy = -256;
507         if (dz >  126)          dz =  126;
508         if (dz < -128)          dz = -128;
509
510         sc->qbuf[sc->qhead] = sc->mode.syncmask[1];
511         sc->qbuf[sc->qhead] |= ~buttons & MOUSE_MSC_BUTTONS;
512         sc->qbuf[sc->qhead+1] = dx >> 1;
513         sc->qbuf[sc->qhead+2] = dy >> 1;
514         sc->qbuf[sc->qhead+3] = dx - (dx >> 1);
515         sc->qbuf[sc->qhead+4] = dy - (dy >> 1);
516
517         if (sc->mode.level == 1) {
518                 sc->qbuf[sc->qhead+5] = dz >> 1;
519                 sc->qbuf[sc->qhead+6] = dz - (dz >> 1);
520                 sc->qbuf[sc->qhead+7] = ((~buttons >> 3)
521                                          & MOUSE_SYS_EXTBUTTONS);
522         }
523
524         sc->qhead += sc->mode.packetsize;
525         sc->qcount += sc->mode.packetsize;
526         /* wrap round at end of buffer */
527         if (sc->qhead >= sizeof(sc->qbuf))
528                 sc->qhead = 0;
529
530         /* someone waiting for data */
531         if (sc->state & UMS_ASLEEP) {
532                 sc->state &= ~UMS_ASLEEP;
533                 wakeup(sc);
534         }
535         if (sc->state & UMS_SELECT) {
536                 sc->state &= ~UMS_SELECT;
537                 selwakeup(&sc->rsel);
538         }
539 }
540 Static int
541 ums_enable(v)
542         void *v;
543 {
544         struct ums_softc *sc = v;
545
546         usbd_status err;
547
548         if (sc->sc_enabled)
549                 return EBUSY;
550
551         sc->sc_enabled = 1;
552         sc->qcount = 0;
553         sc->qhead = sc->qtail = 0;
554         sc->status.flags = 0;
555         sc->status.button = sc->status.obutton = 0;
556         sc->status.dx = sc->status.dy = sc->status.dz = 0;
557
558         callout_handle_init(&sc->timeout_handle);
559
560         /* Set up interrupt pipe. */
561         err = usbd_open_pipe_intr(sc->sc_iface, sc->sc_ep_addr, 
562                                 USBD_SHORT_XFER_OK, &sc->sc_intrpipe, sc, 
563                                 sc->sc_ibuf, sc->sc_isize, ums_intr,
564                                 USBD_DEFAULT_INTERVAL);
565         if (err) {
566                 DPRINTF(("ums_enable: usbd_open_pipe_intr failed, error=%d\n",
567                          err));
568                 sc->sc_enabled = 0;
569                 return (EIO);
570         }
571         return (0);
572 }
573
574 Static void
575 ums_disable(priv)
576         void *priv;
577 {
578         struct ums_softc *sc = priv;
579
580         usb_untimeout(ums_add_to_queue_timeout, sc, sc->timeout_handle);
581
582         /* Disable interrupts. */
583         usbd_abort_pipe(sc->sc_intrpipe);
584         usbd_close_pipe(sc->sc_intrpipe);
585
586         sc->sc_enabled = 0;
587
588         if (sc->qcount != 0)
589                 DPRINTF(("Discarded %d bytes in queue\n", sc->qcount));
590 }
591
592 Static int
593 ums_open(dev_t dev, int flag, int fmt, usb_proc_ptr p)
594 {
595         struct ums_softc *sc;
596
597         USB_GET_SC_OPEN(ums, UMSUNIT(dev), sc);
598
599         return ums_enable(sc);
600 }
601
602 Static int
603 ums_close(dev_t dev, int flag, int fmt, usb_proc_ptr p)
604 {
605         struct ums_softc *sc;
606
607         USB_GET_SC(ums, UMSUNIT(dev), sc);
608
609         if (!sc)
610                 return 0;
611
612         if (sc->sc_enabled)
613                 ums_disable(sc);
614
615         return 0;
616 }
617
618 Static int
619 ums_read(dev_t dev, struct uio *uio, int flag)
620 {
621         struct ums_softc *sc;
622         int s;
623         char buf[sizeof(sc->qbuf)];
624         int l = 0;
625         int error;
626
627         USB_GET_SC(ums, UMSUNIT(dev), sc);
628
629         s = splusb();
630         if (!sc) {
631                 splx(s);
632                 return EIO;
633         }
634
635         while (sc->qcount == 0 )  {
636                 if (flag & IO_NDELAY) {         /* non-blocking I/O */
637                         splx(s);
638                         return EWOULDBLOCK;
639                 }
640                 
641                 sc->state |= UMS_ASLEEP;        /* blocking I/O */
642                 error = tsleep(sc, PCATCH, "umsrea", 0);
643                 if (error) {
644                         splx(s);
645                         return error;
646                 } else if (!sc->sc_enabled) {
647                         splx(s);
648                         return EINTR;
649                 }
650                 /* check whether the device is still there */
651
652                 sc = devclass_get_softc(ums_devclass, UMSUNIT(dev));
653                 if (!sc) {
654                         splx(s);
655                         return EIO;
656                 }
657         }
658
659         /*
660          * XXX we could optimise the use of splx/splusb somewhat. The writer
661          * process only extends qcount and qtail. We could copy them and use the copies
662          * to do the copying out of the queue.
663          */
664
665         while ((sc->qcount > 0) && (uio->uio_resid > 0)) {
666                 l = (sc->qcount < uio->uio_resid? sc->qcount:uio->uio_resid);
667                 if (l > sizeof(buf))
668                         l = sizeof(buf);
669                 if (l > sizeof(sc->qbuf) - sc->qtail)           /* transfer till end of buf */
670                         l = sizeof(sc->qbuf) - sc->qtail;
671
672                 splx(s);
673                 uiomove(&sc->qbuf[sc->qtail], l, uio);
674                 s = splusb();
675
676                 if ( sc->qcount - l < 0 ) {
677                         DPRINTF(("qcount below 0, count=%d l=%d\n", sc->qcount, l));
678                         sc->qcount = l;
679                 }
680                 sc->qcount -= l;        /* remove the bytes from the buffer */
681                 sc->qtail = (sc->qtail + l) % sizeof(sc->qbuf);
682         }
683         splx(s);
684
685         return 0;
686 }
687
688 Static int
689 ums_poll(dev_t dev, int events, usb_proc_ptr p)
690 {
691         struct ums_softc *sc;
692         int revents = 0;
693         int s;
694
695         USB_GET_SC(ums, UMSUNIT(dev), sc);
696
697         if (!sc)
698                 return 0;
699
700         s = splusb();
701         if (events & (POLLIN | POLLRDNORM)) {
702                 if (sc->qcount) {
703                         revents = events & (POLLIN | POLLRDNORM);
704                 } else {
705                         sc->state |= UMS_SELECT;
706                         selrecord(p, &sc->rsel);
707                 }
708         }
709         splx(s);
710
711         return revents;
712 }
713         
714 int
715 ums_ioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, usb_proc_ptr p)
716 {
717         struct ums_softc *sc;
718         int error = 0;
719         int s;
720         mousemode_t mode;
721
722         USB_GET_SC(ums, UMSUNIT(dev), sc);
723
724         if (!sc)
725                 return EIO;
726
727         switch(cmd) {
728         case MOUSE_GETHWINFO:
729                 *(mousehw_t *)addr = sc->hw;
730                 break;
731         case MOUSE_GETMODE:
732                 *(mousemode_t *)addr = sc->mode;
733                 break;
734         case MOUSE_SETMODE:
735                 mode = *(mousemode_t *)addr;
736
737                 if (mode.level == -1)
738                         /* don't change the current setting */
739                         ;
740                 else if ((mode.level < 0) || (mode.level > 1))
741                         return (EINVAL);
742
743                 s = splusb();
744                 sc->mode.level = mode.level;
745
746                 if (sc->mode.level == 0) {
747                         if (sc->nbuttons > MOUSE_MSC_MAXBUTTON)
748                                 sc->hw.buttons = MOUSE_MSC_MAXBUTTON;
749                         else
750                                 sc->hw.buttons = sc->nbuttons;
751                         sc->mode.protocol = MOUSE_PROTO_MSC;
752                         sc->mode.packetsize = MOUSE_MSC_PACKETSIZE;
753                         sc->mode.syncmask[0] = MOUSE_MSC_SYNCMASK;
754                         sc->mode.syncmask[1] = MOUSE_MSC_SYNC;
755                 } else if (sc->mode.level == 1) {
756                         if (sc->nbuttons > MOUSE_SYS_MAXBUTTON)
757                                 sc->hw.buttons = MOUSE_SYS_MAXBUTTON;
758                         else
759                                 sc->hw.buttons = sc->nbuttons;
760                         sc->mode.protocol = MOUSE_PROTO_SYSMOUSE;
761                         sc->mode.packetsize = MOUSE_SYS_PACKETSIZE;
762                         sc->mode.syncmask[0] = MOUSE_SYS_SYNCMASK;
763                         sc->mode.syncmask[1] = MOUSE_SYS_SYNC;
764                 }
765
766                 bzero(sc->qbuf, sizeof(sc->qbuf));
767                 sc->qhead = sc->qtail = sc->qcount = 0;
768                 splx(s);
769
770                 break;
771         case MOUSE_GETLEVEL:
772                 *(int *)addr = sc->mode.level;
773                 break;
774         case MOUSE_SETLEVEL:
775                 if (*(int *)addr < 0 || *(int *)addr > 1)
776                         return (EINVAL);
777
778                 s = splusb();
779                 sc->mode.level = *(int *)addr;
780
781                 if (sc->mode.level == 0) {
782                         if (sc->nbuttons > MOUSE_MSC_MAXBUTTON)
783                                 sc->hw.buttons = MOUSE_MSC_MAXBUTTON;
784                         else
785                                 sc->hw.buttons = sc->nbuttons;
786                         sc->mode.protocol = MOUSE_PROTO_MSC;
787                         sc->mode.packetsize = MOUSE_MSC_PACKETSIZE;
788                         sc->mode.syncmask[0] = MOUSE_MSC_SYNCMASK;
789                         sc->mode.syncmask[1] = MOUSE_MSC_SYNC;
790                 } else if (sc->mode.level == 1) {
791                         if (sc->nbuttons > MOUSE_SYS_MAXBUTTON)
792                                 sc->hw.buttons = MOUSE_SYS_MAXBUTTON;
793                         else
794                                 sc->hw.buttons = sc->nbuttons;
795                         sc->mode.protocol = MOUSE_PROTO_SYSMOUSE;
796                         sc->mode.packetsize = MOUSE_SYS_PACKETSIZE;
797                         sc->mode.syncmask[0] = MOUSE_SYS_SYNCMASK;
798                         sc->mode.syncmask[1] = MOUSE_SYS_SYNC;
799                 }
800
801                 bzero(sc->qbuf, sizeof(sc->qbuf));
802                 sc->qhead = sc->qtail = sc->qcount = 0;
803                 splx(s);
804
805                 break;
806         case MOUSE_GETSTATUS: {
807                 mousestatus_t *status = (mousestatus_t *) addr;
808
809                 s = splusb();
810                 *status = sc->status;
811                 sc->status.obutton = sc->status.button;
812                 sc->status.button = 0;
813                 sc->status.dx = sc->status.dy = sc->status.dz = 0;
814                 splx(s);
815
816                 if (status->dx || status->dy || status->dz)
817                         status->flags |= MOUSE_POSCHANGED;
818                 if (status->button != status->obutton)
819                         status->flags |= MOUSE_BUTTONSCHANGED;
820                 break;
821                 }
822         default:
823                 error = ENOTTY;
824         }
825
826         return error;
827 }
828
829 DRIVER_MODULE(ums, uhub, ums_driver, ums_devclass, usbd_driver_load, 0);