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