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