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