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