• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * (C) Copyright Linus Torvalds 1999
3  * (C) Copyright Johannes Erdfelt 1999-2001
4  * (C) Copyright Andreas Gal 1999
5  * (C) Copyright Gregory P. Smith 1999
6  * (C) Copyright Deti Fliegl 1999
7  * (C) Copyright Randy Dunlap 2000
8  * (C) Copyright David Brownell 2000-2002
9  *
10  * This program is free software; you can redistribute it and/or modify it
11  * under the terms of the GNU General Public License as published by the
12  * Free Software Foundation; either version 2 of the License, or (at your
13  * option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful, but
16  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
17  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
18  * for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software Foundation,
22  * Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23  */
24 
25 #include <linux/bcd.h>
26 #include <linux/module.h>
27 #include <linux/version.h>
28 #include <linux/kernel.h>
29 #include <linux/slab.h>
30 #include <linux/completion.h>
31 #include <linux/utsname.h>
32 #include <linux/mm.h>
33 #include <asm/io.h>
34 #include <linux/device.h>
35 #include <linux/dma-mapping.h>
36 #include <linux/mutex.h>
37 #include <asm/irq.h>
38 #include <asm/byteorder.h>
39 #include <asm/unaligned.h>
40 #include <linux/platform_device.h>
41 #include <linux/workqueue.h>
42 #include <linux/pm_runtime.h>
43 #include <linux/types.h>
44 
45 #include <linux/phy/phy.h>
46 #include <linux/usb.h>
47 #include <linux/usb/hcd.h>
48 #include <linux/usb/phy.h>
49 
50 #include "usb.h"
51 
52 
53 /*-------------------------------------------------------------------------*/
54 
55 /*
56  * USB Host Controller Driver framework
57  *
58  * Plugs into usbcore (usb_bus) and lets HCDs share code, minimizing
59  * HCD-specific behaviors/bugs.
60  *
61  * This does error checks, tracks devices and urbs, and delegates to a
62  * "hc_driver" only for code (and data) that really needs to know about
63  * hardware differences.  That includes root hub registers, i/o queues,
64  * and so on ... but as little else as possible.
65  *
66  * Shared code includes most of the "root hub" code (these are emulated,
67  * though each HC's hardware works differently) and PCI glue, plus request
68  * tracking overhead.  The HCD code should only block on spinlocks or on
69  * hardware handshaking; blocking on software events (such as other kernel
70  * threads releasing resources, or completing actions) is all generic.
71  *
72  * Happens the USB 2.0 spec says this would be invisible inside the "USBD",
73  * and includes mostly a "HCDI" (HCD Interface) along with some APIs used
74  * only by the hub driver ... and that neither should be seen or used by
75  * usb client device drivers.
76  *
77  * Contributors of ideas or unattributed patches include: David Brownell,
78  * Roman Weissgaerber, Rory Bolt, Greg Kroah-Hartman, ...
79  *
80  * HISTORY:
81  * 2002-02-21	Pull in most of the usb_bus support from usb.c; some
82  *		associated cleanup.  "usb_hcd" still != "usb_bus".
83  * 2001-12-12	Initial patch version for Linux 2.5.1 kernel.
84  */
85 
86 /*-------------------------------------------------------------------------*/
87 
88 /* Keep track of which host controller drivers are loaded */
89 unsigned long usb_hcds_loaded;
90 EXPORT_SYMBOL_GPL(usb_hcds_loaded);
91 
92 /* host controllers we manage */
93 LIST_HEAD (usb_bus_list);
94 EXPORT_SYMBOL_GPL (usb_bus_list);
95 
96 /* used when allocating bus numbers */
97 #define USB_MAXBUS		64
98 static DECLARE_BITMAP(busmap, USB_MAXBUS);
99 
100 /* used when updating list of hcds */
101 DEFINE_MUTEX(usb_bus_list_lock);	/* exported only for usbfs */
102 EXPORT_SYMBOL_GPL (usb_bus_list_lock);
103 
104 /* used for controlling access to virtual root hubs */
105 static DEFINE_SPINLOCK(hcd_root_hub_lock);
106 
107 /* used when updating an endpoint's URB list */
108 static DEFINE_SPINLOCK(hcd_urb_list_lock);
109 
110 /* used to protect against unlinking URBs after the device is gone */
111 static DEFINE_SPINLOCK(hcd_urb_unlink_lock);
112 
113 /* wait queue for synchronous unlinks */
114 DECLARE_WAIT_QUEUE_HEAD(usb_kill_urb_queue);
115 
is_root_hub(struct usb_device * udev)116 static inline int is_root_hub(struct usb_device *udev)
117 {
118 	return (udev->parent == NULL);
119 }
120 
121 /*-------------------------------------------------------------------------*/
122 
123 /*
124  * Sharable chunks of root hub code.
125  */
126 
127 /*-------------------------------------------------------------------------*/
128 #define KERNEL_REL	bin2bcd(((LINUX_VERSION_CODE >> 16) & 0x0ff))
129 #define KERNEL_VER	bin2bcd(((LINUX_VERSION_CODE >> 8) & 0x0ff))
130 
131 /* usb 3.0 root hub device descriptor */
132 static const u8 usb3_rh_dev_descriptor[18] = {
133 	0x12,       /*  __u8  bLength; */
134 	USB_DT_DEVICE, /* __u8 bDescriptorType; Device */
135 	0x00, 0x03, /*  __le16 bcdUSB; v3.0 */
136 
137 	0x09,	    /*  __u8  bDeviceClass; HUB_CLASSCODE */
138 	0x00,	    /*  __u8  bDeviceSubClass; */
139 	0x03,       /*  __u8  bDeviceProtocol; USB 3.0 hub */
140 	0x09,       /*  __u8  bMaxPacketSize0; 2^9 = 512 Bytes */
141 
142 	0x6b, 0x1d, /*  __le16 idVendor; Linux Foundation 0x1d6b */
143 	0x03, 0x00, /*  __le16 idProduct; device 0x0003 */
144 	KERNEL_VER, KERNEL_REL, /*  __le16 bcdDevice */
145 
146 	0x03,       /*  __u8  iManufacturer; */
147 	0x02,       /*  __u8  iProduct; */
148 	0x01,       /*  __u8  iSerialNumber; */
149 	0x01        /*  __u8  bNumConfigurations; */
150 };
151 
152 /* usb 2.5 (wireless USB 1.0) root hub device descriptor */
153 static const u8 usb25_rh_dev_descriptor[18] = {
154 	0x12,       /*  __u8  bLength; */
155 	USB_DT_DEVICE, /* __u8 bDescriptorType; Device */
156 	0x50, 0x02, /*  __le16 bcdUSB; v2.5 */
157 
158 	0x09,	    /*  __u8  bDeviceClass; HUB_CLASSCODE */
159 	0x00,	    /*  __u8  bDeviceSubClass; */
160 	0x00,       /*  __u8  bDeviceProtocol; [ usb 2.0 no TT ] */
161 	0xFF,       /*  __u8  bMaxPacketSize0; always 0xFF (WUSB Spec 7.4.1). */
162 
163 	0x6b, 0x1d, /*  __le16 idVendor; Linux Foundation 0x1d6b */
164 	0x02, 0x00, /*  __le16 idProduct; device 0x0002 */
165 	KERNEL_VER, KERNEL_REL, /*  __le16 bcdDevice */
166 
167 	0x03,       /*  __u8  iManufacturer; */
168 	0x02,       /*  __u8  iProduct; */
169 	0x01,       /*  __u8  iSerialNumber; */
170 	0x01        /*  __u8  bNumConfigurations; */
171 };
172 
173 /* usb 2.0 root hub device descriptor */
174 static const u8 usb2_rh_dev_descriptor[18] = {
175 	0x12,       /*  __u8  bLength; */
176 	USB_DT_DEVICE, /* __u8 bDescriptorType; Device */
177 	0x00, 0x02, /*  __le16 bcdUSB; v2.0 */
178 
179 	0x09,	    /*  __u8  bDeviceClass; HUB_CLASSCODE */
180 	0x00,	    /*  __u8  bDeviceSubClass; */
181 	0x00,       /*  __u8  bDeviceProtocol; [ usb 2.0 no TT ] */
182 	0x40,       /*  __u8  bMaxPacketSize0; 64 Bytes */
183 
184 	0x6b, 0x1d, /*  __le16 idVendor; Linux Foundation 0x1d6b */
185 	0x02, 0x00, /*  __le16 idProduct; device 0x0002 */
186 	KERNEL_VER, KERNEL_REL, /*  __le16 bcdDevice */
187 
188 	0x03,       /*  __u8  iManufacturer; */
189 	0x02,       /*  __u8  iProduct; */
190 	0x01,       /*  __u8  iSerialNumber; */
191 	0x01        /*  __u8  bNumConfigurations; */
192 };
193 
194 /* no usb 2.0 root hub "device qualifier" descriptor: one speed only */
195 
196 /* usb 1.1 root hub device descriptor */
197 static const u8 usb11_rh_dev_descriptor[18] = {
198 	0x12,       /*  __u8  bLength; */
199 	USB_DT_DEVICE, /* __u8 bDescriptorType; Device */
200 	0x10, 0x01, /*  __le16 bcdUSB; v1.1 */
201 
202 	0x09,	    /*  __u8  bDeviceClass; HUB_CLASSCODE */
203 	0x00,	    /*  __u8  bDeviceSubClass; */
204 	0x00,       /*  __u8  bDeviceProtocol; [ low/full speeds only ] */
205 	0x40,       /*  __u8  bMaxPacketSize0; 64 Bytes */
206 
207 	0x6b, 0x1d, /*  __le16 idVendor; Linux Foundation 0x1d6b */
208 	0x01, 0x00, /*  __le16 idProduct; device 0x0001 */
209 	KERNEL_VER, KERNEL_REL, /*  __le16 bcdDevice */
210 
211 	0x03,       /*  __u8  iManufacturer; */
212 	0x02,       /*  __u8  iProduct; */
213 	0x01,       /*  __u8  iSerialNumber; */
214 	0x01        /*  __u8  bNumConfigurations; */
215 };
216 
217 
218 /*-------------------------------------------------------------------------*/
219 
220 /* Configuration descriptors for our root hubs */
221 
222 static const u8 fs_rh_config_descriptor[] = {
223 
224 	/* one configuration */
225 	0x09,       /*  __u8  bLength; */
226 	USB_DT_CONFIG, /* __u8 bDescriptorType; Configuration */
227 	0x19, 0x00, /*  __le16 wTotalLength; */
228 	0x01,       /*  __u8  bNumInterfaces; (1) */
229 	0x01,       /*  __u8  bConfigurationValue; */
230 	0x00,       /*  __u8  iConfiguration; */
231 	0xc0,       /*  __u8  bmAttributes;
232 				 Bit 7: must be set,
233 				     6: Self-powered,
234 				     5: Remote wakeup,
235 				     4..0: resvd */
236 	0x00,       /*  __u8  MaxPower; */
237 
238 	/* USB 1.1:
239 	 * USB 2.0, single TT organization (mandatory):
240 	 *	one interface, protocol 0
241 	 *
242 	 * USB 2.0, multiple TT organization (optional):
243 	 *	two interfaces, protocols 1 (like single TT)
244 	 *	and 2 (multiple TT mode) ... config is
245 	 *	sometimes settable
246 	 *	NOT IMPLEMENTED
247 	 */
248 
249 	/* one interface */
250 	0x09,       /*  __u8  if_bLength; */
251 	USB_DT_INTERFACE,  /* __u8 if_bDescriptorType; Interface */
252 	0x00,       /*  __u8  if_bInterfaceNumber; */
253 	0x00,       /*  __u8  if_bAlternateSetting; */
254 	0x01,       /*  __u8  if_bNumEndpoints; */
255 	0x09,       /*  __u8  if_bInterfaceClass; HUB_CLASSCODE */
256 	0x00,       /*  __u8  if_bInterfaceSubClass; */
257 	0x00,       /*  __u8  if_bInterfaceProtocol; [usb1.1 or single tt] */
258 	0x00,       /*  __u8  if_iInterface; */
259 
260 	/* one endpoint (status change endpoint) */
261 	0x07,       /*  __u8  ep_bLength; */
262 	USB_DT_ENDPOINT, /* __u8 ep_bDescriptorType; Endpoint */
263 	0x81,       /*  __u8  ep_bEndpointAddress; IN Endpoint 1 */
264 	0x03,       /*  __u8  ep_bmAttributes; Interrupt */
265 	0x02, 0x00, /*  __le16 ep_wMaxPacketSize; 1 + (MAX_ROOT_PORTS / 8) */
266 	0xff        /*  __u8  ep_bInterval; (255ms -- usb 2.0 spec) */
267 };
268 
269 static const u8 hs_rh_config_descriptor[] = {
270 
271 	/* one configuration */
272 	0x09,       /*  __u8  bLength; */
273 	USB_DT_CONFIG, /* __u8 bDescriptorType; Configuration */
274 	0x19, 0x00, /*  __le16 wTotalLength; */
275 	0x01,       /*  __u8  bNumInterfaces; (1) */
276 	0x01,       /*  __u8  bConfigurationValue; */
277 	0x00,       /*  __u8  iConfiguration; */
278 	0xc0,       /*  __u8  bmAttributes;
279 				 Bit 7: must be set,
280 				     6: Self-powered,
281 				     5: Remote wakeup,
282 				     4..0: resvd */
283 	0x00,       /*  __u8  MaxPower; */
284 
285 	/* USB 1.1:
286 	 * USB 2.0, single TT organization (mandatory):
287 	 *	one interface, protocol 0
288 	 *
289 	 * USB 2.0, multiple TT organization (optional):
290 	 *	two interfaces, protocols 1 (like single TT)
291 	 *	and 2 (multiple TT mode) ... config is
292 	 *	sometimes settable
293 	 *	NOT IMPLEMENTED
294 	 */
295 
296 	/* one interface */
297 	0x09,       /*  __u8  if_bLength; */
298 	USB_DT_INTERFACE, /* __u8 if_bDescriptorType; Interface */
299 	0x00,       /*  __u8  if_bInterfaceNumber; */
300 	0x00,       /*  __u8  if_bAlternateSetting; */
301 	0x01,       /*  __u8  if_bNumEndpoints; */
302 	0x09,       /*  __u8  if_bInterfaceClass; HUB_CLASSCODE */
303 	0x00,       /*  __u8  if_bInterfaceSubClass; */
304 	0x00,       /*  __u8  if_bInterfaceProtocol; [usb1.1 or single tt] */
305 	0x00,       /*  __u8  if_iInterface; */
306 
307 	/* one endpoint (status change endpoint) */
308 	0x07,       /*  __u8  ep_bLength; */
309 	USB_DT_ENDPOINT, /* __u8 ep_bDescriptorType; Endpoint */
310 	0x81,       /*  __u8  ep_bEndpointAddress; IN Endpoint 1 */
311 	0x03,       /*  __u8  ep_bmAttributes; Interrupt */
312 		    /* __le16 ep_wMaxPacketSize; 1 + (MAX_ROOT_PORTS / 8)
313 		     * see hub.c:hub_configure() for details. */
314 	(USB_MAXCHILDREN + 1 + 7) / 8, 0x00,
315 	0x0c        /*  __u8  ep_bInterval; (256ms -- usb 2.0 spec) */
316 };
317 
318 static const u8 ss_rh_config_descriptor[] = {
319 	/* one configuration */
320 	0x09,       /*  __u8  bLength; */
321 	USB_DT_CONFIG, /* __u8 bDescriptorType; Configuration */
322 	0x1f, 0x00, /*  __le16 wTotalLength; */
323 	0x01,       /*  __u8  bNumInterfaces; (1) */
324 	0x01,       /*  __u8  bConfigurationValue; */
325 	0x00,       /*  __u8  iConfiguration; */
326 	0xc0,       /*  __u8  bmAttributes;
327 				 Bit 7: must be set,
328 				     6: Self-powered,
329 				     5: Remote wakeup,
330 				     4..0: resvd */
331 	0x00,       /*  __u8  MaxPower; */
332 
333 	/* one interface */
334 	0x09,       /*  __u8  if_bLength; */
335 	USB_DT_INTERFACE, /* __u8 if_bDescriptorType; Interface */
336 	0x00,       /*  __u8  if_bInterfaceNumber; */
337 	0x00,       /*  __u8  if_bAlternateSetting; */
338 	0x01,       /*  __u8  if_bNumEndpoints; */
339 	0x09,       /*  __u8  if_bInterfaceClass; HUB_CLASSCODE */
340 	0x00,       /*  __u8  if_bInterfaceSubClass; */
341 	0x00,       /*  __u8  if_bInterfaceProtocol; */
342 	0x00,       /*  __u8  if_iInterface; */
343 
344 	/* one endpoint (status change endpoint) */
345 	0x07,       /*  __u8  ep_bLength; */
346 	USB_DT_ENDPOINT, /* __u8 ep_bDescriptorType; Endpoint */
347 	0x81,       /*  __u8  ep_bEndpointAddress; IN Endpoint 1 */
348 	0x03,       /*  __u8  ep_bmAttributes; Interrupt */
349 		    /* __le16 ep_wMaxPacketSize; 1 + (MAX_ROOT_PORTS / 8)
350 		     * see hub.c:hub_configure() for details. */
351 	(USB_MAXCHILDREN + 1 + 7) / 8, 0x00,
352 	0x0c,       /*  __u8  ep_bInterval; (256ms -- usb 2.0 spec) */
353 
354 	/* one SuperSpeed endpoint companion descriptor */
355 	0x06,        /* __u8 ss_bLength */
356 	USB_DT_SS_ENDPOINT_COMP, /* __u8 ss_bDescriptorType; SuperSpeed EP */
357 		     /* Companion */
358 	0x00,        /* __u8 ss_bMaxBurst; allows 1 TX between ACKs */
359 	0x00,        /* __u8 ss_bmAttributes; 1 packet per service interval */
360 	0x02, 0x00   /* __le16 ss_wBytesPerInterval; 15 bits for max 15 ports */
361 };
362 
363 /* authorized_default behaviour:
364  * -1 is authorized for all devices except wireless (old behaviour)
365  * 0 is unauthorized for all devices
366  * 1 is authorized for all devices
367  */
368 static int authorized_default = -1;
369 module_param(authorized_default, int, S_IRUGO|S_IWUSR);
370 MODULE_PARM_DESC(authorized_default,
371 		"Default USB device authorization: 0 is not authorized, 1 is "
372 		"authorized, -1 is authorized except for wireless USB (default, "
373 		"old behaviour");
374 /*-------------------------------------------------------------------------*/
375 
376 /**
377  * ascii2desc() - Helper routine for producing UTF-16LE string descriptors
378  * @s: Null-terminated ASCII (actually ISO-8859-1) string
379  * @buf: Buffer for USB string descriptor (header + UTF-16LE)
380  * @len: Length (in bytes; may be odd) of descriptor buffer.
381  *
382  * Return: The number of bytes filled in: 2 + 2*strlen(s) or @len,
383  * whichever is less.
384  *
385  * Note:
386  * USB String descriptors can contain at most 126 characters; input
387  * strings longer than that are truncated.
388  */
389 static unsigned
ascii2desc(char const * s,u8 * buf,unsigned len)390 ascii2desc(char const *s, u8 *buf, unsigned len)
391 {
392 	unsigned n, t = 2 + 2*strlen(s);
393 
394 	if (t > 254)
395 		t = 254;	/* Longest possible UTF string descriptor */
396 	if (len > t)
397 		len = t;
398 
399 	t += USB_DT_STRING << 8;	/* Now t is first 16 bits to store */
400 
401 	n = len;
402 	while (n--) {
403 		*buf++ = t;
404 		if (!n--)
405 			break;
406 		*buf++ = t >> 8;
407 		t = (unsigned char)*s++;
408 	}
409 	return len;
410 }
411 
412 /**
413  * rh_string() - provides string descriptors for root hub
414  * @id: the string ID number (0: langids, 1: serial #, 2: product, 3: vendor)
415  * @hcd: the host controller for this root hub
416  * @data: buffer for output packet
417  * @len: length of the provided buffer
418  *
419  * Produces either a manufacturer, product or serial number string for the
420  * virtual root hub device.
421  *
422  * Return: The number of bytes filled in: the length of the descriptor or
423  * of the provided buffer, whichever is less.
424  */
425 static unsigned
rh_string(int id,struct usb_hcd const * hcd,u8 * data,unsigned len)426 rh_string(int id, struct usb_hcd const *hcd, u8 *data, unsigned len)
427 {
428 	char buf[100];
429 	char const *s;
430 	static char const langids[4] = {4, USB_DT_STRING, 0x09, 0x04};
431 
432 	/* language ids */
433 	switch (id) {
434 	case 0:
435 		/* Array of LANGID codes (0x0409 is MSFT-speak for "en-us") */
436 		/* See http://www.usb.org/developers/docs/USB_LANGIDs.pdf */
437 		if (len > 4)
438 			len = 4;
439 		memcpy(data, langids, len);
440 		return len;
441 	case 1:
442 		/* Serial number */
443 		s = hcd->self.bus_name;
444 		break;
445 	case 2:
446 		/* Product name */
447 		s = hcd->product_desc;
448 		break;
449 	case 3:
450 		/* Manufacturer */
451 		snprintf (buf, sizeof buf, "%s %s %s", init_utsname()->sysname,
452 			init_utsname()->release, hcd->driver->description);
453 		s = buf;
454 		break;
455 	default:
456 		/* Can't happen; caller guarantees it */
457 		return 0;
458 	}
459 
460 	return ascii2desc(s, data, len);
461 }
462 
463 
464 /* Root hub control transfers execute synchronously */
rh_call_control(struct usb_hcd * hcd,struct urb * urb)465 static int rh_call_control (struct usb_hcd *hcd, struct urb *urb)
466 {
467 	struct usb_ctrlrequest *cmd;
468 	u16		typeReq, wValue, wIndex, wLength;
469 	u8		*ubuf = urb->transfer_buffer;
470 	unsigned	len = 0;
471 	int		status;
472 	u8		patch_wakeup = 0;
473 	u8		patch_protocol = 0;
474 	u16		tbuf_size;
475 	u8		*tbuf = NULL;
476 	const u8	*bufp;
477 
478 	might_sleep();
479 
480 	spin_lock_irq(&hcd_root_hub_lock);
481 	status = usb_hcd_link_urb_to_ep(hcd, urb);
482 	spin_unlock_irq(&hcd_root_hub_lock);
483 	if (status)
484 		return status;
485 	urb->hcpriv = hcd;	/* Indicate it's queued */
486 
487 	cmd = (struct usb_ctrlrequest *) urb->setup_packet;
488 	typeReq  = (cmd->bRequestType << 8) | cmd->bRequest;
489 	wValue   = le16_to_cpu (cmd->wValue);
490 	wIndex   = le16_to_cpu (cmd->wIndex);
491 	wLength  = le16_to_cpu (cmd->wLength);
492 
493 	if (wLength > urb->transfer_buffer_length)
494 		goto error;
495 
496 	/*
497 	 * tbuf should be at least as big as the
498 	 * USB hub descriptor.
499 	 */
500 	tbuf_size =  max_t(u16, sizeof(struct usb_hub_descriptor), wLength);
501 	tbuf = kzalloc(tbuf_size, GFP_KERNEL);
502 	if (!tbuf) {
503 		status = -ENOMEM;
504 		goto err_alloc;
505 	}
506 
507 	bufp = tbuf;
508 
509 
510 	urb->actual_length = 0;
511 	switch (typeReq) {
512 
513 	/* DEVICE REQUESTS */
514 
515 	/* The root hub's remote wakeup enable bit is implemented using
516 	 * driver model wakeup flags.  If this system supports wakeup
517 	 * through USB, userspace may change the default "allow wakeup"
518 	 * policy through sysfs or these calls.
519 	 *
520 	 * Most root hubs support wakeup from downstream devices, for
521 	 * runtime power management (disabling USB clocks and reducing
522 	 * VBUS power usage).  However, not all of them do so; silicon,
523 	 * board, and BIOS bugs here are not uncommon, so these can't
524 	 * be treated quite like external hubs.
525 	 *
526 	 * Likewise, not all root hubs will pass wakeup events upstream,
527 	 * to wake up the whole system.  So don't assume root hub and
528 	 * controller capabilities are identical.
529 	 */
530 
531 	case DeviceRequest | USB_REQ_GET_STATUS:
532 		tbuf[0] = (device_may_wakeup(&hcd->self.root_hub->dev)
533 					<< USB_DEVICE_REMOTE_WAKEUP)
534 				| (1 << USB_DEVICE_SELF_POWERED);
535 		tbuf[1] = 0;
536 		len = 2;
537 		break;
538 	case DeviceOutRequest | USB_REQ_CLEAR_FEATURE:
539 		if (wValue == USB_DEVICE_REMOTE_WAKEUP)
540 			device_set_wakeup_enable(&hcd->self.root_hub->dev, 0);
541 		else
542 			goto error;
543 		break;
544 	case DeviceOutRequest | USB_REQ_SET_FEATURE:
545 		if (device_can_wakeup(&hcd->self.root_hub->dev)
546 				&& wValue == USB_DEVICE_REMOTE_WAKEUP)
547 			device_set_wakeup_enable(&hcd->self.root_hub->dev, 1);
548 		else
549 			goto error;
550 		break;
551 	case DeviceRequest | USB_REQ_GET_CONFIGURATION:
552 		tbuf[0] = 1;
553 		len = 1;
554 			/* FALLTHROUGH */
555 	case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
556 		break;
557 	case DeviceRequest | USB_REQ_GET_DESCRIPTOR:
558 		switch (wValue & 0xff00) {
559 		case USB_DT_DEVICE << 8:
560 			switch (hcd->speed) {
561 			case HCD_USB31:
562 			case HCD_USB3:
563 				bufp = usb3_rh_dev_descriptor;
564 				break;
565 			case HCD_USB25:
566 				bufp = usb25_rh_dev_descriptor;
567 				break;
568 			case HCD_USB2:
569 				bufp = usb2_rh_dev_descriptor;
570 				break;
571 			case HCD_USB11:
572 				bufp = usb11_rh_dev_descriptor;
573 				break;
574 			default:
575 				goto error;
576 			}
577 			len = 18;
578 			if (hcd->has_tt)
579 				patch_protocol = 1;
580 			break;
581 		case USB_DT_CONFIG << 8:
582 			switch (hcd->speed) {
583 			case HCD_USB31:
584 			case HCD_USB3:
585 				bufp = ss_rh_config_descriptor;
586 				len = sizeof ss_rh_config_descriptor;
587 				break;
588 			case HCD_USB25:
589 			case HCD_USB2:
590 				bufp = hs_rh_config_descriptor;
591 				len = sizeof hs_rh_config_descriptor;
592 				break;
593 			case HCD_USB11:
594 				bufp = fs_rh_config_descriptor;
595 				len = sizeof fs_rh_config_descriptor;
596 				break;
597 			default:
598 				goto error;
599 			}
600 			if (device_can_wakeup(&hcd->self.root_hub->dev))
601 				patch_wakeup = 1;
602 			break;
603 		case USB_DT_STRING << 8:
604 			if ((wValue & 0xff) < 4)
605 				urb->actual_length = rh_string(wValue & 0xff,
606 						hcd, ubuf, wLength);
607 			else /* unsupported IDs --> "protocol stall" */
608 				goto error;
609 			break;
610 		case USB_DT_BOS << 8:
611 			goto nongeneric;
612 		default:
613 			goto error;
614 		}
615 		break;
616 	case DeviceRequest | USB_REQ_GET_INTERFACE:
617 		tbuf[0] = 0;
618 		len = 1;
619 			/* FALLTHROUGH */
620 	case DeviceOutRequest | USB_REQ_SET_INTERFACE:
621 		break;
622 	case DeviceOutRequest | USB_REQ_SET_ADDRESS:
623 		/* wValue == urb->dev->devaddr */
624 		dev_dbg (hcd->self.controller, "root hub device address %d\n",
625 			wValue);
626 		break;
627 
628 	/* INTERFACE REQUESTS (no defined feature/status flags) */
629 
630 	/* ENDPOINT REQUESTS */
631 
632 	case EndpointRequest | USB_REQ_GET_STATUS:
633 		/* ENDPOINT_HALT flag */
634 		tbuf[0] = 0;
635 		tbuf[1] = 0;
636 		len = 2;
637 			/* FALLTHROUGH */
638 	case EndpointOutRequest | USB_REQ_CLEAR_FEATURE:
639 	case EndpointOutRequest | USB_REQ_SET_FEATURE:
640 		dev_dbg (hcd->self.controller, "no endpoint features yet\n");
641 		break;
642 
643 	/* CLASS REQUESTS (and errors) */
644 
645 	default:
646 nongeneric:
647 		/* non-generic request */
648 		switch (typeReq) {
649 		case GetHubStatus:
650 		case GetPortStatus:
651 			len = 4;
652 			break;
653 		case GetHubDescriptor:
654 			len = sizeof (struct usb_hub_descriptor);
655 			break;
656 		case DeviceRequest | USB_REQ_GET_DESCRIPTOR:
657 			/* len is returned by hub_control */
658 			break;
659 		}
660 		status = hcd->driver->hub_control (hcd,
661 			typeReq, wValue, wIndex,
662 			tbuf, wLength);
663 
664 		if (typeReq == GetHubDescriptor)
665 			usb_hub_adjust_deviceremovable(hcd->self.root_hub,
666 				(struct usb_hub_descriptor *)tbuf);
667 		break;
668 error:
669 		/* "protocol stall" on error */
670 		status = -EPIPE;
671 	}
672 
673 	if (status < 0) {
674 		len = 0;
675 		if (status != -EPIPE) {
676 			dev_dbg (hcd->self.controller,
677 				"CTRL: TypeReq=0x%x val=0x%x "
678 				"idx=0x%x len=%d ==> %d\n",
679 				typeReq, wValue, wIndex,
680 				wLength, status);
681 		}
682 	} else if (status > 0) {
683 		/* hub_control may return the length of data copied. */
684 		len = status;
685 		status = 0;
686 	}
687 	if (len) {
688 		if (urb->transfer_buffer_length < len)
689 			len = urb->transfer_buffer_length;
690 		urb->actual_length = len;
691 		/* always USB_DIR_IN, toward host */
692 		memcpy (ubuf, bufp, len);
693 
694 		/* report whether RH hardware supports remote wakeup */
695 		if (patch_wakeup &&
696 				len > offsetof (struct usb_config_descriptor,
697 						bmAttributes))
698 			((struct usb_config_descriptor *)ubuf)->bmAttributes
699 				|= USB_CONFIG_ATT_WAKEUP;
700 
701 		/* report whether RH hardware has an integrated TT */
702 		if (patch_protocol &&
703 				len > offsetof(struct usb_device_descriptor,
704 						bDeviceProtocol))
705 			((struct usb_device_descriptor *) ubuf)->
706 				bDeviceProtocol = USB_HUB_PR_HS_SINGLE_TT;
707 	}
708 
709 	kfree(tbuf);
710  err_alloc:
711 
712 	/* any errors get returned through the urb completion */
713 	spin_lock_irq(&hcd_root_hub_lock);
714 	usb_hcd_unlink_urb_from_ep(hcd, urb);
715 	usb_hcd_giveback_urb(hcd, urb, status);
716 	spin_unlock_irq(&hcd_root_hub_lock);
717 	return 0;
718 }
719 
720 /*-------------------------------------------------------------------------*/
721 
722 /*
723  * Root Hub interrupt transfers are polled using a timer if the
724  * driver requests it; otherwise the driver is responsible for
725  * calling usb_hcd_poll_rh_status() when an event occurs.
726  *
727  * Completions are called in_interrupt(), but they may or may not
728  * be in_irq().
729  */
usb_hcd_poll_rh_status(struct usb_hcd * hcd)730 void usb_hcd_poll_rh_status(struct usb_hcd *hcd)
731 {
732 	struct urb	*urb;
733 	int		length;
734 	int		status;
735 	unsigned long	flags;
736 	char		buffer[6];	/* Any root hubs with > 31 ports? */
737 
738 	if (unlikely(!hcd->rh_pollable))
739 		return;
740 	if (!hcd->uses_new_polling && !hcd->status_urb)
741 		return;
742 
743 	length = hcd->driver->hub_status_data(hcd, buffer);
744 	if (length > 0) {
745 
746 		/* try to complete the status urb */
747 		spin_lock_irqsave(&hcd_root_hub_lock, flags);
748 		urb = hcd->status_urb;
749 		if (urb) {
750 			clear_bit(HCD_FLAG_POLL_PENDING, &hcd->flags);
751 			hcd->status_urb = NULL;
752 			if (urb->transfer_buffer_length >= length) {
753 				status = 0;
754 			} else {
755 				status = -EOVERFLOW;
756 				length = urb->transfer_buffer_length;
757 			}
758 			urb->actual_length = length;
759 			memcpy(urb->transfer_buffer, buffer, length);
760 
761 			usb_hcd_unlink_urb_from_ep(hcd, urb);
762 			usb_hcd_giveback_urb(hcd, urb, status);
763 		} else {
764 			length = 0;
765 			set_bit(HCD_FLAG_POLL_PENDING, &hcd->flags);
766 		}
767 		spin_unlock_irqrestore(&hcd_root_hub_lock, flags);
768 	}
769 
770 	/* The USB 2.0 spec says 256 ms.  This is close enough and won't
771 	 * exceed that limit if HZ is 100. The math is more clunky than
772 	 * maybe expected, this is to make sure that all timers for USB devices
773 	 * fire at the same time to give the CPU a break in between */
774 	if (hcd->uses_new_polling ? HCD_POLL_RH(hcd) :
775 			(length == 0 && hcd->status_urb != NULL))
776 		mod_timer (&hcd->rh_timer, (jiffies/(HZ/4) + 1) * (HZ/4));
777 }
778 EXPORT_SYMBOL_GPL(usb_hcd_poll_rh_status);
779 
780 /* timer callback */
rh_timer_func(unsigned long _hcd)781 static void rh_timer_func (unsigned long _hcd)
782 {
783 	usb_hcd_poll_rh_status((struct usb_hcd *) _hcd);
784 }
785 
786 /*-------------------------------------------------------------------------*/
787 
rh_queue_status(struct usb_hcd * hcd,struct urb * urb)788 static int rh_queue_status (struct usb_hcd *hcd, struct urb *urb)
789 {
790 	int		retval;
791 	unsigned long	flags;
792 	unsigned	len = 1 + (urb->dev->maxchild / 8);
793 
794 	spin_lock_irqsave (&hcd_root_hub_lock, flags);
795 	if (hcd->status_urb || urb->transfer_buffer_length < len) {
796 		dev_dbg (hcd->self.controller, "not queuing rh status urb\n");
797 		retval = -EINVAL;
798 		goto done;
799 	}
800 
801 	retval = usb_hcd_link_urb_to_ep(hcd, urb);
802 	if (retval)
803 		goto done;
804 
805 	hcd->status_urb = urb;
806 	urb->hcpriv = hcd;	/* indicate it's queued */
807 	if (!hcd->uses_new_polling)
808 		mod_timer(&hcd->rh_timer, (jiffies/(HZ/4) + 1) * (HZ/4));
809 
810 	/* If a status change has already occurred, report it ASAP */
811 	else if (HCD_POLL_PENDING(hcd))
812 		mod_timer(&hcd->rh_timer, jiffies);
813 	retval = 0;
814  done:
815 	spin_unlock_irqrestore (&hcd_root_hub_lock, flags);
816 	return retval;
817 }
818 
rh_urb_enqueue(struct usb_hcd * hcd,struct urb * urb)819 static int rh_urb_enqueue (struct usb_hcd *hcd, struct urb *urb)
820 {
821 	if (usb_endpoint_xfer_int(&urb->ep->desc))
822 		return rh_queue_status (hcd, urb);
823 	if (usb_endpoint_xfer_control(&urb->ep->desc))
824 		return rh_call_control (hcd, urb);
825 	return -EINVAL;
826 }
827 
828 /*-------------------------------------------------------------------------*/
829 
830 /* Unlinks of root-hub control URBs are legal, but they don't do anything
831  * since these URBs always execute synchronously.
832  */
usb_rh_urb_dequeue(struct usb_hcd * hcd,struct urb * urb,int status)833 static int usb_rh_urb_dequeue(struct usb_hcd *hcd, struct urb *urb, int status)
834 {
835 	unsigned long	flags;
836 	int		rc;
837 
838 	spin_lock_irqsave(&hcd_root_hub_lock, flags);
839 	rc = usb_hcd_check_unlink_urb(hcd, urb, status);
840 	if (rc)
841 		goto done;
842 
843 	if (usb_endpoint_num(&urb->ep->desc) == 0) {	/* Control URB */
844 		;	/* Do nothing */
845 
846 	} else {				/* Status URB */
847 		if (!hcd->uses_new_polling)
848 			del_timer (&hcd->rh_timer);
849 		if (urb == hcd->status_urb) {
850 			hcd->status_urb = NULL;
851 			usb_hcd_unlink_urb_from_ep(hcd, urb);
852 			usb_hcd_giveback_urb(hcd, urb, status);
853 		}
854 	}
855  done:
856 	spin_unlock_irqrestore(&hcd_root_hub_lock, flags);
857 	return rc;
858 }
859 
860 
861 
862 /*
863  * Show & store the current value of authorized_default
864  */
authorized_default_show(struct device * dev,struct device_attribute * attr,char * buf)865 static ssize_t authorized_default_show(struct device *dev,
866 				       struct device_attribute *attr, char *buf)
867 {
868 	struct usb_device *rh_usb_dev = to_usb_device(dev);
869 	struct usb_bus *usb_bus = rh_usb_dev->bus;
870 	struct usb_hcd *hcd;
871 
872 	hcd = bus_to_hcd(usb_bus);
873 	return snprintf(buf, PAGE_SIZE, "%u\n", !!HCD_DEV_AUTHORIZED(hcd));
874 }
875 
authorized_default_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t size)876 static ssize_t authorized_default_store(struct device *dev,
877 					struct device_attribute *attr,
878 					const char *buf, size_t size)
879 {
880 	ssize_t result;
881 	unsigned val;
882 	struct usb_device *rh_usb_dev = to_usb_device(dev);
883 	struct usb_bus *usb_bus = rh_usb_dev->bus;
884 	struct usb_hcd *hcd;
885 
886 	hcd = bus_to_hcd(usb_bus);
887 	result = sscanf(buf, "%u\n", &val);
888 	if (result == 1) {
889 		if (val)
890 			set_bit(HCD_FLAG_DEV_AUTHORIZED, &hcd->flags);
891 		else
892 			clear_bit(HCD_FLAG_DEV_AUTHORIZED, &hcd->flags);
893 
894 		result = size;
895 	} else {
896 		result = -EINVAL;
897 	}
898 	return result;
899 }
900 static DEVICE_ATTR_RW(authorized_default);
901 
902 /*
903  * interface_authorized_default_show - show default authorization status
904  * for USB interfaces
905  *
906  * note: interface_authorized_default is the default value
907  *       for initializing the authorized attribute of interfaces
908  */
interface_authorized_default_show(struct device * dev,struct device_attribute * attr,char * buf)909 static ssize_t interface_authorized_default_show(struct device *dev,
910 		struct device_attribute *attr, char *buf)
911 {
912 	struct usb_device *usb_dev = to_usb_device(dev);
913 	struct usb_hcd *hcd = bus_to_hcd(usb_dev->bus);
914 
915 	return sprintf(buf, "%u\n", !!HCD_INTF_AUTHORIZED(hcd));
916 }
917 
918 /*
919  * interface_authorized_default_store - store default authorization status
920  * for USB interfaces
921  *
922  * note: interface_authorized_default is the default value
923  *       for initializing the authorized attribute of interfaces
924  */
interface_authorized_default_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)925 static ssize_t interface_authorized_default_store(struct device *dev,
926 		struct device_attribute *attr, const char *buf, size_t count)
927 {
928 	struct usb_device *usb_dev = to_usb_device(dev);
929 	struct usb_hcd *hcd = bus_to_hcd(usb_dev->bus);
930 	int rc = count;
931 	bool val;
932 
933 	if (strtobool(buf, &val) != 0)
934 		return -EINVAL;
935 
936 	if (val)
937 		set_bit(HCD_FLAG_INTF_AUTHORIZED, &hcd->flags);
938 	else
939 		clear_bit(HCD_FLAG_INTF_AUTHORIZED, &hcd->flags);
940 
941 	return rc;
942 }
943 static DEVICE_ATTR_RW(interface_authorized_default);
944 
945 /* Group all the USB bus attributes */
946 static struct attribute *usb_bus_attrs[] = {
947 		&dev_attr_authorized_default.attr,
948 		&dev_attr_interface_authorized_default.attr,
949 		NULL,
950 };
951 
952 static struct attribute_group usb_bus_attr_group = {
953 	.name = NULL,	/* we want them in the same directory */
954 	.attrs = usb_bus_attrs,
955 };
956 
957 
958 
959 /*-------------------------------------------------------------------------*/
960 
961 /**
962  * usb_bus_init - shared initialization code
963  * @bus: the bus structure being initialized
964  *
965  * This code is used to initialize a usb_bus structure, memory for which is
966  * separately managed.
967  */
usb_bus_init(struct usb_bus * bus)968 static void usb_bus_init (struct usb_bus *bus)
969 {
970 	memset (&bus->devmap, 0, sizeof(struct usb_devmap));
971 
972 	bus->devnum_next = 1;
973 
974 	bus->root_hub = NULL;
975 	bus->busnum = -1;
976 	bus->bandwidth_allocated = 0;
977 	bus->bandwidth_int_reqs  = 0;
978 	bus->bandwidth_isoc_reqs = 0;
979 	mutex_init(&bus->devnum_next_mutex);
980 
981 	INIT_LIST_HEAD (&bus->bus_list);
982 }
983 
984 /*-------------------------------------------------------------------------*/
985 
986 /**
987  * usb_register_bus - registers the USB host controller with the usb core
988  * @bus: pointer to the bus to register
989  * Context: !in_interrupt()
990  *
991  * Assigns a bus number, and links the controller into usbcore data
992  * structures so that it can be seen by scanning the bus list.
993  *
994  * Return: 0 if successful. A negative error code otherwise.
995  */
usb_register_bus(struct usb_bus * bus)996 static int usb_register_bus(struct usb_bus *bus)
997 {
998 	int result = -E2BIG;
999 	int busnum;
1000 
1001 	mutex_lock(&usb_bus_list_lock);
1002 	busnum = find_next_zero_bit(busmap, USB_MAXBUS, 1);
1003 	if (busnum >= USB_MAXBUS) {
1004 		printk (KERN_ERR "%s: too many buses\n", usbcore_name);
1005 		goto error_find_busnum;
1006 	}
1007 	set_bit(busnum, busmap);
1008 	bus->busnum = busnum;
1009 
1010 	/* Add it to the local list of buses */
1011 	list_add (&bus->bus_list, &usb_bus_list);
1012 	mutex_unlock(&usb_bus_list_lock);
1013 
1014 	usb_notify_add_bus(bus);
1015 
1016 	dev_info (bus->controller, "new USB bus registered, assigned bus "
1017 		  "number %d\n", bus->busnum);
1018 	return 0;
1019 
1020 error_find_busnum:
1021 	mutex_unlock(&usb_bus_list_lock);
1022 	return result;
1023 }
1024 
1025 /**
1026  * usb_deregister_bus - deregisters the USB host controller
1027  * @bus: pointer to the bus to deregister
1028  * Context: !in_interrupt()
1029  *
1030  * Recycles the bus number, and unlinks the controller from usbcore data
1031  * structures so that it won't be seen by scanning the bus list.
1032  */
usb_deregister_bus(struct usb_bus * bus)1033 static void usb_deregister_bus (struct usb_bus *bus)
1034 {
1035 	dev_info (bus->controller, "USB bus %d deregistered\n", bus->busnum);
1036 
1037 	/*
1038 	 * NOTE: make sure that all the devices are removed by the
1039 	 * controller code, as well as having it call this when cleaning
1040 	 * itself up
1041 	 */
1042 	mutex_lock(&usb_bus_list_lock);
1043 	list_del (&bus->bus_list);
1044 	mutex_unlock(&usb_bus_list_lock);
1045 
1046 	usb_notify_remove_bus(bus);
1047 
1048 	clear_bit(bus->busnum, busmap);
1049 }
1050 
1051 /**
1052  * register_root_hub - called by usb_add_hcd() to register a root hub
1053  * @hcd: host controller for this root hub
1054  *
1055  * This function registers the root hub with the USB subsystem.  It sets up
1056  * the device properly in the device tree and then calls usb_new_device()
1057  * to register the usb device.  It also assigns the root hub's USB address
1058  * (always 1).
1059  *
1060  * Return: 0 if successful. A negative error code otherwise.
1061  */
register_root_hub(struct usb_hcd * hcd)1062 static int register_root_hub(struct usb_hcd *hcd)
1063 {
1064 	struct device *parent_dev = hcd->self.controller;
1065 	struct usb_device *usb_dev = hcd->self.root_hub;
1066 	const int devnum = 1;
1067 	int retval;
1068 
1069 	usb_dev->devnum = devnum;
1070 	usb_dev->bus->devnum_next = devnum + 1;
1071 	memset (&usb_dev->bus->devmap.devicemap, 0,
1072 			sizeof usb_dev->bus->devmap.devicemap);
1073 	set_bit (devnum, usb_dev->bus->devmap.devicemap);
1074 	usb_set_device_state(usb_dev, USB_STATE_ADDRESS);
1075 
1076 	mutex_lock(&usb_bus_list_lock);
1077 
1078 	usb_dev->ep0.desc.wMaxPacketSize = cpu_to_le16(64);
1079 	retval = usb_get_device_descriptor(usb_dev, USB_DT_DEVICE_SIZE);
1080 	if (retval != sizeof usb_dev->descriptor) {
1081 		mutex_unlock(&usb_bus_list_lock);
1082 		dev_dbg (parent_dev, "can't read %s device descriptor %d\n",
1083 				dev_name(&usb_dev->dev), retval);
1084 		return (retval < 0) ? retval : -EMSGSIZE;
1085 	}
1086 
1087 	if (le16_to_cpu(usb_dev->descriptor.bcdUSB) >= 0x0201) {
1088 		retval = usb_get_bos_descriptor(usb_dev);
1089 		if (!retval) {
1090 			usb_dev->lpm_capable = usb_device_supports_lpm(usb_dev);
1091 		} else if (usb_dev->speed >= USB_SPEED_SUPER) {
1092 			mutex_unlock(&usb_bus_list_lock);
1093 			dev_dbg(parent_dev, "can't read %s bos descriptor %d\n",
1094 					dev_name(&usb_dev->dev), retval);
1095 			return retval;
1096 		}
1097 	}
1098 
1099 	retval = usb_new_device (usb_dev);
1100 	if (retval) {
1101 		dev_err (parent_dev, "can't register root hub for %s, %d\n",
1102 				dev_name(&usb_dev->dev), retval);
1103 	} else {
1104 		spin_lock_irq (&hcd_root_hub_lock);
1105 		hcd->rh_registered = 1;
1106 		spin_unlock_irq (&hcd_root_hub_lock);
1107 
1108 		/* Did the HC die before the root hub was registered? */
1109 		if (HCD_DEAD(hcd))
1110 			usb_hc_died (hcd);	/* This time clean up */
1111 	}
1112 	mutex_unlock(&usb_bus_list_lock);
1113 
1114 	return retval;
1115 }
1116 
1117 /*
1118  * usb_hcd_start_port_resume - a root-hub port is sending a resume signal
1119  * @bus: the bus which the root hub belongs to
1120  * @portnum: the port which is being resumed
1121  *
1122  * HCDs should call this function when they know that a resume signal is
1123  * being sent to a root-hub port.  The root hub will be prevented from
1124  * going into autosuspend until usb_hcd_end_port_resume() is called.
1125  *
1126  * The bus's private lock must be held by the caller.
1127  */
usb_hcd_start_port_resume(struct usb_bus * bus,int portnum)1128 void usb_hcd_start_port_resume(struct usb_bus *bus, int portnum)
1129 {
1130 	unsigned bit = 1 << portnum;
1131 
1132 	if (!(bus->resuming_ports & bit)) {
1133 		bus->resuming_ports |= bit;
1134 		pm_runtime_get_noresume(&bus->root_hub->dev);
1135 	}
1136 }
1137 EXPORT_SYMBOL_GPL(usb_hcd_start_port_resume);
1138 
1139 /*
1140  * usb_hcd_end_port_resume - a root-hub port has stopped sending a resume signal
1141  * @bus: the bus which the root hub belongs to
1142  * @portnum: the port which is being resumed
1143  *
1144  * HCDs should call this function when they know that a resume signal has
1145  * stopped being sent to a root-hub port.  The root hub will be allowed to
1146  * autosuspend again.
1147  *
1148  * The bus's private lock must be held by the caller.
1149  */
usb_hcd_end_port_resume(struct usb_bus * bus,int portnum)1150 void usb_hcd_end_port_resume(struct usb_bus *bus, int portnum)
1151 {
1152 	unsigned bit = 1 << portnum;
1153 
1154 	if (bus->resuming_ports & bit) {
1155 		bus->resuming_ports &= ~bit;
1156 		pm_runtime_put_noidle(&bus->root_hub->dev);
1157 	}
1158 }
1159 EXPORT_SYMBOL_GPL(usb_hcd_end_port_resume);
1160 
1161 /*-------------------------------------------------------------------------*/
1162 
1163 /**
1164  * usb_calc_bus_time - approximate periodic transaction time in nanoseconds
1165  * @speed: from dev->speed; USB_SPEED_{LOW,FULL,HIGH}
1166  * @is_input: true iff the transaction sends data to the host
1167  * @isoc: true for isochronous transactions, false for interrupt ones
1168  * @bytecount: how many bytes in the transaction.
1169  *
1170  * Return: Approximate bus time in nanoseconds for a periodic transaction.
1171  *
1172  * Note:
1173  * See USB 2.0 spec section 5.11.3; only periodic transfers need to be
1174  * scheduled in software, this function is only used for such scheduling.
1175  */
usb_calc_bus_time(int speed,int is_input,int isoc,int bytecount)1176 long usb_calc_bus_time (int speed, int is_input, int isoc, int bytecount)
1177 {
1178 	unsigned long	tmp;
1179 
1180 	switch (speed) {
1181 	case USB_SPEED_LOW: 	/* INTR only */
1182 		if (is_input) {
1183 			tmp = (67667L * (31L + 10L * BitTime (bytecount))) / 1000L;
1184 			return 64060L + (2 * BW_HUB_LS_SETUP) + BW_HOST_DELAY + tmp;
1185 		} else {
1186 			tmp = (66700L * (31L + 10L * BitTime (bytecount))) / 1000L;
1187 			return 64107L + (2 * BW_HUB_LS_SETUP) + BW_HOST_DELAY + tmp;
1188 		}
1189 	case USB_SPEED_FULL:	/* ISOC or INTR */
1190 		if (isoc) {
1191 			tmp = (8354L * (31L + 10L * BitTime (bytecount))) / 1000L;
1192 			return ((is_input) ? 7268L : 6265L) + BW_HOST_DELAY + tmp;
1193 		} else {
1194 			tmp = (8354L * (31L + 10L * BitTime (bytecount))) / 1000L;
1195 			return 9107L + BW_HOST_DELAY + tmp;
1196 		}
1197 	case USB_SPEED_HIGH:	/* ISOC or INTR */
1198 		/* FIXME adjust for input vs output */
1199 		if (isoc)
1200 			tmp = HS_NSECS_ISO (bytecount);
1201 		else
1202 			tmp = HS_NSECS (bytecount);
1203 		return tmp;
1204 	default:
1205 		pr_debug ("%s: bogus device speed!\n", usbcore_name);
1206 		return -1;
1207 	}
1208 }
1209 EXPORT_SYMBOL_GPL(usb_calc_bus_time);
1210 
1211 
1212 /*-------------------------------------------------------------------------*/
1213 
1214 /*
1215  * Generic HC operations.
1216  */
1217 
1218 /*-------------------------------------------------------------------------*/
1219 
1220 /**
1221  * usb_hcd_link_urb_to_ep - add an URB to its endpoint queue
1222  * @hcd: host controller to which @urb was submitted
1223  * @urb: URB being submitted
1224  *
1225  * Host controller drivers should call this routine in their enqueue()
1226  * method.  The HCD's private spinlock must be held and interrupts must
1227  * be disabled.  The actions carried out here are required for URB
1228  * submission, as well as for endpoint shutdown and for usb_kill_urb.
1229  *
1230  * Return: 0 for no error, otherwise a negative error code (in which case
1231  * the enqueue() method must fail).  If no error occurs but enqueue() fails
1232  * anyway, it must call usb_hcd_unlink_urb_from_ep() before releasing
1233  * the private spinlock and returning.
1234  */
usb_hcd_link_urb_to_ep(struct usb_hcd * hcd,struct urb * urb)1235 int usb_hcd_link_urb_to_ep(struct usb_hcd *hcd, struct urb *urb)
1236 {
1237 	int		rc = 0;
1238 
1239 	spin_lock(&hcd_urb_list_lock);
1240 
1241 	/* Check that the URB isn't being killed */
1242 	if (unlikely(atomic_read(&urb->reject))) {
1243 		rc = -EPERM;
1244 		goto done;
1245 	}
1246 
1247 	if (unlikely(!urb->ep->enabled)) {
1248 		rc = -ENOENT;
1249 		goto done;
1250 	}
1251 
1252 	if (unlikely(!urb->dev->can_submit)) {
1253 		rc = -EHOSTUNREACH;
1254 		goto done;
1255 	}
1256 
1257 	/*
1258 	 * Check the host controller's state and add the URB to the
1259 	 * endpoint's queue.
1260 	 */
1261 	if (HCD_RH_RUNNING(hcd)) {
1262 		urb->unlinked = 0;
1263 		list_add_tail(&urb->urb_list, &urb->ep->urb_list);
1264 	} else {
1265 		rc = -ESHUTDOWN;
1266 		goto done;
1267 	}
1268  done:
1269 	spin_unlock(&hcd_urb_list_lock);
1270 	return rc;
1271 }
1272 EXPORT_SYMBOL_GPL(usb_hcd_link_urb_to_ep);
1273 
1274 /**
1275  * usb_hcd_check_unlink_urb - check whether an URB may be unlinked
1276  * @hcd: host controller to which @urb was submitted
1277  * @urb: URB being checked for unlinkability
1278  * @status: error code to store in @urb if the unlink succeeds
1279  *
1280  * Host controller drivers should call this routine in their dequeue()
1281  * method.  The HCD's private spinlock must be held and interrupts must
1282  * be disabled.  The actions carried out here are required for making
1283  * sure than an unlink is valid.
1284  *
1285  * Return: 0 for no error, otherwise a negative error code (in which case
1286  * the dequeue() method must fail).  The possible error codes are:
1287  *
1288  *	-EIDRM: @urb was not submitted or has already completed.
1289  *		The completion function may not have been called yet.
1290  *
1291  *	-EBUSY: @urb has already been unlinked.
1292  */
usb_hcd_check_unlink_urb(struct usb_hcd * hcd,struct urb * urb,int status)1293 int usb_hcd_check_unlink_urb(struct usb_hcd *hcd, struct urb *urb,
1294 		int status)
1295 {
1296 	struct list_head	*tmp;
1297 
1298 	/* insist the urb is still queued */
1299 	list_for_each(tmp, &urb->ep->urb_list) {
1300 		if (tmp == &urb->urb_list)
1301 			break;
1302 	}
1303 	if (tmp != &urb->urb_list)
1304 		return -EIDRM;
1305 
1306 	/* Any status except -EINPROGRESS means something already started to
1307 	 * unlink this URB from the hardware.  So there's no more work to do.
1308 	 */
1309 	if (urb->unlinked)
1310 		return -EBUSY;
1311 	urb->unlinked = status;
1312 	return 0;
1313 }
1314 EXPORT_SYMBOL_GPL(usb_hcd_check_unlink_urb);
1315 
1316 /**
1317  * usb_hcd_unlink_urb_from_ep - remove an URB from its endpoint queue
1318  * @hcd: host controller to which @urb was submitted
1319  * @urb: URB being unlinked
1320  *
1321  * Host controller drivers should call this routine before calling
1322  * usb_hcd_giveback_urb().  The HCD's private spinlock must be held and
1323  * interrupts must be disabled.  The actions carried out here are required
1324  * for URB completion.
1325  */
usb_hcd_unlink_urb_from_ep(struct usb_hcd * hcd,struct urb * urb)1326 void usb_hcd_unlink_urb_from_ep(struct usb_hcd *hcd, struct urb *urb)
1327 {
1328 	/* clear all state linking urb to this dev (and hcd) */
1329 	spin_lock(&hcd_urb_list_lock);
1330 	list_del_init(&urb->urb_list);
1331 	spin_unlock(&hcd_urb_list_lock);
1332 }
1333 EXPORT_SYMBOL_GPL(usb_hcd_unlink_urb_from_ep);
1334 
1335 /*
1336  * Some usb host controllers can only perform dma using a small SRAM area.
1337  * The usb core itself is however optimized for host controllers that can dma
1338  * using regular system memory - like pci devices doing bus mastering.
1339  *
1340  * To support host controllers with limited dma capabilities we provide dma
1341  * bounce buffers. This feature can be enabled using the HCD_LOCAL_MEM flag.
1342  * For this to work properly the host controller code must first use the
1343  * function dma_declare_coherent_memory() to point out which memory area
1344  * that should be used for dma allocations.
1345  *
1346  * The HCD_LOCAL_MEM flag then tells the usb code to allocate all data for
1347  * dma using dma_alloc_coherent() which in turn allocates from the memory
1348  * area pointed out with dma_declare_coherent_memory().
1349  *
1350  * So, to summarize...
1351  *
1352  * - We need "local" memory, canonical example being
1353  *   a small SRAM on a discrete controller being the
1354  *   only memory that the controller can read ...
1355  *   (a) "normal" kernel memory is no good, and
1356  *   (b) there's not enough to share
1357  *
1358  * - The only *portable* hook for such stuff in the
1359  *   DMA framework is dma_declare_coherent_memory()
1360  *
1361  * - So we use that, even though the primary requirement
1362  *   is that the memory be "local" (hence addressable
1363  *   by that device), not "coherent".
1364  *
1365  */
1366 
hcd_alloc_coherent(struct usb_bus * bus,gfp_t mem_flags,dma_addr_t * dma_handle,void ** vaddr_handle,size_t size,enum dma_data_direction dir)1367 static int hcd_alloc_coherent(struct usb_bus *bus,
1368 			      gfp_t mem_flags, dma_addr_t *dma_handle,
1369 			      void **vaddr_handle, size_t size,
1370 			      enum dma_data_direction dir)
1371 {
1372 	unsigned char *vaddr;
1373 
1374 	if (*vaddr_handle == NULL) {
1375 		WARN_ON_ONCE(1);
1376 		return -EFAULT;
1377 	}
1378 
1379 	vaddr = hcd_buffer_alloc(bus, size + sizeof(vaddr),
1380 				 mem_flags, dma_handle);
1381 	if (!vaddr)
1382 		return -ENOMEM;
1383 
1384 	/*
1385 	 * Store the virtual address of the buffer at the end
1386 	 * of the allocated dma buffer. The size of the buffer
1387 	 * may be uneven so use unaligned functions instead
1388 	 * of just rounding up. It makes sense to optimize for
1389 	 * memory footprint over access speed since the amount
1390 	 * of memory available for dma may be limited.
1391 	 */
1392 	put_unaligned((unsigned long)*vaddr_handle,
1393 		      (unsigned long *)(vaddr + size));
1394 
1395 	if (dir == DMA_TO_DEVICE)
1396 		memcpy(vaddr, *vaddr_handle, size);
1397 
1398 	*vaddr_handle = vaddr;
1399 	return 0;
1400 }
1401 
hcd_free_coherent(struct usb_bus * bus,dma_addr_t * dma_handle,void ** vaddr_handle,size_t size,enum dma_data_direction dir)1402 static void hcd_free_coherent(struct usb_bus *bus, dma_addr_t *dma_handle,
1403 			      void **vaddr_handle, size_t size,
1404 			      enum dma_data_direction dir)
1405 {
1406 	unsigned char *vaddr = *vaddr_handle;
1407 
1408 	vaddr = (void *)get_unaligned((unsigned long *)(vaddr + size));
1409 
1410 	if (dir == DMA_FROM_DEVICE)
1411 		memcpy(vaddr, *vaddr_handle, size);
1412 
1413 	hcd_buffer_free(bus, size + sizeof(vaddr), *vaddr_handle, *dma_handle);
1414 
1415 	*vaddr_handle = vaddr;
1416 	*dma_handle = 0;
1417 }
1418 
usb_hcd_unmap_urb_setup_for_dma(struct usb_hcd * hcd,struct urb * urb)1419 void usb_hcd_unmap_urb_setup_for_dma(struct usb_hcd *hcd, struct urb *urb)
1420 {
1421 	if (urb->transfer_flags & URB_SETUP_MAP_SINGLE)
1422 		dma_unmap_single(hcd->self.controller,
1423 				urb->setup_dma,
1424 				sizeof(struct usb_ctrlrequest),
1425 				DMA_TO_DEVICE);
1426 	else if (urb->transfer_flags & URB_SETUP_MAP_LOCAL)
1427 		hcd_free_coherent(urb->dev->bus,
1428 				&urb->setup_dma,
1429 				(void **) &urb->setup_packet,
1430 				sizeof(struct usb_ctrlrequest),
1431 				DMA_TO_DEVICE);
1432 
1433 	/* Make it safe to call this routine more than once */
1434 	urb->transfer_flags &= ~(URB_SETUP_MAP_SINGLE | URB_SETUP_MAP_LOCAL);
1435 }
1436 EXPORT_SYMBOL_GPL(usb_hcd_unmap_urb_setup_for_dma);
1437 
unmap_urb_for_dma(struct usb_hcd * hcd,struct urb * urb)1438 static void unmap_urb_for_dma(struct usb_hcd *hcd, struct urb *urb)
1439 {
1440 	if (hcd->driver->unmap_urb_for_dma)
1441 		hcd->driver->unmap_urb_for_dma(hcd, urb);
1442 	else
1443 		usb_hcd_unmap_urb_for_dma(hcd, urb);
1444 }
1445 
usb_hcd_unmap_urb_for_dma(struct usb_hcd * hcd,struct urb * urb)1446 void usb_hcd_unmap_urb_for_dma(struct usb_hcd *hcd, struct urb *urb)
1447 {
1448 	enum dma_data_direction dir;
1449 
1450 	usb_hcd_unmap_urb_setup_for_dma(hcd, urb);
1451 
1452 	dir = usb_urb_dir_in(urb) ? DMA_FROM_DEVICE : DMA_TO_DEVICE;
1453 	if (urb->transfer_flags & URB_DMA_MAP_SG)
1454 		dma_unmap_sg(hcd->self.controller,
1455 				urb->sg,
1456 				urb->num_sgs,
1457 				dir);
1458 	else if (urb->transfer_flags & URB_DMA_MAP_PAGE)
1459 		dma_unmap_page(hcd->self.controller,
1460 				urb->transfer_dma,
1461 				urb->transfer_buffer_length,
1462 				dir);
1463 	else if (urb->transfer_flags & URB_DMA_MAP_SINGLE)
1464 		dma_unmap_single(hcd->self.controller,
1465 				urb->transfer_dma,
1466 				urb->transfer_buffer_length,
1467 				dir);
1468 	else if (urb->transfer_flags & URB_MAP_LOCAL)
1469 		hcd_free_coherent(urb->dev->bus,
1470 				&urb->transfer_dma,
1471 				&urb->transfer_buffer,
1472 				urb->transfer_buffer_length,
1473 				dir);
1474 
1475 	/* Make it safe to call this routine more than once */
1476 	urb->transfer_flags &= ~(URB_DMA_MAP_SG | URB_DMA_MAP_PAGE |
1477 			URB_DMA_MAP_SINGLE | URB_MAP_LOCAL);
1478 }
1479 EXPORT_SYMBOL_GPL(usb_hcd_unmap_urb_for_dma);
1480 
map_urb_for_dma(struct usb_hcd * hcd,struct urb * urb,gfp_t mem_flags)1481 static int map_urb_for_dma(struct usb_hcd *hcd, struct urb *urb,
1482 			   gfp_t mem_flags)
1483 {
1484 	if (hcd->driver->map_urb_for_dma)
1485 		return hcd->driver->map_urb_for_dma(hcd, urb, mem_flags);
1486 	else
1487 		return usb_hcd_map_urb_for_dma(hcd, urb, mem_flags);
1488 }
1489 
usb_hcd_map_urb_for_dma(struct usb_hcd * hcd,struct urb * urb,gfp_t mem_flags)1490 int usb_hcd_map_urb_for_dma(struct usb_hcd *hcd, struct urb *urb,
1491 			    gfp_t mem_flags)
1492 {
1493 	enum dma_data_direction dir;
1494 	int ret = 0;
1495 
1496 	/* Map the URB's buffers for DMA access.
1497 	 * Lower level HCD code should use *_dma exclusively,
1498 	 * unless it uses pio or talks to another transport,
1499 	 * or uses the provided scatter gather list for bulk.
1500 	 */
1501 
1502 	if (usb_endpoint_xfer_control(&urb->ep->desc)) {
1503 		if (hcd->self.uses_pio_for_control)
1504 			return ret;
1505 		if (hcd->self.uses_dma) {
1506 			urb->setup_dma = dma_map_single(
1507 					hcd->self.controller,
1508 					urb->setup_packet,
1509 					sizeof(struct usb_ctrlrequest),
1510 					DMA_TO_DEVICE);
1511 			if (dma_mapping_error(hcd->self.controller,
1512 						urb->setup_dma))
1513 				return -EAGAIN;
1514 			urb->transfer_flags |= URB_SETUP_MAP_SINGLE;
1515 		} else if (hcd->driver->flags & HCD_LOCAL_MEM) {
1516 			ret = hcd_alloc_coherent(
1517 					urb->dev->bus, mem_flags,
1518 					&urb->setup_dma,
1519 					(void **)&urb->setup_packet,
1520 					sizeof(struct usb_ctrlrequest),
1521 					DMA_TO_DEVICE);
1522 			if (ret)
1523 				return ret;
1524 			urb->transfer_flags |= URB_SETUP_MAP_LOCAL;
1525 		}
1526 	}
1527 
1528 	dir = usb_urb_dir_in(urb) ? DMA_FROM_DEVICE : DMA_TO_DEVICE;
1529 	if (urb->transfer_buffer_length != 0
1530 	    && !(urb->transfer_flags & URB_NO_TRANSFER_DMA_MAP)) {
1531 		if (hcd->self.uses_dma) {
1532 			if (urb->num_sgs) {
1533 				int n;
1534 
1535 				/* We don't support sg for isoc transfers ! */
1536 				if (usb_endpoint_xfer_isoc(&urb->ep->desc)) {
1537 					WARN_ON(1);
1538 					return -EINVAL;
1539 				}
1540 
1541 				n = dma_map_sg(
1542 						hcd->self.controller,
1543 						urb->sg,
1544 						urb->num_sgs,
1545 						dir);
1546 				if (n <= 0)
1547 					ret = -EAGAIN;
1548 				else
1549 					urb->transfer_flags |= URB_DMA_MAP_SG;
1550 				urb->num_mapped_sgs = n;
1551 				if (n != urb->num_sgs)
1552 					urb->transfer_flags |=
1553 							URB_DMA_SG_COMBINED;
1554 			} else if (urb->sg) {
1555 				struct scatterlist *sg = urb->sg;
1556 				urb->transfer_dma = dma_map_page(
1557 						hcd->self.controller,
1558 						sg_page(sg),
1559 						sg->offset,
1560 						urb->transfer_buffer_length,
1561 						dir);
1562 				if (dma_mapping_error(hcd->self.controller,
1563 						urb->transfer_dma))
1564 					ret = -EAGAIN;
1565 				else
1566 					urb->transfer_flags |= URB_DMA_MAP_PAGE;
1567 			} else if (is_vmalloc_addr(urb->transfer_buffer)) {
1568 				WARN_ONCE(1, "transfer buffer not dma capable\n");
1569 				ret = -EAGAIN;
1570 			} else {
1571 				urb->transfer_dma = dma_map_single(
1572 						hcd->self.controller,
1573 						urb->transfer_buffer,
1574 						urb->transfer_buffer_length,
1575 						dir);
1576 				if (dma_mapping_error(hcd->self.controller,
1577 						urb->transfer_dma))
1578 					ret = -EAGAIN;
1579 				else
1580 					urb->transfer_flags |= URB_DMA_MAP_SINGLE;
1581 			}
1582 		} else if (hcd->driver->flags & HCD_LOCAL_MEM) {
1583 			ret = hcd_alloc_coherent(
1584 					urb->dev->bus, mem_flags,
1585 					&urb->transfer_dma,
1586 					&urb->transfer_buffer,
1587 					urb->transfer_buffer_length,
1588 					dir);
1589 			if (ret == 0)
1590 				urb->transfer_flags |= URB_MAP_LOCAL;
1591 		}
1592 		if (ret && (urb->transfer_flags & (URB_SETUP_MAP_SINGLE |
1593 				URB_SETUP_MAP_LOCAL)))
1594 			usb_hcd_unmap_urb_for_dma(hcd, urb);
1595 	}
1596 	return ret;
1597 }
1598 EXPORT_SYMBOL_GPL(usb_hcd_map_urb_for_dma);
1599 
1600 /*-------------------------------------------------------------------------*/
1601 
1602 /* may be called in any context with a valid urb->dev usecount
1603  * caller surrenders "ownership" of urb
1604  * expects usb_submit_urb() to have sanity checked and conditioned all
1605  * inputs in the urb
1606  */
usb_hcd_submit_urb(struct urb * urb,gfp_t mem_flags)1607 int usb_hcd_submit_urb (struct urb *urb, gfp_t mem_flags)
1608 {
1609 	int			status;
1610 	struct usb_hcd		*hcd = bus_to_hcd(urb->dev->bus);
1611 
1612 	/* increment urb's reference count as part of giving it to the HCD
1613 	 * (which will control it).  HCD guarantees that it either returns
1614 	 * an error or calls giveback(), but not both.
1615 	 */
1616 	usb_get_urb(urb);
1617 	atomic_inc(&urb->use_count);
1618 	atomic_inc(&urb->dev->urbnum);
1619 	usbmon_urb_submit(&hcd->self, urb);
1620 
1621 	/* NOTE requirements on root-hub callers (usbfs and the hub
1622 	 * driver, for now):  URBs' urb->transfer_buffer must be
1623 	 * valid and usb_buffer_{sync,unmap}() not be needed, since
1624 	 * they could clobber root hub response data.  Also, control
1625 	 * URBs must be submitted in process context with interrupts
1626 	 * enabled.
1627 	 */
1628 
1629 	if (is_root_hub(urb->dev)) {
1630 		status = rh_urb_enqueue(hcd, urb);
1631 	} else {
1632 		status = map_urb_for_dma(hcd, urb, mem_flags);
1633 		if (likely(status == 0)) {
1634 			status = hcd->driver->urb_enqueue(hcd, urb, mem_flags);
1635 			if (unlikely(status))
1636 				unmap_urb_for_dma(hcd, urb);
1637 		}
1638 	}
1639 
1640 	if (unlikely(status)) {
1641 		usbmon_urb_submit_error(&hcd->self, urb, status);
1642 		urb->hcpriv = NULL;
1643 		INIT_LIST_HEAD(&urb->urb_list);
1644 		atomic_dec(&urb->use_count);
1645 		/*
1646 		 * Order the write of urb->use_count above before the read
1647 		 * of urb->reject below.  Pairs with the memory barriers in
1648 		 * usb_kill_urb() and usb_poison_urb().
1649 		 */
1650 		smp_mb__after_atomic();
1651 
1652 		atomic_dec(&urb->dev->urbnum);
1653 		if (atomic_read(&urb->reject))
1654 			wake_up(&usb_kill_urb_queue);
1655 		usb_put_urb(urb);
1656 	}
1657 	return status;
1658 }
1659 
1660 /*-------------------------------------------------------------------------*/
1661 
1662 /* this makes the hcd giveback() the urb more quickly, by kicking it
1663  * off hardware queues (which may take a while) and returning it as
1664  * soon as practical.  we've already set up the urb's return status,
1665  * but we can't know if the callback completed already.
1666  */
unlink1(struct usb_hcd * hcd,struct urb * urb,int status)1667 static int unlink1(struct usb_hcd *hcd, struct urb *urb, int status)
1668 {
1669 	int		value;
1670 
1671 	if (is_root_hub(urb->dev))
1672 		value = usb_rh_urb_dequeue(hcd, urb, status);
1673 	else {
1674 
1675 		/* The only reason an HCD might fail this call is if
1676 		 * it has not yet fully queued the urb to begin with.
1677 		 * Such failures should be harmless. */
1678 		value = hcd->driver->urb_dequeue(hcd, urb, status);
1679 	}
1680 	return value;
1681 }
1682 
1683 /*
1684  * called in any context
1685  *
1686  * caller guarantees urb won't be recycled till both unlink()
1687  * and the urb's completion function return
1688  */
usb_hcd_unlink_urb(struct urb * urb,int status)1689 int usb_hcd_unlink_urb (struct urb *urb, int status)
1690 {
1691 	struct usb_hcd		*hcd;
1692 	struct usb_device	*udev = urb->dev;
1693 	int			retval = -EIDRM;
1694 	unsigned long		flags;
1695 
1696 	/* Prevent the device and bus from going away while
1697 	 * the unlink is carried out.  If they are already gone
1698 	 * then urb->use_count must be 0, since disconnected
1699 	 * devices can't have any active URBs.
1700 	 */
1701 	spin_lock_irqsave(&hcd_urb_unlink_lock, flags);
1702 	if (atomic_read(&urb->use_count) > 0) {
1703 		retval = 0;
1704 		usb_get_dev(udev);
1705 	}
1706 	spin_unlock_irqrestore(&hcd_urb_unlink_lock, flags);
1707 	if (retval == 0) {
1708 		hcd = bus_to_hcd(urb->dev->bus);
1709 		retval = unlink1(hcd, urb, status);
1710 		if (retval == 0)
1711 			retval = -EINPROGRESS;
1712 		else if (retval != -EIDRM && retval != -EBUSY)
1713 			dev_dbg(&udev->dev, "hcd_unlink_urb %pK fail %d\n",
1714 					urb, retval);
1715 		usb_put_dev(udev);
1716 	}
1717 	return retval;
1718 }
1719 
1720 /*-------------------------------------------------------------------------*/
1721 
__usb_hcd_giveback_urb(struct urb * urb)1722 static void __usb_hcd_giveback_urb(struct urb *urb)
1723 {
1724 	struct usb_hcd *hcd = bus_to_hcd(urb->dev->bus);
1725 	struct usb_anchor *anchor = urb->anchor;
1726 	int status = urb->unlinked;
1727 	unsigned long flags;
1728 
1729 	urb->hcpriv = NULL;
1730 	if (unlikely((urb->transfer_flags & URB_SHORT_NOT_OK) &&
1731 	    urb->actual_length < urb->transfer_buffer_length &&
1732 	    !status))
1733 		status = -EREMOTEIO;
1734 
1735 	unmap_urb_for_dma(hcd, urb);
1736 	usbmon_urb_complete(&hcd->self, urb, status);
1737 	usb_anchor_suspend_wakeups(anchor);
1738 	usb_unanchor_urb(urb);
1739 	if (likely(status == 0))
1740 		usb_led_activity(USB_LED_EVENT_HOST);
1741 
1742 	/* pass ownership to the completion handler */
1743 	urb->status = status;
1744 
1745 	/*
1746 	 * We disable local IRQs here avoid possible deadlock because
1747 	 * drivers may call spin_lock() to hold lock which might be
1748 	 * acquired in one hard interrupt handler.
1749 	 *
1750 	 * The local_irq_save()/local_irq_restore() around complete()
1751 	 * will be removed if current USB drivers have been cleaned up
1752 	 * and no one may trigger the above deadlock situation when
1753 	 * running complete() in tasklet.
1754 	 */
1755 	local_irq_save(flags);
1756 	urb->complete(urb);
1757 	local_irq_restore(flags);
1758 
1759 	usb_anchor_resume_wakeups(anchor);
1760 	atomic_dec(&urb->use_count);
1761 	/*
1762 	 * Order the write of urb->use_count above before the read
1763 	 * of urb->reject below.  Pairs with the memory barriers in
1764 	 * usb_kill_urb() and usb_poison_urb().
1765 	 */
1766 	smp_mb__after_atomic();
1767 
1768 	if (unlikely(atomic_read(&urb->reject)))
1769 		wake_up(&usb_kill_urb_queue);
1770 	usb_put_urb(urb);
1771 }
1772 
usb_giveback_urb_bh(unsigned long param)1773 static void usb_giveback_urb_bh(unsigned long param)
1774 {
1775 	struct giveback_urb_bh *bh = (struct giveback_urb_bh *)param;
1776 	struct list_head local_list;
1777 
1778 	spin_lock_irq(&bh->lock);
1779 	bh->running = true;
1780  restart:
1781 	list_replace_init(&bh->head, &local_list);
1782 	spin_unlock_irq(&bh->lock);
1783 
1784 	while (!list_empty(&local_list)) {
1785 		struct urb *urb;
1786 
1787 		urb = list_entry(local_list.next, struct urb, urb_list);
1788 		list_del_init(&urb->urb_list);
1789 		bh->completing_ep = urb->ep;
1790 		__usb_hcd_giveback_urb(urb);
1791 		bh->completing_ep = NULL;
1792 	}
1793 
1794 	/* check if there are new URBs to giveback */
1795 	spin_lock_irq(&bh->lock);
1796 	if (!list_empty(&bh->head))
1797 		goto restart;
1798 	bh->running = false;
1799 	spin_unlock_irq(&bh->lock);
1800 }
1801 
1802 /**
1803  * usb_hcd_giveback_urb - return URB from HCD to device driver
1804  * @hcd: host controller returning the URB
1805  * @urb: urb being returned to the USB device driver.
1806  * @status: completion status code for the URB.
1807  * Context: in_interrupt()
1808  *
1809  * This hands the URB from HCD to its USB device driver, using its
1810  * completion function.  The HCD has freed all per-urb resources
1811  * (and is done using urb->hcpriv).  It also released all HCD locks;
1812  * the device driver won't cause problems if it frees, modifies,
1813  * or resubmits this URB.
1814  *
1815  * If @urb was unlinked, the value of @status will be overridden by
1816  * @urb->unlinked.  Erroneous short transfers are detected in case
1817  * the HCD hasn't checked for them.
1818  */
usb_hcd_giveback_urb(struct usb_hcd * hcd,struct urb * urb,int status)1819 void usb_hcd_giveback_urb(struct usb_hcd *hcd, struct urb *urb, int status)
1820 {
1821 	struct giveback_urb_bh *bh;
1822 	bool running, high_prio_bh;
1823 
1824 	/* pass status to tasklet via unlinked */
1825 	if (likely(!urb->unlinked))
1826 		urb->unlinked = status;
1827 
1828 	if (!hcd_giveback_urb_in_bh(hcd) && !is_root_hub(urb->dev)) {
1829 		__usb_hcd_giveback_urb(urb);
1830 		return;
1831 	}
1832 
1833 	if (usb_pipeisoc(urb->pipe) || usb_pipeint(urb->pipe)) {
1834 		bh = &hcd->high_prio_bh;
1835 		high_prio_bh = true;
1836 	} else {
1837 		bh = &hcd->low_prio_bh;
1838 		high_prio_bh = false;
1839 	}
1840 
1841 	spin_lock(&bh->lock);
1842 	list_add_tail(&urb->urb_list, &bh->head);
1843 	running = bh->running;
1844 	spin_unlock(&bh->lock);
1845 
1846 	if (running)
1847 		;
1848 	else if (high_prio_bh)
1849 		tasklet_hi_schedule(&bh->bh);
1850 	else
1851 		tasklet_schedule(&bh->bh);
1852 }
1853 EXPORT_SYMBOL_GPL(usb_hcd_giveback_urb);
1854 
1855 /*-------------------------------------------------------------------------*/
1856 
1857 /* Cancel all URBs pending on this endpoint and wait for the endpoint's
1858  * queue to drain completely.  The caller must first insure that no more
1859  * URBs can be submitted for this endpoint.
1860  */
usb_hcd_flush_endpoint(struct usb_device * udev,struct usb_host_endpoint * ep)1861 void usb_hcd_flush_endpoint(struct usb_device *udev,
1862 		struct usb_host_endpoint *ep)
1863 {
1864 	struct usb_hcd		*hcd;
1865 	struct urb		*urb;
1866 
1867 	if (!ep)
1868 		return;
1869 	might_sleep();
1870 	hcd = bus_to_hcd(udev->bus);
1871 
1872 	/* No more submits can occur */
1873 	spin_lock_irq(&hcd_urb_list_lock);
1874 rescan:
1875 	list_for_each_entry_reverse(urb, &ep->urb_list, urb_list) {
1876 		int	is_in;
1877 
1878 		if (urb->unlinked)
1879 			continue;
1880 		usb_get_urb (urb);
1881 		is_in = usb_urb_dir_in(urb);
1882 		spin_unlock(&hcd_urb_list_lock);
1883 
1884 		/* kick hcd */
1885 		unlink1(hcd, urb, -ESHUTDOWN);
1886 		dev_dbg (hcd->self.controller,
1887 			"shutdown urb %pK ep%d%s%s\n",
1888 			urb, usb_endpoint_num(&ep->desc),
1889 			is_in ? "in" : "out",
1890 			({	char *s;
1891 
1892 				 switch (usb_endpoint_type(&ep->desc)) {
1893 				 case USB_ENDPOINT_XFER_CONTROL:
1894 					s = ""; break;
1895 				 case USB_ENDPOINT_XFER_BULK:
1896 					s = "-bulk"; break;
1897 				 case USB_ENDPOINT_XFER_INT:
1898 					s = "-intr"; break;
1899 				 default:
1900 					s = "-iso"; break;
1901 				};
1902 				s;
1903 			}));
1904 		usb_put_urb (urb);
1905 
1906 		/* list contents may have changed */
1907 		spin_lock(&hcd_urb_list_lock);
1908 		goto rescan;
1909 	}
1910 	spin_unlock_irq(&hcd_urb_list_lock);
1911 
1912 	/* Wait until the endpoint queue is completely empty */
1913 	while (!list_empty (&ep->urb_list)) {
1914 		spin_lock_irq(&hcd_urb_list_lock);
1915 
1916 		/* The list may have changed while we acquired the spinlock */
1917 		urb = NULL;
1918 		if (!list_empty (&ep->urb_list)) {
1919 			urb = list_entry (ep->urb_list.prev, struct urb,
1920 					urb_list);
1921 			usb_get_urb (urb);
1922 		}
1923 		spin_unlock_irq(&hcd_urb_list_lock);
1924 
1925 		if (urb) {
1926 			usb_kill_urb (urb);
1927 			usb_put_urb (urb);
1928 		}
1929 	}
1930 }
1931 
1932 /**
1933  * usb_hcd_alloc_bandwidth - check whether a new bandwidth setting exceeds
1934  *				the bus bandwidth
1935  * @udev: target &usb_device
1936  * @new_config: new configuration to install
1937  * @cur_alt: the current alternate interface setting
1938  * @new_alt: alternate interface setting that is being installed
1939  *
1940  * To change configurations, pass in the new configuration in new_config,
1941  * and pass NULL for cur_alt and new_alt.
1942  *
1943  * To reset a device's configuration (put the device in the ADDRESSED state),
1944  * pass in NULL for new_config, cur_alt, and new_alt.
1945  *
1946  * To change alternate interface settings, pass in NULL for new_config,
1947  * pass in the current alternate interface setting in cur_alt,
1948  * and pass in the new alternate interface setting in new_alt.
1949  *
1950  * Return: An error if the requested bandwidth change exceeds the
1951  * bus bandwidth or host controller internal resources.
1952  */
usb_hcd_alloc_bandwidth(struct usb_device * udev,struct usb_host_config * new_config,struct usb_host_interface * cur_alt,struct usb_host_interface * new_alt)1953 int usb_hcd_alloc_bandwidth(struct usb_device *udev,
1954 		struct usb_host_config *new_config,
1955 		struct usb_host_interface *cur_alt,
1956 		struct usb_host_interface *new_alt)
1957 {
1958 	int num_intfs, i, j;
1959 	struct usb_host_interface *alt = NULL;
1960 	int ret = 0;
1961 	struct usb_hcd *hcd;
1962 	struct usb_host_endpoint *ep;
1963 
1964 	hcd = bus_to_hcd(udev->bus);
1965 	if (!hcd->driver->check_bandwidth)
1966 		return 0;
1967 
1968 	/* Configuration is being removed - set configuration 0 */
1969 	if (!new_config && !cur_alt) {
1970 		for (i = 1; i < 16; ++i) {
1971 			ep = udev->ep_out[i];
1972 			if (ep)
1973 				hcd->driver->drop_endpoint(hcd, udev, ep);
1974 			ep = udev->ep_in[i];
1975 			if (ep)
1976 				hcd->driver->drop_endpoint(hcd, udev, ep);
1977 		}
1978 		hcd->driver->check_bandwidth(hcd, udev);
1979 		return 0;
1980 	}
1981 	/* Check if the HCD says there's enough bandwidth.  Enable all endpoints
1982 	 * each interface's alt setting 0 and ask the HCD to check the bandwidth
1983 	 * of the bus.  There will always be bandwidth for endpoint 0, so it's
1984 	 * ok to exclude it.
1985 	 */
1986 	if (new_config) {
1987 		num_intfs = new_config->desc.bNumInterfaces;
1988 		/* Remove endpoints (except endpoint 0, which is always on the
1989 		 * schedule) from the old config from the schedule
1990 		 */
1991 		for (i = 1; i < 16; ++i) {
1992 			ep = udev->ep_out[i];
1993 			if (ep) {
1994 				ret = hcd->driver->drop_endpoint(hcd, udev, ep);
1995 				if (ret < 0)
1996 					goto reset;
1997 			}
1998 			ep = udev->ep_in[i];
1999 			if (ep) {
2000 				ret = hcd->driver->drop_endpoint(hcd, udev, ep);
2001 				if (ret < 0)
2002 					goto reset;
2003 			}
2004 		}
2005 		for (i = 0; i < num_intfs; ++i) {
2006 			struct usb_host_interface *first_alt;
2007 			int iface_num;
2008 
2009 			first_alt = &new_config->intf_cache[i]->altsetting[0];
2010 			iface_num = first_alt->desc.bInterfaceNumber;
2011 			/* Set up endpoints for alternate interface setting 0 */
2012 			alt = usb_find_alt_setting(new_config, iface_num, 0);
2013 			if (!alt)
2014 				/* No alt setting 0? Pick the first setting. */
2015 				alt = first_alt;
2016 
2017 			for (j = 0; j < alt->desc.bNumEndpoints; j++) {
2018 				ret = hcd->driver->add_endpoint(hcd, udev, &alt->endpoint[j]);
2019 				if (ret < 0)
2020 					goto reset;
2021 			}
2022 		}
2023 	}
2024 	if (cur_alt && new_alt) {
2025 		struct usb_interface *iface = usb_ifnum_to_if(udev,
2026 				cur_alt->desc.bInterfaceNumber);
2027 
2028 		if (!iface)
2029 			return -EINVAL;
2030 		if (iface->resetting_device) {
2031 			/*
2032 			 * The USB core just reset the device, so the xHCI host
2033 			 * and the device will think alt setting 0 is installed.
2034 			 * However, the USB core will pass in the alternate
2035 			 * setting installed before the reset as cur_alt.  Dig
2036 			 * out the alternate setting 0 structure, or the first
2037 			 * alternate setting if a broken device doesn't have alt
2038 			 * setting 0.
2039 			 */
2040 			cur_alt = usb_altnum_to_altsetting(iface, 0);
2041 			if (!cur_alt)
2042 				cur_alt = &iface->altsetting[0];
2043 		}
2044 
2045 		/* Drop all the endpoints in the current alt setting */
2046 		for (i = 0; i < cur_alt->desc.bNumEndpoints; i++) {
2047 			ret = hcd->driver->drop_endpoint(hcd, udev,
2048 					&cur_alt->endpoint[i]);
2049 			if (ret < 0)
2050 				goto reset;
2051 		}
2052 		/* Add all the endpoints in the new alt setting */
2053 		for (i = 0; i < new_alt->desc.bNumEndpoints; i++) {
2054 			ret = hcd->driver->add_endpoint(hcd, udev,
2055 					&new_alt->endpoint[i]);
2056 			if (ret < 0)
2057 				goto reset;
2058 		}
2059 	}
2060 	ret = hcd->driver->check_bandwidth(hcd, udev);
2061 reset:
2062 	if (ret < 0)
2063 		hcd->driver->reset_bandwidth(hcd, udev);
2064 	return ret;
2065 }
2066 
2067 /* Disables the endpoint: synchronizes with the hcd to make sure all
2068  * endpoint state is gone from hardware.  usb_hcd_flush_endpoint() must
2069  * have been called previously.  Use for set_configuration, set_interface,
2070  * driver removal, physical disconnect.
2071  *
2072  * example:  a qh stored in ep->hcpriv, holding state related to endpoint
2073  * type, maxpacket size, toggle, halt status, and scheduling.
2074  */
usb_hcd_disable_endpoint(struct usb_device * udev,struct usb_host_endpoint * ep)2075 void usb_hcd_disable_endpoint(struct usb_device *udev,
2076 		struct usb_host_endpoint *ep)
2077 {
2078 	struct usb_hcd		*hcd;
2079 
2080 	might_sleep();
2081 	hcd = bus_to_hcd(udev->bus);
2082 	if (hcd->driver->endpoint_disable)
2083 		hcd->driver->endpoint_disable(hcd, ep);
2084 }
2085 
2086 /**
2087  * usb_hcd_reset_endpoint - reset host endpoint state
2088  * @udev: USB device.
2089  * @ep:   the endpoint to reset.
2090  *
2091  * Resets any host endpoint state such as the toggle bit, sequence
2092  * number and current window.
2093  */
usb_hcd_reset_endpoint(struct usb_device * udev,struct usb_host_endpoint * ep)2094 void usb_hcd_reset_endpoint(struct usb_device *udev,
2095 			    struct usb_host_endpoint *ep)
2096 {
2097 	struct usb_hcd *hcd = bus_to_hcd(udev->bus);
2098 
2099 	if (hcd->driver->endpoint_reset)
2100 		hcd->driver->endpoint_reset(hcd, ep);
2101 	else {
2102 		int epnum = usb_endpoint_num(&ep->desc);
2103 		int is_out = usb_endpoint_dir_out(&ep->desc);
2104 		int is_control = usb_endpoint_xfer_control(&ep->desc);
2105 
2106 		usb_settoggle(udev, epnum, is_out, 0);
2107 		if (is_control)
2108 			usb_settoggle(udev, epnum, !is_out, 0);
2109 	}
2110 }
2111 
2112 /**
2113  * usb_alloc_streams - allocate bulk endpoint stream IDs.
2114  * @interface:		alternate setting that includes all endpoints.
2115  * @eps:		array of endpoints that need streams.
2116  * @num_eps:		number of endpoints in the array.
2117  * @num_streams:	number of streams to allocate.
2118  * @mem_flags:		flags hcd should use to allocate memory.
2119  *
2120  * Sets up a group of bulk endpoints to have @num_streams stream IDs available.
2121  * Drivers may queue multiple transfers to different stream IDs, which may
2122  * complete in a different order than they were queued.
2123  *
2124  * Return: On success, the number of allocated streams. On failure, a negative
2125  * error code.
2126  */
usb_alloc_streams(struct usb_interface * interface,struct usb_host_endpoint ** eps,unsigned int num_eps,unsigned int num_streams,gfp_t mem_flags)2127 int usb_alloc_streams(struct usb_interface *interface,
2128 		struct usb_host_endpoint **eps, unsigned int num_eps,
2129 		unsigned int num_streams, gfp_t mem_flags)
2130 {
2131 	struct usb_hcd *hcd;
2132 	struct usb_device *dev;
2133 	int i, ret;
2134 
2135 	dev = interface_to_usbdev(interface);
2136 	hcd = bus_to_hcd(dev->bus);
2137 	if (!hcd->driver->alloc_streams || !hcd->driver->free_streams)
2138 		return -EINVAL;
2139 	if (dev->speed < USB_SPEED_SUPER)
2140 		return -EINVAL;
2141 	if (dev->state < USB_STATE_CONFIGURED)
2142 		return -ENODEV;
2143 
2144 	for (i = 0; i < num_eps; i++) {
2145 		/* Streams only apply to bulk endpoints. */
2146 		if (!usb_endpoint_xfer_bulk(&eps[i]->desc))
2147 			return -EINVAL;
2148 		/* Re-alloc is not allowed */
2149 		if (eps[i]->streams)
2150 			return -EINVAL;
2151 	}
2152 
2153 	ret = hcd->driver->alloc_streams(hcd, dev, eps, num_eps,
2154 			num_streams, mem_flags);
2155 	if (ret < 0)
2156 		return ret;
2157 
2158 	for (i = 0; i < num_eps; i++)
2159 		eps[i]->streams = ret;
2160 
2161 	return ret;
2162 }
2163 EXPORT_SYMBOL_GPL(usb_alloc_streams);
2164 
2165 /**
2166  * usb_free_streams - free bulk endpoint stream IDs.
2167  * @interface:	alternate setting that includes all endpoints.
2168  * @eps:	array of endpoints to remove streams from.
2169  * @num_eps:	number of endpoints in the array.
2170  * @mem_flags:	flags hcd should use to allocate memory.
2171  *
2172  * Reverts a group of bulk endpoints back to not using stream IDs.
2173  * Can fail if we are given bad arguments, or HCD is broken.
2174  *
2175  * Return: 0 on success. On failure, a negative error code.
2176  */
usb_free_streams(struct usb_interface * interface,struct usb_host_endpoint ** eps,unsigned int num_eps,gfp_t mem_flags)2177 int usb_free_streams(struct usb_interface *interface,
2178 		struct usb_host_endpoint **eps, unsigned int num_eps,
2179 		gfp_t mem_flags)
2180 {
2181 	struct usb_hcd *hcd;
2182 	struct usb_device *dev;
2183 	int i, ret;
2184 
2185 	dev = interface_to_usbdev(interface);
2186 	hcd = bus_to_hcd(dev->bus);
2187 	if (dev->speed < USB_SPEED_SUPER)
2188 		return -EINVAL;
2189 
2190 	/* Double-free is not allowed */
2191 	for (i = 0; i < num_eps; i++)
2192 		if (!eps[i] || !eps[i]->streams)
2193 			return -EINVAL;
2194 
2195 	ret = hcd->driver->free_streams(hcd, dev, eps, num_eps, mem_flags);
2196 	if (ret < 0)
2197 		return ret;
2198 
2199 	for (i = 0; i < num_eps; i++)
2200 		eps[i]->streams = 0;
2201 
2202 	return ret;
2203 }
2204 EXPORT_SYMBOL_GPL(usb_free_streams);
2205 
2206 /* Protect against drivers that try to unlink URBs after the device
2207  * is gone, by waiting until all unlinks for @udev are finished.
2208  * Since we don't currently track URBs by device, simply wait until
2209  * nothing is running in the locked region of usb_hcd_unlink_urb().
2210  */
usb_hcd_synchronize_unlinks(struct usb_device * udev)2211 void usb_hcd_synchronize_unlinks(struct usb_device *udev)
2212 {
2213 	spin_lock_irq(&hcd_urb_unlink_lock);
2214 	spin_unlock_irq(&hcd_urb_unlink_lock);
2215 }
2216 
2217 /*-------------------------------------------------------------------------*/
2218 
2219 /* called in any context */
usb_hcd_get_frame_number(struct usb_device * udev)2220 int usb_hcd_get_frame_number (struct usb_device *udev)
2221 {
2222 	struct usb_hcd	*hcd = bus_to_hcd(udev->bus);
2223 
2224 	if (!HCD_RH_RUNNING(hcd))
2225 		return -ESHUTDOWN;
2226 	return hcd->driver->get_frame_number (hcd);
2227 }
2228 
2229 /*-------------------------------------------------------------------------*/
2230 
2231 #ifdef	CONFIG_PM
2232 
hcd_bus_suspend(struct usb_device * rhdev,pm_message_t msg)2233 int hcd_bus_suspend(struct usb_device *rhdev, pm_message_t msg)
2234 {
2235 	struct usb_hcd	*hcd = container_of(rhdev->bus, struct usb_hcd, self);
2236 	int		status;
2237 	int		old_state = hcd->state;
2238 
2239 	dev_dbg(&rhdev->dev, "bus %ssuspend, wakeup %d\n",
2240 			(PMSG_IS_AUTO(msg) ? "auto-" : ""),
2241 			rhdev->do_remote_wakeup);
2242 	if (HCD_DEAD(hcd)) {
2243 		dev_dbg(&rhdev->dev, "skipped %s of dead bus\n", "suspend");
2244 		return 0;
2245 	}
2246 
2247 	if (!hcd->driver->bus_suspend) {
2248 		status = -ENOENT;
2249 	} else {
2250 		clear_bit(HCD_FLAG_RH_RUNNING, &hcd->flags);
2251 		hcd->state = HC_STATE_QUIESCING;
2252 		status = hcd->driver->bus_suspend(hcd);
2253 	}
2254 	if (status == 0) {
2255 		usb_set_device_state(rhdev, USB_STATE_SUSPENDED);
2256 		hcd->state = HC_STATE_SUSPENDED;
2257 
2258 		/* Did we race with a root-hub wakeup event? */
2259 		if (rhdev->do_remote_wakeup) {
2260 			char	buffer[6];
2261 
2262 			status = hcd->driver->hub_status_data(hcd, buffer);
2263 			if (status != 0) {
2264 				dev_dbg(&rhdev->dev, "suspend raced with wakeup event\n");
2265 				hcd_bus_resume(rhdev, PMSG_AUTO_RESUME);
2266 				status = -EBUSY;
2267 			}
2268 		}
2269 	} else {
2270 		spin_lock_irq(&hcd_root_hub_lock);
2271 		if (!HCD_DEAD(hcd)) {
2272 			set_bit(HCD_FLAG_RH_RUNNING, &hcd->flags);
2273 			hcd->state = old_state;
2274 		}
2275 		spin_unlock_irq(&hcd_root_hub_lock);
2276 		dev_dbg(&rhdev->dev, "bus %s fail, err %d\n",
2277 				"suspend", status);
2278 	}
2279 	return status;
2280 }
2281 
hcd_bus_resume(struct usb_device * rhdev,pm_message_t msg)2282 int hcd_bus_resume(struct usb_device *rhdev, pm_message_t msg)
2283 {
2284 	struct usb_hcd	*hcd = container_of(rhdev->bus, struct usb_hcd, self);
2285 	int		status;
2286 	int		old_state = hcd->state;
2287 
2288 	dev_dbg(&rhdev->dev, "usb %sresume\n",
2289 			(PMSG_IS_AUTO(msg) ? "auto-" : ""));
2290 	if (HCD_DEAD(hcd)) {
2291 		dev_dbg(&rhdev->dev, "skipped %s of dead bus\n", "resume");
2292 		return 0;
2293 	}
2294 	if (!hcd->driver->bus_resume)
2295 		return -ENOENT;
2296 	if (HCD_RH_RUNNING(hcd))
2297 		return 0;
2298 
2299 	hcd->state = HC_STATE_RESUMING;
2300 	status = hcd->driver->bus_resume(hcd);
2301 	clear_bit(HCD_FLAG_WAKEUP_PENDING, &hcd->flags);
2302 	if (status == 0) {
2303 		struct usb_device *udev;
2304 		int port1;
2305 
2306 		spin_lock_irq(&hcd_root_hub_lock);
2307 		if (!HCD_DEAD(hcd)) {
2308 			usb_set_device_state(rhdev, rhdev->actconfig
2309 					? USB_STATE_CONFIGURED
2310 					: USB_STATE_ADDRESS);
2311 			set_bit(HCD_FLAG_RH_RUNNING, &hcd->flags);
2312 			hcd->state = HC_STATE_RUNNING;
2313 		}
2314 		spin_unlock_irq(&hcd_root_hub_lock);
2315 
2316 		/*
2317 		 * Check whether any of the enabled ports on the root hub are
2318 		 * unsuspended.  If they are then a TRSMRCY delay is needed
2319 		 * (this is what the USB-2 spec calls a "global resume").
2320 		 * Otherwise we can skip the delay.
2321 		 */
2322 		usb_hub_for_each_child(rhdev, port1, udev) {
2323 			if (udev->state != USB_STATE_NOTATTACHED &&
2324 					!udev->port_is_suspended) {
2325 				usleep_range(10000, 11000);	/* TRSMRCY */
2326 				break;
2327 			}
2328 		}
2329 	} else {
2330 		hcd->state = old_state;
2331 		dev_dbg(&rhdev->dev, "bus %s fail, err %d\n",
2332 				"resume", status);
2333 		if (status != -ESHUTDOWN)
2334 			usb_hc_died(hcd);
2335 	}
2336 	return status;
2337 }
2338 
2339 /* Workqueue routine for root-hub remote wakeup */
hcd_resume_work(struct work_struct * work)2340 static void hcd_resume_work(struct work_struct *work)
2341 {
2342 	struct usb_hcd *hcd = container_of(work, struct usb_hcd, wakeup_work);
2343 	struct usb_device *udev = hcd->self.root_hub;
2344 
2345 	usb_remote_wakeup(udev);
2346 }
2347 
2348 /**
2349  * usb_hcd_resume_root_hub - called by HCD to resume its root hub
2350  * @hcd: host controller for this root hub
2351  *
2352  * The USB host controller calls this function when its root hub is
2353  * suspended (with the remote wakeup feature enabled) and a remote
2354  * wakeup request is received.  The routine submits a workqueue request
2355  * to resume the root hub (that is, manage its downstream ports again).
2356  */
usb_hcd_resume_root_hub(struct usb_hcd * hcd)2357 void usb_hcd_resume_root_hub (struct usb_hcd *hcd)
2358 {
2359 	unsigned long flags;
2360 
2361 	spin_lock_irqsave (&hcd_root_hub_lock, flags);
2362 	if (hcd->rh_registered) {
2363 		pm_wakeup_event(&hcd->self.root_hub->dev, 0);
2364 		set_bit(HCD_FLAG_WAKEUP_PENDING, &hcd->flags);
2365 		queue_work(pm_wq, &hcd->wakeup_work);
2366 	}
2367 	spin_unlock_irqrestore (&hcd_root_hub_lock, flags);
2368 }
2369 EXPORT_SYMBOL_GPL(usb_hcd_resume_root_hub);
2370 
2371 #endif	/* CONFIG_PM */
2372 
2373 /*-------------------------------------------------------------------------*/
2374 
2375 #ifdef	CONFIG_USB_OTG
2376 
2377 /**
2378  * usb_bus_start_enum - start immediate enumeration (for OTG)
2379  * @bus: the bus (must use hcd framework)
2380  * @port_num: 1-based number of port; usually bus->otg_port
2381  * Context: in_interrupt()
2382  *
2383  * Starts enumeration, with an immediate reset followed later by
2384  * hub_wq identifying and possibly configuring the device.
2385  * This is needed by OTG controller drivers, where it helps meet
2386  * HNP protocol timing requirements for starting a port reset.
2387  *
2388  * Return: 0 if successful.
2389  */
usb_bus_start_enum(struct usb_bus * bus,unsigned port_num)2390 int usb_bus_start_enum(struct usb_bus *bus, unsigned port_num)
2391 {
2392 	struct usb_hcd		*hcd;
2393 	int			status = -EOPNOTSUPP;
2394 
2395 	/* NOTE: since HNP can't start by grabbing the bus's address0_sem,
2396 	 * boards with root hubs hooked up to internal devices (instead of
2397 	 * just the OTG port) may need more attention to resetting...
2398 	 */
2399 	hcd = container_of (bus, struct usb_hcd, self);
2400 	if (port_num && hcd->driver->start_port_reset)
2401 		status = hcd->driver->start_port_reset(hcd, port_num);
2402 
2403 	/* allocate hub_wq shortly after (first) root port reset finishes;
2404 	 * it may issue others, until at least 50 msecs have passed.
2405 	 */
2406 	if (status == 0)
2407 		mod_timer(&hcd->rh_timer, jiffies + msecs_to_jiffies(10));
2408 	return status;
2409 }
2410 EXPORT_SYMBOL_GPL(usb_bus_start_enum);
2411 
2412 #endif
2413 
2414 /*-------------------------------------------------------------------------*/
2415 
2416 /**
2417  * usb_hcd_irq - hook IRQs to HCD framework (bus glue)
2418  * @irq: the IRQ being raised
2419  * @__hcd: pointer to the HCD whose IRQ is being signaled
2420  *
2421  * If the controller isn't HALTed, calls the driver's irq handler.
2422  * Checks whether the controller is now dead.
2423  *
2424  * Return: %IRQ_HANDLED if the IRQ was handled. %IRQ_NONE otherwise.
2425  */
usb_hcd_irq(int irq,void * __hcd)2426 irqreturn_t usb_hcd_irq (int irq, void *__hcd)
2427 {
2428 	struct usb_hcd		*hcd = __hcd;
2429 	irqreturn_t		rc;
2430 
2431 	if (unlikely(HCD_DEAD(hcd) || !HCD_HW_ACCESSIBLE(hcd)))
2432 		rc = IRQ_NONE;
2433 	else if (hcd->driver->irq(hcd) == IRQ_NONE)
2434 		rc = IRQ_NONE;
2435 	else
2436 		rc = IRQ_HANDLED;
2437 
2438 	return rc;
2439 }
2440 EXPORT_SYMBOL_GPL(usb_hcd_irq);
2441 
2442 /*-------------------------------------------------------------------------*/
2443 
2444 /**
2445  * usb_hc_died - report abnormal shutdown of a host controller (bus glue)
2446  * @hcd: pointer to the HCD representing the controller
2447  *
2448  * This is called by bus glue to report a USB host controller that died
2449  * while operations may still have been pending.  It's called automatically
2450  * by the PCI glue, so only glue for non-PCI busses should need to call it.
2451  *
2452  * Only call this function with the primary HCD.
2453  */
usb_hc_died(struct usb_hcd * hcd)2454 void usb_hc_died (struct usb_hcd *hcd)
2455 {
2456 	unsigned long flags;
2457 
2458 	dev_err (hcd->self.controller, "HC died; cleaning up\n");
2459 
2460 	spin_lock_irqsave (&hcd_root_hub_lock, flags);
2461 	clear_bit(HCD_FLAG_RH_RUNNING, &hcd->flags);
2462 	set_bit(HCD_FLAG_DEAD, &hcd->flags);
2463 	if (hcd->rh_registered) {
2464 		clear_bit(HCD_FLAG_POLL_RH, &hcd->flags);
2465 
2466 		/* make hub_wq clean up old urbs and devices */
2467 		usb_set_device_state (hcd->self.root_hub,
2468 				USB_STATE_NOTATTACHED);
2469 		usb_kick_hub_wq(hcd->self.root_hub);
2470 	}
2471 	if (usb_hcd_is_primary_hcd(hcd) && hcd->shared_hcd) {
2472 		hcd = hcd->shared_hcd;
2473 		clear_bit(HCD_FLAG_RH_RUNNING, &hcd->flags);
2474 		set_bit(HCD_FLAG_DEAD, &hcd->flags);
2475 		if (hcd->rh_registered) {
2476 			clear_bit(HCD_FLAG_POLL_RH, &hcd->flags);
2477 
2478 			/* make hub_wq clean up old urbs and devices */
2479 			usb_set_device_state(hcd->self.root_hub,
2480 					USB_STATE_NOTATTACHED);
2481 			usb_kick_hub_wq(hcd->self.root_hub);
2482 		}
2483 	}
2484 	spin_unlock_irqrestore (&hcd_root_hub_lock, flags);
2485 	/* Make sure that the other roothub is also deallocated. */
2486 }
2487 EXPORT_SYMBOL_GPL (usb_hc_died);
2488 
2489 /*-------------------------------------------------------------------------*/
2490 
init_giveback_urb_bh(struct giveback_urb_bh * bh)2491 static void init_giveback_urb_bh(struct giveback_urb_bh *bh)
2492 {
2493 
2494 	spin_lock_init(&bh->lock);
2495 	INIT_LIST_HEAD(&bh->head);
2496 	tasklet_init(&bh->bh, usb_giveback_urb_bh, (unsigned long)bh);
2497 }
2498 
2499 /**
2500  * usb_create_shared_hcd - create and initialize an HCD structure
2501  * @driver: HC driver that will use this hcd
2502  * @dev: device for this HC, stored in hcd->self.controller
2503  * @bus_name: value to store in hcd->self.bus_name
2504  * @primary_hcd: a pointer to the usb_hcd structure that is sharing the
2505  *              PCI device.  Only allocate certain resources for the primary HCD
2506  * Context: !in_interrupt()
2507  *
2508  * Allocate a struct usb_hcd, with extra space at the end for the
2509  * HC driver's private data.  Initialize the generic members of the
2510  * hcd structure.
2511  *
2512  * Return: On success, a pointer to the created and initialized HCD structure.
2513  * On failure (e.g. if memory is unavailable), %NULL.
2514  */
usb_create_shared_hcd(const struct hc_driver * driver,struct device * dev,const char * bus_name,struct usb_hcd * primary_hcd)2515 struct usb_hcd *usb_create_shared_hcd(const struct hc_driver *driver,
2516 		struct device *dev, const char *bus_name,
2517 		struct usb_hcd *primary_hcd)
2518 {
2519 	struct usb_hcd *hcd;
2520 
2521 	hcd = kzalloc(sizeof(*hcd) + driver->hcd_priv_size, GFP_KERNEL);
2522 	if (!hcd) {
2523 		dev_dbg (dev, "hcd alloc failed\n");
2524 		return NULL;
2525 	}
2526 	if (primary_hcd == NULL) {
2527 		hcd->address0_mutex = kmalloc(sizeof(*hcd->address0_mutex),
2528 				GFP_KERNEL);
2529 		if (!hcd->address0_mutex) {
2530 			kfree(hcd);
2531 			dev_dbg(dev, "hcd address0 mutex alloc failed\n");
2532 			return NULL;
2533 		}
2534 		mutex_init(hcd->address0_mutex);
2535 		hcd->bandwidth_mutex = kmalloc(sizeof(*hcd->bandwidth_mutex),
2536 				GFP_KERNEL);
2537 		if (!hcd->bandwidth_mutex) {
2538 			kfree(hcd->address0_mutex);
2539 			kfree(hcd);
2540 			dev_dbg(dev, "hcd bandwidth mutex alloc failed\n");
2541 			return NULL;
2542 		}
2543 		mutex_init(hcd->bandwidth_mutex);
2544 		dev_set_drvdata(dev, hcd);
2545 	} else {
2546 		mutex_lock(&usb_port_peer_mutex);
2547 		hcd->address0_mutex = primary_hcd->address0_mutex;
2548 		hcd->bandwidth_mutex = primary_hcd->bandwidth_mutex;
2549 		hcd->primary_hcd = primary_hcd;
2550 		primary_hcd->primary_hcd = primary_hcd;
2551 		hcd->shared_hcd = primary_hcd;
2552 		primary_hcd->shared_hcd = hcd;
2553 		mutex_unlock(&usb_port_peer_mutex);
2554 	}
2555 
2556 	kref_init(&hcd->kref);
2557 
2558 	usb_bus_init(&hcd->self);
2559 	hcd->self.controller = dev;
2560 	hcd->self.bus_name = bus_name;
2561 	hcd->self.uses_dma = (dev->dma_mask != NULL);
2562 
2563 	init_timer(&hcd->rh_timer);
2564 	hcd->rh_timer.function = rh_timer_func;
2565 	hcd->rh_timer.data = (unsigned long) hcd;
2566 #ifdef CONFIG_PM
2567 	INIT_WORK(&hcd->wakeup_work, hcd_resume_work);
2568 #endif
2569 
2570 	hcd->driver = driver;
2571 	hcd->speed = driver->flags & HCD_MASK;
2572 	hcd->product_desc = (driver->product_desc) ? driver->product_desc :
2573 			"USB Host Controller";
2574 	return hcd;
2575 }
2576 EXPORT_SYMBOL_GPL(usb_create_shared_hcd);
2577 
2578 /**
2579  * usb_create_hcd - create and initialize an HCD structure
2580  * @driver: HC driver that will use this hcd
2581  * @dev: device for this HC, stored in hcd->self.controller
2582  * @bus_name: value to store in hcd->self.bus_name
2583  * Context: !in_interrupt()
2584  *
2585  * Allocate a struct usb_hcd, with extra space at the end for the
2586  * HC driver's private data.  Initialize the generic members of the
2587  * hcd structure.
2588  *
2589  * Return: On success, a pointer to the created and initialized HCD
2590  * structure. On failure (e.g. if memory is unavailable), %NULL.
2591  */
usb_create_hcd(const struct hc_driver * driver,struct device * dev,const char * bus_name)2592 struct usb_hcd *usb_create_hcd(const struct hc_driver *driver,
2593 		struct device *dev, const char *bus_name)
2594 {
2595 	return usb_create_shared_hcd(driver, dev, bus_name, NULL);
2596 }
2597 EXPORT_SYMBOL_GPL(usb_create_hcd);
2598 
2599 /*
2600  * Roothubs that share one PCI device must also share the bandwidth mutex.
2601  * Don't deallocate the bandwidth_mutex until the last shared usb_hcd is
2602  * deallocated.
2603  *
2604  * Make sure to deallocate the bandwidth_mutex only when the last HCD is
2605  * freed.  When hcd_release() is called for either hcd in a peer set,
2606  * invalidate the peer's ->shared_hcd and ->primary_hcd pointers.
2607  */
hcd_release(struct kref * kref)2608 static void hcd_release(struct kref *kref)
2609 {
2610 	struct usb_hcd *hcd = container_of (kref, struct usb_hcd, kref);
2611 
2612 	mutex_lock(&usb_port_peer_mutex);
2613 	if (hcd->shared_hcd) {
2614 		struct usb_hcd *peer = hcd->shared_hcd;
2615 
2616 		peer->shared_hcd = NULL;
2617 		peer->primary_hcd = NULL;
2618 	} else {
2619 		kfree(hcd->address0_mutex);
2620 		kfree(hcd->bandwidth_mutex);
2621 	}
2622 	mutex_unlock(&usb_port_peer_mutex);
2623 	kfree(hcd);
2624 }
2625 
usb_get_hcd(struct usb_hcd * hcd)2626 struct usb_hcd *usb_get_hcd (struct usb_hcd *hcd)
2627 {
2628 	if (hcd)
2629 		kref_get (&hcd->kref);
2630 	return hcd;
2631 }
2632 EXPORT_SYMBOL_GPL(usb_get_hcd);
2633 
usb_put_hcd(struct usb_hcd * hcd)2634 void usb_put_hcd (struct usb_hcd *hcd)
2635 {
2636 	if (hcd)
2637 		kref_put (&hcd->kref, hcd_release);
2638 }
2639 EXPORT_SYMBOL_GPL(usb_put_hcd);
2640 
usb_hcd_is_primary_hcd(struct usb_hcd * hcd)2641 int usb_hcd_is_primary_hcd(struct usb_hcd *hcd)
2642 {
2643 	if (!hcd->primary_hcd)
2644 		return 1;
2645 	return hcd == hcd->primary_hcd;
2646 }
2647 EXPORT_SYMBOL_GPL(usb_hcd_is_primary_hcd);
2648 
usb_hcd_find_raw_port_number(struct usb_hcd * hcd,int port1)2649 int usb_hcd_find_raw_port_number(struct usb_hcd *hcd, int port1)
2650 {
2651 	if (!hcd->driver->find_raw_port_number)
2652 		return port1;
2653 
2654 	return hcd->driver->find_raw_port_number(hcd, port1);
2655 }
2656 
usb_hcd_request_irqs(struct usb_hcd * hcd,unsigned int irqnum,unsigned long irqflags)2657 static int usb_hcd_request_irqs(struct usb_hcd *hcd,
2658 		unsigned int irqnum, unsigned long irqflags)
2659 {
2660 	int retval;
2661 
2662 	if (hcd->driver->irq) {
2663 
2664 		snprintf(hcd->irq_descr, sizeof(hcd->irq_descr), "%s:usb%d",
2665 				hcd->driver->description, hcd->self.busnum);
2666 		retval = request_irq(irqnum, &usb_hcd_irq, irqflags,
2667 				hcd->irq_descr, hcd);
2668 		if (retval != 0) {
2669 			dev_err(hcd->self.controller,
2670 					"request interrupt %d failed\n",
2671 					irqnum);
2672 			return retval;
2673 		}
2674 		hcd->irq = irqnum;
2675 		dev_info(hcd->self.controller, "irq %d, %s 0x%08llx\n", irqnum,
2676 				(hcd->driver->flags & HCD_MEMORY) ?
2677 					"io mem" : "io base",
2678 					(unsigned long long)hcd->rsrc_start);
2679 	} else {
2680 		hcd->irq = 0;
2681 		if (hcd->rsrc_start)
2682 			dev_info(hcd->self.controller, "%s 0x%08llx\n",
2683 					(hcd->driver->flags & HCD_MEMORY) ?
2684 					"io mem" : "io base",
2685 					(unsigned long long)hcd->rsrc_start);
2686 	}
2687 	return 0;
2688 }
2689 
2690 /*
2691  * Before we free this root hub, flush in-flight peering attempts
2692  * and disable peer lookups
2693  */
usb_put_invalidate_rhdev(struct usb_hcd * hcd)2694 static void usb_put_invalidate_rhdev(struct usb_hcd *hcd)
2695 {
2696 	struct usb_device *rhdev;
2697 
2698 	mutex_lock(&usb_port_peer_mutex);
2699 	rhdev = hcd->self.root_hub;
2700 	hcd->self.root_hub = NULL;
2701 	mutex_unlock(&usb_port_peer_mutex);
2702 	usb_put_dev(rhdev);
2703 }
2704 
2705 /**
2706  * usb_add_hcd - finish generic HCD structure initialization and register
2707  * @hcd: the usb_hcd structure to initialize
2708  * @irqnum: Interrupt line to allocate
2709  * @irqflags: Interrupt type flags
2710  *
2711  * Finish the remaining parts of generic HCD initialization: allocate the
2712  * buffers of consistent memory, register the bus, request the IRQ line,
2713  * and call the driver's reset() and start() routines.
2714  */
usb_add_hcd(struct usb_hcd * hcd,unsigned int irqnum,unsigned long irqflags)2715 int usb_add_hcd(struct usb_hcd *hcd,
2716 		unsigned int irqnum, unsigned long irqflags)
2717 {
2718 	int retval;
2719 	struct usb_device *rhdev;
2720 
2721 	if (IS_ENABLED(CONFIG_USB_PHY) && !hcd->usb_phy) {
2722 		struct usb_phy *phy = usb_get_phy_dev(hcd->self.controller, 0);
2723 
2724 		if (IS_ERR(phy)) {
2725 			retval = PTR_ERR(phy);
2726 			if (retval == -EPROBE_DEFER)
2727 				return retval;
2728 		} else {
2729 			retval = usb_phy_init(phy);
2730 			if (retval) {
2731 				usb_put_phy(phy);
2732 				return retval;
2733 			}
2734 			hcd->usb_phy = phy;
2735 			hcd->remove_phy = 1;
2736 		}
2737 	}
2738 
2739 	if (IS_ENABLED(CONFIG_GENERIC_PHY) && !hcd->phy) {
2740 		struct phy *phy = phy_get(hcd->self.controller, "usb");
2741 
2742 		if (IS_ERR(phy)) {
2743 			retval = PTR_ERR(phy);
2744 			if (retval == -EPROBE_DEFER)
2745 				goto err_phy;
2746 		} else {
2747 			retval = phy_init(phy);
2748 			if (retval) {
2749 				phy_put(phy);
2750 				goto err_phy;
2751 			}
2752 			retval = phy_power_on(phy);
2753 			if (retval) {
2754 				phy_exit(phy);
2755 				phy_put(phy);
2756 				goto err_phy;
2757 			}
2758 			hcd->phy = phy;
2759 			hcd->remove_phy = 1;
2760 		}
2761 	}
2762 
2763 	dev_info(hcd->self.controller, "%s\n", hcd->product_desc);
2764 
2765 	/* Keep old behaviour if authorized_default is not in [0, 1]. */
2766 	if (authorized_default < 0 || authorized_default > 1) {
2767 		if (hcd->wireless)
2768 			clear_bit(HCD_FLAG_DEV_AUTHORIZED, &hcd->flags);
2769 		else
2770 			set_bit(HCD_FLAG_DEV_AUTHORIZED, &hcd->flags);
2771 	} else {
2772 		if (authorized_default)
2773 			set_bit(HCD_FLAG_DEV_AUTHORIZED, &hcd->flags);
2774 		else
2775 			clear_bit(HCD_FLAG_DEV_AUTHORIZED, &hcd->flags);
2776 	}
2777 	set_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
2778 
2779 	/* per default all interfaces are authorized */
2780 	set_bit(HCD_FLAG_INTF_AUTHORIZED, &hcd->flags);
2781 
2782 	/* HC is in reset state, but accessible.  Now do the one-time init,
2783 	 * bottom up so that hcds can customize the root hubs before hub_wq
2784 	 * starts talking to them.  (Note, bus id is assigned early too.)
2785 	 */
2786 	retval = hcd_buffer_create(hcd);
2787 	if (retval != 0) {
2788 		dev_dbg(hcd->self.controller, "pool alloc failed\n");
2789 		goto err_create_buf;
2790 	}
2791 
2792 	retval = usb_register_bus(&hcd->self);
2793 	if (retval < 0)
2794 		goto err_register_bus;
2795 
2796 	rhdev = usb_alloc_dev(NULL, &hcd->self, 0);
2797 	if (rhdev == NULL) {
2798 		dev_err(hcd->self.controller, "unable to allocate root hub\n");
2799 		retval = -ENOMEM;
2800 		goto err_allocate_root_hub;
2801 	}
2802 	mutex_lock(&usb_port_peer_mutex);
2803 	hcd->self.root_hub = rhdev;
2804 	mutex_unlock(&usb_port_peer_mutex);
2805 
2806 	switch (hcd->speed) {
2807 	case HCD_USB11:
2808 		rhdev->speed = USB_SPEED_FULL;
2809 		break;
2810 	case HCD_USB2:
2811 		rhdev->speed = USB_SPEED_HIGH;
2812 		break;
2813 	case HCD_USB25:
2814 		rhdev->speed = USB_SPEED_WIRELESS;
2815 		break;
2816 	case HCD_USB3:
2817 	case HCD_USB31:
2818 		rhdev->speed = USB_SPEED_SUPER;
2819 		break;
2820 	default:
2821 		retval = -EINVAL;
2822 		goto err_set_rh_speed;
2823 	}
2824 
2825 	/* wakeup flag init defaults to "everything works" for root hubs,
2826 	 * but drivers can override it in reset() if needed, along with
2827 	 * recording the overall controller's system wakeup capability.
2828 	 */
2829 	device_set_wakeup_capable(&rhdev->dev, 1);
2830 
2831 	/* HCD_FLAG_RH_RUNNING doesn't matter until the root hub is
2832 	 * registered.  But since the controller can die at any time,
2833 	 * let's initialize the flag before touching the hardware.
2834 	 */
2835 	set_bit(HCD_FLAG_RH_RUNNING, &hcd->flags);
2836 
2837 	/* "reset" is misnamed; its role is now one-time init. the controller
2838 	 * should already have been reset (and boot firmware kicked off etc).
2839 	 */
2840 	if (hcd->driver->reset) {
2841 		retval = hcd->driver->reset(hcd);
2842 		if (retval < 0) {
2843 			dev_err(hcd->self.controller, "can't setup: %d\n",
2844 					retval);
2845 			goto err_hcd_driver_setup;
2846 		}
2847 	}
2848 	hcd->rh_pollable = 1;
2849 
2850 	/* NOTE: root hub and controller capabilities may not be the same */
2851 	if (device_can_wakeup(hcd->self.controller)
2852 			&& device_can_wakeup(&hcd->self.root_hub->dev))
2853 		dev_dbg(hcd->self.controller, "supports USB remote wakeup\n");
2854 
2855 	/* initialize tasklets */
2856 	init_giveback_urb_bh(&hcd->high_prio_bh);
2857 	init_giveback_urb_bh(&hcd->low_prio_bh);
2858 
2859 	/* enable irqs just before we start the controller,
2860 	 * if the BIOS provides legacy PCI irqs.
2861 	 */
2862 	if (usb_hcd_is_primary_hcd(hcd) && irqnum) {
2863 		retval = usb_hcd_request_irqs(hcd, irqnum, irqflags);
2864 		if (retval)
2865 			goto err_request_irq;
2866 	}
2867 
2868 	hcd->state = HC_STATE_RUNNING;
2869 	retval = hcd->driver->start(hcd);
2870 	if (retval < 0) {
2871 		dev_err(hcd->self.controller, "startup error %d\n", retval);
2872 		goto err_hcd_driver_start;
2873 	}
2874 
2875 	/* starting here, usbcore will pay attention to this root hub */
2876 	retval = register_root_hub(hcd);
2877 	if (retval != 0)
2878 		goto err_register_root_hub;
2879 
2880 	retval = sysfs_create_group(&rhdev->dev.kobj, &usb_bus_attr_group);
2881 	if (retval < 0) {
2882 		printk(KERN_ERR "Cannot register USB bus sysfs attributes: %d\n",
2883 		       retval);
2884 		goto error_create_attr_group;
2885 	}
2886 	if (hcd->uses_new_polling && HCD_POLL_RH(hcd))
2887 		usb_hcd_poll_rh_status(hcd);
2888 
2889 	return retval;
2890 
2891 error_create_attr_group:
2892 	clear_bit(HCD_FLAG_RH_RUNNING, &hcd->flags);
2893 	if (HC_IS_RUNNING(hcd->state))
2894 		hcd->state = HC_STATE_QUIESCING;
2895 	spin_lock_irq(&hcd_root_hub_lock);
2896 	hcd->rh_registered = 0;
2897 	spin_unlock_irq(&hcd_root_hub_lock);
2898 
2899 #ifdef CONFIG_PM
2900 	cancel_work_sync(&hcd->wakeup_work);
2901 #endif
2902 	mutex_lock(&usb_bus_list_lock);
2903 	usb_disconnect(&rhdev);		/* Sets rhdev to NULL */
2904 	mutex_unlock(&usb_bus_list_lock);
2905 err_register_root_hub:
2906 	hcd->rh_pollable = 0;
2907 	clear_bit(HCD_FLAG_POLL_RH, &hcd->flags);
2908 	del_timer_sync(&hcd->rh_timer);
2909 	hcd->driver->stop(hcd);
2910 	hcd->state = HC_STATE_HALT;
2911 	clear_bit(HCD_FLAG_POLL_RH, &hcd->flags);
2912 	del_timer_sync(&hcd->rh_timer);
2913 err_hcd_driver_start:
2914 	if (usb_hcd_is_primary_hcd(hcd) && hcd->irq > 0)
2915 		free_irq(irqnum, hcd);
2916 err_request_irq:
2917 err_hcd_driver_setup:
2918 err_set_rh_speed:
2919 	usb_put_invalidate_rhdev(hcd);
2920 err_allocate_root_hub:
2921 	usb_deregister_bus(&hcd->self);
2922 err_register_bus:
2923 	hcd_buffer_destroy(hcd);
2924 err_create_buf:
2925 	if (IS_ENABLED(CONFIG_GENERIC_PHY) && hcd->remove_phy && hcd->phy) {
2926 		phy_power_off(hcd->phy);
2927 		phy_exit(hcd->phy);
2928 		phy_put(hcd->phy);
2929 		hcd->phy = NULL;
2930 	}
2931 err_phy:
2932 	if (hcd->remove_phy && hcd->usb_phy) {
2933 		usb_phy_shutdown(hcd->usb_phy);
2934 		usb_put_phy(hcd->usb_phy);
2935 		hcd->usb_phy = NULL;
2936 	}
2937 	return retval;
2938 }
2939 EXPORT_SYMBOL_GPL(usb_add_hcd);
2940 
2941 /**
2942  * usb_remove_hcd - shutdown processing for generic HCDs
2943  * @hcd: the usb_hcd structure to remove
2944  * Context: !in_interrupt()
2945  *
2946  * Disconnects the root hub, then reverses the effects of usb_add_hcd(),
2947  * invoking the HCD's stop() method.
2948  */
usb_remove_hcd(struct usb_hcd * hcd)2949 void usb_remove_hcd(struct usb_hcd *hcd)
2950 {
2951 	struct usb_device *rhdev = hcd->self.root_hub;
2952 
2953 	dev_info(hcd->self.controller, "remove, state %x\n", hcd->state);
2954 
2955 	usb_get_dev(rhdev);
2956 	sysfs_remove_group(&rhdev->dev.kobj, &usb_bus_attr_group);
2957 
2958 	clear_bit(HCD_FLAG_RH_RUNNING, &hcd->flags);
2959 	if (HC_IS_RUNNING (hcd->state))
2960 		hcd->state = HC_STATE_QUIESCING;
2961 
2962 	dev_dbg(hcd->self.controller, "roothub graceful disconnect\n");
2963 	spin_lock_irq (&hcd_root_hub_lock);
2964 	hcd->rh_registered = 0;
2965 	spin_unlock_irq (&hcd_root_hub_lock);
2966 
2967 #ifdef CONFIG_PM
2968 	cancel_work_sync(&hcd->wakeup_work);
2969 #endif
2970 
2971 	mutex_lock(&usb_bus_list_lock);
2972 	usb_disconnect(&rhdev);		/* Sets rhdev to NULL */
2973 	mutex_unlock(&usb_bus_list_lock);
2974 
2975 	/*
2976 	 * tasklet_kill() isn't needed here because:
2977 	 * - driver's disconnect() called from usb_disconnect() should
2978 	 *   make sure its URBs are completed during the disconnect()
2979 	 *   callback
2980 	 *
2981 	 * - it is too late to run complete() here since driver may have
2982 	 *   been removed already now
2983 	 */
2984 
2985 	/* Prevent any more root-hub status calls from the timer.
2986 	 * The HCD might still restart the timer (if a port status change
2987 	 * interrupt occurs), but usb_hcd_poll_rh_status() won't invoke
2988 	 * the hub_status_data() callback.
2989 	 */
2990 	hcd->rh_pollable = 0;
2991 	clear_bit(HCD_FLAG_POLL_RH, &hcd->flags);
2992 	del_timer_sync(&hcd->rh_timer);
2993 
2994 	hcd->driver->stop(hcd);
2995 	hcd->state = HC_STATE_HALT;
2996 
2997 	/* In case the HCD restarted the timer, stop it again. */
2998 	clear_bit(HCD_FLAG_POLL_RH, &hcd->flags);
2999 	del_timer_sync(&hcd->rh_timer);
3000 
3001 	if (usb_hcd_is_primary_hcd(hcd)) {
3002 		if (hcd->irq > 0)
3003 			free_irq(hcd->irq, hcd);
3004 	}
3005 
3006 	usb_deregister_bus(&hcd->self);
3007 	hcd_buffer_destroy(hcd);
3008 
3009 	if (IS_ENABLED(CONFIG_GENERIC_PHY) && hcd->remove_phy && hcd->phy) {
3010 		phy_power_off(hcd->phy);
3011 		phy_exit(hcd->phy);
3012 		phy_put(hcd->phy);
3013 		hcd->phy = NULL;
3014 	}
3015 	if (hcd->remove_phy && hcd->usb_phy) {
3016 		usb_phy_shutdown(hcd->usb_phy);
3017 		usb_put_phy(hcd->usb_phy);
3018 		hcd->usb_phy = NULL;
3019 	}
3020 
3021 	usb_put_invalidate_rhdev(hcd);
3022 	hcd->flags = 0;
3023 }
3024 EXPORT_SYMBOL_GPL(usb_remove_hcd);
3025 
3026 void
usb_hcd_platform_shutdown(struct platform_device * dev)3027 usb_hcd_platform_shutdown(struct platform_device *dev)
3028 {
3029 	struct usb_hcd *hcd = platform_get_drvdata(dev);
3030 
3031 	/* No need for pm_runtime_put(), we're shutting down */
3032 	pm_runtime_get_sync(&dev->dev);
3033 
3034 	if (hcd->driver->shutdown)
3035 		hcd->driver->shutdown(hcd);
3036 }
3037 EXPORT_SYMBOL_GPL(usb_hcd_platform_shutdown);
3038 
3039 /*-------------------------------------------------------------------------*/
3040 
3041 #if defined(CONFIG_USB_MON) || defined(CONFIG_USB_MON_MODULE)
3042 
3043 struct usb_mon_operations *mon_ops;
3044 
3045 /*
3046  * The registration is unlocked.
3047  * We do it this way because we do not want to lock in hot paths.
3048  *
3049  * Notice that the code is minimally error-proof. Because usbmon needs
3050  * symbols from usbcore, usbcore gets referenced and cannot be unloaded first.
3051  */
3052 
usb_mon_register(struct usb_mon_operations * ops)3053 int usb_mon_register (struct usb_mon_operations *ops)
3054 {
3055 
3056 	if (mon_ops)
3057 		return -EBUSY;
3058 
3059 	mon_ops = ops;
3060 	mb();
3061 	return 0;
3062 }
3063 EXPORT_SYMBOL_GPL (usb_mon_register);
3064 
usb_mon_deregister(void)3065 void usb_mon_deregister (void)
3066 {
3067 
3068 	if (mon_ops == NULL) {
3069 		printk(KERN_ERR "USB: monitor was not registered\n");
3070 		return;
3071 	}
3072 	mon_ops = NULL;
3073 	mb();
3074 }
3075 EXPORT_SYMBOL_GPL (usb_mon_deregister);
3076 
3077 #endif /* CONFIG_USB_MON || CONFIG_USB_MON_MODULE */
3078