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