Home | History | Annotate | Line # | Download | only in usb
ugen.c revision 1.156
      1 /*	$NetBSD: ugen.c,v 1.156 2020/08/16 06:17:31 riastradh Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1998, 2004 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Lennart Augustsson (lennart (at) augustsson.net) at
      9  * Carlstedt Research & Technology.
     10  *
     11  * Copyright (c) 2006 BBN Technologies Corp.  All rights reserved.
     12  * Effort sponsored in part by the Defense Advanced Research Projects
     13  * Agency (DARPA) and the Department of the Interior National Business
     14  * Center under agreement number NBCHC050166.
     15  *
     16  * Redistribution and use in source and binary forms, with or without
     17  * modification, are permitted provided that the following conditions
     18  * are met:
     19  * 1. Redistributions of source code must retain the above copyright
     20  *    notice, this list of conditions and the following disclaimer.
     21  * 2. Redistributions in binary form must reproduce the above copyright
     22  *    notice, this list of conditions and the following disclaimer in the
     23  *    documentation and/or other materials provided with the distribution.
     24  *
     25  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     26  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     27  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     28  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     29  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     30  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     31  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     32  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     33  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     34  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     35  * POSSIBILITY OF SUCH DAMAGE.
     36  */
     37 
     38 
     39 #include <sys/cdefs.h>
     40 __KERNEL_RCSID(0, "$NetBSD: ugen.c,v 1.156 2020/08/16 06:17:31 riastradh Exp $");
     41 
     42 #ifdef _KERNEL_OPT
     43 #include "opt_compat_netbsd.h"
     44 #include "opt_usb.h"
     45 #endif
     46 
     47 #include <sys/param.h>
     48 #include <sys/systm.h>
     49 #include <sys/kernel.h>
     50 #include <sys/kmem.h>
     51 #include <sys/device.h>
     52 #include <sys/ioctl.h>
     53 #include <sys/conf.h>
     54 #include <sys/tty.h>
     55 #include <sys/file.h>
     56 #include <sys/select.h>
     57 #include <sys/proc.h>
     58 #include <sys/vnode.h>
     59 #include <sys/poll.h>
     60 #include <sys/compat_stub.h>
     61 #include <sys/module.h>
     62 #include <sys/rbtree.h>
     63 
     64 #include <dev/usb/usb.h>
     65 #include <dev/usb/usbdi.h>
     66 #include <dev/usb/usbdi_util.h>
     67 
     68 #include "ioconf.h"
     69 
     70 #ifdef UGEN_DEBUG
     71 #define DPRINTF(x)	if (ugendebug) printf x
     72 #define DPRINTFN(n,x)	if (ugendebug>(n)) printf x
     73 int	ugendebug = 0;
     74 #else
     75 #define DPRINTF(x)
     76 #define DPRINTFN(n,x)
     77 #endif
     78 
     79 #define	UGEN_CHUNK	128	/* chunk size for read */
     80 #define	UGEN_IBSIZE	1020	/* buffer size */
     81 #define	UGEN_BBSIZE	1024
     82 
     83 #define UGEN_NISOREQS	4	/* number of outstanding xfer requests */
     84 #define UGEN_NISORFRMS	8	/* number of transactions per req */
     85 #define UGEN_NISOFRAMES	(UGEN_NISORFRMS * UGEN_NISOREQS)
     86 
     87 #define UGEN_BULK_RA_WB_BUFSIZE	16384		/* default buffer size */
     88 #define UGEN_BULK_RA_WB_BUFMAX	(1 << 20)	/* maximum allowed buffer */
     89 
     90 struct isoreq {
     91 	struct ugen_endpoint *sce;
     92 	struct usbd_xfer *xfer;
     93 	void *dmabuf;
     94 	uint16_t sizes[UGEN_NISORFRMS];
     95 };
     96 
     97 struct ugen_endpoint {
     98 	struct ugen_softc *sc;
     99 	usb_endpoint_descriptor_t *edesc;
    100 	struct usbd_interface *iface;
    101 	int state;
    102 #define UGEN_SHORT_OK	0x04	/* short xfers are OK */
    103 #define UGEN_BULK_RA	0x08	/* in bulk read-ahead mode */
    104 #define UGEN_BULK_WB	0x10	/* in bulk write-behind mode */
    105 #define UGEN_RA_WB_STOP	0x20	/* RA/WB xfer is stopped (buffer full/empty) */
    106 	struct usbd_pipe *pipeh;
    107 	struct clist q;
    108 	u_char *ibuf;		/* start of buffer (circular for isoc) */
    109 	u_char *fill;		/* location for input (isoc) */
    110 	u_char *limit;		/* end of circular buffer (isoc) */
    111 	u_char *cur;		/* current read location (isoc) */
    112 	uint32_t timeout;
    113 	uint32_t ra_wb_bufsize; /* requested size for RA/WB buffer */
    114 	uint32_t ra_wb_reqsize; /* requested xfer length for RA/WB */
    115 	uint32_t ra_wb_used;	 /* how much is in buffer */
    116 	uint32_t ra_wb_xferlen; /* current xfer length for RA/WB */
    117 	struct usbd_xfer *ra_wb_xfer;
    118 	struct isoreq isoreqs[UGEN_NISOREQS];
    119 	/* Keep these last; we don't overwrite them in ugen_set_config() */
    120 #define UGEN_ENDPOINT_NONZERO_CRUFT	offsetof(struct ugen_endpoint, rsel)
    121 	struct selinfo rsel;
    122 	kcondvar_t cv;
    123 };
    124 
    125 struct ugen_softc {
    126 	device_t sc_dev;		/* base device */
    127 	struct usbd_device *sc_udev;
    128 	struct rb_node sc_node;
    129 	unsigned sc_unit;
    130 
    131 	kmutex_t		sc_lock;
    132 	kcondvar_t		sc_detach_cv;
    133 
    134 	char sc_is_open[USB_MAX_ENDPOINTS];
    135 	struct ugen_endpoint sc_endpoints[USB_MAX_ENDPOINTS][2];
    136 #define OUT 0
    137 #define IN  1
    138 
    139 	int sc_refcnt;
    140 	char sc_buffer[UGEN_BBSIZE];
    141 	u_char sc_dying;
    142 };
    143 
    144 static struct {
    145 	kmutex_t	lock;
    146 	rb_tree_t	tree;
    147 } ugenif __cacheline_aligned;
    148 
    149 static int
    150 compare_ugen(void *cookie, const void *vsca, const void *vscb)
    151 {
    152 	const struct ugen_softc *sca = vsca;
    153 	const struct ugen_softc *scb = vscb;
    154 
    155 	if (sca->sc_unit < scb->sc_unit)
    156 		return -1;
    157 	if (sca->sc_unit > scb->sc_unit)
    158 		return +1;
    159 	return 0;
    160 }
    161 
    162 static int
    163 compare_ugen_key(void *cookie, const void *vsc, const void *vk)
    164 {
    165 	const struct ugen_softc *sc = vsc;
    166 	const unsigned *k = vk;
    167 
    168 	if (sc->sc_unit < *k)
    169 		return -1;
    170 	if (sc->sc_unit > *k)
    171 		return +1;
    172 	return 0;
    173 }
    174 
    175 static const rb_tree_ops_t ugenif_tree_ops = {
    176 	.rbto_compare_nodes = compare_ugen,
    177 	.rbto_compare_key = compare_ugen_key,
    178 	.rbto_node_offset = offsetof(struct ugen_softc, sc_node),
    179 };
    180 
    181 static void
    182 ugenif_get_unit(struct ugen_softc *sc)
    183 {
    184 	struct ugen_softc *sc0;
    185 	unsigned i;
    186 
    187 	mutex_enter(&ugenif.lock);
    188 	for (i = 0, sc0 = RB_TREE_MIN(&ugenif.tree);
    189 	     sc0 != NULL && i == sc0->sc_unit;
    190 	     i++, sc0 = RB_TREE_NEXT(&ugenif.tree, sc0))
    191 		KASSERT(i < UINT_MAX);
    192 	KASSERT(rb_tree_find_node(&ugenif.tree, &i) == NULL);
    193 	sc->sc_unit = i;
    194 	sc0 = rb_tree_insert_node(&ugenif.tree, sc);
    195 	KASSERT(sc0 == sc);
    196 	KASSERT(rb_tree_find_node(&ugenif.tree, &i) == sc);
    197 	mutex_exit(&ugenif.lock);
    198 }
    199 
    200 static void
    201 ugenif_put_unit(struct ugen_softc *sc)
    202 {
    203 
    204 	mutex_enter(&ugenif.lock);
    205 	KASSERT(rb_tree_find_node(&ugenif.tree, &sc->sc_unit) == sc);
    206 	rb_tree_remove_node(&ugenif.tree, sc);
    207 	sc->sc_unit = -1;
    208 	mutex_exit(&ugenif.lock);
    209 }
    210 
    211 static struct ugen_softc *
    212 ugenif_acquire(unsigned unit)
    213 {
    214 	struct ugen_softc *sc;
    215 
    216 	mutex_enter(&ugenif.lock);
    217 	sc = rb_tree_find_node(&ugenif.tree, &unit);
    218 	if (sc == NULL)
    219 		goto out;
    220 	mutex_enter(&sc->sc_lock);
    221 	if (sc->sc_dying) {
    222 		mutex_exit(&sc->sc_lock);
    223 		sc = NULL;
    224 		goto out;
    225 	}
    226 	KASSERT(sc->sc_refcnt < INT_MAX);
    227 	sc->sc_refcnt++;
    228 	mutex_exit(&sc->sc_lock);
    229 out:	mutex_exit(&ugenif.lock);
    230 
    231 	return sc;
    232 }
    233 
    234 static void
    235 ugenif_release(struct ugen_softc *sc)
    236 {
    237 
    238 	mutex_enter(&sc->sc_lock);
    239 	if (--sc->sc_refcnt < 0)
    240 		cv_broadcast(&sc->sc_detach_cv);
    241 	mutex_exit(&sc->sc_lock);
    242 }
    243 
    244 static dev_type_open(ugenopen);
    245 static dev_type_close(ugenclose);
    246 static dev_type_read(ugenread);
    247 static dev_type_write(ugenwrite);
    248 static dev_type_ioctl(ugenioctl);
    249 static dev_type_poll(ugenpoll);
    250 static dev_type_kqfilter(ugenkqfilter);
    251 
    252 const struct cdevsw ugen_cdevsw = {
    253 	.d_open = ugenopen,
    254 	.d_close = ugenclose,
    255 	.d_read = ugenread,
    256 	.d_write = ugenwrite,
    257 	.d_ioctl = ugenioctl,
    258 	.d_stop = nostop,
    259 	.d_tty = notty,
    260 	.d_poll = ugenpoll,
    261 	.d_mmap = nommap,
    262 	.d_kqfilter = ugenkqfilter,
    263 	.d_discard = nodiscard,
    264 	.d_flag = D_OTHER,
    265 };
    266 
    267 Static void ugenintr(struct usbd_xfer *, void *,
    268 		     usbd_status);
    269 Static void ugen_isoc_rintr(struct usbd_xfer *, void *,
    270 			    usbd_status);
    271 Static void ugen_bulkra_intr(struct usbd_xfer *, void *,
    272 			     usbd_status);
    273 Static void ugen_bulkwb_intr(struct usbd_xfer *, void *,
    274 			     usbd_status);
    275 Static int ugen_do_read(struct ugen_softc *, int, struct uio *, int);
    276 Static int ugen_do_write(struct ugen_softc *, int, struct uio *, int);
    277 Static int ugen_do_ioctl(struct ugen_softc *, int, u_long,
    278 			 void *, int, struct lwp *);
    279 Static int ugen_set_config(struct ugen_softc *, int, int);
    280 Static usb_config_descriptor_t *ugen_get_cdesc(struct ugen_softc *,
    281 					       int, int *);
    282 Static usbd_status ugen_set_interface(struct ugen_softc *, int, int);
    283 Static int ugen_get_alt_index(struct ugen_softc *, int);
    284 Static void ugen_clear_endpoints(struct ugen_softc *);
    285 
    286 #define UGENUNIT(n) ((minor(n) >> 4) & 0xf)
    287 #define UGENENDPOINT(n) (minor(n) & 0xf)
    288 #define UGENDEV(u, e) (makedev(0, ((u) << 4) | (e)))
    289 
    290 static int	ugenif_match(device_t, cfdata_t, void *);
    291 static void	ugenif_attach(device_t, device_t, void *);
    292 static int	ugen_match(device_t, cfdata_t, void *);
    293 static void	ugen_attach(device_t, device_t, void *);
    294 static int	ugen_detach(device_t, int);
    295 static int	ugen_activate(device_t, enum devact);
    296 
    297 CFATTACH_DECL_NEW(ugen, sizeof(struct ugen_softc), ugen_match,
    298     ugen_attach, ugen_detach, ugen_activate);
    299 CFATTACH_DECL_NEW(ugenif, sizeof(struct ugen_softc), ugenif_match,
    300     ugenif_attach, ugen_detach, ugen_activate);
    301 
    302 /* toggle to control attach priority. -1 means "let autoconf decide" */
    303 int ugen_override = -1;
    304 
    305 static int
    306 ugen_match(device_t parent, cfdata_t match, void *aux)
    307 {
    308 	struct usb_attach_arg *uaa = aux;
    309 	int override;
    310 
    311 	if (ugen_override != -1)
    312 		override = ugen_override;
    313 	else
    314 		override = match->cf_flags & 1;
    315 
    316 	if (override)
    317 		return UMATCH_HIGHEST;
    318 	else if (uaa->uaa_usegeneric)
    319 		return UMATCH_GENERIC;
    320 	else
    321 		return UMATCH_NONE;
    322 }
    323 
    324 static int
    325 ugenif_match(device_t parent, cfdata_t match, void *aux)
    326 {
    327 	/* Assume that they knew what they configured! (see ugenif(4)) */
    328 	return UMATCH_HIGHEST;
    329 }
    330 
    331 static void
    332 ugen_attach(device_t parent, device_t self, void *aux)
    333 {
    334 	struct usb_attach_arg *uaa = aux;
    335 	struct usbif_attach_arg uiaa;
    336 
    337 	memset(&uiaa, 0, sizeof(uiaa));
    338 	uiaa.uiaa_port = uaa->uaa_port;
    339 	uiaa.uiaa_vendor = uaa->uaa_vendor;
    340 	uiaa.uiaa_product = uaa->uaa_product;
    341 	uiaa.uiaa_release = uaa->uaa_release;
    342 	uiaa.uiaa_device = uaa->uaa_device;
    343 	uiaa.uiaa_configno = -1;
    344 	uiaa.uiaa_ifaceno = -1;
    345 
    346 	ugenif_attach(parent, self, &uiaa);
    347 }
    348 
    349 static void
    350 ugenif_attach(device_t parent, device_t self, void *aux)
    351 {
    352 	struct ugen_softc *sc = device_private(self);
    353 	struct usbif_attach_arg *uiaa = aux;
    354 	struct usbd_device *udev;
    355 	char *devinfop;
    356 	usbd_status err;
    357 	int i, dir, conf;
    358 
    359 	aprint_naive("\n");
    360 	aprint_normal("\n");
    361 
    362 	mutex_init(&sc->sc_lock, MUTEX_DEFAULT, IPL_SOFTUSB);
    363 	cv_init(&sc->sc_detach_cv, "ugendet");
    364 
    365 	devinfop = usbd_devinfo_alloc(uiaa->uiaa_device, 0);
    366 	aprint_normal_dev(self, "%s\n", devinfop);
    367 	usbd_devinfo_free(devinfop);
    368 
    369 	sc->sc_dev = self;
    370 	sc->sc_udev = udev = uiaa->uiaa_device;
    371 
    372 	for (i = 0; i < USB_MAX_ENDPOINTS; i++) {
    373 		for (dir = OUT; dir <= IN; dir++) {
    374 			struct ugen_endpoint *sce;
    375 
    376 			sce = &sc->sc_endpoints[i][dir];
    377 			selinit(&sce->rsel);
    378 			cv_init(&sce->cv, "ugensce");
    379 		}
    380 	}
    381 
    382 	if (uiaa->uiaa_ifaceno < 0) {
    383 		/*
    384 		 * If we attach the whole device,
    385 		 * set configuration index 0, the default one.
    386 		 */
    387 		err = usbd_set_config_index(udev, 0, 0);
    388 		if (err) {
    389 			aprint_error_dev(self,
    390 			    "setting configuration index 0 failed\n");
    391 			sc->sc_dying = 1;
    392 			return;
    393 		}
    394 	}
    395 
    396 	/* Get current configuration */
    397 	conf = usbd_get_config_descriptor(udev)->bConfigurationValue;
    398 
    399 	/* Set up all the local state for this configuration. */
    400 	err = ugen_set_config(sc, conf, uiaa->uiaa_ifaceno < 0);
    401 	if (err) {
    402 		aprint_error_dev(self, "setting configuration %d failed\n",
    403 		    conf);
    404 		sc->sc_dying = 1;
    405 		return;
    406 	}
    407 
    408 	ugenif_get_unit(sc);
    409 	usbd_add_drv_event(USB_EVENT_DRIVER_ATTACH, sc->sc_udev, sc->sc_dev);
    410 
    411 	if (!pmf_device_register(self, NULL, NULL))
    412 		aprint_error_dev(self, "couldn't establish power handler\n");
    413 
    414 }
    415 
    416 Static void
    417 ugen_clear_endpoints(struct ugen_softc *sc)
    418 {
    419 
    420 	/* Clear out the old info, but leave the selinfo and cv initialised. */
    421 	for (int i = 0; i < USB_MAX_ENDPOINTS; i++) {
    422 		for (int dir = OUT; dir <= IN; dir++) {
    423 			struct ugen_endpoint *sce = &sc->sc_endpoints[i][dir];
    424 			memset(sce, 0, UGEN_ENDPOINT_NONZERO_CRUFT);
    425 		}
    426 	}
    427 }
    428 
    429 Static int
    430 ugen_set_config(struct ugen_softc *sc, int configno, int chkopen)
    431 {
    432 	struct usbd_device *dev = sc->sc_udev;
    433 	usb_config_descriptor_t *cdesc;
    434 	struct usbd_interface *iface;
    435 	usb_endpoint_descriptor_t *ed;
    436 	struct ugen_endpoint *sce;
    437 	uint8_t niface, nendpt;
    438 	int ifaceno, endptno, endpt;
    439 	usbd_status err;
    440 	int dir;
    441 
    442 	DPRINTFN(1,("ugen_set_config: %s to configno %d, sc=%p\n",
    443 		    device_xname(sc->sc_dev), configno, sc));
    444 
    445 	if (chkopen) {
    446 		/*
    447 		 * We start at 1, not 0, because we don't care whether the
    448 		 * control endpoint is open or not. It is always present.
    449 		 */
    450 		for (endptno = 1; endptno < USB_MAX_ENDPOINTS; endptno++)
    451 			if (sc->sc_is_open[endptno]) {
    452 				DPRINTFN(1,
    453 				     ("ugen_set_config: %s - endpoint %d is open\n",
    454 				      device_xname(sc->sc_dev), endptno));
    455 				return USBD_IN_USE;
    456 			}
    457 	}
    458 
    459 	/* Avoid setting the current value. */
    460 	cdesc = usbd_get_config_descriptor(dev);
    461 	if (!cdesc || cdesc->bConfigurationValue != configno) {
    462 		err = usbd_set_config_no(dev, configno, 1);
    463 		if (err)
    464 			return err;
    465 	}
    466 
    467 	ugen_clear_endpoints(sc);
    468 
    469 	err = usbd_interface_count(dev, &niface);
    470 	if (err)
    471 		return err;
    472 
    473 	for (ifaceno = 0; ifaceno < niface; ifaceno++) {
    474 		DPRINTFN(1,("ugen_set_config: ifaceno %d\n", ifaceno));
    475 		err = usbd_device2interface_handle(dev, ifaceno, &iface);
    476 		if (err)
    477 			return err;
    478 		err = usbd_endpoint_count(iface, &nendpt);
    479 		if (err)
    480 			return err;
    481 		for (endptno = 0; endptno < nendpt; endptno++) {
    482 			ed = usbd_interface2endpoint_descriptor(iface,endptno);
    483 			KASSERT(ed != NULL);
    484 			endpt = ed->bEndpointAddress;
    485 			dir = UE_GET_DIR(endpt) == UE_DIR_IN ? IN : OUT;
    486 			sce = &sc->sc_endpoints[UE_GET_ADDR(endpt)][dir];
    487 			DPRINTFN(1,("ugen_set_config: endptno %d, endpt=0x%02x"
    488 				    "(%d,%d), sce=%p\n",
    489 				    endptno, endpt, UE_GET_ADDR(endpt),
    490 				    UE_GET_DIR(endpt), sce));
    491 			sce->sc = sc;
    492 			sce->edesc = ed;
    493 			sce->iface = iface;
    494 		}
    495 	}
    496 	return USBD_NORMAL_COMPLETION;
    497 }
    498 
    499 static int
    500 ugenopen(dev_t dev, int flag, int mode, struct lwp *l)
    501 {
    502 	struct ugen_softc *sc;
    503 	int unit = UGENUNIT(dev);
    504 	int endpt = UGENENDPOINT(dev);
    505 	usb_endpoint_descriptor_t *edesc;
    506 	struct ugen_endpoint *sce;
    507 	int dir, isize;
    508 	usbd_status err;
    509 	struct usbd_xfer *xfer;
    510 	int i, j;
    511 	int error;
    512 
    513 	if ((sc = ugenif_acquire(unit)) == NULL)
    514 		return ENXIO;
    515 
    516 	DPRINTFN(5, ("ugenopen: flag=%d, mode=%d, unit=%d endpt=%d\n",
    517 		     flag, mode, unit, endpt));
    518 
    519 	/* The control endpoint allows multiple opens. */
    520 	if (endpt == USB_CONTROL_ENDPOINT) {
    521 		sc->sc_is_open[USB_CONTROL_ENDPOINT] = 1;
    522 		error = 0;
    523 		goto out;
    524 	}
    525 
    526 	if (sc->sc_is_open[endpt]) {
    527 		error = EBUSY;
    528 		goto out;
    529 	}
    530 
    531 	/* Make sure there are pipes for all directions. */
    532 	for (dir = OUT; dir <= IN; dir++) {
    533 		if (flag & (dir == OUT ? FWRITE : FREAD)) {
    534 			sce = &sc->sc_endpoints[endpt][dir];
    535 			if (sce->edesc == NULL) {
    536 				error = ENXIO;
    537 				goto out;
    538 			}
    539 		}
    540 	}
    541 
    542 	/* Actually open the pipes. */
    543 	/* XXX Should back out properly if it fails. */
    544 	for (dir = OUT; dir <= IN; dir++) {
    545 		if (!(flag & (dir == OUT ? FWRITE : FREAD)))
    546 			continue;
    547 		sce = &sc->sc_endpoints[endpt][dir];
    548 		sce->state = 0;
    549 		sce->timeout = USBD_NO_TIMEOUT;
    550 		DPRINTFN(5, ("ugenopen: sc=%p, endpt=%d, dir=%d, sce=%p\n",
    551 			     sc, endpt, dir, sce));
    552 		edesc = sce->edesc;
    553 		switch (edesc->bmAttributes & UE_XFERTYPE) {
    554 		case UE_INTERRUPT:
    555 			if (dir == OUT) {
    556 				err = usbd_open_pipe(sce->iface,
    557 				    edesc->bEndpointAddress, 0, &sce->pipeh);
    558 				if (err) {
    559 					error = EIO;
    560 					goto out;
    561 				}
    562 				break;
    563 			}
    564 			isize = UGETW(edesc->wMaxPacketSize);
    565 			if (isize == 0) {	/* shouldn't happen */
    566 				error = EINVAL;
    567 				goto out;
    568 			}
    569 			sce->ibuf = kmem_alloc(isize, KM_SLEEP);
    570 			DPRINTFN(5, ("ugenopen: intr endpt=%d,isize=%d\n",
    571 				     endpt, isize));
    572 			if (clalloc(&sce->q, UGEN_IBSIZE, 0) == -1) {
    573 				kmem_free(sce->ibuf, isize);
    574 				sce->ibuf = NULL;
    575 				error = ENOMEM;
    576 				goto out;
    577 			}
    578 			err = usbd_open_pipe_intr(sce->iface,
    579 				  edesc->bEndpointAddress,
    580 				  USBD_SHORT_XFER_OK, &sce->pipeh, sce,
    581 				  sce->ibuf, isize, ugenintr,
    582 				  USBD_DEFAULT_INTERVAL);
    583 			if (err) {
    584 				clfree(&sce->q);
    585 				kmem_free(sce->ibuf, isize);
    586 				sce->ibuf = NULL;
    587 				error = EIO;
    588 				goto out;
    589 			}
    590 			DPRINTFN(5, ("ugenopen: interrupt open done\n"));
    591 			break;
    592 		case UE_BULK:
    593 			err = usbd_open_pipe(sce->iface,
    594 				  edesc->bEndpointAddress, 0, &sce->pipeh);
    595 			if (err) {
    596 				error = EIO;
    597 				goto out;
    598 			}
    599 			sce->ra_wb_bufsize = UGEN_BULK_RA_WB_BUFSIZE;
    600 			/*
    601 			 * Use request size for non-RA/WB transfers
    602 			 * as the default.
    603 			 */
    604 			sce->ra_wb_reqsize = UGEN_BBSIZE;
    605 			break;
    606 		case UE_ISOCHRONOUS:
    607 			if (dir == OUT) {
    608 				error = EINVAL;
    609 				goto out;
    610 			}
    611 			isize = UGETW(edesc->wMaxPacketSize);
    612 			if (isize == 0) {	/* shouldn't happen */
    613 				error = EINVAL;
    614 				goto out;
    615 			}
    616 			sce->ibuf = kmem_alloc(isize * UGEN_NISOFRAMES,
    617 				KM_SLEEP);
    618 			sce->cur = sce->fill = sce->ibuf;
    619 			sce->limit = sce->ibuf + isize * UGEN_NISOFRAMES;
    620 			DPRINTFN(5, ("ugenopen: isoc endpt=%d, isize=%d\n",
    621 				     endpt, isize));
    622 			err = usbd_open_pipe(sce->iface,
    623 				  edesc->bEndpointAddress, 0, &sce->pipeh);
    624 			if (err) {
    625 				kmem_free(sce->ibuf, isize * UGEN_NISOFRAMES);
    626 				sce->ibuf = NULL;
    627 				error = EIO;
    628 				goto out;
    629 			}
    630 			for (i = 0; i < UGEN_NISOREQS; ++i) {
    631 				sce->isoreqs[i].sce = sce;
    632 				err = usbd_create_xfer(sce->pipeh,
    633 				    isize * UGEN_NISORFRMS, 0, UGEN_NISORFRMS,
    634 				    &xfer);
    635 				if (err)
    636 					goto bad;
    637 				sce->isoreqs[i].xfer = xfer;
    638 				sce->isoreqs[i].dmabuf = usbd_get_buffer(xfer);
    639 				for (j = 0; j < UGEN_NISORFRMS; ++j)
    640 					sce->isoreqs[i].sizes[j] = isize;
    641 				usbd_setup_isoc_xfer(xfer, &sce->isoreqs[i],
    642 				    sce->isoreqs[i].sizes, UGEN_NISORFRMS, 0,
    643 				    ugen_isoc_rintr);
    644 				(void)usbd_transfer(xfer);
    645 			}
    646 			DPRINTFN(5, ("ugenopen: isoc open done\n"));
    647 			break;
    648 		bad:
    649 			while (--i >= 0) /* implicit buffer free */
    650 				usbd_destroy_xfer(sce->isoreqs[i].xfer);
    651 			usbd_close_pipe(sce->pipeh);
    652 			sce->pipeh = NULL;
    653 			kmem_free(sce->ibuf, isize * UGEN_NISOFRAMES);
    654 			sce->ibuf = NULL;
    655 			error = ENOMEM;
    656 			goto out;
    657 		case UE_CONTROL:
    658 			sce->timeout = USBD_DEFAULT_TIMEOUT;
    659 			error = EINVAL;
    660 			goto out;
    661 		}
    662 	}
    663 	sc->sc_is_open[endpt] = 1;
    664 	error = 0;
    665 out:	ugenif_release(sc);
    666 	return error;
    667 }
    668 
    669 static int
    670 ugenclose(dev_t dev, int flag, int mode, struct lwp *l)
    671 {
    672 	int endpt = UGENENDPOINT(dev);
    673 	struct ugen_softc *sc;
    674 	struct ugen_endpoint *sce;
    675 	int dir;
    676 	int i;
    677 	int error;
    678 
    679 	if ((sc = ugenif_acquire(UGENUNIT(dev))) == NULL)
    680 		return ENXIO;
    681 
    682 	DPRINTFN(5, ("ugenclose: flag=%d, mode=%d, unit=%d, endpt=%d\n",
    683 		     flag, mode, UGENUNIT(dev), endpt));
    684 
    685 	KASSERT(sc->sc_is_open[endpt]);
    686 
    687 	if (endpt == USB_CONTROL_ENDPOINT) {
    688 		DPRINTFN(5, ("ugenclose: close control\n"));
    689 		sc->sc_is_open[endpt] = 0;
    690 		error = 0;
    691 		goto out;
    692 	}
    693 
    694 	for (dir = OUT; dir <= IN; dir++) {
    695 		if (!(flag & (dir == OUT ? FWRITE : FREAD)))
    696 			continue;
    697 		sce = &sc->sc_endpoints[endpt][dir];
    698 		if (sce->pipeh == NULL)
    699 			continue;
    700 		DPRINTFN(5, ("ugenclose: endpt=%d dir=%d sce=%p\n",
    701 			     endpt, dir, sce));
    702 
    703 		usbd_abort_pipe(sce->pipeh);
    704 
    705 		int isize = UGETW(sce->edesc->wMaxPacketSize);
    706 		int msize = 0;
    707 
    708 		switch (sce->edesc->bmAttributes & UE_XFERTYPE) {
    709 		case UE_INTERRUPT:
    710 			ndflush(&sce->q, sce->q.c_cc);
    711 			clfree(&sce->q);
    712 			msize = isize;
    713 			break;
    714 		case UE_ISOCHRONOUS:
    715 			for (i = 0; i < UGEN_NISOREQS; ++i)
    716 				usbd_destroy_xfer(sce->isoreqs[i].xfer);
    717 			msize = isize * UGEN_NISOFRAMES;
    718 			break;
    719 		case UE_BULK:
    720 			if (sce->state & (UGEN_BULK_RA | UGEN_BULK_WB)) {
    721 				usbd_destroy_xfer(sce->ra_wb_xfer);
    722 				msize = sce->ra_wb_bufsize;
    723 			}
    724 			break;
    725 		default:
    726 			break;
    727 		}
    728 		usbd_close_pipe(sce->pipeh);
    729 		sce->pipeh = NULL;
    730 		if (sce->ibuf != NULL) {
    731 			kmem_free(sce->ibuf, msize);
    732 			sce->ibuf = NULL;
    733 		}
    734 	}
    735 	sc->sc_is_open[endpt] = 0;
    736 	error = 0;
    737 
    738 out:	ugenif_release(sc);
    739 	return error;
    740 }
    741 
    742 Static int
    743 ugen_do_read(struct ugen_softc *sc, int endpt, struct uio *uio, int flag)
    744 {
    745 	struct ugen_endpoint *sce = &sc->sc_endpoints[endpt][IN];
    746 	uint32_t n, tn;
    747 	struct usbd_xfer *xfer;
    748 	usbd_status err;
    749 	int error = 0;
    750 
    751 	DPRINTFN(5, ("%s: ugenread: %d\n", device_xname(sc->sc_dev), endpt));
    752 
    753 	if (endpt == USB_CONTROL_ENDPOINT)
    754 		return ENODEV;
    755 
    756 	KASSERT(sce->edesc);
    757 	KASSERT(sce->pipeh);
    758 
    759 	switch (sce->edesc->bmAttributes & UE_XFERTYPE) {
    760 	case UE_INTERRUPT:
    761 		/* Block until activity occurred. */
    762 		mutex_enter(&sc->sc_lock);
    763 		while (sce->q.c_cc == 0) {
    764 			if (flag & IO_NDELAY) {
    765 				mutex_exit(&sc->sc_lock);
    766 				return EWOULDBLOCK;
    767 			}
    768 			DPRINTFN(5, ("ugenread: sleep on %p\n", sce));
    769 			/* "ugenri" */
    770 			error = cv_timedwait_sig(&sce->cv, &sc->sc_lock,
    771 			    mstohz(sce->timeout));
    772 			DPRINTFN(5, ("ugenread: woke, error=%d\n", error));
    773 			if (sc->sc_dying)
    774 				error = EIO;
    775 			if (error)
    776 				break;
    777 		}
    778 		mutex_exit(&sc->sc_lock);
    779 
    780 		/* Transfer as many chunks as possible. */
    781 		while (sce->q.c_cc > 0 && uio->uio_resid > 0 && !error) {
    782 			n = uimin(sce->q.c_cc, uio->uio_resid);
    783 			if (n > sizeof(sc->sc_buffer))
    784 				n = sizeof(sc->sc_buffer);
    785 
    786 			/* Remove a small chunk from the input queue. */
    787 			q_to_b(&sce->q, sc->sc_buffer, n);
    788 			DPRINTFN(5, ("ugenread: got %d chars\n", n));
    789 
    790 			/* Copy the data to the user process. */
    791 			error = uiomove(sc->sc_buffer, n, uio);
    792 			if (error)
    793 				break;
    794 		}
    795 		break;
    796 	case UE_BULK:
    797 		if (sce->state & UGEN_BULK_RA) {
    798 			DPRINTFN(5, ("ugenread: BULK_RA req: %zd used: %d\n",
    799 				     uio->uio_resid, sce->ra_wb_used));
    800 			xfer = sce->ra_wb_xfer;
    801 
    802 			mutex_enter(&sc->sc_lock);
    803 			if (sce->ra_wb_used == 0 && flag & IO_NDELAY) {
    804 				mutex_exit(&sc->sc_lock);
    805 				return EWOULDBLOCK;
    806 			}
    807 			while (uio->uio_resid > 0 && !error) {
    808 				while (sce->ra_wb_used == 0) {
    809 					DPRINTFN(5,
    810 						 ("ugenread: sleep on %p\n",
    811 						  sce));
    812 					/* "ugenrb" */
    813 					error = cv_timedwait_sig(&sce->cv,
    814 					    &sc->sc_lock, mstohz(sce->timeout));
    815 					DPRINTFN(5,
    816 						 ("ugenread: woke, error=%d\n",
    817 						  error));
    818 					if (sc->sc_dying)
    819 						error = EIO;
    820 					if (error)
    821 						break;
    822 				}
    823 
    824 				/* Copy data to the process. */
    825 				while (uio->uio_resid > 0
    826 				       && sce->ra_wb_used > 0) {
    827 					n = uimin(uio->uio_resid,
    828 						sce->ra_wb_used);
    829 					n = uimin(n, sce->limit - sce->cur);
    830 					error = uiomove(sce->cur, n, uio);
    831 					if (error)
    832 						break;
    833 					sce->cur += n;
    834 					sce->ra_wb_used -= n;
    835 					if (sce->cur == sce->limit)
    836 						sce->cur = sce->ibuf;
    837 				}
    838 
    839 				/*
    840 				 * If the transfers stopped because the
    841 				 * buffer was full, restart them.
    842 				 */
    843 				if (sce->state & UGEN_RA_WB_STOP &&
    844 				    sce->ra_wb_used < sce->limit - sce->ibuf) {
    845 					n = (sce->limit - sce->ibuf)
    846 					    - sce->ra_wb_used;
    847 					usbd_setup_xfer(xfer, sce, NULL,
    848 					    uimin(n, sce->ra_wb_xferlen),
    849 					    0, USBD_NO_TIMEOUT,
    850 					    ugen_bulkra_intr);
    851 					sce->state &= ~UGEN_RA_WB_STOP;
    852 					err = usbd_transfer(xfer);
    853 					if (err != USBD_IN_PROGRESS)
    854 						/*
    855 						 * The transfer has not been
    856 						 * queued.  Setting STOP
    857 						 * will make us try
    858 						 * again at the next read.
    859 						 */
    860 						sce->state |= UGEN_RA_WB_STOP;
    861 				}
    862 			}
    863 			mutex_exit(&sc->sc_lock);
    864 			break;
    865 		}
    866 		error = usbd_create_xfer(sce->pipeh, UGEN_BBSIZE,
    867 		    0, 0, &xfer);
    868 		if (error)
    869 			return error;
    870 		while ((n = uimin(UGEN_BBSIZE, uio->uio_resid)) != 0) {
    871 			DPRINTFN(1, ("ugenread: start transfer %d bytes\n",n));
    872 			tn = n;
    873 			err = usbd_bulk_transfer(xfer, sce->pipeh,
    874 			    sce->state & UGEN_SHORT_OK ? USBD_SHORT_XFER_OK : 0,
    875 			    sce->timeout, sc->sc_buffer, &tn);
    876 			if (err) {
    877 				if (err == USBD_INTERRUPTED)
    878 					error = EINTR;
    879 				else if (err == USBD_TIMEOUT)
    880 					error = ETIMEDOUT;
    881 				else
    882 					error = EIO;
    883 				break;
    884 			}
    885 			DPRINTFN(1, ("ugenread: got %d bytes\n", tn));
    886 			error = uiomove(sc->sc_buffer, tn, uio);
    887 			if (error || tn < n)
    888 				break;
    889 		}
    890 		usbd_destroy_xfer(xfer);
    891 		break;
    892 	case UE_ISOCHRONOUS:
    893 		mutex_enter(&sc->sc_lock);
    894 		while (sce->cur == sce->fill) {
    895 			if (flag & IO_NDELAY) {
    896 				mutex_exit(&sc->sc_lock);
    897 				return EWOULDBLOCK;
    898 			}
    899 			/* "ugenri" */
    900 			DPRINTFN(5, ("ugenread: sleep on %p\n", sce));
    901 			error = cv_timedwait_sig(&sce->cv, &sc->sc_lock,
    902 			    mstohz(sce->timeout));
    903 			DPRINTFN(5, ("ugenread: woke, error=%d\n", error));
    904 			if (sc->sc_dying)
    905 				error = EIO;
    906 			if (error)
    907 				break;
    908 		}
    909 
    910 		while (sce->cur != sce->fill && uio->uio_resid > 0 && !error) {
    911 			if(sce->fill > sce->cur)
    912 				n = uimin(sce->fill - sce->cur, uio->uio_resid);
    913 			else
    914 				n = uimin(sce->limit - sce->cur, uio->uio_resid);
    915 
    916 			DPRINTFN(5, ("ugenread: isoc got %d chars\n", n));
    917 
    918 			/* Copy the data to the user process. */
    919 			error = uiomove(sce->cur, n, uio);
    920 			if (error)
    921 				break;
    922 			sce->cur += n;
    923 			if (sce->cur >= sce->limit)
    924 				sce->cur = sce->ibuf;
    925 		}
    926 		mutex_exit(&sc->sc_lock);
    927 		break;
    928 
    929 
    930 	default:
    931 		return ENXIO;
    932 	}
    933 	return error;
    934 }
    935 
    936 static int
    937 ugenread(dev_t dev, struct uio *uio, int flag)
    938 {
    939 	int endpt = UGENENDPOINT(dev);
    940 	struct ugen_softc *sc;
    941 	int error;
    942 
    943 	if ((sc = ugenif_acquire(UGENUNIT(dev))) == NULL)
    944 		return ENXIO;
    945 	error = ugen_do_read(sc, endpt, uio, flag);
    946 	ugenif_release(sc);
    947 
    948 	return error;
    949 }
    950 
    951 Static int
    952 ugen_do_write(struct ugen_softc *sc, int endpt, struct uio *uio,
    953 	int flag)
    954 {
    955 	struct ugen_endpoint *sce = &sc->sc_endpoints[endpt][OUT];
    956 	uint32_t n;
    957 	int error = 0;
    958 	uint32_t tn;
    959 	char *dbuf;
    960 	struct usbd_xfer *xfer;
    961 	usbd_status err;
    962 
    963 	DPRINTFN(5, ("%s: ugenwrite: %d\n", device_xname(sc->sc_dev), endpt));
    964 
    965 	if (endpt == USB_CONTROL_ENDPOINT)
    966 		return ENODEV;
    967 
    968 	KASSERT(sce->edesc);
    969 	KASSERT(sce->pipeh);
    970 
    971 	switch (sce->edesc->bmAttributes & UE_XFERTYPE) {
    972 	case UE_BULK:
    973 		if (sce->state & UGEN_BULK_WB) {
    974 			DPRINTFN(5, ("ugenwrite: BULK_WB req: %zd used: %d\n",
    975 				     uio->uio_resid, sce->ra_wb_used));
    976 			xfer = sce->ra_wb_xfer;
    977 
    978 			mutex_enter(&sc->sc_lock);
    979 			if (sce->ra_wb_used == sce->limit - sce->ibuf &&
    980 			    flag & IO_NDELAY) {
    981 				mutex_exit(&sc->sc_lock);
    982 				return EWOULDBLOCK;
    983 			}
    984 			while (uio->uio_resid > 0 && !error) {
    985 				while (sce->ra_wb_used ==
    986 				       sce->limit - sce->ibuf) {
    987 					DPRINTFN(5,
    988 						 ("ugenwrite: sleep on %p\n",
    989 						  sce));
    990 					/* "ugenwb" */
    991 					error = cv_timedwait_sig(&sce->cv,
    992 					    &sc->sc_lock, mstohz(sce->timeout));
    993 					DPRINTFN(5,
    994 						 ("ugenwrite: woke, error=%d\n",
    995 						  error));
    996 					if (sc->sc_dying)
    997 						error = EIO;
    998 					if (error)
    999 						break;
   1000 				}
   1001 
   1002 				/* Copy data from the process. */
   1003 				while (uio->uio_resid > 0 &&
   1004 				    sce->ra_wb_used < sce->limit - sce->ibuf) {
   1005 					n = uimin(uio->uio_resid,
   1006 						(sce->limit - sce->ibuf)
   1007 						 - sce->ra_wb_used);
   1008 					n = uimin(n, sce->limit - sce->fill);
   1009 					error = uiomove(sce->fill, n, uio);
   1010 					if (error)
   1011 						break;
   1012 					sce->fill += n;
   1013 					sce->ra_wb_used += n;
   1014 					if (sce->fill == sce->limit)
   1015 						sce->fill = sce->ibuf;
   1016 				}
   1017 
   1018 				/*
   1019 				 * If the transfers stopped because the
   1020 				 * buffer was empty, restart them.
   1021 				 */
   1022 				if (sce->state & UGEN_RA_WB_STOP &&
   1023 				    sce->ra_wb_used > 0) {
   1024 					dbuf = (char *)usbd_get_buffer(xfer);
   1025 					n = uimin(sce->ra_wb_used,
   1026 						sce->ra_wb_xferlen);
   1027 					tn = uimin(n, sce->limit - sce->cur);
   1028 					memcpy(dbuf, sce->cur, tn);
   1029 					dbuf += tn;
   1030 					if (n - tn > 0)
   1031 						memcpy(dbuf, sce->ibuf,
   1032 						       n - tn);
   1033 					usbd_setup_xfer(xfer, sce, NULL, n,
   1034 					    0, USBD_NO_TIMEOUT,
   1035 					    ugen_bulkwb_intr);
   1036 					sce->state &= ~UGEN_RA_WB_STOP;
   1037 					err = usbd_transfer(xfer);
   1038 					if (err != USBD_IN_PROGRESS)
   1039 						/*
   1040 						 * The transfer has not been
   1041 						 * queued.  Setting STOP
   1042 						 * will make us try again
   1043 						 * at the next read.
   1044 						 */
   1045 						sce->state |= UGEN_RA_WB_STOP;
   1046 				}
   1047 			}
   1048 			mutex_exit(&sc->sc_lock);
   1049 			break;
   1050 		}
   1051 		error = usbd_create_xfer(sce->pipeh, UGEN_BBSIZE,
   1052 		    0, 0, &xfer);
   1053 		if (error)
   1054 			return error;
   1055 		while ((n = uimin(UGEN_BBSIZE, uio->uio_resid)) != 0) {
   1056 			error = uiomove(sc->sc_buffer, n, uio);
   1057 			if (error)
   1058 				break;
   1059 			DPRINTFN(1, ("ugenwrite: transfer %d bytes\n", n));
   1060 			err = usbd_bulk_transfer(xfer, sce->pipeh, 0, sce->timeout,
   1061 			    sc->sc_buffer, &n);
   1062 			if (err) {
   1063 				if (err == USBD_INTERRUPTED)
   1064 					error = EINTR;
   1065 				else if (err == USBD_TIMEOUT)
   1066 					error = ETIMEDOUT;
   1067 				else
   1068 					error = EIO;
   1069 				break;
   1070 			}
   1071 		}
   1072 		usbd_destroy_xfer(xfer);
   1073 		break;
   1074 	case UE_INTERRUPT:
   1075 		error = usbd_create_xfer(sce->pipeh,
   1076 		    UGETW(sce->edesc->wMaxPacketSize), 0, 0, &xfer);
   1077 		if (error)
   1078 			return error;
   1079 		while ((n = uimin(UGETW(sce->edesc->wMaxPacketSize),
   1080 		    uio->uio_resid)) != 0) {
   1081 			error = uiomove(sc->sc_buffer, n, uio);
   1082 			if (error)
   1083 				break;
   1084 			DPRINTFN(1, ("ugenwrite: transfer %d bytes\n", n));
   1085 			err = usbd_intr_transfer(xfer, sce->pipeh, 0,
   1086 			    sce->timeout, sc->sc_buffer, &n);
   1087 			if (err) {
   1088 				if (err == USBD_INTERRUPTED)
   1089 					error = EINTR;
   1090 				else if (err == USBD_TIMEOUT)
   1091 					error = ETIMEDOUT;
   1092 				else
   1093 					error = EIO;
   1094 				break;
   1095 			}
   1096 		}
   1097 		usbd_destroy_xfer(xfer);
   1098 		break;
   1099 	default:
   1100 		return ENXIO;
   1101 	}
   1102 	return error;
   1103 }
   1104 
   1105 static int
   1106 ugenwrite(dev_t dev, struct uio *uio, int flag)
   1107 {
   1108 	int endpt = UGENENDPOINT(dev);
   1109 	struct ugen_softc *sc;
   1110 	int error;
   1111 
   1112 	if ((sc = ugenif_acquire(UGENUNIT(dev))) == NULL)
   1113 		return ENXIO;
   1114 	error = ugen_do_write(sc, endpt, uio, flag);
   1115 	ugenif_release(sc);
   1116 
   1117 	return error;
   1118 }
   1119 
   1120 static int
   1121 ugen_activate(device_t self, enum devact act)
   1122 {
   1123 	struct ugen_softc *sc = device_private(self);
   1124 
   1125 	switch (act) {
   1126 	case DVACT_DEACTIVATE:
   1127 		sc->sc_dying = 1;
   1128 		return 0;
   1129 	default:
   1130 		return EOPNOTSUPP;
   1131 	}
   1132 }
   1133 
   1134 static int
   1135 ugen_detach(device_t self, int flags)
   1136 {
   1137 	struct ugen_softc *sc = device_private(self);
   1138 	struct ugen_endpoint *sce;
   1139 	int i, dir;
   1140 	int maj, mn;
   1141 
   1142 	DPRINTF(("ugen_detach: sc=%p flags=%d\n", sc, flags));
   1143 
   1144 	sc->sc_dying = 1;
   1145 	pmf_device_deregister(self);
   1146 	/* Abort all pipes.  Causes processes waiting for transfer to wake. */
   1147 	for (i = 0; i < USB_MAX_ENDPOINTS; i++) {
   1148 		for (dir = OUT; dir <= IN; dir++) {
   1149 			sce = &sc->sc_endpoints[i][dir];
   1150 			if (sce->pipeh)
   1151 				usbd_abort_pipe(sce->pipeh);
   1152 		}
   1153 	}
   1154 
   1155 	mutex_enter(&sc->sc_lock);
   1156 	if (--sc->sc_refcnt >= 0) {
   1157 		/* Wake everyone */
   1158 		for (i = 0; i < USB_MAX_ENDPOINTS; i++)
   1159 			cv_signal(&sc->sc_endpoints[i][IN].cv);
   1160 		/* Wait for processes to go away. */
   1161 		if (cv_timedwait(&sc->sc_detach_cv, &sc->sc_lock, hz * 60))
   1162 			aprint_error_dev(self, ": didn't detach\n");
   1163 	}
   1164 	mutex_exit(&sc->sc_lock);
   1165 
   1166 	/* locate the major number */
   1167 	maj = cdevsw_lookup_major(&ugen_cdevsw);
   1168 
   1169 	/* Nuke the vnodes for any open instances (calls close). */
   1170 	mn = sc->sc_unit * USB_MAX_ENDPOINTS;
   1171 	vdevgone(maj, mn, mn + USB_MAX_ENDPOINTS - 1, VCHR);
   1172 
   1173 	usbd_add_drv_event(USB_EVENT_DRIVER_DETACH, sc->sc_udev, sc->sc_dev);
   1174 	ugenif_put_unit(sc);
   1175 
   1176 	for (i = 0; i < USB_MAX_ENDPOINTS; i++) {
   1177 		for (dir = OUT; dir <= IN; dir++) {
   1178 			sce = &sc->sc_endpoints[i][dir];
   1179 			seldestroy(&sce->rsel);
   1180 			cv_destroy(&sce->cv);
   1181 		}
   1182 	}
   1183 
   1184 	cv_destroy(&sc->sc_detach_cv);
   1185 	mutex_destroy(&sc->sc_lock);
   1186 
   1187 	return 0;
   1188 }
   1189 
   1190 Static void
   1191 ugenintr(struct usbd_xfer *xfer, void *addr, usbd_status status)
   1192 {
   1193 	struct ugen_endpoint *sce = addr;
   1194 	struct ugen_softc *sc = sce->sc;
   1195 	uint32_t count;
   1196 	u_char *ibuf;
   1197 
   1198 	if (status == USBD_CANCELLED)
   1199 		return;
   1200 
   1201 	if (status != USBD_NORMAL_COMPLETION) {
   1202 		DPRINTF(("ugenintr: status=%d\n", status));
   1203 		if (status == USBD_STALLED)
   1204 		    usbd_clear_endpoint_stall_async(sce->pipeh);
   1205 		return;
   1206 	}
   1207 
   1208 	usbd_get_xfer_status(xfer, NULL, NULL, &count, NULL);
   1209 	ibuf = sce->ibuf;
   1210 
   1211 	DPRINTFN(5, ("ugenintr: xfer=%p status=%d count=%d\n",
   1212 		     xfer, status, count));
   1213 	DPRINTFN(5, ("          data = %02x %02x %02x\n",
   1214 		     ibuf[0], ibuf[1], ibuf[2]));
   1215 
   1216 	mutex_enter(&sc->sc_lock);
   1217 	(void)b_to_q(ibuf, count, &sce->q);
   1218 	cv_signal(&sce->cv);
   1219 	mutex_exit(&sc->sc_lock);
   1220 	selnotify(&sce->rsel, 0, 0);
   1221 }
   1222 
   1223 Static void
   1224 ugen_isoc_rintr(struct usbd_xfer *xfer, void *addr,
   1225 		usbd_status status)
   1226 {
   1227 	struct isoreq *req = addr;
   1228 	struct ugen_endpoint *sce = req->sce;
   1229 	struct ugen_softc *sc = sce->sc;
   1230 	uint32_t count, n;
   1231 	int i, isize;
   1232 
   1233 	/* Return if we are aborting. */
   1234 	if (status == USBD_CANCELLED)
   1235 		return;
   1236 
   1237 	usbd_get_xfer_status(xfer, NULL, NULL, &count, NULL);
   1238 	DPRINTFN(5,("ugen_isoc_rintr: xfer %ld, count=%d\n",
   1239 	    (long)(req - sce->isoreqs), count));
   1240 
   1241 	mutex_enter(&sc->sc_lock);
   1242 
   1243 	/* throw away oldest input if the buffer is full */
   1244 	if (sce->fill < sce->cur && sce->cur <= sce->fill + count) {
   1245 		sce->cur += count;
   1246 		if (sce->cur >= sce->limit)
   1247 			sce->cur = sce->ibuf + (sce->limit - sce->cur);
   1248 		DPRINTFN(5, ("ugen_isoc_rintr: throwing away %d bytes\n",
   1249 			     count));
   1250 	}
   1251 
   1252 	isize = UGETW(sce->edesc->wMaxPacketSize);
   1253 	for (i = 0; i < UGEN_NISORFRMS; i++) {
   1254 		uint32_t actlen = req->sizes[i];
   1255 		char const *tbuf = (char const *)req->dmabuf + isize * i;
   1256 
   1257 		/* copy data to buffer */
   1258 		while (actlen > 0) {
   1259 			n = uimin(actlen, sce->limit - sce->fill);
   1260 			memcpy(sce->fill, tbuf, n);
   1261 
   1262 			tbuf += n;
   1263 			actlen -= n;
   1264 			sce->fill += n;
   1265 			if (sce->fill == sce->limit)
   1266 				sce->fill = sce->ibuf;
   1267 		}
   1268 
   1269 		/* setup size for next transfer */
   1270 		req->sizes[i] = isize;
   1271 	}
   1272 
   1273 	usbd_setup_isoc_xfer(xfer, req, req->sizes, UGEN_NISORFRMS, 0,
   1274 	    ugen_isoc_rintr);
   1275 	(void)usbd_transfer(xfer);
   1276 
   1277 	cv_signal(&sce->cv);
   1278 	mutex_exit(&sc->sc_lock);
   1279 	selnotify(&sce->rsel, 0, 0);
   1280 }
   1281 
   1282 Static void
   1283 ugen_bulkra_intr(struct usbd_xfer *xfer, void *addr,
   1284 		 usbd_status status)
   1285 {
   1286 	struct ugen_endpoint *sce = addr;
   1287 	struct ugen_softc *sc = sce->sc;
   1288 	uint32_t count, n;
   1289 	char const *tbuf;
   1290 	usbd_status err;
   1291 
   1292 	/* Return if we are aborting. */
   1293 	if (status == USBD_CANCELLED)
   1294 		return;
   1295 
   1296 	if (status != USBD_NORMAL_COMPLETION) {
   1297 		DPRINTF(("ugen_bulkra_intr: status=%d\n", status));
   1298 		sce->state |= UGEN_RA_WB_STOP;
   1299 		if (status == USBD_STALLED)
   1300 		    usbd_clear_endpoint_stall_async(sce->pipeh);
   1301 		return;
   1302 	}
   1303 
   1304 	usbd_get_xfer_status(xfer, NULL, NULL, &count, NULL);
   1305 
   1306 	mutex_enter(&sc->sc_lock);
   1307 
   1308 	/* Keep track of how much is in the buffer. */
   1309 	sce->ra_wb_used += count;
   1310 
   1311 	/* Copy data to buffer. */
   1312 	tbuf = (char const *)usbd_get_buffer(sce->ra_wb_xfer);
   1313 	n = uimin(count, sce->limit - sce->fill);
   1314 	memcpy(sce->fill, tbuf, n);
   1315 	tbuf += n;
   1316 	count -= n;
   1317 	sce->fill += n;
   1318 	if (sce->fill == sce->limit)
   1319 		sce->fill = sce->ibuf;
   1320 	if (count > 0) {
   1321 		memcpy(sce->fill, tbuf, count);
   1322 		sce->fill += count;
   1323 	}
   1324 
   1325 	/* Set up the next request if necessary. */
   1326 	n = (sce->limit - sce->ibuf) - sce->ra_wb_used;
   1327 	if (n > 0) {
   1328 		usbd_setup_xfer(xfer, sce, NULL, uimin(n, sce->ra_wb_xferlen), 0,
   1329 		    USBD_NO_TIMEOUT, ugen_bulkra_intr);
   1330 		err = usbd_transfer(xfer);
   1331 		if (err != USBD_IN_PROGRESS) {
   1332 			printf("usbd_bulkra_intr: error=%d\n", err);
   1333 			/*
   1334 			 * The transfer has not been queued.  Setting STOP
   1335 			 * will make us try again at the next read.
   1336 			 */
   1337 			sce->state |= UGEN_RA_WB_STOP;
   1338 		}
   1339 	}
   1340 	else
   1341 		sce->state |= UGEN_RA_WB_STOP;
   1342 
   1343 	cv_signal(&sce->cv);
   1344 	mutex_exit(&sc->sc_lock);
   1345 	selnotify(&sce->rsel, 0, 0);
   1346 }
   1347 
   1348 Static void
   1349 ugen_bulkwb_intr(struct usbd_xfer *xfer, void *addr,
   1350 		 usbd_status status)
   1351 {
   1352 	struct ugen_endpoint *sce = addr;
   1353 	struct ugen_softc *sc = sce->sc;
   1354 	uint32_t count, n;
   1355 	char *tbuf;
   1356 	usbd_status err;
   1357 
   1358 	/* Return if we are aborting. */
   1359 	if (status == USBD_CANCELLED)
   1360 		return;
   1361 
   1362 	if (status != USBD_NORMAL_COMPLETION) {
   1363 		DPRINTF(("ugen_bulkwb_intr: status=%d\n", status));
   1364 		sce->state |= UGEN_RA_WB_STOP;
   1365 		if (status == USBD_STALLED)
   1366 		    usbd_clear_endpoint_stall_async(sce->pipeh);
   1367 		return;
   1368 	}
   1369 
   1370 	usbd_get_xfer_status(xfer, NULL, NULL, &count, NULL);
   1371 
   1372 	mutex_enter(&sc->sc_lock);
   1373 
   1374 	/* Keep track of how much is in the buffer. */
   1375 	sce->ra_wb_used -= count;
   1376 
   1377 	/* Update buffer pointers. */
   1378 	sce->cur += count;
   1379 	if (sce->cur >= sce->limit)
   1380 		sce->cur = sce->ibuf + (sce->cur - sce->limit);
   1381 
   1382 	/* Set up next request if necessary. */
   1383 	if (sce->ra_wb_used > 0) {
   1384 		/* copy data from buffer */
   1385 		tbuf = (char *)usbd_get_buffer(sce->ra_wb_xfer);
   1386 		count = uimin(sce->ra_wb_used, sce->ra_wb_xferlen);
   1387 		n = uimin(count, sce->limit - sce->cur);
   1388 		memcpy(tbuf, sce->cur, n);
   1389 		tbuf += n;
   1390 		if (count - n > 0)
   1391 			memcpy(tbuf, sce->ibuf, count - n);
   1392 
   1393 		usbd_setup_xfer(xfer, sce, NULL, count, 0, USBD_NO_TIMEOUT,
   1394 		    ugen_bulkwb_intr);
   1395 		err = usbd_transfer(xfer);
   1396 		if (err != USBD_IN_PROGRESS) {
   1397 			printf("usbd_bulkwb_intr: error=%d\n", err);
   1398 			/*
   1399 			 * The transfer has not been queued.  Setting STOP
   1400 			 * will make us try again at the next write.
   1401 			 */
   1402 			sce->state |= UGEN_RA_WB_STOP;
   1403 		}
   1404 	}
   1405 	else
   1406 		sce->state |= UGEN_RA_WB_STOP;
   1407 
   1408 	cv_signal(&sce->cv);
   1409 	mutex_exit(&sc->sc_lock);
   1410 	selnotify(&sce->rsel, 0, 0);
   1411 }
   1412 
   1413 Static usbd_status
   1414 ugen_set_interface(struct ugen_softc *sc, int ifaceidx, int altno)
   1415 {
   1416 	struct usbd_interface *iface;
   1417 	usb_endpoint_descriptor_t *ed;
   1418 	usbd_status err;
   1419 	struct ugen_endpoint *sce;
   1420 	uint8_t niface, nendpt, endptno, endpt;
   1421 	int dir;
   1422 
   1423 	DPRINTFN(15, ("ugen_set_interface %d %d\n", ifaceidx, altno));
   1424 
   1425 	err = usbd_interface_count(sc->sc_udev, &niface);
   1426 	if (err)
   1427 		return err;
   1428 	if (ifaceidx < 0 || ifaceidx >= niface)
   1429 		return USBD_INVAL;
   1430 
   1431 	err = usbd_device2interface_handle(sc->sc_udev, ifaceidx, &iface);
   1432 	if (err)
   1433 		return err;
   1434 	err = usbd_endpoint_count(iface, &nendpt);
   1435 	if (err)
   1436 		return err;
   1437 
   1438 	/* change setting */
   1439 	err = usbd_set_interface(iface, altno);
   1440 	if (err)
   1441 		return err;
   1442 
   1443 	err = usbd_endpoint_count(iface, &nendpt);
   1444 	if (err)
   1445 		return err;
   1446 
   1447 	ugen_clear_endpoints(sc);
   1448 
   1449 	for (endptno = 0; endptno < nendpt; endptno++) {
   1450 		ed = usbd_interface2endpoint_descriptor(iface,endptno);
   1451 		KASSERT(ed != NULL);
   1452 		endpt = ed->bEndpointAddress;
   1453 		dir = UE_GET_DIR(endpt) == UE_DIR_IN ? IN : OUT;
   1454 		sce = &sc->sc_endpoints[UE_GET_ADDR(endpt)][dir];
   1455 		sce->sc = sc;
   1456 		sce->edesc = ed;
   1457 		sce->iface = iface;
   1458 	}
   1459 	return 0;
   1460 }
   1461 
   1462 /* Retrieve a complete descriptor for a certain device and index. */
   1463 Static usb_config_descriptor_t *
   1464 ugen_get_cdesc(struct ugen_softc *sc, int index, int *lenp)
   1465 {
   1466 	usb_config_descriptor_t *cdesc, *tdesc, cdescr;
   1467 	int len;
   1468 	usbd_status err;
   1469 
   1470 	if (index == USB_CURRENT_CONFIG_INDEX) {
   1471 		tdesc = usbd_get_config_descriptor(sc->sc_udev);
   1472 		if (tdesc == NULL)
   1473 			return NULL;
   1474 		len = UGETW(tdesc->wTotalLength);
   1475 		if (lenp)
   1476 			*lenp = len;
   1477 		cdesc = kmem_alloc(len, KM_SLEEP);
   1478 		memcpy(cdesc, tdesc, len);
   1479 		DPRINTFN(5,("ugen_get_cdesc: current, len=%d\n", len));
   1480 	} else {
   1481 		err = usbd_get_config_desc(sc->sc_udev, index, &cdescr);
   1482 		if (err)
   1483 			return 0;
   1484 		len = UGETW(cdescr.wTotalLength);
   1485 		DPRINTFN(5,("ugen_get_cdesc: index=%d, len=%d\n", index, len));
   1486 		if (lenp)
   1487 			*lenp = len;
   1488 		cdesc = kmem_alloc(len, KM_SLEEP);
   1489 		err = usbd_get_config_desc_full(sc->sc_udev, index, cdesc, len);
   1490 		if (err) {
   1491 			kmem_free(cdesc, len);
   1492 			return 0;
   1493 		}
   1494 	}
   1495 	return cdesc;
   1496 }
   1497 
   1498 Static int
   1499 ugen_get_alt_index(struct ugen_softc *sc, int ifaceidx)
   1500 {
   1501 	struct usbd_interface *iface;
   1502 	usbd_status err;
   1503 
   1504 	err = usbd_device2interface_handle(sc->sc_udev, ifaceidx, &iface);
   1505 	if (err)
   1506 		return -1;
   1507 	return usbd_get_interface_altindex(iface);
   1508 }
   1509 
   1510 Static int
   1511 ugen_do_ioctl(struct ugen_softc *sc, int endpt, u_long cmd,
   1512 	      void *addr, int flag, struct lwp *l)
   1513 {
   1514 	struct ugen_endpoint *sce;
   1515 	usbd_status err;
   1516 	struct usbd_interface *iface;
   1517 	struct usb_config_desc *cd;
   1518 	usb_config_descriptor_t *cdesc;
   1519 	struct usb_interface_desc *id;
   1520 	usb_interface_descriptor_t *idesc;
   1521 	struct usb_endpoint_desc *ed;
   1522 	usb_endpoint_descriptor_t *edesc;
   1523 	struct usb_alt_interface *ai;
   1524 	struct usb_string_desc *si;
   1525 	uint8_t conf, alt;
   1526 	int cdesclen;
   1527 	int error;
   1528 	int dir;
   1529 
   1530 	DPRINTFN(5, ("ugenioctl: cmd=%08lx\n", cmd));
   1531 
   1532 	switch (cmd) {
   1533 	case FIONBIO:
   1534 		/* All handled in the upper FS layer. */
   1535 		return 0;
   1536 	case USB_SET_SHORT_XFER:
   1537 		if (endpt == USB_CONTROL_ENDPOINT)
   1538 			return EINVAL;
   1539 		/* This flag only affects read */
   1540 		sce = &sc->sc_endpoints[endpt][IN];
   1541 		if (sce == NULL || sce->pipeh == NULL)
   1542 			return EINVAL;
   1543 		if (*(int *)addr)
   1544 			sce->state |= UGEN_SHORT_OK;
   1545 		else
   1546 			sce->state &= ~UGEN_SHORT_OK;
   1547 		return 0;
   1548 	case USB_SET_TIMEOUT:
   1549 		for (dir = OUT; dir <= IN; dir++) {
   1550 			sce = &sc->sc_endpoints[endpt][dir];
   1551 			if (sce == NULL)
   1552 				return EINVAL;
   1553 
   1554 			sce->timeout = *(int *)addr;
   1555 		}
   1556 		return 0;
   1557 	case USB_SET_BULK_RA:
   1558 		if (endpt == USB_CONTROL_ENDPOINT)
   1559 			return EINVAL;
   1560 		sce = &sc->sc_endpoints[endpt][IN];
   1561 		if (sce == NULL || sce->pipeh == NULL)
   1562 			return EINVAL;
   1563 		edesc = sce->edesc;
   1564 		if ((edesc->bmAttributes & UE_XFERTYPE) != UE_BULK)
   1565 			return EINVAL;
   1566 
   1567 		if (*(int *)addr) {
   1568 			/* Only turn RA on if it's currently off. */
   1569 			if (sce->state & UGEN_BULK_RA)
   1570 				return 0;
   1571 
   1572 			if (sce->ra_wb_bufsize == 0 || sce->ra_wb_reqsize == 0)
   1573 				/* shouldn't happen */
   1574 				return EINVAL;
   1575 			error = usbd_create_xfer(sce->pipeh,
   1576 			    sce->ra_wb_reqsize, 0, 0, &sce->ra_wb_xfer);
   1577 			if (error)
   1578 				return error;
   1579 			sce->ra_wb_xferlen = sce->ra_wb_reqsize;
   1580 			sce->ibuf = kmem_alloc(sce->ra_wb_bufsize, KM_SLEEP);
   1581 			sce->fill = sce->cur = sce->ibuf;
   1582 			sce->limit = sce->ibuf + sce->ra_wb_bufsize;
   1583 			sce->ra_wb_used = 0;
   1584 			sce->state |= UGEN_BULK_RA;
   1585 			sce->state &= ~UGEN_RA_WB_STOP;
   1586 			/* Now start reading. */
   1587 			usbd_setup_xfer(sce->ra_wb_xfer, sce, NULL,
   1588 			    uimin(sce->ra_wb_xferlen, sce->ra_wb_bufsize),
   1589 			     0, USBD_NO_TIMEOUT, ugen_bulkra_intr);
   1590 			err = usbd_transfer(sce->ra_wb_xfer);
   1591 			if (err != USBD_IN_PROGRESS) {
   1592 				sce->state &= ~UGEN_BULK_RA;
   1593 				kmem_free(sce->ibuf, sce->ra_wb_bufsize);
   1594 				sce->ibuf = NULL;
   1595 				usbd_destroy_xfer(sce->ra_wb_xfer);
   1596 				return EIO;
   1597 			}
   1598 		} else {
   1599 			/* Only turn RA off if it's currently on. */
   1600 			if (!(sce->state & UGEN_BULK_RA))
   1601 				return 0;
   1602 
   1603 			sce->state &= ~UGEN_BULK_RA;
   1604 			usbd_abort_pipe(sce->pipeh);
   1605 			usbd_destroy_xfer(sce->ra_wb_xfer);
   1606 			/*
   1607 			 * XXX Discard whatever's in the buffer, but we
   1608 			 * should keep it around and drain the buffer
   1609 			 * instead.
   1610 			 */
   1611 			kmem_free(sce->ibuf, sce->ra_wb_bufsize);
   1612 			sce->ibuf = NULL;
   1613 		}
   1614 		return 0;
   1615 	case USB_SET_BULK_WB:
   1616 		if (endpt == USB_CONTROL_ENDPOINT)
   1617 			return EINVAL;
   1618 		sce = &sc->sc_endpoints[endpt][OUT];
   1619 		if (sce == NULL || sce->pipeh == NULL)
   1620 			return EINVAL;
   1621 		edesc = sce->edesc;
   1622 		if ((edesc->bmAttributes & UE_XFERTYPE) != UE_BULK)
   1623 			return EINVAL;
   1624 
   1625 		if (*(int *)addr) {
   1626 			/* Only turn WB on if it's currently off. */
   1627 			if (sce->state & UGEN_BULK_WB)
   1628 				return 0;
   1629 
   1630 			if (sce->ra_wb_bufsize == 0 || sce->ra_wb_reqsize == 0)
   1631 				/* shouldn't happen */
   1632 				return EINVAL;
   1633 			error = usbd_create_xfer(sce->pipeh, sce->ra_wb_reqsize,
   1634 			    0, 0, &sce->ra_wb_xfer);
   1635 			sce->ra_wb_xferlen = sce->ra_wb_reqsize;
   1636 			sce->ibuf = kmem_alloc(sce->ra_wb_bufsize, KM_SLEEP);
   1637 			sce->fill = sce->cur = sce->ibuf;
   1638 			sce->limit = sce->ibuf + sce->ra_wb_bufsize;
   1639 			sce->ra_wb_used = 0;
   1640 			sce->state |= UGEN_BULK_WB | UGEN_RA_WB_STOP;
   1641 		} else {
   1642 			/* Only turn WB off if it's currently on. */
   1643 			if (!(sce->state & UGEN_BULK_WB))
   1644 				return 0;
   1645 
   1646 			sce->state &= ~UGEN_BULK_WB;
   1647 			/*
   1648 			 * XXX Discard whatever's in the buffer, but we
   1649 			 * should keep it around and keep writing to
   1650 			 * drain the buffer instead.
   1651 			 */
   1652 			usbd_abort_pipe(sce->pipeh);
   1653 			usbd_destroy_xfer(sce->ra_wb_xfer);
   1654 			kmem_free(sce->ibuf, sce->ra_wb_bufsize);
   1655 			sce->ibuf = NULL;
   1656 		}
   1657 		return 0;
   1658 	case USB_SET_BULK_RA_OPT:
   1659 	case USB_SET_BULK_WB_OPT:
   1660 	{
   1661 		struct usb_bulk_ra_wb_opt *opt;
   1662 
   1663 		if (endpt == USB_CONTROL_ENDPOINT)
   1664 			return EINVAL;
   1665 		opt = (struct usb_bulk_ra_wb_opt *)addr;
   1666 		if (cmd == USB_SET_BULK_RA_OPT)
   1667 			sce = &sc->sc_endpoints[endpt][IN];
   1668 		else
   1669 			sce = &sc->sc_endpoints[endpt][OUT];
   1670 		if (sce == NULL || sce->pipeh == NULL)
   1671 			return EINVAL;
   1672 		if (opt->ra_wb_buffer_size < 1 ||
   1673 		    opt->ra_wb_buffer_size > UGEN_BULK_RA_WB_BUFMAX ||
   1674 		    opt->ra_wb_request_size < 1 ||
   1675 		    opt->ra_wb_request_size > opt->ra_wb_buffer_size)
   1676 			return EINVAL;
   1677 		/*
   1678 		 * XXX These changes do not take effect until the
   1679 		 * next time RA/WB mode is enabled but they ought to
   1680 		 * take effect immediately.
   1681 		 */
   1682 		sce->ra_wb_bufsize = opt->ra_wb_buffer_size;
   1683 		sce->ra_wb_reqsize = opt->ra_wb_request_size;
   1684 		return 0;
   1685 	}
   1686 	default:
   1687 		break;
   1688 	}
   1689 
   1690 	if (endpt != USB_CONTROL_ENDPOINT)
   1691 		return EINVAL;
   1692 
   1693 	switch (cmd) {
   1694 #ifdef UGEN_DEBUG
   1695 	case USB_SETDEBUG:
   1696 		ugendebug = *(int *)addr;
   1697 		break;
   1698 #endif
   1699 	case USB_GET_CONFIG:
   1700 		err = usbd_get_config(sc->sc_udev, &conf);
   1701 		if (err)
   1702 			return EIO;
   1703 		*(int *)addr = conf;
   1704 		break;
   1705 	case USB_SET_CONFIG:
   1706 		if (!(flag & FWRITE))
   1707 			return EPERM;
   1708 		err = ugen_set_config(sc, *(int *)addr, 1);
   1709 		switch (err) {
   1710 		case USBD_NORMAL_COMPLETION:
   1711 			break;
   1712 		case USBD_IN_USE:
   1713 			return EBUSY;
   1714 		default:
   1715 			return EIO;
   1716 		}
   1717 		break;
   1718 	case USB_GET_ALTINTERFACE:
   1719 		ai = (struct usb_alt_interface *)addr;
   1720 		err = usbd_device2interface_handle(sc->sc_udev,
   1721 			  ai->uai_interface_index, &iface);
   1722 		if (err)
   1723 			return EINVAL;
   1724 		idesc = usbd_get_interface_descriptor(iface);
   1725 		if (idesc == NULL)
   1726 			return EIO;
   1727 		ai->uai_alt_no = idesc->bAlternateSetting;
   1728 		break;
   1729 	case USB_SET_ALTINTERFACE:
   1730 		if (!(flag & FWRITE))
   1731 			return EPERM;
   1732 		ai = (struct usb_alt_interface *)addr;
   1733 		err = usbd_device2interface_handle(sc->sc_udev,
   1734 			  ai->uai_interface_index, &iface);
   1735 		if (err)
   1736 			return EINVAL;
   1737 		err = ugen_set_interface(sc, ai->uai_interface_index,
   1738 		    ai->uai_alt_no);
   1739 		if (err)
   1740 			return EINVAL;
   1741 		break;
   1742 	case USB_GET_NO_ALT:
   1743 		ai = (struct usb_alt_interface *)addr;
   1744 		cdesc = ugen_get_cdesc(sc, ai->uai_config_index, &cdesclen);
   1745 		if (cdesc == NULL)
   1746 			return EINVAL;
   1747 		idesc = usbd_find_idesc(cdesc, ai->uai_interface_index, 0);
   1748 		if (idesc == NULL) {
   1749 			kmem_free(cdesc, cdesclen);
   1750 			return EINVAL;
   1751 		}
   1752 		ai->uai_alt_no = usbd_get_no_alts(cdesc,
   1753 		    idesc->bInterfaceNumber);
   1754 		kmem_free(cdesc, cdesclen);
   1755 		break;
   1756 	case USB_GET_DEVICE_DESC:
   1757 		*(usb_device_descriptor_t *)addr =
   1758 			*usbd_get_device_descriptor(sc->sc_udev);
   1759 		break;
   1760 	case USB_GET_CONFIG_DESC:
   1761 		cd = (struct usb_config_desc *)addr;
   1762 		cdesc = ugen_get_cdesc(sc, cd->ucd_config_index, &cdesclen);
   1763 		if (cdesc == NULL)
   1764 			return EINVAL;
   1765 		cd->ucd_desc = *cdesc;
   1766 		kmem_free(cdesc, cdesclen);
   1767 		break;
   1768 	case USB_GET_INTERFACE_DESC:
   1769 		id = (struct usb_interface_desc *)addr;
   1770 		cdesc = ugen_get_cdesc(sc, id->uid_config_index, &cdesclen);
   1771 		if (cdesc == NULL)
   1772 			return EINVAL;
   1773 		if (id->uid_config_index == USB_CURRENT_CONFIG_INDEX &&
   1774 		    id->uid_alt_index == USB_CURRENT_ALT_INDEX)
   1775 			alt = ugen_get_alt_index(sc, id->uid_interface_index);
   1776 		else
   1777 			alt = id->uid_alt_index;
   1778 		idesc = usbd_find_idesc(cdesc, id->uid_interface_index, alt);
   1779 		if (idesc == NULL) {
   1780 			kmem_free(cdesc, cdesclen);
   1781 			return EINVAL;
   1782 		}
   1783 		id->uid_desc = *idesc;
   1784 		kmem_free(cdesc, cdesclen);
   1785 		break;
   1786 	case USB_GET_ENDPOINT_DESC:
   1787 		ed = (struct usb_endpoint_desc *)addr;
   1788 		cdesc = ugen_get_cdesc(sc, ed->ued_config_index, &cdesclen);
   1789 		if (cdesc == NULL)
   1790 			return EINVAL;
   1791 		if (ed->ued_config_index == USB_CURRENT_CONFIG_INDEX &&
   1792 		    ed->ued_alt_index == USB_CURRENT_ALT_INDEX)
   1793 			alt = ugen_get_alt_index(sc, ed->ued_interface_index);
   1794 		else
   1795 			alt = ed->ued_alt_index;
   1796 		edesc = usbd_find_edesc(cdesc, ed->ued_interface_index,
   1797 					alt, ed->ued_endpoint_index);
   1798 		if (edesc == NULL) {
   1799 			kmem_free(cdesc, cdesclen);
   1800 			return EINVAL;
   1801 		}
   1802 		ed->ued_desc = *edesc;
   1803 		kmem_free(cdesc, cdesclen);
   1804 		break;
   1805 	case USB_GET_FULL_DESC:
   1806 	{
   1807 		int len;
   1808 		struct iovec iov;
   1809 		struct uio uio;
   1810 		struct usb_full_desc *fd = (struct usb_full_desc *)addr;
   1811 
   1812 		cdesc = ugen_get_cdesc(sc, fd->ufd_config_index, &cdesclen);
   1813 		if (cdesc == NULL)
   1814 			return EINVAL;
   1815 		len = cdesclen;
   1816 		if (len > fd->ufd_size)
   1817 			len = fd->ufd_size;
   1818 		iov.iov_base = (void *)fd->ufd_data;
   1819 		iov.iov_len = len;
   1820 		uio.uio_iov = &iov;
   1821 		uio.uio_iovcnt = 1;
   1822 		uio.uio_resid = len;
   1823 		uio.uio_offset = 0;
   1824 		uio.uio_rw = UIO_READ;
   1825 		uio.uio_vmspace = l->l_proc->p_vmspace;
   1826 		error = uiomove((void *)cdesc, len, &uio);
   1827 		kmem_free(cdesc, cdesclen);
   1828 		return error;
   1829 	}
   1830 	case USB_GET_STRING_DESC: {
   1831 		int len;
   1832 		si = (struct usb_string_desc *)addr;
   1833 		err = usbd_get_string_desc(sc->sc_udev, si->usd_string_index,
   1834 			  si->usd_language_id, &si->usd_desc, &len);
   1835 		if (err)
   1836 			return EINVAL;
   1837 		break;
   1838 	}
   1839 	case USB_DO_REQUEST:
   1840 	{
   1841 		struct usb_ctl_request *ur = (void *)addr;
   1842 		int len = UGETW(ur->ucr_request.wLength);
   1843 		struct iovec iov;
   1844 		struct uio uio;
   1845 		void *ptr = 0;
   1846 		usbd_status xerr;
   1847 
   1848 		error = 0;
   1849 
   1850 		if (!(flag & FWRITE))
   1851 			return EPERM;
   1852 		/* Avoid requests that would damage the bus integrity. */
   1853 		if ((ur->ucr_request.bmRequestType == UT_WRITE_DEVICE &&
   1854 		     ur->ucr_request.bRequest == UR_SET_ADDRESS) ||
   1855 		    (ur->ucr_request.bmRequestType == UT_WRITE_DEVICE &&
   1856 		     ur->ucr_request.bRequest == UR_SET_CONFIG) ||
   1857 		    (ur->ucr_request.bmRequestType == UT_WRITE_INTERFACE &&
   1858 		     ur->ucr_request.bRequest == UR_SET_INTERFACE))
   1859 			return EINVAL;
   1860 
   1861 		if (len < 0 || len > 32767)
   1862 			return EINVAL;
   1863 		if (len != 0) {
   1864 			iov.iov_base = (void *)ur->ucr_data;
   1865 			iov.iov_len = len;
   1866 			uio.uio_iov = &iov;
   1867 			uio.uio_iovcnt = 1;
   1868 			uio.uio_resid = len;
   1869 			uio.uio_offset = 0;
   1870 			uio.uio_rw =
   1871 				ur->ucr_request.bmRequestType & UT_READ ?
   1872 				UIO_READ : UIO_WRITE;
   1873 			uio.uio_vmspace = l->l_proc->p_vmspace;
   1874 			ptr = kmem_alloc(len, KM_SLEEP);
   1875 			if (uio.uio_rw == UIO_WRITE) {
   1876 				error = uiomove(ptr, len, &uio);
   1877 				if (error)
   1878 					goto ret;
   1879 			}
   1880 		}
   1881 		sce = &sc->sc_endpoints[endpt][IN];
   1882 		xerr = usbd_do_request_flags(sc->sc_udev, &ur->ucr_request,
   1883 			  ptr, ur->ucr_flags, &ur->ucr_actlen, sce->timeout);
   1884 		if (xerr) {
   1885 			error = EIO;
   1886 			goto ret;
   1887 		}
   1888 		if (len != 0) {
   1889 			if (uio.uio_rw == UIO_READ) {
   1890 				size_t alen = uimin(len, ur->ucr_actlen);
   1891 				error = uiomove(ptr, alen, &uio);
   1892 				if (error)
   1893 					goto ret;
   1894 			}
   1895 		}
   1896 	ret:
   1897 		if (ptr)
   1898 			kmem_free(ptr, len);
   1899 		return error;
   1900 	}
   1901 	case USB_GET_DEVICEINFO:
   1902 		usbd_fill_deviceinfo(sc->sc_udev,
   1903 				     (struct usb_device_info *)addr, 0);
   1904 		break;
   1905 	case USB_GET_DEVICEINFO_OLD:
   1906 	{
   1907 		int ret;
   1908 		MODULE_HOOK_CALL(usb_subr_fill_30_hook,
   1909 		    (sc->sc_udev, (struct usb_device_info_old *)addr, 0,
   1910 		      usbd_devinfo_vp, usbd_printBCD),
   1911 		    enosys(), ret);
   1912 		if (ret == 0)
   1913 			return 0;
   1914 		return EINVAL;
   1915 	}
   1916 	default:
   1917 		return EINVAL;
   1918 	}
   1919 	return 0;
   1920 }
   1921 
   1922 static int
   1923 ugenioctl(dev_t dev, u_long cmd, void *addr, int flag, struct lwp *l)
   1924 {
   1925 	int endpt = UGENENDPOINT(dev);
   1926 	struct ugen_softc *sc;
   1927 	int error;
   1928 
   1929 	if ((sc = ugenif_acquire(UGENUNIT(dev))) == 0)
   1930 		return ENXIO;
   1931 	error = ugen_do_ioctl(sc, endpt, cmd, addr, flag, l);
   1932 	ugenif_release(sc);
   1933 
   1934 	return error;
   1935 }
   1936 
   1937 static int
   1938 ugenpoll(dev_t dev, int events, struct lwp *l)
   1939 {
   1940 	struct ugen_softc *sc;
   1941 	struct ugen_endpoint *sce_in, *sce_out;
   1942 	int revents = 0;
   1943 
   1944 	if ((sc = ugenif_acquire(UGENUNIT(dev))) == NULL)
   1945 		return POLLHUP;
   1946 
   1947 	if (UGENENDPOINT(dev) == USB_CONTROL_ENDPOINT) {
   1948 		revents |= POLLERR;
   1949 		goto out;
   1950 	}
   1951 
   1952 	sce_in = &sc->sc_endpoints[UGENENDPOINT(dev)][IN];
   1953 	sce_out = &sc->sc_endpoints[UGENENDPOINT(dev)][OUT];
   1954 	KASSERT(sce_in->edesc || sce_out->edesc);
   1955 	KASSERT(sce_in->pipeh || sce_out->pipeh);
   1956 
   1957 	mutex_enter(&sc->sc_lock);
   1958 	if (sce_in && sce_in->pipeh && (events & (POLLIN | POLLRDNORM)))
   1959 		switch (sce_in->edesc->bmAttributes & UE_XFERTYPE) {
   1960 		case UE_INTERRUPT:
   1961 			if (sce_in->q.c_cc > 0)
   1962 				revents |= events & (POLLIN | POLLRDNORM);
   1963 			else
   1964 				selrecord(l, &sce_in->rsel);
   1965 			break;
   1966 		case UE_ISOCHRONOUS:
   1967 			if (sce_in->cur != sce_in->fill)
   1968 				revents |= events & (POLLIN | POLLRDNORM);
   1969 			else
   1970 				selrecord(l, &sce_in->rsel);
   1971 			break;
   1972 		case UE_BULK:
   1973 			if (sce_in->state & UGEN_BULK_RA) {
   1974 				if (sce_in->ra_wb_used > 0)
   1975 					revents |= events &
   1976 					    (POLLIN | POLLRDNORM);
   1977 				else
   1978 					selrecord(l, &sce_in->rsel);
   1979 				break;
   1980 			}
   1981 			/*
   1982 			 * We have no easy way of determining if a read will
   1983 			 * yield any data or a write will happen.
   1984 			 * Pretend they will.
   1985 			 */
   1986 			revents |= events & (POLLIN | POLLRDNORM);
   1987 			break;
   1988 		default:
   1989 			break;
   1990 		}
   1991 	if (sce_out && sce_out->pipeh && (events & (POLLOUT | POLLWRNORM)))
   1992 		switch (sce_out->edesc->bmAttributes & UE_XFERTYPE) {
   1993 		case UE_INTERRUPT:
   1994 		case UE_ISOCHRONOUS:
   1995 			/* XXX unimplemented */
   1996 			break;
   1997 		case UE_BULK:
   1998 			if (sce_out->state & UGEN_BULK_WB) {
   1999 				if (sce_out->ra_wb_used <
   2000 				    sce_out->limit - sce_out->ibuf)
   2001 					revents |= events &
   2002 					    (POLLOUT | POLLWRNORM);
   2003 				else
   2004 					selrecord(l, &sce_out->rsel);
   2005 				break;
   2006 			}
   2007 			/*
   2008 			 * We have no easy way of determining if a read will
   2009 			 * yield any data or a write will happen.
   2010 			 * Pretend they will.
   2011 			 */
   2012 			 revents |= events & (POLLOUT | POLLWRNORM);
   2013 			 break;
   2014 		default:
   2015 			break;
   2016 		}
   2017 
   2018 	mutex_exit(&sc->sc_lock);
   2019 
   2020 out:	ugenif_release(sc);
   2021 	return revents;
   2022 }
   2023 
   2024 static void
   2025 filt_ugenrdetach(struct knote *kn)
   2026 {
   2027 	struct ugen_endpoint *sce = kn->kn_hook;
   2028 	struct ugen_softc *sc = sce->sc;
   2029 
   2030 	mutex_enter(&sc->sc_lock);
   2031 	SLIST_REMOVE(&sce->rsel.sel_klist, kn, knote, kn_selnext);
   2032 	mutex_exit(&sc->sc_lock);
   2033 }
   2034 
   2035 static int
   2036 filt_ugenread_intr(struct knote *kn, long hint)
   2037 {
   2038 	struct ugen_endpoint *sce = kn->kn_hook;
   2039 	struct ugen_softc *sc = sce->sc;
   2040 	int ret;
   2041 
   2042 	mutex_enter(&sc->sc_lock);
   2043 	if (sc->sc_dying) {
   2044 		ret = 0;
   2045 	} else {
   2046 		kn->kn_data = sce->q.c_cc;
   2047 		ret = kn->kn_data > 0;
   2048 	}
   2049 	mutex_exit(&sc->sc_lock);
   2050 
   2051 	return ret;
   2052 }
   2053 
   2054 static int
   2055 filt_ugenread_isoc(struct knote *kn, long hint)
   2056 {
   2057 	struct ugen_endpoint *sce = kn->kn_hook;
   2058 	struct ugen_softc *sc = sce->sc;
   2059 	int ret;
   2060 
   2061 	mutex_enter(&sc->sc_lock);
   2062 	if (sc->sc_dying) {
   2063 		ret = 0;
   2064 	} else if (sce->cur == sce->fill) {
   2065 		ret = 0;
   2066 	} else if (sce->cur < sce->fill) {
   2067 		kn->kn_data = sce->fill - sce->cur;
   2068 		ret = 1;
   2069 	} else {
   2070 		kn->kn_data = (sce->limit - sce->cur) +
   2071 		    (sce->fill - sce->ibuf);
   2072 		ret = 1;
   2073 	}
   2074 	mutex_exit(&sc->sc_lock);
   2075 
   2076 	return ret;
   2077 }
   2078 
   2079 static int
   2080 filt_ugenread_bulk(struct knote *kn, long hint)
   2081 {
   2082 	struct ugen_endpoint *sce = kn->kn_hook;
   2083 	struct ugen_softc *sc = sce->sc;
   2084 	int ret;
   2085 
   2086 	mutex_enter(&sc->sc_lock);
   2087 	if (sc->sc_dying) {
   2088 		ret = 0;
   2089 	} else if (!(sce->state & UGEN_BULK_RA)) {
   2090 		/*
   2091 		 * We have no easy way of determining if a read will
   2092 		 * yield any data or a write will happen.
   2093 		 * So, emulate "seltrue".
   2094 		 */
   2095 		ret = filt_seltrue(kn, hint);
   2096 	} else if (sce->ra_wb_used == 0) {
   2097 		ret = 0;
   2098 	} else {
   2099 		kn->kn_data = sce->ra_wb_used;
   2100 		ret = 1;
   2101 	}
   2102 	mutex_exit(&sc->sc_lock);
   2103 
   2104 	return ret;
   2105 }
   2106 
   2107 static int
   2108 filt_ugenwrite_bulk(struct knote *kn, long hint)
   2109 {
   2110 	struct ugen_endpoint *sce = kn->kn_hook;
   2111 	struct ugen_softc *sc = sce->sc;
   2112 	int ret;
   2113 
   2114 	mutex_enter(&sc->sc_lock);
   2115 	if (sc->sc_dying) {
   2116 		ret = 0;
   2117 	} else if (!(sce->state & UGEN_BULK_WB)) {
   2118 		/*
   2119 		 * We have no easy way of determining if a read will
   2120 		 * yield any data or a write will happen.
   2121 		 * So, emulate "seltrue".
   2122 		 */
   2123 		ret = filt_seltrue(kn, hint);
   2124 	} else if (sce->ra_wb_used == sce->limit - sce->ibuf) {
   2125 		ret = 0;
   2126 	} else {
   2127 		kn->kn_data = (sce->limit - sce->ibuf) - sce->ra_wb_used;
   2128 		ret = 1;
   2129 	}
   2130 	mutex_exit(&sc->sc_lock);
   2131 
   2132 	return ret;
   2133 }
   2134 
   2135 static const struct filterops ugenread_intr_filtops = {
   2136 	.f_isfd = 1,
   2137 	.f_attach = NULL,
   2138 	.f_detach = filt_ugenrdetach,
   2139 	.f_event = filt_ugenread_intr,
   2140 };
   2141 
   2142 static const struct filterops ugenread_isoc_filtops = {
   2143 	.f_isfd = 1,
   2144 	.f_attach = NULL,
   2145 	.f_detach = filt_ugenrdetach,
   2146 	.f_event = filt_ugenread_isoc,
   2147 };
   2148 
   2149 static const struct filterops ugenread_bulk_filtops = {
   2150 	.f_isfd = 1,
   2151 	.f_attach = NULL,
   2152 	.f_detach = filt_ugenrdetach,
   2153 	.f_event = filt_ugenread_bulk,
   2154 };
   2155 
   2156 static const struct filterops ugenwrite_bulk_filtops = {
   2157 	.f_isfd = 1,
   2158 	.f_attach = NULL,
   2159 	.f_detach = filt_ugenrdetach,
   2160 	.f_event = filt_ugenwrite_bulk,
   2161 };
   2162 
   2163 static int
   2164 ugenkqfilter(dev_t dev, struct knote *kn)
   2165 {
   2166 	struct ugen_softc *sc;
   2167 	struct ugen_endpoint *sce;
   2168 	struct klist *klist;
   2169 	int error;
   2170 
   2171 	if ((sc = ugenif_acquire(UGENUNIT(dev))) == NULL)
   2172 		return ENXIO;
   2173 
   2174 	if (UGENENDPOINT(dev) == USB_CONTROL_ENDPOINT) {
   2175 		error = ENODEV;
   2176 		goto out;
   2177 	}
   2178 
   2179 	switch (kn->kn_filter) {
   2180 	case EVFILT_READ:
   2181 		sce = &sc->sc_endpoints[UGENENDPOINT(dev)][IN];
   2182 		if (sce == NULL) {
   2183 			error = EINVAL;
   2184 			goto out;
   2185 		}
   2186 
   2187 		klist = &sce->rsel.sel_klist;
   2188 		switch (sce->edesc->bmAttributes & UE_XFERTYPE) {
   2189 		case UE_INTERRUPT:
   2190 			kn->kn_fop = &ugenread_intr_filtops;
   2191 			break;
   2192 		case UE_ISOCHRONOUS:
   2193 			kn->kn_fop = &ugenread_isoc_filtops;
   2194 			break;
   2195 		case UE_BULK:
   2196 			kn->kn_fop = &ugenread_bulk_filtops;
   2197 			break;
   2198 		default:
   2199 			error = EINVAL;
   2200 			goto out;
   2201 		}
   2202 		break;
   2203 
   2204 	case EVFILT_WRITE:
   2205 		sce = &sc->sc_endpoints[UGENENDPOINT(dev)][OUT];
   2206 		if (sce == NULL) {
   2207 			error = EINVAL;
   2208 			goto out;
   2209 		}
   2210 
   2211 		klist = &sce->rsel.sel_klist;
   2212 		switch (sce->edesc->bmAttributes & UE_XFERTYPE) {
   2213 		case UE_INTERRUPT:
   2214 		case UE_ISOCHRONOUS:
   2215 			/* XXX poll doesn't support this */
   2216 			error = EINVAL;
   2217 			goto out;
   2218 
   2219 		case UE_BULK:
   2220 			kn->kn_fop = &ugenwrite_bulk_filtops;
   2221 			break;
   2222 		default:
   2223 			error = EINVAL;
   2224 			goto out;
   2225 		}
   2226 		break;
   2227 
   2228 	default:
   2229 		error = EINVAL;
   2230 		goto out;
   2231 	}
   2232 
   2233 	kn->kn_hook = sce;
   2234 
   2235 	mutex_enter(&sc->sc_lock);
   2236 	SLIST_INSERT_HEAD(klist, kn, kn_selnext);
   2237 	mutex_exit(&sc->sc_lock);
   2238 
   2239 	error = 0;
   2240 
   2241 out:	ugenif_release(sc);
   2242 	return error;
   2243 }
   2244 
   2245 MODULE(MODULE_CLASS_DRIVER, ugen, NULL);
   2246 
   2247 static int
   2248 ugen_modcmd(modcmd_t cmd, void *aux)
   2249 {
   2250 
   2251 	switch (cmd) {
   2252 	case MODULE_CMD_INIT:
   2253 		mutex_init(&ugenif.lock, MUTEX_DEFAULT, IPL_NONE);
   2254 		rb_tree_init(&ugenif.tree, &ugenif_tree_ops);
   2255 		return 0;
   2256 	default:
   2257 		return ENOTTY;
   2258 	}
   2259 }
   2260