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