xref: /dragonfly/sys/bus/u4b/usb_dev.c (revision 0ca59c34)
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/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(struct lock *lock);
105 static struct	usb_endpoint *usb_dev_get_ep(struct usb_device *, uint8_t,
106 		    uint8_t);
107 static void	usb_loc_fill(struct usb_fs_privdata *,
108 		    struct usb_cdev_privdata *);
109 static usb_error_t usb_ref_device(struct usb_cdev_privdata *, struct usb_cdev_refdata *, int);
110 static usb_error_t usb_usb_ref_device(struct usb_cdev_privdata *, struct usb_cdev_refdata *);
111 static void	usb_unref_device(struct usb_cdev_privdata *, struct usb_cdev_refdata *);
112 
113 static void	usb_cdevpriv_dtor(void *cd);
114 
115 static void usb_filter_detach(struct knote *kn);
116 static int usb_filter_read(struct knote *kn, long hint);
117 static int usb_filter_write(struct knote *kn, long hint);
118 
119 static d_open_t usb_open;
120 static d_close_t usb_close;
121 static d_ioctl_t usb_ioctl;
122 static d_read_t usb_read;
123 static d_write_t usb_write;
124 static d_kqfilter_t usb_kqfilter;
125 
126 static d_ioctl_t usb_static_ioctl;
127 static d_open_t usb_static_open;
128 static d_close_t usb_static_close;
129 
130 static usb_fifo_open_t usb_fifo_dummy_open;
131 static usb_fifo_close_t usb_fifo_dummy_close;
132 static usb_fifo_ioctl_t usb_fifo_dummy_ioctl;
133 static usb_fifo_cmd_t usb_fifo_dummy_cmd;
134 
135 /* character device structure used for devices (/dev/ugenX.Y and /dev/uXXX) */
136 struct dev_ops usb_ops = {
137 	{ "usbdev", 0, D_MPSAFE | D_MEM },
138 	.d_open = usb_open,
139 	.d_close = usb_close,
140 	.d_ioctl = usb_ioctl,
141 	.d_read = usb_read,
142 	.d_write = usb_write,
143 	.d_kqfilter = usb_kqfilter
144 };
145 
146 static struct cdev* usb_dev = NULL;
147 
148 /* character device structure used for /bus/u4b */
149 static struct dev_ops usb_static_ops = {
150 	{ "usb", 0, D_MPSAFE | D_MEM },
151 	.d_open = usb_static_open,
152 	.d_close = usb_static_close,
153 	.d_ioctl = usb_static_ioctl,
154 };
155 
156 static TAILQ_HEAD(, usb_symlink) usb_sym_head;
157 static struct lock usb_sym_lock;
158 
159 struct lock usb_ref_lock;
160 
161 /*static struct kqinfo usb_kqevent;
162  */
163 
164 /*------------------------------------------------------------------------*
165  *	usb_loc_fill
166  *
167  * This is used to fill out a usb_cdev_privdata structure based on the
168  * device's address as contained in usb_fs_privdata.
169  *------------------------------------------------------------------------*/
170 static void
171 usb_loc_fill(struct usb_fs_privdata* pd, struct usb_cdev_privdata *cpd)
172 {
173 	cpd->bus_index = pd->bus_index;
174 	cpd->dev_index = pd->dev_index;
175 	cpd->ep_addr = pd->ep_addr;
176 	cpd->fifo_index = pd->fifo_index;
177 }
178 
179 /*------------------------------------------------------------------------*
180  *	usb_ref_device
181  *
182  * This function is used to atomically refer an USB device by its
183  * device location. If this function returns success the USB device
184  * will not dissappear until the USB device is unreferenced.
185  *
186  * Return values:
187  *  0: Success, refcount incremented on the given USB device.
188  *  Else: Failure.
189  *------------------------------------------------------------------------*/
190 static usb_error_t
191 usb_ref_device(struct usb_cdev_privdata *cpd,
192     struct usb_cdev_refdata *crd, int need_uref)
193 {
194 	struct usb_fifo **ppf;
195 	struct usb_fifo *f;
196 
197 	DPRINTFN(2, "cpd=%p need uref=%d\n", cpd, need_uref);
198 
199 	/* clear all refs */
200 	memset(crd, 0, sizeof(*crd));
201 
202 	lockmgr(&usb_ref_lock, LK_EXCLUSIVE);
203 	cpd->bus = devclass_get_softc(usb_devclass_ptr, cpd->bus_index);
204 	if (cpd->bus == NULL) {
205 		DPRINTFN(2, "no bus at %u\n", cpd->bus_index);
206 		goto error;
207 	}
208 	cpd->udev = cpd->bus->devices[cpd->dev_index];
209 	if (cpd->udev == NULL) {
210 		DPRINTFN(2, "no device at %u\n", cpd->dev_index);
211 		goto error;
212 	}
213 	if (cpd->udev->state == USB_STATE_DETACHED &&
214 	    (need_uref != 2)) {
215 		DPRINTFN(2, "device is detached\n");
216 		goto error;
217 	}
218 	if (need_uref) {
219 		DPRINTFN(2, "ref udev - needed\n");
220 
221 		if (cpd->udev->refcount == USB_DEV_REF_MAX) {
222 			DPRINTFN(2, "no dev ref\n");
223 			goto error;
224 		}
225 		cpd->udev->refcount++;
226 
227 		lockmgr(&usb_ref_lock, LK_RELEASE);
228 
229 		/*
230 		 * We need to grab the sx-lock before grabbing the
231 		 * FIFO refs to avoid deadlock at detach!
232 		 */
233 		crd->do_unlock = usbd_enum_lock(cpd->udev);
234 
235 		lockmgr(&usb_ref_lock, LK_EXCLUSIVE);
236 
237 		/*
238 		 * Set "is_uref" after grabbing the default SX lock
239 		 */
240 		crd->is_uref = 1;
241 	}
242 
243 	/* check if we are doing an open */
244 	if (cpd->fflags == 0) {
245 		/* use zero defaults */
246 	} else {
247 		/* check for write */
248 		if (cpd->fflags & FWRITE) {
249 			ppf = cpd->udev->fifo;
250 			f = ppf[cpd->fifo_index + USB_FIFO_TX];
251 			crd->txfifo = f;
252 			crd->is_write = 1;	/* ref */
253 			if (f == NULL || f->refcount == USB_FIFO_REF_MAX)
254 				goto error;
255 			if (f->curr_cpd != cpd)
256 				goto error;
257 			/* check if USB-FS is active */
258 			if (f->fs_ep_max != 0) {
259 				crd->is_usbfs = 1;
260 			}
261 		}
262 
263 		/* check for read */
264 		if (cpd->fflags & FREAD) {
265 			ppf = cpd->udev->fifo;
266 			f = ppf[cpd->fifo_index + USB_FIFO_RX];
267 			crd->rxfifo = f;
268 			crd->is_read = 1;	/* ref */
269 			if (f == NULL || f->refcount == USB_FIFO_REF_MAX)
270 				goto error;
271 			if (f->curr_cpd != cpd)
272 				goto error;
273 			/* check if USB-FS is active */
274 			if (f->fs_ep_max != 0) {
275 				crd->is_usbfs = 1;
276 			}
277 		}
278 	}
279 
280 	/* when everything is OK we increment the refcounts */
281 	if (crd->is_write) {
282 		DPRINTFN(2, "ref write\n");
283 		crd->txfifo->refcount++;
284 	}
285 	if (crd->is_read) {
286 		DPRINTFN(2, "ref read\n");
287 		crd->rxfifo->refcount++;
288 	}
289 	lockmgr(&usb_ref_lock, LK_RELEASE);
290 
291 	return (0);
292 
293 error:
294 	if (crd->do_unlock)
295 		usbd_enum_unlock(cpd->udev);
296 
297 	if (crd->is_uref) {
298 		if (--(cpd->udev->refcount) == 0)
299 			cv_broadcast(&cpd->udev->ref_cv);
300 	}
301 	lockmgr(&usb_ref_lock, LK_RELEASE);
302 	DPRINTFN(2, "fail\n");
303 
304 	/* clear all refs */
305 	memset(crd, 0, sizeof(*crd));
306 
307 	return (USB_ERR_INVAL);
308 }
309 
310 /*------------------------------------------------------------------------*
311  *	usb_usb_ref_device
312  *
313  * This function is used to upgrade an USB reference to include the
314  * USB device reference on a USB location.
315  *
316  * Return values:
317  *  0: Success, refcount incremented on the given USB device.
318  *  Else: Failure.
319  *------------------------------------------------------------------------*/
320 static usb_error_t
321 usb_usb_ref_device(struct usb_cdev_privdata *cpd,
322     struct usb_cdev_refdata *crd)
323 {
324 	/*
325 	 * Check if we already got an USB reference on this location:
326 	 */
327 	if (crd->is_uref)
328 		return (0);		/* success */
329 
330 	/*
331 	 * To avoid deadlock at detach we need to drop the FIFO ref
332 	 * and re-acquire a new ref!
333 	 */
334 	usb_unref_device(cpd, crd);
335 
336 	return (usb_ref_device(cpd, crd, 1 /* need uref */));
337 }
338 
339 /*------------------------------------------------------------------------*
340  *	usb_unref_device
341  *
342  * This function will release the reference count by one unit for the
343  * given USB device.
344  *------------------------------------------------------------------------*/
345 static void
346 usb_unref_device(struct usb_cdev_privdata *cpd,
347     struct usb_cdev_refdata *crd)
348 {
349 
350 	DPRINTFN(2, "cpd=%p is_uref=%d\n", cpd, crd->is_uref);
351 
352 	if (crd->do_unlock)
353 		usbd_enum_unlock(cpd->udev);
354 
355 	lockmgr(&usb_ref_lock, LK_EXCLUSIVE);
356 	if (crd->is_read) {
357 		if (--(crd->rxfifo->refcount) == 0) {
358 			cv_signal(&crd->rxfifo->cv_drain);
359 		}
360 		crd->is_read = 0;
361 	}
362 	if (crd->is_write) {
363 		if (--(crd->txfifo->refcount) == 0) {
364 			cv_signal(&crd->txfifo->cv_drain);
365 		}
366 		crd->is_write = 0;
367 	}
368 	if (crd->is_uref) {
369 		crd->is_uref = 0;
370 		if (--(cpd->udev->refcount) == 0)
371 			cv_broadcast(&cpd->udev->ref_cv);
372 	}
373 	lockmgr(&usb_ref_lock, LK_RELEASE);
374 }
375 
376 static struct usb_fifo *
377 usb_fifo_alloc(struct lock *lock)
378 {
379 	struct usb_fifo *f;
380 
381 	f = kmalloc(sizeof(*f), M_USBDEV, M_WAITOK | M_ZERO);
382 	if (f != NULL) {
383 		cv_init(&f->cv_io, "FIFO-IO");
384 		cv_init(&f->cv_drain, "FIFO-DRAIN");
385 		f->priv_lock = lock;
386 		f->refcount = 1;
387 		/* mpf: knlist_init_mtx? the lock is used here in free */
388 	}
389 	return (f);
390 }
391 
392 /*------------------------------------------------------------------------*
393  *	usb_fifo_create
394  *------------------------------------------------------------------------*/
395 static int
396 usb_fifo_create(struct usb_cdev_privdata *cpd,
397     struct usb_cdev_refdata *crd)
398 {
399 	struct usb_device *udev = cpd->udev;
400 	struct usb_fifo *f;
401 	struct usb_endpoint *ep;
402 	uint8_t n;
403 	uint8_t is_tx;
404 	uint8_t is_rx;
405 	uint8_t no_null;
406 	uint8_t is_busy;
407 	int e = cpd->ep_addr;
408 
409 	is_tx = (cpd->fflags & FWRITE) ? 1 : 0;
410 	is_rx = (cpd->fflags & FREAD) ? 1 : 0;
411 	no_null = 1;
412 	is_busy = 0;
413 
414 	/* Preallocated FIFO */
415 	if (e < 0) {
416 		DPRINTFN(5, "Preallocated FIFO\n");
417 		if (is_tx) {
418 			f = udev->fifo[cpd->fifo_index + USB_FIFO_TX];
419 			if (f == NULL)
420 				return (EINVAL);
421 			crd->txfifo = f;
422 		}
423 		if (is_rx) {
424 			f = udev->fifo[cpd->fifo_index + USB_FIFO_RX];
425 			if (f == NULL)
426 				return (EINVAL);
427 			crd->rxfifo = f;
428 		}
429 		return (0);
430 	}
431 
432 	KASSERT(e >= 0 && e <= 15, ("endpoint %d out of range", e));
433 
434 	/* search for a free FIFO slot */
435 	DPRINTFN(5, "Endpoint device, searching for 0x%02x\n", e);
436 	for (n = 0;; n += 2) {
437 
438 		if (n == USB_FIFO_MAX) {
439 			if (no_null) {
440 				no_null = 0;
441 				n = 0;
442 			} else {
443 				/* end of FIFOs reached */
444 				DPRINTFN(5, "out of FIFOs\n");
445 				return (ENOMEM);
446 			}
447 		}
448 		/* Check for TX FIFO */
449 		if (is_tx) {
450 			f = udev->fifo[n + USB_FIFO_TX];
451 			if (f != NULL) {
452 				if (f->dev_ep_index != e) {
453 					/* wrong endpoint index */
454 					continue;
455 				}
456 				if (f->curr_cpd != NULL) {
457 					/* FIFO is opened */
458 					is_busy = 1;
459 					continue;
460 				}
461 			} else if (no_null) {
462 				continue;
463 			}
464 		}
465 		/* Check for RX FIFO */
466 		if (is_rx) {
467 			f = udev->fifo[n + USB_FIFO_RX];
468 			if (f != NULL) {
469 				if (f->dev_ep_index != e) {
470 					/* wrong endpoint index */
471 					continue;
472 				}
473 				if (f->curr_cpd != NULL) {
474 					/* FIFO is opened */
475 					is_busy = 1;
476 					continue;
477 				}
478 			} else if (no_null) {
479 				continue;
480 			}
481 		}
482 		break;
483 	}
484 
485 	if (no_null == 0) {
486 		if (e >= (USB_EP_MAX / 2)) {
487 			/* we don't create any endpoints in this range */
488 			DPRINTFN(5, "ep out of range\n");
489 			return (is_busy ? EBUSY : EINVAL);
490 		}
491 	}
492 
493 	if ((e != 0) && is_busy) {
494 		/*
495 		 * Only the default control endpoint is allowed to be
496 		 * opened multiple times!
497 		 */
498 		DPRINTFN(5, "busy\n");
499 		return (EBUSY);
500 	}
501 
502 	/* Check TX FIFO */
503 	if (is_tx &&
504 	    (udev->fifo[n + USB_FIFO_TX] == NULL)) {
505 		ep = usb_dev_get_ep(udev, e, USB_FIFO_TX);
506 		DPRINTFN(5, "dev_get_endpoint(%d, 0x%x)\n", e, USB_FIFO_TX);
507 		if (ep == NULL) {
508 			DPRINTFN(5, "dev_get_endpoint returned NULL\n");
509 			return (EINVAL);
510 		}
511 		f = usb_fifo_alloc(&udev->device_lock);
512 		if (f == NULL) {
513 			DPRINTFN(5, "could not alloc tx fifo\n");
514 			return (ENOMEM);
515 		}
516 		/* update some fields */
517 		f->fifo_index = n + USB_FIFO_TX;
518 		f->dev_ep_index = e;
519 		f->priv_sc0 = ep;
520 		f->methods = &usb_ugen_methods;
521 		f->iface_index = ep->iface_index;
522 		f->udev = udev;
523 		lockmgr(&usb_ref_lock, LK_EXCLUSIVE);
524 		udev->fifo[n + USB_FIFO_TX] = f;
525 		lockmgr(&usb_ref_lock, LK_RELEASE);
526 	}
527 	/* Check RX FIFO */
528 	if (is_rx &&
529 	    (udev->fifo[n + USB_FIFO_RX] == NULL)) {
530 
531 		ep = usb_dev_get_ep(udev, e, USB_FIFO_RX);
532 		DPRINTFN(5, "dev_get_endpoint(%d, 0x%x)\n", e, USB_FIFO_RX);
533 		if (ep == NULL) {
534 			DPRINTFN(5, "dev_get_endpoint returned NULL\n");
535 			return (EINVAL);
536 		}
537 		f = usb_fifo_alloc(&udev->device_lock);
538 		if (f == NULL) {
539 			DPRINTFN(5, "could not alloc rx fifo\n");
540 			return (ENOMEM);
541 		}
542 		/* update some fields */
543 		f->fifo_index = n + USB_FIFO_RX;
544 		f->dev_ep_index = e;
545 		f->priv_sc0 = ep;
546 		f->methods = &usb_ugen_methods;
547 		f->iface_index = ep->iface_index;
548 		f->udev = udev;
549 		lockmgr(&usb_ref_lock, LK_EXCLUSIVE);
550 		udev->fifo[n + USB_FIFO_RX] = f;
551 		lockmgr(&usb_ref_lock, LK_RELEASE);
552 	}
553 	if (is_tx) {
554 		crd->txfifo = udev->fifo[n + USB_FIFO_TX];
555 	}
556 	if (is_rx) {
557 		crd->rxfifo = udev->fifo[n + USB_FIFO_RX];
558 	}
559 	/* fill out fifo index */
560 	DPRINTFN(5, "fifo index = %d\n", n);
561 	cpd->fifo_index = n;
562 
563 	/* complete */
564 
565 	return (0);
566 }
567 
568 void
569 usb_fifo_free(struct usb_fifo *f)
570 {
571 	uint8_t n;
572 
573 	if (f == NULL) {
574 		/* be NULL safe */
575 		return;
576 	}
577 	/* destroy symlink devices, if any */
578 	for (n = 0; n != 2; n++) {
579 		if (f->symlink[n]) {
580 			usb_free_symlink(f->symlink[n]);
581 			f->symlink[n] = NULL;
582 		}
583 	}
584 	lockmgr(&usb_ref_lock, LK_EXCLUSIVE);
585 
586 	/* delink ourselves to stop calls from userland */
587 	if ((f->fifo_index < USB_FIFO_MAX) &&
588 	    (f->udev != NULL) &&
589 	    (f->udev->fifo[f->fifo_index] == f)) {
590 		f->udev->fifo[f->fifo_index] = NULL;
591 	} else {
592 		DPRINTFN(0, "USB FIFO %p has not been linked\n", f);
593 	}
594 
595 	/* decrease refcount */
596 	f->refcount--;
597 	/* need to wait until all callers have exited */
598 	while (f->refcount != 0) {
599 		lockmgr(&usb_ref_lock, LK_RELEASE);	/* avoid LOR */
600 		lockmgr(f->priv_lock, LK_EXCLUSIVE);
601 		/* prevent write flush, if any */
602 		f->flag_iserror = 1;
603 		/* get I/O thread out of any sleep state */
604 		if (f->flag_sleeping) {
605 			f->flag_sleeping = 0;
606 			cv_broadcast(&f->cv_io);
607 		}
608 		lockmgr(f->priv_lock, LK_RELEASE);
609 		lockmgr(&usb_ref_lock, LK_EXCLUSIVE);
610 
611                /*
612                 * Check if the "f->refcount" variable reached zero
613                 * during the unlocked time before entering wait:
614                 */
615 		if (f->refcount == 0)
616 			break;
617 
618 		/* wait for sync */
619 		cv_wait(&f->cv_drain, &usb_ref_lock);
620 	}
621 	lockmgr(&usb_ref_lock, LK_RELEASE);
622 
623 	/* take care of closing the device here, if any */
624 	usb_fifo_close(f, 0);
625 
626 	cv_destroy(&f->cv_io);
627 	cv_destroy(&f->cv_drain);
628 
629 	/* XXX mpf
630 	knlist_clear(&f->selinfo.si_note, 0);
631 	seldrain(&f->selinfo);
632 	knlist_destroy(&f->selinfo.si_note);
633 	*/
634 	kfree(f, M_USBDEV);
635 }
636 
637 static struct usb_endpoint *
638 usb_dev_get_ep(struct usb_device *udev, uint8_t ep_index, uint8_t dir)
639 {
640 	struct usb_endpoint *ep;
641 	uint8_t ep_dir;
642 
643 	if (ep_index == 0) {
644 		ep = &udev->ctrl_ep;
645 	} else {
646 		if (dir == USB_FIFO_RX) {
647 			if (udev->flags.usb_mode == USB_MODE_HOST) {
648 				ep_dir = UE_DIR_IN;
649 			} else {
650 				ep_dir = UE_DIR_OUT;
651 			}
652 		} else {
653 			if (udev->flags.usb_mode == USB_MODE_HOST) {
654 				ep_dir = UE_DIR_OUT;
655 			} else {
656 				ep_dir = UE_DIR_IN;
657 			}
658 		}
659 		ep = usbd_get_ep_by_addr(udev, ep_index | ep_dir);
660 	}
661 
662 	if (ep == NULL) {
663 		/* if the endpoint does not exist then return */
664 		return (NULL);
665 	}
666 	if (ep->edesc == NULL) {
667 		/* invalid endpoint */
668 		return (NULL);
669 	}
670 	return (ep);			/* success */
671 }
672 
673 /*------------------------------------------------------------------------*
674  *	usb_fifo_open
675  *
676  * Returns:
677  * 0: Success
678  * Else: Failure
679  *------------------------------------------------------------------------*/
680 static int
681 usb_fifo_open(struct usb_cdev_privdata *cpd,
682     struct usb_fifo *f, int fflags)
683 {
684 	int err;
685 
686 	if (f == NULL) {
687 		/* no FIFO there */
688 		DPRINTFN(2, "no FIFO\n");
689 		return (ENXIO);
690 	}
691 	/* remove FWRITE and FREAD flags */
692 	fflags &= ~(FWRITE | FREAD);
693 
694 	/* set correct file flags */
695 	if ((f->fifo_index & 1) == USB_FIFO_TX) {
696 		fflags |= FWRITE;
697 	} else {
698 		fflags |= FREAD;
699 	}
700 
701 	/* check if we are already opened */
702 	/* we don't need any locks when checking this variable */
703 	if (f->curr_cpd != NULL) {
704 		err = EBUSY;
705 		goto done;
706 	}
707 
708 	/* reset short flag before open */
709 	f->flag_short = 0;
710 
711 	/* call open method */
712 	err = (f->methods->f_open) (f, fflags);
713 	if (err) {
714 		goto done;
715 	}
716 	lockmgr(f->priv_lock, LK_EXCLUSIVE);
717 
718 	/* reset sleep flag */
719 	f->flag_sleeping = 0;
720 
721 	/* reset error flag */
722 	f->flag_iserror = 0;
723 
724 	/* reset complete flag */
725 	f->flag_iscomplete = 0;
726 
727 	/* reset select flag */
728 	f->flag_isselect = 0;
729 
730 	/* reset flushing flag */
731 	f->flag_flushing = 0;
732 
733 	/* reset ASYNC proc flag */
734 	f->async_p = NULL;
735 
736 	lockmgr(&usb_ref_lock, LK_EXCLUSIVE);
737 	/* flag the fifo as opened to prevent others */
738 	f->curr_cpd = cpd;
739 	lockmgr(&usb_ref_lock, LK_RELEASE);
740 
741 	/* reset queue */
742 	usb_fifo_reset(f);
743 
744 	lockmgr(f->priv_lock, LK_RELEASE);
745 done:
746 	return (err);
747 }
748 
749 /*------------------------------------------------------------------------*
750  *	usb_fifo_reset
751  *------------------------------------------------------------------------*/
752 void
753 usb_fifo_reset(struct usb_fifo *f)
754 {
755 	struct usb_mbuf *m;
756 
757 	if (f == NULL) {
758 		return;
759 	}
760 	while (1) {
761 		USB_IF_DEQUEUE(&f->used_q, m);
762 		if (m) {
763 			USB_IF_ENQUEUE(&f->free_q, m);
764 		} else {
765 			break;
766 		}
767 	}
768 	/* reset have fragment flag */
769 	f->flag_have_fragment = 0;
770 }
771 
772 /*------------------------------------------------------------------------*
773  *	usb_fifo_close
774  *------------------------------------------------------------------------*/
775 static void
776 usb_fifo_close(struct usb_fifo *f, int fflags)
777 {
778 	int err;
779 
780 	/* check if we are not opened */
781 	if (f->curr_cpd == NULL) {
782 		/* nothing to do - already closed */
783 		return;
784 	}
785 	lockmgr(f->priv_lock, LK_EXCLUSIVE);
786 
787 	/* clear current cdev private data pointer */
788 	lockmgr(&usb_ref_lock, LK_EXCLUSIVE);
789 	f->curr_cpd = NULL;
790 	lockmgr(&usb_ref_lock, LK_RELEASE);
791 
792 	/* check if we are selected */
793 	if (f->flag_isselect) {
794 		KNOTE(&f->selinfo.ki_note, 0);
795 		wakeup(&f->selinfo.ki_note);
796 
797 		f->flag_isselect = 0;
798 	}
799 	/* check if a thread wants SIGIO */
800 	if (f->async_p != NULL && lwkt_trytoken(&f->async_p->p_token)) {
801 		ksignal(f->async_p, SIGIO);
802 		lwkt_reltoken(&f->async_p->p_token);
803 		f->async_p = NULL;
804 	}
805 	/* remove FWRITE and FREAD flags */
806 	fflags &= ~(FWRITE | FREAD);
807 
808 	/* flush written data, if any */
809 	if ((f->fifo_index & 1) == USB_FIFO_TX) {
810 
811 		if (!f->flag_iserror) {
812 
813 			/* set flushing flag */
814 			f->flag_flushing = 1;
815 
816 			/* get the last packet in */
817 			if (f->flag_have_fragment) {
818 				struct usb_mbuf *m;
819 				f->flag_have_fragment = 0;
820 				USB_IF_DEQUEUE(&f->free_q, m);
821 				if (m) {
822 					USB_IF_ENQUEUE(&f->used_q, m);
823 				}
824 			}
825 
826 			/* start write transfer, if not already started */
827 			(f->methods->f_start_write) (f);
828 
829 			/* check if flushed already */
830 			while (f->flag_flushing &&
831 			    (!f->flag_iserror)) {
832 				/* wait until all data has been written */
833 				f->flag_sleeping = 1;
834 				err = cv_wait_sig(&f->cv_io, f->priv_lock);
835 				if (err) {
836 					DPRINTF("signal received\n");
837 					break;
838 				}
839 			}
840 		}
841 		fflags |= FWRITE;
842 
843 		/* stop write transfer, if not already stopped */
844 		(f->methods->f_stop_write) (f);
845 	} else {
846 		fflags |= FREAD;
847 
848 		/* stop write transfer, if not already stopped */
849 		(f->methods->f_stop_read) (f);
850 	}
851 
852 	/* check if we are sleeping */
853 	if (f->flag_sleeping) {
854 		DPRINTFN(2, "Sleeping at close!\n");
855 	}
856 	lockmgr(f->priv_lock, LK_RELEASE);
857 
858 	/* call close method */
859 	(f->methods->f_close) (f, fflags);
860 
861 	DPRINTF("closed\n");
862 }
863 
864 /*------------------------------------------------------------------------*
865  *	usb_open - cdev callback
866  *------------------------------------------------------------------------*/
867 static int
868 usb_open(struct dev_open_args *ap)
869 {
870 	struct cdev *dev = ap->a_head.a_dev;
871 	int fflags = ap->a_oflags;
872 	struct usb_fs_privdata* pd = (struct usb_fs_privdata*)dev->si_drv1;
873 	struct usb_cdev_refdata refs;
874 	struct usb_cdev_privdata *cpd;
875 	int err, ep;
876 
877 	DPRINTFN(2, "%s fflags=0x%08x\n", devtoname(dev), fflags);
878 
879 	KASSERT(fflags & (FREAD|FWRITE), ("invalid open flags"));
880 	if (((fflags & FREAD) && !(pd->mode & FREAD)) ||
881 	    ((fflags & FWRITE) && !(pd->mode & FWRITE))) {
882 		DPRINTFN(2, "access mode not supported\n");
883 		return (EPERM);
884 	}
885 
886 	cpd = kmalloc(sizeof(*cpd), M_USBDEV, M_WAITOK | M_ZERO);
887 	ep = cpd->ep_addr = pd->ep_addr;
888 
889 	usb_loc_fill(pd, cpd);
890 	err = usb_ref_device(cpd, &refs, 1);
891 	if (err) {
892 		DPRINTFN(2, "cannot ref device\n");
893 		kfree(cpd, M_USBDEV);
894 		return (ENXIO);
895 	}
896 	cpd->fflags = fflags;	/* access mode for open lifetime */
897 
898 	/* create FIFOs, if any */
899 	err = usb_fifo_create(cpd, &refs);
900 	/* check for error */
901 	if (err) {
902 		DPRINTFN(2, "cannot create fifo\n");
903 		usb_unref_device(cpd, &refs);
904 		kfree(cpd, M_USBDEV);
905 		return (err);
906 	}
907 	if (fflags & FREAD) {
908 		err = usb_fifo_open(cpd, refs.rxfifo, fflags);
909 		if (err) {
910 			DPRINTFN(2, "read open failed\n");
911 			usb_unref_device(cpd, &refs);
912 			kfree(cpd, M_USBDEV);
913 			return (err);
914 		}
915 	}
916 	if (fflags & FWRITE) {
917 		err = usb_fifo_open(cpd, refs.txfifo, fflags);
918 		if (err) {
919 			DPRINTFN(2, "write open failed\n");
920 			if (fflags & FREAD) {
921 				usb_fifo_close(refs.rxfifo, fflags);
922 			}
923 			usb_unref_device(cpd, &refs);
924 			kfree(cpd, M_USBDEV);
925 			return (err);
926 		}
927 	}
928 	usb_unref_device(cpd, &refs);
929 	err = devfs_set_cdevpriv(ap->a_fp, cpd, &usb_cdevpriv_dtor);
930 	DPRINTFN(2, "fp=%p cpd=%p\n", ap->a_fp, cpd);
931 	if(err) {
932 		DPRINTFN(2, "devfs_set_cdevpriv failed in %s\n", __func__);
933 		kfree(cpd, M_USBDEV);
934 		return(err);
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 			usb_fifo_wakeup(f);
2198 
2199 			if ((len == 0) || (what == 1)) {
2200 				break;
2201 			}
2202 		} else {
2203 			break;
2204 		}
2205 	}
2206 }
2207 
2208 void
2209 usb_fifo_put_data_linear(struct usb_fifo *f, void *ptr,
2210     usb_size_t len, uint8_t what)
2211 {
2212 	struct usb_mbuf *m;
2213 	usb_size_t io_len;
2214 
2215 	while (len || (what == 1)) {
2216 
2217 		USB_IF_DEQUEUE(&f->free_q, m);
2218 
2219 		if (m) {
2220 			USB_MBUF_RESET(m);
2221 
2222 			io_len = MIN(len, m->cur_data_len);
2223 
2224 			memcpy(m->cur_data_ptr, ptr, io_len);
2225 
2226 			m->cur_data_len = io_len;
2227 			ptr = USB_ADD_BYTES(ptr, io_len);
2228 			len -= io_len;
2229 
2230 			if ((len == 0) && (what == 1)) {
2231 				m->last_packet = 1;
2232 			}
2233 			USB_IF_ENQUEUE(&f->used_q, m);
2234 			usb_fifo_wakeup(f);
2235 
2236 			if ((len == 0) || (what == 1)) {
2237 				break;
2238 			}
2239 		} else {
2240 			break;
2241 		}
2242 	}
2243 }
2244 
2245 uint8_t
2246 usb_fifo_put_data_buffer(struct usb_fifo *f, void *ptr, usb_size_t len)
2247 {
2248 	struct usb_mbuf *m;
2249 
2250 	USB_IF_DEQUEUE(&f->free_q, m);
2251 
2252 	if (m) {
2253 		m->cur_data_len = len;
2254 		m->cur_data_ptr = ptr;
2255 		USB_IF_ENQUEUE(&f->used_q, m);
2256 		usb_fifo_wakeup(f);
2257 		return (1);
2258 	}
2259 	return (0);
2260 }
2261 
2262 void
2263 usb_fifo_put_data_error(struct usb_fifo *f)
2264 {
2265 	f->flag_iserror = 1;
2266 	usb_fifo_wakeup(f);
2267 }
2268 
2269 /*------------------------------------------------------------------------*
2270  *	usb_fifo_get_data
2271  *
2272  * what:
2273  *  0 - normal operation
2274  *  1 - only get one "usb_mbuf"
2275  *
2276  * returns:
2277  *  0 - no more data
2278  *  1 - data in buffer
2279  *------------------------------------------------------------------------*/
2280 uint8_t
2281 usb_fifo_get_data(struct usb_fifo *f, struct usb_page_cache *pc,
2282     usb_frlength_t offset, usb_frlength_t len, usb_frlength_t *actlen,
2283     uint8_t what)
2284 {
2285 	struct usb_mbuf *m;
2286 	usb_frlength_t io_len;
2287 	uint8_t tr_data = 0;
2288 
2289 	actlen[0] = 0;
2290 
2291 	while (1) {
2292 
2293 		USB_IF_DEQUEUE(&f->used_q, m);
2294 
2295 		if (m) {
2296 
2297 			tr_data = 1;
2298 
2299 			io_len = MIN(len, m->cur_data_len);
2300 
2301 			usbd_copy_in(pc, offset, m->cur_data_ptr, io_len);
2302 
2303 			len -= io_len;
2304 			offset += io_len;
2305 			actlen[0] += io_len;
2306 			m->cur_data_ptr += io_len;
2307 			m->cur_data_len -= io_len;
2308 
2309 			if ((m->cur_data_len == 0) || (what == 1)) {
2310 				USB_IF_ENQUEUE(&f->free_q, m);
2311 
2312 				usb_fifo_wakeup(f);
2313 
2314 				if (what == 1) {
2315 					break;
2316 				}
2317 			} else {
2318 				USB_IF_PREPEND(&f->used_q, m);
2319 				usb_fifo_wakeup(f);
2320 			}
2321 		} else {
2322 
2323 			if (tr_data) {
2324 				/* wait for data to be written out */
2325 				break;
2326 			}
2327 			if (f->flag_flushing) {
2328 				/* check if we should send a short packet */
2329 				if (f->flag_short != 0) {
2330 					f->flag_short = 0;
2331 					tr_data = 1;
2332 					break;
2333 				}
2334 				/* flushing complete */
2335 				f->flag_flushing = 0;
2336 				usb_fifo_wakeup(f);
2337 			}
2338 			break;
2339 		}
2340 		if (len == 0) {
2341 			break;
2342 		}
2343 	}
2344 	return (tr_data);
2345 }
2346 
2347 uint8_t
2348 usb_fifo_get_data_linear(struct usb_fifo *f, void *ptr,
2349     usb_size_t len, usb_size_t *actlen, uint8_t what)
2350 {
2351 	struct usb_mbuf *m;
2352 	usb_size_t io_len;
2353 	uint8_t tr_data = 0;
2354 
2355 	actlen[0] = 0;
2356 
2357 	while (1) {
2358 
2359 		USB_IF_DEQUEUE(&f->used_q, m);
2360 
2361 		if (m) {
2362 
2363 			tr_data = 1;
2364 
2365 			io_len = MIN(len, m->cur_data_len);
2366 
2367 			memcpy(ptr, m->cur_data_ptr, io_len);
2368 
2369 			len -= io_len;
2370 			ptr = USB_ADD_BYTES(ptr, io_len);
2371 			actlen[0] += io_len;
2372 			m->cur_data_ptr += io_len;
2373 			m->cur_data_len -= io_len;
2374 
2375 			if ((m->cur_data_len == 0) || (what == 1)) {
2376 				USB_IF_ENQUEUE(&f->free_q, m);
2377 
2378 				usb_fifo_wakeup(f);
2379 
2380 				if (what == 1) {
2381 					break;
2382 				}
2383 			} else {
2384 				USB_IF_PREPEND(&f->used_q, m);
2385 				usb_fifo_wakeup(f);
2386 			}
2387 		} else {
2388 
2389 			if (tr_data) {
2390 				/* wait for data to be written out */
2391 				break;
2392 			}
2393 			if (f->flag_flushing) {
2394 				/* check if we should send a short packet */
2395 				if (f->flag_short != 0) {
2396 					f->flag_short = 0;
2397 					tr_data = 1;
2398 					break;
2399 				}
2400 				/* flushing complete */
2401 				f->flag_flushing = 0;
2402 				usb_fifo_wakeup(f);
2403 			}
2404 			break;
2405 		}
2406 		if (len == 0) {
2407 			break;
2408 		}
2409 	}
2410 	return (tr_data);
2411 }
2412 
2413 uint8_t
2414 usb_fifo_get_data_buffer(struct usb_fifo *f, void **pptr, usb_size_t *plen)
2415 {
2416 	struct usb_mbuf *m;
2417 
2418 	USB_IF_POLL(&f->used_q, m);
2419 
2420 	if (m) {
2421 		*plen = m->cur_data_len;
2422 		*pptr = m->cur_data_ptr;
2423 
2424 		return (1);
2425 	}
2426 	return (0);
2427 }
2428 
2429 void
2430 usb_fifo_get_data_error(struct usb_fifo *f)
2431 {
2432 	f->flag_iserror = 1;
2433 	usb_fifo_wakeup(f);
2434 }
2435 
2436 /*------------------------------------------------------------------------*
2437  *	usb_alloc_symlink
2438  *
2439  * Return values:
2440  * NULL: Failure
2441  * Else: Pointer to symlink entry
2442  *------------------------------------------------------------------------*/
2443 struct usb_symlink *
2444 usb_alloc_symlink(const char *target)
2445 {
2446 	struct usb_symlink *ps;
2447 
2448 	ps = kmalloc(sizeof(*ps), M_USBDEV, M_WAITOK);
2449 	if (ps == NULL) {
2450 		return (ps);
2451 	}
2452 	/* XXX no longer needed */
2453 	strlcpy(ps->src_path, target, sizeof(ps->src_path));
2454 	ps->src_len = strlen(ps->src_path);
2455 	strlcpy(ps->dst_path, target, sizeof(ps->dst_path));
2456 	ps->dst_len = strlen(ps->dst_path);
2457 
2458 	lockmgr(&usb_sym_lock, LK_EXCLUSIVE);
2459 	TAILQ_INSERT_TAIL(&usb_sym_head, ps, sym_entry);
2460 	lockmgr(&usb_sym_lock, LK_RELEASE);
2461 	return (ps);
2462 }
2463 
2464 /*------------------------------------------------------------------------*
2465  *	usb_free_symlink
2466  *------------------------------------------------------------------------*/
2467 void
2468 usb_free_symlink(struct usb_symlink *ps)
2469 {
2470 	if (ps == NULL) {
2471 		return;
2472 	}
2473 	lockmgr(&usb_sym_lock, LK_EXCLUSIVE);
2474 	TAILQ_REMOVE(&usb_sym_head, ps, sym_entry);
2475 	lockmgr(&usb_sym_lock, LK_RELEASE);
2476 
2477 	kfree(ps, M_USBDEV);
2478 }
2479 
2480 /*------------------------------------------------------------------------*
2481  *	usb_read_symlink
2482  *
2483  * Return value:
2484  * 0: Success
2485  * Else: Failure
2486  *------------------------------------------------------------------------*/
2487 int
2488 usb_read_symlink(uint8_t *user_ptr, uint32_t startentry, uint32_t user_len)
2489 {
2490 	struct usb_symlink *ps;
2491 	uint32_t temp;
2492 	uint32_t delta = 0;
2493 	uint8_t len;
2494 	int error = 0;
2495 
2496 	lockmgr(&usb_sym_lock, LK_EXCLUSIVE);
2497 
2498 	TAILQ_FOREACH(ps, &usb_sym_head, sym_entry) {
2499 
2500 		/*
2501 		 * Compute total length of source and destination symlink
2502 		 * strings pluss one length byte and two NUL bytes:
2503 		 */
2504 		temp = ps->src_len + ps->dst_len + 3;
2505 
2506 		if (temp > 255) {
2507 			/*
2508 			 * Skip entry because this length cannot fit
2509 			 * into one byte:
2510 			 */
2511 			continue;
2512 		}
2513 		if (startentry != 0) {
2514 			/* decrement read offset */
2515 			startentry--;
2516 			continue;
2517 		}
2518 		if (temp > user_len) {
2519 			/* out of buffer space */
2520 			break;
2521 		}
2522 		len = temp;
2523 
2524 		/* copy out total length */
2525 
2526 		error = copyout(&len,
2527 		    USB_ADD_BYTES(user_ptr, delta), 1);
2528 		if (error) {
2529 			break;
2530 		}
2531 		delta += 1;
2532 
2533 		/* copy out source string */
2534 
2535 		error = copyout(ps->src_path,
2536 		    USB_ADD_BYTES(user_ptr, delta), ps->src_len);
2537 		if (error) {
2538 			break;
2539 		}
2540 		len = 0;
2541 		delta += ps->src_len;
2542 		error = copyout(&len,
2543 		    USB_ADD_BYTES(user_ptr, delta), 1);
2544 		if (error) {
2545 			break;
2546 		}
2547 		delta += 1;
2548 
2549 		/* copy out destination string */
2550 
2551 		error = copyout(ps->dst_path,
2552 		    USB_ADD_BYTES(user_ptr, delta), ps->dst_len);
2553 		if (error) {
2554 			break;
2555 		}
2556 		len = 0;
2557 		delta += ps->dst_len;
2558 		error = copyout(&len,
2559 		    USB_ADD_BYTES(user_ptr, delta), 1);
2560 		if (error) {
2561 			break;
2562 		}
2563 		delta += 1;
2564 
2565 		user_len -= temp;
2566 	}
2567 
2568 	/* a zero length entry indicates the end */
2569 
2570 	if ((user_len != 0) && (error == 0)) {
2571 
2572 		len = 0;
2573 
2574 		error = copyout(&len,
2575 		    USB_ADD_BYTES(user_ptr, delta), 1);
2576 	}
2577 	lockmgr(&usb_sym_lock, LK_RELEASE);
2578 	return (error);
2579 }
2580 
2581 void
2582 usb_fifo_set_close_zlp(struct usb_fifo *f, uint8_t onoff)
2583 {
2584 	if (f == NULL)
2585 		return;
2586 
2587 	/* send a Zero Length Packet, ZLP, before close */
2588 	f->flag_short = onoff;
2589 }
2590 
2591 void
2592 usb_fifo_set_write_defrag(struct usb_fifo *f, uint8_t onoff)
2593 {
2594 	if (f == NULL)
2595 		return;
2596 
2597 	/* defrag written data */
2598 	f->flag_write_defrag = onoff;
2599 	/* reset defrag state */
2600 	f->flag_have_fragment = 0;
2601 }
2602 
2603 void *
2604 usb_fifo_softc(struct usb_fifo *f)
2605 {
2606 	return (f->priv_sc0);
2607 }
2608 #endif	/* USB_HAVE_UGEN */
2609