Home | History | Annotate | Line # | Download | only in usb
ugen.c revision 1.163
      1 /*	$NetBSD: ugen.c,v 1.163 2021/09/07 10:43:11 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.163 2021/09/07 10:43:11 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.  Causes processes waiting for transfer to wake. */
   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 			cv_signal(&sc->sc_endpoints[i][IN].cv);
   1223 		/* Wait for processes to go away. */
   1224 		if (cv_timedwait(&sc->sc_detach_cv, &sc->sc_lock, hz * 60))
   1225 			aprint_error_dev(self, ": didn't detach\n");
   1226 	}
   1227 	mutex_exit(&sc->sc_lock);
   1228 
   1229 	/* locate the major number */
   1230 	maj = cdevsw_lookup_major(&ugen_cdevsw);
   1231 
   1232 	/*
   1233 	 * Nuke the vnodes for any open instances (calls ugenclose, but
   1234 	 * with no effect because we already set sc_dying).
   1235 	 */
   1236 	mn = sc->sc_unit * USB_MAX_ENDPOINTS;
   1237 	vdevgone(maj, mn, mn + USB_MAX_ENDPOINTS - 1, VCHR);
   1238 
   1239 	/* Actually close any lingering pipes.  */
   1240 	for (i = 0; i < USB_MAX_ENDPOINTS; i++)
   1241 		ugen_do_close(sc, FREAD|FWRITE, i);
   1242 
   1243 	usbd_add_drv_event(USB_EVENT_DRIVER_DETACH, sc->sc_udev, sc->sc_dev);
   1244 	ugenif_put_unit(sc);
   1245 
   1246 out:	for (i = 0; i < USB_MAX_ENDPOINTS; i++) {
   1247 		for (dir = OUT; dir <= IN; dir++) {
   1248 			sce = &sc->sc_endpoints[i][dir];
   1249 			seldestroy(&sce->rsel);
   1250 			cv_destroy(&sce->cv);
   1251 		}
   1252 	}
   1253 
   1254 	cv_destroy(&sc->sc_detach_cv);
   1255 	mutex_destroy(&sc->sc_lock);
   1256 
   1257 	return 0;
   1258 }
   1259 
   1260 Static void
   1261 ugenintr(struct usbd_xfer *xfer, void *addr, usbd_status status)
   1262 {
   1263 	struct ugen_endpoint *sce = addr;
   1264 	struct ugen_softc *sc = sce->sc;
   1265 	uint32_t count;
   1266 	u_char *ibuf;
   1267 
   1268 	if (status == USBD_CANCELLED)
   1269 		return;
   1270 
   1271 	if (status != USBD_NORMAL_COMPLETION) {
   1272 		DPRINTF(("ugenintr: status=%d\n", status));
   1273 		if (status == USBD_STALLED)
   1274 		    usbd_clear_endpoint_stall_async(sce->pipeh);
   1275 		return;
   1276 	}
   1277 
   1278 	usbd_get_xfer_status(xfer, NULL, NULL, &count, NULL);
   1279 	ibuf = sce->ibuf;
   1280 
   1281 	DPRINTFN(5, ("ugenintr: xfer=%p status=%d count=%d\n",
   1282 		     xfer, status, count));
   1283 	DPRINTFN(5, ("          data = %02x %02x %02x\n",
   1284 		     ibuf[0], ibuf[1], ibuf[2]));
   1285 
   1286 	mutex_enter(&sc->sc_lock);
   1287 	(void)b_to_q(ibuf, count, &sce->q);
   1288 	cv_signal(&sce->cv);
   1289 	mutex_exit(&sc->sc_lock);
   1290 	selnotify(&sce->rsel, 0, 0);
   1291 }
   1292 
   1293 Static void
   1294 ugen_isoc_rintr(struct usbd_xfer *xfer, void *addr,
   1295 		usbd_status status)
   1296 {
   1297 	struct isoreq *req = addr;
   1298 	struct ugen_endpoint *sce = req->sce;
   1299 	struct ugen_softc *sc = sce->sc;
   1300 	uint32_t count, n;
   1301 	int i, isize;
   1302 
   1303 	/* Return if we are aborting. */
   1304 	if (status == USBD_CANCELLED)
   1305 		return;
   1306 
   1307 	usbd_get_xfer_status(xfer, NULL, NULL, &count, NULL);
   1308 	DPRINTFN(5,("ugen_isoc_rintr: xfer %ld, count=%d\n",
   1309 	    (long)(req - sce->isoreqs), count));
   1310 
   1311 	mutex_enter(&sc->sc_lock);
   1312 
   1313 	/* throw away oldest input if the buffer is full */
   1314 	if (sce->fill < sce->cur && sce->cur <= sce->fill + count) {
   1315 		sce->cur += count;
   1316 		if (sce->cur >= sce->limit)
   1317 			sce->cur = sce->ibuf + (sce->limit - sce->cur);
   1318 		DPRINTFN(5, ("ugen_isoc_rintr: throwing away %d bytes\n",
   1319 			     count));
   1320 	}
   1321 
   1322 	isize = UGETW(sce->edesc->wMaxPacketSize);
   1323 	for (i = 0; i < UGEN_NISORFRMS; i++) {
   1324 		uint32_t actlen = req->sizes[i];
   1325 		char const *tbuf = (char const *)req->dmabuf + isize * i;
   1326 
   1327 		/* copy data to buffer */
   1328 		while (actlen > 0) {
   1329 			n = uimin(actlen, sce->limit - sce->fill);
   1330 			memcpy(sce->fill, tbuf, n);
   1331 
   1332 			tbuf += n;
   1333 			actlen -= n;
   1334 			sce->fill += n;
   1335 			if (sce->fill == sce->limit)
   1336 				sce->fill = sce->ibuf;
   1337 		}
   1338 
   1339 		/* setup size for next transfer */
   1340 		req->sizes[i] = isize;
   1341 	}
   1342 
   1343 	usbd_setup_isoc_xfer(xfer, req, req->sizes, UGEN_NISORFRMS, 0,
   1344 	    ugen_isoc_rintr);
   1345 	(void)usbd_transfer(xfer);
   1346 
   1347 	cv_signal(&sce->cv);
   1348 	mutex_exit(&sc->sc_lock);
   1349 	selnotify(&sce->rsel, 0, 0);
   1350 }
   1351 
   1352 Static void
   1353 ugen_bulkra_intr(struct usbd_xfer *xfer, void *addr,
   1354 		 usbd_status status)
   1355 {
   1356 	struct ugen_endpoint *sce = addr;
   1357 	struct ugen_softc *sc = sce->sc;
   1358 	uint32_t count, n;
   1359 	char const *tbuf;
   1360 	usbd_status err;
   1361 
   1362 	/* Return if we are aborting. */
   1363 	if (status == USBD_CANCELLED)
   1364 		return;
   1365 
   1366 	if (status != USBD_NORMAL_COMPLETION) {
   1367 		DPRINTF(("ugen_bulkra_intr: status=%d\n", status));
   1368 		sce->state |= UGEN_RA_WB_STOP;
   1369 		if (status == USBD_STALLED)
   1370 		    usbd_clear_endpoint_stall_async(sce->pipeh);
   1371 		return;
   1372 	}
   1373 
   1374 	usbd_get_xfer_status(xfer, NULL, NULL, &count, NULL);
   1375 
   1376 	mutex_enter(&sc->sc_lock);
   1377 
   1378 	/* Keep track of how much is in the buffer. */
   1379 	sce->ra_wb_used += count;
   1380 
   1381 	/* Copy data to buffer. */
   1382 	tbuf = (char const *)usbd_get_buffer(sce->ra_wb_xfer);
   1383 	n = uimin(count, sce->limit - sce->fill);
   1384 	memcpy(sce->fill, tbuf, n);
   1385 	tbuf += n;
   1386 	count -= n;
   1387 	sce->fill += n;
   1388 	if (sce->fill == sce->limit)
   1389 		sce->fill = sce->ibuf;
   1390 	if (count > 0) {
   1391 		memcpy(sce->fill, tbuf, count);
   1392 		sce->fill += count;
   1393 	}
   1394 
   1395 	/* Set up the next request if necessary. */
   1396 	n = (sce->limit - sce->ibuf) - sce->ra_wb_used;
   1397 	if (n > 0) {
   1398 		usbd_setup_xfer(xfer, sce, NULL, uimin(n, sce->ra_wb_xferlen), 0,
   1399 		    USBD_NO_TIMEOUT, ugen_bulkra_intr);
   1400 		err = usbd_transfer(xfer);
   1401 		if (err != USBD_IN_PROGRESS) {
   1402 			printf("usbd_bulkra_intr: error=%d\n", err);
   1403 			/*
   1404 			 * The transfer has not been queued.  Setting STOP
   1405 			 * will make us try again at the next read.
   1406 			 */
   1407 			sce->state |= UGEN_RA_WB_STOP;
   1408 		}
   1409 	}
   1410 	else
   1411 		sce->state |= UGEN_RA_WB_STOP;
   1412 
   1413 	cv_signal(&sce->cv);
   1414 	mutex_exit(&sc->sc_lock);
   1415 	selnotify(&sce->rsel, 0, 0);
   1416 }
   1417 
   1418 Static void
   1419 ugen_bulkwb_intr(struct usbd_xfer *xfer, void *addr,
   1420 		 usbd_status status)
   1421 {
   1422 	struct ugen_endpoint *sce = addr;
   1423 	struct ugen_softc *sc = sce->sc;
   1424 	uint32_t count, n;
   1425 	char *tbuf;
   1426 	usbd_status err;
   1427 
   1428 	/* Return if we are aborting. */
   1429 	if (status == USBD_CANCELLED)
   1430 		return;
   1431 
   1432 	if (status != USBD_NORMAL_COMPLETION) {
   1433 		DPRINTF(("ugen_bulkwb_intr: status=%d\n", status));
   1434 		sce->state |= UGEN_RA_WB_STOP;
   1435 		if (status == USBD_STALLED)
   1436 		    usbd_clear_endpoint_stall_async(sce->pipeh);
   1437 		return;
   1438 	}
   1439 
   1440 	usbd_get_xfer_status(xfer, NULL, NULL, &count, NULL);
   1441 
   1442 	mutex_enter(&sc->sc_lock);
   1443 
   1444 	/* Keep track of how much is in the buffer. */
   1445 	sce->ra_wb_used -= count;
   1446 
   1447 	/* Update buffer pointers. */
   1448 	sce->cur += count;
   1449 	if (sce->cur >= sce->limit)
   1450 		sce->cur = sce->ibuf + (sce->cur - sce->limit);
   1451 
   1452 	/* Set up next request if necessary. */
   1453 	if (sce->ra_wb_used > 0) {
   1454 		/* copy data from buffer */
   1455 		tbuf = (char *)usbd_get_buffer(sce->ra_wb_xfer);
   1456 		count = uimin(sce->ra_wb_used, sce->ra_wb_xferlen);
   1457 		n = uimin(count, sce->limit - sce->cur);
   1458 		memcpy(tbuf, sce->cur, n);
   1459 		tbuf += n;
   1460 		if (count - n > 0)
   1461 			memcpy(tbuf, sce->ibuf, count - n);
   1462 
   1463 		usbd_setup_xfer(xfer, sce, NULL, count, 0, USBD_NO_TIMEOUT,
   1464 		    ugen_bulkwb_intr);
   1465 		err = usbd_transfer(xfer);
   1466 		if (err != USBD_IN_PROGRESS) {
   1467 			printf("usbd_bulkwb_intr: error=%d\n", err);
   1468 			/*
   1469 			 * The transfer has not been queued.  Setting STOP
   1470 			 * will make us try again at the next write.
   1471 			 */
   1472 			sce->state |= UGEN_RA_WB_STOP;
   1473 		}
   1474 	}
   1475 	else
   1476 		sce->state |= UGEN_RA_WB_STOP;
   1477 
   1478 	cv_signal(&sce->cv);
   1479 	mutex_exit(&sc->sc_lock);
   1480 	selnotify(&sce->rsel, 0, 0);
   1481 }
   1482 
   1483 Static usbd_status
   1484 ugen_set_interface(struct ugen_softc *sc, int ifaceidx, int altno)
   1485 {
   1486 	struct usbd_interface *iface;
   1487 	usb_endpoint_descriptor_t *ed;
   1488 	usbd_status err;
   1489 	struct ugen_endpoint *sce;
   1490 	uint8_t niface, nendpt, endptno, endpt;
   1491 	int dir;
   1492 
   1493 	DPRINTFN(15, ("ugen_set_interface %d %d\n", ifaceidx, altno));
   1494 
   1495 	err = usbd_interface_count(sc->sc_udev, &niface);
   1496 	if (err)
   1497 		return err;
   1498 	if (ifaceidx < 0 || ifaceidx >= niface)
   1499 		return USBD_INVAL;
   1500 
   1501 	err = usbd_device2interface_handle(sc->sc_udev, ifaceidx, &iface);
   1502 	if (err)
   1503 		return err;
   1504 	err = usbd_endpoint_count(iface, &nendpt);
   1505 	if (err)
   1506 		return err;
   1507 
   1508 	/* change setting */
   1509 	err = usbd_set_interface(iface, altno);
   1510 	if (err)
   1511 		return err;
   1512 
   1513 	err = usbd_endpoint_count(iface, &nendpt);
   1514 	if (err)
   1515 		return err;
   1516 
   1517 	ugen_clear_endpoints(sc);
   1518 
   1519 	for (endptno = 0; endptno < nendpt; endptno++) {
   1520 		ed = usbd_interface2endpoint_descriptor(iface,endptno);
   1521 		KASSERT(ed != NULL);
   1522 		endpt = ed->bEndpointAddress;
   1523 		dir = UE_GET_DIR(endpt) == UE_DIR_IN ? IN : OUT;
   1524 		sce = &sc->sc_endpoints[UE_GET_ADDR(endpt)][dir];
   1525 		sce->sc = sc;
   1526 		sce->edesc = ed;
   1527 		sce->iface = iface;
   1528 	}
   1529 	return 0;
   1530 }
   1531 
   1532 /* Retrieve a complete descriptor for a certain device and index. */
   1533 Static usb_config_descriptor_t *
   1534 ugen_get_cdesc(struct ugen_softc *sc, int index, int *lenp)
   1535 {
   1536 	usb_config_descriptor_t *cdesc, *tdesc, cdescr;
   1537 	int len;
   1538 	usbd_status err;
   1539 
   1540 	if (index == USB_CURRENT_CONFIG_INDEX) {
   1541 		tdesc = usbd_get_config_descriptor(sc->sc_udev);
   1542 		if (tdesc == NULL)
   1543 			return NULL;
   1544 		len = UGETW(tdesc->wTotalLength);
   1545 		if (lenp)
   1546 			*lenp = len;
   1547 		cdesc = kmem_alloc(len, KM_SLEEP);
   1548 		memcpy(cdesc, tdesc, len);
   1549 		DPRINTFN(5,("ugen_get_cdesc: current, len=%d\n", len));
   1550 	} else {
   1551 		err = usbd_get_config_desc(sc->sc_udev, index, &cdescr);
   1552 		if (err)
   1553 			return 0;
   1554 		len = UGETW(cdescr.wTotalLength);
   1555 		DPRINTFN(5,("ugen_get_cdesc: index=%d, len=%d\n", index, len));
   1556 		if (lenp)
   1557 			*lenp = len;
   1558 		cdesc = kmem_alloc(len, KM_SLEEP);
   1559 		err = usbd_get_config_desc_full(sc->sc_udev, index, cdesc, len);
   1560 		if (err) {
   1561 			kmem_free(cdesc, len);
   1562 			return 0;
   1563 		}
   1564 	}
   1565 	return cdesc;
   1566 }
   1567 
   1568 Static int
   1569 ugen_get_alt_index(struct ugen_softc *sc, int ifaceidx)
   1570 {
   1571 	struct usbd_interface *iface;
   1572 	usbd_status err;
   1573 
   1574 	err = usbd_device2interface_handle(sc->sc_udev, ifaceidx, &iface);
   1575 	if (err)
   1576 		return -1;
   1577 	return usbd_get_interface_altindex(iface);
   1578 }
   1579 
   1580 Static int
   1581 ugen_do_ioctl(struct ugen_softc *sc, int endpt, u_long cmd,
   1582 	      void *addr, int flag, struct lwp *l)
   1583 {
   1584 	struct ugen_endpoint *sce;
   1585 	usbd_status err;
   1586 	struct usbd_interface *iface;
   1587 	struct usb_config_desc *cd;
   1588 	usb_config_descriptor_t *cdesc;
   1589 	struct usb_interface_desc *id;
   1590 	usb_interface_descriptor_t *idesc;
   1591 	struct usb_endpoint_desc *ed;
   1592 	usb_endpoint_descriptor_t *edesc;
   1593 	struct usb_alt_interface *ai;
   1594 	struct usb_string_desc *si;
   1595 	uint8_t conf, alt;
   1596 	int cdesclen;
   1597 	int error;
   1598 	int dir;
   1599 
   1600 	KASSERT(KERNEL_LOCKED_P()); /* ugen_set_config */
   1601 
   1602 	DPRINTFN(5, ("ugenioctl: cmd=%08lx\n", cmd));
   1603 
   1604 	switch (cmd) {
   1605 	case FIONBIO:
   1606 		/* All handled in the upper FS layer. */
   1607 		return 0;
   1608 	case USB_SET_SHORT_XFER:
   1609 		if (endpt == USB_CONTROL_ENDPOINT)
   1610 			return EINVAL;
   1611 		/* This flag only affects read */
   1612 		sce = &sc->sc_endpoints[endpt][IN];
   1613 		if (sce == NULL || sce->pipeh == NULL)
   1614 			return EINVAL;
   1615 		if (*(int *)addr)
   1616 			sce->state |= UGEN_SHORT_OK;
   1617 		else
   1618 			sce->state &= ~UGEN_SHORT_OK;
   1619 		return 0;
   1620 	case USB_SET_TIMEOUT:
   1621 		for (dir = OUT; dir <= IN; dir++) {
   1622 			sce = &sc->sc_endpoints[endpt][dir];
   1623 			if (sce == NULL)
   1624 				return EINVAL;
   1625 
   1626 			sce->timeout = *(int *)addr;
   1627 		}
   1628 		return 0;
   1629 	case USB_SET_BULK_RA:
   1630 		if (endpt == USB_CONTROL_ENDPOINT)
   1631 			return EINVAL;
   1632 		sce = &sc->sc_endpoints[endpt][IN];
   1633 		if (sce == NULL || sce->pipeh == NULL)
   1634 			return EINVAL;
   1635 		edesc = sce->edesc;
   1636 		if ((edesc->bmAttributes & UE_XFERTYPE) != UE_BULK)
   1637 			return EINVAL;
   1638 
   1639 		if (*(int *)addr) {
   1640 			/* Only turn RA on if it's currently off. */
   1641 			if (sce->state & UGEN_BULK_RA)
   1642 				return 0;
   1643 
   1644 			if (sce->ra_wb_bufsize == 0 || sce->ra_wb_reqsize == 0)
   1645 				/* shouldn't happen */
   1646 				return EINVAL;
   1647 			error = usbd_create_xfer(sce->pipeh,
   1648 			    sce->ra_wb_reqsize, 0, 0, &sce->ra_wb_xfer);
   1649 			if (error)
   1650 				return error;
   1651 			sce->ra_wb_xferlen = sce->ra_wb_reqsize;
   1652 			sce->ibuf = kmem_alloc(sce->ra_wb_bufsize, KM_SLEEP);
   1653 			sce->fill = sce->cur = sce->ibuf;
   1654 			sce->limit = sce->ibuf + sce->ra_wb_bufsize;
   1655 			sce->ra_wb_used = 0;
   1656 			sce->state |= UGEN_BULK_RA;
   1657 			sce->state &= ~UGEN_RA_WB_STOP;
   1658 			/* Now start reading. */
   1659 			usbd_setup_xfer(sce->ra_wb_xfer, sce, NULL,
   1660 			    uimin(sce->ra_wb_xferlen, sce->ra_wb_bufsize),
   1661 			     0, USBD_NO_TIMEOUT, ugen_bulkra_intr);
   1662 			err = usbd_transfer(sce->ra_wb_xfer);
   1663 			if (err != USBD_IN_PROGRESS) {
   1664 				sce->state &= ~UGEN_BULK_RA;
   1665 				kmem_free(sce->ibuf, sce->ra_wb_bufsize);
   1666 				sce->ibuf = NULL;
   1667 				usbd_destroy_xfer(sce->ra_wb_xfer);
   1668 				return EIO;
   1669 			}
   1670 		} else {
   1671 			/* Only turn RA off if it's currently on. */
   1672 			if (!(sce->state & UGEN_BULK_RA))
   1673 				return 0;
   1674 
   1675 			sce->state &= ~UGEN_BULK_RA;
   1676 			usbd_abort_pipe(sce->pipeh);
   1677 			usbd_destroy_xfer(sce->ra_wb_xfer);
   1678 			/*
   1679 			 * XXX Discard whatever's in the buffer, but we
   1680 			 * should keep it around and drain the buffer
   1681 			 * instead.
   1682 			 */
   1683 			kmem_free(sce->ibuf, sce->ra_wb_bufsize);
   1684 			sce->ibuf = NULL;
   1685 		}
   1686 		return 0;
   1687 	case USB_SET_BULK_WB:
   1688 		if (endpt == USB_CONTROL_ENDPOINT)
   1689 			return EINVAL;
   1690 		sce = &sc->sc_endpoints[endpt][OUT];
   1691 		if (sce == NULL || sce->pipeh == NULL)
   1692 			return EINVAL;
   1693 		edesc = sce->edesc;
   1694 		if ((edesc->bmAttributes & UE_XFERTYPE) != UE_BULK)
   1695 			return EINVAL;
   1696 
   1697 		if (*(int *)addr) {
   1698 			/* Only turn WB on if it's currently off. */
   1699 			if (sce->state & UGEN_BULK_WB)
   1700 				return 0;
   1701 
   1702 			if (sce->ra_wb_bufsize == 0 || sce->ra_wb_reqsize == 0)
   1703 				/* shouldn't happen */
   1704 				return EINVAL;
   1705 			error = usbd_create_xfer(sce->pipeh, sce->ra_wb_reqsize,
   1706 			    0, 0, &sce->ra_wb_xfer);
   1707 			sce->ra_wb_xferlen = sce->ra_wb_reqsize;
   1708 			sce->ibuf = kmem_alloc(sce->ra_wb_bufsize, KM_SLEEP);
   1709 			sce->fill = sce->cur = sce->ibuf;
   1710 			sce->limit = sce->ibuf + sce->ra_wb_bufsize;
   1711 			sce->ra_wb_used = 0;
   1712 			sce->state |= UGEN_BULK_WB | UGEN_RA_WB_STOP;
   1713 		} else {
   1714 			/* Only turn WB off if it's currently on. */
   1715 			if (!(sce->state & UGEN_BULK_WB))
   1716 				return 0;
   1717 
   1718 			sce->state &= ~UGEN_BULK_WB;
   1719 			/*
   1720 			 * XXX Discard whatever's in the buffer, but we
   1721 			 * should keep it around and keep writing to
   1722 			 * drain the buffer instead.
   1723 			 */
   1724 			usbd_abort_pipe(sce->pipeh);
   1725 			usbd_destroy_xfer(sce->ra_wb_xfer);
   1726 			kmem_free(sce->ibuf, sce->ra_wb_bufsize);
   1727 			sce->ibuf = NULL;
   1728 		}
   1729 		return 0;
   1730 	case USB_SET_BULK_RA_OPT:
   1731 	case USB_SET_BULK_WB_OPT:
   1732 	{
   1733 		struct usb_bulk_ra_wb_opt *opt;
   1734 
   1735 		if (endpt == USB_CONTROL_ENDPOINT)
   1736 			return EINVAL;
   1737 		opt = (struct usb_bulk_ra_wb_opt *)addr;
   1738 		if (cmd == USB_SET_BULK_RA_OPT)
   1739 			sce = &sc->sc_endpoints[endpt][IN];
   1740 		else
   1741 			sce = &sc->sc_endpoints[endpt][OUT];
   1742 		if (sce == NULL || sce->pipeh == NULL)
   1743 			return EINVAL;
   1744 		if (opt->ra_wb_buffer_size < 1 ||
   1745 		    opt->ra_wb_buffer_size > UGEN_BULK_RA_WB_BUFMAX ||
   1746 		    opt->ra_wb_request_size < 1 ||
   1747 		    opt->ra_wb_request_size > opt->ra_wb_buffer_size)
   1748 			return EINVAL;
   1749 		/*
   1750 		 * XXX These changes do not take effect until the
   1751 		 * next time RA/WB mode is enabled but they ought to
   1752 		 * take effect immediately.
   1753 		 */
   1754 		sce->ra_wb_bufsize = opt->ra_wb_buffer_size;
   1755 		sce->ra_wb_reqsize = opt->ra_wb_request_size;
   1756 		return 0;
   1757 	}
   1758 	default:
   1759 		break;
   1760 	}
   1761 
   1762 	if (endpt != USB_CONTROL_ENDPOINT)
   1763 		return EINVAL;
   1764 
   1765 	switch (cmd) {
   1766 #ifdef UGEN_DEBUG
   1767 	case USB_SETDEBUG:
   1768 		ugendebug = *(int *)addr;
   1769 		break;
   1770 #endif
   1771 	case USB_GET_CONFIG:
   1772 		err = usbd_get_config(sc->sc_udev, &conf);
   1773 		if (err)
   1774 			return EIO;
   1775 		*(int *)addr = conf;
   1776 		break;
   1777 	case USB_SET_CONFIG:
   1778 		if (!(flag & FWRITE))
   1779 			return EPERM;
   1780 		err = ugen_set_config(sc, *(int *)addr, 1);
   1781 		switch (err) {
   1782 		case USBD_NORMAL_COMPLETION:
   1783 			break;
   1784 		case USBD_IN_USE:
   1785 			return EBUSY;
   1786 		default:
   1787 			return EIO;
   1788 		}
   1789 		break;
   1790 	case USB_GET_ALTINTERFACE:
   1791 		ai = (struct usb_alt_interface *)addr;
   1792 		err = usbd_device2interface_handle(sc->sc_udev,
   1793 			  ai->uai_interface_index, &iface);
   1794 		if (err)
   1795 			return EINVAL;
   1796 		idesc = usbd_get_interface_descriptor(iface);
   1797 		if (idesc == NULL)
   1798 			return EIO;
   1799 		ai->uai_alt_no = idesc->bAlternateSetting;
   1800 		break;
   1801 	case USB_SET_ALTINTERFACE:
   1802 		if (!(flag & FWRITE))
   1803 			return EPERM;
   1804 		ai = (struct usb_alt_interface *)addr;
   1805 		err = usbd_device2interface_handle(sc->sc_udev,
   1806 			  ai->uai_interface_index, &iface);
   1807 		if (err)
   1808 			return EINVAL;
   1809 		err = ugen_set_interface(sc, ai->uai_interface_index,
   1810 		    ai->uai_alt_no);
   1811 		if (err)
   1812 			return EINVAL;
   1813 		break;
   1814 	case USB_GET_NO_ALT:
   1815 		ai = (struct usb_alt_interface *)addr;
   1816 		cdesc = ugen_get_cdesc(sc, ai->uai_config_index, &cdesclen);
   1817 		if (cdesc == NULL)
   1818 			return EINVAL;
   1819 		idesc = usbd_find_idesc(cdesc, ai->uai_interface_index, 0);
   1820 		if (idesc == NULL) {
   1821 			kmem_free(cdesc, cdesclen);
   1822 			return EINVAL;
   1823 		}
   1824 		ai->uai_alt_no = usbd_get_no_alts(cdesc,
   1825 		    idesc->bInterfaceNumber);
   1826 		kmem_free(cdesc, cdesclen);
   1827 		break;
   1828 	case USB_GET_DEVICE_DESC:
   1829 		*(usb_device_descriptor_t *)addr =
   1830 			*usbd_get_device_descriptor(sc->sc_udev);
   1831 		break;
   1832 	case USB_GET_CONFIG_DESC:
   1833 		cd = (struct usb_config_desc *)addr;
   1834 		cdesc = ugen_get_cdesc(sc, cd->ucd_config_index, &cdesclen);
   1835 		if (cdesc == NULL)
   1836 			return EINVAL;
   1837 		cd->ucd_desc = *cdesc;
   1838 		kmem_free(cdesc, cdesclen);
   1839 		break;
   1840 	case USB_GET_INTERFACE_DESC:
   1841 		id = (struct usb_interface_desc *)addr;
   1842 		cdesc = ugen_get_cdesc(sc, id->uid_config_index, &cdesclen);
   1843 		if (cdesc == NULL)
   1844 			return EINVAL;
   1845 		if (id->uid_config_index == USB_CURRENT_CONFIG_INDEX &&
   1846 		    id->uid_alt_index == USB_CURRENT_ALT_INDEX)
   1847 			alt = ugen_get_alt_index(sc, id->uid_interface_index);
   1848 		else
   1849 			alt = id->uid_alt_index;
   1850 		idesc = usbd_find_idesc(cdesc, id->uid_interface_index, alt);
   1851 		if (idesc == NULL) {
   1852 			kmem_free(cdesc, cdesclen);
   1853 			return EINVAL;
   1854 		}
   1855 		id->uid_desc = *idesc;
   1856 		kmem_free(cdesc, cdesclen);
   1857 		break;
   1858 	case USB_GET_ENDPOINT_DESC:
   1859 		ed = (struct usb_endpoint_desc *)addr;
   1860 		cdesc = ugen_get_cdesc(sc, ed->ued_config_index, &cdesclen);
   1861 		if (cdesc == NULL)
   1862 			return EINVAL;
   1863 		if (ed->ued_config_index == USB_CURRENT_CONFIG_INDEX &&
   1864 		    ed->ued_alt_index == USB_CURRENT_ALT_INDEX)
   1865 			alt = ugen_get_alt_index(sc, ed->ued_interface_index);
   1866 		else
   1867 			alt = ed->ued_alt_index;
   1868 		edesc = usbd_find_edesc(cdesc, ed->ued_interface_index,
   1869 					alt, ed->ued_endpoint_index);
   1870 		if (edesc == NULL) {
   1871 			kmem_free(cdesc, cdesclen);
   1872 			return EINVAL;
   1873 		}
   1874 		ed->ued_desc = *edesc;
   1875 		kmem_free(cdesc, cdesclen);
   1876 		break;
   1877 	case USB_GET_FULL_DESC:
   1878 	{
   1879 		int len;
   1880 		struct iovec iov;
   1881 		struct uio uio;
   1882 		struct usb_full_desc *fd = (struct usb_full_desc *)addr;
   1883 
   1884 		cdesc = ugen_get_cdesc(sc, fd->ufd_config_index, &cdesclen);
   1885 		if (cdesc == NULL)
   1886 			return EINVAL;
   1887 		len = cdesclen;
   1888 		if (len > fd->ufd_size)
   1889 			len = fd->ufd_size;
   1890 		iov.iov_base = (void *)fd->ufd_data;
   1891 		iov.iov_len = len;
   1892 		uio.uio_iov = &iov;
   1893 		uio.uio_iovcnt = 1;
   1894 		uio.uio_resid = len;
   1895 		uio.uio_offset = 0;
   1896 		uio.uio_rw = UIO_READ;
   1897 		uio.uio_vmspace = l->l_proc->p_vmspace;
   1898 		error = uiomove((void *)cdesc, len, &uio);
   1899 		kmem_free(cdesc, cdesclen);
   1900 		return error;
   1901 	}
   1902 	case USB_GET_STRING_DESC: {
   1903 		int len;
   1904 		si = (struct usb_string_desc *)addr;
   1905 		err = usbd_get_string_desc(sc->sc_udev, si->usd_string_index,
   1906 			  si->usd_language_id, &si->usd_desc, &len);
   1907 		if (err)
   1908 			return EINVAL;
   1909 		break;
   1910 	}
   1911 	case USB_DO_REQUEST:
   1912 	{
   1913 		struct usb_ctl_request *ur = (void *)addr;
   1914 		int len = UGETW(ur->ucr_request.wLength);
   1915 		struct iovec iov;
   1916 		struct uio uio;
   1917 		void *ptr = 0;
   1918 		usbd_status xerr;
   1919 
   1920 		error = 0;
   1921 
   1922 		if (!(flag & FWRITE))
   1923 			return EPERM;
   1924 		/* Avoid requests that would damage the bus integrity. */
   1925 		if ((ur->ucr_request.bmRequestType == UT_WRITE_DEVICE &&
   1926 		     ur->ucr_request.bRequest == UR_SET_ADDRESS) ||
   1927 		    (ur->ucr_request.bmRequestType == UT_WRITE_DEVICE &&
   1928 		     ur->ucr_request.bRequest == UR_SET_CONFIG) ||
   1929 		    (ur->ucr_request.bmRequestType == UT_WRITE_INTERFACE &&
   1930 		     ur->ucr_request.bRequest == UR_SET_INTERFACE))
   1931 			return EINVAL;
   1932 
   1933 		if (len < 0 || len > 32767)
   1934 			return EINVAL;
   1935 		if (len != 0) {
   1936 			iov.iov_base = (void *)ur->ucr_data;
   1937 			iov.iov_len = len;
   1938 			uio.uio_iov = &iov;
   1939 			uio.uio_iovcnt = 1;
   1940 			uio.uio_resid = len;
   1941 			uio.uio_offset = 0;
   1942 			uio.uio_rw =
   1943 				ur->ucr_request.bmRequestType & UT_READ ?
   1944 				UIO_READ : UIO_WRITE;
   1945 			uio.uio_vmspace = l->l_proc->p_vmspace;
   1946 			ptr = kmem_alloc(len, KM_SLEEP);
   1947 			if (uio.uio_rw == UIO_WRITE) {
   1948 				error = uiomove(ptr, len, &uio);
   1949 				if (error)
   1950 					goto ret;
   1951 			}
   1952 		}
   1953 		sce = &sc->sc_endpoints[endpt][IN];
   1954 		xerr = usbd_do_request_flags(sc->sc_udev, &ur->ucr_request,
   1955 			  ptr, ur->ucr_flags, &ur->ucr_actlen, sce->timeout);
   1956 		if (xerr) {
   1957 			error = EIO;
   1958 			goto ret;
   1959 		}
   1960 		if (len != 0) {
   1961 			if (uio.uio_rw == UIO_READ) {
   1962 				size_t alen = uimin(len, ur->ucr_actlen);
   1963 				error = uiomove(ptr, alen, &uio);
   1964 				if (error)
   1965 					goto ret;
   1966 			}
   1967 		}
   1968 	ret:
   1969 		if (ptr)
   1970 			kmem_free(ptr, len);
   1971 		return error;
   1972 	}
   1973 	case USB_GET_DEVICEINFO:
   1974 		usbd_fill_deviceinfo(sc->sc_udev,
   1975 				     (struct usb_device_info *)addr, 0);
   1976 		break;
   1977 	case USB_GET_DEVICEINFO_OLD:
   1978 	{
   1979 		int ret;
   1980 		MODULE_HOOK_CALL(usb_subr_fill_30_hook,
   1981 		    (sc->sc_udev, (struct usb_device_info_old *)addr, 0,
   1982 		      usbd_devinfo_vp, usbd_printBCD),
   1983 		    enosys(), ret);
   1984 		if (ret == 0)
   1985 			return 0;
   1986 		return EINVAL;
   1987 	}
   1988 	default:
   1989 		return EINVAL;
   1990 	}
   1991 	return 0;
   1992 }
   1993 
   1994 static int
   1995 ugenioctl(dev_t dev, u_long cmd, void *addr, int flag, struct lwp *l)
   1996 {
   1997 	int endpt = UGENENDPOINT(dev);
   1998 	struct ugen_softc *sc;
   1999 	int error;
   2000 
   2001 	if ((sc = ugenif_acquire(UGENUNIT(dev))) == 0)
   2002 		return ENXIO;
   2003 	error = ugen_do_ioctl(sc, endpt, cmd, addr, flag, l);
   2004 	ugenif_release(sc);
   2005 
   2006 	return error;
   2007 }
   2008 
   2009 static int
   2010 ugenpoll(dev_t dev, int events, struct lwp *l)
   2011 {
   2012 	struct ugen_softc *sc;
   2013 	struct ugen_endpoint *sce_in, *sce_out;
   2014 	int revents = 0;
   2015 
   2016 	if ((sc = ugenif_acquire(UGENUNIT(dev))) == NULL)
   2017 		return POLLHUP;
   2018 
   2019 	if (UGENENDPOINT(dev) == USB_CONTROL_ENDPOINT) {
   2020 		revents |= POLLERR;
   2021 		goto out;
   2022 	}
   2023 
   2024 	sce_in = &sc->sc_endpoints[UGENENDPOINT(dev)][IN];
   2025 	sce_out = &sc->sc_endpoints[UGENENDPOINT(dev)][OUT];
   2026 	KASSERT(sce_in->edesc || sce_out->edesc);
   2027 	KASSERT(sce_in->pipeh || sce_out->pipeh);
   2028 
   2029 	mutex_enter(&sc->sc_lock);
   2030 	if (sce_in && sce_in->pipeh && (events & (POLLIN | POLLRDNORM)))
   2031 		switch (sce_in->edesc->bmAttributes & UE_XFERTYPE) {
   2032 		case UE_INTERRUPT:
   2033 			if (sce_in->q.c_cc > 0)
   2034 				revents |= events & (POLLIN | POLLRDNORM);
   2035 			else
   2036 				selrecord(l, &sce_in->rsel);
   2037 			break;
   2038 		case UE_ISOCHRONOUS:
   2039 			if (sce_in->cur != sce_in->fill)
   2040 				revents |= events & (POLLIN | POLLRDNORM);
   2041 			else
   2042 				selrecord(l, &sce_in->rsel);
   2043 			break;
   2044 		case UE_BULK:
   2045 			if (sce_in->state & UGEN_BULK_RA) {
   2046 				if (sce_in->ra_wb_used > 0)
   2047 					revents |= events &
   2048 					    (POLLIN | POLLRDNORM);
   2049 				else
   2050 					selrecord(l, &sce_in->rsel);
   2051 				break;
   2052 			}
   2053 			/*
   2054 			 * We have no easy way of determining if a read will
   2055 			 * yield any data or a write will happen.
   2056 			 * Pretend they will.
   2057 			 */
   2058 			revents |= events & (POLLIN | POLLRDNORM);
   2059 			break;
   2060 		default:
   2061 			break;
   2062 		}
   2063 	if (sce_out && sce_out->pipeh && (events & (POLLOUT | POLLWRNORM)))
   2064 		switch (sce_out->edesc->bmAttributes & UE_XFERTYPE) {
   2065 		case UE_INTERRUPT:
   2066 		case UE_ISOCHRONOUS:
   2067 			/* XXX unimplemented */
   2068 			break;
   2069 		case UE_BULK:
   2070 			if (sce_out->state & UGEN_BULK_WB) {
   2071 				if (sce_out->ra_wb_used <
   2072 				    sce_out->limit - sce_out->ibuf)
   2073 					revents |= events &
   2074 					    (POLLOUT | POLLWRNORM);
   2075 				else
   2076 					selrecord(l, &sce_out->rsel);
   2077 				break;
   2078 			}
   2079 			/*
   2080 			 * We have no easy way of determining if a read will
   2081 			 * yield any data or a write will happen.
   2082 			 * Pretend they will.
   2083 			 */
   2084 			 revents |= events & (POLLOUT | POLLWRNORM);
   2085 			 break;
   2086 		default:
   2087 			break;
   2088 		}
   2089 
   2090 	mutex_exit(&sc->sc_lock);
   2091 
   2092 out:	ugenif_release(sc);
   2093 	return revents;
   2094 }
   2095 
   2096 static void
   2097 filt_ugenrdetach(struct knote *kn)
   2098 {
   2099 	struct ugen_endpoint *sce = kn->kn_hook;
   2100 	struct ugen_softc *sc = sce->sc;
   2101 
   2102 	mutex_enter(&sc->sc_lock);
   2103 	selremove_knote(&sce->rsel, kn);
   2104 	mutex_exit(&sc->sc_lock);
   2105 }
   2106 
   2107 static int
   2108 filt_ugenread_intr(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 {
   2118 		kn->kn_data = sce->q.c_cc;
   2119 		ret = kn->kn_data > 0;
   2120 	}
   2121 	mutex_exit(&sc->sc_lock);
   2122 
   2123 	return ret;
   2124 }
   2125 
   2126 static int
   2127 filt_ugenread_isoc(struct knote *kn, long hint)
   2128 {
   2129 	struct ugen_endpoint *sce = kn->kn_hook;
   2130 	struct ugen_softc *sc = sce->sc;
   2131 	int ret;
   2132 
   2133 	mutex_enter(&sc->sc_lock);
   2134 	if (sc->sc_dying) {
   2135 		ret = 0;
   2136 	} else if (sce->cur == sce->fill) {
   2137 		ret = 0;
   2138 	} else if (sce->cur < sce->fill) {
   2139 		kn->kn_data = sce->fill - sce->cur;
   2140 		ret = 1;
   2141 	} else {
   2142 		kn->kn_data = (sce->limit - sce->cur) +
   2143 		    (sce->fill - sce->ibuf);
   2144 		ret = 1;
   2145 	}
   2146 	mutex_exit(&sc->sc_lock);
   2147 
   2148 	return ret;
   2149 }
   2150 
   2151 static int
   2152 filt_ugenread_bulk(struct knote *kn, long hint)
   2153 {
   2154 	struct ugen_endpoint *sce = kn->kn_hook;
   2155 	struct ugen_softc *sc = sce->sc;
   2156 	int ret;
   2157 
   2158 	mutex_enter(&sc->sc_lock);
   2159 	if (sc->sc_dying) {
   2160 		ret = 0;
   2161 	} else if (!(sce->state & UGEN_BULK_RA)) {
   2162 		/*
   2163 		 * We have no easy way of determining if a read will
   2164 		 * yield any data or a write will happen.
   2165 		 * So, emulate "seltrue".
   2166 		 */
   2167 		ret = filt_seltrue(kn, hint);
   2168 	} else if (sce->ra_wb_used == 0) {
   2169 		ret = 0;
   2170 	} else {
   2171 		kn->kn_data = sce->ra_wb_used;
   2172 		ret = 1;
   2173 	}
   2174 	mutex_exit(&sc->sc_lock);
   2175 
   2176 	return ret;
   2177 }
   2178 
   2179 static int
   2180 filt_ugenwrite_bulk(struct knote *kn, long hint)
   2181 {
   2182 	struct ugen_endpoint *sce = kn->kn_hook;
   2183 	struct ugen_softc *sc = sce->sc;
   2184 	int ret;
   2185 
   2186 	mutex_enter(&sc->sc_lock);
   2187 	if (sc->sc_dying) {
   2188 		ret = 0;
   2189 	} else if (!(sce->state & UGEN_BULK_WB)) {
   2190 		/*
   2191 		 * We have no easy way of determining if a read will
   2192 		 * yield any data or a write will happen.
   2193 		 * So, emulate "seltrue".
   2194 		 */
   2195 		ret = filt_seltrue(kn, hint);
   2196 	} else if (sce->ra_wb_used == sce->limit - sce->ibuf) {
   2197 		ret = 0;
   2198 	} else {
   2199 		kn->kn_data = (sce->limit - sce->ibuf) - sce->ra_wb_used;
   2200 		ret = 1;
   2201 	}
   2202 	mutex_exit(&sc->sc_lock);
   2203 
   2204 	return ret;
   2205 }
   2206 
   2207 static const struct filterops ugenread_intr_filtops = {
   2208 	.f_isfd = 1,
   2209 	.f_attach = NULL,
   2210 	.f_detach = filt_ugenrdetach,
   2211 	.f_event = filt_ugenread_intr,
   2212 };
   2213 
   2214 static const struct filterops ugenread_isoc_filtops = {
   2215 	.f_isfd = 1,
   2216 	.f_attach = NULL,
   2217 	.f_detach = filt_ugenrdetach,
   2218 	.f_event = filt_ugenread_isoc,
   2219 };
   2220 
   2221 static const struct filterops ugenread_bulk_filtops = {
   2222 	.f_isfd = 1,
   2223 	.f_attach = NULL,
   2224 	.f_detach = filt_ugenrdetach,
   2225 	.f_event = filt_ugenread_bulk,
   2226 };
   2227 
   2228 static const struct filterops ugenwrite_bulk_filtops = {
   2229 	.f_isfd = 1,
   2230 	.f_attach = NULL,
   2231 	.f_detach = filt_ugenrdetach,
   2232 	.f_event = filt_ugenwrite_bulk,
   2233 };
   2234 
   2235 static int
   2236 ugenkqfilter(dev_t dev, struct knote *kn)
   2237 {
   2238 	struct ugen_softc *sc;
   2239 	struct ugen_endpoint *sce;
   2240 	struct selinfo *sip;
   2241 	int error;
   2242 
   2243 	if ((sc = ugenif_acquire(UGENUNIT(dev))) == NULL)
   2244 		return ENXIO;
   2245 
   2246 	if (UGENENDPOINT(dev) == USB_CONTROL_ENDPOINT) {
   2247 		error = ENODEV;
   2248 		goto out;
   2249 	}
   2250 
   2251 	switch (kn->kn_filter) {
   2252 	case EVFILT_READ:
   2253 		sce = &sc->sc_endpoints[UGENENDPOINT(dev)][IN];
   2254 		if (sce == NULL) {
   2255 			error = EINVAL;
   2256 			goto out;
   2257 		}
   2258 
   2259 		sip = &sce->rsel;
   2260 		switch (sce->edesc->bmAttributes & UE_XFERTYPE) {
   2261 		case UE_INTERRUPT:
   2262 			kn->kn_fop = &ugenread_intr_filtops;
   2263 			break;
   2264 		case UE_ISOCHRONOUS:
   2265 			kn->kn_fop = &ugenread_isoc_filtops;
   2266 			break;
   2267 		case UE_BULK:
   2268 			kn->kn_fop = &ugenread_bulk_filtops;
   2269 			break;
   2270 		default:
   2271 			error = EINVAL;
   2272 			goto out;
   2273 		}
   2274 		break;
   2275 
   2276 	case EVFILT_WRITE:
   2277 		sce = &sc->sc_endpoints[UGENENDPOINT(dev)][OUT];
   2278 		if (sce == NULL) {
   2279 			error = EINVAL;
   2280 			goto out;
   2281 		}
   2282 
   2283 		sip = &sce->rsel;
   2284 		switch (sce->edesc->bmAttributes & UE_XFERTYPE) {
   2285 		case UE_INTERRUPT:
   2286 		case UE_ISOCHRONOUS:
   2287 			/* XXX poll doesn't support this */
   2288 			error = EINVAL;
   2289 			goto out;
   2290 
   2291 		case UE_BULK:
   2292 			kn->kn_fop = &ugenwrite_bulk_filtops;
   2293 			break;
   2294 		default:
   2295 			error = EINVAL;
   2296 			goto out;
   2297 		}
   2298 		break;
   2299 
   2300 	default:
   2301 		error = EINVAL;
   2302 		goto out;
   2303 	}
   2304 
   2305 	kn->kn_hook = sce;
   2306 
   2307 	mutex_enter(&sc->sc_lock);
   2308 	selrecord_knote(sip, kn);
   2309 	mutex_exit(&sc->sc_lock);
   2310 
   2311 	error = 0;
   2312 
   2313 out:	ugenif_release(sc);
   2314 	return error;
   2315 }
   2316 
   2317 MODULE(MODULE_CLASS_DRIVER, ugen, NULL);
   2318 
   2319 static int
   2320 ugen_modcmd(modcmd_t cmd, void *aux)
   2321 {
   2322 
   2323 	switch (cmd) {
   2324 	case MODULE_CMD_INIT:
   2325 		mutex_init(&ugenif.lock, MUTEX_DEFAULT, IPL_NONE);
   2326 		rb_tree_init(&ugenif.tree, &ugenif_tree_ops);
   2327 		return 0;
   2328 	default:
   2329 		return ENOTTY;
   2330 	}
   2331 }
   2332