xref: /dragonfly/sys/bus/u4b/usb_dev.c (revision 33311965)
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_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_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, NULL, usb_filter_detach, usb_filter_read };
1147 
1148 static struct filterops usb_filtops_write =
1149     { FILTEROP_ISFD, 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)f;
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 = (struct usb_fifo *)kn->kn_hook;
1215 	struct usb_cdev_privdata* cpd = f->curr_cpd;
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 	lockmgr(f->priv_lock, LK_EXCLUSIVE);
1234 	if(f->flag_isselect) {
1235 		klist = &f->selinfo.ki_note;
1236 		knote_remove(klist, kn);
1237 		f->flag_isselect = 0;
1238 	}
1239 	lockmgr(f->priv_lock, LK_RELEASE);
1240 
1241 	usb_unref_device(cpd, &refs);
1242 }
1243 
1244 static int
1245 usb_filter_read(struct knote *kn, long hint)
1246 {
1247 	struct usb_fifo *f = (struct usb_fifo *)kn->kn_hook;
1248 	struct usb_cdev_privdata* cpd = f->curr_cpd;
1249 	struct usb_cdev_refdata refs;
1250 	struct usb_mbuf *m;
1251 	int err,locked,ready = 0;
1252 
1253 	DPRINTF("\n");
1254 	/*
1255 	 * The associated file has been closed.
1256 	 */
1257 	if(cpd == NULL) {
1258 		kn->kn_flags |= EV_ERROR;
1259 		return (ready);
1260 	}
1261 
1262 	err = usb_ref_device(cpd, &refs, 0 /* no uref */ );
1263 	if (err) {
1264 		kn->kn_flags |= EV_ERROR;
1265 		return (ready);
1266 	}
1267 	/* XXX mpf
1268 	   For some reason this function is called both
1269 	   with the priv_lock held and with the priv_lock
1270 	   not held. We need to find out from where and
1271 	   why */
1272 	locked = lockowned(f->priv_lock);
1273 	if(!locked)
1274 		lockmgr(f->priv_lock, LK_EXCLUSIVE);
1275 
1276 	if (!refs.is_usbfs) {
1277 		if (f->flag_iserror) {
1278 			/* we got an error */
1279 			kn->kn_flags |= EV_ERROR;
1280 			ready = 1;
1281 		} else {
1282 			/* start read if not running */
1283 			(f->methods->f_start_read)(f);
1284 			/* check if any packets are available */
1285 			USB_IF_POLL(&f->used_q, m);
1286 			if (m) {
1287 				ready = 1;
1288 			}
1289 		}
1290 	} else {
1291 		if (f->flag_iscomplete) {
1292 			ready = 1;
1293 		} else {
1294 			ready = 0;
1295 		}
1296 	}
1297 
1298 	if(!locked)
1299 		lockmgr(f->priv_lock, LK_RELEASE);
1300 
1301 	usb_unref_device(cpd, &refs);
1302 
1303 	DPRINTFN(3,"ready %d\n", ready);
1304 	return(ready);
1305 }
1306 
1307 static int
1308 usb_filter_write(struct knote *kn, long hint)
1309 {
1310 	DPRINTF("\n");
1311 
1312 	/*
1313 	   XXX mpf
1314 	   write is always ok
1315 	   This seems to work just fine. Not sure whether we
1316            need the whole kerfuffle done in usb_poll.
1317            It also does not work, probably since if there
1318 	   wasn't a write transfer queued before, why
1319 	   should it have completed.
1320 	 */
1321 	return 1;
1322 #if XXXDF
1323 	struct usb_fifo *f = (struct usb_fifo *)kn->kn_hook;
1324 	struct usb_cdev_privdata* cpd = f->curr_cpd;
1325 	struct usb_cdev_refdata refs;
1326 	struct usb_mbuf *m;
1327 	int locked, err,ready = 0;
1328 
1329 	DPRINTF("\n");
1330 
1331 	/*
1332 	 * The associated file has been closed.
1333 	 */
1334 	if(cpd == NULL) {
1335 		kn->kn_flags |= EV_ERROR;
1336 		return (ready);
1337 	}
1338 
1339 	err = usb_ref_device(cpd, &refs, 0 /* no uref */ );
1340 	if (err) {
1341 		kn->kn_flags |= EV_ERROR;
1342 		return (0);
1343 	}
1344 
1345 	locked = lockowned(f->priv_lock);
1346 	if(!locked)
1347 		lockmgr(f->priv_lock, LK_EXCLUSIVE);
1348 
1349 	if (!refs.is_usbfs) {
1350 		if (f->flag_iserror) {
1351 			/* we got an error */
1352 			kn->kn_flags |= EV_ERROR;
1353 			ready = 1;
1354 		} else {
1355 			if (f->queue_data == NULL) {
1356 				/*
1357 				 * start write transfer, if not
1358 				 * already started
1359 				 */
1360 				(f->methods->f_start_write) (f);
1361 			}
1362 			/* check if any packets are available */
1363 			USB_IF_POLL(&f->free_q, m);
1364 			if(m) {
1365 				ready = 1;
1366 			}
1367 		}
1368 	} else {
1369 		if (f->flag_iscomplete) {
1370 			ready = 1;
1371 		} else {
1372 			ready = 0;
1373 		}
1374 	}
1375 
1376 	if(!locked)
1377 		lockmgr(f->priv_lock, LK_RELEASE);
1378 
1379 	usb_unref_device(cpd, &refs);
1380 	return(ready);
1381 #endif
1382 }
1383 
1384 #if 0
1385 /* This is implemented above using kqfilter */
1386 /* ARGSUSED */
1387 static int
1388 usb_poll(struct cdev* dev, int events, struct thread* td)
1389 {
1390 	struct usb_cdev_refdata refs;
1391 	struct usb_cdev_privdata* cpd;
1392 	struct usb_fifo *f;
1393 	struct usb_mbuf *m;
1394 	int fflags, revents;
1395 
1396 	if (devfs_get_cdevpriv((void **)&cpd) != 0 ||
1397 	    usb_ref_device(cpd, &refs, 0) != 0)
1398 		return (events &
1399 		    (POLLHUP|POLLIN|POLLRDNORM|POLLOUT|POLLWRNORM));
1400 
1401 	fflags = cpd->fflags;
1402 
1403 	/* Figure out who needs service */
1404 	revents = 0;
1405 	if ((events & (POLLOUT | POLLWRNORM)) &&
1406 	    (fflags & FWRITE)) {
1407 
1408 		f = refs.txfifo;
1409 
1410 		lockmgr(f->priv_lock, LK_EXCLUSIVE);
1411 
1412 		if (!refs.is_usbfs) {
1413 			if (f->flag_iserror) {
1414 				/* we got an error */
1415 				m = (void *)1;
1416 			} else {
1417 				if (f->queue_data == NULL) {
1418 					/*
1419 					 * start write transfer, if not
1420 					 * already started
1421 					 */
1422 					(f->methods->f_start_write) (f);
1423 				}
1424 				/* check if any packets are available */
1425 				USB_IF_POLL(&f->free_q, m);
1426 			}
1427 		} else {
1428 			if (f->flag_iscomplete) {
1429 				m = (void *)1;
1430 			} else {
1431 				m = NULL;
1432 			}
1433 		}
1434 
1435 		if (m) {
1436 			revents |= events & (POLLOUT | POLLWRNORM);
1437 		} else {
1438 			f->flag_isselect = 1;
1439 			selrecord(td, &f->selinfo);
1440 		}
1441 
1442 		lockmgr(f->priv_lock);
1443 	}
1444 	if ((events & (POLLIN | POLLRDNORM)) &&
1445 	    (fflags & FREAD)) {
1446 
1447 		f = refs.rxfifo;
1448 
1449 		lockmgr(f->priv_lock, LK_EXCLUSIVE);
1450 
1451 		if (!refs.is_usbfs) {
1452 			if (f->flag_iserror) {
1453 				/* we have and error */
1454 				m = (void *)1;
1455 			} else {
1456 				if (f->queue_data == NULL) {
1457 					/*
1458 					 * start read transfer, if not
1459 					 * already started
1460 					 */
1461 					(f->methods->f_start_read) (f);
1462 				}
1463 				/* check if any packets are available */
1464 				USB_IF_POLL(&f->used_q, m);
1465 			}
1466 		} else {
1467 			if (f->flag_iscomplete) {
1468 				m = (void *)1;
1469 			} else {
1470 				m = NULL;
1471 			}
1472 		}
1473 
1474 		if (m) {
1475 			revents |= events & (POLLIN | POLLRDNORM);
1476 		} else {
1477 			f->flag_isselect = 1;
1478 			selrecord(td, &f->selinfo);
1479 
1480 			if (!refs.is_usbfs) {
1481 				/* start reading data */
1482 				(f->methods->f_start_read) (f);
1483 			}
1484 		}
1485 
1486 		lockmgr(f->priv_lock, LK_RELEASE);
1487 	}
1488 	usb_unref_device(cpd, &refs);
1489 	return (revents);
1490 }
1491 #endif
1492 
1493 static int
1494 usb_read(struct dev_read_args *ap)
1495 {
1496 	struct uio *uio = ap->a_uio;
1497 	int ioflag = ap->a_ioflag;
1498 	struct usb_cdev_refdata refs;
1499 	struct usb_cdev_privdata* cpd;
1500 	struct usb_fifo *f;
1501 	struct usb_mbuf *m;
1502 	int fflags;
1503 	int resid;
1504 	int io_len;
1505 	int err;
1506 	uint8_t tr_data = 0;
1507 
1508 	err = devfs_get_cdevpriv(ap->a_fp, (void **)&cpd);
1509 	if (err != 0)
1510 		return (err);
1511 	err = usb_ref_device(cpd, &refs, 0 /* no uref */ );
1512 	if (err) {
1513 		return (ENXIO);
1514 	}
1515 	fflags = cpd->fflags;
1516 
1517 	f = refs.rxfifo;
1518 	if (f == NULL) {
1519 		/* should not happen */
1520 		usb_unref_device(cpd, &refs);
1521 		return (EPERM);
1522 	}
1523 
1524 	resid = uio->uio_resid;
1525 
1526 	lockmgr(f->priv_lock, LK_EXCLUSIVE);
1527 
1528 	/* check for permanent read error */
1529 	if (f->flag_iserror) {
1530 		err = EIO;
1531 		goto done;
1532 	}
1533 	/* check if USB-FS interface is active */
1534 	if (refs.is_usbfs) {
1535 		/*
1536 		 * The queue is used for events that should be
1537 		 * retrieved using the "USB_FS_COMPLETE" ioctl.
1538 		 */
1539 		err = EINVAL;
1540 		goto done;
1541 	}
1542 	while (uio->uio_resid > 0) {
1543 
1544 		USB_IF_DEQUEUE(&f->used_q, m);
1545 
1546 		if (m == NULL) {
1547 
1548 			/* start read transfer, if not already started */
1549 
1550 			(f->methods->f_start_read) (f);
1551 
1552 			if (ioflag & IO_NDELAY) {
1553 				if (tr_data) {
1554 					/* return length before error */
1555 					break;
1556 				}
1557 				err = EWOULDBLOCK;
1558 				break;
1559 			}
1560 			DPRINTF("sleeping\n");
1561 
1562 			err = usb_fifo_wait(f);
1563 			if (err) {
1564 				break;
1565 			}
1566 			continue;
1567 		}
1568 		if (f->methods->f_filter_read) {
1569 			/*
1570 			 * Sometimes it is convenient to process data at the
1571 			 * expense of a userland process instead of a kernel
1572 			 * process.
1573 			 */
1574 			(f->methods->f_filter_read) (f, m);
1575 		}
1576 		tr_data = 1;
1577 
1578 		io_len = MIN(m->cur_data_len, uio->uio_resid);
1579 
1580 		DPRINTFN(2, "transfer %d bytes from %p\n",
1581 		    io_len, m->cur_data_ptr);
1582 
1583 		err = usb_fifo_uiomove(f,
1584 		    m->cur_data_ptr, io_len, uio);
1585 
1586 		m->cur_data_len -= io_len;
1587 		m->cur_data_ptr += io_len;
1588 
1589 		if (m->cur_data_len == 0) {
1590 
1591 			uint8_t last_packet;
1592 
1593 			last_packet = m->last_packet;
1594 
1595 			USB_IF_ENQUEUE(&f->free_q, m);
1596 
1597 			if (last_packet) {
1598 				/* keep framing */
1599 				break;
1600 			}
1601 		} else {
1602 			USB_IF_PREPEND(&f->used_q, m);
1603 			usb_fifo_wakeup(f);
1604 		}
1605 
1606 		if (err) {
1607 			break;
1608 		}
1609 	}
1610 done:
1611 	lockmgr(f->priv_lock, LK_RELEASE);
1612 
1613 	usb_unref_device(cpd, &refs);
1614 
1615 	return (err);
1616 }
1617 
1618 static int
1619 usb_write(struct dev_write_args *ap)
1620 {
1621 	struct uio *uio = ap->a_uio;
1622 	int ioflag = ap->a_ioflag;
1623 	struct usb_cdev_refdata refs;
1624 	struct usb_cdev_privdata* cpd;
1625 	struct usb_fifo *f;
1626 	struct usb_mbuf *m;
1627 	uint8_t *pdata;
1628 	int fflags;
1629 	int resid;
1630 	int io_len;
1631 	int err;
1632 	uint8_t tr_data = 0;
1633 
1634 	DPRINTFN(2, "\n");
1635 
1636 	err = devfs_get_cdevpriv(ap->a_fp, (void **)&cpd);
1637 	if (err != 0)
1638 		return (err);
1639 	err = usb_ref_device(cpd, &refs, 0 /* no uref */ );
1640 	if (err) {
1641 		return (ENXIO);
1642 	}
1643 	fflags = cpd->fflags;
1644 
1645 	f = refs.txfifo;
1646 	if (f == NULL) {
1647 		/* should not happen */
1648 		usb_unref_device(cpd, &refs);
1649 		return (EPERM);
1650 	}
1651 	resid = uio->uio_resid;
1652 
1653 	lockmgr(f->priv_lock, LK_EXCLUSIVE);
1654 
1655 	/* check for permanent write error */
1656 	if (f->flag_iserror) {
1657 		err = EIO;
1658 		goto done;
1659 	}
1660 	/* check if USB-FS interface is active */
1661 	if (refs.is_usbfs) {
1662 		/*
1663 		 * The queue is used for events that should be
1664 		 * retrieved using the "USB_FS_COMPLETE" ioctl.
1665 		 */
1666 		err = EINVAL;
1667 		goto done;
1668 	}
1669 	if (f->queue_data == NULL) {
1670 		/* start write transfer, if not already started */
1671 		(f->methods->f_start_write) (f);
1672 	}
1673 	/* we allow writing zero length data */
1674 	do {
1675 		USB_IF_DEQUEUE(&f->free_q, m);
1676 
1677 		if (m == NULL) {
1678 
1679 			if (ioflag & IO_NDELAY) {
1680 				if (tr_data) {
1681 					/* return length before error */
1682 					break;
1683 				}
1684 				err = EWOULDBLOCK;
1685 				break;
1686 			}
1687 			DPRINTF("sleeping\n");
1688 
1689 			err = usb_fifo_wait(f);
1690 			if (err) {
1691 				break;
1692 			}
1693 			continue;
1694 		}
1695 		tr_data = 1;
1696 
1697 		if (f->flag_have_fragment == 0) {
1698 			USB_MBUF_RESET(m);
1699 			io_len = m->cur_data_len;
1700 			pdata = m->cur_data_ptr;
1701 			if (io_len > uio->uio_resid)
1702 				io_len = uio->uio_resid;
1703 			m->cur_data_len = io_len;
1704 		} else {
1705 			io_len = m->max_data_len - m->cur_data_len;
1706 			pdata = m->cur_data_ptr + m->cur_data_len;
1707 			if (io_len > uio->uio_resid)
1708 				io_len = uio->uio_resid;
1709 			m->cur_data_len += io_len;
1710 		}
1711 
1712 		DPRINTFN(2, "transfer %d bytes to %p\n",
1713 		    io_len, pdata);
1714 
1715 		err = usb_fifo_uiomove(f, pdata, io_len, uio);
1716 
1717 		if (err) {
1718 			f->flag_have_fragment = 0;
1719 			USB_IF_ENQUEUE(&f->free_q, m);
1720 			break;
1721 		}
1722 
1723 		/* check if the buffer is ready to be transmitted */
1724 
1725 		if ((f->flag_write_defrag == 0) ||
1726 		    (m->cur_data_len == m->max_data_len)) {
1727 			f->flag_have_fragment = 0;
1728 
1729 			/*
1730 			 * Check for write filter:
1731 			 *
1732 			 * Sometimes it is convenient to process data
1733 			 * at the expense of a userland process
1734 			 * instead of a kernel process.
1735 			 */
1736 			if (f->methods->f_filter_write) {
1737 				(f->methods->f_filter_write) (f, m);
1738 			}
1739 
1740 			/* Put USB mbuf in the used queue */
1741 			USB_IF_ENQUEUE(&f->used_q, m);
1742 
1743 			/* Start writing data, if not already started */
1744 			(f->methods->f_start_write) (f);
1745 		} else {
1746 			/* Wait for more data or close */
1747 			f->flag_have_fragment = 1;
1748 			USB_IF_PREPEND(&f->free_q, m);
1749 		}
1750 
1751 	} while (uio->uio_resid > 0);
1752 done:
1753 	lockmgr(f->priv_lock, LK_RELEASE);
1754 
1755 	usb_unref_device(cpd, &refs);
1756 
1757 	return (err);
1758 }
1759 
1760 int
1761 usb_static_open(struct dev_open_args *ap)
1762 {
1763 	return 0;
1764 }
1765 
1766 int
1767 usb_static_close(struct dev_close_args *ap)
1768 {
1769 	return 0;
1770 }
1771 
1772 int
1773 usb_static_ioctl(struct dev_ioctl_args *ap)
1774 {
1775 	u_long cmd = ap->a_cmd;
1776 	caddr_t data = ap->a_data;
1777 	struct thread *td = curthread; /* XXX: curthread the correct choice? */
1778 	int fflag = ap->a_fflag;
1779 	union {
1780 		struct usb_read_dir *urd;
1781 		void* data;
1782 	} u;
1783 	int err;
1784 
1785 	u.data = data;
1786 	switch (cmd) {
1787 		case USB_READ_DIR:
1788 			err = usb_read_symlink(u.urd->urd_data,
1789 			    u.urd->urd_startentry, u.urd->urd_maxlen);
1790 			break;
1791 		case USB_DEV_QUIRK_GET:
1792 		case USB_QUIRK_NAME_GET:
1793 		case USB_DEV_QUIRK_ADD:
1794 		case USB_DEV_QUIRK_REMOVE:
1795 			err = usb_quirk_ioctl_p(cmd, data, fflag, td);
1796 			break;
1797 		case USB_GET_TEMPLATE:
1798 			*(int *)data = usb_template;
1799 			err = 0;
1800 			break;
1801 		case USB_SET_TEMPLATE:
1802 			err = priv_check(curthread, PRIV_DRIVER);
1803 			if (err)
1804 				break;
1805 			usb_template = *(int *)data;
1806 			break;
1807 		default:
1808 			err = ENOTTY;
1809 			break;
1810 	}
1811 	return (err);
1812 }
1813 
1814 static int
1815 usb_fifo_uiomove(struct usb_fifo *f, void *cp,
1816     int n, struct uio *uio)
1817 {
1818 	int error;
1819 
1820 	lockmgr(f->priv_lock, LK_RELEASE);
1821 
1822 	/*
1823 	 * "uiomove()" can sleep so one needs to make a wrapper,
1824 	 * exiting the mutex and checking things:
1825 	 */
1826 	error = uiomove(cp, n, uio);
1827 
1828 	lockmgr(f->priv_lock, LK_EXCLUSIVE);
1829 
1830 	return (error);
1831 }
1832 
1833 int
1834 usb_fifo_wait(struct usb_fifo *f)
1835 {
1836 	int err;
1837 
1838 	KKASSERT(lockowned(f->priv_lock));
1839 
1840 	if (f->flag_iserror) {
1841 		/* we are gone */
1842 		return (EIO);
1843 	}
1844 	f->flag_sleeping = 1;
1845 
1846 	err = cv_wait_sig(&f->cv_io, f->priv_lock);
1847 
1848 	if (f->flag_iserror) {
1849 		/* we are gone */
1850 		err = EIO;
1851 	}
1852 	return (err);
1853 }
1854 
1855 void
1856 usb_fifo_signal(struct usb_fifo *f)
1857 {
1858 	if (f->flag_sleeping) {
1859 		f->flag_sleeping = 0;
1860 		cv_broadcast(&f->cv_io);
1861 	}
1862 }
1863 
1864 void
1865 usb_fifo_wakeup(struct usb_fifo *f)
1866 {
1867 	usb_fifo_signal(f);
1868 
1869 	if (f->flag_isselect) {
1870 		KNOTE(&f->selinfo.ki_note, 0);
1871 		wakeup(&f->selinfo.ki_note);
1872 	}
1873 	if (f->async_p != NULL && lwkt_trytoken(&f->async_p->p_token)) {
1874 		ksignal(f->async_p, SIGIO);
1875 		lwkt_reltoken(&f->async_p->p_token);
1876 	}
1877 }
1878 
1879 static int
1880 usb_fifo_dummy_open(struct usb_fifo *fifo, int fflags)
1881 {
1882 	return (0);
1883 }
1884 
1885 static void
1886 usb_fifo_dummy_close(struct usb_fifo *fifo, int fflags)
1887 {
1888 	return;
1889 }
1890 
1891 static int
1892 usb_fifo_dummy_ioctl(struct usb_fifo *fifo, u_long cmd, void *addr, int fflags)
1893 {
1894 	return (ENOIOCTL);
1895 }
1896 
1897 static void
1898 usb_fifo_dummy_cmd(struct usb_fifo *fifo)
1899 {
1900 	fifo->flag_flushing = 0;	/* not flushing */
1901 }
1902 
1903 static void
1904 usb_fifo_check_methods(struct usb_fifo_methods *pm)
1905 {
1906 	/* check that all callback functions are OK */
1907 
1908 	if (pm->f_open == NULL)
1909 		pm->f_open = &usb_fifo_dummy_open;
1910 
1911 	if (pm->f_close == NULL)
1912 		pm->f_close = &usb_fifo_dummy_close;
1913 
1914 	if (pm->f_ioctl == NULL)
1915 		pm->f_ioctl = &usb_fifo_dummy_ioctl;
1916 
1917 	if (pm->f_ioctl_post == NULL)
1918 		pm->f_ioctl_post = &usb_fifo_dummy_ioctl;
1919 
1920 	if (pm->f_start_read == NULL)
1921 		pm->f_start_read = &usb_fifo_dummy_cmd;
1922 
1923 	if (pm->f_stop_read == NULL)
1924 		pm->f_stop_read = &usb_fifo_dummy_cmd;
1925 
1926 	if (pm->f_start_write == NULL)
1927 		pm->f_start_write = &usb_fifo_dummy_cmd;
1928 
1929 	if (pm->f_stop_write == NULL)
1930 		pm->f_stop_write = &usb_fifo_dummy_cmd;
1931 }
1932 
1933 /*------------------------------------------------------------------------*
1934  *	usb_fifo_attach
1935  *
1936  * The following function will create a duplex FIFO.
1937  *
1938  * Return values:
1939  * 0: Success.
1940  * Else: Failure.
1941  *------------------------------------------------------------------------*/
1942 int
1943 usb_fifo_attach(struct usb_device *udev, void *priv_sc,
1944     struct lock *priv_lock, struct usb_fifo_methods *pm,
1945     struct usb_fifo_sc *f_sc, uint16_t unit, int16_t subunit,
1946     uint8_t iface_index, uid_t uid, gid_t gid, int mode)
1947 {
1948 	struct usb_fifo *f_tx;
1949 	struct usb_fifo *f_rx;
1950 	char devname[32];
1951 	uint8_t n;
1952 
1953 	f_sc->fp[USB_FIFO_TX] = NULL;
1954 	f_sc->fp[USB_FIFO_RX] = NULL;
1955 
1956 	if (pm == NULL)
1957 		return (EINVAL);
1958 
1959 	/* check the methods */
1960 	usb_fifo_check_methods(pm);
1961 
1962 	if (priv_lock == NULL) {
1963 		DPRINTF("null priv_lock set\n");
1964 	}
1965 
1966 	/* search for a free FIFO slot */
1967 	for (n = 0;; n += 2) {
1968 
1969 		if (n == USB_FIFO_MAX) {
1970 			/* end of FIFOs reached */
1971 			return (ENOMEM);
1972 		}
1973 		/* Check for TX FIFO */
1974 		if (udev->fifo[n + USB_FIFO_TX] != NULL) {
1975 			continue;
1976 		}
1977 		/* Check for RX FIFO */
1978 		if (udev->fifo[n + USB_FIFO_RX] != NULL) {
1979 			continue;
1980 		}
1981 		break;
1982 	}
1983 
1984 	f_tx = usb_fifo_alloc();
1985 	f_rx = usb_fifo_alloc();
1986 
1987 	if ((f_tx == NULL) || (f_rx == NULL)) {
1988 		usb_fifo_free(f_tx);
1989 		usb_fifo_free(f_rx);
1990 		return (ENOMEM);
1991 	}
1992 	/* initialise FIFO structures */
1993 
1994 	f_tx->fifo_index = n + USB_FIFO_TX;
1995 	f_tx->dev_ep_index = -1;
1996 	f_tx->priv_lock = priv_lock;
1997 	f_tx->priv_sc0 = priv_sc;
1998 	f_tx->methods = pm;
1999 	f_tx->iface_index = iface_index;
2000 	f_tx->udev = udev;
2001 
2002 	f_rx->fifo_index = n + USB_FIFO_RX;
2003 	f_rx->dev_ep_index = -1;
2004 	f_rx->priv_lock = priv_lock;
2005 	f_rx->priv_sc0 = priv_sc;
2006 	f_rx->methods = pm;
2007 	f_rx->iface_index = iface_index;
2008 	f_rx->udev = udev;
2009 
2010 	f_sc->fp[USB_FIFO_TX] = f_tx;
2011 	f_sc->fp[USB_FIFO_RX] = f_rx;
2012 
2013 	lockmgr(&usb_ref_lock, LK_EXCLUSIVE);
2014 	udev->fifo[f_tx->fifo_index] = f_tx;
2015 	udev->fifo[f_rx->fifo_index] = f_rx;
2016 	lockmgr(&usb_ref_lock, LK_RELEASE);
2017 
2018 	for (n = 0; n != 4; n++) {
2019 
2020 		if (pm->basename[n] == NULL) {
2021 			continue;
2022 		}
2023 		if (subunit < 0) {
2024 			if (ksnprintf(devname, sizeof(devname),
2025 			    "%s%u%s", pm->basename[n],
2026 			    unit, pm->postfix[n] ?
2027 			    pm->postfix[n] : "")) {
2028 				/* ignore */
2029 			}
2030 		} else {
2031 			if (ksnprintf(devname, sizeof(devname),
2032 			    "%s%u.%u%s", pm->basename[n],
2033 			    unit, subunit, pm->postfix[n] ?
2034 			    pm->postfix[n] : "")) {
2035 				/* ignore */
2036 			}
2037 		}
2038 
2039 		/*
2040 		 * Distribute the symbolic links into two FIFO structures:
2041 		 */
2042 		if (n & 1) {
2043 			f_rx->symlink[n / 2] =
2044 			    usb_alloc_symlink(devname);
2045 		} else {
2046 			f_tx->symlink[n / 2] =
2047 			    usb_alloc_symlink(devname);
2048 		}
2049 
2050 		/* Create the device */
2051 		f_sc->dev = usb_make_dev(udev, devname, -1,
2052 		    f_tx->fifo_index & f_rx->fifo_index,
2053 		    FREAD|FWRITE, uid, gid, mode);
2054 	}
2055 
2056 	DPRINTFN(2, "attached %p/%p\n", f_tx, f_rx);
2057 	return (0);
2058 }
2059 
2060 /*------------------------------------------------------------------------*
2061  *	usb_fifo_alloc_buffer
2062  *
2063  * Return values:
2064  * 0: Success
2065  * Else failure
2066  *------------------------------------------------------------------------*/
2067 int
2068 usb_fifo_alloc_buffer(struct usb_fifo *f, usb_size_t bufsize,
2069     uint16_t nbuf)
2070 {
2071 	usb_fifo_free_buffer(f);
2072 
2073 	/* allocate an endpoint */
2074 	f->free_q.ifq_maxlen = nbuf;
2075 	f->used_q.ifq_maxlen = nbuf;
2076 
2077 	f->queue_data = usb_alloc_mbufs(
2078 	    M_USBDEV, &f->free_q, bufsize, nbuf);
2079 
2080 	if ((f->queue_data == NULL) && bufsize && nbuf) {
2081 		return (ENOMEM);
2082 	}
2083 	return (0);			/* success */
2084 }
2085 
2086 /*------------------------------------------------------------------------*
2087  *	usb_fifo_free_buffer
2088  *
2089  * This function will free the buffers associated with a FIFO. This
2090  * function can be called multiple times in a row.
2091  *------------------------------------------------------------------------*/
2092 void
2093 usb_fifo_free_buffer(struct usb_fifo *f)
2094 {
2095 	if (f->queue_data) {
2096 		/* free old buffer */
2097 		kfree(f->queue_data, M_USBDEV);
2098 		f->queue_data = NULL;
2099 	}
2100 	/* reset queues */
2101 
2102 	memset(&f->free_q, 0, sizeof(f->free_q));
2103 	memset(&f->used_q, 0, sizeof(f->used_q));
2104 }
2105 
2106 void
2107 usb_fifo_detach(struct usb_fifo_sc *f_sc)
2108 {
2109 	if (f_sc == NULL) {
2110 		return;
2111 	}
2112 	usb_fifo_free(f_sc->fp[USB_FIFO_TX]);
2113 	usb_fifo_free(f_sc->fp[USB_FIFO_RX]);
2114 
2115 	f_sc->fp[USB_FIFO_TX] = NULL;
2116 	f_sc->fp[USB_FIFO_RX] = NULL;
2117 
2118 	usb_destroy_dev(f_sc->dev);
2119 
2120 	f_sc->dev = NULL;
2121 
2122 	DPRINTFN(2, "detached %p\n", f_sc);
2123 }
2124 
2125 usb_size_t
2126 usb_fifo_put_bytes_max(struct usb_fifo *f)
2127 {
2128 	struct usb_mbuf *m;
2129 	usb_size_t len;
2130 
2131 	USB_IF_POLL(&f->free_q, m);
2132 
2133 	if (m) {
2134 		len = m->max_data_len;
2135 	} else {
2136 		len = 0;
2137 	}
2138 	return (len);
2139 }
2140 
2141 /*------------------------------------------------------------------------*
2142  *	usb_fifo_put_data
2143  *
2144  * what:
2145  *  0 - normal operation
2146  *  1 - set last packet flag to enforce framing
2147  *------------------------------------------------------------------------*/
2148 void
2149 usb_fifo_put_data(struct usb_fifo *f, struct usb_page_cache *pc,
2150     usb_frlength_t offset, usb_frlength_t len, uint8_t what)
2151 {
2152 	struct usb_mbuf *m;
2153 	usb_frlength_t io_len;
2154 
2155 	while (len || (what == 1)) {
2156 
2157 		USB_IF_DEQUEUE(&f->free_q, m);
2158 
2159 		if (m) {
2160 			USB_MBUF_RESET(m);
2161 
2162 			io_len = MIN(len, m->cur_data_len);
2163 
2164 			usbd_copy_out(pc, offset, m->cur_data_ptr, io_len);
2165 
2166 			m->cur_data_len = io_len;
2167 			offset += io_len;
2168 			len -= io_len;
2169 
2170 			if ((len == 0) && (what == 1)) {
2171 				m->last_packet = 1;
2172 			}
2173 			USB_IF_ENQUEUE(&f->used_q, m);
2174 			usb_fifo_wakeup(f);
2175 
2176 			if ((len == 0) || (what == 1)) {
2177 				break;
2178 			}
2179 		} else {
2180 			break;
2181 		}
2182 	}
2183 }
2184 
2185 void
2186 usb_fifo_put_data_linear(struct usb_fifo *f, void *ptr,
2187     usb_size_t len, uint8_t what)
2188 {
2189 	struct usb_mbuf *m;
2190 	usb_size_t io_len;
2191 
2192 	while (len || (what == 1)) {
2193 
2194 		USB_IF_DEQUEUE(&f->free_q, m);
2195 
2196 		if (m) {
2197 			USB_MBUF_RESET(m);
2198 
2199 			io_len = MIN(len, m->cur_data_len);
2200 
2201 			memcpy(m->cur_data_ptr, ptr, io_len);
2202 
2203 			m->cur_data_len = io_len;
2204 			ptr = USB_ADD_BYTES(ptr, io_len);
2205 			len -= io_len;
2206 
2207 			if ((len == 0) && (what == 1)) {
2208 				m->last_packet = 1;
2209 			}
2210 			USB_IF_ENQUEUE(&f->used_q, m);
2211 			usb_fifo_wakeup(f);
2212 
2213 			if ((len == 0) || (what == 1)) {
2214 				break;
2215 			}
2216 		} else {
2217 			break;
2218 		}
2219 	}
2220 }
2221 
2222 uint8_t
2223 usb_fifo_put_data_buffer(struct usb_fifo *f, void *ptr, usb_size_t len)
2224 {
2225 	struct usb_mbuf *m;
2226 
2227 	USB_IF_DEQUEUE(&f->free_q, m);
2228 
2229 	if (m) {
2230 		m->cur_data_len = len;
2231 		m->cur_data_ptr = ptr;
2232 		USB_IF_ENQUEUE(&f->used_q, m);
2233 		usb_fifo_wakeup(f);
2234 		return (1);
2235 	}
2236 	return (0);
2237 }
2238 
2239 void
2240 usb_fifo_put_data_error(struct usb_fifo *f)
2241 {
2242 	f->flag_iserror = 1;
2243 	usb_fifo_wakeup(f);
2244 }
2245 
2246 /*------------------------------------------------------------------------*
2247  *	usb_fifo_get_data
2248  *
2249  * what:
2250  *  0 - normal operation
2251  *  1 - only get one "usb_mbuf"
2252  *
2253  * returns:
2254  *  0 - no more data
2255  *  1 - data in buffer
2256  *------------------------------------------------------------------------*/
2257 uint8_t
2258 usb_fifo_get_data(struct usb_fifo *f, struct usb_page_cache *pc,
2259     usb_frlength_t offset, usb_frlength_t len, usb_frlength_t *actlen,
2260     uint8_t what)
2261 {
2262 	struct usb_mbuf *m;
2263 	usb_frlength_t io_len;
2264 	uint8_t tr_data = 0;
2265 
2266 	actlen[0] = 0;
2267 
2268 	while (1) {
2269 
2270 		USB_IF_DEQUEUE(&f->used_q, m);
2271 
2272 		if (m) {
2273 
2274 			tr_data = 1;
2275 
2276 			io_len = MIN(len, m->cur_data_len);
2277 
2278 			usbd_copy_in(pc, offset, m->cur_data_ptr, io_len);
2279 
2280 			len -= io_len;
2281 			offset += io_len;
2282 			actlen[0] += io_len;
2283 			m->cur_data_ptr += io_len;
2284 			m->cur_data_len -= io_len;
2285 
2286 			if ((m->cur_data_len == 0) || (what == 1)) {
2287 				USB_IF_ENQUEUE(&f->free_q, m);
2288 
2289 				usb_fifo_wakeup(f);
2290 
2291 				if (what == 1) {
2292 					break;
2293 				}
2294 			} else {
2295 				USB_IF_PREPEND(&f->used_q, m);
2296 				usb_fifo_wakeup(f);
2297 			}
2298 		} else {
2299 
2300 			if (tr_data) {
2301 				/* wait for data to be written out */
2302 				break;
2303 			}
2304 			if (f->flag_flushing) {
2305 				/* check if we should send a short packet */
2306 				if (f->flag_short != 0) {
2307 					f->flag_short = 0;
2308 					tr_data = 1;
2309 					break;
2310 				}
2311 				/* flushing complete */
2312 				f->flag_flushing = 0;
2313 				usb_fifo_wakeup(f);
2314 			}
2315 			break;
2316 		}
2317 		if (len == 0) {
2318 			break;
2319 		}
2320 	}
2321 	return (tr_data);
2322 }
2323 
2324 uint8_t
2325 usb_fifo_get_data_linear(struct usb_fifo *f, void *ptr,
2326     usb_size_t len, usb_size_t *actlen, uint8_t what)
2327 {
2328 	struct usb_mbuf *m;
2329 	usb_size_t io_len;
2330 	uint8_t tr_data = 0;
2331 
2332 	actlen[0] = 0;
2333 
2334 	while (1) {
2335 
2336 		USB_IF_DEQUEUE(&f->used_q, m);
2337 
2338 		if (m) {
2339 
2340 			tr_data = 1;
2341 
2342 			io_len = MIN(len, m->cur_data_len);
2343 
2344 			memcpy(ptr, m->cur_data_ptr, io_len);
2345 
2346 			len -= io_len;
2347 			ptr = USB_ADD_BYTES(ptr, io_len);
2348 			actlen[0] += io_len;
2349 			m->cur_data_ptr += io_len;
2350 			m->cur_data_len -= io_len;
2351 
2352 			if ((m->cur_data_len == 0) || (what == 1)) {
2353 				USB_IF_ENQUEUE(&f->free_q, m);
2354 
2355 				usb_fifo_wakeup(f);
2356 
2357 				if (what == 1) {
2358 					break;
2359 				}
2360 			} else {
2361 				USB_IF_PREPEND(&f->used_q, m);
2362 				usb_fifo_wakeup(f);
2363 			}
2364 		} else {
2365 
2366 			if (tr_data) {
2367 				/* wait for data to be written out */
2368 				break;
2369 			}
2370 			if (f->flag_flushing) {
2371 				/* check if we should send a short packet */
2372 				if (f->flag_short != 0) {
2373 					f->flag_short = 0;
2374 					tr_data = 1;
2375 					break;
2376 				}
2377 				/* flushing complete */
2378 				f->flag_flushing = 0;
2379 				usb_fifo_wakeup(f);
2380 			}
2381 			break;
2382 		}
2383 		if (len == 0) {
2384 			break;
2385 		}
2386 	}
2387 	return (tr_data);
2388 }
2389 
2390 uint8_t
2391 usb_fifo_get_data_buffer(struct usb_fifo *f, void **pptr, usb_size_t *plen)
2392 {
2393 	struct usb_mbuf *m;
2394 
2395 	USB_IF_POLL(&f->used_q, m);
2396 
2397 	if (m) {
2398 		*plen = m->cur_data_len;
2399 		*pptr = m->cur_data_ptr;
2400 
2401 		return (1);
2402 	}
2403 	return (0);
2404 }
2405 
2406 void
2407 usb_fifo_get_data_error(struct usb_fifo *f)
2408 {
2409 	f->flag_iserror = 1;
2410 	usb_fifo_wakeup(f);
2411 }
2412 
2413 /*------------------------------------------------------------------------*
2414  *	usb_alloc_symlink
2415  *
2416  * Return values:
2417  * NULL: Failure
2418  * Else: Pointer to symlink entry
2419  *------------------------------------------------------------------------*/
2420 struct usb_symlink *
2421 usb_alloc_symlink(const char *target)
2422 {
2423 	struct usb_symlink *ps;
2424 
2425 	ps = kmalloc(sizeof(*ps), M_USBDEV, M_WAITOK);
2426 	if (ps == NULL) {
2427 		return (ps);
2428 	}
2429 	/* XXX no longer needed */
2430 	strlcpy(ps->src_path, target, sizeof(ps->src_path));
2431 	ps->src_len = strlen(ps->src_path);
2432 	strlcpy(ps->dst_path, target, sizeof(ps->dst_path));
2433 	ps->dst_len = strlen(ps->dst_path);
2434 
2435 	lockmgr(&usb_sym_lock, LK_EXCLUSIVE);
2436 	TAILQ_INSERT_TAIL(&usb_sym_head, ps, sym_entry);
2437 	lockmgr(&usb_sym_lock, LK_RELEASE);
2438 	return (ps);
2439 }
2440 
2441 /*------------------------------------------------------------------------*
2442  *	usb_free_symlink
2443  *------------------------------------------------------------------------*/
2444 void
2445 usb_free_symlink(struct usb_symlink *ps)
2446 {
2447 	if (ps == NULL) {
2448 		return;
2449 	}
2450 	lockmgr(&usb_sym_lock, LK_EXCLUSIVE);
2451 	TAILQ_REMOVE(&usb_sym_head, ps, sym_entry);
2452 	lockmgr(&usb_sym_lock, LK_RELEASE);
2453 
2454 	kfree(ps, M_USBDEV);
2455 }
2456 
2457 /*------------------------------------------------------------------------*
2458  *	usb_read_symlink
2459  *
2460  * Return value:
2461  * 0: Success
2462  * Else: Failure
2463  *------------------------------------------------------------------------*/
2464 int
2465 usb_read_symlink(uint8_t *user_ptr, uint32_t startentry, uint32_t user_len)
2466 {
2467 	struct usb_symlink *ps;
2468 	uint32_t temp;
2469 	uint32_t delta = 0;
2470 	uint8_t len;
2471 	int error = 0;
2472 
2473 	lockmgr(&usb_sym_lock, LK_EXCLUSIVE);
2474 
2475 	TAILQ_FOREACH(ps, &usb_sym_head, sym_entry) {
2476 
2477 		/*
2478 		 * Compute total length of source and destination symlink
2479 		 * strings pluss one length byte and two NUL bytes:
2480 		 */
2481 		temp = ps->src_len + ps->dst_len + 3;
2482 
2483 		if (temp > 255) {
2484 			/*
2485 			 * Skip entry because this length cannot fit
2486 			 * into one byte:
2487 			 */
2488 			continue;
2489 		}
2490 		if (startentry != 0) {
2491 			/* decrement read offset */
2492 			startentry--;
2493 			continue;
2494 		}
2495 		if (temp > user_len) {
2496 			/* out of buffer space */
2497 			break;
2498 		}
2499 		len = temp;
2500 
2501 		/* copy out total length */
2502 
2503 		error = copyout(&len,
2504 		    USB_ADD_BYTES(user_ptr, delta), 1);
2505 		if (error) {
2506 			break;
2507 		}
2508 		delta += 1;
2509 
2510 		/* copy out source string */
2511 
2512 		error = copyout(ps->src_path,
2513 		    USB_ADD_BYTES(user_ptr, delta), ps->src_len);
2514 		if (error) {
2515 			break;
2516 		}
2517 		len = 0;
2518 		delta += ps->src_len;
2519 		error = copyout(&len,
2520 		    USB_ADD_BYTES(user_ptr, delta), 1);
2521 		if (error) {
2522 			break;
2523 		}
2524 		delta += 1;
2525 
2526 		/* copy out destination string */
2527 
2528 		error = copyout(ps->dst_path,
2529 		    USB_ADD_BYTES(user_ptr, delta), ps->dst_len);
2530 		if (error) {
2531 			break;
2532 		}
2533 		len = 0;
2534 		delta += ps->dst_len;
2535 		error = copyout(&len,
2536 		    USB_ADD_BYTES(user_ptr, delta), 1);
2537 		if (error) {
2538 			break;
2539 		}
2540 		delta += 1;
2541 
2542 		user_len -= temp;
2543 	}
2544 
2545 	/* a zero length entry indicates the end */
2546 
2547 	if ((user_len != 0) && (error == 0)) {
2548 
2549 		len = 0;
2550 
2551 		error = copyout(&len,
2552 		    USB_ADD_BYTES(user_ptr, delta), 1);
2553 	}
2554 	lockmgr(&usb_sym_lock, LK_RELEASE);
2555 	return (error);
2556 }
2557 
2558 void
2559 usb_fifo_set_close_zlp(struct usb_fifo *f, uint8_t onoff)
2560 {
2561 	if (f == NULL)
2562 		return;
2563 
2564 	/* send a Zero Length Packet, ZLP, before close */
2565 	f->flag_short = onoff;
2566 }
2567 
2568 void
2569 usb_fifo_set_write_defrag(struct usb_fifo *f, uint8_t onoff)
2570 {
2571 	if (f == NULL)
2572 		return;
2573 
2574 	/* defrag written data */
2575 	f->flag_write_defrag = onoff;
2576 	/* reset defrag state */
2577 	f->flag_have_fragment = 0;
2578 }
2579 
2580 void *
2581 usb_fifo_softc(struct usb_fifo *f)
2582 {
2583 	return (f->priv_sc0);
2584 }
2585 #endif	/* USB_HAVE_UGEN */
2586