File Index
Files and directories
Sign in
FILE

usb.c

File preview with syntax highlighting.

linux-6.19.14/drivers/usb/core/usb.c C
   1// SPDX-License-Identifier: GPL-2.0
   2/*
   3 * drivers/usb/core/usb.c
   4 *
   5 * (C) Copyright Linus Torvalds 1999
   6 * (C) Copyright Johannes Erdfelt 1999-2001
   7 * (C) Copyright Andreas Gal 1999
   8 * (C) Copyright Gregory P. Smith 1999
   9 * (C) Copyright Deti Fliegl 1999 (new USB architecture)
  10 * (C) Copyright Randy Dunlap 2000
  11 * (C) Copyright David Brownell 2000-2004
  12 * (C) Copyright Yggdrasil Computing, Inc. 2000
  13 *     (usb_device_id matching changes by Adam J. Richter)
  14 * (C) Copyright Greg Kroah-Hartman 2002-2003
  15 *
  16 * Released under the GPLv2 only.
  17 *
  18 * NOTE! This is not actually a driver at all, rather this is
  19 * just a collection of helper routines that implement the
  20 * generic USB things that the real drivers can use..
  21 *
  22 * Think of this as a "USB library" rather than anything else,
  23 * with no callbacks.  Callbacks are evil.
  24 */
  25
  26#include <linux/module.h>
  27#include <linux/moduleparam.h>
  28#include <linux/of.h>
  29#include <linux/string.h>
  30#include <linux/bitops.h>
  31#include <linux/slab.h>
  32#include <linux/kmod.h>
  33#include <linux/init.h>
  34#include <linux/spinlock.h>
  35#include <linux/errno.h>
  36#include <linux/usb.h>
  37#include <linux/usb/hcd.h>
  38#include <linux/mutex.h>
  39#include <linux/workqueue.h>
  40#include <linux/debugfs.h>
  41#include <linux/usb/of.h>
  42
  43#include <asm/io.h>
  44#include <linux/scatterlist.h>
  45#include <linux/mm.h>
  46#include <linux/dma-mapping.h>
  47
  48#include "hub.h"
  49#include "trace.h"
  50
  51const char *usbcore_name = "usbcore";
  52
  53static bool nousb;	/* Disable USB when built into kernel image */
  54
  55module_param(nousb, bool, 0444);
  56
  57/*
  58 * for external read access to <nousb>
  59 */
  60int usb_disabled(void)
  61{
  62	return nousb;
  63}
  64EXPORT_SYMBOL_GPL(usb_disabled);
  65
  66#ifdef	CONFIG_PM
  67/* Default delay value, in seconds */
  68static int usb_autosuspend_delay = CONFIG_USB_AUTOSUSPEND_DELAY;
  69module_param_named(autosuspend, usb_autosuspend_delay, int, 0644);
  70MODULE_PARM_DESC(autosuspend, "default autosuspend delay");
  71
  72#else
  73#define usb_autosuspend_delay		0
  74#endif
  75
  76static bool match_endpoint(struct usb_endpoint_descriptor *epd,
  77		struct usb_endpoint_descriptor **bulk_in,
  78		struct usb_endpoint_descriptor **bulk_out,
  79		struct usb_endpoint_descriptor **int_in,
  80		struct usb_endpoint_descriptor **int_out)
  81{
  82	switch (usb_endpoint_type(epd)) {
  83	case USB_ENDPOINT_XFER_BULK:
  84		if (usb_endpoint_dir_in(epd)) {
  85			if (bulk_in && !*bulk_in) {
  86				*bulk_in = epd;
  87				break;
  88			}
  89		} else {
  90			if (bulk_out && !*bulk_out) {
  91				*bulk_out = epd;
  92				break;
  93			}
  94		}
  95
  96		return false;
  97	case USB_ENDPOINT_XFER_INT:
  98		if (usb_endpoint_dir_in(epd)) {
  99			if (int_in && !*int_in) {
 100				*int_in = epd;
 101				break;
 102			}
 103		} else {
 104			if (int_out && !*int_out) {
 105				*int_out = epd;
 106				break;
 107			}
 108		}
 109
 110		return false;
 111	default:
 112		return false;
 113	}
 114
 115	return (!bulk_in || *bulk_in) && (!bulk_out || *bulk_out) &&
 116			(!int_in || *int_in) && (!int_out || *int_out);
 117}
 118
 119/**
 120 * usb_find_common_endpoints() -- look up common endpoint descriptors
 121 * @alt:	alternate setting to search
 122 * @bulk_in:	pointer to descriptor pointer, or NULL
 123 * @bulk_out:	pointer to descriptor pointer, or NULL
 124 * @int_in:	pointer to descriptor pointer, or NULL
 125 * @int_out:	pointer to descriptor pointer, or NULL
 126 *
 127 * Search the alternate setting's endpoint descriptors for the first bulk-in,
 128 * bulk-out, interrupt-in and interrupt-out endpoints and return them in the
 129 * provided pointers (unless they are NULL).
 130 *
 131 * If a requested endpoint is not found, the corresponding pointer is set to
 132 * NULL.
 133 *
 134 * Return: Zero if all requested descriptors were found, or -ENXIO otherwise.
 135 */
 136int usb_find_common_endpoints(struct usb_host_interface *alt,
 137		struct usb_endpoint_descriptor **bulk_in,
 138		struct usb_endpoint_descriptor **bulk_out,
 139		struct usb_endpoint_descriptor **int_in,
 140		struct usb_endpoint_descriptor **int_out)
 141{
 142	struct usb_endpoint_descriptor *epd;
 143	int i;
 144
 145	if (bulk_in)
 146		*bulk_in = NULL;
 147	if (bulk_out)
 148		*bulk_out = NULL;
 149	if (int_in)
 150		*int_in = NULL;
 151	if (int_out)
 152		*int_out = NULL;
 153
 154	for (i = 0; i < alt->desc.bNumEndpoints; ++i) {
 155		epd = &alt->endpoint[i].desc;
 156
 157		if (match_endpoint(epd, bulk_in, bulk_out, int_in, int_out))
 158			return 0;
 159	}
 160
 161	return -ENXIO;
 162}
 163EXPORT_SYMBOL_GPL(usb_find_common_endpoints);
 164
 165/**
 166 * usb_find_common_endpoints_reverse() -- look up common endpoint descriptors
 167 * @alt:	alternate setting to search
 168 * @bulk_in:	pointer to descriptor pointer, or NULL
 169 * @bulk_out:	pointer to descriptor pointer, or NULL
 170 * @int_in:	pointer to descriptor pointer, or NULL
 171 * @int_out:	pointer to descriptor pointer, or NULL
 172 *
 173 * Search the alternate setting's endpoint descriptors for the last bulk-in,
 174 * bulk-out, interrupt-in and interrupt-out endpoints and return them in the
 175 * provided pointers (unless they are NULL).
 176 *
 177 * If a requested endpoint is not found, the corresponding pointer is set to
 178 * NULL.
 179 *
 180 * Return: Zero if all requested descriptors were found, or -ENXIO otherwise.
 181 */
 182int usb_find_common_endpoints_reverse(struct usb_host_interface *alt,
 183		struct usb_endpoint_descriptor **bulk_in,
 184		struct usb_endpoint_descriptor **bulk_out,
 185		struct usb_endpoint_descriptor **int_in,
 186		struct usb_endpoint_descriptor **int_out)
 187{
 188	struct usb_endpoint_descriptor *epd;
 189	int i;
 190
 191	if (bulk_in)
 192		*bulk_in = NULL;
 193	if (bulk_out)
 194		*bulk_out = NULL;
 195	if (int_in)
 196		*int_in = NULL;
 197	if (int_out)
 198		*int_out = NULL;
 199
 200	for (i = alt->desc.bNumEndpoints - 1; i >= 0; --i) {
 201		epd = &alt->endpoint[i].desc;
 202
 203		if (match_endpoint(epd, bulk_in, bulk_out, int_in, int_out))
 204			return 0;
 205	}
 206
 207	return -ENXIO;
 208}
 209EXPORT_SYMBOL_GPL(usb_find_common_endpoints_reverse);
 210
 211/**
 212 * usb_find_endpoint() - Given an endpoint address, search for the endpoint's
 213 * usb_host_endpoint structure in an interface's current altsetting.
 214 * @intf: the interface whose current altsetting should be searched
 215 * @ep_addr: the endpoint address (number and direction) to find
 216 *
 217 * Search the altsetting's list of endpoints for one with the specified address.
 218 *
 219 * Return: Pointer to the usb_host_endpoint if found, %NULL otherwise.
 220 */
 221static const struct usb_host_endpoint *usb_find_endpoint(
 222		const struct usb_interface *intf, unsigned int ep_addr)
 223{
 224	int n;
 225	const struct usb_host_endpoint *ep;
 226
 227	n = intf->cur_altsetting->desc.bNumEndpoints;
 228	ep = intf->cur_altsetting->endpoint;
 229	for (; n > 0; (--n, ++ep)) {
 230		if (ep->desc.bEndpointAddress == ep_addr)
 231			return ep;
 232	}
 233	return NULL;
 234}
 235
 236/**
 237 * usb_check_bulk_endpoints - Check whether an interface's current altsetting
 238 * contains a set of bulk endpoints with the given addresses.
 239 * @intf: the interface whose current altsetting should be searched
 240 * @ep_addrs: 0-terminated array of the endpoint addresses (number and
 241 * direction) to look for
 242 *
 243 * Search for endpoints with the specified addresses and check their types.
 244 *
 245 * Return: %true if all the endpoints are found and are bulk, %false otherwise.
 246 */
 247bool usb_check_bulk_endpoints(
 248		const struct usb_interface *intf, const u8 *ep_addrs)
 249{
 250	const struct usb_host_endpoint *ep;
 251
 252	for (; *ep_addrs; ++ep_addrs) {
 253		ep = usb_find_endpoint(intf, *ep_addrs);
 254		if (!ep || !usb_endpoint_xfer_bulk(&ep->desc))
 255			return false;
 256	}
 257	return true;
 258}
 259EXPORT_SYMBOL_GPL(usb_check_bulk_endpoints);
 260
 261/**
 262 * usb_check_int_endpoints - Check whether an interface's current altsetting
 263 * contains a set of interrupt endpoints with the given addresses.
 264 * @intf: the interface whose current altsetting should be searched
 265 * @ep_addrs: 0-terminated array of the endpoint addresses (number and
 266 * direction) to look for
 267 *
 268 * Search for endpoints with the specified addresses and check their types.
 269 *
 270 * Return: %true if all the endpoints are found and are interrupt,
 271 * %false otherwise.
 272 */
 273bool usb_check_int_endpoints(
 274		const struct usb_interface *intf, const u8 *ep_addrs)
 275{
 276	const struct usb_host_endpoint *ep;
 277
 278	for (; *ep_addrs; ++ep_addrs) {
 279		ep = usb_find_endpoint(intf, *ep_addrs);
 280		if (!ep || !usb_endpoint_xfer_int(&ep->desc))
 281			return false;
 282	}
 283	return true;
 284}
 285EXPORT_SYMBOL_GPL(usb_check_int_endpoints);
 286
 287/**
 288 * usb_find_alt_setting() - Given a configuration, find the alternate setting
 289 * for the given interface.
 290 * @config: the configuration to search (not necessarily the current config).
 291 * @iface_num: interface number to search in
 292 * @alt_num: alternate interface setting number to search for.
 293 *
 294 * Search the configuration's interface cache for the given alt setting.
 295 *
 296 * Return: The alternate setting, if found. %NULL otherwise.
 297 */
 298struct usb_host_interface *usb_find_alt_setting(
 299		struct usb_host_config *config,
 300		unsigned int iface_num,
 301		unsigned int alt_num)
 302{
 303	struct usb_interface_cache *intf_cache = NULL;
 304	int i;
 305
 306	if (!config)
 307		return NULL;
 308	for (i = 0; i < config->desc.bNumInterfaces; i++) {
 309		if (config->intf_cache[i]->altsetting[0].desc.bInterfaceNumber
 310				== iface_num) {
 311			intf_cache = config->intf_cache[i];
 312			break;
 313		}
 314	}
 315	if (!intf_cache)
 316		return NULL;
 317	for (i = 0; i < intf_cache->num_altsetting; i++)
 318		if (intf_cache->altsetting[i].desc.bAlternateSetting == alt_num)
 319			return &intf_cache->altsetting[i];
 320
 321	printk(KERN_DEBUG "Did not find alt setting %u for intf %u, "
 322			"config %u\n", alt_num, iface_num,
 323			config->desc.bConfigurationValue);
 324	return NULL;
 325}
 326EXPORT_SYMBOL_GPL(usb_find_alt_setting);
 327
 328/**
 329 * usb_ifnum_to_if - get the interface object with a given interface number
 330 * @dev: the device whose current configuration is considered
 331 * @ifnum: the desired interface
 332 *
 333 * This walks the device descriptor for the currently active configuration
 334 * to find the interface object with the particular interface number.
 335 *
 336 * Note that configuration descriptors are not required to assign interface
 337 * numbers sequentially, so that it would be incorrect to assume that
 338 * the first interface in that descriptor corresponds to interface zero.
 339 * This routine helps device drivers avoid such mistakes.
 340 * However, you should make sure that you do the right thing with any
 341 * alternate settings available for this interfaces.
 342 *
 343 * Don't call this function unless you are bound to one of the interfaces
 344 * on this device or you have locked the device!
 345 *
 346 * Return: A pointer to the interface that has @ifnum as interface number,
 347 * if found. %NULL otherwise.
 348 */
 349struct usb_interface *usb_ifnum_to_if(const struct usb_device *dev,
 350				      unsigned ifnum)
 351{
 352	struct usb_host_config *config = dev->actconfig;
 353	int i;
 354
 355	if (!config)
 356		return NULL;
 357	for (i = 0; i < config->desc.bNumInterfaces; i++)
 358		if (config->interface[i]->altsetting[0]
 359				.desc.bInterfaceNumber == ifnum)
 360			return config->interface[i];
 361
 362	return NULL;
 363}
 364EXPORT_SYMBOL_GPL(usb_ifnum_to_if);
 365
 366/**
 367 * usb_altnum_to_altsetting - get the altsetting structure with a given alternate setting number.
 368 * @intf: the interface containing the altsetting in question
 369 * @altnum: the desired alternate setting number
 370 *
 371 * This searches the altsetting array of the specified interface for
 372 * an entry with the correct bAlternateSetting value.
 373 *
 374 * Note that altsettings need not be stored sequentially by number, so
 375 * it would be incorrect to assume that the first altsetting entry in
 376 * the array corresponds to altsetting zero.  This routine helps device
 377 * drivers avoid such mistakes.
 378 *
 379 * Don't call this function unless you are bound to the intf interface
 380 * or you have locked the device!
 381 *
 382 * Return: A pointer to the entry of the altsetting array of @intf that
 383 * has @altnum as the alternate setting number. %NULL if not found.
 384 */
 385struct usb_host_interface *usb_altnum_to_altsetting(
 386					const struct usb_interface *intf,
 387					unsigned int altnum)
 388{
 389	int i;
 390
 391	for (i = 0; i < intf->num_altsetting; i++) {
 392		if (intf->altsetting[i].desc.bAlternateSetting == altnum)
 393			return &intf->altsetting[i];
 394	}
 395	return NULL;
 396}
 397EXPORT_SYMBOL_GPL(usb_altnum_to_altsetting);
 398
 399struct find_interface_arg {
 400	int minor;
 401	struct device_driver *drv;
 402};
 403
 404static int __find_interface(struct device *dev, const void *data)
 405{
 406	const struct find_interface_arg *arg = data;
 407	struct usb_interface *intf;
 408
 409	if (!is_usb_interface(dev))
 410		return 0;
 411
 412	if (dev->driver != arg->drv)
 413		return 0;
 414	intf = to_usb_interface(dev);
 415	return intf->minor == arg->minor;
 416}
 417
 418/**
 419 * usb_find_interface - find usb_interface pointer for driver and device
 420 * @drv: the driver whose current configuration is considered
 421 * @minor: the minor number of the desired device
 422 *
 423 * This walks the bus device list and returns a pointer to the interface
 424 * with the matching minor and driver.  Note, this only works for devices
 425 * that share the USB major number.
 426 *
 427 * Return: A pointer to the interface with the matching major and @minor.
 428 */
 429struct usb_interface *usb_find_interface(struct usb_driver *drv, int minor)
 430{
 431	struct find_interface_arg argb;
 432	struct device *dev;
 433
 434	argb.minor = minor;
 435	argb.drv = &drv->driver;
 436
 437	dev = bus_find_device(&usb_bus_type, NULL, &argb, __find_interface);
 438
 439	/* Drop reference count from bus_find_device */
 440	put_device(dev);
 441
 442	return dev ? to_usb_interface(dev) : NULL;
 443}
 444EXPORT_SYMBOL_GPL(usb_find_interface);
 445
 446struct each_dev_arg {
 447	void *data;
 448	int (*fn)(struct usb_device *, void *);
 449};
 450
 451static int __each_dev(struct device *dev, void *data)
 452{
 453	struct each_dev_arg *arg = (struct each_dev_arg *)data;
 454
 455	/* There are struct usb_interface on the same bus, filter them out */
 456	if (!is_usb_device(dev))
 457		return 0;
 458
 459	return arg->fn(to_usb_device(dev), arg->data);
 460}
 461
 462/**
 463 * usb_for_each_dev - iterate over all USB devices in the system
 464 * @data: data pointer that will be handed to the callback function
 465 * @fn: callback function to be called for each USB device
 466 *
 467 * Iterate over all USB devices and call @fn for each, passing it @data. If it
 468 * returns anything other than 0, we break the iteration prematurely and return
 469 * that value.
 470 */
 471int usb_for_each_dev(void *data, int (*fn)(struct usb_device *, void *))
 472{
 473	struct each_dev_arg arg = {data, fn};
 474
 475	return bus_for_each_dev(&usb_bus_type, NULL, &arg, __each_dev);
 476}
 477EXPORT_SYMBOL_GPL(usb_for_each_dev);
 478
 479/**
 480 * usb_release_dev - free a usb device structure when all users of it are finished.
 481 * @dev: device that's been disconnected
 482 *
 483 * Will be called only by the device core when all users of this usb device are
 484 * done.
 485 */
 486static void usb_release_dev(struct device *dev)
 487{
 488	struct usb_device *udev;
 489	struct usb_hcd *hcd;
 490
 491	udev = to_usb_device(dev);
 492	hcd = bus_to_hcd(udev->bus);
 493
 494	usb_destroy_configuration(udev);
 495	usb_release_bos_descriptor(udev);
 496	of_node_put(dev->of_node);
 497	usb_put_hcd(hcd);
 498	kfree(udev->product);
 499	kfree(udev->manufacturer);
 500	kfree(udev->serial);
 501	kfree(udev);
 502}
 503
 504static int usb_dev_uevent(const struct device *dev, struct kobj_uevent_env *env)
 505{
 506	const struct usb_device *usb_dev;
 507
 508	usb_dev = to_usb_device(dev);
 509
 510	if (add_uevent_var(env, "BUSNUM=%03d", usb_dev->bus->busnum))
 511		return -ENOMEM;
 512
 513	if (add_uevent_var(env, "DEVNUM=%03d", usb_dev->devnum))
 514		return -ENOMEM;
 515
 516	return 0;
 517}
 518
 519#ifdef	CONFIG_PM
 520
 521/* USB device Power-Management thunks.
 522 * There's no need to distinguish here between quiescing a USB device
 523 * and powering it down; the generic_suspend() routine takes care of
 524 * it by skipping the usb_port_suspend() call for a quiesce.  And for
 525 * USB interfaces there's no difference at all.
 526 */
 527
 528static int usb_dev_prepare(struct device *dev)
 529{
 530	return 0;		/* Implement eventually? */
 531}
 532
 533static void usb_dev_complete(struct device *dev)
 534{
 535	/* Currently used only for rebinding interfaces */
 536	usb_resume_complete(dev);
 537}
 538
 539static int usb_dev_suspend(struct device *dev)
 540{
 541	return usb_suspend(dev, PMSG_SUSPEND);
 542}
 543
 544static int usb_dev_resume(struct device *dev)
 545{
 546	return usb_resume(dev, PMSG_RESUME);
 547}
 548
 549static int usb_dev_freeze(struct device *dev)
 550{
 551	return usb_suspend(dev, PMSG_FREEZE);
 552}
 553
 554static int usb_dev_thaw(struct device *dev)
 555{
 556	return usb_resume(dev, PMSG_THAW);
 557}
 558
 559static int usb_dev_poweroff(struct device *dev)
 560{
 561	return usb_suspend(dev, PMSG_HIBERNATE);
 562}
 563
 564static int usb_dev_restore(struct device *dev)
 565{
 566	return usb_resume(dev, PMSG_RESTORE);
 567}
 568
 569static const struct dev_pm_ops usb_device_pm_ops = {
 570	.prepare =	usb_dev_prepare,
 571	.complete =	usb_dev_complete,
 572	.suspend =	usb_dev_suspend,
 573	.resume =	usb_dev_resume,
 574	.freeze =	usb_dev_freeze,
 575	.thaw =		usb_dev_thaw,
 576	.poweroff =	usb_dev_poweroff,
 577	.restore =	usb_dev_restore,
 578	.runtime_suspend =	usb_runtime_suspend,
 579	.runtime_resume =	usb_runtime_resume,
 580	.runtime_idle =		usb_runtime_idle,
 581};
 582
 583#endif	/* CONFIG_PM */
 584
 585
 586static char *usb_devnode(const struct device *dev,
 587			 umode_t *mode, kuid_t *uid, kgid_t *gid)
 588{
 589	const struct usb_device *usb_dev;
 590
 591	usb_dev = to_usb_device(dev);
 592	return kasprintf(GFP_KERNEL, "bus/usb/%03d/%03d",
 593			 usb_dev->bus->busnum, usb_dev->devnum);
 594}
 595
 596const struct device_type usb_device_type = {
 597	.name =		"usb_device",
 598	.release =	usb_release_dev,
 599	.uevent =	usb_dev_uevent,
 600	.devnode = 	usb_devnode,
 601#ifdef CONFIG_PM
 602	.pm =		&usb_device_pm_ops,
 603#endif
 604};
 605
 606static bool usb_dev_authorized(struct usb_device *dev, struct usb_hcd *hcd)
 607{
 608	struct usb_hub *hub;
 609
 610	if (!dev->parent)
 611		return true; /* Root hub always ok [and always wired] */
 612
 613	switch (hcd->dev_policy) {
 614	case USB_DEVICE_AUTHORIZE_NONE:
 615	default:
 616		return false;
 617
 618	case USB_DEVICE_AUTHORIZE_ALL:
 619		return true;
 620
 621	case USB_DEVICE_AUTHORIZE_INTERNAL:
 622		hub = usb_hub_to_struct_hub(dev->parent);
 623		return hub->ports[dev->portnum - 1]->connect_type ==
 624				USB_PORT_CONNECT_TYPE_HARD_WIRED;
 625	}
 626}
 627
 628/**
 629 * usb_alloc_dev - usb device constructor (usbcore-internal)
 630 * @parent: hub to which device is connected; null to allocate a root hub
 631 * @bus: bus used to access the device
 632 * @port1: one-based index of port; ignored for root hubs
 633 *
 634 * Context: task context, might sleep.
 635 *
 636 * Only hub drivers (including virtual root hub drivers for host
 637 * controllers) should ever call this.
 638 *
 639 * This call may not be used in a non-sleeping context.
 640 *
 641 * Return: On success, a pointer to the allocated usb device. %NULL on
 642 * failure.
 643 */
 644struct usb_device *usb_alloc_dev(struct usb_device *parent,
 645				 struct usb_bus *bus, unsigned port1)
 646{
 647	struct usb_device *dev;
 648	struct usb_hcd *usb_hcd = bus_to_hcd(bus);
 649	unsigned raw_port = port1;
 650
 651	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
 652	if (!dev)
 653		return NULL;
 654
 655	if (!usb_get_hcd(usb_hcd)) {
 656		kfree(dev);
 657		return NULL;
 658	}
 659	/* Root hubs aren't true devices, so don't allocate HCD resources */
 660	if (usb_hcd->driver->alloc_dev && parent &&
 661		!usb_hcd->driver->alloc_dev(usb_hcd, dev)) {
 662		usb_put_hcd(bus_to_hcd(bus));
 663		kfree(dev);
 664		return NULL;
 665	}
 666
 667	device_initialize(&dev->dev);
 668	dev->dev.bus = &usb_bus_type;
 669	dev->dev.type = &usb_device_type;
 670	dev->dev.groups = usb_device_groups;
 671	set_dev_node(&dev->dev, dev_to_node(bus->sysdev));
 672	dev->state = USB_STATE_ATTACHED;
 673	dev->lpm_disable_count = 1;
 674	spin_lock_init(&dev->offload_lock);
 675	dev->offload_usage = 0;
 676	atomic_set(&dev->urbnum, 0);
 677
 678	INIT_LIST_HEAD(&dev->ep0.urb_list);
 679	dev->ep0.desc.bLength = USB_DT_ENDPOINT_SIZE;
 680	dev->ep0.desc.bDescriptorType = USB_DT_ENDPOINT;
 681	/* ep0 maxpacket comes later, from device descriptor */
 682	usb_enable_endpoint(dev, &dev->ep0, false);
 683	dev->can_submit = 1;
 684
 685	/* Save readable and stable topology id, distinguishing devices
 686	 * by location for diagnostics, tools, driver model, etc.  The
 687	 * string is a path along hub ports, from the root.  Each device's
 688	 * dev->devpath will be stable until USB is re-cabled, and hubs
 689	 * are often labeled with these port numbers.  The name isn't
 690	 * as stable:  bus->busnum changes easily from modprobe order,
 691	 * cardbus or pci hotplugging, and so on.
 692	 */
 693	if (unlikely(!parent)) {
 694		dev->devpath[0] = '0';
 695		dev->route = 0;
 696
 697		dev->dev.parent = bus->controller;
 698		device_set_of_node_from_dev(&dev->dev, bus->sysdev);
 699		dev_set_name(&dev->dev, "usb%d", bus->busnum);
 700	} else {
 701		int n;
 702
 703		/* match any labeling on the hubs; it's one-based */
 704		if (parent->devpath[0] == '0') {
 705			n = snprintf(dev->devpath, sizeof(dev->devpath), "%d", port1);
 706			/* Root ports are not counted in route string */
 707			dev->route = 0;
 708		} else {
 709			n = snprintf(dev->devpath, sizeof(dev->devpath), "%s.%d",
 710				     parent->devpath, port1);
 711			/* Route string assumes hubs have less than 16 ports */
 712			if (port1 < 15)
 713				dev->route = parent->route +
 714					(port1 << ((parent->level - 1)*4));
 715			else
 716				dev->route = parent->route +
 717					(15 << ((parent->level - 1)*4));
 718		}
 719		if (n >= sizeof(dev->devpath)) {
 720			usb_put_hcd(bus_to_hcd(bus));
 721			usb_put_dev(dev);
 722			return NULL;
 723		}
 724
 725		dev->dev.parent = &parent->dev;
 726		dev_set_name(&dev->dev, "%d-%s", bus->busnum, dev->devpath);
 727
 728		if (!parent->parent) {
 729			/* device under root hub's port */
 730			raw_port = usb_hcd_find_raw_port_number(usb_hcd,
 731				port1);
 732		}
 733		dev->dev.of_node = usb_of_get_device_node(parent, raw_port);
 734
 735		/* hub driver sets up TT records */
 736	}
 737
 738	dev->portnum = port1;
 739	dev->bus = bus;
 740	dev->parent = parent;
 741	INIT_LIST_HEAD(&dev->filelist);
 742
 743#ifdef	CONFIG_PM
 744	pm_runtime_set_autosuspend_delay(&dev->dev,
 745			usb_autosuspend_delay * 1000);
 746	dev->connect_time = jiffies;
 747	dev->active_duration = -jiffies;
 748#endif
 749
 750	dev->authorized = usb_dev_authorized(dev, usb_hcd);
 751	trace_usb_alloc_dev(dev);
 752	return dev;
 753}
 754EXPORT_SYMBOL_GPL(usb_alloc_dev);
 755
 756/**
 757 * usb_get_dev - increments the reference count of the usb device structure
 758 * @dev: the device being referenced
 759 *
 760 * Each live reference to a device should be refcounted.
 761 *
 762 * Drivers for USB interfaces should normally record such references in
 763 * their probe() methods, when they bind to an interface, and release
 764 * them by calling usb_put_dev(), in their disconnect() methods.
 765 * However, if a driver does not access the usb_device structure after
 766 * its disconnect() method returns then refcounting is not necessary,
 767 * because the USB core guarantees that a usb_device will not be
 768 * deallocated until after all of its interface drivers have been unbound.
 769 *
 770 * Return: A pointer to the device with the incremented reference counter.
 771 */
 772struct usb_device *usb_get_dev(struct usb_device *dev)
 773{
 774	if (dev)
 775		get_device(&dev->dev);
 776	return dev;
 777}
 778EXPORT_SYMBOL_GPL(usb_get_dev);
 779
 780/**
 781 * usb_put_dev - release a use of the usb device structure
 782 * @dev: device that's been disconnected
 783 *
 784 * Must be called when a user of a device is finished with it.  When the last
 785 * user of the device calls this function, the memory of the device is freed.
 786 */
 787void usb_put_dev(struct usb_device *dev)
 788{
 789	if (dev)
 790		put_device(&dev->dev);
 791}
 792EXPORT_SYMBOL_GPL(usb_put_dev);
 793
 794/**
 795 * usb_get_intf - increments the reference count of the usb interface structure
 796 * @intf: the interface being referenced
 797 *
 798 * Each live reference to a interface must be refcounted.
 799 *
 800 * Drivers for USB interfaces should normally record such references in
 801 * their probe() methods, when they bind to an interface, and release
 802 * them by calling usb_put_intf(), in their disconnect() methods.
 803 * However, if a driver does not access the usb_interface structure after
 804 * its disconnect() method returns then refcounting is not necessary,
 805 * because the USB core guarantees that a usb_interface will not be
 806 * deallocated until after its driver has been unbound.
 807 *
 808 * Return: A pointer to the interface with the incremented reference counter.
 809 */
 810struct usb_interface *usb_get_intf(struct usb_interface *intf)
 811{
 812	if (intf)
 813		get_device(&intf->dev);
 814	return intf;
 815}
 816EXPORT_SYMBOL_GPL(usb_get_intf);
 817
 818/**
 819 * usb_put_intf - release a use of the usb interface structure
 820 * @intf: interface that's been decremented
 821 *
 822 * Must be called when a user of an interface is finished with it.  When the
 823 * last user of the interface calls this function, the memory of the interface
 824 * is freed.
 825 */
 826void usb_put_intf(struct usb_interface *intf)
 827{
 828	if (intf)
 829		put_device(&intf->dev);
 830}
 831EXPORT_SYMBOL_GPL(usb_put_intf);
 832
 833/**
 834 * usb_intf_get_dma_device - acquire a reference on the usb interface's DMA endpoint
 835 * @intf: the usb interface
 836 *
 837 * While a USB device cannot perform DMA operations by itself, many USB
 838 * controllers can. A call to usb_intf_get_dma_device() returns the DMA endpoint
 839 * for the given USB interface, if any. The returned device structure must be
 840 * released with put_device().
 841 *
 842 * See also usb_get_dma_device().
 843 *
 844 * Returns: A reference to the usb interface's DMA endpoint; or NULL if none
 845 *          exists.
 846 */
 847struct device *usb_intf_get_dma_device(struct usb_interface *intf)
 848{
 849	struct usb_device *udev = interface_to_usbdev(intf);
 850	struct device *dmadev;
 851
 852	if (!udev->bus)
 853		return NULL;
 854
 855	dmadev = get_device(udev->bus->sysdev);
 856	if (!dmadev || !dmadev->dma_mask) {
 857		put_device(dmadev);
 858		return NULL;
 859	}
 860
 861	return dmadev;
 862}
 863EXPORT_SYMBOL_GPL(usb_intf_get_dma_device);
 864
 865/*			USB device locking
 866 *
 867 * USB devices and interfaces are locked using the semaphore in their
 868 * embedded struct device.  The hub driver guarantees that whenever a
 869 * device is connected or disconnected, drivers are called with the
 870 * USB device locked as well as their particular interface.
 871 *
 872 * Complications arise when several devices are to be locked at the same
 873 * time.  Only hub-aware drivers that are part of usbcore ever have to
 874 * do this; nobody else needs to worry about it.  The rule for locking
 875 * is simple:
 876 *
 877 *	When locking both a device and its parent, always lock the
 878 *	parent first.
 879 */
 880
 881/**
 882 * usb_lock_device_for_reset - cautiously acquire the lock for a usb device structure
 883 * @udev: device that's being locked
 884 * @iface: interface bound to the driver making the request (optional)
 885 *
 886 * Attempts to acquire the device lock, but fails if the device is
 887 * NOTATTACHED or SUSPENDED, or if iface is specified and the interface
 888 * is neither BINDING nor BOUND.  Rather than sleeping to wait for the
 889 * lock, the routine polls repeatedly.  This is to prevent deadlock with
 890 * disconnect; in some drivers (such as usb-storage) the disconnect()
 891 * or suspend() method will block waiting for a device reset to complete.
 892 *
 893 * Return: A negative error code for failure, otherwise 0.
 894 */
 895int usb_lock_device_for_reset(struct usb_device *udev,
 896			      const struct usb_interface *iface)
 897{
 898	unsigned long jiffies_expire = jiffies + HZ;
 899
 900	if (udev->state == USB_STATE_NOTATTACHED)
 901		return -ENODEV;
 902	if (udev->state == USB_STATE_SUSPENDED)
 903		return -EHOSTUNREACH;
 904	if (iface && (iface->condition == USB_INTERFACE_UNBINDING ||
 905			iface->condition == USB_INTERFACE_UNBOUND))
 906		return -EINTR;
 907
 908	while (!usb_trylock_device(udev)) {
 909
 910		/* If we can't acquire the lock after waiting one second,
 911		 * we're probably deadlocked */
 912		if (time_after(jiffies, jiffies_expire))
 913			return -EBUSY;
 914
 915		msleep(15);
 916		if (udev->state == USB_STATE_NOTATTACHED)
 917			return -ENODEV;
 918		if (udev->state == USB_STATE_SUSPENDED)
 919			return -EHOSTUNREACH;
 920		if (iface && (iface->condition == USB_INTERFACE_UNBINDING ||
 921				iface->condition == USB_INTERFACE_UNBOUND))
 922			return -EINTR;
 923	}
 924	return 0;
 925}
 926EXPORT_SYMBOL_GPL(usb_lock_device_for_reset);
 927
 928/**
 929 * usb_get_current_frame_number - return current bus frame number
 930 * @dev: the device whose bus is being queried
 931 *
 932 * Return: The current frame number for the USB host controller used
 933 * with the given USB device. This can be used when scheduling
 934 * isochronous requests.
 935 *
 936 * Note: Different kinds of host controller have different "scheduling
 937 * horizons". While one type might support scheduling only 32 frames
 938 * into the future, others could support scheduling up to 1024 frames
 939 * into the future.
 940 *
 941 */
 942int usb_get_current_frame_number(struct usb_device *dev)
 943{
 944	return usb_hcd_get_frame_number(dev);
 945}
 946EXPORT_SYMBOL_GPL(usb_get_current_frame_number);
 947
 948/*-------------------------------------------------------------------*/
 949/*
 950 * __usb_get_extra_descriptor() finds a descriptor of specific type in the
 951 * extra field of the interface and endpoint descriptor structs.
 952 */
 953
 954int __usb_get_extra_descriptor(char *buffer, unsigned size,
 955			       unsigned char type, void **ptr, size_t minsize)
 956{
 957	struct usb_descriptor_header *header;
 958
 959	while (size >= sizeof(struct usb_descriptor_header)) {
 960		header = (struct usb_descriptor_header *)buffer;
 961
 962		if (header->bLength < 2 || header->bLength > size) {
 963			printk(KERN_ERR
 964				"%s: bogus descriptor, type %d length %d\n",
 965				usbcore_name,
 966				header->bDescriptorType,
 967				header->bLength);
 968			return -1;
 969		}
 970
 971		if (header->bDescriptorType == type && header->bLength >= minsize) {
 972			*ptr = header;
 973			return 0;
 974		}
 975
 976		buffer += header->bLength;
 977		size -= header->bLength;
 978	}
 979	return -1;
 980}
 981EXPORT_SYMBOL_GPL(__usb_get_extra_descriptor);
 982
 983/**
 984 * usb_alloc_coherent - allocate dma-consistent buffer for URB_NO_xxx_DMA_MAP
 985 * @dev: device the buffer will be used with
 986 * @size: requested buffer size
 987 * @mem_flags: affect whether allocation may block
 988 * @dma: used to return DMA address of buffer
 989 *
 990 * Return: Either null (indicating no buffer could be allocated), or the
 991 * cpu-space pointer to a buffer that may be used to perform DMA to the
 992 * specified device.  Such cpu-space buffers are returned along with the DMA
 993 * address (through the pointer provided).
 994 *
 995 * Note:
 996 * These buffers are used with URB_NO_xxx_DMA_MAP set in urb->transfer_flags
 997 * to avoid behaviors like using "DMA bounce buffers", or thrashing IOMMU
 998 * hardware during URB completion/resubmit.  The implementation varies between
 999 * platforms, depending on details of how DMA will work to this device.
1000 * Using these buffers also eliminates cacheline sharing problems on
1001 * architectures where CPU caches are not DMA-coherent.  On systems without
1002 * bus-snooping caches, these buffers are uncached.
1003 *
1004 * When the buffer is no longer used, free it with usb_free_coherent().
1005 */
1006void *usb_alloc_coherent(struct usb_device *dev, size_t size, gfp_t mem_flags,
1007			 dma_addr_t *dma)
1008{
1009	if (!dev || !dev->bus)
1010		return NULL;
1011	return hcd_buffer_alloc(dev->bus, size, mem_flags, dma);
1012}
1013EXPORT_SYMBOL_GPL(usb_alloc_coherent);
1014
1015/**
1016 * usb_free_coherent - free memory allocated with usb_alloc_coherent()
1017 * @dev: device the buffer was used with
1018 * @size: requested buffer size
1019 * @addr: CPU address of buffer
1020 * @dma: DMA address of buffer
1021 *
1022 * This reclaims an I/O buffer, letting it be reused.  The memory must have
1023 * been allocated using usb_alloc_coherent(), and the parameters must match
1024 * those provided in that allocation request.
1025 */
1026void usb_free_coherent(struct usb_device *dev, size_t size, void *addr,
1027		       dma_addr_t dma)
1028{
1029	if (!dev || !dev->bus)
1030		return;
1031	if (!addr)
1032		return;
1033	hcd_buffer_free(dev->bus, size, addr, dma);
1034}
1035EXPORT_SYMBOL_GPL(usb_free_coherent);
1036
1037/**
1038 * usb_alloc_noncoherent - allocate dma-noncoherent buffer for URB_NO_xxx_DMA_MAP
1039 * @dev: device the buffer will be used with
1040 * @size: requested buffer size
1041 * @mem_flags: affect whether allocation may block
1042 * @dma: used to return DMA address of buffer
1043 * @dir: DMA transfer direction
1044 * @table: used to return sg_table of allocated memory
1045 *
1046 * To explicit manage the memory ownership for the kernel vs the device by
1047 * USB core, the user needs save sg_table to urb->sgt. Then USB core will
1048 * do DMA sync for CPU and device properly.
1049 *
1050 * When the buffer is no longer used, free it with usb_free_noncoherent().
1051 *
1052 * Return: Either null (indicating no buffer could be allocated), or the
1053 * cpu-space pointer to a buffer that may be used to perform DMA to the
1054 * specified device.  Such cpu-space buffers are returned along with the DMA
1055 * address (through the pointer provided).
1056 */
1057void *usb_alloc_noncoherent(struct usb_device *dev, size_t size,
1058			    gfp_t mem_flags, dma_addr_t *dma,
1059			    enum dma_data_direction dir,
1060			    struct sg_table **table)
1061{
1062	struct device *dmadev;
1063	struct sg_table *sgt;
1064	void *buffer;
1065
1066	if (!dev || !dev->bus)
1067		return NULL;
1068
1069	dmadev = bus_to_hcd(dev->bus)->self.sysdev;
1070
1071	sgt = dma_alloc_noncontiguous(dmadev, size, dir, mem_flags, 0);
1072	if (!sgt)
1073		return NULL;
1074
1075	buffer = dma_vmap_noncontiguous(dmadev, size, sgt);
1076	if (!buffer) {
1077		dma_free_noncontiguous(dmadev, size, sgt, dir);
1078		return NULL;
1079	}
1080
1081	*table = sgt;
1082	*dma = sg_dma_address(sgt->sgl);
1083
1084	return buffer;
1085}
1086EXPORT_SYMBOL_GPL(usb_alloc_noncoherent);
1087
1088/**
1089 * usb_free_noncoherent - free memory allocated with usb_alloc_noncoherent()
1090 * @dev: device the buffer was used with
1091 * @size: requested buffer size
1092 * @addr: CPU address of buffer
1093 * @dir: DMA transfer direction
1094 * @table: describe the allocated and DMA mapped memory,
1095 *
1096 * This reclaims an I/O buffer, letting it be reused.  The memory must have
1097 * been allocated using usb_alloc_noncoherent(), and the parameters must match
1098 * those provided in that allocation request.
1099 */
1100void usb_free_noncoherent(struct usb_device *dev, size_t size,
1101			  void *addr, enum dma_data_direction dir,
1102			  struct sg_table *table)
1103{
1104	struct device *dmadev;
1105
1106	if (!dev || !dev->bus)
1107		return;
1108	if (!addr)
1109		return;
1110
1111	dmadev = bus_to_hcd(dev->bus)->self.sysdev;
1112	dma_vunmap_noncontiguous(dmadev, addr);
1113	dma_free_noncontiguous(dmadev, size, table, dir);
1114}
1115EXPORT_SYMBOL_GPL(usb_free_noncoherent);
1116
1117/**
1118 * usb_endpoint_max_periodic_payload - Get maximum payload bytes per service
1119 *				       interval
1120 * @udev: The USB device
1121 * @ep: The endpoint
1122 *
1123 * Returns: the maximum number of bytes isochronous or interrupt endpoint @ep
1124 * can transfer during a service interval, or 0 for other endpoints.
1125 */
1126u32 usb_endpoint_max_periodic_payload(struct usb_device *udev,
1127				      const struct usb_host_endpoint *ep)
1128{
1129	if (!usb_endpoint_xfer_isoc(&ep->desc) &&
1130	    !usb_endpoint_xfer_int(&ep->desc))
1131		return 0;
1132
1133	switch (udev->speed) {
1134	case USB_SPEED_SUPER_PLUS:
1135		if (USB_SS_SSP_ISOC_COMP(ep->ss_ep_comp.bmAttributes))
1136			return le32_to_cpu(ep->ssp_isoc_ep_comp.dwBytesPerInterval);
1137		fallthrough;
1138	case USB_SPEED_SUPER:
1139		return le16_to_cpu(ep->ss_ep_comp.wBytesPerInterval);
1140	default:
1141		if (usb_endpoint_is_hs_isoc_double(udev, ep))
1142			return le32_to_cpu(ep->eusb2_isoc_ep_comp.dwBytesPerInterval);
1143		return usb_endpoint_maxp(&ep->desc) * usb_endpoint_maxp_mult(&ep->desc);
1144	}
1145}
1146EXPORT_SYMBOL_GPL(usb_endpoint_max_periodic_payload);
1147
1148/**
1149 * usb_endpoint_is_hs_isoc_double - Tell whether an endpoint uses USB 2
1150 *                                  Isochronous Double IN Bandwidth
1151 * @udev: The USB device
1152 * @ep: The endpoint
1153 *
1154 * Returns: true if an endpoint @ep conforms to USB 2 Isochronous Double IN
1155 * Bandwidth ECN, false otherwise.
1156 */
1157bool usb_endpoint_is_hs_isoc_double(struct usb_device *udev,
1158				    const struct usb_host_endpoint *ep)
1159{
1160	return ep->eusb2_isoc_ep_comp.bDescriptorType &&
1161		le16_to_cpu(udev->descriptor.bcdUSB) == 0x220 &&
1162		usb_endpoint_is_isoc_in(&ep->desc) &&
1163		!le16_to_cpu(ep->desc.wMaxPacketSize);
1164}
1165EXPORT_SYMBOL_GPL(usb_endpoint_is_hs_isoc_double);
1166
1167/*
1168 * Notifications of device and interface registration
1169 */
1170static int usb_bus_notify(struct notifier_block *nb, unsigned long action,
1171		void *data)
1172{
1173	struct device *dev = data;
1174
1175	switch (action) {
1176	case BUS_NOTIFY_ADD_DEVICE:
1177		if (dev->type == &usb_device_type)
1178			(void) usb_create_sysfs_dev_files(to_usb_device(dev));
1179		else if (dev->type == &usb_if_device_type)
1180			usb_create_sysfs_intf_files(to_usb_interface(dev));
1181		break;
1182
1183	case BUS_NOTIFY_DEL_DEVICE:
1184		if (dev->type == &usb_device_type)
1185			usb_remove_sysfs_dev_files(to_usb_device(dev));
1186		else if (dev->type == &usb_if_device_type)
1187			usb_remove_sysfs_intf_files(to_usb_interface(dev));
1188		break;
1189	}
1190	return 0;
1191}
1192
1193static struct notifier_block usb_bus_nb = {
1194	.notifier_call = usb_bus_notify,
1195};
1196
1197static void usb_debugfs_init(void)
1198{
1199	debugfs_create_file("devices", 0444, usb_debug_root, NULL,
1200			    &usbfs_devices_fops);
1201}
1202
1203static void usb_debugfs_cleanup(void)
1204{
1205	debugfs_lookup_and_remove("devices", usb_debug_root);
1206}
1207
1208/*
1209 * Init
1210 */
1211static int __init usb_init(void)
1212{
1213	int retval;
1214	if (usb_disabled()) {
1215		pr_info("%s: USB support disabled\n", usbcore_name);
1216		return 0;
1217	}
1218	usb_init_pool_max();
1219
1220	usb_debugfs_init();
1221
1222	usb_acpi_register();
1223	retval = bus_register(&usb_bus_type);
1224	if (retval)
1225		goto bus_register_failed;
1226	retval = bus_register_notifier(&usb_bus_type, &usb_bus_nb);
1227	if (retval)
1228		goto bus_notifier_failed;
1229	retval = usb_major_init();
1230	if (retval)
1231		goto major_init_failed;
1232	retval = class_register(&usbmisc_class);
1233	if (retval)
1234		goto class_register_failed;
1235	retval = usb_register(&usbfs_driver);
1236	if (retval)
1237		goto driver_register_failed;
1238	retval = usb_devio_init();
1239	if (retval)
1240		goto usb_devio_init_failed;
1241	retval = usb_hub_init();
1242	if (retval)
1243		goto hub_init_failed;
1244	retval = usb_register_device_driver(&usb_generic_driver, THIS_MODULE);
1245	if (!retval)
1246		goto out;
1247
1248	usb_hub_cleanup();
1249hub_init_failed:
1250	usb_devio_cleanup();
1251usb_devio_init_failed:
1252	usb_deregister(&usbfs_driver);
1253driver_register_failed:
1254	class_unregister(&usbmisc_class);
1255class_register_failed:
1256	usb_major_cleanup();
1257major_init_failed:
1258	bus_unregister_notifier(&usb_bus_type, &usb_bus_nb);
1259bus_notifier_failed:
1260	bus_unregister(&usb_bus_type);
1261bus_register_failed:
1262	usb_acpi_unregister();
1263	usb_debugfs_cleanup();
1264out:
1265	return retval;
1266}
1267
1268/*
1269 * Cleanup
1270 */
1271static void __exit usb_exit(void)
1272{
1273	/* This will matter if shutdown/reboot does exitcalls. */
1274	if (usb_disabled())
1275		return;
1276
1277	usb_release_quirk_list();
1278	usb_deregister_device_driver(&usb_generic_driver);
1279	usb_major_cleanup();
1280	usb_deregister(&usbfs_driver);
1281	usb_devio_cleanup();
1282	usb_hub_cleanup();
1283	class_unregister(&usbmisc_class);
1284	bus_unregister_notifier(&usb_bus_type, &usb_bus_nb);
1285	bus_unregister(&usb_bus_type);
1286	usb_acpi_unregister();
1287	usb_debugfs_cleanup();
1288	idr_destroy(&usb_bus_idr);
1289}
1290
1291subsys_initcall(usb_init);
1292module_exit(usb_exit);
1293MODULE_DESCRIPTION("USB core host-side support");
1294MODULE_LICENSE("GPL");
~/ Read-only file preview.