source: rtems-libbsd/freebsd/sys/dev/usb/usb_device.c @ 02279d6

55-freebsd-126-freebsd-12freebsd-9.3
Last change on this file since 02279d6 was 02279d6, checked in by Sebastian Huber <sebastian.huber@…>, on 11/12/15 at 12:01:12

USB: Update to FreeBSD trunk 2015-11-10

  • Property mode set to 100644
File size: 72.7 KB
Line 
1#include <machine/rtems-bsd-kernel-space.h>
2
3/* $FreeBSD$ */
4/*-
5 * Copyright (c) 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#ifdef USB_GLOBAL_INCLUDE_FILE
30#include USB_GLOBAL_INCLUDE_FILE
31#else
32#include <sys/stdint.h>
33#include <sys/stddef.h>
34#include <rtems/bsd/sys/param.h>
35#include <sys/queue.h>
36#include <rtems/bsd/sys/types.h>
37#include <sys/systm.h>
38#include <sys/kernel.h>
39#include <sys/bus.h>
40#include <sys/module.h>
41#include <rtems/bsd/sys/lock.h>
42#include <sys/mutex.h>
43#include <sys/condvar.h>
44#include <sys/sysctl.h>
45#include <sys/sx.h>
46#include <rtems/bsd/sys/unistd.h>
47#include <sys/callout.h>
48#include <sys/malloc.h>
49#include <sys/priv.h>
50#include <sys/conf.h>
51#include <sys/fcntl.h>
52
53#include <dev/usb/usb.h>
54#include <dev/usb/usbdi.h>
55#include <dev/usb/usbdi_util.h>
56#include <dev/usb/usb_ioctl.h>
57
58#if USB_HAVE_UGEN
59#include <sys/sbuf.h>
60#endif
61
62#include <rtems/bsd/local/usbdevs.h>
63
64#define USB_DEBUG_VAR usb_debug
65
66#include <dev/usb/usb_core.h>
67#include <dev/usb/usb_debug.h>
68#include <dev/usb/usb_process.h>
69#include <dev/usb/usb_device.h>
70#include <dev/usb/usb_busdma.h>
71#include <dev/usb/usb_transfer.h>
72#include <dev/usb/usb_request.h>
73#include <dev/usb/usb_dynamic.h>
74#include <dev/usb/usb_hub.h>
75#include <dev/usb/usb_util.h>
76#include <dev/usb/usb_msctest.h>
77#if USB_HAVE_UGEN
78#include <dev/usb/usb_dev.h>
79#include <dev/usb/usb_generic.h>
80#endif
81
82#include <dev/usb/quirk/usb_quirk.h>
83
84#include <dev/usb/usb_controller.h>
85#include <dev/usb/usb_bus.h>
86#endif                  /* USB_GLOBAL_INCLUDE_FILE */
87
88/* function prototypes  */
89
90static void     usb_init_endpoint(struct usb_device *, uint8_t,
91                    struct usb_endpoint_descriptor *,
92                    struct usb_endpoint_ss_comp_descriptor *,
93                    struct usb_endpoint *);
94static void     usb_unconfigure(struct usb_device *, uint8_t);
95static void     usb_detach_device_sub(struct usb_device *, device_t *,
96                    char **, uint8_t);
97static uint8_t  usb_probe_and_attach_sub(struct usb_device *,
98                    struct usb_attach_arg *);
99static void     usb_init_attach_arg(struct usb_device *,
100                    struct usb_attach_arg *);
101static void     usb_suspend_resume_sub(struct usb_device *, device_t,
102                    uint8_t);
103static usb_proc_callback_t usbd_clear_stall_proc;
104static usb_error_t usb_config_parse(struct usb_device *, uint8_t, uint8_t);
105static void     usbd_set_device_strings(struct usb_device *);
106#if USB_HAVE_DEVCTL
107static void     usb_notify_addq(const char *type, struct usb_device *);
108#endif
109#if USB_HAVE_UGEN
110static void     usb_fifo_free_wrap(struct usb_device *, uint8_t, uint8_t);
111static void     usb_cdev_create(struct usb_device *);
112static void     usb_cdev_free(struct usb_device *);
113#endif
114
115/* This variable is global to allow easy access to it: */
116
117#ifdef  USB_TEMPLATE
118int     usb_template = USB_TEMPLATE;
119#else
120int     usb_template;
121#endif
122
123#ifndef __rtems__
124SYSCTL_INT(_hw_usb, OID_AUTO, template, CTLFLAG_RWTUN,
125    &usb_template, 0, "Selected USB device side template");
126#endif /* __rtems__ */
127
128/* English is default language */
129
130static int usb_lang_id = 0x0009;
131static int usb_lang_mask = 0x00FF;
132
133#ifndef __rtems__
134SYSCTL_INT(_hw_usb, OID_AUTO, usb_lang_id, CTLFLAG_RWTUN,
135    &usb_lang_id, 0, "Preferred USB language ID");
136
137SYSCTL_INT(_hw_usb, OID_AUTO, usb_lang_mask, CTLFLAG_RWTUN,
138    &usb_lang_mask, 0, "Preferred USB language mask");
139#endif /* __rtems__ */
140
141static const char* statestr[USB_STATE_MAX] = {
142        [USB_STATE_DETACHED]    = "DETACHED",
143        [USB_STATE_ATTACHED]    = "ATTACHED",
144        [USB_STATE_POWERED]     = "POWERED",
145        [USB_STATE_ADDRESSED]   = "ADDRESSED",
146        [USB_STATE_CONFIGURED]  = "CONFIGURED",
147};
148
149const char *
150usb_statestr(enum usb_dev_state state)
151{
152        return ((state < USB_STATE_MAX) ? statestr[state] : "UNKNOWN");
153}
154
155const char *
156usb_get_manufacturer(struct usb_device *udev)
157{
158        return (udev->manufacturer ? udev->manufacturer : "Unknown");
159}
160
161const char *
162usb_get_product(struct usb_device *udev)
163{
164        return (udev->product ? udev->product : "");
165}
166
167const char *
168usb_get_serial(struct usb_device *udev)
169{
170        return (udev->serial ? udev->serial : "");
171}
172
173/*------------------------------------------------------------------------*
174 *      usbd_get_ep_by_addr
175 *
176 * This function searches for an USB ep by endpoint address and
177 * direction.
178 *
179 * Returns:
180 * NULL: Failure
181 * Else: Success
182 *------------------------------------------------------------------------*/
183struct usb_endpoint *
184usbd_get_ep_by_addr(struct usb_device *udev, uint8_t ea_val)
185{
186        struct usb_endpoint *ep = udev->endpoints;
187        struct usb_endpoint *ep_end = udev->endpoints + udev->endpoints_max;
188        enum {
189                EA_MASK = (UE_DIR_IN | UE_DIR_OUT | UE_ADDR),
190        };
191
192        /*
193         * According to the USB specification not all bits are used
194         * for the endpoint address. Keep defined bits only:
195         */
196        ea_val &= EA_MASK;
197
198        /*
199         * Iterate accross all the USB endpoints searching for a match
200         * based on the endpoint address:
201         */
202        for (; ep != ep_end; ep++) {
203
204                if (ep->edesc == NULL) {
205                        continue;
206                }
207                /* do the mask and check the value */
208                if ((ep->edesc->bEndpointAddress & EA_MASK) == ea_val) {
209                        goto found;
210                }
211        }
212
213        /*
214         * The default endpoint is always present and is checked separately:
215         */
216        if ((udev->ctrl_ep.edesc != NULL) &&
217            ((udev->ctrl_ep.edesc->bEndpointAddress & EA_MASK) == ea_val)) {
218                ep = &udev->ctrl_ep;
219                goto found;
220        }
221        return (NULL);
222
223found:
224        return (ep);
225}
226
227/*------------------------------------------------------------------------*
228 *      usbd_get_endpoint
229 *
230 * This function searches for an USB endpoint based on the information
231 * given by the passed "struct usb_config" pointer.
232 *
233 * Return values:
234 * NULL: No match.
235 * Else: Pointer to "struct usb_endpoint".
236 *------------------------------------------------------------------------*/
237struct usb_endpoint *
238usbd_get_endpoint(struct usb_device *udev, uint8_t iface_index,
239    const struct usb_config *setup)
240{
241        struct usb_endpoint *ep = udev->endpoints;
242        struct usb_endpoint *ep_end = udev->endpoints + udev->endpoints_max;
243        uint8_t index = setup->ep_index;
244        uint8_t ea_mask;
245        uint8_t ea_val;
246        uint8_t type_mask;
247        uint8_t type_val;
248
249        DPRINTFN(10, "udev=%p iface_index=%d address=0x%x "
250            "type=0x%x dir=0x%x index=%d\n",
251            udev, iface_index, setup->endpoint,
252            setup->type, setup->direction, setup->ep_index);
253
254        /* check USB mode */
255
256        if (setup->usb_mode != USB_MODE_DUAL &&
257            udev->flags.usb_mode != setup->usb_mode) {
258                /* wrong mode - no endpoint */
259                return (NULL);
260        }
261
262        /* setup expected endpoint direction mask and value */
263
264        if (setup->direction == UE_DIR_RX) {
265                ea_mask = (UE_DIR_IN | UE_DIR_OUT);
266                ea_val = (udev->flags.usb_mode == USB_MODE_DEVICE) ?
267                    UE_DIR_OUT : UE_DIR_IN;
268        } else if (setup->direction == UE_DIR_TX) {
269                ea_mask = (UE_DIR_IN | UE_DIR_OUT);
270                ea_val = (udev->flags.usb_mode == USB_MODE_DEVICE) ?
271                    UE_DIR_IN : UE_DIR_OUT;
272        } else if (setup->direction == UE_DIR_ANY) {
273                /* match any endpoint direction */
274                ea_mask = 0;
275                ea_val = 0;
276        } else {
277                /* match the given endpoint direction */
278                ea_mask = (UE_DIR_IN | UE_DIR_OUT);
279                ea_val = (setup->direction & (UE_DIR_IN | UE_DIR_OUT));
280        }
281
282        /* setup expected endpoint address */
283
284        if (setup->endpoint == UE_ADDR_ANY) {
285                /* match any endpoint address */
286        } else {
287                /* match the given endpoint address */
288                ea_mask |= UE_ADDR;
289                ea_val |= (setup->endpoint & UE_ADDR);
290        }
291
292        /* setup expected endpoint type */
293
294        if (setup->type == UE_BULK_INTR) {
295                /* this will match BULK and INTERRUPT endpoints */
296                type_mask = 2;
297                type_val = 2;
298        } else if (setup->type == UE_TYPE_ANY) {
299                /* match any endpoint type */
300                type_mask = 0;
301                type_val = 0;
302        } else {
303                /* match the given endpoint type */
304                type_mask = UE_XFERTYPE;
305                type_val = (setup->type & UE_XFERTYPE);
306        }
307
308        /*
309         * Iterate accross all the USB endpoints searching for a match
310         * based on the endpoint address. Note that we are searching
311         * the endpoints from the beginning of the "udev->endpoints" array.
312         */
313        for (; ep != ep_end; ep++) {
314
315                if ((ep->edesc == NULL) ||
316                    (ep->iface_index != iface_index)) {
317                        continue;
318                }
319                /* do the masks and check the values */
320
321                if (((ep->edesc->bEndpointAddress & ea_mask) == ea_val) &&
322                    ((ep->edesc->bmAttributes & type_mask) == type_val)) {
323                        if (!index--) {
324                                goto found;
325                        }
326                }
327        }
328
329        /*
330         * Match against default endpoint last, so that "any endpoint", "any
331         * address" and "any direction" returns the first endpoint of the
332         * interface. "iface_index" and "direction" is ignored:
333         */
334        if ((udev->ctrl_ep.edesc != NULL) &&
335            ((udev->ctrl_ep.edesc->bEndpointAddress & ea_mask) == ea_val) &&
336            ((udev->ctrl_ep.edesc->bmAttributes & type_mask) == type_val) &&
337            (!index)) {
338                ep = &udev->ctrl_ep;
339                goto found;
340        }
341        return (NULL);
342
343found:
344        return (ep);
345}
346
347/*------------------------------------------------------------------------*
348 *      usbd_interface_count
349 *
350 * This function stores the number of USB interfaces excluding
351 * alternate settings, which the USB config descriptor reports into
352 * the unsigned 8-bit integer pointed to by "count".
353 *
354 * Returns:
355 *    0: Success
356 * Else: Failure
357 *------------------------------------------------------------------------*/
358usb_error_t
359usbd_interface_count(struct usb_device *udev, uint8_t *count)
360{
361        if (udev->cdesc == NULL) {
362                *count = 0;
363                return (USB_ERR_NOT_CONFIGURED);
364        }
365        *count = udev->ifaces_max;
366        return (USB_ERR_NORMAL_COMPLETION);
367}
368
369/*------------------------------------------------------------------------*
370 *      usb_init_endpoint
371 *
372 * This function will initialise the USB endpoint structure pointed to by
373 * the "endpoint" argument. The structure pointed to by "endpoint" must be
374 * zeroed before calling this function.
375 *------------------------------------------------------------------------*/
376static void
377usb_init_endpoint(struct usb_device *udev, uint8_t iface_index,
378    struct usb_endpoint_descriptor *edesc,
379    struct usb_endpoint_ss_comp_descriptor *ecomp,
380    struct usb_endpoint *ep)
381{
382        const struct usb_bus_methods *methods;
383        usb_stream_t x;
384
385        methods = udev->bus->methods;
386
387        (methods->endpoint_init) (udev, edesc, ep);
388
389        /* initialise USB endpoint structure */
390        ep->edesc = edesc;
391        ep->ecomp = ecomp;
392        ep->iface_index = iface_index;
393
394        /* setup USB stream queues */
395        for (x = 0; x != USB_MAX_EP_STREAMS; x++) {
396                TAILQ_INIT(&ep->endpoint_q[x].head);
397                ep->endpoint_q[x].command = &usbd_pipe_start;
398        }
399
400        /* the pipe is not supported by the hardware */
401        if (ep->methods == NULL)
402                return;
403
404        /* check for SUPER-speed streams mode endpoint */
405        if (udev->speed == USB_SPEED_SUPER && ecomp != NULL &&
406            (edesc->bmAttributes & UE_XFERTYPE) == UE_BULK &&
407            (UE_GET_BULK_STREAMS(ecomp->bmAttributes) != 0)) {
408                usbd_set_endpoint_mode(udev, ep, USB_EP_MODE_STREAMS);
409        } else {
410                usbd_set_endpoint_mode(udev, ep, USB_EP_MODE_DEFAULT);
411        }
412
413        /* clear stall, if any */
414        if (methods->clear_stall != NULL) {
415                USB_BUS_LOCK(udev->bus);
416                (methods->clear_stall) (udev, ep);
417                USB_BUS_UNLOCK(udev->bus);
418        }
419}
420
421/*-----------------------------------------------------------------------*
422 *      usb_endpoint_foreach
423 *
424 * This function will iterate all the USB endpoints except the control
425 * endpoint. This function is NULL safe.
426 *
427 * Return values:
428 * NULL: End of USB endpoints
429 * Else: Pointer to next USB endpoint
430 *------------------------------------------------------------------------*/
431struct usb_endpoint *
432usb_endpoint_foreach(struct usb_device *udev, struct usb_endpoint *ep)
433{
434        struct usb_endpoint *ep_end;
435
436        /* be NULL safe */
437        if (udev == NULL)
438                return (NULL);
439
440        ep_end = udev->endpoints + udev->endpoints_max;
441
442        /* get next endpoint */
443        if (ep == NULL)
444                ep = udev->endpoints;
445        else
446                ep++;
447
448        /* find next allocated ep */
449        while (ep != ep_end) {
450                if (ep->edesc != NULL)
451                        return (ep);
452                ep++;
453        }
454        return (NULL);
455}
456
457/*------------------------------------------------------------------------*
458 *      usb_wait_pending_refs
459 *
460 * This function will wait for any USB references to go away before
461 * returning. This function is used before freeing a USB device.
462 *------------------------------------------------------------------------*/
463static void
464usb_wait_pending_refs(struct usb_device *udev)
465{
466#if USB_HAVE_UGEN
467        DPRINTF("Refcount = %d\n", (int)udev->refcount);
468
469        mtx_lock(&usb_ref_lock);
470        udev->refcount--;
471        while (1) {
472                /* wait for any pending references to go away */
473                if (udev->refcount == 0) {
474                        /* prevent further refs being taken, if any */
475                        udev->refcount = USB_DEV_REF_MAX;
476                        break;
477                }
478                cv_wait(&udev->ref_cv, &usb_ref_lock);
479        }
480        mtx_unlock(&usb_ref_lock);
481#endif
482}
483
484/*------------------------------------------------------------------------*
485 *      usb_unconfigure
486 *
487 * This function will free all USB interfaces and USB endpoints belonging
488 * to an USB device.
489 *
490 * Flag values, see "USB_UNCFG_FLAG_XXX".
491 *------------------------------------------------------------------------*/
492static void
493usb_unconfigure(struct usb_device *udev, uint8_t flag)
494{
495        uint8_t do_unlock;
496
497        /* Prevent re-enumeration */
498        do_unlock = usbd_enum_lock(udev);
499
500        /* detach all interface drivers */
501        usb_detach_device(udev, USB_IFACE_INDEX_ANY, flag);
502
503#if USB_HAVE_UGEN
504        /* free all FIFOs except control endpoint FIFOs */
505        usb_fifo_free_wrap(udev, USB_IFACE_INDEX_ANY, flag);
506
507        /*
508         * Free all cdev's, if any.
509         */
510        usb_cdev_free(udev);
511#endif
512
513#if USB_HAVE_COMPAT_LINUX
514        /* free Linux compat device, if any */
515        if (udev->linux_endpoint_start != NULL) {
516                usb_linux_free_device_p(udev);
517                udev->linux_endpoint_start = NULL;
518        }
519#endif
520
521        usb_config_parse(udev, USB_IFACE_INDEX_ANY, USB_CFG_FREE);
522
523        /* free "cdesc" after "ifaces" and "endpoints", if any */
524        if (udev->cdesc != NULL) {
525                if (udev->flags.usb_mode != USB_MODE_DEVICE)
526                        usbd_free_config_desc(udev, udev->cdesc);
527                udev->cdesc = NULL;
528        }
529        /* set unconfigured state */
530        udev->curr_config_no = USB_UNCONFIG_NO;
531        udev->curr_config_index = USB_UNCONFIG_INDEX;
532
533        if (do_unlock)
534                usbd_enum_unlock(udev);
535}
536
537/*------------------------------------------------------------------------*
538 *      usbd_set_config_index
539 *
540 * This function selects configuration by index, independent of the
541 * actual configuration number. This function should not be used by
542 * USB drivers.
543 *
544 * Returns:
545 *    0: Success
546 * Else: Failure
547 *------------------------------------------------------------------------*/
548usb_error_t
549usbd_set_config_index(struct usb_device *udev, uint8_t index)
550{
551        struct usb_status ds;
552        struct usb_config_descriptor *cdp;
553        uint16_t power;
554        uint16_t max_power;
555        uint8_t selfpowered;
556        uint8_t do_unlock;
557        usb_error_t err;
558
559        DPRINTFN(6, "udev=%p index=%d\n", udev, index);
560
561        /* Prevent re-enumeration */
562        do_unlock = usbd_enum_lock(udev);
563
564        usb_unconfigure(udev, 0);
565
566        if (index == USB_UNCONFIG_INDEX) {
567                /*
568                 * Leave unallocated when unconfiguring the
569                 * device. "usb_unconfigure()" will also reset
570                 * the current config number and index.
571                 */
572                err = usbd_req_set_config(udev, NULL, USB_UNCONFIG_NO);
573                if (udev->state == USB_STATE_CONFIGURED)
574                        usb_set_device_state(udev, USB_STATE_ADDRESSED);
575                goto done;
576        }
577        /* get the full config descriptor */
578        if (udev->flags.usb_mode == USB_MODE_DEVICE) {
579                /* save some memory */
580                err = usbd_req_get_descriptor_ptr(udev, &cdp,
581                    (UDESC_CONFIG << 8) | index);
582        } else {
583                /* normal request */
584                err = usbd_req_get_config_desc_full(udev,
585                    NULL, &cdp, index);
586        }
587        if (err) {
588                goto done;
589        }
590        /* set the new config descriptor */
591
592        udev->cdesc = cdp;
593
594        /* Figure out if the device is self or bus powered. */
595        selfpowered = 0;
596        if ((!udev->flags.uq_bus_powered) &&
597            (cdp->bmAttributes & UC_SELF_POWERED) &&
598            (udev->flags.usb_mode == USB_MODE_HOST)) {
599                /* May be self powered. */
600                if (cdp->bmAttributes & UC_BUS_POWERED) {
601                        /* Must ask device. */
602                        err = usbd_req_get_device_status(udev, NULL, &ds);
603                        if (err) {
604                                DPRINTFN(0, "could not read "
605                                    "device status: %s\n",
606                                    usbd_errstr(err));
607                        } else if (UGETW(ds.wStatus) & UDS_SELF_POWERED) {
608                                selfpowered = 1;
609                        }
610                        DPRINTF("status=0x%04x \n",
611                                UGETW(ds.wStatus));
612                } else
613                        selfpowered = 1;
614        }
615        DPRINTF("udev=%p cdesc=%p (addr %d) cno=%d attr=0x%02x, "
616            "selfpowered=%d, power=%d\n",
617            udev, cdp,
618            udev->address, cdp->bConfigurationValue, cdp->bmAttributes,
619            selfpowered, cdp->bMaxPower * 2);
620
621        /* Check if we have enough power. */
622        power = cdp->bMaxPower * 2;
623
624        if (udev->parent_hub) {
625                max_power = udev->parent_hub->hub->portpower;
626        } else {
627                max_power = USB_MAX_POWER;
628        }
629
630        if (power > max_power) {
631                DPRINTFN(0, "power exceeded %d > %d\n", power, max_power);
632                err = USB_ERR_NO_POWER;
633                goto done;
634        }
635        /* Only update "self_powered" in USB Host Mode */
636        if (udev->flags.usb_mode == USB_MODE_HOST) {
637                udev->flags.self_powered = selfpowered;
638        }
639        udev->power = power;
640        udev->curr_config_no = cdp->bConfigurationValue;
641        udev->curr_config_index = index;
642        usb_set_device_state(udev, USB_STATE_CONFIGURED);
643
644        /* Set the actual configuration value. */
645        err = usbd_req_set_config(udev, NULL, cdp->bConfigurationValue);
646        if (err) {
647                goto done;
648        }
649
650        err = usb_config_parse(udev, USB_IFACE_INDEX_ANY, USB_CFG_ALLOC);
651        if (err) {
652                goto done;
653        }
654
655        err = usb_config_parse(udev, USB_IFACE_INDEX_ANY, USB_CFG_INIT);
656        if (err) {
657                goto done;
658        }
659
660#if USB_HAVE_UGEN
661        /* create device nodes for each endpoint */
662        usb_cdev_create(udev);
663#endif
664
665done:
666        DPRINTF("error=%s\n", usbd_errstr(err));
667        if (err) {
668                usb_unconfigure(udev, 0);
669        }
670        if (do_unlock)
671                usbd_enum_unlock(udev);
672        return (err);
673}
674
675/*------------------------------------------------------------------------*
676 *      usb_config_parse
677 *
678 * This function will allocate and free USB interfaces and USB endpoints,
679 * parse the USB configuration structure and initialise the USB endpoints
680 * and interfaces. If "iface_index" is not equal to
681 * "USB_IFACE_INDEX_ANY" then the "cmd" parameter is the
682 * alternate_setting to be selected for the given interface. Else the
683 * "cmd" parameter is defined by "USB_CFG_XXX". "iface_index" can be
684 * "USB_IFACE_INDEX_ANY" or a valid USB interface index. This function
685 * is typically called when setting the configuration or when setting
686 * an alternate interface.
687 *
688 * Returns:
689 *    0: Success
690 * Else: Failure
691 *------------------------------------------------------------------------*/
692static usb_error_t
693usb_config_parse(struct usb_device *udev, uint8_t iface_index, uint8_t cmd)
694{
695        struct usb_idesc_parse_state ips;
696        struct usb_interface_descriptor *id;
697        struct usb_endpoint_descriptor *ed;
698        struct usb_interface *iface;
699        struct usb_endpoint *ep;
700        usb_error_t err;
701        uint8_t ep_curr;
702        uint8_t ep_max;
703        uint8_t temp;
704        uint8_t do_init;
705        uint8_t alt_index;
706
707        if (iface_index != USB_IFACE_INDEX_ANY) {
708                /* parameter overload */
709                alt_index = cmd;
710                cmd = USB_CFG_INIT;
711        } else {
712                /* not used */
713                alt_index = 0;
714        }
715
716        err = 0;
717
718        DPRINTFN(5, "iface_index=%d cmd=%d\n",
719            iface_index, cmd);
720
721        if (cmd == USB_CFG_FREE)
722                goto cleanup;
723
724        if (cmd == USB_CFG_INIT) {
725                sx_assert(&udev->enum_sx, SA_LOCKED);
726
727                /* check for in-use endpoints */
728
729                ep = udev->endpoints;
730                ep_max = udev->endpoints_max;
731                while (ep_max--) {
732                        /* look for matching endpoints */
733                        if ((iface_index == USB_IFACE_INDEX_ANY) ||
734                            (iface_index == ep->iface_index)) {
735                                if (ep->refcount_alloc != 0) {
736                                        /*
737                                         * This typically indicates a
738                                         * more serious error.
739                                         */
740                                        err = USB_ERR_IN_USE;
741                                } else {
742                                        /* reset endpoint */
743                                        memset(ep, 0, sizeof(*ep));
744                                        /* make sure we don't zero the endpoint again */
745                                        ep->iface_index = USB_IFACE_INDEX_ANY;
746                                }
747                        }
748                        ep++;
749                }
750
751                if (err)
752                        return (err);
753        }
754
755        memset(&ips, 0, sizeof(ips));
756
757        ep_curr = 0;
758        ep_max = 0;
759
760        while ((id = usb_idesc_foreach(udev->cdesc, &ips))) {
761
762                iface = udev->ifaces + ips.iface_index;
763
764                /* check for specific interface match */
765
766                if (cmd == USB_CFG_INIT) {
767                        if ((iface_index != USB_IFACE_INDEX_ANY) &&
768                            (iface_index != ips.iface_index)) {
769                                /* wrong interface */
770                                do_init = 0;
771                        } else if (alt_index != ips.iface_index_alt) {
772                                /* wrong alternate setting */
773                                do_init = 0;
774                        } else {
775                                /* initialise interface */
776                                do_init = 1;
777                        }
778                } else
779                        do_init = 0;
780
781                /* check for new interface */
782                if (ips.iface_index_alt == 0) {
783                        /* update current number of endpoints */
784                        ep_curr = ep_max;
785                }
786                /* check for init */
787                if (do_init) {
788                        /* setup the USB interface structure */
789                        iface->idesc = id;
790                        /* set alternate index */
791                        iface->alt_index = alt_index;
792                        /* set default interface parent */
793                        if (iface_index == USB_IFACE_INDEX_ANY) {
794                                iface->parent_iface_index =
795                                    USB_IFACE_INDEX_ANY;
796                        }
797                }
798
799                DPRINTFN(5, "found idesc nendpt=%d\n", id->bNumEndpoints);
800
801                ed = (struct usb_endpoint_descriptor *)id;
802
803                temp = ep_curr;
804
805                /* iterate all the endpoint descriptors */
806                while ((ed = usb_edesc_foreach(udev->cdesc, ed))) {
807
808                        /* check if endpoint limit has been reached */
809                        if (temp >= USB_MAX_EP_UNITS) {
810                                DPRINTF("Endpoint limit reached\n");
811                                break;
812                        }
813
814                        ep = udev->endpoints + temp;
815
816                        if (do_init) {
817                                void *ecomp;
818
819                                ecomp = usb_ed_comp_foreach(udev->cdesc, (void *)ed);
820                                if (ecomp != NULL)
821                                        DPRINTFN(5, "Found endpoint companion descriptor\n");
822
823                                usb_init_endpoint(udev,
824                                    ips.iface_index, ed, ecomp, ep);
825                        }
826
827                        temp ++;
828
829                        /* find maximum number of endpoints */
830                        if (ep_max < temp)
831                                ep_max = temp;
832                }
833        }
834
835        /* NOTE: It is valid to have no interfaces and no endpoints! */
836
837        if (cmd == USB_CFG_ALLOC) {
838                udev->ifaces_max = ips.iface_index;
839#if (USB_HAVE_FIXED_IFACE == 0)
840                udev->ifaces = NULL;
841                if (udev->ifaces_max != 0) {
842                        udev->ifaces = malloc(sizeof(*iface) * udev->ifaces_max,
843                                M_USB, M_WAITOK | M_ZERO);
844                        if (udev->ifaces == NULL) {
845                                err = USB_ERR_NOMEM;
846                                goto done;
847                        }
848                }
849#endif
850#if (USB_HAVE_FIXED_ENDPOINT == 0)
851                if (ep_max != 0) {
852                        udev->endpoints = malloc(sizeof(*ep) * ep_max,
853                                M_USB, M_WAITOK | M_ZERO);
854                        if (udev->endpoints == NULL) {
855                                err = USB_ERR_NOMEM;
856                                goto done;
857                        }
858                } else {
859                        udev->endpoints = NULL;
860                }
861#endif
862                USB_BUS_LOCK(udev->bus);
863                udev->endpoints_max = ep_max;
864                /* reset any ongoing clear-stall */
865                udev->ep_curr = NULL;
866                USB_BUS_UNLOCK(udev->bus);
867        }
868#if (USB_HAVE_FIXED_IFACE == 0) || (USB_HAVE_FIXED_ENDPOINT == 0)
869done:
870#endif
871        if (err) {
872                if (cmd == USB_CFG_ALLOC) {
873cleanup:
874                        USB_BUS_LOCK(udev->bus);
875                        udev->endpoints_max = 0;
876                        /* reset any ongoing clear-stall */
877                        udev->ep_curr = NULL;
878                        USB_BUS_UNLOCK(udev->bus);
879
880#if (USB_HAVE_FIXED_IFACE == 0)
881                        free(udev->ifaces, M_USB);
882                        udev->ifaces = NULL;
883#endif
884#if (USB_HAVE_FIXED_ENDPOINT == 0)
885                        free(udev->endpoints, M_USB);
886                        udev->endpoints = NULL;
887#endif
888                        udev->ifaces_max = 0;
889                }
890        }
891        return (err);
892}
893
894/*------------------------------------------------------------------------*
895 *      usbd_set_alt_interface_index
896 *
897 * This function will select an alternate interface index for the
898 * given interface index. The interface should not be in use when this
899 * function is called. That means there should not be any open USB
900 * transfers. Else an error is returned. If the alternate setting is
901 * already set this function will simply return success. This function
902 * is called in Host mode and Device mode!
903 *
904 * Returns:
905 *    0: Success
906 * Else: Failure
907 *------------------------------------------------------------------------*/
908usb_error_t
909usbd_set_alt_interface_index(struct usb_device *udev,
910    uint8_t iface_index, uint8_t alt_index)
911{
912        struct usb_interface *iface = usbd_get_iface(udev, iface_index);
913        usb_error_t err;
914        uint8_t do_unlock;
915
916        /* Prevent re-enumeration */
917        do_unlock = usbd_enum_lock(udev);
918
919        if (iface == NULL) {
920                err = USB_ERR_INVAL;
921                goto done;
922        }
923        if (iface->alt_index == alt_index) {
924                /*
925                 * Optimise away duplicate setting of
926                 * alternate setting in USB Host Mode!
927                 */
928                err = 0;
929                goto done;
930        }
931#if USB_HAVE_UGEN
932        /*
933         * Free all generic FIFOs for this interface, except control
934         * endpoint FIFOs:
935         */
936        usb_fifo_free_wrap(udev, iface_index, 0);
937#endif
938
939        err = usb_config_parse(udev, iface_index, alt_index);
940        if (err) {
941                goto done;
942        }
943        if (iface->alt_index != alt_index) {
944                /* the alternate setting does not exist */
945                err = USB_ERR_INVAL;
946                goto done;
947        }
948
949        err = usbd_req_set_alt_interface_no(udev, NULL, iface_index,
950            iface->idesc->bAlternateSetting);
951
952done:
953        if (do_unlock)
954                usbd_enum_unlock(udev);
955        return (err);
956}
957
958/*------------------------------------------------------------------------*
959 *      usbd_set_endpoint_stall
960 *
961 * This function is used to make a BULK or INTERRUPT endpoint send
962 * STALL tokens in USB device mode.
963 *
964 * Returns:
965 *    0: Success
966 * Else: Failure
967 *------------------------------------------------------------------------*/
968usb_error_t
969usbd_set_endpoint_stall(struct usb_device *udev, struct usb_endpoint *ep,
970    uint8_t do_stall)
971{
972        struct usb_xfer *xfer;
973        usb_stream_t x;
974        uint8_t et;
975        uint8_t was_stalled;
976
977        if (ep == NULL) {
978                /* nothing to do */
979                DPRINTF("Cannot find endpoint\n");
980                /*
981                 * Pretend that the clear or set stall request is
982                 * successful else some USB host stacks can do
983                 * strange things, especially when a control endpoint
984                 * stalls.
985                 */
986                return (0);
987        }
988        et = (ep->edesc->bmAttributes & UE_XFERTYPE);
989
990        if ((et != UE_BULK) &&
991            (et != UE_INTERRUPT)) {
992                /*
993                 * Should not stall control
994                 * nor isochronous endpoints.
995                 */
996                DPRINTF("Invalid endpoint\n");
997                return (0);
998        }
999        USB_BUS_LOCK(udev->bus);
1000
1001        /* store current stall state */
1002        was_stalled = ep->is_stalled;
1003
1004        /* check for no change */
1005        if (was_stalled && do_stall) {
1006                /* if the endpoint is already stalled do nothing */
1007                USB_BUS_UNLOCK(udev->bus);
1008                DPRINTF("No change\n");
1009                return (0);
1010        }
1011        /* set stalled state */
1012        ep->is_stalled = 1;
1013
1014        if (do_stall || (!was_stalled)) {
1015                if (!was_stalled) {
1016                        for (x = 0; x != USB_MAX_EP_STREAMS; x++) {
1017                                /* lookup the current USB transfer, if any */
1018                                xfer = ep->endpoint_q[x].curr;
1019                                if (xfer != NULL) {
1020                                        /*
1021                                         * The "xfer_stall" method
1022                                         * will complete the USB
1023                                         * transfer like in case of a
1024                                         * timeout setting the error
1025                                         * code "USB_ERR_STALLED".
1026                                         */
1027                                        (udev->bus->methods->xfer_stall) (xfer);
1028                                }
1029                        }
1030                }
1031                (udev->bus->methods->set_stall) (udev, ep, &do_stall);
1032        }
1033        if (!do_stall) {
1034                ep->toggle_next = 0;    /* reset data toggle */
1035                ep->is_stalled = 0;     /* clear stalled state */
1036
1037                (udev->bus->methods->clear_stall) (udev, ep);
1038
1039                /* start the current or next transfer, if any */
1040                for (x = 0; x != USB_MAX_EP_STREAMS; x++) {
1041                        usb_command_wrapper(&ep->endpoint_q[x],
1042                            ep->endpoint_q[x].curr);
1043                }
1044        }
1045        USB_BUS_UNLOCK(udev->bus);
1046        return (0);
1047}
1048
1049/*------------------------------------------------------------------------*
1050 *      usb_reset_iface_endpoints - used in USB device side mode
1051 *------------------------------------------------------------------------*/
1052usb_error_t
1053usb_reset_iface_endpoints(struct usb_device *udev, uint8_t iface_index)
1054{
1055        struct usb_endpoint *ep;
1056        struct usb_endpoint *ep_end;
1057
1058        ep = udev->endpoints;
1059        ep_end = udev->endpoints + udev->endpoints_max;
1060
1061        for (; ep != ep_end; ep++) {
1062
1063                if ((ep->edesc == NULL) ||
1064                    (ep->iface_index != iface_index)) {
1065                        continue;
1066                }
1067                /* simulate a clear stall from the peer */
1068                usbd_set_endpoint_stall(udev, ep, 0);
1069        }
1070        return (0);
1071}
1072
1073/*------------------------------------------------------------------------*
1074 *      usb_detach_device_sub
1075 *
1076 * This function will try to detach an USB device. If it fails a panic
1077 * will result.
1078 *
1079 * Flag values, see "USB_UNCFG_FLAG_XXX".
1080 *------------------------------------------------------------------------*/
1081static void
1082usb_detach_device_sub(struct usb_device *udev, device_t *ppdev,
1083    char **ppnpinfo, uint8_t flag)
1084{
1085        device_t dev;
1086        char *pnpinfo;
1087        int err;
1088
1089        dev = *ppdev;
1090        if (dev) {
1091                /*
1092                 * NOTE: It is important to clear "*ppdev" before deleting
1093                 * the child due to some device methods being called late
1094                 * during the delete process !
1095                 */
1096                *ppdev = NULL;
1097
1098                if (!rebooting) {
1099                        device_printf(dev, "at %s, port %d, addr %d "
1100                            "(disconnected)\n",
1101                            device_get_nameunit(udev->parent_dev),
1102                            udev->port_no, udev->address);
1103                }
1104
1105                if (device_is_attached(dev)) {
1106                        if (udev->flags.peer_suspended) {
1107                                err = DEVICE_RESUME(dev);
1108                                if (err) {
1109                                        device_printf(dev, "Resume failed\n");
1110                                }
1111                        }
1112                        if (device_detach(dev)) {
1113                                goto error;
1114                        }
1115                }
1116                if (device_delete_child(udev->parent_dev, dev)) {
1117                        goto error;
1118                }
1119        }
1120
1121        pnpinfo = *ppnpinfo;
1122        if (pnpinfo != NULL) {
1123                *ppnpinfo = NULL;
1124                free(pnpinfo, M_USBDEV);
1125        }
1126        return;
1127
1128error:
1129        /* Detach is not allowed to fail in the USB world */
1130        panic("usb_detach_device_sub: A USB driver would not detach\n");
1131}
1132
1133/*------------------------------------------------------------------------*
1134 *      usb_detach_device
1135 *
1136 * The following function will detach the matching interfaces.
1137 * This function is NULL safe.
1138 *
1139 * Flag values, see "USB_UNCFG_FLAG_XXX".
1140 *------------------------------------------------------------------------*/
1141void
1142usb_detach_device(struct usb_device *udev, uint8_t iface_index,
1143    uint8_t flag)
1144{
1145        struct usb_interface *iface;
1146        uint8_t i;
1147
1148        if (udev == NULL) {
1149                /* nothing to do */
1150                return;
1151        }
1152        DPRINTFN(4, "udev=%p\n", udev);
1153
1154        sx_assert(&udev->enum_sx, SA_LOCKED);
1155
1156        /*
1157         * First detach the child to give the child's detach routine a
1158         * chance to detach the sub-devices in the correct order.
1159         * Then delete the child using "device_delete_child()" which
1160         * will detach all sub-devices from the bottom and upwards!
1161         */
1162        if (iface_index != USB_IFACE_INDEX_ANY) {
1163                i = iface_index;
1164                iface_index = i + 1;
1165        } else {
1166                i = 0;
1167                iface_index = USB_IFACE_MAX;
1168        }
1169
1170        /* do the detach */
1171
1172        for (; i != iface_index; i++) {
1173
1174                iface = usbd_get_iface(udev, i);
1175                if (iface == NULL) {
1176                        /* looks like the end of the USB interfaces */
1177                        break;
1178                }
1179                usb_detach_device_sub(udev, &iface->subdev,
1180                    &iface->pnpinfo, flag);
1181        }
1182}
1183
1184/*------------------------------------------------------------------------*
1185 *      usb_probe_and_attach_sub
1186 *
1187 * Returns:
1188 *    0: Success
1189 * Else: Failure
1190 *------------------------------------------------------------------------*/
1191static uint8_t
1192usb_probe_and_attach_sub(struct usb_device *udev,
1193    struct usb_attach_arg *uaa)
1194{
1195        struct usb_interface *iface;
1196        device_t dev;
1197        int err;
1198
1199        iface = uaa->iface;
1200        if (iface->parent_iface_index != USB_IFACE_INDEX_ANY) {
1201                /* leave interface alone */
1202                return (0);
1203        }
1204        dev = iface->subdev;
1205        if (dev) {
1206
1207                /* clean up after module unload */
1208
1209                if (device_is_attached(dev)) {
1210                        /* already a device there */
1211                        return (0);
1212                }
1213                /* clear "iface->subdev" as early as possible */
1214
1215                iface->subdev = NULL;
1216
1217                if (device_delete_child(udev->parent_dev, dev)) {
1218
1219                        /*
1220                         * Panic here, else one can get a double call
1221                         * to device_detach().  USB devices should
1222                         * never fail on detach!
1223                         */
1224                        panic("device_delete_child() failed\n");
1225                }
1226        }
1227        if (uaa->temp_dev == NULL) {
1228
1229                /* create a new child */
1230                uaa->temp_dev = device_add_child(udev->parent_dev, NULL, -1);
1231                if (uaa->temp_dev == NULL) {
1232                        device_printf(udev->parent_dev,
1233                            "Device creation failed\n");
1234                        return (1);     /* failure */
1235                }
1236                device_set_ivars(uaa->temp_dev, uaa);
1237                device_quiet(uaa->temp_dev);
1238        }
1239        /*
1240         * Set "subdev" before probe and attach so that "devd" gets
1241         * the information it needs.
1242         */
1243        iface->subdev = uaa->temp_dev;
1244
1245        if (device_probe_and_attach(iface->subdev) == 0) {
1246                /*
1247                 * The USB attach arguments are only available during probe
1248                 * and attach !
1249                 */
1250                uaa->temp_dev = NULL;
1251                device_set_ivars(iface->subdev, NULL);
1252
1253                if (udev->flags.peer_suspended) {
1254                        err = DEVICE_SUSPEND(iface->subdev);
1255                        if (err)
1256                                device_printf(iface->subdev, "Suspend failed\n");
1257                }
1258                return (0);             /* success */
1259        } else {
1260                /* No USB driver found */
1261                iface->subdev = NULL;
1262        }
1263        return (1);                     /* failure */
1264}
1265
1266/*------------------------------------------------------------------------*
1267 *      usbd_set_parent_iface
1268 *
1269 * Using this function will lock the alternate interface setting on an
1270 * interface. It is typically used for multi interface drivers. In USB
1271 * device side mode it is assumed that the alternate interfaces all
1272 * have the same endpoint descriptors. The default parent index value
1273 * is "USB_IFACE_INDEX_ANY". Then the alternate setting value is not
1274 * locked.
1275 *------------------------------------------------------------------------*/
1276void
1277usbd_set_parent_iface(struct usb_device *udev, uint8_t iface_index,
1278    uint8_t parent_index)
1279{
1280        struct usb_interface *iface;
1281
1282        if (udev == NULL) {
1283                /* nothing to do */
1284                return;
1285        }
1286        iface = usbd_get_iface(udev, iface_index);
1287        if (iface != NULL)
1288                iface->parent_iface_index = parent_index;
1289}
1290
1291static void
1292usb_init_attach_arg(struct usb_device *udev,
1293    struct usb_attach_arg *uaa)
1294{
1295        memset(uaa, 0, sizeof(*uaa));
1296
1297        uaa->device = udev;
1298        uaa->usb_mode = udev->flags.usb_mode;
1299        uaa->port = udev->port_no;
1300        uaa->dev_state = UAA_DEV_READY;
1301
1302        uaa->info.idVendor = UGETW(udev->ddesc.idVendor);
1303        uaa->info.idProduct = UGETW(udev->ddesc.idProduct);
1304        uaa->info.bcdDevice = UGETW(udev->ddesc.bcdDevice);
1305        uaa->info.bDeviceClass = udev->ddesc.bDeviceClass;
1306        uaa->info.bDeviceSubClass = udev->ddesc.bDeviceSubClass;
1307        uaa->info.bDeviceProtocol = udev->ddesc.bDeviceProtocol;
1308        uaa->info.bConfigIndex = udev->curr_config_index;
1309        uaa->info.bConfigNum = udev->curr_config_no;
1310}
1311
1312/*------------------------------------------------------------------------*
1313 *      usb_probe_and_attach
1314 *
1315 * This function is called from "uhub_explore_sub()",
1316 * "usb_handle_set_config()" and "usb_handle_request()".
1317 *
1318 * Returns:
1319 *    0: Success
1320 * Else: A control transfer failed
1321 *------------------------------------------------------------------------*/
1322usb_error_t
1323usb_probe_and_attach(struct usb_device *udev, uint8_t iface_index)
1324{
1325        struct usb_attach_arg uaa;
1326        struct usb_interface *iface;
1327        uint8_t i;
1328        uint8_t j;
1329        uint8_t do_unlock;
1330
1331        if (udev == NULL) {
1332                DPRINTF("udev == NULL\n");
1333                return (USB_ERR_INVAL);
1334        }
1335        /* Prevent re-enumeration */
1336        do_unlock = usbd_enum_lock(udev);
1337
1338        if (udev->curr_config_index == USB_UNCONFIG_INDEX) {
1339                /* do nothing - no configuration has been set */
1340                goto done;
1341        }
1342        /* setup USB attach arguments */
1343
1344        usb_init_attach_arg(udev, &uaa);
1345
1346        /*
1347         * If the whole USB device is targeted, invoke the USB event
1348         * handler(s):
1349         */
1350        if (iface_index == USB_IFACE_INDEX_ANY) {
1351
1352                if (usb_test_quirk(&uaa, UQ_MSC_DYMO_EJECT) != 0 &&
1353                    usb_dymo_eject(udev, 0) == 0) {
1354                        /* success, mark the udev as disappearing */
1355                        uaa.dev_state = UAA_DEV_EJECTING;
1356                }
1357
1358                EVENTHANDLER_INVOKE(usb_dev_configured, udev, &uaa);
1359
1360                if (uaa.dev_state != UAA_DEV_READY) {
1361                        /* leave device unconfigured */
1362                        usb_unconfigure(udev, 0);
1363                        goto done;
1364                }
1365        }
1366
1367        /* Check if only one interface should be probed: */
1368        if (iface_index != USB_IFACE_INDEX_ANY) {
1369                i = iface_index;
1370                j = i + 1;
1371        } else {
1372                i = 0;
1373                j = USB_IFACE_MAX;
1374        }
1375
1376        /* Do the probe and attach */
1377        for (; i != j; i++) {
1378
1379                iface = usbd_get_iface(udev, i);
1380                if (iface == NULL) {
1381                        /*
1382                         * Looks like the end of the USB
1383                         * interfaces !
1384                         */
1385                        DPRINTFN(2, "end of interfaces "
1386                            "at %u\n", i);
1387                        break;
1388                }
1389                if (iface->idesc == NULL) {
1390                        /* no interface descriptor */
1391                        continue;
1392                }
1393                uaa.iface = iface;
1394
1395                uaa.info.bInterfaceClass =
1396                    iface->idesc->bInterfaceClass;
1397                uaa.info.bInterfaceSubClass =
1398                    iface->idesc->bInterfaceSubClass;
1399                uaa.info.bInterfaceProtocol =
1400                    iface->idesc->bInterfaceProtocol;
1401                uaa.info.bIfaceIndex = i;
1402                uaa.info.bIfaceNum =
1403                    iface->idesc->bInterfaceNumber;
1404                uaa.driver_info = 0;    /* reset driver_info */
1405
1406                DPRINTFN(2, "iclass=%u/%u/%u iindex=%u/%u\n",
1407                    uaa.info.bInterfaceClass,
1408                    uaa.info.bInterfaceSubClass,
1409                    uaa.info.bInterfaceProtocol,
1410                    uaa.info.bIfaceIndex,
1411                    uaa.info.bIfaceNum);
1412
1413                usb_probe_and_attach_sub(udev, &uaa);
1414
1415                /*
1416                 * Remove the leftover child, if any, to enforce that
1417                 * a new nomatch devd event is generated for the next
1418                 * interface if no driver is found:
1419                 */
1420                if (uaa.temp_dev == NULL)
1421                        continue;
1422                if (device_delete_child(udev->parent_dev, uaa.temp_dev))
1423                        DPRINTFN(0, "device delete child failed\n");
1424                uaa.temp_dev = NULL;
1425        }
1426done:
1427        if (do_unlock)
1428                usbd_enum_unlock(udev);
1429        return (0);
1430}
1431
1432/*------------------------------------------------------------------------*
1433 *      usb_suspend_resume_sub
1434 *
1435 * This function is called when the suspend or resume methods should
1436 * be executed on an USB device.
1437 *------------------------------------------------------------------------*/
1438static void
1439usb_suspend_resume_sub(struct usb_device *udev, device_t dev, uint8_t do_suspend)
1440{
1441        int err;
1442
1443        if (dev == NULL) {
1444                return;
1445        }
1446        if (!device_is_attached(dev)) {
1447                return;
1448        }
1449        if (do_suspend) {
1450                err = DEVICE_SUSPEND(dev);
1451        } else {
1452                err = DEVICE_RESUME(dev);
1453        }
1454        if (err) {
1455                device_printf(dev, "%s failed\n",
1456                    do_suspend ? "Suspend" : "Resume");
1457        }
1458}
1459
1460/*------------------------------------------------------------------------*
1461 *      usb_suspend_resume
1462 *
1463 * The following function will suspend or resume the USB device.
1464 *
1465 * Returns:
1466 *    0: Success
1467 * Else: Failure
1468 *------------------------------------------------------------------------*/
1469usb_error_t
1470usb_suspend_resume(struct usb_device *udev, uint8_t do_suspend)
1471{
1472        struct usb_interface *iface;
1473        uint8_t i;
1474
1475        if (udev == NULL) {
1476                /* nothing to do */
1477                return (0);
1478        }
1479        DPRINTFN(4, "udev=%p do_suspend=%d\n", udev, do_suspend);
1480
1481        sx_assert(&udev->sr_sx, SA_LOCKED);
1482
1483        USB_BUS_LOCK(udev->bus);
1484        /* filter the suspend events */
1485        if (udev->flags.peer_suspended == do_suspend) {
1486                USB_BUS_UNLOCK(udev->bus);
1487                /* nothing to do */
1488                return (0);
1489        }
1490        udev->flags.peer_suspended = do_suspend;
1491        USB_BUS_UNLOCK(udev->bus);
1492
1493        /* do the suspend or resume */
1494
1495        for (i = 0; i != USB_IFACE_MAX; i++) {
1496
1497                iface = usbd_get_iface(udev, i);
1498                if (iface == NULL) {
1499                        /* looks like the end of the USB interfaces */
1500                        break;
1501                }
1502                usb_suspend_resume_sub(udev, iface->subdev, do_suspend);
1503        }
1504        return (0);
1505}
1506
1507/*------------------------------------------------------------------------*
1508 *      usbd_clear_stall_proc
1509 *
1510 * This function performs generic USB clear stall operations.
1511 *------------------------------------------------------------------------*/
1512static void
1513usbd_clear_stall_proc(struct usb_proc_msg *_pm)
1514{
1515        struct usb_udev_msg *pm = (void *)_pm;
1516        struct usb_device *udev = pm->udev;
1517
1518        /* Change lock */
1519        USB_BUS_UNLOCK(udev->bus);
1520        mtx_lock(&udev->device_mtx);
1521
1522        /* Start clear stall callback */
1523        usbd_transfer_start(udev->ctrl_xfer[1]);
1524
1525        /* Change lock */
1526        mtx_unlock(&udev->device_mtx);
1527        USB_BUS_LOCK(udev->bus);
1528}
1529
1530/*------------------------------------------------------------------------*
1531 *      usb_alloc_device
1532 *
1533 * This function allocates a new USB device. This function is called
1534 * when a new device has been put in the powered state, but not yet in
1535 * the addressed state. Get initial descriptor, set the address, get
1536 * full descriptor and get strings.
1537 *
1538 * Return values:
1539 *    0: Failure
1540 * Else: Success
1541 *------------------------------------------------------------------------*/
1542struct usb_device *
1543usb_alloc_device(device_t parent_dev, struct usb_bus *bus,
1544    struct usb_device *parent_hub, uint8_t depth, uint8_t port_index,
1545    uint8_t port_no, enum usb_dev_speed speed, enum usb_hc_mode mode)
1546{
1547        struct usb_attach_arg uaa;
1548        struct usb_device *udev;
1549        struct usb_device *adev;
1550        struct usb_device *hub;
1551        uint8_t *scratch_ptr;
1552        usb_error_t err;
1553        uint8_t device_index;
1554        uint8_t config_index;
1555        uint8_t config_quirk;
1556        uint8_t set_config_failed;
1557        uint8_t do_unlock;
1558
1559        DPRINTF("parent_dev=%p, bus=%p, parent_hub=%p, depth=%u, "
1560            "port_index=%u, port_no=%u, speed=%u, usb_mode=%u\n",
1561            parent_dev, bus, parent_hub, depth, port_index, port_no,
1562            speed, mode);
1563
1564        /*
1565         * Find an unused device index. In USB Host mode this is the
1566         * same as the device address.
1567         *
1568         * Device index zero is not used and device index 1 should
1569         * always be the root hub.
1570         */
1571        for (device_index = USB_ROOT_HUB_ADDR;
1572            (device_index != bus->devices_max) &&
1573            (bus->devices[device_index] != NULL);
1574            device_index++) /* nop */;
1575
1576        if (device_index == bus->devices_max) {
1577                device_printf(bus->bdev,
1578                    "No free USB device index for new device\n");
1579                return (NULL);
1580        }
1581
1582        if (depth > 0x10) {
1583                device_printf(bus->bdev,
1584                    "Invalid device depth\n");
1585                return (NULL);
1586        }
1587        udev = malloc(sizeof(*udev), M_USB, M_WAITOK | M_ZERO);
1588        if (udev == NULL) {
1589                return (NULL);
1590        }
1591        /* initialise our SX-lock */
1592        sx_init_flags(&udev->enum_sx, "USB config SX lock", SX_DUPOK);
1593        sx_init_flags(&udev->sr_sx, "USB suspend and resume SX lock", SX_NOWITNESS);
1594
1595        cv_init(&udev->ctrlreq_cv, "WCTRL");
1596        cv_init(&udev->ref_cv, "UGONE");
1597
1598        /* initialise our mutex */
1599        mtx_init(&udev->device_mtx, "USB device mutex", NULL, MTX_DEF);
1600
1601        /* initialise generic clear stall */
1602        udev->cs_msg[0].hdr.pm_callback = &usbd_clear_stall_proc;
1603        udev->cs_msg[0].udev = udev;
1604        udev->cs_msg[1].hdr.pm_callback = &usbd_clear_stall_proc;
1605        udev->cs_msg[1].udev = udev;
1606
1607        /* initialise some USB device fields */
1608        udev->parent_hub = parent_hub;
1609        udev->parent_dev = parent_dev;
1610        udev->port_index = port_index;
1611        udev->port_no = port_no;
1612        udev->depth = depth;
1613        udev->bus = bus;
1614        udev->address = USB_START_ADDR; /* default value */
1615        udev->plugtime = (usb_ticks_t)ticks;
1616        /*
1617         * We need to force the power mode to "on" because there are plenty
1618         * of USB devices out there that do not work very well with
1619         * automatic suspend and resume!
1620         */
1621        udev->power_mode = usbd_filter_power_mode(udev, USB_POWER_MODE_ON);
1622        udev->pwr_save.last_xfer_time = ticks;
1623        /* we are not ready yet */
1624        udev->refcount = 1;
1625
1626        /* set up default endpoint descriptor */
1627        udev->ctrl_ep_desc.bLength = sizeof(udev->ctrl_ep_desc);
1628        udev->ctrl_ep_desc.bDescriptorType = UDESC_ENDPOINT;
1629        udev->ctrl_ep_desc.bEndpointAddress = USB_CONTROL_ENDPOINT;
1630        udev->ctrl_ep_desc.bmAttributes = UE_CONTROL;
1631        udev->ctrl_ep_desc.wMaxPacketSize[0] = USB_MAX_IPACKET;
1632        udev->ctrl_ep_desc.wMaxPacketSize[1] = 0;
1633        udev->ctrl_ep_desc.bInterval = 0;
1634
1635        /* set up default endpoint companion descriptor */
1636        udev->ctrl_ep_comp_desc.bLength = sizeof(udev->ctrl_ep_comp_desc);
1637        udev->ctrl_ep_comp_desc.bDescriptorType = UDESC_ENDPOINT_SS_COMP;
1638
1639        udev->ddesc.bMaxPacketSize = USB_MAX_IPACKET;
1640
1641        udev->speed = speed;
1642        udev->flags.usb_mode = mode;
1643
1644        /* search for our High Speed USB HUB, if any */
1645
1646        adev = udev;
1647        hub = udev->parent_hub;
1648
1649        while (hub) {
1650                if (hub->speed == USB_SPEED_HIGH) {
1651                        udev->hs_hub_addr = hub->address;
1652                        udev->parent_hs_hub = hub;
1653                        udev->hs_port_no = adev->port_no;
1654                        break;
1655                }
1656                adev = hub;
1657                hub = hub->parent_hub;
1658        }
1659
1660        /* init the default endpoint */
1661        usb_init_endpoint(udev, 0,
1662            &udev->ctrl_ep_desc,
1663            &udev->ctrl_ep_comp_desc,
1664            &udev->ctrl_ep);
1665
1666        /* set device index */
1667        udev->device_index = device_index;
1668
1669#if USB_HAVE_UGEN
1670        /* Create ugen name */
1671        snprintf(udev->ugen_name, sizeof(udev->ugen_name),
1672            USB_GENERIC_NAME "%u.%u", device_get_unit(bus->bdev),
1673            device_index);
1674        LIST_INIT(&udev->pd_list);
1675
1676        /* Create the control endpoint device */
1677        udev->ctrl_dev = usb_make_dev(udev, NULL, 0, 0,
1678            FREAD|FWRITE, UID_ROOT, GID_OPERATOR, 0600);
1679
1680        /* Create a link from /dev/ugenX.X to the default endpoint */
1681        if (udev->ctrl_dev != NULL)
1682                make_dev_alias(udev->ctrl_dev->cdev, "%s", udev->ugen_name);
1683#endif
1684        /* Initialise device */
1685        if (bus->methods->device_init != NULL) {
1686                err = (bus->methods->device_init) (udev);
1687                if (err != 0) {
1688                        DPRINTFN(0, "device init %d failed "
1689                            "(%s, ignored)\n", device_index,
1690                            usbd_errstr(err));
1691                        goto done;
1692                }
1693        }
1694        /* set powered device state after device init is complete */
1695        usb_set_device_state(udev, USB_STATE_POWERED);
1696
1697        if (udev->flags.usb_mode == USB_MODE_HOST) {
1698
1699                err = usbd_req_set_address(udev, NULL, device_index);
1700
1701                /*
1702                 * This is the new USB device address from now on, if
1703                 * the set address request didn't set it already.
1704                 */
1705                if (udev->address == USB_START_ADDR)
1706                        udev->address = device_index;
1707
1708                /*
1709                 * We ignore any set-address errors, hence there are
1710                 * buggy USB devices out there that actually receive
1711                 * the SETUP PID, but manage to set the address before
1712                 * the STATUS stage is ACK'ed. If the device responds
1713                 * to the subsequent get-descriptor at the new
1714                 * address, then we know that the set-address command
1715                 * was successful.
1716                 */
1717                if (err) {
1718                        DPRINTFN(0, "set address %d failed "
1719                            "(%s, ignored)\n", udev->address,
1720                            usbd_errstr(err));
1721                }
1722        } else {
1723                /* We are not self powered */
1724                udev->flags.self_powered = 0;
1725
1726                /* Set unconfigured state */
1727                udev->curr_config_no = USB_UNCONFIG_NO;
1728                udev->curr_config_index = USB_UNCONFIG_INDEX;
1729
1730                /* Setup USB descriptors */
1731                err = (usb_temp_setup_by_index_p) (udev, usb_template);
1732                if (err) {
1733                        DPRINTFN(0, "setting up USB template failed maybe the USB "
1734                            "template module has not been loaded\n");
1735                        goto done;
1736                }
1737        }
1738        usb_set_device_state(udev, USB_STATE_ADDRESSED);
1739
1740        /* setup the device descriptor and the initial "wMaxPacketSize" */
1741        err = usbd_setup_device_desc(udev, NULL);
1742
1743        if (err != 0) {
1744                /* try to enumerate two more times */
1745                err = usbd_req_re_enumerate(udev, NULL);
1746                if (err != 0) {
1747                        err = usbd_req_re_enumerate(udev, NULL);
1748                        if (err != 0) {
1749                                goto done;
1750                        }
1751                }
1752        }
1753
1754        /*
1755         * Setup temporary USB attach args so that we can figure out some
1756         * basic quirks for this device.
1757         */
1758        usb_init_attach_arg(udev, &uaa);
1759
1760        if (usb_test_quirk(&uaa, UQ_BUS_POWERED)) {
1761                udev->flags.uq_bus_powered = 1;
1762        }
1763        if (usb_test_quirk(&uaa, UQ_NO_STRINGS)) {
1764                udev->flags.no_strings = 1;
1765        }
1766        /*
1767         * Workaround for buggy USB devices.
1768         *
1769         * It appears that some string-less USB chips will crash and
1770         * disappear if any attempts are made to read any string
1771         * descriptors.
1772         *
1773         * Try to detect such chips by checking the strings in the USB
1774         * device descriptor. If no strings are present there we
1775         * simply disable all USB strings.
1776         */
1777
1778        /* Protect scratch area */
1779        do_unlock = usbd_enum_lock(udev);
1780
1781        scratch_ptr = udev->scratch.data;
1782
1783        if (udev->ddesc.iManufacturer ||
1784            udev->ddesc.iProduct ||
1785            udev->ddesc.iSerialNumber) {
1786                /* read out the language ID string */
1787                err = usbd_req_get_string_desc(udev, NULL,
1788                    (char *)scratch_ptr, 4, 0, USB_LANGUAGE_TABLE);
1789        } else {
1790                err = USB_ERR_INVAL;
1791        }
1792
1793        if (err || (scratch_ptr[0] < 4)) {
1794                udev->flags.no_strings = 1;
1795        } else {
1796                uint16_t langid;
1797                uint16_t pref;
1798                uint16_t mask;
1799                uint8_t x;
1800
1801                /* load preferred value and mask */
1802                pref = usb_lang_id;
1803                mask = usb_lang_mask;
1804
1805                /* align length correctly */
1806                scratch_ptr[0] &= ~1U;
1807
1808                /* fix compiler warning */
1809                langid = 0;
1810
1811                /* search for preferred language */
1812                for (x = 2; (x < scratch_ptr[0]); x += 2) {
1813                        langid = UGETW(scratch_ptr + x);
1814                        if ((langid & mask) == pref)
1815                                break;
1816                }
1817                if (x >= scratch_ptr[0]) {
1818                        /* pick the first language as the default */
1819                        DPRINTFN(1, "Using first language\n");
1820                        langid = UGETW(scratch_ptr + 2);
1821                }
1822
1823                DPRINTFN(1, "Language selected: 0x%04x\n", langid);
1824                udev->langid = langid;
1825        }
1826
1827        if (do_unlock)
1828                usbd_enum_unlock(udev);
1829
1830        /* assume 100mA bus powered for now. Changed when configured. */
1831        udev->power = USB_MIN_POWER;
1832        /* fetch the vendor and product strings from the device */
1833        usbd_set_device_strings(udev);
1834
1835        if (udev->flags.usb_mode == USB_MODE_DEVICE) {
1836                /* USB device mode setup is complete */
1837                err = 0;
1838                goto config_done;
1839        }
1840
1841        /*
1842         * Most USB devices should attach to config index 0 by
1843         * default
1844         */
1845        if (usb_test_quirk(&uaa, UQ_CFG_INDEX_0)) {
1846                config_index = 0;
1847                config_quirk = 1;
1848        } else if (usb_test_quirk(&uaa, UQ_CFG_INDEX_1)) {
1849                config_index = 1;
1850                config_quirk = 1;
1851        } else if (usb_test_quirk(&uaa, UQ_CFG_INDEX_2)) {
1852                config_index = 2;
1853                config_quirk = 1;
1854        } else if (usb_test_quirk(&uaa, UQ_CFG_INDEX_3)) {
1855                config_index = 3;
1856                config_quirk = 1;
1857        } else if (usb_test_quirk(&uaa, UQ_CFG_INDEX_4)) {
1858                config_index = 4;
1859                config_quirk = 1;
1860        } else {
1861                config_index = 0;
1862                config_quirk = 0;
1863        }
1864
1865        set_config_failed = 0;
1866repeat_set_config:
1867
1868        DPRINTF("setting config %u\n", config_index);
1869
1870        /* get the USB device configured */
1871        err = usbd_set_config_index(udev, config_index);
1872        if (err) {
1873                if (udev->ddesc.bNumConfigurations != 0) {
1874                        if (!set_config_failed) {
1875                                set_config_failed = 1;
1876                                /* XXX try to re-enumerate the device */
1877                                err = usbd_req_re_enumerate(udev, NULL);
1878                                if (err == 0)
1879                                        goto repeat_set_config;
1880                        }
1881                        DPRINTFN(0, "Failure selecting configuration index %u:"
1882                            "%s, port %u, addr %u (ignored)\n",
1883                            config_index, usbd_errstr(err), udev->port_no,
1884                            udev->address);
1885                }
1886                /*
1887                 * Some USB devices do not have any configurations. Ignore any
1888                 * set config failures!
1889                 */
1890                err = 0;
1891                goto config_done;
1892        }
1893        if (!config_quirk && config_index + 1 < udev->ddesc.bNumConfigurations) {
1894                if ((udev->cdesc->bNumInterface < 2) &&
1895                    usbd_get_no_descriptors(udev->cdesc, UDESC_ENDPOINT) == 0) {
1896                        DPRINTFN(0, "Found no endpoints, trying next config\n");
1897                        config_index++;
1898                        goto repeat_set_config;
1899                }
1900#if USB_HAVE_MSCTEST
1901                if (config_index == 0) {
1902                        /*
1903                         * Try to figure out if we have an
1904                         * auto-install disk there:
1905                         */
1906                        if (usb_iface_is_cdrom(udev, 0)) {
1907                                DPRINTFN(0, "Found possible auto-install "
1908                                    "disk (trying next config)\n");
1909                                config_index++;
1910                                goto repeat_set_config;
1911                        }
1912                }
1913#endif
1914        }
1915#if USB_HAVE_MSCTEST
1916        if (set_config_failed == 0 && config_index == 0 &&
1917            usb_test_quirk(&uaa, UQ_MSC_NO_SYNC_CACHE) == 0 &&
1918            usb_test_quirk(&uaa, UQ_MSC_NO_GETMAXLUN) == 0) {
1919
1920                /*
1921                 * Try to figure out if there are any MSC quirks we
1922                 * should apply automatically:
1923                 */
1924                err = usb_msc_auto_quirk(udev, 0);
1925
1926                if (err != 0) {
1927                        set_config_failed = 1;
1928                        goto repeat_set_config;
1929                }
1930        }
1931#endif
1932
1933config_done:
1934        DPRINTF("new dev (addr %d), udev=%p, parent_hub=%p\n",
1935            udev->address, udev, udev->parent_hub);
1936
1937        /* register our device - we are ready */
1938        usb_bus_port_set_device(bus, parent_hub ?
1939            parent_hub->hub->ports + port_index : NULL, udev, device_index);
1940
1941#if USB_HAVE_UGEN
1942        /* Symlink the ugen device name */
1943        udev->ugen_symlink = usb_alloc_symlink(udev->ugen_name);
1944
1945        /* Announce device */
1946        printf("%s: <%s> at %s\n", udev->ugen_name,
1947            usb_get_manufacturer(udev),
1948            device_get_nameunit(udev->bus->bdev));
1949#endif
1950
1951#if USB_HAVE_DEVCTL
1952        usb_notify_addq("ATTACH", udev);
1953#endif
1954done:
1955        if (err) {
1956                /*
1957                 * Free USB device and all subdevices, if any.
1958                 */
1959                usb_free_device(udev, 0);
1960                udev = NULL;
1961        }
1962        return (udev);
1963}
1964
1965#if USB_HAVE_UGEN
1966struct usb_fs_privdata *
1967usb_make_dev(struct usb_device *udev, const char *devname, int ep,
1968    int fi, int rwmode, uid_t uid, gid_t gid, int mode)
1969{
1970        struct usb_fs_privdata* pd;
1971        char buffer[32];
1972
1973        /* Store information to locate ourselves again later */
1974        pd = malloc(sizeof(struct usb_fs_privdata), M_USBDEV,
1975            M_WAITOK | M_ZERO);
1976        pd->bus_index = device_get_unit(udev->bus->bdev);
1977        pd->dev_index = udev->device_index;
1978        pd->ep_addr = ep;
1979        pd->fifo_index = fi;
1980        pd->mode = rwmode;
1981
1982        /* Now, create the device itself */
1983        if (devname == NULL) {
1984                devname = buffer;
1985                snprintf(buffer, sizeof(buffer), USB_DEVICE_DIR "/%u.%u.%u",
1986                    pd->bus_index, pd->dev_index, pd->ep_addr);
1987        }
1988
1989        pd->cdev = make_dev(&usb_devsw, 0, uid, gid, mode, "%s", devname);
1990
1991        if (pd->cdev == NULL) {
1992                DPRINTFN(0, "Failed to create device %s\n", devname);
1993                free(pd, M_USBDEV);
1994                return (NULL);
1995        }
1996
1997        /* XXX setting si_drv1 and creating the device is not atomic! */
1998        pd->cdev->si_drv1 = pd;
1999
2000        return (pd);
2001}
2002
2003void
2004usb_destroy_dev_sync(struct usb_fs_privdata *pd)
2005{
2006        DPRINTFN(1, "Destroying device at ugen%d.%d\n",
2007            pd->bus_index, pd->dev_index);
2008
2009        /*
2010         * Destroy character device synchronously. After this
2011         * all system calls are returned. Can block.
2012         */
2013        destroy_dev(pd->cdev);
2014
2015        free(pd, M_USBDEV);
2016}
2017
2018void
2019usb_destroy_dev(struct usb_fs_privdata *pd)
2020{
2021        struct usb_bus *bus;
2022
2023        if (pd == NULL)
2024                return;
2025
2026        mtx_lock(&usb_ref_lock);
2027        bus = devclass_get_softc(usb_devclass_ptr, pd->bus_index);
2028        mtx_unlock(&usb_ref_lock);
2029
2030        if (bus == NULL) {
2031                usb_destroy_dev_sync(pd);
2032                return;
2033        }
2034
2035        /* make sure we can re-use the device name */
2036        delist_dev(pd->cdev);
2037
2038        USB_BUS_LOCK(bus);
2039        LIST_INSERT_HEAD(&bus->pd_cleanup_list, pd, pd_next);
2040        /* get cleanup going */
2041        usb_proc_msignal(USB_BUS_EXPLORE_PROC(bus),
2042            &bus->cleanup_msg[0], &bus->cleanup_msg[1]);
2043        USB_BUS_UNLOCK(bus);
2044}
2045
2046static void
2047usb_cdev_create(struct usb_device *udev)
2048{
2049        struct usb_config_descriptor *cd;
2050        struct usb_endpoint_descriptor *ed;
2051        struct usb_descriptor *desc;
2052        struct usb_fs_privdata* pd;
2053        int inmode, outmode, inmask, outmask, mode;
2054        uint8_t ep;
2055
2056        KASSERT(LIST_FIRST(&udev->pd_list) == NULL, ("stale cdev entries"));
2057
2058        DPRINTFN(2, "Creating device nodes\n");
2059
2060        if (usbd_get_mode(udev) == USB_MODE_DEVICE) {
2061                inmode = FWRITE;
2062                outmode = FREAD;
2063        } else {                 /* USB_MODE_HOST */
2064                inmode = FREAD;
2065                outmode = FWRITE;
2066        }
2067
2068        inmask = 0;
2069        outmask = 0;
2070        desc = NULL;
2071
2072        /*
2073         * Collect all used endpoint numbers instead of just
2074         * generating 16 static endpoints.
2075         */
2076        cd = usbd_get_config_descriptor(udev);
2077        while ((desc = usb_desc_foreach(cd, desc))) {
2078                /* filter out all endpoint descriptors */
2079                if ((desc->bDescriptorType == UDESC_ENDPOINT) &&
2080                    (desc->bLength >= sizeof(*ed))) {
2081                        ed = (struct usb_endpoint_descriptor *)desc;
2082
2083                        /* update masks */
2084                        ep = ed->bEndpointAddress;
2085                        if (UE_GET_DIR(ep)  == UE_DIR_OUT)
2086                                outmask |= 1 << UE_GET_ADDR(ep);
2087                        else
2088                                inmask |= 1 << UE_GET_ADDR(ep);
2089                }
2090        }
2091
2092        /* Create all available endpoints except EP0 */
2093        for (ep = 1; ep < 16; ep++) {
2094                mode = (inmask & (1 << ep)) ? inmode : 0;
2095                mode |= (outmask & (1 << ep)) ? outmode : 0;
2096                if (mode == 0)
2097                        continue;       /* no IN or OUT endpoint */
2098
2099                pd = usb_make_dev(udev, NULL, ep, 0,
2100                    mode, UID_ROOT, GID_OPERATOR, 0600);
2101
2102                if (pd != NULL)
2103                        LIST_INSERT_HEAD(&udev->pd_list, pd, pd_next);
2104        }
2105}
2106
2107static void
2108usb_cdev_free(struct usb_device *udev)
2109{
2110        struct usb_fs_privdata* pd;
2111
2112        DPRINTFN(2, "Freeing device nodes\n");
2113
2114        while ((pd = LIST_FIRST(&udev->pd_list)) != NULL) {
2115                KASSERT(pd->cdev->si_drv1 == pd, ("privdata corrupt"));
2116
2117                LIST_REMOVE(pd, pd_next);
2118
2119                usb_destroy_dev(pd);
2120        }
2121}
2122#endif
2123
2124/*------------------------------------------------------------------------*
2125 *      usb_free_device
2126 *
2127 * This function is NULL safe and will free an USB device and its
2128 * children devices, if any.
2129 *
2130 * Flag values: Reserved, set to zero.
2131 *------------------------------------------------------------------------*/
2132void
2133usb_free_device(struct usb_device *udev, uint8_t flag)
2134{
2135        struct usb_bus *bus;
2136
2137        if (udev == NULL)
2138                return;         /* already freed */
2139
2140        DPRINTFN(4, "udev=%p port=%d\n", udev, udev->port_no);
2141
2142        bus = udev->bus;
2143
2144        /* set DETACHED state to prevent any further references */
2145        usb_set_device_state(udev, USB_STATE_DETACHED);
2146
2147#if USB_HAVE_DEVCTL
2148        usb_notify_addq("DETACH", udev);
2149#endif
2150
2151#if USB_HAVE_UGEN
2152        if (!rebooting) {
2153                printf("%s: <%s> at %s (disconnected)\n", udev->ugen_name,
2154                    usb_get_manufacturer(udev), device_get_nameunit(bus->bdev));
2155        }
2156
2157        /* Destroy UGEN symlink, if any */
2158        if (udev->ugen_symlink) {
2159                usb_free_symlink(udev->ugen_symlink);
2160                udev->ugen_symlink = NULL;
2161        }
2162
2163        usb_destroy_dev(udev->ctrl_dev);
2164#endif
2165
2166        if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2167                /* stop receiving any control transfers (Device Side Mode) */
2168                usbd_transfer_unsetup(udev->ctrl_xfer, USB_CTRL_XFER_MAX);
2169        }
2170
2171        /* the following will get the device unconfigured in software */
2172        usb_unconfigure(udev, USB_UNCFG_FLAG_FREE_EP0);
2173
2174        /* final device unregister after all character devices are closed */
2175        usb_bus_port_set_device(bus, udev->parent_hub ?
2176            udev->parent_hub->hub->ports + udev->port_index : NULL,
2177            NULL, USB_ROOT_HUB_ADDR);
2178
2179        /* unsetup any leftover default USB transfers */
2180        usbd_transfer_unsetup(udev->ctrl_xfer, USB_CTRL_XFER_MAX);
2181
2182        /* template unsetup, if any */
2183        (usb_temp_unsetup_p) (udev);
2184
2185        /*
2186         * Make sure that our clear-stall messages are not queued
2187         * anywhere:
2188         */
2189        USB_BUS_LOCK(udev->bus);
2190        usb_proc_mwait(USB_BUS_CS_PROC(udev->bus),
2191            &udev->cs_msg[0], &udev->cs_msg[1]);
2192        USB_BUS_UNLOCK(udev->bus);
2193
2194        /* wait for all references to go away */
2195        usb_wait_pending_refs(udev);
2196       
2197        sx_destroy(&udev->enum_sx);
2198        sx_destroy(&udev->sr_sx);
2199
2200        cv_destroy(&udev->ctrlreq_cv);
2201        cv_destroy(&udev->ref_cv);
2202
2203        mtx_destroy(&udev->device_mtx);
2204#if USB_HAVE_UGEN
2205        KASSERT(LIST_FIRST(&udev->pd_list) == NULL, ("leaked cdev entries"));
2206#endif
2207
2208        /* Uninitialise device */
2209        if (bus->methods->device_uninit != NULL)
2210                (bus->methods->device_uninit) (udev);
2211
2212        /* free device */
2213        free(udev->serial, M_USB);
2214        free(udev->manufacturer, M_USB);
2215        free(udev->product, M_USB);
2216        free(udev, M_USB);
2217}
2218
2219/*------------------------------------------------------------------------*
2220 *      usbd_get_iface
2221 *
2222 * This function is the safe way to get the USB interface structure
2223 * pointer by interface index.
2224 *
2225 * Return values:
2226 *   NULL: Interface not present.
2227 *   Else: Pointer to USB interface structure.
2228 *------------------------------------------------------------------------*/
2229struct usb_interface *
2230usbd_get_iface(struct usb_device *udev, uint8_t iface_index)
2231{
2232        struct usb_interface *iface = udev->ifaces + iface_index;
2233
2234        if (iface_index >= udev->ifaces_max)
2235                return (NULL);
2236        return (iface);
2237}
2238
2239/*------------------------------------------------------------------------*
2240 *      usbd_find_descriptor
2241 *
2242 * This function will lookup the first descriptor that matches the
2243 * criteria given by the arguments "type" and "subtype". Descriptors
2244 * will only be searched within the interface having the index
2245 * "iface_index".  If the "id" argument points to an USB descriptor,
2246 * it will be skipped before the search is started. This allows
2247 * searching for multiple descriptors using the same criteria. Else
2248 * the search is started after the interface descriptor.
2249 *
2250 * Return values:
2251 *   NULL: End of descriptors
2252 *   Else: A descriptor matching the criteria
2253 *------------------------------------------------------------------------*/
2254void   *
2255usbd_find_descriptor(struct usb_device *udev, void *id, uint8_t iface_index,
2256    uint8_t type, uint8_t type_mask,
2257    uint8_t subtype, uint8_t subtype_mask)
2258{
2259        struct usb_descriptor *desc;
2260        struct usb_config_descriptor *cd;
2261        struct usb_interface *iface;
2262
2263        cd = usbd_get_config_descriptor(udev);
2264        if (cd == NULL) {
2265                return (NULL);
2266        }
2267        if (id == NULL) {
2268                iface = usbd_get_iface(udev, iface_index);
2269                if (iface == NULL) {
2270                        return (NULL);
2271                }
2272                id = usbd_get_interface_descriptor(iface);
2273                if (id == NULL) {
2274                        return (NULL);
2275                }
2276        }
2277        desc = (void *)id;
2278
2279        while ((desc = usb_desc_foreach(cd, desc))) {
2280
2281                if (desc->bDescriptorType == UDESC_INTERFACE) {
2282                        break;
2283                }
2284                if (((desc->bDescriptorType & type_mask) == type) &&
2285                    ((desc->bDescriptorSubtype & subtype_mask) == subtype)) {
2286                        return (desc);
2287                }
2288        }
2289        return (NULL);
2290}
2291
2292/*------------------------------------------------------------------------*
2293 *      usb_devinfo
2294 *
2295 * This function will dump information from the device descriptor
2296 * belonging to the USB device pointed to by "udev", to the string
2297 * pointed to by "dst_ptr" having a maximum length of "dst_len" bytes
2298 * including the terminating zero.
2299 *------------------------------------------------------------------------*/
2300void
2301usb_devinfo(struct usb_device *udev, char *dst_ptr, uint16_t dst_len)
2302{
2303        struct usb_device_descriptor *udd = &udev->ddesc;
2304        uint16_t bcdDevice;
2305        uint16_t bcdUSB;
2306
2307        bcdUSB = UGETW(udd->bcdUSB);
2308        bcdDevice = UGETW(udd->bcdDevice);
2309
2310        if (udd->bDeviceClass != 0xFF) {
2311                snprintf(dst_ptr, dst_len, "%s %s, class %d/%d, rev %x.%02x/"
2312                    "%x.%02x, addr %d",
2313                    usb_get_manufacturer(udev),
2314                    usb_get_product(udev),
2315                    udd->bDeviceClass, udd->bDeviceSubClass,
2316                    (bcdUSB >> 8), bcdUSB & 0xFF,
2317                    (bcdDevice >> 8), bcdDevice & 0xFF,
2318                    udev->address);
2319        } else {
2320                snprintf(dst_ptr, dst_len, "%s %s, rev %x.%02x/"
2321                    "%x.%02x, addr %d",
2322                    usb_get_manufacturer(udev),
2323                    usb_get_product(udev),
2324                    (bcdUSB >> 8), bcdUSB & 0xFF,
2325                    (bcdDevice >> 8), bcdDevice & 0xFF,
2326                    udev->address);
2327        }
2328}
2329
2330#ifdef USB_VERBOSE
2331/*
2332 * Descriptions of of known vendors and devices ("products").
2333 */
2334struct usb_knowndev {
2335        uint16_t vendor;
2336        uint16_t product;
2337        uint32_t flags;
2338        const char *vendorname;
2339        const char *productname;
2340};
2341
2342#define USB_KNOWNDEV_NOPROD     0x01    /* match on vendor only */
2343
2344#include <rtems/bsd/local/usbdevs.h>
2345#include <rtems/bsd/local/usbdevs_data.h>
2346#endif                                  /* USB_VERBOSE */
2347
2348static void
2349usbd_set_device_strings(struct usb_device *udev)
2350{
2351        struct usb_device_descriptor *udd = &udev->ddesc;
2352#ifdef USB_VERBOSE
2353        const struct usb_knowndev *kdp;
2354#endif
2355        char *temp_ptr;
2356        size_t temp_size;
2357        uint16_t vendor_id;
2358        uint16_t product_id;
2359        uint8_t do_unlock;
2360
2361        /* Protect scratch area */
2362        do_unlock = usbd_enum_lock(udev);
2363
2364        temp_ptr = (char *)udev->scratch.data;
2365        temp_size = sizeof(udev->scratch.data);
2366
2367        vendor_id = UGETW(udd->idVendor);
2368        product_id = UGETW(udd->idProduct);
2369
2370        /* get serial number string */
2371        usbd_req_get_string_any(udev, NULL, temp_ptr, temp_size,
2372            udev->ddesc.iSerialNumber);
2373        udev->serial = strdup(temp_ptr, M_USB);
2374
2375        /* get manufacturer string */
2376        usbd_req_get_string_any(udev, NULL, temp_ptr, temp_size,
2377            udev->ddesc.iManufacturer);
2378        usb_trim_spaces(temp_ptr);
2379        if (temp_ptr[0] != '\0')
2380                udev->manufacturer = strdup(temp_ptr, M_USB);
2381
2382        /* get product string */
2383        usbd_req_get_string_any(udev, NULL, temp_ptr, temp_size,
2384            udev->ddesc.iProduct);
2385        usb_trim_spaces(temp_ptr);
2386        if (temp_ptr[0] != '\0')
2387                udev->product = strdup(temp_ptr, M_USB);
2388
2389#ifdef USB_VERBOSE
2390        if (udev->manufacturer == NULL || udev->product == NULL) {
2391                for (kdp = usb_knowndevs; kdp->vendorname != NULL; kdp++) {
2392                        if (kdp->vendor == vendor_id &&
2393                            (kdp->product == product_id ||
2394                            (kdp->flags & USB_KNOWNDEV_NOPROD) != 0))
2395                                break;
2396                }
2397                if (kdp->vendorname != NULL) {
2398                        /* XXX should use pointer to knowndevs string */
2399                        if (udev->manufacturer == NULL) {
2400                                udev->manufacturer = strdup(kdp->vendorname,
2401                                    M_USB);
2402                        }
2403                        if (udev->product == NULL &&
2404                            (kdp->flags & USB_KNOWNDEV_NOPROD) == 0) {
2405                                udev->product = strdup(kdp->productname,
2406                                    M_USB);
2407                        }
2408                }
2409        }
2410#endif
2411        /* Provide default strings if none were found */
2412        if (udev->manufacturer == NULL) {
2413                snprintf(temp_ptr, temp_size, "vendor 0x%04x", vendor_id);
2414                udev->manufacturer = strdup(temp_ptr, M_USB);
2415        }
2416        if (udev->product == NULL) {
2417                snprintf(temp_ptr, temp_size, "product 0x%04x", product_id);
2418                udev->product = strdup(temp_ptr, M_USB);
2419        }
2420
2421        if (do_unlock)
2422                usbd_enum_unlock(udev);
2423}
2424
2425/*
2426 * Returns:
2427 * See: USB_MODE_XXX
2428 */
2429enum usb_hc_mode
2430usbd_get_mode(struct usb_device *udev)
2431{
2432        return (udev->flags.usb_mode);
2433}
2434
2435/*
2436 * Returns:
2437 * See: USB_SPEED_XXX
2438 */
2439enum usb_dev_speed
2440usbd_get_speed(struct usb_device *udev)
2441{
2442        return (udev->speed);
2443}
2444
2445uint32_t
2446usbd_get_isoc_fps(struct usb_device *udev)
2447{
2448        ;                               /* indent fix */
2449        switch (udev->speed) {
2450        case USB_SPEED_LOW:
2451        case USB_SPEED_FULL:
2452                return (1000);
2453        default:
2454                return (8000);
2455        }
2456}
2457
2458struct usb_device_descriptor *
2459usbd_get_device_descriptor(struct usb_device *udev)
2460{
2461        if (udev == NULL)
2462                return (NULL);          /* be NULL safe */
2463        return (&udev->ddesc);
2464}
2465
2466struct usb_config_descriptor *
2467usbd_get_config_descriptor(struct usb_device *udev)
2468{
2469        if (udev == NULL)
2470                return (NULL);          /* be NULL safe */
2471        return (udev->cdesc);
2472}
2473
2474/*------------------------------------------------------------------------*
2475 *      usb_test_quirk - test a device for a given quirk
2476 *
2477 * Return values:
2478 * 0: The USB device does not have the given quirk.
2479 * Else: The USB device has the given quirk.
2480 *------------------------------------------------------------------------*/
2481uint8_t
2482usb_test_quirk(const struct usb_attach_arg *uaa, uint16_t quirk)
2483{
2484        uint8_t found;
2485        uint8_t x;
2486
2487        if (quirk == UQ_NONE)
2488                return (0);
2489
2490        /* search the automatic per device quirks first */
2491
2492        for (x = 0; x != USB_MAX_AUTO_QUIRK; x++) {
2493                if (uaa->device->autoQuirk[x] == quirk)
2494                        return (1);
2495        }
2496
2497        /* search global quirk table, if any */
2498
2499        found = (usb_test_quirk_p) (&uaa->info, quirk);
2500
2501        return (found);
2502}
2503
2504struct usb_interface_descriptor *
2505usbd_get_interface_descriptor(struct usb_interface *iface)
2506{
2507        if (iface == NULL)
2508                return (NULL);          /* be NULL safe */
2509        return (iface->idesc);
2510}
2511
2512uint8_t
2513usbd_get_interface_altindex(struct usb_interface *iface)
2514{
2515        return (iface->alt_index);
2516}
2517
2518uint8_t
2519usbd_get_bus_index(struct usb_device *udev)
2520{
2521        return ((uint8_t)device_get_unit(udev->bus->bdev));
2522}
2523
2524uint8_t
2525usbd_get_device_index(struct usb_device *udev)
2526{
2527        return (udev->device_index);
2528}
2529
2530#if USB_HAVE_DEVCTL
2531static void
2532usb_notify_addq(const char *type, struct usb_device *udev)
2533{
2534        struct usb_interface *iface;
2535        struct sbuf *sb;
2536        int i;
2537
2538        /* announce the device */
2539        sb = sbuf_new_auto();
2540        sbuf_printf(sb,
2541#if USB_HAVE_UGEN
2542            "ugen=%s "
2543            "cdev=%s "
2544#endif
2545            "vendor=0x%04x "
2546            "product=0x%04x "
2547            "devclass=0x%02x "
2548            "devsubclass=0x%02x "
2549            "sernum=\"%s\" "
2550            "release=0x%04x "
2551            "mode=%s "
2552            "port=%u "
2553#if USB_HAVE_UGEN
2554            "parent=%s"
2555#endif
2556            "",
2557#if USB_HAVE_UGEN
2558            udev->ugen_name,
2559            udev->ugen_name,
2560#endif
2561            UGETW(udev->ddesc.idVendor),
2562            UGETW(udev->ddesc.idProduct),
2563            udev->ddesc.bDeviceClass,
2564            udev->ddesc.bDeviceSubClass,
2565            usb_get_serial(udev),
2566            UGETW(udev->ddesc.bcdDevice),
2567            (udev->flags.usb_mode == USB_MODE_HOST) ? "host" : "device",
2568            udev->port_no
2569#if USB_HAVE_UGEN
2570            , udev->parent_hub != NULL ?
2571                udev->parent_hub->ugen_name :
2572                device_get_nameunit(device_get_parent(udev->bus->bdev))
2573#endif
2574            );
2575        sbuf_finish(sb);
2576        devctl_notify("USB", "DEVICE", type, sbuf_data(sb));
2577        sbuf_delete(sb);
2578
2579        /* announce each interface */
2580        for (i = 0; i < USB_IFACE_MAX; i++) {
2581                iface = usbd_get_iface(udev, i);
2582                if (iface == NULL)
2583                        break;          /* end of interfaces */
2584                if (iface->idesc == NULL)
2585                        continue;       /* no interface descriptor */
2586
2587                sb = sbuf_new_auto();
2588                sbuf_printf(sb,
2589#if USB_HAVE_UGEN
2590                    "ugen=%s "
2591                    "cdev=%s "
2592#endif
2593                    "vendor=0x%04x "
2594                    "product=0x%04x "
2595                    "devclass=0x%02x "
2596                    "devsubclass=0x%02x "
2597                    "sernum=\"%s\" "
2598                    "release=0x%04x "
2599                    "mode=%s "
2600                    "interface=%d "
2601                    "endpoints=%d "
2602                    "intclass=0x%02x "
2603                    "intsubclass=0x%02x "
2604                    "intprotocol=0x%02x",
2605#if USB_HAVE_UGEN
2606                    udev->ugen_name,
2607                    udev->ugen_name,
2608#endif
2609                    UGETW(udev->ddesc.idVendor),
2610                    UGETW(udev->ddesc.idProduct),
2611                    udev->ddesc.bDeviceClass,
2612                    udev->ddesc.bDeviceSubClass,
2613                    usb_get_serial(udev),
2614                    UGETW(udev->ddesc.bcdDevice),
2615                    (udev->flags.usb_mode == USB_MODE_HOST) ? "host" : "device",
2616                    iface->idesc->bInterfaceNumber,
2617                    iface->idesc->bNumEndpoints,
2618                    iface->idesc->bInterfaceClass,
2619                    iface->idesc->bInterfaceSubClass,
2620                    iface->idesc->bInterfaceProtocol);
2621                sbuf_finish(sb);
2622                devctl_notify("USB", "INTERFACE", type, sbuf_data(sb));
2623                sbuf_delete(sb);
2624        }
2625}
2626#endif
2627
2628#if USB_HAVE_UGEN
2629/*------------------------------------------------------------------------*
2630 *      usb_fifo_free_wrap
2631 *
2632 * This function will free the FIFOs.
2633 *
2634 * Description of "flag" argument: If the USB_UNCFG_FLAG_FREE_EP0 flag
2635 * is set and "iface_index" is set to "USB_IFACE_INDEX_ANY", we free
2636 * all FIFOs. If the USB_UNCFG_FLAG_FREE_EP0 flag is not set and
2637 * "iface_index" is set to "USB_IFACE_INDEX_ANY", we free all non
2638 * control endpoint FIFOs. If "iface_index" is not set to
2639 * "USB_IFACE_INDEX_ANY" the flag has no effect.
2640 *------------------------------------------------------------------------*/
2641static void
2642usb_fifo_free_wrap(struct usb_device *udev,
2643    uint8_t iface_index, uint8_t flag)
2644{
2645        struct usb_fifo *f;
2646        uint16_t i;
2647
2648        /*
2649         * Free any USB FIFOs on the given interface:
2650         */
2651        for (i = 0; i != USB_FIFO_MAX; i++) {
2652                f = udev->fifo[i];
2653                if (f == NULL) {
2654                        continue;
2655                }
2656                /* Check if the interface index matches */
2657                if (iface_index == f->iface_index) {
2658                        if (f->methods != &usb_ugen_methods) {
2659                                /*
2660                                 * Don't free any non-generic FIFOs in
2661                                 * this case.
2662                                 */
2663                                continue;
2664                        }
2665                        if ((f->dev_ep_index == 0) &&
2666                            (f->fs_xfer == NULL)) {
2667                                /* no need to free this FIFO */
2668                                continue;
2669                        }
2670                } else if (iface_index == USB_IFACE_INDEX_ANY) {
2671                        if ((f->methods == &usb_ugen_methods) &&
2672                            (f->dev_ep_index == 0) &&
2673                            (!(flag & USB_UNCFG_FLAG_FREE_EP0)) &&
2674                            (f->fs_xfer == NULL)) {
2675                                /* no need to free this FIFO */
2676                                continue;
2677                        }
2678                } else {
2679                        /* no need to free this FIFO */
2680                        continue;
2681                }
2682                /* free this FIFO */
2683                usb_fifo_free(f);
2684        }
2685}
2686#endif
2687
2688/*------------------------------------------------------------------------*
2689 *      usb_peer_can_wakeup
2690 *
2691 * Return values:
2692 * 0: Peer cannot do resume signalling.
2693 * Else: Peer can do resume signalling.
2694 *------------------------------------------------------------------------*/
2695uint8_t
2696usb_peer_can_wakeup(struct usb_device *udev)
2697{
2698        const struct usb_config_descriptor *cdp;
2699
2700        cdp = udev->cdesc;
2701        if ((cdp != NULL) && (udev->flags.usb_mode == USB_MODE_HOST)) {
2702                return (cdp->bmAttributes & UC_REMOTE_WAKEUP);
2703        }
2704        return (0);                     /* not supported */
2705}
2706
2707void
2708usb_set_device_state(struct usb_device *udev, enum usb_dev_state state)
2709{
2710
2711        KASSERT(state < USB_STATE_MAX, ("invalid udev state"));
2712
2713        DPRINTF("udev %p state %s -> %s\n", udev,
2714            usb_statestr(udev->state), usb_statestr(state));
2715
2716#if USB_HAVE_UGEN
2717        mtx_lock(&usb_ref_lock);
2718#endif
2719        udev->state = state;
2720#if USB_HAVE_UGEN
2721        mtx_unlock(&usb_ref_lock);
2722#endif
2723        if (udev->bus->methods->device_state_change != NULL)
2724                (udev->bus->methods->device_state_change) (udev);
2725}
2726
2727enum usb_dev_state
2728usb_get_device_state(struct usb_device *udev)
2729{
2730        if (udev == NULL)
2731                return (USB_STATE_DETACHED);
2732        return (udev->state);
2733}
2734
2735uint8_t
2736usbd_device_attached(struct usb_device *udev)
2737{
2738        return (udev->state > USB_STATE_DETACHED);
2739}
2740
2741/*
2742 * The following function locks enumerating the given USB device. If
2743 * the lock is already grabbed this function returns zero. Else a
2744 * non-zero value is returned.
2745 */
2746uint8_t
2747usbd_enum_lock(struct usb_device *udev)
2748{
2749        if (sx_xlocked(&udev->enum_sx))
2750                return (0);
2751
2752        sx_xlock(&udev->enum_sx);
2753        sx_xlock(&udev->sr_sx);
2754        /*
2755         * NEWBUS LOCK NOTE: We should check if any parent SX locks
2756         * are locked before locking Giant. Else the lock can be
2757         * locked multiple times.
2758         */
2759        mtx_lock(&Giant);
2760        return (1);
2761}
2762
2763/* The following function unlocks enumerating the given USB device. */
2764
2765void
2766usbd_enum_unlock(struct usb_device *udev)
2767{
2768        mtx_unlock(&Giant);
2769        sx_xunlock(&udev->enum_sx);
2770        sx_xunlock(&udev->sr_sx);
2771}
2772
2773/* The following function locks suspend and resume. */
2774
2775void
2776usbd_sr_lock(struct usb_device *udev)
2777{
2778        sx_xlock(&udev->sr_sx);
2779        /*
2780         * NEWBUS LOCK NOTE: We should check if any parent SX locks
2781         * are locked before locking Giant. Else the lock can be
2782         * locked multiple times.
2783         */
2784        mtx_lock(&Giant);
2785}
2786
2787/* The following function unlocks suspend and resume. */
2788
2789void
2790usbd_sr_unlock(struct usb_device *udev)
2791{
2792        mtx_unlock(&Giant);
2793        sx_xunlock(&udev->sr_sx);
2794}
2795
2796/*
2797 * The following function checks the enumerating lock for the given
2798 * USB device.
2799 */
2800
2801uint8_t
2802usbd_enum_is_locked(struct usb_device *udev)
2803{
2804        return (sx_xlocked(&udev->enum_sx));
2805}
2806
2807/*
2808 * The following function is used to set the per-interface specific
2809 * plug and play information. The string referred to by the pnpinfo
2810 * argument can safely be freed after calling this function. The
2811 * pnpinfo of an interface will be reset at device detach or when
2812 * passing a NULL argument to this function. This function
2813 * returns zero on success, else a USB_ERR_XXX failure code.
2814 */
2815
2816usb_error_t
2817usbd_set_pnpinfo(struct usb_device *udev, uint8_t iface_index, const char *pnpinfo)
2818{
2819        struct usb_interface *iface;
2820
2821        iface = usbd_get_iface(udev, iface_index);
2822        if (iface == NULL)
2823                return (USB_ERR_INVAL);
2824
2825        if (iface->pnpinfo != NULL) {
2826                free(iface->pnpinfo, M_USBDEV);
2827                iface->pnpinfo = NULL;
2828        }
2829
2830        if (pnpinfo == NULL || pnpinfo[0] == 0)
2831                return (0);             /* success */
2832
2833        iface->pnpinfo = strdup(pnpinfo, M_USBDEV);
2834        if (iface->pnpinfo == NULL)
2835                return (USB_ERR_NOMEM);
2836
2837        return (0);                     /* success */
2838}
2839
2840usb_error_t
2841usbd_add_dynamic_quirk(struct usb_device *udev, uint16_t quirk)
2842{
2843        uint8_t x;
2844
2845        for (x = 0; x != USB_MAX_AUTO_QUIRK; x++) {
2846                if (udev->autoQuirk[x] == 0 ||
2847                    udev->autoQuirk[x] == quirk) {
2848                        udev->autoQuirk[x] = quirk;
2849                        return (0);     /* success */
2850                }
2851        }
2852        return (USB_ERR_NOMEM);
2853}
2854
2855/*
2856 * The following function is used to select the endpoint mode. It
2857 * should not be called outside enumeration context.
2858 */
2859
2860usb_error_t
2861usbd_set_endpoint_mode(struct usb_device *udev, struct usb_endpoint *ep,
2862    uint8_t ep_mode)
2863{   
2864        usb_error_t error;
2865        uint8_t do_unlock;
2866
2867        /* Prevent re-enumeration */
2868        do_unlock = usbd_enum_lock(udev);
2869
2870        if (udev->bus->methods->set_endpoint_mode != NULL) {
2871                error = (udev->bus->methods->set_endpoint_mode) (
2872                    udev, ep, ep_mode);
2873        } else if (ep_mode != USB_EP_MODE_DEFAULT) {
2874                error = USB_ERR_INVAL;
2875        } else {
2876                error = 0;
2877        }
2878
2879        /* only set new mode regardless of error */
2880        ep->ep_mode = ep_mode;
2881
2882        if (do_unlock)
2883                usbd_enum_unlock(udev);
2884        return (error);
2885}
2886
2887uint8_t
2888usbd_get_endpoint_mode(struct usb_device *udev, struct usb_endpoint *ep)
2889{
2890        return (ep->ep_mode);
2891}
Note: See TracBrowser for help on using the repository browser.