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