Home | History | Annotate | Line # | Download | only in usb
ugen.c revision 1.31
      1 /*	$NetBSD: ugen.c,v 1.31 1999/12/18 23:22:54 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 			if (err) {
    331 				free(sce->ibuf, M_USBDEV);
    332 				clfree(&sce->q);
    333 				return (EIO);
    334 			}
    335 			DPRINTFN(5, ("ugenopen: interrupt open done\n"));
    336 			break;
    337 		case UE_BULK:
    338 			err = usbd_open_pipe(sce->iface,
    339 				  edesc->bEndpointAddress, 0, &sce->pipeh);
    340 			if (err)
    341 				return (EIO);
    342 			break;
    343 		case UE_CONTROL:
    344 		case UE_ISOCHRONOUS:
    345 			return (EINVAL);
    346 		}
    347 	}
    348 	sc->sc_is_open[endpt] = 1;
    349 	return (0);
    350 }
    351 
    352 int
    353 ugenclose(dev, flag, mode, p)
    354 	dev_t dev;
    355 	int flag;
    356 	int mode;
    357 	struct proc *p;
    358 {
    359 	int endpt = UGENENDPOINT(dev);
    360 	struct ugen_softc *sc;
    361 	struct ugen_endpoint *sce;
    362 	int dir;
    363 
    364 	USB_GET_SC(ugen, UGENUNIT(dev), sc);
    365 
    366 	DPRINTFN(5, ("ugenclose: flag=%d, mode=%d, unit=%d, endpt=%d\n",
    367 		     flag, mode, UGENUNIT(dev), endpt));
    368 
    369 #ifdef DIAGNOSTIC
    370 	if (!sc->sc_is_open[endpt]) {
    371 		printf("ugenclose: not open\n");
    372 		return (EINVAL);
    373 	}
    374 #endif
    375 
    376 	if (endpt == USB_CONTROL_ENDPOINT) {
    377 		DPRINTFN(5, ("ugenclose: close control\n"));
    378 		sc->sc_is_open[endpt] = 0;
    379 		return (0);
    380 	}
    381 
    382 	for (dir = OUT; dir <= IN; dir++) {
    383 		if (!(flag & (dir == OUT ? FWRITE : FREAD)))
    384 			continue;
    385 		sce = &sc->sc_endpoints[endpt][dir];
    386 		if (sce == NULL || sce->pipeh == NULL)
    387 			continue;
    388 		DPRINTFN(5, ("ugenclose: endpt=%d dir=%d sce=%p\n",
    389 			     endpt, dir, sce));
    390 
    391 		usbd_abort_pipe(sce->pipeh);
    392 		usbd_close_pipe(sce->pipeh);
    393 		sce->pipeh = NULL;
    394 
    395 		if (sce->ibuf != NULL) {
    396 			free(sce->ibuf, M_USBDEV);
    397 			sce->ibuf = NULL;
    398 			clfree(&sce->q);
    399 
    400 		}
    401 	}
    402 	sc->sc_is_open[endpt] = 0;
    403 
    404 	return (0);
    405 }
    406 
    407 static int
    408 ugen_do_read(sc, endpt, uio, flag)
    409 	struct ugen_softc *sc;
    410 	int endpt;
    411 	struct uio *uio;
    412 	int flag;
    413 {
    414 	struct ugen_endpoint *sce = &sc->sc_endpoints[endpt][IN];
    415 	u_int32_t n, tn;
    416 	char buf[UGEN_BBSIZE];
    417 	usbd_xfer_handle xfer;
    418 	usbd_status err;
    419 	int s;
    420 	int error = 0;
    421 	u_char buffer[UGEN_CHUNK];
    422 
    423 #ifdef __NetBSD__
    424 	DPRINTFN(5, ("ugenread: %d:%d\n", sc->sc_dev.dv_unit, endpt));
    425 #endif
    426 
    427 	if (sc->sc_dying)
    428 		return (EIO);
    429 
    430 	if (endpt == USB_CONTROL_ENDPOINT)
    431 		return (ENODEV);
    432 
    433 #ifdef DIAGNOSTIC
    434 	if (sce->edesc == NULL) {
    435 		printf("ugenread: no edesc\n");
    436 		return (EIO);
    437 	}
    438 	if (sce->pipeh == NULL) {
    439 		printf("ugenread: no pipe\n");
    440 		return (EIO);
    441 	}
    442 #endif
    443 
    444 	switch (sce->edesc->bmAttributes & UE_XFERTYPE) {
    445 	case UE_INTERRUPT:
    446 		/* Block until activity occured. */
    447 		s = splusb();
    448 		while (sce->q.c_cc == 0) {
    449 			if (flag & IO_NDELAY) {
    450 				splx(s);
    451 				return (EWOULDBLOCK);
    452 			}
    453 			sce->state |= UGEN_ASLP;
    454 			DPRINTFN(5, ("ugenread: sleep on %p\n", sc));
    455 			error = tsleep(sce, PZERO | PCATCH, "ugenri", 0);
    456 			DPRINTFN(5, ("ugenread: woke, error=%d\n", error));
    457 			if (sc->sc_dying)
    458 				error = EIO;
    459 			if (error) {
    460 				sce->state &= ~UGEN_ASLP;
    461 				break;
    462 			}
    463 		}
    464 		splx(s);
    465 
    466 		/* Transfer as many chunks as possible. */
    467 		while (sce->q.c_cc > 0 && uio->uio_resid > 0 && !error) {
    468 			n = min(sce->q.c_cc, uio->uio_resid);
    469 			if (n > sizeof(buffer))
    470 				n = sizeof(buffer);
    471 
    472 			/* Remove a small chunk from the input queue. */
    473 			q_to_b(&sce->q, buffer, n);
    474 			DPRINTFN(5, ("ugenread: got %d chars\n", n));
    475 
    476 			/* Copy the data to the user process. */
    477 			error = uiomove(buffer, n, uio);
    478 			if (error)
    479 				break;
    480 		}
    481 		break;
    482 	case UE_BULK:
    483 		xfer = usbd_alloc_xfer(sc->sc_udev);
    484 		if (xfer == 0)
    485 			return (ENOMEM);
    486 		while ((n = min(UGEN_BBSIZE, uio->uio_resid)) != 0) {
    487 			DPRINTFN(1, ("ugenread: start transfer %d bytes\n",n));
    488 			tn = n;
    489 			err = usbd_bulk_transfer(
    490 				  xfer, sce->pipeh,
    491 				  sce->state & UGEN_SHORT_OK ?
    492 				      USBD_SHORT_XFER_OK : 0,
    493 				  sce->timeout, buf, &tn, "ugenrb");
    494 			if (err) {
    495 				if (err == USBD_INTERRUPTED)
    496 					error = EINTR;
    497 				else if (err == USBD_TIMEOUT)
    498 					error = ETIMEDOUT;
    499 				else
    500 					error = EIO;
    501 				break;
    502 			}
    503 			DPRINTFN(1, ("ugenread: got %d bytes\n", tn));
    504 			error = uiomove(buf, tn, uio);
    505 			if (error || tn < n)
    506 				break;
    507 		}
    508 		usbd_free_xfer(xfer);
    509 		break;
    510 	default:
    511 		return (ENXIO);
    512 	}
    513 	return (error);
    514 }
    515 
    516 int
    517 ugenread(dev, uio, flag)
    518 	dev_t dev;
    519 	struct uio *uio;
    520 	int flag;
    521 {
    522 	int endpt = UGENENDPOINT(dev);
    523 	struct ugen_softc *sc;
    524 	int error;
    525 
    526 	USB_GET_SC(ugen, UGENUNIT(dev), sc);
    527 
    528 	sc->sc_refcnt++;
    529 	error = ugen_do_read(sc, endpt, uio, flag);
    530 	if (--sc->sc_refcnt < 0)
    531 		usb_detach_wakeup(USBDEV(sc->sc_dev));
    532 	return (error);
    533 }
    534 
    535 static int
    536 ugen_do_write(sc, endpt, uio, flag)
    537 	struct ugen_softc *sc;
    538 	int endpt;
    539 	struct uio *uio;
    540 	int flag;
    541 {
    542 	struct ugen_endpoint *sce = &sc->sc_endpoints[endpt][OUT];
    543 	u_int32_t n;
    544 	int error = 0;
    545 	char buf[UGEN_BBSIZE];
    546 	usbd_xfer_handle xfer;
    547 	usbd_status err;
    548 
    549 	DPRINTFN(5, ("%s: ugenwrite: %d\n", USBDEVNAME(sc->sc_dev), endpt));
    550 
    551 	if (sc->sc_dying)
    552 		return (EIO);
    553 
    554 	if (endpt == USB_CONTROL_ENDPOINT)
    555 		return (ENODEV);
    556 
    557 #ifdef DIAGNOSTIC
    558 	if (sce->edesc == NULL) {
    559 		printf("ugenwrite: no edesc\n");
    560 		return (EIO);
    561 	}
    562 	if (sce->pipeh == NULL) {
    563 		printf("ugenwrite: no pipe\n");
    564 		return (EIO);
    565 	}
    566 #endif
    567 
    568 	switch (sce->edesc->bmAttributes & UE_XFERTYPE) {
    569 	case UE_BULK:
    570 		xfer = usbd_alloc_xfer(sc->sc_udev);
    571 		if (xfer == 0)
    572 			return (EIO);
    573 		while ((n = min(UGEN_BBSIZE, uio->uio_resid)) != 0) {
    574 			error = uiomove(buf, n, uio);
    575 			if (error)
    576 				break;
    577 			DPRINTFN(1, ("ugenwrite: transfer %d bytes\n", n));
    578 			err = usbd_bulk_transfer(xfer, sce->pipeh, 0,
    579 				  sce->timeout, buf, &n,"ugenwb");
    580 			if (err) {
    581 				if (err == USBD_INTERRUPTED)
    582 					error = EINTR;
    583 				else
    584 					error = EIO;
    585 				break;
    586 			}
    587 		}
    588 		usbd_free_xfer(xfer);
    589 		break;
    590 	default:
    591 		return (ENXIO);
    592 	}
    593 	return (error);
    594 }
    595 
    596 int
    597 ugenwrite(dev, uio, flag)
    598 	dev_t dev;
    599 	struct uio *uio;
    600 	int flag;
    601 {
    602 	int endpt = UGENENDPOINT(dev);
    603 	struct ugen_softc *sc;
    604 	int error;
    605 
    606 	USB_GET_SC(ugen, UGENUNIT(dev), sc);
    607 
    608 	sc->sc_refcnt++;
    609 	error = ugen_do_write(sc, endpt, uio, flag);
    610 	if (--sc->sc_refcnt < 0)
    611 		usb_detach_wakeup(USBDEV(sc->sc_dev));
    612 	return (error);
    613 }
    614 
    615 #if defined(__NetBSD__) || defined(__OpenBSD__)
    616 int
    617 ugen_activate(self, act)
    618 	device_ptr_t self;
    619 	enum devact act;
    620 {
    621 	struct ugen_softc *sc = (struct ugen_softc *)self;
    622 
    623 	switch (act) {
    624 	case DVACT_ACTIVATE:
    625 		return (EOPNOTSUPP);
    626 		break;
    627 
    628 	case DVACT_DEACTIVATE:
    629 		sc->sc_dying = 1;
    630 		break;
    631 	}
    632 	return (0);
    633 }
    634 #endif
    635 
    636 USB_DETACH(ugen)
    637 {
    638 	USB_DETACH_START(ugen, sc);
    639 	struct ugen_endpoint *sce;
    640 	int i, dir;
    641 	int s;
    642 #if defined(__NetBSD__) || defined(__OpenBSD__)
    643 	int maj, mn;
    644 
    645 	DPRINTF(("ugen_detach: sc=%p flags=%d\n", sc, flags));
    646 #elif defined(__FreeBSD__)
    647 	DPRINTF(("ugen_detach: sc=%p\n", sc));
    648 #endif
    649 
    650 	sc->sc_dying = 1;
    651 	/* Abort all pipes.  Causes processes waiting for transfer to wake. */
    652 	for (i = 0; i < USB_MAX_ENDPOINTS; i++) {
    653 		for (dir = OUT; dir <= IN; dir++) {
    654 			sce = &sc->sc_endpoints[i][dir];
    655 			if (sce && sce->pipeh)
    656 				usbd_abort_pipe(sce->pipeh);
    657 		}
    658 	}
    659 
    660 	s = splusb();
    661 	if (--sc->sc_refcnt >= 0) {
    662 		/* Wake everyone */
    663 		for (i = 0; i < USB_MAX_ENDPOINTS; i++)
    664 			wakeup(&sc->sc_endpoints[i][IN]);
    665 		/* Wait for processes to go away. */
    666 		usb_detach_wait(USBDEV(sc->sc_dev));
    667 	}
    668 	splx(s);
    669 
    670 #if defined(__NetBSD__) || defined(__OpenBSD__)
    671 	/* locate the major number */
    672 	for (maj = 0; maj < nchrdev; maj++)
    673 		if (cdevsw[maj].d_open == ugenopen)
    674 			break;
    675 
    676 	/* Nuke the vnodes for any open instances (calls close). */
    677 	mn = self->dv_unit * USB_MAX_ENDPOINTS;
    678 	vdevgone(maj, mn, mn + USB_MAX_ENDPOINTS - 1, VCHR);
    679 #elif defined(__FreeBSD__)
    680 	/* XXX not implemented yet */
    681 #endif
    682 
    683 	return (0);
    684 }
    685 
    686 static void
    687 ugenintr(xfer, addr, status)
    688 	usbd_xfer_handle xfer;
    689 	usbd_private_handle addr;
    690 	usbd_status status;
    691 {
    692 	struct ugen_endpoint *sce = addr;
    693 	/*struct ugen_softc *sc = sce->sc;*/
    694 	u_int32_t count;
    695 	u_char *ibuf;
    696 
    697 	if (status == USBD_CANCELLED)
    698 		return;
    699 
    700 	if (status != USBD_NORMAL_COMPLETION) {
    701 		DPRINTF(("ugenintr: status=%d\n", status));
    702 		usbd_clear_endpoint_stall_async(sce->pipeh);
    703 		return;
    704 	}
    705 
    706 	usbd_get_xfer_status(xfer, 0, 0, &count, 0);
    707 	ibuf = sce->ibuf;
    708 
    709 	DPRINTFN(5, ("ugenintr: xfer=%p status=%d count=%d\n",
    710 		     xfer, status, count));
    711 	DPRINTFN(5, ("          data = %02x %02x %02x\n",
    712 		     ibuf[0], ibuf[1], ibuf[2]));
    713 
    714 	(void)b_to_q(ibuf, count, &sce->q);
    715 
    716 	if (sce->state & UGEN_ASLP) {
    717 		sce->state &= ~UGEN_ASLP;
    718 		DPRINTFN(5, ("ugen_intr: waking %p\n", sce));
    719 		wakeup(sce);
    720 	}
    721 	selwakeup(&sce->rsel);
    722 }
    723 
    724 static usbd_status
    725 ugen_set_interface(sc, ifaceidx, altno)
    726 	struct ugen_softc *sc;
    727 	int ifaceidx, altno;
    728 {
    729 	usbd_interface_handle iface;
    730 	usb_endpoint_descriptor_t *ed;
    731 	usbd_status err;
    732 	struct ugen_endpoint *sce;
    733 	u_int8_t niface, nendpt, endptno, endpt;
    734 	int dir;
    735 
    736 	DPRINTFN(15, ("ugen_set_interface %d %d\n", ifaceidx, altno));
    737 
    738 	err = usbd_interface_count(sc->sc_udev, &niface);
    739 	if (err)
    740 		return (err);
    741 	if (ifaceidx < 0 || ifaceidx >= niface)
    742 		return (USBD_INVAL);
    743 
    744 	err = usbd_device2interface_handle(sc->sc_udev, ifaceidx, &iface);
    745 	if (err)
    746 		return (err);
    747 	err = usbd_endpoint_count(iface, &nendpt);
    748 	if (err)
    749 		return (err);
    750 	for (endptno = 0; endptno < nendpt; endptno++) {
    751 		ed = usbd_interface2endpoint_descriptor(iface,endptno);
    752 		endpt = ed->bEndpointAddress;
    753 		dir = UE_GET_DIR(endpt) == UE_DIR_IN ? IN : OUT;
    754 		sce = &sc->sc_endpoints[UE_GET_ADDR(endpt)][dir];
    755 		sce->sc = 0;
    756 		sce->edesc = 0;
    757 		sce->iface = 0;
    758 	}
    759 
    760 	/* change setting */
    761 	err = usbd_set_interface(iface, altno);
    762 	if (err)
    763 		return (err);
    764 
    765 	err = usbd_endpoint_count(iface, &nendpt);
    766 	if (err)
    767 		return (err);
    768 	for (endptno = 0; endptno < nendpt; endptno++) {
    769 		ed = usbd_interface2endpoint_descriptor(iface,endptno);
    770 		endpt = ed->bEndpointAddress;
    771 		dir = UE_GET_DIR(endpt) == UE_DIR_IN ? IN : OUT;
    772 		sce = &sc->sc_endpoints[UE_GET_ADDR(endpt)][dir];
    773 		sce->sc = sc;
    774 		sce->edesc = ed;
    775 		sce->iface = iface;
    776 	}
    777 	return (0);
    778 }
    779 
    780 /* Retrieve a complete descriptor for a certain device and index. */
    781 static usb_config_descriptor_t *
    782 ugen_get_cdesc(sc, index, lenp)
    783 	struct ugen_softc *sc;
    784 	int index;
    785 	int *lenp;
    786 {
    787 	usb_config_descriptor_t *cdesc, *tdesc, cdescr;
    788 	int len;
    789 	usbd_status err;
    790 
    791 	if (index == USB_CURRENT_CONFIG_INDEX) {
    792 		tdesc = usbd_get_config_descriptor(sc->sc_udev);
    793 		len = UGETW(tdesc->wTotalLength);
    794 		if (lenp)
    795 			*lenp = len;
    796 		cdesc = malloc(len, M_TEMP, M_WAITOK);
    797 		memcpy(cdesc, tdesc, len);
    798 		DPRINTFN(5,("ugen_get_cdesc: current, len=%d\n", len));
    799 	} else {
    800 		err = usbd_get_config_desc(sc->sc_udev, index, &cdescr);
    801 		if (err)
    802 			return (0);
    803 		len = UGETW(cdescr.wTotalLength);
    804 		DPRINTFN(5,("ugen_get_cdesc: index=%d, len=%d\n", index, len));
    805 		if (lenp)
    806 			*lenp = len;
    807 		cdesc = malloc(len, M_TEMP, M_WAITOK);
    808 		err = usbd_get_config_desc_full(sc->sc_udev, index, cdesc,len);
    809 		if (err) {
    810 			free(cdesc, M_TEMP);
    811 			return (0);
    812 		}
    813 	}
    814 	return (cdesc);
    815 }
    816 
    817 static int
    818 ugen_get_alt_index(sc, ifaceidx)
    819 	struct ugen_softc *sc;
    820 	int ifaceidx;
    821 {
    822 	usbd_interface_handle iface;
    823 	usbd_status err;
    824 
    825 	err = usbd_device2interface_handle(sc->sc_udev, ifaceidx, &iface);
    826 	if (err)
    827 			return (-1);
    828 	return (usbd_get_interface_altindex(iface));
    829 }
    830 
    831 static int
    832 ugen_do_ioctl(sc, endpt, cmd, addr, flag, p)
    833 	struct ugen_softc *sc;
    834 	int endpt;
    835 	u_long cmd;
    836 	caddr_t addr;
    837 	int flag;
    838 	struct proc *p;
    839 {
    840 	struct ugen_endpoint *sce;
    841 	usbd_status err;
    842 	usbd_interface_handle iface;
    843 	struct usb_config_desc *cd;
    844 	usb_config_descriptor_t *cdesc;
    845 	struct usb_interface_desc *id;
    846 	usb_interface_descriptor_t *idesc;
    847 	struct usb_endpoint_desc *ed;
    848 	usb_endpoint_descriptor_t *edesc;
    849 	struct usb_alt_interface *ai;
    850 	struct usb_string_desc *si;
    851 	u_int8_t conf, alt;
    852 
    853 	DPRINTFN(5, ("ugenioctl: cmd=%08lx\n", cmd));
    854 	if (sc->sc_dying)
    855 		return (EIO);
    856 
    857 	switch (cmd) {
    858 	case FIONBIO:
    859 		/* All handled in the upper FS layer. */
    860 		return (0);
    861 	case USB_SET_SHORT_XFER:
    862 		/* This flag only affects read */
    863 		if (endpt == USB_CONTROL_ENDPOINT)
    864 			return (EINVAL);
    865 		sce = &sc->sc_endpoints[endpt][IN];
    866 		if (sce == NULL)
    867 			return (EINVAL);
    868 #ifdef DIAGNOSTIC
    869 		if (sce->pipeh == NULL) {
    870 			printf("ugenioctl: USB_SET_SHORT_XFER, no pipe\n");
    871 			return (EIO);
    872 		}
    873 #endif
    874 		if (*(int *)addr)
    875 			sce->state |= UGEN_SHORT_OK;
    876 		else
    877 			sce->state &= ~UGEN_SHORT_OK;
    878 		return (0);
    879 	case USB_SET_TIMEOUT:
    880 		sce = &sc->sc_endpoints[endpt][IN];
    881 		if (sce == NULL)
    882 			return (EINVAL);
    883 #ifdef DIAGNOSTIC
    884 		if (sce->pipeh == NULL) {
    885 			printf("ugenioctl: USB_SET_TIMEOUT, no pipe\n");
    886 			return (EIO);
    887 		}
    888 #endif
    889 		sce->timeout = *(int *)addr;
    890 		return (0);
    891 	default:
    892 		break;
    893 	}
    894 
    895 	if (endpt != USB_CONTROL_ENDPOINT)
    896 		return (EINVAL);
    897 
    898 	switch (cmd) {
    899 #ifdef UGEN_DEBUG
    900 	case USB_SETDEBUG:
    901 		ugendebug = *(int *)addr;
    902 		break;
    903 #endif
    904 	case USB_GET_CONFIG:
    905 		err = usbd_get_config(sc->sc_udev, &conf);
    906 		if (err)
    907 			return (EIO);
    908 		*(int *)addr = conf;
    909 		break;
    910 	case USB_SET_CONFIG:
    911 		if (!(flag & FWRITE))
    912 			return (EPERM);
    913 		err = ugen_set_config(sc, *(int *)addr);
    914 		if (err)
    915 			return (EIO);
    916 		break;
    917 	case USB_GET_ALTINTERFACE:
    918 		ai = (struct usb_alt_interface *)addr;
    919 		err = usbd_device2interface_handle(sc->sc_udev,
    920 			  ai->interface_index, &iface);
    921 		if (err)
    922 			return (EINVAL);
    923 		idesc = usbd_get_interface_descriptor(iface);
    924 		if (idesc == NULL)
    925 			return (EIO);
    926 		ai->alt_no = idesc->bAlternateSetting;
    927 		break;
    928 	case USB_SET_ALTINTERFACE:
    929 		if (!(flag & FWRITE))
    930 			return (EPERM);
    931 		ai = (struct usb_alt_interface *)addr;
    932 		err = usbd_device2interface_handle(sc->sc_udev,
    933 			  ai->interface_index, &iface);
    934 		if (err)
    935 			return (EINVAL);
    936 		err = ugen_set_interface(sc, ai->interface_index, ai->alt_no);
    937 		if (err)
    938 			return (EINVAL);
    939 		break;
    940 	case USB_GET_NO_ALT:
    941 		ai = (struct usb_alt_interface *)addr;
    942 		cdesc = ugen_get_cdesc(sc, ai->config_index, 0);
    943 		if (cdesc == NULL)
    944 			return (EINVAL);
    945 		idesc = usbd_find_idesc(cdesc, ai->interface_index, 0);
    946 		if (idesc == NULL) {
    947 			free(cdesc, M_TEMP);
    948 			return (EINVAL);
    949 		}
    950 		ai->alt_no = usbd_get_no_alts(cdesc, idesc->bInterfaceNumber);
    951 		free(cdesc, M_TEMP);
    952 		break;
    953 	case USB_GET_DEVICE_DESC:
    954 		*(usb_device_descriptor_t *)addr =
    955 			*usbd_get_device_descriptor(sc->sc_udev);
    956 		break;
    957 	case USB_GET_CONFIG_DESC:
    958 		cd = (struct usb_config_desc *)addr;
    959 		cdesc = ugen_get_cdesc(sc, cd->config_index, 0);
    960 		if (cdesc == NULL)
    961 			return (EINVAL);
    962 		cd->desc = *cdesc;
    963 		free(cdesc, M_TEMP);
    964 		break;
    965 	case USB_GET_INTERFACE_DESC:
    966 		id = (struct usb_interface_desc *)addr;
    967 		cdesc = ugen_get_cdesc(sc, id->config_index, 0);
    968 		if (cdesc == NULL)
    969 			return (EINVAL);
    970 		if (id->config_index == USB_CURRENT_CONFIG_INDEX &&
    971 		    id->alt_index == USB_CURRENT_ALT_INDEX)
    972 			alt = ugen_get_alt_index(sc, id->interface_index);
    973 		else
    974 			alt = id->alt_index;
    975 		idesc = usbd_find_idesc(cdesc, id->interface_index, alt);
    976 		if (idesc == NULL) {
    977 			free(cdesc, M_TEMP);
    978 			return (EINVAL);
    979 		}
    980 		id->desc = *idesc;
    981 		free(cdesc, M_TEMP);
    982 		break;
    983 	case USB_GET_ENDPOINT_DESC:
    984 		ed = (struct usb_endpoint_desc *)addr;
    985 		cdesc = ugen_get_cdesc(sc, ed->config_index, 0);
    986 		if (cdesc == NULL)
    987 			return (EINVAL);
    988 		if (ed->config_index == USB_CURRENT_CONFIG_INDEX &&
    989 		    ed->alt_index == USB_CURRENT_ALT_INDEX)
    990 			alt = ugen_get_alt_index(sc, ed->interface_index);
    991 		else
    992 			alt = ed->alt_index;
    993 		edesc = usbd_find_edesc(cdesc, ed->interface_index,
    994 					alt, ed->endpoint_index);
    995 		if (edesc == NULL) {
    996 			free(cdesc, M_TEMP);
    997 			return (EINVAL);
    998 		}
    999 		ed->desc = *edesc;
   1000 		free(cdesc, M_TEMP);
   1001 		break;
   1002 	case USB_GET_FULL_DESC:
   1003 	{
   1004 		int len;
   1005 		struct iovec iov;
   1006 		struct uio uio;
   1007 		struct usb_full_desc *fd = (struct usb_full_desc *)addr;
   1008 		int error;
   1009 
   1010 		cdesc = ugen_get_cdesc(sc, fd->config_index, &len);
   1011 		if (len > fd->size)
   1012 			len = fd->size;
   1013 		iov.iov_base = (caddr_t)fd->data;
   1014 		iov.iov_len = len;
   1015 		uio.uio_iov = &iov;
   1016 		uio.uio_iovcnt = 1;
   1017 		uio.uio_resid = len;
   1018 		uio.uio_offset = 0;
   1019 		uio.uio_segflg = UIO_USERSPACE;
   1020 		uio.uio_rw = UIO_READ;
   1021 		uio.uio_procp = p;
   1022 		error = uiomove((void *)cdesc, len, &uio);
   1023 		free(cdesc, M_TEMP);
   1024 		return (error);
   1025 	}
   1026 	case USB_GET_STRING_DESC:
   1027 		si = (struct usb_string_desc *)addr;
   1028 		err = usbd_get_string_desc(sc->sc_udev, si->string_index,
   1029 			  si->language_id, &si->desc);
   1030 		if (err)
   1031 			return (EINVAL);
   1032 		break;
   1033 	case USB_DO_REQUEST:
   1034 	{
   1035 		struct usb_ctl_request *ur = (void *)addr;
   1036 		int len = UGETW(ur->request.wLength);
   1037 		struct iovec iov;
   1038 		struct uio uio;
   1039 		void *ptr = 0;
   1040 		usbd_status err;
   1041 		int error = 0;
   1042 
   1043 		if (!(flag & FWRITE))
   1044 			return (EPERM);
   1045 		/* Avoid requests that would damage the bus integrity. */
   1046 		if ((ur->request.bmRequestType == UT_WRITE_DEVICE &&
   1047 		     ur->request.bRequest == UR_SET_ADDRESS) ||
   1048 		    (ur->request.bmRequestType == UT_WRITE_DEVICE &&
   1049 		     ur->request.bRequest == UR_SET_CONFIG) ||
   1050 		    (ur->request.bmRequestType == UT_WRITE_INTERFACE &&
   1051 		     ur->request.bRequest == UR_SET_INTERFACE))
   1052 			return (EINVAL);
   1053 
   1054 		if (len < 0 || len > 32767)
   1055 			return (EINVAL);
   1056 		if (len != 0) {
   1057 			iov.iov_base = (caddr_t)ur->data;
   1058 			iov.iov_len = len;
   1059 			uio.uio_iov = &iov;
   1060 			uio.uio_iovcnt = 1;
   1061 			uio.uio_resid = len;
   1062 			uio.uio_offset = 0;
   1063 			uio.uio_segflg = UIO_USERSPACE;
   1064 			uio.uio_rw =
   1065 				ur->request.bmRequestType & UT_READ ?
   1066 				UIO_READ : UIO_WRITE;
   1067 			uio.uio_procp = p;
   1068 			ptr = malloc(len, M_TEMP, M_WAITOK);
   1069 			if (uio.uio_rw == UIO_WRITE) {
   1070 				error = uiomove(ptr, len, &uio);
   1071 				if (error)
   1072 					goto ret;
   1073 			}
   1074 		}
   1075 		err = usbd_do_request_flags(sc->sc_udev, &ur->request,
   1076 			  ptr, ur->flags, &ur->actlen);
   1077 		if (err) {
   1078 			error = EIO;
   1079 			goto ret;
   1080 		}
   1081 		if (len != 0) {
   1082 			if (uio.uio_rw == UIO_READ) {
   1083 				error = uiomove(ptr, len, &uio);
   1084 				if (error)
   1085 					goto ret;
   1086 			}
   1087 		}
   1088 	ret:
   1089 		if (ptr)
   1090 			free(ptr, M_TEMP);
   1091 		return (error);
   1092 	}
   1093 	case USB_GET_DEVICEINFO:
   1094 		usbd_fill_deviceinfo(sc->sc_udev,
   1095 				     (struct usb_device_info *)addr);
   1096 		break;
   1097 	default:
   1098 		return (EINVAL);
   1099 	}
   1100 	return (0);
   1101 }
   1102 
   1103 int
   1104 ugenioctl(dev, cmd, addr, flag, p)
   1105 	dev_t dev;
   1106 	u_long cmd;
   1107 	caddr_t addr;
   1108 	int flag;
   1109 	struct proc *p;
   1110 {
   1111 	int endpt = UGENENDPOINT(dev);
   1112 	struct ugen_softc *sc;
   1113 	int error;
   1114 
   1115 	USB_GET_SC(ugen, UGENUNIT(dev), sc);
   1116 
   1117 	sc->sc_refcnt++;
   1118 	error = ugen_do_ioctl(sc, endpt, cmd, addr, flag, p);
   1119 	if (--sc->sc_refcnt < 0)
   1120 		usb_detach_wakeup(USBDEV(sc->sc_dev));
   1121 	return (error);
   1122 }
   1123 
   1124 int
   1125 ugenpoll(dev, events, p)
   1126 	dev_t dev;
   1127 	int events;
   1128 	struct proc *p;
   1129 {
   1130 	struct ugen_softc *sc;
   1131 	struct ugen_endpoint *sce;
   1132 	int revents = 0;
   1133 	int s;
   1134 
   1135 	USB_GET_SC(ugen, UGENUNIT(dev), sc);
   1136 
   1137 	if (sc->sc_dying)
   1138 		return (EIO);
   1139 
   1140 	/* XXX always IN */
   1141 	sce = &sc->sc_endpoints[UGENENDPOINT(dev)][IN];
   1142 	if (sce == NULL)
   1143 		return (EINVAL);
   1144 #ifdef DIAGNOSTIC
   1145 	if (!sce->edesc) {
   1146 		printf("ugenwrite: no edesc\n");
   1147 		return (EIO);
   1148 	}
   1149 	if (!sce->pipeh) {
   1150 		printf("ugenpoll: no pipe\n");
   1151 		return (EIO);
   1152 	}
   1153 #endif
   1154 	s = splusb();
   1155 	switch (sce->edesc->bmAttributes & UE_XFERTYPE) {
   1156 	case UE_INTERRUPT:
   1157 		if (events & (POLLIN | POLLRDNORM)) {
   1158 			if (sce->q.c_cc > 0)
   1159 				revents |= events & (POLLIN | POLLRDNORM);
   1160 			else
   1161 				selrecord(p, &sce->rsel);
   1162 		}
   1163 		break;
   1164 	case UE_BULK:
   1165 		/*
   1166 		 * We have no easy way of determining if a read will
   1167 		 * yield any data or a write will happen.
   1168 		 * Pretend they will.
   1169 		 */
   1170 		revents |= events &
   1171 			   (POLLIN | POLLRDNORM | POLLOUT | POLLWRNORM);
   1172 		break;
   1173 	default:
   1174 		break;
   1175 	}
   1176 	splx(s);
   1177 	return (revents);
   1178 }
   1179 
   1180 #if defined(__FreeBSD__)
   1181 DRIVER_MODULE(ugen, uhub, ugen_driver, ugen_devclass, usbd_driver_load, 0);
   1182 #endif
   1183