1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * USB hub driver.
4 *
5 * (C) Copyright 1999 Linus Torvalds
6 * (C) Copyright 1999 Johannes Erdfelt
7 * (C) Copyright 1999 Gregory P. Smith
8 * (C) Copyright 2001 Brad Hards (bhards@bigpond.net.au)
9 *
10 * Released under the GPLv2 only.
11 */
12
13 #include <linux/kernel.h>
14 #include <linux/errno.h>
15 #include <linux/module.h>
16 #include <linux/moduleparam.h>
17 #include <linux/completion.h>
18 #include <linux/sched/mm.h>
19 #include <linux/list.h>
20 #include <linux/slab.h>
21 #include <linux/kcov.h>
22 #include <linux/ioctl.h>
23 #include <linux/usb.h>
24 #include <linux/usbdevice_fs.h>
25 #include <linux/usb/hcd.h>
26 #include <linux/usb/onboard_dev.h>
27 #include <linux/usb/otg.h>
28 #include <linux/usb/quirks.h>
29 #include <linux/workqueue.h>
30 #include <linux/mutex.h>
31 #include <linux/random.h>
32 #include <linux/pm_qos.h>
33 #include <linux/kobject.h>
34
35 #include <linux/bitfield.h>
36 #include <linux/uaccess.h>
37 #include <asm/byteorder.h>
38
39 #include "hub.h"
40 #include "phy.h"
41 #include "otg_productlist.h"
42
43 #define USB_VENDOR_GENESYS_LOGIC 0x05e3
44 #define USB_VENDOR_SMSC 0x0424
45 #define USB_PRODUCT_USB5534B 0x5534
46 #define USB_VENDOR_CYPRESS 0x04b4
47 #define USB_PRODUCT_CY7C65632 0x6570
48 #define USB_VENDOR_TEXAS_INSTRUMENTS 0x0451
49 #define USB_PRODUCT_TUSB8041_USB3 0x8140
50 #define USB_PRODUCT_TUSB8041_USB2 0x8142
51 #define USB_VENDOR_MICROCHIP 0x0424
52 #define USB_PRODUCT_USB4913 0x4913
53 #define USB_PRODUCT_USB4914 0x4914
54 #define USB_PRODUCT_USB4915 0x4915
55 #define HUB_QUIRK_CHECK_PORT_AUTOSUSPEND BIT(0)
56 #define HUB_QUIRK_DISABLE_AUTOSUSPEND BIT(1)
57 #define HUB_QUIRK_REDUCE_FRAME_INTR_BINTERVAL BIT(2)
58
59 #define USB_TP_TRANSMISSION_DELAY 40 /* ns */
60 #define USB_TP_TRANSMISSION_DELAY_MAX 65535 /* ns */
61 #define USB_PING_RESPONSE_TIME 400 /* ns */
62 #define USB_REDUCE_FRAME_INTR_BINTERVAL 9
63
64 /*
65 * The SET_ADDRESS request timeout will be 500 ms when
66 * USB_QUIRK_SHORT_SET_ADDRESS_REQ_TIMEOUT quirk flag is set.
67 */
68 #define USB_SHORT_SET_ADDRESS_REQ_TIMEOUT 500 /* ms */
69
70 /*
71 * Give SS hubs 200ms time after wake to train downstream links before
72 * assuming no port activity and allowing hub to runtime suspend back.
73 */
74 #define USB_SS_PORT_U0_WAKE_TIME 200 /* ms */
75
76 /* Protect struct usb_device->state and ->children members
77 * Note: Both are also protected by ->dev.sem, except that ->state can
78 * change to USB_STATE_NOTATTACHED even when the semaphore isn't held. */
79 static DEFINE_SPINLOCK(device_state_lock);
80
81 /* workqueue to process hub events */
82 static struct workqueue_struct *hub_wq;
83 static void hub_event(struct work_struct *work);
84
85 /* synchronize hub-port add/remove and peering operations */
86 DEFINE_MUTEX(usb_port_peer_mutex);
87
88 /* cycle leds on hubs that aren't blinking for attention */
89 static bool blinkenlights;
90 module_param(blinkenlights, bool, S_IRUGO);
91 MODULE_PARM_DESC(blinkenlights, "true to cycle leds on hubs");
92
93 /*
94 * Device SATA8000 FW1.0 from DATAST0R Technology Corp requires about
95 * 10 seconds to send reply for the initial 64-byte descriptor request.
96 */
97 /* define initial 64-byte descriptor request timeout in milliseconds */
98 static int initial_descriptor_timeout = USB_CTRL_GET_TIMEOUT;
99 module_param(initial_descriptor_timeout, int, S_IRUGO|S_IWUSR);
100 MODULE_PARM_DESC(initial_descriptor_timeout,
101 "initial 64-byte descriptor request timeout in milliseconds "
102 "(default 5000 - 5.0 seconds)");
103
104 /*
105 * As of 2.6.10 we introduce a new USB device initialization scheme which
106 * closely resembles the way Windows works. Hopefully it will be compatible
107 * with a wider range of devices than the old scheme. However some previously
108 * working devices may start giving rise to "device not accepting address"
109 * errors; if that happens the user can try the old scheme by adjusting the
110 * following module parameters.
111 *
112 * For maximum flexibility there are two boolean parameters to control the
113 * hub driver's behavior. On the first initialization attempt, if the
114 * "old_scheme_first" parameter is set then the old scheme will be used,
115 * otherwise the new scheme is used. If that fails and "use_both_schemes"
116 * is set, then the driver will make another attempt, using the other scheme.
117 */
118 static bool old_scheme_first;
119 module_param(old_scheme_first, bool, S_IRUGO | S_IWUSR);
120 MODULE_PARM_DESC(old_scheme_first,
121 "start with the old device initialization scheme");
122
123 static bool use_both_schemes = true;
124 module_param(use_both_schemes, bool, S_IRUGO | S_IWUSR);
125 MODULE_PARM_DESC(use_both_schemes,
126 "try the other device initialization scheme if the "
127 "first one fails");
128
129 /* Mutual exclusion for EHCI CF initialization. This interferes with
130 * port reset on some companion controllers.
131 */
132 DECLARE_RWSEM(ehci_cf_port_reset_rwsem);
133 EXPORT_SYMBOL_GPL(ehci_cf_port_reset_rwsem);
134
135 #define HUB_DEBOUNCE_TIMEOUT 2000
136 #define HUB_DEBOUNCE_STEP 25
137 #define HUB_DEBOUNCE_STABLE 100
138
139 static int usb_reset_and_verify_device(struct usb_device *udev);
140 static int hub_port_disable(struct usb_hub *hub, int port1, int set_state);
141 static bool hub_port_warm_reset_required(struct usb_hub *hub, int port1,
142 u16 portstatus);
143
portspeed(struct usb_hub * hub,int portstatus)144 static inline char *portspeed(struct usb_hub *hub, int portstatus)
145 {
146 if (hub_is_superspeedplus(hub->hdev))
147 return "10.0 Gb/s";
148 if (hub_is_superspeed(hub->hdev))
149 return "5.0 Gb/s";
150 if (portstatus & USB_PORT_STAT_HIGH_SPEED)
151 return "480 Mb/s";
152 else if (portstatus & USB_PORT_STAT_LOW_SPEED)
153 return "1.5 Mb/s";
154 else
155 return "12 Mb/s";
156 }
157
158 /* Note that hdev or one of its children must be locked! */
usb_hub_to_struct_hub(struct usb_device * hdev)159 struct usb_hub *usb_hub_to_struct_hub(struct usb_device *hdev)
160 {
161 if (!hdev || !hdev->actconfig || !hdev->maxchild)
162 return NULL;
163 return usb_get_intfdata(hdev->actconfig->interface[0]);
164 }
165
usb_device_supports_lpm(struct usb_device * udev)166 int usb_device_supports_lpm(struct usb_device *udev)
167 {
168 /* Some devices have trouble with LPM */
169 if (udev->quirks & USB_QUIRK_NO_LPM)
170 return 0;
171
172 /* Skip if the device BOS descriptor couldn't be read */
173 if (!udev->bos)
174 return 0;
175
176 /* USB 2.1 (and greater) devices indicate LPM support through
177 * their USB 2.0 Extended Capabilities BOS descriptor.
178 */
179 if (udev->speed == USB_SPEED_HIGH || udev->speed == USB_SPEED_FULL) {
180 if (udev->bos->ext_cap &&
181 (USB_LPM_SUPPORT &
182 le32_to_cpu(udev->bos->ext_cap->bmAttributes)))
183 return 1;
184 return 0;
185 }
186
187 /*
188 * According to the USB 3.0 spec, all USB 3.0 devices must support LPM.
189 * However, there are some that don't, and they set the U1/U2 exit
190 * latencies to zero.
191 */
192 if (!udev->bos->ss_cap) {
193 dev_info(&udev->dev, "No LPM exit latency info found, disabling LPM.\n");
194 return 0;
195 }
196
197 if (udev->bos->ss_cap->bU1devExitLat == 0 &&
198 udev->bos->ss_cap->bU2DevExitLat == 0) {
199 if (udev->parent)
200 dev_info(&udev->dev, "LPM exit latency is zeroed, disabling LPM.\n");
201 else
202 dev_info(&udev->dev, "We don't know the algorithms for LPM for this host, disabling LPM.\n");
203 return 0;
204 }
205
206 if (!udev->parent || udev->parent->lpm_capable)
207 return 1;
208 return 0;
209 }
210
211 /*
212 * Set the Maximum Exit Latency (MEL) for the host to wakup up the path from
213 * U1/U2, send a PING to the device and receive a PING_RESPONSE.
214 * See USB 3.1 section C.1.5.2
215 */
usb_set_lpm_mel(struct usb_device * udev,struct usb3_lpm_parameters * udev_lpm_params,unsigned int udev_exit_latency,struct usb_hub * hub,struct usb3_lpm_parameters * hub_lpm_params,unsigned int hub_exit_latency)216 static void usb_set_lpm_mel(struct usb_device *udev,
217 struct usb3_lpm_parameters *udev_lpm_params,
218 unsigned int udev_exit_latency,
219 struct usb_hub *hub,
220 struct usb3_lpm_parameters *hub_lpm_params,
221 unsigned int hub_exit_latency)
222 {
223 unsigned int total_mel;
224
225 /*
226 * tMEL1. time to transition path from host to device into U0.
227 * MEL for parent already contains the delay up to parent, so only add
228 * the exit latency for the last link (pick the slower exit latency),
229 * and the hub header decode latency. See USB 3.1 section C 2.2.1
230 * Store MEL in nanoseconds
231 */
232 total_mel = hub_lpm_params->mel +
233 max(udev_exit_latency, hub_exit_latency) * 1000 +
234 hub->descriptor->u.ss.bHubHdrDecLat * 100;
235
236 /*
237 * tMEL2. Time to submit PING packet. Sum of tTPTransmissionDelay for
238 * each link + wHubDelay for each hub. Add only for last link.
239 * tMEL4, the time for PING_RESPONSE to traverse upstream is similar.
240 * Multiply by 2 to include it as well.
241 */
242 total_mel += (__le16_to_cpu(hub->descriptor->u.ss.wHubDelay) +
243 USB_TP_TRANSMISSION_DELAY) * 2;
244
245 /*
246 * tMEL3, tPingResponse. Time taken by device to generate PING_RESPONSE
247 * after receiving PING. Also add 2100ns as stated in USB 3.1 C 1.5.2.4
248 * to cover the delay if the PING_RESPONSE is queued behind a Max Packet
249 * Size DP.
250 * Note these delays should be added only once for the entire path, so
251 * add them to the MEL of the device connected to the roothub.
252 */
253 if (!hub->hdev->parent)
254 total_mel += USB_PING_RESPONSE_TIME + 2100;
255
256 udev_lpm_params->mel = total_mel;
257 }
258
259 /*
260 * Set the maximum Device to Host Exit Latency (PEL) for the device to initiate
261 * a transition from either U1 or U2.
262 */
usb_set_lpm_pel(struct usb_device * udev,struct usb3_lpm_parameters * udev_lpm_params,unsigned int udev_exit_latency,struct usb_hub * hub,struct usb3_lpm_parameters * hub_lpm_params,unsigned int hub_exit_latency,unsigned int port_to_port_exit_latency)263 static void usb_set_lpm_pel(struct usb_device *udev,
264 struct usb3_lpm_parameters *udev_lpm_params,
265 unsigned int udev_exit_latency,
266 struct usb_hub *hub,
267 struct usb3_lpm_parameters *hub_lpm_params,
268 unsigned int hub_exit_latency,
269 unsigned int port_to_port_exit_latency)
270 {
271 unsigned int first_link_pel;
272 unsigned int hub_pel;
273
274 /*
275 * First, the device sends an LFPS to transition the link between the
276 * device and the parent hub into U0. The exit latency is the bigger of
277 * the device exit latency or the hub exit latency.
278 */
279 if (udev_exit_latency > hub_exit_latency)
280 first_link_pel = udev_exit_latency * 1000;
281 else
282 first_link_pel = hub_exit_latency * 1000;
283
284 /*
285 * When the hub starts to receive the LFPS, there is a slight delay for
286 * it to figure out that one of the ports is sending an LFPS. Then it
287 * will forward the LFPS to its upstream link. The exit latency is the
288 * delay, plus the PEL that we calculated for this hub.
289 */
290 hub_pel = port_to_port_exit_latency * 1000 + hub_lpm_params->pel;
291
292 /*
293 * According to figure C-7 in the USB 3.0 spec, the PEL for this device
294 * is the greater of the two exit latencies.
295 */
296 if (first_link_pel > hub_pel)
297 udev_lpm_params->pel = first_link_pel;
298 else
299 udev_lpm_params->pel = hub_pel;
300 }
301
302 /*
303 * Set the System Exit Latency (SEL) to indicate the total worst-case time from
304 * when a device initiates a transition to U0, until when it will receive the
305 * first packet from the host controller.
306 *
307 * Section C.1.5.1 describes the four components to this:
308 * - t1: device PEL
309 * - t2: time for the ERDY to make it from the device to the host.
310 * - t3: a host-specific delay to process the ERDY.
311 * - t4: time for the packet to make it from the host to the device.
312 *
313 * t3 is specific to both the xHCI host and the platform the host is integrated
314 * into. The Intel HW folks have said it's negligible, FIXME if a different
315 * vendor says otherwise.
316 */
usb_set_lpm_sel(struct usb_device * udev,struct usb3_lpm_parameters * udev_lpm_params)317 static void usb_set_lpm_sel(struct usb_device *udev,
318 struct usb3_lpm_parameters *udev_lpm_params)
319 {
320 struct usb_device *parent;
321 unsigned int num_hubs;
322 unsigned int total_sel;
323
324 /* t1 = device PEL */
325 total_sel = udev_lpm_params->pel;
326 /* How many external hubs are in between the device & the root port. */
327 for (parent = udev->parent, num_hubs = 0; parent->parent;
328 parent = parent->parent)
329 num_hubs++;
330 /* t2 = 2.1us + 250ns * (num_hubs - 1) */
331 if (num_hubs > 0)
332 total_sel += 2100 + 250 * (num_hubs - 1);
333
334 /* t4 = 250ns * num_hubs */
335 total_sel += 250 * num_hubs;
336
337 udev_lpm_params->sel = total_sel;
338 }
339
usb_set_lpm_parameters(struct usb_device * udev)340 static void usb_set_lpm_parameters(struct usb_device *udev)
341 {
342 struct usb_hub *hub;
343 unsigned int port_to_port_delay;
344 unsigned int udev_u1_del;
345 unsigned int udev_u2_del;
346 unsigned int hub_u1_del;
347 unsigned int hub_u2_del;
348
349 if (!udev->lpm_capable || udev->speed < USB_SPEED_SUPER)
350 return;
351
352 /* Skip if the device BOS descriptor couldn't be read */
353 if (!udev->bos)
354 return;
355
356 hub = usb_hub_to_struct_hub(udev->parent);
357 /* It doesn't take time to transition the roothub into U0, since it
358 * doesn't have an upstream link.
359 */
360 if (!hub)
361 return;
362
363 udev_u1_del = udev->bos->ss_cap->bU1devExitLat;
364 udev_u2_del = le16_to_cpu(udev->bos->ss_cap->bU2DevExitLat);
365 hub_u1_del = udev->parent->bos->ss_cap->bU1devExitLat;
366 hub_u2_del = le16_to_cpu(udev->parent->bos->ss_cap->bU2DevExitLat);
367
368 usb_set_lpm_mel(udev, &udev->u1_params, udev_u1_del,
369 hub, &udev->parent->u1_params, hub_u1_del);
370
371 usb_set_lpm_mel(udev, &udev->u2_params, udev_u2_del,
372 hub, &udev->parent->u2_params, hub_u2_del);
373
374 /*
375 * Appendix C, section C.2.2.2, says that there is a slight delay from
376 * when the parent hub notices the downstream port is trying to
377 * transition to U0 to when the hub initiates a U0 transition on its
378 * upstream port. The section says the delays are tPort2PortU1EL and
379 * tPort2PortU2EL, but it doesn't define what they are.
380 *
381 * The hub chapter, sections 10.4.2.4 and 10.4.2.5 seem to be talking
382 * about the same delays. Use the maximum delay calculations from those
383 * sections. For U1, it's tHubPort2PortExitLat, which is 1us max. For
384 * U2, it's tHubPort2PortExitLat + U2DevExitLat - U1DevExitLat. I
385 * assume the device exit latencies they are talking about are the hub
386 * exit latencies.
387 *
388 * What do we do if the U2 exit latency is less than the U1 exit
389 * latency? It's possible, although not likely...
390 */
391 port_to_port_delay = 1;
392
393 usb_set_lpm_pel(udev, &udev->u1_params, udev_u1_del,
394 hub, &udev->parent->u1_params, hub_u1_del,
395 port_to_port_delay);
396
397 if (hub_u2_del > hub_u1_del)
398 port_to_port_delay = 1 + hub_u2_del - hub_u1_del;
399 else
400 port_to_port_delay = 1 + hub_u1_del;
401
402 usb_set_lpm_pel(udev, &udev->u2_params, udev_u2_del,
403 hub, &udev->parent->u2_params, hub_u2_del,
404 port_to_port_delay);
405
406 /* Now that we've got PEL, calculate SEL. */
407 usb_set_lpm_sel(udev, &udev->u1_params);
408 usb_set_lpm_sel(udev, &udev->u2_params);
409 }
410
411 /* USB 2.0 spec Section 11.24.4.5 */
get_hub_descriptor(struct usb_device * hdev,struct usb_hub_descriptor * desc)412 static int get_hub_descriptor(struct usb_device *hdev,
413 struct usb_hub_descriptor *desc)
414 {
415 int i, ret, size;
416 unsigned dtype;
417
418 if (hub_is_superspeed(hdev)) {
419 dtype = USB_DT_SS_HUB;
420 size = USB_DT_SS_HUB_SIZE;
421 } else {
422 dtype = USB_DT_HUB;
423 size = sizeof(struct usb_hub_descriptor);
424 }
425
426 for (i = 0; i < 3; i++) {
427 ret = usb_control_msg(hdev, usb_rcvctrlpipe(hdev, 0),
428 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN | USB_RT_HUB,
429 dtype << 8, 0, desc, size,
430 USB_CTRL_GET_TIMEOUT);
431 if (hub_is_superspeed(hdev)) {
432 if (ret == size)
433 return ret;
434 } else if (ret >= USB_DT_HUB_NONVAR_SIZE + 2) {
435 /* Make sure we have the DeviceRemovable field. */
436 size = USB_DT_HUB_NONVAR_SIZE + desc->bNbrPorts / 8 + 1;
437 if (ret < size)
438 return -EMSGSIZE;
439 return ret;
440 }
441 }
442 return -EINVAL;
443 }
444
445 /*
446 * USB 2.0 spec Section 11.24.2.1
447 */
clear_hub_feature(struct usb_device * hdev,int feature)448 static int clear_hub_feature(struct usb_device *hdev, int feature)
449 {
450 return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
451 USB_REQ_CLEAR_FEATURE, USB_RT_HUB, feature, 0, NULL, 0, 1000);
452 }
453
454 /*
455 * USB 2.0 spec Section 11.24.2.2
456 */
usb_clear_port_feature(struct usb_device * hdev,int port1,int feature)457 int usb_clear_port_feature(struct usb_device *hdev, int port1, int feature)
458 {
459 return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
460 USB_REQ_CLEAR_FEATURE, USB_RT_PORT, feature, port1,
461 NULL, 0, 1000);
462 }
463
464 /*
465 * USB 2.0 spec Section 11.24.2.13
466 */
set_port_feature(struct usb_device * hdev,int port1,int feature)467 static int set_port_feature(struct usb_device *hdev, int port1, int feature)
468 {
469 return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
470 USB_REQ_SET_FEATURE, USB_RT_PORT, feature, port1,
471 NULL, 0, 1000);
472 }
473
to_led_name(int selector)474 static char *to_led_name(int selector)
475 {
476 switch (selector) {
477 case HUB_LED_AMBER:
478 return "amber";
479 case HUB_LED_GREEN:
480 return "green";
481 case HUB_LED_OFF:
482 return "off";
483 case HUB_LED_AUTO:
484 return "auto";
485 default:
486 return "??";
487 }
488 }
489
490 /*
491 * USB 2.0 spec Section 11.24.2.7.1.10 and table 11-7
492 * for info about using port indicators
493 */
set_port_led(struct usb_hub * hub,int port1,int selector)494 static void set_port_led(struct usb_hub *hub, int port1, int selector)
495 {
496 struct usb_port *port_dev = hub->ports[port1 - 1];
497 int status;
498
499 status = set_port_feature(hub->hdev, (selector << 8) | port1,
500 USB_PORT_FEAT_INDICATOR);
501 dev_dbg(&port_dev->dev, "indicator %s status %d\n",
502 to_led_name(selector), status);
503 }
504
505 #define LED_CYCLE_PERIOD ((2*HZ)/3)
506
led_work(struct work_struct * work)507 static void led_work(struct work_struct *work)
508 {
509 struct usb_hub *hub =
510 container_of(work, struct usb_hub, leds.work);
511 struct usb_device *hdev = hub->hdev;
512 unsigned i;
513 unsigned changed = 0;
514 int cursor = -1;
515
516 if (hdev->state != USB_STATE_CONFIGURED || hub->quiescing)
517 return;
518
519 for (i = 0; i < hdev->maxchild; i++) {
520 unsigned selector, mode;
521
522 /* 30%-50% duty cycle */
523
524 switch (hub->indicator[i]) {
525 /* cycle marker */
526 case INDICATOR_CYCLE:
527 cursor = i;
528 selector = HUB_LED_AUTO;
529 mode = INDICATOR_AUTO;
530 break;
531 /* blinking green = sw attention */
532 case INDICATOR_GREEN_BLINK:
533 selector = HUB_LED_GREEN;
534 mode = INDICATOR_GREEN_BLINK_OFF;
535 break;
536 case INDICATOR_GREEN_BLINK_OFF:
537 selector = HUB_LED_OFF;
538 mode = INDICATOR_GREEN_BLINK;
539 break;
540 /* blinking amber = hw attention */
541 case INDICATOR_AMBER_BLINK:
542 selector = HUB_LED_AMBER;
543 mode = INDICATOR_AMBER_BLINK_OFF;
544 break;
545 case INDICATOR_AMBER_BLINK_OFF:
546 selector = HUB_LED_OFF;
547 mode = INDICATOR_AMBER_BLINK;
548 break;
549 /* blink green/amber = reserved */
550 case INDICATOR_ALT_BLINK:
551 selector = HUB_LED_GREEN;
552 mode = INDICATOR_ALT_BLINK_OFF;
553 break;
554 case INDICATOR_ALT_BLINK_OFF:
555 selector = HUB_LED_AMBER;
556 mode = INDICATOR_ALT_BLINK;
557 break;
558 default:
559 continue;
560 }
561 if (selector != HUB_LED_AUTO)
562 changed = 1;
563 set_port_led(hub, i + 1, selector);
564 hub->indicator[i] = mode;
565 }
566 if (!changed && blinkenlights) {
567 cursor++;
568 cursor %= hdev->maxchild;
569 set_port_led(hub, cursor + 1, HUB_LED_GREEN);
570 hub->indicator[cursor] = INDICATOR_CYCLE;
571 changed++;
572 }
573 if (changed)
574 queue_delayed_work(system_power_efficient_wq,
575 &hub->leds, LED_CYCLE_PERIOD);
576 }
577
578 /* use a short timeout for hub/port status fetches */
579 #define USB_STS_TIMEOUT 1000
580 #define USB_STS_RETRIES 5
581
582 /*
583 * USB 2.0 spec Section 11.24.2.6
584 */
get_hub_status(struct usb_device * hdev,struct usb_hub_status * data)585 static int get_hub_status(struct usb_device *hdev,
586 struct usb_hub_status *data)
587 {
588 int i, status = -ETIMEDOUT;
589
590 for (i = 0; i < USB_STS_RETRIES &&
591 (status == -ETIMEDOUT || status == -EPIPE); i++) {
592 status = usb_control_msg(hdev, usb_rcvctrlpipe(hdev, 0),
593 USB_REQ_GET_STATUS, USB_DIR_IN | USB_RT_HUB, 0, 0,
594 data, sizeof(*data), USB_STS_TIMEOUT);
595 }
596 return status;
597 }
598
599 /*
600 * USB 2.0 spec Section 11.24.2.7
601 * USB 3.1 takes into use the wValue and wLength fields, spec Section 10.16.2.6
602 */
get_port_status(struct usb_device * hdev,int port1,void * data,u16 value,u16 length)603 static int get_port_status(struct usb_device *hdev, int port1,
604 void *data, u16 value, u16 length)
605 {
606 int i, status = -ETIMEDOUT;
607
608 for (i = 0; i < USB_STS_RETRIES &&
609 (status == -ETIMEDOUT || status == -EPIPE); i++) {
610 status = usb_control_msg(hdev, usb_rcvctrlpipe(hdev, 0),
611 USB_REQ_GET_STATUS, USB_DIR_IN | USB_RT_PORT, value,
612 port1, data, length, USB_STS_TIMEOUT);
613 }
614 return status;
615 }
616
hub_ext_port_status(struct usb_hub * hub,int port1,int type,u16 * status,u16 * change,u32 * ext_status)617 static int hub_ext_port_status(struct usb_hub *hub, int port1, int type,
618 u16 *status, u16 *change, u32 *ext_status)
619 {
620 int ret;
621 int len = 4;
622
623 if (type != HUB_PORT_STATUS)
624 len = 8;
625
626 mutex_lock(&hub->status_mutex);
627 ret = get_port_status(hub->hdev, port1, &hub->status->port, type, len);
628 if (ret < len) {
629 if (ret != -ENODEV)
630 dev_err(hub->intfdev,
631 "%s failed (err = %d)\n", __func__, ret);
632 if (ret >= 0)
633 ret = -EIO;
634 } else {
635 *status = le16_to_cpu(hub->status->port.wPortStatus);
636 *change = le16_to_cpu(hub->status->port.wPortChange);
637 if (type != HUB_PORT_STATUS && ext_status)
638 *ext_status = le32_to_cpu(
639 hub->status->port.dwExtPortStatus);
640 ret = 0;
641 }
642 mutex_unlock(&hub->status_mutex);
643
644 /*
645 * There is no need to lock status_mutex here, because status_mutex
646 * protects hub->status, and the phy driver only checks the port
647 * status without changing the status.
648 */
649 if (!ret) {
650 struct usb_device *hdev = hub->hdev;
651
652 /*
653 * Only roothub will be notified of connection changes,
654 * since the USB PHY only cares about changes at the next
655 * level.
656 */
657 if (is_root_hub(hdev)) {
658 struct usb_hcd *hcd = bus_to_hcd(hdev->bus);
659 bool connect;
660 bool connect_change;
661
662 connect_change = *change & USB_PORT_STAT_C_CONNECTION;
663 connect = *status & USB_PORT_STAT_CONNECTION;
664 if (connect_change && connect)
665 usb_phy_roothub_notify_connect(hcd->phy_roothub, port1 - 1);
666 else if (connect_change)
667 usb_phy_roothub_notify_disconnect(hcd->phy_roothub, port1 - 1);
668 }
669 }
670
671 return ret;
672 }
673
usb_hub_port_status(struct usb_hub * hub,int port1,u16 * status,u16 * change)674 int usb_hub_port_status(struct usb_hub *hub, int port1,
675 u16 *status, u16 *change)
676 {
677 return hub_ext_port_status(hub, port1, HUB_PORT_STATUS,
678 status, change, NULL);
679 }
680
hub_resubmit_irq_urb(struct usb_hub * hub)681 static void hub_resubmit_irq_urb(struct usb_hub *hub)
682 {
683 unsigned long flags;
684 int status;
685
686 spin_lock_irqsave(&hub->irq_urb_lock, flags);
687
688 if (hub->quiescing) {
689 spin_unlock_irqrestore(&hub->irq_urb_lock, flags);
690 return;
691 }
692
693 status = usb_submit_urb(hub->urb, GFP_ATOMIC);
694 if (status && status != -ENODEV && status != -EPERM &&
695 status != -ESHUTDOWN) {
696 dev_err(hub->intfdev, "resubmit --> %d\n", status);
697 mod_timer(&hub->irq_urb_retry, jiffies + HZ);
698 }
699
700 spin_unlock_irqrestore(&hub->irq_urb_lock, flags);
701 }
702
hub_retry_irq_urb(struct timer_list * t)703 static void hub_retry_irq_urb(struct timer_list *t)
704 {
705 struct usb_hub *hub = from_timer(hub, t, irq_urb_retry);
706
707 hub_resubmit_irq_urb(hub);
708 }
709
710
kick_hub_wq(struct usb_hub * hub)711 static void kick_hub_wq(struct usb_hub *hub)
712 {
713 struct usb_interface *intf;
714
715 if (hub->disconnected || work_pending(&hub->events))
716 return;
717
718 /*
719 * Suppress autosuspend until the event is proceed.
720 *
721 * Be careful and make sure that the symmetric operation is
722 * always called. We are here only when there is no pending
723 * work for this hub. Therefore put the interface either when
724 * the new work is called or when it is canceled.
725 */
726 intf = to_usb_interface(hub->intfdev);
727 usb_autopm_get_interface_no_resume(intf);
728 hub_get(hub);
729
730 if (queue_work(hub_wq, &hub->events))
731 return;
732
733 /* the work has already been scheduled */
734 usb_autopm_put_interface_async(intf);
735 hub_put(hub);
736 }
737
usb_kick_hub_wq(struct usb_device * hdev)738 void usb_kick_hub_wq(struct usb_device *hdev)
739 {
740 struct usb_hub *hub = usb_hub_to_struct_hub(hdev);
741
742 if (hub)
743 kick_hub_wq(hub);
744 }
745
746 /*
747 * Let the USB core know that a USB 3.0 device has sent a Function Wake Device
748 * Notification, which indicates it had initiated remote wakeup.
749 *
750 * USB 3.0 hubs do not report the port link state change from U3 to U0 when the
751 * device initiates resume, so the USB core will not receive notice of the
752 * resume through the normal hub interrupt URB.
753 */
usb_wakeup_notification(struct usb_device * hdev,unsigned int portnum)754 void usb_wakeup_notification(struct usb_device *hdev,
755 unsigned int portnum)
756 {
757 struct usb_hub *hub;
758 struct usb_port *port_dev;
759
760 if (!hdev)
761 return;
762
763 hub = usb_hub_to_struct_hub(hdev);
764 if (hub) {
765 port_dev = hub->ports[portnum - 1];
766 if (port_dev && port_dev->child)
767 pm_wakeup_event(&port_dev->child->dev, 0);
768
769 set_bit(portnum, hub->wakeup_bits);
770 kick_hub_wq(hub);
771 }
772 }
773 EXPORT_SYMBOL_GPL(usb_wakeup_notification);
774
775 /* completion function, fires on port status changes and various faults */
hub_irq(struct urb * urb)776 static void hub_irq(struct urb *urb)
777 {
778 struct usb_hub *hub = urb->context;
779 int status = urb->status;
780 unsigned i;
781 unsigned long bits;
782
783 switch (status) {
784 case -ENOENT: /* synchronous unlink */
785 case -ECONNRESET: /* async unlink */
786 case -ESHUTDOWN: /* hardware going away */
787 return;
788
789 default: /* presumably an error */
790 /* Cause a hub reset after 10 consecutive errors */
791 dev_dbg(hub->intfdev, "transfer --> %d\n", status);
792 if ((++hub->nerrors < 10) || hub->error)
793 goto resubmit;
794 hub->error = status;
795 fallthrough;
796
797 /* let hub_wq handle things */
798 case 0: /* we got data: port status changed */
799 bits = 0;
800 for (i = 0; i < urb->actual_length; ++i)
801 bits |= ((unsigned long) ((*hub->buffer)[i]))
802 << (i*8);
803 hub->event_bits[0] = bits;
804 break;
805 }
806
807 hub->nerrors = 0;
808
809 /* Something happened, let hub_wq figure it out */
810 kick_hub_wq(hub);
811
812 resubmit:
813 hub_resubmit_irq_urb(hub);
814 }
815
816 /* USB 2.0 spec Section 11.24.2.3 */
817 static inline int
hub_clear_tt_buffer(struct usb_device * hdev,u16 devinfo,u16 tt)818 hub_clear_tt_buffer(struct usb_device *hdev, u16 devinfo, u16 tt)
819 {
820 /* Need to clear both directions for control ep */
821 if (((devinfo >> 11) & USB_ENDPOINT_XFERTYPE_MASK) ==
822 USB_ENDPOINT_XFER_CONTROL) {
823 int status = usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
824 HUB_CLEAR_TT_BUFFER, USB_RT_PORT,
825 devinfo ^ 0x8000, tt, NULL, 0, 1000);
826 if (status)
827 return status;
828 }
829 return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
830 HUB_CLEAR_TT_BUFFER, USB_RT_PORT, devinfo,
831 tt, NULL, 0, 1000);
832 }
833
834 /*
835 * enumeration blocks hub_wq for a long time. we use keventd instead, since
836 * long blocking there is the exception, not the rule. accordingly, HCDs
837 * talking to TTs must queue control transfers (not just bulk and iso), so
838 * both can talk to the same hub concurrently.
839 */
hub_tt_work(struct work_struct * work)840 static void hub_tt_work(struct work_struct *work)
841 {
842 struct usb_hub *hub =
843 container_of(work, struct usb_hub, tt.clear_work);
844 unsigned long flags;
845
846 spin_lock_irqsave(&hub->tt.lock, flags);
847 while (!list_empty(&hub->tt.clear_list)) {
848 struct list_head *next;
849 struct usb_tt_clear *clear;
850 struct usb_device *hdev = hub->hdev;
851 const struct hc_driver *drv;
852 int status;
853
854 next = hub->tt.clear_list.next;
855 clear = list_entry(next, struct usb_tt_clear, clear_list);
856 list_del(&clear->clear_list);
857
858 /* drop lock so HCD can concurrently report other TT errors */
859 spin_unlock_irqrestore(&hub->tt.lock, flags);
860 status = hub_clear_tt_buffer(hdev, clear->devinfo, clear->tt);
861 if (status && status != -ENODEV)
862 dev_err(&hdev->dev,
863 "clear tt %d (%04x) error %d\n",
864 clear->tt, clear->devinfo, status);
865
866 /* Tell the HCD, even if the operation failed */
867 drv = clear->hcd->driver;
868 if (drv->clear_tt_buffer_complete)
869 (drv->clear_tt_buffer_complete)(clear->hcd, clear->ep);
870
871 kfree(clear);
872 spin_lock_irqsave(&hub->tt.lock, flags);
873 }
874 spin_unlock_irqrestore(&hub->tt.lock, flags);
875 }
876
877 /**
878 * usb_hub_set_port_power - control hub port's power state
879 * @hdev: USB device belonging to the usb hub
880 * @hub: target hub
881 * @port1: port index
882 * @set: expected status
883 *
884 * call this function to control port's power via setting or
885 * clearing the port's PORT_POWER feature.
886 *
887 * Return: 0 if successful. A negative error code otherwise.
888 */
usb_hub_set_port_power(struct usb_device * hdev,struct usb_hub * hub,int port1,bool set)889 int usb_hub_set_port_power(struct usb_device *hdev, struct usb_hub *hub,
890 int port1, bool set)
891 {
892 int ret;
893
894 if (set)
895 ret = set_port_feature(hdev, port1, USB_PORT_FEAT_POWER);
896 else
897 ret = usb_clear_port_feature(hdev, port1, USB_PORT_FEAT_POWER);
898
899 if (ret)
900 return ret;
901
902 if (set)
903 set_bit(port1, hub->power_bits);
904 else
905 clear_bit(port1, hub->power_bits);
906 return 0;
907 }
908
909 /**
910 * usb_hub_clear_tt_buffer - clear control/bulk TT state in high speed hub
911 * @urb: an URB associated with the failed or incomplete split transaction
912 *
913 * High speed HCDs use this to tell the hub driver that some split control or
914 * bulk transaction failed in a way that requires clearing internal state of
915 * a transaction translator. This is normally detected (and reported) from
916 * interrupt context.
917 *
918 * It may not be possible for that hub to handle additional full (or low)
919 * speed transactions until that state is fully cleared out.
920 *
921 * Return: 0 if successful. A negative error code otherwise.
922 */
usb_hub_clear_tt_buffer(struct urb * urb)923 int usb_hub_clear_tt_buffer(struct urb *urb)
924 {
925 struct usb_device *udev = urb->dev;
926 int pipe = urb->pipe;
927 struct usb_tt *tt = udev->tt;
928 unsigned long flags;
929 struct usb_tt_clear *clear;
930
931 /* we've got to cope with an arbitrary number of pending TT clears,
932 * since each TT has "at least two" buffers that can need it (and
933 * there can be many TTs per hub). even if they're uncommon.
934 */
935 clear = kmalloc(sizeof *clear, GFP_ATOMIC);
936 if (clear == NULL) {
937 dev_err(&udev->dev, "can't save CLEAR_TT_BUFFER state\n");
938 /* FIXME recover somehow ... RESET_TT? */
939 return -ENOMEM;
940 }
941
942 /* info that CLEAR_TT_BUFFER needs */
943 clear->tt = tt->multi ? udev->ttport : 1;
944 clear->devinfo = usb_pipeendpoint (pipe);
945 clear->devinfo |= ((u16)udev->devaddr) << 4;
946 clear->devinfo |= usb_pipecontrol(pipe)
947 ? (USB_ENDPOINT_XFER_CONTROL << 11)
948 : (USB_ENDPOINT_XFER_BULK << 11);
949 if (usb_pipein(pipe))
950 clear->devinfo |= 1 << 15;
951
952 /* info for completion callback */
953 clear->hcd = bus_to_hcd(udev->bus);
954 clear->ep = urb->ep;
955
956 /* tell keventd to clear state for this TT */
957 spin_lock_irqsave(&tt->lock, flags);
958 list_add_tail(&clear->clear_list, &tt->clear_list);
959 schedule_work(&tt->clear_work);
960 spin_unlock_irqrestore(&tt->lock, flags);
961 return 0;
962 }
963 EXPORT_SYMBOL_GPL(usb_hub_clear_tt_buffer);
964
hub_power_on(struct usb_hub * hub,bool do_delay)965 static void hub_power_on(struct usb_hub *hub, bool do_delay)
966 {
967 int port1;
968
969 /* Enable power on each port. Some hubs have reserved values
970 * of LPSM (> 2) in their descriptors, even though they are
971 * USB 2.0 hubs. Some hubs do not implement port-power switching
972 * but only emulate it. In all cases, the ports won't work
973 * unless we send these messages to the hub.
974 */
975 if (hub_is_port_power_switchable(hub))
976 dev_dbg(hub->intfdev, "enabling power on all ports\n");
977 else
978 dev_dbg(hub->intfdev, "trying to enable port power on "
979 "non-switchable hub\n");
980 for (port1 = 1; port1 <= hub->hdev->maxchild; port1++)
981 if (test_bit(port1, hub->power_bits))
982 set_port_feature(hub->hdev, port1, USB_PORT_FEAT_POWER);
983 else
984 usb_clear_port_feature(hub->hdev, port1,
985 USB_PORT_FEAT_POWER);
986 if (do_delay)
987 msleep(hub_power_on_good_delay(hub));
988 }
989
hub_hub_status(struct usb_hub * hub,u16 * status,u16 * change)990 static int hub_hub_status(struct usb_hub *hub,
991 u16 *status, u16 *change)
992 {
993 int ret;
994
995 mutex_lock(&hub->status_mutex);
996 ret = get_hub_status(hub->hdev, &hub->status->hub);
997 if (ret < 0) {
998 if (ret != -ENODEV)
999 dev_err(hub->intfdev,
1000 "%s failed (err = %d)\n", __func__, ret);
1001 } else {
1002 *status = le16_to_cpu(hub->status->hub.wHubStatus);
1003 *change = le16_to_cpu(hub->status->hub.wHubChange);
1004 ret = 0;
1005 }
1006 mutex_unlock(&hub->status_mutex);
1007 return ret;
1008 }
1009
hub_set_port_link_state(struct usb_hub * hub,int port1,unsigned int link_status)1010 static int hub_set_port_link_state(struct usb_hub *hub, int port1,
1011 unsigned int link_status)
1012 {
1013 return set_port_feature(hub->hdev,
1014 port1 | (link_status << 3),
1015 USB_PORT_FEAT_LINK_STATE);
1016 }
1017
1018 /*
1019 * Disable a port and mark a logical connect-change event, so that some
1020 * time later hub_wq will disconnect() any existing usb_device on the port
1021 * and will re-enumerate if there actually is a device attached.
1022 */
hub_port_logical_disconnect(struct usb_hub * hub,int port1)1023 static void hub_port_logical_disconnect(struct usb_hub *hub, int port1)
1024 {
1025 dev_dbg(&hub->ports[port1 - 1]->dev, "logical disconnect\n");
1026 hub_port_disable(hub, port1, 1);
1027
1028 /* FIXME let caller ask to power down the port:
1029 * - some devices won't enumerate without a VBUS power cycle
1030 * - SRP saves power that way
1031 * - ... new call, TBD ...
1032 * That's easy if this hub can switch power per-port, and
1033 * hub_wq reactivates the port later (timer, SRP, etc).
1034 * Powerdown must be optional, because of reset/DFU.
1035 */
1036
1037 set_bit(port1, hub->change_bits);
1038 kick_hub_wq(hub);
1039 }
1040
1041 /**
1042 * usb_remove_device - disable a device's port on its parent hub
1043 * @udev: device to be disabled and removed
1044 * Context: @udev locked, must be able to sleep.
1045 *
1046 * After @udev's port has been disabled, hub_wq is notified and it will
1047 * see that the device has been disconnected. When the device is
1048 * physically unplugged and something is plugged in, the events will
1049 * be received and processed normally.
1050 *
1051 * Return: 0 if successful. A negative error code otherwise.
1052 */
usb_remove_device(struct usb_device * udev)1053 int usb_remove_device(struct usb_device *udev)
1054 {
1055 struct usb_hub *hub;
1056 struct usb_interface *intf;
1057 int ret;
1058
1059 if (!udev->parent) /* Can't remove a root hub */
1060 return -EINVAL;
1061 hub = usb_hub_to_struct_hub(udev->parent);
1062 intf = to_usb_interface(hub->intfdev);
1063
1064 ret = usb_autopm_get_interface(intf);
1065 if (ret < 0)
1066 return ret;
1067
1068 set_bit(udev->portnum, hub->removed_bits);
1069 hub_port_logical_disconnect(hub, udev->portnum);
1070 usb_autopm_put_interface(intf);
1071 return 0;
1072 }
1073
1074 enum hub_activation_type {
1075 HUB_INIT, HUB_INIT2, HUB_INIT3, /* INITs must come first */
1076 HUB_POST_RESET, HUB_RESUME, HUB_RESET_RESUME,
1077 };
1078
1079 static void hub_init_func2(struct work_struct *ws);
1080 static void hub_init_func3(struct work_struct *ws);
1081
hub_activate(struct usb_hub * hub,enum hub_activation_type type)1082 static void hub_activate(struct usb_hub *hub, enum hub_activation_type type)
1083 {
1084 struct usb_device *hdev = hub->hdev;
1085 struct usb_hcd *hcd;
1086 int ret;
1087 int port1;
1088 int status;
1089 bool need_debounce_delay = false;
1090 unsigned delay;
1091
1092 /* Continue a partial initialization */
1093 if (type == HUB_INIT2 || type == HUB_INIT3) {
1094 device_lock(&hdev->dev);
1095
1096 /* Was the hub disconnected while we were waiting? */
1097 if (hub->disconnected)
1098 goto disconnected;
1099 if (type == HUB_INIT2)
1100 goto init2;
1101 goto init3;
1102 }
1103
1104 hub_get(hub);
1105
1106 /* The superspeed hub except for root hub has to use Hub Depth
1107 * value as an offset into the route string to locate the bits
1108 * it uses to determine the downstream port number. So hub driver
1109 * should send a set hub depth request to superspeed hub after
1110 * the superspeed hub is set configuration in initialization or
1111 * reset procedure.
1112 *
1113 * After a resume, port power should still be on.
1114 * For any other type of activation, turn it on.
1115 */
1116 if (type != HUB_RESUME) {
1117 if (hdev->parent && hub_is_superspeed(hdev)) {
1118 ret = usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
1119 HUB_SET_DEPTH, USB_RT_HUB,
1120 hdev->level - 1, 0, NULL, 0,
1121 USB_CTRL_SET_TIMEOUT);
1122 if (ret < 0)
1123 dev_err(hub->intfdev,
1124 "set hub depth failed\n");
1125 }
1126
1127 /* Speed up system boot by using a delayed_work for the
1128 * hub's initial power-up delays. This is pretty awkward
1129 * and the implementation looks like a home-brewed sort of
1130 * setjmp/longjmp, but it saves at least 100 ms for each
1131 * root hub (assuming usbcore is compiled into the kernel
1132 * rather than as a module). It adds up.
1133 *
1134 * This can't be done for HUB_RESUME or HUB_RESET_RESUME
1135 * because for those activation types the ports have to be
1136 * operational when we return. In theory this could be done
1137 * for HUB_POST_RESET, but it's easier not to.
1138 */
1139 if (type == HUB_INIT) {
1140 delay = hub_power_on_good_delay(hub);
1141
1142 hub_power_on(hub, false);
1143 INIT_DELAYED_WORK(&hub->init_work, hub_init_func2);
1144 queue_delayed_work(system_power_efficient_wq,
1145 &hub->init_work,
1146 msecs_to_jiffies(delay));
1147
1148 /* Suppress autosuspend until init is done */
1149 usb_autopm_get_interface_no_resume(
1150 to_usb_interface(hub->intfdev));
1151 return; /* Continues at init2: below */
1152 } else if (type == HUB_RESET_RESUME) {
1153 /* The internal host controller state for the hub device
1154 * may be gone after a host power loss on system resume.
1155 * Update the device's info so the HW knows it's a hub.
1156 */
1157 hcd = bus_to_hcd(hdev->bus);
1158 if (hcd->driver->update_hub_device) {
1159 ret = hcd->driver->update_hub_device(hcd, hdev,
1160 &hub->tt, GFP_NOIO);
1161 if (ret < 0) {
1162 dev_err(hub->intfdev,
1163 "Host not accepting hub info update\n");
1164 dev_err(hub->intfdev,
1165 "LS/FS devices and hubs may not work under this hub\n");
1166 }
1167 }
1168 hub_power_on(hub, true);
1169 } else {
1170 hub_power_on(hub, true);
1171 }
1172 /* Give some time on remote wakeup to let links to transit to U0 */
1173 } else if (hub_is_superspeed(hub->hdev))
1174 msleep(20);
1175
1176 init2:
1177
1178 /*
1179 * Check each port and set hub->change_bits to let hub_wq know
1180 * which ports need attention.
1181 */
1182 for (port1 = 1; port1 <= hdev->maxchild; ++port1) {
1183 struct usb_port *port_dev = hub->ports[port1 - 1];
1184 struct usb_device *udev = port_dev->child;
1185 u16 portstatus, portchange;
1186
1187 portstatus = portchange = 0;
1188 status = usb_hub_port_status(hub, port1, &portstatus, &portchange);
1189 if (status)
1190 goto abort;
1191
1192 if (udev || (portstatus & USB_PORT_STAT_CONNECTION))
1193 dev_dbg(&port_dev->dev, "status %04x change %04x\n",
1194 portstatus, portchange);
1195
1196 /*
1197 * After anything other than HUB_RESUME (i.e., initialization
1198 * or any sort of reset), every port should be disabled.
1199 * Unconnected ports should likewise be disabled (paranoia),
1200 * and so should ports for which we have no usb_device.
1201 */
1202 if ((portstatus & USB_PORT_STAT_ENABLE) && (
1203 type != HUB_RESUME ||
1204 !(portstatus & USB_PORT_STAT_CONNECTION) ||
1205 !udev ||
1206 udev->state == USB_STATE_NOTATTACHED)) {
1207 /*
1208 * USB3 protocol ports will automatically transition
1209 * to Enabled state when detect an USB3.0 device attach.
1210 * Do not disable USB3 protocol ports, just pretend
1211 * power was lost
1212 */
1213 portstatus &= ~USB_PORT_STAT_ENABLE;
1214 if (!hub_is_superspeed(hdev))
1215 usb_clear_port_feature(hdev, port1,
1216 USB_PORT_FEAT_ENABLE);
1217 }
1218
1219 /* Make sure a warm-reset request is handled by port_event */
1220 if (type == HUB_RESUME &&
1221 hub_port_warm_reset_required(hub, port1, portstatus))
1222 set_bit(port1, hub->event_bits);
1223
1224 /*
1225 * Add debounce if USB3 link is in polling/link training state.
1226 * Link will automatically transition to Enabled state after
1227 * link training completes.
1228 */
1229 if (hub_is_superspeed(hdev) &&
1230 ((portstatus & USB_PORT_STAT_LINK_STATE) ==
1231 USB_SS_PORT_LS_POLLING))
1232 need_debounce_delay = true;
1233
1234 /* Clear status-change flags; we'll debounce later */
1235 if (portchange & USB_PORT_STAT_C_CONNECTION) {
1236 need_debounce_delay = true;
1237 usb_clear_port_feature(hub->hdev, port1,
1238 USB_PORT_FEAT_C_CONNECTION);
1239 }
1240 if (portchange & USB_PORT_STAT_C_ENABLE) {
1241 need_debounce_delay = true;
1242 usb_clear_port_feature(hub->hdev, port1,
1243 USB_PORT_FEAT_C_ENABLE);
1244 }
1245 if (portchange & USB_PORT_STAT_C_RESET) {
1246 need_debounce_delay = true;
1247 usb_clear_port_feature(hub->hdev, port1,
1248 USB_PORT_FEAT_C_RESET);
1249 }
1250 if ((portchange & USB_PORT_STAT_C_BH_RESET) &&
1251 hub_is_superspeed(hub->hdev)) {
1252 need_debounce_delay = true;
1253 usb_clear_port_feature(hub->hdev, port1,
1254 USB_PORT_FEAT_C_BH_PORT_RESET);
1255 }
1256 /* We can forget about a "removed" device when there's a
1257 * physical disconnect or the connect status changes.
1258 */
1259 if (!(portstatus & USB_PORT_STAT_CONNECTION) ||
1260 (portchange & USB_PORT_STAT_C_CONNECTION))
1261 clear_bit(port1, hub->removed_bits);
1262
1263 if (!udev || udev->state == USB_STATE_NOTATTACHED) {
1264 /* Tell hub_wq to disconnect the device or
1265 * check for a new connection or over current condition.
1266 * Based on USB2.0 Spec Section 11.12.5,
1267 * C_PORT_OVER_CURRENT could be set while
1268 * PORT_OVER_CURRENT is not. So check for any of them.
1269 */
1270 if (udev || (portstatus & USB_PORT_STAT_CONNECTION) ||
1271 (portchange & USB_PORT_STAT_C_CONNECTION) ||
1272 (portstatus & USB_PORT_STAT_OVERCURRENT) ||
1273 (portchange & USB_PORT_STAT_C_OVERCURRENT))
1274 set_bit(port1, hub->change_bits);
1275
1276 } else if (portstatus & USB_PORT_STAT_ENABLE) {
1277 bool port_resumed = (portstatus &
1278 USB_PORT_STAT_LINK_STATE) ==
1279 USB_SS_PORT_LS_U0;
1280 /* The power session apparently survived the resume.
1281 * If there was an overcurrent or suspend change
1282 * (i.e., remote wakeup request), have hub_wq
1283 * take care of it. Look at the port link state
1284 * for USB 3.0 hubs, since they don't have a suspend
1285 * change bit, and they don't set the port link change
1286 * bit on device-initiated resume.
1287 */
1288 if (portchange || (hub_is_superspeed(hub->hdev) &&
1289 port_resumed))
1290 set_bit(port1, hub->event_bits);
1291
1292 } else if (udev->persist_enabled) {
1293 #ifdef CONFIG_PM
1294 udev->reset_resume = 1;
1295 #endif
1296 /* Don't set the change_bits when the device
1297 * was powered off.
1298 */
1299 if (test_bit(port1, hub->power_bits))
1300 set_bit(port1, hub->change_bits);
1301
1302 } else {
1303 /* The power session is gone; tell hub_wq */
1304 usb_set_device_state(udev, USB_STATE_NOTATTACHED);
1305 set_bit(port1, hub->change_bits);
1306 }
1307 }
1308
1309 /* If no port-status-change flags were set, we don't need any
1310 * debouncing. If flags were set we can try to debounce the
1311 * ports all at once right now, instead of letting hub_wq do them
1312 * one at a time later on.
1313 *
1314 * If any port-status changes do occur during this delay, hub_wq
1315 * will see them later and handle them normally.
1316 */
1317 if (need_debounce_delay) {
1318 delay = HUB_DEBOUNCE_STABLE;
1319
1320 /* Don't do a long sleep inside a workqueue routine */
1321 if (type == HUB_INIT2) {
1322 INIT_DELAYED_WORK(&hub->init_work, hub_init_func3);
1323 queue_delayed_work(system_power_efficient_wq,
1324 &hub->init_work,
1325 msecs_to_jiffies(delay));
1326 device_unlock(&hdev->dev);
1327 return; /* Continues at init3: below */
1328 } else {
1329 msleep(delay);
1330 }
1331 }
1332 init3:
1333 hub->quiescing = 0;
1334
1335 status = usb_submit_urb(hub->urb, GFP_NOIO);
1336 if (status < 0)
1337 dev_err(hub->intfdev, "activate --> %d\n", status);
1338 if (hub->has_indicators && blinkenlights)
1339 queue_delayed_work(system_power_efficient_wq,
1340 &hub->leds, LED_CYCLE_PERIOD);
1341
1342 /* Scan all ports that need attention */
1343 kick_hub_wq(hub);
1344 abort:
1345 if (type == HUB_INIT2 || type == HUB_INIT3) {
1346 /* Allow autosuspend if it was suppressed */
1347 disconnected:
1348 usb_autopm_put_interface_async(to_usb_interface(hub->intfdev));
1349 device_unlock(&hdev->dev);
1350 }
1351
1352 if (type == HUB_RESUME && hub_is_superspeed(hub->hdev)) {
1353 /* give usb3 downstream links training time after hub resume */
1354 usb_autopm_get_interface_no_resume(
1355 to_usb_interface(hub->intfdev));
1356
1357 queue_delayed_work(system_power_efficient_wq,
1358 &hub->post_resume_work,
1359 msecs_to_jiffies(USB_SS_PORT_U0_WAKE_TIME));
1360 return;
1361 }
1362
1363 hub_put(hub);
1364 }
1365
1366 /* Implement the continuations for the delays above */
hub_init_func2(struct work_struct * ws)1367 static void hub_init_func2(struct work_struct *ws)
1368 {
1369 struct usb_hub *hub = container_of(ws, struct usb_hub, init_work.work);
1370
1371 hub_activate(hub, HUB_INIT2);
1372 }
1373
hub_init_func3(struct work_struct * ws)1374 static void hub_init_func3(struct work_struct *ws)
1375 {
1376 struct usb_hub *hub = container_of(ws, struct usb_hub, init_work.work);
1377
1378 hub_activate(hub, HUB_INIT3);
1379 }
1380
hub_post_resume(struct work_struct * ws)1381 static void hub_post_resume(struct work_struct *ws)
1382 {
1383 struct usb_hub *hub = container_of(ws, struct usb_hub, post_resume_work.work);
1384
1385 usb_autopm_put_interface_async(to_usb_interface(hub->intfdev));
1386 hub_put(hub);
1387 }
1388
1389 enum hub_quiescing_type {
1390 HUB_DISCONNECT, HUB_PRE_RESET, HUB_SUSPEND
1391 };
1392
hub_quiesce(struct usb_hub * hub,enum hub_quiescing_type type)1393 static void hub_quiesce(struct usb_hub *hub, enum hub_quiescing_type type)
1394 {
1395 struct usb_device *hdev = hub->hdev;
1396 unsigned long flags;
1397 int i;
1398
1399 /* hub_wq and related activity won't re-trigger */
1400 spin_lock_irqsave(&hub->irq_urb_lock, flags);
1401 hub->quiescing = 1;
1402 spin_unlock_irqrestore(&hub->irq_urb_lock, flags);
1403
1404 if (type != HUB_SUSPEND) {
1405 /* Disconnect all the children */
1406 for (i = 0; i < hdev->maxchild; ++i) {
1407 if (hub->ports[i]->child)
1408 usb_disconnect(&hub->ports[i]->child);
1409 }
1410 }
1411
1412 /* Stop hub_wq and related activity */
1413 del_timer_sync(&hub->irq_urb_retry);
1414 flush_delayed_work(&hub->post_resume_work);
1415 usb_kill_urb(hub->urb);
1416 if (hub->has_indicators)
1417 cancel_delayed_work_sync(&hub->leds);
1418 if (hub->tt.hub)
1419 flush_work(&hub->tt.clear_work);
1420 }
1421
hub_pm_barrier_for_all_ports(struct usb_hub * hub)1422 static void hub_pm_barrier_for_all_ports(struct usb_hub *hub)
1423 {
1424 int i;
1425
1426 for (i = 0; i < hub->hdev->maxchild; ++i)
1427 pm_runtime_barrier(&hub->ports[i]->dev);
1428 }
1429
1430 /* caller has locked the hub device */
hub_pre_reset(struct usb_interface * intf)1431 static int hub_pre_reset(struct usb_interface *intf)
1432 {
1433 struct usb_hub *hub = usb_get_intfdata(intf);
1434
1435 hub_quiesce(hub, HUB_PRE_RESET);
1436 hub->in_reset = 1;
1437 hub_pm_barrier_for_all_ports(hub);
1438 return 0;
1439 }
1440
1441 /* caller has locked the hub device */
hub_post_reset(struct usb_interface * intf)1442 static int hub_post_reset(struct usb_interface *intf)
1443 {
1444 struct usb_hub *hub = usb_get_intfdata(intf);
1445
1446 hub->in_reset = 0;
1447 hub_pm_barrier_for_all_ports(hub);
1448 hub_activate(hub, HUB_POST_RESET);
1449 return 0;
1450 }
1451
hub_configure(struct usb_hub * hub,struct usb_endpoint_descriptor * endpoint)1452 static int hub_configure(struct usb_hub *hub,
1453 struct usb_endpoint_descriptor *endpoint)
1454 {
1455 struct usb_hcd *hcd;
1456 struct usb_device *hdev = hub->hdev;
1457 struct device *hub_dev = hub->intfdev;
1458 u16 hubstatus, hubchange;
1459 u16 wHubCharacteristics;
1460 unsigned int pipe;
1461 int maxp, ret, i;
1462 char *message = "out of memory";
1463 unsigned unit_load;
1464 unsigned full_load;
1465 unsigned maxchild;
1466
1467 hub->buffer = kmalloc(sizeof(*hub->buffer), GFP_KERNEL);
1468 if (!hub->buffer) {
1469 ret = -ENOMEM;
1470 goto fail;
1471 }
1472
1473 hub->status = kmalloc(sizeof(*hub->status), GFP_KERNEL);
1474 if (!hub->status) {
1475 ret = -ENOMEM;
1476 goto fail;
1477 }
1478 mutex_init(&hub->status_mutex);
1479
1480 hub->descriptor = kzalloc(sizeof(*hub->descriptor), GFP_KERNEL);
1481 if (!hub->descriptor) {
1482 ret = -ENOMEM;
1483 goto fail;
1484 }
1485
1486 /* Request the entire hub descriptor.
1487 * hub->descriptor can handle USB_MAXCHILDREN ports,
1488 * but a (non-SS) hub can/will return fewer bytes here.
1489 */
1490 ret = get_hub_descriptor(hdev, hub->descriptor);
1491 if (ret < 0) {
1492 message = "can't read hub descriptor";
1493 goto fail;
1494 }
1495
1496 maxchild = USB_MAXCHILDREN;
1497 if (hub_is_superspeed(hdev))
1498 maxchild = min_t(unsigned, maxchild, USB_SS_MAXPORTS);
1499
1500 if (hub->descriptor->bNbrPorts > maxchild) {
1501 message = "hub has too many ports!";
1502 ret = -ENODEV;
1503 goto fail;
1504 } else if (hub->descriptor->bNbrPorts == 0) {
1505 message = "hub doesn't have any ports!";
1506 ret = -ENODEV;
1507 goto fail;
1508 }
1509
1510 /*
1511 * Accumulate wHubDelay + 40ns for every hub in the tree of devices.
1512 * The resulting value will be used for SetIsochDelay() request.
1513 */
1514 if (hub_is_superspeed(hdev) || hub_is_superspeedplus(hdev)) {
1515 u32 delay = __le16_to_cpu(hub->descriptor->u.ss.wHubDelay);
1516
1517 if (hdev->parent)
1518 delay += hdev->parent->hub_delay;
1519
1520 delay += USB_TP_TRANSMISSION_DELAY;
1521 hdev->hub_delay = min_t(u32, delay, USB_TP_TRANSMISSION_DELAY_MAX);
1522 }
1523
1524 maxchild = hub->descriptor->bNbrPorts;
1525 dev_info(hub_dev, "%d port%s detected\n", maxchild,
1526 (maxchild == 1) ? "" : "s");
1527
1528 hub->ports = kcalloc(maxchild, sizeof(struct usb_port *), GFP_KERNEL);
1529 if (!hub->ports) {
1530 ret = -ENOMEM;
1531 goto fail;
1532 }
1533
1534 wHubCharacteristics = le16_to_cpu(hub->descriptor->wHubCharacteristics);
1535 if (hub_is_superspeed(hdev)) {
1536 unit_load = 150;
1537 full_load = 900;
1538 } else {
1539 unit_load = 100;
1540 full_load = 500;
1541 }
1542
1543 /* FIXME for USB 3.0, skip for now */
1544 if ((wHubCharacteristics & HUB_CHAR_COMPOUND) &&
1545 !(hub_is_superspeed(hdev))) {
1546 char portstr[USB_MAXCHILDREN + 1];
1547
1548 for (i = 0; i < maxchild; i++)
1549 portstr[i] = hub->descriptor->u.hs.DeviceRemovable
1550 [((i + 1) / 8)] & (1 << ((i + 1) % 8))
1551 ? 'F' : 'R';
1552 portstr[maxchild] = 0;
1553 dev_dbg(hub_dev, "compound device; port removable status: %s\n", portstr);
1554 } else
1555 dev_dbg(hub_dev, "standalone hub\n");
1556
1557 switch (wHubCharacteristics & HUB_CHAR_LPSM) {
1558 case HUB_CHAR_COMMON_LPSM:
1559 dev_dbg(hub_dev, "ganged power switching\n");
1560 break;
1561 case HUB_CHAR_INDV_PORT_LPSM:
1562 dev_dbg(hub_dev, "individual port power switching\n");
1563 break;
1564 case HUB_CHAR_NO_LPSM:
1565 case HUB_CHAR_LPSM:
1566 dev_dbg(hub_dev, "no power switching (usb 1.0)\n");
1567 break;
1568 }
1569
1570 switch (wHubCharacteristics & HUB_CHAR_OCPM) {
1571 case HUB_CHAR_COMMON_OCPM:
1572 dev_dbg(hub_dev, "global over-current protection\n");
1573 break;
1574 case HUB_CHAR_INDV_PORT_OCPM:
1575 dev_dbg(hub_dev, "individual port over-current protection\n");
1576 break;
1577 case HUB_CHAR_NO_OCPM:
1578 case HUB_CHAR_OCPM:
1579 dev_dbg(hub_dev, "no over-current protection\n");
1580 break;
1581 }
1582
1583 spin_lock_init(&hub->tt.lock);
1584 INIT_LIST_HEAD(&hub->tt.clear_list);
1585 INIT_WORK(&hub->tt.clear_work, hub_tt_work);
1586 switch (hdev->descriptor.bDeviceProtocol) {
1587 case USB_HUB_PR_FS:
1588 break;
1589 case USB_HUB_PR_HS_SINGLE_TT:
1590 dev_dbg(hub_dev, "Single TT\n");
1591 hub->tt.hub = hdev;
1592 break;
1593 case USB_HUB_PR_HS_MULTI_TT:
1594 ret = usb_set_interface(hdev, 0, 1);
1595 if (ret == 0) {
1596 dev_dbg(hub_dev, "TT per port\n");
1597 hub->tt.multi = 1;
1598 } else
1599 dev_err(hub_dev, "Using single TT (err %d)\n",
1600 ret);
1601 hub->tt.hub = hdev;
1602 break;
1603 case USB_HUB_PR_SS:
1604 /* USB 3.0 hubs don't have a TT */
1605 break;
1606 default:
1607 dev_dbg(hub_dev, "Unrecognized hub protocol %d\n",
1608 hdev->descriptor.bDeviceProtocol);
1609 break;
1610 }
1611
1612 /* Note 8 FS bit times == (8 bits / 12000000 bps) ~= 666ns */
1613 switch (wHubCharacteristics & HUB_CHAR_TTTT) {
1614 case HUB_TTTT_8_BITS:
1615 if (hdev->descriptor.bDeviceProtocol != 0) {
1616 hub->tt.think_time = 666;
1617 dev_dbg(hub_dev, "TT requires at most %d "
1618 "FS bit times (%d ns)\n",
1619 8, hub->tt.think_time);
1620 }
1621 break;
1622 case HUB_TTTT_16_BITS:
1623 hub->tt.think_time = 666 * 2;
1624 dev_dbg(hub_dev, "TT requires at most %d "
1625 "FS bit times (%d ns)\n",
1626 16, hub->tt.think_time);
1627 break;
1628 case HUB_TTTT_24_BITS:
1629 hub->tt.think_time = 666 * 3;
1630 dev_dbg(hub_dev, "TT requires at most %d "
1631 "FS bit times (%d ns)\n",
1632 24, hub->tt.think_time);
1633 break;
1634 case HUB_TTTT_32_BITS:
1635 hub->tt.think_time = 666 * 4;
1636 dev_dbg(hub_dev, "TT requires at most %d "
1637 "FS bit times (%d ns)\n",
1638 32, hub->tt.think_time);
1639 break;
1640 }
1641
1642 /* probe() zeroes hub->indicator[] */
1643 if (wHubCharacteristics & HUB_CHAR_PORTIND) {
1644 hub->has_indicators = 1;
1645 dev_dbg(hub_dev, "Port indicators are supported\n");
1646 }
1647
1648 dev_dbg(hub_dev, "power on to power good time: %dms\n",
1649 hub->descriptor->bPwrOn2PwrGood * 2);
1650
1651 /* power budgeting mostly matters with bus-powered hubs,
1652 * and battery-powered root hubs (may provide just 8 mA).
1653 */
1654 ret = usb_get_std_status(hdev, USB_RECIP_DEVICE, 0, &hubstatus);
1655 if (ret) {
1656 message = "can't get hub status";
1657 goto fail;
1658 }
1659 hcd = bus_to_hcd(hdev->bus);
1660 if (hdev == hdev->bus->root_hub) {
1661 if (hcd->power_budget > 0)
1662 hdev->bus_mA = hcd->power_budget;
1663 else
1664 hdev->bus_mA = full_load * maxchild;
1665 if (hdev->bus_mA >= full_load)
1666 hub->mA_per_port = full_load;
1667 else {
1668 hub->mA_per_port = hdev->bus_mA;
1669 hub->limited_power = 1;
1670 }
1671 } else if ((hubstatus & (1 << USB_DEVICE_SELF_POWERED)) == 0) {
1672 int remaining = hdev->bus_mA -
1673 hub->descriptor->bHubContrCurrent;
1674
1675 dev_dbg(hub_dev, "hub controller current requirement: %dmA\n",
1676 hub->descriptor->bHubContrCurrent);
1677 hub->limited_power = 1;
1678
1679 if (remaining < maxchild * unit_load)
1680 dev_warn(hub_dev,
1681 "insufficient power available "
1682 "to use all downstream ports\n");
1683 hub->mA_per_port = unit_load; /* 7.2.1 */
1684
1685 } else { /* Self-powered external hub */
1686 /* FIXME: What about battery-powered external hubs that
1687 * provide less current per port? */
1688 hub->mA_per_port = full_load;
1689 }
1690 if (hub->mA_per_port < full_load)
1691 dev_dbg(hub_dev, "%umA bus power budget for each child\n",
1692 hub->mA_per_port);
1693
1694 ret = hub_hub_status(hub, &hubstatus, &hubchange);
1695 if (ret < 0) {
1696 message = "can't get hub status";
1697 goto fail;
1698 }
1699
1700 /* local power status reports aren't always correct */
1701 if (hdev->actconfig->desc.bmAttributes & USB_CONFIG_ATT_SELFPOWER)
1702 dev_dbg(hub_dev, "local power source is %s\n",
1703 (hubstatus & HUB_STATUS_LOCAL_POWER)
1704 ? "lost (inactive)" : "good");
1705
1706 if ((wHubCharacteristics & HUB_CHAR_OCPM) == 0)
1707 dev_dbg(hub_dev, "%sover-current condition exists\n",
1708 (hubstatus & HUB_STATUS_OVERCURRENT) ? "" : "no ");
1709
1710 /* set up the interrupt endpoint
1711 * We use the EP's maxpacket size instead of (PORTS+1+7)/8
1712 * bytes as USB2.0[11.12.3] says because some hubs are known
1713 * to send more data (and thus cause overflow). For root hubs,
1714 * maxpktsize is defined in hcd.c's fake endpoint descriptors
1715 * to be big enough for at least USB_MAXCHILDREN ports. */
1716 pipe = usb_rcvintpipe(hdev, endpoint->bEndpointAddress);
1717 maxp = usb_maxpacket(hdev, pipe);
1718
1719 if (maxp > sizeof(*hub->buffer))
1720 maxp = sizeof(*hub->buffer);
1721
1722 hub->urb = usb_alloc_urb(0, GFP_KERNEL);
1723 if (!hub->urb) {
1724 ret = -ENOMEM;
1725 goto fail;
1726 }
1727
1728 usb_fill_int_urb(hub->urb, hdev, pipe, *hub->buffer, maxp, hub_irq,
1729 hub, endpoint->bInterval);
1730
1731 /* maybe cycle the hub leds */
1732 if (hub->has_indicators && blinkenlights)
1733 hub->indicator[0] = INDICATOR_CYCLE;
1734
1735 mutex_lock(&usb_port_peer_mutex);
1736 for (i = 0; i < maxchild; i++) {
1737 ret = usb_hub_create_port_device(hub, i + 1);
1738 if (ret < 0) {
1739 dev_err(hub->intfdev,
1740 "couldn't create port%d device.\n", i + 1);
1741 break;
1742 }
1743 }
1744 hdev->maxchild = i;
1745 for (i = 0; i < hdev->maxchild; i++) {
1746 struct usb_port *port_dev = hub->ports[i];
1747
1748 pm_runtime_put(&port_dev->dev);
1749 }
1750
1751 mutex_unlock(&usb_port_peer_mutex);
1752 if (ret < 0)
1753 goto fail;
1754
1755 /* Update the HCD's internal representation of this hub before hub_wq
1756 * starts getting port status changes for devices under the hub.
1757 */
1758 if (hcd->driver->update_hub_device) {
1759 ret = hcd->driver->update_hub_device(hcd, hdev,
1760 &hub->tt, GFP_KERNEL);
1761 if (ret < 0) {
1762 message = "can't update HCD hub info";
1763 goto fail;
1764 }
1765 }
1766
1767 usb_hub_adjust_deviceremovable(hdev, hub->descriptor);
1768
1769 hub_activate(hub, HUB_INIT);
1770 return 0;
1771
1772 fail:
1773 dev_err(hub_dev, "config failed, %s (err %d)\n",
1774 message, ret);
1775 /* hub_disconnect() frees urb and descriptor */
1776 return ret;
1777 }
1778
hub_release(struct kref * kref)1779 static void hub_release(struct kref *kref)
1780 {
1781 struct usb_hub *hub = container_of(kref, struct usb_hub, kref);
1782
1783 usb_put_dev(hub->hdev);
1784 usb_put_intf(to_usb_interface(hub->intfdev));
1785 kfree(hub);
1786 }
1787
hub_get(struct usb_hub * hub)1788 void hub_get(struct usb_hub *hub)
1789 {
1790 kref_get(&hub->kref);
1791 }
1792
hub_put(struct usb_hub * hub)1793 void hub_put(struct usb_hub *hub)
1794 {
1795 kref_put(&hub->kref, hub_release);
1796 }
1797
1798 static unsigned highspeed_hubs;
1799
hub_disconnect(struct usb_interface * intf)1800 static void hub_disconnect(struct usb_interface *intf)
1801 {
1802 struct usb_hub *hub = usb_get_intfdata(intf);
1803 struct usb_device *hdev = interface_to_usbdev(intf);
1804 int port1;
1805
1806 /*
1807 * Stop adding new hub events. We do not want to block here and thus
1808 * will not try to remove any pending work item.
1809 */
1810 hub->disconnected = 1;
1811
1812 /* Disconnect all children and quiesce the hub */
1813 hub->error = 0;
1814 hub_quiesce(hub, HUB_DISCONNECT);
1815
1816 mutex_lock(&usb_port_peer_mutex);
1817
1818 /* Avoid races with recursively_mark_NOTATTACHED() */
1819 spin_lock_irq(&device_state_lock);
1820 port1 = hdev->maxchild;
1821 hdev->maxchild = 0;
1822 usb_set_intfdata(intf, NULL);
1823 spin_unlock_irq(&device_state_lock);
1824
1825 for (; port1 > 0; --port1)
1826 usb_hub_remove_port_device(hub, port1);
1827
1828 mutex_unlock(&usb_port_peer_mutex);
1829
1830 if (hub->hdev->speed == USB_SPEED_HIGH)
1831 highspeed_hubs--;
1832
1833 usb_free_urb(hub->urb);
1834 kfree(hub->ports);
1835 kfree(hub->descriptor);
1836 kfree(hub->status);
1837 kfree(hub->buffer);
1838
1839 pm_suspend_ignore_children(&intf->dev, false);
1840
1841 if (hub->quirk_disable_autosuspend)
1842 usb_autopm_put_interface(intf);
1843
1844 onboard_dev_destroy_pdevs(&hub->onboard_devs);
1845
1846 hub_put(hub);
1847 }
1848
hub_descriptor_is_sane(struct usb_host_interface * desc)1849 static bool hub_descriptor_is_sane(struct usb_host_interface *desc)
1850 {
1851 /* Some hubs have a subclass of 1, which AFAICT according to the */
1852 /* specs is not defined, but it works */
1853 if (desc->desc.bInterfaceSubClass != 0 &&
1854 desc->desc.bInterfaceSubClass != 1)
1855 return false;
1856
1857 /* Multiple endpoints? What kind of mutant ninja-hub is this? */
1858 if (desc->desc.bNumEndpoints != 1)
1859 return false;
1860
1861 /* If the first endpoint is not interrupt IN, we'd better punt! */
1862 if (!usb_endpoint_is_int_in(&desc->endpoint[0].desc))
1863 return false;
1864
1865 return true;
1866 }
1867
hub_probe(struct usb_interface * intf,const struct usb_device_id * id)1868 static int hub_probe(struct usb_interface *intf, const struct usb_device_id *id)
1869 {
1870 struct usb_host_interface *desc;
1871 struct usb_device *hdev;
1872 struct usb_hub *hub;
1873
1874 desc = intf->cur_altsetting;
1875 hdev = interface_to_usbdev(intf);
1876
1877 /*
1878 * The USB 2.0 spec prohibits hubs from having more than one
1879 * configuration or interface, and we rely on this prohibition.
1880 * Refuse to accept a device that violates it.
1881 */
1882 if (hdev->descriptor.bNumConfigurations > 1 ||
1883 hdev->actconfig->desc.bNumInterfaces > 1) {
1884 dev_err(&intf->dev, "Invalid hub with more than one config or interface\n");
1885 return -EINVAL;
1886 }
1887
1888 /*
1889 * Set default autosuspend delay as 0 to speedup bus suspend,
1890 * based on the below considerations:
1891 *
1892 * - Unlike other drivers, the hub driver does not rely on the
1893 * autosuspend delay to provide enough time to handle a wakeup
1894 * event, and the submitted status URB is just to check future
1895 * change on hub downstream ports, so it is safe to do it.
1896 *
1897 * - The patch might cause one or more auto supend/resume for
1898 * below very rare devices when they are plugged into hub
1899 * first time:
1900 *
1901 * devices having trouble initializing, and disconnect
1902 * themselves from the bus and then reconnect a second
1903 * or so later
1904 *
1905 * devices just for downloading firmware, and disconnects
1906 * themselves after completing it
1907 *
1908 * For these quite rare devices, their drivers may change the
1909 * autosuspend delay of their parent hub in the probe() to one
1910 * appropriate value to avoid the subtle problem if someone
1911 * does care it.
1912 *
1913 * - The patch may cause one or more auto suspend/resume on
1914 * hub during running 'lsusb', but it is probably too
1915 * infrequent to worry about.
1916 *
1917 * - Change autosuspend delay of hub can avoid unnecessary auto
1918 * suspend timer for hub, also may decrease power consumption
1919 * of USB bus.
1920 *
1921 * - If user has indicated to prevent autosuspend by passing
1922 * usbcore.autosuspend = -1 then keep autosuspend disabled.
1923 */
1924 #ifdef CONFIG_PM
1925 if (hdev->dev.power.autosuspend_delay >= 0)
1926 pm_runtime_set_autosuspend_delay(&hdev->dev, 0);
1927 #endif
1928
1929 /*
1930 * Hubs have proper suspend/resume support, except for root hubs
1931 * where the controller driver doesn't have bus_suspend and
1932 * bus_resume methods.
1933 */
1934 if (hdev->parent) { /* normal device */
1935 usb_enable_autosuspend(hdev);
1936 } else { /* root hub */
1937 const struct hc_driver *drv = bus_to_hcd(hdev->bus)->driver;
1938
1939 if (drv->bus_suspend && drv->bus_resume)
1940 usb_enable_autosuspend(hdev);
1941 }
1942
1943 if (hdev->level == MAX_TOPO_LEVEL) {
1944 dev_err(&intf->dev,
1945 "Unsupported bus topology: hub nested too deep\n");
1946 return -E2BIG;
1947 }
1948
1949 #ifdef CONFIG_USB_OTG_DISABLE_EXTERNAL_HUB
1950 if (hdev->parent) {
1951 dev_warn(&intf->dev, "ignoring external hub\n");
1952 return -ENODEV;
1953 }
1954 #endif
1955
1956 if (!hub_descriptor_is_sane(desc)) {
1957 dev_err(&intf->dev, "bad descriptor, ignoring hub\n");
1958 return -EIO;
1959 }
1960
1961 /* We found a hub */
1962 dev_info(&intf->dev, "USB hub found\n");
1963
1964 hub = kzalloc(sizeof(*hub), GFP_KERNEL);
1965 if (!hub)
1966 return -ENOMEM;
1967
1968 kref_init(&hub->kref);
1969 hub->intfdev = &intf->dev;
1970 hub->hdev = hdev;
1971 INIT_DELAYED_WORK(&hub->leds, led_work);
1972 INIT_DELAYED_WORK(&hub->init_work, NULL);
1973 INIT_DELAYED_WORK(&hub->post_resume_work, hub_post_resume);
1974 INIT_WORK(&hub->events, hub_event);
1975 INIT_LIST_HEAD(&hub->onboard_devs);
1976 spin_lock_init(&hub->irq_urb_lock);
1977 timer_setup(&hub->irq_urb_retry, hub_retry_irq_urb, 0);
1978 usb_get_intf(intf);
1979 usb_get_dev(hdev);
1980
1981 usb_set_intfdata(intf, hub);
1982 intf->needs_remote_wakeup = 1;
1983 pm_suspend_ignore_children(&intf->dev, true);
1984
1985 if (hdev->speed == USB_SPEED_HIGH)
1986 highspeed_hubs++;
1987
1988 if (id->driver_info & HUB_QUIRK_CHECK_PORT_AUTOSUSPEND)
1989 hub->quirk_check_port_auto_suspend = 1;
1990
1991 if (id->driver_info & HUB_QUIRK_DISABLE_AUTOSUSPEND) {
1992 hub->quirk_disable_autosuspend = 1;
1993 usb_autopm_get_interface_no_resume(intf);
1994 }
1995
1996 if ((id->driver_info & HUB_QUIRK_REDUCE_FRAME_INTR_BINTERVAL) &&
1997 desc->endpoint[0].desc.bInterval > USB_REDUCE_FRAME_INTR_BINTERVAL) {
1998 desc->endpoint[0].desc.bInterval =
1999 USB_REDUCE_FRAME_INTR_BINTERVAL;
2000 /* Tell the HCD about the interrupt ep's new bInterval */
2001 usb_set_interface(hdev, 0, 0);
2002 }
2003
2004 if (hub_configure(hub, &desc->endpoint[0].desc) >= 0) {
2005 onboard_dev_create_pdevs(hdev, &hub->onboard_devs);
2006
2007 return 0;
2008 }
2009
2010 hub_disconnect(intf);
2011 return -ENODEV;
2012 }
2013
2014 static int
hub_ioctl(struct usb_interface * intf,unsigned int code,void * user_data)2015 hub_ioctl(struct usb_interface *intf, unsigned int code, void *user_data)
2016 {
2017 struct usb_device *hdev = interface_to_usbdev(intf);
2018 struct usb_hub *hub = usb_hub_to_struct_hub(hdev);
2019
2020 /* assert ifno == 0 (part of hub spec) */
2021 switch (code) {
2022 case USBDEVFS_HUB_PORTINFO: {
2023 struct usbdevfs_hub_portinfo *info = user_data;
2024 int i;
2025
2026 spin_lock_irq(&device_state_lock);
2027 if (hdev->devnum <= 0)
2028 info->nports = 0;
2029 else {
2030 info->nports = hdev->maxchild;
2031 for (i = 0; i < info->nports; i++) {
2032 if (hub->ports[i]->child == NULL)
2033 info->port[i] = 0;
2034 else
2035 info->port[i] =
2036 hub->ports[i]->child->devnum;
2037 }
2038 }
2039 spin_unlock_irq(&device_state_lock);
2040
2041 return info->nports + 1;
2042 }
2043
2044 default:
2045 return -ENOSYS;
2046 }
2047 }
2048
2049 /*
2050 * Allow user programs to claim ports on a hub. When a device is attached
2051 * to one of these "claimed" ports, the program will "own" the device.
2052 */
find_port_owner(struct usb_device * hdev,unsigned port1,struct usb_dev_state *** ppowner)2053 static int find_port_owner(struct usb_device *hdev, unsigned port1,
2054 struct usb_dev_state ***ppowner)
2055 {
2056 struct usb_hub *hub = usb_hub_to_struct_hub(hdev);
2057
2058 if (hdev->state == USB_STATE_NOTATTACHED)
2059 return -ENODEV;
2060 if (port1 == 0 || port1 > hdev->maxchild)
2061 return -EINVAL;
2062
2063 /* Devices not managed by the hub driver
2064 * will always have maxchild equal to 0.
2065 */
2066 *ppowner = &(hub->ports[port1 - 1]->port_owner);
2067 return 0;
2068 }
2069
2070 /* In the following three functions, the caller must hold hdev's lock */
usb_hub_claim_port(struct usb_device * hdev,unsigned port1,struct usb_dev_state * owner)2071 int usb_hub_claim_port(struct usb_device *hdev, unsigned port1,
2072 struct usb_dev_state *owner)
2073 {
2074 int rc;
2075 struct usb_dev_state **powner;
2076
2077 rc = find_port_owner(hdev, port1, &powner);
2078 if (rc)
2079 return rc;
2080 if (*powner)
2081 return -EBUSY;
2082 *powner = owner;
2083 return rc;
2084 }
2085 EXPORT_SYMBOL_GPL(usb_hub_claim_port);
2086
usb_hub_release_port(struct usb_device * hdev,unsigned port1,struct usb_dev_state * owner)2087 int usb_hub_release_port(struct usb_device *hdev, unsigned port1,
2088 struct usb_dev_state *owner)
2089 {
2090 int rc;
2091 struct usb_dev_state **powner;
2092
2093 rc = find_port_owner(hdev, port1, &powner);
2094 if (rc)
2095 return rc;
2096 if (*powner != owner)
2097 return -ENOENT;
2098 *powner = NULL;
2099 return rc;
2100 }
2101 EXPORT_SYMBOL_GPL(usb_hub_release_port);
2102
usb_hub_release_all_ports(struct usb_device * hdev,struct usb_dev_state * owner)2103 void usb_hub_release_all_ports(struct usb_device *hdev, struct usb_dev_state *owner)
2104 {
2105 struct usb_hub *hub = usb_hub_to_struct_hub(hdev);
2106 int n;
2107
2108 for (n = 0; n < hdev->maxchild; n++) {
2109 if (hub->ports[n]->port_owner == owner)
2110 hub->ports[n]->port_owner = NULL;
2111 }
2112
2113 }
2114
2115 /* The caller must hold udev's lock */
usb_device_is_owned(struct usb_device * udev)2116 bool usb_device_is_owned(struct usb_device *udev)
2117 {
2118 struct usb_hub *hub;
2119
2120 if (udev->state == USB_STATE_NOTATTACHED || !udev->parent)
2121 return false;
2122 hub = usb_hub_to_struct_hub(udev->parent);
2123 return !!hub->ports[udev->portnum - 1]->port_owner;
2124 }
2125
update_port_device_state(struct usb_device * udev)2126 static void update_port_device_state(struct usb_device *udev)
2127 {
2128 struct usb_hub *hub;
2129 struct usb_port *port_dev;
2130
2131 if (udev->parent) {
2132 hub = usb_hub_to_struct_hub(udev->parent);
2133
2134 /*
2135 * The Link Layer Validation System Driver (lvstest)
2136 * has a test step to unbind the hub before running the
2137 * rest of the procedure. This triggers hub_disconnect
2138 * which will set the hub's maxchild to 0, further
2139 * resulting in usb_hub_to_struct_hub returning NULL.
2140 */
2141 if (hub) {
2142 port_dev = hub->ports[udev->portnum - 1];
2143 WRITE_ONCE(port_dev->state, udev->state);
2144 sysfs_notify_dirent(port_dev->state_kn);
2145 }
2146 }
2147 }
2148
recursively_mark_NOTATTACHED(struct usb_device * udev)2149 static void recursively_mark_NOTATTACHED(struct usb_device *udev)
2150 {
2151 struct usb_hub *hub = usb_hub_to_struct_hub(udev);
2152 int i;
2153
2154 for (i = 0; i < udev->maxchild; ++i) {
2155 if (hub->ports[i]->child)
2156 recursively_mark_NOTATTACHED(hub->ports[i]->child);
2157 }
2158 if (udev->state == USB_STATE_SUSPENDED)
2159 udev->active_duration -= jiffies;
2160 udev->state = USB_STATE_NOTATTACHED;
2161 update_port_device_state(udev);
2162 }
2163
2164 /**
2165 * usb_set_device_state - change a device's current state (usbcore, hcds)
2166 * @udev: pointer to device whose state should be changed
2167 * @new_state: new state value to be stored
2168 *
2169 * udev->state is _not_ fully protected by the device lock. Although
2170 * most transitions are made only while holding the lock, the state can
2171 * can change to USB_STATE_NOTATTACHED at almost any time. This
2172 * is so that devices can be marked as disconnected as soon as possible,
2173 * without having to wait for any semaphores to be released. As a result,
2174 * all changes to any device's state must be protected by the
2175 * device_state_lock spinlock.
2176 *
2177 * Once a device has been added to the device tree, all changes to its state
2178 * should be made using this routine. The state should _not_ be set directly.
2179 *
2180 * If udev->state is already USB_STATE_NOTATTACHED then no change is made.
2181 * Otherwise udev->state is set to new_state, and if new_state is
2182 * USB_STATE_NOTATTACHED then all of udev's descendants' states are also set
2183 * to USB_STATE_NOTATTACHED.
2184 */
usb_set_device_state(struct usb_device * udev,enum usb_device_state new_state)2185 void usb_set_device_state(struct usb_device *udev,
2186 enum usb_device_state new_state)
2187 {
2188 unsigned long flags;
2189 int wakeup = -1;
2190
2191 spin_lock_irqsave(&device_state_lock, flags);
2192 if (udev->state == USB_STATE_NOTATTACHED)
2193 ; /* do nothing */
2194 else if (new_state != USB_STATE_NOTATTACHED) {
2195
2196 /* root hub wakeup capabilities are managed out-of-band
2197 * and may involve silicon errata ... ignore them here.
2198 */
2199 if (udev->parent) {
2200 if (udev->state == USB_STATE_SUSPENDED
2201 || new_state == USB_STATE_SUSPENDED)
2202 ; /* No change to wakeup settings */
2203 else if (new_state == USB_STATE_CONFIGURED)
2204 wakeup = (udev->quirks &
2205 USB_QUIRK_IGNORE_REMOTE_WAKEUP) ? 0 :
2206 udev->actconfig->desc.bmAttributes &
2207 USB_CONFIG_ATT_WAKEUP;
2208 else
2209 wakeup = 0;
2210 }
2211 if (udev->state == USB_STATE_SUSPENDED &&
2212 new_state != USB_STATE_SUSPENDED)
2213 udev->active_duration -= jiffies;
2214 else if (new_state == USB_STATE_SUSPENDED &&
2215 udev->state != USB_STATE_SUSPENDED)
2216 udev->active_duration += jiffies;
2217 udev->state = new_state;
2218 update_port_device_state(udev);
2219 } else
2220 recursively_mark_NOTATTACHED(udev);
2221 spin_unlock_irqrestore(&device_state_lock, flags);
2222 if (wakeup >= 0)
2223 device_set_wakeup_capable(&udev->dev, wakeup);
2224 }
2225 EXPORT_SYMBOL_GPL(usb_set_device_state);
2226
2227 /*
2228 * Choose a device number.
2229 *
2230 * Device numbers are used as filenames in usbfs. On USB-1.1 and
2231 * USB-2.0 buses they are also used as device addresses, however on
2232 * USB-3.0 buses the address is assigned by the controller hardware
2233 * and it usually is not the same as the device number.
2234 *
2235 * Devices connected under xHCI are not as simple. The host controller
2236 * supports virtualization, so the hardware assigns device addresses and
2237 * the HCD must setup data structures before issuing a set address
2238 * command to the hardware.
2239 */
choose_devnum(struct usb_device * udev)2240 static void choose_devnum(struct usb_device *udev)
2241 {
2242 int devnum;
2243 struct usb_bus *bus = udev->bus;
2244
2245 /* be safe when more hub events are proceed in parallel */
2246 mutex_lock(&bus->devnum_next_mutex);
2247
2248 /* Try to allocate the next devnum beginning at bus->devnum_next. */
2249 devnum = find_next_zero_bit(bus->devmap, 128, bus->devnum_next);
2250 if (devnum >= 128)
2251 devnum = find_next_zero_bit(bus->devmap, 128, 1);
2252 bus->devnum_next = (devnum >= 127 ? 1 : devnum + 1);
2253 if (devnum < 128) {
2254 set_bit(devnum, bus->devmap);
2255 udev->devnum = devnum;
2256 }
2257 mutex_unlock(&bus->devnum_next_mutex);
2258 }
2259
release_devnum(struct usb_device * udev)2260 static void release_devnum(struct usb_device *udev)
2261 {
2262 if (udev->devnum > 0) {
2263 clear_bit(udev->devnum, udev->bus->devmap);
2264 udev->devnum = -1;
2265 }
2266 }
2267
update_devnum(struct usb_device * udev,int devnum)2268 static void update_devnum(struct usb_device *udev, int devnum)
2269 {
2270 udev->devnum = devnum;
2271 if (!udev->devaddr)
2272 udev->devaddr = (u8)devnum;
2273 }
2274
hub_free_dev(struct usb_device * udev)2275 static void hub_free_dev(struct usb_device *udev)
2276 {
2277 struct usb_hcd *hcd = bus_to_hcd(udev->bus);
2278
2279 /* Root hubs aren't real devices, so don't free HCD resources */
2280 if (hcd->driver->free_dev && udev->parent)
2281 hcd->driver->free_dev(hcd, udev);
2282 }
2283
hub_disconnect_children(struct usb_device * udev)2284 static void hub_disconnect_children(struct usb_device *udev)
2285 {
2286 struct usb_hub *hub = usb_hub_to_struct_hub(udev);
2287 int i;
2288
2289 /* Free up all the children before we remove this device */
2290 for (i = 0; i < udev->maxchild; i++) {
2291 if (hub->ports[i]->child)
2292 usb_disconnect(&hub->ports[i]->child);
2293 }
2294 }
2295
2296 /**
2297 * usb_disconnect - disconnect a device (usbcore-internal)
2298 * @pdev: pointer to device being disconnected
2299 *
2300 * Context: task context, might sleep
2301 *
2302 * Something got disconnected. Get rid of it and all of its children.
2303 *
2304 * If *pdev is a normal device then the parent hub must already be locked.
2305 * If *pdev is a root hub then the caller must hold the usb_bus_idr_lock,
2306 * which protects the set of root hubs as well as the list of buses.
2307 *
2308 * Only hub drivers (including virtual root hub drivers for host
2309 * controllers) should ever call this.
2310 *
2311 * This call is synchronous, and may not be used in an interrupt context.
2312 */
usb_disconnect(struct usb_device ** pdev)2313 void usb_disconnect(struct usb_device **pdev)
2314 {
2315 struct usb_port *port_dev = NULL;
2316 struct usb_device *udev = *pdev;
2317 struct usb_hub *hub = NULL;
2318 int port1 = 1;
2319
2320 /* mark the device as inactive, so any further urb submissions for
2321 * this device (and any of its children) will fail immediately.
2322 * this quiesces everything except pending urbs.
2323 */
2324 usb_set_device_state(udev, USB_STATE_NOTATTACHED);
2325 dev_info(&udev->dev, "USB disconnect, device number %d\n",
2326 udev->devnum);
2327
2328 /*
2329 * Ensure that the pm runtime code knows that the USB device
2330 * is in the process of being disconnected.
2331 */
2332 pm_runtime_barrier(&udev->dev);
2333
2334 usb_lock_device(udev);
2335
2336 hub_disconnect_children(udev);
2337
2338 /* deallocate hcd/hardware state ... nuking all pending urbs and
2339 * cleaning up all state associated with the current configuration
2340 * so that the hardware is now fully quiesced.
2341 */
2342 dev_dbg(&udev->dev, "unregistering device\n");
2343 usb_disable_device(udev, 0);
2344 usb_hcd_synchronize_unlinks(udev);
2345
2346 if (udev->parent) {
2347 port1 = udev->portnum;
2348 hub = usb_hub_to_struct_hub(udev->parent);
2349 port_dev = hub->ports[port1 - 1];
2350
2351 sysfs_remove_link(&udev->dev.kobj, "port");
2352 sysfs_remove_link(&port_dev->dev.kobj, "device");
2353
2354 /*
2355 * As usb_port_runtime_resume() de-references udev, make
2356 * sure no resumes occur during removal
2357 */
2358 if (!test_and_set_bit(port1, hub->child_usage_bits))
2359 pm_runtime_get_sync(&port_dev->dev);
2360
2361 typec_deattach(port_dev->connector, &udev->dev);
2362 }
2363
2364 usb_remove_ep_devs(&udev->ep0);
2365 usb_unlock_device(udev);
2366
2367 /* Unregister the device. The device driver is responsible
2368 * for de-configuring the device and invoking the remove-device
2369 * notifier chain (used by usbfs and possibly others).
2370 */
2371 device_del(&udev->dev);
2372
2373 /* Free the device number and delete the parent's children[]
2374 * (or root_hub) pointer.
2375 */
2376 release_devnum(udev);
2377
2378 /* Avoid races with recursively_mark_NOTATTACHED() */
2379 spin_lock_irq(&device_state_lock);
2380 *pdev = NULL;
2381 spin_unlock_irq(&device_state_lock);
2382
2383 if (port_dev && test_and_clear_bit(port1, hub->child_usage_bits))
2384 pm_runtime_put(&port_dev->dev);
2385
2386 hub_free_dev(udev);
2387
2388 put_device(&udev->dev);
2389 }
2390
2391 #ifdef CONFIG_USB_ANNOUNCE_NEW_DEVICES
show_string(struct usb_device * udev,char * id,char * string)2392 static void show_string(struct usb_device *udev, char *id, char *string)
2393 {
2394 if (!string)
2395 return;
2396 dev_info(&udev->dev, "%s: %s\n", id, string);
2397 }
2398
announce_device(struct usb_device * udev)2399 static void announce_device(struct usb_device *udev)
2400 {
2401 u16 bcdDevice = le16_to_cpu(udev->descriptor.bcdDevice);
2402
2403 dev_info(&udev->dev,
2404 "New USB device found, idVendor=%04x, idProduct=%04x, bcdDevice=%2x.%02x\n",
2405 le16_to_cpu(udev->descriptor.idVendor),
2406 le16_to_cpu(udev->descriptor.idProduct),
2407 bcdDevice >> 8, bcdDevice & 0xff);
2408 dev_info(&udev->dev,
2409 "New USB device strings: Mfr=%d, Product=%d, SerialNumber=%d\n",
2410 udev->descriptor.iManufacturer,
2411 udev->descriptor.iProduct,
2412 udev->descriptor.iSerialNumber);
2413 show_string(udev, "Product", udev->product);
2414 show_string(udev, "Manufacturer", udev->manufacturer);
2415 show_string(udev, "SerialNumber", udev->serial);
2416 }
2417 #else
announce_device(struct usb_device * udev)2418 static inline void announce_device(struct usb_device *udev) { }
2419 #endif
2420
2421
2422 /**
2423 * usb_enumerate_device_otg - FIXME (usbcore-internal)
2424 * @udev: newly addressed device (in ADDRESS state)
2425 *
2426 * Finish enumeration for On-The-Go devices
2427 *
2428 * Return: 0 if successful. A negative error code otherwise.
2429 */
usb_enumerate_device_otg(struct usb_device * udev)2430 static int usb_enumerate_device_otg(struct usb_device *udev)
2431 {
2432 int err = 0;
2433
2434 #ifdef CONFIG_USB_OTG
2435 /*
2436 * OTG-aware devices on OTG-capable root hubs may be able to use SRP,
2437 * to wake us after we've powered off VBUS; and HNP, switching roles
2438 * "host" to "peripheral". The OTG descriptor helps figure this out.
2439 */
2440 if (!udev->bus->is_b_host
2441 && udev->config
2442 && udev->parent == udev->bus->root_hub) {
2443 struct usb_otg_descriptor *desc = NULL;
2444 struct usb_bus *bus = udev->bus;
2445 unsigned port1 = udev->portnum;
2446
2447 /* descriptor may appear anywhere in config */
2448 err = __usb_get_extra_descriptor(udev->rawdescriptors[0],
2449 le16_to_cpu(udev->config[0].desc.wTotalLength),
2450 USB_DT_OTG, (void **) &desc, sizeof(*desc));
2451 if (err || !(desc->bmAttributes & USB_OTG_HNP))
2452 return 0;
2453
2454 dev_info(&udev->dev, "Dual-Role OTG device on %sHNP port\n",
2455 (port1 == bus->otg_port) ? "" : "non-");
2456
2457 /* enable HNP before suspend, it's simpler */
2458 if (port1 == bus->otg_port) {
2459 bus->b_hnp_enable = 1;
2460 err = usb_control_msg(udev,
2461 usb_sndctrlpipe(udev, 0),
2462 USB_REQ_SET_FEATURE, 0,
2463 USB_DEVICE_B_HNP_ENABLE,
2464 0, NULL, 0,
2465 USB_CTRL_SET_TIMEOUT);
2466 if (err < 0) {
2467 /*
2468 * OTG MESSAGE: report errors here,
2469 * customize to match your product.
2470 */
2471 dev_err(&udev->dev, "can't set HNP mode: %d\n",
2472 err);
2473 bus->b_hnp_enable = 0;
2474 }
2475 } else if (desc->bLength == sizeof
2476 (struct usb_otg_descriptor)) {
2477 /*
2478 * We are operating on a legacy OTP device
2479 * These should be told that they are operating
2480 * on the wrong port if we have another port that does
2481 * support HNP
2482 */
2483 if (bus->otg_port != 0) {
2484 /* Set a_alt_hnp_support for legacy otg device */
2485 err = usb_control_msg(udev,
2486 usb_sndctrlpipe(udev, 0),
2487 USB_REQ_SET_FEATURE, 0,
2488 USB_DEVICE_A_ALT_HNP_SUPPORT,
2489 0, NULL, 0,
2490 USB_CTRL_SET_TIMEOUT);
2491 if (err < 0)
2492 dev_err(&udev->dev,
2493 "set a_alt_hnp_support failed: %d\n",
2494 err);
2495 }
2496 }
2497 }
2498 #endif
2499 return err;
2500 }
2501
2502
2503 /**
2504 * usb_enumerate_device - Read device configs/intfs/otg (usbcore-internal)
2505 * @udev: newly addressed device (in ADDRESS state)
2506 *
2507 * This is only called by usb_new_device() -- all comments that apply there
2508 * apply here wrt to environment.
2509 *
2510 * If the device is WUSB and not authorized, we don't attempt to read
2511 * the string descriptors, as they will be errored out by the device
2512 * until it has been authorized.
2513 *
2514 * Return: 0 if successful. A negative error code otherwise.
2515 */
usb_enumerate_device(struct usb_device * udev)2516 static int usb_enumerate_device(struct usb_device *udev)
2517 {
2518 int err;
2519 struct usb_hcd *hcd = bus_to_hcd(udev->bus);
2520
2521 if (udev->config == NULL) {
2522 err = usb_get_configuration(udev);
2523 if (err < 0) {
2524 if (err != -ENODEV)
2525 dev_err(&udev->dev, "can't read configurations, error %d\n",
2526 err);
2527 return err;
2528 }
2529 }
2530
2531 /* read the standard strings and cache them if present */
2532 udev->product = usb_cache_string(udev, udev->descriptor.iProduct);
2533 udev->manufacturer = usb_cache_string(udev,
2534 udev->descriptor.iManufacturer);
2535 udev->serial = usb_cache_string(udev, udev->descriptor.iSerialNumber);
2536
2537 err = usb_enumerate_device_otg(udev);
2538 if (err < 0)
2539 return err;
2540
2541 if (IS_ENABLED(CONFIG_USB_OTG_PRODUCTLIST) && hcd->tpl_support &&
2542 !is_targeted(udev)) {
2543 /* Maybe it can talk to us, though we can't talk to it.
2544 * (Includes HNP test device.)
2545 */
2546 if (IS_ENABLED(CONFIG_USB_OTG) && (udev->bus->b_hnp_enable
2547 || udev->bus->is_b_host)) {
2548 err = usb_port_suspend(udev, PMSG_AUTO_SUSPEND);
2549 if (err < 0)
2550 dev_dbg(&udev->dev, "HNP fail, %d\n", err);
2551 }
2552 return -ENOTSUPP;
2553 }
2554
2555 usb_detect_interface_quirks(udev);
2556
2557 return 0;
2558 }
2559
set_usb_port_removable(struct usb_device * udev)2560 static void set_usb_port_removable(struct usb_device *udev)
2561 {
2562 struct usb_device *hdev = udev->parent;
2563 struct usb_hub *hub;
2564 u8 port = udev->portnum;
2565 u16 wHubCharacteristics;
2566 bool removable = true;
2567
2568 dev_set_removable(&udev->dev, DEVICE_REMOVABLE_UNKNOWN);
2569
2570 if (!hdev)
2571 return;
2572
2573 hub = usb_hub_to_struct_hub(udev->parent);
2574
2575 /*
2576 * If the platform firmware has provided information about a port,
2577 * use that to determine whether it's removable.
2578 */
2579 switch (hub->ports[udev->portnum - 1]->connect_type) {
2580 case USB_PORT_CONNECT_TYPE_HOT_PLUG:
2581 dev_set_removable(&udev->dev, DEVICE_REMOVABLE);
2582 return;
2583 case USB_PORT_CONNECT_TYPE_HARD_WIRED:
2584 case USB_PORT_NOT_USED:
2585 dev_set_removable(&udev->dev, DEVICE_FIXED);
2586 return;
2587 default:
2588 break;
2589 }
2590
2591 /*
2592 * Otherwise, check whether the hub knows whether a port is removable
2593 * or not
2594 */
2595 wHubCharacteristics = le16_to_cpu(hub->descriptor->wHubCharacteristics);
2596
2597 if (!(wHubCharacteristics & HUB_CHAR_COMPOUND))
2598 return;
2599
2600 if (hub_is_superspeed(hdev)) {
2601 if (le16_to_cpu(hub->descriptor->u.ss.DeviceRemovable)
2602 & (1 << port))
2603 removable = false;
2604 } else {
2605 if (hub->descriptor->u.hs.DeviceRemovable[port / 8] & (1 << (port % 8)))
2606 removable = false;
2607 }
2608
2609 if (removable)
2610 dev_set_removable(&udev->dev, DEVICE_REMOVABLE);
2611 else
2612 dev_set_removable(&udev->dev, DEVICE_FIXED);
2613
2614 }
2615
2616 /**
2617 * usb_new_device - perform initial device setup (usbcore-internal)
2618 * @udev: newly addressed device (in ADDRESS state)
2619 *
2620 * This is called with devices which have been detected but not fully
2621 * enumerated. The device descriptor is available, but not descriptors
2622 * for any device configuration. The caller must have locked either
2623 * the parent hub (if udev is a normal device) or else the
2624 * usb_bus_idr_lock (if udev is a root hub). The parent's pointer to
2625 * udev has already been installed, but udev is not yet visible through
2626 * sysfs or other filesystem code.
2627 *
2628 * This call is synchronous, and may not be used in an interrupt context.
2629 *
2630 * Only the hub driver or root-hub registrar should ever call this.
2631 *
2632 * Return: Whether the device is configured properly or not. Zero if the
2633 * interface was registered with the driver core; else a negative errno
2634 * value.
2635 *
2636 */
usb_new_device(struct usb_device * udev)2637 int usb_new_device(struct usb_device *udev)
2638 {
2639 int err;
2640
2641 if (udev->parent) {
2642 /* Initialize non-root-hub device wakeup to disabled;
2643 * device (un)configuration controls wakeup capable
2644 * sysfs power/wakeup controls wakeup enabled/disabled
2645 */
2646 device_init_wakeup(&udev->dev, 0);
2647 }
2648
2649 /* Tell the runtime-PM framework the device is active */
2650 pm_runtime_set_active(&udev->dev);
2651 pm_runtime_get_noresume(&udev->dev);
2652 pm_runtime_use_autosuspend(&udev->dev);
2653 pm_runtime_enable(&udev->dev);
2654
2655 /* By default, forbid autosuspend for all devices. It will be
2656 * allowed for hubs during binding.
2657 */
2658 usb_disable_autosuspend(udev);
2659
2660 err = usb_enumerate_device(udev); /* Read descriptors */
2661 if (err < 0)
2662 goto fail;
2663 dev_dbg(&udev->dev, "udev %d, busnum %d, minor = %d\n",
2664 udev->devnum, udev->bus->busnum,
2665 (((udev->bus->busnum-1) * 128) + (udev->devnum-1)));
2666 /* export the usbdev device-node for libusb */
2667 udev->dev.devt = MKDEV(USB_DEVICE_MAJOR,
2668 (((udev->bus->busnum-1) * 128) + (udev->devnum-1)));
2669
2670 /* Tell the world! */
2671 announce_device(udev);
2672
2673 if (udev->serial)
2674 add_device_randomness(udev->serial, strlen(udev->serial));
2675 if (udev->product)
2676 add_device_randomness(udev->product, strlen(udev->product));
2677 if (udev->manufacturer)
2678 add_device_randomness(udev->manufacturer,
2679 strlen(udev->manufacturer));
2680
2681 device_enable_async_suspend(&udev->dev);
2682
2683 /* check whether the hub or firmware marks this port as non-removable */
2684 set_usb_port_removable(udev);
2685
2686 /* Register the device. The device driver is responsible
2687 * for configuring the device and invoking the add-device
2688 * notifier chain (used by usbfs and possibly others).
2689 */
2690 err = device_add(&udev->dev);
2691 if (err) {
2692 dev_err(&udev->dev, "can't device_add, error %d\n", err);
2693 goto fail;
2694 }
2695
2696 /* Create link files between child device and usb port device. */
2697 if (udev->parent) {
2698 struct usb_hub *hub = usb_hub_to_struct_hub(udev->parent);
2699 int port1 = udev->portnum;
2700 struct usb_port *port_dev = hub->ports[port1 - 1];
2701
2702 err = sysfs_create_link(&udev->dev.kobj,
2703 &port_dev->dev.kobj, "port");
2704 if (err)
2705 goto out_del_dev;
2706
2707 err = sysfs_create_link(&port_dev->dev.kobj,
2708 &udev->dev.kobj, "device");
2709 if (err) {
2710 sysfs_remove_link(&udev->dev.kobj, "port");
2711 goto out_del_dev;
2712 }
2713
2714 if (!test_and_set_bit(port1, hub->child_usage_bits))
2715 pm_runtime_get_sync(&port_dev->dev);
2716
2717 typec_attach(port_dev->connector, &udev->dev);
2718 }
2719
2720 (void) usb_create_ep_devs(&udev->dev, &udev->ep0, udev);
2721 usb_mark_last_busy(udev);
2722 pm_runtime_put_sync_autosuspend(&udev->dev);
2723 return err;
2724
2725 out_del_dev:
2726 device_del(&udev->dev);
2727 fail:
2728 usb_set_device_state(udev, USB_STATE_NOTATTACHED);
2729 pm_runtime_disable(&udev->dev);
2730 pm_runtime_set_suspended(&udev->dev);
2731 return err;
2732 }
2733
2734
2735 /**
2736 * usb_deauthorize_device - deauthorize a device (usbcore-internal)
2737 * @usb_dev: USB device
2738 *
2739 * Move the USB device to a very basic state where interfaces are disabled
2740 * and the device is in fact unconfigured and unusable.
2741 *
2742 * We share a lock (that we have) with device_del(), so we need to
2743 * defer its call.
2744 *
2745 * Return: 0.
2746 */
usb_deauthorize_device(struct usb_device * usb_dev)2747 int usb_deauthorize_device(struct usb_device *usb_dev)
2748 {
2749 usb_lock_device(usb_dev);
2750 if (usb_dev->authorized == 0)
2751 goto out_unauthorized;
2752
2753 usb_dev->authorized = 0;
2754 usb_set_configuration(usb_dev, -1);
2755
2756 out_unauthorized:
2757 usb_unlock_device(usb_dev);
2758 return 0;
2759 }
2760
2761
usb_authorize_device(struct usb_device * usb_dev)2762 int usb_authorize_device(struct usb_device *usb_dev)
2763 {
2764 int result = 0, c;
2765
2766 usb_lock_device(usb_dev);
2767 if (usb_dev->authorized == 1)
2768 goto out_authorized;
2769
2770 result = usb_autoresume_device(usb_dev);
2771 if (result < 0) {
2772 dev_err(&usb_dev->dev,
2773 "can't autoresume for authorization: %d\n", result);
2774 goto error_autoresume;
2775 }
2776
2777 usb_dev->authorized = 1;
2778 /* Choose and set the configuration. This registers the interfaces
2779 * with the driver core and lets interface drivers bind to them.
2780 */
2781 c = usb_choose_configuration(usb_dev);
2782 if (c >= 0) {
2783 result = usb_set_configuration(usb_dev, c);
2784 if (result) {
2785 dev_err(&usb_dev->dev,
2786 "can't set config #%d, error %d\n", c, result);
2787 /* This need not be fatal. The user can try to
2788 * set other configurations. */
2789 }
2790 }
2791 dev_info(&usb_dev->dev, "authorized to connect\n");
2792
2793 usb_autosuspend_device(usb_dev);
2794 error_autoresume:
2795 out_authorized:
2796 usb_unlock_device(usb_dev); /* complements locktree */
2797 return result;
2798 }
2799
2800 /**
2801 * get_port_ssp_rate - Match the extended port status to SSP rate
2802 * @hdev: The hub device
2803 * @ext_portstatus: extended port status
2804 *
2805 * Match the extended port status speed id to the SuperSpeed Plus sublink speed
2806 * capability attributes. Base on the number of connected lanes and speed,
2807 * return the corresponding enum usb_ssp_rate.
2808 */
get_port_ssp_rate(struct usb_device * hdev,u32 ext_portstatus)2809 static enum usb_ssp_rate get_port_ssp_rate(struct usb_device *hdev,
2810 u32 ext_portstatus)
2811 {
2812 struct usb_ssp_cap_descriptor *ssp_cap;
2813 u32 attr;
2814 u8 speed_id;
2815 u8 ssac;
2816 u8 lanes;
2817 int i;
2818
2819 if (!hdev->bos)
2820 goto out;
2821
2822 ssp_cap = hdev->bos->ssp_cap;
2823 if (!ssp_cap)
2824 goto out;
2825
2826 speed_id = ext_portstatus & USB_EXT_PORT_STAT_RX_SPEED_ID;
2827 lanes = USB_EXT_PORT_RX_LANES(ext_portstatus) + 1;
2828
2829 ssac = le32_to_cpu(ssp_cap->bmAttributes) &
2830 USB_SSP_SUBLINK_SPEED_ATTRIBS;
2831
2832 for (i = 0; i <= ssac; i++) {
2833 u8 ssid;
2834
2835 attr = le32_to_cpu(ssp_cap->bmSublinkSpeedAttr[i]);
2836 ssid = FIELD_GET(USB_SSP_SUBLINK_SPEED_SSID, attr);
2837 if (speed_id == ssid) {
2838 u16 mantissa;
2839 u8 lse;
2840 u8 type;
2841
2842 /*
2843 * Note: currently asymmetric lane types are only
2844 * applicable for SSIC operate in SuperSpeed protocol
2845 */
2846 type = FIELD_GET(USB_SSP_SUBLINK_SPEED_ST, attr);
2847 if (type == USB_SSP_SUBLINK_SPEED_ST_ASYM_RX ||
2848 type == USB_SSP_SUBLINK_SPEED_ST_ASYM_TX)
2849 goto out;
2850
2851 if (FIELD_GET(USB_SSP_SUBLINK_SPEED_LP, attr) !=
2852 USB_SSP_SUBLINK_SPEED_LP_SSP)
2853 goto out;
2854
2855 lse = FIELD_GET(USB_SSP_SUBLINK_SPEED_LSE, attr);
2856 mantissa = FIELD_GET(USB_SSP_SUBLINK_SPEED_LSM, attr);
2857
2858 /* Convert to Gbps */
2859 for (; lse < USB_SSP_SUBLINK_SPEED_LSE_GBPS; lse++)
2860 mantissa /= 1000;
2861
2862 if (mantissa >= 10 && lanes == 1)
2863 return USB_SSP_GEN_2x1;
2864
2865 if (mantissa >= 10 && lanes == 2)
2866 return USB_SSP_GEN_2x2;
2867
2868 if (mantissa >= 5 && lanes == 2)
2869 return USB_SSP_GEN_1x2;
2870
2871 goto out;
2872 }
2873 }
2874
2875 out:
2876 return USB_SSP_GEN_UNKNOWN;
2877 }
2878
2879 #ifdef CONFIG_USB_FEW_INIT_RETRIES
2880 #define PORT_RESET_TRIES 2
2881 #define SET_ADDRESS_TRIES 1
2882 #define GET_DESCRIPTOR_TRIES 1
2883 #define GET_MAXPACKET0_TRIES 1
2884 #define PORT_INIT_TRIES 4
2885
2886 #else
2887 #define PORT_RESET_TRIES 5
2888 #define SET_ADDRESS_TRIES 2
2889 #define GET_DESCRIPTOR_TRIES 2
2890 #define GET_MAXPACKET0_TRIES 3
2891 #define PORT_INIT_TRIES 4
2892 #endif /* CONFIG_USB_FEW_INIT_RETRIES */
2893
2894 #define DETECT_DISCONNECT_TRIES 5
2895
2896 #define HUB_ROOT_RESET_TIME 60 /* times are in msec */
2897 #define HUB_SHORT_RESET_TIME 10
2898 #define HUB_BH_RESET_TIME 50
2899 #define HUB_LONG_RESET_TIME 200
2900 #define HUB_RESET_TIMEOUT 800
2901
use_new_scheme(struct usb_device * udev,int retry,struct usb_port * port_dev)2902 static bool use_new_scheme(struct usb_device *udev, int retry,
2903 struct usb_port *port_dev)
2904 {
2905 int old_scheme_first_port =
2906 (port_dev->quirks & USB_PORT_QUIRK_OLD_SCHEME) ||
2907 old_scheme_first;
2908
2909 /*
2910 * "New scheme" enumeration causes an extra state transition to be
2911 * exposed to an xhci host and causes USB3 devices to receive control
2912 * commands in the default state. This has been seen to cause
2913 * enumeration failures, so disable this enumeration scheme for USB3
2914 * devices.
2915 */
2916 if (udev->speed >= USB_SPEED_SUPER)
2917 return false;
2918
2919 /*
2920 * If use_both_schemes is set, use the first scheme (whichever
2921 * it is) for the larger half of the retries, then use the other
2922 * scheme. Otherwise, use the first scheme for all the retries.
2923 */
2924 if (use_both_schemes && retry >= (PORT_INIT_TRIES + 1) / 2)
2925 return old_scheme_first_port; /* Second half */
2926 return !old_scheme_first_port; /* First half or all */
2927 }
2928
2929 /* Is a USB 3.0 port in the Inactive or Compliance Mode state?
2930 * Port warm reset is required to recover
2931 */
hub_port_warm_reset_required(struct usb_hub * hub,int port1,u16 portstatus)2932 static bool hub_port_warm_reset_required(struct usb_hub *hub, int port1,
2933 u16 portstatus)
2934 {
2935 u16 link_state;
2936
2937 if (!hub_is_superspeed(hub->hdev))
2938 return false;
2939
2940 if (test_bit(port1, hub->warm_reset_bits))
2941 return true;
2942
2943 link_state = portstatus & USB_PORT_STAT_LINK_STATE;
2944 return link_state == USB_SS_PORT_LS_SS_INACTIVE
2945 || link_state == USB_SS_PORT_LS_COMP_MOD;
2946 }
2947
hub_port_wait_reset(struct usb_hub * hub,int port1,struct usb_device * udev,unsigned int delay,bool warm)2948 static int hub_port_wait_reset(struct usb_hub *hub, int port1,
2949 struct usb_device *udev, unsigned int delay, bool warm)
2950 {
2951 int delay_time, ret;
2952 u16 portstatus;
2953 u16 portchange;
2954 u32 ext_portstatus = 0;
2955
2956 for (delay_time = 0;
2957 delay_time < HUB_RESET_TIMEOUT;
2958 delay_time += delay) {
2959 /* wait to give the device a chance to reset */
2960 msleep(delay);
2961
2962 /* read and decode port status */
2963 if (hub_is_superspeedplus(hub->hdev))
2964 ret = hub_ext_port_status(hub, port1,
2965 HUB_EXT_PORT_STATUS,
2966 &portstatus, &portchange,
2967 &ext_portstatus);
2968 else
2969 ret = usb_hub_port_status(hub, port1, &portstatus,
2970 &portchange);
2971 if (ret < 0)
2972 return ret;
2973
2974 /*
2975 * The port state is unknown until the reset completes.
2976 *
2977 * On top of that, some chips may require additional time
2978 * to re-establish a connection after the reset is complete,
2979 * so also wait for the connection to be re-established.
2980 */
2981 if (!(portstatus & USB_PORT_STAT_RESET) &&
2982 (portstatus & USB_PORT_STAT_CONNECTION))
2983 break;
2984
2985 /* switch to the long delay after two short delay failures */
2986 if (delay_time >= 2 * HUB_SHORT_RESET_TIME)
2987 delay = HUB_LONG_RESET_TIME;
2988
2989 dev_dbg(&hub->ports[port1 - 1]->dev,
2990 "not %sreset yet, waiting %dms\n",
2991 warm ? "warm " : "", delay);
2992 }
2993
2994 if ((portstatus & USB_PORT_STAT_RESET))
2995 return -EBUSY;
2996
2997 if (hub_port_warm_reset_required(hub, port1, portstatus))
2998 return -ENOTCONN;
2999
3000 /* Device went away? */
3001 if (!(portstatus & USB_PORT_STAT_CONNECTION))
3002 return -ENOTCONN;
3003
3004 /* Retry if connect change is set but status is still connected.
3005 * A USB 3.0 connection may bounce if multiple warm resets were issued,
3006 * but the device may have successfully re-connected. Ignore it.
3007 */
3008 if (!hub_is_superspeed(hub->hdev) &&
3009 (portchange & USB_PORT_STAT_C_CONNECTION)) {
3010 usb_clear_port_feature(hub->hdev, port1,
3011 USB_PORT_FEAT_C_CONNECTION);
3012 return -EAGAIN;
3013 }
3014
3015 if (!(portstatus & USB_PORT_STAT_ENABLE))
3016 return -EBUSY;
3017
3018 if (!udev)
3019 return 0;
3020
3021 if (hub_is_superspeedplus(hub->hdev)) {
3022 /* extended portstatus Rx and Tx lane count are zero based */
3023 udev->rx_lanes = USB_EXT_PORT_RX_LANES(ext_portstatus) + 1;
3024 udev->tx_lanes = USB_EXT_PORT_TX_LANES(ext_portstatus) + 1;
3025 udev->ssp_rate = get_port_ssp_rate(hub->hdev, ext_portstatus);
3026 } else {
3027 udev->rx_lanes = 1;
3028 udev->tx_lanes = 1;
3029 udev->ssp_rate = USB_SSP_GEN_UNKNOWN;
3030 }
3031 if (udev->ssp_rate != USB_SSP_GEN_UNKNOWN)
3032 udev->speed = USB_SPEED_SUPER_PLUS;
3033 else if (hub_is_superspeed(hub->hdev))
3034 udev->speed = USB_SPEED_SUPER;
3035 else if (portstatus & USB_PORT_STAT_HIGH_SPEED)
3036 udev->speed = USB_SPEED_HIGH;
3037 else if (portstatus & USB_PORT_STAT_LOW_SPEED)
3038 udev->speed = USB_SPEED_LOW;
3039 else
3040 udev->speed = USB_SPEED_FULL;
3041 return 0;
3042 }
3043
3044 /* Handle port reset and port warm(BH) reset (for USB3 protocol ports) */
hub_port_reset(struct usb_hub * hub,int port1,struct usb_device * udev,unsigned int delay,bool warm)3045 static int hub_port_reset(struct usb_hub *hub, int port1,
3046 struct usb_device *udev, unsigned int delay, bool warm)
3047 {
3048 int i, status;
3049 u16 portchange, portstatus;
3050 struct usb_port *port_dev = hub->ports[port1 - 1];
3051 int reset_recovery_time;
3052
3053 if (!hub_is_superspeed(hub->hdev)) {
3054 if (warm) {
3055 dev_err(hub->intfdev, "only USB3 hub support "
3056 "warm reset\n");
3057 return -EINVAL;
3058 }
3059 /* Block EHCI CF initialization during the port reset.
3060 * Some companion controllers don't like it when they mix.
3061 */
3062 down_read(&ehci_cf_port_reset_rwsem);
3063 } else if (!warm) {
3064 /*
3065 * If the caller hasn't explicitly requested a warm reset,
3066 * double check and see if one is needed.
3067 */
3068 if (usb_hub_port_status(hub, port1, &portstatus,
3069 &portchange) == 0)
3070 if (hub_port_warm_reset_required(hub, port1,
3071 portstatus))
3072 warm = true;
3073 }
3074 clear_bit(port1, hub->warm_reset_bits);
3075
3076 /* Reset the port */
3077 for (i = 0; i < PORT_RESET_TRIES; i++) {
3078 status = set_port_feature(hub->hdev, port1, (warm ?
3079 USB_PORT_FEAT_BH_PORT_RESET :
3080 USB_PORT_FEAT_RESET));
3081 if (status == -ENODEV) {
3082 ; /* The hub is gone */
3083 } else if (status) {
3084 dev_err(&port_dev->dev,
3085 "cannot %sreset (err = %d)\n",
3086 warm ? "warm " : "", status);
3087 } else {
3088 status = hub_port_wait_reset(hub, port1, udev, delay,
3089 warm);
3090 if (status && status != -ENOTCONN && status != -ENODEV)
3091 dev_dbg(hub->intfdev,
3092 "port_wait_reset: err = %d\n",
3093 status);
3094 }
3095
3096 /*
3097 * Check for disconnect or reset, and bail out after several
3098 * reset attempts to avoid warm reset loop.
3099 */
3100 if (status == 0 || status == -ENOTCONN || status == -ENODEV ||
3101 (status == -EBUSY && i == PORT_RESET_TRIES - 1)) {
3102 usb_clear_port_feature(hub->hdev, port1,
3103 USB_PORT_FEAT_C_RESET);
3104
3105 if (!hub_is_superspeed(hub->hdev))
3106 goto done;
3107
3108 usb_clear_port_feature(hub->hdev, port1,
3109 USB_PORT_FEAT_C_BH_PORT_RESET);
3110 usb_clear_port_feature(hub->hdev, port1,
3111 USB_PORT_FEAT_C_PORT_LINK_STATE);
3112
3113 if (udev)
3114 usb_clear_port_feature(hub->hdev, port1,
3115 USB_PORT_FEAT_C_CONNECTION);
3116
3117 /*
3118 * If a USB 3.0 device migrates from reset to an error
3119 * state, re-issue the warm reset.
3120 */
3121 if (usb_hub_port_status(hub, port1,
3122 &portstatus, &portchange) < 0)
3123 goto done;
3124
3125 if (!hub_port_warm_reset_required(hub, port1,
3126 portstatus))
3127 goto done;
3128
3129 /*
3130 * If the port is in SS.Inactive or Compliance Mode, the
3131 * hot or warm reset failed. Try another warm reset.
3132 */
3133 if (!warm) {
3134 dev_dbg(&port_dev->dev,
3135 "hot reset failed, warm reset\n");
3136 warm = true;
3137 }
3138 }
3139
3140 dev_dbg(&port_dev->dev,
3141 "not enabled, trying %sreset again...\n",
3142 warm ? "warm " : "");
3143 delay = HUB_LONG_RESET_TIME;
3144 }
3145
3146 dev_err(&port_dev->dev, "Cannot enable. Maybe the USB cable is bad?\n");
3147
3148 done:
3149 if (status == 0) {
3150 if (port_dev->quirks & USB_PORT_QUIRK_FAST_ENUM)
3151 usleep_range(10000, 12000);
3152 else {
3153 /* TRSTRCY = 10 ms; plus some extra */
3154 reset_recovery_time = 10 + 40;
3155
3156 /* Hub needs extra delay after resetting its port. */
3157 if (hub->hdev->quirks & USB_QUIRK_HUB_SLOW_RESET)
3158 reset_recovery_time += 100;
3159
3160 msleep(reset_recovery_time);
3161 }
3162
3163 if (udev) {
3164 struct usb_hcd *hcd = bus_to_hcd(udev->bus);
3165
3166 update_devnum(udev, 0);
3167 /* The xHC may think the device is already reset,
3168 * so ignore the status.
3169 */
3170 if (hcd->driver->reset_device)
3171 hcd->driver->reset_device(hcd, udev);
3172
3173 usb_set_device_state(udev, USB_STATE_DEFAULT);
3174 }
3175 } else {
3176 if (udev)
3177 usb_set_device_state(udev, USB_STATE_NOTATTACHED);
3178 }
3179
3180 if (!hub_is_superspeed(hub->hdev))
3181 up_read(&ehci_cf_port_reset_rwsem);
3182
3183 return status;
3184 }
3185
3186 /*
3187 * hub_port_stop_enumerate - stop USB enumeration or ignore port events
3188 * @hub: target hub
3189 * @port1: port num of the port
3190 * @retries: port retries number of hub_port_init()
3191 *
3192 * Return:
3193 * true: ignore port actions/events or give up connection attempts.
3194 * false: keep original behavior.
3195 *
3196 * This function will be based on retries to check whether the port which is
3197 * marked with early_stop attribute would stop enumeration or ignore events.
3198 *
3199 * Note:
3200 * This function didn't change anything if early_stop is not set, and it will
3201 * prevent all connection attempts when early_stop is set and the attempts of
3202 * the port are more than 1.
3203 */
hub_port_stop_enumerate(struct usb_hub * hub,int port1,int retries)3204 static bool hub_port_stop_enumerate(struct usb_hub *hub, int port1, int retries)
3205 {
3206 struct usb_port *port_dev = hub->ports[port1 - 1];
3207
3208 if (port_dev->early_stop) {
3209 if (port_dev->ignore_event)
3210 return true;
3211
3212 /*
3213 * We want unsuccessful attempts to fail quickly.
3214 * Since some devices may need one failure during
3215 * port initialization, we allow two tries but no
3216 * more.
3217 */
3218 if (retries < 2)
3219 return false;
3220
3221 port_dev->ignore_event = 1;
3222 } else
3223 port_dev->ignore_event = 0;
3224
3225 return port_dev->ignore_event;
3226 }
3227
3228 /* Check if a port is power on */
usb_port_is_power_on(struct usb_hub * hub,unsigned int portstatus)3229 int usb_port_is_power_on(struct usb_hub *hub, unsigned int portstatus)
3230 {
3231 int ret = 0;
3232
3233 if (hub_is_superspeed(hub->hdev)) {
3234 if (portstatus & USB_SS_PORT_STAT_POWER)
3235 ret = 1;
3236 } else {
3237 if (portstatus & USB_PORT_STAT_POWER)
3238 ret = 1;
3239 }
3240
3241 return ret;
3242 }
3243
usb_lock_port(struct usb_port * port_dev)3244 static void usb_lock_port(struct usb_port *port_dev)
3245 __acquires(&port_dev->status_lock)
3246 {
3247 mutex_lock(&port_dev->status_lock);
3248 __acquire(&port_dev->status_lock);
3249 }
3250
usb_unlock_port(struct usb_port * port_dev)3251 static void usb_unlock_port(struct usb_port *port_dev)
3252 __releases(&port_dev->status_lock)
3253 {
3254 mutex_unlock(&port_dev->status_lock);
3255 __release(&port_dev->status_lock);
3256 }
3257
3258 #ifdef CONFIG_PM
3259
3260 /* Check if a port is suspended(USB2.0 port) or in U3 state(USB3.0 port) */
port_is_suspended(struct usb_hub * hub,unsigned portstatus)3261 static int port_is_suspended(struct usb_hub *hub, unsigned portstatus)
3262 {
3263 int ret = 0;
3264
3265 if (hub_is_superspeed(hub->hdev)) {
3266 if ((portstatus & USB_PORT_STAT_LINK_STATE)
3267 == USB_SS_PORT_LS_U3)
3268 ret = 1;
3269 } else {
3270 if (portstatus & USB_PORT_STAT_SUSPEND)
3271 ret = 1;
3272 }
3273
3274 return ret;
3275 }
3276
3277 /* Determine whether the device on a port is ready for a normal resume,
3278 * is ready for a reset-resume, or should be disconnected.
3279 */
check_port_resume_type(struct usb_device * udev,struct usb_hub * hub,int port1,int status,u16 portchange,u16 portstatus)3280 static int check_port_resume_type(struct usb_device *udev,
3281 struct usb_hub *hub, int port1,
3282 int status, u16 portchange, u16 portstatus)
3283 {
3284 struct usb_port *port_dev = hub->ports[port1 - 1];
3285 int retries = 3;
3286
3287 retry:
3288 /* Is a warm reset needed to recover the connection? */
3289 if (status == 0 && udev->reset_resume
3290 && hub_port_warm_reset_required(hub, port1, portstatus)) {
3291 /* pass */;
3292 }
3293 /* Is the device still present? */
3294 else if (status || port_is_suspended(hub, portstatus) ||
3295 !usb_port_is_power_on(hub, portstatus)) {
3296 if (status >= 0)
3297 status = -ENODEV;
3298 } else if (!(portstatus & USB_PORT_STAT_CONNECTION)) {
3299 if (retries--) {
3300 usleep_range(200, 300);
3301 status = usb_hub_port_status(hub, port1, &portstatus,
3302 &portchange);
3303 goto retry;
3304 }
3305 status = -ENODEV;
3306 }
3307
3308 /* Can't do a normal resume if the port isn't enabled,
3309 * so try a reset-resume instead.
3310 */
3311 else if (!(portstatus & USB_PORT_STAT_ENABLE) && !udev->reset_resume) {
3312 if (udev->persist_enabled)
3313 udev->reset_resume = 1;
3314 else
3315 status = -ENODEV;
3316 }
3317
3318 if (status) {
3319 dev_dbg(&port_dev->dev, "status %04x.%04x after resume, %d\n",
3320 portchange, portstatus, status);
3321 } else if (udev->reset_resume) {
3322
3323 /* Late port handoff can set status-change bits */
3324 if (portchange & USB_PORT_STAT_C_CONNECTION)
3325 usb_clear_port_feature(hub->hdev, port1,
3326 USB_PORT_FEAT_C_CONNECTION);
3327 if (portchange & USB_PORT_STAT_C_ENABLE)
3328 usb_clear_port_feature(hub->hdev, port1,
3329 USB_PORT_FEAT_C_ENABLE);
3330
3331 /*
3332 * Whatever made this reset-resume necessary may have
3333 * turned on the port1 bit in hub->change_bits. But after
3334 * a successful reset-resume we want the bit to be clear;
3335 * if it was on it would indicate that something happened
3336 * following the reset-resume.
3337 */
3338 clear_bit(port1, hub->change_bits);
3339 }
3340
3341 return status;
3342 }
3343
usb_disable_ltm(struct usb_device * udev)3344 int usb_disable_ltm(struct usb_device *udev)
3345 {
3346 struct usb_hcd *hcd = bus_to_hcd(udev->bus);
3347
3348 /* Check if the roothub and device supports LTM. */
3349 if (!usb_device_supports_ltm(hcd->self.root_hub) ||
3350 !usb_device_supports_ltm(udev))
3351 return 0;
3352
3353 /* Clear Feature LTM Enable can only be sent if the device is
3354 * configured.
3355 */
3356 if (!udev->actconfig)
3357 return 0;
3358
3359 return usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
3360 USB_REQ_CLEAR_FEATURE, USB_RECIP_DEVICE,
3361 USB_DEVICE_LTM_ENABLE, 0, NULL, 0,
3362 USB_CTRL_SET_TIMEOUT);
3363 }
3364 EXPORT_SYMBOL_GPL(usb_disable_ltm);
3365
usb_enable_ltm(struct usb_device * udev)3366 void usb_enable_ltm(struct usb_device *udev)
3367 {
3368 struct usb_hcd *hcd = bus_to_hcd(udev->bus);
3369
3370 /* Check if the roothub and device supports LTM. */
3371 if (!usb_device_supports_ltm(hcd->self.root_hub) ||
3372 !usb_device_supports_ltm(udev))
3373 return;
3374
3375 /* Set Feature LTM Enable can only be sent if the device is
3376 * configured.
3377 */
3378 if (!udev->actconfig)
3379 return;
3380
3381 usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
3382 USB_REQ_SET_FEATURE, USB_RECIP_DEVICE,
3383 USB_DEVICE_LTM_ENABLE, 0, NULL, 0,
3384 USB_CTRL_SET_TIMEOUT);
3385 }
3386 EXPORT_SYMBOL_GPL(usb_enable_ltm);
3387
3388 /*
3389 * usb_enable_remote_wakeup - enable remote wakeup for a device
3390 * @udev: target device
3391 *
3392 * For USB-2 devices: Set the device's remote wakeup feature.
3393 *
3394 * For USB-3 devices: Assume there's only one function on the device and
3395 * enable remote wake for the first interface. FIXME if the interface
3396 * association descriptor shows there's more than one function.
3397 */
usb_enable_remote_wakeup(struct usb_device * udev)3398 static int usb_enable_remote_wakeup(struct usb_device *udev)
3399 {
3400 if (udev->speed < USB_SPEED_SUPER)
3401 return usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
3402 USB_REQ_SET_FEATURE, USB_RECIP_DEVICE,
3403 USB_DEVICE_REMOTE_WAKEUP, 0, NULL, 0,
3404 USB_CTRL_SET_TIMEOUT);
3405 else
3406 return usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
3407 USB_REQ_SET_FEATURE, USB_RECIP_INTERFACE,
3408 USB_INTRF_FUNC_SUSPEND,
3409 USB_INTRF_FUNC_SUSPEND_RW |
3410 USB_INTRF_FUNC_SUSPEND_LP,
3411 NULL, 0, USB_CTRL_SET_TIMEOUT);
3412 }
3413
3414 /*
3415 * usb_disable_remote_wakeup - disable remote wakeup for a device
3416 * @udev: target device
3417 *
3418 * For USB-2 devices: Clear the device's remote wakeup feature.
3419 *
3420 * For USB-3 devices: Assume there's only one function on the device and
3421 * disable remote wake for the first interface. FIXME if the interface
3422 * association descriptor shows there's more than one function.
3423 */
usb_disable_remote_wakeup(struct usb_device * udev)3424 static int usb_disable_remote_wakeup(struct usb_device *udev)
3425 {
3426 if (udev->speed < USB_SPEED_SUPER)
3427 return usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
3428 USB_REQ_CLEAR_FEATURE, USB_RECIP_DEVICE,
3429 USB_DEVICE_REMOTE_WAKEUP, 0, NULL, 0,
3430 USB_CTRL_SET_TIMEOUT);
3431 else
3432 return usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
3433 USB_REQ_SET_FEATURE, USB_RECIP_INTERFACE,
3434 USB_INTRF_FUNC_SUSPEND, 0, NULL, 0,
3435 USB_CTRL_SET_TIMEOUT);
3436 }
3437
3438 /* Count of wakeup-enabled devices at or below udev */
usb_wakeup_enabled_descendants(struct usb_device * udev)3439 unsigned usb_wakeup_enabled_descendants(struct usb_device *udev)
3440 {
3441 struct usb_hub *hub = usb_hub_to_struct_hub(udev);
3442
3443 return udev->do_remote_wakeup +
3444 (hub ? hub->wakeup_enabled_descendants : 0);
3445 }
3446 EXPORT_SYMBOL_GPL(usb_wakeup_enabled_descendants);
3447
3448 /*
3449 * usb_port_suspend - suspend a usb device's upstream port
3450 * @udev: device that's no longer in active use, not a root hub
3451 * Context: must be able to sleep; device not locked; pm locks held
3452 *
3453 * Suspends a USB device that isn't in active use, conserving power.
3454 * Devices may wake out of a suspend, if anything important happens,
3455 * using the remote wakeup mechanism. They may also be taken out of
3456 * suspend by the host, using usb_port_resume(). It's also routine
3457 * to disconnect devices while they are suspended.
3458 *
3459 * This only affects the USB hardware for a device; its interfaces
3460 * (and, for hubs, child devices) must already have been suspended.
3461 *
3462 * Selective port suspend reduces power; most suspended devices draw
3463 * less than 500 uA. It's also used in OTG, along with remote wakeup.
3464 * All devices below the suspended port are also suspended.
3465 *
3466 * Devices leave suspend state when the host wakes them up. Some devices
3467 * also support "remote wakeup", where the device can activate the USB
3468 * tree above them to deliver data, such as a keypress or packet. In
3469 * some cases, this wakes the USB host.
3470 *
3471 * Suspending OTG devices may trigger HNP, if that's been enabled
3472 * between a pair of dual-role devices. That will change roles, such
3473 * as from A-Host to A-Peripheral or from B-Host back to B-Peripheral.
3474 *
3475 * Devices on USB hub ports have only one "suspend" state, corresponding
3476 * to ACPI D2, "may cause the device to lose some context".
3477 * State transitions include:
3478 *
3479 * - suspend, resume ... when the VBUS power link stays live
3480 * - suspend, disconnect ... VBUS lost
3481 *
3482 * Once VBUS drop breaks the circuit, the port it's using has to go through
3483 * normal re-enumeration procedures, starting with enabling VBUS power.
3484 * Other than re-initializing the hub (plug/unplug, except for root hubs),
3485 * Linux (2.6) currently has NO mechanisms to initiate that: no hub_wq
3486 * timer, no SRP, no requests through sysfs.
3487 *
3488 * If Runtime PM isn't enabled or used, non-SuperSpeed devices may not get
3489 * suspended until their bus goes into global suspend (i.e., the root
3490 * hub is suspended). Nevertheless, we change @udev->state to
3491 * USB_STATE_SUSPENDED as this is the device's "logical" state. The actual
3492 * upstream port setting is stored in @udev->port_is_suspended.
3493 *
3494 * Returns 0 on success, else negative errno.
3495 */
usb_port_suspend(struct usb_device * udev,pm_message_t msg)3496 int usb_port_suspend(struct usb_device *udev, pm_message_t msg)
3497 {
3498 struct usb_hub *hub = usb_hub_to_struct_hub(udev->parent);
3499 struct usb_port *port_dev = hub->ports[udev->portnum - 1];
3500 int port1 = udev->portnum;
3501 int status;
3502 bool really_suspend = true;
3503
3504 usb_lock_port(port_dev);
3505
3506 /* enable remote wakeup when appropriate; this lets the device
3507 * wake up the upstream hub (including maybe the root hub).
3508 *
3509 * NOTE: OTG devices may issue remote wakeup (or SRP) even when
3510 * we don't explicitly enable it here.
3511 */
3512 if (udev->do_remote_wakeup) {
3513 status = usb_enable_remote_wakeup(udev);
3514 if (status) {
3515 dev_dbg(&udev->dev, "won't remote wakeup, status %d\n",
3516 status);
3517 /* bail if autosuspend is requested */
3518 if (PMSG_IS_AUTO(msg))
3519 goto err_wakeup;
3520 }
3521 }
3522
3523 /* disable USB2 hardware LPM */
3524 usb_disable_usb2_hardware_lpm(udev);
3525
3526 if (usb_disable_ltm(udev)) {
3527 dev_err(&udev->dev, "Failed to disable LTM before suspend\n");
3528 status = -ENOMEM;
3529 if (PMSG_IS_AUTO(msg))
3530 goto err_ltm;
3531 }
3532
3533 /* see 7.1.7.6 */
3534 if (hub_is_superspeed(hub->hdev))
3535 status = hub_set_port_link_state(hub, port1, USB_SS_PORT_LS_U3);
3536
3537 /*
3538 * For system suspend, we do not need to enable the suspend feature
3539 * on individual USB-2 ports. The devices will automatically go
3540 * into suspend a few ms after the root hub stops sending packets.
3541 * The USB 2.0 spec calls this "global suspend".
3542 *
3543 * However, many USB hubs have a bug: They don't relay wakeup requests
3544 * from a downstream port if the port's suspend feature isn't on.
3545 * Therefore we will turn on the suspend feature if udev or any of its
3546 * descendants is enabled for remote wakeup.
3547 */
3548 else if (PMSG_IS_AUTO(msg) || usb_wakeup_enabled_descendants(udev) > 0)
3549 status = set_port_feature(hub->hdev, port1,
3550 USB_PORT_FEAT_SUSPEND);
3551 else {
3552 really_suspend = false;
3553 status = 0;
3554 }
3555 if (status) {
3556 /* Check if the port has been suspended for the timeout case
3557 * to prevent the suspended port from incorrect handling.
3558 */
3559 if (status == -ETIMEDOUT) {
3560 int ret;
3561 u16 portstatus, portchange;
3562
3563 portstatus = portchange = 0;
3564 ret = usb_hub_port_status(hub, port1, &portstatus,
3565 &portchange);
3566
3567 dev_dbg(&port_dev->dev,
3568 "suspend timeout, status %04x\n", portstatus);
3569
3570 if (ret == 0 && port_is_suspended(hub, portstatus)) {
3571 status = 0;
3572 goto suspend_done;
3573 }
3574 }
3575
3576 dev_dbg(&port_dev->dev, "can't suspend, status %d\n", status);
3577
3578 /* Try to enable USB3 LTM again */
3579 usb_enable_ltm(udev);
3580 err_ltm:
3581 /* Try to enable USB2 hardware LPM again */
3582 usb_enable_usb2_hardware_lpm(udev);
3583
3584 if (udev->do_remote_wakeup)
3585 (void) usb_disable_remote_wakeup(udev);
3586 err_wakeup:
3587
3588 /* System sleep transitions should never fail */
3589 if (!PMSG_IS_AUTO(msg))
3590 status = 0;
3591 } else {
3592 suspend_done:
3593 dev_dbg(&udev->dev, "usb %ssuspend, wakeup %d\n",
3594 (PMSG_IS_AUTO(msg) ? "auto-" : ""),
3595 udev->do_remote_wakeup);
3596 if (really_suspend) {
3597 udev->port_is_suspended = 1;
3598
3599 /* device has up to 10 msec to fully suspend */
3600 msleep(10);
3601 }
3602 usb_set_device_state(udev, USB_STATE_SUSPENDED);
3603 }
3604
3605 if (status == 0 && !udev->do_remote_wakeup && udev->persist_enabled
3606 && test_and_clear_bit(port1, hub->child_usage_bits))
3607 pm_runtime_put_sync(&port_dev->dev);
3608
3609 usb_mark_last_busy(hub->hdev);
3610
3611 usb_unlock_port(port_dev);
3612 return status;
3613 }
3614
3615 /*
3616 * If the USB "suspend" state is in use (rather than "global suspend"),
3617 * many devices will be individually taken out of suspend state using
3618 * special "resume" signaling. This routine kicks in shortly after
3619 * hardware resume signaling is finished, either because of selective
3620 * resume (by host) or remote wakeup (by device) ... now see what changed
3621 * in the tree that's rooted at this device.
3622 *
3623 * If @udev->reset_resume is set then the device is reset before the
3624 * status check is done.
3625 */
finish_port_resume(struct usb_device * udev)3626 static int finish_port_resume(struct usb_device *udev)
3627 {
3628 int status = 0;
3629 u16 devstatus = 0;
3630
3631 /* caller owns the udev device lock */
3632 dev_dbg(&udev->dev, "%s\n",
3633 udev->reset_resume ? "finish reset-resume" : "finish resume");
3634
3635 /* usb ch9 identifies four variants of SUSPENDED, based on what
3636 * state the device resumes to. Linux currently won't see the
3637 * first two on the host side; they'd be inside hub_port_init()
3638 * during many timeouts, but hub_wq can't suspend until later.
3639 */
3640 usb_set_device_state(udev, udev->actconfig
3641 ? USB_STATE_CONFIGURED
3642 : USB_STATE_ADDRESS);
3643
3644 /* 10.5.4.5 says not to reset a suspended port if the attached
3645 * device is enabled for remote wakeup. Hence the reset
3646 * operation is carried out here, after the port has been
3647 * resumed.
3648 */
3649 if (udev->reset_resume) {
3650 /*
3651 * If the device morphs or switches modes when it is reset,
3652 * we don't want to perform a reset-resume. We'll fail the
3653 * resume, which will cause a logical disconnect, and then
3654 * the device will be rediscovered.
3655 */
3656 retry_reset_resume:
3657 if (udev->quirks & USB_QUIRK_RESET)
3658 status = -ENODEV;
3659 else
3660 status = usb_reset_and_verify_device(udev);
3661 }
3662
3663 /* 10.5.4.5 says be sure devices in the tree are still there.
3664 * For now let's assume the device didn't go crazy on resume,
3665 * and device drivers will know about any resume quirks.
3666 */
3667 if (status == 0) {
3668 devstatus = 0;
3669 status = usb_get_std_status(udev, USB_RECIP_DEVICE, 0, &devstatus);
3670
3671 /* If a normal resume failed, try doing a reset-resume */
3672 if (status && !udev->reset_resume && udev->persist_enabled) {
3673 dev_dbg(&udev->dev, "retry with reset-resume\n");
3674 udev->reset_resume = 1;
3675 goto retry_reset_resume;
3676 }
3677 }
3678
3679 if (status) {
3680 dev_dbg(&udev->dev, "gone after usb resume? status %d\n",
3681 status);
3682 /*
3683 * There are a few quirky devices which violate the standard
3684 * by claiming to have remote wakeup enabled after a reset,
3685 * which crash if the feature is cleared, hence check for
3686 * udev->reset_resume
3687 */
3688 } else if (udev->actconfig && !udev->reset_resume) {
3689 if (udev->speed < USB_SPEED_SUPER) {
3690 if (devstatus & (1 << USB_DEVICE_REMOTE_WAKEUP))
3691 status = usb_disable_remote_wakeup(udev);
3692 } else {
3693 status = usb_get_std_status(udev, USB_RECIP_INTERFACE, 0,
3694 &devstatus);
3695 if (!status && devstatus & (USB_INTRF_STAT_FUNC_RW_CAP
3696 | USB_INTRF_STAT_FUNC_RW))
3697 status = usb_disable_remote_wakeup(udev);
3698 }
3699
3700 if (status)
3701 dev_dbg(&udev->dev,
3702 "disable remote wakeup, status %d\n",
3703 status);
3704 status = 0;
3705 }
3706 return status;
3707 }
3708
3709 /*
3710 * There are some SS USB devices which take longer time for link training.
3711 * XHCI specs 4.19.4 says that when Link training is successful, port
3712 * sets CCS bit to 1. So if SW reads port status before successful link
3713 * training, then it will not find device to be present.
3714 * USB Analyzer log with such buggy devices show that in some cases
3715 * device switch on the RX termination after long delay of host enabling
3716 * the VBUS. In few other cases it has been seen that device fails to
3717 * negotiate link training in first attempt. It has been
3718 * reported till now that few devices take as long as 2000 ms to train
3719 * the link after host enabling its VBUS and termination. Following
3720 * routine implements a 2000 ms timeout for link training. If in a case
3721 * link trains before timeout, loop will exit earlier.
3722 *
3723 * There are also some 2.0 hard drive based devices and 3.0 thumb
3724 * drives that, when plugged into a 2.0 only port, take a long
3725 * time to set CCS after VBUS enable.
3726 *
3727 * FIXME: If a device was connected before suspend, but was removed
3728 * while system was asleep, then the loop in the following routine will
3729 * only exit at timeout.
3730 *
3731 * This routine should only be called when persist is enabled.
3732 */
wait_for_connected(struct usb_device * udev,struct usb_hub * hub,int port1,u16 * portchange,u16 * portstatus)3733 static int wait_for_connected(struct usb_device *udev,
3734 struct usb_hub *hub, int port1,
3735 u16 *portchange, u16 *portstatus)
3736 {
3737 int status = 0, delay_ms = 0;
3738
3739 while (delay_ms < 2000) {
3740 if (status || *portstatus & USB_PORT_STAT_CONNECTION)
3741 break;
3742 if (!usb_port_is_power_on(hub, *portstatus)) {
3743 status = -ENODEV;
3744 break;
3745 }
3746 msleep(20);
3747 delay_ms += 20;
3748 status = usb_hub_port_status(hub, port1, portstatus, portchange);
3749 }
3750 dev_dbg(&udev->dev, "Waited %dms for CONNECT\n", delay_ms);
3751 return status;
3752 }
3753
3754 /*
3755 * usb_port_resume - re-activate a suspended usb device's upstream port
3756 * @udev: device to re-activate, not a root hub
3757 * Context: must be able to sleep; device not locked; pm locks held
3758 *
3759 * This will re-activate the suspended device, increasing power usage
3760 * while letting drivers communicate again with its endpoints.
3761 * USB resume explicitly guarantees that the power session between
3762 * the host and the device is the same as it was when the device
3763 * suspended.
3764 *
3765 * If @udev->reset_resume is set then this routine won't check that the
3766 * port is still enabled. Furthermore, finish_port_resume() above will
3767 * reset @udev. The end result is that a broken power session can be
3768 * recovered and @udev will appear to persist across a loss of VBUS power.
3769 *
3770 * For example, if a host controller doesn't maintain VBUS suspend current
3771 * during a system sleep or is reset when the system wakes up, all the USB
3772 * power sessions below it will be broken. This is especially troublesome
3773 * for mass-storage devices containing mounted filesystems, since the
3774 * device will appear to have disconnected and all the memory mappings
3775 * to it will be lost. Using the USB_PERSIST facility, the device can be
3776 * made to appear as if it had not disconnected.
3777 *
3778 * This facility can be dangerous. Although usb_reset_and_verify_device() makes
3779 * every effort to insure that the same device is present after the
3780 * reset as before, it cannot provide a 100% guarantee. Furthermore it's
3781 * quite possible for a device to remain unaltered but its media to be
3782 * changed. If the user replaces a flash memory card while the system is
3783 * asleep, he will have only himself to blame when the filesystem on the
3784 * new card is corrupted and the system crashes.
3785 *
3786 * Returns 0 on success, else negative errno.
3787 */
usb_port_resume(struct usb_device * udev,pm_message_t msg)3788 int usb_port_resume(struct usb_device *udev, pm_message_t msg)
3789 {
3790 struct usb_hub *hub = usb_hub_to_struct_hub(udev->parent);
3791 struct usb_port *port_dev = hub->ports[udev->portnum - 1];
3792 int port1 = udev->portnum;
3793 int status;
3794 u16 portchange, portstatus;
3795
3796 if (!test_and_set_bit(port1, hub->child_usage_bits)) {
3797 status = pm_runtime_resume_and_get(&port_dev->dev);
3798 if (status < 0) {
3799 dev_dbg(&udev->dev, "can't resume usb port, status %d\n",
3800 status);
3801 return status;
3802 }
3803 }
3804
3805 usb_lock_port(port_dev);
3806
3807 /* Skip the initial Clear-Suspend step for a remote wakeup */
3808 status = usb_hub_port_status(hub, port1, &portstatus, &portchange);
3809 if (status == 0 && !port_is_suspended(hub, portstatus)) {
3810 if (portchange & USB_PORT_STAT_C_SUSPEND)
3811 pm_wakeup_event(&udev->dev, 0);
3812 goto SuspendCleared;
3813 }
3814
3815 /* see 7.1.7.7; affects power usage, but not budgeting */
3816 if (hub_is_superspeed(hub->hdev))
3817 status = hub_set_port_link_state(hub, port1, USB_SS_PORT_LS_U0);
3818 else
3819 status = usb_clear_port_feature(hub->hdev,
3820 port1, USB_PORT_FEAT_SUSPEND);
3821 if (status) {
3822 dev_dbg(&port_dev->dev, "can't resume, status %d\n", status);
3823 } else {
3824 /* drive resume for USB_RESUME_TIMEOUT msec */
3825 dev_dbg(&udev->dev, "usb %sresume\n",
3826 (PMSG_IS_AUTO(msg) ? "auto-" : ""));
3827 msleep(USB_RESUME_TIMEOUT);
3828
3829 /* Virtual root hubs can trigger on GET_PORT_STATUS to
3830 * stop resume signaling. Then finish the resume
3831 * sequence.
3832 */
3833 status = usb_hub_port_status(hub, port1, &portstatus, &portchange);
3834 }
3835
3836 SuspendCleared:
3837 if (status == 0) {
3838 udev->port_is_suspended = 0;
3839 if (hub_is_superspeed(hub->hdev)) {
3840 if (portchange & USB_PORT_STAT_C_LINK_STATE)
3841 usb_clear_port_feature(hub->hdev, port1,
3842 USB_PORT_FEAT_C_PORT_LINK_STATE);
3843 } else {
3844 if (portchange & USB_PORT_STAT_C_SUSPEND)
3845 usb_clear_port_feature(hub->hdev, port1,
3846 USB_PORT_FEAT_C_SUSPEND);
3847 }
3848
3849 /* TRSMRCY = 10 msec */
3850 msleep(10);
3851 }
3852
3853 if (udev->persist_enabled)
3854 status = wait_for_connected(udev, hub, port1, &portchange,
3855 &portstatus);
3856
3857 status = check_port_resume_type(udev,
3858 hub, port1, status, portchange, portstatus);
3859 if (status == 0)
3860 status = finish_port_resume(udev);
3861 if (status < 0) {
3862 dev_dbg(&udev->dev, "can't resume, status %d\n", status);
3863 hub_port_logical_disconnect(hub, port1);
3864 } else {
3865 /* Try to enable USB2 hardware LPM */
3866 usb_enable_usb2_hardware_lpm(udev);
3867
3868 /* Try to enable USB3 LTM */
3869 usb_enable_ltm(udev);
3870 }
3871
3872 usb_unlock_port(port_dev);
3873
3874 return status;
3875 }
3876
usb_remote_wakeup(struct usb_device * udev)3877 int usb_remote_wakeup(struct usb_device *udev)
3878 {
3879 int status = 0;
3880
3881 usb_lock_device(udev);
3882 if (udev->state == USB_STATE_SUSPENDED) {
3883 dev_dbg(&udev->dev, "usb %sresume\n", "wakeup-");
3884 status = usb_autoresume_device(udev);
3885 if (status == 0) {
3886 /* Let the drivers do their thing, then... */
3887 usb_autosuspend_device(udev);
3888 }
3889 }
3890 usb_unlock_device(udev);
3891 return status;
3892 }
3893
3894 /* Returns 1 if there was a remote wakeup and a connect status change. */
hub_handle_remote_wakeup(struct usb_hub * hub,unsigned int port,u16 portstatus,u16 portchange)3895 static int hub_handle_remote_wakeup(struct usb_hub *hub, unsigned int port,
3896 u16 portstatus, u16 portchange)
3897 __must_hold(&port_dev->status_lock)
3898 {
3899 struct usb_port *port_dev = hub->ports[port - 1];
3900 struct usb_device *hdev;
3901 struct usb_device *udev;
3902 int connect_change = 0;
3903 u16 link_state;
3904 int ret;
3905
3906 hdev = hub->hdev;
3907 udev = port_dev->child;
3908 if (!hub_is_superspeed(hdev)) {
3909 if (!(portchange & USB_PORT_STAT_C_SUSPEND))
3910 return 0;
3911 usb_clear_port_feature(hdev, port, USB_PORT_FEAT_C_SUSPEND);
3912 } else {
3913 link_state = portstatus & USB_PORT_STAT_LINK_STATE;
3914 if (!udev || udev->state != USB_STATE_SUSPENDED ||
3915 (link_state != USB_SS_PORT_LS_U0 &&
3916 link_state != USB_SS_PORT_LS_U1 &&
3917 link_state != USB_SS_PORT_LS_U2))
3918 return 0;
3919 }
3920
3921 if (udev) {
3922 /* TRSMRCY = 10 msec */
3923 msleep(10);
3924
3925 usb_unlock_port(port_dev);
3926 ret = usb_remote_wakeup(udev);
3927 usb_lock_port(port_dev);
3928 if (ret < 0)
3929 connect_change = 1;
3930 } else {
3931 ret = -ENODEV;
3932 hub_port_disable(hub, port, 1);
3933 }
3934 dev_dbg(&port_dev->dev, "resume, status %d\n", ret);
3935 return connect_change;
3936 }
3937
check_ports_changed(struct usb_hub * hub)3938 static int check_ports_changed(struct usb_hub *hub)
3939 {
3940 int port1;
3941
3942 for (port1 = 1; port1 <= hub->hdev->maxchild; ++port1) {
3943 u16 portstatus, portchange;
3944 int status;
3945
3946 status = usb_hub_port_status(hub, port1, &portstatus, &portchange);
3947 if (!status && portchange)
3948 return 1;
3949 }
3950 return 0;
3951 }
3952
hub_suspend(struct usb_interface * intf,pm_message_t msg)3953 static int hub_suspend(struct usb_interface *intf, pm_message_t msg)
3954 {
3955 struct usb_hub *hub = usb_get_intfdata(intf);
3956 struct usb_device *hdev = hub->hdev;
3957 unsigned port1;
3958
3959 /*
3960 * Warn if children aren't already suspended.
3961 * Also, add up the number of wakeup-enabled descendants.
3962 */
3963 hub->wakeup_enabled_descendants = 0;
3964 for (port1 = 1; port1 <= hdev->maxchild; port1++) {
3965 struct usb_port *port_dev = hub->ports[port1 - 1];
3966 struct usb_device *udev = port_dev->child;
3967
3968 if (udev && udev->can_submit) {
3969 dev_warn(&port_dev->dev, "device %s not suspended yet\n",
3970 dev_name(&udev->dev));
3971 if (PMSG_IS_AUTO(msg))
3972 return -EBUSY;
3973 }
3974 if (udev)
3975 hub->wakeup_enabled_descendants +=
3976 usb_wakeup_enabled_descendants(udev);
3977 }
3978
3979 if (hdev->do_remote_wakeup && hub->quirk_check_port_auto_suspend) {
3980 /* check if there are changes pending on hub ports */
3981 if (check_ports_changed(hub)) {
3982 if (PMSG_IS_AUTO(msg))
3983 return -EBUSY;
3984 pm_wakeup_event(&hdev->dev, 2000);
3985 }
3986 }
3987
3988 if (hub_is_superspeed(hdev) && hdev->do_remote_wakeup) {
3989 /* Enable hub to send remote wakeup for all ports. */
3990 for (port1 = 1; port1 <= hdev->maxchild; port1++) {
3991 set_port_feature(hdev,
3992 port1 |
3993 USB_PORT_FEAT_REMOTE_WAKE_CONNECT |
3994 USB_PORT_FEAT_REMOTE_WAKE_DISCONNECT |
3995 USB_PORT_FEAT_REMOTE_WAKE_OVER_CURRENT,
3996 USB_PORT_FEAT_REMOTE_WAKE_MASK);
3997 }
3998 }
3999
4000 dev_dbg(&intf->dev, "%s\n", __func__);
4001
4002 /* stop hub_wq and related activity */
4003 hub_quiesce(hub, HUB_SUSPEND);
4004 return 0;
4005 }
4006
4007 /* Report wakeup requests from the ports of a resuming root hub */
report_wakeup_requests(struct usb_hub * hub)4008 static void report_wakeup_requests(struct usb_hub *hub)
4009 {
4010 struct usb_device *hdev = hub->hdev;
4011 struct usb_device *udev;
4012 struct usb_hcd *hcd;
4013 unsigned long resuming_ports;
4014 int i;
4015
4016 if (hdev->parent)
4017 return; /* Not a root hub */
4018
4019 hcd = bus_to_hcd(hdev->bus);
4020 if (hcd->driver->get_resuming_ports) {
4021
4022 /*
4023 * The get_resuming_ports() method returns a bitmap (origin 0)
4024 * of ports which have started wakeup signaling but have not
4025 * yet finished resuming. During system resume we will
4026 * resume all the enabled ports, regardless of any wakeup
4027 * signals, which means the wakeup requests would be lost.
4028 * To prevent this, report them to the PM core here.
4029 */
4030 resuming_ports = hcd->driver->get_resuming_ports(hcd);
4031 for (i = 0; i < hdev->maxchild; ++i) {
4032 if (test_bit(i, &resuming_ports)) {
4033 udev = hub->ports[i]->child;
4034 if (udev)
4035 pm_wakeup_event(&udev->dev, 0);
4036 }
4037 }
4038 }
4039 }
4040
hub_resume(struct usb_interface * intf)4041 static int hub_resume(struct usb_interface *intf)
4042 {
4043 struct usb_hub *hub = usb_get_intfdata(intf);
4044
4045 dev_dbg(&intf->dev, "%s\n", __func__);
4046 hub_activate(hub, HUB_RESUME);
4047
4048 /*
4049 * This should be called only for system resume, not runtime resume.
4050 * We can't tell the difference here, so some wakeup requests will be
4051 * reported at the wrong time or more than once. This shouldn't
4052 * matter much, so long as they do get reported.
4053 */
4054 report_wakeup_requests(hub);
4055 return 0;
4056 }
4057
hub_reset_resume(struct usb_interface * intf)4058 static int hub_reset_resume(struct usb_interface *intf)
4059 {
4060 struct usb_hub *hub = usb_get_intfdata(intf);
4061
4062 dev_dbg(&intf->dev, "%s\n", __func__);
4063 hub_activate(hub, HUB_RESET_RESUME);
4064 return 0;
4065 }
4066
4067 /**
4068 * usb_root_hub_lost_power - called by HCD if the root hub lost Vbus power
4069 * @rhdev: struct usb_device for the root hub
4070 *
4071 * The USB host controller driver calls this function when its root hub
4072 * is resumed and Vbus power has been interrupted or the controller
4073 * has been reset. The routine marks @rhdev as having lost power.
4074 * When the hub driver is resumed it will take notice and carry out
4075 * power-session recovery for all the "USB-PERSIST"-enabled child devices;
4076 * the others will be disconnected.
4077 */
usb_root_hub_lost_power(struct usb_device * rhdev)4078 void usb_root_hub_lost_power(struct usb_device *rhdev)
4079 {
4080 dev_notice(&rhdev->dev, "root hub lost power or was reset\n");
4081 rhdev->reset_resume = 1;
4082 }
4083 EXPORT_SYMBOL_GPL(usb_root_hub_lost_power);
4084
4085 static const char * const usb3_lpm_names[] = {
4086 "U0",
4087 "U1",
4088 "U2",
4089 "U3",
4090 };
4091
4092 /*
4093 * Send a Set SEL control transfer to the device, prior to enabling
4094 * device-initiated U1 or U2. This lets the device know the exit latencies from
4095 * the time the device initiates a U1 or U2 exit, to the time it will receive a
4096 * packet from the host.
4097 *
4098 * This function will fail if the SEL or PEL values for udev are greater than
4099 * the maximum allowed values for the link state to be enabled.
4100 */
usb_req_set_sel(struct usb_device * udev)4101 static int usb_req_set_sel(struct usb_device *udev)
4102 {
4103 struct usb_set_sel_req *sel_values;
4104 unsigned long long u1_sel;
4105 unsigned long long u1_pel;
4106 unsigned long long u2_sel;
4107 unsigned long long u2_pel;
4108 int ret;
4109
4110 if (!udev->parent || udev->speed < USB_SPEED_SUPER || !udev->lpm_capable)
4111 return 0;
4112
4113 /* Convert SEL and PEL stored in ns to us */
4114 u1_sel = DIV_ROUND_UP(udev->u1_params.sel, 1000);
4115 u1_pel = DIV_ROUND_UP(udev->u1_params.pel, 1000);
4116 u2_sel = DIV_ROUND_UP(udev->u2_params.sel, 1000);
4117 u2_pel = DIV_ROUND_UP(udev->u2_params.pel, 1000);
4118
4119 /*
4120 * Make sure that the calculated SEL and PEL values for the link
4121 * state we're enabling aren't bigger than the max SEL/PEL
4122 * value that will fit in the SET SEL control transfer.
4123 * Otherwise the device would get an incorrect idea of the exit
4124 * latency for the link state, and could start a device-initiated
4125 * U1/U2 when the exit latencies are too high.
4126 */
4127 if (u1_sel > USB3_LPM_MAX_U1_SEL_PEL ||
4128 u1_pel > USB3_LPM_MAX_U1_SEL_PEL ||
4129 u2_sel > USB3_LPM_MAX_U2_SEL_PEL ||
4130 u2_pel > USB3_LPM_MAX_U2_SEL_PEL) {
4131 dev_dbg(&udev->dev, "Device-initiated U1/U2 disabled due to long SEL or PEL\n");
4132 return -EINVAL;
4133 }
4134
4135 /*
4136 * usb_enable_lpm() can be called as part of a failed device reset,
4137 * which may be initiated by an error path of a mass storage driver.
4138 * Therefore, use GFP_NOIO.
4139 */
4140 sel_values = kmalloc(sizeof *(sel_values), GFP_NOIO);
4141 if (!sel_values)
4142 return -ENOMEM;
4143
4144 sel_values->u1_sel = u1_sel;
4145 sel_values->u1_pel = u1_pel;
4146 sel_values->u2_sel = cpu_to_le16(u2_sel);
4147 sel_values->u2_pel = cpu_to_le16(u2_pel);
4148
4149 ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
4150 USB_REQ_SET_SEL,
4151 USB_RECIP_DEVICE,
4152 0, 0,
4153 sel_values, sizeof *(sel_values),
4154 USB_CTRL_SET_TIMEOUT);
4155 kfree(sel_values);
4156
4157 if (ret > 0)
4158 udev->lpm_devinit_allow = 1;
4159
4160 return ret;
4161 }
4162
4163 /*
4164 * Enable or disable device-initiated U1 or U2 transitions.
4165 */
usb_set_device_initiated_lpm(struct usb_device * udev,enum usb3_link_state state,bool enable)4166 static int usb_set_device_initiated_lpm(struct usb_device *udev,
4167 enum usb3_link_state state, bool enable)
4168 {
4169 int ret;
4170 int feature;
4171
4172 switch (state) {
4173 case USB3_LPM_U1:
4174 feature = USB_DEVICE_U1_ENABLE;
4175 break;
4176 case USB3_LPM_U2:
4177 feature = USB_DEVICE_U2_ENABLE;
4178 break;
4179 default:
4180 dev_warn(&udev->dev, "%s: Can't %s non-U1 or U2 state.\n",
4181 __func__, enable ? "enable" : "disable");
4182 return -EINVAL;
4183 }
4184
4185 if (udev->state != USB_STATE_CONFIGURED) {
4186 dev_dbg(&udev->dev, "%s: Can't %s %s state "
4187 "for unconfigured device.\n",
4188 __func__, enable ? "enable" : "disable",
4189 usb3_lpm_names[state]);
4190 return 0;
4191 }
4192
4193 if (enable) {
4194 /*
4195 * Now send the control transfer to enable device-initiated LPM
4196 * for either U1 or U2.
4197 */
4198 ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
4199 USB_REQ_SET_FEATURE,
4200 USB_RECIP_DEVICE,
4201 feature,
4202 0, NULL, 0,
4203 USB_CTRL_SET_TIMEOUT);
4204 } else {
4205 ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
4206 USB_REQ_CLEAR_FEATURE,
4207 USB_RECIP_DEVICE,
4208 feature,
4209 0, NULL, 0,
4210 USB_CTRL_SET_TIMEOUT);
4211 }
4212 if (ret < 0) {
4213 dev_warn(&udev->dev, "%s of device-initiated %s failed.\n",
4214 enable ? "Enable" : "Disable",
4215 usb3_lpm_names[state]);
4216 return -EBUSY;
4217 }
4218 return 0;
4219 }
4220
usb_set_lpm_timeout(struct usb_device * udev,enum usb3_link_state state,int timeout)4221 static int usb_set_lpm_timeout(struct usb_device *udev,
4222 enum usb3_link_state state, int timeout)
4223 {
4224 int ret;
4225 int feature;
4226
4227 switch (state) {
4228 case USB3_LPM_U1:
4229 feature = USB_PORT_FEAT_U1_TIMEOUT;
4230 break;
4231 case USB3_LPM_U2:
4232 feature = USB_PORT_FEAT_U2_TIMEOUT;
4233 break;
4234 default:
4235 dev_warn(&udev->dev, "%s: Can't set timeout for non-U1 or U2 state.\n",
4236 __func__);
4237 return -EINVAL;
4238 }
4239
4240 if (state == USB3_LPM_U1 && timeout > USB3_LPM_U1_MAX_TIMEOUT &&
4241 timeout != USB3_LPM_DEVICE_INITIATED) {
4242 dev_warn(&udev->dev, "Failed to set %s timeout to 0x%x, "
4243 "which is a reserved value.\n",
4244 usb3_lpm_names[state], timeout);
4245 return -EINVAL;
4246 }
4247
4248 ret = set_port_feature(udev->parent,
4249 USB_PORT_LPM_TIMEOUT(timeout) | udev->portnum,
4250 feature);
4251 if (ret < 0) {
4252 dev_warn(&udev->dev, "Failed to set %s timeout to 0x%x,"
4253 "error code %i\n", usb3_lpm_names[state],
4254 timeout, ret);
4255 return -EBUSY;
4256 }
4257 if (state == USB3_LPM_U1)
4258 udev->u1_params.timeout = timeout;
4259 else
4260 udev->u2_params.timeout = timeout;
4261 return 0;
4262 }
4263
4264 /*
4265 * Don't allow device intiated U1/U2 if the system exit latency + one bus
4266 * interval is greater than the minimum service interval of any active
4267 * periodic endpoint. See USB 3.2 section 9.4.9
4268 */
usb_device_may_initiate_lpm(struct usb_device * udev,enum usb3_link_state state)4269 static bool usb_device_may_initiate_lpm(struct usb_device *udev,
4270 enum usb3_link_state state)
4271 {
4272 unsigned int sel; /* us */
4273 int i, j;
4274
4275 if (!udev->lpm_devinit_allow)
4276 return false;
4277
4278 if (state == USB3_LPM_U1)
4279 sel = DIV_ROUND_UP(udev->u1_params.sel, 1000);
4280 else if (state == USB3_LPM_U2)
4281 sel = DIV_ROUND_UP(udev->u2_params.sel, 1000);
4282 else
4283 return false;
4284
4285 for (i = 0; i < udev->actconfig->desc.bNumInterfaces; i++) {
4286 struct usb_interface *intf;
4287 struct usb_endpoint_descriptor *desc;
4288 unsigned int interval;
4289
4290 intf = udev->actconfig->interface[i];
4291 if (!intf)
4292 continue;
4293
4294 for (j = 0; j < intf->cur_altsetting->desc.bNumEndpoints; j++) {
4295 desc = &intf->cur_altsetting->endpoint[j].desc;
4296
4297 if (usb_endpoint_xfer_int(desc) ||
4298 usb_endpoint_xfer_isoc(desc)) {
4299 interval = (1 << (desc->bInterval - 1)) * 125;
4300 if (sel + 125 > interval)
4301 return false;
4302 }
4303 }
4304 }
4305 return true;
4306 }
4307
4308 /*
4309 * Enable the hub-initiated U1/U2 idle timeouts, and enable device-initiated
4310 * U1/U2 entry.
4311 *
4312 * We will attempt to enable U1 or U2, but there are no guarantees that the
4313 * control transfers to set the hub timeout or enable device-initiated U1/U2
4314 * will be successful.
4315 *
4316 * If the control transfer to enable device-initiated U1/U2 entry fails, then
4317 * hub-initiated U1/U2 will be disabled.
4318 *
4319 * If we cannot set the parent hub U1/U2 timeout, we attempt to let the xHCI
4320 * driver know about it. If that call fails, it should be harmless, and just
4321 * take up more slightly more bus bandwidth for unnecessary U1/U2 exit latency.
4322 */
usb_enable_link_state(struct usb_hcd * hcd,struct usb_device * udev,enum usb3_link_state state)4323 static void usb_enable_link_state(struct usb_hcd *hcd, struct usb_device *udev,
4324 enum usb3_link_state state)
4325 {
4326 int timeout;
4327 __u8 u1_mel;
4328 __le16 u2_mel;
4329
4330 /* Skip if the device BOS descriptor couldn't be read */
4331 if (!udev->bos)
4332 return;
4333
4334 u1_mel = udev->bos->ss_cap->bU1devExitLat;
4335 u2_mel = udev->bos->ss_cap->bU2DevExitLat;
4336
4337 /* If the device says it doesn't have *any* exit latency to come out of
4338 * U1 or U2, it's probably lying. Assume it doesn't implement that link
4339 * state.
4340 */
4341 if ((state == USB3_LPM_U1 && u1_mel == 0) ||
4342 (state == USB3_LPM_U2 && u2_mel == 0))
4343 return;
4344
4345 /* We allow the host controller to set the U1/U2 timeout internally
4346 * first, so that it can change its schedule to account for the
4347 * additional latency to send data to a device in a lower power
4348 * link state.
4349 */
4350 timeout = hcd->driver->enable_usb3_lpm_timeout(hcd, udev, state);
4351
4352 /* xHCI host controller doesn't want to enable this LPM state. */
4353 if (timeout == 0)
4354 return;
4355
4356 if (timeout < 0) {
4357 dev_warn(&udev->dev, "Could not enable %s link state, "
4358 "xHCI error %i.\n", usb3_lpm_names[state],
4359 timeout);
4360 return;
4361 }
4362
4363 if (usb_set_lpm_timeout(udev, state, timeout)) {
4364 /* If we can't set the parent hub U1/U2 timeout,
4365 * device-initiated LPM won't be allowed either, so let the xHCI
4366 * host know that this link state won't be enabled.
4367 */
4368 hcd->driver->disable_usb3_lpm_timeout(hcd, udev, state);
4369 return;
4370 }
4371
4372 /* Only a configured device will accept the Set Feature
4373 * U1/U2_ENABLE
4374 */
4375 if (udev->actconfig &&
4376 usb_device_may_initiate_lpm(udev, state)) {
4377 if (usb_set_device_initiated_lpm(udev, state, true)) {
4378 /*
4379 * Request to enable device initiated U1/U2 failed,
4380 * better to turn off lpm in this case.
4381 */
4382 usb_set_lpm_timeout(udev, state, 0);
4383 hcd->driver->disable_usb3_lpm_timeout(hcd, udev, state);
4384 return;
4385 }
4386 }
4387
4388 if (state == USB3_LPM_U1)
4389 udev->usb3_lpm_u1_enabled = 1;
4390 else if (state == USB3_LPM_U2)
4391 udev->usb3_lpm_u2_enabled = 1;
4392 }
4393 /*
4394 * Disable the hub-initiated U1/U2 idle timeouts, and disable device-initiated
4395 * U1/U2 entry.
4396 *
4397 * If this function returns -EBUSY, the parent hub will still allow U1/U2 entry.
4398 * If zero is returned, the parent will not allow the link to go into U1/U2.
4399 *
4400 * If zero is returned, device-initiated U1/U2 entry may still be enabled, but
4401 * it won't have an effect on the bus link state because the parent hub will
4402 * still disallow device-initiated U1/U2 entry.
4403 *
4404 * If zero is returned, the xHCI host controller may still think U1/U2 entry is
4405 * possible. The result will be slightly more bus bandwidth will be taken up
4406 * (to account for U1/U2 exit latency), but it should be harmless.
4407 */
usb_disable_link_state(struct usb_hcd * hcd,struct usb_device * udev,enum usb3_link_state state)4408 static int usb_disable_link_state(struct usb_hcd *hcd, struct usb_device *udev,
4409 enum usb3_link_state state)
4410 {
4411 switch (state) {
4412 case USB3_LPM_U1:
4413 case USB3_LPM_U2:
4414 break;
4415 default:
4416 dev_warn(&udev->dev, "%s: Can't disable non-U1 or U2 state.\n",
4417 __func__);
4418 return -EINVAL;
4419 }
4420
4421 if (usb_set_lpm_timeout(udev, state, 0))
4422 return -EBUSY;
4423
4424 usb_set_device_initiated_lpm(udev, state, false);
4425
4426 if (hcd->driver->disable_usb3_lpm_timeout(hcd, udev, state))
4427 dev_warn(&udev->dev, "Could not disable xHCI %s timeout, "
4428 "bus schedule bandwidth may be impacted.\n",
4429 usb3_lpm_names[state]);
4430
4431 /* As soon as usb_set_lpm_timeout(0) return 0, hub initiated LPM
4432 * is disabled. Hub will disallows link to enter U1/U2 as well,
4433 * even device is initiating LPM. Hence LPM is disabled if hub LPM
4434 * timeout set to 0, no matter device-initiated LPM is disabled or
4435 * not.
4436 */
4437 if (state == USB3_LPM_U1)
4438 udev->usb3_lpm_u1_enabled = 0;
4439 else if (state == USB3_LPM_U2)
4440 udev->usb3_lpm_u2_enabled = 0;
4441
4442 return 0;
4443 }
4444
4445 /*
4446 * Disable hub-initiated and device-initiated U1 and U2 entry.
4447 * Caller must own the bandwidth_mutex.
4448 *
4449 * This will call usb_enable_lpm() on failure, which will decrement
4450 * lpm_disable_count, and will re-enable LPM if lpm_disable_count reaches zero.
4451 */
usb_disable_lpm(struct usb_device * udev)4452 int usb_disable_lpm(struct usb_device *udev)
4453 {
4454 struct usb_hcd *hcd;
4455
4456 if (!udev || !udev->parent ||
4457 udev->speed < USB_SPEED_SUPER ||
4458 !udev->lpm_capable ||
4459 udev->state < USB_STATE_CONFIGURED)
4460 return 0;
4461
4462 hcd = bus_to_hcd(udev->bus);
4463 if (!hcd || !hcd->driver->disable_usb3_lpm_timeout)
4464 return 0;
4465
4466 udev->lpm_disable_count++;
4467 if ((udev->u1_params.timeout == 0 && udev->u2_params.timeout == 0))
4468 return 0;
4469
4470 /* If LPM is enabled, attempt to disable it. */
4471 if (usb_disable_link_state(hcd, udev, USB3_LPM_U1))
4472 goto enable_lpm;
4473 if (usb_disable_link_state(hcd, udev, USB3_LPM_U2))
4474 goto enable_lpm;
4475
4476 return 0;
4477
4478 enable_lpm:
4479 usb_enable_lpm(udev);
4480 return -EBUSY;
4481 }
4482 EXPORT_SYMBOL_GPL(usb_disable_lpm);
4483
4484 /* Grab the bandwidth_mutex before calling usb_disable_lpm() */
usb_unlocked_disable_lpm(struct usb_device * udev)4485 int usb_unlocked_disable_lpm(struct usb_device *udev)
4486 {
4487 struct usb_hcd *hcd = bus_to_hcd(udev->bus);
4488 int ret;
4489
4490 if (!hcd)
4491 return -EINVAL;
4492
4493 mutex_lock(hcd->bandwidth_mutex);
4494 ret = usb_disable_lpm(udev);
4495 mutex_unlock(hcd->bandwidth_mutex);
4496
4497 return ret;
4498 }
4499 EXPORT_SYMBOL_GPL(usb_unlocked_disable_lpm);
4500
4501 /*
4502 * Attempt to enable device-initiated and hub-initiated U1 and U2 entry. The
4503 * xHCI host policy may prevent U1 or U2 from being enabled.
4504 *
4505 * Other callers may have disabled link PM, so U1 and U2 entry will be disabled
4506 * until the lpm_disable_count drops to zero. Caller must own the
4507 * bandwidth_mutex.
4508 */
usb_enable_lpm(struct usb_device * udev)4509 void usb_enable_lpm(struct usb_device *udev)
4510 {
4511 struct usb_hcd *hcd;
4512 struct usb_hub *hub;
4513 struct usb_port *port_dev;
4514
4515 if (!udev || !udev->parent ||
4516 udev->speed < USB_SPEED_SUPER ||
4517 !udev->lpm_capable ||
4518 udev->state < USB_STATE_CONFIGURED)
4519 return;
4520
4521 udev->lpm_disable_count--;
4522 hcd = bus_to_hcd(udev->bus);
4523 /* Double check that we can both enable and disable LPM.
4524 * Device must be configured to accept set feature U1/U2 timeout.
4525 */
4526 if (!hcd || !hcd->driver->enable_usb3_lpm_timeout ||
4527 !hcd->driver->disable_usb3_lpm_timeout)
4528 return;
4529
4530 if (udev->lpm_disable_count > 0)
4531 return;
4532
4533 hub = usb_hub_to_struct_hub(udev->parent);
4534 if (!hub)
4535 return;
4536
4537 port_dev = hub->ports[udev->portnum - 1];
4538
4539 if (port_dev->usb3_lpm_u1_permit)
4540 usb_enable_link_state(hcd, udev, USB3_LPM_U1);
4541
4542 if (port_dev->usb3_lpm_u2_permit)
4543 usb_enable_link_state(hcd, udev, USB3_LPM_U2);
4544 }
4545 EXPORT_SYMBOL_GPL(usb_enable_lpm);
4546
4547 /* Grab the bandwidth_mutex before calling usb_enable_lpm() */
usb_unlocked_enable_lpm(struct usb_device * udev)4548 void usb_unlocked_enable_lpm(struct usb_device *udev)
4549 {
4550 struct usb_hcd *hcd = bus_to_hcd(udev->bus);
4551
4552 if (!hcd)
4553 return;
4554
4555 mutex_lock(hcd->bandwidth_mutex);
4556 usb_enable_lpm(udev);
4557 mutex_unlock(hcd->bandwidth_mutex);
4558 }
4559 EXPORT_SYMBOL_GPL(usb_unlocked_enable_lpm);
4560
4561 /* usb3 devices use U3 for disabled, make sure remote wakeup is disabled */
hub_usb3_port_prepare_disable(struct usb_hub * hub,struct usb_port * port_dev)4562 static void hub_usb3_port_prepare_disable(struct usb_hub *hub,
4563 struct usb_port *port_dev)
4564 {
4565 struct usb_device *udev = port_dev->child;
4566 int ret;
4567
4568 if (udev && udev->port_is_suspended && udev->do_remote_wakeup) {
4569 ret = hub_set_port_link_state(hub, port_dev->portnum,
4570 USB_SS_PORT_LS_U0);
4571 if (!ret) {
4572 msleep(USB_RESUME_TIMEOUT);
4573 ret = usb_disable_remote_wakeup(udev);
4574 }
4575 if (ret)
4576 dev_warn(&udev->dev,
4577 "Port disable: can't disable remote wake\n");
4578 udev->do_remote_wakeup = 0;
4579 }
4580 }
4581
4582 #else /* CONFIG_PM */
4583
4584 #define hub_suspend NULL
4585 #define hub_resume NULL
4586 #define hub_reset_resume NULL
4587
hub_usb3_port_prepare_disable(struct usb_hub * hub,struct usb_port * port_dev)4588 static inline void hub_usb3_port_prepare_disable(struct usb_hub *hub,
4589 struct usb_port *port_dev) { }
4590
usb_disable_lpm(struct usb_device * udev)4591 int usb_disable_lpm(struct usb_device *udev)
4592 {
4593 return 0;
4594 }
4595 EXPORT_SYMBOL_GPL(usb_disable_lpm);
4596
usb_enable_lpm(struct usb_device * udev)4597 void usb_enable_lpm(struct usb_device *udev) { }
4598 EXPORT_SYMBOL_GPL(usb_enable_lpm);
4599
usb_unlocked_disable_lpm(struct usb_device * udev)4600 int usb_unlocked_disable_lpm(struct usb_device *udev)
4601 {
4602 return 0;
4603 }
4604 EXPORT_SYMBOL_GPL(usb_unlocked_disable_lpm);
4605
usb_unlocked_enable_lpm(struct usb_device * udev)4606 void usb_unlocked_enable_lpm(struct usb_device *udev) { }
4607 EXPORT_SYMBOL_GPL(usb_unlocked_enable_lpm);
4608
usb_disable_ltm(struct usb_device * udev)4609 int usb_disable_ltm(struct usb_device *udev)
4610 {
4611 return 0;
4612 }
4613 EXPORT_SYMBOL_GPL(usb_disable_ltm);
4614
usb_enable_ltm(struct usb_device * udev)4615 void usb_enable_ltm(struct usb_device *udev) { }
4616 EXPORT_SYMBOL_GPL(usb_enable_ltm);
4617
hub_handle_remote_wakeup(struct usb_hub * hub,unsigned int port,u16 portstatus,u16 portchange)4618 static int hub_handle_remote_wakeup(struct usb_hub *hub, unsigned int port,
4619 u16 portstatus, u16 portchange)
4620 {
4621 return 0;
4622 }
4623
usb_req_set_sel(struct usb_device * udev)4624 static int usb_req_set_sel(struct usb_device *udev)
4625 {
4626 return 0;
4627 }
4628
4629 #endif /* CONFIG_PM */
4630
4631 /*
4632 * USB-3 does not have a similar link state as USB-2 that will avoid negotiating
4633 * a connection with a plugged-in cable but will signal the host when the cable
4634 * is unplugged. Disable remote wake and set link state to U3 for USB-3 devices
4635 */
hub_port_disable(struct usb_hub * hub,int port1,int set_state)4636 static int hub_port_disable(struct usb_hub *hub, int port1, int set_state)
4637 {
4638 struct usb_port *port_dev = hub->ports[port1 - 1];
4639 struct usb_device *hdev = hub->hdev;
4640 int ret = 0;
4641
4642 if (!hub->error) {
4643 if (hub_is_superspeed(hub->hdev)) {
4644 hub_usb3_port_prepare_disable(hub, port_dev);
4645 ret = hub_set_port_link_state(hub, port_dev->portnum,
4646 USB_SS_PORT_LS_U3);
4647 } else {
4648 ret = usb_clear_port_feature(hdev, port1,
4649 USB_PORT_FEAT_ENABLE);
4650 }
4651 }
4652 if (port_dev->child && set_state)
4653 usb_set_device_state(port_dev->child, USB_STATE_NOTATTACHED);
4654 if (ret && ret != -ENODEV)
4655 dev_err(&port_dev->dev, "cannot disable (err = %d)\n", ret);
4656 return ret;
4657 }
4658
4659 /*
4660 * usb_port_disable - disable a usb device's upstream port
4661 * @udev: device to disable
4662 * Context: @udev locked, must be able to sleep.
4663 *
4664 * Disables a USB device that isn't in active use.
4665 */
usb_port_disable(struct usb_device * udev)4666 int usb_port_disable(struct usb_device *udev)
4667 {
4668 struct usb_hub *hub = usb_hub_to_struct_hub(udev->parent);
4669
4670 return hub_port_disable(hub, udev->portnum, 0);
4671 }
4672
4673 /* USB 2.0 spec, 7.1.7.3 / fig 7-29:
4674 *
4675 * Between connect detection and reset signaling there must be a delay
4676 * of 100ms at least for debounce and power-settling. The corresponding
4677 * timer shall restart whenever the downstream port detects a disconnect.
4678 *
4679 * Apparently there are some bluetooth and irda-dongles and a number of
4680 * low-speed devices for which this debounce period may last over a second.
4681 * Not covered by the spec - but easy to deal with.
4682 *
4683 * This implementation uses a 1500ms total debounce timeout; if the
4684 * connection isn't stable by then it returns -ETIMEDOUT. It checks
4685 * every 25ms for transient disconnects. When the port status has been
4686 * unchanged for 100ms it returns the port status.
4687 */
hub_port_debounce(struct usb_hub * hub,int port1,bool must_be_connected)4688 int hub_port_debounce(struct usb_hub *hub, int port1, bool must_be_connected)
4689 {
4690 int ret;
4691 u16 portchange, portstatus;
4692 unsigned connection = 0xffff;
4693 int total_time, stable_time = 0;
4694 struct usb_port *port_dev = hub->ports[port1 - 1];
4695
4696 for (total_time = 0; ; total_time += HUB_DEBOUNCE_STEP) {
4697 ret = usb_hub_port_status(hub, port1, &portstatus, &portchange);
4698 if (ret < 0)
4699 return ret;
4700
4701 if (!(portchange & USB_PORT_STAT_C_CONNECTION) &&
4702 (portstatus & USB_PORT_STAT_CONNECTION) == connection) {
4703 if (!must_be_connected ||
4704 (connection == USB_PORT_STAT_CONNECTION))
4705 stable_time += HUB_DEBOUNCE_STEP;
4706 if (stable_time >= HUB_DEBOUNCE_STABLE)
4707 break;
4708 } else {
4709 stable_time = 0;
4710 connection = portstatus & USB_PORT_STAT_CONNECTION;
4711 }
4712
4713 if (portchange & USB_PORT_STAT_C_CONNECTION) {
4714 usb_clear_port_feature(hub->hdev, port1,
4715 USB_PORT_FEAT_C_CONNECTION);
4716 }
4717
4718 if (total_time >= HUB_DEBOUNCE_TIMEOUT)
4719 break;
4720 msleep(HUB_DEBOUNCE_STEP);
4721 }
4722
4723 dev_dbg(&port_dev->dev, "debounce total %dms stable %dms status 0x%x\n",
4724 total_time, stable_time, portstatus);
4725
4726 if (stable_time < HUB_DEBOUNCE_STABLE)
4727 return -ETIMEDOUT;
4728 return portstatus;
4729 }
4730
usb_ep0_reinit(struct usb_device * udev)4731 void usb_ep0_reinit(struct usb_device *udev)
4732 {
4733 usb_disable_endpoint(udev, 0 + USB_DIR_IN, true);
4734 usb_disable_endpoint(udev, 0 + USB_DIR_OUT, true);
4735 usb_enable_endpoint(udev, &udev->ep0, true);
4736 }
4737 EXPORT_SYMBOL_GPL(usb_ep0_reinit);
4738
4739 #define usb_sndaddr0pipe() (PIPE_CONTROL << 30)
4740
hub_set_address(struct usb_device * udev,int devnum)4741 static int hub_set_address(struct usb_device *udev, int devnum)
4742 {
4743 int retval;
4744 unsigned int timeout_ms = USB_CTRL_SET_TIMEOUT;
4745 struct usb_hcd *hcd = bus_to_hcd(udev->bus);
4746 struct usb_hub *hub = usb_hub_to_struct_hub(udev->parent);
4747
4748 if (hub->hdev->quirks & USB_QUIRK_SHORT_SET_ADDRESS_REQ_TIMEOUT)
4749 timeout_ms = USB_SHORT_SET_ADDRESS_REQ_TIMEOUT;
4750
4751 /*
4752 * The host controller will choose the device address,
4753 * instead of the core having chosen it earlier
4754 */
4755 if (!hcd->driver->address_device && devnum <= 1)
4756 return -EINVAL;
4757 if (udev->state == USB_STATE_ADDRESS)
4758 return 0;
4759 if (udev->state != USB_STATE_DEFAULT)
4760 return -EINVAL;
4761 if (hcd->driver->address_device)
4762 retval = hcd->driver->address_device(hcd, udev, timeout_ms);
4763 else
4764 retval = usb_control_msg(udev, usb_sndaddr0pipe(),
4765 USB_REQ_SET_ADDRESS, 0, devnum, 0,
4766 NULL, 0, timeout_ms);
4767 if (retval == 0) {
4768 update_devnum(udev, devnum);
4769 /* Device now using proper address. */
4770 usb_set_device_state(udev, USB_STATE_ADDRESS);
4771 usb_ep0_reinit(udev);
4772 }
4773 return retval;
4774 }
4775
4776 /*
4777 * There are reports of USB 3.0 devices that say they support USB 2.0 Link PM
4778 * when they're plugged into a USB 2.0 port, but they don't work when LPM is
4779 * enabled.
4780 *
4781 * Only enable USB 2.0 Link PM if the port is internal (hardwired), or the
4782 * device says it supports the new USB 2.0 Link PM errata by setting the BESL
4783 * support bit in the BOS descriptor.
4784 */
hub_set_initial_usb2_lpm_policy(struct usb_device * udev)4785 static void hub_set_initial_usb2_lpm_policy(struct usb_device *udev)
4786 {
4787 struct usb_hub *hub = usb_hub_to_struct_hub(udev->parent);
4788 int connect_type = USB_PORT_CONNECT_TYPE_UNKNOWN;
4789
4790 if (!udev->usb2_hw_lpm_capable || !udev->bos)
4791 return;
4792
4793 if (hub)
4794 connect_type = hub->ports[udev->portnum - 1]->connect_type;
4795
4796 if ((udev->bos->ext_cap->bmAttributes & cpu_to_le32(USB_BESL_SUPPORT)) ||
4797 connect_type == USB_PORT_CONNECT_TYPE_HARD_WIRED) {
4798 udev->usb2_hw_lpm_allowed = 1;
4799 usb_enable_usb2_hardware_lpm(udev);
4800 }
4801 }
4802
hub_enable_device(struct usb_device * udev)4803 static int hub_enable_device(struct usb_device *udev)
4804 {
4805 struct usb_hcd *hcd = bus_to_hcd(udev->bus);
4806
4807 if (!hcd->driver->enable_device)
4808 return 0;
4809 if (udev->state == USB_STATE_ADDRESS)
4810 return 0;
4811 if (udev->state != USB_STATE_DEFAULT)
4812 return -EINVAL;
4813
4814 return hcd->driver->enable_device(hcd, udev);
4815 }
4816
4817 /*
4818 * Get the bMaxPacketSize0 value during initialization by reading the
4819 * device's device descriptor. Since we don't already know this value,
4820 * the transfer is unsafe and it ignores I/O errors, only testing for
4821 * reasonable received values.
4822 *
4823 * For "old scheme" initialization, size will be 8 so we read just the
4824 * start of the device descriptor, which should work okay regardless of
4825 * the actual bMaxPacketSize0 value. For "new scheme" initialization,
4826 * size will be 64 (and buf will point to a sufficiently large buffer),
4827 * which might not be kosher according to the USB spec but it's what
4828 * Windows does and what many devices expect.
4829 *
4830 * Returns: bMaxPacketSize0 or a negative error code.
4831 */
get_bMaxPacketSize0(struct usb_device * udev,struct usb_device_descriptor * buf,int size,bool first_time)4832 static int get_bMaxPacketSize0(struct usb_device *udev,
4833 struct usb_device_descriptor *buf, int size, bool first_time)
4834 {
4835 int i, rc;
4836
4837 /*
4838 * Retry on all errors; some devices are flakey.
4839 * 255 is for WUSB devices, we actually need to use
4840 * 512 (WUSB1.0[4.8.1]).
4841 */
4842 for (i = 0; i < GET_MAXPACKET0_TRIES; ++i) {
4843 /* Start with invalid values in case the transfer fails */
4844 buf->bDescriptorType = buf->bMaxPacketSize0 = 0;
4845 rc = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0),
4846 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
4847 USB_DT_DEVICE << 8, 0,
4848 buf, size,
4849 initial_descriptor_timeout);
4850 switch (buf->bMaxPacketSize0) {
4851 case 8: case 16: case 32: case 64: case 9:
4852 if (buf->bDescriptorType == USB_DT_DEVICE) {
4853 rc = buf->bMaxPacketSize0;
4854 break;
4855 }
4856 fallthrough;
4857 default:
4858 if (rc >= 0)
4859 rc = -EPROTO;
4860 break;
4861 }
4862
4863 /*
4864 * Some devices time out if they are powered on
4865 * when already connected. They need a second
4866 * reset, so return early. But only on the first
4867 * attempt, lest we get into a time-out/reset loop.
4868 */
4869 if (rc > 0 || (rc == -ETIMEDOUT && first_time &&
4870 udev->speed > USB_SPEED_FULL))
4871 break;
4872 }
4873 return rc;
4874 }
4875
4876 #define GET_DESCRIPTOR_BUFSIZE 64
4877
4878 /* Reset device, (re)assign address, get device descriptor.
4879 * Device connection must be stable, no more debouncing needed.
4880 * Returns device in USB_STATE_ADDRESS, except on error.
4881 *
4882 * If this is called for an already-existing device (as part of
4883 * usb_reset_and_verify_device), the caller must own the device lock and
4884 * the port lock. For a newly detected device that is not accessible
4885 * through any global pointers, it's not necessary to lock the device,
4886 * but it is still necessary to lock the port.
4887 *
4888 * For a newly detected device, @dev_descr must be NULL. The device
4889 * descriptor retrieved from the device will then be stored in
4890 * @udev->descriptor. For an already existing device, @dev_descr
4891 * must be non-NULL. The device descriptor will be stored there,
4892 * not in @udev->descriptor, because descriptors for registered
4893 * devices are meant to be immutable.
4894 */
4895 static int
hub_port_init(struct usb_hub * hub,struct usb_device * udev,int port1,int retry_counter,struct usb_device_descriptor * dev_descr)4896 hub_port_init(struct usb_hub *hub, struct usb_device *udev, int port1,
4897 int retry_counter, struct usb_device_descriptor *dev_descr)
4898 {
4899 struct usb_device *hdev = hub->hdev;
4900 struct usb_hcd *hcd = bus_to_hcd(hdev->bus);
4901 struct usb_port *port_dev = hub->ports[port1 - 1];
4902 int retries, operations, retval, i;
4903 unsigned delay = HUB_SHORT_RESET_TIME;
4904 enum usb_device_speed oldspeed = udev->speed;
4905 const char *speed;
4906 int devnum = udev->devnum;
4907 const char *driver_name;
4908 bool do_new_scheme;
4909 const bool initial = !dev_descr;
4910 int maxp0;
4911 struct usb_device_descriptor *buf, *descr;
4912
4913 buf = kmalloc(GET_DESCRIPTOR_BUFSIZE, GFP_NOIO);
4914 if (!buf)
4915 return -ENOMEM;
4916
4917 /* root hub ports have a slightly longer reset period
4918 * (from USB 2.0 spec, section 7.1.7.5)
4919 */
4920 if (!hdev->parent) {
4921 delay = HUB_ROOT_RESET_TIME;
4922 if (port1 == hdev->bus->otg_port)
4923 hdev->bus->b_hnp_enable = 0;
4924 }
4925
4926 /* Some low speed devices have problems with the quick delay, so */
4927 /* be a bit pessimistic with those devices. RHbug #23670 */
4928 if (oldspeed == USB_SPEED_LOW)
4929 delay = HUB_LONG_RESET_TIME;
4930
4931 /* Reset the device; full speed may morph to high speed */
4932 /* FIXME a USB 2.0 device may morph into SuperSpeed on reset. */
4933 retval = hub_port_reset(hub, port1, udev, delay, false);
4934 if (retval < 0) /* error or disconnect */
4935 goto fail;
4936 /* success, speed is known */
4937
4938 retval = -ENODEV;
4939
4940 /* Don't allow speed changes at reset, except usb 3.0 to faster */
4941 if (oldspeed != USB_SPEED_UNKNOWN && oldspeed != udev->speed &&
4942 !(oldspeed == USB_SPEED_SUPER && udev->speed > oldspeed)) {
4943 dev_dbg(&udev->dev, "device reset changed speed!\n");
4944 goto fail;
4945 }
4946 oldspeed = udev->speed;
4947
4948 if (initial) {
4949 /* USB 2.0 section 5.5.3 talks about ep0 maxpacket ...
4950 * it's fixed size except for full speed devices.
4951 */
4952 switch (udev->speed) {
4953 case USB_SPEED_SUPER_PLUS:
4954 case USB_SPEED_SUPER:
4955 udev->ep0.desc.wMaxPacketSize = cpu_to_le16(512);
4956 break;
4957 case USB_SPEED_HIGH: /* fixed at 64 */
4958 udev->ep0.desc.wMaxPacketSize = cpu_to_le16(64);
4959 break;
4960 case USB_SPEED_FULL: /* 8, 16, 32, or 64 */
4961 /* to determine the ep0 maxpacket size, try to read
4962 * the device descriptor to get bMaxPacketSize0 and
4963 * then correct our initial guess.
4964 */
4965 udev->ep0.desc.wMaxPacketSize = cpu_to_le16(64);
4966 break;
4967 case USB_SPEED_LOW: /* fixed at 8 */
4968 udev->ep0.desc.wMaxPacketSize = cpu_to_le16(8);
4969 break;
4970 default:
4971 goto fail;
4972 }
4973 }
4974
4975 speed = usb_speed_string(udev->speed);
4976
4977 /*
4978 * The controller driver may be NULL if the controller device
4979 * is the middle device between platform device and roothub.
4980 * This middle device may not need a device driver due to
4981 * all hardware control can be at platform device driver, this
4982 * platform device is usually a dual-role USB controller device.
4983 */
4984 if (udev->bus->controller->driver)
4985 driver_name = udev->bus->controller->driver->name;
4986 else
4987 driver_name = udev->bus->sysdev->driver->name;
4988
4989 if (udev->speed < USB_SPEED_SUPER)
4990 dev_info(&udev->dev,
4991 "%s %s USB device number %d using %s\n",
4992 (initial ? "new" : "reset"), speed,
4993 devnum, driver_name);
4994
4995 if (initial) {
4996 /* Set up TT records, if needed */
4997 if (hdev->tt) {
4998 udev->tt = hdev->tt;
4999 udev->ttport = hdev->ttport;
5000 } else if (udev->speed != USB_SPEED_HIGH
5001 && hdev->speed == USB_SPEED_HIGH) {
5002 if (!hub->tt.hub) {
5003 dev_err(&udev->dev, "parent hub has no TT\n");
5004 retval = -EINVAL;
5005 goto fail;
5006 }
5007 udev->tt = &hub->tt;
5008 udev->ttport = port1;
5009 }
5010 }
5011
5012 /* Why interleave GET_DESCRIPTOR and SET_ADDRESS this way?
5013 * Because device hardware and firmware is sometimes buggy in
5014 * this area, and this is how Linux has done it for ages.
5015 * Change it cautiously.
5016 *
5017 * NOTE: If use_new_scheme() is true we will start by issuing
5018 * a 64-byte GET_DESCRIPTOR request. This is what Windows does,
5019 * so it may help with some non-standards-compliant devices.
5020 * Otherwise we start with SET_ADDRESS and then try to read the
5021 * first 8 bytes of the device descriptor to get the ep0 maxpacket
5022 * value.
5023 */
5024 do_new_scheme = use_new_scheme(udev, retry_counter, port_dev);
5025
5026 for (retries = 0; retries < GET_DESCRIPTOR_TRIES; (++retries, msleep(100))) {
5027 if (hub_port_stop_enumerate(hub, port1, retries)) {
5028 retval = -ENODEV;
5029 break;
5030 }
5031
5032 if (do_new_scheme) {
5033 retval = hub_enable_device(udev);
5034 if (retval < 0) {
5035 dev_err(&udev->dev,
5036 "hub failed to enable device, error %d\n",
5037 retval);
5038 goto fail;
5039 }
5040
5041 maxp0 = get_bMaxPacketSize0(udev, buf,
5042 GET_DESCRIPTOR_BUFSIZE, retries == 0);
5043 if (maxp0 > 0 && !initial &&
5044 maxp0 != udev->descriptor.bMaxPacketSize0) {
5045 dev_err(&udev->dev, "device reset changed ep0 maxpacket size!\n");
5046 retval = -ENODEV;
5047 goto fail;
5048 }
5049
5050 retval = hub_port_reset(hub, port1, udev, delay, false);
5051 if (retval < 0) /* error or disconnect */
5052 goto fail;
5053 if (oldspeed != udev->speed) {
5054 dev_dbg(&udev->dev,
5055 "device reset changed speed!\n");
5056 retval = -ENODEV;
5057 goto fail;
5058 }
5059 if (maxp0 < 0) {
5060 if (maxp0 != -ENODEV)
5061 dev_err(&udev->dev, "device descriptor read/64, error %d\n",
5062 maxp0);
5063 retval = maxp0;
5064 continue;
5065 }
5066 }
5067
5068 for (operations = 0; operations < SET_ADDRESS_TRIES; ++operations) {
5069 retval = hub_set_address(udev, devnum);
5070 if (retval >= 0)
5071 break;
5072 msleep(200);
5073 }
5074 if (retval < 0) {
5075 if (retval != -ENODEV)
5076 dev_err(&udev->dev, "device not accepting address %d, error %d\n",
5077 devnum, retval);
5078 goto fail;
5079 }
5080 if (udev->speed >= USB_SPEED_SUPER) {
5081 devnum = udev->devnum;
5082 dev_info(&udev->dev,
5083 "%s SuperSpeed%s%s USB device number %d using %s\n",
5084 (udev->config) ? "reset" : "new",
5085 (udev->speed == USB_SPEED_SUPER_PLUS) ?
5086 " Plus" : "",
5087 (udev->ssp_rate == USB_SSP_GEN_2x2) ?
5088 " Gen 2x2" :
5089 (udev->ssp_rate == USB_SSP_GEN_2x1) ?
5090 " Gen 2x1" :
5091 (udev->ssp_rate == USB_SSP_GEN_1x2) ?
5092 " Gen 1x2" : "",
5093 devnum, driver_name);
5094 }
5095
5096 /*
5097 * cope with hardware quirkiness:
5098 * - let SET_ADDRESS settle, some device hardware wants it
5099 * - read ep0 maxpacket even for high and low speed,
5100 */
5101 msleep(10);
5102
5103 if (do_new_scheme)
5104 break;
5105
5106 maxp0 = get_bMaxPacketSize0(udev, buf, 8, retries == 0);
5107 if (maxp0 < 0) {
5108 retval = maxp0;
5109 if (retval != -ENODEV)
5110 dev_err(&udev->dev,
5111 "device descriptor read/8, error %d\n",
5112 retval);
5113 } else {
5114 u32 delay;
5115
5116 if (!initial && maxp0 != udev->descriptor.bMaxPacketSize0) {
5117 dev_err(&udev->dev, "device reset changed ep0 maxpacket size!\n");
5118 retval = -ENODEV;
5119 goto fail;
5120 }
5121
5122 delay = udev->parent->hub_delay;
5123 udev->hub_delay = min_t(u32, delay,
5124 USB_TP_TRANSMISSION_DELAY_MAX);
5125 retval = usb_set_isoch_delay(udev);
5126 if (retval) {
5127 dev_dbg(&udev->dev,
5128 "Failed set isoch delay, error %d\n",
5129 retval);
5130 retval = 0;
5131 }
5132 break;
5133 }
5134 }
5135 if (retval)
5136 goto fail;
5137
5138 /*
5139 * Check the ep0 maxpacket guess and correct it if necessary.
5140 * maxp0 is the value stored in the device descriptor;
5141 * i is the value it encodes (logarithmic for SuperSpeed or greater).
5142 */
5143 i = maxp0;
5144 if (udev->speed >= USB_SPEED_SUPER) {
5145 if (maxp0 <= 16)
5146 i = 1 << maxp0;
5147 else
5148 i = 0; /* Invalid */
5149 }
5150 if (usb_endpoint_maxp(&udev->ep0.desc) == i) {
5151 ; /* Initial ep0 maxpacket guess is right */
5152 } else if (((udev->speed == USB_SPEED_FULL ||
5153 udev->speed == USB_SPEED_HIGH) &&
5154 (i == 8 || i == 16 || i == 32 || i == 64)) ||
5155 (udev->speed >= USB_SPEED_SUPER && i > 0)) {
5156 /* Initial guess is wrong; use the descriptor's value */
5157 if (udev->speed == USB_SPEED_FULL)
5158 dev_dbg(&udev->dev, "ep0 maxpacket = %d\n", i);
5159 else
5160 dev_warn(&udev->dev, "Using ep0 maxpacket: %d\n", i);
5161 udev->ep0.desc.wMaxPacketSize = cpu_to_le16(i);
5162 usb_ep0_reinit(udev);
5163 } else {
5164 /* Initial guess is wrong and descriptor's value is invalid */
5165 dev_err(&udev->dev, "Invalid ep0 maxpacket: %d\n", maxp0);
5166 retval = -EMSGSIZE;
5167 goto fail;
5168 }
5169
5170 descr = usb_get_device_descriptor(udev);
5171 if (IS_ERR(descr)) {
5172 retval = PTR_ERR(descr);
5173 if (retval != -ENODEV)
5174 dev_err(&udev->dev, "device descriptor read/all, error %d\n",
5175 retval);
5176 goto fail;
5177 }
5178 if (initial)
5179 udev->descriptor = *descr;
5180 else
5181 *dev_descr = *descr;
5182 kfree(descr);
5183
5184 /*
5185 * Some superspeed devices have finished the link training process
5186 * and attached to a superspeed hub port, but the device descriptor
5187 * got from those devices show they aren't superspeed devices. Warm
5188 * reset the port attached by the devices can fix them.
5189 */
5190 if ((udev->speed >= USB_SPEED_SUPER) &&
5191 (le16_to_cpu(udev->descriptor.bcdUSB) < 0x0300)) {
5192 dev_err(&udev->dev, "got a wrong device descriptor, warm reset device\n");
5193 hub_port_reset(hub, port1, udev, HUB_BH_RESET_TIME, true);
5194 retval = -EINVAL;
5195 goto fail;
5196 }
5197
5198 usb_detect_quirks(udev);
5199
5200 if (le16_to_cpu(udev->descriptor.bcdUSB) >= 0x0201) {
5201 retval = usb_get_bos_descriptor(udev);
5202 if (!retval) {
5203 udev->lpm_capable = usb_device_supports_lpm(udev);
5204 udev->lpm_disable_count = 1;
5205 usb_set_lpm_parameters(udev);
5206 usb_req_set_sel(udev);
5207 }
5208 }
5209
5210 retval = 0;
5211 /* notify HCD that we have a device connected and addressed */
5212 if (hcd->driver->update_device)
5213 hcd->driver->update_device(hcd, udev);
5214 hub_set_initial_usb2_lpm_policy(udev);
5215 fail:
5216 if (retval) {
5217 hub_port_disable(hub, port1, 0);
5218 update_devnum(udev, devnum); /* for disconnect processing */
5219 }
5220 kfree(buf);
5221 return retval;
5222 }
5223
5224 static void
check_highspeed(struct usb_hub * hub,struct usb_device * udev,int port1)5225 check_highspeed(struct usb_hub *hub, struct usb_device *udev, int port1)
5226 {
5227 struct usb_qualifier_descriptor *qual;
5228 int status;
5229
5230 if (udev->quirks & USB_QUIRK_DEVICE_QUALIFIER)
5231 return;
5232
5233 qual = kmalloc(sizeof *qual, GFP_KERNEL);
5234 if (qual == NULL)
5235 return;
5236
5237 status = usb_get_descriptor(udev, USB_DT_DEVICE_QUALIFIER, 0,
5238 qual, sizeof *qual);
5239 if (status == sizeof *qual) {
5240 dev_info(&udev->dev, "not running at top speed; "
5241 "connect to a high speed hub\n");
5242 /* hub LEDs are probably harder to miss than syslog */
5243 if (hub->has_indicators) {
5244 hub->indicator[port1-1] = INDICATOR_GREEN_BLINK;
5245 queue_delayed_work(system_power_efficient_wq,
5246 &hub->leds, 0);
5247 }
5248 }
5249 kfree(qual);
5250 }
5251
5252 static unsigned
hub_power_remaining(struct usb_hub * hub)5253 hub_power_remaining(struct usb_hub *hub)
5254 {
5255 struct usb_device *hdev = hub->hdev;
5256 int remaining;
5257 int port1;
5258
5259 if (!hub->limited_power)
5260 return 0;
5261
5262 remaining = hdev->bus_mA - hub->descriptor->bHubContrCurrent;
5263 for (port1 = 1; port1 <= hdev->maxchild; ++port1) {
5264 struct usb_port *port_dev = hub->ports[port1 - 1];
5265 struct usb_device *udev = port_dev->child;
5266 unsigned unit_load;
5267 int delta;
5268
5269 if (!udev)
5270 continue;
5271 if (hub_is_superspeed(udev))
5272 unit_load = 150;
5273 else
5274 unit_load = 100;
5275
5276 /*
5277 * Unconfigured devices may not use more than one unit load,
5278 * or 8mA for OTG ports
5279 */
5280 if (udev->actconfig)
5281 delta = usb_get_max_power(udev, udev->actconfig);
5282 else if (port1 != udev->bus->otg_port || hdev->parent)
5283 delta = unit_load;
5284 else
5285 delta = 8;
5286 if (delta > hub->mA_per_port)
5287 dev_warn(&port_dev->dev, "%dmA is over %umA budget!\n",
5288 delta, hub->mA_per_port);
5289 remaining -= delta;
5290 }
5291 if (remaining < 0) {
5292 dev_warn(hub->intfdev, "%dmA over power budget!\n",
5293 -remaining);
5294 remaining = 0;
5295 }
5296 return remaining;
5297 }
5298
5299
descriptors_changed(struct usb_device * udev,struct usb_device_descriptor * new_device_descriptor,struct usb_host_bos * old_bos)5300 static int descriptors_changed(struct usb_device *udev,
5301 struct usb_device_descriptor *new_device_descriptor,
5302 struct usb_host_bos *old_bos)
5303 {
5304 int changed = 0;
5305 unsigned index;
5306 unsigned serial_len = 0;
5307 unsigned len;
5308 unsigned old_length;
5309 int length;
5310 char *buf;
5311
5312 if (memcmp(&udev->descriptor, new_device_descriptor,
5313 sizeof(*new_device_descriptor)) != 0)
5314 return 1;
5315
5316 if ((old_bos && !udev->bos) || (!old_bos && udev->bos))
5317 return 1;
5318 if (udev->bos) {
5319 len = le16_to_cpu(udev->bos->desc->wTotalLength);
5320 if (len != le16_to_cpu(old_bos->desc->wTotalLength))
5321 return 1;
5322 if (memcmp(udev->bos->desc, old_bos->desc, len))
5323 return 1;
5324 }
5325
5326 /* Since the idVendor, idProduct, and bcdDevice values in the
5327 * device descriptor haven't changed, we will assume the
5328 * Manufacturer and Product strings haven't changed either.
5329 * But the SerialNumber string could be different (e.g., a
5330 * different flash card of the same brand).
5331 */
5332 if (udev->serial)
5333 serial_len = strlen(udev->serial) + 1;
5334
5335 len = serial_len;
5336 for (index = 0; index < udev->descriptor.bNumConfigurations; index++) {
5337 old_length = le16_to_cpu(udev->config[index].desc.wTotalLength);
5338 len = max(len, old_length);
5339 }
5340
5341 buf = kmalloc(len, GFP_NOIO);
5342 if (!buf)
5343 /* assume the worst */
5344 return 1;
5345
5346 for (index = 0; index < udev->descriptor.bNumConfigurations; index++) {
5347 old_length = le16_to_cpu(udev->config[index].desc.wTotalLength);
5348 length = usb_get_descriptor(udev, USB_DT_CONFIG, index, buf,
5349 old_length);
5350 if (length != old_length) {
5351 dev_dbg(&udev->dev, "config index %d, error %d\n",
5352 index, length);
5353 changed = 1;
5354 break;
5355 }
5356 if (memcmp(buf, udev->rawdescriptors[index], old_length)
5357 != 0) {
5358 dev_dbg(&udev->dev, "config index %d changed (#%d)\n",
5359 index,
5360 ((struct usb_config_descriptor *) buf)->
5361 bConfigurationValue);
5362 changed = 1;
5363 break;
5364 }
5365 }
5366
5367 if (!changed && serial_len) {
5368 length = usb_string(udev, udev->descriptor.iSerialNumber,
5369 buf, serial_len);
5370 if (length + 1 != serial_len) {
5371 dev_dbg(&udev->dev, "serial string error %d\n",
5372 length);
5373 changed = 1;
5374 } else if (memcmp(buf, udev->serial, length) != 0) {
5375 dev_dbg(&udev->dev, "serial string changed\n");
5376 changed = 1;
5377 }
5378 }
5379
5380 kfree(buf);
5381 return changed;
5382 }
5383
hub_port_connect(struct usb_hub * hub,int port1,u16 portstatus,u16 portchange)5384 static void hub_port_connect(struct usb_hub *hub, int port1, u16 portstatus,
5385 u16 portchange)
5386 {
5387 int status = -ENODEV;
5388 int i;
5389 unsigned unit_load;
5390 struct usb_device *hdev = hub->hdev;
5391 struct usb_hcd *hcd = bus_to_hcd(hdev->bus);
5392 struct usb_port *port_dev = hub->ports[port1 - 1];
5393 struct usb_device *udev = port_dev->child;
5394 static int unreliable_port = -1;
5395 bool retry_locked;
5396
5397 /* Disconnect any existing devices under this port */
5398 if (udev) {
5399 if (hcd->usb_phy && !hdev->parent)
5400 usb_phy_notify_disconnect(hcd->usb_phy, udev->speed);
5401 usb_disconnect(&port_dev->child);
5402 }
5403
5404 /* We can forget about a "removed" device when there's a physical
5405 * disconnect or the connect status changes.
5406 */
5407 if (!(portstatus & USB_PORT_STAT_CONNECTION) ||
5408 (portchange & USB_PORT_STAT_C_CONNECTION))
5409 clear_bit(port1, hub->removed_bits);
5410
5411 if (portchange & (USB_PORT_STAT_C_CONNECTION |
5412 USB_PORT_STAT_C_ENABLE)) {
5413 status = hub_port_debounce_be_stable(hub, port1);
5414 if (status < 0) {
5415 if (status != -ENODEV &&
5416 port1 != unreliable_port &&
5417 printk_ratelimit())
5418 dev_err(&port_dev->dev, "connect-debounce failed\n");
5419 portstatus &= ~USB_PORT_STAT_CONNECTION;
5420 unreliable_port = port1;
5421 } else {
5422 portstatus = status;
5423 }
5424 }
5425
5426 /* Return now if debouncing failed or nothing is connected or
5427 * the device was "removed".
5428 */
5429 if (!(portstatus & USB_PORT_STAT_CONNECTION) ||
5430 test_bit(port1, hub->removed_bits)) {
5431
5432 /*
5433 * maybe switch power back on (e.g. root hub was reset)
5434 * but only if the port isn't owned by someone else.
5435 */
5436 if (hub_is_port_power_switchable(hub)
5437 && !usb_port_is_power_on(hub, portstatus)
5438 && !port_dev->port_owner)
5439 set_port_feature(hdev, port1, USB_PORT_FEAT_POWER);
5440
5441 if (portstatus & USB_PORT_STAT_ENABLE)
5442 goto done;
5443 return;
5444 }
5445 if (hub_is_superspeed(hub->hdev))
5446 unit_load = 150;
5447 else
5448 unit_load = 100;
5449
5450 status = 0;
5451
5452 for (i = 0; i < PORT_INIT_TRIES; i++) {
5453 if (hub_port_stop_enumerate(hub, port1, i)) {
5454 status = -ENODEV;
5455 break;
5456 }
5457
5458 usb_lock_port(port_dev);
5459 mutex_lock(hcd->address0_mutex);
5460 retry_locked = true;
5461 /* reallocate for each attempt, since references
5462 * to the previous one can escape in various ways
5463 */
5464 udev = usb_alloc_dev(hdev, hdev->bus, port1);
5465 if (!udev) {
5466 dev_err(&port_dev->dev,
5467 "couldn't allocate usb_device\n");
5468 mutex_unlock(hcd->address0_mutex);
5469 usb_unlock_port(port_dev);
5470 goto done;
5471 }
5472
5473 usb_set_device_state(udev, USB_STATE_POWERED);
5474 udev->bus_mA = hub->mA_per_port;
5475 udev->level = hdev->level + 1;
5476
5477 /* Devices connected to SuperSpeed hubs are USB 3.0 or later */
5478 if (hub_is_superspeed(hub->hdev))
5479 udev->speed = USB_SPEED_SUPER;
5480 else
5481 udev->speed = USB_SPEED_UNKNOWN;
5482
5483 choose_devnum(udev);
5484 if (udev->devnum <= 0) {
5485 status = -ENOTCONN; /* Don't retry */
5486 goto loop;
5487 }
5488
5489 /* reset (non-USB 3.0 devices) and get descriptor */
5490 status = hub_port_init(hub, udev, port1, i, NULL);
5491 if (status < 0)
5492 goto loop;
5493
5494 mutex_unlock(hcd->address0_mutex);
5495 usb_unlock_port(port_dev);
5496 retry_locked = false;
5497
5498 if (udev->quirks & USB_QUIRK_DELAY_INIT)
5499 msleep(2000);
5500
5501 /* consecutive bus-powered hubs aren't reliable; they can
5502 * violate the voltage drop budget. if the new child has
5503 * a "powered" LED, users should notice we didn't enable it
5504 * (without reading syslog), even without per-port LEDs
5505 * on the parent.
5506 */
5507 if (udev->descriptor.bDeviceClass == USB_CLASS_HUB
5508 && udev->bus_mA <= unit_load) {
5509 u16 devstat;
5510
5511 status = usb_get_std_status(udev, USB_RECIP_DEVICE, 0,
5512 &devstat);
5513 if (status) {
5514 dev_dbg(&udev->dev, "get status %d ?\n", status);
5515 goto loop_disable;
5516 }
5517 if ((devstat & (1 << USB_DEVICE_SELF_POWERED)) == 0) {
5518 dev_err(&udev->dev,
5519 "can't connect bus-powered hub "
5520 "to this port\n");
5521 if (hub->has_indicators) {
5522 hub->indicator[port1-1] =
5523 INDICATOR_AMBER_BLINK;
5524 queue_delayed_work(
5525 system_power_efficient_wq,
5526 &hub->leds, 0);
5527 }
5528 status = -ENOTCONN; /* Don't retry */
5529 goto loop_disable;
5530 }
5531 }
5532
5533 /* check for devices running slower than they could */
5534 if (le16_to_cpu(udev->descriptor.bcdUSB) >= 0x0200
5535 && udev->speed == USB_SPEED_FULL
5536 && highspeed_hubs != 0)
5537 check_highspeed(hub, udev, port1);
5538
5539 /* Store the parent's children[] pointer. At this point
5540 * udev becomes globally accessible, although presumably
5541 * no one will look at it until hdev is unlocked.
5542 */
5543 status = 0;
5544
5545 mutex_lock(&usb_port_peer_mutex);
5546
5547 /* We mustn't add new devices if the parent hub has
5548 * been disconnected; we would race with the
5549 * recursively_mark_NOTATTACHED() routine.
5550 */
5551 spin_lock_irq(&device_state_lock);
5552 if (hdev->state == USB_STATE_NOTATTACHED)
5553 status = -ENOTCONN;
5554 else
5555 port_dev->child = udev;
5556 spin_unlock_irq(&device_state_lock);
5557 mutex_unlock(&usb_port_peer_mutex);
5558
5559 /* Run it through the hoops (find a driver, etc) */
5560 if (!status) {
5561 status = usb_new_device(udev);
5562 if (status) {
5563 mutex_lock(&usb_port_peer_mutex);
5564 spin_lock_irq(&device_state_lock);
5565 port_dev->child = NULL;
5566 spin_unlock_irq(&device_state_lock);
5567 mutex_unlock(&usb_port_peer_mutex);
5568 } else {
5569 if (hcd->usb_phy && !hdev->parent)
5570 usb_phy_notify_connect(hcd->usb_phy,
5571 udev->speed);
5572 }
5573 }
5574
5575 if (status)
5576 goto loop_disable;
5577
5578 status = hub_power_remaining(hub);
5579 if (status)
5580 dev_dbg(hub->intfdev, "%dmA power budget left\n", status);
5581
5582 return;
5583
5584 loop_disable:
5585 hub_port_disable(hub, port1, 1);
5586 loop:
5587 usb_ep0_reinit(udev);
5588 release_devnum(udev);
5589 hub_free_dev(udev);
5590 if (retry_locked) {
5591 mutex_unlock(hcd->address0_mutex);
5592 usb_unlock_port(port_dev);
5593 }
5594 usb_put_dev(udev);
5595 if ((status == -ENOTCONN) || (status == -ENOTSUPP))
5596 break;
5597
5598 /* When halfway through our retry count, power-cycle the port */
5599 if (i == (PORT_INIT_TRIES - 1) / 2) {
5600 dev_info(&port_dev->dev, "attempt power cycle\n");
5601 usb_hub_set_port_power(hdev, hub, port1, false);
5602 msleep(2 * hub_power_on_good_delay(hub));
5603 usb_hub_set_port_power(hdev, hub, port1, true);
5604 msleep(hub_power_on_good_delay(hub));
5605 }
5606 }
5607 if (hub->hdev->parent ||
5608 !hcd->driver->port_handed_over ||
5609 !(hcd->driver->port_handed_over)(hcd, port1)) {
5610 if (status != -ENOTCONN && status != -ENODEV)
5611 dev_err(&port_dev->dev,
5612 "unable to enumerate USB device\n");
5613 }
5614
5615 done:
5616 hub_port_disable(hub, port1, 1);
5617 if (hcd->driver->relinquish_port && !hub->hdev->parent) {
5618 if (status != -ENOTCONN && status != -ENODEV)
5619 hcd->driver->relinquish_port(hcd, port1);
5620 }
5621 }
5622
5623 /* Handle physical or logical connection change events.
5624 * This routine is called when:
5625 * a port connection-change occurs;
5626 * a port enable-change occurs (often caused by EMI);
5627 * usb_reset_and_verify_device() encounters changed descriptors (as from
5628 * a firmware download)
5629 * caller already locked the hub
5630 */
hub_port_connect_change(struct usb_hub * hub,int port1,u16 portstatus,u16 portchange)5631 static void hub_port_connect_change(struct usb_hub *hub, int port1,
5632 u16 portstatus, u16 portchange)
5633 __must_hold(&port_dev->status_lock)
5634 {
5635 struct usb_port *port_dev = hub->ports[port1 - 1];
5636 struct usb_device *udev = port_dev->child;
5637 struct usb_device_descriptor *descr;
5638 int status = -ENODEV;
5639
5640 dev_dbg(&port_dev->dev, "status %04x, change %04x, %s\n", portstatus,
5641 portchange, portspeed(hub, portstatus));
5642
5643 if (hub->has_indicators) {
5644 set_port_led(hub, port1, HUB_LED_AUTO);
5645 hub->indicator[port1-1] = INDICATOR_AUTO;
5646 }
5647
5648 #ifdef CONFIG_USB_OTG
5649 /* during HNP, don't repeat the debounce */
5650 if (hub->hdev->bus->is_b_host)
5651 portchange &= ~(USB_PORT_STAT_C_CONNECTION |
5652 USB_PORT_STAT_C_ENABLE);
5653 #endif
5654
5655 /* Try to resuscitate an existing device */
5656 if ((portstatus & USB_PORT_STAT_CONNECTION) && udev &&
5657 udev->state != USB_STATE_NOTATTACHED) {
5658 if (portstatus & USB_PORT_STAT_ENABLE) {
5659 /*
5660 * USB-3 connections are initialized automatically by
5661 * the hostcontroller hardware. Therefore check for
5662 * changed device descriptors before resuscitating the
5663 * device.
5664 */
5665 descr = usb_get_device_descriptor(udev);
5666 if (IS_ERR(descr)) {
5667 dev_dbg(&udev->dev,
5668 "can't read device descriptor %ld\n",
5669 PTR_ERR(descr));
5670 } else {
5671 if (descriptors_changed(udev, descr,
5672 udev->bos)) {
5673 dev_dbg(&udev->dev,
5674 "device descriptor has changed\n");
5675 } else {
5676 status = 0; /* Nothing to do */
5677 }
5678 kfree(descr);
5679 }
5680 #ifdef CONFIG_PM
5681 } else if (udev->state == USB_STATE_SUSPENDED &&
5682 udev->persist_enabled) {
5683 /* For a suspended device, treat this as a
5684 * remote wakeup event.
5685 */
5686 usb_unlock_port(port_dev);
5687 status = usb_remote_wakeup(udev);
5688 usb_lock_port(port_dev);
5689 #endif
5690 } else {
5691 /* Don't resuscitate */;
5692 }
5693 }
5694 clear_bit(port1, hub->change_bits);
5695
5696 /* successfully revalidated the connection */
5697 if (status == 0)
5698 return;
5699
5700 usb_unlock_port(port_dev);
5701 hub_port_connect(hub, port1, portstatus, portchange);
5702 usb_lock_port(port_dev);
5703 }
5704
5705 /* Handle notifying userspace about hub over-current events */
port_over_current_notify(struct usb_port * port_dev)5706 static void port_over_current_notify(struct usb_port *port_dev)
5707 {
5708 char *envp[3] = { NULL, NULL, NULL };
5709 struct device *hub_dev;
5710 char *port_dev_path;
5711
5712 sysfs_notify(&port_dev->dev.kobj, NULL, "over_current_count");
5713
5714 hub_dev = port_dev->dev.parent;
5715
5716 if (!hub_dev)
5717 return;
5718
5719 port_dev_path = kobject_get_path(&port_dev->dev.kobj, GFP_KERNEL);
5720 if (!port_dev_path)
5721 return;
5722
5723 envp[0] = kasprintf(GFP_KERNEL, "OVER_CURRENT_PORT=%s", port_dev_path);
5724 if (!envp[0])
5725 goto exit;
5726
5727 envp[1] = kasprintf(GFP_KERNEL, "OVER_CURRENT_COUNT=%u",
5728 port_dev->over_current_count);
5729 if (!envp[1])
5730 goto exit;
5731
5732 kobject_uevent_env(&hub_dev->kobj, KOBJ_CHANGE, envp);
5733
5734 exit:
5735 kfree(envp[1]);
5736 kfree(envp[0]);
5737 kfree(port_dev_path);
5738 }
5739
port_event(struct usb_hub * hub,int port1)5740 static void port_event(struct usb_hub *hub, int port1)
5741 __must_hold(&port_dev->status_lock)
5742 {
5743 int connect_change;
5744 struct usb_port *port_dev = hub->ports[port1 - 1];
5745 struct usb_device *udev = port_dev->child;
5746 struct usb_device *hdev = hub->hdev;
5747 u16 portstatus, portchange;
5748 int i = 0;
5749 int err;
5750
5751 connect_change = test_bit(port1, hub->change_bits);
5752 clear_bit(port1, hub->event_bits);
5753 clear_bit(port1, hub->wakeup_bits);
5754
5755 if (usb_hub_port_status(hub, port1, &portstatus, &portchange) < 0)
5756 return;
5757
5758 if (portchange & USB_PORT_STAT_C_CONNECTION) {
5759 usb_clear_port_feature(hdev, port1, USB_PORT_FEAT_C_CONNECTION);
5760 connect_change = 1;
5761 }
5762
5763 if (portchange & USB_PORT_STAT_C_ENABLE) {
5764 if (!connect_change)
5765 dev_dbg(&port_dev->dev, "enable change, status %08x\n",
5766 portstatus);
5767 usb_clear_port_feature(hdev, port1, USB_PORT_FEAT_C_ENABLE);
5768
5769 /*
5770 * EM interference sometimes causes badly shielded USB devices
5771 * to be shutdown by the hub, this hack enables them again.
5772 * Works at least with mouse driver.
5773 */
5774 if (!(portstatus & USB_PORT_STAT_ENABLE)
5775 && !connect_change && udev) {
5776 dev_err(&port_dev->dev, "disabled by hub (EMI?), re-enabling...\n");
5777 connect_change = 1;
5778 }
5779 }
5780
5781 if (portchange & USB_PORT_STAT_C_OVERCURRENT) {
5782 u16 status = 0, unused;
5783 port_dev->over_current_count++;
5784 port_over_current_notify(port_dev);
5785
5786 dev_dbg(&port_dev->dev, "over-current change #%u\n",
5787 port_dev->over_current_count);
5788 usb_clear_port_feature(hdev, port1,
5789 USB_PORT_FEAT_C_OVER_CURRENT);
5790 msleep(100); /* Cool down */
5791 hub_power_on(hub, true);
5792 usb_hub_port_status(hub, port1, &status, &unused);
5793 if (status & USB_PORT_STAT_OVERCURRENT)
5794 dev_err(&port_dev->dev, "over-current condition\n");
5795 }
5796
5797 if (portchange & USB_PORT_STAT_C_RESET) {
5798 dev_dbg(&port_dev->dev, "reset change\n");
5799 usb_clear_port_feature(hdev, port1, USB_PORT_FEAT_C_RESET);
5800 }
5801 if ((portchange & USB_PORT_STAT_C_BH_RESET)
5802 && hub_is_superspeed(hdev)) {
5803 dev_dbg(&port_dev->dev, "warm reset change\n");
5804 usb_clear_port_feature(hdev, port1,
5805 USB_PORT_FEAT_C_BH_PORT_RESET);
5806 }
5807 if (portchange & USB_PORT_STAT_C_LINK_STATE) {
5808 dev_dbg(&port_dev->dev, "link state change\n");
5809 usb_clear_port_feature(hdev, port1,
5810 USB_PORT_FEAT_C_PORT_LINK_STATE);
5811 }
5812 if (portchange & USB_PORT_STAT_C_CONFIG_ERROR) {
5813 dev_warn(&port_dev->dev, "config error\n");
5814 usb_clear_port_feature(hdev, port1,
5815 USB_PORT_FEAT_C_PORT_CONFIG_ERROR);
5816 }
5817
5818 /* skip port actions that require the port to be powered on */
5819 if (!pm_runtime_active(&port_dev->dev))
5820 return;
5821
5822 /* skip port actions if ignore_event and early_stop are true */
5823 if (port_dev->ignore_event && port_dev->early_stop)
5824 return;
5825
5826 if (hub_handle_remote_wakeup(hub, port1, portstatus, portchange))
5827 connect_change = 1;
5828
5829 /*
5830 * Avoid trying to recover a USB3 SS.Inactive port with a warm reset if
5831 * the device was disconnected. A 12ms disconnect detect timer in
5832 * SS.Inactive state transitions the port to RxDetect automatically.
5833 * SS.Inactive link error state is common during device disconnect.
5834 */
5835 while (hub_port_warm_reset_required(hub, port1, portstatus)) {
5836 if ((i++ < DETECT_DISCONNECT_TRIES) && udev) {
5837 u16 unused;
5838
5839 msleep(20);
5840 usb_hub_port_status(hub, port1, &portstatus, &unused);
5841 dev_dbg(&port_dev->dev, "Wait for inactive link disconnect detect\n");
5842 continue;
5843 } else if (!udev || !(portstatus & USB_PORT_STAT_CONNECTION)
5844 || udev->state == USB_STATE_NOTATTACHED) {
5845 dev_dbg(&port_dev->dev, "do warm reset, port only\n");
5846 err = hub_port_reset(hub, port1, NULL,
5847 HUB_BH_RESET_TIME, true);
5848 if (!udev && err == -ENOTCONN)
5849 connect_change = 0;
5850 else if (err < 0)
5851 hub_port_disable(hub, port1, 1);
5852 } else {
5853 dev_dbg(&port_dev->dev, "do warm reset, full device\n");
5854 usb_unlock_port(port_dev);
5855 usb_lock_device(udev);
5856 usb_reset_device(udev);
5857 usb_unlock_device(udev);
5858 usb_lock_port(port_dev);
5859 connect_change = 0;
5860 }
5861 break;
5862 }
5863
5864 if (connect_change)
5865 hub_port_connect_change(hub, port1, portstatus, portchange);
5866 }
5867
hub_event(struct work_struct * work)5868 static void hub_event(struct work_struct *work)
5869 {
5870 struct usb_device *hdev;
5871 struct usb_interface *intf;
5872 struct usb_hub *hub;
5873 struct device *hub_dev;
5874 u16 hubstatus;
5875 u16 hubchange;
5876 int i, ret;
5877
5878 hub = container_of(work, struct usb_hub, events);
5879 hdev = hub->hdev;
5880 hub_dev = hub->intfdev;
5881 intf = to_usb_interface(hub_dev);
5882
5883 kcov_remote_start_usb((u64)hdev->bus->busnum);
5884
5885 dev_dbg(hub_dev, "state %d ports %d chg %04x evt %04x\n",
5886 hdev->state, hdev->maxchild,
5887 /* NOTE: expects max 15 ports... */
5888 (u16) hub->change_bits[0],
5889 (u16) hub->event_bits[0]);
5890
5891 /* Lock the device, then check to see if we were
5892 * disconnected while waiting for the lock to succeed. */
5893 usb_lock_device(hdev);
5894 if (unlikely(hub->disconnected))
5895 goto out_hdev_lock;
5896
5897 /* If the hub has died, clean up after it */
5898 if (hdev->state == USB_STATE_NOTATTACHED) {
5899 hub->error = -ENODEV;
5900 hub_quiesce(hub, HUB_DISCONNECT);
5901 goto out_hdev_lock;
5902 }
5903
5904 /* Autoresume */
5905 ret = usb_autopm_get_interface(intf);
5906 if (ret) {
5907 dev_dbg(hub_dev, "Can't autoresume: %d\n", ret);
5908 goto out_hdev_lock;
5909 }
5910
5911 /* If this is an inactive hub, do nothing */
5912 if (hub->quiescing)
5913 goto out_autopm;
5914
5915 if (hub->error) {
5916 dev_dbg(hub_dev, "resetting for error %d\n", hub->error);
5917
5918 ret = usb_reset_device(hdev);
5919 if (ret) {
5920 dev_dbg(hub_dev, "error resetting hub: %d\n", ret);
5921 goto out_autopm;
5922 }
5923
5924 hub->nerrors = 0;
5925 hub->error = 0;
5926 }
5927
5928 /* deal with port status changes */
5929 for (i = 1; i <= hdev->maxchild; i++) {
5930 struct usb_port *port_dev = hub->ports[i - 1];
5931
5932 if (test_bit(i, hub->event_bits)
5933 || test_bit(i, hub->change_bits)
5934 || test_bit(i, hub->wakeup_bits)) {
5935 /*
5936 * The get_noresume and barrier ensure that if
5937 * the port was in the process of resuming, we
5938 * flush that work and keep the port active for
5939 * the duration of the port_event(). However,
5940 * if the port is runtime pm suspended
5941 * (powered-off), we leave it in that state, run
5942 * an abbreviated port_event(), and move on.
5943 */
5944 pm_runtime_get_noresume(&port_dev->dev);
5945 pm_runtime_barrier(&port_dev->dev);
5946 usb_lock_port(port_dev);
5947 port_event(hub, i);
5948 usb_unlock_port(port_dev);
5949 pm_runtime_put_sync(&port_dev->dev);
5950 }
5951 }
5952
5953 /* deal with hub status changes */
5954 if (test_and_clear_bit(0, hub->event_bits) == 0)
5955 ; /* do nothing */
5956 else if (hub_hub_status(hub, &hubstatus, &hubchange) < 0)
5957 dev_err(hub_dev, "get_hub_status failed\n");
5958 else {
5959 if (hubchange & HUB_CHANGE_LOCAL_POWER) {
5960 dev_dbg(hub_dev, "power change\n");
5961 clear_hub_feature(hdev, C_HUB_LOCAL_POWER);
5962 if (hubstatus & HUB_STATUS_LOCAL_POWER)
5963 /* FIXME: Is this always true? */
5964 hub->limited_power = 1;
5965 else
5966 hub->limited_power = 0;
5967 }
5968 if (hubchange & HUB_CHANGE_OVERCURRENT) {
5969 u16 status = 0;
5970 u16 unused;
5971
5972 dev_dbg(hub_dev, "over-current change\n");
5973 clear_hub_feature(hdev, C_HUB_OVER_CURRENT);
5974 msleep(500); /* Cool down */
5975 hub_power_on(hub, true);
5976 hub_hub_status(hub, &status, &unused);
5977 if (status & HUB_STATUS_OVERCURRENT)
5978 dev_err(hub_dev, "over-current condition\n");
5979 }
5980 }
5981
5982 out_autopm:
5983 /* Balance the usb_autopm_get_interface() above */
5984 usb_autopm_put_interface_no_suspend(intf);
5985 out_hdev_lock:
5986 usb_unlock_device(hdev);
5987
5988 /* Balance the stuff in kick_hub_wq() and allow autosuspend */
5989 usb_autopm_put_interface(intf);
5990 hub_put(hub);
5991
5992 kcov_remote_stop();
5993 }
5994
5995 static const struct usb_device_id hub_id_table[] = {
5996 { .match_flags = USB_DEVICE_ID_MATCH_VENDOR
5997 | USB_DEVICE_ID_MATCH_PRODUCT
5998 | USB_DEVICE_ID_MATCH_INT_CLASS,
5999 .idVendor = USB_VENDOR_SMSC,
6000 .idProduct = USB_PRODUCT_USB5534B,
6001 .bInterfaceClass = USB_CLASS_HUB,
6002 .driver_info = HUB_QUIRK_DISABLE_AUTOSUSPEND},
6003 { .match_flags = USB_DEVICE_ID_MATCH_VENDOR
6004 | USB_DEVICE_ID_MATCH_PRODUCT,
6005 .idVendor = USB_VENDOR_CYPRESS,
6006 .idProduct = USB_PRODUCT_CY7C65632,
6007 .driver_info = HUB_QUIRK_DISABLE_AUTOSUSPEND},
6008 { .match_flags = USB_DEVICE_ID_MATCH_VENDOR
6009 | USB_DEVICE_ID_MATCH_INT_CLASS,
6010 .idVendor = USB_VENDOR_GENESYS_LOGIC,
6011 .bInterfaceClass = USB_CLASS_HUB,
6012 .driver_info = HUB_QUIRK_CHECK_PORT_AUTOSUSPEND},
6013 { .match_flags = USB_DEVICE_ID_MATCH_VENDOR
6014 | USB_DEVICE_ID_MATCH_PRODUCT,
6015 .idVendor = USB_VENDOR_TEXAS_INSTRUMENTS,
6016 .idProduct = USB_PRODUCT_TUSB8041_USB2,
6017 .driver_info = HUB_QUIRK_DISABLE_AUTOSUSPEND},
6018 { .match_flags = USB_DEVICE_ID_MATCH_VENDOR
6019 | USB_DEVICE_ID_MATCH_PRODUCT,
6020 .idVendor = USB_VENDOR_TEXAS_INSTRUMENTS,
6021 .idProduct = USB_PRODUCT_TUSB8041_USB3,
6022 .driver_info = HUB_QUIRK_DISABLE_AUTOSUSPEND},
6023 { .match_flags = USB_DEVICE_ID_MATCH_VENDOR
6024 | USB_DEVICE_ID_MATCH_PRODUCT,
6025 .idVendor = USB_VENDOR_MICROCHIP,
6026 .idProduct = USB_PRODUCT_USB4913,
6027 .driver_info = HUB_QUIRK_REDUCE_FRAME_INTR_BINTERVAL},
6028 { .match_flags = USB_DEVICE_ID_MATCH_VENDOR
6029 | USB_DEVICE_ID_MATCH_PRODUCT,
6030 .idVendor = USB_VENDOR_MICROCHIP,
6031 .idProduct = USB_PRODUCT_USB4914,
6032 .driver_info = HUB_QUIRK_REDUCE_FRAME_INTR_BINTERVAL},
6033 { .match_flags = USB_DEVICE_ID_MATCH_VENDOR
6034 | USB_DEVICE_ID_MATCH_PRODUCT,
6035 .idVendor = USB_VENDOR_MICROCHIP,
6036 .idProduct = USB_PRODUCT_USB4915,
6037 .driver_info = HUB_QUIRK_REDUCE_FRAME_INTR_BINTERVAL},
6038 { .match_flags = USB_DEVICE_ID_MATCH_DEV_CLASS,
6039 .bDeviceClass = USB_CLASS_HUB},
6040 { .match_flags = USB_DEVICE_ID_MATCH_INT_CLASS,
6041 .bInterfaceClass = USB_CLASS_HUB},
6042 { } /* Terminating entry */
6043 };
6044
6045 MODULE_DEVICE_TABLE(usb, hub_id_table);
6046
6047 static struct usb_driver hub_driver = {
6048 .name = "hub",
6049 .probe = hub_probe,
6050 .disconnect = hub_disconnect,
6051 .suspend = hub_suspend,
6052 .resume = hub_resume,
6053 .reset_resume = hub_reset_resume,
6054 .pre_reset = hub_pre_reset,
6055 .post_reset = hub_post_reset,
6056 .unlocked_ioctl = hub_ioctl,
6057 .id_table = hub_id_table,
6058 .supports_autosuspend = 1,
6059 };
6060
usb_hub_init(void)6061 int usb_hub_init(void)
6062 {
6063 if (usb_register(&hub_driver) < 0) {
6064 printk(KERN_ERR "%s: can't register hub driver\n",
6065 usbcore_name);
6066 return -1;
6067 }
6068
6069 /*
6070 * The workqueue needs to be freezable to avoid interfering with
6071 * USB-PERSIST port handover. Otherwise it might see that a full-speed
6072 * device was gone before the EHCI controller had handed its port
6073 * over to the companion full-speed controller.
6074 */
6075 hub_wq = alloc_workqueue("usb_hub_wq", WQ_FREEZABLE, 0);
6076 if (hub_wq)
6077 return 0;
6078
6079 /* Fall through if kernel_thread failed */
6080 usb_deregister(&hub_driver);
6081 pr_err("%s: can't allocate workqueue for usb hub\n", usbcore_name);
6082
6083 return -1;
6084 }
6085
usb_hub_cleanup(void)6086 void usb_hub_cleanup(void)
6087 {
6088 destroy_workqueue(hub_wq);
6089
6090 /*
6091 * Hub resources are freed for us by usb_deregister. It calls
6092 * usb_driver_purge on every device which in turn calls that
6093 * devices disconnect function if it is using this driver.
6094 * The hub_disconnect function takes care of releasing the
6095 * individual hub resources. -greg
6096 */
6097 usb_deregister(&hub_driver);
6098 } /* usb_hub_cleanup() */
6099
6100 /**
6101 * hub_hc_release_resources - clear resources used by host controller
6102 * @udev: pointer to device being released
6103 *
6104 * Context: task context, might sleep
6105 *
6106 * Function releases the host controller resources in correct order before
6107 * making any operation on resuming usb device. The host controller resources
6108 * allocated for devices in tree should be released starting from the last
6109 * usb device in tree toward the root hub. This function is used only during
6110 * resuming device when usb device require reinitialization – that is, when
6111 * flag udev->reset_resume is set.
6112 *
6113 * This call is synchronous, and may not be used in an interrupt context.
6114 */
hub_hc_release_resources(struct usb_device * udev)6115 static void hub_hc_release_resources(struct usb_device *udev)
6116 {
6117 struct usb_hub *hub = usb_hub_to_struct_hub(udev);
6118 struct usb_hcd *hcd = bus_to_hcd(udev->bus);
6119 int i;
6120
6121 /* Release up resources for all children before this device */
6122 for (i = 0; i < udev->maxchild; i++)
6123 if (hub->ports[i]->child)
6124 hub_hc_release_resources(hub->ports[i]->child);
6125
6126 if (hcd->driver->reset_device)
6127 hcd->driver->reset_device(hcd, udev);
6128 }
6129
6130 /**
6131 * usb_reset_and_verify_device - perform a USB port reset to reinitialize a device
6132 * @udev: device to reset (not in SUSPENDED or NOTATTACHED state)
6133 *
6134 * WARNING - don't use this routine to reset a composite device
6135 * (one with multiple interfaces owned by separate drivers)!
6136 * Use usb_reset_device() instead.
6137 *
6138 * Do a port reset, reassign the device's address, and establish its
6139 * former operating configuration. If the reset fails, or the device's
6140 * descriptors change from their values before the reset, or the original
6141 * configuration and altsettings cannot be restored, a flag will be set
6142 * telling hub_wq to pretend the device has been disconnected and then
6143 * re-connected. All drivers will be unbound, and the device will be
6144 * re-enumerated and probed all over again.
6145 *
6146 * Return: 0 if the reset succeeded, -ENODEV if the device has been
6147 * flagged for logical disconnection, or some other negative error code
6148 * if the reset wasn't even attempted.
6149 *
6150 * Note:
6151 * The caller must own the device lock and the port lock, the latter is
6152 * taken by usb_reset_device(). For example, it's safe to use
6153 * usb_reset_device() from a driver probe() routine after downloading
6154 * new firmware. For calls that might not occur during probe(), drivers
6155 * should lock the device using usb_lock_device_for_reset().
6156 *
6157 * Locking exception: This routine may also be called from within an
6158 * autoresume handler. Such usage won't conflict with other tasks
6159 * holding the device lock because these tasks should always call
6160 * usb_autopm_resume_device(), thereby preventing any unwanted
6161 * autoresume. The autoresume handler is expected to have already
6162 * acquired the port lock before calling this routine.
6163 */
usb_reset_and_verify_device(struct usb_device * udev)6164 static int usb_reset_and_verify_device(struct usb_device *udev)
6165 {
6166 struct usb_device *parent_hdev = udev->parent;
6167 struct usb_hub *parent_hub;
6168 struct usb_hcd *hcd = bus_to_hcd(udev->bus);
6169 struct usb_device_descriptor descriptor;
6170 struct usb_interface *intf;
6171 struct usb_host_bos *bos;
6172 int i, j, ret = 0;
6173 int port1 = udev->portnum;
6174
6175 if (udev->state == USB_STATE_NOTATTACHED ||
6176 udev->state == USB_STATE_SUSPENDED) {
6177 dev_dbg(&udev->dev, "device reset not allowed in state %d\n",
6178 udev->state);
6179 return -EINVAL;
6180 }
6181
6182 if (!parent_hdev)
6183 return -EISDIR;
6184
6185 parent_hub = usb_hub_to_struct_hub(parent_hdev);
6186
6187 /* Disable USB2 hardware LPM.
6188 * It will be re-enabled by the enumeration process.
6189 */
6190 usb_disable_usb2_hardware_lpm(udev);
6191
6192 bos = udev->bos;
6193 udev->bos = NULL;
6194
6195 if (udev->reset_resume)
6196 hub_hc_release_resources(udev);
6197
6198 mutex_lock(hcd->address0_mutex);
6199
6200 for (i = 0; i < PORT_INIT_TRIES; ++i) {
6201 if (hub_port_stop_enumerate(parent_hub, port1, i)) {
6202 ret = -ENODEV;
6203 break;
6204 }
6205
6206 /* ep0 maxpacket size may change; let the HCD know about it.
6207 * Other endpoints will be handled by re-enumeration. */
6208 usb_ep0_reinit(udev);
6209 ret = hub_port_init(parent_hub, udev, port1, i, &descriptor);
6210 if (ret >= 0 || ret == -ENOTCONN || ret == -ENODEV)
6211 break;
6212 }
6213 mutex_unlock(hcd->address0_mutex);
6214
6215 if (ret < 0)
6216 goto re_enumerate;
6217
6218 /* Device might have changed firmware (DFU or similar) */
6219 if (descriptors_changed(udev, &descriptor, bos)) {
6220 dev_info(&udev->dev, "device firmware changed\n");
6221 goto re_enumerate;
6222 }
6223
6224 /* Restore the device's previous configuration */
6225 if (!udev->actconfig)
6226 goto done;
6227
6228 /*
6229 * Some devices can't handle setting default altsetting 0 with a
6230 * Set-Interface request. Disable host-side endpoints of those
6231 * interfaces here. Enable and reset them back after host has set
6232 * its internal endpoint structures during usb_hcd_alloc_bandwith()
6233 */
6234 for (i = 0; i < udev->actconfig->desc.bNumInterfaces; i++) {
6235 intf = udev->actconfig->interface[i];
6236 if (intf->cur_altsetting->desc.bAlternateSetting == 0)
6237 usb_disable_interface(udev, intf, true);
6238 }
6239
6240 mutex_lock(hcd->bandwidth_mutex);
6241 ret = usb_hcd_alloc_bandwidth(udev, udev->actconfig, NULL, NULL);
6242 if (ret < 0) {
6243 dev_warn(&udev->dev,
6244 "Busted HC? Not enough HCD resources for "
6245 "old configuration.\n");
6246 mutex_unlock(hcd->bandwidth_mutex);
6247 goto re_enumerate;
6248 }
6249 ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
6250 USB_REQ_SET_CONFIGURATION, 0,
6251 udev->actconfig->desc.bConfigurationValue, 0,
6252 NULL, 0, USB_CTRL_SET_TIMEOUT);
6253 if (ret < 0) {
6254 dev_err(&udev->dev,
6255 "can't restore configuration #%d (error=%d)\n",
6256 udev->actconfig->desc.bConfigurationValue, ret);
6257 mutex_unlock(hcd->bandwidth_mutex);
6258 goto re_enumerate;
6259 }
6260 mutex_unlock(hcd->bandwidth_mutex);
6261 usb_set_device_state(udev, USB_STATE_CONFIGURED);
6262
6263 /* Put interfaces back into the same altsettings as before.
6264 * Don't bother to send the Set-Interface request for interfaces
6265 * that were already in altsetting 0; besides being unnecessary,
6266 * many devices can't handle it. Instead just reset the host-side
6267 * endpoint state.
6268 */
6269 for (i = 0; i < udev->actconfig->desc.bNumInterfaces; i++) {
6270 struct usb_host_config *config = udev->actconfig;
6271 struct usb_interface_descriptor *desc;
6272
6273 intf = config->interface[i];
6274 desc = &intf->cur_altsetting->desc;
6275 if (desc->bAlternateSetting == 0) {
6276 usb_enable_interface(udev, intf, true);
6277 ret = 0;
6278 } else {
6279 /* Let the bandwidth allocation function know that this
6280 * device has been reset, and it will have to use
6281 * alternate setting 0 as the current alternate setting.
6282 */
6283 intf->resetting_device = 1;
6284 ret = usb_set_interface(udev, desc->bInterfaceNumber,
6285 desc->bAlternateSetting);
6286 intf->resetting_device = 0;
6287 }
6288 if (ret < 0) {
6289 dev_err(&udev->dev, "failed to restore interface %d "
6290 "altsetting %d (error=%d)\n",
6291 desc->bInterfaceNumber,
6292 desc->bAlternateSetting,
6293 ret);
6294 goto re_enumerate;
6295 }
6296 /* Resetting also frees any allocated streams */
6297 for (j = 0; j < intf->cur_altsetting->desc.bNumEndpoints; j++)
6298 intf->cur_altsetting->endpoint[j].streams = 0;
6299 }
6300
6301 done:
6302 /* Now that the alt settings are re-installed, enable LTM and LPM. */
6303 usb_enable_usb2_hardware_lpm(udev);
6304 usb_unlocked_enable_lpm(udev);
6305 usb_enable_ltm(udev);
6306 usb_release_bos_descriptor(udev);
6307 udev->bos = bos;
6308 return 0;
6309
6310 re_enumerate:
6311 usb_release_bos_descriptor(udev);
6312 udev->bos = bos;
6313 hub_port_logical_disconnect(parent_hub, port1);
6314 return -ENODEV;
6315 }
6316
6317 /**
6318 * usb_reset_device - warn interface drivers and perform a USB port reset
6319 * @udev: device to reset (not in NOTATTACHED state)
6320 *
6321 * Warns all drivers bound to registered interfaces (using their pre_reset
6322 * method), performs the port reset, and then lets the drivers know that
6323 * the reset is over (using their post_reset method).
6324 *
6325 * Return: The same as for usb_reset_and_verify_device().
6326 * However, if a reset is already in progress (for instance, if a
6327 * driver doesn't have pre_reset() or post_reset() callbacks, and while
6328 * being unbound or re-bound during the ongoing reset its disconnect()
6329 * or probe() routine tries to perform a second, nested reset), the
6330 * routine returns -EINPROGRESS.
6331 *
6332 * Note:
6333 * The caller must own the device lock. For example, it's safe to use
6334 * this from a driver probe() routine after downloading new firmware.
6335 * For calls that might not occur during probe(), drivers should lock
6336 * the device using usb_lock_device_for_reset().
6337 *
6338 * If an interface is currently being probed or disconnected, we assume
6339 * its driver knows how to handle resets. For all other interfaces,
6340 * if the driver doesn't have pre_reset and post_reset methods then
6341 * we attempt to unbind it and rebind afterward.
6342 */
usb_reset_device(struct usb_device * udev)6343 int usb_reset_device(struct usb_device *udev)
6344 {
6345 int ret;
6346 int i;
6347 unsigned int noio_flag;
6348 struct usb_port *port_dev;
6349 struct usb_host_config *config = udev->actconfig;
6350 struct usb_hub *hub = usb_hub_to_struct_hub(udev->parent);
6351
6352 if (udev->state == USB_STATE_NOTATTACHED) {
6353 dev_dbg(&udev->dev, "device reset not allowed in state %d\n",
6354 udev->state);
6355 return -EINVAL;
6356 }
6357
6358 if (!udev->parent) {
6359 /* this requires hcd-specific logic; see ohci_restart() */
6360 dev_dbg(&udev->dev, "%s for root hub!\n", __func__);
6361 return -EISDIR;
6362 }
6363
6364 if (udev->reset_in_progress)
6365 return -EINPROGRESS;
6366 udev->reset_in_progress = 1;
6367
6368 port_dev = hub->ports[udev->portnum - 1];
6369
6370 /*
6371 * Don't allocate memory with GFP_KERNEL in current
6372 * context to avoid possible deadlock if usb mass
6373 * storage interface or usbnet interface(iSCSI case)
6374 * is included in current configuration. The easist
6375 * approach is to do it for every device reset,
6376 * because the device 'memalloc_noio' flag may have
6377 * not been set before reseting the usb device.
6378 */
6379 noio_flag = memalloc_noio_save();
6380
6381 /* Prevent autosuspend during the reset */
6382 usb_autoresume_device(udev);
6383
6384 if (config) {
6385 for (i = 0; i < config->desc.bNumInterfaces; ++i) {
6386 struct usb_interface *cintf = config->interface[i];
6387 struct usb_driver *drv;
6388 int unbind = 0;
6389
6390 if (cintf->dev.driver) {
6391 drv = to_usb_driver(cintf->dev.driver);
6392 if (drv->pre_reset && drv->post_reset)
6393 unbind = (drv->pre_reset)(cintf);
6394 else if (cintf->condition ==
6395 USB_INTERFACE_BOUND)
6396 unbind = 1;
6397 if (unbind)
6398 usb_forced_unbind_intf(cintf);
6399 }
6400 }
6401 }
6402
6403 usb_lock_port(port_dev);
6404 ret = usb_reset_and_verify_device(udev);
6405 usb_unlock_port(port_dev);
6406
6407 if (config) {
6408 for (i = config->desc.bNumInterfaces - 1; i >= 0; --i) {
6409 struct usb_interface *cintf = config->interface[i];
6410 struct usb_driver *drv;
6411 int rebind = cintf->needs_binding;
6412
6413 if (!rebind && cintf->dev.driver) {
6414 drv = to_usb_driver(cintf->dev.driver);
6415 if (drv->post_reset)
6416 rebind = (drv->post_reset)(cintf);
6417 else if (cintf->condition ==
6418 USB_INTERFACE_BOUND)
6419 rebind = 1;
6420 if (rebind)
6421 cintf->needs_binding = 1;
6422 }
6423 }
6424
6425 /* If the reset failed, hub_wq will unbind drivers later */
6426 if (ret == 0)
6427 usb_unbind_and_rebind_marked_interfaces(udev);
6428 }
6429
6430 usb_autosuspend_device(udev);
6431 memalloc_noio_restore(noio_flag);
6432 udev->reset_in_progress = 0;
6433 return ret;
6434 }
6435 EXPORT_SYMBOL_GPL(usb_reset_device);
6436
6437
6438 /**
6439 * usb_queue_reset_device - Reset a USB device from an atomic context
6440 * @iface: USB interface belonging to the device to reset
6441 *
6442 * This function can be used to reset a USB device from an atomic
6443 * context, where usb_reset_device() won't work (as it blocks).
6444 *
6445 * Doing a reset via this method is functionally equivalent to calling
6446 * usb_reset_device(), except for the fact that it is delayed to a
6447 * workqueue. This means that any drivers bound to other interfaces
6448 * might be unbound, as well as users from usbfs in user space.
6449 *
6450 * Corner cases:
6451 *
6452 * - Scheduling two resets at the same time from two different drivers
6453 * attached to two different interfaces of the same device is
6454 * possible; depending on how the driver attached to each interface
6455 * handles ->pre_reset(), the second reset might happen or not.
6456 *
6457 * - If the reset is delayed so long that the interface is unbound from
6458 * its driver, the reset will be skipped.
6459 *
6460 * - This function can be called during .probe(). It can also be called
6461 * during .disconnect(), but doing so is pointless because the reset
6462 * will not occur. If you really want to reset the device during
6463 * .disconnect(), call usb_reset_device() directly -- but watch out
6464 * for nested unbinding issues!
6465 */
usb_queue_reset_device(struct usb_interface * iface)6466 void usb_queue_reset_device(struct usb_interface *iface)
6467 {
6468 if (schedule_work(&iface->reset_ws))
6469 usb_get_intf(iface);
6470 }
6471 EXPORT_SYMBOL_GPL(usb_queue_reset_device);
6472
6473 /**
6474 * usb_hub_find_child - Get the pointer of child device
6475 * attached to the port which is specified by @port1.
6476 * @hdev: USB device belonging to the usb hub
6477 * @port1: port num to indicate which port the child device
6478 * is attached to.
6479 *
6480 * USB drivers call this function to get hub's child device
6481 * pointer.
6482 *
6483 * Return: %NULL if input param is invalid and
6484 * child's usb_device pointer if non-NULL.
6485 */
usb_hub_find_child(struct usb_device * hdev,int port1)6486 struct usb_device *usb_hub_find_child(struct usb_device *hdev,
6487 int port1)
6488 {
6489 struct usb_hub *hub = usb_hub_to_struct_hub(hdev);
6490
6491 if (port1 < 1 || port1 > hdev->maxchild)
6492 return NULL;
6493 return hub->ports[port1 - 1]->child;
6494 }
6495 EXPORT_SYMBOL_GPL(usb_hub_find_child);
6496
usb_hub_adjust_deviceremovable(struct usb_device * hdev,struct usb_hub_descriptor * desc)6497 void usb_hub_adjust_deviceremovable(struct usb_device *hdev,
6498 struct usb_hub_descriptor *desc)
6499 {
6500 struct usb_hub *hub = usb_hub_to_struct_hub(hdev);
6501 enum usb_port_connect_type connect_type;
6502 int i;
6503
6504 if (!hub)
6505 return;
6506
6507 if (!hub_is_superspeed(hdev)) {
6508 for (i = 1; i <= hdev->maxchild; i++) {
6509 struct usb_port *port_dev = hub->ports[i - 1];
6510
6511 connect_type = port_dev->connect_type;
6512 if (connect_type == USB_PORT_CONNECT_TYPE_HARD_WIRED) {
6513 u8 mask = 1 << (i%8);
6514
6515 if (!(desc->u.hs.DeviceRemovable[i/8] & mask)) {
6516 dev_dbg(&port_dev->dev, "DeviceRemovable is changed to 1 according to platform information.\n");
6517 desc->u.hs.DeviceRemovable[i/8] |= mask;
6518 }
6519 }
6520 }
6521 } else {
6522 u16 port_removable = le16_to_cpu(desc->u.ss.DeviceRemovable);
6523
6524 for (i = 1; i <= hdev->maxchild; i++) {
6525 struct usb_port *port_dev = hub->ports[i - 1];
6526
6527 connect_type = port_dev->connect_type;
6528 if (connect_type == USB_PORT_CONNECT_TYPE_HARD_WIRED) {
6529 u16 mask = 1 << i;
6530
6531 if (!(port_removable & mask)) {
6532 dev_dbg(&port_dev->dev, "DeviceRemovable is changed to 1 according to platform information.\n");
6533 port_removable |= mask;
6534 }
6535 }
6536 }
6537
6538 desc->u.ss.DeviceRemovable = cpu_to_le16(port_removable);
6539 }
6540 }
6541
6542 #ifdef CONFIG_ACPI
6543 /**
6544 * usb_get_hub_port_acpi_handle - Get the usb port's acpi handle
6545 * @hdev: USB device belonging to the usb hub
6546 * @port1: port num of the port
6547 *
6548 * Return: Port's acpi handle if successful, %NULL if params are
6549 * invalid.
6550 */
usb_get_hub_port_acpi_handle(struct usb_device * hdev,int port1)6551 acpi_handle usb_get_hub_port_acpi_handle(struct usb_device *hdev,
6552 int port1)
6553 {
6554 struct usb_hub *hub = usb_hub_to_struct_hub(hdev);
6555
6556 if (!hub)
6557 return NULL;
6558
6559 return ACPI_HANDLE(&hub->ports[port1 - 1]->dev);
6560 }
6561 #endif
6562