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