xref: /netbsd-src/sys/dev/usb/ugen.c (revision 53b02e147d4ed531c0d2a5ca9b3e8026ba3e99b5)
1 /*	$NetBSD: ugen.c,v 1.168 2021/09/26 01:16:09 thorpej Exp $	*/
2 
3 /*
4  * Copyright (c) 1998, 2004 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Lennart Augustsson (lennart@augustsson.net) at
9  * Carlstedt Research & Technology.
10  *
11  * Copyright (c) 2006 BBN Technologies Corp.  All rights reserved.
12  * Effort sponsored in part by the Defense Advanced Research Projects
13  * Agency (DARPA) and the Department of the Interior National Business
14  * Center under agreement number NBCHC050166.
15  *
16  * Redistribution and use in source and binary forms, with or without
17  * modification, are permitted provided that the following conditions
18  * are met:
19  * 1. Redistributions of source code must retain the above copyright
20  *    notice, this list of conditions and the following disclaimer.
21  * 2. Redistributions in binary form must reproduce the above copyright
22  *    notice, this list of conditions and the following disclaimer in the
23  *    documentation and/or other materials provided with the distribution.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
26  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
27  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
28  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
29  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
30  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
31  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
33  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
34  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35  * POSSIBILITY OF SUCH DAMAGE.
36  */
37 
38 
39 #include <sys/cdefs.h>
40 __KERNEL_RCSID(0, "$NetBSD: ugen.c,v 1.168 2021/09/26 01:16:09 thorpej Exp $");
41 
42 #ifdef _KERNEL_OPT
43 #include "opt_compat_netbsd.h"
44 #include "opt_usb.h"
45 #endif
46 
47 #include <sys/param.h>
48 #include <sys/systm.h>
49 #include <sys/kernel.h>
50 #include <sys/kmem.h>
51 #include <sys/device.h>
52 #include <sys/ioctl.h>
53 #include <sys/conf.h>
54 #include <sys/tty.h>
55 #include <sys/file.h>
56 #include <sys/select.h>
57 #include <sys/proc.h>
58 #include <sys/vnode.h>
59 #include <sys/poll.h>
60 #include <sys/compat_stub.h>
61 #include <sys/module.h>
62 #include <sys/rbtree.h>
63 
64 #include <dev/usb/usb.h>
65 #include <dev/usb/usbdi.h>
66 #include <dev/usb/usbdi_util.h>
67 
68 #include "ioconf.h"
69 
70 #ifdef UGEN_DEBUG
71 #define DPRINTF(x)	if (ugendebug) printf x
72 #define DPRINTFN(n,x)	if (ugendebug>(n)) printf x
73 int	ugendebug = 0;
74 #else
75 #define DPRINTF(x)
76 #define DPRINTFN(n,x)
77 #endif
78 
79 #define	UGEN_CHUNK	128	/* chunk size for read */
80 #define	UGEN_IBSIZE	1020	/* buffer size */
81 #define	UGEN_BBSIZE	1024
82 
83 #define UGEN_NISOREQS	4	/* number of outstanding xfer requests */
84 #define UGEN_NISORFRMS	8	/* number of transactions per req */
85 #define UGEN_NISOFRAMES	(UGEN_NISORFRMS * UGEN_NISOREQS)
86 
87 #define UGEN_BULK_RA_WB_BUFSIZE	16384		/* default buffer size */
88 #define UGEN_BULK_RA_WB_BUFMAX	(1 << 20)	/* maximum allowed buffer */
89 
90 struct isoreq {
91 	struct ugen_endpoint *sce;
92 	struct usbd_xfer *xfer;
93 	void *dmabuf;
94 	uint16_t sizes[UGEN_NISORFRMS];
95 };
96 
97 struct ugen_endpoint {
98 	struct ugen_softc *sc;
99 	usb_endpoint_descriptor_t *edesc;
100 	struct usbd_interface *iface;
101 	int state;
102 #define UGEN_SHORT_OK	0x04	/* short xfers are OK */
103 #define UGEN_BULK_RA	0x08	/* in bulk read-ahead mode */
104 #define UGEN_BULK_WB	0x10	/* in bulk write-behind mode */
105 #define UGEN_RA_WB_STOP	0x20	/* RA/WB xfer is stopped (buffer full/empty) */
106 	struct usbd_pipe *pipeh;
107 	struct clist q;
108 	u_char *ibuf;		/* start of buffer (circular for isoc) */
109 	u_char *fill;		/* location for input (isoc) */
110 	u_char *limit;		/* end of circular buffer (isoc) */
111 	u_char *cur;		/* current read location (isoc) */
112 	uint32_t timeout;
113 	uint32_t ra_wb_bufsize; /* requested size for RA/WB buffer */
114 	uint32_t ra_wb_reqsize; /* requested xfer length for RA/WB */
115 	uint32_t ra_wb_used;	 /* how much is in buffer */
116 	uint32_t ra_wb_xferlen; /* current xfer length for RA/WB */
117 	struct usbd_xfer *ra_wb_xfer;
118 	struct isoreq isoreqs[UGEN_NISOREQS];
119 	/* Keep these last; we don't overwrite them in ugen_set_config() */
120 #define UGEN_ENDPOINT_NONZERO_CRUFT	offsetof(struct ugen_endpoint, rsel)
121 	struct selinfo rsel;
122 	kcondvar_t cv;
123 };
124 
125 struct ugen_softc {
126 	device_t sc_dev;		/* base device */
127 	struct usbd_device *sc_udev;
128 	struct rb_node sc_node;
129 	unsigned sc_unit;
130 
131 	kmutex_t		sc_lock;
132 	kcondvar_t		sc_detach_cv;
133 
134 	char sc_is_open[USB_MAX_ENDPOINTS];
135 	struct ugen_endpoint sc_endpoints[USB_MAX_ENDPOINTS][2];
136 #define OUT 0
137 #define IN  1
138 
139 	int sc_refcnt;
140 	char sc_buffer[UGEN_BBSIZE];
141 	u_char sc_dying;
142 	u_char sc_attached;
143 };
144 
145 static struct {
146 	kmutex_t	lock;
147 	rb_tree_t	tree;
148 } ugenif __cacheline_aligned;
149 
150 static int
151 compare_ugen(void *cookie, const void *vsca, const void *vscb)
152 {
153 	const struct ugen_softc *sca = vsca;
154 	const struct ugen_softc *scb = vscb;
155 
156 	if (sca->sc_unit < scb->sc_unit)
157 		return -1;
158 	if (sca->sc_unit > scb->sc_unit)
159 		return +1;
160 	return 0;
161 }
162 
163 static int
164 compare_ugen_key(void *cookie, const void *vsc, const void *vk)
165 {
166 	const struct ugen_softc *sc = vsc;
167 	const unsigned *k = vk;
168 
169 	if (sc->sc_unit < *k)
170 		return -1;
171 	if (sc->sc_unit > *k)
172 		return +1;
173 	return 0;
174 }
175 
176 static const rb_tree_ops_t ugenif_tree_ops = {
177 	.rbto_compare_nodes = compare_ugen,
178 	.rbto_compare_key = compare_ugen_key,
179 	.rbto_node_offset = offsetof(struct ugen_softc, sc_node),
180 };
181 
182 static void
183 ugenif_get_unit(struct ugen_softc *sc)
184 {
185 	struct ugen_softc *sc0;
186 	unsigned i;
187 
188 	mutex_enter(&ugenif.lock);
189 	for (i = 0, sc0 = RB_TREE_MIN(&ugenif.tree);
190 	     sc0 != NULL && i == sc0->sc_unit;
191 	     i++, sc0 = RB_TREE_NEXT(&ugenif.tree, sc0))
192 		KASSERT(i < UINT_MAX);
193 	KASSERT(rb_tree_find_node(&ugenif.tree, &i) == NULL);
194 	sc->sc_unit = i;
195 	sc0 = rb_tree_insert_node(&ugenif.tree, sc);
196 	KASSERT(sc0 == sc);
197 	KASSERT(rb_tree_find_node(&ugenif.tree, &i) == sc);
198 	mutex_exit(&ugenif.lock);
199 }
200 
201 static void
202 ugenif_put_unit(struct ugen_softc *sc)
203 {
204 
205 	mutex_enter(&ugenif.lock);
206 	KASSERT(rb_tree_find_node(&ugenif.tree, &sc->sc_unit) == sc);
207 	rb_tree_remove_node(&ugenif.tree, sc);
208 	sc->sc_unit = -1;
209 	mutex_exit(&ugenif.lock);
210 }
211 
212 static struct ugen_softc *
213 ugenif_acquire(unsigned unit)
214 {
215 	struct ugen_softc *sc;
216 
217 	mutex_enter(&ugenif.lock);
218 	sc = rb_tree_find_node(&ugenif.tree, &unit);
219 	if (sc == NULL)
220 		goto out;
221 	mutex_enter(&sc->sc_lock);
222 	if (sc->sc_dying) {
223 		mutex_exit(&sc->sc_lock);
224 		sc = NULL;
225 		goto out;
226 	}
227 	KASSERT(sc->sc_refcnt < INT_MAX);
228 	sc->sc_refcnt++;
229 	mutex_exit(&sc->sc_lock);
230 out:	mutex_exit(&ugenif.lock);
231 
232 	return sc;
233 }
234 
235 static void
236 ugenif_release(struct ugen_softc *sc)
237 {
238 
239 	mutex_enter(&sc->sc_lock);
240 	if (--sc->sc_refcnt < 0)
241 		cv_broadcast(&sc->sc_detach_cv);
242 	mutex_exit(&sc->sc_lock);
243 }
244 
245 static dev_type_open(ugenopen);
246 static dev_type_close(ugenclose);
247 static dev_type_read(ugenread);
248 static dev_type_write(ugenwrite);
249 static dev_type_ioctl(ugenioctl);
250 static dev_type_poll(ugenpoll);
251 static dev_type_kqfilter(ugenkqfilter);
252 
253 const struct cdevsw ugen_cdevsw = {
254 	.d_open = ugenopen,
255 	.d_close = ugenclose,
256 	.d_read = ugenread,
257 	.d_write = ugenwrite,
258 	.d_ioctl = ugenioctl,
259 	.d_stop = nostop,
260 	.d_tty = notty,
261 	.d_poll = ugenpoll,
262 	.d_mmap = nommap,
263 	.d_kqfilter = ugenkqfilter,
264 	.d_discard = nodiscard,
265 	.d_flag = D_OTHER,
266 };
267 
268 Static void ugenintr(struct usbd_xfer *, void *,
269 		     usbd_status);
270 Static void ugen_isoc_rintr(struct usbd_xfer *, void *,
271 			    usbd_status);
272 Static void ugen_bulkra_intr(struct usbd_xfer *, void *,
273 			     usbd_status);
274 Static void ugen_bulkwb_intr(struct usbd_xfer *, void *,
275 			     usbd_status);
276 Static int ugen_do_read(struct ugen_softc *, int, struct uio *, int);
277 Static int ugen_do_write(struct ugen_softc *, int, struct uio *, int);
278 Static int ugen_do_ioctl(struct ugen_softc *, int, u_long,
279 			 void *, int, struct lwp *);
280 Static int ugen_set_config(struct ugen_softc *, int, int);
281 Static usb_config_descriptor_t *ugen_get_cdesc(struct ugen_softc *,
282 					       int, int *);
283 Static usbd_status ugen_set_interface(struct ugen_softc *, int, int);
284 Static int ugen_get_alt_index(struct ugen_softc *, int);
285 Static void ugen_clear_endpoints(struct ugen_softc *);
286 
287 #define UGENUNIT(n) ((minor(n) >> 4) & 0xf)
288 #define UGENENDPOINT(n) (minor(n) & 0xf)
289 #define UGENDEV(u, e) (makedev(0, ((u) << 4) | (e)))
290 
291 static int	ugenif_match(device_t, cfdata_t, void *);
292 static void	ugenif_attach(device_t, device_t, void *);
293 static int	ugen_match(device_t, cfdata_t, void *);
294 static void	ugen_attach(device_t, device_t, void *);
295 static int	ugen_detach(device_t, int);
296 static int	ugen_activate(device_t, enum devact);
297 
298 CFATTACH_DECL_NEW(ugen, sizeof(struct ugen_softc), ugen_match,
299     ugen_attach, ugen_detach, ugen_activate);
300 CFATTACH_DECL_NEW(ugenif, sizeof(struct ugen_softc), ugenif_match,
301     ugenif_attach, ugen_detach, ugen_activate);
302 
303 /* toggle to control attach priority. -1 means "let autoconf decide" */
304 int ugen_override = -1;
305 
306 static int
307 ugen_match(device_t parent, cfdata_t match, void *aux)
308 {
309 	struct usb_attach_arg *uaa = aux;
310 	int override;
311 
312 	if (ugen_override != -1)
313 		override = ugen_override;
314 	else
315 		override = match->cf_flags & 1;
316 
317 	if (override)
318 		return UMATCH_HIGHEST;
319 	else if (uaa->uaa_usegeneric)
320 		return UMATCH_GENERIC;
321 	else
322 		return UMATCH_NONE;
323 }
324 
325 static int
326 ugenif_match(device_t parent, cfdata_t match, void *aux)
327 {
328 	/* Assume that they knew what they configured! (see ugenif(4)) */
329 	return UMATCH_HIGHEST;
330 }
331 
332 static void
333 ugen_attach(device_t parent, device_t self, void *aux)
334 {
335 	struct usb_attach_arg *uaa = aux;
336 	struct usbif_attach_arg uiaa;
337 
338 	memset(&uiaa, 0, sizeof(uiaa));
339 	uiaa.uiaa_port = uaa->uaa_port;
340 	uiaa.uiaa_vendor = uaa->uaa_vendor;
341 	uiaa.uiaa_product = uaa->uaa_product;
342 	uiaa.uiaa_release = uaa->uaa_release;
343 	uiaa.uiaa_device = uaa->uaa_device;
344 	uiaa.uiaa_configno = -1;
345 	uiaa.uiaa_ifaceno = -1;
346 
347 	ugenif_attach(parent, self, &uiaa);
348 }
349 
350 static void
351 ugenif_attach(device_t parent, device_t self, void *aux)
352 {
353 	struct ugen_softc *sc = device_private(self);
354 	struct usbif_attach_arg *uiaa = aux;
355 	struct usbd_device *udev;
356 	char *devinfop;
357 	usbd_status err;
358 	int i, dir, conf;
359 
360 	aprint_naive("\n");
361 	aprint_normal("\n");
362 
363 	mutex_init(&sc->sc_lock, MUTEX_DEFAULT, IPL_SOFTUSB);
364 	cv_init(&sc->sc_detach_cv, "ugendet");
365 
366 	devinfop = usbd_devinfo_alloc(uiaa->uiaa_device, 0);
367 	aprint_normal_dev(self, "%s\n", devinfop);
368 	usbd_devinfo_free(devinfop);
369 
370 	sc->sc_dev = self;
371 	sc->sc_udev = udev = uiaa->uiaa_device;
372 
373 	for (i = 0; i < USB_MAX_ENDPOINTS; i++) {
374 		for (dir = OUT; dir <= IN; dir++) {
375 			struct ugen_endpoint *sce;
376 
377 			sce = &sc->sc_endpoints[i][dir];
378 			selinit(&sce->rsel);
379 			cv_init(&sce->cv, "ugensce");
380 		}
381 	}
382 
383 	if (!pmf_device_register(self, NULL, NULL))
384 		aprint_error_dev(self, "couldn't establish power handler\n");
385 
386 	if (uiaa->uiaa_ifaceno < 0) {
387 		/*
388 		 * If we attach the whole device,
389 		 * set configuration index 0, the default one.
390 		 */
391 		err = usbd_set_config_index(udev, 0, 0);
392 		if (err) {
393 			aprint_error_dev(self,
394 			    "setting configuration index 0 failed\n");
395 			return;
396 		}
397 	}
398 
399 	/* Get current configuration */
400 	conf = usbd_get_config_descriptor(udev)->bConfigurationValue;
401 
402 	/* Set up all the local state for this configuration. */
403 	err = ugen_set_config(sc, conf, uiaa->uiaa_ifaceno < 0);
404 	if (err) {
405 		aprint_error_dev(self, "setting configuration %d failed\n",
406 		    conf);
407 		return;
408 	}
409 
410 	ugenif_get_unit(sc);
411 	usbd_add_drv_event(USB_EVENT_DRIVER_ATTACH, sc->sc_udev, sc->sc_dev);
412 	sc->sc_attached = 1;
413 }
414 
415 Static void
416 ugen_clear_endpoints(struct ugen_softc *sc)
417 {
418 
419 	/* Clear out the old info, but leave the selinfo and cv initialised. */
420 	for (int i = 0; i < USB_MAX_ENDPOINTS; i++) {
421 		for (int dir = OUT; dir <= IN; dir++) {
422 			struct ugen_endpoint *sce = &sc->sc_endpoints[i][dir];
423 			memset(sce, 0, UGEN_ENDPOINT_NONZERO_CRUFT);
424 		}
425 	}
426 }
427 
428 Static int
429 ugen_set_config(struct ugen_softc *sc, int configno, int chkopen)
430 {
431 	struct usbd_device *dev = sc->sc_udev;
432 	usb_config_descriptor_t *cdesc;
433 	struct usbd_interface *iface;
434 	usb_endpoint_descriptor_t *ed;
435 	struct ugen_endpoint *sce;
436 	uint8_t niface, nendpt;
437 	int ifaceno, endptno, endpt;
438 	usbd_status err;
439 	int dir;
440 
441 	DPRINTFN(1,("ugen_set_config: %s to configno %d, sc=%p\n",
442 		    device_xname(sc->sc_dev), configno, sc));
443 
444 	KASSERT(KERNEL_LOCKED_P()); /* sc_is_open */
445 
446 	if (chkopen) {
447 		/*
448 		 * We start at 1, not 0, because we don't care whether the
449 		 * control endpoint is open or not. It is always present.
450 		 */
451 		for (endptno = 1; endptno < USB_MAX_ENDPOINTS; endptno++)
452 			if (sc->sc_is_open[endptno]) {
453 				DPRINTFN(1,
454 				     ("ugen_set_config: %s - endpoint %d is open\n",
455 				      device_xname(sc->sc_dev), endptno));
456 				return USBD_IN_USE;
457 			}
458 
459 		/* Prevent opening while we're setting the config.  */
460 		for (endptno = 1; endptno < USB_MAX_ENDPOINTS; endptno++) {
461 			KASSERT(!sc->sc_is_open[endptno]);
462 			sc->sc_is_open[endptno] = 1;
463 		}
464 	}
465 
466 	/* Avoid setting the current value. */
467 	cdesc = usbd_get_config_descriptor(dev);
468 	if (!cdesc || cdesc->bConfigurationValue != configno) {
469 		err = usbd_set_config_no(dev, configno, 1);
470 		if (err)
471 			goto out;
472 	}
473 
474 	ugen_clear_endpoints(sc);
475 
476 	err = usbd_interface_count(dev, &niface);
477 	if (err)
478 		goto out;
479 
480 	for (ifaceno = 0; ifaceno < niface; ifaceno++) {
481 		DPRINTFN(1,("ugen_set_config: ifaceno %d\n", ifaceno));
482 		err = usbd_device2interface_handle(dev, ifaceno, &iface);
483 		if (err)
484 			goto out;
485 		err = usbd_endpoint_count(iface, &nendpt);
486 		if (err)
487 			goto out;
488 		for (endptno = 0; endptno < nendpt; endptno++) {
489 			ed = usbd_interface2endpoint_descriptor(iface,endptno);
490 			KASSERT(ed != NULL);
491 			endpt = ed->bEndpointAddress;
492 			dir = UE_GET_DIR(endpt) == UE_DIR_IN ? IN : OUT;
493 			sce = &sc->sc_endpoints[UE_GET_ADDR(endpt)][dir];
494 			DPRINTFN(1,("ugen_set_config: endptno %d, endpt=0x%02x"
495 				    "(%d,%d), sce=%p\n",
496 				    endptno, endpt, UE_GET_ADDR(endpt),
497 				    UE_GET_DIR(endpt), sce));
498 			sce->sc = sc;
499 			sce->edesc = ed;
500 			sce->iface = iface;
501 		}
502 	}
503 	err = USBD_NORMAL_COMPLETION;
504 
505 out:	if (chkopen) {
506 		/*
507 		 * Allow open again now that we're done trying to set
508 		 * the config.
509 		 */
510 		for (endptno = 1; endptno < USB_MAX_ENDPOINTS; endptno++) {
511 			KASSERT(sc->sc_is_open[endptno]);
512 			sc->sc_is_open[endptno] = 0;
513 		}
514 	}
515 	return err;
516 }
517 
518 static int
519 ugenopen(dev_t dev, int flag, int mode, struct lwp *l)
520 {
521 	struct ugen_softc *sc;
522 	int unit = UGENUNIT(dev);
523 	int endpt = UGENENDPOINT(dev);
524 	usb_endpoint_descriptor_t *edesc;
525 	struct ugen_endpoint *sce;
526 	int dir, isize;
527 	usbd_status err;
528 	struct usbd_xfer *xfer;
529 	int i, j;
530 	int error;
531 	int opened;
532 
533 	KASSERT(KERNEL_LOCKED_P()); /* sc_is_open */
534 
535 	if ((sc = ugenif_acquire(unit)) == NULL)
536 		return ENXIO;
537 
538 	DPRINTFN(5, ("ugenopen: flag=%d, mode=%d, unit=%d endpt=%d\n",
539 		     flag, mode, unit, endpt));
540 
541 	/* The control endpoint allows multiple opens. */
542 	if (endpt == USB_CONTROL_ENDPOINT) {
543 		opened = sc->sc_is_open[USB_CONTROL_ENDPOINT] = 1;
544 		error = 0;
545 		goto out;
546 	}
547 
548 	if (sc->sc_is_open[endpt]) {
549 		error = EBUSY;
550 		goto out;
551 	}
552 	opened = sc->sc_is_open[endpt] = 1;
553 
554 	/* Make sure there are pipes for all directions. */
555 	for (dir = OUT; dir <= IN; dir++) {
556 		if (flag & (dir == OUT ? FWRITE : FREAD)) {
557 			sce = &sc->sc_endpoints[endpt][dir];
558 			if (sce->edesc == NULL) {
559 				error = ENXIO;
560 				goto out;
561 			}
562 		}
563 	}
564 
565 	/* Actually open the pipes. */
566 	/* XXX Should back out properly if it fails. */
567 	for (dir = OUT; dir <= IN; dir++) {
568 		if (!(flag & (dir == OUT ? FWRITE : FREAD)))
569 			continue;
570 		sce = &sc->sc_endpoints[endpt][dir];
571 		sce->state = 0;
572 		sce->timeout = USBD_NO_TIMEOUT;
573 		DPRINTFN(5, ("ugenopen: sc=%p, endpt=%d, dir=%d, sce=%p\n",
574 			     sc, endpt, dir, sce));
575 		edesc = sce->edesc;
576 		switch (edesc->bmAttributes & UE_XFERTYPE) {
577 		case UE_INTERRUPT:
578 			if (dir == OUT) {
579 				err = usbd_open_pipe(sce->iface,
580 				    edesc->bEndpointAddress, 0, &sce->pipeh);
581 				if (err) {
582 					error = EIO;
583 					goto out;
584 				}
585 				break;
586 			}
587 			isize = UGETW(edesc->wMaxPacketSize);
588 			if (isize == 0) {	/* shouldn't happen */
589 				error = EINVAL;
590 				goto out;
591 			}
592 			sce->ibuf = kmem_alloc(isize, KM_SLEEP);
593 			DPRINTFN(5, ("ugenopen: intr endpt=%d,isize=%d\n",
594 				     endpt, isize));
595 			if (clalloc(&sce->q, UGEN_IBSIZE, 0) == -1) {
596 				kmem_free(sce->ibuf, isize);
597 				sce->ibuf = NULL;
598 				error = ENOMEM;
599 				goto out;
600 			}
601 			err = usbd_open_pipe_intr(sce->iface,
602 				  edesc->bEndpointAddress,
603 				  USBD_SHORT_XFER_OK, &sce->pipeh, sce,
604 				  sce->ibuf, isize, ugenintr,
605 				  USBD_DEFAULT_INTERVAL);
606 			if (err) {
607 				clfree(&sce->q);
608 				kmem_free(sce->ibuf, isize);
609 				sce->ibuf = NULL;
610 				error = EIO;
611 				goto out;
612 			}
613 			DPRINTFN(5, ("ugenopen: interrupt open done\n"));
614 			break;
615 		case UE_BULK:
616 			err = usbd_open_pipe(sce->iface,
617 				  edesc->bEndpointAddress, 0, &sce->pipeh);
618 			if (err) {
619 				error = EIO;
620 				goto out;
621 			}
622 			sce->ra_wb_bufsize = UGEN_BULK_RA_WB_BUFSIZE;
623 			/*
624 			 * Use request size for non-RA/WB transfers
625 			 * as the default.
626 			 */
627 			sce->ra_wb_reqsize = UGEN_BBSIZE;
628 			break;
629 		case UE_ISOCHRONOUS:
630 			if (dir == OUT) {
631 				error = EINVAL;
632 				goto out;
633 			}
634 			isize = UGETW(edesc->wMaxPacketSize);
635 			if (isize == 0) {	/* shouldn't happen */
636 				error = EINVAL;
637 				goto out;
638 			}
639 			sce->ibuf = kmem_alloc(isize * UGEN_NISOFRAMES,
640 				KM_SLEEP);
641 			sce->cur = sce->fill = sce->ibuf;
642 			sce->limit = sce->ibuf + isize * UGEN_NISOFRAMES;
643 			DPRINTFN(5, ("ugenopen: isoc endpt=%d, isize=%d\n",
644 				     endpt, isize));
645 			err = usbd_open_pipe(sce->iface,
646 				  edesc->bEndpointAddress, 0, &sce->pipeh);
647 			if (err) {
648 				kmem_free(sce->ibuf, isize * UGEN_NISOFRAMES);
649 				sce->ibuf = NULL;
650 				error = EIO;
651 				goto out;
652 			}
653 			for (i = 0; i < UGEN_NISOREQS; ++i) {
654 				sce->isoreqs[i].sce = sce;
655 				err = usbd_create_xfer(sce->pipeh,
656 				    isize * UGEN_NISORFRMS, 0, UGEN_NISORFRMS,
657 				    &xfer);
658 				if (err)
659 					goto bad;
660 				sce->isoreqs[i].xfer = xfer;
661 				sce->isoreqs[i].dmabuf = usbd_get_buffer(xfer);
662 				for (j = 0; j < UGEN_NISORFRMS; ++j)
663 					sce->isoreqs[i].sizes[j] = isize;
664 				usbd_setup_isoc_xfer(xfer, &sce->isoreqs[i],
665 				    sce->isoreqs[i].sizes, UGEN_NISORFRMS, 0,
666 				    ugen_isoc_rintr);
667 				(void)usbd_transfer(xfer);
668 			}
669 			DPRINTFN(5, ("ugenopen: isoc open done\n"));
670 			break;
671 		bad:
672 			while (--i >= 0) { /* implicit buffer free */
673 				usbd_destroy_xfer(sce->isoreqs[i].xfer);
674 				sce->isoreqs[i].xfer = NULL;
675 			}
676 			usbd_close_pipe(sce->pipeh);
677 			sce->pipeh = NULL;
678 			kmem_free(sce->ibuf, isize * UGEN_NISOFRAMES);
679 			sce->ibuf = NULL;
680 			error = ENOMEM;
681 			goto out;
682 		case UE_CONTROL:
683 			sce->timeout = USBD_DEFAULT_TIMEOUT;
684 			error = EINVAL;
685 			goto out;
686 		}
687 	}
688 	error = 0;
689 out:	if (error && opened)
690 		sc->sc_is_open[endpt] = 0;
691 	ugenif_release(sc);
692 	return error;
693 }
694 
695 static void
696 ugen_do_close(struct ugen_softc *sc, int flag, int endpt)
697 {
698 	struct ugen_endpoint *sce;
699 	int dir;
700 	int i;
701 
702 	KASSERT(KERNEL_LOCKED_P()); /* sc_is_open */
703 
704 	if (!sc->sc_is_open[endpt])
705 		goto out;
706 
707 	if (endpt == USB_CONTROL_ENDPOINT) {
708 		DPRINTFN(5, ("ugenclose: close control\n"));
709 		goto out;
710 	}
711 
712 	for (dir = OUT; dir <= IN; dir++) {
713 		if (!(flag & (dir == OUT ? FWRITE : FREAD)))
714 			continue;
715 		sce = &sc->sc_endpoints[endpt][dir];
716 		if (sce->pipeh == NULL)
717 			continue;
718 		DPRINTFN(5, ("ugenclose: endpt=%d dir=%d sce=%p\n",
719 			     endpt, dir, sce));
720 
721 		usbd_abort_pipe(sce->pipeh);
722 
723 		int isize = UGETW(sce->edesc->wMaxPacketSize);
724 		int msize = 0;
725 
726 		switch (sce->edesc->bmAttributes & UE_XFERTYPE) {
727 		case UE_INTERRUPT:
728 			ndflush(&sce->q, sce->q.c_cc);
729 			clfree(&sce->q);
730 			msize = isize;
731 			break;
732 		case UE_ISOCHRONOUS:
733 			for (i = 0; i < UGEN_NISOREQS; ++i) {
734 				usbd_destroy_xfer(sce->isoreqs[i].xfer);
735 				sce->isoreqs[i].xfer = NULL;
736 			}
737 			msize = isize * UGEN_NISOFRAMES;
738 			break;
739 		case UE_BULK:
740 			if (sce->state & (UGEN_BULK_RA | UGEN_BULK_WB)) {
741 				usbd_destroy_xfer(sce->ra_wb_xfer);
742 				sce->ra_wb_xfer = NULL;
743 				msize = sce->ra_wb_bufsize;
744 			}
745 			break;
746 		default:
747 			break;
748 		}
749 		usbd_close_pipe(sce->pipeh);
750 		sce->pipeh = NULL;
751 		if (sce->ibuf != NULL) {
752 			kmem_free(sce->ibuf, msize);
753 			sce->ibuf = NULL;
754 		}
755 	}
756 
757 out:	sc->sc_is_open[endpt] = 0;
758 	for (dir = OUT; dir <= IN; dir++) {
759 		sce = &sc->sc_endpoints[endpt][dir];
760 		KASSERT(sce->pipeh == NULL);
761 		KASSERT(sce->ibuf == NULL);
762 		KASSERT(sce->ra_wb_xfer == NULL);
763 		for (i = 0; i < UGEN_NISOREQS; i++)
764 			KASSERT(sce->isoreqs[i].xfer == NULL);
765 	}
766 }
767 
768 static int
769 ugenclose(dev_t dev, int flag, int mode, struct lwp *l)
770 {
771 	int endpt = UGENENDPOINT(dev);
772 	struct ugen_softc *sc;
773 
774 	DPRINTFN(5, ("ugenclose: flag=%d, mode=%d, unit=%d, endpt=%d\n",
775 		     flag, mode, UGENUNIT(dev), endpt));
776 
777 	KASSERT(KERNEL_LOCKED_P()); /* ugen_do_close */
778 
779 	if ((sc = ugenif_acquire(UGENUNIT(dev))) == NULL)
780 		return ENXIO;
781 
782 	KASSERT(sc->sc_is_open[endpt]);
783 	ugen_do_close(sc, flag, endpt);
784 	KASSERT(!sc->sc_is_open[endpt]);
785 
786 	ugenif_release(sc);
787 
788 	return 0;
789 }
790 
791 Static int
792 ugen_do_read(struct ugen_softc *sc, int endpt, struct uio *uio, int flag)
793 {
794 	struct ugen_endpoint *sce = &sc->sc_endpoints[endpt][IN];
795 	uint32_t n, tn;
796 	struct usbd_xfer *xfer;
797 	usbd_status err;
798 	int error = 0;
799 
800 	DPRINTFN(5, ("%s: ugenread: %d\n", device_xname(sc->sc_dev), endpt));
801 
802 	if (endpt == USB_CONTROL_ENDPOINT)
803 		return ENODEV;
804 
805 	KASSERT(sce->edesc);
806 	KASSERT(sce->pipeh);
807 
808 	switch (sce->edesc->bmAttributes & UE_XFERTYPE) {
809 	case UE_INTERRUPT:
810 		/* Block until activity occurred. */
811 		mutex_enter(&sc->sc_lock);
812 		while (sce->q.c_cc == 0) {
813 			if (flag & IO_NDELAY) {
814 				mutex_exit(&sc->sc_lock);
815 				return EWOULDBLOCK;
816 			}
817 			DPRINTFN(5, ("ugenread: sleep on %p\n", sce));
818 			/* "ugenri" */
819 			error = cv_timedwait_sig(&sce->cv, &sc->sc_lock,
820 			    mstohz(sce->timeout));
821 			DPRINTFN(5, ("ugenread: woke, error=%d\n", error));
822 			if (sc->sc_dying)
823 				error = EIO;
824 			if (error)
825 				break;
826 		}
827 		mutex_exit(&sc->sc_lock);
828 
829 		/* Transfer as many chunks as possible. */
830 		while (sce->q.c_cc > 0 && uio->uio_resid > 0 && !error) {
831 			n = uimin(sce->q.c_cc, uio->uio_resid);
832 			if (n > sizeof(sc->sc_buffer))
833 				n = sizeof(sc->sc_buffer);
834 
835 			/* Remove a small chunk from the input queue. */
836 			q_to_b(&sce->q, sc->sc_buffer, n);
837 			DPRINTFN(5, ("ugenread: got %d chars\n", n));
838 
839 			/* Copy the data to the user process. */
840 			error = uiomove(sc->sc_buffer, n, uio);
841 			if (error)
842 				break;
843 		}
844 		break;
845 	case UE_BULK:
846 		if (sce->state & UGEN_BULK_RA) {
847 			DPRINTFN(5, ("ugenread: BULK_RA req: %zd used: %d\n",
848 				     uio->uio_resid, sce->ra_wb_used));
849 			xfer = sce->ra_wb_xfer;
850 
851 			mutex_enter(&sc->sc_lock);
852 			if (sce->ra_wb_used == 0 && flag & IO_NDELAY) {
853 				mutex_exit(&sc->sc_lock);
854 				return EWOULDBLOCK;
855 			}
856 			while (uio->uio_resid > 0 && !error) {
857 				while (sce->ra_wb_used == 0) {
858 					DPRINTFN(5,
859 						 ("ugenread: sleep on %p\n",
860 						  sce));
861 					/* "ugenrb" */
862 					error = cv_timedwait_sig(&sce->cv,
863 					    &sc->sc_lock, mstohz(sce->timeout));
864 					DPRINTFN(5,
865 						 ("ugenread: woke, error=%d\n",
866 						  error));
867 					if (sc->sc_dying)
868 						error = EIO;
869 					if (error)
870 						break;
871 				}
872 
873 				/* Copy data to the process. */
874 				while (uio->uio_resid > 0
875 				       && sce->ra_wb_used > 0) {
876 					n = uimin(uio->uio_resid,
877 						sce->ra_wb_used);
878 					n = uimin(n, sce->limit - sce->cur);
879 					error = uiomove(sce->cur, n, uio);
880 					if (error)
881 						break;
882 					sce->cur += n;
883 					sce->ra_wb_used -= n;
884 					if (sce->cur == sce->limit)
885 						sce->cur = sce->ibuf;
886 				}
887 
888 				/*
889 				 * If the transfers stopped because the
890 				 * buffer was full, restart them.
891 				 */
892 				if (sce->state & UGEN_RA_WB_STOP &&
893 				    sce->ra_wb_used < sce->limit - sce->ibuf) {
894 					n = (sce->limit - sce->ibuf)
895 					    - sce->ra_wb_used;
896 					usbd_setup_xfer(xfer, sce, NULL,
897 					    uimin(n, sce->ra_wb_xferlen),
898 					    0, USBD_NO_TIMEOUT,
899 					    ugen_bulkra_intr);
900 					sce->state &= ~UGEN_RA_WB_STOP;
901 					err = usbd_transfer(xfer);
902 					if (err != USBD_IN_PROGRESS)
903 						/*
904 						 * The transfer has not been
905 						 * queued.  Setting STOP
906 						 * will make us try
907 						 * again at the next read.
908 						 */
909 						sce->state |= UGEN_RA_WB_STOP;
910 				}
911 			}
912 			mutex_exit(&sc->sc_lock);
913 			break;
914 		}
915 		error = usbd_create_xfer(sce->pipeh, UGEN_BBSIZE,
916 		    0, 0, &xfer);
917 		if (error)
918 			return error;
919 		while ((n = uimin(UGEN_BBSIZE, uio->uio_resid)) != 0) {
920 			DPRINTFN(1, ("ugenread: start transfer %d bytes\n",n));
921 			tn = n;
922 			err = usbd_bulk_transfer(xfer, sce->pipeh,
923 			    sce->state & UGEN_SHORT_OK ? USBD_SHORT_XFER_OK : 0,
924 			    sce->timeout, sc->sc_buffer, &tn);
925 			if (err) {
926 				if (err == USBD_INTERRUPTED)
927 					error = EINTR;
928 				else if (err == USBD_TIMEOUT)
929 					error = ETIMEDOUT;
930 				else
931 					error = EIO;
932 				break;
933 			}
934 			DPRINTFN(1, ("ugenread: got %d bytes\n", tn));
935 			error = uiomove(sc->sc_buffer, tn, uio);
936 			if (error || tn < n)
937 				break;
938 		}
939 		usbd_destroy_xfer(xfer);
940 		break;
941 	case UE_ISOCHRONOUS:
942 		mutex_enter(&sc->sc_lock);
943 		while (sce->cur == sce->fill) {
944 			if (flag & IO_NDELAY) {
945 				mutex_exit(&sc->sc_lock);
946 				return EWOULDBLOCK;
947 			}
948 			/* "ugenri" */
949 			DPRINTFN(5, ("ugenread: sleep on %p\n", sce));
950 			error = cv_timedwait_sig(&sce->cv, &sc->sc_lock,
951 			    mstohz(sce->timeout));
952 			DPRINTFN(5, ("ugenread: woke, error=%d\n", error));
953 			if (sc->sc_dying)
954 				error = EIO;
955 			if (error)
956 				break;
957 		}
958 
959 		while (sce->cur != sce->fill && uio->uio_resid > 0 && !error) {
960 			if(sce->fill > sce->cur)
961 				n = uimin(sce->fill - sce->cur, uio->uio_resid);
962 			else
963 				n = uimin(sce->limit - sce->cur, uio->uio_resid);
964 
965 			DPRINTFN(5, ("ugenread: isoc got %d chars\n", n));
966 
967 			/* Copy the data to the user process. */
968 			error = uiomove(sce->cur, n, uio);
969 			if (error)
970 				break;
971 			sce->cur += n;
972 			if (sce->cur >= sce->limit)
973 				sce->cur = sce->ibuf;
974 		}
975 		mutex_exit(&sc->sc_lock);
976 		break;
977 
978 
979 	default:
980 		return ENXIO;
981 	}
982 	return error;
983 }
984 
985 static int
986 ugenread(dev_t dev, struct uio *uio, int flag)
987 {
988 	int endpt = UGENENDPOINT(dev);
989 	struct ugen_softc *sc;
990 	int error;
991 
992 	if ((sc = ugenif_acquire(UGENUNIT(dev))) == NULL)
993 		return ENXIO;
994 	error = ugen_do_read(sc, endpt, uio, flag);
995 	ugenif_release(sc);
996 
997 	return error;
998 }
999 
1000 Static int
1001 ugen_do_write(struct ugen_softc *sc, int endpt, struct uio *uio,
1002 	int flag)
1003 {
1004 	struct ugen_endpoint *sce = &sc->sc_endpoints[endpt][OUT];
1005 	uint32_t n;
1006 	int error = 0;
1007 	uint32_t tn;
1008 	char *dbuf;
1009 	struct usbd_xfer *xfer;
1010 	usbd_status err;
1011 
1012 	DPRINTFN(5, ("%s: ugenwrite: %d\n", device_xname(sc->sc_dev), endpt));
1013 
1014 	if (endpt == USB_CONTROL_ENDPOINT)
1015 		return ENODEV;
1016 
1017 	KASSERT(sce->edesc);
1018 	KASSERT(sce->pipeh);
1019 
1020 	switch (sce->edesc->bmAttributes & UE_XFERTYPE) {
1021 	case UE_BULK:
1022 		if (sce->state & UGEN_BULK_WB) {
1023 			DPRINTFN(5, ("ugenwrite: BULK_WB req: %zd used: %d\n",
1024 				     uio->uio_resid, sce->ra_wb_used));
1025 			xfer = sce->ra_wb_xfer;
1026 
1027 			mutex_enter(&sc->sc_lock);
1028 			if (sce->ra_wb_used == sce->limit - sce->ibuf &&
1029 			    flag & IO_NDELAY) {
1030 				mutex_exit(&sc->sc_lock);
1031 				return EWOULDBLOCK;
1032 			}
1033 			while (uio->uio_resid > 0 && !error) {
1034 				while (sce->ra_wb_used ==
1035 				       sce->limit - sce->ibuf) {
1036 					DPRINTFN(5,
1037 						 ("ugenwrite: sleep on %p\n",
1038 						  sce));
1039 					/* "ugenwb" */
1040 					error = cv_timedwait_sig(&sce->cv,
1041 					    &sc->sc_lock, mstohz(sce->timeout));
1042 					DPRINTFN(5,
1043 						 ("ugenwrite: woke, error=%d\n",
1044 						  error));
1045 					if (sc->sc_dying)
1046 						error = EIO;
1047 					if (error)
1048 						break;
1049 				}
1050 
1051 				/* Copy data from the process. */
1052 				while (uio->uio_resid > 0 &&
1053 				    sce->ra_wb_used < sce->limit - sce->ibuf) {
1054 					n = uimin(uio->uio_resid,
1055 						(sce->limit - sce->ibuf)
1056 						 - sce->ra_wb_used);
1057 					n = uimin(n, sce->limit - sce->fill);
1058 					error = uiomove(sce->fill, n, uio);
1059 					if (error)
1060 						break;
1061 					sce->fill += n;
1062 					sce->ra_wb_used += n;
1063 					if (sce->fill == sce->limit)
1064 						sce->fill = sce->ibuf;
1065 				}
1066 
1067 				/*
1068 				 * If the transfers stopped because the
1069 				 * buffer was empty, restart them.
1070 				 */
1071 				if (sce->state & UGEN_RA_WB_STOP &&
1072 				    sce->ra_wb_used > 0) {
1073 					dbuf = (char *)usbd_get_buffer(xfer);
1074 					n = uimin(sce->ra_wb_used,
1075 						sce->ra_wb_xferlen);
1076 					tn = uimin(n, sce->limit - sce->cur);
1077 					memcpy(dbuf, sce->cur, tn);
1078 					dbuf += tn;
1079 					if (n - tn > 0)
1080 						memcpy(dbuf, sce->ibuf,
1081 						       n - tn);
1082 					usbd_setup_xfer(xfer, sce, NULL, n,
1083 					    0, USBD_NO_TIMEOUT,
1084 					    ugen_bulkwb_intr);
1085 					sce->state &= ~UGEN_RA_WB_STOP;
1086 					err = usbd_transfer(xfer);
1087 					if (err != USBD_IN_PROGRESS)
1088 						/*
1089 						 * The transfer has not been
1090 						 * queued.  Setting STOP
1091 						 * will make us try again
1092 						 * at the next read.
1093 						 */
1094 						sce->state |= UGEN_RA_WB_STOP;
1095 				}
1096 			}
1097 			mutex_exit(&sc->sc_lock);
1098 			break;
1099 		}
1100 		error = usbd_create_xfer(sce->pipeh, UGEN_BBSIZE,
1101 		    0, 0, &xfer);
1102 		if (error)
1103 			return error;
1104 		while ((n = uimin(UGEN_BBSIZE, uio->uio_resid)) != 0) {
1105 			error = uiomove(sc->sc_buffer, n, uio);
1106 			if (error)
1107 				break;
1108 			DPRINTFN(1, ("ugenwrite: transfer %d bytes\n", n));
1109 			err = usbd_bulk_transfer(xfer, sce->pipeh, 0, sce->timeout,
1110 			    sc->sc_buffer, &n);
1111 			if (err) {
1112 				if (err == USBD_INTERRUPTED)
1113 					error = EINTR;
1114 				else if (err == USBD_TIMEOUT)
1115 					error = ETIMEDOUT;
1116 				else
1117 					error = EIO;
1118 				break;
1119 			}
1120 		}
1121 		usbd_destroy_xfer(xfer);
1122 		break;
1123 	case UE_INTERRUPT:
1124 		error = usbd_create_xfer(sce->pipeh,
1125 		    UGETW(sce->edesc->wMaxPacketSize), 0, 0, &xfer);
1126 		if (error)
1127 			return error;
1128 		while ((n = uimin(UGETW(sce->edesc->wMaxPacketSize),
1129 		    uio->uio_resid)) != 0) {
1130 			error = uiomove(sc->sc_buffer, n, uio);
1131 			if (error)
1132 				break;
1133 			DPRINTFN(1, ("ugenwrite: transfer %d bytes\n", n));
1134 			err = usbd_intr_transfer(xfer, sce->pipeh, 0,
1135 			    sce->timeout, sc->sc_buffer, &n);
1136 			if (err) {
1137 				if (err == USBD_INTERRUPTED)
1138 					error = EINTR;
1139 				else if (err == USBD_TIMEOUT)
1140 					error = ETIMEDOUT;
1141 				else
1142 					error = EIO;
1143 				break;
1144 			}
1145 		}
1146 		usbd_destroy_xfer(xfer);
1147 		break;
1148 	default:
1149 		return ENXIO;
1150 	}
1151 	return error;
1152 }
1153 
1154 static int
1155 ugenwrite(dev_t dev, struct uio *uio, int flag)
1156 {
1157 	int endpt = UGENENDPOINT(dev);
1158 	struct ugen_softc *sc;
1159 	int error;
1160 
1161 	if ((sc = ugenif_acquire(UGENUNIT(dev))) == NULL)
1162 		return ENXIO;
1163 	error = ugen_do_write(sc, endpt, uio, flag);
1164 	ugenif_release(sc);
1165 
1166 	return error;
1167 }
1168 
1169 static int
1170 ugen_activate(device_t self, enum devact act)
1171 {
1172 	struct ugen_softc *sc = device_private(self);
1173 
1174 	switch (act) {
1175 	case DVACT_DEACTIVATE:
1176 		sc->sc_dying = 1;
1177 		return 0;
1178 	default:
1179 		return EOPNOTSUPP;
1180 	}
1181 }
1182 
1183 static int
1184 ugen_detach(device_t self, int flags)
1185 {
1186 	struct ugen_softc *sc = device_private(self);
1187 	struct ugen_endpoint *sce;
1188 	int i, dir;
1189 	int maj, mn;
1190 
1191 	DPRINTF(("ugen_detach: sc=%p flags=%d\n", sc, flags));
1192 
1193 	KASSERT(KERNEL_LOCKED_P()); /* sc_is_open */
1194 
1195 	/*
1196 	 * Fail if we're not forced to detach and userland has any
1197 	 * endpoints open.
1198 	 */
1199 	if ((flags & DETACH_FORCE) == 0) {
1200 		for (i = 0; i < USB_MAX_ENDPOINTS; i++) {
1201 			if (sc->sc_is_open[i])
1202 				return EBUSY;
1203 		}
1204 	}
1205 
1206 	/* Prevent new users.  Prevent suspend/resume.  */
1207 	sc->sc_dying = 1;
1208 	pmf_device_deregister(self);
1209 
1210 	/*
1211 	 * If we never finished attaching, skip nixing endpoints and
1212 	 * users because there aren't any.
1213 	 */
1214 	if (!sc->sc_attached)
1215 		goto out;
1216 
1217 	/* Abort all pipes.  */
1218 	for (i = 0; i < USB_MAX_ENDPOINTS; i++) {
1219 		for (dir = OUT; dir <= IN; dir++) {
1220 			sce = &sc->sc_endpoints[i][dir];
1221 			if (sce->pipeh)
1222 				usbd_abort_pipe(sce->pipeh);
1223 		}
1224 	}
1225 
1226 	/*
1227 	 * Wait for users to drain.  Before this point there can be no
1228 	 * more I/O operations started because we set sc_dying; after
1229 	 * this, there can be no more I/O operations in progress, so it
1230 	 * will be safe to free things.
1231 	 */
1232 	mutex_enter(&sc->sc_lock);
1233 	if (--sc->sc_refcnt >= 0) {
1234 		/* Wake everyone */
1235 		for (i = 0; i < USB_MAX_ENDPOINTS; i++) {
1236 			for (dir = OUT; dir <= IN; dir++)
1237 				cv_broadcast(&sc->sc_endpoints[i][dir].cv);
1238 		}
1239 		/* Wait for processes to go away. */
1240 		do {
1241 			cv_wait(&sc->sc_detach_cv, &sc->sc_lock);
1242 		} while (sc->sc_refcnt >= 0);
1243 	}
1244 	mutex_exit(&sc->sc_lock);
1245 
1246 	/* locate the major number */
1247 	maj = cdevsw_lookup_major(&ugen_cdevsw);
1248 
1249 	/*
1250 	 * Nuke the vnodes for any open instances (calls ugenclose, but
1251 	 * with no effect because we already set sc_dying).
1252 	 */
1253 	mn = sc->sc_unit * USB_MAX_ENDPOINTS;
1254 	vdevgone(maj, mn, mn + USB_MAX_ENDPOINTS - 1, VCHR);
1255 
1256 	/* Actually close any lingering pipes.  */
1257 	for (i = 0; i < USB_MAX_ENDPOINTS; i++)
1258 		ugen_do_close(sc, FREAD|FWRITE, i);
1259 
1260 	usbd_add_drv_event(USB_EVENT_DRIVER_DETACH, sc->sc_udev, sc->sc_dev);
1261 	ugenif_put_unit(sc);
1262 
1263 out:	for (i = 0; i < USB_MAX_ENDPOINTS; i++) {
1264 		for (dir = OUT; dir <= IN; dir++) {
1265 			sce = &sc->sc_endpoints[i][dir];
1266 			seldestroy(&sce->rsel);
1267 			cv_destroy(&sce->cv);
1268 		}
1269 	}
1270 
1271 	cv_destroy(&sc->sc_detach_cv);
1272 	mutex_destroy(&sc->sc_lock);
1273 
1274 	return 0;
1275 }
1276 
1277 Static void
1278 ugenintr(struct usbd_xfer *xfer, void *addr, usbd_status status)
1279 {
1280 	struct ugen_endpoint *sce = addr;
1281 	struct ugen_softc *sc = sce->sc;
1282 	uint32_t count;
1283 	u_char *ibuf;
1284 
1285 	if (status == USBD_CANCELLED)
1286 		return;
1287 
1288 	if (status != USBD_NORMAL_COMPLETION) {
1289 		DPRINTF(("ugenintr: status=%d\n", status));
1290 		if (status == USBD_STALLED)
1291 		    usbd_clear_endpoint_stall_async(sce->pipeh);
1292 		return;
1293 	}
1294 
1295 	usbd_get_xfer_status(xfer, NULL, NULL, &count, NULL);
1296 	ibuf = sce->ibuf;
1297 
1298 	DPRINTFN(5, ("ugenintr: xfer=%p status=%d count=%d\n",
1299 		     xfer, status, count));
1300 	DPRINTFN(5, ("          data = %02x %02x %02x\n",
1301 		     ibuf[0], ibuf[1], ibuf[2]));
1302 
1303 	mutex_enter(&sc->sc_lock);
1304 	(void)b_to_q(ibuf, count, &sce->q);
1305 	cv_signal(&sce->cv);
1306 	mutex_exit(&sc->sc_lock);
1307 	selnotify(&sce->rsel, 0, 0);
1308 }
1309 
1310 Static void
1311 ugen_isoc_rintr(struct usbd_xfer *xfer, void *addr,
1312 		usbd_status status)
1313 {
1314 	struct isoreq *req = addr;
1315 	struct ugen_endpoint *sce = req->sce;
1316 	struct ugen_softc *sc = sce->sc;
1317 	uint32_t count, n;
1318 	int i, isize;
1319 
1320 	/* Return if we are aborting. */
1321 	if (status == USBD_CANCELLED)
1322 		return;
1323 
1324 	usbd_get_xfer_status(xfer, NULL, NULL, &count, NULL);
1325 	DPRINTFN(5,("ugen_isoc_rintr: xfer %ld, count=%d\n",
1326 	    (long)(req - sce->isoreqs), count));
1327 
1328 	mutex_enter(&sc->sc_lock);
1329 
1330 	/* throw away oldest input if the buffer is full */
1331 	if (sce->fill < sce->cur && sce->cur <= sce->fill + count) {
1332 		sce->cur += count;
1333 		if (sce->cur >= sce->limit)
1334 			sce->cur = sce->ibuf + (sce->limit - sce->cur);
1335 		DPRINTFN(5, ("ugen_isoc_rintr: throwing away %d bytes\n",
1336 			     count));
1337 	}
1338 
1339 	isize = UGETW(sce->edesc->wMaxPacketSize);
1340 	for (i = 0; i < UGEN_NISORFRMS; i++) {
1341 		uint32_t actlen = req->sizes[i];
1342 		char const *tbuf = (char const *)req->dmabuf + isize * i;
1343 
1344 		/* copy data to buffer */
1345 		while (actlen > 0) {
1346 			n = uimin(actlen, sce->limit - sce->fill);
1347 			memcpy(sce->fill, tbuf, n);
1348 
1349 			tbuf += n;
1350 			actlen -= n;
1351 			sce->fill += n;
1352 			if (sce->fill == sce->limit)
1353 				sce->fill = sce->ibuf;
1354 		}
1355 
1356 		/* setup size for next transfer */
1357 		req->sizes[i] = isize;
1358 	}
1359 
1360 	usbd_setup_isoc_xfer(xfer, req, req->sizes, UGEN_NISORFRMS, 0,
1361 	    ugen_isoc_rintr);
1362 	(void)usbd_transfer(xfer);
1363 
1364 	cv_signal(&sce->cv);
1365 	mutex_exit(&sc->sc_lock);
1366 	selnotify(&sce->rsel, 0, 0);
1367 }
1368 
1369 Static void
1370 ugen_bulkra_intr(struct usbd_xfer *xfer, void *addr,
1371 		 usbd_status status)
1372 {
1373 	struct ugen_endpoint *sce = addr;
1374 	struct ugen_softc *sc = sce->sc;
1375 	uint32_t count, n;
1376 	char const *tbuf;
1377 	usbd_status err;
1378 
1379 	/* Return if we are aborting. */
1380 	if (status == USBD_CANCELLED)
1381 		return;
1382 
1383 	if (status != USBD_NORMAL_COMPLETION) {
1384 		DPRINTF(("ugen_bulkra_intr: status=%d\n", status));
1385 		sce->state |= UGEN_RA_WB_STOP;
1386 		if (status == USBD_STALLED)
1387 		    usbd_clear_endpoint_stall_async(sce->pipeh);
1388 		return;
1389 	}
1390 
1391 	usbd_get_xfer_status(xfer, NULL, NULL, &count, NULL);
1392 
1393 	mutex_enter(&sc->sc_lock);
1394 
1395 	/* Keep track of how much is in the buffer. */
1396 	sce->ra_wb_used += count;
1397 
1398 	/* Copy data to buffer. */
1399 	tbuf = (char const *)usbd_get_buffer(sce->ra_wb_xfer);
1400 	n = uimin(count, sce->limit - sce->fill);
1401 	memcpy(sce->fill, tbuf, n);
1402 	tbuf += n;
1403 	count -= n;
1404 	sce->fill += n;
1405 	if (sce->fill == sce->limit)
1406 		sce->fill = sce->ibuf;
1407 	if (count > 0) {
1408 		memcpy(sce->fill, tbuf, count);
1409 		sce->fill += count;
1410 	}
1411 
1412 	/* Set up the next request if necessary. */
1413 	n = (sce->limit - sce->ibuf) - sce->ra_wb_used;
1414 	if (n > 0) {
1415 		usbd_setup_xfer(xfer, sce, NULL, uimin(n, sce->ra_wb_xferlen), 0,
1416 		    USBD_NO_TIMEOUT, ugen_bulkra_intr);
1417 		err = usbd_transfer(xfer);
1418 		if (err != USBD_IN_PROGRESS) {
1419 			printf("usbd_bulkra_intr: error=%d\n", err);
1420 			/*
1421 			 * The transfer has not been queued.  Setting STOP
1422 			 * will make us try again at the next read.
1423 			 */
1424 			sce->state |= UGEN_RA_WB_STOP;
1425 		}
1426 	}
1427 	else
1428 		sce->state |= UGEN_RA_WB_STOP;
1429 
1430 	cv_signal(&sce->cv);
1431 	mutex_exit(&sc->sc_lock);
1432 	selnotify(&sce->rsel, 0, 0);
1433 }
1434 
1435 Static void
1436 ugen_bulkwb_intr(struct usbd_xfer *xfer, void *addr,
1437 		 usbd_status status)
1438 {
1439 	struct ugen_endpoint *sce = addr;
1440 	struct ugen_softc *sc = sce->sc;
1441 	uint32_t count, n;
1442 	char *tbuf;
1443 	usbd_status err;
1444 
1445 	/* Return if we are aborting. */
1446 	if (status == USBD_CANCELLED)
1447 		return;
1448 
1449 	if (status != USBD_NORMAL_COMPLETION) {
1450 		DPRINTF(("ugen_bulkwb_intr: status=%d\n", status));
1451 		sce->state |= UGEN_RA_WB_STOP;
1452 		if (status == USBD_STALLED)
1453 		    usbd_clear_endpoint_stall_async(sce->pipeh);
1454 		return;
1455 	}
1456 
1457 	usbd_get_xfer_status(xfer, NULL, NULL, &count, NULL);
1458 
1459 	mutex_enter(&sc->sc_lock);
1460 
1461 	/* Keep track of how much is in the buffer. */
1462 	sce->ra_wb_used -= count;
1463 
1464 	/* Update buffer pointers. */
1465 	sce->cur += count;
1466 	if (sce->cur >= sce->limit)
1467 		sce->cur = sce->ibuf + (sce->cur - sce->limit);
1468 
1469 	/* Set up next request if necessary. */
1470 	if (sce->ra_wb_used > 0) {
1471 		/* copy data from buffer */
1472 		tbuf = (char *)usbd_get_buffer(sce->ra_wb_xfer);
1473 		count = uimin(sce->ra_wb_used, sce->ra_wb_xferlen);
1474 		n = uimin(count, sce->limit - sce->cur);
1475 		memcpy(tbuf, sce->cur, n);
1476 		tbuf += n;
1477 		if (count - n > 0)
1478 			memcpy(tbuf, sce->ibuf, count - n);
1479 
1480 		usbd_setup_xfer(xfer, sce, NULL, count, 0, USBD_NO_TIMEOUT,
1481 		    ugen_bulkwb_intr);
1482 		err = usbd_transfer(xfer);
1483 		if (err != USBD_IN_PROGRESS) {
1484 			printf("usbd_bulkwb_intr: error=%d\n", err);
1485 			/*
1486 			 * The transfer has not been queued.  Setting STOP
1487 			 * will make us try again at the next write.
1488 			 */
1489 			sce->state |= UGEN_RA_WB_STOP;
1490 		}
1491 	}
1492 	else
1493 		sce->state |= UGEN_RA_WB_STOP;
1494 
1495 	cv_signal(&sce->cv);
1496 	mutex_exit(&sc->sc_lock);
1497 	selnotify(&sce->rsel, 0, 0);
1498 }
1499 
1500 Static usbd_status
1501 ugen_set_interface(struct ugen_softc *sc, int ifaceidx, int altno)
1502 {
1503 	struct usbd_interface *iface;
1504 	usb_endpoint_descriptor_t *ed;
1505 	usbd_status err;
1506 	struct ugen_endpoint *sce;
1507 	uint8_t niface, nendpt, endptno, endpt;
1508 	int dir;
1509 
1510 	DPRINTFN(15, ("ugen_set_interface %d %d\n", ifaceidx, altno));
1511 
1512 	err = usbd_interface_count(sc->sc_udev, &niface);
1513 	if (err)
1514 		return err;
1515 	if (ifaceidx < 0 || ifaceidx >= niface)
1516 		return USBD_INVAL;
1517 
1518 	err = usbd_device2interface_handle(sc->sc_udev, ifaceidx, &iface);
1519 	if (err)
1520 		return err;
1521 	err = usbd_endpoint_count(iface, &nendpt);
1522 	if (err)
1523 		return err;
1524 
1525 	/* change setting */
1526 	err = usbd_set_interface(iface, altno);
1527 	if (err)
1528 		return err;
1529 
1530 	err = usbd_endpoint_count(iface, &nendpt);
1531 	if (err)
1532 		return err;
1533 
1534 	ugen_clear_endpoints(sc);
1535 
1536 	for (endptno = 0; endptno < nendpt; endptno++) {
1537 		ed = usbd_interface2endpoint_descriptor(iface,endptno);
1538 		KASSERT(ed != NULL);
1539 		endpt = ed->bEndpointAddress;
1540 		dir = UE_GET_DIR(endpt) == UE_DIR_IN ? IN : OUT;
1541 		sce = &sc->sc_endpoints[UE_GET_ADDR(endpt)][dir];
1542 		sce->sc = sc;
1543 		sce->edesc = ed;
1544 		sce->iface = iface;
1545 	}
1546 	return 0;
1547 }
1548 
1549 /* Retrieve a complete descriptor for a certain device and index. */
1550 Static usb_config_descriptor_t *
1551 ugen_get_cdesc(struct ugen_softc *sc, int index, int *lenp)
1552 {
1553 	usb_config_descriptor_t *cdesc, *tdesc, cdescr;
1554 	int len;
1555 	usbd_status err;
1556 
1557 	if (index == USB_CURRENT_CONFIG_INDEX) {
1558 		tdesc = usbd_get_config_descriptor(sc->sc_udev);
1559 		if (tdesc == NULL)
1560 			return NULL;
1561 		len = UGETW(tdesc->wTotalLength);
1562 		if (lenp)
1563 			*lenp = len;
1564 		cdesc = kmem_alloc(len, KM_SLEEP);
1565 		memcpy(cdesc, tdesc, len);
1566 		DPRINTFN(5,("ugen_get_cdesc: current, len=%d\n", len));
1567 	} else {
1568 		err = usbd_get_config_desc(sc->sc_udev, index, &cdescr);
1569 		if (err)
1570 			return 0;
1571 		len = UGETW(cdescr.wTotalLength);
1572 		DPRINTFN(5,("ugen_get_cdesc: index=%d, len=%d\n", index, len));
1573 		if (lenp)
1574 			*lenp = len;
1575 		cdesc = kmem_alloc(len, KM_SLEEP);
1576 		err = usbd_get_config_desc_full(sc->sc_udev, index, cdesc, len);
1577 		if (err) {
1578 			kmem_free(cdesc, len);
1579 			return 0;
1580 		}
1581 	}
1582 	return cdesc;
1583 }
1584 
1585 Static int
1586 ugen_get_alt_index(struct ugen_softc *sc, int ifaceidx)
1587 {
1588 	struct usbd_interface *iface;
1589 	usbd_status err;
1590 
1591 	err = usbd_device2interface_handle(sc->sc_udev, ifaceidx, &iface);
1592 	if (err)
1593 		return -1;
1594 	return usbd_get_interface_altindex(iface);
1595 }
1596 
1597 Static int
1598 ugen_do_ioctl(struct ugen_softc *sc, int endpt, u_long cmd,
1599 	      void *addr, int flag, struct lwp *l)
1600 {
1601 	struct ugen_endpoint *sce;
1602 	usbd_status err;
1603 	struct usbd_interface *iface;
1604 	struct usb_config_desc *cd;
1605 	usb_config_descriptor_t *cdesc;
1606 	struct usb_interface_desc *id;
1607 	usb_interface_descriptor_t *idesc;
1608 	struct usb_endpoint_desc *ed;
1609 	usb_endpoint_descriptor_t *edesc;
1610 	struct usb_alt_interface *ai;
1611 	struct usb_string_desc *si;
1612 	uint8_t conf, alt;
1613 	int cdesclen;
1614 	int error;
1615 	int dir;
1616 
1617 	KASSERT(KERNEL_LOCKED_P()); /* ugen_set_config */
1618 
1619 	DPRINTFN(5, ("ugenioctl: cmd=%08lx\n", cmd));
1620 
1621 	switch (cmd) {
1622 	case FIONBIO:
1623 		/* All handled in the upper FS layer. */
1624 		return 0;
1625 	case USB_SET_SHORT_XFER:
1626 		if (endpt == USB_CONTROL_ENDPOINT)
1627 			return EINVAL;
1628 		/* This flag only affects read */
1629 		sce = &sc->sc_endpoints[endpt][IN];
1630 		if (sce == NULL || sce->pipeh == NULL)
1631 			return EINVAL;
1632 		if (*(int *)addr)
1633 			sce->state |= UGEN_SHORT_OK;
1634 		else
1635 			sce->state &= ~UGEN_SHORT_OK;
1636 		return 0;
1637 	case USB_SET_TIMEOUT:
1638 		for (dir = OUT; dir <= IN; dir++) {
1639 			sce = &sc->sc_endpoints[endpt][dir];
1640 			if (sce == NULL)
1641 				return EINVAL;
1642 
1643 			sce->timeout = *(int *)addr;
1644 		}
1645 		return 0;
1646 	case USB_SET_BULK_RA:
1647 		if (endpt == USB_CONTROL_ENDPOINT)
1648 			return EINVAL;
1649 		sce = &sc->sc_endpoints[endpt][IN];
1650 		if (sce == NULL || sce->pipeh == NULL)
1651 			return EINVAL;
1652 		edesc = sce->edesc;
1653 		if ((edesc->bmAttributes & UE_XFERTYPE) != UE_BULK)
1654 			return EINVAL;
1655 
1656 		if (*(int *)addr) {
1657 			/* Only turn RA on if it's currently off. */
1658 			if (sce->state & UGEN_BULK_RA)
1659 				return 0;
1660 			KASSERT(sce->ra_wb_xfer == NULL);
1661 			KASSERT(sce->ibuf == NULL);
1662 
1663 			if (sce->ra_wb_bufsize == 0 || sce->ra_wb_reqsize == 0)
1664 				/* shouldn't happen */
1665 				return EINVAL;
1666 			error = usbd_create_xfer(sce->pipeh,
1667 			    sce->ra_wb_reqsize, 0, 0, &sce->ra_wb_xfer);
1668 			if (error)
1669 				return error;
1670 			sce->ra_wb_xferlen = sce->ra_wb_reqsize;
1671 			sce->ibuf = kmem_alloc(sce->ra_wb_bufsize, KM_SLEEP);
1672 			sce->fill = sce->cur = sce->ibuf;
1673 			sce->limit = sce->ibuf + sce->ra_wb_bufsize;
1674 			sce->ra_wb_used = 0;
1675 			sce->state |= UGEN_BULK_RA;
1676 			sce->state &= ~UGEN_RA_WB_STOP;
1677 			/* Now start reading. */
1678 			usbd_setup_xfer(sce->ra_wb_xfer, sce, NULL,
1679 			    uimin(sce->ra_wb_xferlen, sce->ra_wb_bufsize),
1680 			     0, USBD_NO_TIMEOUT, ugen_bulkra_intr);
1681 			err = usbd_transfer(sce->ra_wb_xfer);
1682 			if (err != USBD_IN_PROGRESS) {
1683 				sce->state &= ~UGEN_BULK_RA;
1684 				kmem_free(sce->ibuf, sce->ra_wb_bufsize);
1685 				sce->ibuf = NULL;
1686 				usbd_destroy_xfer(sce->ra_wb_xfer);
1687 				sce->ra_wb_xfer = NULL;
1688 				return EIO;
1689 			}
1690 		} else {
1691 			/* Only turn RA off if it's currently on. */
1692 			if (!(sce->state & UGEN_BULK_RA))
1693 				return 0;
1694 
1695 			sce->state &= ~UGEN_BULK_RA;
1696 			usbd_abort_pipe(sce->pipeh);
1697 			usbd_destroy_xfer(sce->ra_wb_xfer);
1698 			sce->ra_wb_xfer = NULL;
1699 			/*
1700 			 * XXX Discard whatever's in the buffer, but we
1701 			 * should keep it around and drain the buffer
1702 			 * instead.
1703 			 */
1704 			kmem_free(sce->ibuf, sce->ra_wb_bufsize);
1705 			sce->ibuf = NULL;
1706 		}
1707 		return 0;
1708 	case USB_SET_BULK_WB:
1709 		if (endpt == USB_CONTROL_ENDPOINT)
1710 			return EINVAL;
1711 		sce = &sc->sc_endpoints[endpt][OUT];
1712 		if (sce == NULL || sce->pipeh == NULL)
1713 			return EINVAL;
1714 		edesc = sce->edesc;
1715 		if ((edesc->bmAttributes & UE_XFERTYPE) != UE_BULK)
1716 			return EINVAL;
1717 
1718 		if (*(int *)addr) {
1719 			/* Only turn WB on if it's currently off. */
1720 			if (sce->state & UGEN_BULK_WB)
1721 				return 0;
1722 			KASSERT(sce->ra_wb_xfer == NULL);
1723 			KASSERT(sce->ibuf == NULL);
1724 
1725 			if (sce->ra_wb_bufsize == 0 || sce->ra_wb_reqsize == 0)
1726 				/* shouldn't happen */
1727 				return EINVAL;
1728 			error = usbd_create_xfer(sce->pipeh, sce->ra_wb_reqsize,
1729 			    0, 0, &sce->ra_wb_xfer);
1730 			/* XXX check error???  */
1731 			sce->ra_wb_xferlen = sce->ra_wb_reqsize;
1732 			sce->ibuf = kmem_alloc(sce->ra_wb_bufsize, KM_SLEEP);
1733 			sce->fill = sce->cur = sce->ibuf;
1734 			sce->limit = sce->ibuf + sce->ra_wb_bufsize;
1735 			sce->ra_wb_used = 0;
1736 			sce->state |= UGEN_BULK_WB | UGEN_RA_WB_STOP;
1737 		} else {
1738 			/* Only turn WB off if it's currently on. */
1739 			if (!(sce->state & UGEN_BULK_WB))
1740 				return 0;
1741 
1742 			sce->state &= ~UGEN_BULK_WB;
1743 			/*
1744 			 * XXX Discard whatever's in the buffer, but we
1745 			 * should keep it around and keep writing to
1746 			 * drain the buffer instead.
1747 			 */
1748 			usbd_abort_pipe(sce->pipeh);
1749 			usbd_destroy_xfer(sce->ra_wb_xfer);
1750 			sce->ra_wb_xfer = NULL;
1751 			kmem_free(sce->ibuf, sce->ra_wb_bufsize);
1752 			sce->ibuf = NULL;
1753 		}
1754 		return 0;
1755 	case USB_SET_BULK_RA_OPT:
1756 	case USB_SET_BULK_WB_OPT:
1757 	{
1758 		struct usb_bulk_ra_wb_opt *opt;
1759 
1760 		if (endpt == USB_CONTROL_ENDPOINT)
1761 			return EINVAL;
1762 		opt = (struct usb_bulk_ra_wb_opt *)addr;
1763 		if (cmd == USB_SET_BULK_RA_OPT)
1764 			sce = &sc->sc_endpoints[endpt][IN];
1765 		else
1766 			sce = &sc->sc_endpoints[endpt][OUT];
1767 		if (sce == NULL || sce->pipeh == NULL)
1768 			return EINVAL;
1769 		if (opt->ra_wb_buffer_size < 1 ||
1770 		    opt->ra_wb_buffer_size > UGEN_BULK_RA_WB_BUFMAX ||
1771 		    opt->ra_wb_request_size < 1 ||
1772 		    opt->ra_wb_request_size > opt->ra_wb_buffer_size)
1773 			return EINVAL;
1774 		/*
1775 		 * XXX These changes do not take effect until the
1776 		 * next time RA/WB mode is enabled but they ought to
1777 		 * take effect immediately.
1778 		 */
1779 		sce->ra_wb_bufsize = opt->ra_wb_buffer_size;
1780 		sce->ra_wb_reqsize = opt->ra_wb_request_size;
1781 		return 0;
1782 	}
1783 	default:
1784 		break;
1785 	}
1786 
1787 	if (endpt != USB_CONTROL_ENDPOINT)
1788 		return EINVAL;
1789 
1790 	switch (cmd) {
1791 #ifdef UGEN_DEBUG
1792 	case USB_SETDEBUG:
1793 		ugendebug = *(int *)addr;
1794 		break;
1795 #endif
1796 	case USB_GET_CONFIG:
1797 		err = usbd_get_config(sc->sc_udev, &conf);
1798 		if (err)
1799 			return EIO;
1800 		*(int *)addr = conf;
1801 		break;
1802 	case USB_SET_CONFIG:
1803 		if (!(flag & FWRITE))
1804 			return EPERM;
1805 		err = ugen_set_config(sc, *(int *)addr, 1);
1806 		switch (err) {
1807 		case USBD_NORMAL_COMPLETION:
1808 			break;
1809 		case USBD_IN_USE:
1810 			return EBUSY;
1811 		default:
1812 			return EIO;
1813 		}
1814 		break;
1815 	case USB_GET_ALTINTERFACE:
1816 		ai = (struct usb_alt_interface *)addr;
1817 		err = usbd_device2interface_handle(sc->sc_udev,
1818 			  ai->uai_interface_index, &iface);
1819 		if (err)
1820 			return EINVAL;
1821 		idesc = usbd_get_interface_descriptor(iface);
1822 		if (idesc == NULL)
1823 			return EIO;
1824 		ai->uai_alt_no = idesc->bAlternateSetting;
1825 		break;
1826 	case USB_SET_ALTINTERFACE:
1827 		if (!(flag & FWRITE))
1828 			return EPERM;
1829 		ai = (struct usb_alt_interface *)addr;
1830 		err = usbd_device2interface_handle(sc->sc_udev,
1831 			  ai->uai_interface_index, &iface);
1832 		if (err)
1833 			return EINVAL;
1834 		err = ugen_set_interface(sc, ai->uai_interface_index,
1835 		    ai->uai_alt_no);
1836 		if (err)
1837 			return EINVAL;
1838 		break;
1839 	case USB_GET_NO_ALT:
1840 		ai = (struct usb_alt_interface *)addr;
1841 		cdesc = ugen_get_cdesc(sc, ai->uai_config_index, &cdesclen);
1842 		if (cdesc == NULL)
1843 			return EINVAL;
1844 		idesc = usbd_find_idesc(cdesc, ai->uai_interface_index, 0);
1845 		if (idesc == NULL) {
1846 			kmem_free(cdesc, cdesclen);
1847 			return EINVAL;
1848 		}
1849 		ai->uai_alt_no = usbd_get_no_alts(cdesc,
1850 		    idesc->bInterfaceNumber);
1851 		kmem_free(cdesc, cdesclen);
1852 		break;
1853 	case USB_GET_DEVICE_DESC:
1854 		*(usb_device_descriptor_t *)addr =
1855 			*usbd_get_device_descriptor(sc->sc_udev);
1856 		break;
1857 	case USB_GET_CONFIG_DESC:
1858 		cd = (struct usb_config_desc *)addr;
1859 		cdesc = ugen_get_cdesc(sc, cd->ucd_config_index, &cdesclen);
1860 		if (cdesc == NULL)
1861 			return EINVAL;
1862 		cd->ucd_desc = *cdesc;
1863 		kmem_free(cdesc, cdesclen);
1864 		break;
1865 	case USB_GET_INTERFACE_DESC:
1866 		id = (struct usb_interface_desc *)addr;
1867 		cdesc = ugen_get_cdesc(sc, id->uid_config_index, &cdesclen);
1868 		if (cdesc == NULL)
1869 			return EINVAL;
1870 		if (id->uid_config_index == USB_CURRENT_CONFIG_INDEX &&
1871 		    id->uid_alt_index == USB_CURRENT_ALT_INDEX)
1872 			alt = ugen_get_alt_index(sc, id->uid_interface_index);
1873 		else
1874 			alt = id->uid_alt_index;
1875 		idesc = usbd_find_idesc(cdesc, id->uid_interface_index, alt);
1876 		if (idesc == NULL) {
1877 			kmem_free(cdesc, cdesclen);
1878 			return EINVAL;
1879 		}
1880 		id->uid_desc = *idesc;
1881 		kmem_free(cdesc, cdesclen);
1882 		break;
1883 	case USB_GET_ENDPOINT_DESC:
1884 		ed = (struct usb_endpoint_desc *)addr;
1885 		cdesc = ugen_get_cdesc(sc, ed->ued_config_index, &cdesclen);
1886 		if (cdesc == NULL)
1887 			return EINVAL;
1888 		if (ed->ued_config_index == USB_CURRENT_CONFIG_INDEX &&
1889 		    ed->ued_alt_index == USB_CURRENT_ALT_INDEX)
1890 			alt = ugen_get_alt_index(sc, ed->ued_interface_index);
1891 		else
1892 			alt = ed->ued_alt_index;
1893 		edesc = usbd_find_edesc(cdesc, ed->ued_interface_index,
1894 					alt, ed->ued_endpoint_index);
1895 		if (edesc == NULL) {
1896 			kmem_free(cdesc, cdesclen);
1897 			return EINVAL;
1898 		}
1899 		ed->ued_desc = *edesc;
1900 		kmem_free(cdesc, cdesclen);
1901 		break;
1902 	case USB_GET_FULL_DESC:
1903 	{
1904 		int len;
1905 		struct iovec iov;
1906 		struct uio uio;
1907 		struct usb_full_desc *fd = (struct usb_full_desc *)addr;
1908 
1909 		cdesc = ugen_get_cdesc(sc, fd->ufd_config_index, &cdesclen);
1910 		if (cdesc == NULL)
1911 			return EINVAL;
1912 		len = cdesclen;
1913 		if (len > fd->ufd_size)
1914 			len = fd->ufd_size;
1915 		iov.iov_base = (void *)fd->ufd_data;
1916 		iov.iov_len = len;
1917 		uio.uio_iov = &iov;
1918 		uio.uio_iovcnt = 1;
1919 		uio.uio_resid = len;
1920 		uio.uio_offset = 0;
1921 		uio.uio_rw = UIO_READ;
1922 		uio.uio_vmspace = l->l_proc->p_vmspace;
1923 		error = uiomove((void *)cdesc, len, &uio);
1924 		kmem_free(cdesc, cdesclen);
1925 		return error;
1926 	}
1927 	case USB_GET_STRING_DESC: {
1928 		int len;
1929 		si = (struct usb_string_desc *)addr;
1930 		err = usbd_get_string_desc(sc->sc_udev, si->usd_string_index,
1931 			  si->usd_language_id, &si->usd_desc, &len);
1932 		if (err)
1933 			return EINVAL;
1934 		break;
1935 	}
1936 	case USB_DO_REQUEST:
1937 	{
1938 		struct usb_ctl_request *ur = (void *)addr;
1939 		int len = UGETW(ur->ucr_request.wLength);
1940 		struct iovec iov;
1941 		struct uio uio;
1942 		void *ptr = 0;
1943 		usbd_status xerr;
1944 
1945 		error = 0;
1946 
1947 		if (!(flag & FWRITE))
1948 			return EPERM;
1949 		/* Avoid requests that would damage the bus integrity. */
1950 		if ((ur->ucr_request.bmRequestType == UT_WRITE_DEVICE &&
1951 		     ur->ucr_request.bRequest == UR_SET_ADDRESS) ||
1952 		    (ur->ucr_request.bmRequestType == UT_WRITE_DEVICE &&
1953 		     ur->ucr_request.bRequest == UR_SET_CONFIG) ||
1954 		    (ur->ucr_request.bmRequestType == UT_WRITE_INTERFACE &&
1955 		     ur->ucr_request.bRequest == UR_SET_INTERFACE))
1956 			return EINVAL;
1957 
1958 		if (len < 0 || len > 32767)
1959 			return EINVAL;
1960 		if (len != 0) {
1961 			iov.iov_base = (void *)ur->ucr_data;
1962 			iov.iov_len = len;
1963 			uio.uio_iov = &iov;
1964 			uio.uio_iovcnt = 1;
1965 			uio.uio_resid = len;
1966 			uio.uio_offset = 0;
1967 			uio.uio_rw =
1968 				ur->ucr_request.bmRequestType & UT_READ ?
1969 				UIO_READ : UIO_WRITE;
1970 			uio.uio_vmspace = l->l_proc->p_vmspace;
1971 			ptr = kmem_alloc(len, KM_SLEEP);
1972 			if (uio.uio_rw == UIO_WRITE) {
1973 				error = uiomove(ptr, len, &uio);
1974 				if (error)
1975 					goto ret;
1976 			}
1977 		}
1978 		sce = &sc->sc_endpoints[endpt][IN];
1979 		xerr = usbd_do_request_flags(sc->sc_udev, &ur->ucr_request,
1980 			  ptr, ur->ucr_flags, &ur->ucr_actlen, sce->timeout);
1981 		if (xerr) {
1982 			error = EIO;
1983 			goto ret;
1984 		}
1985 		if (len != 0) {
1986 			if (uio.uio_rw == UIO_READ) {
1987 				size_t alen = uimin(len, ur->ucr_actlen);
1988 				error = uiomove(ptr, alen, &uio);
1989 				if (error)
1990 					goto ret;
1991 			}
1992 		}
1993 	ret:
1994 		if (ptr)
1995 			kmem_free(ptr, len);
1996 		return error;
1997 	}
1998 	case USB_GET_DEVICEINFO:
1999 		usbd_fill_deviceinfo(sc->sc_udev,
2000 				     (struct usb_device_info *)addr, 0);
2001 		break;
2002 	case USB_GET_DEVICEINFO_OLD:
2003 	{
2004 		int ret;
2005 		MODULE_HOOK_CALL(usb_subr_fill_30_hook,
2006 		    (sc->sc_udev, (struct usb_device_info_old *)addr, 0,
2007 		      usbd_devinfo_vp, usbd_printBCD),
2008 		    enosys(), ret);
2009 		if (ret == 0)
2010 			return 0;
2011 		return EINVAL;
2012 	}
2013 	default:
2014 		return EINVAL;
2015 	}
2016 	return 0;
2017 }
2018 
2019 static int
2020 ugenioctl(dev_t dev, u_long cmd, void *addr, int flag, struct lwp *l)
2021 {
2022 	int endpt = UGENENDPOINT(dev);
2023 	struct ugen_softc *sc;
2024 	int error;
2025 
2026 	if ((sc = ugenif_acquire(UGENUNIT(dev))) == 0)
2027 		return ENXIO;
2028 	error = ugen_do_ioctl(sc, endpt, cmd, addr, flag, l);
2029 	ugenif_release(sc);
2030 
2031 	return error;
2032 }
2033 
2034 static int
2035 ugenpoll(dev_t dev, int events, struct lwp *l)
2036 {
2037 	struct ugen_softc *sc;
2038 	struct ugen_endpoint *sce_in, *sce_out;
2039 	int revents = 0;
2040 
2041 	if ((sc = ugenif_acquire(UGENUNIT(dev))) == NULL)
2042 		return POLLHUP;
2043 
2044 	if (UGENENDPOINT(dev) == USB_CONTROL_ENDPOINT) {
2045 		revents |= POLLERR;
2046 		goto out;
2047 	}
2048 
2049 	sce_in = &sc->sc_endpoints[UGENENDPOINT(dev)][IN];
2050 	sce_out = &sc->sc_endpoints[UGENENDPOINT(dev)][OUT];
2051 	KASSERT(sce_in->edesc || sce_out->edesc);
2052 	KASSERT(sce_in->pipeh || sce_out->pipeh);
2053 
2054 	mutex_enter(&sc->sc_lock);
2055 	if (sce_in && sce_in->pipeh && (events & (POLLIN | POLLRDNORM)))
2056 		switch (sce_in->edesc->bmAttributes & UE_XFERTYPE) {
2057 		case UE_INTERRUPT:
2058 			if (sce_in->q.c_cc > 0)
2059 				revents |= events & (POLLIN | POLLRDNORM);
2060 			else
2061 				selrecord(l, &sce_in->rsel);
2062 			break;
2063 		case UE_ISOCHRONOUS:
2064 			if (sce_in->cur != sce_in->fill)
2065 				revents |= events & (POLLIN | POLLRDNORM);
2066 			else
2067 				selrecord(l, &sce_in->rsel);
2068 			break;
2069 		case UE_BULK:
2070 			if (sce_in->state & UGEN_BULK_RA) {
2071 				if (sce_in->ra_wb_used > 0)
2072 					revents |= events &
2073 					    (POLLIN | POLLRDNORM);
2074 				else
2075 					selrecord(l, &sce_in->rsel);
2076 				break;
2077 			}
2078 			/*
2079 			 * We have no easy way of determining if a read will
2080 			 * yield any data or a write will happen.
2081 			 * Pretend they will.
2082 			 */
2083 			revents |= events & (POLLIN | POLLRDNORM);
2084 			break;
2085 		default:
2086 			break;
2087 		}
2088 	if (sce_out && sce_out->pipeh && (events & (POLLOUT | POLLWRNORM)))
2089 		switch (sce_out->edesc->bmAttributes & UE_XFERTYPE) {
2090 		case UE_INTERRUPT:
2091 		case UE_ISOCHRONOUS:
2092 			/* XXX unimplemented */
2093 			break;
2094 		case UE_BULK:
2095 			if (sce_out->state & UGEN_BULK_WB) {
2096 				if (sce_out->ra_wb_used <
2097 				    sce_out->limit - sce_out->ibuf)
2098 					revents |= events &
2099 					    (POLLOUT | POLLWRNORM);
2100 				else
2101 					selrecord(l, &sce_out->rsel);
2102 				break;
2103 			}
2104 			/*
2105 			 * We have no easy way of determining if a read will
2106 			 * yield any data or a write will happen.
2107 			 * Pretend they will.
2108 			 */
2109 			 revents |= events & (POLLOUT | POLLWRNORM);
2110 			 break;
2111 		default:
2112 			break;
2113 		}
2114 
2115 	mutex_exit(&sc->sc_lock);
2116 
2117 out:	ugenif_release(sc);
2118 	return revents;
2119 }
2120 
2121 static void
2122 filt_ugenrdetach(struct knote *kn)
2123 {
2124 	struct ugen_endpoint *sce = kn->kn_hook;
2125 	struct ugen_softc *sc = sce->sc;
2126 
2127 	mutex_enter(&sc->sc_lock);
2128 	selremove_knote(&sce->rsel, kn);
2129 	mutex_exit(&sc->sc_lock);
2130 }
2131 
2132 static int
2133 filt_ugenread_intr(struct knote *kn, long hint)
2134 {
2135 	struct ugen_endpoint *sce = kn->kn_hook;
2136 	struct ugen_softc *sc = sce->sc;
2137 	int ret;
2138 
2139 	mutex_enter(&sc->sc_lock);
2140 	if (sc->sc_dying) {
2141 		ret = 0;
2142 	} else {
2143 		kn->kn_data = sce->q.c_cc;
2144 		ret = kn->kn_data > 0;
2145 	}
2146 	mutex_exit(&sc->sc_lock);
2147 
2148 	return ret;
2149 }
2150 
2151 static int
2152 filt_ugenread_isoc(struct knote *kn, long hint)
2153 {
2154 	struct ugen_endpoint *sce = kn->kn_hook;
2155 	struct ugen_softc *sc = sce->sc;
2156 	int ret;
2157 
2158 	mutex_enter(&sc->sc_lock);
2159 	if (sc->sc_dying) {
2160 		ret = 0;
2161 	} else if (sce->cur == sce->fill) {
2162 		ret = 0;
2163 	} else if (sce->cur < sce->fill) {
2164 		kn->kn_data = sce->fill - sce->cur;
2165 		ret = 1;
2166 	} else {
2167 		kn->kn_data = (sce->limit - sce->cur) +
2168 		    (sce->fill - sce->ibuf);
2169 		ret = 1;
2170 	}
2171 	mutex_exit(&sc->sc_lock);
2172 
2173 	return ret;
2174 }
2175 
2176 static int
2177 filt_ugenread_bulk(struct knote *kn, long hint)
2178 {
2179 	struct ugen_endpoint *sce = kn->kn_hook;
2180 	struct ugen_softc *sc = sce->sc;
2181 	int ret;
2182 
2183 	mutex_enter(&sc->sc_lock);
2184 	if (sc->sc_dying) {
2185 		ret = 0;
2186 	} else if (!(sce->state & UGEN_BULK_RA)) {
2187 		/*
2188 		 * We have no easy way of determining if a read will
2189 		 * yield any data or a write will happen.
2190 		 * So, emulate "seltrue".
2191 		 */
2192 		ret = filt_seltrue(kn, hint);
2193 	} else if (sce->ra_wb_used == 0) {
2194 		ret = 0;
2195 	} else {
2196 		kn->kn_data = sce->ra_wb_used;
2197 		ret = 1;
2198 	}
2199 	mutex_exit(&sc->sc_lock);
2200 
2201 	return ret;
2202 }
2203 
2204 static int
2205 filt_ugenwrite_bulk(struct knote *kn, long hint)
2206 {
2207 	struct ugen_endpoint *sce = kn->kn_hook;
2208 	struct ugen_softc *sc = sce->sc;
2209 	int ret;
2210 
2211 	mutex_enter(&sc->sc_lock);
2212 	if (sc->sc_dying) {
2213 		ret = 0;
2214 	} else if (!(sce->state & UGEN_BULK_WB)) {
2215 		/*
2216 		 * We have no easy way of determining if a read will
2217 		 * yield any data or a write will happen.
2218 		 * So, emulate "seltrue".
2219 		 */
2220 		ret = filt_seltrue(kn, hint);
2221 	} else if (sce->ra_wb_used == sce->limit - sce->ibuf) {
2222 		ret = 0;
2223 	} else {
2224 		kn->kn_data = (sce->limit - sce->ibuf) - sce->ra_wb_used;
2225 		ret = 1;
2226 	}
2227 	mutex_exit(&sc->sc_lock);
2228 
2229 	return ret;
2230 }
2231 
2232 static const struct filterops ugenread_intr_filtops = {
2233 	.f_flags = FILTEROP_ISFD,
2234 	.f_attach = NULL,
2235 	.f_detach = filt_ugenrdetach,
2236 	.f_event = filt_ugenread_intr,
2237 };
2238 
2239 static const struct filterops ugenread_isoc_filtops = {
2240 	.f_flags = FILTEROP_ISFD,
2241 	.f_attach = NULL,
2242 	.f_detach = filt_ugenrdetach,
2243 	.f_event = filt_ugenread_isoc,
2244 };
2245 
2246 static const struct filterops ugenread_bulk_filtops = {
2247 	.f_flags = FILTEROP_ISFD,
2248 	.f_attach = NULL,
2249 	.f_detach = filt_ugenrdetach,
2250 	.f_event = filt_ugenread_bulk,
2251 };
2252 
2253 static const struct filterops ugenwrite_bulk_filtops = {
2254 	.f_flags = FILTEROP_ISFD,
2255 	.f_attach = NULL,
2256 	.f_detach = filt_ugenrdetach,
2257 	.f_event = filt_ugenwrite_bulk,
2258 };
2259 
2260 static int
2261 ugenkqfilter(dev_t dev, struct knote *kn)
2262 {
2263 	struct ugen_softc *sc;
2264 	struct ugen_endpoint *sce;
2265 	struct selinfo *sip;
2266 	int error;
2267 
2268 	if ((sc = ugenif_acquire(UGENUNIT(dev))) == NULL)
2269 		return ENXIO;
2270 
2271 	if (UGENENDPOINT(dev) == USB_CONTROL_ENDPOINT) {
2272 		error = ENODEV;
2273 		goto out;
2274 	}
2275 
2276 	switch (kn->kn_filter) {
2277 	case EVFILT_READ:
2278 		sce = &sc->sc_endpoints[UGENENDPOINT(dev)][IN];
2279 		if (sce == NULL) {
2280 			error = EINVAL;
2281 			goto out;
2282 		}
2283 
2284 		sip = &sce->rsel;
2285 		switch (sce->edesc->bmAttributes & UE_XFERTYPE) {
2286 		case UE_INTERRUPT:
2287 			kn->kn_fop = &ugenread_intr_filtops;
2288 			break;
2289 		case UE_ISOCHRONOUS:
2290 			kn->kn_fop = &ugenread_isoc_filtops;
2291 			break;
2292 		case UE_BULK:
2293 			kn->kn_fop = &ugenread_bulk_filtops;
2294 			break;
2295 		default:
2296 			error = EINVAL;
2297 			goto out;
2298 		}
2299 		break;
2300 
2301 	case EVFILT_WRITE:
2302 		sce = &sc->sc_endpoints[UGENENDPOINT(dev)][OUT];
2303 		if (sce == NULL) {
2304 			error = EINVAL;
2305 			goto out;
2306 		}
2307 
2308 		sip = &sce->rsel;
2309 		switch (sce->edesc->bmAttributes & UE_XFERTYPE) {
2310 		case UE_INTERRUPT:
2311 		case UE_ISOCHRONOUS:
2312 			/* XXX poll doesn't support this */
2313 			error = EINVAL;
2314 			goto out;
2315 
2316 		case UE_BULK:
2317 			kn->kn_fop = &ugenwrite_bulk_filtops;
2318 			break;
2319 		default:
2320 			error = EINVAL;
2321 			goto out;
2322 		}
2323 		break;
2324 
2325 	default:
2326 		error = EINVAL;
2327 		goto out;
2328 	}
2329 
2330 	kn->kn_hook = sce;
2331 
2332 	mutex_enter(&sc->sc_lock);
2333 	selrecord_knote(sip, kn);
2334 	mutex_exit(&sc->sc_lock);
2335 
2336 	error = 0;
2337 
2338 out:	ugenif_release(sc);
2339 	return error;
2340 }
2341 
2342 MODULE(MODULE_CLASS_DRIVER, ugen, NULL);
2343 
2344 static int
2345 ugen_modcmd(modcmd_t cmd, void *aux)
2346 {
2347 
2348 	switch (cmd) {
2349 	case MODULE_CMD_INIT:
2350 		mutex_init(&ugenif.lock, MUTEX_DEFAULT, IPL_NONE);
2351 		rb_tree_init(&ugenif.tree, &ugenif_tree_ops);
2352 		return 0;
2353 	default:
2354 		return ENOTTY;
2355 	}
2356 }
2357