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