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