Home | History | Annotate | Line # | Download | only in usb
ugen.c revision 1.28
      1 /*	$NetBSD: ugen.c,v 1.28 1999/11/12 00:34:57 augustss Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1998 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 (augustss (at) carlstedt.se) at
      9  * Carlstedt Research & Technology.
     10  *
     11  * Redistribution and use in source and binary forms, with or without
     12  * modification, are permitted provided that the following conditions
     13  * are met:
     14  * 1. Redistributions of source code must retain the above copyright
     15  *    notice, this list of conditions and the following disclaimer.
     16  * 2. Redistributions in binary form must reproduce the above copyright
     17  *    notice, this list of conditions and the following disclaimer in the
     18  *    documentation and/or other materials provided with the distribution.
     19  * 3. All advertising materials mentioning features or use of this software
     20  *    must display the following acknowledgement:
     21  *        This product includes software developed by the NetBSD
     22  *        Foundation, Inc. and its contributors.
     23  * 4. Neither the name of The NetBSD Foundation nor the names of its
     24  *    contributors may be used to endorse or promote products derived
     25  *    from this software without specific prior written permission.
     26  *
     27  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     28  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     29  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     30  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     31  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     32  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     33  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     34  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     35  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     36  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     37  * POSSIBILITY OF SUCH DAMAGE.
     38  */
     39 
     40 
     41 #include <sys/param.h>
     42 #include <sys/systm.h>
     43 #include <sys/kernel.h>
     44 #include <sys/malloc.h>
     45 #if defined(__NetBSD__) || defined(__OpenBSD__)
     46 #include <sys/device.h>
     47 #include <sys/ioctl.h>
     48 #elif defined(__FreeBSD__)
     49 #include <sys/module.h>
     50 #include <sys/bus.h>
     51 #include <sys/ioccom.h>
     52 #include <sys/conf.h>
     53 #include <sys/fcntl.h>
     54 #include <sys/filio.h>
     55 #endif
     56 #include <sys/conf.h>
     57 #include <sys/tty.h>
     58 #include <sys/file.h>
     59 #include <sys/select.h>
     60 #include <sys/proc.h>
     61 #include <sys/vnode.h>
     62 #include <sys/poll.h>
     63 
     64 #include <dev/usb/usb.h>
     65 #include <dev/usb/usbdi.h>
     66 #include <dev/usb/usbdi_util.h>
     67 
     68 #ifdef UGEN_DEBUG
     69 #define DPRINTF(x)	if (ugendebug) logprintf x
     70 #define DPRINTFN(n,x)	if (ugendebug>(n)) logprintf x
     71 int	ugendebug = 0;
     72 #else
     73 #define DPRINTF(x)
     74 #define DPRINTFN(n,x)
     75 #endif
     76 
     77 struct ugen_endpoint {
     78 	struct ugen_softc *sc;
     79 	usb_endpoint_descriptor_t *edesc;
     80 	usbd_interface_handle iface;
     81 	int state;
     82 #define	UGEN_ASLP	0x02	/* waiting for data */
     83 #define UGEN_SHORT_OK	0x04	/* short xfers are OK */
     84 	usbd_pipe_handle pipeh;
     85 	struct clist q;
     86 	struct selinfo rsel;
     87 	void *ibuf;
     88 	u_int32_t timeout;
     89 };
     90 
     91 #define	UGEN_CHUNK	128	/* chunk size for read */
     92 #define	UGEN_IBSIZE	1020	/* buffer size */
     93 #define	UGEN_BBSIZE	1024
     94 
     95 struct ugen_softc {
     96 	USBBASEDEVICE sc_dev;		/* base device */
     97 	usbd_device_handle sc_udev;
     98 
     99 	char sc_is_open[USB_MAX_ENDPOINTS];
    100 	struct ugen_endpoint sc_endpoints[USB_MAX_ENDPOINTS][2];
    101 #define OUT 0
    102 #define IN  1
    103 
    104 	int sc_refcnt;
    105 	u_char sc_dying;
    106 };
    107 
    108 #if defined(__NetBSD__) || defined(__OpenBSD__)
    109 cdev_decl(ugen);
    110 #elif defined(__FreeBSD__)
    111 d_open_t  ugenopen;
    112 d_close_t ugenclose;
    113 d_read_t  ugenread;
    114 d_write_t ugenwrite;
    115 d_ioctl_t ugenioctl;
    116 d_poll_t  ugenpoll;
    117 
    118 #define UGEN_CDEV_MAJOR	114
    119 
    120 static struct cdevsw ugen_cdevsw = {
    121 	/* open */	ugenopen,
    122 	/* close */	ugenclose,
    123 	/* read */	ugenread,
    124 	/* write */	ugenwrite,
    125 	/* ioctl */	ugenioctl,
    126 	/* stop */	nostop,
    127 	/* reset */	noreset,
    128 	/* devtotty */	nodevtotty,
    129 	/* poll */	ugenpoll,
    130 	/* mmap */	nommap,
    131 	/* strategy */	nostrategy,
    132 	/* name */	"ugen",
    133 	/* parms */	noparms,
    134 	/* maj */	UGEN_CDEV_MAJOR,
    135 	/* dump */	nodump,
    136 	/* psize */	nopsize,
    137 	/* flags */	0,
    138 	/* maxio */	0,
    139 	/* bmaj */	-1
    140 };
    141 #endif
    142 
    143 static void ugenintr __P((usbd_xfer_handle xfer, usbd_private_handle addr,
    144 			  usbd_status status));
    145 
    146 static int ugen_do_read __P((struct ugen_softc *, int, struct uio *, int));
    147 static int ugen_do_write __P((struct ugen_softc *, int, struct uio *, int));
    148 static int ugen_do_ioctl __P((struct ugen_softc *, int, u_long,
    149 			      caddr_t, int, struct proc *));
    150 static int ugen_set_config __P((struct ugen_softc *sc, int configno));
    151 static usb_config_descriptor_t *ugen_get_cdesc __P((struct ugen_softc *sc,
    152 						    int index, int *lenp));
    153 static usbd_status ugen_set_interface __P((struct ugen_softc *, int, int));
    154 static int ugen_get_alt_index __P((struct ugen_softc *sc, int ifaceidx));
    155 
    156 #define UGENUNIT(n) ((minor(n) >> 4) & 0xf)
    157 #define UGENENDPOINT(n) (minor(n) & 0xf)
    158 #define UGENDEV(u, e) (makedev(0, ((u) << 4) | (e)))
    159 
    160 USB_DECLARE_DRIVER(ugen);
    161 
    162 USB_MATCH(ugen)
    163 {
    164 	USB_MATCH_START(ugen, uaa);
    165 
    166 	if (uaa->usegeneric)
    167 		return (UMATCH_GENERIC);
    168 	else
    169 		return (UMATCH_NONE);
    170 }
    171 
    172 USB_ATTACH(ugen)
    173 {
    174 	USB_ATTACH_START(ugen, sc, uaa);
    175 	char devinfo[1024];
    176 	usbd_status err;
    177 	int conf;
    178 
    179 	usbd_devinfo(uaa->device, 0, devinfo);
    180 	USB_ATTACH_SETUP;
    181 	printf("%s: %s\n", USBDEVNAME(sc->sc_dev), devinfo);
    182 
    183 	sc->sc_udev = uaa->device;
    184 	conf = 1;		/* XXX should not hard code 1 */
    185 	err = ugen_set_config(sc, conf);
    186 	if (err) {
    187 		printf("%s: setting configuration %d failed\n",
    188 		       USBDEVNAME(sc->sc_dev), conf);
    189 		sc->sc_dying = 1;
    190 		USB_ATTACH_ERROR_RETURN;
    191 	}
    192 	USB_ATTACH_SUCCESS_RETURN;
    193 }
    194 
    195 int
    196 ugen_set_config(sc, configno)
    197 	struct ugen_softc *sc;
    198 	int configno;
    199 {
    200 	usbd_device_handle dev = sc->sc_udev;
    201 	usbd_interface_handle iface;
    202 	usb_endpoint_descriptor_t *ed;
    203 	struct ugen_endpoint *sce;
    204 	u_int8_t niface, nendpt;
    205 	int ifaceno, endptno, endpt;
    206 	usbd_status err;
    207 	int dir;
    208 
    209 	DPRINTFN(1,("ugen_set_config: %s to configno %d, sc=%p\n",
    210 		    USBDEVNAME(sc->sc_dev), configno, sc));
    211 	if (usbd_get_config_descriptor(dev)->bConfigurationValue != configno) {
    212 		/* Avoid setting the current value. */
    213 		err = usbd_set_config_no(dev, configno, 0);
    214 		if (err)
    215 			return (err);
    216 	}
    217 
    218 	err = usbd_interface_count(dev, &niface);
    219 	if (err)
    220 		return (err);
    221 	memset(sc->sc_endpoints, 0, sizeof sc->sc_endpoints);
    222 	for (ifaceno = 0; ifaceno < niface; ifaceno++) {
    223 		DPRINTFN(1,("ugen_set_config: ifaceno %d\n", ifaceno));
    224 		err = usbd_device2interface_handle(dev, ifaceno, &iface);
    225 		if (err)
    226 			return (err);
    227 		err = usbd_endpoint_count(iface, &nendpt);
    228 		if (err)
    229 			return (err);
    230 		for (endptno = 0; endptno < nendpt; endptno++) {
    231 			ed = usbd_interface2endpoint_descriptor(iface,endptno);
    232 			endpt = ed->bEndpointAddress;
    233 			dir = UE_GET_DIR(endpt) == UE_DIR_IN ? IN : OUT;
    234 			sce = &sc->sc_endpoints[UE_GET_ADDR(endpt)][dir];
    235 			DPRINTFN(1,("ugen_set_config: endptno %d, endpt=0x%02x"
    236 				    "(%d,%d), sce=%p\n",
    237 				    endptno, endpt, UE_GET_ADDR(endpt),
    238 				    UE_GET_DIR(endpt), sce));
    239 			sce->sc = sc;
    240 			sce->edesc = ed;
    241 			sce->iface = iface;
    242 		}
    243 	}
    244 	return (USBD_NORMAL_COMPLETION);
    245 }
    246 
    247 int
    248 ugenopen(dev, flag, mode, p)
    249 	dev_t dev;
    250 	int flag;
    251 	int mode;
    252 	struct proc *p;
    253 {
    254 	struct ugen_softc *sc;
    255 	int unit = UGENUNIT(dev);
    256 	int endpt = UGENENDPOINT(dev);
    257 	usb_endpoint_descriptor_t *edesc;
    258 	struct ugen_endpoint *sce;
    259 	int dir, isize;
    260 	usbd_status err;
    261 
    262 	USB_GET_SC_OPEN(ugen, unit, sc);
    263  	DPRINTFN(5, ("ugenopen: flag=%d, mode=%d, unit=%d endpt=%d\n",
    264 		     flag, mode, unit, endpt));
    265 
    266 	if (sc->sc_dying)
    267 		return (ENXIO);
    268 
    269 	if (sc->sc_is_open[endpt])
    270 		return (EBUSY);
    271 
    272 	if (endpt == USB_CONTROL_ENDPOINT) {
    273 		sc->sc_is_open[USB_CONTROL_ENDPOINT] = 1;
    274 		return (0);
    275 	}
    276 	/* Make sure there are pipes for all directions. */
    277 	for (dir = OUT; dir <= IN; dir++) {
    278 		if (flag & (dir == OUT ? FWRITE : FREAD)) {
    279 			sce = &sc->sc_endpoints[endpt][dir];
    280 			if (sce == 0 || sce->edesc == 0)
    281 				return (ENXIO);
    282 		}
    283 	}
    284 
    285 	/* Actually open the pipes. */
    286 	/* XXX Should back out properly if it fails. */
    287 	for (dir = OUT; dir <= IN; dir++) {
    288 		if (!(flag & (dir == OUT ? FWRITE : FREAD)))
    289 			continue;
    290 		sce = &sc->sc_endpoints[endpt][dir];
    291 		sce->state = 0;
    292 		sce->timeout = USBD_NO_TIMEOUT;
    293 		DPRINTFN(5, ("ugenopen: sc=%p, endpt=%d, dir=%d, sce=%p\n",
    294 			     sc, endpt, dir, sce));
    295 		edesc = sce->edesc;
    296 		switch (edesc->bmAttributes & UE_XFERTYPE) {
    297 		case UE_INTERRUPT:
    298 			isize = UGETW(edesc->wMaxPacketSize);
    299 			if (isize == 0)	/* shouldn't happen */
    300 				return (EINVAL);
    301 			sce->ibuf = malloc(isize, M_USBDEV, M_WAITOK);
    302 			DPRINTFN(5, ("ugenopen: intr endpt=%d,isize=%d\n",
    303 				     endpt, isize));
    304                         if (clalloc(&sce->q, UGEN_IBSIZE, 0) == -1)
    305                                 return (ENOMEM);
    306 			err = usbd_open_pipe_intr(sce->iface,
    307 				  edesc->bEndpointAddress,
    308 				  USBD_SHORT_XFER_OK, &sce->pipeh, sce,
    309 				  sce->ibuf, isize, ugenintr);
    310 			if (err) {
    311 				free(sce->ibuf, M_USBDEV);
    312 				clfree(&sce->q);
    313 				return (EIO);
    314 			}
    315 			DPRINTFN(5, ("ugenopen: interrupt open done\n"));
    316 			break;
    317 		case UE_BULK:
    318 			err = usbd_open_pipe(sce->iface,
    319 				  edesc->bEndpointAddress, 0, &sce->pipeh);
    320 			if (err)
    321 				return (EIO);
    322 			break;
    323 		case UE_CONTROL:
    324 		case UE_ISOCHRONOUS:
    325 			return (EINVAL);
    326 		}
    327 	}
    328 	sc->sc_is_open[endpt] = 1;
    329 	return (0);
    330 }
    331 
    332 int
    333 ugenclose(dev, flag, mode, p)
    334 	dev_t dev;
    335 	int flag;
    336 	int mode;
    337 	struct proc *p;
    338 {
    339 	int endpt = UGENENDPOINT(dev);
    340 	struct ugen_softc *sc;
    341 	struct ugen_endpoint *sce;
    342 	int dir;
    343 
    344 	USB_GET_SC(ugen, UGENUNIT(dev), sc);
    345 	DPRINTFN(5, ("ugenclose: flag=%d, mode=%d, unit=%d, endpt=%d\n",
    346 		     flag, mode, UGENUNIT(dev), endpt));
    347 
    348 #ifdef DIAGNOSTIC
    349 	if (!sc->sc_is_open[endpt]) {
    350 		printf("ugenclose: not open\n");
    351 		return (EINVAL);
    352 	}
    353 #endif
    354 
    355 	if (endpt == USB_CONTROL_ENDPOINT) {
    356 		DPRINTFN(5, ("ugenclose: close control\n"));
    357 		sc->sc_is_open[endpt] = 0;
    358 		return (0);
    359 	}
    360 
    361 	for (dir = OUT; dir <= IN; dir++) {
    362 		if (!(flag & (dir == OUT ? FWRITE : FREAD)))
    363 			continue;
    364 		sce = &sc->sc_endpoints[endpt][dir];
    365 		if (!sce || !sce->pipeh)
    366 			continue;
    367 		DPRINTFN(5, ("ugenclose: endpt=%d dir=%d sce=%p\n",
    368 			     endpt, dir, sce));
    369 
    370 		usbd_abort_pipe(sce->pipeh);
    371 		usbd_close_pipe(sce->pipeh);
    372 		sce->pipeh = NULL;
    373 
    374 		if (sce->ibuf != NULL) {
    375 			free(sce->ibuf, M_USBDEV);
    376 			sce->ibuf = 0;
    377 			clfree(&sce->q);
    378 		}
    379 	}
    380 	sc->sc_is_open[endpt] = 0;
    381 
    382 	return (0);
    383 }
    384 
    385 int
    386 ugen_do_read(sc, endpt, uio, flag)
    387 	struct ugen_softc *sc;
    388 	int endpt;
    389 	struct uio *uio;
    390 	int flag;
    391 {
    392 	struct ugen_endpoint *sce = &sc->sc_endpoints[endpt][IN];
    393 	u_int32_t n, tn;
    394 	char buf[UGEN_BBSIZE];
    395 	usbd_xfer_handle xfer;
    396 	usbd_status err;
    397 	int s;
    398 	int error = 0;
    399 	u_char buffer[UGEN_CHUNK];
    400 
    401 #ifdef __NetBSD__
    402 	DPRINTFN(5, ("ugenread: %d:%d\n", sc->sc_dev.dv_unit, endpt));
    403 #endif
    404 
    405 	if (sc->sc_dying)
    406 		return (EIO);
    407 
    408 	if (endpt == USB_CONTROL_ENDPOINT)
    409 		return (ENODEV);
    410 
    411 #ifdef DIAGNOSTIC
    412 	if (sce->edesc == NULL) {
    413 		printf("ugenread: no edesc\n");
    414 		return (EIO);
    415 	}
    416 	if (sce->pipeh == NULL) {
    417 		printf("ugenread: no pipe\n");
    418 		return (EIO);
    419 	}
    420 #endif
    421 
    422 	switch (sce->edesc->bmAttributes & UE_XFERTYPE) {
    423 	case UE_INTERRUPT:
    424 		/* Block until activity occured. */
    425 		s = splusb();
    426 		while (sce->q.c_cc == 0) {
    427 			if (flag & IO_NDELAY) {
    428 				splx(s);
    429 				return (EWOULDBLOCK);
    430 			}
    431 			sce->state |= UGEN_ASLP;
    432 			DPRINTFN(5, ("ugenread: sleep on %p\n", sc));
    433 			error = tsleep(sce, PZERO | PCATCH, "ugenri", 0);
    434 			DPRINTFN(5, ("ugenread: woke, error=%d\n", error));
    435 			if (sc->sc_dying)
    436 				error = EIO;
    437 			if (error) {
    438 				sce->state &= ~UGEN_ASLP;
    439 				break;
    440 			}
    441 		}
    442 		splx(s);
    443 
    444 		/* Transfer as many chunks as possible. */
    445 		while (sce->q.c_cc > 0 && uio->uio_resid > 0 && !error) {
    446 			n = min(sce->q.c_cc, uio->uio_resid);
    447 			if (n > sizeof(buffer))
    448 				n = sizeof(buffer);
    449 
    450 			/* Remove a small chunk from the input queue. */
    451 			q_to_b(&sce->q, buffer, n);
    452 			DPRINTFN(5, ("ugenread: got %d chars\n", n));
    453 
    454 			/* Copy the data to the user process. */
    455 			error = uiomove(buffer, n, uio);
    456 			if (error)
    457 				break;
    458 		}
    459 		break;
    460 	case UE_BULK:
    461 		xfer = usbd_alloc_request(sc->sc_udev);
    462 		if (xfer == 0)
    463 			return (ENOMEM);
    464 		while ((n = min(UGEN_BBSIZE, uio->uio_resid)) != 0) {
    465 			DPRINTFN(1, ("ugenread: start transfer %d bytes\n",n));
    466 			tn = n;
    467 			err = usbd_bulk_transfer(
    468 				  xfer, sce->pipeh,
    469 				  sce->state & UGEN_SHORT_OK ?
    470 				      USBD_SHORT_XFER_OK : 0,
    471 				  sce->timeout, buf, &tn, "ugenrb");
    472 			if (err != USBD_NORMAL_COMPLETION) {
    473 				if (err == USBD_INTERRUPTED)
    474 					error = EINTR;
    475 				else if (err == USBD_TIMEOUT)
    476 					error = ETIMEDOUT;
    477 				else
    478 					error = EIO;
    479 				break;
    480 			}
    481 			DPRINTFN(1, ("ugenread: got %d bytes\n", tn));
    482 			error = uiomove(buf, tn, uio);
    483 			if (error || tn < n)
    484 				break;
    485 		}
    486 		usbd_free_request(xfer);
    487 		break;
    488 	default:
    489 		return (ENXIO);
    490 	}
    491 	return (error);
    492 }
    493 
    494 int
    495 ugenread(dev, uio, flag)
    496 	dev_t dev;
    497 	struct uio *uio;
    498 	int flag;
    499 {
    500 	int endpt = UGENENDPOINT(dev);
    501 	struct ugen_softc *sc;
    502 	int error;
    503 
    504 	USB_GET_SC(ugen, UGENUNIT(dev), sc);
    505 	sc->sc_refcnt++;
    506 	error = ugen_do_read(sc, endpt, uio, flag);
    507 	if (--sc->sc_refcnt < 0)
    508 		usb_detach_wakeup(USBDEV(sc->sc_dev));
    509 	return (error);
    510 }
    511 
    512 int
    513 ugen_do_write(sc, endpt, uio, flag)
    514 	struct ugen_softc *sc;
    515 	int endpt;
    516 	struct uio *uio;
    517 	int flag;
    518 {
    519 	struct ugen_endpoint *sce = &sc->sc_endpoints[endpt][OUT];
    520 	u_int32_t n;
    521 	int error = 0;
    522 	char buf[UGEN_BBSIZE];
    523 	usbd_xfer_handle xfer;
    524 	usbd_status err;
    525 
    526 #ifdef __NetBSD__
    527 	DPRINTFN(5, ("ugenwrite: %d:%d\n", sc->sc_dev.dv_unit, endpt));
    528 #endif
    529 
    530 	if (sc->sc_dying)
    531 		return (EIO);
    532 
    533 	if (endpt == USB_CONTROL_ENDPOINT)
    534 		return (ENODEV);
    535 
    536 #ifdef DIAGNOSTIC
    537 	if (sce->edesc == NULL) {
    538 		printf("ugenwrite: no edesc\n");
    539 		return (EIO);
    540 	}
    541 	if (sce->pipeh == NULL) {
    542 		printf("ugenwrite: no pipe\n");
    543 		return (EIO);
    544 	}
    545 #endif
    546 
    547 	switch (sce->edesc->bmAttributes & UE_XFERTYPE) {
    548 	case UE_BULK:
    549 		xfer = usbd_alloc_request(sc->sc_udev);
    550 		if (xfer == 0)
    551 			return (EIO);
    552 		while ((n = min(UGEN_BBSIZE, uio->uio_resid)) != 0) {
    553 			error = uiomove(buf, n, uio);
    554 			if (error)
    555 				break;
    556 			DPRINTFN(1, ("ugenwrite: transfer %d bytes\n", n));
    557 			err = usbd_bulk_transfer(xfer, sce->pipeh, 0,
    558 				  sce->timeout, buf, &n,"ugenwb");
    559 			if (err) {
    560 				if (err == USBD_INTERRUPTED)
    561 					error = EINTR;
    562 				else
    563 					error = EIO;
    564 				break;
    565 			}
    566 		}
    567 		usbd_free_request(xfer);
    568 		break;
    569 	default:
    570 		return (ENXIO);
    571 	}
    572 	return (error);
    573 }
    574 
    575 int
    576 ugenwrite(dev, uio, flag)
    577 	dev_t dev;
    578 	struct uio *uio;
    579 	int flag;
    580 {
    581 	int endpt = UGENENDPOINT(dev);
    582 	struct ugen_softc *sc;
    583 	int error;
    584 
    585 	USB_GET_SC(ugen, UGENUNIT(dev), sc);
    586 	sc->sc_refcnt++;
    587 	error = ugen_do_write(sc, endpt, uio, flag);
    588 	if (--sc->sc_refcnt < 0)
    589 		usb_detach_wakeup(USBDEV(sc->sc_dev));
    590 	return (error);
    591 }
    592 
    593 #if defined(__NetBSD__) || defined(__OpenBSD__)
    594 int
    595 ugen_activate(self, act)
    596 	device_ptr_t self;
    597 	enum devact act;
    598 {
    599 	struct ugen_softc *sc = (struct ugen_softc *)self;
    600 
    601 	switch (act) {
    602 	case DVACT_ACTIVATE:
    603 		return (EOPNOTSUPP);
    604 		break;
    605 
    606 	case DVACT_DEACTIVATE:
    607 		sc->sc_dying = 1;
    608 		break;
    609 	}
    610 	return (0);
    611 }
    612 #endif
    613 
    614 USB_DETACH(ugen)
    615 {
    616 	USB_DETACH_START(ugen, sc);
    617 	struct ugen_endpoint *sce;
    618 	int i, dir;
    619 	int s;
    620 #if defined(__NetBSD__) || defined(__OpenBSD__)
    621 	int maj, mn;
    622 
    623 	DPRINTF(("ugen_detach: sc=%p flags=%d\n", sc, flags));
    624 #elif defined(__FreeBSD__)
    625 	DPRINTF(("ugen_detach: sc=%p\n", sc));
    626 #endif
    627 
    628 	sc->sc_dying = 1;
    629 	/* Abort all pipes.  Causes processes waiting for transfer to wake. */
    630 	for (i = 0; i < USB_MAX_ENDPOINTS; i++) {
    631 		for (dir = OUT; dir <= IN; dir++) {
    632 			sce = &sc->sc_endpoints[i][dir];
    633 			if (sce && sce->pipeh)
    634 				usbd_abort_pipe(sce->pipeh);
    635 		}
    636 	}
    637 
    638 	s = splusb();
    639 	if (--sc->sc_refcnt >= 0) {
    640 		/* Wake everyone */
    641 		for (i = 0; i < USB_MAX_ENDPOINTS; i++)
    642 			wakeup(&sc->sc_endpoints[i][IN]);
    643 		/* Wait for processes to go away. */
    644 		usb_detach_wait(USBDEV(sc->sc_dev));
    645 	}
    646 	splx(s);
    647 
    648 #if defined(__NetBSD__) || defined(__OpenBSD__)
    649 	/* locate the major number */
    650 	for (maj = 0; maj < nchrdev; maj++)
    651 		if (cdevsw[maj].d_open == ugenopen)
    652 			break;
    653 
    654 	/* Nuke the vnodes for any open instances (calls close). */
    655 	mn = self->dv_unit * USB_MAX_ENDPOINTS;
    656 	vdevgone(maj, mn, mn + USB_MAX_ENDPOINTS - 1, VCHR);
    657 #elif defined(__FreeBSD__)
    658 	/* XXX not implemented yet */
    659 #endif
    660 
    661 	return (0);
    662 }
    663 
    664 void
    665 ugenintr(xfer, addr, status)
    666 	usbd_xfer_handle xfer;
    667 	usbd_private_handle addr;
    668 	usbd_status status;
    669 {
    670 	struct ugen_endpoint *sce = addr;
    671 	/*struct ugen_softc *sc = sce->sc;*/
    672 	u_int32_t count;
    673 	u_char *ibuf;
    674 
    675 	if (status == USBD_CANCELLED)
    676 		return;
    677 
    678 	if (status != USBD_NORMAL_COMPLETION) {
    679 		DPRINTF(("ugenintr: status=%d\n", status));
    680 		usbd_clear_endpoint_stall_async(sce->pipeh);
    681 		return;
    682 	}
    683 
    684 	usbd_get_request_status(xfer, 0, 0, &count, 0);
    685 	ibuf = sce->ibuf;
    686 
    687 	DPRINTFN(5, ("ugenintr: xfer=%p status=%d count=%d\n",
    688 		     xfer, status, count));
    689 	DPRINTFN(5, ("          data = %02x %02x %02x\n",
    690 		     ibuf[0], ibuf[1], ibuf[2]));
    691 
    692 	(void)b_to_q(ibuf, count, &sce->q);
    693 
    694 	if (sce->state & UGEN_ASLP) {
    695 		sce->state &= ~UGEN_ASLP;
    696 		DPRINTFN(5, ("ugen_intr: waking %p\n", sce));
    697 		wakeup(sce);
    698 	}
    699 	selwakeup(&sce->rsel);
    700 }
    701 
    702 usbd_status
    703 ugen_set_interface(sc, ifaceidx, altno)
    704 	struct ugen_softc *sc;
    705 	int ifaceidx, altno;
    706 {
    707 	usbd_interface_handle iface;
    708 	usb_endpoint_descriptor_t *ed;
    709 	usbd_status err;
    710 	struct ugen_endpoint *sce;
    711 	u_int8_t niface, nendpt, endptno, endpt;
    712 	int dir;
    713 
    714 	DPRINTFN(15, ("ugen_set_interface %d %d\n", ifaceidx, altno));
    715 
    716 	err = usbd_interface_count(sc->sc_udev, &niface);
    717 	if (err)
    718 		return (err);
    719 	if (ifaceidx < 0 || ifaceidx >= niface)
    720 		return (USBD_INVAL);
    721 
    722 	err = usbd_device2interface_handle(sc->sc_udev, ifaceidx, &iface);
    723 	if (err)
    724 		return (err);
    725 	err = usbd_endpoint_count(iface, &nendpt);
    726 	if (err)
    727 		return (err);
    728 	for (endptno = 0; endptno < nendpt; endptno++) {
    729 		ed = usbd_interface2endpoint_descriptor(iface,endptno);
    730 		endpt = ed->bEndpointAddress;
    731 		dir = UE_GET_DIR(endpt) == UE_DIR_IN ? IN : OUT;
    732 		sce = &sc->sc_endpoints[UE_GET_ADDR(endpt)][dir];
    733 		sce->sc = 0;
    734 		sce->edesc = 0;
    735 		sce->iface = 0;
    736 	}
    737 
    738 	/* change setting */
    739 	err = usbd_set_interface(iface, altno);
    740 	if (err)
    741 		return (err);
    742 
    743 	err = usbd_endpoint_count(iface, &nendpt);
    744 	if (err)
    745 		return (err);
    746 	for (endptno = 0; endptno < nendpt; endptno++) {
    747 		ed = usbd_interface2endpoint_descriptor(iface,endptno);
    748 		endpt = ed->bEndpointAddress;
    749 		dir = UE_GET_DIR(endpt) == UE_DIR_IN ? IN : OUT;
    750 		sce = &sc->sc_endpoints[UE_GET_ADDR(endpt)][dir];
    751 		sce->sc = sc;
    752 		sce->edesc = ed;
    753 		sce->iface = iface;
    754 	}
    755 	return (0);
    756 }
    757 
    758 /* Retrieve a complete descriptor for a certain device and index. */
    759 usb_config_descriptor_t *
    760 ugen_get_cdesc(sc, index, lenp)
    761 	struct ugen_softc *sc;
    762 	int index;
    763 	int *lenp;
    764 {
    765 	usb_config_descriptor_t *cdesc, *tdesc, cdescr;
    766 	int len;
    767 	usbd_status err;
    768 
    769 	if (index == USB_CURRENT_CONFIG_INDEX) {
    770 		tdesc = usbd_get_config_descriptor(sc->sc_udev);
    771 		len = UGETW(tdesc->wTotalLength);
    772 		if (lenp)
    773 			*lenp = len;
    774 		cdesc = malloc(len, M_TEMP, M_WAITOK);
    775 		memcpy(cdesc, tdesc, len);
    776 		DPRINTFN(5,("ugen_get_cdesc: current, len=%d\n", len));
    777 	} else {
    778 		err = usbd_get_config_desc(sc->sc_udev, index, &cdescr);
    779 		if (err)
    780 			return (0);
    781 		len = UGETW(cdescr.wTotalLength);
    782 		DPRINTFN(5,("ugen_get_cdesc: index=%d, len=%d\n", index, len));
    783 		if (lenp)
    784 			*lenp = len;
    785 		cdesc = malloc(len, M_TEMP, M_WAITOK);
    786 		err = usbd_get_config_desc_full(sc->sc_udev, index, cdesc,len);
    787 		if (err) {
    788 			free(cdesc, M_TEMP);
    789 			return (0);
    790 		}
    791 	}
    792 	return (cdesc);
    793 }
    794 
    795 int
    796 ugen_get_alt_index(sc, ifaceidx)
    797 	struct ugen_softc *sc;
    798 	int ifaceidx;
    799 {
    800 	usbd_interface_handle iface;
    801 	usbd_status err;
    802 
    803 	err = usbd_device2interface_handle(sc->sc_udev, ifaceidx, &iface);
    804 	if (err)
    805 			return (-1);
    806 	return (usbd_get_interface_altindex(iface));
    807 }
    808 
    809 int
    810 ugen_do_ioctl(sc, endpt, cmd, addr, flag, p)
    811 	struct ugen_softc *sc;
    812 	int endpt;
    813 	u_long cmd;
    814 	caddr_t addr;
    815 	int flag;
    816 	struct proc *p;
    817 {
    818 	struct ugen_endpoint *sce;
    819 	usbd_status err;
    820 	usbd_interface_handle iface;
    821 	struct usb_config_desc *cd;
    822 	usb_config_descriptor_t *cdesc;
    823 	struct usb_interface_desc *id;
    824 	usb_interface_descriptor_t *idesc;
    825 	struct usb_endpoint_desc *ed;
    826 	usb_endpoint_descriptor_t *edesc;
    827 	struct usb_alt_interface *ai;
    828 	struct usb_string_desc *si;
    829 	u_int8_t conf, alt;
    830 
    831 	DPRINTFN(5, ("ugenioctl: cmd=%08lx\n", cmd));
    832 	if (sc->sc_dying)
    833 		return (EIO);
    834 
    835 	switch (cmd) {
    836 	case FIONBIO:
    837 		/* All handled in the upper FS layer. */
    838 		return (0);
    839 	case USB_SET_SHORT_XFER:
    840 		/* This flag only affects read */
    841 		if (endpt == USB_CONTROL_ENDPOINT)
    842 			return (EINVAL);
    843 		sce = &sc->sc_endpoints[endpt][IN];
    844 		if (sce == NULL)
    845 			return (EINVAL);
    846 #ifdef DIAGNOSTIC
    847 		if (sce->pipeh == NULL) {
    848 			printf("ugenioctl: USB_SET_SHORT_XFER, no pipe\n");
    849 			return (EIO);
    850 		}
    851 #endif
    852 		if (*(int *)addr)
    853 			sce->state |= UGEN_SHORT_OK;
    854 		else
    855 			sce->state &= ~UGEN_SHORT_OK;
    856 		return (0);
    857 	case USB_SET_TIMEOUT:
    858 		sce = &sc->sc_endpoints[endpt][IN];
    859 		if (sce == NULL)
    860 			return (EINVAL);
    861 #ifdef DIAGNOSTIC
    862 		if (sce->pipeh == NULL) {
    863 			printf("ugenioctl: USB_SET_TIMEOUT, no pipe\n");
    864 			return (EIO);
    865 		}
    866 #endif
    867 		sce->timeout = *(int *)addr;
    868 		return (0);
    869 	default:
    870 		break;
    871 	}
    872 
    873 	if (endpt != USB_CONTROL_ENDPOINT)
    874 		return (EINVAL);
    875 
    876 	switch (cmd) {
    877 #ifdef USB_DEBUG
    878 	case USB_SETDEBUG:
    879 		ugendebug = *(int *)addr;
    880 		break;
    881 #endif
    882 	case USB_GET_CONFIG:
    883 		err = usbd_get_config(sc->sc_udev, &conf);
    884 		if (err)
    885 			return (EIO);
    886 		*(int *)addr = conf;
    887 		break;
    888 	case USB_SET_CONFIG:
    889 		if (!(flag & FWRITE))
    890 			return (EPERM);
    891 		err = ugen_set_config(sc, *(int *)addr);
    892 		if (err)
    893 			return (EIO);
    894 		break;
    895 	case USB_GET_ALTINTERFACE:
    896 		ai = (struct usb_alt_interface *)addr;
    897 		err = usbd_device2interface_handle(sc->sc_udev,
    898 			  ai->interface_index, &iface);
    899 		if (err)
    900 			return (EINVAL);
    901 		idesc = usbd_get_interface_descriptor(iface);
    902 		if (idesc == NULL)
    903 			return (EIO);
    904 		ai->alt_no = idesc->bAlternateSetting;
    905 		break;
    906 	case USB_SET_ALTINTERFACE:
    907 		if (!(flag & FWRITE))
    908 			return (EPERM);
    909 		ai = (struct usb_alt_interface *)addr;
    910 		err = usbd_device2interface_handle(sc->sc_udev,
    911 			  ai->interface_index, &iface);
    912 		if (err)
    913 			return (EINVAL);
    914 		err = ugen_set_interface(sc, ai->interface_index, ai->alt_no);
    915 		if (err)
    916 			return (EINVAL);
    917 		break;
    918 	case USB_GET_NO_ALT:
    919 		ai = (struct usb_alt_interface *)addr;
    920 		cdesc = ugen_get_cdesc(sc, ai->config_index, 0);
    921 		if (cdesc == NULL)
    922 			return (EINVAL);
    923 		idesc = usbd_find_idesc(cdesc, ai->interface_index, 0);
    924 		if (idesc == NULL) {
    925 			free(cdesc, M_TEMP);
    926 			return (EINVAL);
    927 		}
    928 		ai->alt_no = usbd_get_no_alts(cdesc, idesc->bInterfaceNumber);
    929 		free(cdesc, M_TEMP);
    930 		break;
    931 	case USB_GET_DEVICE_DESC:
    932 		*(usb_device_descriptor_t *)addr =
    933 			*usbd_get_device_descriptor(sc->sc_udev);
    934 		break;
    935 	case USB_GET_CONFIG_DESC:
    936 		cd = (struct usb_config_desc *)addr;
    937 		cdesc = ugen_get_cdesc(sc, cd->config_index, 0);
    938 		if (cdesc == NULL)
    939 			return (EINVAL);
    940 		cd->desc = *cdesc;
    941 		free(cdesc, M_TEMP);
    942 		break;
    943 	case USB_GET_INTERFACE_DESC:
    944 		id = (struct usb_interface_desc *)addr;
    945 		cdesc = ugen_get_cdesc(sc, id->config_index, 0);
    946 		if (cdesc == NULL)
    947 			return (EINVAL);
    948 		if (id->config_index == USB_CURRENT_CONFIG_INDEX &&
    949 		    id->alt_index == USB_CURRENT_ALT_INDEX)
    950 			alt = ugen_get_alt_index(sc, id->interface_index);
    951 		else
    952 			alt = id->alt_index;
    953 		idesc = usbd_find_idesc(cdesc, id->interface_index, alt);
    954 		if (idesc == NULL) {
    955 			free(cdesc, M_TEMP);
    956 			return (EINVAL);
    957 		}
    958 		id->desc = *idesc;
    959 		free(cdesc, M_TEMP);
    960 		break;
    961 	case USB_GET_ENDPOINT_DESC:
    962 		ed = (struct usb_endpoint_desc *)addr;
    963 		cdesc = ugen_get_cdesc(sc, ed->config_index, 0);
    964 		if (cdesc == NULL)
    965 			return (EINVAL);
    966 		if (ed->config_index == USB_CURRENT_CONFIG_INDEX &&
    967 		    ed->alt_index == USB_CURRENT_ALT_INDEX)
    968 			alt = ugen_get_alt_index(sc, ed->interface_index);
    969 		else
    970 			alt = ed->alt_index;
    971 		edesc = usbd_find_edesc(cdesc, ed->interface_index,
    972 					alt, ed->endpoint_index);
    973 		if (edesc == NULL) {
    974 			free(cdesc, M_TEMP);
    975 			return (EINVAL);
    976 		}
    977 		ed->desc = *edesc;
    978 		free(cdesc, M_TEMP);
    979 		break;
    980 	case USB_GET_FULL_DESC:
    981 	{
    982 		int len;
    983 		struct iovec iov;
    984 		struct uio uio;
    985 		struct usb_full_desc *fd = (struct usb_full_desc *)addr;
    986 		int error;
    987 
    988 		cdesc = ugen_get_cdesc(sc, fd->config_index, &len);
    989 		if (len > fd->size)
    990 			len = fd->size;
    991 		iov.iov_base = (caddr_t)fd->data;
    992 		iov.iov_len = len;
    993 		uio.uio_iov = &iov;
    994 		uio.uio_iovcnt = 1;
    995 		uio.uio_resid = len;
    996 		uio.uio_offset = 0;
    997 		uio.uio_segflg = UIO_USERSPACE;
    998 		uio.uio_rw = UIO_READ;
    999 		uio.uio_procp = p;
   1000 		error = uiomove(cdesc, len, &uio);
   1001 		free(cdesc, M_TEMP);
   1002 		return (error);
   1003 	}
   1004 	case USB_GET_STRING_DESC:
   1005 		si = (struct usb_string_desc *)addr;
   1006 		err = usbd_get_string_desc(sc->sc_udev, si->string_index,
   1007 			  si->language_id, &si->desc);
   1008 		if (err)
   1009 			return (EINVAL);
   1010 		break;
   1011 	case USB_DO_REQUEST:
   1012 	{
   1013 		struct usb_ctl_request *ur = (void *)addr;
   1014 		int len = UGETW(ur->request.wLength);
   1015 		struct iovec iov;
   1016 		struct uio uio;
   1017 		void *ptr = 0;
   1018 		usbd_status err;
   1019 		int error = 0;
   1020 
   1021 		if (!(flag & FWRITE))
   1022 			return (EPERM);
   1023 		/* Avoid requests that would damage the bus integrity. */
   1024 		if ((ur->request.bmRequestType == UT_WRITE_DEVICE &&
   1025 		     ur->request.bRequest == UR_SET_ADDRESS) ||
   1026 		    (ur->request.bmRequestType == UT_WRITE_DEVICE &&
   1027 		     ur->request.bRequest == UR_SET_CONFIG) ||
   1028 		    (ur->request.bmRequestType == UT_WRITE_INTERFACE &&
   1029 		     ur->request.bRequest == UR_SET_INTERFACE))
   1030 			return (EINVAL);
   1031 
   1032 		if (len < 0 || len > 32767)
   1033 			return (EINVAL);
   1034 		if (len != 0) {
   1035 			iov.iov_base = (caddr_t)ur->data;
   1036 			iov.iov_len = len;
   1037 			uio.uio_iov = &iov;
   1038 			uio.uio_iovcnt = 1;
   1039 			uio.uio_resid = len;
   1040 			uio.uio_offset = 0;
   1041 			uio.uio_segflg = UIO_USERSPACE;
   1042 			uio.uio_rw =
   1043 				ur->request.bmRequestType & UT_READ ?
   1044 				UIO_READ : UIO_WRITE;
   1045 			uio.uio_procp = p;
   1046 			ptr = malloc(len, M_TEMP, M_WAITOK);
   1047 			if (uio.uio_rw == UIO_WRITE) {
   1048 				error = uiomove(ptr, len, &uio);
   1049 				if (error)
   1050 					goto ret;
   1051 			}
   1052 		}
   1053 		err = usbd_do_request_flags(sc->sc_udev, &ur->request,
   1054 			  ptr, ur->flags, &ur->actlen);
   1055 		if (err) {
   1056 			error = EIO;
   1057 			goto ret;
   1058 		}
   1059 		if (len != 0) {
   1060 			if (uio.uio_rw == UIO_READ) {
   1061 				error = uiomove(ptr, len, &uio);
   1062 				if (error)
   1063 					goto ret;
   1064 			}
   1065 		}
   1066 	ret:
   1067 		if (ptr)
   1068 			free(ptr, M_TEMP);
   1069 		return (error);
   1070 	}
   1071 	case USB_GET_DEVICEINFO:
   1072 		usbd_fill_deviceinfo(sc->sc_udev,
   1073 				     (struct usb_device_info *)addr);
   1074 		break;
   1075 	default:
   1076 		return (EINVAL);
   1077 	}
   1078 	return (0);
   1079 }
   1080 
   1081 int
   1082 ugenioctl(dev, cmd, addr, flag, p)
   1083 	dev_t dev;
   1084 	u_long cmd;
   1085 	caddr_t addr;
   1086 	int flag;
   1087 	struct proc *p;
   1088 {
   1089 	int endpt = UGENENDPOINT(dev);
   1090 	struct ugen_softc *sc;
   1091 	int error;
   1092 
   1093 	USB_GET_SC(ugen, UGENUNIT(dev), sc);
   1094 	sc->sc_refcnt++;
   1095 	error = ugen_do_ioctl(sc, endpt, cmd, addr, flag, p);
   1096 	if (--sc->sc_refcnt < 0)
   1097 		usb_detach_wakeup(USBDEV(sc->sc_dev));
   1098 	return (error);
   1099 }
   1100 
   1101 int
   1102 ugenpoll(dev, events, p)
   1103 	dev_t dev;
   1104 	int events;
   1105 	struct proc *p;
   1106 {
   1107 	struct ugen_softc *sc;
   1108 	struct ugen_endpoint *sce;
   1109 	int revents = 0;
   1110 	int s;
   1111 
   1112 	USB_GET_SC(ugen, UGENUNIT(dev), sc);
   1113 	if (sc->sc_dying)
   1114 		return (EIO);
   1115 
   1116 	/* XXX always IN */
   1117 	sce = &sc->sc_endpoints[UGENENDPOINT(dev)][IN];
   1118 	if (sce == NULL)
   1119 		return (EINVAL);
   1120 #ifdef DIAGNOSTIC
   1121 	if (!sce->edesc) {
   1122 		printf("ugenwrite: no edesc\n");
   1123 		return (EIO);
   1124 	}
   1125 	if (!sce->pipeh) {
   1126 		printf("ugenpoll: no pipe\n");
   1127 		return (EIO);
   1128 	}
   1129 #endif
   1130 	s = splusb();
   1131 	switch (sce->edesc->bmAttributes & UE_XFERTYPE) {
   1132 	case UE_INTERRUPT:
   1133 		if (events & (POLLIN | POLLRDNORM)) {
   1134 			if (sce->q.c_cc > 0)
   1135 				revents |= events & (POLLIN | POLLRDNORM);
   1136 			else
   1137 				selrecord(p, &sce->rsel);
   1138 		}
   1139 		break;
   1140 	case UE_BULK:
   1141 		/*
   1142 		 * We have no easy way of determining if a read will
   1143 		 * yield any data or a write will happen.
   1144 		 * Pretend they will.
   1145 		 */
   1146 		revents |= events &
   1147 			   (POLLIN | POLLRDNORM | POLLOUT | POLLWRNORM);
   1148 		break;
   1149 	default:
   1150 		break;
   1151 	}
   1152 	splx(s);
   1153 	return (revents);
   1154 }
   1155 
   1156 #if defined(__FreeBSD__)
   1157 DEV_DRIVER_MODULE(ugen, uhub, ugen_driver, ugen_devclass, ugen_cdevsw, usbd_driver_load, 0);
   1158 #endif
   1159