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