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