xref: /linux-6.15/include/linux/usb.h (revision 539adfed)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 #ifndef __LINUX_USB_H
3 #define __LINUX_USB_H
4 
5 #include <linux/mod_devicetable.h>
6 #include <linux/usb/ch9.h>
7 
8 #define USB_MAJOR			180
9 #define USB_DEVICE_MAJOR		189
10 
11 
12 #ifdef __KERNEL__
13 
14 #include <linux/errno.h>        /* for -ENODEV */
15 #include <linux/delay.h>	/* for mdelay() */
16 #include <linux/interrupt.h>	/* for in_interrupt() */
17 #include <linux/list.h>		/* for struct list_head */
18 #include <linux/kref.h>		/* for struct kref */
19 #include <linux/device.h>	/* for struct device */
20 #include <linux/fs.h>		/* for struct file_operations */
21 #include <linux/completion.h>	/* for struct completion */
22 #include <linux/sched.h>	/* for current && schedule_timeout */
23 #include <linux/mutex.h>	/* for struct mutex */
24 #include <linux/pm_runtime.h>	/* for runtime PM */
25 
26 struct usb_device;
27 struct usb_driver;
28 struct wusb_dev;
29 
30 /*-------------------------------------------------------------------------*/
31 
32 /*
33  * Host-side wrappers for standard USB descriptors ... these are parsed
34  * from the data provided by devices.  Parsing turns them from a flat
35  * sequence of descriptors into a hierarchy:
36  *
37  *  - devices have one (usually) or more configs;
38  *  - configs have one (often) or more interfaces;
39  *  - interfaces have one (usually) or more settings;
40  *  - each interface setting has zero or (usually) more endpoints.
41  *  - a SuperSpeed endpoint has a companion descriptor
42  *
43  * And there might be other descriptors mixed in with those.
44  *
45  * Devices may also have class-specific or vendor-specific descriptors.
46  */
47 
48 struct ep_device;
49 
50 /**
51  * struct usb_host_endpoint - host-side endpoint descriptor and queue
52  * @desc: descriptor for this endpoint, wMaxPacketSize in native byteorder
53  * @ss_ep_comp: SuperSpeed companion descriptor for this endpoint
54  * @ssp_isoc_ep_comp: SuperSpeedPlus isoc companion descriptor for this endpoint
55  * @urb_list: urbs queued to this endpoint; maintained by usbcore
56  * @hcpriv: for use by HCD; typically holds hardware dma queue head (QH)
57  *	with one or more transfer descriptors (TDs) per urb
58  * @ep_dev: ep_device for sysfs info
59  * @extra: descriptors following this endpoint in the configuration
60  * @extralen: how many bytes of "extra" are valid
61  * @enabled: URBs may be submitted to this endpoint
62  * @streams: number of USB-3 streams allocated on the endpoint
63  *
64  * USB requests are always queued to a given endpoint, identified by a
65  * descriptor within an active interface in a given USB configuration.
66  */
67 struct usb_host_endpoint {
68 	struct usb_endpoint_descriptor		desc;
69 	struct usb_ss_ep_comp_descriptor	ss_ep_comp;
70 	struct usb_ssp_isoc_ep_comp_descriptor	ssp_isoc_ep_comp;
71 	struct list_head		urb_list;
72 	void				*hcpriv;
73 	struct ep_device		*ep_dev;	/* For sysfs info */
74 
75 	unsigned char *extra;   /* Extra descriptors */
76 	int extralen;
77 	int enabled;
78 	int streams;
79 };
80 
81 /* host-side wrapper for one interface setting's parsed descriptors */
82 struct usb_host_interface {
83 	struct usb_interface_descriptor	desc;
84 
85 	int extralen;
86 	unsigned char *extra;   /* Extra descriptors */
87 
88 	/* array of desc.bNumEndpoints endpoints associated with this
89 	 * interface setting.  these will be in no particular order.
90 	 */
91 	struct usb_host_endpoint *endpoint;
92 
93 	char *string;		/* iInterface string, if present */
94 };
95 
96 enum usb_interface_condition {
97 	USB_INTERFACE_UNBOUND = 0,
98 	USB_INTERFACE_BINDING,
99 	USB_INTERFACE_BOUND,
100 	USB_INTERFACE_UNBINDING,
101 };
102 
103 int __must_check
104 usb_find_common_endpoints(struct usb_host_interface *alt,
105 		struct usb_endpoint_descriptor **bulk_in,
106 		struct usb_endpoint_descriptor **bulk_out,
107 		struct usb_endpoint_descriptor **int_in,
108 		struct usb_endpoint_descriptor **int_out);
109 
110 int __must_check
111 usb_find_common_endpoints_reverse(struct usb_host_interface *alt,
112 		struct usb_endpoint_descriptor **bulk_in,
113 		struct usb_endpoint_descriptor **bulk_out,
114 		struct usb_endpoint_descriptor **int_in,
115 		struct usb_endpoint_descriptor **int_out);
116 
117 static inline int __must_check
118 usb_find_bulk_in_endpoint(struct usb_host_interface *alt,
119 		struct usb_endpoint_descriptor **bulk_in)
120 {
121 	return usb_find_common_endpoints(alt, bulk_in, NULL, NULL, NULL);
122 }
123 
124 static inline int __must_check
125 usb_find_bulk_out_endpoint(struct usb_host_interface *alt,
126 		struct usb_endpoint_descriptor **bulk_out)
127 {
128 	return usb_find_common_endpoints(alt, NULL, bulk_out, NULL, NULL);
129 }
130 
131 static inline int __must_check
132 usb_find_int_in_endpoint(struct usb_host_interface *alt,
133 		struct usb_endpoint_descriptor **int_in)
134 {
135 	return usb_find_common_endpoints(alt, NULL, NULL, int_in, NULL);
136 }
137 
138 static inline int __must_check
139 usb_find_int_out_endpoint(struct usb_host_interface *alt,
140 		struct usb_endpoint_descriptor **int_out)
141 {
142 	return usb_find_common_endpoints(alt, NULL, NULL, NULL, int_out);
143 }
144 
145 static inline int __must_check
146 usb_find_last_bulk_in_endpoint(struct usb_host_interface *alt,
147 		struct usb_endpoint_descriptor **bulk_in)
148 {
149 	return usb_find_common_endpoints_reverse(alt, bulk_in, NULL, NULL, NULL);
150 }
151 
152 static inline int __must_check
153 usb_find_last_bulk_out_endpoint(struct usb_host_interface *alt,
154 		struct usb_endpoint_descriptor **bulk_out)
155 {
156 	return usb_find_common_endpoints_reverse(alt, NULL, bulk_out, NULL, NULL);
157 }
158 
159 static inline int __must_check
160 usb_find_last_int_in_endpoint(struct usb_host_interface *alt,
161 		struct usb_endpoint_descriptor **int_in)
162 {
163 	return usb_find_common_endpoints_reverse(alt, NULL, NULL, int_in, NULL);
164 }
165 
166 static inline int __must_check
167 usb_find_last_int_out_endpoint(struct usb_host_interface *alt,
168 		struct usb_endpoint_descriptor **int_out)
169 {
170 	return usb_find_common_endpoints_reverse(alt, NULL, NULL, NULL, int_out);
171 }
172 
173 enum usb_wireless_status {
174 	USB_WIRELESS_STATUS_NA = 0,
175 	USB_WIRELESS_STATUS_DISCONNECTED,
176 	USB_WIRELESS_STATUS_CONNECTED,
177 };
178 
179 /**
180  * struct usb_interface - what usb device drivers talk to
181  * @altsetting: array of interface structures, one for each alternate
182  *	setting that may be selected.  Each one includes a set of
183  *	endpoint configurations.  They will be in no particular order.
184  * @cur_altsetting: the current altsetting.
185  * @num_altsetting: number of altsettings defined.
186  * @intf_assoc: interface association descriptor
187  * @minor: the minor number assigned to this interface, if this
188  *	interface is bound to a driver that uses the USB major number.
189  *	If this interface does not use the USB major, this field should
190  *	be unused.  The driver should set this value in the probe()
191  *	function of the driver, after it has been assigned a minor
192  *	number from the USB core by calling usb_register_dev().
193  * @condition: binding state of the interface: not bound, binding
194  *	(in probe()), bound to a driver, or unbinding (in disconnect())
195  * @sysfs_files_created: sysfs attributes exist
196  * @ep_devs_created: endpoint child pseudo-devices exist
197  * @unregistering: flag set when the interface is being unregistered
198  * @needs_remote_wakeup: flag set when the driver requires remote-wakeup
199  *	capability during autosuspend.
200  * @needs_altsetting0: flag set when a set-interface request for altsetting 0
201  *	has been deferred.
202  * @needs_binding: flag set when the driver should be re-probed or unbound
203  *	following a reset or suspend operation it doesn't support.
204  * @authorized: This allows to (de)authorize individual interfaces instead
205  *	a whole device in contrast to the device authorization.
206  * @wireless_status: if the USB device uses a receiver/emitter combo, whether
207  *	the emitter is connected.
208  * @wireless_status_work: Used for scheduling wireless status changes
209  *	from atomic context.
210  * @dev: driver model's view of this device
211  * @usb_dev: if an interface is bound to the USB major, this will point
212  *	to the sysfs representation for that device.
213  * @reset_ws: Used for scheduling resets from atomic context.
214  * @resetting_device: USB core reset the device, so use alt setting 0 as
215  *	current; needs bandwidth alloc after reset.
216  *
217  * USB device drivers attach to interfaces on a physical device.  Each
218  * interface encapsulates a single high level function, such as feeding
219  * an audio stream to a speaker or reporting a change in a volume control.
220  * Many USB devices only have one interface.  The protocol used to talk to
221  * an interface's endpoints can be defined in a usb "class" specification,
222  * or by a product's vendor.  The (default) control endpoint is part of
223  * every interface, but is never listed among the interface's descriptors.
224  *
225  * The driver that is bound to the interface can use standard driver model
226  * calls such as dev_get_drvdata() on the dev member of this structure.
227  *
228  * Each interface may have alternate settings.  The initial configuration
229  * of a device sets altsetting 0, but the device driver can change
230  * that setting using usb_set_interface().  Alternate settings are often
231  * used to control the use of periodic endpoints, such as by having
232  * different endpoints use different amounts of reserved USB bandwidth.
233  * All standards-conformant USB devices that use isochronous endpoints
234  * will use them in non-default settings.
235  *
236  * The USB specification says that alternate setting numbers must run from
237  * 0 to one less than the total number of alternate settings.  But some
238  * devices manage to mess this up, and the structures aren't necessarily
239  * stored in numerical order anyhow.  Use usb_altnum_to_altsetting() to
240  * look up an alternate setting in the altsetting array based on its number.
241  */
242 struct usb_interface {
243 	/* array of alternate settings for this interface,
244 	 * stored in no particular order */
245 	struct usb_host_interface *altsetting;
246 
247 	struct usb_host_interface *cur_altsetting;	/* the currently
248 					 * active alternate setting */
249 	unsigned num_altsetting;	/* number of alternate settings */
250 
251 	/* If there is an interface association descriptor then it will list
252 	 * the associated interfaces */
253 	struct usb_interface_assoc_descriptor *intf_assoc;
254 
255 	int minor;			/* minor number this interface is
256 					 * bound to */
257 	enum usb_interface_condition condition;		/* state of binding */
258 	unsigned sysfs_files_created:1;	/* the sysfs attributes exist */
259 	unsigned ep_devs_created:1;	/* endpoint "devices" exist */
260 	unsigned unregistering:1;	/* unregistration is in progress */
261 	unsigned needs_remote_wakeup:1;	/* driver requires remote wakeup */
262 	unsigned needs_altsetting0:1;	/* switch to altsetting 0 is pending */
263 	unsigned needs_binding:1;	/* needs delayed unbind/rebind */
264 	unsigned resetting_device:1;	/* true: bandwidth alloc after reset */
265 	unsigned authorized:1;		/* used for interface authorization */
266 	enum usb_wireless_status wireless_status;
267 	struct work_struct wireless_status_work;
268 
269 	struct device dev;		/* interface specific device info */
270 	struct device *usb_dev;
271 	struct work_struct reset_ws;	/* for resets in atomic context */
272 };
273 
274 #define to_usb_interface(__dev)	container_of_const(__dev, struct usb_interface, dev)
275 
276 static inline void *usb_get_intfdata(struct usb_interface *intf)
277 {
278 	return dev_get_drvdata(&intf->dev);
279 }
280 
281 /**
282  * usb_set_intfdata() - associate driver-specific data with an interface
283  * @intf: USB interface
284  * @data: driver data
285  *
286  * Drivers can use this function in their probe() callbacks to associate
287  * driver-specific data with an interface.
288  *
289  * Note that there is generally no need to clear the driver-data pointer even
290  * if some drivers do so for historical or implementation-specific reasons.
291  */
292 static inline void usb_set_intfdata(struct usb_interface *intf, void *data)
293 {
294 	dev_set_drvdata(&intf->dev, data);
295 }
296 
297 struct usb_interface *usb_get_intf(struct usb_interface *intf);
298 void usb_put_intf(struct usb_interface *intf);
299 
300 /* Hard limit */
301 #define USB_MAXENDPOINTS	30
302 /* this maximum is arbitrary */
303 #define USB_MAXINTERFACES	32
304 #define USB_MAXIADS		(USB_MAXINTERFACES/2)
305 
306 /*
307  * USB Resume Timer: Every Host controller driver should drive the resume
308  * signalling on the bus for the amount of time defined by this macro.
309  *
310  * That way we will have a 'stable' behavior among all HCDs supported by Linux.
311  *
312  * Note that the USB Specification states we should drive resume for *at least*
313  * 20 ms, but it doesn't give an upper bound. This creates two possible
314  * situations which we want to avoid:
315  *
316  * (a) sometimes an msleep(20) might expire slightly before 20 ms, which causes
317  * us to fail USB Electrical Tests, thus failing Certification
318  *
319  * (b) Some (many) devices actually need more than 20 ms of resume signalling,
320  * and while we can argue that's against the USB Specification, we don't have
321  * control over which devices a certification laboratory will be using for
322  * certification. If CertLab uses a device which was tested against Windows and
323  * that happens to have relaxed resume signalling rules, we might fall into
324  * situations where we fail interoperability and electrical tests.
325  *
326  * In order to avoid both conditions, we're using a 40 ms resume timeout, which
327  * should cope with both LPJ calibration errors and devices not following every
328  * detail of the USB Specification.
329  */
330 #define USB_RESUME_TIMEOUT	40 /* ms */
331 
332 /**
333  * struct usb_interface_cache - long-term representation of a device interface
334  * @num_altsetting: number of altsettings defined.
335  * @ref: reference counter.
336  * @altsetting: variable-length array of interface structures, one for
337  *	each alternate setting that may be selected.  Each one includes a
338  *	set of endpoint configurations.  They will be in no particular order.
339  *
340  * These structures persist for the lifetime of a usb_device, unlike
341  * struct usb_interface (which persists only as long as its configuration
342  * is installed).  The altsetting arrays can be accessed through these
343  * structures at any time, permitting comparison of configurations and
344  * providing support for the /sys/kernel/debug/usb/devices pseudo-file.
345  */
346 struct usb_interface_cache {
347 	unsigned num_altsetting;	/* number of alternate settings */
348 	struct kref ref;		/* reference counter */
349 
350 	/* variable-length array of alternate settings for this interface,
351 	 * stored in no particular order */
352 	struct usb_host_interface altsetting[];
353 };
354 #define	ref_to_usb_interface_cache(r) \
355 		container_of(r, struct usb_interface_cache, ref)
356 #define	altsetting_to_usb_interface_cache(a) \
357 		container_of(a, struct usb_interface_cache, altsetting[0])
358 
359 /**
360  * struct usb_host_config - representation of a device's configuration
361  * @desc: the device's configuration descriptor.
362  * @string: pointer to the cached version of the iConfiguration string, if
363  *	present for this configuration.
364  * @intf_assoc: list of any interface association descriptors in this config
365  * @interface: array of pointers to usb_interface structures, one for each
366  *	interface in the configuration.  The number of interfaces is stored
367  *	in desc.bNumInterfaces.  These pointers are valid only while the
368  *	configuration is active.
369  * @intf_cache: array of pointers to usb_interface_cache structures, one
370  *	for each interface in the configuration.  These structures exist
371  *	for the entire life of the device.
372  * @extra: pointer to buffer containing all extra descriptors associated
373  *	with this configuration (those preceding the first interface
374  *	descriptor).
375  * @extralen: length of the extra descriptors buffer.
376  *
377  * USB devices may have multiple configurations, but only one can be active
378  * at any time.  Each encapsulates a different operational environment;
379  * for example, a dual-speed device would have separate configurations for
380  * full-speed and high-speed operation.  The number of configurations
381  * available is stored in the device descriptor as bNumConfigurations.
382  *
383  * A configuration can contain multiple interfaces.  Each corresponds to
384  * a different function of the USB device, and all are available whenever
385  * the configuration is active.  The USB standard says that interfaces
386  * are supposed to be numbered from 0 to desc.bNumInterfaces-1, but a lot
387  * of devices get this wrong.  In addition, the interface array is not
388  * guaranteed to be sorted in numerical order.  Use usb_ifnum_to_if() to
389  * look up an interface entry based on its number.
390  *
391  * Device drivers should not attempt to activate configurations.  The choice
392  * of which configuration to install is a policy decision based on such
393  * considerations as available power, functionality provided, and the user's
394  * desires (expressed through userspace tools).  However, drivers can call
395  * usb_reset_configuration() to reinitialize the current configuration and
396  * all its interfaces.
397  */
398 struct usb_host_config {
399 	struct usb_config_descriptor	desc;
400 
401 	char *string;		/* iConfiguration string, if present */
402 
403 	/* List of any Interface Association Descriptors in this
404 	 * configuration. */
405 	struct usb_interface_assoc_descriptor *intf_assoc[USB_MAXIADS];
406 
407 	/* the interfaces associated with this configuration,
408 	 * stored in no particular order */
409 	struct usb_interface *interface[USB_MAXINTERFACES];
410 
411 	/* Interface information available even when this is not the
412 	 * active configuration */
413 	struct usb_interface_cache *intf_cache[USB_MAXINTERFACES];
414 
415 	unsigned char *extra;   /* Extra descriptors */
416 	int extralen;
417 };
418 
419 /* USB2.0 and USB3.0 device BOS descriptor set */
420 struct usb_host_bos {
421 	struct usb_bos_descriptor	*desc;
422 
423 	/* wireless cap descriptor is handled by wusb */
424 	struct usb_ext_cap_descriptor	*ext_cap;
425 	struct usb_ss_cap_descriptor	*ss_cap;
426 	struct usb_ssp_cap_descriptor	*ssp_cap;
427 	struct usb_ss_container_id_descriptor	*ss_id;
428 	struct usb_ptm_cap_descriptor	*ptm_cap;
429 };
430 
431 int __usb_get_extra_descriptor(char *buffer, unsigned size,
432 	unsigned char type, void **ptr, size_t min);
433 #define usb_get_extra_descriptor(ifpoint, type, ptr) \
434 				__usb_get_extra_descriptor((ifpoint)->extra, \
435 				(ifpoint)->extralen, \
436 				type, (void **)ptr, sizeof(**(ptr)))
437 
438 /* ----------------------------------------------------------------------- */
439 
440 /* USB device number allocation bitmap */
441 struct usb_devmap {
442 	unsigned long devicemap[128 / (8*sizeof(unsigned long))];
443 };
444 
445 /*
446  * Allocated per bus (tree of devices) we have:
447  */
448 struct usb_bus {
449 	struct device *controller;	/* host side hardware */
450 	struct device *sysdev;		/* as seen from firmware or bus */
451 	int busnum;			/* Bus number (in order of reg) */
452 	const char *bus_name;		/* stable id (PCI slot_name etc) */
453 	u8 uses_pio_for_control;	/*
454 					 * Does the host controller use PIO
455 					 * for control transfers?
456 					 */
457 	u8 otg_port;			/* 0, or number of OTG/HNP port */
458 	unsigned is_b_host:1;		/* true during some HNP roleswitches */
459 	unsigned b_hnp_enable:1;	/* OTG: did A-Host enable HNP? */
460 	unsigned no_stop_on_short:1;    /*
461 					 * Quirk: some controllers don't stop
462 					 * the ep queue on a short transfer
463 					 * with the URB_SHORT_NOT_OK flag set.
464 					 */
465 	unsigned no_sg_constraint:1;	/* no sg constraint */
466 	unsigned sg_tablesize;		/* 0 or largest number of sg list entries */
467 
468 	int devnum_next;		/* Next open device number in
469 					 * round-robin allocation */
470 	struct mutex devnum_next_mutex; /* devnum_next mutex */
471 
472 	struct usb_devmap devmap;	/* device address allocation map */
473 	struct usb_device *root_hub;	/* Root hub */
474 	struct usb_bus *hs_companion;	/* Companion EHCI bus, if any */
475 
476 	int bandwidth_allocated;	/* on this bus: how much of the time
477 					 * reserved for periodic (intr/iso)
478 					 * requests is used, on average?
479 					 * Units: microseconds/frame.
480 					 * Limits: Full/low speed reserve 90%,
481 					 * while high speed reserves 80%.
482 					 */
483 	int bandwidth_int_reqs;		/* number of Interrupt requests */
484 	int bandwidth_isoc_reqs;	/* number of Isoc. requests */
485 
486 	unsigned resuming_ports;	/* bit array: resuming root-hub ports */
487 
488 #if defined(CONFIG_USB_MON) || defined(CONFIG_USB_MON_MODULE)
489 	struct mon_bus *mon_bus;	/* non-null when associated */
490 	int monitored;			/* non-zero when monitored */
491 #endif
492 };
493 
494 struct usb_dev_state;
495 
496 /* ----------------------------------------------------------------------- */
497 
498 struct usb_tt;
499 
500 enum usb_port_connect_type {
501 	USB_PORT_CONNECT_TYPE_UNKNOWN = 0,
502 	USB_PORT_CONNECT_TYPE_HOT_PLUG,
503 	USB_PORT_CONNECT_TYPE_HARD_WIRED,
504 	USB_PORT_NOT_USED,
505 };
506 
507 /*
508  * USB port quirks.
509  */
510 
511 /* For the given port, prefer the old (faster) enumeration scheme. */
512 #define USB_PORT_QUIRK_OLD_SCHEME	BIT(0)
513 
514 /* Decrease TRSTRCY to 10ms during device enumeration. */
515 #define USB_PORT_QUIRK_FAST_ENUM	BIT(1)
516 
517 /*
518  * USB 2.0 Link Power Management (LPM) parameters.
519  */
520 struct usb2_lpm_parameters {
521 	/* Best effort service latency indicate how long the host will drive
522 	 * resume on an exit from L1.
523 	 */
524 	unsigned int besl;
525 
526 	/* Timeout value in microseconds for the L1 inactivity (LPM) timer.
527 	 * When the timer counts to zero, the parent hub will initiate a LPM
528 	 * transition to L1.
529 	 */
530 	int timeout;
531 };
532 
533 /*
534  * USB 3.0 Link Power Management (LPM) parameters.
535  *
536  * PEL and SEL are USB 3.0 Link PM latencies for device-initiated LPM exit.
537  * MEL is the USB 3.0 Link PM latency for host-initiated LPM exit.
538  * All three are stored in nanoseconds.
539  */
540 struct usb3_lpm_parameters {
541 	/*
542 	 * Maximum exit latency (MEL) for the host to send a packet to the
543 	 * device (either a Ping for isoc endpoints, or a data packet for
544 	 * interrupt endpoints), the hubs to decode the packet, and for all hubs
545 	 * in the path to transition the links to U0.
546 	 */
547 	unsigned int mel;
548 	/*
549 	 * Maximum exit latency for a device-initiated LPM transition to bring
550 	 * all links into U0.  Abbreviated as "PEL" in section 9.4.12 of the USB
551 	 * 3.0 spec, with no explanation of what "P" stands for.  "Path"?
552 	 */
553 	unsigned int pel;
554 
555 	/*
556 	 * The System Exit Latency (SEL) includes PEL, and three other
557 	 * latencies.  After a device initiates a U0 transition, it will take
558 	 * some time from when the device sends the ERDY to when it will finally
559 	 * receive the data packet.  Basically, SEL should be the worse-case
560 	 * latency from when a device starts initiating a U0 transition to when
561 	 * it will get data.
562 	 */
563 	unsigned int sel;
564 	/*
565 	 * The idle timeout value that is currently programmed into the parent
566 	 * hub for this device.  When the timer counts to zero, the parent hub
567 	 * will initiate an LPM transition to either U1 or U2.
568 	 */
569 	int timeout;
570 };
571 
572 /**
573  * struct usb_device - kernel's representation of a USB device
574  * @devnum: device number; address on a USB bus
575  * @devpath: device ID string for use in messages (e.g., /port/...)
576  * @route: tree topology hex string for use with xHCI
577  * @state: device state: configured, not attached, etc.
578  * @speed: device speed: high/full/low (or error)
579  * @rx_lanes: number of rx lanes in use, USB 3.2 adds dual-lane support
580  * @tx_lanes: number of tx lanes in use, USB 3.2 adds dual-lane support
581  * @ssp_rate: SuperSpeed Plus phy signaling rate and lane count
582  * @tt: Transaction Translator info; used with low/full speed dev, highspeed hub
583  * @ttport: device port on that tt hub
584  * @toggle: one bit for each endpoint, with ([0] = IN, [1] = OUT) endpoints
585  * @parent: our hub, unless we're the root
586  * @bus: bus we're part of
587  * @ep0: endpoint 0 data (default control pipe)
588  * @dev: generic device interface
589  * @descriptor: USB device descriptor
590  * @bos: USB device BOS descriptor set
591  * @config: all of the device's configs
592  * @actconfig: the active configuration
593  * @ep_in: array of IN endpoints
594  * @ep_out: array of OUT endpoints
595  * @rawdescriptors: raw descriptors for each config
596  * @bus_mA: Current available from the bus
597  * @portnum: parent port number (origin 1)
598  * @level: number of USB hub ancestors
599  * @devaddr: device address, XHCI: assigned by HW, others: same as devnum
600  * @can_submit: URBs may be submitted
601  * @persist_enabled:  USB_PERSIST enabled for this device
602  * @reset_in_progress: the device is being reset
603  * @have_langid: whether string_langid is valid
604  * @authorized: policy has said we can use it;
605  *	(user space) policy determines if we authorize this device to be
606  *	used or not. By default, wired USB devices are authorized.
607  *	WUSB devices are not, until we authorize them from user space.
608  *	FIXME -- complete doc
609  * @authenticated: Crypto authentication passed
610  * @wusb: device is Wireless USB
611  * @lpm_capable: device supports LPM
612  * @lpm_devinit_allow: Allow USB3 device initiated LPM, exit latency is in range
613  * @usb2_hw_lpm_capable: device can perform USB2 hardware LPM
614  * @usb2_hw_lpm_besl_capable: device can perform USB2 hardware BESL LPM
615  * @usb2_hw_lpm_enabled: USB2 hardware LPM is enabled
616  * @usb2_hw_lpm_allowed: Userspace allows USB 2.0 LPM to be enabled
617  * @usb3_lpm_u1_enabled: USB3 hardware U1 LPM enabled
618  * @usb3_lpm_u2_enabled: USB3 hardware U2 LPM enabled
619  * @string_langid: language ID for strings
620  * @product: iProduct string, if present (static)
621  * @manufacturer: iManufacturer string, if present (static)
622  * @serial: iSerialNumber string, if present (static)
623  * @filelist: usbfs files that are open to this device
624  * @maxchild: number of ports if hub
625  * @quirks: quirks of the whole device
626  * @urbnum: number of URBs submitted for the whole device
627  * @active_duration: total time device is not suspended
628  * @connect_time: time device was first connected
629  * @do_remote_wakeup:  remote wakeup should be enabled
630  * @reset_resume: needs reset instead of resume
631  * @port_is_suspended: the upstream port is suspended (L2 or U3)
632  * @wusb_dev: if this is a Wireless USB device, link to the WUSB
633  *	specific data for the device.
634  * @slot_id: Slot ID assigned by xHCI
635  * @removable: Device can be physically removed from this port
636  * @l1_params: best effor service latency for USB2 L1 LPM state, and L1 timeout.
637  * @u1_params: exit latencies for USB3 U1 LPM state, and hub-initiated timeout.
638  * @u2_params: exit latencies for USB3 U2 LPM state, and hub-initiated timeout.
639  * @lpm_disable_count: Ref count used by usb_disable_lpm() and usb_enable_lpm()
640  *	to keep track of the number of functions that require USB 3.0 Link Power
641  *	Management to be disabled for this usb_device.  This count should only
642  *	be manipulated by those functions, with the bandwidth_mutex is held.
643  * @hub_delay: cached value consisting of:
644  *	parent->hub_delay + wHubDelay + tTPTransmissionDelay (40ns)
645  *	Will be used as wValue for SetIsochDelay requests.
646  * @use_generic_driver: ask driver core to reprobe using the generic driver.
647  *
648  * Notes:
649  * Usbcore drivers should not set usbdev->state directly.  Instead use
650  * usb_set_device_state().
651  */
652 struct usb_device {
653 	int		devnum;
654 	char		devpath[16];
655 	u32		route;
656 	enum usb_device_state	state;
657 	enum usb_device_speed	speed;
658 	unsigned int		rx_lanes;
659 	unsigned int		tx_lanes;
660 	enum usb_ssp_rate	ssp_rate;
661 
662 	struct usb_tt	*tt;
663 	int		ttport;
664 
665 	unsigned int toggle[2];
666 
667 	struct usb_device *parent;
668 	struct usb_bus *bus;
669 	struct usb_host_endpoint ep0;
670 
671 	struct device dev;
672 
673 	struct usb_device_descriptor descriptor;
674 	struct usb_host_bos *bos;
675 	struct usb_host_config *config;
676 
677 	struct usb_host_config *actconfig;
678 	struct usb_host_endpoint *ep_in[16];
679 	struct usb_host_endpoint *ep_out[16];
680 
681 	char **rawdescriptors;
682 
683 	unsigned short bus_mA;
684 	u8 portnum;
685 	u8 level;
686 	u8 devaddr;
687 
688 	unsigned can_submit:1;
689 	unsigned persist_enabled:1;
690 	unsigned reset_in_progress:1;
691 	unsigned have_langid:1;
692 	unsigned authorized:1;
693 	unsigned authenticated:1;
694 	unsigned wusb:1;
695 	unsigned lpm_capable:1;
696 	unsigned lpm_devinit_allow:1;
697 	unsigned usb2_hw_lpm_capable:1;
698 	unsigned usb2_hw_lpm_besl_capable:1;
699 	unsigned usb2_hw_lpm_enabled:1;
700 	unsigned usb2_hw_lpm_allowed:1;
701 	unsigned usb3_lpm_u1_enabled:1;
702 	unsigned usb3_lpm_u2_enabled:1;
703 	int string_langid;
704 
705 	/* static strings from the device */
706 	char *product;
707 	char *manufacturer;
708 	char *serial;
709 
710 	struct list_head filelist;
711 
712 	int maxchild;
713 
714 	u32 quirks;
715 	atomic_t urbnum;
716 
717 	unsigned long active_duration;
718 
719 #ifdef CONFIG_PM
720 	unsigned long connect_time;
721 
722 	unsigned do_remote_wakeup:1;
723 	unsigned reset_resume:1;
724 	unsigned port_is_suspended:1;
725 #endif
726 	struct wusb_dev *wusb_dev;
727 	int slot_id;
728 	struct usb2_lpm_parameters l1_params;
729 	struct usb3_lpm_parameters u1_params;
730 	struct usb3_lpm_parameters u2_params;
731 	unsigned lpm_disable_count;
732 
733 	u16 hub_delay;
734 	unsigned use_generic_driver:1;
735 };
736 
737 #define to_usb_device(__dev)	container_of_const(__dev, struct usb_device, dev)
738 
739 static inline struct usb_device *__intf_to_usbdev(struct usb_interface *intf)
740 {
741 	return to_usb_device(intf->dev.parent);
742 }
743 static inline const struct usb_device *__intf_to_usbdev_const(const struct usb_interface *intf)
744 {
745 	return to_usb_device((const struct device *)intf->dev.parent);
746 }
747 
748 #define interface_to_usbdev(intf)					\
749 	_Generic((intf),						\
750 		 const struct usb_interface *: __intf_to_usbdev_const,	\
751 		 struct usb_interface *: __intf_to_usbdev)(intf)
752 
753 extern struct usb_device *usb_get_dev(struct usb_device *dev);
754 extern void usb_put_dev(struct usb_device *dev);
755 extern struct usb_device *usb_hub_find_child(struct usb_device *hdev,
756 	int port1);
757 
758 /**
759  * usb_hub_for_each_child - iterate over all child devices on the hub
760  * @hdev:  USB device belonging to the usb hub
761  * @port1: portnum associated with child device
762  * @child: child device pointer
763  */
764 #define usb_hub_for_each_child(hdev, port1, child) \
765 	for (port1 = 1,	child =	usb_hub_find_child(hdev, port1); \
766 			port1 <= hdev->maxchild; \
767 			child = usb_hub_find_child(hdev, ++port1)) \
768 		if (!child) continue; else
769 
770 /* USB device locking */
771 #define usb_lock_device(udev)			device_lock(&(udev)->dev)
772 #define usb_unlock_device(udev)			device_unlock(&(udev)->dev)
773 #define usb_lock_device_interruptible(udev)	device_lock_interruptible(&(udev)->dev)
774 #define usb_trylock_device(udev)		device_trylock(&(udev)->dev)
775 extern int usb_lock_device_for_reset(struct usb_device *udev,
776 				     const struct usb_interface *iface);
777 
778 /* USB port reset for device reinitialization */
779 extern int usb_reset_device(struct usb_device *dev);
780 extern void usb_queue_reset_device(struct usb_interface *dev);
781 
782 extern struct device *usb_intf_get_dma_device(struct usb_interface *intf);
783 
784 #ifdef CONFIG_ACPI
785 extern int usb_acpi_set_power_state(struct usb_device *hdev, int index,
786 	bool enable);
787 extern bool usb_acpi_power_manageable(struct usb_device *hdev, int index);
788 extern int usb_acpi_port_lpm_incapable(struct usb_device *hdev, int index);
789 #else
790 static inline int usb_acpi_set_power_state(struct usb_device *hdev, int index,
791 	bool enable) { return 0; }
792 static inline bool usb_acpi_power_manageable(struct usb_device *hdev, int index)
793 	{ return true; }
794 static inline int usb_acpi_port_lpm_incapable(struct usb_device *hdev, int index)
795 	{ return 0; }
796 #endif
797 
798 /* USB autosuspend and autoresume */
799 #ifdef CONFIG_PM
800 extern void usb_enable_autosuspend(struct usb_device *udev);
801 extern void usb_disable_autosuspend(struct usb_device *udev);
802 
803 extern int usb_autopm_get_interface(struct usb_interface *intf);
804 extern void usb_autopm_put_interface(struct usb_interface *intf);
805 extern int usb_autopm_get_interface_async(struct usb_interface *intf);
806 extern void usb_autopm_put_interface_async(struct usb_interface *intf);
807 extern void usb_autopm_get_interface_no_resume(struct usb_interface *intf);
808 extern void usb_autopm_put_interface_no_suspend(struct usb_interface *intf);
809 
810 static inline void usb_mark_last_busy(struct usb_device *udev)
811 {
812 	pm_runtime_mark_last_busy(&udev->dev);
813 }
814 
815 #else
816 
817 static inline int usb_enable_autosuspend(struct usb_device *udev)
818 { return 0; }
819 static inline int usb_disable_autosuspend(struct usb_device *udev)
820 { return 0; }
821 
822 static inline int usb_autopm_get_interface(struct usb_interface *intf)
823 { return 0; }
824 static inline int usb_autopm_get_interface_async(struct usb_interface *intf)
825 { return 0; }
826 
827 static inline void usb_autopm_put_interface(struct usb_interface *intf)
828 { }
829 static inline void usb_autopm_put_interface_async(struct usb_interface *intf)
830 { }
831 static inline void usb_autopm_get_interface_no_resume(
832 		struct usb_interface *intf)
833 { }
834 static inline void usb_autopm_put_interface_no_suspend(
835 		struct usb_interface *intf)
836 { }
837 static inline void usb_mark_last_busy(struct usb_device *udev)
838 { }
839 #endif
840 
841 extern int usb_disable_lpm(struct usb_device *udev);
842 extern void usb_enable_lpm(struct usb_device *udev);
843 /* Same as above, but these functions lock/unlock the bandwidth_mutex. */
844 extern int usb_unlocked_disable_lpm(struct usb_device *udev);
845 extern void usb_unlocked_enable_lpm(struct usb_device *udev);
846 
847 extern int usb_disable_ltm(struct usb_device *udev);
848 extern void usb_enable_ltm(struct usb_device *udev);
849 
850 static inline bool usb_device_supports_ltm(struct usb_device *udev)
851 {
852 	if (udev->speed < USB_SPEED_SUPER || !udev->bos || !udev->bos->ss_cap)
853 		return false;
854 	return udev->bos->ss_cap->bmAttributes & USB_LTM_SUPPORT;
855 }
856 
857 static inline bool usb_device_no_sg_constraint(struct usb_device *udev)
858 {
859 	return udev && udev->bus && udev->bus->no_sg_constraint;
860 }
861 
862 
863 /*-------------------------------------------------------------------------*/
864 
865 /* for drivers using iso endpoints */
866 extern int usb_get_current_frame_number(struct usb_device *usb_dev);
867 
868 /* Sets up a group of bulk endpoints to support multiple stream IDs. */
869 extern int usb_alloc_streams(struct usb_interface *interface,
870 		struct usb_host_endpoint **eps, unsigned int num_eps,
871 		unsigned int num_streams, gfp_t mem_flags);
872 
873 /* Reverts a group of bulk endpoints back to not using stream IDs. */
874 extern int usb_free_streams(struct usb_interface *interface,
875 		struct usb_host_endpoint **eps, unsigned int num_eps,
876 		gfp_t mem_flags);
877 
878 /* used these for multi-interface device registration */
879 extern int usb_driver_claim_interface(struct usb_driver *driver,
880 			struct usb_interface *iface, void *data);
881 
882 /**
883  * usb_interface_claimed - returns true iff an interface is claimed
884  * @iface: the interface being checked
885  *
886  * Return: %true (nonzero) iff the interface is claimed, else %false
887  * (zero).
888  *
889  * Note:
890  * Callers must own the driver model's usb bus readlock.  So driver
891  * probe() entries don't need extra locking, but other call contexts
892  * may need to explicitly claim that lock.
893  *
894  */
895 static inline int usb_interface_claimed(struct usb_interface *iface)
896 {
897 	return (iface->dev.driver != NULL);
898 }
899 
900 extern void usb_driver_release_interface(struct usb_driver *driver,
901 			struct usb_interface *iface);
902 
903 int usb_set_wireless_status(struct usb_interface *iface,
904 			enum usb_wireless_status status);
905 
906 const struct usb_device_id *usb_match_id(struct usb_interface *interface,
907 					 const struct usb_device_id *id);
908 extern int usb_match_one_id(struct usb_interface *interface,
909 			    const struct usb_device_id *id);
910 
911 extern int usb_for_each_dev(void *data, int (*fn)(struct usb_device *, void *));
912 extern struct usb_interface *usb_find_interface(struct usb_driver *drv,
913 		int minor);
914 extern struct usb_interface *usb_ifnum_to_if(const struct usb_device *dev,
915 		unsigned ifnum);
916 extern struct usb_host_interface *usb_altnum_to_altsetting(
917 		const struct usb_interface *intf, unsigned int altnum);
918 extern struct usb_host_interface *usb_find_alt_setting(
919 		struct usb_host_config *config,
920 		unsigned int iface_num,
921 		unsigned int alt_num);
922 
923 /* port claiming functions */
924 int usb_hub_claim_port(struct usb_device *hdev, unsigned port1,
925 		struct usb_dev_state *owner);
926 int usb_hub_release_port(struct usb_device *hdev, unsigned port1,
927 		struct usb_dev_state *owner);
928 
929 /**
930  * usb_make_path - returns stable device path in the usb tree
931  * @dev: the device whose path is being constructed
932  * @buf: where to put the string
933  * @size: how big is "buf"?
934  *
935  * Return: Length of the string (> 0) or negative if size was too small.
936  *
937  * Note:
938  * This identifier is intended to be "stable", reflecting physical paths in
939  * hardware such as physical bus addresses for host controllers or ports on
940  * USB hubs.  That makes it stay the same until systems are physically
941  * reconfigured, by re-cabling a tree of USB devices or by moving USB host
942  * controllers.  Adding and removing devices, including virtual root hubs
943  * in host controller driver modules, does not change these path identifiers;
944  * neither does rebooting or re-enumerating.  These are more useful identifiers
945  * than changeable ("unstable") ones like bus numbers or device addresses.
946  *
947  * With a partial exception for devices connected to USB 2.0 root hubs, these
948  * identifiers are also predictable.  So long as the device tree isn't changed,
949  * plugging any USB device into a given hub port always gives it the same path.
950  * Because of the use of "companion" controllers, devices connected to ports on
951  * USB 2.0 root hubs (EHCI host controllers) will get one path ID if they are
952  * high speed, and a different one if they are full or low speed.
953  */
954 static inline int usb_make_path(struct usb_device *dev, char *buf, size_t size)
955 {
956 	int actual;
957 	actual = snprintf(buf, size, "usb-%s-%s", dev->bus->bus_name,
958 			  dev->devpath);
959 	return (actual >= (int)size) ? -1 : actual;
960 }
961 
962 /*-------------------------------------------------------------------------*/
963 
964 #define USB_DEVICE_ID_MATCH_DEVICE \
965 		(USB_DEVICE_ID_MATCH_VENDOR | USB_DEVICE_ID_MATCH_PRODUCT)
966 #define USB_DEVICE_ID_MATCH_DEV_RANGE \
967 		(USB_DEVICE_ID_MATCH_DEV_LO | USB_DEVICE_ID_MATCH_DEV_HI)
968 #define USB_DEVICE_ID_MATCH_DEVICE_AND_VERSION \
969 		(USB_DEVICE_ID_MATCH_DEVICE | USB_DEVICE_ID_MATCH_DEV_RANGE)
970 #define USB_DEVICE_ID_MATCH_DEV_INFO \
971 		(USB_DEVICE_ID_MATCH_DEV_CLASS | \
972 		USB_DEVICE_ID_MATCH_DEV_SUBCLASS | \
973 		USB_DEVICE_ID_MATCH_DEV_PROTOCOL)
974 #define USB_DEVICE_ID_MATCH_INT_INFO \
975 		(USB_DEVICE_ID_MATCH_INT_CLASS | \
976 		USB_DEVICE_ID_MATCH_INT_SUBCLASS | \
977 		USB_DEVICE_ID_MATCH_INT_PROTOCOL)
978 
979 /**
980  * USB_DEVICE - macro used to describe a specific usb device
981  * @vend: the 16 bit USB Vendor ID
982  * @prod: the 16 bit USB Product ID
983  *
984  * This macro is used to create a struct usb_device_id that matches a
985  * specific device.
986  */
987 #define USB_DEVICE(vend, prod) \
988 	.match_flags = USB_DEVICE_ID_MATCH_DEVICE, \
989 	.idVendor = (vend), \
990 	.idProduct = (prod)
991 /**
992  * USB_DEVICE_VER - describe a specific usb device with a version range
993  * @vend: the 16 bit USB Vendor ID
994  * @prod: the 16 bit USB Product ID
995  * @lo: the bcdDevice_lo value
996  * @hi: the bcdDevice_hi value
997  *
998  * This macro is used to create a struct usb_device_id that matches a
999  * specific device, with a version range.
1000  */
1001 #define USB_DEVICE_VER(vend, prod, lo, hi) \
1002 	.match_flags = USB_DEVICE_ID_MATCH_DEVICE_AND_VERSION, \
1003 	.idVendor = (vend), \
1004 	.idProduct = (prod), \
1005 	.bcdDevice_lo = (lo), \
1006 	.bcdDevice_hi = (hi)
1007 
1008 /**
1009  * USB_DEVICE_INTERFACE_CLASS - describe a usb device with a specific interface class
1010  * @vend: the 16 bit USB Vendor ID
1011  * @prod: the 16 bit USB Product ID
1012  * @cl: bInterfaceClass value
1013  *
1014  * This macro is used to create a struct usb_device_id that matches a
1015  * specific interface class of devices.
1016  */
1017 #define USB_DEVICE_INTERFACE_CLASS(vend, prod, cl) \
1018 	.match_flags = USB_DEVICE_ID_MATCH_DEVICE | \
1019 		       USB_DEVICE_ID_MATCH_INT_CLASS, \
1020 	.idVendor = (vend), \
1021 	.idProduct = (prod), \
1022 	.bInterfaceClass = (cl)
1023 
1024 /**
1025  * USB_DEVICE_INTERFACE_PROTOCOL - describe a usb device with a specific interface protocol
1026  * @vend: the 16 bit USB Vendor ID
1027  * @prod: the 16 bit USB Product ID
1028  * @pr: bInterfaceProtocol value
1029  *
1030  * This macro is used to create a struct usb_device_id that matches a
1031  * specific interface protocol of devices.
1032  */
1033 #define USB_DEVICE_INTERFACE_PROTOCOL(vend, prod, pr) \
1034 	.match_flags = USB_DEVICE_ID_MATCH_DEVICE | \
1035 		       USB_DEVICE_ID_MATCH_INT_PROTOCOL, \
1036 	.idVendor = (vend), \
1037 	.idProduct = (prod), \
1038 	.bInterfaceProtocol = (pr)
1039 
1040 /**
1041  * USB_DEVICE_INTERFACE_NUMBER - describe a usb device with a specific interface number
1042  * @vend: the 16 bit USB Vendor ID
1043  * @prod: the 16 bit USB Product ID
1044  * @num: bInterfaceNumber value
1045  *
1046  * This macro is used to create a struct usb_device_id that matches a
1047  * specific interface number of devices.
1048  */
1049 #define USB_DEVICE_INTERFACE_NUMBER(vend, prod, num) \
1050 	.match_flags = USB_DEVICE_ID_MATCH_DEVICE | \
1051 		       USB_DEVICE_ID_MATCH_INT_NUMBER, \
1052 	.idVendor = (vend), \
1053 	.idProduct = (prod), \
1054 	.bInterfaceNumber = (num)
1055 
1056 /**
1057  * USB_DEVICE_INFO - macro used to describe a class of usb devices
1058  * @cl: bDeviceClass value
1059  * @sc: bDeviceSubClass value
1060  * @pr: bDeviceProtocol value
1061  *
1062  * This macro is used to create a struct usb_device_id that matches a
1063  * specific class of devices.
1064  */
1065 #define USB_DEVICE_INFO(cl, sc, pr) \
1066 	.match_flags = USB_DEVICE_ID_MATCH_DEV_INFO, \
1067 	.bDeviceClass = (cl), \
1068 	.bDeviceSubClass = (sc), \
1069 	.bDeviceProtocol = (pr)
1070 
1071 /**
1072  * USB_INTERFACE_INFO - macro used to describe a class of usb interfaces
1073  * @cl: bInterfaceClass value
1074  * @sc: bInterfaceSubClass value
1075  * @pr: bInterfaceProtocol value
1076  *
1077  * This macro is used to create a struct usb_device_id that matches a
1078  * specific class of interfaces.
1079  */
1080 #define USB_INTERFACE_INFO(cl, sc, pr) \
1081 	.match_flags = USB_DEVICE_ID_MATCH_INT_INFO, \
1082 	.bInterfaceClass = (cl), \
1083 	.bInterfaceSubClass = (sc), \
1084 	.bInterfaceProtocol = (pr)
1085 
1086 /**
1087  * USB_DEVICE_AND_INTERFACE_INFO - describe a specific usb device with a class of usb interfaces
1088  * @vend: the 16 bit USB Vendor ID
1089  * @prod: the 16 bit USB Product ID
1090  * @cl: bInterfaceClass value
1091  * @sc: bInterfaceSubClass value
1092  * @pr: bInterfaceProtocol value
1093  *
1094  * This macro is used to create a struct usb_device_id that matches a
1095  * specific device with a specific class of interfaces.
1096  *
1097  * This is especially useful when explicitly matching devices that have
1098  * vendor specific bDeviceClass values, but standards-compliant interfaces.
1099  */
1100 #define USB_DEVICE_AND_INTERFACE_INFO(vend, prod, cl, sc, pr) \
1101 	.match_flags = USB_DEVICE_ID_MATCH_INT_INFO \
1102 		| USB_DEVICE_ID_MATCH_DEVICE, \
1103 	.idVendor = (vend), \
1104 	.idProduct = (prod), \
1105 	.bInterfaceClass = (cl), \
1106 	.bInterfaceSubClass = (sc), \
1107 	.bInterfaceProtocol = (pr)
1108 
1109 /**
1110  * USB_VENDOR_AND_INTERFACE_INFO - describe a specific usb vendor with a class of usb interfaces
1111  * @vend: the 16 bit USB Vendor ID
1112  * @cl: bInterfaceClass value
1113  * @sc: bInterfaceSubClass value
1114  * @pr: bInterfaceProtocol value
1115  *
1116  * This macro is used to create a struct usb_device_id that matches a
1117  * specific vendor with a specific class of interfaces.
1118  *
1119  * This is especially useful when explicitly matching devices that have
1120  * vendor specific bDeviceClass values, but standards-compliant interfaces.
1121  */
1122 #define USB_VENDOR_AND_INTERFACE_INFO(vend, cl, sc, pr) \
1123 	.match_flags = USB_DEVICE_ID_MATCH_INT_INFO \
1124 		| USB_DEVICE_ID_MATCH_VENDOR, \
1125 	.idVendor = (vend), \
1126 	.bInterfaceClass = (cl), \
1127 	.bInterfaceSubClass = (sc), \
1128 	.bInterfaceProtocol = (pr)
1129 
1130 /* ----------------------------------------------------------------------- */
1131 
1132 /* Stuff for dynamic usb ids */
1133 struct usb_dynids {
1134 	spinlock_t lock;
1135 	struct list_head list;
1136 };
1137 
1138 struct usb_dynid {
1139 	struct list_head node;
1140 	struct usb_device_id id;
1141 };
1142 
1143 extern ssize_t usb_store_new_id(struct usb_dynids *dynids,
1144 				const struct usb_device_id *id_table,
1145 				struct device_driver *driver,
1146 				const char *buf, size_t count);
1147 
1148 extern ssize_t usb_show_dynids(struct usb_dynids *dynids, char *buf);
1149 
1150 /**
1151  * struct usbdrv_wrap - wrapper for driver-model structure
1152  * @driver: The driver-model core driver structure.
1153  * @for_devices: Non-zero for device drivers, 0 for interface drivers.
1154  */
1155 struct usbdrv_wrap {
1156 	struct device_driver driver;
1157 	int for_devices;
1158 };
1159 
1160 /**
1161  * struct usb_driver - identifies USB interface driver to usbcore
1162  * @name: The driver name should be unique among USB drivers,
1163  *	and should normally be the same as the module name.
1164  * @probe: Called to see if the driver is willing to manage a particular
1165  *	interface on a device.  If it is, probe returns zero and uses
1166  *	usb_set_intfdata() to associate driver-specific data with the
1167  *	interface.  It may also use usb_set_interface() to specify the
1168  *	appropriate altsetting.  If unwilling to manage the interface,
1169  *	return -ENODEV, if genuine IO errors occurred, an appropriate
1170  *	negative errno value.
1171  * @disconnect: Called when the interface is no longer accessible, usually
1172  *	because its device has been (or is being) disconnected or the
1173  *	driver module is being unloaded.
1174  * @unlocked_ioctl: Used for drivers that want to talk to userspace through
1175  *	the "usbfs" filesystem.  This lets devices provide ways to
1176  *	expose information to user space regardless of where they
1177  *	do (or don't) show up otherwise in the filesystem.
1178  * @suspend: Called when the device is going to be suspended by the
1179  *	system either from system sleep or runtime suspend context. The
1180  *	return value will be ignored in system sleep context, so do NOT
1181  *	try to continue using the device if suspend fails in this case.
1182  *	Instead, let the resume or reset-resume routine recover from
1183  *	the failure.
1184  * @resume: Called when the device is being resumed by the system.
1185  * @reset_resume: Called when the suspended device has been reset instead
1186  *	of being resumed.
1187  * @pre_reset: Called by usb_reset_device() when the device is about to be
1188  *	reset.  This routine must not return until the driver has no active
1189  *	URBs for the device, and no more URBs may be submitted until the
1190  *	post_reset method is called.
1191  * @post_reset: Called by usb_reset_device() after the device
1192  *	has been reset
1193  * @id_table: USB drivers use ID table to support hotplugging.
1194  *	Export this with MODULE_DEVICE_TABLE(usb,...).  This must be set
1195  *	or your driver's probe function will never get called.
1196  * @dev_groups: Attributes attached to the device that will be created once it
1197  *	is bound to the driver.
1198  * @dynids: used internally to hold the list of dynamically added device
1199  *	ids for this driver.
1200  * @drvwrap: Driver-model core structure wrapper.
1201  * @no_dynamic_id: if set to 1, the USB core will not allow dynamic ids to be
1202  *	added to this driver by preventing the sysfs file from being created.
1203  * @supports_autosuspend: if set to 0, the USB core will not allow autosuspend
1204  *	for interfaces bound to this driver.
1205  * @soft_unbind: if set to 1, the USB core will not kill URBs and disable
1206  *	endpoints before calling the driver's disconnect method.
1207  * @disable_hub_initiated_lpm: if set to 1, the USB core will not allow hubs
1208  *	to initiate lower power link state transitions when an idle timeout
1209  *	occurs.  Device-initiated USB 3.0 link PM will still be allowed.
1210  *
1211  * USB interface drivers must provide a name, probe() and disconnect()
1212  * methods, and an id_table.  Other driver fields are optional.
1213  *
1214  * The id_table is used in hotplugging.  It holds a set of descriptors,
1215  * and specialized data may be associated with each entry.  That table
1216  * is used by both user and kernel mode hotplugging support.
1217  *
1218  * The probe() and disconnect() methods are called in a context where
1219  * they can sleep, but they should avoid abusing the privilege.  Most
1220  * work to connect to a device should be done when the device is opened,
1221  * and undone at the last close.  The disconnect code needs to address
1222  * concurrency issues with respect to open() and close() methods, as
1223  * well as forcing all pending I/O requests to complete (by unlinking
1224  * them as necessary, and blocking until the unlinks complete).
1225  */
1226 struct usb_driver {
1227 	const char *name;
1228 
1229 	int (*probe) (struct usb_interface *intf,
1230 		      const struct usb_device_id *id);
1231 
1232 	void (*disconnect) (struct usb_interface *intf);
1233 
1234 	int (*unlocked_ioctl) (struct usb_interface *intf, unsigned int code,
1235 			void *buf);
1236 
1237 	int (*suspend) (struct usb_interface *intf, pm_message_t message);
1238 	int (*resume) (struct usb_interface *intf);
1239 	int (*reset_resume)(struct usb_interface *intf);
1240 
1241 	int (*pre_reset)(struct usb_interface *intf);
1242 	int (*post_reset)(struct usb_interface *intf);
1243 
1244 	const struct usb_device_id *id_table;
1245 	const struct attribute_group **dev_groups;
1246 
1247 	struct usb_dynids dynids;
1248 	struct usbdrv_wrap drvwrap;
1249 	unsigned int no_dynamic_id:1;
1250 	unsigned int supports_autosuspend:1;
1251 	unsigned int disable_hub_initiated_lpm:1;
1252 	unsigned int soft_unbind:1;
1253 };
1254 #define	to_usb_driver(d) container_of(d, struct usb_driver, drvwrap.driver)
1255 
1256 /**
1257  * struct usb_device_driver - identifies USB device driver to usbcore
1258  * @name: The driver name should be unique among USB drivers,
1259  *	and should normally be the same as the module name.
1260  * @match: If set, used for better device/driver matching.
1261  * @probe: Called to see if the driver is willing to manage a particular
1262  *	device.  If it is, probe returns zero and uses dev_set_drvdata()
1263  *	to associate driver-specific data with the device.  If unwilling
1264  *	to manage the device, return a negative errno value.
1265  * @disconnect: Called when the device is no longer accessible, usually
1266  *	because it has been (or is being) disconnected or the driver's
1267  *	module is being unloaded.
1268  * @suspend: Called when the device is going to be suspended by the system.
1269  * @resume: Called when the device is being resumed by the system.
1270  * @dev_groups: Attributes attached to the device that will be created once it
1271  *	is bound to the driver.
1272  * @drvwrap: Driver-model core structure wrapper.
1273  * @id_table: used with @match() to select better matching driver at
1274  * 	probe() time.
1275  * @supports_autosuspend: if set to 0, the USB core will not allow autosuspend
1276  *	for devices bound to this driver.
1277  * @generic_subclass: if set to 1, the generic USB driver's probe, disconnect,
1278  *	resume and suspend functions will be called in addition to the driver's
1279  *	own, so this part of the setup does not need to be replicated.
1280  *
1281  * USB drivers must provide all the fields listed above except drvwrap,
1282  * match, and id_table.
1283  */
1284 struct usb_device_driver {
1285 	const char *name;
1286 
1287 	bool (*match) (struct usb_device *udev);
1288 	int (*probe) (struct usb_device *udev);
1289 	void (*disconnect) (struct usb_device *udev);
1290 
1291 	int (*suspend) (struct usb_device *udev, pm_message_t message);
1292 	int (*resume) (struct usb_device *udev, pm_message_t message);
1293 	const struct attribute_group **dev_groups;
1294 	struct usbdrv_wrap drvwrap;
1295 	const struct usb_device_id *id_table;
1296 	unsigned int supports_autosuspend:1;
1297 	unsigned int generic_subclass:1;
1298 };
1299 #define	to_usb_device_driver(d) container_of(d, struct usb_device_driver, \
1300 		drvwrap.driver)
1301 
1302 /**
1303  * struct usb_class_driver - identifies a USB driver that wants to use the USB major number
1304  * @name: the usb class device name for this driver.  Will show up in sysfs.
1305  * @devnode: Callback to provide a naming hint for a possible
1306  *	device node to create.
1307  * @fops: pointer to the struct file_operations of this driver.
1308  * @minor_base: the start of the minor range for this driver.
1309  *
1310  * This structure is used for the usb_register_dev() and
1311  * usb_deregister_dev() functions, to consolidate a number of the
1312  * parameters used for them.
1313  */
1314 struct usb_class_driver {
1315 	char *name;
1316 	char *(*devnode)(const struct device *dev, umode_t *mode);
1317 	const struct file_operations *fops;
1318 	int minor_base;
1319 };
1320 
1321 /*
1322  * use these in module_init()/module_exit()
1323  * and don't forget MODULE_DEVICE_TABLE(usb, ...)
1324  */
1325 extern int usb_register_driver(struct usb_driver *, struct module *,
1326 			       const char *);
1327 
1328 /* use a define to avoid include chaining to get THIS_MODULE & friends */
1329 #define usb_register(driver) \
1330 	usb_register_driver(driver, THIS_MODULE, KBUILD_MODNAME)
1331 
1332 extern void usb_deregister(struct usb_driver *);
1333 
1334 /**
1335  * module_usb_driver() - Helper macro for registering a USB driver
1336  * @__usb_driver: usb_driver struct
1337  *
1338  * Helper macro for USB drivers which do not do anything special in module
1339  * init/exit. This eliminates a lot of boilerplate. Each module may only
1340  * use this macro once, and calling it replaces module_init() and module_exit()
1341  */
1342 #define module_usb_driver(__usb_driver) \
1343 	module_driver(__usb_driver, usb_register, \
1344 		       usb_deregister)
1345 
1346 extern int usb_register_device_driver(struct usb_device_driver *,
1347 			struct module *);
1348 extern void usb_deregister_device_driver(struct usb_device_driver *);
1349 
1350 extern int usb_register_dev(struct usb_interface *intf,
1351 			    struct usb_class_driver *class_driver);
1352 extern void usb_deregister_dev(struct usb_interface *intf,
1353 			       struct usb_class_driver *class_driver);
1354 
1355 extern int usb_disabled(void);
1356 
1357 /* ----------------------------------------------------------------------- */
1358 
1359 /*
1360  * URB support, for asynchronous request completions
1361  */
1362 
1363 /*
1364  * urb->transfer_flags:
1365  *
1366  * Note: URB_DIR_IN/OUT is automatically set in usb_submit_urb().
1367  */
1368 #define URB_SHORT_NOT_OK	0x0001	/* report short reads as errors */
1369 #define URB_ISO_ASAP		0x0002	/* iso-only; use the first unexpired
1370 					 * slot in the schedule */
1371 #define URB_NO_TRANSFER_DMA_MAP	0x0004	/* urb->transfer_dma valid on submit */
1372 #define URB_ZERO_PACKET		0x0040	/* Finish bulk OUT with short packet */
1373 #define URB_NO_INTERRUPT	0x0080	/* HINT: no non-error interrupt
1374 					 * needed */
1375 #define URB_FREE_BUFFER		0x0100	/* Free transfer buffer with the URB */
1376 
1377 /* The following flags are used internally by usbcore and HCDs */
1378 #define URB_DIR_IN		0x0200	/* Transfer from device to host */
1379 #define URB_DIR_OUT		0
1380 #define URB_DIR_MASK		URB_DIR_IN
1381 
1382 #define URB_DMA_MAP_SINGLE	0x00010000	/* Non-scatter-gather mapping */
1383 #define URB_DMA_MAP_PAGE	0x00020000	/* HCD-unsupported S-G */
1384 #define URB_DMA_MAP_SG		0x00040000	/* HCD-supported S-G */
1385 #define URB_MAP_LOCAL		0x00080000	/* HCD-local-memory mapping */
1386 #define URB_SETUP_MAP_SINGLE	0x00100000	/* Setup packet DMA mapped */
1387 #define URB_SETUP_MAP_LOCAL	0x00200000	/* HCD-local setup packet */
1388 #define URB_DMA_SG_COMBINED	0x00400000	/* S-G entries were combined */
1389 #define URB_ALIGNED_TEMP_BUFFER	0x00800000	/* Temp buffer was alloc'd */
1390 
1391 struct usb_iso_packet_descriptor {
1392 	unsigned int offset;
1393 	unsigned int length;		/* expected length */
1394 	unsigned int actual_length;
1395 	int status;
1396 };
1397 
1398 struct urb;
1399 
1400 struct usb_anchor {
1401 	struct list_head urb_list;
1402 	wait_queue_head_t wait;
1403 	spinlock_t lock;
1404 	atomic_t suspend_wakeups;
1405 	unsigned int poisoned:1;
1406 };
1407 
1408 static inline void init_usb_anchor(struct usb_anchor *anchor)
1409 {
1410 	memset(anchor, 0, sizeof(*anchor));
1411 	INIT_LIST_HEAD(&anchor->urb_list);
1412 	init_waitqueue_head(&anchor->wait);
1413 	spin_lock_init(&anchor->lock);
1414 }
1415 
1416 typedef void (*usb_complete_t)(struct urb *);
1417 
1418 /**
1419  * struct urb - USB Request Block
1420  * @urb_list: For use by current owner of the URB.
1421  * @anchor_list: membership in the list of an anchor
1422  * @anchor: to anchor URBs to a common mooring
1423  * @ep: Points to the endpoint's data structure.  Will eventually
1424  *	replace @pipe.
1425  * @pipe: Holds endpoint number, direction, type, and more.
1426  *	Create these values with the eight macros available;
1427  *	usb_{snd,rcv}TYPEpipe(dev,endpoint), where the TYPE is "ctrl"
1428  *	(control), "bulk", "int" (interrupt), or "iso" (isochronous).
1429  *	For example usb_sndbulkpipe() or usb_rcvintpipe().  Endpoint
1430  *	numbers range from zero to fifteen.  Note that "in" endpoint two
1431  *	is a different endpoint (and pipe) from "out" endpoint two.
1432  *	The current configuration controls the existence, type, and
1433  *	maximum packet size of any given endpoint.
1434  * @stream_id: the endpoint's stream ID for bulk streams
1435  * @dev: Identifies the USB device to perform the request.
1436  * @status: This is read in non-iso completion functions to get the
1437  *	status of the particular request.  ISO requests only use it
1438  *	to tell whether the URB was unlinked; detailed status for
1439  *	each frame is in the fields of the iso_frame-desc.
1440  * @transfer_flags: A variety of flags may be used to affect how URB
1441  *	submission, unlinking, or operation are handled.  Different
1442  *	kinds of URB can use different flags.
1443  * @transfer_buffer:  This identifies the buffer to (or from) which the I/O
1444  *	request will be performed unless URB_NO_TRANSFER_DMA_MAP is set
1445  *	(however, do not leave garbage in transfer_buffer even then).
1446  *	This buffer must be suitable for DMA; allocate it with
1447  *	kmalloc() or equivalent.  For transfers to "in" endpoints, contents
1448  *	of this buffer will be modified.  This buffer is used for the data
1449  *	stage of control transfers.
1450  * @transfer_dma: When transfer_flags includes URB_NO_TRANSFER_DMA_MAP,
1451  *	the device driver is saying that it provided this DMA address,
1452  *	which the host controller driver should use in preference to the
1453  *	transfer_buffer.
1454  * @sg: scatter gather buffer list, the buffer size of each element in
1455  * 	the list (except the last) must be divisible by the endpoint's
1456  * 	max packet size if no_sg_constraint isn't set in 'struct usb_bus'
1457  * @num_mapped_sgs: (internal) number of mapped sg entries
1458  * @num_sgs: number of entries in the sg list
1459  * @transfer_buffer_length: How big is transfer_buffer.  The transfer may
1460  *	be broken up into chunks according to the current maximum packet
1461  *	size for the endpoint, which is a function of the configuration
1462  *	and is encoded in the pipe.  When the length is zero, neither
1463  *	transfer_buffer nor transfer_dma is used.
1464  * @actual_length: This is read in non-iso completion functions, and
1465  *	it tells how many bytes (out of transfer_buffer_length) were
1466  *	transferred.  It will normally be the same as requested, unless
1467  *	either an error was reported or a short read was performed.
1468  *	The URB_SHORT_NOT_OK transfer flag may be used to make such
1469  *	short reads be reported as errors.
1470  * @setup_packet: Only used for control transfers, this points to eight bytes
1471  *	of setup data.  Control transfers always start by sending this data
1472  *	to the device.  Then transfer_buffer is read or written, if needed.
1473  * @setup_dma: DMA pointer for the setup packet.  The caller must not use
1474  *	this field; setup_packet must point to a valid buffer.
1475  * @start_frame: Returns the initial frame for isochronous transfers.
1476  * @number_of_packets: Lists the number of ISO transfer buffers.
1477  * @interval: Specifies the polling interval for interrupt or isochronous
1478  *	transfers.  The units are frames (milliseconds) for full and low
1479  *	speed devices, and microframes (1/8 millisecond) for highspeed
1480  *	and SuperSpeed devices.
1481  * @error_count: Returns the number of ISO transfers that reported errors.
1482  * @context: For use in completion functions.  This normally points to
1483  *	request-specific driver context.
1484  * @complete: Completion handler. This URB is passed as the parameter to the
1485  *	completion function.  The completion function may then do what
1486  *	it likes with the URB, including resubmitting or freeing it.
1487  * @iso_frame_desc: Used to provide arrays of ISO transfer buffers and to
1488  *	collect the transfer status for each buffer.
1489  *
1490  * This structure identifies USB transfer requests.  URBs must be allocated by
1491  * calling usb_alloc_urb() and freed with a call to usb_free_urb().
1492  * Initialization may be done using various usb_fill_*_urb() functions.  URBs
1493  * are submitted using usb_submit_urb(), and pending requests may be canceled
1494  * using usb_unlink_urb() or usb_kill_urb().
1495  *
1496  * Data Transfer Buffers:
1497  *
1498  * Normally drivers provide I/O buffers allocated with kmalloc() or otherwise
1499  * taken from the general page pool.  That is provided by transfer_buffer
1500  * (control requests also use setup_packet), and host controller drivers
1501  * perform a dma mapping (and unmapping) for each buffer transferred.  Those
1502  * mapping operations can be expensive on some platforms (perhaps using a dma
1503  * bounce buffer or talking to an IOMMU),
1504  * although they're cheap on commodity x86 and ppc hardware.
1505  *
1506  * Alternatively, drivers may pass the URB_NO_TRANSFER_DMA_MAP transfer flag,
1507  * which tells the host controller driver that no such mapping is needed for
1508  * the transfer_buffer since
1509  * the device driver is DMA-aware.  For example, a device driver might
1510  * allocate a DMA buffer with usb_alloc_coherent() or call usb_buffer_map().
1511  * When this transfer flag is provided, host controller drivers will
1512  * attempt to use the dma address found in the transfer_dma
1513  * field rather than determining a dma address themselves.
1514  *
1515  * Note that transfer_buffer must still be set if the controller
1516  * does not support DMA (as indicated by hcd_uses_dma()) and when talking
1517  * to root hub. If you have to transfer between highmem zone and the device
1518  * on such controller, create a bounce buffer or bail out with an error.
1519  * If transfer_buffer cannot be set (is in highmem) and the controller is DMA
1520  * capable, assign NULL to it, so that usbmon knows not to use the value.
1521  * The setup_packet must always be set, so it cannot be located in highmem.
1522  *
1523  * Initialization:
1524  *
1525  * All URBs submitted must initialize the dev, pipe, transfer_flags (may be
1526  * zero), and complete fields.  All URBs must also initialize
1527  * transfer_buffer and transfer_buffer_length.  They may provide the
1528  * URB_SHORT_NOT_OK transfer flag, indicating that short reads are
1529  * to be treated as errors; that flag is invalid for write requests.
1530  *
1531  * Bulk URBs may
1532  * use the URB_ZERO_PACKET transfer flag, indicating that bulk OUT transfers
1533  * should always terminate with a short packet, even if it means adding an
1534  * extra zero length packet.
1535  *
1536  * Control URBs must provide a valid pointer in the setup_packet field.
1537  * Unlike the transfer_buffer, the setup_packet may not be mapped for DMA
1538  * beforehand.
1539  *
1540  * Interrupt URBs must provide an interval, saying how often (in milliseconds
1541  * or, for highspeed devices, 125 microsecond units)
1542  * to poll for transfers.  After the URB has been submitted, the interval
1543  * field reflects how the transfer was actually scheduled.
1544  * The polling interval may be more frequent than requested.
1545  * For example, some controllers have a maximum interval of 32 milliseconds,
1546  * while others support intervals of up to 1024 milliseconds.
1547  * Isochronous URBs also have transfer intervals.  (Note that for isochronous
1548  * endpoints, as well as high speed interrupt endpoints, the encoding of
1549  * the transfer interval in the endpoint descriptor is logarithmic.
1550  * Device drivers must convert that value to linear units themselves.)
1551  *
1552  * If an isochronous endpoint queue isn't already running, the host
1553  * controller will schedule a new URB to start as soon as bandwidth
1554  * utilization allows.  If the queue is running then a new URB will be
1555  * scheduled to start in the first transfer slot following the end of the
1556  * preceding URB, if that slot has not already expired.  If the slot has
1557  * expired (which can happen when IRQ delivery is delayed for a long time),
1558  * the scheduling behavior depends on the URB_ISO_ASAP flag.  If the flag
1559  * is clear then the URB will be scheduled to start in the expired slot,
1560  * implying that some of its packets will not be transferred; if the flag
1561  * is set then the URB will be scheduled in the first unexpired slot,
1562  * breaking the queue's synchronization.  Upon URB completion, the
1563  * start_frame field will be set to the (micro)frame number in which the
1564  * transfer was scheduled.  Ranges for frame counter values are HC-specific
1565  * and can go from as low as 256 to as high as 65536 frames.
1566  *
1567  * Isochronous URBs have a different data transfer model, in part because
1568  * the quality of service is only "best effort".  Callers provide specially
1569  * allocated URBs, with number_of_packets worth of iso_frame_desc structures
1570  * at the end.  Each such packet is an individual ISO transfer.  Isochronous
1571  * URBs are normally queued, submitted by drivers to arrange that
1572  * transfers are at least double buffered, and then explicitly resubmitted
1573  * in completion handlers, so
1574  * that data (such as audio or video) streams at as constant a rate as the
1575  * host controller scheduler can support.
1576  *
1577  * Completion Callbacks:
1578  *
1579  * The completion callback is made in_interrupt(), and one of the first
1580  * things that a completion handler should do is check the status field.
1581  * The status field is provided for all URBs.  It is used to report
1582  * unlinked URBs, and status for all non-ISO transfers.  It should not
1583  * be examined before the URB is returned to the completion handler.
1584  *
1585  * The context field is normally used to link URBs back to the relevant
1586  * driver or request state.
1587  *
1588  * When the completion callback is invoked for non-isochronous URBs, the
1589  * actual_length field tells how many bytes were transferred.  This field
1590  * is updated even when the URB terminated with an error or was unlinked.
1591  *
1592  * ISO transfer status is reported in the status and actual_length fields
1593  * of the iso_frame_desc array, and the number of errors is reported in
1594  * error_count.  Completion callbacks for ISO transfers will normally
1595  * (re)submit URBs to ensure a constant transfer rate.
1596  *
1597  * Note that even fields marked "public" should not be touched by the driver
1598  * when the urb is owned by the hcd, that is, since the call to
1599  * usb_submit_urb() till the entry into the completion routine.
1600  */
1601 struct urb {
1602 	/* private: usb core and host controller only fields in the urb */
1603 	struct kref kref;		/* reference count of the URB */
1604 	int unlinked;			/* unlink error code */
1605 	void *hcpriv;			/* private data for host controller */
1606 	atomic_t use_count;		/* concurrent submissions counter */
1607 	atomic_t reject;		/* submissions will fail */
1608 
1609 	/* public: documented fields in the urb that can be used by drivers */
1610 	struct list_head urb_list;	/* list head for use by the urb's
1611 					 * current owner */
1612 	struct list_head anchor_list;	/* the URB may be anchored */
1613 	struct usb_anchor *anchor;
1614 	struct usb_device *dev;		/* (in) pointer to associated device */
1615 	struct usb_host_endpoint *ep;	/* (internal) pointer to endpoint */
1616 	unsigned int pipe;		/* (in) pipe information */
1617 	unsigned int stream_id;		/* (in) stream ID */
1618 	int status;			/* (return) non-ISO status */
1619 	unsigned int transfer_flags;	/* (in) URB_SHORT_NOT_OK | ...*/
1620 	void *transfer_buffer;		/* (in) associated data buffer */
1621 	dma_addr_t transfer_dma;	/* (in) dma addr for transfer_buffer */
1622 	struct scatterlist *sg;		/* (in) scatter gather buffer list */
1623 	int num_mapped_sgs;		/* (internal) mapped sg entries */
1624 	int num_sgs;			/* (in) number of entries in the sg list */
1625 	u32 transfer_buffer_length;	/* (in) data buffer length */
1626 	u32 actual_length;		/* (return) actual transfer length */
1627 	unsigned char *setup_packet;	/* (in) setup packet (control only) */
1628 	dma_addr_t setup_dma;		/* (in) dma addr for setup_packet */
1629 	int start_frame;		/* (modify) start frame (ISO) */
1630 	int number_of_packets;		/* (in) number of ISO packets */
1631 	int interval;			/* (modify) transfer interval
1632 					 * (INT/ISO) */
1633 	int error_count;		/* (return) number of ISO errors */
1634 	void *context;			/* (in) context for completion */
1635 	usb_complete_t complete;	/* (in) completion routine */
1636 	struct usb_iso_packet_descriptor iso_frame_desc[];
1637 					/* (in) ISO ONLY */
1638 };
1639 
1640 /* ----------------------------------------------------------------------- */
1641 
1642 /**
1643  * usb_fill_control_urb - initializes a control urb
1644  * @urb: pointer to the urb to initialize.
1645  * @dev: pointer to the struct usb_device for this urb.
1646  * @pipe: the endpoint pipe
1647  * @setup_packet: pointer to the setup_packet buffer. The buffer must be
1648  *	suitable for DMA.
1649  * @transfer_buffer: pointer to the transfer buffer. The buffer must be
1650  *	suitable for DMA.
1651  * @buffer_length: length of the transfer buffer
1652  * @complete_fn: pointer to the usb_complete_t function
1653  * @context: what to set the urb context to.
1654  *
1655  * Initializes a control urb with the proper information needed to submit
1656  * it to a device.
1657  *
1658  * The transfer buffer and the setup_packet buffer will most likely be filled
1659  * or read via DMA. The simplest way to get a buffer that can be DMAed to is
1660  * allocating it via kmalloc() or equivalent, even for very small buffers.
1661  * If the buffers are embedded in a bigger structure, there is a risk that
1662  * the buffer itself, the previous fields and/or the next fields are corrupted
1663  * due to cache incoherencies; or slowed down if they are evicted from the
1664  * cache. For more information, check &struct urb.
1665  *
1666  */
1667 static inline void usb_fill_control_urb(struct urb *urb,
1668 					struct usb_device *dev,
1669 					unsigned int pipe,
1670 					unsigned char *setup_packet,
1671 					void *transfer_buffer,
1672 					int buffer_length,
1673 					usb_complete_t complete_fn,
1674 					void *context)
1675 {
1676 	urb->dev = dev;
1677 	urb->pipe = pipe;
1678 	urb->setup_packet = setup_packet;
1679 	urb->transfer_buffer = transfer_buffer;
1680 	urb->transfer_buffer_length = buffer_length;
1681 	urb->complete = complete_fn;
1682 	urb->context = context;
1683 }
1684 
1685 /**
1686  * usb_fill_bulk_urb - macro to help initialize a bulk urb
1687  * @urb: pointer to the urb to initialize.
1688  * @dev: pointer to the struct usb_device for this urb.
1689  * @pipe: the endpoint pipe
1690  * @transfer_buffer: pointer to the transfer buffer. The buffer must be
1691  *	suitable for DMA.
1692  * @buffer_length: length of the transfer buffer
1693  * @complete_fn: pointer to the usb_complete_t function
1694  * @context: what to set the urb context to.
1695  *
1696  * Initializes a bulk urb with the proper information needed to submit it
1697  * to a device.
1698  *
1699  * Refer to usb_fill_control_urb() for a description of the requirements for
1700  * transfer_buffer.
1701  */
1702 static inline void usb_fill_bulk_urb(struct urb *urb,
1703 				     struct usb_device *dev,
1704 				     unsigned int pipe,
1705 				     void *transfer_buffer,
1706 				     int buffer_length,
1707 				     usb_complete_t complete_fn,
1708 				     void *context)
1709 {
1710 	urb->dev = dev;
1711 	urb->pipe = pipe;
1712 	urb->transfer_buffer = transfer_buffer;
1713 	urb->transfer_buffer_length = buffer_length;
1714 	urb->complete = complete_fn;
1715 	urb->context = context;
1716 }
1717 
1718 /**
1719  * usb_fill_int_urb - macro to help initialize a interrupt urb
1720  * @urb: pointer to the urb to initialize.
1721  * @dev: pointer to the struct usb_device for this urb.
1722  * @pipe: the endpoint pipe
1723  * @transfer_buffer: pointer to the transfer buffer. The buffer must be
1724  *	suitable for DMA.
1725  * @buffer_length: length of the transfer buffer
1726  * @complete_fn: pointer to the usb_complete_t function
1727  * @context: what to set the urb context to.
1728  * @interval: what to set the urb interval to, encoded like
1729  *	the endpoint descriptor's bInterval value.
1730  *
1731  * Initializes a interrupt urb with the proper information needed to submit
1732  * it to a device.
1733  *
1734  * Refer to usb_fill_control_urb() for a description of the requirements for
1735  * transfer_buffer.
1736  *
1737  * Note that High Speed and SuperSpeed(+) interrupt endpoints use a logarithmic
1738  * encoding of the endpoint interval, and express polling intervals in
1739  * microframes (eight per millisecond) rather than in frames (one per
1740  * millisecond).
1741  *
1742  * Wireless USB also uses the logarithmic encoding, but specifies it in units of
1743  * 128us instead of 125us.  For Wireless USB devices, the interval is passed
1744  * through to the host controller, rather than being translated into microframe
1745  * units.
1746  */
1747 static inline void usb_fill_int_urb(struct urb *urb,
1748 				    struct usb_device *dev,
1749 				    unsigned int pipe,
1750 				    void *transfer_buffer,
1751 				    int buffer_length,
1752 				    usb_complete_t complete_fn,
1753 				    void *context,
1754 				    int interval)
1755 {
1756 	urb->dev = dev;
1757 	urb->pipe = pipe;
1758 	urb->transfer_buffer = transfer_buffer;
1759 	urb->transfer_buffer_length = buffer_length;
1760 	urb->complete = complete_fn;
1761 	urb->context = context;
1762 
1763 	if (dev->speed == USB_SPEED_HIGH || dev->speed >= USB_SPEED_SUPER) {
1764 		/* make sure interval is within allowed range */
1765 		interval = clamp(interval, 1, 16);
1766 
1767 		urb->interval = 1 << (interval - 1);
1768 	} else {
1769 		urb->interval = interval;
1770 	}
1771 
1772 	urb->start_frame = -1;
1773 }
1774 
1775 extern void usb_init_urb(struct urb *urb);
1776 extern struct urb *usb_alloc_urb(int iso_packets, gfp_t mem_flags);
1777 extern void usb_free_urb(struct urb *urb);
1778 #define usb_put_urb usb_free_urb
1779 extern struct urb *usb_get_urb(struct urb *urb);
1780 extern int usb_submit_urb(struct urb *urb, gfp_t mem_flags);
1781 extern int usb_unlink_urb(struct urb *urb);
1782 extern void usb_kill_urb(struct urb *urb);
1783 extern void usb_poison_urb(struct urb *urb);
1784 extern void usb_unpoison_urb(struct urb *urb);
1785 extern void usb_block_urb(struct urb *urb);
1786 extern void usb_kill_anchored_urbs(struct usb_anchor *anchor);
1787 extern void usb_poison_anchored_urbs(struct usb_anchor *anchor);
1788 extern void usb_unpoison_anchored_urbs(struct usb_anchor *anchor);
1789 extern void usb_unlink_anchored_urbs(struct usb_anchor *anchor);
1790 extern void usb_anchor_suspend_wakeups(struct usb_anchor *anchor);
1791 extern void usb_anchor_resume_wakeups(struct usb_anchor *anchor);
1792 extern void usb_anchor_urb(struct urb *urb, struct usb_anchor *anchor);
1793 extern void usb_unanchor_urb(struct urb *urb);
1794 extern int usb_wait_anchor_empty_timeout(struct usb_anchor *anchor,
1795 					 unsigned int timeout);
1796 extern struct urb *usb_get_from_anchor(struct usb_anchor *anchor);
1797 extern void usb_scuttle_anchored_urbs(struct usb_anchor *anchor);
1798 extern int usb_anchor_empty(struct usb_anchor *anchor);
1799 
1800 #define usb_unblock_urb	usb_unpoison_urb
1801 
1802 /**
1803  * usb_urb_dir_in - check if an URB describes an IN transfer
1804  * @urb: URB to be checked
1805  *
1806  * Return: 1 if @urb describes an IN transfer (device-to-host),
1807  * otherwise 0.
1808  */
1809 static inline int usb_urb_dir_in(struct urb *urb)
1810 {
1811 	return (urb->transfer_flags & URB_DIR_MASK) == URB_DIR_IN;
1812 }
1813 
1814 /**
1815  * usb_urb_dir_out - check if an URB describes an OUT transfer
1816  * @urb: URB to be checked
1817  *
1818  * Return: 1 if @urb describes an OUT transfer (host-to-device),
1819  * otherwise 0.
1820  */
1821 static inline int usb_urb_dir_out(struct urb *urb)
1822 {
1823 	return (urb->transfer_flags & URB_DIR_MASK) == URB_DIR_OUT;
1824 }
1825 
1826 int usb_pipe_type_check(struct usb_device *dev, unsigned int pipe);
1827 int usb_urb_ep_type_check(const struct urb *urb);
1828 
1829 void *usb_alloc_coherent(struct usb_device *dev, size_t size,
1830 	gfp_t mem_flags, dma_addr_t *dma);
1831 void usb_free_coherent(struct usb_device *dev, size_t size,
1832 	void *addr, dma_addr_t dma);
1833 
1834 #if 0
1835 struct urb *usb_buffer_map(struct urb *urb);
1836 void usb_buffer_dmasync(struct urb *urb);
1837 void usb_buffer_unmap(struct urb *urb);
1838 #endif
1839 
1840 struct scatterlist;
1841 int usb_buffer_map_sg(const struct usb_device *dev, int is_in,
1842 		      struct scatterlist *sg, int nents);
1843 #if 0
1844 void usb_buffer_dmasync_sg(const struct usb_device *dev, int is_in,
1845 			   struct scatterlist *sg, int n_hw_ents);
1846 #endif
1847 void usb_buffer_unmap_sg(const struct usb_device *dev, int is_in,
1848 			 struct scatterlist *sg, int n_hw_ents);
1849 
1850 /*-------------------------------------------------------------------*
1851  *                         SYNCHRONOUS CALL SUPPORT                  *
1852  *-------------------------------------------------------------------*/
1853 
1854 extern int usb_control_msg(struct usb_device *dev, unsigned int pipe,
1855 	__u8 request, __u8 requesttype, __u16 value, __u16 index,
1856 	void *data, __u16 size, int timeout);
1857 extern int usb_interrupt_msg(struct usb_device *usb_dev, unsigned int pipe,
1858 	void *data, int len, int *actual_length, int timeout);
1859 extern int usb_bulk_msg(struct usb_device *usb_dev, unsigned int pipe,
1860 	void *data, int len, int *actual_length,
1861 	int timeout);
1862 
1863 /* wrappers around usb_control_msg() for the most common standard requests */
1864 int usb_control_msg_send(struct usb_device *dev, __u8 endpoint, __u8 request,
1865 			 __u8 requesttype, __u16 value, __u16 index,
1866 			 const void *data, __u16 size, int timeout,
1867 			 gfp_t memflags);
1868 int usb_control_msg_recv(struct usb_device *dev, __u8 endpoint, __u8 request,
1869 			 __u8 requesttype, __u16 value, __u16 index,
1870 			 void *data, __u16 size, int timeout,
1871 			 gfp_t memflags);
1872 extern int usb_get_descriptor(struct usb_device *dev, unsigned char desctype,
1873 	unsigned char descindex, void *buf, int size);
1874 extern int usb_get_status(struct usb_device *dev,
1875 	int recip, int type, int target, void *data);
1876 
1877 static inline int usb_get_std_status(struct usb_device *dev,
1878 	int recip, int target, void *data)
1879 {
1880 	return usb_get_status(dev, recip, USB_STATUS_TYPE_STANDARD, target,
1881 		data);
1882 }
1883 
1884 static inline int usb_get_ptm_status(struct usb_device *dev, void *data)
1885 {
1886 	return usb_get_status(dev, USB_RECIP_DEVICE, USB_STATUS_TYPE_PTM,
1887 		0, data);
1888 }
1889 
1890 extern int usb_string(struct usb_device *dev, int index,
1891 	char *buf, size_t size);
1892 extern char *usb_cache_string(struct usb_device *udev, int index);
1893 
1894 /* wrappers that also update important state inside usbcore */
1895 extern int usb_clear_halt(struct usb_device *dev, int pipe);
1896 extern int usb_reset_configuration(struct usb_device *dev);
1897 extern int usb_set_interface(struct usb_device *dev, int ifnum, int alternate);
1898 extern void usb_reset_endpoint(struct usb_device *dev, unsigned int epaddr);
1899 
1900 /* this request isn't really synchronous, but it belongs with the others */
1901 extern int usb_driver_set_configuration(struct usb_device *udev, int config);
1902 
1903 /* choose and set configuration for device */
1904 extern int usb_choose_configuration(struct usb_device *udev);
1905 extern int usb_set_configuration(struct usb_device *dev, int configuration);
1906 
1907 /*
1908  * timeouts, in milliseconds, used for sending/receiving control messages
1909  * they typically complete within a few frames (msec) after they're issued
1910  * USB identifies 5 second timeouts, maybe more in a few cases, and a few
1911  * slow devices (like some MGE Ellipse UPSes) actually push that limit.
1912  */
1913 #define USB_CTRL_GET_TIMEOUT	5000
1914 #define USB_CTRL_SET_TIMEOUT	5000
1915 
1916 
1917 /**
1918  * struct usb_sg_request - support for scatter/gather I/O
1919  * @status: zero indicates success, else negative errno
1920  * @bytes: counts bytes transferred.
1921  *
1922  * These requests are initialized using usb_sg_init(), and then are used
1923  * as request handles passed to usb_sg_wait() or usb_sg_cancel().  Most
1924  * members of the request object aren't for driver access.
1925  *
1926  * The status and bytecount values are valid only after usb_sg_wait()
1927  * returns.  If the status is zero, then the bytecount matches the total
1928  * from the request.
1929  *
1930  * After an error completion, drivers may need to clear a halt condition
1931  * on the endpoint.
1932  */
1933 struct usb_sg_request {
1934 	int			status;
1935 	size_t			bytes;
1936 
1937 	/* private:
1938 	 * members below are private to usbcore,
1939 	 * and are not provided for driver access!
1940 	 */
1941 	spinlock_t		lock;
1942 
1943 	struct usb_device	*dev;
1944 	int			pipe;
1945 
1946 	int			entries;
1947 	struct urb		**urbs;
1948 
1949 	int			count;
1950 	struct completion	complete;
1951 };
1952 
1953 int usb_sg_init(
1954 	struct usb_sg_request	*io,
1955 	struct usb_device	*dev,
1956 	unsigned		pipe,
1957 	unsigned		period,
1958 	struct scatterlist	*sg,
1959 	int			nents,
1960 	size_t			length,
1961 	gfp_t			mem_flags
1962 );
1963 void usb_sg_cancel(struct usb_sg_request *io);
1964 void usb_sg_wait(struct usb_sg_request *io);
1965 
1966 
1967 /* ----------------------------------------------------------------------- */
1968 
1969 /*
1970  * For various legacy reasons, Linux has a small cookie that's paired with
1971  * a struct usb_device to identify an endpoint queue.  Queue characteristics
1972  * are defined by the endpoint's descriptor.  This cookie is called a "pipe",
1973  * an unsigned int encoded as:
1974  *
1975  *  - direction:	bit 7		(0 = Host-to-Device [Out],
1976  *					 1 = Device-to-Host [In] ...
1977  *					like endpoint bEndpointAddress)
1978  *  - device address:	bits 8-14       ... bit positions known to uhci-hcd
1979  *  - endpoint:		bits 15-18      ... bit positions known to uhci-hcd
1980  *  - pipe type:	bits 30-31	(00 = isochronous, 01 = interrupt,
1981  *					 10 = control, 11 = bulk)
1982  *
1983  * Given the device address and endpoint descriptor, pipes are redundant.
1984  */
1985 
1986 /* NOTE:  these are not the standard USB_ENDPOINT_XFER_* values!! */
1987 /* (yet ... they're the values used by usbfs) */
1988 #define PIPE_ISOCHRONOUS		0
1989 #define PIPE_INTERRUPT			1
1990 #define PIPE_CONTROL			2
1991 #define PIPE_BULK			3
1992 
1993 #define usb_pipein(pipe)	((pipe) & USB_DIR_IN)
1994 #define usb_pipeout(pipe)	(!usb_pipein(pipe))
1995 
1996 #define usb_pipedevice(pipe)	(((pipe) >> 8) & 0x7f)
1997 #define usb_pipeendpoint(pipe)	(((pipe) >> 15) & 0xf)
1998 
1999 #define usb_pipetype(pipe)	(((pipe) >> 30) & 3)
2000 #define usb_pipeisoc(pipe)	(usb_pipetype((pipe)) == PIPE_ISOCHRONOUS)
2001 #define usb_pipeint(pipe)	(usb_pipetype((pipe)) == PIPE_INTERRUPT)
2002 #define usb_pipecontrol(pipe)	(usb_pipetype((pipe)) == PIPE_CONTROL)
2003 #define usb_pipebulk(pipe)	(usb_pipetype((pipe)) == PIPE_BULK)
2004 
2005 static inline unsigned int __create_pipe(struct usb_device *dev,
2006 		unsigned int endpoint)
2007 {
2008 	return (dev->devnum << 8) | (endpoint << 15);
2009 }
2010 
2011 /* Create various pipes... */
2012 #define usb_sndctrlpipe(dev, endpoint)	\
2013 	((PIPE_CONTROL << 30) | __create_pipe(dev, endpoint))
2014 #define usb_rcvctrlpipe(dev, endpoint)	\
2015 	((PIPE_CONTROL << 30) | __create_pipe(dev, endpoint) | USB_DIR_IN)
2016 #define usb_sndisocpipe(dev, endpoint)	\
2017 	((PIPE_ISOCHRONOUS << 30) | __create_pipe(dev, endpoint))
2018 #define usb_rcvisocpipe(dev, endpoint)	\
2019 	((PIPE_ISOCHRONOUS << 30) | __create_pipe(dev, endpoint) | USB_DIR_IN)
2020 #define usb_sndbulkpipe(dev, endpoint)	\
2021 	((PIPE_BULK << 30) | __create_pipe(dev, endpoint))
2022 #define usb_rcvbulkpipe(dev, endpoint)	\
2023 	((PIPE_BULK << 30) | __create_pipe(dev, endpoint) | USB_DIR_IN)
2024 #define usb_sndintpipe(dev, endpoint)	\
2025 	((PIPE_INTERRUPT << 30) | __create_pipe(dev, endpoint))
2026 #define usb_rcvintpipe(dev, endpoint)	\
2027 	((PIPE_INTERRUPT << 30) | __create_pipe(dev, endpoint) | USB_DIR_IN)
2028 
2029 static inline struct usb_host_endpoint *
2030 usb_pipe_endpoint(struct usb_device *dev, unsigned int pipe)
2031 {
2032 	struct usb_host_endpoint **eps;
2033 	eps = usb_pipein(pipe) ? dev->ep_in : dev->ep_out;
2034 	return eps[usb_pipeendpoint(pipe)];
2035 }
2036 
2037 static inline u16 usb_maxpacket(struct usb_device *udev, int pipe)
2038 {
2039 	struct usb_host_endpoint *ep = usb_pipe_endpoint(udev, pipe);
2040 
2041 	if (!ep)
2042 		return 0;
2043 
2044 	/* NOTE:  only 0x07ff bits are for packet size... */
2045 	return usb_endpoint_maxp(&ep->desc);
2046 }
2047 
2048 /* translate USB error codes to codes user space understands */
2049 static inline int usb_translate_errors(int error_code)
2050 {
2051 	switch (error_code) {
2052 	case 0:
2053 	case -ENOMEM:
2054 	case -ENODEV:
2055 	case -EOPNOTSUPP:
2056 		return error_code;
2057 	default:
2058 		return -EIO;
2059 	}
2060 }
2061 
2062 /* Events from the usb core */
2063 #define USB_DEVICE_ADD		0x0001
2064 #define USB_DEVICE_REMOVE	0x0002
2065 #define USB_BUS_ADD		0x0003
2066 #define USB_BUS_REMOVE		0x0004
2067 extern void usb_register_notify(struct notifier_block *nb);
2068 extern void usb_unregister_notify(struct notifier_block *nb);
2069 
2070 /* debugfs stuff */
2071 extern struct dentry *usb_debug_root;
2072 
2073 /* LED triggers */
2074 enum usb_led_event {
2075 	USB_LED_EVENT_HOST = 0,
2076 	USB_LED_EVENT_GADGET = 1,
2077 };
2078 
2079 #ifdef CONFIG_USB_LED_TRIG
2080 extern void usb_led_activity(enum usb_led_event ev);
2081 #else
2082 static inline void usb_led_activity(enum usb_led_event ev) {}
2083 #endif
2084 
2085 #endif  /* __KERNEL__ */
2086 
2087 #endif
2088