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