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