Merge from vendor branch GDB:
[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.16 2005/12/11 01:54:09 swildner 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 #if defined(__FreeBSD__) && __FreeBSD_version >= 500014
58 #include <sys/selinfo.h>
59 #else
60 #include <sys/select.h>
61 #endif
62 #include <sys/vnode.h>
63 #include <sys/poll.h>
64 #include <sys/sysctl.h>
65 #include <sys/thread2.h>
66
67 #include <bus/usb/usb.h>
68 #include <bus/usb/usbhid.h>
69
70 #include <bus/usb/usbdi.h>
71 #include <bus/usb/usbdi_util.h>
72 #include <bus/usb/usbdevs.h>
73 #include <bus/usb/usb_quirks.h>
74 #include <bus/usb/hid.h>
75
76 #if defined(__FreeBSD__) && __FreeBSD_version >= 500000
77 #include <sys/mouse.h>
78 #else
79 #include <machine/mouse.h>
80 #endif
81
82 #ifdef USB_DEBUG
83 #define DPRINTF(x)      if (umsdebug) logprintf x
84 #define DPRINTFN(n,x)   if (umsdebug>(n)) logprintf x
85 int     umsdebug = 0;
86 SYSCTL_NODE(_hw_usb, OID_AUTO, ums, CTLFLAG_RW, 0, "USB ums");
87 SYSCTL_INT(_hw_usb_ums, OID_AUTO, debug, CTLFLAG_RW,
88            &umsdebug, 0, "ums debug level");
89 #else
90 #define DPRINTF(x)
91 #define DPRINTFN(n,x)
92 #endif
93
94 #define UMSUNIT(s)      (minor(s)&0x1f)
95
96 #define MS_TO_TICKS(ms) ((ms) * hz / 1000)
97
98 #define QUEUE_BUFSIZE   400     /* MUST be divisible by 5 _and_ 8 */
99
100 struct ums_softc {
101         device_t sc_dev;                /* base device */
102         usbd_interface_handle sc_iface; /* interface */
103         usbd_pipe_handle sc_intrpipe;   /* interrupt pipe */
104         int sc_ep_addr;
105
106         u_char *sc_ibuf;
107         u_int8_t sc_iid;
108         int sc_isize;
109         struct hid_location sc_loc_x, sc_loc_y, sc_loc_z;
110         struct hid_location *sc_loc_btn;
111
112         struct callout sc_timeout;      /* for spurious button ups */
113
114         int sc_enabled;
115         int sc_disconnected;    /* device is gone */
116
117         int flags;              /* device configuration */
118 #define UMS_Z           0x01    /* z direction available */
119 #define UMS_SPUR_BUT_UP 0x02    /* spurious button up events */
120         int nbuttons;
121 #define MAX_BUTTONS     31      /* must not exceed size of sc_buttons */
122
123         u_char          qbuf[QUEUE_BUFSIZE];    /* must be divisable by 3&4 */
124         u_char          dummy[100];     /* XXX just for safety and for now */
125         int             qcount, qhead, qtail;
126         mousehw_t       hw;
127         mousemode_t     mode;
128         mousestatus_t   status;
129
130         int             state;
131 #         define        UMS_ASLEEP      0x01    /* readFromDevice is waiting */
132 #         define        UMS_SELECT      0x02    /* select is waiting */
133         struct selinfo  rsel;           /* process waiting in select */
134 };
135
136 #define MOUSE_FLAGS_MASK (HIO_CONST|HIO_RELATIVE)
137 #define MOUSE_FLAGS (HIO_RELATIVE)
138
139 Static void ums_intr(usbd_xfer_handle xfer,
140                           usbd_private_handle priv, usbd_status status);
141
142 Static void ums_add_to_queue(struct ums_softc *sc,
143                                 int dx, int dy, int dz, int buttons);
144 Static void ums_add_to_queue_timeout(void *priv);
145
146 Static int  ums_enable(void *);
147 Static void ums_disable(void *);
148
149 Static d_open_t  ums_open;
150 Static d_close_t ums_close;
151 Static d_read_t  ums_read;
152 Static d_ioctl_t ums_ioctl;
153 Static d_poll_t  ums_poll;
154
155 #define UMS_CDEV_MAJOR  111
156
157 Static struct cdevsw ums_cdevsw = {
158         /* name */      "ums",
159         /* maj */       UMS_CDEV_MAJOR,
160         /* flags */     0,
161         /* port */      NULL,
162         /* clone */     NULL,
163
164         /* open */      ums_open,
165         /* close */     ums_close,
166         /* read */      ums_read,
167         /* write */     nowrite,
168         /* ioctl */     ums_ioctl,
169         /* poll */      ums_poll,
170         /* mmap */      nommap,
171         /* strategy */  nostrategy,
172         /* dump */      nodump,
173         /* psize */     nopsize
174 };
175
176 USB_DECLARE_DRIVER(ums);
177
178 USB_MATCH(ums)
179 {
180         USB_MATCH_START(ums, uaa);
181         usb_interface_descriptor_t *id;
182         int size, ret;
183         void *desc;
184         usbd_status err;
185
186         if (!uaa->iface)
187                 return (UMATCH_NONE);
188         id = usbd_get_interface_descriptor(uaa->iface);
189         if (!id || id->bInterfaceClass != UICLASS_HID)
190                 return (UMATCH_NONE);
191
192         err = usbd_read_report_desc(uaa->iface, &desc, &size, M_TEMP);
193         if (err)
194                 return (UMATCH_NONE);
195
196         if (hid_is_collection(desc, size,
197                               HID_USAGE2(HUP_GENERIC_DESKTOP, HUG_MOUSE)))
198                 ret = UMATCH_IFACECLASS;
199         else
200                 ret = UMATCH_NONE;
201
202         free(desc, M_TEMP);
203         return (ret);
204 }
205
206 USB_ATTACH(ums)
207 {
208         USB_ATTACH_START(ums, sc, uaa);
209         usbd_interface_handle iface = uaa->iface;
210         usb_interface_descriptor_t *id;
211         usb_endpoint_descriptor_t *ed;
212         int size;
213         void *desc;
214         usbd_status err;
215         char devinfo[1024];
216         u_int32_t flags;
217         int i;
218         struct hid_location loc_btn;
219
220         sc->sc_disconnected = 1;
221         sc->sc_iface = iface;
222         id = usbd_get_interface_descriptor(iface);
223         usbd_devinfo(uaa->device, 0, devinfo);
224         USB_ATTACH_SETUP;
225         printf("%s: %s, iclass %d/%d\n", USBDEVNAME(sc->sc_dev),
226                devinfo, id->bInterfaceClass, id->bInterfaceSubClass);
227         ed = usbd_interface2endpoint_descriptor(iface, 0);
228         if (!ed) {
229                 printf("%s: could not read endpoint descriptor\n",
230                        USBDEVNAME(sc->sc_dev));
231                 USB_ATTACH_ERROR_RETURN;
232         }
233
234         DPRINTFN(10,("ums_attach: bLength=%d bDescriptorType=%d "
235                      "bEndpointAddress=%d-%s bmAttributes=%d wMaxPacketSize=%d"
236                      " bInterval=%d\n",
237                      ed->bLength, ed->bDescriptorType,
238                      UE_GET_ADDR(ed->bEndpointAddress),
239                      UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN ? "in":"out",
240                      UE_GET_XFERTYPE(ed->bmAttributes),
241                      UGETW(ed->wMaxPacketSize), ed->bInterval));
242
243         if (UE_GET_DIR(ed->bEndpointAddress) != UE_DIR_IN ||
244             UE_GET_XFERTYPE(ed->bmAttributes) != UE_INTERRUPT) {
245                 printf("%s: unexpected endpoint\n",
246                        USBDEVNAME(sc->sc_dev));
247                 USB_ATTACH_ERROR_RETURN;
248         }
249
250         err = usbd_read_report_desc(uaa->iface, &desc, &size, M_TEMP);
251         if (err)
252                 USB_ATTACH_ERROR_RETURN;
253
254         if (!hid_locate(desc, size, HID_USAGE2(HUP_GENERIC_DESKTOP, HUG_X),
255                        hid_input, &sc->sc_loc_x, &flags)) {
256                 printf("%s: mouse has no X report\n", USBDEVNAME(sc->sc_dev));
257                 USB_ATTACH_ERROR_RETURN;
258         }
259         if ((flags & MOUSE_FLAGS_MASK) != MOUSE_FLAGS) {
260                 printf("%s: X report 0x%04x not supported\n",
261                        USBDEVNAME(sc->sc_dev), flags);
262                 USB_ATTACH_ERROR_RETURN;
263         }
264
265         if (!hid_locate(desc, size, HID_USAGE2(HUP_GENERIC_DESKTOP, HUG_Y),
266                        hid_input, &sc->sc_loc_y, &flags)) {
267                 printf("%s: mouse has no Y report\n", USBDEVNAME(sc->sc_dev));
268                 USB_ATTACH_ERROR_RETURN;
269         }
270         if ((flags & MOUSE_FLAGS_MASK) != MOUSE_FLAGS) {
271                 printf("%s: Y report 0x%04x not supported\n",
272                        USBDEVNAME(sc->sc_dev), flags);
273                 USB_ATTACH_ERROR_RETURN;
274         }
275
276         /* try to guess the Z activator: first check Z, then WHEEL */
277         if (hid_locate(desc, size, HID_USAGE2(HUP_GENERIC_DESKTOP, HUG_Z),
278                        hid_input, &sc->sc_loc_z, &flags) ||
279             hid_locate(desc, size, HID_USAGE2(HUP_GENERIC_DESKTOP, HUG_WHEEL),
280                        hid_input, &sc->sc_loc_z, &flags)) {
281                 if ((flags & MOUSE_FLAGS_MASK) != MOUSE_FLAGS) {
282                         sc->sc_loc_z.size = 0;  /* Bad Z coord, ignore it */
283                 } else {
284                         sc->flags |= UMS_Z;
285                 }
286         }
287
288         /* figure out the number of buttons */
289         for (i = 1; i <= MAX_BUTTONS; i++)
290                 if (!hid_locate(desc, size, HID_USAGE2(HUP_BUTTON, i),
291                                 hid_input, &loc_btn, 0))
292                         break;
293         sc->nbuttons = i - 1;
294         sc->sc_loc_btn = malloc(sizeof(struct hid_location)*sc->nbuttons,
295                                 M_USBDEV, M_INTWAIT);
296
297         printf("%s: %d buttons%s\n", USBDEVNAME(sc->sc_dev),
298                sc->nbuttons, sc->flags & UMS_Z? " and Z dir." : "");
299
300         for (i = 1; i <= sc->nbuttons; i++)
301                 hid_locate(desc, size, HID_USAGE2(HUP_BUTTON, i),
302                                 hid_input, &sc->sc_loc_btn[i-1], 0);
303
304         sc->sc_isize = hid_report_size(desc, size, hid_input, &sc->sc_iid);
305         sc->sc_ibuf = malloc(sc->sc_isize, M_USB, M_INTWAIT);
306         sc->sc_ep_addr = ed->bEndpointAddress;
307         sc->sc_disconnected = 0;
308         free(desc, M_TEMP);
309
310 #ifdef USB_DEBUG
311         DPRINTF(("ums_attach: sc=%p\n", sc));
312         DPRINTF(("ums_attach: X\t%d/%d\n",
313                  sc->sc_loc_x.pos, sc->sc_loc_x.size));
314         DPRINTF(("ums_attach: Y\t%d/%d\n",
315                  sc->sc_loc_y.pos, sc->sc_loc_y.size));
316         if (sc->flags & UMS_Z)
317                 DPRINTF(("ums_attach: Z\t%d/%d\n",
318                          sc->sc_loc_z.pos, sc->sc_loc_z.size));
319         for (i = 1; i <= sc->nbuttons; i++) {
320                 DPRINTF(("ums_attach: B%d\t%d/%d\n",
321                          i, sc->sc_loc_btn[i-1].pos,sc->sc_loc_btn[i-1].size));
322         }
323         DPRINTF(("ums_attach: size=%d, id=%d\n", sc->sc_isize, sc->sc_iid));
324 #endif
325
326         if (sc->nbuttons > MOUSE_MSC_MAXBUTTON)
327                 sc->hw.buttons = MOUSE_MSC_MAXBUTTON;
328         else
329                 sc->hw.buttons = sc->nbuttons;
330         sc->hw.iftype = MOUSE_IF_USB;
331         sc->hw.type = MOUSE_MOUSE;
332         sc->hw.model = MOUSE_MODEL_GENERIC;
333         sc->hw.hwid = 0;
334         sc->mode.protocol = MOUSE_PROTO_MSC;
335         sc->mode.rate = -1;
336         sc->mode.resolution = MOUSE_RES_UNKNOWN;
337         sc->mode.accelfactor = 0;
338         sc->mode.level = 0;
339         sc->mode.packetsize = MOUSE_MSC_PACKETSIZE;
340         sc->mode.syncmask[0] = MOUSE_MSC_SYNCMASK;
341         sc->mode.syncmask[1] = MOUSE_MSC_SYNC;
342
343         sc->status.flags = 0;
344         sc->status.button = sc->status.obutton = 0;
345         sc->status.dx = sc->status.dy = sc->status.dz = 0;
346
347 #if !defined(__FreeBSD__) && !defined(__DragonFly__)
348         sc->rsel.si_flags = 0;
349         sc->rsel.si_pid = 0;
350 #endif
351         cdevsw_add(&ums_cdevsw, -1, device_get_unit(self));
352         make_dev(&ums_cdevsw, device_get_unit(self),
353                 UID_ROOT, GID_OPERATOR,
354                 0644, "ums%d", device_get_unit(self));
355
356         if (usbd_get_quirks(uaa->device)->uq_flags & UQ_SPUR_BUT_UP) {
357                 DPRINTF(("%s: Spurious button up events\n",
358                         USBDEVNAME(sc->sc_dev)));
359                 sc->flags |= UMS_SPUR_BUT_UP;
360         }
361
362         USB_ATTACH_SUCCESS_RETURN;
363 }
364
365
366 Static int
367 ums_detach(device_t self)
368 {
369         struct ums_softc *sc = device_get_softc(self);
370
371         if (sc->sc_enabled)
372                 ums_disable(sc);
373
374         DPRINTF(("%s: disconnected\n", USBDEVNAME(self)));
375
376         free(sc->sc_loc_btn, M_USB);
377         free(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                 selwakeuppri(&sc->rsel, 0);
394         }
395         cdevsw_remove(&ums_cdevsw, -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                 selwakeuppri(&sc->rsel, 0);
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(dev_t dev, int flag, int fmt, usb_proc_ptr p)
583 {
584         struct ums_softc *sc;
585
586         USB_GET_SC_OPEN(ums, UMSUNIT(dev), sc);
587
588         return ums_enable(sc);
589 }
590
591 Static int
592 ums_close(dev_t dev, int flag, int fmt, usb_proc_ptr p)
593 {
594         struct ums_softc *sc;
595
596         USB_GET_SC(ums, UMSUNIT(dev), sc);
597
598         if (!sc)
599                 return 0;
600
601         if (sc->sc_enabled)
602                 ums_disable(sc);
603
604         return 0;
605 }
606
607 Static int
608 ums_read(dev_t dev, struct uio *uio, int flag)
609 {
610         struct ums_softc *sc;
611         char buf[sizeof(sc->qbuf)];
612         int l = 0;
613         int error;
614
615         USB_GET_SC(ums, UMSUNIT(dev), sc);
616
617         crit_enter();
618         if (!sc) {
619                 crit_exit();
620                 return EIO;
621         }
622
623         while (sc->qcount == 0 )  {
624                 if (flag & IO_NDELAY) {         /* non-blocking I/O */
625                         crit_exit();
626                         return EWOULDBLOCK;
627                 }
628
629                 sc->state |= UMS_ASLEEP;        /* blocking I/O */
630                 error = tsleep(sc, PCATCH, "umsrea", 0);
631                 if (error) {
632                         crit_exit();
633                         return error;
634                 } else if (!sc->sc_enabled) {
635                         crit_exit();
636                         return EINTR;
637                 }
638                 /* check whether the device is still there */
639
640                 sc = devclass_get_softc(ums_devclass, UMSUNIT(dev));
641                 if (!sc) {
642                         crit_exit();
643                         return EIO;
644                 }
645         }
646
647         /*
648          * The writer process only extends qcount and qtail. We could copy
649          * them and use the copies to do the copying out of the queue.
650          */
651
652         while ((sc->qcount > 0) && (uio->uio_resid > 0)) {
653                 l = (sc->qcount < uio->uio_resid? sc->qcount:uio->uio_resid);
654                 if (l > sizeof(buf))
655                         l = sizeof(buf);
656                 if (l > sizeof(sc->qbuf) - sc->qtail)           /* transfer till end of buf */
657                         l = sizeof(sc->qbuf) - sc->qtail;
658
659                 crit_exit();
660                 uiomove(&sc->qbuf[sc->qtail], l, uio);
661                 crit_enter();
662
663                 if ( sc->qcount - l < 0 ) {
664                         DPRINTF(("qcount below 0, count=%d l=%d\n", sc->qcount, l));
665                         sc->qcount = l;
666                 }
667                 sc->qcount -= l;        /* remove the bytes from the buffer */
668                 sc->qtail = (sc->qtail + l) % sizeof(sc->qbuf);
669         }
670         crit_exit();
671
672         return 0;
673 }
674
675 Static int
676 ums_poll(dev_t dev, int events, usb_proc_ptr p)
677 {
678         struct ums_softc *sc;
679         int revents = 0;
680
681         USB_GET_SC(ums, UMSUNIT(dev), sc);
682
683         if (!sc)
684                 return 0;
685
686         crit_enter();
687         if (events & (POLLIN | POLLRDNORM)) {
688                 if (sc->qcount) {
689                         revents = events & (POLLIN | POLLRDNORM);
690                 } else {
691                         sc->state |= UMS_SELECT;
692                         selrecord(p, &sc->rsel);
693                 }
694         }
695         crit_exit();
696
697         return revents;
698 }
699
700 int
701 ums_ioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, usb_proc_ptr p)
702 {
703         struct ums_softc *sc;
704         int error = 0;
705         mousemode_t mode;
706
707         USB_GET_SC(ums, UMSUNIT(dev), sc);
708
709         if (!sc)
710                 return EIO;
711
712         switch(cmd) {
713         case MOUSE_GETHWINFO:
714                 *(mousehw_t *)addr = sc->hw;
715                 break;
716         case MOUSE_GETMODE:
717                 *(mousemode_t *)addr = sc->mode;
718                 break;
719         case MOUSE_SETMODE:
720                 mode = *(mousemode_t *)addr;
721
722                 if (mode.level == -1)
723                         /* don't change the current setting */
724                         ;
725                 else if ((mode.level < 0) || (mode.level > 1))
726                         return (EINVAL);
727
728                 crit_enter();
729                 sc->mode.level = mode.level;
730
731                 if (sc->mode.level == 0) {
732                         if (sc->nbuttons > MOUSE_MSC_MAXBUTTON)
733                                 sc->hw.buttons = MOUSE_MSC_MAXBUTTON;
734                         else
735                                 sc->hw.buttons = sc->nbuttons;
736                         sc->mode.protocol = MOUSE_PROTO_MSC;
737                         sc->mode.packetsize = MOUSE_MSC_PACKETSIZE;
738                         sc->mode.syncmask[0] = MOUSE_MSC_SYNCMASK;
739                         sc->mode.syncmask[1] = MOUSE_MSC_SYNC;
740                 } else if (sc->mode.level == 1) {
741                         if (sc->nbuttons > MOUSE_SYS_MAXBUTTON)
742                                 sc->hw.buttons = MOUSE_SYS_MAXBUTTON;
743                         else
744                                 sc->hw.buttons = sc->nbuttons;
745                         sc->mode.protocol = MOUSE_PROTO_SYSMOUSE;
746                         sc->mode.packetsize = MOUSE_SYS_PACKETSIZE;
747                         sc->mode.syncmask[0] = MOUSE_SYS_SYNCMASK;
748                         sc->mode.syncmask[1] = MOUSE_SYS_SYNC;
749                 }
750
751                 bzero(sc->qbuf, sizeof(sc->qbuf));
752                 sc->qhead = sc->qtail = sc->qcount = 0;
753                 crit_exit();
754
755                 break;
756         case MOUSE_GETLEVEL:
757                 *(int *)addr = sc->mode.level;
758                 break;
759         case MOUSE_SETLEVEL:
760                 if (*(int *)addr < 0 || *(int *)addr > 1)
761                         return (EINVAL);
762
763                 crit_enter();
764                 sc->mode.level = *(int *)addr;
765
766                 if (sc->mode.level == 0) {
767                         if (sc->nbuttons > MOUSE_MSC_MAXBUTTON)
768                                 sc->hw.buttons = MOUSE_MSC_MAXBUTTON;
769                         else
770                                 sc->hw.buttons = sc->nbuttons;
771                         sc->mode.protocol = MOUSE_PROTO_MSC;
772                         sc->mode.packetsize = MOUSE_MSC_PACKETSIZE;
773                         sc->mode.syncmask[0] = MOUSE_MSC_SYNCMASK;
774                         sc->mode.syncmask[1] = MOUSE_MSC_SYNC;
775                 } else if (sc->mode.level == 1) {
776                         if (sc->nbuttons > MOUSE_SYS_MAXBUTTON)
777                                 sc->hw.buttons = MOUSE_SYS_MAXBUTTON;
778                         else
779                                 sc->hw.buttons = sc->nbuttons;
780                         sc->mode.protocol = MOUSE_PROTO_SYSMOUSE;
781                         sc->mode.packetsize = MOUSE_SYS_PACKETSIZE;
782                         sc->mode.syncmask[0] = MOUSE_SYS_SYNCMASK;
783                         sc->mode.syncmask[1] = MOUSE_SYS_SYNC;
784                 }
785
786                 bzero(sc->qbuf, sizeof(sc->qbuf));
787                 sc->qhead = sc->qtail = sc->qcount = 0;
788                 crit_exit();
789
790                 break;
791         case MOUSE_GETSTATUS: {
792                 mousestatus_t *status = (mousestatus_t *) addr;
793
794                 crit_enter();
795                 *status = sc->status;
796                 sc->status.obutton = sc->status.button;
797                 sc->status.button = 0;
798                 sc->status.dx = sc->status.dy = sc->status.dz = 0;
799                 crit_exit();
800
801                 if (status->dx || status->dy || status->dz)
802                         status->flags |= MOUSE_POSCHANGED;
803                 if (status->button != status->obutton)
804                         status->flags |= MOUSE_BUTTONSCHANGED;
805                 break;
806                 }
807         default:
808                 error = ENOTTY;
809         }
810
811         return error;
812 }
813
814 DRIVER_MODULE(ums, uhub, ums_driver, ums_devclass, usbd_driver_load, 0);