Nuke USB_DECLARE_DRIVER and USB_DECLARE_DRIVER_INIT macros.
[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.31 2007/07/02 23:52:05 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/ioccom.h>
60 #include <sys/conf.h>
61 #include <sys/fcntl.h>
62 #include <sys/filio.h>
63 #include <sys/tty.h>
64 #include <sys/file.h>
65 #include <sys/select.h>
66 #include <sys/vnode.h>
67 #include <sys/poll.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
145 #define UGEN_CDEV_MAJOR 114
146
147 static struct dev_ops ugen_ops = {
148         { "ugen", UGEN_CDEV_MAJOR, 0 },
149         .d_open =       ugenopen,
150         .d_close =      ugenclose,
151         .d_read =       ugenread,
152         .d_write =      ugenwrite,
153         .d_ioctl =      ugenioctl,
154         .d_poll =       ugenpoll,
155 };
156
157 static void ugenintr(usbd_xfer_handle xfer, usbd_private_handle addr,
158                             usbd_status status);
159 static void ugen_isoc_rintr(usbd_xfer_handle xfer, usbd_private_handle addr,
160                             usbd_status status);
161 static int ugen_do_read(struct ugen_softc *, int, struct uio *, int);
162 static int ugen_do_write(struct ugen_softc *, int, struct uio *, int);
163 static int ugen_do_ioctl(struct ugen_softc *, int, u_long,
164                             caddr_t, int);
165 static void ugen_make_devnodes(struct ugen_softc *sc);
166 static void ugen_destroy_devnodes(struct ugen_softc *sc);
167 static int ugen_set_config(struct ugen_softc *sc, int configno);
168 static usb_config_descriptor_t *ugen_get_cdesc(struct ugen_softc *sc,
169                                                 int index, int *lenp);
170 static usbd_status ugen_set_interface(struct ugen_softc *, int, int);
171 static int ugen_get_alt_index(struct ugen_softc *sc, int ifaceidx);
172
173 #define UGENUNIT(n) ((lminor(n) >> 4) & 0xff)
174 #define UGENENDPOINT(n) (minor(n) & 0xf)
175 #define UGENMINOR(u, e) (((u & 0xf) << 4) | ((u & 0xf0) << 12) | (e))
176 #define UGENUNITMASK    0xffff00f0
177
178 static device_probe_t ugen_match;
179 static device_attach_t ugen_attach;
180 static device_detach_t ugen_detach;
181
182 static devclass_t ugen_devclass;
183
184 static kobj_method_t ugen_methods[] = {
185         DEVMETHOD(device_probe, ugen_match),
186         DEVMETHOD(device_attach, ugen_attach),
187         DEVMETHOD(device_detach, ugen_detach),
188         {0,0}
189 };
190
191 static driver_t ugen_driver = {
192         "ugen",
193         ugen_methods,
194         sizeof(struct ugen_softc)
195 };
196
197 MODULE_DEPEND(ugen, usb, 1, 1, 1);
198
199 static int
200 ugen_match(device_t self)
201 {
202         struct usb_attach_arg *uaa = device_get_ivars(self);
203
204 #if 0
205         if (uaa->matchlvl)
206                 return (uaa->matchlvl);
207 #endif
208         if (uaa->usegeneric)
209                 return (UMATCH_GENERIC);
210         else
211                 return (UMATCH_NONE);
212 }
213
214 static int
215 ugen_attach(device_t self)
216 {
217         struct ugen_softc *sc = device_get_softc(self);
218         struct usb_attach_arg *uaa = device_get_ivars(self);
219         usbd_device_handle udev;
220         char devinfo[1024];
221         usbd_status err;
222         int conf;
223
224         usbd_devinfo(uaa->device, 0, devinfo);
225         sc->sc_dev = self;
226         device_set_desc_copy(self, devinfo);
227         kprintf("%s: %s\n", device_get_nameunit(sc->sc_dev), devinfo);
228
229         sc->sc_udev = udev = uaa->device;
230
231         memset(sc->sc_endpoints, 0, sizeof sc->sc_endpoints);
232
233         /* First set configuration index 0, the default one for ugen. */
234         err = usbd_set_config_index(udev, 0, 0);
235         if (err) {
236                 kprintf("%s: setting configuration index 0 failed\n",
237                        device_get_nameunit(sc->sc_dev));
238                 sc->sc_dying = 1;
239                 return ENXIO;
240         }
241         conf = usbd_get_config_descriptor(udev)->bConfigurationValue;
242
243         /* Set up all the local state for this configuration. */
244         err = ugen_set_config(sc, conf);
245         if (err) {
246                 kprintf("%s: setting configuration %d failed\n",
247                        device_get_nameunit(sc->sc_dev), conf);
248                 sc->sc_dying = 1;
249                 return ENXIO;
250         }
251
252         /* the main device, ctrl endpoint */
253         dev_ops_add(&ugen_ops, 
254                     UGENUNITMASK, UGENMINOR(device_get_unit(sc->sc_dev), 0));
255         make_dev(&ugen_ops, UGENMINOR(device_get_unit(sc->sc_dev), 0),
256                 UID_ROOT, GID_OPERATOR, 0644, "%s", device_get_nameunit(sc->sc_dev));
257
258         return 0;
259 }
260
261 static void
262 ugen_make_devnodes(struct ugen_softc *sc)
263 {
264         int endptno;
265         cdev_t dev;
266
267         for (endptno = 1; endptno < USB_MAX_ENDPOINTS; endptno++) {
268                 if (sc->sc_endpoints[endptno][IN].sc != NULL ||
269                     sc->sc_endpoints[endptno][OUT].sc != NULL ) {
270                         /* endpt can be 0x81 and 0x01, representing
271                          * endpoint address 0x01 and IN/OUT directions.
272                          * We map both endpts to the same device,
273                          * IN is reading from it, OUT is writing to it.
274                          *
275                          * In the if clause above we check whether one
276                          * of the structs is populated.
277                          */
278                         dev = make_dev(&ugen_ops,
279                                 UGENMINOR(device_get_unit(sc->sc_dev), endptno),
280                                 UID_ROOT, GID_OPERATOR, 0644,
281                                 "%s.%d",
282                                 device_get_nameunit(sc->sc_dev), endptno);
283                         if (sc->sc_endpoints[endptno][IN].sc != NULL) {
284                                 reference_dev(dev);
285                                 if (sc->sc_endpoints[endptno][IN].dev)
286                                         release_dev(sc->sc_endpoints[endptno][IN].dev);
287                                 sc->sc_endpoints[endptno][IN].dev = dev;
288                         }
289                         if (sc->sc_endpoints[endptno][OUT].sc != NULL) {
290                                 reference_dev(dev);
291                                 if (sc->sc_endpoints[endptno][OUT].dev)
292                                         release_dev(sc->sc_endpoints[endptno][OUT].dev);
293                                 sc->sc_endpoints[endptno][OUT].dev = dev;
294                         }
295                 }
296         }
297 }
298
299 static void
300 ugen_destroy_devnodes(struct ugen_softc *sc)
301 {
302         int endptno;
303         cdev_t dev;
304
305         /* destroy all devices for the other (existing) endpoints as well */
306         for (endptno = 1; endptno < USB_MAX_ENDPOINTS; endptno++) {
307                 if (sc->sc_endpoints[endptno][IN].sc != NULL ||
308                     sc->sc_endpoints[endptno][OUT].sc != NULL ) {
309                         /* endpt can be 0x81 and 0x01, representing
310                          * endpoint address 0x01 and IN/OUT directions.
311                          * We map both endpoint addresses to the same device,
312                          * IN is reading from it, OUT is writing to it.
313                          *
314                          * In the if clause above we check whether one
315                          * of the structs is populated.
316                          */
317                         dev = sc->sc_endpoints[endptno][IN].dev;
318                         if (dev != NULL) {
319                                 destroy_dev(dev);
320                                 sc->sc_endpoints[endptno][IN].dev = NULL;
321                         }
322                         dev = sc->sc_endpoints[endptno][OUT].dev;
323                         if (dev != NULL) {
324                                 destroy_dev(dev);
325                                 sc->sc_endpoints[endptno][OUT].dev = NULL;
326                         }
327                 }
328         }
329 }
330
331 static int
332 ugen_set_config(struct ugen_softc *sc, int configno)
333 {
334         usbd_device_handle dev = sc->sc_udev;
335         usbd_interface_handle iface;
336         usb_endpoint_descriptor_t *ed;
337         struct ugen_endpoint *sce;
338         u_int8_t niface, nendpt;
339         int ifaceno, endptno, endpt;
340         usbd_status err;
341         int dir;
342
343         DPRINTFN(1,("ugen_set_config: %s to configno %d, sc=%p\n",
344                     device_get_nameunit(sc->sc_dev), configno, sc));
345
346         ugen_destroy_devnodes(sc);
347
348         /* We start at 1, not 0, because we don't care whether the
349          * control endpoint is open or not. It is always present.
350          */
351         for (endptno = 1; endptno < USB_MAX_ENDPOINTS; endptno++) {
352                 if (sc->sc_is_open[endptno]) {
353                         DPRINTFN(1,
354                              ("ugen_set_config: %s - endpoint %d is open\n",
355                               device_get_nameunit(sc->sc_dev), endptno));
356                         return (USBD_IN_USE);
357                 }
358         }
359
360         /* Avoid setting the current value. */
361         if (usbd_get_config_descriptor(dev)->bConfigurationValue != configno) {
362                 err = usbd_set_config_no(dev, configno, 1);
363                 if (err)
364                         return (err);
365         }
366
367         err = usbd_interface_count(dev, &niface);
368         if (err)
369                 return (err);
370         memset(sc->sc_endpoints, 0, sizeof sc->sc_endpoints);
371         for (ifaceno = 0; ifaceno < niface; ifaceno++) {
372                 DPRINTFN(1,("ugen_set_config: ifaceno %d\n", ifaceno));
373                 err = usbd_device2interface_handle(dev, ifaceno, &iface);
374                 if (err)
375                         return (err);
376                 err = usbd_endpoint_count(iface, &nendpt);
377                 if (err)
378                         return (err);
379                 for (endptno = 0; endptno < nendpt; endptno++) {
380                         ed = usbd_interface2endpoint_descriptor(iface,endptno);
381                         endpt = ed->bEndpointAddress;
382                         dir = UE_GET_DIR(endpt) == UE_DIR_IN ? IN : OUT;
383                         sce = &sc->sc_endpoints[UE_GET_ADDR(endpt)][dir];
384                         DPRINTFN(1,("ugen_set_config: endptno %d, endpt=0x%02x"
385                                     "(%d,%d), sce=%p\n",
386                                     endptno, endpt, UE_GET_ADDR(endpt),
387                                     UE_GET_DIR(endpt), sce));
388                         sce->sc = sc;
389                         sce->edesc = ed;
390                         sce->iface = iface;
391                 }
392         }
393
394         ugen_make_devnodes(sc);
395
396         return (USBD_NORMAL_COMPLETION);
397 }
398
399 int
400 ugenopen(struct dev_open_args *ap)
401 {
402         cdev_t dev = ap->a_head.a_dev;
403         struct ugen_softc *sc;
404         int unit = UGENUNIT(dev);
405         int endpt = UGENENDPOINT(dev);
406         usb_endpoint_descriptor_t *edesc;
407         struct ugen_endpoint *sce;
408         int dir, isize;
409         usbd_status err;
410         usbd_xfer_handle xfer;
411         void *buf;
412         int i, j;
413
414         sc = devclass_get_softc(ugen_devclass, unit);
415         if (sc == NULL)
416                 return (ENXIO);
417
418         DPRINTFN(5, ("ugenopen: flag=%d, mode=%d, unit=%d endpt=%d\n",
419                      ap->a_oflags, ap->a_devtype, unit, endpt));
420
421         if (sc == NULL || sc->sc_dying)
422                 return (ENXIO);
423
424         if (sc->sc_is_open[endpt])
425                 return (EBUSY);
426
427         if (endpt == USB_CONTROL_ENDPOINT) {
428                 sc->sc_is_open[USB_CONTROL_ENDPOINT] = 1;
429                 return (0);
430         }
431
432         /* Make sure there are pipes for all directions. */
433         for (dir = OUT; dir <= IN; dir++) {
434                 if (ap->a_oflags & (dir == OUT ? FWRITE : FREAD)) {
435                         sce = &sc->sc_endpoints[endpt][dir];
436                         if (sce == 0 || sce->edesc == 0)
437                                 return (ENXIO);
438                 }
439         }
440
441         /* Actually open the pipes. */
442         /* XXX Should back out properly if it fails. */
443         for (dir = OUT; dir <= IN; dir++) {
444                 if (!(ap->a_oflags & (dir == OUT ? FWRITE : FREAD)))
445                         continue;
446                 sce = &sc->sc_endpoints[endpt][dir];
447                 sce->state = 0;
448                 sce->timeout = USBD_NO_TIMEOUT;
449                 DPRINTFN(5, ("ugenopen: sc=%p, endpt=%d, dir=%d, sce=%p\n",
450                              sc, endpt, dir, sce));
451                 edesc = sce->edesc;
452                 switch (edesc->bmAttributes & UE_XFERTYPE) {
453                 case UE_INTERRUPT:
454                         if (dir == OUT) {
455                                 err = usbd_open_pipe(sce->iface,
456                                     edesc->bEndpointAddress, 0, &sce->pipeh);
457                                 if (err)
458                                         return (EIO);
459                                 break;
460                         }
461                         isize = UGETW(edesc->wMaxPacketSize);
462                         if (isize == 0) /* shouldn't happen */
463                                 return (EINVAL);
464                         sce->ibuf = kmalloc(isize, M_USBDEV, M_WAITOK);
465                         DPRINTFN(5, ("ugenopen: intr endpt=%d,isize=%d\n",
466                                      endpt, isize));
467                         if (clalloc(&sce->q, UGEN_IBSIZE, 0) == -1)
468                                 return (ENOMEM);
469                         err = usbd_open_pipe_intr(sce->iface,
470                                 edesc->bEndpointAddress,
471                                 USBD_SHORT_XFER_OK, &sce->pipeh, sce,
472                                 sce->ibuf, isize, ugenintr,
473                                 USBD_DEFAULT_INTERVAL);
474                         if (err) {
475                                 kfree(sce->ibuf, M_USBDEV);
476                                 clfree(&sce->q);
477                                 return (EIO);
478                         }
479                         DPRINTFN(5, ("ugenopen: interrupt open done\n"));
480                         break;
481                 case UE_BULK:
482                         err = usbd_open_pipe(sce->iface,
483                                   edesc->bEndpointAddress, 0, &sce->pipeh);
484                         if (err)
485                                 return (EIO);
486                         break;
487                 case UE_ISOCHRONOUS:
488                         if (dir == OUT)
489                                 return (EINVAL);
490                         isize = UGETW(edesc->wMaxPacketSize);
491                         if (isize == 0) /* shouldn't happen */
492                                 return (EINVAL);
493                         sce->ibuf = kmalloc(isize * UGEN_NISOFRAMES,
494                                 M_USBDEV, M_WAITOK);
495                         sce->cur = sce->fill = sce->ibuf;
496                         sce->limit = sce->ibuf + isize * UGEN_NISOFRAMES;
497                         DPRINTFN(5, ("ugenopen: isoc endpt=%d, isize=%d\n",
498                                      endpt, isize));
499                         err = usbd_open_pipe(sce->iface,
500                                   edesc->bEndpointAddress, 0, &sce->pipeh);
501                         if (err) {
502                                 kfree(sce->ibuf, M_USBDEV);
503                                 return (EIO);
504                         }
505                         for(i = 0; i < UGEN_NISOREQS; ++i) {
506                                 sce->isoreqs[i].sce = sce;
507                                 xfer = usbd_alloc_xfer(sc->sc_udev);
508                                 if (xfer == 0)
509                                         goto bad;
510                                 sce->isoreqs[i].xfer = xfer;
511                                 buf = usbd_alloc_buffer
512                                         (xfer, isize * UGEN_NISORFRMS);
513                                 if (buf == 0) {
514                                         i++;
515                                         goto bad;
516                                 }
517                                 sce->isoreqs[i].dmabuf = buf;
518                                 for(j = 0; j < UGEN_NISORFRMS; ++j)
519                                         sce->isoreqs[i].sizes[j] = isize;
520                                 usbd_setup_isoc_xfer
521                                         (xfer, sce->pipeh, &sce->isoreqs[i],
522                                          sce->isoreqs[i].sizes,
523                                          UGEN_NISORFRMS, USBD_NO_COPY,
524                                          ugen_isoc_rintr);
525                                 (void)usbd_transfer(xfer);
526                         }
527                         DPRINTFN(5, ("ugenopen: isoc open done\n"));
528                         break;
529                 bad:
530                         while (--i >= 0) /* implicit buffer free */
531                                 usbd_free_xfer(sce->isoreqs[i].xfer);
532                         return (ENOMEM);
533                 case UE_CONTROL:
534                         sce->timeout = USBD_DEFAULT_TIMEOUT;
535                         return (EINVAL);
536                 }
537         }
538         sc->sc_is_open[endpt] = 1;
539         return (0);
540 }
541
542 int
543 ugenclose(struct dev_close_args *ap)
544 {
545         cdev_t dev = ap->a_head.a_dev;
546         int endpt = UGENENDPOINT(dev);
547         struct ugen_softc *sc;
548         struct ugen_endpoint *sce;
549         int dir;
550         int i;
551
552         sc = devclass_get_softc(ugen_devclass, UGENUNIT(dev));
553
554         DPRINTFN(5, ("ugenclose: flag=%d, mode=%d, unit=%d, endpt=%d\n",
555                      ap->a_fflag, ap->a_devtype, UGENUNIT(dev), endpt));
556
557 #ifdef DIAGNOSTIC
558         if (!sc->sc_is_open[endpt]) {
559                 kprintf("ugenclose: not open\n");
560                 return (EINVAL);
561         }
562 #endif
563
564         if (endpt == USB_CONTROL_ENDPOINT) {
565                 DPRINTFN(5, ("ugenclose: close control\n"));
566                 sc->sc_is_open[endpt] = 0;
567                 return (0);
568         }
569
570         for (dir = OUT; dir <= IN; dir++) {
571                 if (!(ap->a_fflag & (dir == OUT ? FWRITE : FREAD)))
572                         continue;
573                 sce = &sc->sc_endpoints[endpt][dir];
574                 if (sce == NULL || sce->pipeh == NULL)
575                         continue;
576                 DPRINTFN(5, ("ugenclose: endpt=%d dir=%d sce=%p\n",
577                              endpt, dir, sce));
578
579                 usbd_abort_pipe(sce->pipeh);
580                 usbd_close_pipe(sce->pipeh);
581                 sce->pipeh = NULL;
582
583                 switch (sce->edesc->bmAttributes & UE_XFERTYPE) {
584                 case UE_INTERRUPT:
585                         ndflush(&sce->q, sce->q.c_cc);
586                         clfree(&sce->q);
587                         break;
588                 case UE_ISOCHRONOUS:
589                         for (i = 0; i < UGEN_NISOREQS; ++i)
590                                 usbd_free_xfer(sce->isoreqs[i].xfer);
591                 default:
592                         break;
593                 }
594
595                 if (sce->ibuf != NULL) {
596                         kfree(sce->ibuf, M_USBDEV);
597                         sce->ibuf = NULL;
598                         clfree(&sce->q);
599                 }
600         }
601         sc->sc_is_open[endpt] = 0;
602
603         return (0);
604 }
605
606 static int
607 ugen_do_read(struct ugen_softc *sc, int endpt, struct uio *uio, int flag)
608 {
609         struct ugen_endpoint *sce = &sc->sc_endpoints[endpt][IN];
610         u_int32_t n, tn;
611         char *buf;
612         usbd_xfer_handle xfer;
613         usbd_status err;
614         int error = 0;
615         int ugen_bbsize;
616         u_char buffer[UGEN_CHUNK];
617
618         DPRINTFN(5, ("%s: ugenread: %d\n", device_get_nameunit(sc->sc_dev), endpt));
619
620         if (sc->sc_dying)
621                 return (EIO);
622
623         if (endpt == USB_CONTROL_ENDPOINT)
624                 return (ENODEV);
625
626         if (sce == NULL)
627                 return (EINVAL);
628
629         if (sce->edesc == NULL) {
630                 kprintf("ugenread: no edesc\n");
631                 return (EIO);
632         }
633         if (sce->pipeh == NULL) {
634                 kprintf("ugenread: no pipe\n");
635                 return (EIO);
636         }
637
638         buf = getugenbuf(ugen_bufsize, &ugen_bbsize);
639
640         switch (sce->edesc->bmAttributes & UE_XFERTYPE) {
641         case UE_INTERRUPT:
642                 /* Block until activity occurred. */
643                 crit_enter();
644                 while (sce->q.c_cc == 0) {
645                         if (flag & IO_NDELAY) {
646                                 crit_exit();
647                                 error = EWOULDBLOCK;
648                                 goto done;
649                         }
650                         sce->state |= UGEN_ASLP;
651                         DPRINTFN(5, ("ugenread: sleep on %p\n", sce));
652                         error = tsleep(sce, PCATCH, "ugenri", 0);
653                         DPRINTFN(5, ("ugenread: woke, error=%d\n", error));
654                         if (sc->sc_dying)
655                                 error = EIO;
656                         if (error) {
657                                 sce->state &= ~UGEN_ASLP;
658                                 break;
659                         }
660                 }
661                 crit_exit();
662
663                 /* Transfer as many chunks as possible. */
664                 while (sce->q.c_cc > 0 && uio->uio_resid > 0 && !error) {
665                         n = min(sce->q.c_cc, uio->uio_resid);
666                         if (n > sizeof(buffer))
667                                 n = sizeof(buffer);
668
669                         /* Remove a small chunk from the input queue. */
670                         q_to_b(&sce->q, buffer, n);
671                         DPRINTFN(5, ("ugenread: got %d chars\n", n));
672
673                         /* Copy the data to the user process. */
674                         error = uiomove(buffer, n, uio);
675                         if (error)
676                                 break;
677                 }
678                 break;
679         case UE_BULK:
680                 xfer = usbd_alloc_xfer(sc->sc_udev);
681                 if (xfer == 0) {
682                         error = ENOMEM;
683                         goto done;
684                 }
685                 while ((n = min(ugen_bbsize, uio->uio_resid)) != 0) {
686                         DPRINTFN(1, ("ugenread: start transfer %d bytes\n",n));
687                         tn = n;
688                         err = usbd_bulk_transfer(
689                                 xfer, sce->pipeh,
690                                 sce->state & UGEN_SHORT_OK ?
691                                     USBD_SHORT_XFER_OK : 0,
692                                 sce->timeout, buf, &tn, "ugenrb");
693                         if (err) {
694                                 if (err == USBD_INTERRUPTED)
695                                         error = EINTR;
696                                 else if (err == USBD_TIMEOUT)
697                                         error = ETIMEDOUT;
698                                 else
699                                         error = EIO;
700                                 break;
701                         }
702                         DPRINTFN(1, ("ugenread: got %d bytes\n", tn));
703                         error = uiomove(buf, tn, uio);
704                         if (error || tn < n)
705                                 break;
706                 }
707                 usbd_free_xfer(xfer);
708                 break;
709         case UE_ISOCHRONOUS:
710                 crit_enter();
711                 while (sce->cur == sce->fill) {
712                         if (flag & IO_NDELAY) {
713                                 crit_exit();
714                                 error = EWOULDBLOCK;
715                                 goto done;
716                         }
717                         sce->state |= UGEN_ASLP;
718                         DPRINTFN(5, ("ugenread: sleep on %p\n", sce));
719                         error = tsleep(sce, PCATCH, "ugenri", 0);
720                         DPRINTFN(5, ("ugenread: woke, error=%d\n", error));
721                         if (sc->sc_dying)
722                                 error = EIO;
723                         if (error) {
724                                 sce->state &= ~UGEN_ASLP;
725                                 break;
726                         }
727                 }
728
729                 while (sce->cur != sce->fill && uio->uio_resid > 0 && !error) {
730                         if(sce->fill > sce->cur)
731                                 n = min(sce->fill - sce->cur, uio->uio_resid);
732                         else
733                                 n = min(sce->limit - sce->cur, uio->uio_resid);
734
735                         DPRINTFN(5, ("ugenread: isoc got %d chars\n", n));
736
737                         /* Copy the data to the user process. */
738                         error = uiomove(sce->cur, n, uio);
739                         if (error)
740                                 break;
741                         sce->cur += n;
742                         if(sce->cur >= sce->limit)
743                                 sce->cur = sce->ibuf;
744                 }
745                 crit_exit();
746                 break;
747
748
749         default:
750                 error = ENXIO;
751                 break;
752         }
753 done:
754         relugenbuf(buf, ugen_bbsize);
755         return (error);
756 }
757
758 int
759 ugenread(struct dev_read_args *ap)
760 {
761         cdev_t dev = ap->a_head.a_dev;
762         int endpt = UGENENDPOINT(dev);
763         struct ugen_softc *sc;
764         int error;
765
766         sc = devclass_get_softc(ugen_devclass, UGENUNIT(dev));
767
768         sc->sc_refcnt++;
769         error = ugen_do_read(sc, endpt, ap->a_uio, ap->a_ioflag);
770         if (--sc->sc_refcnt < 0)
771                 usb_detach_wakeup(sc->sc_dev);
772         return (error);
773 }
774
775 static int
776 ugen_do_write(struct ugen_softc *sc, int endpt, struct uio *uio, int flag)
777 {
778         struct ugen_endpoint *sce = &sc->sc_endpoints[endpt][OUT];
779         u_int32_t n;
780         int error = 0;
781         int ugen_bbsize;
782         char *buf;
783         usbd_xfer_handle xfer;
784         usbd_status err;
785
786         DPRINTFN(5, ("%s: ugenwrite: %d\n", device_get_nameunit(sc->sc_dev), endpt));
787
788         if (sc->sc_dying)
789                 return (EIO);
790
791         if (endpt == USB_CONTROL_ENDPOINT)
792                 return (ENODEV);
793
794         if (sce == NULL)
795                 return (EINVAL);
796
797         if (sce->edesc == NULL) {
798                 kprintf("ugenwrite: no edesc\n");
799                 return (EIO);
800         }
801         if (sce->pipeh == NULL) {
802                 kprintf("ugenwrite: no pipe\n");
803                 return (EIO);
804         }
805
806         buf = getugenbuf(ugen_bufsize, &ugen_bbsize);
807
808         switch (sce->edesc->bmAttributes & UE_XFERTYPE) {
809         case UE_BULK:
810                 xfer = usbd_alloc_xfer(sc->sc_udev);
811                 if (xfer == 0) {
812                         error = EIO;
813                         goto done;
814                 }
815                 while ((n = min(ugen_bbsize, uio->uio_resid)) != 0) {
816                         error = uiomove(buf, n, uio);
817                         if (error)
818                                 break;
819                         DPRINTFN(1, ("ugenwrite: transfer %d bytes\n", n));
820                         err = usbd_bulk_transfer(xfer, sce->pipeh, 0,
821                                   sce->timeout, buf, &n,"ugenwb");
822                         if (err) {
823                                 if (err == USBD_INTERRUPTED)
824                                         error = EINTR;
825                                 else if (err == USBD_TIMEOUT)
826                                         error = ETIMEDOUT;
827                                 else
828                                         error = EIO;
829                                 break;
830                         }
831                 }
832                 usbd_free_xfer(xfer);
833                 break;
834         case UE_INTERRUPT:
835                 xfer = usbd_alloc_xfer(sc->sc_udev);
836                 if (xfer == 0) {
837                         error = EIO;
838                         goto done;
839                 }
840                 while ((n = min(UGETW(sce->edesc->wMaxPacketSize),
841                     uio->uio_resid)) != 0) {
842                         error = uiomove(buf, n, uio);
843                         if (error)
844                                 break;
845                         DPRINTFN(1, ("ugenwrite: transfer %d bytes\n", n));
846                         err = usbd_intr_transfer(xfer, sce->pipeh, 0,
847                                   sce->timeout, buf, &n,"ugenwi");
848                         if (err) {
849                                 if (err == USBD_INTERRUPTED)
850                                         error = EINTR;
851                                 else if (err == USBD_TIMEOUT)
852                                         error = ETIMEDOUT;
853                                 else
854                                         error = EIO;
855                                 break;
856                         }
857                 }
858                 usbd_free_xfer(xfer);
859                 break;
860         default:
861                 error = ENXIO;
862                 break;
863         }
864 done:
865         relugenbuf(buf, ugen_bbsize);
866         return (error);
867 }
868
869 int
870 ugenwrite(struct dev_write_args *ap)
871 {
872         cdev_t dev = ap->a_head.a_dev;
873         int endpt = UGENENDPOINT(dev);
874         struct ugen_softc *sc;
875         int error;
876
877         sc = devclass_get_softc(ugen_devclass, UGENUNIT(dev));
878
879         sc->sc_refcnt++;
880         error = ugen_do_write(sc, endpt, ap->a_uio, ap->a_ioflag);
881         if (--sc->sc_refcnt < 0)
882                 usb_detach_wakeup(sc->sc_dev);
883         return (error);
884 }
885
886 static int
887 ugen_detach(device_t self)
888 {
889         struct ugen_softc *sc = device_get_softc(self);
890         struct ugen_endpoint *sce;
891         int i, dir;
892
893         DPRINTF(("ugen_detach: sc=%p\n", sc));
894
895         sc->sc_dying = 1;
896         /* Abort all pipes.  Causes processes waiting for transfer to wake. */
897         for (i = 0; i < USB_MAX_ENDPOINTS; i++) {
898                 for (dir = OUT; dir <= IN; dir++) {
899                         sce = &sc->sc_endpoints[i][dir];
900                         if (sce && sce->pipeh)
901                                 usbd_abort_pipe(sce->pipeh);
902                 }
903         }
904         crit_enter();
905         if (--sc->sc_refcnt >= 0) {
906                 /* Wake everyone */
907                 for (i = 0; i < USB_MAX_ENDPOINTS; i++)
908                         wakeup(&sc->sc_endpoints[i][IN]);
909                 /* Wait for processes to go away. */
910                 usb_detach_wait(sc->sc_dev);
911         }
912         crit_exit();
913
914         /* destroy the device for the control endpoint */
915         ugen_destroy_devnodes(sc);
916         dev_ops_remove(&ugen_ops, 
917                     UGENUNITMASK, UGENMINOR(device_get_unit(sc->sc_dev), 0));
918         return (0);
919 }
920
921 static void
922 ugenintr(usbd_xfer_handle xfer, usbd_private_handle addr, usbd_status status)
923 {
924         struct ugen_endpoint *sce = addr;
925         /*struct ugen_softc *sc = sce->sc;*/
926         u_int32_t count;
927         u_char *ibuf;
928
929         if (status == USBD_CANCELLED)
930                 return;
931
932         if (status != USBD_NORMAL_COMPLETION) {
933                 DPRINTF(("ugenintr: status=%d\n", status));
934                 if (status == USBD_STALLED)
935                     usbd_clear_endpoint_stall_async(sce->pipeh);
936                 return;
937         }
938
939         usbd_get_xfer_status(xfer, NULL, NULL, &count, NULL);
940         ibuf = sce->ibuf;
941
942         DPRINTFN(5, ("ugenintr: xfer=%p status=%d count=%d\n",
943                      xfer, status, count));
944         DPRINTFN(5, ("          data = %02x %02x %02x\n",
945                      ibuf[0], ibuf[1], ibuf[2]));
946
947         (void)b_to_q(ibuf, count, &sce->q);
948
949         if (sce->state & UGEN_ASLP) {
950                 sce->state &= ~UGEN_ASLP;
951                 DPRINTFN(5, ("ugen_intr: waking %p\n", sce));
952                 wakeup(sce);
953         }
954         selwakeuppri(&sce->rsel, 0);
955 }
956
957 static void
958 ugen_isoc_rintr(usbd_xfer_handle xfer, usbd_private_handle addr,
959                 usbd_status status)
960 {
961         struct isoreq *req = addr;
962         struct ugen_endpoint *sce = req->sce;
963         u_int32_t count, n;
964         int i, isize;
965
966         /* Return if we are aborting. */
967         if (status == USBD_CANCELLED)
968                 return;
969
970         usbd_get_xfer_status(xfer, NULL, NULL, &count, NULL);
971         DPRINTFN(5,("ugen_isoc_rintr: xfer %d, count=%d\n",
972                     (int)(req - sce->isoreqs),
973                     count));
974
975         /* throw away oldest input if the buffer is full */
976         if(sce->fill < sce->cur && sce->cur <= sce->fill + count) {
977                 sce->cur += count;
978                 if(sce->cur >= sce->limit)
979                         sce->cur = sce->ibuf + (sce->limit - sce->cur);
980                 DPRINTFN(5, ("ugen_isoc_rintr: throwing away %d bytes\n",
981                              count));
982         }
983
984         isize = UGETW(sce->edesc->wMaxPacketSize);
985         for (i = 0; i < UGEN_NISORFRMS; i++) {
986                 u_int32_t actlen = req->sizes[i];
987                 char const *buf = (char const *)req->dmabuf + isize * i;
988
989                 /* copy data to buffer */
990                 while (actlen > 0) {
991                         n = min(actlen, sce->limit - sce->fill);
992                         memcpy(sce->fill, buf, n);
993
994                         buf += n;
995                         actlen -= n;
996                         sce->fill += n;
997                         if(sce->fill == sce->limit)
998                                 sce->fill = sce->ibuf;
999                 }
1000
1001                 /* setup size for next transfer */
1002                 req->sizes[i] = isize;
1003         }
1004
1005         usbd_setup_isoc_xfer(xfer, sce->pipeh, req, req->sizes, UGEN_NISORFRMS,
1006                              USBD_NO_COPY, ugen_isoc_rintr);
1007         (void)usbd_transfer(xfer);
1008
1009         if (sce->state & UGEN_ASLP) {
1010                 sce->state &= ~UGEN_ASLP;
1011                 DPRINTFN(5, ("ugen_isoc_rintr: waking %p\n", sce));
1012                 wakeup(sce);
1013         }
1014         selwakeuppri(&sce->rsel, 0);
1015 }
1016
1017 static usbd_status
1018 ugen_set_interface(struct ugen_softc *sc, int ifaceidx, int altno)
1019 {
1020         usbd_interface_handle iface;
1021         usb_endpoint_descriptor_t *ed;
1022         usbd_status err;
1023         struct ugen_endpoint *sce;
1024         u_int8_t niface, nendpt, endptno, endpt;
1025         int dir;
1026
1027         DPRINTFN(15, ("ugen_set_interface %d %d\n", ifaceidx, altno));
1028
1029         err = usbd_interface_count(sc->sc_udev, &niface);
1030         if (err)
1031                 return (err);
1032         if (ifaceidx < 0 || ifaceidx >= niface)
1033                 return (USBD_INVAL);
1034
1035         err = usbd_device2interface_handle(sc->sc_udev, ifaceidx, &iface);
1036         if (err)
1037                 return (err);
1038         err = usbd_endpoint_count(iface, &nendpt);
1039         if (err)
1040                 return (err);
1041
1042         /* destroy the existing devices, we remake the new ones in a moment */
1043         ugen_destroy_devnodes(sc);
1044
1045         /* XXX should only do this after setting new altno has succeeded */
1046         for (endptno = 0; endptno < nendpt; endptno++) {
1047                 ed = usbd_interface2endpoint_descriptor(iface,endptno);
1048                 endpt = ed->bEndpointAddress;
1049                 dir = UE_GET_DIR(endpt) == UE_DIR_IN ? IN : OUT;
1050                 sce = &sc->sc_endpoints[UE_GET_ADDR(endpt)][dir];
1051                 sce->sc = 0;
1052                 sce->edesc = 0;
1053                 sce->iface = 0;
1054         }
1055
1056         /* change setting */
1057         err = usbd_set_interface(iface, altno);
1058         if (err)
1059                 return (err);
1060
1061         err = usbd_endpoint_count(iface, &nendpt);
1062         if (err)
1063                 return (err);
1064         for (endptno = 0; endptno < nendpt; endptno++) {
1065                 ed = usbd_interface2endpoint_descriptor(iface,endptno);
1066                 endpt = ed->bEndpointAddress;
1067                 dir = UE_GET_DIR(endpt) == UE_DIR_IN ? IN : OUT;
1068                 sce = &sc->sc_endpoints[UE_GET_ADDR(endpt)][dir];
1069                 sce->sc = sc;
1070                 sce->edesc = ed;
1071                 sce->iface = iface;
1072         }
1073
1074         /* make the new devices */
1075         ugen_make_devnodes(sc);
1076
1077         return (0);
1078 }
1079
1080 /* Retrieve a complete descriptor for a certain device and index. */
1081 static usb_config_descriptor_t *
1082 ugen_get_cdesc(struct ugen_softc *sc, int index, int *lenp)
1083 {
1084         usb_config_descriptor_t *cdesc, *tdesc, cdescr;
1085         int len;
1086         usbd_status err;
1087
1088         if (index == USB_CURRENT_CONFIG_INDEX) {
1089                 tdesc = usbd_get_config_descriptor(sc->sc_udev);
1090                 len = UGETW(tdesc->wTotalLength);
1091                 if (lenp)
1092                         *lenp = len;
1093                 cdesc = kmalloc(len, M_TEMP, M_INTWAIT);
1094                 memcpy(cdesc, tdesc, len);
1095                 DPRINTFN(5,("ugen_get_cdesc: current, len=%d\n", len));
1096         } else {
1097                 err = usbd_get_config_desc(sc->sc_udev, index, &cdescr);
1098                 if (err)
1099                         return (0);
1100                 len = UGETW(cdescr.wTotalLength);
1101                 DPRINTFN(5,("ugen_get_cdesc: index=%d, len=%d\n", index, len));
1102                 if (lenp)
1103                         *lenp = len;
1104                 cdesc = kmalloc(len, M_TEMP, M_INTWAIT);
1105                 err = usbd_get_config_desc_full(sc->sc_udev, index, cdesc, len);
1106                 if (err) {
1107                         kfree(cdesc, M_TEMP);
1108                         return (0);
1109                 }
1110         }
1111         return (cdesc);
1112 }
1113
1114 static int
1115 ugen_get_alt_index(struct ugen_softc *sc, int ifaceidx)
1116 {
1117         usbd_interface_handle iface;
1118         usbd_status err;
1119
1120         err = usbd_device2interface_handle(sc->sc_udev, ifaceidx, &iface);
1121         if (err)
1122                 return (-1);
1123         return (usbd_get_interface_altindex(iface));
1124 }
1125
1126 static int
1127 ugen_do_ioctl(struct ugen_softc *sc, int endpt, u_long cmd,
1128               caddr_t addr, int flag)
1129 {
1130         struct ugen_endpoint *sce;
1131         usbd_status err;
1132         usbd_interface_handle iface;
1133         struct usb_config_desc *cd;
1134         usb_config_descriptor_t *cdesc;
1135         struct usb_interface_desc *id;
1136         usb_interface_descriptor_t *idesc;
1137         struct usb_endpoint_desc *ed;
1138         usb_endpoint_descriptor_t *edesc;
1139         struct usb_alt_interface *ai;
1140         struct usb_string_desc *si;
1141         u_int8_t conf, alt;
1142
1143         DPRINTFN(5, ("ugenioctl: cmd=%08lx\n", cmd));
1144         if (sc->sc_dying)
1145                 return (EIO);
1146
1147         switch (cmd) {
1148         case USB_SET_SHORT_XFER:
1149                 /* This flag only affects read */
1150                 if (endpt == USB_CONTROL_ENDPOINT)
1151                         return (EINVAL);
1152                 sce = &sc->sc_endpoints[endpt][IN];
1153                 if (sce == NULL)
1154                         return (EINVAL);
1155
1156                 if (sce->pipeh == NULL) {
1157                         kprintf("ugenioctl: USB_SET_SHORT_XFER, no pipe\n");
1158                         return (EIO);
1159                 }
1160
1161                 if (*(int *)addr)
1162                         sce->state |= UGEN_SHORT_OK;
1163                 else
1164                         sce->state &= ~UGEN_SHORT_OK;
1165                 return (0);
1166         case USB_SET_TIMEOUT:
1167                 sce = &sc->sc_endpoints[endpt][IN];
1168                 if (sce == NULL)
1169                         return (EINVAL);
1170                 sce->timeout = *(int *)addr;
1171                 return (0);
1172         default:
1173                 break;
1174         }
1175
1176         if (endpt != USB_CONTROL_ENDPOINT)
1177                 return (EINVAL);
1178
1179         switch (cmd) {
1180 #ifdef USB_DEBUG
1181         case USB_SETDEBUG:
1182                 ugendebug = *(int *)addr;
1183                 break;
1184 #endif
1185         case USB_GET_CONFIG:
1186                 err = usbd_get_config(sc->sc_udev, &conf);
1187                 if (err)
1188                         return (EIO);
1189                 *(int *)addr = conf;
1190                 break;
1191         case USB_SET_CONFIG:
1192                 if (!(flag & FWRITE))
1193                         return (EPERM);
1194                 err = ugen_set_config(sc, *(int *)addr);
1195                 switch (err) {
1196                 case USBD_NORMAL_COMPLETION:
1197                         break;
1198                 case USBD_IN_USE:
1199                         return (EBUSY);
1200                 default:
1201                         return (EIO);
1202                 }
1203                 break;
1204         case USB_GET_ALTINTERFACE:
1205                 ai = (struct usb_alt_interface *)addr;
1206                 err = usbd_device2interface_handle(sc->sc_udev,
1207                           ai->uai_interface_index, &iface);
1208                 if (err)
1209                         return (EINVAL);
1210                 idesc = usbd_get_interface_descriptor(iface);
1211                 if (idesc == NULL)
1212                         return (EIO);
1213                 ai->uai_alt_no = idesc->bAlternateSetting;
1214                 break;
1215         case USB_SET_ALTINTERFACE:
1216                 if (!(flag & FWRITE))
1217                         return (EPERM);
1218                 ai = (struct usb_alt_interface *)addr;
1219                 err = usbd_device2interface_handle(sc->sc_udev,
1220                           ai->uai_interface_index, &iface);
1221                 if (err)
1222                         return (EINVAL);
1223                 err = ugen_set_interface(sc, ai->uai_interface_index, ai->uai_alt_no);
1224                 if (err)
1225                         return (EINVAL);
1226                 break;
1227         case USB_GET_NO_ALT:
1228                 ai = (struct usb_alt_interface *)addr;
1229                 cdesc = ugen_get_cdesc(sc, ai->uai_config_index, 0);
1230                 if (cdesc == NULL)
1231                         return (EINVAL);
1232                 idesc = usbd_find_idesc(cdesc, ai->uai_interface_index, 0);
1233                 if (idesc == NULL) {
1234                         kfree(cdesc, M_TEMP);
1235                         return (EINVAL);
1236                 }
1237                 ai->uai_alt_no = usbd_get_no_alts(cdesc, idesc->bInterfaceNumber);
1238                 kfree(cdesc, M_TEMP);
1239                 break;
1240         case USB_GET_DEVICE_DESC:
1241                 *(usb_device_descriptor_t *)addr =
1242                         *usbd_get_device_descriptor(sc->sc_udev);
1243                 break;
1244         case USB_GET_CONFIG_DESC:
1245                 cd = (struct usb_config_desc *)addr;
1246                 cdesc = ugen_get_cdesc(sc, cd->ucd_config_index, 0);
1247                 if (cdesc == NULL)
1248                         return (EINVAL);
1249                 cd->ucd_desc = *cdesc;
1250                 kfree(cdesc, M_TEMP);
1251                 break;
1252         case USB_GET_INTERFACE_DESC:
1253                 id = (struct usb_interface_desc *)addr;
1254                 cdesc = ugen_get_cdesc(sc, id->uid_config_index, 0);
1255                 if (cdesc == NULL)
1256                         return (EINVAL);
1257                 if (id->uid_config_index == USB_CURRENT_CONFIG_INDEX &&
1258                     id->uid_alt_index == USB_CURRENT_ALT_INDEX)
1259                         alt = ugen_get_alt_index(sc, id->uid_interface_index);
1260                 else
1261                         alt = id->uid_alt_index;
1262                 idesc = usbd_find_idesc(cdesc, id->uid_interface_index, alt);
1263                 if (idesc == NULL) {
1264                         kfree(cdesc, M_TEMP);
1265                         return (EINVAL);
1266                 }
1267                 id->uid_desc = *idesc;
1268                 kfree(cdesc, M_TEMP);
1269                 break;
1270         case USB_GET_ENDPOINT_DESC:
1271                 ed = (struct usb_endpoint_desc *)addr;
1272                 cdesc = ugen_get_cdesc(sc, ed->ued_config_index, 0);
1273                 if (cdesc == NULL)
1274                         return (EINVAL);
1275                 if (ed->ued_config_index == USB_CURRENT_CONFIG_INDEX &&
1276                     ed->ued_alt_index == USB_CURRENT_ALT_INDEX)
1277                         alt = ugen_get_alt_index(sc, ed->ued_interface_index);
1278                 else
1279                         alt = ed->ued_alt_index;
1280                 edesc = usbd_find_edesc(cdesc, ed->ued_interface_index,
1281                                         alt, ed->ued_endpoint_index);
1282                 if (edesc == NULL) {
1283                         kfree(cdesc, M_TEMP);
1284                         return (EINVAL);
1285                 }
1286                 ed->ued_desc = *edesc;
1287                 kfree(cdesc, M_TEMP);
1288                 break;
1289         case USB_GET_FULL_DESC:
1290         {
1291                 int len;
1292                 struct iovec iov;
1293                 struct uio uio;
1294                 struct usb_full_desc *fd = (struct usb_full_desc *)addr;
1295                 int error;
1296
1297                 cdesc = ugen_get_cdesc(sc, fd->ufd_config_index, &len);
1298                 if (len > fd->ufd_size)
1299                         len = fd->ufd_size;
1300                 iov.iov_base = (caddr_t)fd->ufd_data;
1301                 iov.iov_len = len;
1302                 uio.uio_iov = &iov;
1303                 uio.uio_iovcnt = 1;
1304                 uio.uio_resid = len;
1305                 uio.uio_offset = 0;
1306                 uio.uio_segflg = UIO_USERSPACE;
1307                 uio.uio_rw = UIO_READ;
1308                 uio.uio_td = curthread;
1309                 error = uiomove((void *)cdesc, len, &uio);
1310                 kfree(cdesc, M_TEMP);
1311                 return (error);
1312         }
1313         case USB_GET_STRING_DESC:
1314         {
1315                 int size;
1316
1317                 si = (struct usb_string_desc *)addr;
1318                 err = usbd_get_string_desc(sc->sc_udev, si->usd_string_index,
1319                           si->usd_language_id, &si->usd_desc, &size);
1320                 if (err)
1321                         return (EINVAL);
1322                 break;
1323         }
1324         case USB_DO_REQUEST:
1325         {
1326                 struct usb_ctl_request *ur = (void *)addr;
1327                 int len = UGETW(ur->ucr_request.wLength);
1328                 struct iovec iov;
1329                 struct uio uio;
1330                 void *ptr = 0;
1331                 usbd_status err;
1332                 int error = 0;
1333
1334                 if (!(flag & FWRITE))
1335                         return (EPERM);
1336                 /* Avoid requests that would damage the bus integrity. */
1337                 if ((ur->ucr_request.bmRequestType == UT_WRITE_DEVICE &&
1338                      ur->ucr_request.bRequest == UR_SET_ADDRESS) ||
1339                     (ur->ucr_request.bmRequestType == UT_WRITE_DEVICE &&
1340                      ur->ucr_request.bRequest == UR_SET_CONFIG) ||
1341                     (ur->ucr_request.bmRequestType == UT_WRITE_INTERFACE &&
1342                      ur->ucr_request.bRequest == UR_SET_INTERFACE))
1343                         return (EINVAL);
1344
1345                 if (len < 0 || len > 32767)
1346                         return (EINVAL);
1347                 if (len != 0) {
1348                         iov.iov_base = (caddr_t)ur->ucr_data;
1349                         iov.iov_len = len;
1350                         uio.uio_iov = &iov;
1351                         uio.uio_iovcnt = 1;
1352                         uio.uio_resid = len;
1353                         uio.uio_offset = 0;
1354                         uio.uio_segflg = UIO_USERSPACE;
1355                         uio.uio_rw =
1356                                 ur->ucr_request.bmRequestType & UT_READ ?
1357                                 UIO_READ : UIO_WRITE;
1358                         uio.uio_td = curthread;
1359                         ptr = kmalloc(len, M_TEMP, M_WAITOK);
1360                         if (uio.uio_rw == UIO_WRITE) {
1361                                 error = uiomove(ptr, len, &uio);
1362                                 if (error)
1363                                         goto ret;
1364                         }
1365                 }
1366                 sce = &sc->sc_endpoints[endpt][IN];
1367                 err = usbd_do_request_flags(sc->sc_udev, &ur->ucr_request,
1368                           ptr, ur->ucr_flags, &ur->ucr_actlen, sce->timeout);
1369                 if (err) {
1370                         error = EIO;
1371                         goto ret;
1372                 }
1373                 if (len != 0) {
1374                         if (uio.uio_rw == UIO_READ) {
1375                                 error = uiomove(ptr, len, &uio);
1376                                 if (error)
1377                                         goto ret;
1378                         }
1379                 }
1380         ret:
1381                 if (ptr)
1382                         kfree(ptr, M_TEMP);
1383                 return (error);
1384         }
1385         case USB_GET_DEVICEINFO:
1386                 usbd_fill_deviceinfo(sc->sc_udev,
1387                     (struct usb_device_info *)addr, 1);
1388                 break;
1389         default:
1390                 return (EINVAL);
1391         }
1392         return (0);
1393 }
1394
1395 int
1396 ugenioctl(struct dev_ioctl_args *ap)
1397 {
1398         cdev_t dev = ap->a_head.a_dev;
1399         int endpt = UGENENDPOINT(dev);
1400         struct ugen_softc *sc;
1401         int error;
1402
1403         sc = devclass_get_softc(ugen_devclass, UGENUNIT(dev));
1404
1405         sc->sc_refcnt++;
1406         error = ugen_do_ioctl(sc, endpt, ap->a_cmd, ap->a_data, ap->a_fflag);
1407         if (--sc->sc_refcnt < 0)
1408                 usb_detach_wakeup(sc->sc_dev);
1409         return (error);
1410 }
1411
1412 int
1413 ugenpoll(struct dev_poll_args *ap)
1414 {
1415         cdev_t dev = ap->a_head.a_dev;
1416         struct ugen_softc *sc;
1417         struct ugen_endpoint *sce;
1418         int revents = 0;
1419
1420         sc = devclass_get_softc(ugen_devclass, UGENUNIT(dev));
1421
1422         if (sc->sc_dying)
1423                 return (EIO);
1424
1425         /* XXX always IN */
1426         sce = &sc->sc_endpoints[UGENENDPOINT(dev)][IN];
1427         if (sce == NULL)
1428                 return (EINVAL);
1429
1430         if (!sce->edesc) {
1431                 kprintf("ugenpoll: no edesc\n");
1432                 return (EIO);
1433         }
1434         if (!sce->pipeh) {
1435                 kprintf("ugenpoll: no pipe\n");
1436                 return (EIO);
1437         }
1438
1439         crit_enter();
1440         switch (sce->edesc->bmAttributes & UE_XFERTYPE) {
1441         case UE_INTERRUPT:
1442                 if (ap->a_events & (POLLIN | POLLRDNORM)) {
1443                         if (sce->q.c_cc > 0)
1444                                 revents |= ap->a_events & (POLLIN | POLLRDNORM);
1445                         else
1446                                 selrecord(curthread, &sce->rsel);
1447                 }
1448                 break;
1449         case UE_ISOCHRONOUS:
1450                 if (ap->a_events & (POLLIN | POLLRDNORM)) {
1451                         if (sce->cur != sce->fill)
1452                                 revents |= ap->a_events & (POLLIN | POLLRDNORM);
1453                         else
1454                                 selrecord(curthread, &sce->rsel);
1455                 }
1456                 break;
1457         case UE_BULK:
1458                 /*
1459                  * We have no easy way of determining if a read will
1460                  * yield any data or a write will happen.
1461                  * Pretend they will.
1462                  */
1463                 revents |= ap->a_events &
1464                            (POLLIN | POLLRDNORM | POLLOUT | POLLWRNORM);
1465                 break;
1466         default:
1467                 break;
1468         }
1469         crit_exit();
1470         ap->a_events = revents;
1471         return (0);
1472 }
1473
1474 DRIVER_MODULE(ugen, uhub, ugen_driver, ugen_devclass, usbd_driver_load, 0);
1475