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