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