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