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