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