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