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