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