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