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