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