xref: /freebsd/sys/dev/usb/usb_generic.c (revision 397e83df75e0fcd0d3fcb95ae4d794cb7600fc89)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2008-2023 Hans Petter Selasky
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27 
28 #ifdef USB_GLOBAL_INCLUDE_FILE
29 #include USB_GLOBAL_INCLUDE_FILE
30 #else
31 #ifdef COMPAT_FREEBSD32
32 #include <sys/abi_compat.h>
33 #endif
34 #include <sys/stdint.h>
35 #include <sys/stddef.h>
36 #include <sys/param.h>
37 #include <sys/queue.h>
38 #include <sys/types.h>
39 #include <sys/systm.h>
40 #include <sys/kernel.h>
41 #include <sys/bus.h>
42 #include <sys/module.h>
43 #include <sys/lock.h>
44 #include <sys/mutex.h>
45 #include <sys/condvar.h>
46 #include <sys/sysctl.h>
47 #include <sys/sx.h>
48 #include <sys/unistd.h>
49 #include <sys/callout.h>
50 #include <sys/malloc.h>
51 #include <sys/priv.h>
52 #include <sys/conf.h>
53 #include <sys/fcntl.h>
54 
55 #include <dev/usb/usb.h>
56 #include <dev/usb/usb_ioctl.h>
57 #include <dev/usb/usbdi.h>
58 #include <dev/usb/usbdi_util.h>
59 
60 #define	USB_DEBUG_VAR ugen_debug
61 
62 #include <dev/usb/usb_core.h>
63 #include <dev/usb/usb_dev.h>
64 #include <dev/usb/usb_mbuf.h>
65 #include <dev/usb/usb_process.h>
66 #include <dev/usb/usb_device.h>
67 #include <dev/usb/usb_debug.h>
68 #include <dev/usb/usb_request.h>
69 #include <dev/usb/usb_busdma.h>
70 #include <dev/usb/usb_util.h>
71 #include <dev/usb/usb_hub.h>
72 #include <dev/usb/usb_generic.h>
73 #include <dev/usb/usb_transfer.h>
74 
75 #include <dev/usb/usb_controller.h>
76 #include <dev/usb/usb_bus.h>
77 #endif			/* USB_GLOBAL_INCLUDE_FILE */
78 
79 #if USB_HAVE_UGEN
80 
81 /* defines */
82 
83 #define	UGEN_BULK_FS_BUFFER_SIZE	(64*32)	/* bytes */
84 #define	UGEN_BULK_HS_BUFFER_SIZE	(1024*32)	/* bytes */
85 #define	UGEN_HW_FRAMES	50		/* number of milliseconds per transfer */
86 
87 /* function prototypes */
88 
89 static usb_callback_t ugen_read_clear_stall_callback;
90 static usb_callback_t ugen_write_clear_stall_callback;
91 static usb_callback_t ugen_ctrl_read_callback;
92 static usb_callback_t ugen_ctrl_write_callback;
93 static usb_callback_t ugen_isoc_read_callback;
94 static usb_callback_t ugen_isoc_write_callback;
95 static usb_callback_t ugen_ctrl_fs_callback;
96 
97 static usb_fifo_open_t ugen_open;
98 static usb_fifo_close_t ugen_close;
99 static usb_fifo_ioctl_t ugen_ioctl;
100 static usb_fifo_ioctl_t ugen_ioctl_post;
101 static usb_fifo_cmd_t ugen_start_read;
102 static usb_fifo_cmd_t ugen_start_write;
103 static usb_fifo_cmd_t ugen_stop_io;
104 
105 static int	ugen_transfer_setup(struct usb_fifo *,
106 		     const struct usb_config *, uint8_t);
107 static int	ugen_open_pipe_write(struct usb_fifo *);
108 static int	ugen_open_pipe_read(struct usb_fifo *);
109 static int	ugen_set_config(struct usb_fifo *, uint8_t);
110 static int	ugen_set_interface(struct usb_fifo *, uint8_t, uint8_t);
111 static int	ugen_get_cdesc(struct usb_fifo *, struct usb_gen_descriptor *);
112 static int	ugen_get_sdesc(struct usb_fifo *, struct usb_gen_descriptor *);
113 static int	ugen_get_iface_driver(struct usb_fifo *f, struct usb_gen_descriptor *ugd);
114 #ifdef COMPAT_FREEBSD32
115 static int	ugen_get32(u_long cmd, struct usb_fifo *f, struct usb_gen_descriptor32 *ugd32);
116 #endif
117 static int	ugen_re_enumerate(struct usb_fifo *);
118 static int	ugen_iface_ioctl(struct usb_fifo *, u_long, void *, int);
119 static uint8_t	ugen_fs_get_complete(struct usb_fifo *, uint8_t *);
120 static int	ugen_fs_uninit(struct usb_fifo *f);
121 static int	ugen_fs_copyin(struct usb_fifo *, uint8_t, struct usb_fs_endpoint*);
122 static uint8_t	ugen_fifo_in_use(struct usb_fifo *, int fflags);
123 
124 /* structures */
125 
126 struct usb_fifo_methods usb_ugen_methods = {
127 	.f_open = &ugen_open,
128 	.f_close = &ugen_close,
129 	.f_ioctl = &ugen_ioctl,
130 	.f_ioctl_post = &ugen_ioctl_post,
131 	.f_start_read = &ugen_start_read,
132 	.f_stop_read = &ugen_stop_io,
133 	.f_start_write = &ugen_start_write,
134 	.f_stop_write = &ugen_stop_io,
135 };
136 
137 #ifdef USB_DEBUG
138 static int ugen_debug = 0;
139 
140 static SYSCTL_NODE(_hw_usb, OID_AUTO, ugen, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
141     "USB generic");
142 SYSCTL_INT(_hw_usb_ugen, OID_AUTO, debug, CTLFLAG_RWTUN, &ugen_debug,
143     0, "Debug level");
144 #endif
145 
146 /* prototypes */
147 
148 static int
149 ugen_transfer_setup(struct usb_fifo *f,
150     const struct usb_config *setup, uint8_t n_setup)
151 {
152 	struct usb_endpoint *ep = usb_fifo_softc(f);
153 	struct usb_device *udev = f->udev;
154 	uint8_t iface_index = ep->iface_index;
155 	int error;
156 
157 	mtx_unlock(f->priv_mtx);
158 
159 	/*
160 	 * "usbd_transfer_setup()" can sleep so one needs to make a wrapper,
161 	 * exiting the mutex and checking things
162 	 */
163 	error = usbd_transfer_setup(udev, &iface_index, f->xfer,
164 	    setup, n_setup, f, f->priv_mtx);
165 	if (error == 0) {
166 		if (f->xfer[0]->nframes == 1) {
167 			error = usb_fifo_alloc_buffer(f,
168 			    f->xfer[0]->max_data_length, 2);
169 		} else {
170 			error = usb_fifo_alloc_buffer(f,
171 			    f->xfer[0]->max_frame_size,
172 			    2 * f->xfer[0]->nframes);
173 		}
174 		if (error) {
175 			usbd_transfer_unsetup(f->xfer, n_setup);
176 		}
177 	}
178 	mtx_lock(f->priv_mtx);
179 
180 	return (error);
181 }
182 
183 static int
184 ugen_open(struct usb_fifo *f, int fflags)
185 {
186 	struct usb_endpoint *ep = usb_fifo_softc(f);
187 	struct usb_endpoint_descriptor *ed = ep->edesc;
188 	uint8_t type;
189 
190 	DPRINTFN(1, "flag=0x%x pid=%d name=%s\n", fflags,
191 	    curthread->td_proc->p_pid, curthread->td_proc->p_comm);
192 
193 	mtx_lock(f->priv_mtx);
194 	switch (usbd_get_speed(f->udev)) {
195 	case USB_SPEED_LOW:
196 	case USB_SPEED_FULL:
197 		f->nframes = UGEN_HW_FRAMES;
198 		f->bufsize = UGEN_BULK_FS_BUFFER_SIZE;
199 		break;
200 	default:
201 		f->nframes = UGEN_HW_FRAMES * 8;
202 		f->bufsize = UGEN_BULK_HS_BUFFER_SIZE;
203 		break;
204 	}
205 
206 	type = ed->bmAttributes & UE_XFERTYPE;
207 	if (type == UE_INTERRUPT) {
208 		f->bufsize = 0;		/* use "wMaxPacketSize" */
209 	}
210 	f->timeout = USB_NO_TIMEOUT;
211 	f->flag_short = 0;
212 	f->fifo_zlp = 0;
213 	mtx_unlock(f->priv_mtx);
214 
215 	return (0);
216 }
217 
218 static void
219 ugen_close(struct usb_fifo *f, int fflags)
220 {
221 
222 	DPRINTFN(1, "flag=0x%x pid=%d name=%s\n", fflags,
223 	    curthread->td_proc->p_pid, curthread->td_proc->p_comm);
224 
225 	/* cleanup */
226 
227 	mtx_lock(f->priv_mtx);
228 	usbd_transfer_stop(f->xfer[0]);
229 	usbd_transfer_stop(f->xfer[1]);
230 	mtx_unlock(f->priv_mtx);
231 
232 	usbd_transfer_unsetup(f->xfer, 2);
233 	usb_fifo_free_buffer(f);
234 
235 	if (ugen_fs_uninit(f)) {
236 		/* ignore any errors - we are closing */
237 		DPRINTFN(6, "no FIFOs\n");
238 	}
239 }
240 
241 static int
242 ugen_open_pipe_write(struct usb_fifo *f)
243 {
244 	struct usb_config usb_config[2];
245 	struct usb_endpoint *ep = usb_fifo_softc(f);
246 	struct usb_endpoint_descriptor *ed = ep->edesc;
247 
248 	USB_MTX_ASSERT(f->priv_mtx, MA_OWNED);
249 
250 	if (f->xfer[0] || f->xfer[1]) {
251 		/* transfers are already opened */
252 		return (0);
253 	}
254 	memset(usb_config, 0, sizeof(usb_config));
255 
256 	usb_config[1].type = UE_CONTROL;
257 	usb_config[1].endpoint = 0;
258 	usb_config[1].direction = UE_DIR_ANY;
259 	usb_config[1].timeout = 1000;	/* 1 second */
260 	usb_config[1].interval = 50;/* 50 milliseconds */
261 	usb_config[1].bufsize = sizeof(struct usb_device_request);
262 	usb_config[1].callback = &ugen_write_clear_stall_callback;
263 	usb_config[1].usb_mode = USB_MODE_HOST;
264 
265 	usb_config[0].type = ed->bmAttributes & UE_XFERTYPE;
266 	usb_config[0].endpoint = ed->bEndpointAddress & UE_ADDR;
267 	usb_config[0].stream_id = 0;	/* XXX support more stream ID's */
268 	usb_config[0].direction = UE_DIR_TX;
269 	usb_config[0].interval = USB_DEFAULT_INTERVAL;
270 	usb_config[0].flags.proxy_buffer = 1;
271 	usb_config[0].usb_mode = USB_MODE_DUAL;	/* both modes */
272 
273 	switch (ed->bmAttributes & UE_XFERTYPE) {
274 	case UE_INTERRUPT:
275 	case UE_BULK:
276 		if (f->flag_short) {
277 			usb_config[0].flags.force_short_xfer = 1;
278 		}
279 		usb_config[0].callback = &ugen_ctrl_write_callback;
280 		usb_config[0].timeout = f->timeout;
281 		usb_config[0].frames = 1;
282 		usb_config[0].bufsize = f->bufsize;
283 		if (ugen_transfer_setup(f, usb_config, 2)) {
284 			return (EIO);
285 		}
286 		/* first transfer does not clear stall */
287 		f->flag_stall = 0;
288 		break;
289 
290 	case UE_ISOCHRONOUS:
291 		usb_config[0].flags.short_xfer_ok = 1;
292 		usb_config[0].bufsize = 0;	/* use default */
293 		usb_config[0].frames = f->nframes;
294 		usb_config[0].callback = &ugen_isoc_write_callback;
295 		usb_config[0].timeout = 0;
296 
297 		/* clone configuration */
298 		usb_config[1] = usb_config[0];
299 
300 		if (ugen_transfer_setup(f, usb_config, 2)) {
301 			return (EIO);
302 		}
303 		break;
304 	default:
305 		return (EINVAL);
306 	}
307 	return (0);
308 }
309 
310 static int
311 ugen_open_pipe_read(struct usb_fifo *f)
312 {
313 	struct usb_config usb_config[2];
314 	struct usb_endpoint *ep = usb_fifo_softc(f);
315 	struct usb_endpoint_descriptor *ed = ep->edesc;
316 
317 	USB_MTX_ASSERT(f->priv_mtx, MA_OWNED);
318 
319 	if (f->xfer[0] || f->xfer[1]) {
320 		/* transfers are already opened */
321 		return (0);
322 	}
323 	memset(usb_config, 0, sizeof(usb_config));
324 
325 	usb_config[1].type = UE_CONTROL;
326 	usb_config[1].endpoint = 0;
327 	usb_config[1].direction = UE_DIR_ANY;
328 	usb_config[1].timeout = 1000;	/* 1 second */
329 	usb_config[1].interval = 50;/* 50 milliseconds */
330 	usb_config[1].bufsize = sizeof(struct usb_device_request);
331 	usb_config[1].callback = &ugen_read_clear_stall_callback;
332 	usb_config[1].usb_mode = USB_MODE_HOST;
333 
334 	usb_config[0].type = ed->bmAttributes & UE_XFERTYPE;
335 	usb_config[0].endpoint = ed->bEndpointAddress & UE_ADDR;
336 	usb_config[0].stream_id = 0;	/* XXX support more stream ID's */
337 	usb_config[0].direction = UE_DIR_RX;
338 	usb_config[0].interval = USB_DEFAULT_INTERVAL;
339 	usb_config[0].flags.proxy_buffer = 1;
340 	usb_config[0].usb_mode = USB_MODE_DUAL;	/* both modes */
341 
342 	switch (ed->bmAttributes & UE_XFERTYPE) {
343 	case UE_INTERRUPT:
344 	case UE_BULK:
345 		if (f->flag_short) {
346 			usb_config[0].flags.short_xfer_ok = 1;
347 		}
348 		usb_config[0].timeout = f->timeout;
349 		usb_config[0].frames = 1;
350 		usb_config[0].callback = &ugen_ctrl_read_callback;
351 		usb_config[0].bufsize = f->bufsize;
352 
353 		if (ugen_transfer_setup(f, usb_config, 2)) {
354 			return (EIO);
355 		}
356 		/* first transfer does not clear stall */
357 		f->flag_stall = 0;
358 		break;
359 
360 	case UE_ISOCHRONOUS:
361 		usb_config[0].flags.short_xfer_ok = 1;
362 		usb_config[0].bufsize = 0;	/* use default */
363 		usb_config[0].frames = f->nframes;
364 		usb_config[0].callback = &ugen_isoc_read_callback;
365 		usb_config[0].timeout = 0;
366 
367 		/* clone configuration */
368 		usb_config[1] = usb_config[0];
369 
370 		if (ugen_transfer_setup(f, usb_config, 2)) {
371 			return (EIO);
372 		}
373 		break;
374 
375 	default:
376 		return (EINVAL);
377 	}
378 	return (0);
379 }
380 
381 static void
382 ugen_start_read(struct usb_fifo *f)
383 {
384 	/* check that pipes are open */
385 	if (ugen_open_pipe_read(f)) {
386 		/* signal error */
387 		usb_fifo_put_data_error(f);
388 	}
389 	/* start transfers */
390 	usbd_transfer_start(f->xfer[0]);
391 	usbd_transfer_start(f->xfer[1]);
392 }
393 
394 static void
395 ugen_start_write(struct usb_fifo *f)
396 {
397 	/* check that pipes are open */
398 	if (ugen_open_pipe_write(f)) {
399 		/* signal error */
400 		usb_fifo_get_data_error(f);
401 	}
402 	/* start transfers */
403 	usbd_transfer_start(f->xfer[0]);
404 	usbd_transfer_start(f->xfer[1]);
405 }
406 
407 static void
408 ugen_stop_io(struct usb_fifo *f)
409 {
410 	/* stop transfers */
411 	usbd_transfer_stop(f->xfer[0]);
412 	usbd_transfer_stop(f->xfer[1]);
413 }
414 
415 static void
416 ugen_ctrl_read_callback(struct usb_xfer *xfer, usb_error_t error)
417 {
418 	struct usb_fifo *f = usbd_xfer_softc(xfer);
419 	struct usb_mbuf *m;
420 
421 	DPRINTFN(4, "actlen=%u, aframes=%u\n", xfer->actlen, xfer->aframes);
422 
423 	switch (USB_GET_STATE(xfer)) {
424 	case USB_ST_TRANSFERRED:
425 		if (xfer->actlen == 0) {
426 			if (f->fifo_zlp != 4) {
427 				f->fifo_zlp++;
428 			} else {
429 				/*
430 				 * Throttle a little bit we have multiple ZLPs
431 				 * in a row!
432 				 */
433 				xfer->interval = 64;	/* ms */
434 			}
435 		} else {
436 			/* clear throttle */
437 			xfer->interval = 0;
438 			f->fifo_zlp = 0;
439 		}
440 		usb_fifo_put_data(f, xfer->frbuffers, 0,
441 		    xfer->actlen, 1);
442 
443 	case USB_ST_SETUP:
444 		if (f->flag_stall) {
445 			usbd_transfer_start(f->xfer[1]);
446 			break;
447 		}
448 		USB_IF_POLL(&f->free_q, m);
449 		if (m) {
450 			usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
451 			usbd_transfer_submit(xfer);
452 		}
453 		break;
454 
455 	default:			/* Error */
456 		if (xfer->error != USB_ERR_CANCELLED) {
457 			/* send a zero length packet to userland */
458 			usb_fifo_put_data(f, xfer->frbuffers, 0, 0, 1);
459 			f->flag_stall = 1;
460 			f->fifo_zlp = 0;
461 			usbd_transfer_start(f->xfer[1]);
462 		}
463 		break;
464 	}
465 }
466 
467 static void
468 ugen_ctrl_write_callback(struct usb_xfer *xfer, usb_error_t error)
469 {
470 	struct usb_fifo *f = usbd_xfer_softc(xfer);
471 	usb_frlength_t actlen;
472 
473 	DPRINTFN(4, "actlen=%u, aframes=%u\n", xfer->actlen, xfer->aframes);
474 
475 	switch (USB_GET_STATE(xfer)) {
476 	case USB_ST_SETUP:
477 	case USB_ST_TRANSFERRED:
478 		/*
479 		 * If writing is in stall, just jump to clear stall
480 		 * callback and solve the situation.
481 		 */
482 		if (f->flag_stall) {
483 			usbd_transfer_start(f->xfer[1]);
484 			break;
485 		}
486 		/*
487 		 * Write data, setup and perform hardware transfer.
488 		 */
489 		if (usb_fifo_get_data(f, xfer->frbuffers, 0,
490 		    xfer->max_data_length, &actlen, 0)) {
491 			usbd_xfer_set_frame_len(xfer, 0, actlen);
492 			usbd_transfer_submit(xfer);
493 		}
494 		break;
495 
496 	default:			/* Error */
497 		if (xfer->error != USB_ERR_CANCELLED) {
498 			f->flag_stall = 1;
499 			usbd_transfer_start(f->xfer[1]);
500 		}
501 		break;
502 	}
503 }
504 
505 static void
506 ugen_read_clear_stall_callback(struct usb_xfer *xfer, usb_error_t error)
507 {
508 	struct usb_fifo *f = usbd_xfer_softc(xfer);
509 	struct usb_xfer *xfer_other = f->xfer[0];
510 
511 	if (f->flag_stall == 0) {
512 		/* nothing to do */
513 		return;
514 	}
515 	if (usbd_clear_stall_callback(xfer, xfer_other)) {
516 		DPRINTFN(5, "f=%p: stall cleared\n", f);
517 		f->flag_stall = 0;
518 		usbd_transfer_start(xfer_other);
519 	}
520 }
521 
522 static void
523 ugen_write_clear_stall_callback(struct usb_xfer *xfer, usb_error_t error)
524 {
525 	struct usb_fifo *f = usbd_xfer_softc(xfer);
526 	struct usb_xfer *xfer_other = f->xfer[0];
527 
528 	if (f->flag_stall == 0) {
529 		/* nothing to do */
530 		return;
531 	}
532 	if (usbd_clear_stall_callback(xfer, xfer_other)) {
533 		DPRINTFN(5, "f=%p: stall cleared\n", f);
534 		f->flag_stall = 0;
535 		usbd_transfer_start(xfer_other);
536 	}
537 }
538 
539 static void
540 ugen_isoc_read_callback(struct usb_xfer *xfer, usb_error_t error)
541 {
542 	struct usb_fifo *f = usbd_xfer_softc(xfer);
543 	usb_frlength_t offset;
544 	usb_frcount_t n;
545 
546 	DPRINTFN(4, "actlen=%u, aframes=%u\n", xfer->actlen, xfer->aframes);
547 
548 	switch (USB_GET_STATE(xfer)) {
549 	case USB_ST_TRANSFERRED:
550 
551 		DPRINTFN(6, "actlen=%d\n", xfer->actlen);
552 
553 		offset = 0;
554 
555 		for (n = 0; n != xfer->aframes; n++) {
556 			usb_fifo_put_data(f, xfer->frbuffers, offset,
557 			    xfer->frlengths[n], 1);
558 			offset += xfer->max_frame_size;
559 		}
560 
561 	case USB_ST_SETUP:
562 tr_setup:
563 		for (n = 0; n != xfer->nframes; n++) {
564 			/* setup size for next transfer */
565 			usbd_xfer_set_frame_len(xfer, n, xfer->max_frame_size);
566 		}
567 		usbd_transfer_submit(xfer);
568 		break;
569 
570 	default:			/* Error */
571 		if (xfer->error == USB_ERR_CANCELLED) {
572 			break;
573 		}
574 		goto tr_setup;
575 	}
576 }
577 
578 static void
579 ugen_isoc_write_callback(struct usb_xfer *xfer, usb_error_t error)
580 {
581 	struct usb_fifo *f = usbd_xfer_softc(xfer);
582 	usb_frlength_t actlen;
583 	usb_frlength_t offset;
584 	usb_frcount_t n;
585 
586 	DPRINTFN(4, "actlen=%u, aframes=%u\n", xfer->actlen, xfer->aframes);
587 
588 	switch (USB_GET_STATE(xfer)) {
589 	case USB_ST_TRANSFERRED:
590 	case USB_ST_SETUP:
591 tr_setup:
592 		offset = 0;
593 		for (n = 0; n != xfer->nframes; n++) {
594 			if (usb_fifo_get_data(f, xfer->frbuffers, offset,
595 			    xfer->max_frame_size, &actlen, 1)) {
596 				usbd_xfer_set_frame_len(xfer, n, actlen);
597 				offset += actlen;
598 			} else {
599 				break;
600 			}
601 		}
602 
603 		for (; n != xfer->nframes; n++) {
604 			/* fill in zero frames */
605 			usbd_xfer_set_frame_len(xfer, n, 0);
606 		}
607 		usbd_transfer_submit(xfer);
608 		break;
609 
610 	default:			/* Error */
611 		if (xfer->error == USB_ERR_CANCELLED) {
612 			break;
613 		}
614 		goto tr_setup;
615 	}
616 }
617 
618 static int
619 ugen_set_config(struct usb_fifo *f, uint8_t index)
620 {
621 	DPRINTFN(2, "index %u\n", index);
622 
623 	if (f->udev->flags.usb_mode != USB_MODE_HOST) {
624 		/* not possible in device side mode */
625 		return (ENOTTY);
626 	}
627 
628 	/* make sure all FIFO's are gone */
629 	/* else there can be a deadlock */
630 	if (ugen_fs_uninit(f)) {
631 		/* ignore any errors */
632 		DPRINTFN(6, "no FIFOs\n");
633 	}
634 
635 	if (usbd_start_set_config(f->udev, index) != 0)
636 		return (EIO);
637 
638 	return (0);
639 }
640 
641 static int
642 ugen_set_interface(struct usb_fifo *f,
643     uint8_t iface_index, uint8_t alt_index)
644 {
645 	DPRINTFN(2, "%u, %u\n", iface_index, alt_index);
646 
647 	if (f->udev->flags.usb_mode != USB_MODE_HOST) {
648 		/* not possible in device side mode */
649 		return (ENOTTY);
650 	}
651 	/* make sure all FIFO's are gone */
652 	/* else there can be a deadlock */
653 	if (ugen_fs_uninit(f)) {
654 		/* ignore any errors */
655 		DPRINTFN(6, "no FIFOs\n");
656 	}
657 	/* change setting - will free generic FIFOs, if any */
658 	if (usbd_set_alt_interface_index(f->udev, iface_index, alt_index)) {
659 		return (EIO);
660 	}
661 	/* probe and attach */
662 	if (usb_probe_and_attach(f->udev, iface_index)) {
663 		return (EIO);
664 	}
665 	return (0);
666 }
667 
668 /*------------------------------------------------------------------------*
669  *	ugen_get_cdesc
670  *
671  * This function will retrieve the complete configuration descriptor
672  * at the given index.
673  *------------------------------------------------------------------------*/
674 static int
675 ugen_get_cdesc(struct usb_fifo *f, struct usb_gen_descriptor *ugd)
676 {
677 	struct usb_config_descriptor *cdesc;
678 	struct usb_device *udev = f->udev;
679 	int error;
680 	uint16_t len;
681 	uint8_t free_data;
682 
683 	DPRINTFN(6, "\n");
684 
685 	if (ugd->ugd_data == NULL) {
686 		/* userland pointer should not be zero */
687 		return (EINVAL);
688 	}
689 	if ((ugd->ugd_config_index == USB_UNCONFIG_INDEX) ||
690 	    (ugd->ugd_config_index == udev->curr_config_index)) {
691 		cdesc = usbd_get_config_descriptor(udev);
692 		if (cdesc == NULL)
693 			return (ENXIO);
694 		free_data = 0;
695 
696 	} else {
697 #if (USB_HAVE_FIXED_CONFIG == 0)
698 		if (usbd_req_get_config_desc_full(udev,
699 		    NULL, &cdesc, ugd->ugd_config_index)) {
700 			return (ENXIO);
701 		}
702 		free_data = 1;
703 #else
704 		/* configuration descriptor data is shared */
705 		return (EINVAL);
706 #endif
707 	}
708 
709 	len = UGETW(cdesc->wTotalLength);
710 	if (len > ugd->ugd_maxlen) {
711 		len = ugd->ugd_maxlen;
712 	}
713 	DPRINTFN(6, "len=%u\n", len);
714 
715 	ugd->ugd_actlen = len;
716 	ugd->ugd_offset = 0;
717 
718 	error = copyout(cdesc, ugd->ugd_data, len);
719 
720 	if (free_data)
721 		usbd_free_config_desc(udev, cdesc);
722 
723 	return (error);
724 }
725 
726 static int
727 ugen_get_sdesc(struct usb_fifo *f, struct usb_gen_descriptor *ugd)
728 {
729 	void *ptr;
730 	uint16_t size;
731 	int error;
732 	uint8_t do_unlock;
733 
734 	/* Protect scratch area */
735 	do_unlock = usbd_ctrl_lock(f->udev);
736 
737 	ptr = f->udev->scratch.data;
738 	size = sizeof(f->udev->scratch.data);
739 
740 	if (usbd_req_get_string_desc(f->udev, NULL, ptr,
741 	    size, ugd->ugd_lang_id, ugd->ugd_string_index)) {
742 		error = EINVAL;
743 	} else {
744 		if (size > ((uint8_t *)ptr)[0]) {
745 			size = ((uint8_t *)ptr)[0];
746 		}
747 		if (size > ugd->ugd_maxlen) {
748 			size = ugd->ugd_maxlen;
749 		}
750 		ugd->ugd_actlen = size;
751 		ugd->ugd_offset = 0;
752 
753 		error = copyout(ptr, ugd->ugd_data, size);
754 	}
755 	if (do_unlock)
756 		usbd_ctrl_unlock(f->udev);
757 
758 	return (error);
759 }
760 
761 /*------------------------------------------------------------------------*
762  *	ugen_get_iface_driver
763  *
764  * This function generates an USB interface description for userland.
765  *
766  * Returns:
767  *    0: Success
768  * Else: Failure
769  *------------------------------------------------------------------------*/
770 static int
771 ugen_get_iface_driver(struct usb_fifo *f, struct usb_gen_descriptor *ugd)
772 {
773 	struct usb_device *udev = f->udev;
774 	struct usb_interface *iface;
775 	const char *ptr;
776 	const char *desc;
777 	unsigned len;
778 	unsigned maxlen;
779 	char buf[128];
780 	int error;
781 
782 	DPRINTFN(6, "\n");
783 
784 	if ((ugd->ugd_data == NULL) || (ugd->ugd_maxlen == 0)) {
785 		/* userland pointer should not be zero */
786 		return (EINVAL);
787 	}
788 
789 	iface = usbd_get_iface(udev, ugd->ugd_iface_index);
790 	if ((iface == NULL) || (iface->idesc == NULL)) {
791 		/* invalid interface index */
792 		return (EINVAL);
793 	}
794 
795 	/* read out device nameunit string, if any */
796 	if ((iface->subdev != NULL) &&
797 	    device_is_attached(iface->subdev) &&
798 	    (ptr = device_get_nameunit(iface->subdev)) &&
799 	    (desc = device_get_desc(iface->subdev))) {
800 		/* print description */
801 		snprintf(buf, sizeof(buf), "%s: <%s>", ptr, desc);
802 
803 		/* range checks */
804 		maxlen = ugd->ugd_maxlen - 1;
805 		len = strlen(buf);
806 		if (len > maxlen)
807 			len = maxlen;
808 
809 		/* update actual length, including terminating zero */
810 		ugd->ugd_actlen = len + 1;
811 
812 		/* copy out interface description */
813 		error = copyout(buf, ugd->ugd_data, ugd->ugd_actlen);
814 	} else {
815 		/* zero length string is default */
816 		error = copyout("", ugd->ugd_data, 1);
817 	}
818 	return (error);
819 }
820 
821 /*------------------------------------------------------------------------*
822  *	ugen_fill_deviceinfo
823  *
824  * This function dumps information about an USB device to the
825  * structure pointed to by the "di" argument.
826  *
827  * Returns:
828  *    0: Success
829  * Else: Failure
830  *------------------------------------------------------------------------*/
831 int
832 ugen_fill_deviceinfo(struct usb_fifo *f, struct usb_device_info *di)
833 {
834 	struct usb_device *udev;
835 	struct usb_device *hub;
836 
837 	udev = f->udev;
838 
839 	bzero(di, sizeof(di[0]));
840 
841 	di->udi_bus = device_get_unit(udev->bus->bdev);
842 	di->udi_addr = udev->address;
843 	di->udi_index = udev->device_index;
844 	strlcpy(di->udi_serial, usb_get_serial(udev), sizeof(di->udi_serial));
845 	strlcpy(di->udi_vendor, usb_get_manufacturer(udev), sizeof(di->udi_vendor));
846 	strlcpy(di->udi_product, usb_get_product(udev), sizeof(di->udi_product));
847 	usb_printbcd(di->udi_release, sizeof(di->udi_release),
848 	    UGETW(udev->ddesc.bcdDevice));
849 	di->udi_vendorNo = UGETW(udev->ddesc.idVendor);
850 	di->udi_productNo = UGETW(udev->ddesc.idProduct);
851 	di->udi_releaseNo = UGETW(udev->ddesc.bcdDevice);
852 	di->udi_class = udev->ddesc.bDeviceClass;
853 	di->udi_subclass = udev->ddesc.bDeviceSubClass;
854 	di->udi_protocol = udev->ddesc.bDeviceProtocol;
855 	di->udi_config_no = udev->curr_config_no;
856 	di->udi_config_index = udev->curr_config_index;
857 	di->udi_power = udev->flags.self_powered ? 0 : udev->power;
858 	di->udi_speed = udev->speed;
859 	di->udi_mode = udev->flags.usb_mode;
860 	di->udi_power_mode = udev->power_mode;
861 	di->udi_suspended = udev->flags.peer_suspended;
862 
863 	hub = udev->parent_hub;
864 	if (hub) {
865 		di->udi_hubaddr = hub->address;
866 		di->udi_hubindex = hub->device_index;
867 		di->udi_hubport = udev->port_no;
868 	}
869 	return (0);
870 }
871 
872 int
873 ugen_do_request(struct usb_fifo *f, struct usb_ctl_request *ur)
874 {
875 	int error;
876 	uint16_t len;
877 	uint16_t actlen;
878 
879 	if (usb_check_request(f->udev, &ur->ucr_request)) {
880 		return (EPERM);
881 	}
882 	len = UGETW(ur->ucr_request.wLength);
883 
884 	/* check if "ucr_data" is valid */
885 	if (len != 0) {
886 		if (ur->ucr_data == NULL) {
887 			return (EFAULT);
888 		}
889 	}
890 	/* do the USB request */
891 	error = usbd_do_request_flags
892 	    (f->udev, NULL, &ur->ucr_request, ur->ucr_data,
893 	    (ur->ucr_flags & USB_SHORT_XFER_OK) |
894 	    USB_USER_DATA_PTR, &actlen,
895 	    USB_DEFAULT_TIMEOUT);
896 
897 	ur->ucr_actlen = actlen;
898 
899 	if (error) {
900 		error = EIO;
901 	}
902 	return (error);
903 }
904 
905 #ifdef COMPAT_FREEBSD32
906 static int
907 ugen_do_request32(struct usb_fifo *f, struct usb_ctl_request32 *ur32)
908 {
909 	struct usb_ctl_request ur;
910 	int error;
911 
912 	PTRIN_CP(*ur32, ur, ucr_data);
913 	CP(*ur32, ur, ucr_flags);
914 	CP(*ur32, ur, ucr_actlen);
915 	CP(*ur32, ur, ucr_addr);
916 	CP(*ur32, ur, ucr_request);
917 
918 	error = ugen_do_request(f, &ur);
919 
920 	/* Don't update ucr_data pointer */
921 	CP(ur, *ur32, ucr_flags);
922 	CP(ur, *ur32, ucr_actlen);
923 	CP(ur, *ur32, ucr_addr);
924 	CP(ur, *ur32, ucr_request);
925 
926 	return (error);
927 }
928 #endif
929 
930 /*------------------------------------------------------------------------
931  *	ugen_re_enumerate
932  *------------------------------------------------------------------------*/
933 static int
934 ugen_re_enumerate(struct usb_fifo *f)
935 {
936 	struct usb_device *udev = f->udev;
937 	int error;
938 
939 	/*
940 	 * This request can be useful for testing USB drivers:
941 	 */
942 	error = priv_check(curthread, PRIV_DRIVER);
943 	if (error) {
944 		return (error);
945 	}
946 	if (udev->flags.usb_mode != USB_MODE_HOST) {
947 		/* not possible in device side mode */
948 		DPRINTFN(6, "device mode\n");
949 		return (ENOTTY);
950 	}
951 	/* make sure all FIFO's are gone */
952 	/* else there can be a deadlock */
953 	if (ugen_fs_uninit(f)) {
954 		/* ignore any errors */
955 		DPRINTFN(6, "no FIFOs\n");
956 	}
957 	/* start re-enumeration of device */
958 	usbd_start_re_enumerate(udev);
959 	return (0);
960 }
961 
962 static int
963 ugen_fs_init(struct usb_fifo *f,
964     struct usb_fs_endpoint *fs_ep_ptr, usb_size_t fs_ep_sz,
965     int fflags, uint8_t ep_index_max)
966 {
967 	int error;
968 
969 	/* verify input parameters */
970 	if (fs_ep_ptr == NULL || ep_index_max > USB_FS_XFER_MAX)
971 		return (EINVAL);
972 
973 	if (f->fs_ep_max != 0)
974 		return (EBUSY);
975 
976 	if (f->dev_ep_index != 0 || ep_index_max == 0)
977 		return (EINVAL);
978 
979 	if (ugen_fifo_in_use(f, fflags))
980 		return (EBUSY);
981 
982 	error = usb_fifo_alloc_buffer(f, 1, ep_index_max);
983 	if (error == 0) {
984 		mtx_lock(f->priv_mtx);
985 		f->fs_ep_max = ep_index_max;
986 		f->fs_ep_ptr = fs_ep_ptr;
987 		f->fs_ep_sz = fs_ep_sz;
988 		mtx_unlock(f->priv_mtx);
989 	}
990 	return (error);
991 }
992 
993 int
994 ugen_fs_uninit(struct usb_fifo *f)
995 {
996 	if (f->fs_ep_max == 0)
997 		return (EINVAL);
998 
999 	/*
1000 	 * Prevent calls into the fast-path code, by setting fs_ep_max
1001 	 * to zero:
1002 	 */
1003 	sx_xlock(&f->fs_fastpath_lock);
1004 	mtx_lock(f->priv_mtx);
1005 	f->fs_ep_max = 0;
1006 	mtx_unlock(f->priv_mtx);
1007 	sx_xunlock(&f->fs_fastpath_lock);
1008 
1009 	usbd_transfer_unsetup(f->fs_xfer, USB_FS_XFER_MAX);
1010 
1011 	mtx_lock(f->priv_mtx);
1012 	f->fs_ep_ptr = NULL;
1013 	f->flag_iscomplete = 0;
1014 	mtx_unlock(f->priv_mtx);
1015 
1016 	usb_fifo_free_buffer(f);
1017 	return (0);
1018 }
1019 
1020 static int
1021 usb_fs_open(struct usb_fifo *f, struct usb_fs_open *popen,
1022     int fflags, usb_stream_t stream_id)
1023 {
1024 	struct usb_config usb_config[1] = {};
1025 	struct usb_endpoint *ep;
1026 	struct usb_endpoint_descriptor *ed;
1027 	uint8_t iface_index;
1028 	uint8_t pre_scale;
1029 	uint8_t isread;
1030 	int error;
1031 
1032 	if (popen->ep_index >= f->fs_ep_max)
1033 		return (EINVAL);
1034 
1035 	if (f->fs_xfer[popen->ep_index] != NULL)
1036 		return (EBUSY);
1037 
1038 	if (popen->max_bufsize > USB_FS_MAX_BUFSIZE)
1039 		popen->max_bufsize = USB_FS_MAX_BUFSIZE;
1040 
1041 	if (popen->max_frames & USB_FS_MAX_FRAMES_PRE_SCALE) {
1042 		pre_scale = 1;
1043 		popen->max_frames &= ~USB_FS_MAX_FRAMES_PRE_SCALE;
1044 	} else {
1045 		pre_scale = 0;
1046 	}
1047 
1048 	if (popen->max_frames > USB_FS_MAX_FRAMES)
1049 		popen->max_frames = USB_FS_MAX_FRAMES;
1050 
1051 	if (popen->max_frames == 0)
1052 		return (EINVAL);
1053 
1054 	ep = usbd_get_ep_by_addr(f->udev, popen->ep_no);
1055 	if (ep == NULL)
1056 		return (EINVAL);
1057 
1058 	ed = ep->edesc;
1059 	if (ed == NULL)
1060 		return (ENXIO);
1061 
1062 	iface_index = ep->iface_index;
1063 
1064 	usb_config[0].type = ed->bmAttributes & UE_XFERTYPE;
1065 	usb_config[0].endpoint = ed->bEndpointAddress & UE_ADDR;
1066 	usb_config[0].direction = ed->bEndpointAddress & (UE_DIR_OUT | UE_DIR_IN);
1067 	usb_config[0].interval = USB_DEFAULT_INTERVAL;
1068 	usb_config[0].flags.proxy_buffer = 1;
1069 	if (pre_scale != 0)
1070 		usb_config[0].flags.pre_scale_frames = 1;
1071 
1072 	usb_config[0].callback = &ugen_ctrl_fs_callback;
1073 	usb_config[0].timeout = 0;	/* no timeout */
1074 	usb_config[0].frames = popen->max_frames;
1075 	usb_config[0].bufsize = popen->max_bufsize;
1076 	usb_config[0].usb_mode = USB_MODE_DUAL;	/* both modes */
1077 	usb_config[0].stream_id = stream_id;
1078 
1079 	if (usb_config[0].type == UE_CONTROL) {
1080 		if (f->udev->flags.usb_mode != USB_MODE_HOST)
1081 			return (EINVAL);
1082 	} else {
1083 		isread = ((usb_config[0].endpoint &
1084 		    (UE_DIR_IN | UE_DIR_OUT)) == UE_DIR_IN);
1085 
1086 		if (f->udev->flags.usb_mode != USB_MODE_HOST)
1087 			isread = !isread;
1088 
1089 		/* check permissions */
1090 		if (isread) {
1091 			if (!(fflags & FREAD))
1092 				return (EPERM);
1093 		} else {
1094 			if (!(fflags & FWRITE))
1095 				return (EPERM);
1096 		}
1097 	}
1098 	error = usbd_transfer_setup(f->udev, &iface_index,
1099 	    f->fs_xfer + popen->ep_index, usb_config, 1,
1100 	    f, f->priv_mtx);
1101 	if (error == 0) {
1102 		/* update maximums */
1103 		popen->max_packet_length =
1104 		    f->fs_xfer[popen->ep_index]->max_frame_size;
1105 		popen->max_bufsize =
1106 		    f->fs_xfer[popen->ep_index]->max_data_length;
1107 		/* update number of frames */
1108 		popen->max_frames =
1109 		    f->fs_xfer[popen->ep_index]->nframes;
1110 		/* store index of endpoint */
1111 		f->fs_xfer[popen->ep_index]->priv_fifo =
1112 		    ((uint8_t *)0) + popen->ep_index;
1113 	} else {
1114 		error = ENOMEM;
1115 	}
1116 	return (error);
1117 }
1118 
1119 static int
1120 usb_fs_close(struct usb_fifo *f, struct usb_fs_close *pclose)
1121 {
1122 	struct usb_xfer *xfer;
1123 
1124 	if (pclose->ep_index >= f->fs_ep_max)
1125 		return (EINVAL);
1126 
1127 	/*
1128 	 * Prevent calls into the fast-path code, by setting the
1129 	 * fs_xfer[] in question to NULL:
1130 	 */
1131 	sx_xlock(&f->fs_fastpath_lock);
1132 	mtx_lock(f->priv_mtx);
1133 	xfer = f->fs_xfer[pclose->ep_index];
1134 	f->fs_xfer[pclose->ep_index] = NULL;
1135 	mtx_unlock(f->priv_mtx);
1136 	sx_xunlock(&f->fs_fastpath_lock);
1137 
1138 	if (xfer == NULL)
1139 		return (EINVAL);
1140 
1141 	usbd_transfer_unsetup(&xfer, 1);
1142 	return (0);
1143 }
1144 
1145 static int
1146 usb_fs_clear_stall_sync(struct usb_fifo *f, struct usb_fs_clear_stall_sync *pstall)
1147 {
1148 	struct usb_device_request req;
1149 	struct usb_endpoint *ep;
1150 	int error;
1151 
1152 	if (pstall->ep_index >= f->fs_ep_max)
1153 		return (EINVAL);
1154 
1155 	if (f->fs_xfer[pstall->ep_index] == NULL)
1156 		return (EINVAL);
1157 
1158 	if (f->udev->flags.usb_mode != USB_MODE_HOST)
1159 		return (EINVAL);
1160 
1161 	mtx_lock(f->priv_mtx);
1162 	error = usbd_transfer_pending(f->fs_xfer[pstall->ep_index]);
1163 	mtx_unlock(f->priv_mtx);
1164 
1165 	if (error)
1166 		return (EBUSY);
1167 
1168 	ep = f->fs_xfer[pstall->ep_index]->endpoint;
1169 
1170 	/* setup a clear-stall packet */
1171 	req.bmRequestType = UT_WRITE_ENDPOINT;
1172 	req.bRequest = UR_CLEAR_FEATURE;
1173 	USETW(req.wValue, UF_ENDPOINT_HALT);
1174 	req.wIndex[0] = ep->edesc->bEndpointAddress;
1175 	req.wIndex[1] = 0;
1176 	USETW(req.wLength, 0);
1177 
1178 	error = usbd_do_request(f->udev, NULL, &req, NULL);
1179 	if (error == 0) {
1180 		usbd_clear_data_toggle(f->udev, ep);
1181 	} else {
1182 		error = ENXIO;
1183 	}
1184 	return (error);
1185 }
1186 
1187 static uint8_t
1188 ugen_fs_get_complete(struct usb_fifo *f, uint8_t *pindex)
1189 {
1190 	struct usb_mbuf *m;
1191 
1192 	USB_IF_DEQUEUE(&f->used_q, m);
1193 
1194 	if (m) {
1195 		*pindex = *((uint8_t *)(m->cur_data_ptr));
1196 
1197 		USB_IF_ENQUEUE(&f->free_q, m);
1198 
1199 		return (0);		/* success */
1200 	} else {
1201 		*pindex = 0;		/* fix compiler warning */
1202 
1203 		f->flag_iscomplete = 0;
1204 	}
1205 	return (1);			/* failure */
1206 }
1207 
1208 static void
1209 ugen_fs_set_complete(struct usb_fifo *f, uint8_t index)
1210 {
1211 	struct usb_mbuf *m;
1212 
1213 	USB_IF_DEQUEUE(&f->free_q, m);
1214 
1215 	if (m == NULL) {
1216 		/* can happen during close */
1217 		DPRINTF("out of buffers\n");
1218 		return;
1219 	}
1220 	USB_MBUF_RESET(m);
1221 
1222 	*((uint8_t *)(m->cur_data_ptr)) = index;
1223 
1224 	USB_IF_ENQUEUE(&f->used_q, m);
1225 
1226 	f->flag_iscomplete = 1;
1227 
1228 	usb_fifo_wakeup(f);
1229 }
1230 
1231 static int
1232 ugen_fs_getbuffer(void **uptrp, struct usb_fifo *f, void *buffer,
1233     usb_frcount_t n)
1234 {
1235 	union {
1236 		void **ppBuffer;
1237 #ifdef COMPAT_FREEBSD32
1238 		uint32_t *ppBuffer32;
1239 #endif
1240 	} u;
1241 #ifdef COMPAT_FREEBSD32
1242 	uint32_t uptr32;
1243 #endif
1244 
1245 	u.ppBuffer = buffer;
1246 	switch (f->fs_ep_sz) {
1247 	case sizeof(struct usb_fs_endpoint):
1248 		if (fueword(u.ppBuffer + n, (long *)uptrp) != 0)
1249 			return (EFAULT);
1250 		return (0);
1251 #ifdef COMPAT_FREEBSD32
1252 	case sizeof(struct usb_fs_endpoint32):
1253 		if (fueword32(u.ppBuffer32 + n, &uptr32) != 0)
1254 			return (EFAULT);
1255 		*uptrp = PTRIN(uptr32);
1256 		return (0);
1257 #endif
1258 	default:
1259 		panic("%s: unhandled fs_ep_sz %#x", __func__, f->fs_ep_sz);
1260 	}
1261 }
1262 
1263 static int
1264 ugen_fs_copy_in(struct usb_fifo *f, uint8_t ep_index)
1265 {
1266 	struct usb_device_request *req;
1267 	struct usb_xfer *xfer;
1268 	struct usb_fs_endpoint fs_ep;
1269 	void *uaddr;			/* userland pointer */
1270 	void *kaddr;
1271 	usb_frlength_t offset;
1272 	usb_frlength_t rem;
1273 	usb_frcount_t n;
1274 	uint32_t length;
1275 	int error;
1276 	uint8_t isread;
1277 
1278 	mtx_lock(f->priv_mtx);
1279 	if (ep_index >= f->fs_ep_max) {
1280 		mtx_unlock(f->priv_mtx);
1281 		return (EINVAL);
1282 	}
1283 	xfer = f->fs_xfer[ep_index];
1284 	if (xfer == NULL) {
1285 		mtx_unlock(f->priv_mtx);
1286 		return (EINVAL);
1287 	}
1288 	if (usbd_transfer_pending(xfer)) {
1289 		mtx_unlock(f->priv_mtx);
1290 		return (EBUSY);		/* should not happen */
1291 	}
1292 	mtx_unlock(f->priv_mtx);
1293 
1294 	error = ugen_fs_copyin(f, ep_index, &fs_ep);
1295 	if (error) {
1296 		return (error);
1297 	}
1298 	/* security checks */
1299 
1300 	if (fs_ep.nFrames > xfer->max_frame_count) {
1301 		xfer->error = USB_ERR_INVAL;
1302 		goto complete;
1303 	}
1304 	if (fs_ep.nFrames == 0) {
1305 		xfer->error = USB_ERR_INVAL;
1306 		goto complete;
1307 	}
1308 	error = ugen_fs_getbuffer(&uaddr, f, fs_ep.ppBuffer, 0);
1309 	if (error) {
1310 		return (error);
1311 	}
1312 	/* reset first frame */
1313 	usbd_xfer_set_frame_offset(xfer, 0, 0);
1314 
1315 	if (xfer->flags_int.control_xfr) {
1316 		req = xfer->frbuffers[0].buffer;
1317 
1318 		if (fueword32(fs_ep.pLength, &length) != 0) {
1319 			return (EFAULT);
1320 		}
1321 		if (length != sizeof(*req)) {
1322 			xfer->error = USB_ERR_INVAL;
1323 			goto complete;
1324 		}
1325 		if (length != 0) {
1326 			error = copyin(uaddr, req, length);
1327 			if (error) {
1328 				return (error);
1329 			}
1330 		}
1331 		if (usb_check_request(f->udev, req)) {
1332 			xfer->error = USB_ERR_INVAL;
1333 			goto complete;
1334 		}
1335 		usbd_xfer_set_frame_len(xfer, 0, length);
1336 
1337 		/* Host mode only ! */
1338 		if ((req->bmRequestType &
1339 		    (UT_READ | UT_WRITE)) == UT_READ) {
1340 			isread = 1;
1341 		} else {
1342 			isread = 0;
1343 		}
1344 		n = 1;
1345 		offset = sizeof(*req);
1346 
1347 	} else {
1348 		/* Device and Host mode */
1349 		if (USB_GET_DATA_ISREAD(xfer)) {
1350 			isread = 1;
1351 		} else {
1352 			isread = 0;
1353 		}
1354 		n = 0;
1355 		offset = 0;
1356 	}
1357 
1358 	rem = usbd_xfer_max_len(xfer);
1359 	xfer->nframes = fs_ep.nFrames;
1360 	xfer->timeout = fs_ep.timeout;
1361 	if (xfer->timeout > 65535) {
1362 		xfer->timeout = 65535;
1363 	}
1364 	if (fs_ep.flags & USB_FS_FLAG_SINGLE_SHORT_OK)
1365 		xfer->flags.short_xfer_ok = 1;
1366 	else
1367 		xfer->flags.short_xfer_ok = 0;
1368 
1369 	if (fs_ep.flags & USB_FS_FLAG_MULTI_SHORT_OK)
1370 		xfer->flags.short_frames_ok = 1;
1371 	else
1372 		xfer->flags.short_frames_ok = 0;
1373 
1374 	if (fs_ep.flags & USB_FS_FLAG_FORCE_SHORT)
1375 		xfer->flags.force_short_xfer = 1;
1376 	else
1377 		xfer->flags.force_short_xfer = 0;
1378 
1379 	if (fs_ep.flags & USB_FS_FLAG_CLEAR_STALL)
1380 		usbd_xfer_set_stall(xfer);
1381 	else
1382 		xfer->flags.stall_pipe = 0;
1383 
1384 	for (; n != xfer->nframes; n++) {
1385 		if (fueword32(fs_ep.pLength + n, &length) != 0) {
1386 			break;
1387 		}
1388 		usbd_xfer_set_frame_len(xfer, n, length);
1389 
1390 		if (length > rem) {
1391 			xfer->error = USB_ERR_INVAL;
1392 			goto complete;
1393 		}
1394 		rem -= length;
1395 
1396 		if (!isread) {
1397 			/* we need to know the source buffer */
1398 			error = ugen_fs_getbuffer(&uaddr, f, fs_ep.ppBuffer, n);
1399 			if (error) {
1400 				break;
1401 			}
1402 			if (xfer->flags_int.isochronous_xfr) {
1403 				/* get kernel buffer address */
1404 				kaddr = xfer->frbuffers[0].buffer;
1405 				kaddr = USB_ADD_BYTES(kaddr, offset);
1406 			} else {
1407 				/* set current frame offset */
1408 				usbd_xfer_set_frame_offset(xfer, offset, n);
1409 
1410 				/* get kernel buffer address */
1411 				kaddr = xfer->frbuffers[n].buffer;
1412 			}
1413 
1414 			/* move data */
1415 			error = copyin(uaddr, kaddr, length);
1416 			if (error) {
1417 				break;
1418 			}
1419 		}
1420 		offset += length;
1421 	}
1422 	return (error);
1423 
1424 complete:
1425 	mtx_lock(f->priv_mtx);
1426 	ugen_fs_set_complete(f, ep_index);
1427 	mtx_unlock(f->priv_mtx);
1428 	return (0);
1429 }
1430 
1431 static struct usb_fs_endpoint *
1432 ugen_fs_ep_uptr(struct usb_fifo *f, uint8_t ep_index)
1433 {
1434 	return ((struct usb_fs_endpoint *)
1435 	    ((char *)f->fs_ep_ptr + (ep_index * f->fs_ep_sz)));
1436 }
1437 
1438 static int
1439 ugen_fs_copyin(struct usb_fifo *f, uint8_t ep_index,
1440     struct usb_fs_endpoint* fs_ep)
1441 {
1442 #ifdef COMPAT_FREEBSD32
1443 	struct usb_fs_endpoint32 fs_ep32;
1444 #endif
1445 	int error;
1446 
1447 	switch (f->fs_ep_sz) {
1448 	case sizeof(struct usb_fs_endpoint):
1449 		error = copyin(ugen_fs_ep_uptr(f, ep_index), fs_ep,
1450 		    f->fs_ep_sz);
1451 		if (error != 0)
1452 			return (error);
1453 		break;
1454 
1455 #ifdef COMPAT_FREEBSD32
1456 	case sizeof(struct usb_fs_endpoint32):
1457 		error = copyin(ugen_fs_ep_uptr(f, ep_index), &fs_ep32,
1458 		    f->fs_ep_sz);
1459 		if (error != 0)
1460 			return (error);
1461 		PTRIN_CP(fs_ep32, *fs_ep, ppBuffer);
1462 		PTRIN_CP(fs_ep32, *fs_ep, pLength);
1463 		CP(fs_ep32, *fs_ep, nFrames);
1464 		CP(fs_ep32, *fs_ep, aFrames);
1465 		CP(fs_ep32, *fs_ep, flags);
1466 		CP(fs_ep32, *fs_ep, timeout);
1467 		CP(fs_ep32, *fs_ep, isoc_time_complete);
1468 		CP(fs_ep32, *fs_ep, status);
1469 		break;
1470 #endif
1471 	default:
1472 		panic("%s: unhandled fs_ep_sz %#x", __func__, f->fs_ep_sz);
1473 	}
1474 
1475 	return (0);
1476 }
1477 
1478 static int
1479 ugen_fs_update(const struct usb_fs_endpoint *fs_ep,
1480     struct usb_fifo *f, uint8_t ep_index)
1481 {
1482 	union {
1483 		struct usb_fs_endpoint *fs_ep_uptr;
1484 #ifdef COMPAT_FREEBSD32
1485 		struct usb_fs_endpoint32 *fs_ep_uptr32;
1486 #endif
1487 	} u;
1488 	uint32_t *aFrames_uptr;
1489 	uint16_t *isoc_time_complete_uptr;
1490 	int *status_uptr;
1491 
1492 	switch (f->fs_ep_sz) {
1493 	case sizeof(struct usb_fs_endpoint):
1494 		u.fs_ep_uptr = ugen_fs_ep_uptr(f, ep_index);
1495 		aFrames_uptr = &u.fs_ep_uptr->aFrames;
1496 		isoc_time_complete_uptr = &u.fs_ep_uptr->isoc_time_complete;
1497 		status_uptr = &u.fs_ep_uptr->status;
1498 		break;
1499 #ifdef COMPAT_FREEBSD32
1500 	case sizeof(struct usb_fs_endpoint32):
1501 		u.fs_ep_uptr32 = (struct usb_fs_endpoint32 *)
1502 		    ugen_fs_ep_uptr(f, ep_index);
1503 		aFrames_uptr = &u.fs_ep_uptr32->aFrames;
1504 		isoc_time_complete_uptr = &u.fs_ep_uptr32->isoc_time_complete;
1505 		status_uptr = &u.fs_ep_uptr32->status;
1506 		break;
1507 #endif
1508 	default:
1509 		panic("%s: unhandled fs_ep_sz %#x", __func__, f->fs_ep_sz);
1510 	}
1511 
1512 	/* update "aFrames" */
1513 	if (suword32(aFrames_uptr, fs_ep->aFrames) != 0)
1514 		return (EFAULT);
1515 
1516 	/* update "isoc_time_complete" */
1517 	if (suword16(isoc_time_complete_uptr, fs_ep->isoc_time_complete) != 0)
1518 		return (EFAULT);
1519 
1520 	/* update "status" */
1521 	if (suword32(status_uptr, fs_ep->status) != 0)
1522 		return (EFAULT);
1523 
1524 	return (0);
1525 }
1526 
1527 static int
1528 ugen_fs_copy_out_cancelled(struct usb_fifo *f, uint8_t ep_index)
1529 {
1530 	struct usb_fs_endpoint fs_ep;
1531 	int error;
1532 
1533 	error = ugen_fs_copyin(f, ep_index, &fs_ep);
1534 	if (error)
1535 		return (error);
1536 
1537 	fs_ep.status = USB_ERR_CANCELLED;
1538 	fs_ep.aFrames = 0;
1539 	fs_ep.isoc_time_complete = 0;
1540 
1541 	return (ugen_fs_update(&fs_ep, f, ep_index));
1542 }
1543 
1544 static int
1545 ugen_fs_copy_out(struct usb_fifo *f, uint8_t ep_index)
1546 {
1547 	struct usb_device_request *req;
1548 	struct usb_xfer *xfer;
1549 	struct usb_fs_endpoint fs_ep;
1550 	void *uaddr;			/* userland ptr */
1551 	void *kaddr;
1552 	usb_frlength_t offset;
1553 	usb_frlength_t rem;
1554 	usb_frcount_t n;
1555 	uint32_t length;
1556 	uint32_t temp;
1557 	int error;
1558 	uint8_t isread;
1559 
1560 	mtx_lock(f->priv_mtx);
1561 	if (ep_index >= f->fs_ep_max) {
1562 		mtx_unlock(f->priv_mtx);
1563 		return (EINVAL);
1564 	}
1565 	xfer = f->fs_xfer[ep_index];
1566 	if (xfer == NULL) {
1567 		mtx_unlock(f->priv_mtx);
1568 		return (EINVAL);
1569 	}
1570 	if (!xfer->flags_int.transferring &&
1571 	    !xfer->flags_int.started) {
1572 		mtx_unlock(f->priv_mtx);
1573 		DPRINTF("Returning fake cancel event\n");
1574 		return (ugen_fs_copy_out_cancelled(f, ep_index));
1575 	} else if (usbd_transfer_pending(xfer)) {
1576 		mtx_unlock(f->priv_mtx);
1577 		return (EBUSY);		/* should not happen */
1578 	}
1579 	mtx_unlock(f->priv_mtx);
1580 
1581 	error = ugen_fs_copyin(f, ep_index, &fs_ep);
1582 	if (error) {
1583 		return (error);
1584 	}
1585 
1586 	fs_ep.status = xfer->error;
1587 	fs_ep.aFrames = xfer->aframes;
1588 	fs_ep.isoc_time_complete = xfer->isoc_time_complete;
1589 	if (xfer->error) {
1590 		goto complete;
1591 	}
1592 	if (xfer->flags_int.control_xfr) {
1593 		req = xfer->frbuffers[0].buffer;
1594 
1595 		/* Host mode only ! */
1596 		if ((req->bmRequestType & (UT_READ | UT_WRITE)) == UT_READ) {
1597 			isread = 1;
1598 		} else {
1599 			isread = 0;
1600 		}
1601 		if (xfer->nframes == 0)
1602 			n = 0;		/* should never happen */
1603 		else
1604 			n = 1;
1605 	} else {
1606 		/* Device and Host mode */
1607 		if (USB_GET_DATA_ISREAD(xfer)) {
1608 			isread = 1;
1609 		} else {
1610 			isread = 0;
1611 		}
1612 		n = 0;
1613 	}
1614 
1615 	/* Update lengths and copy out data */
1616 
1617 	rem = usbd_xfer_max_len(xfer);
1618 	offset = 0;
1619 
1620 	for (; n != xfer->nframes; n++) {
1621 		/* get initial length into "temp" */
1622 		if (fueword32(fs_ep.pLength + n, &temp) != 0) {
1623 			return (EFAULT);
1624 		}
1625 		if (temp > rem) {
1626 			/* the userland length has been corrupted */
1627 			DPRINTF("corrupt userland length "
1628 			    "%u > %u\n", temp, rem);
1629 			fs_ep.status = USB_ERR_INVAL;
1630 			goto complete;
1631 		}
1632 		rem -= temp;
1633 
1634 		/* get actual transfer length */
1635 		length = xfer->frlengths[n];
1636 		if (length > temp) {
1637 			/* data overflow */
1638 			fs_ep.status = USB_ERR_INVAL;
1639 			DPRINTF("data overflow %u > %u\n",
1640 			    length, temp);
1641 			goto complete;
1642 		}
1643 		if (isread) {
1644 			/* we need to know the destination buffer */
1645 			error = ugen_fs_getbuffer(&uaddr, f, fs_ep.ppBuffer, n);
1646 			if (error) {
1647 				return (error);
1648 			}
1649 			if (xfer->flags_int.isochronous_xfr) {
1650 				/* only one frame buffer */
1651 				kaddr = USB_ADD_BYTES(
1652 				    xfer->frbuffers[0].buffer, offset);
1653 			} else {
1654 				/* multiple frame buffers */
1655 				kaddr = xfer->frbuffers[n].buffer;
1656 			}
1657 
1658 			/* move data */
1659 			error = copyout(kaddr, uaddr, length);
1660 			if (error) {
1661 				goto complete;
1662 			}
1663 		}
1664 		/*
1665 		 * Update offset according to initial length, which is
1666 		 * needed by isochronous transfers!
1667 		 */
1668 		offset += temp;
1669 
1670 		/* update length */
1671 		if (suword32(fs_ep.pLength + n, length) != 0)
1672 			goto complete;
1673 	}
1674 
1675 complete:
1676 	if (error == 0)
1677 		error = ugen_fs_update(&fs_ep, f, ep_index);
1678 	return (error);
1679 }
1680 
1681 static uint8_t
1682 ugen_fifo_in_use(struct usb_fifo *f, int fflags)
1683 {
1684 	struct usb_fifo *f_rx;
1685 	struct usb_fifo *f_tx;
1686 
1687 	f_rx = f->udev->fifo[(f->fifo_index & ~1) + USB_FIFO_RX];
1688 	f_tx = f->udev->fifo[(f->fifo_index & ~1) + USB_FIFO_TX];
1689 
1690 	if ((fflags & FREAD) && f_rx &&
1691 	    (f_rx->xfer[0] || f_rx->xfer[1])) {
1692 		return (1);		/* RX FIFO in use */
1693 	}
1694 	if ((fflags & FWRITE) && f_tx &&
1695 	    (f_tx->xfer[0] || f_tx->xfer[1])) {
1696 		return (1);		/* TX FIFO in use */
1697 	}
1698 	return (0);			/* not in use */
1699 }
1700 
1701 static int
1702 ugen_ioctl(struct usb_fifo *f, u_long cmd, void *addr, int fflags)
1703 {
1704 	union {
1705 		struct usb_fs_complete *pcomp;
1706 		struct usb_fs_start *pstart;
1707 		struct usb_fs_stop *pstop;
1708 		void   *addr;
1709 	}     u;
1710 	struct usb_xfer *xfer;
1711 	int error;
1712 	uint8_t ep_index;
1713 
1714 	u.addr = addr;
1715 
1716 	DPRINTFN(6, "cmd=0x%08lx\n", cmd);
1717 
1718 	switch (cmd) {
1719 	case USB_FS_COMPLETE:
1720 		sx_slock(&f->fs_fastpath_lock);
1721 		mtx_lock(f->priv_mtx);
1722 		error = ugen_fs_get_complete(f, &ep_index);
1723 		mtx_unlock(f->priv_mtx);
1724 
1725 		if (error != 0) {
1726 			error = EBUSY;
1727 		} else {
1728 			u.pcomp->ep_index = ep_index;
1729 			error = ugen_fs_copy_out(f, u.pcomp->ep_index);
1730 		}
1731 		sx_sunlock(&f->fs_fastpath_lock);
1732 		break;
1733 
1734 	case USB_FS_START:
1735 		sx_slock(&f->fs_fastpath_lock);
1736 		error = ugen_fs_copy_in(f, u.pstart->ep_index);
1737 		if (error == 0) {
1738 			mtx_lock(f->priv_mtx);
1739 			xfer = f->fs_xfer[u.pstart->ep_index];
1740 			usbd_transfer_start(xfer);
1741 			mtx_unlock(f->priv_mtx);
1742 		}
1743 		sx_sunlock(&f->fs_fastpath_lock);
1744 		break;
1745 
1746 	case USB_FS_STOP:
1747 		mtx_lock(f->priv_mtx);
1748 		if (u.pstop->ep_index >= f->fs_ep_max) {
1749 			error = EINVAL;
1750 		} else {
1751 			error = 0;
1752 			xfer = f->fs_xfer[u.pstart->ep_index];
1753 			if (usbd_transfer_pending(xfer)) {
1754 				usbd_transfer_stop(xfer);
1755 
1756 				/*
1757 				 * Check if the USB transfer was
1758 				 * stopped before it was even started
1759 				 * and fake a cancel event.
1760 				 */
1761 				if (!xfer->flags_int.transferring &&
1762 				    !xfer->flags_int.started) {
1763 					DPRINTF("Issuing fake completion event\n");
1764 					ugen_fs_set_complete(xfer->priv_sc,
1765 					    USB_P2U(xfer->priv_fifo));
1766 				}
1767 			}
1768 		}
1769 		mtx_unlock(f->priv_mtx);
1770 		break;
1771 
1772 	default:
1773 		error = ENOIOCTL;
1774 		break;
1775 	}
1776 
1777 	DPRINTFN(6, "error=%d\n", error);
1778 
1779 	return (error);
1780 }
1781 
1782 static int
1783 ugen_set_short_xfer(struct usb_fifo *f, void *addr)
1784 {
1785 	uint8_t t;
1786 
1787 	if (*(int *)addr)
1788 		t = 1;
1789 	else
1790 		t = 0;
1791 
1792 	if (f->flag_short == t) {
1793 		/* same value like before - accept */
1794 		return (0);
1795 	}
1796 	if (f->xfer[0] || f->xfer[1]) {
1797 		/* cannot change this during transfer */
1798 		return (EBUSY);
1799 	}
1800 	f->flag_short = t;
1801 	return (0);
1802 }
1803 
1804 static int
1805 ugen_set_timeout(struct usb_fifo *f, void *addr)
1806 {
1807 	f->timeout = *(int *)addr;
1808 	if (f->timeout > 65535) {
1809 		/* limit user input */
1810 		f->timeout = 65535;
1811 	}
1812 	return (0);
1813 }
1814 
1815 static int
1816 ugen_get_frame_size(struct usb_fifo *f, void *addr)
1817 {
1818 	if (f->xfer[0]) {
1819 		*(int *)addr = f->xfer[0]->max_frame_size;
1820 	} else {
1821 		return (EINVAL);
1822 	}
1823 	return (0);
1824 }
1825 
1826 static int
1827 ugen_set_buffer_size(struct usb_fifo *f, void *addr)
1828 {
1829 	usb_frlength_t t;
1830 
1831 	if (*(int *)addr < 0)
1832 		t = 0;		/* use "wMaxPacketSize" */
1833 	else if (*(int *)addr < (256 * 1024))
1834 		t = *(int *)addr;
1835 	else
1836 		t = 256 * 1024;
1837 
1838 	if (f->bufsize == t) {
1839 		/* same value like before - accept */
1840 		return (0);
1841 	}
1842 	if (f->xfer[0] || f->xfer[1]) {
1843 		/* cannot change this during transfer */
1844 		return (EBUSY);
1845 	}
1846 	f->bufsize = t;
1847 	return (0);
1848 }
1849 
1850 static int
1851 ugen_get_buffer_size(struct usb_fifo *f, void *addr)
1852 {
1853 	*(int *)addr = f->bufsize;
1854 	return (0);
1855 }
1856 
1857 static int
1858 ugen_get_iface_desc(struct usb_fifo *f,
1859     struct usb_interface_descriptor *idesc)
1860 {
1861 	struct usb_interface *iface;
1862 
1863 	iface = usbd_get_iface(f->udev, f->iface_index);
1864 	if (iface && iface->idesc) {
1865 		*idesc = *(iface->idesc);
1866 	} else {
1867 		return (EIO);
1868 	}
1869 	return (0);
1870 }
1871 
1872 static int
1873 ugen_get_endpoint_desc(struct usb_fifo *f,
1874     struct usb_endpoint_descriptor *ed)
1875 {
1876 	struct usb_endpoint *ep;
1877 
1878 	ep = usb_fifo_softc(f);
1879 
1880 	if (ep && ep->edesc) {
1881 		*ed = *ep->edesc;
1882 	} else {
1883 		return (EINVAL);
1884 	}
1885 	return (0);
1886 }
1887 
1888 static int
1889 ugen_set_power_mode(struct usb_fifo *f, int mode)
1890 {
1891 	struct usb_device *udev = f->udev;
1892 	int err;
1893 	uint8_t old_mode;
1894 
1895 	if ((udev == NULL) ||
1896 	    (udev->parent_hub == NULL)) {
1897 		return (EINVAL);
1898 	}
1899 	err = priv_check(curthread, PRIV_DRIVER);
1900 	if (err)
1901 		return (err);
1902 
1903 	/* get old power mode */
1904 	old_mode = udev->power_mode;
1905 
1906 	/* if no change, then just return */
1907 	if (old_mode == mode)
1908 		return (0);
1909 
1910 	switch (mode) {
1911 	case USB_POWER_MODE_OFF:
1912 		if (udev->flags.usb_mode == USB_MODE_HOST &&
1913 		    udev->re_enumerate_wait == USB_RE_ENUM_DONE) {
1914 			udev->re_enumerate_wait = USB_RE_ENUM_PWR_OFF;
1915 		}
1916 		/* set power mode will wake up the explore thread */
1917 		break;
1918 
1919 	case USB_POWER_MODE_ON:
1920 	case USB_POWER_MODE_SAVE:
1921 		break;
1922 
1923 	case USB_POWER_MODE_RESUME:
1924 #if USB_HAVE_POWERD
1925 		/* let USB-powerd handle resume */
1926 		USB_BUS_LOCK(udev->bus);
1927 		udev->pwr_save.write_refs++;
1928 		udev->pwr_save.last_xfer_time = ticks;
1929 		USB_BUS_UNLOCK(udev->bus);
1930 
1931 		/* set new power mode */
1932 		usbd_set_power_mode(udev, USB_POWER_MODE_SAVE);
1933 
1934 		/* wait for resume to complete */
1935 		usb_pause_mtx(NULL, hz / 4);
1936 
1937 		/* clear write reference */
1938 		USB_BUS_LOCK(udev->bus);
1939 		udev->pwr_save.write_refs--;
1940 		USB_BUS_UNLOCK(udev->bus);
1941 #endif
1942 		mode = USB_POWER_MODE_SAVE;
1943 		break;
1944 
1945 	case USB_POWER_MODE_SUSPEND:
1946 #if USB_HAVE_POWERD
1947 		/* let USB-powerd handle suspend */
1948 		USB_BUS_LOCK(udev->bus);
1949 		udev->pwr_save.last_xfer_time = ticks - (256 * hz);
1950 		USB_BUS_UNLOCK(udev->bus);
1951 #endif
1952 		mode = USB_POWER_MODE_SAVE;
1953 		break;
1954 
1955 	default:
1956 		return (EINVAL);
1957 	}
1958 
1959 	if (err)
1960 		return (ENXIO);		/* I/O failure */
1961 
1962 	/* if we are powered off we need to re-enumerate first */
1963 	if (old_mode == USB_POWER_MODE_OFF) {
1964 		if (udev->flags.usb_mode == USB_MODE_HOST &&
1965 		    udev->re_enumerate_wait == USB_RE_ENUM_DONE) {
1966 			udev->re_enumerate_wait = USB_RE_ENUM_START;
1967 		}
1968 		/* set power mode will wake up the explore thread */
1969 	}
1970 
1971 	/* set new power mode */
1972 	usbd_set_power_mode(udev, mode);
1973 
1974 	return (0);			/* success */
1975 }
1976 
1977 static int
1978 ugen_get_power_mode(struct usb_fifo *f)
1979 {
1980 	struct usb_device *udev = f->udev;
1981 
1982 	if (udev == NULL)
1983 		return (USB_POWER_MODE_ON);
1984 
1985 	return (udev->power_mode);
1986 }
1987 
1988 static int
1989 ugen_get_port_path(struct usb_fifo *f, struct usb_device_port_path *dpp)
1990 {
1991 	struct usb_device *udev = f->udev;
1992 	struct usb_device *next;
1993 	unsigned nlevel = 0;
1994 
1995 	if (udev == NULL)
1996 		goto error;
1997 
1998 	dpp->udp_bus = device_get_unit(udev->bus->bdev);
1999 	dpp->udp_index = udev->device_index;
2000 
2001 	/* count port levels */
2002 	next = udev;
2003 	while (next->parent_hub != NULL) {
2004 		nlevel++;
2005 		next = next->parent_hub;
2006 	}
2007 
2008 	/* check if too many levels */
2009 	if (nlevel > USB_DEVICE_PORT_PATH_MAX)
2010 		goto error;
2011 
2012 	/* store total level of ports */
2013 	dpp->udp_port_level = nlevel;
2014 
2015 	/* store port index array */
2016 	next = udev;
2017 	while (next->parent_hub != NULL) {
2018 		dpp->udp_port_no[--nlevel] = next->port_no;
2019 		next = next->parent_hub;
2020 	}
2021 	return (0);	/* success */
2022 
2023 error:
2024 	return (EINVAL);	/* failure */
2025 }
2026 
2027 static int
2028 ugen_get_power_usage(struct usb_fifo *f)
2029 {
2030 	struct usb_device *udev = f->udev;
2031 
2032 	if (udev == NULL)
2033 		return (0);
2034 
2035 	return (udev->power);
2036 }
2037 
2038 static int
2039 ugen_do_port_feature(struct usb_fifo *f, uint8_t port_no,
2040     uint8_t set, uint16_t feature)
2041 {
2042 	struct usb_device *udev = f->udev;
2043 	struct usb_hub *hub;
2044 	int err;
2045 
2046 	err = priv_check(curthread, PRIV_DRIVER);
2047 	if (err) {
2048 		return (err);
2049 	}
2050 	if (port_no == 0) {
2051 		return (EINVAL);
2052 	}
2053 	if ((udev == NULL) ||
2054 	    (udev->hub == NULL)) {
2055 		return (EINVAL);
2056 	}
2057 	hub = udev->hub;
2058 
2059 	if (port_no > hub->nports) {
2060 		return (EINVAL);
2061 	}
2062 	if (set)
2063 		err = usbd_req_set_port_feature(udev,
2064 		    NULL, port_no, feature);
2065 	else
2066 		err = usbd_req_clear_port_feature(udev,
2067 		    NULL, port_no, feature);
2068 
2069 	if (err)
2070 		return (ENXIO);		/* failure */
2071 
2072 	return (0);			/* success */
2073 }
2074 
2075 static int
2076 ugen_iface_ioctl(struct usb_fifo *f, u_long cmd, void *addr, int fflags)
2077 {
2078 	struct usb_fifo *f_rx;
2079 	struct usb_fifo *f_tx;
2080 	int error = 0;
2081 
2082 	f_rx = f->udev->fifo[(f->fifo_index & ~1) + USB_FIFO_RX];
2083 	f_tx = f->udev->fifo[(f->fifo_index & ~1) + USB_FIFO_TX];
2084 
2085 	switch (cmd) {
2086 	case USB_SET_RX_SHORT_XFER:
2087 		if (fflags & FREAD) {
2088 			error = ugen_set_short_xfer(f_rx, addr);
2089 		} else {
2090 			error = EINVAL;
2091 		}
2092 		break;
2093 
2094 	case USB_SET_TX_FORCE_SHORT:
2095 		if (fflags & FWRITE) {
2096 			error = ugen_set_short_xfer(f_tx, addr);
2097 		} else {
2098 			error = EINVAL;
2099 		}
2100 		break;
2101 
2102 	case USB_SET_RX_TIMEOUT:
2103 		if (fflags & FREAD) {
2104 			error = ugen_set_timeout(f_rx, addr);
2105 		} else {
2106 			error = EINVAL;
2107 		}
2108 		break;
2109 
2110 	case USB_SET_TX_TIMEOUT:
2111 		if (fflags & FWRITE) {
2112 			error = ugen_set_timeout(f_tx, addr);
2113 		} else {
2114 			error = EINVAL;
2115 		}
2116 		break;
2117 
2118 	case USB_GET_RX_FRAME_SIZE:
2119 		if (fflags & FREAD) {
2120 			error = ugen_get_frame_size(f_rx, addr);
2121 		} else {
2122 			error = EINVAL;
2123 		}
2124 		break;
2125 
2126 	case USB_GET_TX_FRAME_SIZE:
2127 		if (fflags & FWRITE) {
2128 			error = ugen_get_frame_size(f_tx, addr);
2129 		} else {
2130 			error = EINVAL;
2131 		}
2132 		break;
2133 
2134 	case USB_SET_RX_BUFFER_SIZE:
2135 		if (fflags & FREAD) {
2136 			error = ugen_set_buffer_size(f_rx, addr);
2137 		} else {
2138 			error = EINVAL;
2139 		}
2140 		break;
2141 
2142 	case USB_SET_TX_BUFFER_SIZE:
2143 		if (fflags & FWRITE) {
2144 			error = ugen_set_buffer_size(f_tx, addr);
2145 		} else {
2146 			error = EINVAL;
2147 		}
2148 		break;
2149 
2150 	case USB_GET_RX_BUFFER_SIZE:
2151 		if (fflags & FREAD) {
2152 			error = ugen_get_buffer_size(f_rx, addr);
2153 		} else {
2154 			error = EINVAL;
2155 		}
2156 		break;
2157 
2158 	case USB_GET_TX_BUFFER_SIZE:
2159 		if (fflags & FWRITE) {
2160 			error = ugen_get_buffer_size(f_tx, addr);
2161 		} else {
2162 			error = EINVAL;
2163 		}
2164 		break;
2165 
2166 	case USB_GET_RX_INTERFACE_DESC:
2167 		if (fflags & FREAD) {
2168 			error = ugen_get_iface_desc(f_rx, addr);
2169 		} else {
2170 			error = EINVAL;
2171 		}
2172 		break;
2173 
2174 	case USB_GET_TX_INTERFACE_DESC:
2175 		if (fflags & FWRITE) {
2176 			error = ugen_get_iface_desc(f_tx, addr);
2177 		} else {
2178 			error = EINVAL;
2179 		}
2180 		break;
2181 
2182 	case USB_GET_RX_ENDPOINT_DESC:
2183 		if (fflags & FREAD) {
2184 			error = ugen_get_endpoint_desc(f_rx, addr);
2185 		} else {
2186 			error = EINVAL;
2187 		}
2188 		break;
2189 
2190 	case USB_GET_TX_ENDPOINT_DESC:
2191 		if (fflags & FWRITE) {
2192 			error = ugen_get_endpoint_desc(f_tx, addr);
2193 		} else {
2194 			error = EINVAL;
2195 		}
2196 		break;
2197 
2198 	case USB_SET_RX_STALL_FLAG:
2199 		if ((fflags & FREAD) && (*(int *)addr)) {
2200 			f_rx->flag_stall = 1;
2201 		}
2202 		break;
2203 
2204 	case USB_SET_TX_STALL_FLAG:
2205 		if ((fflags & FWRITE) && (*(int *)addr)) {
2206 			f_tx->flag_stall = 1;
2207 		}
2208 		break;
2209 
2210 	default:
2211 		error = ENOIOCTL;
2212 		break;
2213 	}
2214 	return (error);
2215 }
2216 
2217 static int
2218 ugen_ioctl_post(struct usb_fifo *f, u_long cmd, void *addr, int fflags)
2219 {
2220 	union {
2221 		struct usb_interface_descriptor *idesc;
2222 		struct usb_alt_interface *ai;
2223 		struct usb_device_descriptor *ddesc;
2224 		struct usb_config_descriptor *cdesc;
2225 		struct usb_device_stats *stat;
2226 		struct usb_fs_init *pinit;
2227 #ifdef COMPAT_FREEBSD32
2228 		struct usb_fs_init32 *pinit32;
2229 #endif
2230 		struct usb_fs_uninit *puninit;
2231 		struct usb_fs_open *popen;
2232 		struct usb_fs_open_stream *popen_stream;
2233 		struct usb_fs_close *pclose;
2234 		struct usb_fs_clear_stall_sync *pstall;
2235 		struct usb_device_port_path *dpp;
2236 		uint32_t *ptime;
2237 		void   *addr;
2238 		int    *pint;
2239 	}     u;
2240 	struct usb_device_descriptor *dtemp;
2241 	struct usb_config_descriptor *ctemp;
2242 	struct usb_interface *iface;
2243 	int error = 0;
2244 	uint8_t n;
2245 
2246 	u.addr = addr;
2247 
2248 	DPRINTFN(6, "cmd=0x%08lx\n", cmd);
2249 
2250 	switch (cmd) {
2251 	case USB_DISCOVER:
2252 		usb_needs_explore_all();
2253 		break;
2254 
2255 	case USB_SETDEBUG:
2256 		if (!(fflags & FWRITE)) {
2257 			error = EPERM;
2258 			break;
2259 		}
2260 		usb_debug = *(int *)addr;
2261 		break;
2262 
2263 	case USB_GET_CONFIG:
2264 		*(int *)addr = f->udev->curr_config_index;
2265 		break;
2266 
2267 	case USB_SET_CONFIG:
2268 		if (!(fflags & FWRITE)) {
2269 			error = EPERM;
2270 			break;
2271 		}
2272 		error = ugen_set_config(f, *(int *)addr);
2273 		break;
2274 
2275 	case USB_GET_ALTINTERFACE:
2276 		iface = usbd_get_iface(f->udev,
2277 		    u.ai->uai_interface_index);
2278 		if (iface && iface->idesc) {
2279 			u.ai->uai_alt_index = iface->alt_index;
2280 		} else {
2281 			error = EINVAL;
2282 		}
2283 		break;
2284 
2285 	case USB_SET_ALTINTERFACE:
2286 		if (!(fflags & FWRITE)) {
2287 			error = EPERM;
2288 			break;
2289 		}
2290 		error = ugen_set_interface(f,
2291 		    u.ai->uai_interface_index, u.ai->uai_alt_index);
2292 		break;
2293 
2294 	case USB_GET_DEVICE_DESC:
2295 		dtemp = usbd_get_device_descriptor(f->udev);
2296 		if (!dtemp) {
2297 			error = EIO;
2298 			break;
2299 		}
2300 		*u.ddesc = *dtemp;
2301 		break;
2302 
2303 	case USB_GET_CONFIG_DESC:
2304 		ctemp = usbd_get_config_descriptor(f->udev);
2305 		if (!ctemp) {
2306 			error = EIO;
2307 			break;
2308 		}
2309 		*u.cdesc = *ctemp;
2310 		break;
2311 
2312 	case USB_GET_FULL_DESC:
2313 		error = ugen_get_cdesc(f, addr);
2314 		break;
2315 
2316 	case USB_GET_STRING_DESC:
2317 		error = ugen_get_sdesc(f, addr);
2318 		break;
2319 
2320 	case USB_GET_IFACE_DRIVER:
2321 		error = ugen_get_iface_driver(f, addr);
2322 		break;
2323 
2324 #ifdef COMPAT_FREEBSD32
2325 	case USB_GET_FULL_DESC32:
2326 	case USB_GET_STRING_DESC32:
2327 	case USB_GET_IFACE_DRIVER32:
2328 		error = ugen_get32(cmd, f, addr);
2329 		break;
2330 #endif
2331 
2332 	case USB_REQUEST:
2333 	case USB_DO_REQUEST:
2334 		if (!(fflags & FWRITE)) {
2335 			error = EPERM;
2336 			break;
2337 		}
2338 		error = ugen_do_request(f, addr);
2339 		break;
2340 
2341 #ifdef COMPAT_FREEBSD32
2342 	case USB_REQUEST32:
2343 	case USB_DO_REQUEST32:
2344 		if (!(fflags & FWRITE)) {
2345 			error = EPERM;
2346 			break;
2347 		}
2348 		error = ugen_do_request32(f, addr);
2349 		break;
2350 #endif
2351 
2352 	case USB_DEVICEINFO:
2353 	case USB_GET_DEVICEINFO:
2354 		error = ugen_fill_deviceinfo(f, addr);
2355 		break;
2356 
2357 	case USB_DEVICESTATS:
2358 		for (n = 0; n != 4; n++) {
2359 			u.stat->uds_requests_fail[n] =
2360 			    f->udev->stats_err.uds_requests[n];
2361 			u.stat->uds_requests_ok[n] =
2362 			    f->udev->stats_ok.uds_requests[n];
2363 		}
2364 		break;
2365 
2366 	case USB_DEVICEENUMERATE:
2367 		error = ugen_re_enumerate(f);
2368 		break;
2369 
2370 	case USB_GET_PLUGTIME:
2371 		*u.ptime = f->udev->plugtime;
2372 		break;
2373 
2374 	case USB_CLAIM_INTERFACE:
2375 	case USB_RELEASE_INTERFACE:
2376 		/* TODO */
2377 		break;
2378 
2379 	case USB_IFACE_DRIVER_ACTIVE:
2380 		n = *u.pint & 0xFF;
2381 		iface = usbd_get_iface(f->udev, n);
2382 		if (iface != NULL && iface->subdev != NULL &&
2383 		    device_is_alive(iface->subdev))
2384 			error = 0;
2385 		else
2386 			error = ENXIO;
2387 		break;
2388 
2389 	case USB_IFACE_DRIVER_DETACH:
2390 
2391 		error = priv_check(curthread, PRIV_DRIVER);
2392 
2393 		if (error)
2394 			break;
2395 
2396 		n = *u.pint & 0xFF;
2397 
2398 		if (n == USB_IFACE_INDEX_ANY) {
2399 			error = EINVAL;
2400 			break;
2401 		}
2402 
2403 		/*
2404 		 * Detach the currently attached driver.
2405 		 */
2406 		usb_detach_device(f->udev, n, 0);
2407 
2408 		/*
2409 		 * Set parent to self, this should keep attach away
2410 		 * until the next set configuration event.
2411 		 */
2412 		usbd_set_parent_iface(f->udev, n, n);
2413 		break;
2414 
2415 	case USB_SET_POWER_MODE:
2416 		error = ugen_set_power_mode(f, *u.pint);
2417 		break;
2418 
2419 	case USB_GET_POWER_MODE:
2420 		*u.pint = ugen_get_power_mode(f);
2421 		break;
2422 
2423 	case USB_GET_DEV_PORT_PATH:
2424 		error = ugen_get_port_path(f, u.dpp);
2425 		break;
2426 
2427 	case USB_GET_POWER_USAGE:
2428 		*u.pint = ugen_get_power_usage(f);
2429 		break;
2430 
2431 	case USB_SET_PORT_ENABLE:
2432 		error = ugen_do_port_feature(f,
2433 		    *u.pint, 1, UHF_PORT_ENABLE);
2434 		break;
2435 
2436 	case USB_SET_PORT_DISABLE:
2437 		error = ugen_do_port_feature(f,
2438 		    *u.pint, 0, UHF_PORT_ENABLE);
2439 		break;
2440 
2441 	case USB_FS_INIT:
2442 		error = ugen_fs_init(f, u.pinit->pEndpoints,
2443 		    sizeof(struct usb_fs_endpoint), fflags,
2444 		    u.pinit->ep_index_max);
2445 		break;
2446 #ifdef COMPAT_FREEBSD32
2447 	case USB_FS_INIT32:
2448 		error = ugen_fs_init(f, PTRIN(u.pinit32->pEndpoints),
2449 		    sizeof(struct usb_fs_endpoint32), fflags,
2450 		    u.pinit32->ep_index_max);
2451 		break;
2452 #endif
2453 	case USB_FS_UNINIT:
2454 		if (u.puninit->dummy != 0) {
2455 			error = EINVAL;
2456 			break;
2457 		}
2458 		error = ugen_fs_uninit(f);
2459 		break;
2460 
2461 	case USB_FS_OPEN:
2462 	case USB_FS_OPEN_STREAM:
2463 		error = usb_fs_open(f, u.popen, fflags,
2464 		    (cmd == USB_FS_OPEN_STREAM) ? u.popen_stream->stream_id : 0);
2465 		break;
2466 
2467 	case USB_FS_CLOSE:
2468 		error = usb_fs_close(f, u.pclose);
2469 		break;
2470 
2471 	case USB_FS_CLEAR_STALL_SYNC:
2472 		error = usb_fs_clear_stall_sync(f, u.pstall);
2473 		break;
2474 
2475 	default:
2476 		mtx_lock(f->priv_mtx);
2477 		error = ugen_iface_ioctl(f, cmd, addr, fflags);
2478 		mtx_unlock(f->priv_mtx);
2479 		break;
2480 	}
2481 	DPRINTFN(6, "error=%d\n", error);
2482 	return (error);
2483 }
2484 
2485 static void
2486 ugen_ctrl_fs_callback(struct usb_xfer *xfer, usb_error_t error)
2487 {
2488 	;				/* workaround for a bug in "indent" */
2489 
2490 	DPRINTF("st=%u alen=%u aframes=%u\n",
2491 	    USB_GET_STATE(xfer), xfer->actlen, xfer->aframes);
2492 
2493 	switch (USB_GET_STATE(xfer)) {
2494 	case USB_ST_SETUP:
2495 		usbd_transfer_submit(xfer);
2496 		break;
2497 	default:
2498 		ugen_fs_set_complete(xfer->priv_sc, USB_P2U(xfer->priv_fifo));
2499 		break;
2500 	}
2501 }
2502 
2503 #ifdef COMPAT_FREEBSD32
2504 void
2505 usb_gen_descriptor_from32(struct usb_gen_descriptor *ugd,
2506     const struct usb_gen_descriptor32 *ugd32)
2507 {
2508 	PTRIN_CP(*ugd32, *ugd, ugd_data);
2509 	CP(*ugd32, *ugd, ugd_lang_id);
2510 	CP(*ugd32, *ugd, ugd_maxlen);
2511 	CP(*ugd32, *ugd, ugd_actlen);
2512 	CP(*ugd32, *ugd, ugd_offset);
2513 	CP(*ugd32, *ugd, ugd_config_index);
2514 	CP(*ugd32, *ugd, ugd_string_index);
2515 	CP(*ugd32, *ugd, ugd_iface_index);
2516 	CP(*ugd32, *ugd, ugd_altif_index);
2517 	CP(*ugd32, *ugd, ugd_endpt_index);
2518 	CP(*ugd32, *ugd, ugd_report_type);
2519 	/* Don't copy reserved */
2520 }
2521 
2522 void
2523 update_usb_gen_descriptor32(struct usb_gen_descriptor32 *ugd32,
2524     struct usb_gen_descriptor *ugd)
2525 {
2526 	/* Don't update ugd_data pointer */
2527 	CP(*ugd32, *ugd, ugd_lang_id);
2528 	CP(*ugd32, *ugd, ugd_maxlen);
2529 	CP(*ugd32, *ugd, ugd_actlen);
2530 	CP(*ugd32, *ugd, ugd_offset);
2531 	CP(*ugd32, *ugd, ugd_config_index);
2532 	CP(*ugd32, *ugd, ugd_string_index);
2533 	CP(*ugd32, *ugd, ugd_iface_index);
2534 	CP(*ugd32, *ugd, ugd_altif_index);
2535 	CP(*ugd32, *ugd, ugd_endpt_index);
2536 	CP(*ugd32, *ugd, ugd_report_type);
2537 	/* Don't update reserved */
2538 }
2539 
2540 static int
2541 ugen_get32(u_long cmd, struct usb_fifo *f, struct usb_gen_descriptor32 *ugd32)
2542 {
2543 	struct usb_gen_descriptor ugd;
2544 	int error;
2545 
2546 	usb_gen_descriptor_from32(&ugd, ugd32);
2547 	switch (cmd) {
2548 	case USB_GET_FULL_DESC32:
2549 		error = ugen_get_cdesc(f, &ugd);
2550 		break;
2551 
2552 	case USB_GET_STRING_DESC32:
2553 		error = ugen_get_sdesc(f, &ugd);
2554 		break;
2555 
2556 	case USB_GET_IFACE_DRIVER32:
2557 		error = ugen_get_iface_driver(f, &ugd);
2558 		break;
2559 	default:
2560 		/* Can't happen except by programmer error */
2561 		panic("%s: called with invalid cmd %lx", __func__, cmd);
2562 	}
2563 	update_usb_gen_descriptor32(ugd32, &ugd);
2564 
2565 	return (error);
2566 }
2567 
2568 #endif /* COMPAT_FREEBSD32 */
2569 
2570 #endif	/* USB_HAVE_UGEN */
2571