xref: /freebsd/sys/dev/usb/usb_dev.c (revision 36138969847b231cd98f48272e2bdf88a8dc08dd)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2006-2023 Hans Petter Selasky
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  *
27  *
28  * usb_dev.c - An abstraction layer for creating devices under /dev/...
29  */
30 
31 #ifdef USB_GLOBAL_INCLUDE_FILE
32 #include USB_GLOBAL_INCLUDE_FILE
33 #else
34 #ifdef COMPAT_FREEBSD32
35 #include <sys/abi_compat.h>
36 #endif
37 #include <sys/stdint.h>
38 #include <sys/stddef.h>
39 #include <sys/param.h>
40 #include <sys/queue.h>
41 #include <sys/types.h>
42 #include <sys/systm.h>
43 #include <sys/kernel.h>
44 #include <sys/bus.h>
45 #include <sys/module.h>
46 #include <sys/lock.h>
47 #include <sys/mutex.h>
48 #include <sys/condvar.h>
49 #include <sys/sysctl.h>
50 #include <sys/sx.h>
51 #include <sys/unistd.h>
52 #include <sys/callout.h>
53 #include <sys/malloc.h>
54 #include <sys/priv.h>
55 #include <sys/vnode.h>
56 #include <sys/conf.h>
57 #include <sys/fcntl.h>
58 
59 #include <dev/usb/usb.h>
60 #include <dev/usb/usb_ioctl.h>
61 #include <dev/usb/usbdi.h>
62 #include <dev/usb/usbdi_util.h>
63 
64 #define	USB_DEBUG_VAR usb_fifo_debug
65 
66 #include <dev/usb/usb_core.h>
67 #include <dev/usb/usb_dev.h>
68 #include <dev/usb/usb_mbuf.h>
69 #include <dev/usb/usb_process.h>
70 #include <dev/usb/usb_device.h>
71 #include <dev/usb/usb_debug.h>
72 #include <dev/usb/usb_busdma.h>
73 #include <dev/usb/usb_generic.h>
74 #include <dev/usb/usb_dynamic.h>
75 #include <dev/usb/usb_util.h>
76 
77 #include <dev/usb/usb_controller.h>
78 #include <dev/usb/usb_bus.h>
79 
80 #include <sys/filio.h>
81 #include <sys/ttycom.h>
82 #include <sys/syscallsubr.h>
83 #include <sys/stdarg.h>
84 #endif			/* USB_GLOBAL_INCLUDE_FILE */
85 
86 #if USB_HAVE_UGEN
87 
88 #ifdef USB_DEBUG
89 static int usb_fifo_debug = 0;
90 
91 static SYSCTL_NODE(_hw_usb, OID_AUTO, dev, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
92     "USB device");
93 SYSCTL_INT(_hw_usb_dev, OID_AUTO, debug, CTLFLAG_RWTUN,
94     &usb_fifo_debug, 0, "Debug Level");
95 #endif
96 
97 #define	USB_UCRED struct ucred *ucred,
98 
99 /* prototypes */
100 
101 static int	usb_fifo_open(struct usb_cdev_privdata *,
102 		    struct usb_fifo *, int);
103 static void	usb_fifo_close(struct usb_fifo *, int);
104 static void	usb_dev_init(void *);
105 static void	usb_dev_init_post(void *);
106 static void	usb_dev_uninit(void *);
107 static int	usb_fifo_uiomove(struct usb_fifo *, void *, int,
108 		    struct uio *);
109 static void	usb_fifo_check_methods(struct usb_fifo_methods *);
110 static struct	usb_fifo *usb_fifo_alloc(struct mtx *);
111 static struct	usb_endpoint *usb_dev_get_ep(struct usb_device *, uint8_t,
112 		    uint8_t);
113 static void	usb_loc_fill(struct usb_fs_privdata *,
114 		    struct usb_cdev_privdata *);
115 static void	usb_close(void *);
116 static usb_error_t usb_ref_device(struct usb_cdev_privdata *, struct usb_cdev_refdata *, int);
117 static usb_error_t usb_usb_ref_device(struct usb_cdev_privdata *, struct usb_cdev_refdata *);
118 static void	usb_unref_device(struct usb_cdev_privdata *, struct usb_cdev_refdata *);
119 
120 static d_open_t usb_open;
121 static d_ioctl_t usb_ioctl;
122 static d_read_t usb_read;
123 static d_write_t usb_write;
124 static d_poll_t usb_poll;
125 static d_kqfilter_t usb_kqfilter;
126 
127 static d_ioctl_t usb_static_ioctl;
128 
129 static usb_fifo_open_t usb_fifo_dummy_open;
130 static usb_fifo_close_t usb_fifo_dummy_close;
131 static usb_fifo_ioctl_t usb_fifo_dummy_ioctl;
132 static usb_fifo_cmd_t usb_fifo_dummy_cmd;
133 
134 /* character device structure used for devices (/dev/ugenX.Y and /dev/uXXX) */
135 struct cdevsw usb_devsw = {
136 	.d_version = D_VERSION,
137 	.d_open = usb_open,
138 	.d_ioctl = usb_ioctl,
139 	.d_name = "usbdev",
140 	.d_flags = D_TRACKCLOSE,
141 	.d_read = usb_read,
142 	.d_write = usb_write,
143 	.d_poll = usb_poll,
144 	.d_kqfilter = usb_kqfilter,
145 };
146 
147 static struct cdev* usb_dev = NULL;
148 
149 /* character device structure used for /dev/usb */
150 static struct cdevsw usb_static_devsw = {
151 	.d_version = D_VERSION,
152 	.d_ioctl = usb_static_ioctl,
153 	.d_name = "usb"
154 };
155 
156 static TAILQ_HEAD(, usb_symlink) usb_sym_head;
157 static struct sx usb_sym_lock;
158 
159 struct mtx usb_ref_lock;
160 
161 /*------------------------------------------------------------------------*
162  *	usb_loc_fill
163  *
164  * This is used to fill out a usb_cdev_privdata structure based on the
165  * device's address as contained in usb_fs_privdata.
166  *------------------------------------------------------------------------*/
167 static void
usb_loc_fill(struct usb_fs_privdata * pd,struct usb_cdev_privdata * cpd)168 usb_loc_fill(struct usb_fs_privdata* pd, struct usb_cdev_privdata *cpd)
169 {
170 	cpd->bus_index = pd->bus_index;
171 	cpd->dev_index = pd->dev_index;
172 	cpd->ep_addr = pd->ep_addr;
173 	cpd->fifo_index = pd->fifo_index;
174 }
175 
176 /*------------------------------------------------------------------------*
177  *	usb_ref_device
178  *
179  * This function is used to atomically refer an USB device by its
180  * device location. If this function returns success the USB device
181  * will not disappear until the USB device is unreferenced.
182  *
183  * Return values:
184  *  0: Success, refcount incremented on the given USB device.
185  *  Else: Failure.
186  *------------------------------------------------------------------------*/
187 static usb_error_t
usb_ref_device(struct usb_cdev_privdata * cpd,struct usb_cdev_refdata * crd,int need_uref)188 usb_ref_device(struct usb_cdev_privdata *cpd,
189     struct usb_cdev_refdata *crd, int need_uref)
190 {
191 	struct usb_fifo **ppf;
192 	struct usb_fifo *f;
193 
194 	DPRINTFN(2, "cpd=%p need uref=%d\n", cpd, need_uref);
195 
196 	/* clear all refs */
197 	memset(crd, 0, sizeof(*crd));
198 
199 	mtx_lock(&usb_ref_lock);
200 	cpd->bus = devclass_get_softc(usb_devclass_ptr, cpd->bus_index);
201 	if (cpd->bus == NULL) {
202 		DPRINTFN(2, "no bus at %u\n", cpd->bus_index);
203 		goto error;
204 	}
205 	cpd->udev = cpd->bus->devices[cpd->dev_index];
206 	if (cpd->udev == NULL) {
207 		DPRINTFN(2, "no device at %u\n", cpd->dev_index);
208 		goto error;
209 	}
210 	if (cpd->udev->state == USB_STATE_DETACHED &&
211 	    (need_uref != 2)) {
212 		DPRINTFN(2, "device is detached\n");
213 		goto error;
214 	}
215 	if (need_uref) {
216 		DPRINTFN(2, "ref udev - needed\n");
217 
218 		if (cpd->udev->refcount == USB_DEV_REF_MAX) {
219 			DPRINTFN(2, "no dev ref\n");
220 			goto error;
221 		}
222 		cpd->udev->refcount++;
223 
224 		mtx_unlock(&usb_ref_lock);
225 
226 		/*
227 		 * We need to grab the enumeration SX-lock before
228 		 * grabbing the FIFO refs to avoid deadlock at detach!
229 		 */
230 		crd->do_unlock = usbd_enum_lock_sig(cpd->udev);
231 
232 		mtx_lock(&usb_ref_lock);
233 
234 		/*
235 		 * Set "is_uref" after grabbing the default SX lock
236 		 */
237 		crd->is_uref = 1;
238 
239 		/* check for signal */
240 		if (crd->do_unlock > 1) {
241 			crd->do_unlock = 0;
242 			goto error;
243 		}
244 	}
245 
246 	/* check if we are doing an open */
247 	if (cpd->fflags == 0) {
248 		/* use zero defaults */
249 	} else {
250 		/* check for write */
251 		if (cpd->fflags & FWRITE) {
252 			ppf = cpd->udev->fifo;
253 			f = ppf[cpd->fifo_index + USB_FIFO_TX];
254 			crd->txfifo = f;
255 			crd->is_write = 1;	/* ref */
256 			if (f == NULL || f->refcount == USB_FIFO_REF_MAX)
257 				goto error;
258 			if (f->curr_cpd != cpd)
259 				goto error;
260 			/* check if USB-FS is active */
261 			if (f->fs_ep_max != 0) {
262 				crd->is_usbfs = 1;
263 			}
264 		}
265 
266 		/* check for read */
267 		if (cpd->fflags & FREAD) {
268 			ppf = cpd->udev->fifo;
269 			f = ppf[cpd->fifo_index + USB_FIFO_RX];
270 			crd->rxfifo = f;
271 			crd->is_read = 1;	/* ref */
272 			if (f == NULL || f->refcount == USB_FIFO_REF_MAX)
273 				goto error;
274 			if (f->curr_cpd != cpd)
275 				goto error;
276 			/* check if USB-FS is active */
277 			if (f->fs_ep_max != 0) {
278 				crd->is_usbfs = 1;
279 			}
280 		}
281 	}
282 
283 	/* when everything is OK we increment the refcounts */
284 	if (crd->is_write) {
285 		DPRINTFN(2, "ref write\n");
286 		crd->txfifo->refcount++;
287 	}
288 	if (crd->is_read) {
289 		DPRINTFN(2, "ref read\n");
290 		crd->rxfifo->refcount++;
291 	}
292 	mtx_unlock(&usb_ref_lock);
293 
294 	return (0);
295 
296 error:
297 	if (crd->do_unlock)
298 		usbd_enum_unlock(cpd->udev);
299 
300 	if (crd->is_uref) {
301 		if (--(cpd->udev->refcount) == 0)
302 			cv_broadcast(&cpd->udev->ref_cv);
303 	}
304 	mtx_unlock(&usb_ref_lock);
305 	DPRINTFN(2, "fail\n");
306 
307 	/* clear all refs */
308 	memset(crd, 0, sizeof(*crd));
309 
310 	return (USB_ERR_INVAL);
311 }
312 
313 /*------------------------------------------------------------------------*
314  *	usb_usb_ref_device
315  *
316  * This function is used to upgrade an USB reference to include the
317  * USB device reference on a USB location.
318  *
319  * Return values:
320  *  0: Success, refcount incremented on the given USB device.
321  *  Else: Failure.
322  *------------------------------------------------------------------------*/
323 static usb_error_t
usb_usb_ref_device(struct usb_cdev_privdata * cpd,struct usb_cdev_refdata * crd)324 usb_usb_ref_device(struct usb_cdev_privdata *cpd,
325     struct usb_cdev_refdata *crd)
326 {
327 	/*
328 	 * Check if we already got an USB reference on this location:
329 	 */
330 	if (crd->is_uref)
331 		return (0);		/* success */
332 
333 	/*
334 	 * To avoid deadlock at detach we need to drop the FIFO ref
335 	 * and re-acquire a new ref!
336 	 */
337 	usb_unref_device(cpd, crd);
338 
339 	return (usb_ref_device(cpd, crd, 1 /* need uref */));
340 }
341 
342 /*------------------------------------------------------------------------*
343  *	usb_unref_device
344  *
345  * This function will release the reference count by one unit for the
346  * given USB device.
347  *------------------------------------------------------------------------*/
348 static void
usb_unref_device(struct usb_cdev_privdata * cpd,struct usb_cdev_refdata * crd)349 usb_unref_device(struct usb_cdev_privdata *cpd,
350     struct usb_cdev_refdata *crd)
351 {
352 
353 	DPRINTFN(2, "cpd=%p is_uref=%d\n", cpd, crd->is_uref);
354 
355 	if (crd->do_unlock)
356 		usbd_enum_unlock(cpd->udev);
357 
358 	mtx_lock(&usb_ref_lock);
359 	if (crd->is_read) {
360 		if (--(crd->rxfifo->refcount) == 0) {
361 			cv_signal(&crd->rxfifo->cv_drain);
362 		}
363 		crd->is_read = 0;
364 	}
365 	if (crd->is_write) {
366 		if (--(crd->txfifo->refcount) == 0) {
367 			cv_signal(&crd->txfifo->cv_drain);
368 		}
369 		crd->is_write = 0;
370 	}
371 	if (crd->is_uref) {
372 		crd->is_uref = 0;
373 		if (--(cpd->udev->refcount) == 0)
374 			cv_broadcast(&cpd->udev->ref_cv);
375 	}
376 	mtx_unlock(&usb_ref_lock);
377 }
378 
379 static struct usb_fifo *
usb_fifo_alloc(struct mtx * mtx)380 usb_fifo_alloc(struct mtx *mtx)
381 {
382 	struct usb_fifo *f;
383 
384 	f = malloc(sizeof(*f), M_USBDEV, M_WAITOK | M_ZERO);
385 	cv_init(&f->cv_io, "FIFO-IO");
386 	cv_init(&f->cv_drain, "FIFO-DRAIN");
387 	sx_init(&f->fs_fastpath_lock, "FIFO-FP");
388 	f->priv_mtx = mtx;
389 	f->refcount = 1;
390 	knlist_init_mtx(&f->selinfo.si_note, mtx);
391 	return (f);
392 }
393 
394 /*------------------------------------------------------------------------*
395  *	usb_fifo_create
396  *------------------------------------------------------------------------*/
397 static int
usb_fifo_create(struct usb_cdev_privdata * cpd,struct usb_cdev_refdata * crd)398 usb_fifo_create(struct usb_cdev_privdata *cpd,
399     struct usb_cdev_refdata *crd)
400 {
401 	struct usb_device *udev = cpd->udev;
402 	struct usb_fifo *f;
403 	struct usb_endpoint *ep;
404 	uint8_t n;
405 	uint8_t is_tx;
406 	uint8_t is_rx;
407 	uint8_t no_null;
408 	uint8_t is_busy;
409 	int e = cpd->ep_addr;
410 
411 	is_tx = (cpd->fflags & FWRITE) ? 1 : 0;
412 	is_rx = (cpd->fflags & FREAD) ? 1 : 0;
413 	no_null = 1;
414 	is_busy = 0;
415 
416 	/* Preallocated FIFO */
417 	if (e < 0) {
418 		DPRINTFN(5, "Preallocated FIFO\n");
419 		if (is_tx) {
420 			f = udev->fifo[cpd->fifo_index + USB_FIFO_TX];
421 			if (f == NULL)
422 				return (EINVAL);
423 			crd->txfifo = f;
424 		}
425 		if (is_rx) {
426 			f = udev->fifo[cpd->fifo_index + USB_FIFO_RX];
427 			if (f == NULL)
428 				return (EINVAL);
429 			crd->rxfifo = f;
430 		}
431 		return (0);
432 	}
433 
434 	KASSERT(e >= 0 && e <= 15, ("endpoint %d out of range", e));
435 
436 	/* search for a free FIFO slot */
437 	DPRINTFN(5, "Endpoint device, searching for 0x%02x\n", e);
438 	for (n = 0;; n += 2) {
439 		if (n == USB_FIFO_MAX) {
440 			if (no_null) {
441 				no_null = 0;
442 				n = 0;
443 			} else {
444 				/* end of FIFOs reached */
445 				DPRINTFN(5, "out of FIFOs\n");
446 				return (ENOMEM);
447 			}
448 		}
449 		/* Check for TX FIFO */
450 		if (is_tx) {
451 			f = udev->fifo[n + USB_FIFO_TX];
452 			if (f != NULL) {
453 				if (f->dev_ep_index != e) {
454 					/* wrong endpoint index */
455 					continue;
456 				}
457 				if (f->curr_cpd != NULL) {
458 					/* FIFO is opened */
459 					is_busy = 1;
460 					continue;
461 				}
462 			} else if (no_null) {
463 				continue;
464 			}
465 		}
466 		/* Check for RX FIFO */
467 		if (is_rx) {
468 			f = udev->fifo[n + USB_FIFO_RX];
469 			if (f != NULL) {
470 				if (f->dev_ep_index != e) {
471 					/* wrong endpoint index */
472 					continue;
473 				}
474 				if (f->curr_cpd != NULL) {
475 					/* FIFO is opened */
476 					is_busy = 1;
477 					continue;
478 				}
479 			} else if (no_null) {
480 				continue;
481 			}
482 		}
483 		break;
484 	}
485 
486 	if (no_null == 0) {
487 		if (e >= (USB_EP_MAX / 2)) {
488 			/* we don't create any endpoints in this range */
489 			DPRINTFN(5, "ep out of range\n");
490 			return (is_busy ? EBUSY : EINVAL);
491 		}
492 	}
493 
494 	if ((e != 0) && is_busy) {
495 		/*
496 		 * Only the default control endpoint is allowed to be
497 		 * opened multiple times!
498 		 */
499 		DPRINTFN(5, "busy\n");
500 		return (EBUSY);
501 	}
502 
503 	/* Check TX FIFO */
504 	if (is_tx &&
505 	    (udev->fifo[n + USB_FIFO_TX] == NULL)) {
506 		ep = usb_dev_get_ep(udev, e, USB_FIFO_TX);
507 		DPRINTFN(5, "dev_get_endpoint(%d, 0x%x)\n", e, USB_FIFO_TX);
508 		if (ep == NULL) {
509 			DPRINTFN(5, "dev_get_endpoint returned NULL\n");
510 			return (EINVAL);
511 		}
512 		f = usb_fifo_alloc(&udev->device_mtx);
513 		if (f == NULL) {
514 			DPRINTFN(5, "could not alloc tx fifo\n");
515 			return (ENOMEM);
516 		}
517 		/* update some fields */
518 		f->fifo_index = n + USB_FIFO_TX;
519 		f->dev_ep_index = e;
520 		f->priv_sc0 = ep;
521 		f->methods = &usb_ugen_methods;
522 		f->iface_index = ep->iface_index;
523 		f->udev = udev;
524 		mtx_lock(&usb_ref_lock);
525 		udev->fifo[n + USB_FIFO_TX] = f;
526 		mtx_unlock(&usb_ref_lock);
527 	}
528 	/* Check RX FIFO */
529 	if (is_rx &&
530 	    (udev->fifo[n + USB_FIFO_RX] == NULL)) {
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_mtx);
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 		mtx_lock(&usb_ref_lock);
550 		udev->fifo[n + USB_FIFO_RX] = f;
551 		mtx_unlock(&usb_ref_lock);
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
usb_fifo_free(struct usb_fifo * f)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 	mtx_lock(&usb_ref_lock);
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 		mtx_unlock(&usb_ref_lock);	/* avoid LOR */
600 		mtx_lock(f->priv_mtx);
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 		mtx_unlock(f->priv_mtx);
609 		mtx_lock(&usb_ref_lock);
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 	mtx_unlock(&usb_ref_lock);
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 	sx_destroy(&f->fs_fastpath_lock);
629 
630 	knlist_clear(&f->selinfo.si_note, 0);
631 	seldrain(&f->selinfo);
632 	knlist_destroy(&f->selinfo.si_note);
633 
634 	free(f, M_USBDEV);
635 }
636 
637 static struct usb_endpoint *
usb_dev_get_ep(struct usb_device * udev,uint8_t ep_index,uint8_t dir)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
usb_fifo_open(struct usb_cdev_privdata * cpd,struct usb_fifo * f,int fflags)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 	mtx_lock(f->priv_mtx);
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 	mtx_lock(&usb_ref_lock);
737 	/* flag the fifo as opened to prevent others */
738 	f->curr_cpd = cpd;
739 	mtx_unlock(&usb_ref_lock);
740 
741 	/* reset queue */
742 	usb_fifo_reset(f);
743 
744 	mtx_unlock(f->priv_mtx);
745 done:
746 	return (err);
747 }
748 
749 /*------------------------------------------------------------------------*
750  *	usb_fifo_reset
751  *------------------------------------------------------------------------*/
752 void
usb_fifo_reset(struct usb_fifo * f)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
usb_fifo_close(struct usb_fifo * f,int fflags)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 	mtx_lock(f->priv_mtx);
786 
787 	/* clear current cdev private data pointer */
788 	mtx_lock(&usb_ref_lock);
789 	f->curr_cpd = NULL;
790 	mtx_unlock(&usb_ref_lock);
791 
792 	/* check if we are watched by kevent */
793 	KNOTE_LOCKED(&f->selinfo.si_note, 0);
794 
795 	/* check if we are selected */
796 	if (f->flag_isselect) {
797 		selwakeup(&f->selinfo);
798 		f->flag_isselect = 0;
799 	}
800 	/* check if a thread wants SIGIO */
801 	if (f->async_p != NULL) {
802 		PROC_LOCK(f->async_p);
803 		kern_psignal(f->async_p, SIGIO);
804 		PROC_UNLOCK(f->async_p);
805 		f->async_p = NULL;
806 	}
807 	/* remove FWRITE and FREAD flags */
808 	fflags &= ~(FWRITE | FREAD);
809 
810 	/* flush written data, if any */
811 	if ((f->fifo_index & 1) == USB_FIFO_TX) {
812 		if (!f->flag_iserror) {
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_timedwait_sig(&f->cv_io, f->priv_mtx,
835 				    USB_MS_TO_TICKS(USB_DEFAULT_TIMEOUT));
836 				if (err) {
837 					DPRINTF("signal received\n");
838 					break;
839 				}
840 			}
841 		}
842 		fflags |= FWRITE;
843 
844 		/* stop write transfer, if not already stopped */
845 		(f->methods->f_stop_write) (f);
846 	} else {
847 		fflags |= FREAD;
848 
849 		/* stop write transfer, if not already stopped */
850 		(f->methods->f_stop_read) (f);
851 	}
852 
853 	/* check if we are sleeping */
854 	if (f->flag_sleeping) {
855 		DPRINTFN(2, "Sleeping at close!\n");
856 	}
857 	mtx_unlock(f->priv_mtx);
858 
859 	/* call close method */
860 	(f->methods->f_close) (f, fflags);
861 
862 	DPRINTF("closed\n");
863 }
864 
865 /*------------------------------------------------------------------------*
866  *	usb_open - cdev callback
867  *------------------------------------------------------------------------*/
868 static int
usb_open(struct cdev * dev,int fflags,int devtype,struct thread * td)869 usb_open(struct cdev *dev, int fflags, int devtype, struct thread *td)
870 {
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;
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 = malloc(sizeof(*cpd), M_USBDEV, M_WAITOK | M_ZERO);
886 
887 	usb_loc_fill(pd, cpd);
888 	err = usb_ref_device(cpd, &refs, 1);
889 	if (err) {
890 		DPRINTFN(2, "cannot ref device\n");
891 		free(cpd, M_USBDEV);
892 		return (ENXIO);
893 	}
894 	cpd->fflags = fflags;	/* access mode for open lifetime */
895 
896 	/* create FIFOs, if any */
897 	err = usb_fifo_create(cpd, &refs);
898 	/* check for error */
899 	if (err) {
900 		DPRINTFN(2, "cannot create fifo\n");
901 		usb_unref_device(cpd, &refs);
902 		free(cpd, M_USBDEV);
903 		return (err);
904 	}
905 	if (fflags & FREAD) {
906 		err = usb_fifo_open(cpd, refs.rxfifo, fflags);
907 		if (err) {
908 			DPRINTFN(2, "read open failed\n");
909 			usb_unref_device(cpd, &refs);
910 			free(cpd, M_USBDEV);
911 			return (err);
912 		}
913 	}
914 	if (fflags & FWRITE) {
915 		err = usb_fifo_open(cpd, refs.txfifo, fflags);
916 		if (err) {
917 			DPRINTFN(2, "write open failed\n");
918 			if (fflags & FREAD) {
919 				usb_fifo_close(refs.rxfifo, fflags);
920 			}
921 			usb_unref_device(cpd, &refs);
922 			free(cpd, M_USBDEV);
923 			return (err);
924 		}
925 	}
926 	usb_unref_device(cpd, &refs);
927 	devfs_set_cdevpriv(cpd, usb_close);
928 
929 	return (0);
930 }
931 
932 /*------------------------------------------------------------------------*
933  *	usb_close - cdev callback
934  *------------------------------------------------------------------------*/
935 static void
usb_close(void * arg)936 usb_close(void *arg)
937 {
938 	struct usb_cdev_refdata refs;
939 	struct usb_cdev_privdata *cpd = arg;
940 	int err;
941 
942 	DPRINTFN(2, "cpd=%p\n", cpd);
943 
944 	err = usb_ref_device(cpd, &refs,
945 	    2 /* uref and allow detached state */);
946 	if (err) {
947 		DPRINTFN(2, "Cannot grab USB reference when "
948 		    "closing USB file handle\n");
949 		goto done;
950 	}
951 	if (cpd->fflags & FREAD) {
952 		usb_fifo_close(refs.rxfifo, cpd->fflags);
953 	}
954 	if (cpd->fflags & FWRITE) {
955 		usb_fifo_close(refs.txfifo, cpd->fflags);
956 	}
957 	usb_unref_device(cpd, &refs);
958 done:
959 	free(cpd, M_USBDEV);
960 }
961 
962 static void
usb_dev_init(void * arg)963 usb_dev_init(void *arg)
964 {
965 	mtx_init(&usb_ref_lock, "USB ref mutex", NULL, MTX_DEF);
966 	sx_init(&usb_sym_lock, "USB sym mutex");
967 	TAILQ_INIT(&usb_sym_head);
968 
969 	/* check the UGEN methods */
970 	usb_fifo_check_methods(&usb_ugen_methods);
971 }
972 
973 SYSINIT(usb_dev_init, SI_SUB_KLD, SI_ORDER_FIRST, usb_dev_init, NULL);
974 
975 static void
usb_dev_init_post(void * arg)976 usb_dev_init_post(void *arg)
977 {
978 	/*
979 	 * Create /dev/usb - this is needed for usbconfig(8), which
980 	 * needs a well-known device name to access.
981 	 */
982 	usb_dev = make_dev(&usb_static_devsw, 0, UID_ROOT, GID_OPERATOR,
983 	    0644, USB_DEVICE_NAME);
984 	if (usb_dev == NULL) {
985 		DPRINTFN(0, "Could not create usb bus device\n");
986 	}
987 }
988 
989 SYSINIT(usb_dev_init_post, SI_SUB_KICK_SCHEDULER, SI_ORDER_FIRST, usb_dev_init_post, NULL);
990 
991 static void
usb_dev_uninit(void * arg)992 usb_dev_uninit(void *arg)
993 {
994 	if (usb_dev != NULL) {
995 		destroy_dev(usb_dev);
996 		usb_dev = NULL;
997 	}
998 	mtx_destroy(&usb_ref_lock);
999 	sx_destroy(&usb_sym_lock);
1000 }
1001 
1002 SYSUNINIT(usb_dev_uninit, SI_SUB_KICK_SCHEDULER, SI_ORDER_ANY, usb_dev_uninit, NULL);
1003 
1004 static int
usb_ioctl_f_sub(struct usb_fifo * f,u_long cmd,void * addr,struct thread * td)1005 usb_ioctl_f_sub(struct usb_fifo *f, u_long cmd, void *addr,
1006     struct thread *td)
1007 {
1008 	int error = 0;
1009 
1010 	switch (cmd) {
1011 	case FIODTYPE:
1012 		*(int *)addr = 0;	/* character device */
1013 		break;
1014 
1015 	case FIONBIO:
1016 		/* handled by upper FS layer */
1017 		break;
1018 
1019 	case FIOASYNC:
1020 		if (*(int *)addr) {
1021 			if (f->async_p != NULL) {
1022 				error = EBUSY;
1023 				break;
1024 			}
1025 			f->async_p = USB_TD_GET_PROC(td);
1026 		} else {
1027 			f->async_p = NULL;
1028 		}
1029 		break;
1030 
1031 		/* XXX this is not the most general solution */
1032 	case TIOCSPGRP:
1033 		if (f->async_p == NULL) {
1034 			error = EINVAL;
1035 			break;
1036 		}
1037 		if (*(int *)addr != USB_PROC_GET_GID(f->async_p)) {
1038 			error = EPERM;
1039 			break;
1040 		}
1041 		break;
1042 	default:
1043 		return (ENOIOCTL);
1044 	}
1045 	DPRINTFN(3, "cmd 0x%lx = %d\n", cmd, error);
1046 	return (error);
1047 }
1048 
1049 /*------------------------------------------------------------------------*
1050  *	usb_ioctl - cdev callback
1051  *------------------------------------------------------------------------*/
1052 static int
usb_ioctl(struct cdev * dev,u_long cmd,caddr_t addr,int fflag,struct thread * td)1053 usb_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int fflag, struct thread* td)
1054 {
1055 	struct usb_cdev_refdata refs;
1056 	struct usb_cdev_privdata* cpd;
1057 	struct usb_fifo *f;
1058 	int fflags;
1059 	int err;
1060 
1061 	DPRINTFN(2, "cmd=0x%lx\n", cmd);
1062 
1063 	err = devfs_get_cdevpriv((void **)&cpd);
1064 	if (err != 0)
1065 		return (err);
1066 
1067 	/*
1068 	 * Performance optimisation: We try to check for IOCTL's that
1069 	 * don't need the USB reference first. Then we grab the USB
1070 	 * reference if we need it!
1071 	 */
1072 	err = usb_ref_device(cpd, &refs, 0 /* no uref */ );
1073 	if (err)
1074 		return (ENXIO);
1075 
1076 	fflags = cpd->fflags;
1077 
1078 	f = NULL;			/* set default value */
1079 	err = ENOIOCTL;			/* set default value */
1080 
1081 	if (fflags & FWRITE) {
1082 		f = refs.txfifo;
1083 		err = usb_ioctl_f_sub(f, cmd, addr, td);
1084 	}
1085 	if (fflags & FREAD) {
1086 		f = refs.rxfifo;
1087 		err = usb_ioctl_f_sub(f, cmd, addr, td);
1088 	}
1089 	KASSERT(f != NULL, ("fifo not found"));
1090 	if (err != ENOIOCTL)
1091 		goto done;
1092 
1093 	err = (f->methods->f_ioctl) (f, cmd, addr, fflags);
1094 
1095 	DPRINTFN(2, "f_ioctl cmd 0x%lx = %d\n", cmd, err);
1096 
1097 	if (err != ENOIOCTL)
1098 		goto done;
1099 
1100 	if (usb_usb_ref_device(cpd, &refs)) {
1101 		/* we lost the reference */
1102 		return (ENXIO);
1103 	}
1104 
1105 	err = (f->methods->f_ioctl_post) (f, cmd, addr, fflags);
1106 
1107 	DPRINTFN(2, "f_ioctl_post cmd 0x%lx = %d\n", cmd, err);
1108 
1109 	if (err == ENOIOCTL)
1110 		err = ENOTTY;
1111 
1112 	if (err)
1113 		goto done;
1114 
1115 	/* Wait for re-enumeration, if any */
1116 
1117 	while (f->udev->re_enumerate_wait != USB_RE_ENUM_DONE) {
1118 		usb_unref_device(cpd, &refs);
1119 
1120 		usb_pause_mtx(NULL, hz / 128);
1121 
1122 		while (usb_ref_device(cpd, &refs, 1 /* need uref */)) {
1123 			if (usb_ref_device(cpd, &refs, 0)) {
1124 				/* device no longer exists */
1125 				return (ENXIO);
1126 			}
1127 			usb_unref_device(cpd, &refs);
1128 			usb_pause_mtx(NULL, hz / 128);
1129 		}
1130 	}
1131 
1132 done:
1133 	usb_unref_device(cpd, &refs);
1134 	return (err);
1135 }
1136 
1137 static void
usb_filter_detach(struct knote * kn)1138 usb_filter_detach(struct knote *kn)
1139 {
1140 	struct usb_fifo *f = kn->kn_hook;
1141 	knlist_remove(&f->selinfo.si_note, kn, 0);
1142 }
1143 
1144 static int
usb_filter_write(struct knote * kn,long hint)1145 usb_filter_write(struct knote *kn, long hint)
1146 {
1147 	struct usb_cdev_privdata* cpd;
1148 	struct usb_fifo *f;
1149 	struct usb_mbuf *m;
1150 
1151 	DPRINTFN(2, "\n");
1152 
1153 	f = kn->kn_hook;
1154 
1155 	USB_MTX_ASSERT(f->priv_mtx, MA_OWNED);
1156 
1157 	cpd = f->curr_cpd;
1158 	if (cpd == NULL) {
1159 		m = (void *)1;
1160 	} else if (f->fs_ep_max == 0) {
1161 		if (f->flag_iserror) {
1162 			/* we got an error */
1163 			m = (void *)1;
1164 		} else {
1165 			if (f->queue_data == NULL) {
1166 				/*
1167 				 * start write transfer, if not
1168 				 * already started
1169 				 */
1170 				(f->methods->f_start_write) (f);
1171 			}
1172 			/* check if any packets are available */
1173 			USB_IF_POLL(&f->free_q, m);
1174 		}
1175 	} else {
1176 		if (f->flag_iscomplete) {
1177 			m = (void *)1;
1178 		} else {
1179 			m = NULL;
1180 		}
1181 	}
1182 	return (m ? 1 : 0);
1183 }
1184 
1185 static int
usb_filter_read(struct knote * kn,long hint)1186 usb_filter_read(struct knote *kn, long hint)
1187 {
1188 	struct usb_cdev_privdata* cpd;
1189 	struct usb_fifo *f;
1190 	struct usb_mbuf *m;
1191 
1192 	DPRINTFN(2, "\n");
1193 
1194 	f = kn->kn_hook;
1195 
1196 	USB_MTX_ASSERT(f->priv_mtx, MA_OWNED);
1197 
1198 	cpd = f->curr_cpd;
1199 	if (cpd == NULL) {
1200 		m = (void *)1;
1201 	} else if (f->fs_ep_max == 0) {
1202 		if (f->flag_iserror) {
1203 			/* we have an error */
1204 			m = (void *)1;
1205 		} else {
1206 			if (f->queue_data == NULL) {
1207 				/*
1208 				 * start read transfer, if not
1209 				 * already started
1210 				 */
1211 				(f->methods->f_start_read) (f);
1212 			}
1213 			/* check if any packets are available */
1214 			USB_IF_POLL(&f->used_q, m);
1215 
1216 			/* start reading data, if any */
1217 			if (m == NULL)
1218 				(f->methods->f_start_read) (f);
1219 		}
1220 	} else {
1221 		if (f->flag_iscomplete) {
1222 			m = (void *)1;
1223 		} else {
1224 			m = NULL;
1225 		}
1226 	}
1227 	return (m ? 1 : 0);
1228 }
1229 
1230 static const struct filterops usb_filtops_write = {
1231 	.f_isfd = 1,
1232 	.f_detach = usb_filter_detach,
1233 	.f_event = usb_filter_write,
1234 	.f_copy = knote_triv_copy,
1235 };
1236 
1237 static const struct filterops usb_filtops_read = {
1238 	.f_isfd = 1,
1239 	.f_detach = usb_filter_detach,
1240 	.f_event = usb_filter_read,
1241 	.f_copy = knote_triv_copy,
1242 };
1243 
1244 /* ARGSUSED */
1245 static int
usb_kqfilter(struct cdev * dev,struct knote * kn)1246 usb_kqfilter(struct cdev* dev, struct knote *kn)
1247 {
1248 	struct usb_cdev_refdata refs;
1249 	struct usb_cdev_privdata* cpd;
1250 	struct usb_fifo *f;
1251 	int fflags;
1252 	int err = EINVAL;
1253 
1254 	DPRINTFN(2, "\n");
1255 
1256 	if (devfs_get_cdevpriv((void **)&cpd) != 0 ||
1257 	    usb_ref_device(cpd, &refs, 0) != 0)
1258 		return (ENXIO);
1259 
1260 	fflags = cpd->fflags;
1261 
1262 	/* Figure out who needs service */
1263 	switch (kn->kn_filter) {
1264 	case EVFILT_WRITE:
1265 		if (fflags & FWRITE) {
1266 			f = refs.txfifo;
1267 			kn->kn_fop = &usb_filtops_write;
1268 			err = 0;
1269 		}
1270 		break;
1271 	case EVFILT_READ:
1272 		if (fflags & FREAD) {
1273 			f = refs.rxfifo;
1274 			kn->kn_fop = &usb_filtops_read;
1275 			err = 0;
1276 		}
1277 		break;
1278 	default:
1279 		err = EOPNOTSUPP;
1280 		break;
1281 	}
1282 
1283 	if (err == 0) {
1284 		kn->kn_hook = f;
1285 		mtx_lock(f->priv_mtx);
1286 		knlist_add(&f->selinfo.si_note, kn, 1);
1287 		mtx_unlock(f->priv_mtx);
1288 	}
1289 
1290 	usb_unref_device(cpd, &refs);
1291 	return (err);
1292 }
1293 
1294 /* ARGSUSED */
1295 static int
usb_poll(struct cdev * dev,int events,struct thread * td)1296 usb_poll(struct cdev* dev, int events, struct thread* td)
1297 {
1298 	struct usb_cdev_refdata refs;
1299 	struct usb_cdev_privdata* cpd;
1300 	struct usb_fifo *f;
1301 	struct usb_mbuf *m;
1302 	int fflags, revents;
1303 
1304 	if (devfs_get_cdevpriv((void **)&cpd) != 0 ||
1305 	    usb_ref_device(cpd, &refs, 0) != 0)
1306 		return (events &
1307 		    (POLLHUP|POLLIN|POLLRDNORM|POLLOUT|POLLWRNORM));
1308 
1309 	fflags = cpd->fflags;
1310 
1311 	/* Figure out who needs service */
1312 	revents = 0;
1313 	if ((events & (POLLOUT | POLLWRNORM)) &&
1314 	    (fflags & FWRITE)) {
1315 		f = refs.txfifo;
1316 
1317 		mtx_lock(f->priv_mtx);
1318 
1319 		if (!refs.is_usbfs) {
1320 			if (f->flag_iserror) {
1321 				/* we got an error */
1322 				m = (void *)1;
1323 			} else {
1324 				if (f->queue_data == NULL) {
1325 					/*
1326 					 * start write transfer, if not
1327 					 * already started
1328 					 */
1329 					(f->methods->f_start_write) (f);
1330 				}
1331 				/* check if any packets are available */
1332 				USB_IF_POLL(&f->free_q, m);
1333 			}
1334 		} else {
1335 			if (f->flag_iscomplete) {
1336 				m = (void *)1;
1337 			} else {
1338 				m = NULL;
1339 			}
1340 		}
1341 
1342 		if (m) {
1343 			revents |= events & (POLLOUT | POLLWRNORM);
1344 		} else {
1345 			f->flag_isselect = 1;
1346 			selrecord(td, &f->selinfo);
1347 		}
1348 
1349 		mtx_unlock(f->priv_mtx);
1350 	}
1351 	if ((events & (POLLIN | POLLRDNORM)) &&
1352 	    (fflags & FREAD)) {
1353 		f = refs.rxfifo;
1354 
1355 		mtx_lock(f->priv_mtx);
1356 
1357 		if (!refs.is_usbfs) {
1358 			if (f->flag_iserror) {
1359 				/* we have an error */
1360 				m = (void *)1;
1361 			} else {
1362 				if (f->queue_data == NULL) {
1363 					/*
1364 					 * start read transfer, if not
1365 					 * already started
1366 					 */
1367 					(f->methods->f_start_read) (f);
1368 				}
1369 				/* check if any packets are available */
1370 				USB_IF_POLL(&f->used_q, m);
1371 			}
1372 		} else {
1373 			if (f->flag_iscomplete) {
1374 				m = (void *)1;
1375 			} else {
1376 				m = NULL;
1377 			}
1378 		}
1379 
1380 		if (m) {
1381 			revents |= events & (POLLIN | POLLRDNORM);
1382 		} else {
1383 			f->flag_isselect = 1;
1384 			selrecord(td, &f->selinfo);
1385 
1386 			if (!refs.is_usbfs) {
1387 				/* start reading data */
1388 				(f->methods->f_start_read) (f);
1389 			}
1390 		}
1391 
1392 		mtx_unlock(f->priv_mtx);
1393 	}
1394 	usb_unref_device(cpd, &refs);
1395 	return (revents);
1396 }
1397 
1398 static int
usb_read(struct cdev * dev,struct uio * uio,int ioflag)1399 usb_read(struct cdev *dev, struct uio *uio, int ioflag)
1400 {
1401 	struct usb_cdev_refdata refs;
1402 	struct usb_cdev_privdata* cpd;
1403 	struct usb_fifo *f;
1404 	struct usb_mbuf *m;
1405 	int io_len;
1406 	int err;
1407 	uint8_t tr_data = 0;
1408 
1409 	err = devfs_get_cdevpriv((void **)&cpd);
1410 	if (err != 0)
1411 		return (err);
1412 
1413 	err = usb_ref_device(cpd, &refs, 0 /* no uref */ );
1414 	if (err)
1415 		return (ENXIO);
1416 
1417 	f = refs.rxfifo;
1418 	if (f == NULL) {
1419 		/* should not happen */
1420 		usb_unref_device(cpd, &refs);
1421 		return (EPERM);
1422 	}
1423 
1424 	mtx_lock(f->priv_mtx);
1425 
1426 	/* check for permanent read error */
1427 	if (f->flag_iserror) {
1428 		err = EIO;
1429 		goto done;
1430 	}
1431 	/* check if USB-FS interface is active */
1432 	if (refs.is_usbfs) {
1433 		/*
1434 		 * The queue is used for events that should be
1435 		 * retrieved using the "USB_FS_COMPLETE" ioctl.
1436 		 */
1437 		err = EINVAL;
1438 		goto done;
1439 	}
1440 	while (uio->uio_resid > 0) {
1441 		USB_IF_DEQUEUE(&f->used_q, m);
1442 
1443 		if (m == NULL) {
1444 			/* start read transfer, if not already started */
1445 
1446 			(f->methods->f_start_read) (f);
1447 
1448 			if (ioflag & IO_NDELAY) {
1449 				if (tr_data) {
1450 					/* return length before error */
1451 					break;
1452 				}
1453 				err = EWOULDBLOCK;
1454 				break;
1455 			}
1456 			DPRINTF("sleeping\n");
1457 
1458 			err = usb_fifo_wait(f);
1459 			if (err) {
1460 				break;
1461 			}
1462 			continue;
1463 		}
1464 		if (f->methods->f_filter_read) {
1465 			/*
1466 			 * Sometimes it is convenient to process data at the
1467 			 * expense of a userland process instead of a kernel
1468 			 * process.
1469 			 */
1470 			(f->methods->f_filter_read) (f, m);
1471 		}
1472 		tr_data = 1;
1473 
1474 		io_len = MIN(m->cur_data_len, uio->uio_resid);
1475 
1476 		DPRINTFN(2, "transfer %d bytes from %p\n",
1477 		    io_len, m->cur_data_ptr);
1478 
1479 		err = usb_fifo_uiomove(f,
1480 		    m->cur_data_ptr, io_len, uio);
1481 
1482 		m->cur_data_len -= io_len;
1483 		m->cur_data_ptr += io_len;
1484 
1485 		if (m->cur_data_len == 0) {
1486 			uint8_t last_packet;
1487 
1488 			last_packet = m->last_packet;
1489 
1490 			USB_IF_ENQUEUE(&f->free_q, m);
1491 
1492 			if (last_packet) {
1493 				/* keep framing */
1494 				break;
1495 			}
1496 		} else {
1497 			USB_IF_PREPEND(&f->used_q, m);
1498 		}
1499 
1500 		if (err) {
1501 			break;
1502 		}
1503 	}
1504 done:
1505 	mtx_unlock(f->priv_mtx);
1506 
1507 	usb_unref_device(cpd, &refs);
1508 
1509 	return (err);
1510 }
1511 
1512 static int
usb_write(struct cdev * dev,struct uio * uio,int ioflag)1513 usb_write(struct cdev *dev, struct uio *uio, int ioflag)
1514 {
1515 	struct usb_cdev_refdata refs;
1516 	struct usb_cdev_privdata* cpd;
1517 	struct usb_fifo *f;
1518 	struct usb_mbuf *m;
1519 	uint8_t *pdata;
1520 	int io_len;
1521 	int err;
1522 	uint8_t tr_data = 0;
1523 
1524 	DPRINTFN(2, "\n");
1525 
1526 	err = devfs_get_cdevpriv((void **)&cpd);
1527 	if (err != 0)
1528 		return (err);
1529 
1530 	err = usb_ref_device(cpd, &refs, 0 /* no uref */ );
1531 	if (err)
1532 		return (ENXIO);
1533 
1534 	f = refs.txfifo;
1535 	if (f == NULL) {
1536 		/* should not happen */
1537 		usb_unref_device(cpd, &refs);
1538 		return (EPERM);
1539 	}
1540 
1541 	mtx_lock(f->priv_mtx);
1542 
1543 	/* check for permanent write error */
1544 	if (f->flag_iserror) {
1545 		err = EIO;
1546 		goto done;
1547 	}
1548 	/* check if USB-FS interface is active */
1549 	if (refs.is_usbfs) {
1550 		/*
1551 		 * The queue is used for events that should be
1552 		 * retrieved using the "USB_FS_COMPLETE" ioctl.
1553 		 */
1554 		err = EINVAL;
1555 		goto done;
1556 	}
1557 	if (f->queue_data == NULL) {
1558 		/* start write transfer, if not already started */
1559 		(f->methods->f_start_write) (f);
1560 	}
1561 	/* we allow writing zero length data */
1562 	do {
1563 		USB_IF_DEQUEUE(&f->free_q, m);
1564 
1565 		if (m == NULL) {
1566 			if (ioflag & IO_NDELAY) {
1567 				if (tr_data) {
1568 					/* return length before error */
1569 					break;
1570 				}
1571 				err = EWOULDBLOCK;
1572 				break;
1573 			}
1574 			DPRINTF("sleeping\n");
1575 
1576 			err = usb_fifo_wait(f);
1577 			if (err) {
1578 				break;
1579 			}
1580 			continue;
1581 		}
1582 		tr_data = 1;
1583 
1584 		if (f->flag_have_fragment == 0) {
1585 			USB_MBUF_RESET(m);
1586 			io_len = m->cur_data_len;
1587 			pdata = m->cur_data_ptr;
1588 			if (io_len > uio->uio_resid)
1589 				io_len = uio->uio_resid;
1590 			m->cur_data_len = io_len;
1591 		} else {
1592 			io_len = m->max_data_len - m->cur_data_len;
1593 			pdata = m->cur_data_ptr + m->cur_data_len;
1594 			if (io_len > uio->uio_resid)
1595 				io_len = uio->uio_resid;
1596 			m->cur_data_len += io_len;
1597 		}
1598 
1599 		DPRINTFN(2, "transfer %d bytes to %p\n",
1600 		    io_len, pdata);
1601 
1602 		err = usb_fifo_uiomove(f, pdata, io_len, uio);
1603 
1604 		if (err) {
1605 			f->flag_have_fragment = 0;
1606 			USB_IF_ENQUEUE(&f->free_q, m);
1607 			break;
1608 		}
1609 
1610 		/* check if the buffer is ready to be transmitted */
1611 
1612 		if ((f->flag_write_defrag == 0) ||
1613 		    (m->cur_data_len == m->max_data_len)) {
1614 			f->flag_have_fragment = 0;
1615 
1616 			/*
1617 			 * Check for write filter:
1618 			 *
1619 			 * Sometimes it is convenient to process data
1620 			 * at the expense of a userland process
1621 			 * instead of a kernel process.
1622 			 */
1623 			if (f->methods->f_filter_write) {
1624 				(f->methods->f_filter_write) (f, m);
1625 			}
1626 
1627 			/* Put USB mbuf in the used queue */
1628 			USB_IF_ENQUEUE(&f->used_q, m);
1629 
1630 			/* Start writing data, if not already started */
1631 			(f->methods->f_start_write) (f);
1632 		} else {
1633 			/* Wait for more data or close */
1634 			f->flag_have_fragment = 1;
1635 			USB_IF_PREPEND(&f->free_q, m);
1636 		}
1637 
1638 	} while (uio->uio_resid > 0);
1639 done:
1640 	mtx_unlock(f->priv_mtx);
1641 
1642 	usb_unref_device(cpd, &refs);
1643 
1644 	return (err);
1645 }
1646 
1647 int
usb_static_ioctl(struct cdev * dev,u_long cmd,caddr_t data,int fflag,struct thread * td)1648 usb_static_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
1649     struct thread *td)
1650 {
1651 	union {
1652 		struct usb_read_dir *urd;
1653 #ifdef COMPAT_FREEBSD32
1654 		struct usb_read_dir32 *urd32;
1655 #endif
1656 		void* data;
1657 	} u;
1658 	int err;
1659 
1660 	u.data = data;
1661 	switch (cmd) {
1662 		case USB_READ_DIR:
1663 			err = usb_read_symlink(u.urd->urd_data,
1664 			    u.urd->urd_startentry, u.urd->urd_maxlen);
1665 			break;
1666 #ifdef COMPAT_FREEBSD32
1667 		case USB_READ_DIR32:
1668 			err = usb_read_symlink(PTRIN(u.urd32->urd_data),
1669 			    u.urd32->urd_startentry, u.urd32->urd_maxlen);
1670 			break;
1671 #endif
1672 		case USB_DEV_QUIRK_GET:
1673 		case USB_QUIRK_NAME_GET:
1674 		case USB_DEV_QUIRK_ADD:
1675 		case USB_DEV_QUIRK_REMOVE:
1676 			err = usb_quirk_ioctl_p(cmd, data, fflag, td);
1677 			break;
1678 		case USB_GET_TEMPLATE:
1679 			*(int *)data = usb_template;
1680 			err = 0;
1681 			break;
1682 		case USB_SET_TEMPLATE:
1683 			err = priv_check(curthread, PRIV_DRIVER);
1684 			if (err)
1685 				break;
1686 			usb_template = *(int *)data;
1687 			break;
1688 		default:
1689 			err = ENOTTY;
1690 			break;
1691 	}
1692 	return (err);
1693 }
1694 
1695 static int
usb_fifo_uiomove(struct usb_fifo * f,void * cp,int n,struct uio * uio)1696 usb_fifo_uiomove(struct usb_fifo *f, void *cp,
1697     int n, struct uio *uio)
1698 {
1699 	int error;
1700 
1701 	mtx_unlock(f->priv_mtx);
1702 
1703 	/*
1704 	 * "uiomove()" can sleep so one needs to make a wrapper,
1705 	 * exiting the mutex and checking things:
1706 	 */
1707 	error = uiomove(cp, n, uio);
1708 
1709 	mtx_lock(f->priv_mtx);
1710 
1711 	return (error);
1712 }
1713 
1714 int
usb_fifo_wait(struct usb_fifo * f)1715 usb_fifo_wait(struct usb_fifo *f)
1716 {
1717 	int err;
1718 
1719 	USB_MTX_ASSERT(f->priv_mtx, MA_OWNED);
1720 
1721 	if (f->flag_iserror) {
1722 		/* we are gone */
1723 		return (EIO);
1724 	}
1725 	f->flag_sleeping = 1;
1726 
1727 	err = cv_wait_sig(&f->cv_io, f->priv_mtx);
1728 
1729 	if (f->flag_iserror) {
1730 		/* we are gone */
1731 		err = EIO;
1732 	}
1733 	return (err);
1734 }
1735 
1736 void
usb_fifo_signal(struct usb_fifo * f)1737 usb_fifo_signal(struct usb_fifo *f)
1738 {
1739 	if (f->flag_sleeping) {
1740 		f->flag_sleeping = 0;
1741 		cv_broadcast(&f->cv_io);
1742 	}
1743 }
1744 
1745 void
usb_fifo_wakeup(struct usb_fifo * f)1746 usb_fifo_wakeup(struct usb_fifo *f)
1747 {
1748 	usb_fifo_signal(f);
1749 
1750 	KNOTE_LOCKED(&f->selinfo.si_note, 0);
1751 
1752 	if (f->flag_isselect) {
1753 		selwakeup(&f->selinfo);
1754 		f->flag_isselect = 0;
1755 	}
1756 	if (f->async_p != NULL) {
1757 		PROC_LOCK(f->async_p);
1758 		kern_psignal(f->async_p, SIGIO);
1759 		PROC_UNLOCK(f->async_p);
1760 	}
1761 }
1762 
1763 static int
usb_fifo_dummy_open(struct usb_fifo * fifo,int fflags)1764 usb_fifo_dummy_open(struct usb_fifo *fifo, int fflags)
1765 {
1766 	return (0);
1767 }
1768 
1769 static void
usb_fifo_dummy_close(struct usb_fifo * fifo,int fflags)1770 usb_fifo_dummy_close(struct usb_fifo *fifo, int fflags)
1771 {
1772 	return;
1773 }
1774 
1775 static int
usb_fifo_dummy_ioctl(struct usb_fifo * fifo,u_long cmd,void * addr,int fflags)1776 usb_fifo_dummy_ioctl(struct usb_fifo *fifo, u_long cmd, void *addr, int fflags)
1777 {
1778 	return (ENOIOCTL);
1779 }
1780 
1781 static void
usb_fifo_dummy_cmd(struct usb_fifo * fifo)1782 usb_fifo_dummy_cmd(struct usb_fifo *fifo)
1783 {
1784 	fifo->flag_flushing = 0;	/* not flushing */
1785 }
1786 
1787 static void
usb_fifo_check_methods(struct usb_fifo_methods * pm)1788 usb_fifo_check_methods(struct usb_fifo_methods *pm)
1789 {
1790 	/* check that all callback functions are OK */
1791 
1792 	if (pm->f_open == NULL)
1793 		pm->f_open = &usb_fifo_dummy_open;
1794 
1795 	if (pm->f_close == NULL)
1796 		pm->f_close = &usb_fifo_dummy_close;
1797 
1798 	if (pm->f_ioctl == NULL)
1799 		pm->f_ioctl = &usb_fifo_dummy_ioctl;
1800 
1801 	if (pm->f_ioctl_post == NULL)
1802 		pm->f_ioctl_post = &usb_fifo_dummy_ioctl;
1803 
1804 	if (pm->f_start_read == NULL)
1805 		pm->f_start_read = &usb_fifo_dummy_cmd;
1806 
1807 	if (pm->f_stop_read == NULL)
1808 		pm->f_stop_read = &usb_fifo_dummy_cmd;
1809 
1810 	if (pm->f_start_write == NULL)
1811 		pm->f_start_write = &usb_fifo_dummy_cmd;
1812 
1813 	if (pm->f_stop_write == NULL)
1814 		pm->f_stop_write = &usb_fifo_dummy_cmd;
1815 }
1816 
1817 /*------------------------------------------------------------------------*
1818  *	usb_fifo_attach
1819  *
1820  * The following function will create a duplex FIFO.
1821  *
1822  * Return values:
1823  * 0: Success.
1824  * Else: Failure.
1825  *------------------------------------------------------------------------*/
1826 int
usb_fifo_attach(struct usb_device * udev,void * priv_sc,struct mtx * priv_mtx,struct usb_fifo_methods * pm,struct usb_fifo_sc * f_sc,uint16_t unit,int16_t subunit,uint8_t iface_index,uid_t uid,gid_t gid,int mode)1827 usb_fifo_attach(struct usb_device *udev, void *priv_sc,
1828     struct mtx *priv_mtx, struct usb_fifo_methods *pm,
1829     struct usb_fifo_sc *f_sc, uint16_t unit, int16_t subunit,
1830     uint8_t iface_index, uid_t uid, gid_t gid, int mode)
1831 {
1832 	struct usb_fifo *f_tx;
1833 	struct usb_fifo *f_rx;
1834 	char devname[32];
1835 	uint8_t n;
1836 
1837 	f_sc->fp[USB_FIFO_TX] = NULL;
1838 	f_sc->fp[USB_FIFO_RX] = NULL;
1839 
1840 	if (pm == NULL)
1841 		return (EINVAL);
1842 
1843 	/* check the methods */
1844 	usb_fifo_check_methods(pm);
1845 
1846 	if (priv_mtx == NULL)
1847 		priv_mtx = &Giant;
1848 
1849 	/* search for a free FIFO slot */
1850 	for (n = 0;; n += 2) {
1851 		if (n == USB_FIFO_MAX) {
1852 			/* end of FIFOs reached */
1853 			return (ENOMEM);
1854 		}
1855 		/* Check for TX FIFO */
1856 		if (udev->fifo[n + USB_FIFO_TX] != NULL) {
1857 			continue;
1858 		}
1859 		/* Check for RX FIFO */
1860 		if (udev->fifo[n + USB_FIFO_RX] != NULL) {
1861 			continue;
1862 		}
1863 		break;
1864 	}
1865 
1866 	f_tx = usb_fifo_alloc(priv_mtx);
1867 	f_rx = usb_fifo_alloc(priv_mtx);
1868 
1869 	if ((f_tx == NULL) || (f_rx == NULL)) {
1870 		usb_fifo_free(f_tx);
1871 		usb_fifo_free(f_rx);
1872 		return (ENOMEM);
1873 	}
1874 	/* initialise FIFO structures */
1875 
1876 	f_tx->fifo_index = n + USB_FIFO_TX;
1877 	f_tx->dev_ep_index = -1;
1878 	f_tx->priv_sc0 = priv_sc;
1879 	f_tx->methods = pm;
1880 	f_tx->iface_index = iface_index;
1881 	f_tx->udev = udev;
1882 
1883 	f_rx->fifo_index = n + USB_FIFO_RX;
1884 	f_rx->dev_ep_index = -1;
1885 	f_rx->priv_sc0 = priv_sc;
1886 	f_rx->methods = pm;
1887 	f_rx->iface_index = iface_index;
1888 	f_rx->udev = udev;
1889 
1890 	f_sc->fp[USB_FIFO_TX] = f_tx;
1891 	f_sc->fp[USB_FIFO_RX] = f_rx;
1892 
1893 	mtx_lock(&usb_ref_lock);
1894 	udev->fifo[f_tx->fifo_index] = f_tx;
1895 	udev->fifo[f_rx->fifo_index] = f_rx;
1896 	mtx_unlock(&usb_ref_lock);
1897 
1898 	for (n = 0; n != 4; n++) {
1899 		if (pm->basename[n] == NULL) {
1900 			continue;
1901 		}
1902 		if (subunit < 0) {
1903 			if (snprintf(devname, sizeof(devname),
1904 			    "%s%u%s", pm->basename[n],
1905 			    unit, pm->postfix[n] ?
1906 			    pm->postfix[n] : "")) {
1907 				/* ignore */
1908 			}
1909 		} else {
1910 			if (snprintf(devname, sizeof(devname),
1911 			    "%s%u.%d%s", pm->basename[n],
1912 			    unit, subunit, pm->postfix[n] ?
1913 			    pm->postfix[n] : "")) {
1914 				/* ignore */
1915 			}
1916 		}
1917 
1918 		/*
1919 		 * Distribute the symbolic links into two FIFO structures:
1920 		 */
1921 		if (n & 1) {
1922 			f_rx->symlink[n / 2] =
1923 			    usb_alloc_symlink(devname);
1924 		} else {
1925 			f_tx->symlink[n / 2] =
1926 			    usb_alloc_symlink(devname);
1927 		}
1928 
1929 		/* Create the device */
1930 		f_sc->dev = usb_make_dev(udev, devname, -1,
1931 		    f_tx->fifo_index & f_rx->fifo_index,
1932 		    FREAD|FWRITE, uid, gid, mode);
1933 	}
1934 
1935 	DPRINTFN(2, "attached %p/%p\n", f_tx, f_rx);
1936 	return (0);
1937 }
1938 
1939 /*------------------------------------------------------------------------*
1940  *	usb_fifo_alloc_buffer
1941  *
1942  * Return values:
1943  * 0: Success
1944  * Else failure
1945  *------------------------------------------------------------------------*/
1946 int
usb_fifo_alloc_buffer(struct usb_fifo * f,usb_size_t bufsize,uint16_t nbuf)1947 usb_fifo_alloc_buffer(struct usb_fifo *f, usb_size_t bufsize,
1948     uint16_t nbuf)
1949 {
1950 	struct usb_ifqueue temp_q = {};
1951 	void *queue_data;
1952 
1953 	usb_fifo_free_buffer(f);
1954 
1955 	temp_q.ifq_maxlen = nbuf;
1956 
1957 	queue_data = usb_alloc_mbufs(
1958 	    M_USBDEV, &temp_q, bufsize, nbuf);
1959 
1960 	if (queue_data == NULL && bufsize != 0 && nbuf != 0)
1961 		return (ENOMEM);
1962 
1963 	mtx_lock(f->priv_mtx);
1964 
1965 	/*
1966 	 * Setup queues and sizes under lock to avoid early use by
1967 	 * concurrent FIFO access:
1968 	 */
1969 	f->free_q = temp_q;
1970 	f->used_q.ifq_maxlen = nbuf;
1971 	f->queue_data = queue_data;
1972 	mtx_unlock(f->priv_mtx);
1973 
1974 	return (0);			/* success */
1975 }
1976 
1977 /*------------------------------------------------------------------------*
1978  *	usb_fifo_free_buffer
1979  *
1980  * This function will free the buffers associated with a FIFO. This
1981  * function can be called multiple times in a row.
1982  *------------------------------------------------------------------------*/
1983 void
usb_fifo_free_buffer(struct usb_fifo * f)1984 usb_fifo_free_buffer(struct usb_fifo *f)
1985 {
1986 	void *queue_data;
1987 
1988 	mtx_lock(f->priv_mtx);
1989 
1990 	/* Get and clear pointer to free, if any. */
1991 	queue_data = f->queue_data;
1992 	f->queue_data = NULL;
1993 
1994 	/*
1995 	 * Reset queues under lock to avoid use of freed buffers by
1996 	 * concurrent FIFO activity:
1997 	 */
1998 	memset(&f->free_q, 0, sizeof(f->free_q));
1999 	memset(&f->used_q, 0, sizeof(f->used_q));
2000 	mtx_unlock(f->priv_mtx);
2001 
2002 	/* Free old buffer, if any. */
2003 	free(queue_data, M_USBDEV);
2004 }
2005 
2006 void
usb_fifo_detach(struct usb_fifo_sc * f_sc)2007 usb_fifo_detach(struct usb_fifo_sc *f_sc)
2008 {
2009 	if (f_sc == NULL) {
2010 		return;
2011 	}
2012 	usb_fifo_free(f_sc->fp[USB_FIFO_TX]);
2013 	usb_fifo_free(f_sc->fp[USB_FIFO_RX]);
2014 
2015 	f_sc->fp[USB_FIFO_TX] = NULL;
2016 	f_sc->fp[USB_FIFO_RX] = NULL;
2017 
2018 	usb_destroy_dev(f_sc->dev);
2019 
2020 	f_sc->dev = NULL;
2021 
2022 	DPRINTFN(2, "detached %p\n", f_sc);
2023 }
2024 
2025 usb_size_t
usb_fifo_put_bytes_max(struct usb_fifo * f)2026 usb_fifo_put_bytes_max(struct usb_fifo *f)
2027 {
2028 	struct usb_mbuf *m;
2029 	usb_size_t len;
2030 
2031 	USB_IF_POLL(&f->free_q, m);
2032 
2033 	if (m) {
2034 		len = m->max_data_len;
2035 	} else {
2036 		len = 0;
2037 	}
2038 	return (len);
2039 }
2040 
2041 /*------------------------------------------------------------------------*
2042  *	usb_fifo_put_data
2043  *
2044  * what:
2045  *  0 - normal operation
2046  *  1 - set last packet flag to enforce framing
2047  *------------------------------------------------------------------------*/
2048 void
usb_fifo_put_data(struct usb_fifo * f,struct usb_page_cache * pc,usb_frlength_t offset,usb_frlength_t len,uint8_t what)2049 usb_fifo_put_data(struct usb_fifo *f, struct usb_page_cache *pc,
2050     usb_frlength_t offset, usb_frlength_t len, uint8_t what)
2051 {
2052 	struct usb_mbuf *m;
2053 	usb_frlength_t io_len;
2054 
2055 	while (len || (what == 1)) {
2056 		USB_IF_DEQUEUE(&f->free_q, m);
2057 
2058 		if (m) {
2059 			USB_MBUF_RESET(m);
2060 
2061 			io_len = MIN(len, m->cur_data_len);
2062 
2063 			usbd_copy_out(pc, offset, m->cur_data_ptr, io_len);
2064 
2065 			m->cur_data_len = io_len;
2066 			offset += io_len;
2067 			len -= io_len;
2068 
2069 			if ((len == 0) && (what == 1)) {
2070 				m->last_packet = 1;
2071 			}
2072 			USB_IF_ENQUEUE(&f->used_q, m);
2073 
2074 			usb_fifo_wakeup(f);
2075 
2076 			if ((len == 0) || (what == 1)) {
2077 				break;
2078 			}
2079 		} else {
2080 			break;
2081 		}
2082 	}
2083 }
2084 
2085 void
usb_fifo_put_data_linear(struct usb_fifo * f,void * ptr,usb_size_t len,uint8_t what)2086 usb_fifo_put_data_linear(struct usb_fifo *f, void *ptr,
2087     usb_size_t len, uint8_t what)
2088 {
2089 	struct usb_mbuf *m;
2090 	usb_size_t io_len;
2091 
2092 	while (len || (what == 1)) {
2093 		USB_IF_DEQUEUE(&f->free_q, m);
2094 
2095 		if (m) {
2096 			USB_MBUF_RESET(m);
2097 
2098 			io_len = MIN(len, m->cur_data_len);
2099 
2100 			memcpy(m->cur_data_ptr, ptr, io_len);
2101 
2102 			m->cur_data_len = io_len;
2103 			ptr = USB_ADD_BYTES(ptr, io_len);
2104 			len -= io_len;
2105 
2106 			if ((len == 0) && (what == 1)) {
2107 				m->last_packet = 1;
2108 			}
2109 			USB_IF_ENQUEUE(&f->used_q, m);
2110 
2111 			usb_fifo_wakeup(f);
2112 
2113 			if ((len == 0) || (what == 1)) {
2114 				break;
2115 			}
2116 		} else {
2117 			break;
2118 		}
2119 	}
2120 }
2121 
2122 uint8_t
usb_fifo_put_data_buffer(struct usb_fifo * f,void * ptr,usb_size_t len)2123 usb_fifo_put_data_buffer(struct usb_fifo *f, void *ptr, usb_size_t len)
2124 {
2125 	struct usb_mbuf *m;
2126 
2127 	USB_IF_DEQUEUE(&f->free_q, m);
2128 
2129 	if (m) {
2130 		m->cur_data_len = len;
2131 		m->cur_data_ptr = ptr;
2132 		USB_IF_ENQUEUE(&f->used_q, m);
2133 		usb_fifo_wakeup(f);
2134 		return (1);
2135 	}
2136 	return (0);
2137 }
2138 
2139 void
usb_fifo_put_data_error(struct usb_fifo * f)2140 usb_fifo_put_data_error(struct usb_fifo *f)
2141 {
2142 	f->flag_iserror = 1;
2143 	usb_fifo_wakeup(f);
2144 }
2145 
2146 /*------------------------------------------------------------------------*
2147  *	usb_fifo_get_data
2148  *
2149  * what:
2150  *  0 - normal operation
2151  *  1 - only get one "usb_mbuf"
2152  *
2153  * returns:
2154  *  0 - no more data
2155  *  1 - data in buffer
2156  *------------------------------------------------------------------------*/
2157 uint8_t
usb_fifo_get_data(struct usb_fifo * f,struct usb_page_cache * pc,usb_frlength_t offset,usb_frlength_t len,usb_frlength_t * actlen,uint8_t what)2158 usb_fifo_get_data(struct usb_fifo *f, struct usb_page_cache *pc,
2159     usb_frlength_t offset, usb_frlength_t len, usb_frlength_t *actlen,
2160     uint8_t what)
2161 {
2162 	struct usb_mbuf *m;
2163 	usb_frlength_t io_len;
2164 	uint8_t tr_data = 0;
2165 
2166 	actlen[0] = 0;
2167 
2168 	while (1) {
2169 		USB_IF_DEQUEUE(&f->used_q, m);
2170 
2171 		if (m) {
2172 			tr_data = 1;
2173 
2174 			io_len = MIN(len, m->cur_data_len);
2175 
2176 			usbd_copy_in(pc, offset, m->cur_data_ptr, io_len);
2177 
2178 			len -= io_len;
2179 			offset += io_len;
2180 			actlen[0] += io_len;
2181 			m->cur_data_ptr += io_len;
2182 			m->cur_data_len -= io_len;
2183 
2184 			if ((m->cur_data_len == 0) || (what == 1)) {
2185 				USB_IF_ENQUEUE(&f->free_q, m);
2186 
2187 				usb_fifo_wakeup(f);
2188 
2189 				if (what == 1) {
2190 					break;
2191 				}
2192 			} else {
2193 				USB_IF_PREPEND(&f->used_q, m);
2194 			}
2195 		} else {
2196 			if (tr_data) {
2197 				/* wait for data to be written out */
2198 				break;
2199 			}
2200 			if (f->flag_flushing) {
2201 				/* check if we should send a short packet */
2202 				if (f->flag_short != 0) {
2203 					f->flag_short = 0;
2204 					tr_data = 1;
2205 					break;
2206 				}
2207 				/* flushing complete */
2208 				f->flag_flushing = 0;
2209 				usb_fifo_wakeup(f);
2210 			}
2211 			break;
2212 		}
2213 		if (len == 0) {
2214 			break;
2215 		}
2216 	}
2217 	return (tr_data);
2218 }
2219 
2220 uint8_t
usb_fifo_get_data_linear(struct usb_fifo * f,void * ptr,usb_size_t len,usb_size_t * actlen,uint8_t what)2221 usb_fifo_get_data_linear(struct usb_fifo *f, void *ptr,
2222     usb_size_t len, usb_size_t *actlen, uint8_t what)
2223 {
2224 	struct usb_mbuf *m;
2225 	usb_size_t io_len;
2226 	uint8_t tr_data = 0;
2227 
2228 	actlen[0] = 0;
2229 
2230 	while (1) {
2231 		USB_IF_DEQUEUE(&f->used_q, m);
2232 
2233 		if (m) {
2234 			tr_data = 1;
2235 
2236 			io_len = MIN(len, m->cur_data_len);
2237 
2238 			memcpy(ptr, m->cur_data_ptr, io_len);
2239 
2240 			len -= io_len;
2241 			ptr = USB_ADD_BYTES(ptr, io_len);
2242 			actlen[0] += io_len;
2243 			m->cur_data_ptr += io_len;
2244 			m->cur_data_len -= io_len;
2245 
2246 			if ((m->cur_data_len == 0) || (what == 1)) {
2247 				USB_IF_ENQUEUE(&f->free_q, m);
2248 
2249 				usb_fifo_wakeup(f);
2250 
2251 				if (what == 1) {
2252 					break;
2253 				}
2254 			} else {
2255 				USB_IF_PREPEND(&f->used_q, m);
2256 			}
2257 		} else {
2258 			if (tr_data) {
2259 				/* wait for data to be written out */
2260 				break;
2261 			}
2262 			if (f->flag_flushing) {
2263 				/* check if we should send a short packet */
2264 				if (f->flag_short != 0) {
2265 					f->flag_short = 0;
2266 					tr_data = 1;
2267 					break;
2268 				}
2269 				/* flushing complete */
2270 				f->flag_flushing = 0;
2271 				usb_fifo_wakeup(f);
2272 			}
2273 			break;
2274 		}
2275 		if (len == 0) {
2276 			break;
2277 		}
2278 	}
2279 	return (tr_data);
2280 }
2281 
2282 uint8_t
usb_fifo_get_data_buffer(struct usb_fifo * f,void ** pptr,usb_size_t * plen)2283 usb_fifo_get_data_buffer(struct usb_fifo *f, void **pptr, usb_size_t *plen)
2284 {
2285 	struct usb_mbuf *m;
2286 
2287 	USB_IF_POLL(&f->used_q, m);
2288 
2289 	if (m) {
2290 		*plen = m->cur_data_len;
2291 		*pptr = m->cur_data_ptr;
2292 
2293 		return (1);
2294 	}
2295 	return (0);
2296 }
2297 
2298 void
usb_fifo_get_data_error(struct usb_fifo * f)2299 usb_fifo_get_data_error(struct usb_fifo *f)
2300 {
2301 	f->flag_iserror = 1;
2302 	usb_fifo_wakeup(f);
2303 }
2304 
2305 /*------------------------------------------------------------------------*
2306  *	usb_alloc_symlink
2307  *
2308  * Return values:
2309  * NULL: Failure
2310  * Else: Pointer to symlink entry
2311  *------------------------------------------------------------------------*/
2312 struct usb_symlink *
usb_alloc_symlink(const char * target)2313 usb_alloc_symlink(const char *target)
2314 {
2315 	struct usb_symlink *ps;
2316 
2317 	ps = malloc(sizeof(*ps), M_USBDEV, M_WAITOK);
2318 	/* XXX no longer needed */
2319 	strlcpy(ps->src_path, target, sizeof(ps->src_path));
2320 	ps->src_len = strlen(ps->src_path);
2321 	strlcpy(ps->dst_path, target, sizeof(ps->dst_path));
2322 	ps->dst_len = strlen(ps->dst_path);
2323 
2324 	sx_xlock(&usb_sym_lock);
2325 	TAILQ_INSERT_TAIL(&usb_sym_head, ps, sym_entry);
2326 	sx_unlock(&usb_sym_lock);
2327 	return (ps);
2328 }
2329 
2330 /*------------------------------------------------------------------------*
2331  *	usb_free_symlink
2332  *------------------------------------------------------------------------*/
2333 void
usb_free_symlink(struct usb_symlink * ps)2334 usb_free_symlink(struct usb_symlink *ps)
2335 {
2336 	if (ps == NULL) {
2337 		return;
2338 	}
2339 	sx_xlock(&usb_sym_lock);
2340 	TAILQ_REMOVE(&usb_sym_head, ps, sym_entry);
2341 	sx_unlock(&usb_sym_lock);
2342 
2343 	free(ps, M_USBDEV);
2344 }
2345 
2346 /*------------------------------------------------------------------------*
2347  *	usb_read_symlink
2348  *
2349  * Return value:
2350  * 0: Success
2351  * Else: Failure
2352  *------------------------------------------------------------------------*/
2353 int
usb_read_symlink(uint8_t * user_ptr,uint32_t startentry,uint32_t user_len)2354 usb_read_symlink(uint8_t *user_ptr, uint32_t startentry, uint32_t user_len)
2355 {
2356 	struct usb_symlink *ps;
2357 	uint32_t temp;
2358 	uint32_t delta = 0;
2359 	uint8_t len;
2360 	int error = 0;
2361 
2362 	sx_xlock(&usb_sym_lock);
2363 
2364 	TAILQ_FOREACH(ps, &usb_sym_head, sym_entry) {
2365 		/*
2366 		 * Compute total length of source and destination symlink
2367 		 * strings pluss one length byte and two NUL bytes:
2368 		 */
2369 		temp = ps->src_len + ps->dst_len + 3;
2370 
2371 		if (temp > 255) {
2372 			/*
2373 			 * Skip entry because this length cannot fit
2374 			 * into one byte:
2375 			 */
2376 			continue;
2377 		}
2378 		if (startentry != 0) {
2379 			/* decrement read offset */
2380 			startentry--;
2381 			continue;
2382 		}
2383 		if (temp > user_len) {
2384 			/* out of buffer space */
2385 			break;
2386 		}
2387 		len = temp;
2388 
2389 		/* copy out total length */
2390 
2391 		error = copyout(&len,
2392 		    USB_ADD_BYTES(user_ptr, delta), 1);
2393 		if (error) {
2394 			break;
2395 		}
2396 		delta += 1;
2397 
2398 		/* copy out source string */
2399 
2400 		error = copyout(ps->src_path,
2401 		    USB_ADD_BYTES(user_ptr, delta), ps->src_len);
2402 		if (error) {
2403 			break;
2404 		}
2405 		len = 0;
2406 		delta += ps->src_len;
2407 		error = copyout(&len,
2408 		    USB_ADD_BYTES(user_ptr, delta), 1);
2409 		if (error) {
2410 			break;
2411 		}
2412 		delta += 1;
2413 
2414 		/* copy out destination string */
2415 
2416 		error = copyout(ps->dst_path,
2417 		    USB_ADD_BYTES(user_ptr, delta), ps->dst_len);
2418 		if (error) {
2419 			break;
2420 		}
2421 		len = 0;
2422 		delta += ps->dst_len;
2423 		error = copyout(&len,
2424 		    USB_ADD_BYTES(user_ptr, delta), 1);
2425 		if (error) {
2426 			break;
2427 		}
2428 		delta += 1;
2429 
2430 		user_len -= temp;
2431 	}
2432 
2433 	/* a zero length entry indicates the end */
2434 
2435 	if ((user_len != 0) && (error == 0)) {
2436 		len = 0;
2437 
2438 		error = copyout(&len,
2439 		    USB_ADD_BYTES(user_ptr, delta), 1);
2440 	}
2441 	sx_unlock(&usb_sym_lock);
2442 	return (error);
2443 }
2444 
2445 void
usb_fifo_set_close_zlp(struct usb_fifo * f,uint8_t onoff)2446 usb_fifo_set_close_zlp(struct usb_fifo *f, uint8_t onoff)
2447 {
2448 	if (f == NULL)
2449 		return;
2450 
2451 	/* send a Zero Length Packet, ZLP, before close */
2452 	f->flag_short = onoff;
2453 }
2454 
2455 void
usb_fifo_set_write_defrag(struct usb_fifo * f,uint8_t onoff)2456 usb_fifo_set_write_defrag(struct usb_fifo *f, uint8_t onoff)
2457 {
2458 	if (f == NULL)
2459 		return;
2460 
2461 	/* defrag written data */
2462 	f->flag_write_defrag = onoff;
2463 	/* reset defrag state */
2464 	f->flag_have_fragment = 0;
2465 }
2466 
2467 void *
usb_fifo_softc(struct usb_fifo * f)2468 usb_fifo_softc(struct usb_fifo *f)
2469 {
2470 	return (f->priv_sc0);
2471 }
2472 #endif	/* USB_HAVE_UGEN */
2473