xref: /freebsd/sys/dev/usb/usb_dev.c (revision ee7b0571c2c18bdec848ed2044223cc88db29bd8)
1 /* $FreeBSD$ */
2 /*-
3  * Copyright (c) 2006-2008 Hans Petter Selasky. All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  *
27  * usb_dev.c - An abstraction layer for creating devices under /dev/...
28  */
29 
30 #ifdef USB_GLOBAL_INCLUDE_FILE
31 #include USB_GLOBAL_INCLUDE_FILE
32 #else
33 #include <sys/stdint.h>
34 #include <sys/stddef.h>
35 #include <sys/param.h>
36 #include <sys/queue.h>
37 #include <sys/types.h>
38 #include <sys/systm.h>
39 #include <sys/kernel.h>
40 #include <sys/bus.h>
41 #include <sys/module.h>
42 #include <sys/lock.h>
43 #include <sys/mutex.h>
44 #include <sys/condvar.h>
45 #include <sys/sysctl.h>
46 #include <sys/sx.h>
47 #include <sys/unistd.h>
48 #include <sys/callout.h>
49 #include <sys/malloc.h>
50 #include <sys/priv.h>
51 #include <sys/vnode.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 usb_fifo_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_busdma.h>
69 #include <dev/usb/usb_generic.h>
70 #include <dev/usb/usb_dynamic.h>
71 #include <dev/usb/usb_util.h>
72 
73 #include <dev/usb/usb_controller.h>
74 #include <dev/usb/usb_bus.h>
75 
76 #include <sys/filio.h>
77 #include <sys/ttycom.h>
78 #include <sys/syscallsubr.h>
79 
80 #include <machine/stdarg.h>
81 #endif			/* USB_GLOBAL_INCLUDE_FILE */
82 
83 #if USB_HAVE_UGEN
84 
85 #ifdef USB_DEBUG
86 static int usb_fifo_debug = 0;
87 
88 static SYSCTL_NODE(_hw_usb, OID_AUTO, dev, CTLFLAG_RW, 0, "USB device");
89 SYSCTL_INT(_hw_usb_dev, OID_AUTO, debug, CTLFLAG_RWTUN,
90     &usb_fifo_debug, 0, "Debug Level");
91 #endif
92 
93 #if ((__FreeBSD_version >= 700001) || (__FreeBSD_version == 0) || \
94      ((__FreeBSD_version >= 600034) && (__FreeBSD_version < 700000)))
95 #define	USB_UCRED struct ucred *ucred,
96 #else
97 #define	USB_UCRED
98 #endif
99 
100 /* prototypes */
101 
102 static int	usb_fifo_open(struct usb_cdev_privdata *,
103 		    struct usb_fifo *, int);
104 static void	usb_fifo_close(struct usb_fifo *, int);
105 static void	usb_dev_init(void *);
106 static void	usb_dev_init_post(void *);
107 static void	usb_dev_uninit(void *);
108 static int	usb_fifo_uiomove(struct usb_fifo *, void *, int,
109 		    struct uio *);
110 static void	usb_fifo_check_methods(struct usb_fifo_methods *);
111 static struct	usb_fifo *usb_fifo_alloc(struct mtx *);
112 static struct	usb_endpoint *usb_dev_get_ep(struct usb_device *, uint8_t,
113 		    uint8_t);
114 static void	usb_loc_fill(struct usb_fs_privdata *,
115 		    struct usb_cdev_privdata *);
116 static void	usb_close(void *);
117 static usb_error_t usb_ref_device(struct usb_cdev_privdata *, struct usb_cdev_refdata *, int);
118 static usb_error_t usb_usb_ref_device(struct usb_cdev_privdata *, struct usb_cdev_refdata *);
119 static void	usb_unref_device(struct usb_cdev_privdata *, struct usb_cdev_refdata *);
120 
121 static d_open_t usb_open;
122 static d_ioctl_t usb_ioctl;
123 static d_read_t usb_read;
124 static d_write_t usb_write;
125 static d_poll_t usb_poll;
126 static d_kqfilter_t usb_kqfilter;
127 
128 static d_ioctl_t usb_static_ioctl;
129 
130 static usb_fifo_open_t usb_fifo_dummy_open;
131 static usb_fifo_close_t usb_fifo_dummy_close;
132 static usb_fifo_ioctl_t usb_fifo_dummy_ioctl;
133 static usb_fifo_cmd_t usb_fifo_dummy_cmd;
134 
135 /* character device structure used for devices (/dev/ugenX.Y and /dev/uXXX) */
136 struct cdevsw usb_devsw = {
137 	.d_version = D_VERSION,
138 	.d_open = usb_open,
139 	.d_ioctl = usb_ioctl,
140 	.d_name = "usbdev",
141 	.d_flags = D_TRACKCLOSE,
142 	.d_read = usb_read,
143 	.d_write = usb_write,
144 	.d_poll = usb_poll,
145 	.d_kqfilter = usb_kqfilter,
146 };
147 
148 static struct cdev* usb_dev = NULL;
149 
150 /* character device structure used for /dev/usb */
151 static struct cdevsw usb_static_devsw = {
152 	.d_version = D_VERSION,
153 	.d_ioctl = usb_static_ioctl,
154 	.d_name = "usb"
155 };
156 
157 static TAILQ_HEAD(, usb_symlink) usb_sym_head;
158 static struct sx usb_sym_lock;
159 
160 struct mtx usb_ref_lock;
161 
162 /*------------------------------------------------------------------------*
163  *	usb_loc_fill
164  *
165  * This is used to fill out a usb_cdev_privdata structure based on the
166  * device's address as contained in usb_fs_privdata.
167  *------------------------------------------------------------------------*/
168 static void
169 usb_loc_fill(struct usb_fs_privdata* pd, struct usb_cdev_privdata *cpd)
170 {
171 	cpd->bus_index = pd->bus_index;
172 	cpd->dev_index = pd->dev_index;
173 	cpd->ep_addr = pd->ep_addr;
174 	cpd->fifo_index = pd->fifo_index;
175 }
176 
177 /*------------------------------------------------------------------------*
178  *	usb_ref_device
179  *
180  * This function is used to atomically refer an USB device by its
181  * device location. If this function returns success the USB device
182  * will not dissappear until the USB device is unreferenced.
183  *
184  * Return values:
185  *  0: Success, refcount incremented on the given USB device.
186  *  Else: Failure.
187  *------------------------------------------------------------------------*/
188 static usb_error_t
189 usb_ref_device(struct usb_cdev_privdata *cpd,
190     struct usb_cdev_refdata *crd, int need_uref)
191 {
192 	struct usb_fifo **ppf;
193 	struct usb_fifo *f;
194 
195 	DPRINTFN(2, "cpd=%p need uref=%d\n", cpd, need_uref);
196 
197 	/* clear all refs */
198 	memset(crd, 0, sizeof(*crd));
199 
200 	mtx_lock(&usb_ref_lock);
201 	cpd->bus = devclass_get_softc(usb_devclass_ptr, cpd->bus_index);
202 	if (cpd->bus == NULL) {
203 		DPRINTFN(2, "no bus at %u\n", cpd->bus_index);
204 		goto error;
205 	}
206 	cpd->udev = cpd->bus->devices[cpd->dev_index];
207 	if (cpd->udev == NULL) {
208 		DPRINTFN(2, "no device at %u\n", cpd->dev_index);
209 		goto error;
210 	}
211 	if (cpd->udev->state == USB_STATE_DETACHED &&
212 	    (need_uref != 2)) {
213 		DPRINTFN(2, "device is detached\n");
214 		goto error;
215 	}
216 	if (need_uref) {
217 		DPRINTFN(2, "ref udev - needed\n");
218 
219 		if (cpd->udev->refcount == USB_DEV_REF_MAX) {
220 			DPRINTFN(2, "no dev ref\n");
221 			goto error;
222 		}
223 		cpd->udev->refcount++;
224 
225 		mtx_unlock(&usb_ref_lock);
226 
227 		/*
228 		 * We need to grab the enumeration SX-lock before
229 		 * grabbing the FIFO refs to avoid deadlock at detach!
230 		 */
231 		crd->do_unlock = usbd_enum_lock(cpd->udev);
232 
233 		mtx_lock(&usb_ref_lock);
234 
235 		/*
236 		 * Set "is_uref" after grabbing the default SX lock
237 		 */
238 		crd->is_uref = 1;
239 	}
240 
241 	/* check if we are doing an open */
242 	if (cpd->fflags == 0) {
243 		/* use zero defaults */
244 	} else {
245 		/* check for write */
246 		if (cpd->fflags & FWRITE) {
247 			ppf = cpd->udev->fifo;
248 			f = ppf[cpd->fifo_index + USB_FIFO_TX];
249 			crd->txfifo = f;
250 			crd->is_write = 1;	/* ref */
251 			if (f == NULL || f->refcount == USB_FIFO_REF_MAX)
252 				goto error;
253 			if (f->curr_cpd != cpd)
254 				goto error;
255 			/* check if USB-FS is active */
256 			if (f->fs_ep_max != 0) {
257 				crd->is_usbfs = 1;
258 			}
259 		}
260 
261 		/* check for read */
262 		if (cpd->fflags & FREAD) {
263 			ppf = cpd->udev->fifo;
264 			f = ppf[cpd->fifo_index + USB_FIFO_RX];
265 			crd->rxfifo = f;
266 			crd->is_read = 1;	/* ref */
267 			if (f == NULL || f->refcount == USB_FIFO_REF_MAX)
268 				goto error;
269 			if (f->curr_cpd != cpd)
270 				goto error;
271 			/* check if USB-FS is active */
272 			if (f->fs_ep_max != 0) {
273 				crd->is_usbfs = 1;
274 			}
275 		}
276 	}
277 
278 	/* when everything is OK we increment the refcounts */
279 	if (crd->is_write) {
280 		DPRINTFN(2, "ref write\n");
281 		crd->txfifo->refcount++;
282 	}
283 	if (crd->is_read) {
284 		DPRINTFN(2, "ref read\n");
285 		crd->rxfifo->refcount++;
286 	}
287 	mtx_unlock(&usb_ref_lock);
288 
289 	return (0);
290 
291 error:
292 	if (crd->do_unlock)
293 		usbd_enum_unlock(cpd->udev);
294 
295 	if (crd->is_uref) {
296 		cpd->udev->refcount--;
297 		cv_broadcast(&cpd->udev->ref_cv);
298 	}
299 	mtx_unlock(&usb_ref_lock);
300 	DPRINTFN(2, "fail\n");
301 	return (USB_ERR_INVAL);
302 }
303 
304 /*------------------------------------------------------------------------*
305  *	usb_usb_ref_device
306  *
307  * This function is used to upgrade an USB reference to include the
308  * USB device reference on a USB location.
309  *
310  * Return values:
311  *  0: Success, refcount incremented on the given USB device.
312  *  Else: Failure.
313  *------------------------------------------------------------------------*/
314 static usb_error_t
315 usb_usb_ref_device(struct usb_cdev_privdata *cpd,
316     struct usb_cdev_refdata *crd)
317 {
318 	/*
319 	 * Check if we already got an USB reference on this location:
320 	 */
321 	if (crd->is_uref)
322 		return (0);		/* success */
323 
324 	/*
325 	 * To avoid deadlock at detach we need to drop the FIFO ref
326 	 * and re-acquire a new ref!
327 	 */
328 	usb_unref_device(cpd, crd);
329 
330 	return (usb_ref_device(cpd, crd, 1 /* need uref */));
331 }
332 
333 /*------------------------------------------------------------------------*
334  *	usb_unref_device
335  *
336  * This function will release the reference count by one unit for the
337  * given USB device.
338  *------------------------------------------------------------------------*/
339 static void
340 usb_unref_device(struct usb_cdev_privdata *cpd,
341     struct usb_cdev_refdata *crd)
342 {
343 
344 	DPRINTFN(2, "cpd=%p is_uref=%d\n", cpd, crd->is_uref);
345 
346 	if (crd->do_unlock)
347 		usbd_enum_unlock(cpd->udev);
348 
349 	mtx_lock(&usb_ref_lock);
350 	if (crd->is_read) {
351 		if (--(crd->rxfifo->refcount) == 0) {
352 			cv_signal(&crd->rxfifo->cv_drain);
353 		}
354 		crd->is_read = 0;
355 	}
356 	if (crd->is_write) {
357 		if (--(crd->txfifo->refcount) == 0) {
358 			cv_signal(&crd->txfifo->cv_drain);
359 		}
360 		crd->is_write = 0;
361 	}
362 	if (crd->is_uref) {
363 		crd->is_uref = 0;
364 		cpd->udev->refcount--;
365 		cv_broadcast(&cpd->udev->ref_cv);
366 	}
367 	mtx_unlock(&usb_ref_lock);
368 }
369 
370 static struct usb_fifo *
371 usb_fifo_alloc(struct mtx *mtx)
372 {
373 	struct usb_fifo *f;
374 
375 	f = malloc(sizeof(*f), M_USBDEV, M_WAITOK | M_ZERO);
376 	if (f != NULL) {
377 		cv_init(&f->cv_io, "FIFO-IO");
378 		cv_init(&f->cv_drain, "FIFO-DRAIN");
379 		f->priv_mtx = mtx;
380 		f->refcount = 1;
381 		knlist_init_mtx(&f->selinfo.si_note, mtx);
382 	}
383 	return (f);
384 }
385 
386 /*------------------------------------------------------------------------*
387  *	usb_fifo_create
388  *------------------------------------------------------------------------*/
389 static int
390 usb_fifo_create(struct usb_cdev_privdata *cpd,
391     struct usb_cdev_refdata *crd)
392 {
393 	struct usb_device *udev = cpd->udev;
394 	struct usb_fifo *f;
395 	struct usb_endpoint *ep;
396 	uint8_t n;
397 	uint8_t is_tx;
398 	uint8_t is_rx;
399 	uint8_t no_null;
400 	uint8_t is_busy;
401 	int e = cpd->ep_addr;
402 
403 	is_tx = (cpd->fflags & FWRITE) ? 1 : 0;
404 	is_rx = (cpd->fflags & FREAD) ? 1 : 0;
405 	no_null = 1;
406 	is_busy = 0;
407 
408 	/* Preallocated FIFO */
409 	if (e < 0) {
410 		DPRINTFN(5, "Preallocated FIFO\n");
411 		if (is_tx) {
412 			f = udev->fifo[cpd->fifo_index + USB_FIFO_TX];
413 			if (f == NULL)
414 				return (EINVAL);
415 			crd->txfifo = f;
416 		}
417 		if (is_rx) {
418 			f = udev->fifo[cpd->fifo_index + USB_FIFO_RX];
419 			if (f == NULL)
420 				return (EINVAL);
421 			crd->rxfifo = f;
422 		}
423 		return (0);
424 	}
425 
426 	KASSERT(e >= 0 && e <= 15, ("endpoint %d out of range", e));
427 
428 	/* search for a free FIFO slot */
429 	DPRINTFN(5, "Endpoint device, searching for 0x%02x\n", e);
430 	for (n = 0;; n += 2) {
431 
432 		if (n == USB_FIFO_MAX) {
433 			if (no_null) {
434 				no_null = 0;
435 				n = 0;
436 			} else {
437 				/* end of FIFOs reached */
438 				DPRINTFN(5, "out of FIFOs\n");
439 				return (ENOMEM);
440 			}
441 		}
442 		/* Check for TX FIFO */
443 		if (is_tx) {
444 			f = udev->fifo[n + USB_FIFO_TX];
445 			if (f != NULL) {
446 				if (f->dev_ep_index != e) {
447 					/* wrong endpoint index */
448 					continue;
449 				}
450 				if (f->curr_cpd != NULL) {
451 					/* FIFO is opened */
452 					is_busy = 1;
453 					continue;
454 				}
455 			} else if (no_null) {
456 				continue;
457 			}
458 		}
459 		/* Check for RX FIFO */
460 		if (is_rx) {
461 			f = udev->fifo[n + USB_FIFO_RX];
462 			if (f != NULL) {
463 				if (f->dev_ep_index != e) {
464 					/* wrong endpoint index */
465 					continue;
466 				}
467 				if (f->curr_cpd != NULL) {
468 					/* FIFO is opened */
469 					is_busy = 1;
470 					continue;
471 				}
472 			} else if (no_null) {
473 				continue;
474 			}
475 		}
476 		break;
477 	}
478 
479 	if (no_null == 0) {
480 		if (e >= (USB_EP_MAX / 2)) {
481 			/* we don't create any endpoints in this range */
482 			DPRINTFN(5, "ep out of range\n");
483 			return (is_busy ? EBUSY : EINVAL);
484 		}
485 	}
486 
487 	if ((e != 0) && is_busy) {
488 		/*
489 		 * Only the default control endpoint is allowed to be
490 		 * opened multiple times!
491 		 */
492 		DPRINTFN(5, "busy\n");
493 		return (EBUSY);
494 	}
495 
496 	/* Check TX FIFO */
497 	if (is_tx &&
498 	    (udev->fifo[n + USB_FIFO_TX] == NULL)) {
499 		ep = usb_dev_get_ep(udev, e, USB_FIFO_TX);
500 		DPRINTFN(5, "dev_get_endpoint(%d, 0x%x)\n", e, USB_FIFO_TX);
501 		if (ep == NULL) {
502 			DPRINTFN(5, "dev_get_endpoint returned NULL\n");
503 			return (EINVAL);
504 		}
505 		f = usb_fifo_alloc(&udev->device_mtx);
506 		if (f == NULL) {
507 			DPRINTFN(5, "could not alloc tx fifo\n");
508 			return (ENOMEM);
509 		}
510 		/* update some fields */
511 		f->fifo_index = n + USB_FIFO_TX;
512 		f->dev_ep_index = e;
513 		f->priv_sc0 = ep;
514 		f->methods = &usb_ugen_methods;
515 		f->iface_index = ep->iface_index;
516 		f->udev = udev;
517 		mtx_lock(&usb_ref_lock);
518 		udev->fifo[n + USB_FIFO_TX] = f;
519 		mtx_unlock(&usb_ref_lock);
520 	}
521 	/* Check RX FIFO */
522 	if (is_rx &&
523 	    (udev->fifo[n + USB_FIFO_RX] == NULL)) {
524 
525 		ep = usb_dev_get_ep(udev, e, USB_FIFO_RX);
526 		DPRINTFN(5, "dev_get_endpoint(%d, 0x%x)\n", e, USB_FIFO_RX);
527 		if (ep == NULL) {
528 			DPRINTFN(5, "dev_get_endpoint returned NULL\n");
529 			return (EINVAL);
530 		}
531 		f = usb_fifo_alloc(&udev->device_mtx);
532 		if (f == NULL) {
533 			DPRINTFN(5, "could not alloc rx fifo\n");
534 			return (ENOMEM);
535 		}
536 		/* update some fields */
537 		f->fifo_index = n + USB_FIFO_RX;
538 		f->dev_ep_index = e;
539 		f->priv_sc0 = ep;
540 		f->methods = &usb_ugen_methods;
541 		f->iface_index = ep->iface_index;
542 		f->udev = udev;
543 		mtx_lock(&usb_ref_lock);
544 		udev->fifo[n + USB_FIFO_RX] = f;
545 		mtx_unlock(&usb_ref_lock);
546 	}
547 	if (is_tx) {
548 		crd->txfifo = udev->fifo[n + USB_FIFO_TX];
549 	}
550 	if (is_rx) {
551 		crd->rxfifo = udev->fifo[n + USB_FIFO_RX];
552 	}
553 	/* fill out fifo index */
554 	DPRINTFN(5, "fifo index = %d\n", n);
555 	cpd->fifo_index = n;
556 
557 	/* complete */
558 
559 	return (0);
560 }
561 
562 void
563 usb_fifo_free(struct usb_fifo *f)
564 {
565 	uint8_t n;
566 
567 	if (f == NULL) {
568 		/* be NULL safe */
569 		return;
570 	}
571 	/* destroy symlink devices, if any */
572 	for (n = 0; n != 2; n++) {
573 		if (f->symlink[n]) {
574 			usb_free_symlink(f->symlink[n]);
575 			f->symlink[n] = NULL;
576 		}
577 	}
578 	mtx_lock(&usb_ref_lock);
579 
580 	/* delink ourselves to stop calls from userland */
581 	if ((f->fifo_index < USB_FIFO_MAX) &&
582 	    (f->udev != NULL) &&
583 	    (f->udev->fifo[f->fifo_index] == f)) {
584 		f->udev->fifo[f->fifo_index] = NULL;
585 	} else {
586 		DPRINTFN(0, "USB FIFO %p has not been linked\n", f);
587 	}
588 
589 	/* decrease refcount */
590 	f->refcount--;
591 	/* prevent any write flush */
592 	f->flag_iserror = 1;
593 	/* need to wait until all callers have exited */
594 	while (f->refcount != 0) {
595 		mtx_unlock(&usb_ref_lock);	/* avoid LOR */
596 		mtx_lock(f->priv_mtx);
597 		/* get I/O thread out of any sleep state */
598 		if (f->flag_sleeping) {
599 			f->flag_sleeping = 0;
600 			cv_broadcast(&f->cv_io);
601 		}
602 		mtx_unlock(f->priv_mtx);
603 		mtx_lock(&usb_ref_lock);
604 
605 		/*
606 		 * Check if the "f->refcount" variable reached zero
607 		 * during the unlocked time before entering wait:
608 		 */
609 		if (f->refcount == 0)
610 			break;
611 
612 		/* wait for sync */
613 		cv_wait(&f->cv_drain, &usb_ref_lock);
614 	}
615 	mtx_unlock(&usb_ref_lock);
616 
617 	/* take care of closing the device here, if any */
618 	usb_fifo_close(f, 0);
619 
620 	cv_destroy(&f->cv_io);
621 	cv_destroy(&f->cv_drain);
622 
623 	knlist_clear(&f->selinfo.si_note, 0);
624 	seldrain(&f->selinfo);
625 	knlist_destroy(&f->selinfo.si_note);
626 
627 	free(f, M_USBDEV);
628 }
629 
630 static struct usb_endpoint *
631 usb_dev_get_ep(struct usb_device *udev, uint8_t ep_index, uint8_t dir)
632 {
633 	struct usb_endpoint *ep;
634 	uint8_t ep_dir;
635 
636 	if (ep_index == 0) {
637 		ep = &udev->ctrl_ep;
638 	} else {
639 		if (dir == USB_FIFO_RX) {
640 			if (udev->flags.usb_mode == USB_MODE_HOST) {
641 				ep_dir = UE_DIR_IN;
642 			} else {
643 				ep_dir = UE_DIR_OUT;
644 			}
645 		} else {
646 			if (udev->flags.usb_mode == USB_MODE_HOST) {
647 				ep_dir = UE_DIR_OUT;
648 			} else {
649 				ep_dir = UE_DIR_IN;
650 			}
651 		}
652 		ep = usbd_get_ep_by_addr(udev, ep_index | ep_dir);
653 	}
654 
655 	if (ep == NULL) {
656 		/* if the endpoint does not exist then return */
657 		return (NULL);
658 	}
659 	if (ep->edesc == NULL) {
660 		/* invalid endpoint */
661 		return (NULL);
662 	}
663 	return (ep);			/* success */
664 }
665 
666 /*------------------------------------------------------------------------*
667  *	usb_fifo_open
668  *
669  * Returns:
670  * 0: Success
671  * Else: Failure
672  *------------------------------------------------------------------------*/
673 static int
674 usb_fifo_open(struct usb_cdev_privdata *cpd,
675     struct usb_fifo *f, int fflags)
676 {
677 	int err;
678 
679 	if (f == NULL) {
680 		/* no FIFO there */
681 		DPRINTFN(2, "no FIFO\n");
682 		return (ENXIO);
683 	}
684 	/* remove FWRITE and FREAD flags */
685 	fflags &= ~(FWRITE | FREAD);
686 
687 	/* set correct file flags */
688 	if ((f->fifo_index & 1) == USB_FIFO_TX) {
689 		fflags |= FWRITE;
690 	} else {
691 		fflags |= FREAD;
692 	}
693 
694 	/* check if we are already opened */
695 	/* we don't need any locks when checking this variable */
696 	if (f->curr_cpd != NULL) {
697 		err = EBUSY;
698 		goto done;
699 	}
700 
701 	/* reset short flag before open */
702 	f->flag_short = 0;
703 
704 	/* call open method */
705 	err = (f->methods->f_open) (f, fflags);
706 	if (err) {
707 		goto done;
708 	}
709 	mtx_lock(f->priv_mtx);
710 
711 	/* reset sleep flag */
712 	f->flag_sleeping = 0;
713 
714 	/* reset error flag */
715 	f->flag_iserror = 0;
716 
717 	/* reset complete flag */
718 	f->flag_iscomplete = 0;
719 
720 	/* reset select flag */
721 	f->flag_isselect = 0;
722 
723 	/* reset flushing flag */
724 	f->flag_flushing = 0;
725 
726 	/* reset ASYNC proc flag */
727 	f->async_p = NULL;
728 
729 	mtx_lock(&usb_ref_lock);
730 	/* flag the fifo as opened to prevent others */
731 	f->curr_cpd = cpd;
732 	mtx_unlock(&usb_ref_lock);
733 
734 	/* reset queue */
735 	usb_fifo_reset(f);
736 
737 	mtx_unlock(f->priv_mtx);
738 done:
739 	return (err);
740 }
741 
742 /*------------------------------------------------------------------------*
743  *	usb_fifo_reset
744  *------------------------------------------------------------------------*/
745 void
746 usb_fifo_reset(struct usb_fifo *f)
747 {
748 	struct usb_mbuf *m;
749 
750 	if (f == NULL) {
751 		return;
752 	}
753 	while (1) {
754 		USB_IF_DEQUEUE(&f->used_q, m);
755 		if (m) {
756 			USB_IF_ENQUEUE(&f->free_q, m);
757 		} else {
758 			break;
759 		}
760 	}
761 	/* reset have fragment flag */
762 	f->flag_have_fragment = 0;
763 }
764 
765 /*------------------------------------------------------------------------*
766  *	usb_fifo_close
767  *------------------------------------------------------------------------*/
768 static void
769 usb_fifo_close(struct usb_fifo *f, int fflags)
770 {
771 	int err;
772 
773 	/* check if we are not opened */
774 	if (f->curr_cpd == NULL) {
775 		/* nothing to do - already closed */
776 		return;
777 	}
778 	mtx_lock(f->priv_mtx);
779 
780 	/* clear current cdev private data pointer */
781 	mtx_lock(&usb_ref_lock);
782 	f->curr_cpd = NULL;
783 	mtx_unlock(&usb_ref_lock);
784 
785 	/* check if we are watched by kevent */
786 	KNOTE_LOCKED(&f->selinfo.si_note, 0);
787 
788 	/* check if we are selected */
789 	if (f->flag_isselect) {
790 		selwakeup(&f->selinfo);
791 		f->flag_isselect = 0;
792 	}
793 	/* check if a thread wants SIGIO */
794 	if (f->async_p != NULL) {
795 		PROC_LOCK(f->async_p);
796 		kern_psignal(f->async_p, SIGIO);
797 		PROC_UNLOCK(f->async_p);
798 		f->async_p = NULL;
799 	}
800 	/* remove FWRITE and FREAD flags */
801 	fflags &= ~(FWRITE | FREAD);
802 
803 	/* flush written data, if any */
804 	if ((f->fifo_index & 1) == USB_FIFO_TX) {
805 
806 		if (!f->flag_iserror) {
807 
808 			/* set flushing flag */
809 			f->flag_flushing = 1;
810 
811 			/* get the last packet in */
812 			if (f->flag_have_fragment) {
813 				struct usb_mbuf *m;
814 				f->flag_have_fragment = 0;
815 				USB_IF_DEQUEUE(&f->free_q, m);
816 				if (m) {
817 					USB_IF_ENQUEUE(&f->used_q, m);
818 				}
819 			}
820 
821 			/* start write transfer, if not already started */
822 			(f->methods->f_start_write) (f);
823 
824 			/* check if flushed already */
825 			while (f->flag_flushing &&
826 			    (!f->flag_iserror)) {
827 				/* wait until all data has been written */
828 				f->flag_sleeping = 1;
829 				err = cv_wait_sig(&f->cv_io, f->priv_mtx);
830 				if (err) {
831 					DPRINTF("signal received\n");
832 					break;
833 				}
834 			}
835 		}
836 		fflags |= FWRITE;
837 
838 		/* stop write transfer, if not already stopped */
839 		(f->methods->f_stop_write) (f);
840 	} else {
841 		fflags |= FREAD;
842 
843 		/* stop write transfer, if not already stopped */
844 		(f->methods->f_stop_read) (f);
845 	}
846 
847 	/* check if we are sleeping */
848 	if (f->flag_sleeping) {
849 		DPRINTFN(2, "Sleeping at close!\n");
850 	}
851 	mtx_unlock(f->priv_mtx);
852 
853 	/* call close method */
854 	(f->methods->f_close) (f, fflags);
855 
856 	DPRINTF("closed\n");
857 }
858 
859 /*------------------------------------------------------------------------*
860  *	usb_open - cdev callback
861  *------------------------------------------------------------------------*/
862 static int
863 usb_open(struct cdev *dev, int fflags, int devtype, struct thread *td)
864 {
865 	struct usb_fs_privdata* pd = (struct usb_fs_privdata*)dev->si_drv1;
866 	struct usb_cdev_refdata refs;
867 	struct usb_cdev_privdata *cpd;
868 	int err, ep;
869 
870 	DPRINTFN(2, "%s fflags=0x%08x\n", devtoname(dev), fflags);
871 
872 	KASSERT(fflags & (FREAD|FWRITE), ("invalid open flags"));
873 	if (((fflags & FREAD) && !(pd->mode & FREAD)) ||
874 	    ((fflags & FWRITE) && !(pd->mode & FWRITE))) {
875 		DPRINTFN(2, "access mode not supported\n");
876 		return (EPERM);
877 	}
878 
879 	cpd = malloc(sizeof(*cpd), M_USBDEV, M_WAITOK | M_ZERO);
880 	ep = cpd->ep_addr = pd->ep_addr;
881 
882 	usb_loc_fill(pd, cpd);
883 	err = usb_ref_device(cpd, &refs, 1);
884 	if (err) {
885 		DPRINTFN(2, "cannot ref device\n");
886 		free(cpd, M_USBDEV);
887 		return (ENXIO);
888 	}
889 	cpd->fflags = fflags;	/* access mode for open lifetime */
890 
891 	/* create FIFOs, if any */
892 	err = usb_fifo_create(cpd, &refs);
893 	/* check for error */
894 	if (err) {
895 		DPRINTFN(2, "cannot create fifo\n");
896 		usb_unref_device(cpd, &refs);
897 		free(cpd, M_USBDEV);
898 		return (err);
899 	}
900 	if (fflags & FREAD) {
901 		err = usb_fifo_open(cpd, refs.rxfifo, fflags);
902 		if (err) {
903 			DPRINTFN(2, "read open failed\n");
904 			usb_unref_device(cpd, &refs);
905 			free(cpd, M_USBDEV);
906 			return (err);
907 		}
908 	}
909 	if (fflags & FWRITE) {
910 		err = usb_fifo_open(cpd, refs.txfifo, fflags);
911 		if (err) {
912 			DPRINTFN(2, "write open failed\n");
913 			if (fflags & FREAD) {
914 				usb_fifo_close(refs.rxfifo, fflags);
915 			}
916 			usb_unref_device(cpd, &refs);
917 			free(cpd, M_USBDEV);
918 			return (err);
919 		}
920 	}
921 	usb_unref_device(cpd, &refs);
922 	devfs_set_cdevpriv(cpd, usb_close);
923 
924 	return (0);
925 }
926 
927 /*------------------------------------------------------------------------*
928  *	usb_close - cdev callback
929  *------------------------------------------------------------------------*/
930 static void
931 usb_close(void *arg)
932 {
933 	struct usb_cdev_refdata refs;
934 	struct usb_cdev_privdata *cpd = arg;
935 	int err;
936 
937 	DPRINTFN(2, "cpd=%p\n", cpd);
938 
939 	err = usb_ref_device(cpd, &refs,
940 	    2 /* uref and allow detached state */);
941 	if (err) {
942 		DPRINTFN(2, "Cannot grab USB reference when "
943 		    "closing USB file handle\n");
944 		goto done;
945 	}
946 	if (cpd->fflags & FREAD) {
947 		usb_fifo_close(refs.rxfifo, cpd->fflags);
948 	}
949 	if (cpd->fflags & FWRITE) {
950 		usb_fifo_close(refs.txfifo, cpd->fflags);
951 	}
952 	usb_unref_device(cpd, &refs);
953 done:
954 	free(cpd, M_USBDEV);
955 }
956 
957 static void
958 usb_dev_init(void *arg)
959 {
960 	mtx_init(&usb_ref_lock, "USB ref mutex", NULL, MTX_DEF);
961 	sx_init(&usb_sym_lock, "USB sym mutex");
962 	TAILQ_INIT(&usb_sym_head);
963 
964 	/* check the UGEN methods */
965 	usb_fifo_check_methods(&usb_ugen_methods);
966 }
967 
968 SYSINIT(usb_dev_init, SI_SUB_KLD, SI_ORDER_FIRST, usb_dev_init, NULL);
969 
970 static void
971 usb_dev_init_post(void *arg)
972 {
973 	/*
974 	 * Create /dev/usb - this is needed for usbconfig(8), which
975 	 * needs a well-known device name to access.
976 	 */
977 	usb_dev = make_dev(&usb_static_devsw, 0, UID_ROOT, GID_OPERATOR,
978 	    0644, USB_DEVICE_NAME);
979 	if (usb_dev == NULL) {
980 		DPRINTFN(0, "Could not create usb bus device\n");
981 	}
982 }
983 
984 SYSINIT(usb_dev_init_post, SI_SUB_KICK_SCHEDULER, SI_ORDER_FIRST, usb_dev_init_post, NULL);
985 
986 static void
987 usb_dev_uninit(void *arg)
988 {
989 	if (usb_dev != NULL) {
990 		destroy_dev(usb_dev);
991 		usb_dev = NULL;
992 	}
993 	mtx_destroy(&usb_ref_lock);
994 	sx_destroy(&usb_sym_lock);
995 }
996 
997 SYSUNINIT(usb_dev_uninit, SI_SUB_KICK_SCHEDULER, SI_ORDER_ANY, usb_dev_uninit, NULL);
998 
999 static int
1000 usb_ioctl_f_sub(struct usb_fifo *f, u_long cmd, void *addr,
1001     struct thread *td)
1002 {
1003 	int error = 0;
1004 
1005 	switch (cmd) {
1006 	case FIODTYPE:
1007 		*(int *)addr = 0;	/* character device */
1008 		break;
1009 
1010 	case FIONBIO:
1011 		/* handled by upper FS layer */
1012 		break;
1013 
1014 	case FIOASYNC:
1015 		if (*(int *)addr) {
1016 			if (f->async_p != NULL) {
1017 				error = EBUSY;
1018 				break;
1019 			}
1020 			f->async_p = USB_TD_GET_PROC(td);
1021 		} else {
1022 			f->async_p = NULL;
1023 		}
1024 		break;
1025 
1026 		/* XXX this is not the most general solution */
1027 	case TIOCSPGRP:
1028 		if (f->async_p == NULL) {
1029 			error = EINVAL;
1030 			break;
1031 		}
1032 		if (*(int *)addr != USB_PROC_GET_GID(f->async_p)) {
1033 			error = EPERM;
1034 			break;
1035 		}
1036 		break;
1037 	default:
1038 		return (ENOIOCTL);
1039 	}
1040 	DPRINTFN(3, "cmd 0x%lx = %d\n", cmd, error);
1041 	return (error);
1042 }
1043 
1044 /*------------------------------------------------------------------------*
1045  *	usb_ioctl - cdev callback
1046  *------------------------------------------------------------------------*/
1047 static int
1048 usb_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int fflag, struct thread* td)
1049 {
1050 	struct usb_cdev_refdata refs;
1051 	struct usb_cdev_privdata* cpd;
1052 	struct usb_fifo *f;
1053 	int fflags;
1054 	int err;
1055 
1056 	DPRINTFN(2, "cmd=0x%lx\n", cmd);
1057 
1058 	err = devfs_get_cdevpriv((void **)&cpd);
1059 	if (err != 0)
1060 		return (err);
1061 
1062 	/*
1063 	 * Performance optimisation: We try to check for IOCTL's that
1064 	 * don't need the USB reference first. Then we grab the USB
1065 	 * reference if we need it!
1066 	 */
1067 	err = usb_ref_device(cpd, &refs, 0 /* no uref */ );
1068 	if (err)
1069 		return (ENXIO);
1070 
1071 	fflags = cpd->fflags;
1072 
1073 	f = NULL;			/* set default value */
1074 	err = ENOIOCTL;			/* set default value */
1075 
1076 	if (fflags & FWRITE) {
1077 		f = refs.txfifo;
1078 		err = usb_ioctl_f_sub(f, cmd, addr, td);
1079 	}
1080 	if (fflags & FREAD) {
1081 		f = refs.rxfifo;
1082 		err = usb_ioctl_f_sub(f, cmd, addr, td);
1083 	}
1084 	KASSERT(f != NULL, ("fifo not found"));
1085 	if (err != ENOIOCTL)
1086 		goto done;
1087 
1088 	err = (f->methods->f_ioctl) (f, cmd, addr, fflags);
1089 
1090 	DPRINTFN(2, "f_ioctl cmd 0x%lx = %d\n", cmd, err);
1091 
1092 	if (err != ENOIOCTL)
1093 		goto done;
1094 
1095 	if (usb_usb_ref_device(cpd, &refs)) {
1096 		err = ENXIO;
1097 		goto done;
1098 	}
1099 
1100 	err = (f->methods->f_ioctl_post) (f, cmd, addr, fflags);
1101 
1102 	DPRINTFN(2, "f_ioctl_post cmd 0x%lx = %d\n", cmd, err);
1103 
1104 	if (err == ENOIOCTL)
1105 		err = ENOTTY;
1106 
1107 	if (err)
1108 		goto done;
1109 
1110 	/* Wait for re-enumeration, if any */
1111 
1112 	while (f->udev->re_enumerate_wait != USB_RE_ENUM_DONE) {
1113 
1114 		usb_unref_device(cpd, &refs);
1115 
1116 		usb_pause_mtx(NULL, hz / 128);
1117 
1118 		while (usb_ref_device(cpd, &refs, 1 /* need uref */)) {
1119 			if (usb_ref_device(cpd, &refs, 0)) {
1120 				/* device no longer exits */
1121 				err = ENXIO;
1122 				goto done;
1123 			}
1124 			usb_unref_device(cpd, &refs);
1125 			usb_pause_mtx(NULL, hz / 128);
1126 		}
1127 	}
1128 
1129 done:
1130 	usb_unref_device(cpd, &refs);
1131 	return (err);
1132 }
1133 
1134 static void
1135 usb_filter_detach(struct knote *kn)
1136 {
1137 	struct usb_fifo *f = kn->kn_hook;
1138 	knlist_remove(&f->selinfo.si_note, kn, 0);
1139 }
1140 
1141 static int
1142 usb_filter_write(struct knote *kn, long hint)
1143 {
1144 	struct usb_cdev_privdata* cpd;
1145 	struct usb_fifo *f;
1146 	struct usb_mbuf *m;
1147 
1148 	DPRINTFN(2, "\n");
1149 
1150 	f = kn->kn_hook;
1151 
1152 	mtx_assert(f->priv_mtx, MA_OWNED);
1153 
1154 	cpd = f->curr_cpd;
1155 	if (cpd == NULL) {
1156 		m = (void *)1;
1157 	} else if (f->fs_ep_max == 0) {
1158 		if (f->flag_iserror) {
1159 			/* we got an error */
1160 			m = (void *)1;
1161 		} else {
1162 			if (f->queue_data == NULL) {
1163 				/*
1164 				 * start write transfer, if not
1165 				 * already started
1166 				 */
1167 				(f->methods->f_start_write) (f);
1168 			}
1169 			/* check if any packets are available */
1170 			USB_IF_POLL(&f->free_q, m);
1171 		}
1172 	} else {
1173 		if (f->flag_iscomplete) {
1174 			m = (void *)1;
1175 		} else {
1176 			m = NULL;
1177 		}
1178 	}
1179 	return (m ? 1 : 0);
1180 }
1181 
1182 static int
1183 usb_filter_read(struct knote *kn, long hint)
1184 {
1185 	struct usb_cdev_privdata* cpd;
1186 	struct usb_fifo *f;
1187 	struct usb_mbuf *m;
1188 
1189 	DPRINTFN(2, "\n");
1190 
1191 	f = kn->kn_hook;
1192 
1193 	mtx_assert(f->priv_mtx, MA_OWNED);
1194 
1195 	cpd = f->curr_cpd;
1196 	if (cpd == NULL) {
1197 		m = (void *)1;
1198 	} else if (f->fs_ep_max == 0) {
1199 		if (f->flag_iserror) {
1200 			/* we have an error */
1201 			m = (void *)1;
1202 		} else {
1203 			if (f->queue_data == NULL) {
1204 				/*
1205 				 * start read transfer, if not
1206 				 * already started
1207 				 */
1208 				(f->methods->f_start_read) (f);
1209 			}
1210 			/* check if any packets are available */
1211 			USB_IF_POLL(&f->used_q, m);
1212 
1213 			/* start reading data, if any */
1214 			if (m == NULL)
1215 				(f->methods->f_start_read) (f);
1216 		}
1217 	} else {
1218 		if (f->flag_iscomplete) {
1219 			m = (void *)1;
1220 		} else {
1221 			m = NULL;
1222 		}
1223 	}
1224 	return (m ? 1 : 0);
1225 }
1226 
1227 static struct filterops usb_filtops_write = {
1228 	.f_isfd = 1,
1229 	.f_detach = usb_filter_detach,
1230 	.f_event = usb_filter_write,
1231 };
1232 
1233 static struct filterops usb_filtops_read = {
1234 	.f_isfd = 1,
1235 	.f_detach = usb_filter_detach,
1236 	.f_event = usb_filter_read,
1237 };
1238 
1239 
1240 /* ARGSUSED */
1241 static int
1242 usb_kqfilter(struct cdev* dev, struct knote *kn)
1243 {
1244 	struct usb_cdev_refdata refs;
1245 	struct usb_cdev_privdata* cpd;
1246 	struct usb_fifo *f;
1247 	int fflags;
1248 	int err = EINVAL;
1249 
1250 	DPRINTFN(2, "\n");
1251 
1252 	if (devfs_get_cdevpriv((void **)&cpd) != 0 ||
1253 	    usb_ref_device(cpd, &refs, 0) != 0)
1254 		return (ENXIO);
1255 
1256 	fflags = cpd->fflags;
1257 
1258 	/* Figure out who needs service */
1259 	switch (kn->kn_filter) {
1260 	case EVFILT_WRITE:
1261 		if (fflags & FWRITE) {
1262 			f = refs.txfifo;
1263 			kn->kn_fop = &usb_filtops_write;
1264 			err = 0;
1265 		}
1266 		break;
1267 	case EVFILT_READ:
1268 		if (fflags & FREAD) {
1269 			f = refs.rxfifo;
1270 			kn->kn_fop = &usb_filtops_read;
1271 			err = 0;
1272 		}
1273 		break;
1274 	default:
1275 		err = EOPNOTSUPP;
1276 		break;
1277 	}
1278 
1279 	if (err == 0) {
1280 		kn->kn_hook = f;
1281 		mtx_lock(f->priv_mtx);
1282 		knlist_add(&f->selinfo.si_note, kn, 1);
1283 		mtx_unlock(f->priv_mtx);
1284 	}
1285 
1286 	usb_unref_device(cpd, &refs);
1287 	return (err);
1288 }
1289 
1290 /* ARGSUSED */
1291 static int
1292 usb_poll(struct cdev* dev, int events, struct thread* td)
1293 {
1294 	struct usb_cdev_refdata refs;
1295 	struct usb_cdev_privdata* cpd;
1296 	struct usb_fifo *f;
1297 	struct usb_mbuf *m;
1298 	int fflags, revents;
1299 
1300 	if (devfs_get_cdevpriv((void **)&cpd) != 0 ||
1301 	    usb_ref_device(cpd, &refs, 0) != 0)
1302 		return (events &
1303 		    (POLLHUP|POLLIN|POLLRDNORM|POLLOUT|POLLWRNORM));
1304 
1305 	fflags = cpd->fflags;
1306 
1307 	/* Figure out who needs service */
1308 	revents = 0;
1309 	if ((events & (POLLOUT | POLLWRNORM)) &&
1310 	    (fflags & FWRITE)) {
1311 
1312 		f = refs.txfifo;
1313 
1314 		mtx_lock(f->priv_mtx);
1315 
1316 		if (!refs.is_usbfs) {
1317 			if (f->flag_iserror) {
1318 				/* we got an error */
1319 				m = (void *)1;
1320 			} else {
1321 				if (f->queue_data == NULL) {
1322 					/*
1323 					 * start write transfer, if not
1324 					 * already started
1325 					 */
1326 					(f->methods->f_start_write) (f);
1327 				}
1328 				/* check if any packets are available */
1329 				USB_IF_POLL(&f->free_q, m);
1330 			}
1331 		} else {
1332 			if (f->flag_iscomplete) {
1333 				m = (void *)1;
1334 			} else {
1335 				m = NULL;
1336 			}
1337 		}
1338 
1339 		if (m) {
1340 			revents |= events & (POLLOUT | POLLWRNORM);
1341 		} else {
1342 			f->flag_isselect = 1;
1343 			selrecord(td, &f->selinfo);
1344 		}
1345 
1346 		mtx_unlock(f->priv_mtx);
1347 	}
1348 	if ((events & (POLLIN | POLLRDNORM)) &&
1349 	    (fflags & FREAD)) {
1350 
1351 		f = refs.rxfifo;
1352 
1353 		mtx_lock(f->priv_mtx);
1354 
1355 		if (!refs.is_usbfs) {
1356 			if (f->flag_iserror) {
1357 				/* we have an error */
1358 				m = (void *)1;
1359 			} else {
1360 				if (f->queue_data == NULL) {
1361 					/*
1362 					 * start read transfer, if not
1363 					 * already started
1364 					 */
1365 					(f->methods->f_start_read) (f);
1366 				}
1367 				/* check if any packets are available */
1368 				USB_IF_POLL(&f->used_q, m);
1369 			}
1370 		} else {
1371 			if (f->flag_iscomplete) {
1372 				m = (void *)1;
1373 			} else {
1374 				m = NULL;
1375 			}
1376 		}
1377 
1378 		if (m) {
1379 			revents |= events & (POLLIN | POLLRDNORM);
1380 		} else {
1381 			f->flag_isselect = 1;
1382 			selrecord(td, &f->selinfo);
1383 
1384 			if (!refs.is_usbfs) {
1385 				/* start reading data */
1386 				(f->methods->f_start_read) (f);
1387 			}
1388 		}
1389 
1390 		mtx_unlock(f->priv_mtx);
1391 	}
1392 	usb_unref_device(cpd, &refs);
1393 	return (revents);
1394 }
1395 
1396 static int
1397 usb_read(struct cdev *dev, struct uio *uio, int ioflag)
1398 {
1399 	struct usb_cdev_refdata refs;
1400 	struct usb_cdev_privdata* cpd;
1401 	struct usb_fifo *f;
1402 	struct usb_mbuf *m;
1403 	int fflags;
1404 	int resid;
1405 	int io_len;
1406 	int err;
1407 	uint8_t tr_data = 0;
1408 
1409 	err = devfs_get_cdevpriv((void **)&cpd);
1410 	if (err != 0)
1411 		return (err);
1412 
1413 	err = usb_ref_device(cpd, &refs, 0 /* no uref */ );
1414 	if (err) {
1415 		return (ENXIO);
1416 	}
1417 	fflags = cpd->fflags;
1418 
1419 	f = refs.rxfifo;
1420 	if (f == NULL) {
1421 		/* should not happen */
1422 		usb_unref_device(cpd, &refs);
1423 		return (EPERM);
1424 	}
1425 
1426 	resid = uio->uio_resid;
1427 
1428 	mtx_lock(f->priv_mtx);
1429 
1430 	/* check for permanent read error */
1431 	if (f->flag_iserror) {
1432 		err = EIO;
1433 		goto done;
1434 	}
1435 	/* check if USB-FS interface is active */
1436 	if (refs.is_usbfs) {
1437 		/*
1438 		 * The queue is used for events that should be
1439 		 * retrieved using the "USB_FS_COMPLETE" ioctl.
1440 		 */
1441 		err = EINVAL;
1442 		goto done;
1443 	}
1444 	while (uio->uio_resid > 0) {
1445 
1446 		USB_IF_DEQUEUE(&f->used_q, m);
1447 
1448 		if (m == NULL) {
1449 
1450 			/* start read transfer, if not already started */
1451 
1452 			(f->methods->f_start_read) (f);
1453 
1454 			if (ioflag & IO_NDELAY) {
1455 				if (tr_data) {
1456 					/* return length before error */
1457 					break;
1458 				}
1459 				err = EWOULDBLOCK;
1460 				break;
1461 			}
1462 			DPRINTF("sleeping\n");
1463 
1464 			err = usb_fifo_wait(f);
1465 			if (err) {
1466 				break;
1467 			}
1468 			continue;
1469 		}
1470 		if (f->methods->f_filter_read) {
1471 			/*
1472 			 * Sometimes it is convenient to process data at the
1473 			 * expense of a userland process instead of a kernel
1474 			 * process.
1475 			 */
1476 			(f->methods->f_filter_read) (f, m);
1477 		}
1478 		tr_data = 1;
1479 
1480 		io_len = MIN(m->cur_data_len, uio->uio_resid);
1481 
1482 		DPRINTFN(2, "transfer %d bytes from %p\n",
1483 		    io_len, m->cur_data_ptr);
1484 
1485 		err = usb_fifo_uiomove(f,
1486 		    m->cur_data_ptr, io_len, uio);
1487 
1488 		m->cur_data_len -= io_len;
1489 		m->cur_data_ptr += io_len;
1490 
1491 		if (m->cur_data_len == 0) {
1492 
1493 			uint8_t last_packet;
1494 
1495 			last_packet = m->last_packet;
1496 
1497 			USB_IF_ENQUEUE(&f->free_q, m);
1498 
1499 			if (last_packet) {
1500 				/* keep framing */
1501 				break;
1502 			}
1503 		} else {
1504 			USB_IF_PREPEND(&f->used_q, m);
1505 		}
1506 
1507 		if (err) {
1508 			break;
1509 		}
1510 	}
1511 done:
1512 	mtx_unlock(f->priv_mtx);
1513 
1514 	usb_unref_device(cpd, &refs);
1515 
1516 	return (err);
1517 }
1518 
1519 static int
1520 usb_write(struct cdev *dev, struct uio *uio, int ioflag)
1521 {
1522 	struct usb_cdev_refdata refs;
1523 	struct usb_cdev_privdata* cpd;
1524 	struct usb_fifo *f;
1525 	struct usb_mbuf *m;
1526 	uint8_t *pdata;
1527 	int fflags;
1528 	int resid;
1529 	int io_len;
1530 	int err;
1531 	uint8_t tr_data = 0;
1532 
1533 	DPRINTFN(2, "\n");
1534 
1535 	err = devfs_get_cdevpriv((void **)&cpd);
1536 	if (err != 0)
1537 		return (err);
1538 
1539 	err = usb_ref_device(cpd, &refs, 0 /* no uref */ );
1540 	if (err) {
1541 		return (ENXIO);
1542 	}
1543 	fflags = cpd->fflags;
1544 
1545 	f = refs.txfifo;
1546 	if (f == NULL) {
1547 		/* should not happen */
1548 		usb_unref_device(cpd, &refs);
1549 		return (EPERM);
1550 	}
1551 	resid = uio->uio_resid;
1552 
1553 	mtx_lock(f->priv_mtx);
1554 
1555 	/* check for permanent write error */
1556 	if (f->flag_iserror) {
1557 		err = EIO;
1558 		goto done;
1559 	}
1560 	/* check if USB-FS interface is active */
1561 	if (refs.is_usbfs) {
1562 		/*
1563 		 * The queue is used for events that should be
1564 		 * retrieved using the "USB_FS_COMPLETE" ioctl.
1565 		 */
1566 		err = EINVAL;
1567 		goto done;
1568 	}
1569 	if (f->queue_data == NULL) {
1570 		/* start write transfer, if not already started */
1571 		(f->methods->f_start_write) (f);
1572 	}
1573 	/* we allow writing zero length data */
1574 	do {
1575 		USB_IF_DEQUEUE(&f->free_q, m);
1576 
1577 		if (m == NULL) {
1578 
1579 			if (ioflag & IO_NDELAY) {
1580 				if (tr_data) {
1581 					/* return length before error */
1582 					break;
1583 				}
1584 				err = EWOULDBLOCK;
1585 				break;
1586 			}
1587 			DPRINTF("sleeping\n");
1588 
1589 			err = usb_fifo_wait(f);
1590 			if (err) {
1591 				break;
1592 			}
1593 			continue;
1594 		}
1595 		tr_data = 1;
1596 
1597 		if (f->flag_have_fragment == 0) {
1598 			USB_MBUF_RESET(m);
1599 			io_len = m->cur_data_len;
1600 			pdata = m->cur_data_ptr;
1601 			if (io_len > uio->uio_resid)
1602 				io_len = uio->uio_resid;
1603 			m->cur_data_len = io_len;
1604 		} else {
1605 			io_len = m->max_data_len - m->cur_data_len;
1606 			pdata = m->cur_data_ptr + m->cur_data_len;
1607 			if (io_len > uio->uio_resid)
1608 				io_len = uio->uio_resid;
1609 			m->cur_data_len += io_len;
1610 		}
1611 
1612 		DPRINTFN(2, "transfer %d bytes to %p\n",
1613 		    io_len, pdata);
1614 
1615 		err = usb_fifo_uiomove(f, pdata, io_len, uio);
1616 
1617 		if (err) {
1618 			f->flag_have_fragment = 0;
1619 			USB_IF_ENQUEUE(&f->free_q, m);
1620 			break;
1621 		}
1622 
1623 		/* check if the buffer is ready to be transmitted */
1624 
1625 		if ((f->flag_write_defrag == 0) ||
1626 		    (m->cur_data_len == m->max_data_len)) {
1627 			f->flag_have_fragment = 0;
1628 
1629 			/*
1630 			 * Check for write filter:
1631 			 *
1632 			 * Sometimes it is convenient to process data
1633 			 * at the expense of a userland process
1634 			 * instead of a kernel process.
1635 			 */
1636 			if (f->methods->f_filter_write) {
1637 				(f->methods->f_filter_write) (f, m);
1638 			}
1639 
1640 			/* Put USB mbuf in the used queue */
1641 			USB_IF_ENQUEUE(&f->used_q, m);
1642 
1643 			/* Start writing data, if not already started */
1644 			(f->methods->f_start_write) (f);
1645 		} else {
1646 			/* Wait for more data or close */
1647 			f->flag_have_fragment = 1;
1648 			USB_IF_PREPEND(&f->free_q, m);
1649 		}
1650 
1651 	} while (uio->uio_resid > 0);
1652 done:
1653 	mtx_unlock(f->priv_mtx);
1654 
1655 	usb_unref_device(cpd, &refs);
1656 
1657 	return (err);
1658 }
1659 
1660 int
1661 usb_static_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
1662     struct thread *td)
1663 {
1664 	union {
1665 		struct usb_read_dir *urd;
1666 		void* data;
1667 	} u;
1668 	int err;
1669 
1670 	u.data = data;
1671 	switch (cmd) {
1672 		case USB_READ_DIR:
1673 			err = usb_read_symlink(u.urd->urd_data,
1674 			    u.urd->urd_startentry, u.urd->urd_maxlen);
1675 			break;
1676 		case USB_DEV_QUIRK_GET:
1677 		case USB_QUIRK_NAME_GET:
1678 		case USB_DEV_QUIRK_ADD:
1679 		case USB_DEV_QUIRK_REMOVE:
1680 			err = usb_quirk_ioctl_p(cmd, data, fflag, td);
1681 			break;
1682 		case USB_GET_TEMPLATE:
1683 			*(int *)data = usb_template;
1684 			err = 0;
1685 			break;
1686 		case USB_SET_TEMPLATE:
1687 			err = priv_check(curthread, PRIV_DRIVER);
1688 			if (err)
1689 				break;
1690 			usb_template = *(int *)data;
1691 			break;
1692 		default:
1693 			err = ENOTTY;
1694 			break;
1695 	}
1696 	return (err);
1697 }
1698 
1699 static int
1700 usb_fifo_uiomove(struct usb_fifo *f, void *cp,
1701     int n, struct uio *uio)
1702 {
1703 	int error;
1704 
1705 	mtx_unlock(f->priv_mtx);
1706 
1707 	/*
1708 	 * "uiomove()" can sleep so one needs to make a wrapper,
1709 	 * exiting the mutex and checking things:
1710 	 */
1711 	error = uiomove(cp, n, uio);
1712 
1713 	mtx_lock(f->priv_mtx);
1714 
1715 	return (error);
1716 }
1717 
1718 int
1719 usb_fifo_wait(struct usb_fifo *f)
1720 {
1721 	int err;
1722 
1723 	mtx_assert(f->priv_mtx, MA_OWNED);
1724 
1725 	if (f->flag_iserror) {
1726 		/* we are gone */
1727 		return (EIO);
1728 	}
1729 	f->flag_sleeping = 1;
1730 
1731 	err = cv_wait_sig(&f->cv_io, f->priv_mtx);
1732 
1733 	if (f->flag_iserror) {
1734 		/* we are gone */
1735 		err = EIO;
1736 	}
1737 	return (err);
1738 }
1739 
1740 void
1741 usb_fifo_signal(struct usb_fifo *f)
1742 {
1743 	if (f->flag_sleeping) {
1744 		f->flag_sleeping = 0;
1745 		cv_broadcast(&f->cv_io);
1746 	}
1747 }
1748 
1749 void
1750 usb_fifo_wakeup(struct usb_fifo *f)
1751 {
1752 	usb_fifo_signal(f);
1753 
1754 	KNOTE_LOCKED(&f->selinfo.si_note, 0);
1755 
1756 	if (f->flag_isselect) {
1757 		selwakeup(&f->selinfo);
1758 		f->flag_isselect = 0;
1759 	}
1760 	if (f->async_p != NULL) {
1761 		PROC_LOCK(f->async_p);
1762 		kern_psignal(f->async_p, SIGIO);
1763 		PROC_UNLOCK(f->async_p);
1764 	}
1765 }
1766 
1767 static int
1768 usb_fifo_dummy_open(struct usb_fifo *fifo, int fflags)
1769 {
1770 	return (0);
1771 }
1772 
1773 static void
1774 usb_fifo_dummy_close(struct usb_fifo *fifo, int fflags)
1775 {
1776 	return;
1777 }
1778 
1779 static int
1780 usb_fifo_dummy_ioctl(struct usb_fifo *fifo, u_long cmd, void *addr, int fflags)
1781 {
1782 	return (ENOIOCTL);
1783 }
1784 
1785 static void
1786 usb_fifo_dummy_cmd(struct usb_fifo *fifo)
1787 {
1788 	fifo->flag_flushing = 0;	/* not flushing */
1789 }
1790 
1791 static void
1792 usb_fifo_check_methods(struct usb_fifo_methods *pm)
1793 {
1794 	/* check that all callback functions are OK */
1795 
1796 	if (pm->f_open == NULL)
1797 		pm->f_open = &usb_fifo_dummy_open;
1798 
1799 	if (pm->f_close == NULL)
1800 		pm->f_close = &usb_fifo_dummy_close;
1801 
1802 	if (pm->f_ioctl == NULL)
1803 		pm->f_ioctl = &usb_fifo_dummy_ioctl;
1804 
1805 	if (pm->f_ioctl_post == NULL)
1806 		pm->f_ioctl_post = &usb_fifo_dummy_ioctl;
1807 
1808 	if (pm->f_start_read == NULL)
1809 		pm->f_start_read = &usb_fifo_dummy_cmd;
1810 
1811 	if (pm->f_stop_read == NULL)
1812 		pm->f_stop_read = &usb_fifo_dummy_cmd;
1813 
1814 	if (pm->f_start_write == NULL)
1815 		pm->f_start_write = &usb_fifo_dummy_cmd;
1816 
1817 	if (pm->f_stop_write == NULL)
1818 		pm->f_stop_write = &usb_fifo_dummy_cmd;
1819 }
1820 
1821 /*------------------------------------------------------------------------*
1822  *	usb_fifo_attach
1823  *
1824  * The following function will create a duplex FIFO.
1825  *
1826  * Return values:
1827  * 0: Success.
1828  * Else: Failure.
1829  *------------------------------------------------------------------------*/
1830 int
1831 usb_fifo_attach(struct usb_device *udev, void *priv_sc,
1832     struct mtx *priv_mtx, struct usb_fifo_methods *pm,
1833     struct usb_fifo_sc *f_sc, uint16_t unit, int16_t subunit,
1834     uint8_t iface_index, uid_t uid, gid_t gid, int mode)
1835 {
1836 	struct usb_fifo *f_tx;
1837 	struct usb_fifo *f_rx;
1838 	char devname[32];
1839 	uint8_t n;
1840 
1841 	f_sc->fp[USB_FIFO_TX] = NULL;
1842 	f_sc->fp[USB_FIFO_RX] = NULL;
1843 
1844 	if (pm == NULL)
1845 		return (EINVAL);
1846 
1847 	/* check the methods */
1848 	usb_fifo_check_methods(pm);
1849 
1850 	if (priv_mtx == NULL)
1851 		priv_mtx = &Giant;
1852 
1853 	/* search for a free FIFO slot */
1854 	for (n = 0;; n += 2) {
1855 
1856 		if (n == USB_FIFO_MAX) {
1857 			/* end of FIFOs reached */
1858 			return (ENOMEM);
1859 		}
1860 		/* Check for TX FIFO */
1861 		if (udev->fifo[n + USB_FIFO_TX] != NULL) {
1862 			continue;
1863 		}
1864 		/* Check for RX FIFO */
1865 		if (udev->fifo[n + USB_FIFO_RX] != NULL) {
1866 			continue;
1867 		}
1868 		break;
1869 	}
1870 
1871 	f_tx = usb_fifo_alloc(priv_mtx);
1872 	f_rx = usb_fifo_alloc(priv_mtx);
1873 
1874 	if ((f_tx == NULL) || (f_rx == NULL)) {
1875 		usb_fifo_free(f_tx);
1876 		usb_fifo_free(f_rx);
1877 		return (ENOMEM);
1878 	}
1879 	/* initialise FIFO structures */
1880 
1881 	f_tx->fifo_index = n + USB_FIFO_TX;
1882 	f_tx->dev_ep_index = -1;
1883 	f_tx->priv_sc0 = priv_sc;
1884 	f_tx->methods = pm;
1885 	f_tx->iface_index = iface_index;
1886 	f_tx->udev = udev;
1887 
1888 	f_rx->fifo_index = n + USB_FIFO_RX;
1889 	f_rx->dev_ep_index = -1;
1890 	f_rx->priv_sc0 = priv_sc;
1891 	f_rx->methods = pm;
1892 	f_rx->iface_index = iface_index;
1893 	f_rx->udev = udev;
1894 
1895 	f_sc->fp[USB_FIFO_TX] = f_tx;
1896 	f_sc->fp[USB_FIFO_RX] = f_rx;
1897 
1898 	mtx_lock(&usb_ref_lock);
1899 	udev->fifo[f_tx->fifo_index] = f_tx;
1900 	udev->fifo[f_rx->fifo_index] = f_rx;
1901 	mtx_unlock(&usb_ref_lock);
1902 
1903 	for (n = 0; n != 4; n++) {
1904 
1905 		if (pm->basename[n] == NULL) {
1906 			continue;
1907 		}
1908 		if (subunit < 0) {
1909 			if (snprintf(devname, sizeof(devname),
1910 			    "%s%u%s", pm->basename[n],
1911 			    unit, pm->postfix[n] ?
1912 			    pm->postfix[n] : "")) {
1913 				/* ignore */
1914 			}
1915 		} else {
1916 			if (snprintf(devname, sizeof(devname),
1917 			    "%s%u.%d%s", pm->basename[n],
1918 			    unit, subunit, pm->postfix[n] ?
1919 			    pm->postfix[n] : "")) {
1920 				/* ignore */
1921 			}
1922 		}
1923 
1924 		/*
1925 		 * Distribute the symbolic links into two FIFO structures:
1926 		 */
1927 		if (n & 1) {
1928 			f_rx->symlink[n / 2] =
1929 			    usb_alloc_symlink(devname);
1930 		} else {
1931 			f_tx->symlink[n / 2] =
1932 			    usb_alloc_symlink(devname);
1933 		}
1934 
1935 		/* Create the device */
1936 		f_sc->dev = usb_make_dev(udev, devname, -1,
1937 		    f_tx->fifo_index & f_rx->fifo_index,
1938 		    FREAD|FWRITE, uid, gid, mode);
1939 	}
1940 
1941 	DPRINTFN(2, "attached %p/%p\n", f_tx, f_rx);
1942 	return (0);
1943 }
1944 
1945 /*------------------------------------------------------------------------*
1946  *	usb_fifo_alloc_buffer
1947  *
1948  * Return values:
1949  * 0: Success
1950  * Else failure
1951  *------------------------------------------------------------------------*/
1952 int
1953 usb_fifo_alloc_buffer(struct usb_fifo *f, usb_size_t bufsize,
1954     uint16_t nbuf)
1955 {
1956 	usb_fifo_free_buffer(f);
1957 
1958 	/* allocate an endpoint */
1959 	f->free_q.ifq_maxlen = nbuf;
1960 	f->used_q.ifq_maxlen = nbuf;
1961 
1962 	f->queue_data = usb_alloc_mbufs(
1963 	    M_USBDEV, &f->free_q, bufsize, nbuf);
1964 
1965 	if ((f->queue_data == NULL) && bufsize && nbuf) {
1966 		return (ENOMEM);
1967 	}
1968 	return (0);			/* success */
1969 }
1970 
1971 /*------------------------------------------------------------------------*
1972  *	usb_fifo_free_buffer
1973  *
1974  * This function will free the buffers associated with a FIFO. This
1975  * function can be called multiple times in a row.
1976  *------------------------------------------------------------------------*/
1977 void
1978 usb_fifo_free_buffer(struct usb_fifo *f)
1979 {
1980 	if (f->queue_data) {
1981 		/* free old buffer */
1982 		free(f->queue_data, M_USBDEV);
1983 		f->queue_data = NULL;
1984 	}
1985 	/* reset queues */
1986 
1987 	memset(&f->free_q, 0, sizeof(f->free_q));
1988 	memset(&f->used_q, 0, sizeof(f->used_q));
1989 }
1990 
1991 void
1992 usb_fifo_detach(struct usb_fifo_sc *f_sc)
1993 {
1994 	if (f_sc == NULL) {
1995 		return;
1996 	}
1997 	usb_fifo_free(f_sc->fp[USB_FIFO_TX]);
1998 	usb_fifo_free(f_sc->fp[USB_FIFO_RX]);
1999 
2000 	f_sc->fp[USB_FIFO_TX] = NULL;
2001 	f_sc->fp[USB_FIFO_RX] = NULL;
2002 
2003 	usb_destroy_dev(f_sc->dev);
2004 
2005 	f_sc->dev = NULL;
2006 
2007 	DPRINTFN(2, "detached %p\n", f_sc);
2008 }
2009 
2010 usb_size_t
2011 usb_fifo_put_bytes_max(struct usb_fifo *f)
2012 {
2013 	struct usb_mbuf *m;
2014 	usb_size_t len;
2015 
2016 	USB_IF_POLL(&f->free_q, m);
2017 
2018 	if (m) {
2019 		len = m->max_data_len;
2020 	} else {
2021 		len = 0;
2022 	}
2023 	return (len);
2024 }
2025 
2026 /*------------------------------------------------------------------------*
2027  *	usb_fifo_put_data
2028  *
2029  * what:
2030  *  0 - normal operation
2031  *  1 - set last packet flag to enforce framing
2032  *------------------------------------------------------------------------*/
2033 void
2034 usb_fifo_put_data(struct usb_fifo *f, struct usb_page_cache *pc,
2035     usb_frlength_t offset, usb_frlength_t len, uint8_t what)
2036 {
2037 	struct usb_mbuf *m;
2038 	usb_frlength_t io_len;
2039 
2040 	while (len || (what == 1)) {
2041 
2042 		USB_IF_DEQUEUE(&f->free_q, m);
2043 
2044 		if (m) {
2045 			USB_MBUF_RESET(m);
2046 
2047 			io_len = MIN(len, m->cur_data_len);
2048 
2049 			usbd_copy_out(pc, offset, m->cur_data_ptr, io_len);
2050 
2051 			m->cur_data_len = io_len;
2052 			offset += io_len;
2053 			len -= io_len;
2054 
2055 			if ((len == 0) && (what == 1)) {
2056 				m->last_packet = 1;
2057 			}
2058 			USB_IF_ENQUEUE(&f->used_q, m);
2059 
2060 			usb_fifo_wakeup(f);
2061 
2062 			if ((len == 0) || (what == 1)) {
2063 				break;
2064 			}
2065 		} else {
2066 			break;
2067 		}
2068 	}
2069 }
2070 
2071 void
2072 usb_fifo_put_data_linear(struct usb_fifo *f, void *ptr,
2073     usb_size_t len, uint8_t what)
2074 {
2075 	struct usb_mbuf *m;
2076 	usb_size_t io_len;
2077 
2078 	while (len || (what == 1)) {
2079 
2080 		USB_IF_DEQUEUE(&f->free_q, m);
2081 
2082 		if (m) {
2083 			USB_MBUF_RESET(m);
2084 
2085 			io_len = MIN(len, m->cur_data_len);
2086 
2087 			memcpy(m->cur_data_ptr, ptr, io_len);
2088 
2089 			m->cur_data_len = io_len;
2090 			ptr = USB_ADD_BYTES(ptr, io_len);
2091 			len -= io_len;
2092 
2093 			if ((len == 0) && (what == 1)) {
2094 				m->last_packet = 1;
2095 			}
2096 			USB_IF_ENQUEUE(&f->used_q, m);
2097 
2098 			usb_fifo_wakeup(f);
2099 
2100 			if ((len == 0) || (what == 1)) {
2101 				break;
2102 			}
2103 		} else {
2104 			break;
2105 		}
2106 	}
2107 }
2108 
2109 uint8_t
2110 usb_fifo_put_data_buffer(struct usb_fifo *f, void *ptr, usb_size_t len)
2111 {
2112 	struct usb_mbuf *m;
2113 
2114 	USB_IF_DEQUEUE(&f->free_q, m);
2115 
2116 	if (m) {
2117 		m->cur_data_len = len;
2118 		m->cur_data_ptr = ptr;
2119 		USB_IF_ENQUEUE(&f->used_q, m);
2120 		usb_fifo_wakeup(f);
2121 		return (1);
2122 	}
2123 	return (0);
2124 }
2125 
2126 void
2127 usb_fifo_put_data_error(struct usb_fifo *f)
2128 {
2129 	f->flag_iserror = 1;
2130 	usb_fifo_wakeup(f);
2131 }
2132 
2133 /*------------------------------------------------------------------------*
2134  *	usb_fifo_get_data
2135  *
2136  * what:
2137  *  0 - normal operation
2138  *  1 - only get one "usb_mbuf"
2139  *
2140  * returns:
2141  *  0 - no more data
2142  *  1 - data in buffer
2143  *------------------------------------------------------------------------*/
2144 uint8_t
2145 usb_fifo_get_data(struct usb_fifo *f, struct usb_page_cache *pc,
2146     usb_frlength_t offset, usb_frlength_t len, usb_frlength_t *actlen,
2147     uint8_t what)
2148 {
2149 	struct usb_mbuf *m;
2150 	usb_frlength_t io_len;
2151 	uint8_t tr_data = 0;
2152 
2153 	actlen[0] = 0;
2154 
2155 	while (1) {
2156 
2157 		USB_IF_DEQUEUE(&f->used_q, m);
2158 
2159 		if (m) {
2160 
2161 			tr_data = 1;
2162 
2163 			io_len = MIN(len, m->cur_data_len);
2164 
2165 			usbd_copy_in(pc, offset, m->cur_data_ptr, io_len);
2166 
2167 			len -= io_len;
2168 			offset += io_len;
2169 			actlen[0] += io_len;
2170 			m->cur_data_ptr += io_len;
2171 			m->cur_data_len -= io_len;
2172 
2173 			if ((m->cur_data_len == 0) || (what == 1)) {
2174 				USB_IF_ENQUEUE(&f->free_q, m);
2175 
2176 				usb_fifo_wakeup(f);
2177 
2178 				if (what == 1) {
2179 					break;
2180 				}
2181 			} else {
2182 				USB_IF_PREPEND(&f->used_q, m);
2183 			}
2184 		} else {
2185 
2186 			if (tr_data) {
2187 				/* wait for data to be written out */
2188 				break;
2189 			}
2190 			if (f->flag_flushing) {
2191 				/* check if we should send a short packet */
2192 				if (f->flag_short != 0) {
2193 					f->flag_short = 0;
2194 					tr_data = 1;
2195 					break;
2196 				}
2197 				/* flushing complete */
2198 				f->flag_flushing = 0;
2199 				usb_fifo_wakeup(f);
2200 			}
2201 			break;
2202 		}
2203 		if (len == 0) {
2204 			break;
2205 		}
2206 	}
2207 	return (tr_data);
2208 }
2209 
2210 uint8_t
2211 usb_fifo_get_data_linear(struct usb_fifo *f, void *ptr,
2212     usb_size_t len, usb_size_t *actlen, uint8_t what)
2213 {
2214 	struct usb_mbuf *m;
2215 	usb_size_t io_len;
2216 	uint8_t tr_data = 0;
2217 
2218 	actlen[0] = 0;
2219 
2220 	while (1) {
2221 
2222 		USB_IF_DEQUEUE(&f->used_q, m);
2223 
2224 		if (m) {
2225 
2226 			tr_data = 1;
2227 
2228 			io_len = MIN(len, m->cur_data_len);
2229 
2230 			memcpy(ptr, m->cur_data_ptr, io_len);
2231 
2232 			len -= io_len;
2233 			ptr = USB_ADD_BYTES(ptr, io_len);
2234 			actlen[0] += io_len;
2235 			m->cur_data_ptr += io_len;
2236 			m->cur_data_len -= io_len;
2237 
2238 			if ((m->cur_data_len == 0) || (what == 1)) {
2239 				USB_IF_ENQUEUE(&f->free_q, m);
2240 
2241 				usb_fifo_wakeup(f);
2242 
2243 				if (what == 1) {
2244 					break;
2245 				}
2246 			} else {
2247 				USB_IF_PREPEND(&f->used_q, m);
2248 			}
2249 		} else {
2250 
2251 			if (tr_data) {
2252 				/* wait for data to be written out */
2253 				break;
2254 			}
2255 			if (f->flag_flushing) {
2256 				/* check if we should send a short packet */
2257 				if (f->flag_short != 0) {
2258 					f->flag_short = 0;
2259 					tr_data = 1;
2260 					break;
2261 				}
2262 				/* flushing complete */
2263 				f->flag_flushing = 0;
2264 				usb_fifo_wakeup(f);
2265 			}
2266 			break;
2267 		}
2268 		if (len == 0) {
2269 			break;
2270 		}
2271 	}
2272 	return (tr_data);
2273 }
2274 
2275 uint8_t
2276 usb_fifo_get_data_buffer(struct usb_fifo *f, void **pptr, usb_size_t *plen)
2277 {
2278 	struct usb_mbuf *m;
2279 
2280 	USB_IF_POLL(&f->used_q, m);
2281 
2282 	if (m) {
2283 		*plen = m->cur_data_len;
2284 		*pptr = m->cur_data_ptr;
2285 
2286 		return (1);
2287 	}
2288 	return (0);
2289 }
2290 
2291 void
2292 usb_fifo_get_data_error(struct usb_fifo *f)
2293 {
2294 	f->flag_iserror = 1;
2295 	usb_fifo_wakeup(f);
2296 }
2297 
2298 /*------------------------------------------------------------------------*
2299  *	usb_alloc_symlink
2300  *
2301  * Return values:
2302  * NULL: Failure
2303  * Else: Pointer to symlink entry
2304  *------------------------------------------------------------------------*/
2305 struct usb_symlink *
2306 usb_alloc_symlink(const char *target)
2307 {
2308 	struct usb_symlink *ps;
2309 
2310 	ps = malloc(sizeof(*ps), M_USBDEV, M_WAITOK);
2311 	if (ps == NULL) {
2312 		return (ps);
2313 	}
2314 	/* XXX no longer needed */
2315 	strlcpy(ps->src_path, target, sizeof(ps->src_path));
2316 	ps->src_len = strlen(ps->src_path);
2317 	strlcpy(ps->dst_path, target, sizeof(ps->dst_path));
2318 	ps->dst_len = strlen(ps->dst_path);
2319 
2320 	sx_xlock(&usb_sym_lock);
2321 	TAILQ_INSERT_TAIL(&usb_sym_head, ps, sym_entry);
2322 	sx_unlock(&usb_sym_lock);
2323 	return (ps);
2324 }
2325 
2326 /*------------------------------------------------------------------------*
2327  *	usb_free_symlink
2328  *------------------------------------------------------------------------*/
2329 void
2330 usb_free_symlink(struct usb_symlink *ps)
2331 {
2332 	if (ps == NULL) {
2333 		return;
2334 	}
2335 	sx_xlock(&usb_sym_lock);
2336 	TAILQ_REMOVE(&usb_sym_head, ps, sym_entry);
2337 	sx_unlock(&usb_sym_lock);
2338 
2339 	free(ps, M_USBDEV);
2340 }
2341 
2342 /*------------------------------------------------------------------------*
2343  *	usb_read_symlink
2344  *
2345  * Return value:
2346  * 0: Success
2347  * Else: Failure
2348  *------------------------------------------------------------------------*/
2349 int
2350 usb_read_symlink(uint8_t *user_ptr, uint32_t startentry, uint32_t user_len)
2351 {
2352 	struct usb_symlink *ps;
2353 	uint32_t temp;
2354 	uint32_t delta = 0;
2355 	uint8_t len;
2356 	int error = 0;
2357 
2358 	sx_xlock(&usb_sym_lock);
2359 
2360 	TAILQ_FOREACH(ps, &usb_sym_head, sym_entry) {
2361 
2362 		/*
2363 		 * Compute total length of source and destination symlink
2364 		 * strings pluss one length byte and two NUL bytes:
2365 		 */
2366 		temp = ps->src_len + ps->dst_len + 3;
2367 
2368 		if (temp > 255) {
2369 			/*
2370 			 * Skip entry because this length cannot fit
2371 			 * into one byte:
2372 			 */
2373 			continue;
2374 		}
2375 		if (startentry != 0) {
2376 			/* decrement read offset */
2377 			startentry--;
2378 			continue;
2379 		}
2380 		if (temp > user_len) {
2381 			/* out of buffer space */
2382 			break;
2383 		}
2384 		len = temp;
2385 
2386 		/* copy out total length */
2387 
2388 		error = copyout(&len,
2389 		    USB_ADD_BYTES(user_ptr, delta), 1);
2390 		if (error) {
2391 			break;
2392 		}
2393 		delta += 1;
2394 
2395 		/* copy out source string */
2396 
2397 		error = copyout(ps->src_path,
2398 		    USB_ADD_BYTES(user_ptr, delta), ps->src_len);
2399 		if (error) {
2400 			break;
2401 		}
2402 		len = 0;
2403 		delta += ps->src_len;
2404 		error = copyout(&len,
2405 		    USB_ADD_BYTES(user_ptr, delta), 1);
2406 		if (error) {
2407 			break;
2408 		}
2409 		delta += 1;
2410 
2411 		/* copy out destination string */
2412 
2413 		error = copyout(ps->dst_path,
2414 		    USB_ADD_BYTES(user_ptr, delta), ps->dst_len);
2415 		if (error) {
2416 			break;
2417 		}
2418 		len = 0;
2419 		delta += ps->dst_len;
2420 		error = copyout(&len,
2421 		    USB_ADD_BYTES(user_ptr, delta), 1);
2422 		if (error) {
2423 			break;
2424 		}
2425 		delta += 1;
2426 
2427 		user_len -= temp;
2428 	}
2429 
2430 	/* a zero length entry indicates the end */
2431 
2432 	if ((user_len != 0) && (error == 0)) {
2433 
2434 		len = 0;
2435 
2436 		error = copyout(&len,
2437 		    USB_ADD_BYTES(user_ptr, delta), 1);
2438 	}
2439 	sx_unlock(&usb_sym_lock);
2440 	return (error);
2441 }
2442 
2443 void
2444 usb_fifo_set_close_zlp(struct usb_fifo *f, uint8_t onoff)
2445 {
2446 	if (f == NULL)
2447 		return;
2448 
2449 	/* send a Zero Length Packet, ZLP, before close */
2450 	f->flag_short = onoff;
2451 }
2452 
2453 void
2454 usb_fifo_set_write_defrag(struct usb_fifo *f, uint8_t onoff)
2455 {
2456 	if (f == NULL)
2457 		return;
2458 
2459 	/* defrag written data */
2460 	f->flag_write_defrag = onoff;
2461 	/* reset defrag state */
2462 	f->flag_have_fragment = 0;
2463 }
2464 
2465 void *
2466 usb_fifo_softc(struct usb_fifo *f)
2467 {
2468 	return (f->priv_sc0);
2469 }
2470 #endif	/* USB_HAVE_UGEN */
2471