dev - Add kq support to usbmisc devices
[dragonfly.git] / sys / dev / usbmisc / ugen / ugen.c
1 /*
2  * $NetBSD: ugen.c,v 1.27 1999/10/28 12:08:38 augustss Exp $
3  * $NetBSD: ugen.c,v 1.59 2002/07/11 21:14:28 augustss Exp $
4  * $FreeBSD: src/sys/dev/usb/ugen.c,v 1.81 2003/11/09 09:17:22 tanimura Exp $
5  * $DragonFly: src/sys/dev/usbmisc/ugen/ugen.c,v 1.34 2008/05/13 08:35:12 hasso Exp $
6  */
7
8 /* 
9  * Also already merged from NetBSD:
10  *      $NetBSD: ugen.c,v 1.61 2002/09/23 05:51:20 simonb Exp $
11  *      $NetBSD: ugen.c,v 1.64 2003/06/28 14:21:46 darrenr Exp $
12  *      $NetBSD: ugen.c,v 1.65 2003/06/29 22:30:56 fvdl Exp $
13  */
14
15 /*
16  * Copyright (c) 1998 The NetBSD Foundation, Inc.
17  * All rights reserved.
18  *
19  * This code is derived from software contributed to The NetBSD Foundation
20  * by Lennart Augustsson (lennart@augustsson.net) at
21  * Carlstedt Research & Technology.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the above copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *        This product includes software developed by the NetBSD
34  *        Foundation, Inc. and its contributors.
35  * 4. Neither the name of The NetBSD Foundation nor the names of its
36  *    contributors may be used to endorse or promote products derived
37  *    from this software without specific prior written permission.
38  *
39  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
40  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
41  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
43  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
44  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
45  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
46  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
47  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
48  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
49  * POSSIBILITY OF SUCH DAMAGE.
50  */
51
52
53 #include <sys/param.h>
54 #include <sys/systm.h>
55 #include <sys/kernel.h>
56 #include <sys/malloc.h>
57 #include <sys/module.h>
58 #include <sys/bus.h>
59 #include <sys/conf.h>
60 #include <sys/fcntl.h>
61 #include <sys/filio.h>
62 #include <sys/tty.h>
63 #include <sys/file.h>
64 #include <sys/select.h>
65 #include <sys/vnode.h>
66 #include <sys/poll.h>
67 #include <sys/event.h>
68 #include <sys/sysctl.h>
69 #include <sys/thread2.h>
70
71 #include <bus/usb/usb.h>
72 #include <bus/usb/usbdi.h>
73 #include <bus/usb/usbdi_util.h>
74
75 #include "ugenbuf.h"
76
77 SYSCTL_NODE(_hw_usb, OID_AUTO, ugen, CTLFLAG_RW, 0, "USB ugen");
78
79 #ifdef USB_DEBUG
80 #define DPRINTF(x)      if (ugendebug) kprintf x
81 #define DPRINTFN(n,x)   if (ugendebug>(n)) kprintf x
82 int     ugendebug = 0;
83 SYSCTL_INT(_hw_usb_ugen, OID_AUTO, debug, CTLFLAG_RW,
84            &ugendebug, 0, "ugen debug level");
85 #else
86 #define DPRINTF(x)
87 #define DPRINTFN(n,x)
88 #endif
89
90 static int ugen_bufsize = 16384;
91 SYSCTL_INT(_hw_usb_ugen, OID_AUTO, bufsize, CTLFLAG_RW,
92            &ugen_bufsize, 0, "ugen temporary buffer size");
93
94 #define UGEN_CHUNK      128     /* chunk size for read */
95 #define UGEN_IBSIZE     1020    /* buffer size */
96
97 #define UGEN_NISOFRAMES 500     /* 0.5 seconds worth */
98 #define UGEN_NISOREQS   6       /* number of outstanding xfer requests */
99 #define UGEN_NISORFRMS  4       /* number of frames (miliseconds) per req */
100
101 struct ugen_endpoint {
102         struct ugen_softc *sc;
103         cdev_t dev;
104         usb_endpoint_descriptor_t *edesc;
105         usbd_interface_handle iface;
106         int state;
107 #define UGEN_ASLP       0x02    /* waiting for data */
108 #define UGEN_SHORT_OK   0x04    /* short xfers are OK */
109         usbd_pipe_handle pipeh;
110         struct clist q;
111         struct selinfo rsel;
112         u_char *ibuf;           /* start of buffer (circular for isoc) */
113         u_char *fill;           /* location for input (isoc) */
114         u_char *limit;          /* end of circular buffer (isoc) */
115         u_char *cur;            /* current read location (isoc) */
116         u_int32_t timeout;
117         struct isoreq {
118                 struct ugen_endpoint *sce;
119                 usbd_xfer_handle xfer;
120                 void *dmabuf;
121                 u_int16_t sizes[UGEN_NISORFRMS];
122         } isoreqs[UGEN_NISOREQS];
123 };
124
125 struct ugen_softc {
126         device_t sc_dev;                /* base device */
127         usbd_device_handle sc_udev;
128
129         char sc_is_open[USB_MAX_ENDPOINTS];
130         struct ugen_endpoint sc_endpoints[USB_MAX_ENDPOINTS][2];
131 #define OUT 0
132 #define IN  1
133
134         int sc_refcnt;
135         u_char sc_dying;
136 };
137
138 d_open_t  ugenopen;
139 d_close_t ugenclose;
140 d_read_t  ugenread;
141 d_write_t ugenwrite;
142 d_ioctl_t ugenioctl;
143 d_poll_t  ugenpoll;
144 d_kqfilter_t ugenkqfilter;
145
146 static void ugen_filt_detach(struct knote *);
147 static int ugen_filt_read(struct knote *, long);
148 static int ugen_filt_write(struct knote *, long);
149
150 #define UGEN_CDEV_MAJOR 114
151
152 static struct dev_ops ugen_ops = {
153         { "ugen", UGEN_CDEV_MAJOR, D_KQFILTER },
154         .d_open =       ugenopen,
155         .d_close =      ugenclose,
156         .d_read =       ugenread,
157         .d_write =      ugenwrite,
158         .d_ioctl =      ugenioctl,
159         .d_poll =       ugenpoll,
160         .d_kqfilter =   ugenkqfilter
161 };
162
163 static void ugenintr(usbd_xfer_handle xfer, usbd_private_handle addr,
164                             usbd_status status);
165 static void ugen_isoc_rintr(usbd_xfer_handle xfer, usbd_private_handle addr,
166                             usbd_status status);
167 static int ugen_do_read(struct ugen_softc *, int, struct uio *, int);
168 static int ugen_do_write(struct ugen_softc *, int, struct uio *, int);
169 static int ugen_do_ioctl(struct ugen_softc *, int, u_long,
170                             caddr_t, int);
171 static void ugen_make_devnodes(struct ugen_softc *sc);
172 static void ugen_destroy_devnodes(struct ugen_softc *sc);
173 static int ugen_set_config(struct ugen_softc *sc, int configno);
174 static usb_config_descriptor_t *ugen_get_cdesc(struct ugen_softc *sc,
175                                                 int index, int *lenp);
176 static usbd_status ugen_set_interface(struct ugen_softc *, int, int);
177 static int ugen_get_alt_index(struct ugen_softc *sc, int ifaceidx);
178
179 #define UGENUNIT(n) ((lminor(n) >> 4) & 0xff)
180 #define UGENENDPOINT(n) (minor(n) & 0xf)
181 #define UGENMINOR(u, e) (((u & 0xf) << 4) | ((u & 0xf0) << 12) | (e))
182 #define UGENUNITMASK    0xffff00f0
183
184 static device_probe_t ugen_match;
185 static device_attach_t ugen_attach;
186 static device_detach_t ugen_detach;
187
188 static devclass_t ugen_devclass;
189
190 static kobj_method_t ugen_methods[] = {
191         DEVMETHOD(device_probe, ugen_match),
192         DEVMETHOD(device_attach, ugen_attach),
193         DEVMETHOD(device_detach, ugen_detach),
194         {0,0}
195 };
196
197 static driver_t ugen_driver = {
198         "ugen",
199         ugen_methods,
200         sizeof(struct ugen_softc)
201 };
202
203 MODULE_DEPEND(ugen, usb, 1, 1, 1);
204
205 static int
206 ugen_match(device_t self)
207 {
208         struct usb_attach_arg *uaa = device_get_ivars(self);
209
210 #if 0
211         if (uaa->matchlvl)
212                 return (uaa->matchlvl);
213 #endif
214         if (uaa->usegeneric)
215                 return (UMATCH_GENERIC);
216         else
217                 return (UMATCH_NONE);
218 }
219
220 static int
221 ugen_attach(device_t self)
222 {
223         struct ugen_softc *sc = device_get_softc(self);
224         struct usb_attach_arg *uaa = device_get_ivars(self);
225         usbd_device_handle udev;
226         usbd_status err;
227         int conf;
228
229         sc->sc_dev = self;
230         sc->sc_udev = udev = uaa->device;
231
232         memset(sc->sc_endpoints, 0, sizeof sc->sc_endpoints);
233
234         /* First set configuration index 0, the default one for ugen. */
235         err = usbd_set_config_index(udev, 0, 0);
236         if (err) {
237                 kprintf("%s: setting configuration index 0 failed\n",
238                        device_get_nameunit(sc->sc_dev));
239                 sc->sc_dying = 1;
240                 return ENXIO;
241         }
242         conf = usbd_get_config_descriptor(udev)->bConfigurationValue;
243
244         /* Set up all the local state for this configuration. */
245         err = ugen_set_config(sc, conf);
246         if (err) {
247                 kprintf("%s: setting configuration %d failed\n",
248                        device_get_nameunit(sc->sc_dev), conf);
249                 sc->sc_dying = 1;
250                 return ENXIO;
251         }
252
253         /* the main device, ctrl endpoint */
254         make_dev(&ugen_ops, UGENMINOR(device_get_unit(sc->sc_dev), 0),
255                  UID_ROOT, GID_OPERATOR, 0644,
256                  "%s", device_get_nameunit(sc->sc_dev));
257
258         usbd_add_drv_event(USB_EVENT_DRIVER_ATTACH, sc->sc_udev, sc->sc_dev);
259         return 0;
260 }
261
262 static void
263 ugen_make_devnodes(struct ugen_softc *sc)
264 {
265         int endptno;
266         cdev_t dev;
267
268         for (endptno = 1; endptno < USB_MAX_ENDPOINTS; endptno++) {
269                 if (sc->sc_endpoints[endptno][IN].sc != NULL ||
270                     sc->sc_endpoints[endptno][OUT].sc != NULL ) {
271                         /* endpt can be 0x81 and 0x01, representing
272                          * endpoint address 0x01 and IN/OUT directions.
273                          * We map both endpts to the same device,
274                          * IN is reading from it, OUT is writing to it.
275                          *
276                          * In the if clause above we check whether one
277                          * of the structs is populated.
278                          */
279                         dev = make_dev(&ugen_ops,
280                                 UGENMINOR(device_get_unit(sc->sc_dev), endptno),
281                                 UID_ROOT, GID_OPERATOR, 0644,
282                                 "%s.%d",
283                                 device_get_nameunit(sc->sc_dev), endptno);
284                         if (sc->sc_endpoints[endptno][IN].sc != NULL) {
285                                 reference_dev(dev);
286                                 if (sc->sc_endpoints[endptno][IN].dev)
287                                         release_dev(sc->sc_endpoints[endptno][IN].dev);
288                                 sc->sc_endpoints[endptno][IN].dev = dev;
289                         }
290                         if (sc->sc_endpoints[endptno][OUT].sc != NULL) {
291                                 reference_dev(dev);
292                                 if (sc->sc_endpoints[endptno][OUT].dev)
293                                         release_dev(sc->sc_endpoints[endptno][OUT].dev);
294                                 sc->sc_endpoints[endptno][OUT].dev = dev;
295                         }
296                 }
297         }
298 }
299
300 static void
301 ugen_destroy_devnodes(struct ugen_softc *sc)
302 {
303         int endptno, prev_sc_dying;
304         cdev_t dev;
305
306         prev_sc_dying = sc->sc_dying;
307         sc->sc_dying = 1;
308
309         /* destroy all devices for the other (existing) endpoints as well */
310         for (endptno = 1; endptno < USB_MAX_ENDPOINTS; endptno++) {
311                 if (sc->sc_endpoints[endptno][IN].sc != NULL ||
312                     sc->sc_endpoints[endptno][OUT].sc != NULL ) {
313                         /* endpt can be 0x81 and 0x01, representing
314                          * endpoint address 0x01 and IN/OUT directions.
315                          * We map both endpoint addresses to the same device,
316                          * IN is reading from it, OUT is writing to it.
317                          *
318                          * In the if clause above we check whether one
319                          * of the structs is populated.
320                          */
321                         dev = sc->sc_endpoints[endptno][IN].dev;
322                         if (dev != NULL) {
323                                 destroy_dev(dev);
324                                 sc->sc_endpoints[endptno][IN].dev = NULL;
325                         }
326                         dev = sc->sc_endpoints[endptno][OUT].dev;
327                         if (dev != NULL) {
328                                 destroy_dev(dev);
329                                 sc->sc_endpoints[endptno][OUT].dev = NULL;
330                         }
331                 }
332         }
333         sc->sc_dying = prev_sc_dying;
334 }
335
336 static int
337 ugen_set_config(struct ugen_softc *sc, int configno)
338 {
339         usbd_device_handle dev = sc->sc_udev;
340         usbd_interface_handle iface;
341         usb_endpoint_descriptor_t *ed;
342         struct ugen_endpoint *sce;
343         u_int8_t niface, nendpt;
344         int ifaceno, endptno, endpt;
345         usbd_status err;
346         int dir;
347
348         DPRINTFN(1,("ugen_set_config: %s to configno %d, sc=%p\n",
349                     device_get_nameunit(sc->sc_dev), configno, sc));
350
351         ugen_destroy_devnodes(sc);
352
353         /* We start at 1, not 0, because we don't care whether the
354          * control endpoint is open or not. It is always present.
355          */
356         for (endptno = 1; endptno < USB_MAX_ENDPOINTS; endptno++) {
357                 if (sc->sc_is_open[endptno]) {
358                         DPRINTFN(1,
359                              ("ugen_set_config: %s - endpoint %d is open\n",
360                               device_get_nameunit(sc->sc_dev), endptno));
361                         return (USBD_IN_USE);
362                 }
363         }
364
365         /* Avoid setting the current value. */
366         if (usbd_get_config_descriptor(dev)->bConfigurationValue != configno) {
367                 err = usbd_set_config_no(dev, configno, 1);
368                 if (err)
369                         return (err);
370         }
371
372         err = usbd_interface_count(dev, &niface);
373         if (err)
374                 return (err);
375         memset(sc->sc_endpoints, 0, sizeof sc->sc_endpoints);
376         for (ifaceno = 0; ifaceno < niface; ifaceno++) {
377                 DPRINTFN(1,("ugen_set_config: ifaceno %d\n", ifaceno));
378                 err = usbd_device2interface_handle(dev, ifaceno, &iface);
379                 if (err)
380                         return (err);
381                 err = usbd_endpoint_count(iface, &nendpt);
382                 if (err)
383                         return (err);
384                 for (endptno = 0; endptno < nendpt; endptno++) {
385                         ed = usbd_interface2endpoint_descriptor(iface,endptno);
386                         endpt = ed->bEndpointAddress;
387                         dir = UE_GET_DIR(endpt) == UE_DIR_IN ? IN : OUT;
388                         sce = &sc->sc_endpoints[UE_GET_ADDR(endpt)][dir];
389                         DPRINTFN(1,("ugen_set_config: endptno %d, endpt=0x%02x"
390                                     "(%d,%d), sce=%p\n",
391                                     endptno, endpt, UE_GET_ADDR(endpt),
392                                     UE_GET_DIR(endpt), sce));
393                         sce->sc = sc;
394                         sce->edesc = ed;
395                         sce->iface = iface;
396                 }
397         }
398
399         ugen_make_devnodes(sc);
400
401         return (USBD_NORMAL_COMPLETION);
402 }
403
404 int
405 ugenopen(struct dev_open_args *ap)
406 {
407         cdev_t dev = ap->a_head.a_dev;
408         struct ugen_softc *sc;
409         int unit = UGENUNIT(dev);
410         int endpt = UGENENDPOINT(dev);
411         usb_endpoint_descriptor_t *edesc;
412         struct ugen_endpoint *sce;
413         int dir, isize;
414         usbd_status err;
415         usbd_xfer_handle xfer;
416         void *buf;
417         int i, j;
418
419         sc = devclass_get_softc(ugen_devclass, unit);
420         if (sc == NULL)
421                 return (ENXIO);
422
423         DPRINTFN(5, ("ugenopen: flag=%d, mode=%d, unit=%d endpt=%d\n",
424                      ap->a_oflags, ap->a_devtype, unit, endpt));
425
426         if (sc->sc_dying)
427                 return (ENXIO);
428
429         if (sc->sc_is_open[endpt])
430                 return (EBUSY);
431
432         if (endpt == USB_CONTROL_ENDPOINT) {
433                 sc->sc_is_open[USB_CONTROL_ENDPOINT] = 1;
434                 return (0);
435         }
436
437         /* Make sure there are pipes for all directions. */
438         for (dir = OUT; dir <= IN; dir++) {
439                 if (ap->a_oflags & (dir == OUT ? FWRITE : FREAD)) {
440                         sce = &sc->sc_endpoints[endpt][dir];
441                         if (sce == 0 || sce->edesc == 0)
442                                 return (ENXIO);
443                 }
444         }
445
446         /* Actually open the pipes. */
447         /* XXX Should back out properly if it fails. */
448         for (dir = OUT; dir <= IN; dir++) {
449                 if (!(ap->a_oflags & (dir == OUT ? FWRITE : FREAD)))
450                         continue;
451                 sce = &sc->sc_endpoints[endpt][dir];
452                 sce->state = 0;
453                 sce->timeout = USBD_NO_TIMEOUT;
454                 DPRINTFN(5, ("ugenopen: sc=%p, endpt=%d, dir=%d, sce=%p\n",
455                              sc, endpt, dir, sce));
456                 edesc = sce->edesc;
457                 switch (edesc->bmAttributes & UE_XFERTYPE) {
458                 case UE_INTERRUPT:
459                         if (dir == OUT) {
460                                 err = usbd_open_pipe(sce->iface,
461                                     edesc->bEndpointAddress, 0, &sce->pipeh);
462                                 if (err)
463                                         return (EIO);
464                                 break;
465                         }
466                         isize = UGETW(edesc->wMaxPacketSize);
467                         if (isize == 0) /* shouldn't happen */
468                                 return (EINVAL);
469                         sce->ibuf = kmalloc(isize, M_USBDEV, M_WAITOK);
470                         DPRINTFN(5, ("ugenopen: intr endpt=%d,isize=%d\n",
471                                      endpt, isize));
472                         if ((clist_alloc_cblocks(&sce->q, UGEN_IBSIZE,
473                                                  UGEN_IBSIZE), 0) == -1)
474                                 return (ENOMEM);
475                         err = usbd_open_pipe_intr(sce->iface,
476                                 edesc->bEndpointAddress,
477                                 USBD_SHORT_XFER_OK, &sce->pipeh, sce,
478                                 sce->ibuf, isize, ugenintr,
479                                 USBD_DEFAULT_INTERVAL);
480                         if (err) {
481                                 kfree(sce->ibuf, M_USBDEV);
482                                 clist_free_cblocks(&sce->q);
483                                 return (EIO);
484                         }
485                         DPRINTFN(5, ("ugenopen: interrupt open done\n"));
486                         break;
487                 case UE_BULK:
488                         err = usbd_open_pipe(sce->iface,
489                                   edesc->bEndpointAddress, 0, &sce->pipeh);
490                         if (err)
491                                 return (EIO);
492                         break;
493                 case UE_ISOCHRONOUS:
494                         if (dir == OUT)
495                                 return (EINVAL);
496                         isize = UGETW(edesc->wMaxPacketSize);
497                         if (isize == 0) /* shouldn't happen */
498                                 return (EINVAL);
499                         sce->ibuf = kmalloc(isize * UGEN_NISOFRAMES,
500                                 M_USBDEV, M_WAITOK);
501                         sce->cur = sce->fill = sce->ibuf;
502                         sce->limit = sce->ibuf + isize * UGEN_NISOFRAMES;
503                         DPRINTFN(5, ("ugenopen: isoc endpt=%d, isize=%d\n",
504                                      endpt, isize));
505                         err = usbd_open_pipe(sce->iface,
506                                   edesc->bEndpointAddress, 0, &sce->pipeh);
507                         if (err) {
508                                 kfree(sce->ibuf, M_USBDEV);
509                                 return (EIO);
510                         }
511                         for(i = 0; i < UGEN_NISOREQS; ++i) {
512                                 sce->isoreqs[i].sce = sce;
513                                 xfer = usbd_alloc_xfer(sc->sc_udev);
514                                 if (xfer == 0)
515                                         goto bad;
516                                 sce->isoreqs[i].xfer = xfer;
517                                 buf = usbd_alloc_buffer
518                                         (xfer, isize * UGEN_NISORFRMS);
519                                 if (buf == 0) {
520                                         i++;
521                                         goto bad;
522                                 }
523                                 sce->isoreqs[i].dmabuf = buf;
524                                 for(j = 0; j < UGEN_NISORFRMS; ++j)
525                                         sce->isoreqs[i].sizes[j] = isize;
526                                 usbd_setup_isoc_xfer
527                                         (xfer, sce->pipeh, &sce->isoreqs[i],
528                                          sce->isoreqs[i].sizes,
529                                          UGEN_NISORFRMS, USBD_NO_COPY,
530                                          ugen_isoc_rintr);
531                                 (void)usbd_transfer(xfer);
532                         }
533                         DPRINTFN(5, ("ugenopen: isoc open done\n"));
534                         break;
535                 bad:
536                         while (--i >= 0) /* implicit buffer free */
537                                 usbd_free_xfer(sce->isoreqs[i].xfer);
538                         return (ENOMEM);
539                 case UE_CONTROL:
540                         sce->timeout = USBD_DEFAULT_TIMEOUT;
541                         return (EINVAL);
542                 }
543         }
544         sc->sc_is_open[endpt] = 1;
545         return (0);
546 }
547
548 int
549 ugenclose(struct dev_close_args *ap)
550 {
551         cdev_t dev = ap->a_head.a_dev;
552         int endpt = UGENENDPOINT(dev);
553         struct ugen_softc *sc;
554         struct ugen_endpoint *sce;
555         int dir;
556         int i;
557
558         sc = devclass_get_softc(ugen_devclass, UGENUNIT(dev));
559
560         DPRINTFN(5, ("ugenclose: flag=%d, mode=%d, unit=%d, endpt=%d\n",
561                      ap->a_fflag, ap->a_devtype, UGENUNIT(dev), endpt));
562
563 #ifdef DIAGNOSTIC
564         if (!sc->sc_is_open[endpt]) {
565                 kprintf("ugenclose: not open\n");
566                 return (EINVAL);
567         }
568 #endif
569
570         if (endpt == USB_CONTROL_ENDPOINT) {
571                 DPRINTFN(5, ("ugenclose: close control\n"));
572                 sc->sc_is_open[endpt] = 0;
573                 return (0);
574         }
575
576         for (dir = OUT; dir <= IN; dir++) {
577                 if (!(ap->a_fflag & (dir == OUT ? FWRITE : FREAD)))
578                         continue;
579                 sce = &sc->sc_endpoints[endpt][dir];
580                 if (sce->pipeh == NULL)
581                         continue;
582                 DPRINTFN(5, ("ugenclose: endpt=%d dir=%d sce=%p\n",
583                              endpt, dir, sce));
584
585                 usbd_abort_pipe(sce->pipeh);
586                 usbd_close_pipe(sce->pipeh);
587                 sce->pipeh = NULL;
588
589                 switch (sce->edesc->bmAttributes & UE_XFERTYPE) {
590                 case UE_INTERRUPT:
591                         ndflush(&sce->q, sce->q.c_cc);
592                         clist_free_cblocks(&sce->q);
593                         break;
594                 case UE_ISOCHRONOUS:
595                         for (i = 0; i < UGEN_NISOREQS; ++i)
596                                 usbd_free_xfer(sce->isoreqs[i].xfer);
597                 default:
598                         break;
599                 }
600
601                 if (sce->ibuf != NULL) {
602                         kfree(sce->ibuf, M_USBDEV);
603                         sce->ibuf = NULL;
604                         clist_free_cblocks(&sce->q);
605                 }
606         }
607         sc->sc_is_open[endpt] = 0;
608
609         return (0);
610 }
611
612 static int
613 ugen_do_read(struct ugen_softc *sc, int endpt, struct uio *uio, int flag)
614 {
615         struct ugen_endpoint *sce = &sc->sc_endpoints[endpt][IN];
616         u_int32_t n, tn;
617         char *buf;
618         usbd_xfer_handle xfer;
619         usbd_status err;
620         int error = 0;
621         int ugen_bbsize;
622         u_char buffer[UGEN_CHUNK];
623
624         DPRINTFN(5, ("%s: ugenread: %d\n", device_get_nameunit(sc->sc_dev), endpt));
625
626         if (sc->sc_dying)
627                 return (EIO);
628
629         if (endpt == USB_CONTROL_ENDPOINT)
630                 return (ENODEV);
631
632 #ifdef DIAGNOSTIC
633         if (sce->edesc == NULL) {
634                 kprintf("ugenread: no edesc\n");
635                 return (EIO);
636         }
637         if (sce->pipeh == NULL) {
638                 kprintf("ugenread: no pipe\n");
639                 return (EIO);
640         }
641 #endif
642
643         buf = getugenbuf(ugen_bufsize, &ugen_bbsize);
644
645         switch (sce->edesc->bmAttributes & UE_XFERTYPE) {
646         case UE_INTERRUPT:
647                 /* Block until activity occurred. */
648                 crit_enter();
649                 while (sce->q.c_cc == 0) {
650                         if (flag & IO_NDELAY) {
651                                 crit_exit();
652                                 error = EWOULDBLOCK;
653                                 goto done;
654                         }
655                         sce->state |= UGEN_ASLP;
656                         DPRINTFN(5, ("ugenread: sleep on %p\n", sce));
657                         error = tsleep(sce, PCATCH, "ugenri",
658                             (sce->timeout * hz + 999) / 1000);
659                         sce->state &= ~UGEN_ASLP;
660                         DPRINTFN(5, ("ugenread: woke, error=%d\n", error));
661                         if (sc->sc_dying)
662                                 error = EIO;
663                         if (error == EAGAIN) {
664                                 error = 0;      /* timeout, return 0 bytes */
665                                 break;
666                         }
667                         if (error)
668                                 break;
669                 }
670                 crit_exit();
671
672                 /* Transfer as many chunks as possible. */
673                 while (sce->q.c_cc > 0 && uio->uio_resid > 0 && !error) {
674                         n = szmin(sce->q.c_cc, uio->uio_resid);
675                         if (n > sizeof(buffer))
676                                 n = sizeof(buffer);
677
678                         /* Remove a small chunk from the input queue. */
679                         q_to_b(&sce->q, buffer, n);
680                         DPRINTFN(5, ("ugenread: got %d chars\n", n));
681
682                         /* Copy the data to the user process. */
683                         error = uiomove(buffer, n, uio);
684                         if (error)
685                                 break;
686                 }
687                 break;
688         case UE_BULK:
689                 xfer = usbd_alloc_xfer(sc->sc_udev);
690                 if (xfer == 0) {
691                         error = ENOMEM;
692                         goto done;
693                 }
694                 while ((n = szmin(ugen_bbsize, uio->uio_resid)) != 0) {
695                         DPRINTFN(1, ("ugenread: start transfer %d bytes\n",n));
696                         tn = n;
697                         err = usbd_bulk_transfer(
698                                 xfer, sce->pipeh,
699                                 sce->state & UGEN_SHORT_OK ?
700                                     USBD_SHORT_XFER_OK : 0,
701                                 sce->timeout, buf, &tn, "ugenrb");
702                         if (err) {
703                                 if (err == USBD_INTERRUPTED)
704                                         error = EINTR;
705                                 else if (err == USBD_TIMEOUT)
706                                         error = ETIMEDOUT;
707                                 else
708                                         error = EIO;
709                                 break;
710                         }
711                         DPRINTFN(1, ("ugenread: got %d bytes\n", tn));
712                         error = uiomove(buf, tn, uio);
713                         if (error || tn < n)
714                                 break;
715                 }
716                 usbd_free_xfer(xfer);
717                 break;
718         case UE_ISOCHRONOUS:
719                 crit_enter();
720                 while (sce->cur == sce->fill) {
721                         if (flag & IO_NDELAY) {
722                                 crit_exit();
723                                 error = EWOULDBLOCK;
724                                 goto done;
725                         }
726                         sce->state |= UGEN_ASLP;
727                         DPRINTFN(5, ("ugenread: sleep on %p\n", sce));
728                         error = tsleep(sce, PCATCH, "ugenri",
729                             (sce->timeout * hz + 999) / 1000);
730                         sce->state &= ~UGEN_ASLP;
731                         DPRINTFN(5, ("ugenread: woke, error=%d\n", error));
732                         if (sc->sc_dying)
733                                 error = EIO;
734                         if (error == EAGAIN) {
735                                 error = 0;      /* timeout, return 0 bytes */
736                                 break;
737                         }
738                         if (error)
739                                 break;
740                 }
741
742                 while (sce->cur != sce->fill && uio->uio_resid > 0 && !error) {
743                         if (sce->fill > sce->cur)
744                                 n = szmin(sce->fill - sce->cur, uio->uio_resid);
745                         else
746                                 n = szmin(sce->limit- sce->cur, uio->uio_resid);
747
748                         DPRINTFN(5, ("ugenread: isoc got %d chars\n", n));
749
750                         /* Copy the data to the user process. */
751                         error = uiomove(sce->cur, n, uio);
752                         if (error)
753                                 break;
754                         sce->cur += n;
755                         if(sce->cur >= sce->limit)
756                                 sce->cur = sce->ibuf;
757                 }
758                 crit_exit();
759                 break;
760
761
762         default:
763                 error = ENXIO;
764                 break;
765         }
766 done:
767         relugenbuf(buf, ugen_bbsize);
768         return (error);
769 }
770
771 int
772 ugenread(struct dev_read_args *ap)
773 {
774         cdev_t dev = ap->a_head.a_dev;
775         int endpt = UGENENDPOINT(dev);
776         struct ugen_softc *sc;
777         int error;
778
779         sc = devclass_get_softc(ugen_devclass, UGENUNIT(dev));
780
781         if (sc->sc_dying)
782                 return (EIO);
783
784         sc->sc_refcnt++;
785         error = ugen_do_read(sc, endpt, ap->a_uio, ap->a_ioflag);
786         if (--sc->sc_refcnt < 0)
787                 usb_detach_wakeup(sc->sc_dev);
788         return (error);
789 }
790
791 static int
792 ugen_do_write(struct ugen_softc *sc, int endpt, struct uio *uio, int flag)
793 {
794         struct ugen_endpoint *sce = &sc->sc_endpoints[endpt][OUT];
795         u_int32_t n;
796         int error = 0;
797         int ugen_bbsize;
798         char *buf;
799         usbd_xfer_handle xfer;
800         usbd_status err;
801
802         DPRINTFN(5, ("%s: ugenwrite: %d\n", device_get_nameunit(sc->sc_dev), endpt));
803
804         if (sc->sc_dying)
805                 return (EIO);
806
807         if (endpt == USB_CONTROL_ENDPOINT)
808                 return (ENODEV);
809
810 #ifdef DIAGNOSTIC
811         if (sce->edesc == NULL) {
812                 kprintf("ugenwrite: no edesc\n");
813                 return (EIO);
814         }
815         if (sce->pipeh == NULL) {
816                 kprintf("ugenwrite: no pipe\n");
817                 return (EIO);
818         }
819 #endif
820
821         buf = getugenbuf(ugen_bufsize, &ugen_bbsize);
822
823         switch (sce->edesc->bmAttributes & UE_XFERTYPE) {
824         case UE_BULK:
825                 xfer = usbd_alloc_xfer(sc->sc_udev);
826                 if (xfer == 0) {
827                         error = EIO;
828                         goto done;
829                 }
830                 while ((n = szmin(ugen_bbsize, uio->uio_resid)) != 0) {
831                         error = uiomove(buf, n, uio);
832                         if (error)
833                                 break;
834                         DPRINTFN(1, ("ugenwrite: transfer %d bytes\n", n));
835                         err = usbd_bulk_transfer(xfer, sce->pipeh, 0,
836                                   sce->timeout, buf, &n,"ugenwb");
837                         if (err) {
838                                 if (err == USBD_INTERRUPTED)
839                                         error = EINTR;
840                                 else if (err == USBD_TIMEOUT)
841                                         error = ETIMEDOUT;
842                                 else
843                                         error = EIO;
844                                 break;
845                         }
846                 }
847                 usbd_free_xfer(xfer);
848                 break;
849         case UE_INTERRUPT:
850                 xfer = usbd_alloc_xfer(sc->sc_udev);
851                 if (xfer == 0) {
852                         error = EIO;
853                         goto done;
854                 }
855                 while ((n = szmin(UGETW(sce->edesc->wMaxPacketSize),
856                                 uio->uio_resid)) != 0) {
857                         error = uiomove(buf, n, uio);
858                         if (error)
859                                 break;
860                         DPRINTFN(1, ("ugenwrite: transfer %d bytes\n", n));
861                         err = usbd_intr_transfer(xfer, sce->pipeh, 0,
862                                   sce->timeout, buf, &n,"ugenwi");
863                         if (err) {
864                                 if (err == USBD_INTERRUPTED)
865                                         error = EINTR;
866                                 else if (err == USBD_TIMEOUT)
867                                         error = ETIMEDOUT;
868                                 else
869                                         error = EIO;
870                                 break;
871                         }
872                 }
873                 usbd_free_xfer(xfer);
874                 break;
875         default:
876                 error = ENXIO;
877                 break;
878         }
879 done:
880         relugenbuf(buf, ugen_bbsize);
881         return (error);
882 }
883
884 int
885 ugenwrite(struct dev_write_args *ap)
886 {
887         cdev_t dev = ap->a_head.a_dev;
888         int endpt = UGENENDPOINT(dev);
889         struct ugen_softc *sc;
890         int error;
891
892         sc = devclass_get_softc(ugen_devclass, UGENUNIT(dev));
893
894         if (sc->sc_dying)
895                 return (EIO);
896
897         sc->sc_refcnt++;
898         error = ugen_do_write(sc, endpt, ap->a_uio, ap->a_ioflag);
899         if (--sc->sc_refcnt < 0)
900                 usb_detach_wakeup(sc->sc_dev);
901         return (error);
902 }
903
904 static int
905 ugen_detach(device_t self)
906 {
907         struct ugen_softc *sc = device_get_softc(self);
908         struct ugen_endpoint *sce;
909         int i, dir;
910
911         DPRINTF(("ugen_detach: sc=%p\n", sc));
912
913         sc->sc_dying = 1;
914         /* Abort all pipes.  Causes processes waiting for transfer to wake. */
915         for (i = 0; i < USB_MAX_ENDPOINTS; i++) {
916                 for (dir = OUT; dir <= IN; dir++) {
917                         sce = &sc->sc_endpoints[i][dir];
918                         if (sce && sce->pipeh)
919                                 usbd_abort_pipe(sce->pipeh);
920                         selwakeup(&sce->rsel);
921                 }
922         }
923         crit_enter();
924         if (--sc->sc_refcnt >= 0) {
925                 /* Wake everyone */
926                 for (i = 0; i < USB_MAX_ENDPOINTS; i++)
927                         wakeup(&sc->sc_endpoints[i][IN]);
928                 /* Wait for processes to go away. */
929                 usb_detach_wait(sc->sc_dev);
930         }
931         crit_exit();
932
933         /* destroy the device for the control endpoint */
934         ugen_destroy_devnodes(sc);
935         dev_ops_remove_minor(&ugen_ops,
936                     /*UGENUNITMASK,*/ UGENMINOR(device_get_unit(sc->sc_dev), 0));
937         usbd_add_drv_event(USB_EVENT_DRIVER_DETACH, sc->sc_udev, sc->sc_dev);
938         return (0);
939 }
940
941 static void
942 ugenintr(usbd_xfer_handle xfer, usbd_private_handle addr, usbd_status status)
943 {
944         struct ugen_endpoint *sce = addr;
945         /*struct ugen_softc *sc = sce->sc;*/
946         u_int32_t count;
947         u_char *ibuf;
948
949         if (status == USBD_CANCELLED)
950                 return;
951
952         if (status != USBD_NORMAL_COMPLETION) {
953                 DPRINTF(("ugenintr: status=%d\n", status));
954                 if (status == USBD_STALLED)
955                     usbd_clear_endpoint_stall_async(sce->pipeh);
956                 return;
957         }
958
959         usbd_get_xfer_status(xfer, NULL, NULL, &count, NULL);
960         ibuf = sce->ibuf;
961
962         DPRINTFN(5, ("ugenintr: xfer=%p status=%d count=%d\n",
963                      xfer, status, count));
964         DPRINTFN(5, ("          data = %02x %02x %02x\n",
965                      ibuf[0], ibuf[1], ibuf[2]));
966
967         (void)b_to_q(ibuf, count, &sce->q);
968
969         if (sce->state & UGEN_ASLP) {
970                 sce->state &= ~UGEN_ASLP;
971                 DPRINTFN(5, ("ugen_intr: waking %p\n", sce));
972                 wakeup(sce);
973         }
974         selwakeup(&sce->rsel);
975 }
976
977 static void
978 ugen_isoc_rintr(usbd_xfer_handle xfer, usbd_private_handle addr,
979                 usbd_status status)
980 {
981         struct isoreq *req = addr;
982         struct ugen_endpoint *sce = req->sce;
983         u_int32_t count, n;
984         int i, isize;
985
986         /* Return if we are aborting. */
987         if (status == USBD_CANCELLED)
988                 return;
989
990         usbd_get_xfer_status(xfer, NULL, NULL, &count, NULL);
991         DPRINTFN(5,("ugen_isoc_rintr: xfer %d, count=%d\n",
992                     (int)(req - sce->isoreqs),
993                     count));
994
995         /* throw away oldest input if the buffer is full */
996         if(sce->fill < sce->cur && sce->cur <= sce->fill + count) {
997                 sce->cur += count;
998                 if(sce->cur >= sce->limit)
999                         sce->cur = sce->ibuf + (sce->limit - sce->cur);
1000                 DPRINTFN(5, ("ugen_isoc_rintr: throwing away %d bytes\n",
1001                              count));
1002         }
1003
1004         isize = UGETW(sce->edesc->wMaxPacketSize);
1005         for (i = 0; i < UGEN_NISORFRMS; i++) {
1006                 u_int32_t actlen = req->sizes[i];
1007                 char const *buf = (char const *)req->dmabuf + isize * i;
1008
1009                 /* copy data to buffer */
1010                 while (actlen > 0) {
1011                         n = min(actlen, sce->limit - sce->fill);
1012                         memcpy(sce->fill, buf, n);
1013
1014                         buf += n;
1015                         actlen -= n;
1016                         sce->fill += n;
1017                         if(sce->fill == sce->limit)
1018                                 sce->fill = sce->ibuf;
1019                 }
1020
1021                 /* setup size for next transfer */
1022                 req->sizes[i] = isize;
1023         }
1024
1025         usbd_setup_isoc_xfer(xfer, sce->pipeh, req, req->sizes, UGEN_NISORFRMS,
1026                              USBD_NO_COPY, ugen_isoc_rintr);
1027         (void)usbd_transfer(xfer);
1028
1029         if (sce->state & UGEN_ASLP) {
1030                 sce->state &= ~UGEN_ASLP;
1031                 DPRINTFN(5, ("ugen_isoc_rintr: waking %p\n", sce));
1032                 wakeup(sce);
1033         }
1034         selwakeup(&sce->rsel);
1035 }
1036
1037 static usbd_status
1038 ugen_set_interface(struct ugen_softc *sc, int ifaceidx, int altno)
1039 {
1040         usbd_interface_handle iface;
1041         usb_endpoint_descriptor_t *ed;
1042         usbd_status err;
1043         struct ugen_endpoint *sce;
1044         u_int8_t niface, nendpt, endptno, endpt;
1045         int dir;
1046
1047         DPRINTFN(15, ("ugen_set_interface %d %d\n", ifaceidx, altno));
1048
1049         err = usbd_interface_count(sc->sc_udev, &niface);
1050         if (err)
1051                 return (err);
1052         if (ifaceidx < 0 || ifaceidx >= niface)
1053                 return (USBD_INVAL);
1054
1055         err = usbd_device2interface_handle(sc->sc_udev, ifaceidx, &iface);
1056         if (err)
1057                 return (err);
1058         err = usbd_endpoint_count(iface, &nendpt);
1059         if (err)
1060                 return (err);
1061
1062         /* destroy the existing devices, we remake the new ones in a moment */
1063         ugen_destroy_devnodes(sc);
1064
1065         /* XXX should only do this after setting new altno has succeeded */
1066         for (endptno = 0; endptno < nendpt; endptno++) {
1067                 ed = usbd_interface2endpoint_descriptor(iface,endptno);
1068                 endpt = ed->bEndpointAddress;
1069                 dir = UE_GET_DIR(endpt) == UE_DIR_IN ? IN : OUT;
1070                 sce = &sc->sc_endpoints[UE_GET_ADDR(endpt)][dir];
1071                 sce->sc = 0;
1072                 sce->edesc = 0;
1073                 sce->iface = 0;
1074         }
1075
1076         /* change setting */
1077         err = usbd_set_interface(iface, altno);
1078         if (err)
1079                 return (err);
1080
1081         err = usbd_endpoint_count(iface, &nendpt);
1082         if (err)
1083                 return (err);
1084         for (endptno = 0; endptno < nendpt; endptno++) {
1085                 ed = usbd_interface2endpoint_descriptor(iface,endptno);
1086                 endpt = ed->bEndpointAddress;
1087                 dir = UE_GET_DIR(endpt) == UE_DIR_IN ? IN : OUT;
1088                 sce = &sc->sc_endpoints[UE_GET_ADDR(endpt)][dir];
1089                 sce->sc = sc;
1090                 sce->edesc = ed;
1091                 sce->iface = iface;
1092         }
1093
1094         /* make the new devices */
1095         ugen_make_devnodes(sc);
1096
1097         return (0);
1098 }
1099
1100 /* Retrieve a complete descriptor for a certain device and index. */
1101 static usb_config_descriptor_t *
1102 ugen_get_cdesc(struct ugen_softc *sc, int index, int *lenp)
1103 {
1104         usb_config_descriptor_t *cdesc, *tdesc, cdescr;
1105         int len;
1106         usbd_status err;
1107
1108         if (index == USB_CURRENT_CONFIG_INDEX) {
1109                 tdesc = usbd_get_config_descriptor(sc->sc_udev);
1110                 len = UGETW(tdesc->wTotalLength);
1111                 if (lenp)
1112                         *lenp = len;
1113                 cdesc = kmalloc(len, M_TEMP, M_INTWAIT);
1114                 memcpy(cdesc, tdesc, len);
1115                 DPRINTFN(5,("ugen_get_cdesc: current, len=%d\n", len));
1116         } else {
1117                 err = usbd_get_config_desc(sc->sc_udev, index, &cdescr);
1118                 if (err)
1119                         return (0);
1120                 len = UGETW(cdescr.wTotalLength);
1121                 DPRINTFN(5,("ugen_get_cdesc: index=%d, len=%d\n", index, len));
1122                 if (lenp)
1123                         *lenp = len;
1124                 cdesc = kmalloc(len, M_TEMP, M_INTWAIT);
1125                 err = usbd_get_config_desc_full(sc->sc_udev, index, cdesc, len);
1126                 if (err) {
1127                         kfree(cdesc, M_TEMP);
1128                         return (0);
1129                 }
1130         }
1131         return (cdesc);
1132 }
1133
1134 static int
1135 ugen_get_alt_index(struct ugen_softc *sc, int ifaceidx)
1136 {
1137         usbd_interface_handle iface;
1138         usbd_status err;
1139
1140         err = usbd_device2interface_handle(sc->sc_udev, ifaceidx, &iface);
1141         if (err)
1142                 return (-1);
1143         return (usbd_get_interface_altindex(iface));
1144 }
1145
1146 static int
1147 ugen_do_ioctl(struct ugen_softc *sc, int endpt, u_long cmd,
1148               caddr_t addr, int flag)
1149 {
1150         struct ugen_endpoint *sce;
1151         usbd_status err;
1152         usbd_interface_handle iface;
1153         struct usb_config_desc *cd;
1154         usb_config_descriptor_t *cdesc;
1155         struct usb_interface_desc *id;
1156         usb_interface_descriptor_t *idesc;
1157         struct usb_endpoint_desc *ed;
1158         usb_endpoint_descriptor_t *edesc;
1159         struct usb_alt_interface *ai;
1160         struct usb_string_desc *si;
1161         u_int8_t conf, alt;
1162
1163         DPRINTFN(5, ("ugenioctl: cmd=%08lx\n", cmd));
1164         if (sc->sc_dying)
1165                 return (EIO);
1166
1167         switch (cmd) {
1168         case USB_SET_SHORT_XFER:
1169                 /* This flag only affects read */
1170                 if (endpt == USB_CONTROL_ENDPOINT)
1171                         return (EINVAL);
1172                 sce = &sc->sc_endpoints[endpt][IN];
1173
1174                 if (sce->pipeh == NULL) {
1175                         kprintf("ugenioctl: USB_SET_SHORT_XFER, no pipe\n");
1176                         return (EIO);
1177                 }
1178
1179                 if (*(int *)addr)
1180                         sce->state |= UGEN_SHORT_OK;
1181                 else
1182                         sce->state &= ~UGEN_SHORT_OK;
1183                 return (0);
1184         case USB_SET_TIMEOUT:
1185                 sce = &sc->sc_endpoints[endpt][IN];
1186                 sce->timeout = *(int *)addr;
1187                 sce = &sc->sc_endpoints[endpt][OUT];
1188                 sce->timeout = *(int *)addr;
1189                 return (0);
1190         default:
1191                 break;
1192         }
1193
1194         if (endpt != USB_CONTROL_ENDPOINT)
1195                 return (EINVAL);
1196
1197         switch (cmd) {
1198 #ifdef USB_DEBUG
1199         case USB_SETDEBUG:
1200                 ugendebug = *(int *)addr;
1201                 break;
1202 #endif
1203         case USB_GET_CONFIG:
1204                 err = usbd_get_config(sc->sc_udev, &conf);
1205                 if (err)
1206                         return (EIO);
1207                 *(int *)addr = conf;
1208                 break;
1209         case USB_SET_CONFIG:
1210                 if (!(flag & FWRITE))
1211                         return (EPERM);
1212                 err = ugen_set_config(sc, *(int *)addr);
1213                 switch (err) {
1214                 case USBD_NORMAL_COMPLETION:
1215                         break;
1216                 case USBD_IN_USE:
1217                         return (EBUSY);
1218                 default:
1219                         return (EIO);
1220                 }
1221                 break;
1222         case USB_GET_ALTINTERFACE:
1223                 ai = (struct usb_alt_interface *)addr;
1224                 err = usbd_device2interface_handle(sc->sc_udev,
1225                           ai->uai_interface_index, &iface);
1226                 if (err)
1227                         return (EINVAL);
1228                 idesc = usbd_get_interface_descriptor(iface);
1229                 if (idesc == NULL)
1230                         return (EIO);
1231                 ai->uai_alt_no = idesc->bAlternateSetting;
1232                 break;
1233         case USB_SET_ALTINTERFACE:
1234                 if (!(flag & FWRITE))
1235                         return (EPERM);
1236                 ai = (struct usb_alt_interface *)addr;
1237                 err = usbd_device2interface_handle(sc->sc_udev,
1238                           ai->uai_interface_index, &iface);
1239                 if (err)
1240                         return (EINVAL);
1241                 err = ugen_set_interface(sc, ai->uai_interface_index, ai->uai_alt_no);
1242                 if (err)
1243                         return (EINVAL);
1244                 break;
1245         case USB_GET_NO_ALT:
1246                 ai = (struct usb_alt_interface *)addr;
1247                 cdesc = ugen_get_cdesc(sc, ai->uai_config_index, 0);
1248                 if (cdesc == NULL)
1249                         return (EINVAL);
1250                 idesc = usbd_find_idesc(cdesc, ai->uai_interface_index, 0);
1251                 if (idesc == NULL) {
1252                         kfree(cdesc, M_TEMP);
1253                         return (EINVAL);
1254                 }
1255                 ai->uai_alt_no = usbd_get_no_alts(cdesc, idesc->bInterfaceNumber);
1256                 kfree(cdesc, M_TEMP);
1257                 break;
1258         case USB_GET_DEVICE_DESC:
1259                 *(usb_device_descriptor_t *)addr =
1260                         *usbd_get_device_descriptor(sc->sc_udev);
1261                 break;
1262         case USB_GET_CONFIG_DESC:
1263                 cd = (struct usb_config_desc *)addr;
1264                 cdesc = ugen_get_cdesc(sc, cd->ucd_config_index, 0);
1265                 if (cdesc == NULL)
1266                         return (EINVAL);
1267                 cd->ucd_desc = *cdesc;
1268                 kfree(cdesc, M_TEMP);
1269                 break;
1270         case USB_GET_INTERFACE_DESC:
1271                 id = (struct usb_interface_desc *)addr;
1272                 cdesc = ugen_get_cdesc(sc, id->uid_config_index, 0);
1273                 if (cdesc == NULL)
1274                         return (EINVAL);
1275                 if (id->uid_config_index == USB_CURRENT_CONFIG_INDEX &&
1276                     id->uid_alt_index == USB_CURRENT_ALT_INDEX)
1277                         alt = ugen_get_alt_index(sc, id->uid_interface_index);
1278                 else
1279                         alt = id->uid_alt_index;
1280                 idesc = usbd_find_idesc(cdesc, id->uid_interface_index, alt);
1281                 if (idesc == NULL) {
1282                         kfree(cdesc, M_TEMP);
1283                         return (EINVAL);
1284                 }
1285                 id->uid_desc = *idesc;
1286                 kfree(cdesc, M_TEMP);
1287                 break;
1288         case USB_GET_ENDPOINT_DESC:
1289                 ed = (struct usb_endpoint_desc *)addr;
1290                 cdesc = ugen_get_cdesc(sc, ed->ued_config_index, 0);
1291                 if (cdesc == NULL)
1292                         return (EINVAL);
1293                 if (ed->ued_config_index == USB_CURRENT_CONFIG_INDEX &&
1294                     ed->ued_alt_index == USB_CURRENT_ALT_INDEX)
1295                         alt = ugen_get_alt_index(sc, ed->ued_interface_index);
1296                 else
1297                         alt = ed->ued_alt_index;
1298                 edesc = usbd_find_edesc(cdesc, ed->ued_interface_index,
1299                                         alt, ed->ued_endpoint_index);
1300                 if (edesc == NULL) {
1301                         kfree(cdesc, M_TEMP);
1302                         return (EINVAL);
1303                 }
1304                 ed->ued_desc = *edesc;
1305                 kfree(cdesc, M_TEMP);
1306                 break;
1307         case USB_GET_FULL_DESC:
1308         {
1309                 int len;
1310                 struct iovec iov;
1311                 struct uio uio;
1312                 struct usb_full_desc *fd = (struct usb_full_desc *)addr;
1313                 int error;
1314
1315                 cdesc = ugen_get_cdesc(sc, fd->ufd_config_index, &len);
1316                 if (len > fd->ufd_size)
1317                         len = fd->ufd_size;
1318                 iov.iov_base = (caddr_t)fd->ufd_data;
1319                 iov.iov_len = len;
1320                 uio.uio_iov = &iov;
1321                 uio.uio_iovcnt = 1;
1322                 uio.uio_resid = len;
1323                 uio.uio_offset = 0;
1324                 uio.uio_segflg = UIO_USERSPACE;
1325                 uio.uio_rw = UIO_READ;
1326                 uio.uio_td = curthread;
1327                 error = uiomove((void *)cdesc, len, &uio);
1328                 kfree(cdesc, M_TEMP);
1329                 return (error);
1330         }
1331         case USB_GET_STRING_DESC:
1332         {
1333                 int size;
1334
1335                 si = (struct usb_string_desc *)addr;
1336                 err = usbd_get_string_desc(sc->sc_udev, si->usd_string_index,
1337                           si->usd_language_id, &si->usd_desc, &size);
1338                 if (err)
1339                         return (EINVAL);
1340                 break;
1341         }
1342         case USB_DO_REQUEST:
1343         {
1344                 struct usb_ctl_request *ur = (void *)addr;
1345                 int len = UGETW(ur->ucr_request.wLength);
1346                 struct iovec iov;
1347                 struct uio uio;
1348                 void *ptr = 0;
1349                 usbd_status err;
1350                 int error = 0;
1351
1352                 if (!(flag & FWRITE))
1353                         return (EPERM);
1354                 /* Avoid requests that would damage the bus integrity. */
1355                 if ((ur->ucr_request.bmRequestType == UT_WRITE_DEVICE &&
1356                      ur->ucr_request.bRequest == UR_SET_ADDRESS) ||
1357                     (ur->ucr_request.bmRequestType == UT_WRITE_DEVICE &&
1358                      ur->ucr_request.bRequest == UR_SET_CONFIG) ||
1359                     (ur->ucr_request.bmRequestType == UT_WRITE_INTERFACE &&
1360                      ur->ucr_request.bRequest == UR_SET_INTERFACE))
1361                         return (EINVAL);
1362
1363                 if (len < 0 || len > 32767)
1364                         return (EINVAL);
1365                 if (len != 0) {
1366                         iov.iov_base = (caddr_t)ur->ucr_data;
1367                         iov.iov_len = len;
1368                         uio.uio_iov = &iov;
1369                         uio.uio_iovcnt = 1;
1370                         uio.uio_resid = len;
1371                         uio.uio_offset = 0;
1372                         uio.uio_segflg = UIO_USERSPACE;
1373                         uio.uio_rw =
1374                                 ur->ucr_request.bmRequestType & UT_READ ?
1375                                 UIO_READ : UIO_WRITE;
1376                         uio.uio_td = curthread;
1377                         ptr = kmalloc(len, M_TEMP, M_WAITOK);
1378                         if (uio.uio_rw == UIO_WRITE) {
1379                                 error = uiomove(ptr, len, &uio);
1380                                 if (error)
1381                                         goto ret;
1382                         }
1383                 }
1384                 sce = &sc->sc_endpoints[endpt][IN];
1385                 err = usbd_do_request_flags(sc->sc_udev, &ur->ucr_request,
1386                           ptr, ur->ucr_flags, &ur->ucr_actlen, sce->timeout);
1387                 if (err) {
1388                         error = EIO;
1389                         goto ret;
1390                 }
1391                 if (len != 0) {
1392                         if (uio.uio_rw == UIO_READ) {
1393                                 error = uiomove(ptr, len, &uio);
1394                                 if (error)
1395                                         goto ret;
1396                         }
1397                 }
1398         ret:
1399                 if (ptr)
1400                         kfree(ptr, M_TEMP);
1401                 return (error);
1402         }
1403         case USB_GET_DEVICEINFO:
1404                 usbd_fill_deviceinfo(sc->sc_udev,
1405                     (struct usb_device_info *)addr, 1);
1406                 break;
1407         default:
1408                 return (EINVAL);
1409         }
1410         return (0);
1411 }
1412
1413 int
1414 ugenioctl(struct dev_ioctl_args *ap)
1415 {
1416         cdev_t dev = ap->a_head.a_dev;
1417         int endpt = UGENENDPOINT(dev);
1418         struct ugen_softc *sc;
1419         int error;
1420
1421         sc = devclass_get_softc(ugen_devclass, UGENUNIT(dev));
1422         if (sc->sc_dying)
1423                 return (EIO);
1424
1425         sc->sc_refcnt++;
1426         error = ugen_do_ioctl(sc, endpt, ap->a_cmd, ap->a_data, ap->a_fflag);
1427         if (--sc->sc_refcnt < 0)
1428                 usb_detach_wakeup(sc->sc_dev);
1429         return (error);
1430 }
1431
1432 int
1433 ugenpoll(struct dev_poll_args *ap)
1434 {
1435         cdev_t dev = ap->a_head.a_dev;
1436         struct ugen_softc *sc;
1437         struct ugen_endpoint *sce_in, *sce_out;
1438         usb_endpoint_descriptor_t *edesc;
1439         int revents = 0;
1440
1441         sc = devclass_get_softc(ugen_devclass, UGENUNIT(dev));
1442
1443         if (sc->sc_dying) {
1444                 return ((ap->a_events & (POLLIN | POLLOUT | POLLRDNORM |
1445                         POLLWRNORM)) | POLLHUP);
1446         }
1447
1448         /* Do not allow to poll a control endpoint */
1449         if (UGENENDPOINT(dev) == USB_CONTROL_ENDPOINT) {
1450                 return (ap->a_events & (POLLIN | POLLOUT | POLLRDNORM |
1451                         POLLWRNORM));
1452         }
1453
1454         sce_in = &sc->sc_endpoints[UGENENDPOINT(dev)][IN];
1455         sce_out = &sc->sc_endpoints[UGENENDPOINT(dev)][OUT];
1456         edesc = (sce_in->edesc != NULL) ? sce_in->edesc : sce_out->edesc;
1457         KASSERT(edesc != NULL, ("ugenpoll: NULL edesc"));
1458
1459         if (sce_in->edesc == NULL || sce_in->pipeh == NULL)
1460                 sce_in = NULL;
1461         if (sce_out->edesc == NULL || sce_out->pipeh == NULL)
1462                 sce_out = NULL;
1463
1464         crit_enter();
1465         switch (edesc->bmAttributes & UE_XFERTYPE) {
1466         case UE_INTERRUPT:
1467                 if (sce_in != NULL && (ap->a_events & (POLLIN | POLLRDNORM))) {
1468                         if (sce_in->q.c_cc > 0)
1469                                 revents |= ap->a_events & (POLLIN | POLLRDNORM);
1470                         else
1471                                 selrecord(curthread, &sce_in->rsel);
1472                 }
1473                 if (sce_out != NULL && (ap->a_events & (POLLOUT | POLLWRNORM))) {
1474                         if (sce_out->q.c_cc > 0)
1475                                 revents |= ap->a_events & (POLLOUT | POLLWRNORM);
1476                         else
1477                                 selrecord(curthread, &sce_out->rsel);
1478                 }
1479                 break;
1480         case UE_ISOCHRONOUS:
1481                 if (sce_in != NULL && (ap->a_events & (POLLIN | POLLRDNORM))) {
1482                         if (sce_in->cur != sce_in->fill)
1483                                 revents |= ap->a_events & (POLLIN | POLLRDNORM);
1484                         else
1485                                 selrecord(curthread, &sce_in->rsel);
1486                 }
1487                 if (sce_out != NULL && (ap->a_events & (POLLOUT | POLLWRNORM))) {
1488                         if (sce_out->cur != sce_out->fill)
1489                                 revents |= ap->a_events & (POLLOUT | POLLWRNORM);
1490                         else
1491                                 selrecord(curthread, &sce_out->rsel);
1492                 }
1493                 break;
1494         case UE_BULK:
1495                 /*
1496                  * We have no easy way of determining if a read will
1497                  * yield any data or a write will happen.
1498                  * Pretend they will.
1499                  */
1500                 revents |= ap->a_events &
1501                            (POLLIN | POLLRDNORM | POLLOUT | POLLWRNORM);
1502                 break;
1503         default:
1504                 break;
1505         }
1506         crit_exit();
1507         ap->a_events = revents;
1508         return (0);
1509 }
1510
1511 static struct filterops ugen_filtops_read =
1512         { 1, NULL, ugen_filt_detach, ugen_filt_read };
1513 static struct filterops ugen_filtops_write =
1514         { 1, NULL, ugen_filt_detach, ugen_filt_write };
1515
1516 int
1517 ugenkqfilter(struct dev_kqfilter_args *ap)
1518 {
1519         cdev_t dev = ap->a_head.a_dev;
1520         struct knote *kn = ap->a_kn;
1521         struct klist *klist;
1522         struct ugen_softc *sc;
1523         struct ugen_endpoint *sce;
1524
1525         sc = devclass_get_softc(ugen_devclass, UGENUNIT(dev));
1526
1527         ap->a_result = 1;
1528
1529         if (sc->sc_dying)
1530                 return (0);
1531
1532         /* Do not allow filter on a control endpoint */
1533         if (UGENENDPOINT(dev) == USB_CONTROL_ENDPOINT)
1534                 return (0);
1535
1536         ap->a_result = 0;
1537
1538         switch (kn->kn_filter) {
1539         case EVFILT_READ:
1540                 sce = &sc->sc_endpoints[UGENENDPOINT(dev)][IN];
1541                 kn->kn_fop = &ugen_filtops_read;
1542                 kn->kn_hook = (caddr_t)dev;
1543                 break;
1544         case EVFILT_WRITE:
1545                 sce = &sc->sc_endpoints[UGENENDPOINT(dev)][OUT];
1546                 kn->kn_fop = &ugen_filtops_write;
1547                 kn->kn_hook = (caddr_t)dev;
1548                 break;
1549         default:
1550                 ap->a_result = 1;
1551                 return (0);
1552         }
1553
1554         if (sce->edesc != NULL || sce->pipeh != NULL) {
1555                 crit_enter();
1556                 klist = &sce->rsel.si_note;
1557                 SLIST_INSERT_HEAD(klist, kn, kn_selnext);
1558                 crit_exit();
1559         }
1560
1561         return (0);
1562 }
1563
1564 static void
1565 ugen_filt_detach(struct knote *kn)
1566 {
1567         cdev_t dev = (cdev_t)kn->kn_hook;
1568         struct ugen_softc *sc;
1569         struct ugen_endpoint *sce;
1570         struct klist *klist;
1571
1572         sc = devclass_get_softc(ugen_devclass, UGENUNIT(dev));
1573
1574         switch (kn->kn_filter) {
1575         case EVFILT_READ:
1576                 sce = &sc->sc_endpoints[UGENENDPOINT(dev)][IN];
1577                 break;
1578         case EVFILT_WRITE:
1579                 sce = &sc->sc_endpoints[UGENENDPOINT(dev)][OUT];
1580                 break;
1581         default:
1582                 return;
1583         }
1584
1585         if (sce->edesc != NULL || sce->pipeh != NULL) {
1586                 crit_enter();
1587                 klist = &sce->rsel.si_note;
1588                 SLIST_REMOVE(klist, kn, knote, kn_selnext);
1589                 crit_exit();
1590         }
1591 }
1592
1593 static int
1594 ugen_filt_read(struct knote *kn, long hint)
1595 {
1596         cdev_t dev = (cdev_t)kn->kn_hook;
1597         struct ugen_softc *sc;
1598         struct ugen_endpoint *sce;
1599         int ready = 0;
1600
1601         sc = devclass_get_softc(ugen_devclass, UGENUNIT(dev));
1602         sce = &sc->sc_endpoints[UGENENDPOINT(dev)][IN];
1603
1604         switch (sce->edesc->bmAttributes & UE_XFERTYPE) {
1605         case UE_INTERRUPT:
1606                 if (sce->q.c_cc > 0)
1607                         ready = 1;
1608                 break;
1609         case UE_ISOCHRONOUS:
1610                 if (sce->cur != sce->fill)
1611                         ready = 1;
1612                 break;
1613         case UE_BULK:
1614                 ready = 1;
1615                 break;
1616         default:
1617                 break;
1618         }
1619
1620         return (ready);
1621 }
1622
1623 static int
1624 ugen_filt_write(struct knote *kn, long hint)
1625 {
1626         cdev_t dev = (cdev_t)kn->kn_hook;
1627         struct ugen_softc *sc;
1628         struct ugen_endpoint *sce;
1629         int ready = 0;
1630
1631         sc = devclass_get_softc(ugen_devclass, UGENUNIT(dev));
1632         sce = &sc->sc_endpoints[UGENENDPOINT(dev)][OUT];
1633
1634         switch (sce->edesc->bmAttributes & UE_XFERTYPE) {
1635         case UE_INTERRUPT:
1636                 if (sce->q.c_cc > 0)
1637                         ready = 1;
1638                 break;
1639         case UE_ISOCHRONOUS:
1640                 if (sce->cur != sce->fill)
1641                         ready = 1;
1642                 break;
1643         case UE_BULK:
1644                 ready = 1;
1645                 break;
1646         default:
1647                 break;
1648         }
1649
1650         return (ready);
1651 }
1652
1653 DRIVER_MODULE(ugen, uhub, ugen_driver, ugen_devclass, usbd_driver_load, 0);
1654