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 BIT(0)
50 #define HUB_QUIRK_DISABLE_AUTOSUSPEND BIT(1)
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 * The USB 2.0 spec prohibits hubs from having more than one
1799 * configuration or interface, and we rely on this prohibition.
1800 * Refuse to accept a device that violates it.
1801 */
1802 if (hdev->descriptor.bNumConfigurations > 1 ||
1803 hdev->actconfig->desc.bNumInterfaces > 1) {
1804 dev_err(&intf->dev, "Invalid hub with more than one config or interface\n");
1805 return -EINVAL;
1806 }
1807
1808 /*
1809 * Set default autosuspend delay as 0 to speedup bus suspend,
1810 * based on the below considerations:
1811 *
1812 * - Unlike other drivers, the hub driver does not rely on the
1813 * autosuspend delay to provide enough time to handle a wakeup
1814 * event, and the submitted status URB is just to check future
1815 * change on hub downstream ports, so it is safe to do it.
1816 *
1817 * - The patch might cause one or more auto supend/resume for
1818 * below very rare devices when they are plugged into hub
1819 * first time:
1820 *
1821 * devices having trouble initializing, and disconnect
1822 * themselves from the bus and then reconnect a second
1823 * or so later
1824 *
1825 * devices just for downloading firmware, and disconnects
1826 * themselves after completing it
1827 *
1828 * For these quite rare devices, their drivers may change the
1829 * autosuspend delay of their parent hub in the probe() to one
1830 * appropriate value to avoid the subtle problem if someone
1831 * does care it.
1832 *
1833 * - The patch may cause one or more auto suspend/resume on
1834 * hub during running 'lsusb', but it is probably too
1835 * infrequent to worry about.
1836 *
1837 * - Change autosuspend delay of hub can avoid unnecessary auto
1838 * suspend timer for hub, also may decrease power consumption
1839 * of USB bus.
1840 *
1841 * - If user has indicated to prevent autosuspend by passing
1842 * usbcore.autosuspend = -1 then keep autosuspend disabled.
1843 */
1844 #ifdef CONFIG_PM
1845 if (hdev->dev.power.autosuspend_delay >= 0)
1846 pm_runtime_set_autosuspend_delay(&hdev->dev, 0);
1847 #endif
1848
1849 /*
1850 * Hubs have proper suspend/resume support, except for root hubs
1851 * where the controller driver doesn't have bus_suspend and
1852 * bus_resume methods.
1853 */
1854 if (hdev->parent) { /* normal device */
1855 usb_enable_autosuspend(hdev);
1856 } else { /* root hub */
1857 const struct hc_driver *drv = bus_to_hcd(hdev->bus)->driver;
1858
1859 if (drv->bus_suspend && drv->bus_resume)
1860 usb_enable_autosuspend(hdev);
1861 }
1862
1863 if (hdev->level == MAX_TOPO_LEVEL) {
1864 dev_err(&intf->dev,
1865 "Unsupported bus topology: hub nested too deep\n");
1866 return -E2BIG;
1867 }
1868
1869 #ifdef CONFIG_USB_OTG_DISABLE_EXTERNAL_HUB
1870 if (hdev->parent) {
1871 dev_warn(&intf->dev, "ignoring external hub\n");
1872 return -ENODEV;
1873 }
1874 #endif
1875
1876 if (!hub_descriptor_is_sane(desc)) {
1877 dev_err(&intf->dev, "bad descriptor, ignoring hub\n");
1878 return -EIO;
1879 }
1880
1881 /* We found a hub */
1882 dev_info(&intf->dev, "USB hub found\n");
1883
1884 hub = kzalloc(sizeof(*hub), GFP_KERNEL);
1885 if (!hub)
1886 return -ENOMEM;
1887
1888 kref_init(&hub->kref);
1889 hub->intfdev = &intf->dev;
1890 hub->hdev = hdev;
1891 INIT_DELAYED_WORK(&hub->leds, led_work);
1892 INIT_DELAYED_WORK(&hub->init_work, NULL);
1893 INIT_WORK(&hub->events, hub_event);
1894 spin_lock_init(&hub->irq_urb_lock);
1895 timer_setup(&hub->irq_urb_retry, hub_retry_irq_urb, 0);
1896 usb_get_intf(intf);
1897 usb_get_dev(hdev);
1898
1899 usb_set_intfdata(intf, hub);
1900 intf->needs_remote_wakeup = 1;
1901 pm_suspend_ignore_children(&intf->dev, true);
1902
1903 if (hdev->speed == USB_SPEED_HIGH)
1904 highspeed_hubs++;
1905
1906 if (id->driver_info & HUB_QUIRK_CHECK_PORT_AUTOSUSPEND)
1907 hub->quirk_check_port_auto_suspend = 1;
1908
1909 if (id->driver_info & HUB_QUIRK_DISABLE_AUTOSUSPEND) {
1910 hub->quirk_disable_autosuspend = 1;
1911 usb_autopm_get_interface_no_resume(intf);
1912 }
1913
1914 if (hub_configure(hub, &desc->endpoint[0].desc) >= 0)
1915 return 0;
1916
1917 hub_disconnect(intf);
1918 return -ENODEV;
1919 }
1920
1921 static int
hub_ioctl(struct usb_interface * intf,unsigned int code,void * user_data)1922 hub_ioctl(struct usb_interface *intf, unsigned int code, void *user_data)
1923 {
1924 struct usb_device *hdev = interface_to_usbdev(intf);
1925 struct usb_hub *hub = usb_hub_to_struct_hub(hdev);
1926
1927 /* assert ifno == 0 (part of hub spec) */
1928 switch (code) {
1929 case USBDEVFS_HUB_PORTINFO: {
1930 struct usbdevfs_hub_portinfo *info = user_data;
1931 int i;
1932
1933 spin_lock_irq(&device_state_lock);
1934 if (hdev->devnum <= 0)
1935 info->nports = 0;
1936 else {
1937 info->nports = hdev->maxchild;
1938 for (i = 0; i < info->nports; i++) {
1939 if (hub->ports[i]->child == NULL)
1940 info->port[i] = 0;
1941 else
1942 info->port[i] =
1943 hub->ports[i]->child->devnum;
1944 }
1945 }
1946 spin_unlock_irq(&device_state_lock);
1947
1948 return info->nports + 1;
1949 }
1950
1951 default:
1952 return -ENOSYS;
1953 }
1954 }
1955
1956 /*
1957 * Allow user programs to claim ports on a hub. When a device is attached
1958 * to one of these "claimed" ports, the program will "own" the device.
1959 */
find_port_owner(struct usb_device * hdev,unsigned port1,struct usb_dev_state *** ppowner)1960 static int find_port_owner(struct usb_device *hdev, unsigned port1,
1961 struct usb_dev_state ***ppowner)
1962 {
1963 struct usb_hub *hub = usb_hub_to_struct_hub(hdev);
1964
1965 if (hdev->state == USB_STATE_NOTATTACHED)
1966 return -ENODEV;
1967 if (port1 == 0 || port1 > hdev->maxchild)
1968 return -EINVAL;
1969
1970 /* Devices not managed by the hub driver
1971 * will always have maxchild equal to 0.
1972 */
1973 *ppowner = &(hub->ports[port1 - 1]->port_owner);
1974 return 0;
1975 }
1976
1977 /* 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)1978 int usb_hub_claim_port(struct usb_device *hdev, unsigned port1,
1979 struct usb_dev_state *owner)
1980 {
1981 int rc;
1982 struct usb_dev_state **powner;
1983
1984 rc = find_port_owner(hdev, port1, &powner);
1985 if (rc)
1986 return rc;
1987 if (*powner)
1988 return -EBUSY;
1989 *powner = owner;
1990 return rc;
1991 }
1992 EXPORT_SYMBOL_GPL(usb_hub_claim_port);
1993
usb_hub_release_port(struct usb_device * hdev,unsigned port1,struct usb_dev_state * owner)1994 int usb_hub_release_port(struct usb_device *hdev, unsigned port1,
1995 struct usb_dev_state *owner)
1996 {
1997 int rc;
1998 struct usb_dev_state **powner;
1999
2000 rc = find_port_owner(hdev, port1, &powner);
2001 if (rc)
2002 return rc;
2003 if (*powner != owner)
2004 return -ENOENT;
2005 *powner = NULL;
2006 return rc;
2007 }
2008 EXPORT_SYMBOL_GPL(usb_hub_release_port);
2009
usb_hub_release_all_ports(struct usb_device * hdev,struct usb_dev_state * owner)2010 void usb_hub_release_all_ports(struct usb_device *hdev, struct usb_dev_state *owner)
2011 {
2012 struct usb_hub *hub = usb_hub_to_struct_hub(hdev);
2013 int n;
2014
2015 for (n = 0; n < hdev->maxchild; n++) {
2016 if (hub->ports[n]->port_owner == owner)
2017 hub->ports[n]->port_owner = NULL;
2018 }
2019
2020 }
2021
2022 /* The caller must hold udev's lock */
usb_device_is_owned(struct usb_device * udev)2023 bool usb_device_is_owned(struct usb_device *udev)
2024 {
2025 struct usb_hub *hub;
2026
2027 if (udev->state == USB_STATE_NOTATTACHED || !udev->parent)
2028 return false;
2029 hub = usb_hub_to_struct_hub(udev->parent);
2030 return !!hub->ports[udev->portnum - 1]->port_owner;
2031 }
2032
recursively_mark_NOTATTACHED(struct usb_device * udev)2033 static void recursively_mark_NOTATTACHED(struct usb_device *udev)
2034 {
2035 struct usb_hub *hub = usb_hub_to_struct_hub(udev);
2036 int i;
2037
2038 for (i = 0; i < udev->maxchild; ++i) {
2039 if (hub->ports[i]->child)
2040 recursively_mark_NOTATTACHED(hub->ports[i]->child);
2041 }
2042 if (udev->state == USB_STATE_SUSPENDED)
2043 udev->active_duration -= jiffies;
2044 udev->state = USB_STATE_NOTATTACHED;
2045 }
2046
2047 /**
2048 * usb_set_device_state - change a device's current state (usbcore, hcds)
2049 * @udev: pointer to device whose state should be changed
2050 * @new_state: new state value to be stored
2051 *
2052 * udev->state is _not_ fully protected by the device lock. Although
2053 * most transitions are made only while holding the lock, the state can
2054 * can change to USB_STATE_NOTATTACHED at almost any time. This
2055 * is so that devices can be marked as disconnected as soon as possible,
2056 * without having to wait for any semaphores to be released. As a result,
2057 * all changes to any device's state must be protected by the
2058 * device_state_lock spinlock.
2059 *
2060 * Once a device has been added to the device tree, all changes to its state
2061 * should be made using this routine. The state should _not_ be set directly.
2062 *
2063 * If udev->state is already USB_STATE_NOTATTACHED then no change is made.
2064 * Otherwise udev->state is set to new_state, and if new_state is
2065 * USB_STATE_NOTATTACHED then all of udev's descendants' states are also set
2066 * to USB_STATE_NOTATTACHED.
2067 */
usb_set_device_state(struct usb_device * udev,enum usb_device_state new_state)2068 void usb_set_device_state(struct usb_device *udev,
2069 enum usb_device_state new_state)
2070 {
2071 unsigned long flags;
2072 int wakeup = -1;
2073
2074 spin_lock_irqsave(&device_state_lock, flags);
2075 if (udev->state == USB_STATE_NOTATTACHED)
2076 ; /* do nothing */
2077 else if (new_state != USB_STATE_NOTATTACHED) {
2078
2079 /* root hub wakeup capabilities are managed out-of-band
2080 * and may involve silicon errata ... ignore them here.
2081 */
2082 if (udev->parent) {
2083 if (udev->state == USB_STATE_SUSPENDED
2084 || new_state == USB_STATE_SUSPENDED)
2085 ; /* No change to wakeup settings */
2086 else if (new_state == USB_STATE_CONFIGURED)
2087 wakeup = (udev->quirks &
2088 USB_QUIRK_IGNORE_REMOTE_WAKEUP) ? 0 :
2089 udev->actconfig->desc.bmAttributes &
2090 USB_CONFIG_ATT_WAKEUP;
2091 else
2092 wakeup = 0;
2093 }
2094 if (udev->state == USB_STATE_SUSPENDED &&
2095 new_state != USB_STATE_SUSPENDED)
2096 udev->active_duration -= jiffies;
2097 else if (new_state == USB_STATE_SUSPENDED &&
2098 udev->state != USB_STATE_SUSPENDED)
2099 udev->active_duration += jiffies;
2100 udev->state = new_state;
2101 } else
2102 recursively_mark_NOTATTACHED(udev);
2103 spin_unlock_irqrestore(&device_state_lock, flags);
2104 if (wakeup >= 0)
2105 device_set_wakeup_capable(&udev->dev, wakeup);
2106 }
2107 EXPORT_SYMBOL_GPL(usb_set_device_state);
2108
2109 /*
2110 * Choose a device number.
2111 *
2112 * Device numbers are used as filenames in usbfs. On USB-1.1 and
2113 * USB-2.0 buses they are also used as device addresses, however on
2114 * USB-3.0 buses the address is assigned by the controller hardware
2115 * and it usually is not the same as the device number.
2116 *
2117 * WUSB devices are simple: they have no hubs behind, so the mapping
2118 * device <-> virtual port number becomes 1:1. Why? to simplify the
2119 * life of the device connection logic in
2120 * drivers/usb/wusbcore/devconnect.c. When we do the initial secret
2121 * handshake we need to assign a temporary address in the unauthorized
2122 * space. For simplicity we use the first virtual port number found to
2123 * be free [drivers/usb/wusbcore/devconnect.c:wusbhc_devconnect_ack()]
2124 * and that becomes it's address [X < 128] or its unauthorized address
2125 * [X | 0x80].
2126 *
2127 * We add 1 as an offset to the one-based USB-stack port number
2128 * (zero-based wusb virtual port index) for two reasons: (a) dev addr
2129 * 0 is reserved by USB for default address; (b) Linux's USB stack
2130 * uses always #1 for the root hub of the controller. So USB stack's
2131 * port #1, which is wusb virtual-port #0 has address #2.
2132 *
2133 * Devices connected under xHCI are not as simple. The host controller
2134 * supports virtualization, so the hardware assigns device addresses and
2135 * the HCD must setup data structures before issuing a set address
2136 * command to the hardware.
2137 */
choose_devnum(struct usb_device * udev)2138 static void choose_devnum(struct usb_device *udev)
2139 {
2140 int devnum;
2141 struct usb_bus *bus = udev->bus;
2142
2143 /* be safe when more hub events are proceed in parallel */
2144 mutex_lock(&bus->devnum_next_mutex);
2145 if (udev->wusb) {
2146 devnum = udev->portnum + 1;
2147 BUG_ON(test_bit(devnum, bus->devmap.devicemap));
2148 } else {
2149 /* Try to allocate the next devnum beginning at
2150 * bus->devnum_next. */
2151 devnum = find_next_zero_bit(bus->devmap.devicemap, 128,
2152 bus->devnum_next);
2153 if (devnum >= 128)
2154 devnum = find_next_zero_bit(bus->devmap.devicemap,
2155 128, 1);
2156 bus->devnum_next = (devnum >= 127 ? 1 : devnum + 1);
2157 }
2158 if (devnum < 128) {
2159 set_bit(devnum, bus->devmap.devicemap);
2160 udev->devnum = devnum;
2161 }
2162 mutex_unlock(&bus->devnum_next_mutex);
2163 }
2164
release_devnum(struct usb_device * udev)2165 static void release_devnum(struct usb_device *udev)
2166 {
2167 if (udev->devnum > 0) {
2168 clear_bit(udev->devnum, udev->bus->devmap.devicemap);
2169 udev->devnum = -1;
2170 }
2171 }
2172
update_devnum(struct usb_device * udev,int devnum)2173 static void update_devnum(struct usb_device *udev, int devnum)
2174 {
2175 /* The address for a WUSB device is managed by wusbcore. */
2176 if (!udev->wusb)
2177 udev->devnum = devnum;
2178 if (!udev->devaddr)
2179 udev->devaddr = (u8)devnum;
2180 }
2181
hub_free_dev(struct usb_device * udev)2182 static void hub_free_dev(struct usb_device *udev)
2183 {
2184 struct usb_hcd *hcd = bus_to_hcd(udev->bus);
2185
2186 /* Root hubs aren't real devices, so don't free HCD resources */
2187 if (hcd->driver->free_dev && udev->parent)
2188 hcd->driver->free_dev(hcd, udev);
2189 }
2190
hub_disconnect_children(struct usb_device * udev)2191 static void hub_disconnect_children(struct usb_device *udev)
2192 {
2193 struct usb_hub *hub = usb_hub_to_struct_hub(udev);
2194 int i;
2195
2196 /* Free up all the children before we remove this device */
2197 for (i = 0; i < udev->maxchild; i++) {
2198 if (hub->ports[i]->child)
2199 usb_disconnect(&hub->ports[i]->child);
2200 }
2201 }
2202
2203 /**
2204 * usb_disconnect - disconnect a device (usbcore-internal)
2205 * @pdev: pointer to device being disconnected
2206 * Context: !in_interrupt ()
2207 *
2208 * Something got disconnected. Get rid of it and all of its children.
2209 *
2210 * If *pdev is a normal device then the parent hub must already be locked.
2211 * If *pdev is a root hub then the caller must hold the usb_bus_idr_lock,
2212 * which protects the set of root hubs as well as the list of buses.
2213 *
2214 * Only hub drivers (including virtual root hub drivers for host
2215 * controllers) should ever call this.
2216 *
2217 * This call is synchronous, and may not be used in an interrupt context.
2218 */
usb_disconnect(struct usb_device ** pdev)2219 void usb_disconnect(struct usb_device **pdev)
2220 {
2221 struct usb_port *port_dev = NULL;
2222 struct usb_device *udev = *pdev;
2223 struct usb_hub *hub = NULL;
2224 int port1 = 1;
2225
2226 /* mark the device as inactive, so any further urb submissions for
2227 * this device (and any of its children) will fail immediately.
2228 * this quiesces everything except pending urbs.
2229 */
2230 usb_set_device_state(udev, USB_STATE_NOTATTACHED);
2231 dev_info(&udev->dev, "USB disconnect, device number %d\n",
2232 udev->devnum);
2233
2234 /*
2235 * Ensure that the pm runtime code knows that the USB device
2236 * is in the process of being disconnected.
2237 */
2238 pm_runtime_barrier(&udev->dev);
2239
2240 usb_lock_device(udev);
2241
2242 hub_disconnect_children(udev);
2243
2244 /* deallocate hcd/hardware state ... nuking all pending urbs and
2245 * cleaning up all state associated with the current configuration
2246 * so that the hardware is now fully quiesced.
2247 */
2248 dev_dbg(&udev->dev, "unregistering device\n");
2249 usb_disable_device(udev, 0);
2250 usb_hcd_synchronize_unlinks(udev);
2251
2252 if (udev->parent) {
2253 port1 = udev->portnum;
2254 hub = usb_hub_to_struct_hub(udev->parent);
2255 port_dev = hub->ports[port1 - 1];
2256
2257 sysfs_remove_link(&udev->dev.kobj, "port");
2258 sysfs_remove_link(&port_dev->dev.kobj, "device");
2259
2260 /*
2261 * As usb_port_runtime_resume() de-references udev, make
2262 * sure no resumes occur during removal
2263 */
2264 if (!test_and_set_bit(port1, hub->child_usage_bits))
2265 pm_runtime_get_sync(&port_dev->dev);
2266 }
2267
2268 usb_remove_ep_devs(&udev->ep0);
2269 usb_unlock_device(udev);
2270
2271 /* Unregister the device. The device driver is responsible
2272 * for de-configuring the device and invoking the remove-device
2273 * notifier chain (used by usbfs and possibly others).
2274 */
2275 device_del(&udev->dev);
2276
2277 /* Free the device number and delete the parent's children[]
2278 * (or root_hub) pointer.
2279 */
2280 release_devnum(udev);
2281
2282 /* Avoid races with recursively_mark_NOTATTACHED() */
2283 spin_lock_irq(&device_state_lock);
2284 *pdev = NULL;
2285 spin_unlock_irq(&device_state_lock);
2286
2287 if (port_dev && test_and_clear_bit(port1, hub->child_usage_bits))
2288 pm_runtime_put(&port_dev->dev);
2289
2290 hub_free_dev(udev);
2291
2292 put_device(&udev->dev);
2293 }
2294
2295 #ifdef CONFIG_USB_ANNOUNCE_NEW_DEVICES
show_string(struct usb_device * udev,char * id,char * string)2296 static void show_string(struct usb_device *udev, char *id, char *string)
2297 {
2298 if (!string)
2299 return;
2300 dev_info(&udev->dev, "%s: %s\n", id, string);
2301 }
2302
announce_device(struct usb_device * udev)2303 static void announce_device(struct usb_device *udev)
2304 {
2305 u16 bcdDevice = le16_to_cpu(udev->descriptor.bcdDevice);
2306
2307 dev_info(&udev->dev,
2308 "New USB device found, idVendor=%04x, idProduct=%04x, bcdDevice=%2x.%02x\n",
2309 le16_to_cpu(udev->descriptor.idVendor),
2310 le16_to_cpu(udev->descriptor.idProduct),
2311 bcdDevice >> 8, bcdDevice & 0xff);
2312 dev_info(&udev->dev,
2313 "New USB device strings: Mfr=%d, Product=%d, SerialNumber=%d\n",
2314 udev->descriptor.iManufacturer,
2315 udev->descriptor.iProduct,
2316 udev->descriptor.iSerialNumber);
2317 show_string(udev, "Product", udev->product);
2318 show_string(udev, "Manufacturer", udev->manufacturer);
2319 show_string(udev, "SerialNumber", udev->serial);
2320 }
2321 #else
announce_device(struct usb_device * udev)2322 static inline void announce_device(struct usb_device *udev) { }
2323 #endif
2324
2325
2326 /**
2327 * usb_enumerate_device_otg - FIXME (usbcore-internal)
2328 * @udev: newly addressed device (in ADDRESS state)
2329 *
2330 * Finish enumeration for On-The-Go devices
2331 *
2332 * Return: 0 if successful. A negative error code otherwise.
2333 */
usb_enumerate_device_otg(struct usb_device * udev)2334 static int usb_enumerate_device_otg(struct usb_device *udev)
2335 {
2336 int err = 0;
2337
2338 #ifdef CONFIG_USB_OTG
2339 /*
2340 * OTG-aware devices on OTG-capable root hubs may be able to use SRP,
2341 * to wake us after we've powered off VBUS; and HNP, switching roles
2342 * "host" to "peripheral". The OTG descriptor helps figure this out.
2343 */
2344 if (!udev->bus->is_b_host
2345 && udev->config
2346 && udev->parent == udev->bus->root_hub) {
2347 struct usb_otg_descriptor *desc = NULL;
2348 struct usb_bus *bus = udev->bus;
2349 unsigned port1 = udev->portnum;
2350
2351 /* descriptor may appear anywhere in config */
2352 err = __usb_get_extra_descriptor(udev->rawdescriptors[0],
2353 le16_to_cpu(udev->config[0].desc.wTotalLength),
2354 USB_DT_OTG, (void **) &desc, sizeof(*desc));
2355 if (err || !(desc->bmAttributes & USB_OTG_HNP))
2356 return 0;
2357
2358 dev_info(&udev->dev, "Dual-Role OTG device on %sHNP port\n",
2359 (port1 == bus->otg_port) ? "" : "non-");
2360
2361 /* enable HNP before suspend, it's simpler */
2362 if (port1 == bus->otg_port) {
2363 bus->b_hnp_enable = 1;
2364 err = usb_control_msg(udev,
2365 usb_sndctrlpipe(udev, 0),
2366 USB_REQ_SET_FEATURE, 0,
2367 USB_DEVICE_B_HNP_ENABLE,
2368 0, NULL, 0,
2369 USB_CTRL_SET_TIMEOUT);
2370 if (err < 0) {
2371 /*
2372 * OTG MESSAGE: report errors here,
2373 * customize to match your product.
2374 */
2375 dev_err(&udev->dev, "can't set HNP mode: %d\n",
2376 err);
2377 bus->b_hnp_enable = 0;
2378 }
2379 } else if (desc->bLength == sizeof
2380 (struct usb_otg_descriptor)) {
2381 /*
2382 * We are operating on a legacy OTP device
2383 * These should be told that they are operating
2384 * on the wrong port if we have another port that does
2385 * support HNP
2386 */
2387 if (bus->otg_port != 0) {
2388 /* Set a_alt_hnp_support for legacy otg device */
2389 err = usb_control_msg(udev,
2390 usb_sndctrlpipe(udev, 0),
2391 USB_REQ_SET_FEATURE, 0,
2392 USB_DEVICE_A_ALT_HNP_SUPPORT,
2393 0, NULL, 0,
2394 USB_CTRL_SET_TIMEOUT);
2395 if (err < 0)
2396 dev_err(&udev->dev,
2397 "set a_alt_hnp_support failed: %d\n",
2398 err);
2399 }
2400 }
2401 }
2402 #endif
2403 return err;
2404 }
2405
2406
2407 /**
2408 * usb_enumerate_device - Read device configs/intfs/otg (usbcore-internal)
2409 * @udev: newly addressed device (in ADDRESS state)
2410 *
2411 * This is only called by usb_new_device() -- all comments that apply there
2412 * apply here wrt to environment.
2413 *
2414 * If the device is WUSB and not authorized, we don't attempt to read
2415 * the string descriptors, as they will be errored out by the device
2416 * until it has been authorized.
2417 *
2418 * Return: 0 if successful. A negative error code otherwise.
2419 */
usb_enumerate_device(struct usb_device * udev)2420 static int usb_enumerate_device(struct usb_device *udev)
2421 {
2422 int err;
2423 struct usb_hcd *hcd = bus_to_hcd(udev->bus);
2424
2425 if (udev->config == NULL) {
2426 err = usb_get_configuration(udev);
2427 if (err < 0) {
2428 if (err != -ENODEV)
2429 dev_err(&udev->dev, "can't read configurations, error %d\n",
2430 err);
2431 return err;
2432 }
2433 }
2434
2435 /* read the standard strings and cache them if present */
2436 udev->product = usb_cache_string(udev, udev->descriptor.iProduct);
2437 udev->manufacturer = usb_cache_string(udev,
2438 udev->descriptor.iManufacturer);
2439 udev->serial = usb_cache_string(udev, udev->descriptor.iSerialNumber);
2440
2441 err = usb_enumerate_device_otg(udev);
2442 if (err < 0)
2443 return err;
2444
2445 if (IS_ENABLED(CONFIG_USB_OTG_PRODUCTLIST) && hcd->tpl_support &&
2446 !is_targeted(udev)) {
2447 /* Maybe it can talk to us, though we can't talk to it.
2448 * (Includes HNP test device.)
2449 */
2450 if (IS_ENABLED(CONFIG_USB_OTG) && (udev->bus->b_hnp_enable
2451 || udev->bus->is_b_host)) {
2452 err = usb_port_suspend(udev, PMSG_AUTO_SUSPEND);
2453 if (err < 0)
2454 dev_dbg(&udev->dev, "HNP fail, %d\n", err);
2455 }
2456 return -ENOTSUPP;
2457 }
2458
2459 usb_detect_interface_quirks(udev);
2460
2461 return 0;
2462 }
2463
set_usb_port_removable(struct usb_device * udev)2464 static void set_usb_port_removable(struct usb_device *udev)
2465 {
2466 struct usb_device *hdev = udev->parent;
2467 struct usb_hub *hub;
2468 u8 port = udev->portnum;
2469 u16 wHubCharacteristics;
2470 bool removable = true;
2471
2472 dev_set_removable(&udev->dev, DEVICE_REMOVABLE_UNKNOWN);
2473
2474 if (!hdev)
2475 return;
2476
2477 hub = usb_hub_to_struct_hub(udev->parent);
2478
2479 /*
2480 * If the platform firmware has provided information about a port,
2481 * use that to determine whether it's removable.
2482 */
2483 switch (hub->ports[udev->portnum - 1]->connect_type) {
2484 case USB_PORT_CONNECT_TYPE_HOT_PLUG:
2485 dev_set_removable(&udev->dev, DEVICE_REMOVABLE);
2486 return;
2487 case USB_PORT_CONNECT_TYPE_HARD_WIRED:
2488 case USB_PORT_NOT_USED:
2489 dev_set_removable(&udev->dev, DEVICE_FIXED);
2490 return;
2491 default:
2492 break;
2493 }
2494
2495 /*
2496 * Otherwise, check whether the hub knows whether a port is removable
2497 * or not
2498 */
2499 wHubCharacteristics = le16_to_cpu(hub->descriptor->wHubCharacteristics);
2500
2501 if (!(wHubCharacteristics & HUB_CHAR_COMPOUND))
2502 return;
2503
2504 if (hub_is_superspeed(hdev)) {
2505 if (le16_to_cpu(hub->descriptor->u.ss.DeviceRemovable)
2506 & (1 << port))
2507 removable = false;
2508 } else {
2509 if (hub->descriptor->u.hs.DeviceRemovable[port / 8] & (1 << (port % 8)))
2510 removable = false;
2511 }
2512
2513 if (removable)
2514 dev_set_removable(&udev->dev, DEVICE_REMOVABLE);
2515 else
2516 dev_set_removable(&udev->dev, DEVICE_FIXED);
2517
2518 }
2519
2520 /**
2521 * usb_new_device - perform initial device setup (usbcore-internal)
2522 * @udev: newly addressed device (in ADDRESS state)
2523 *
2524 * This is called with devices which have been detected but not fully
2525 * enumerated. The device descriptor is available, but not descriptors
2526 * for any device configuration. The caller must have locked either
2527 * the parent hub (if udev is a normal device) or else the
2528 * usb_bus_idr_lock (if udev is a root hub). The parent's pointer to
2529 * udev has already been installed, but udev is not yet visible through
2530 * sysfs or other filesystem code.
2531 *
2532 * This call is synchronous, and may not be used in an interrupt context.
2533 *
2534 * Only the hub driver or root-hub registrar should ever call this.
2535 *
2536 * Return: Whether the device is configured properly or not. Zero if the
2537 * interface was registered with the driver core; else a negative errno
2538 * value.
2539 *
2540 */
usb_new_device(struct usb_device * udev)2541 int usb_new_device(struct usb_device *udev)
2542 {
2543 int err;
2544
2545 if (udev->parent) {
2546 /* Initialize non-root-hub device wakeup to disabled;
2547 * device (un)configuration controls wakeup capable
2548 * sysfs power/wakeup controls wakeup enabled/disabled
2549 */
2550 device_init_wakeup(&udev->dev, 0);
2551 }
2552
2553 /* Tell the runtime-PM framework the device is active */
2554 pm_runtime_set_active(&udev->dev);
2555 pm_runtime_get_noresume(&udev->dev);
2556 pm_runtime_use_autosuspend(&udev->dev);
2557 pm_runtime_enable(&udev->dev);
2558
2559 /* By default, forbid autosuspend for all devices. It will be
2560 * allowed for hubs during binding.
2561 */
2562 usb_disable_autosuspend(udev);
2563
2564 err = usb_enumerate_device(udev); /* Read descriptors */
2565 if (err < 0)
2566 goto fail;
2567 dev_dbg(&udev->dev, "udev %d, busnum %d, minor = %d\n",
2568 udev->devnum, udev->bus->busnum,
2569 (((udev->bus->busnum-1) * 128) + (udev->devnum-1)));
2570 /* export the usbdev device-node for libusb */
2571 udev->dev.devt = MKDEV(USB_DEVICE_MAJOR,
2572 (((udev->bus->busnum-1) * 128) + (udev->devnum-1)));
2573
2574 /* Tell the world! */
2575 announce_device(udev);
2576
2577 if (udev->serial)
2578 add_device_randomness(udev->serial, strlen(udev->serial));
2579 if (udev->product)
2580 add_device_randomness(udev->product, strlen(udev->product));
2581 if (udev->manufacturer)
2582 add_device_randomness(udev->manufacturer,
2583 strlen(udev->manufacturer));
2584
2585 device_enable_async_suspend(&udev->dev);
2586
2587 /* check whether the hub or firmware marks this port as non-removable */
2588 set_usb_port_removable(udev);
2589
2590 /* Register the device. The device driver is responsible
2591 * for configuring the device and invoking the add-device
2592 * notifier chain (used by usbfs and possibly others).
2593 */
2594 err = device_add(&udev->dev);
2595 if (err) {
2596 dev_err(&udev->dev, "can't device_add, error %d\n", err);
2597 goto fail;
2598 }
2599
2600 /* Create link files between child device and usb port device. */
2601 if (udev->parent) {
2602 struct usb_hub *hub = usb_hub_to_struct_hub(udev->parent);
2603 int port1 = udev->portnum;
2604 struct usb_port *port_dev = hub->ports[port1 - 1];
2605
2606 err = sysfs_create_link(&udev->dev.kobj,
2607 &port_dev->dev.kobj, "port");
2608 if (err)
2609 goto fail;
2610
2611 err = sysfs_create_link(&port_dev->dev.kobj,
2612 &udev->dev.kobj, "device");
2613 if (err) {
2614 sysfs_remove_link(&udev->dev.kobj, "port");
2615 goto fail;
2616 }
2617
2618 if (!test_and_set_bit(port1, hub->child_usage_bits))
2619 pm_runtime_get_sync(&port_dev->dev);
2620 }
2621
2622 (void) usb_create_ep_devs(&udev->dev, &udev->ep0, udev);
2623 usb_mark_last_busy(udev);
2624 pm_runtime_put_sync_autosuspend(&udev->dev);
2625 return err;
2626
2627 fail:
2628 usb_set_device_state(udev, USB_STATE_NOTATTACHED);
2629 pm_runtime_disable(&udev->dev);
2630 pm_runtime_set_suspended(&udev->dev);
2631 return err;
2632 }
2633
2634
2635 /**
2636 * usb_deauthorize_device - deauthorize a device (usbcore-internal)
2637 * @usb_dev: USB device
2638 *
2639 * Move the USB device to a very basic state where interfaces are disabled
2640 * and the device is in fact unconfigured and unusable.
2641 *
2642 * We share a lock (that we have) with device_del(), so we need to
2643 * defer its call.
2644 *
2645 * Return: 0.
2646 */
usb_deauthorize_device(struct usb_device * usb_dev)2647 int usb_deauthorize_device(struct usb_device *usb_dev)
2648 {
2649 usb_lock_device(usb_dev);
2650 if (usb_dev->authorized == 0)
2651 goto out_unauthorized;
2652
2653 usb_dev->authorized = 0;
2654 usb_set_configuration(usb_dev, -1);
2655
2656 out_unauthorized:
2657 usb_unlock_device(usb_dev);
2658 return 0;
2659 }
2660
2661
usb_authorize_device(struct usb_device * usb_dev)2662 int usb_authorize_device(struct usb_device *usb_dev)
2663 {
2664 int result = 0, c;
2665
2666 usb_lock_device(usb_dev);
2667 if (usb_dev->authorized == 1)
2668 goto out_authorized;
2669
2670 result = usb_autoresume_device(usb_dev);
2671 if (result < 0) {
2672 dev_err(&usb_dev->dev,
2673 "can't autoresume for authorization: %d\n", result);
2674 goto error_autoresume;
2675 }
2676
2677 if (usb_dev->wusb) {
2678 struct usb_device_descriptor *descr;
2679
2680 descr = usb_get_device_descriptor(usb_dev);
2681 if (IS_ERR(descr)) {
2682 result = PTR_ERR(descr);
2683 dev_err(&usb_dev->dev, "can't re-read device descriptor for "
2684 "authorization: %d\n", result);
2685 goto error_device_descriptor;
2686 }
2687 usb_dev->descriptor = *descr;
2688 kfree(descr);
2689 }
2690
2691 usb_dev->authorized = 1;
2692 /* Choose and set the configuration. This registers the interfaces
2693 * with the driver core and lets interface drivers bind to them.
2694 */
2695 c = usb_choose_configuration(usb_dev);
2696 if (c >= 0) {
2697 result = usb_set_configuration(usb_dev, c);
2698 if (result) {
2699 dev_err(&usb_dev->dev,
2700 "can't set config #%d, error %d\n", c, result);
2701 /* This need not be fatal. The user can try to
2702 * set other configurations. */
2703 }
2704 }
2705 dev_info(&usb_dev->dev, "authorized to connect\n");
2706
2707 error_device_descriptor:
2708 usb_autosuspend_device(usb_dev);
2709 error_autoresume:
2710 out_authorized:
2711 usb_unlock_device(usb_dev); /* complements locktree */
2712 return result;
2713 }
2714
2715 /**
2716 * get_port_ssp_rate - Match the extended port status to SSP rate
2717 * @hdev: The hub device
2718 * @ext_portstatus: extended port status
2719 *
2720 * Match the extended port status speed id to the SuperSpeed Plus sublink speed
2721 * capability attributes. Base on the number of connected lanes and speed,
2722 * return the corresponding enum usb_ssp_rate.
2723 */
get_port_ssp_rate(struct usb_device * hdev,u32 ext_portstatus)2724 static enum usb_ssp_rate get_port_ssp_rate(struct usb_device *hdev,
2725 u32 ext_portstatus)
2726 {
2727 struct usb_ssp_cap_descriptor *ssp_cap = hdev->bos->ssp_cap;
2728 u32 attr;
2729 u8 speed_id;
2730 u8 ssac;
2731 u8 lanes;
2732 int i;
2733
2734 if (!ssp_cap)
2735 goto out;
2736
2737 speed_id = ext_portstatus & USB_EXT_PORT_STAT_RX_SPEED_ID;
2738 lanes = USB_EXT_PORT_RX_LANES(ext_portstatus) + 1;
2739
2740 ssac = le32_to_cpu(ssp_cap->bmAttributes) &
2741 USB_SSP_SUBLINK_SPEED_ATTRIBS;
2742
2743 for (i = 0; i <= ssac; i++) {
2744 u8 ssid;
2745
2746 attr = le32_to_cpu(ssp_cap->bmSublinkSpeedAttr[i]);
2747 ssid = FIELD_GET(USB_SSP_SUBLINK_SPEED_SSID, attr);
2748 if (speed_id == ssid) {
2749 u16 mantissa;
2750 u8 lse;
2751 u8 type;
2752
2753 /*
2754 * Note: currently asymmetric lane types are only
2755 * applicable for SSIC operate in SuperSpeed protocol
2756 */
2757 type = FIELD_GET(USB_SSP_SUBLINK_SPEED_ST, attr);
2758 if (type == USB_SSP_SUBLINK_SPEED_ST_ASYM_RX ||
2759 type == USB_SSP_SUBLINK_SPEED_ST_ASYM_TX)
2760 goto out;
2761
2762 if (FIELD_GET(USB_SSP_SUBLINK_SPEED_LP, attr) !=
2763 USB_SSP_SUBLINK_SPEED_LP_SSP)
2764 goto out;
2765
2766 lse = FIELD_GET(USB_SSP_SUBLINK_SPEED_LSE, attr);
2767 mantissa = FIELD_GET(USB_SSP_SUBLINK_SPEED_LSM, attr);
2768
2769 /* Convert to Gbps */
2770 for (; lse < USB_SSP_SUBLINK_SPEED_LSE_GBPS; lse++)
2771 mantissa /= 1000;
2772
2773 if (mantissa >= 10 && lanes == 1)
2774 return USB_SSP_GEN_2x1;
2775
2776 if (mantissa >= 10 && lanes == 2)
2777 return USB_SSP_GEN_2x2;
2778
2779 if (mantissa >= 5 && lanes == 2)
2780 return USB_SSP_GEN_1x2;
2781
2782 goto out;
2783 }
2784 }
2785
2786 out:
2787 return USB_SSP_GEN_UNKNOWN;
2788 }
2789
2790 /*
2791 * Return 1 if port speed is SuperSpeedPlus, 0 otherwise or if the
2792 * capability couldn't be checked.
2793 * check it from the link protocol field of the current speed ID attribute.
2794 * current speed ID is got from ext port status request. Sublink speed attribute
2795 * table is returned with the hub BOS SSP device capability descriptor
2796 */
port_speed_is_ssp(struct usb_device * hdev,int speed_id)2797 static int port_speed_is_ssp(struct usb_device *hdev, int speed_id)
2798 {
2799 int ssa_count;
2800 u32 ss_attr;
2801 int i;
2802 struct usb_ssp_cap_descriptor *ssp_cap;
2803
2804 if (!hdev->bos)
2805 return 0;
2806
2807 ssp_cap = hdev->bos->ssp_cap;
2808 if (!ssp_cap)
2809 return 0;
2810
2811 ssa_count = le32_to_cpu(ssp_cap->bmAttributes) &
2812 USB_SSP_SUBLINK_SPEED_ATTRIBS;
2813
2814 for (i = 0; i <= ssa_count; i++) {
2815 ss_attr = le32_to_cpu(ssp_cap->bmSublinkSpeedAttr[i]);
2816 if (speed_id == (ss_attr & USB_SSP_SUBLINK_SPEED_SSID))
2817 return !!(ss_attr & USB_SSP_SUBLINK_SPEED_LP);
2818 }
2819 return 0;
2820 }
2821
2822 /* Returns 1 if @hub is a WUSB root hub, 0 otherwise */
hub_is_wusb(struct usb_hub * hub)2823 static unsigned hub_is_wusb(struct usb_hub *hub)
2824 {
2825 struct usb_hcd *hcd;
2826 if (hub->hdev->parent != NULL) /* not a root hub? */
2827 return 0;
2828 hcd = bus_to_hcd(hub->hdev->bus);
2829 return hcd->wireless;
2830 }
2831
2832
2833 #ifdef CONFIG_USB_FEW_INIT_RETRIES
2834 #define PORT_RESET_TRIES 2
2835 #define SET_ADDRESS_TRIES 1
2836 #define GET_DESCRIPTOR_TRIES 1
2837 #define GET_MAXPACKET0_TRIES 1
2838 #define PORT_INIT_TRIES 4
2839
2840 #else
2841 #define PORT_RESET_TRIES 5
2842 #define SET_ADDRESS_TRIES 2
2843 #define GET_DESCRIPTOR_TRIES 2
2844 #define GET_MAXPACKET0_TRIES 3
2845 #define PORT_INIT_TRIES 4
2846 #endif /* CONFIG_USB_FEW_INIT_RETRIES */
2847
2848 #define HUB_ROOT_RESET_TIME 60 /* times are in msec */
2849 #define HUB_SHORT_RESET_TIME 10
2850 #define HUB_BH_RESET_TIME 50
2851 #define HUB_LONG_RESET_TIME 200
2852 #define HUB_RESET_TIMEOUT 800
2853
use_new_scheme(struct usb_device * udev,int retry,struct usb_port * port_dev)2854 static bool use_new_scheme(struct usb_device *udev, int retry,
2855 struct usb_port *port_dev)
2856 {
2857 int old_scheme_first_port =
2858 (port_dev->quirks & USB_PORT_QUIRK_OLD_SCHEME) ||
2859 old_scheme_first;
2860
2861 /*
2862 * "New scheme" enumeration causes an extra state transition to be
2863 * exposed to an xhci host and causes USB3 devices to receive control
2864 * commands in the default state. This has been seen to cause
2865 * enumeration failures, so disable this enumeration scheme for USB3
2866 * devices.
2867 */
2868 if (udev->speed >= USB_SPEED_SUPER)
2869 return false;
2870
2871 /*
2872 * If use_both_schemes is set, use the first scheme (whichever
2873 * it is) for the larger half of the retries, then use the other
2874 * scheme. Otherwise, use the first scheme for all the retries.
2875 */
2876 if (use_both_schemes && retry >= (PORT_INIT_TRIES + 1) / 2)
2877 return old_scheme_first_port; /* Second half */
2878 return !old_scheme_first_port; /* First half or all */
2879 }
2880
2881 /* Is a USB 3.0 port in the Inactive or Compliance Mode state?
2882 * Port warm reset is required to recover
2883 */
hub_port_warm_reset_required(struct usb_hub * hub,int port1,u16 portstatus)2884 static bool hub_port_warm_reset_required(struct usb_hub *hub, int port1,
2885 u16 portstatus)
2886 {
2887 u16 link_state;
2888
2889 if (!hub_is_superspeed(hub->hdev))
2890 return false;
2891
2892 if (test_bit(port1, hub->warm_reset_bits))
2893 return true;
2894
2895 link_state = portstatus & USB_PORT_STAT_LINK_STATE;
2896 return link_state == USB_SS_PORT_LS_SS_INACTIVE
2897 || link_state == USB_SS_PORT_LS_COMP_MOD;
2898 }
2899
hub_port_wait_reset(struct usb_hub * hub,int port1,struct usb_device * udev,unsigned int delay,bool warm)2900 static int hub_port_wait_reset(struct usb_hub *hub, int port1,
2901 struct usb_device *udev, unsigned int delay, bool warm)
2902 {
2903 int delay_time, ret;
2904 u16 portstatus;
2905 u16 portchange;
2906 u32 ext_portstatus = 0;
2907
2908 for (delay_time = 0;
2909 delay_time < HUB_RESET_TIMEOUT;
2910 delay_time += delay) {
2911 /* wait to give the device a chance to reset */
2912 msleep(delay);
2913
2914 /* read and decode port status */
2915 if (hub_is_superspeedplus(hub->hdev))
2916 ret = hub_ext_port_status(hub, port1,
2917 HUB_EXT_PORT_STATUS,
2918 &portstatus, &portchange,
2919 &ext_portstatus);
2920 else
2921 ret = hub_port_status(hub, port1, &portstatus,
2922 &portchange);
2923 if (ret < 0)
2924 return ret;
2925
2926 /*
2927 * The port state is unknown until the reset completes.
2928 *
2929 * On top of that, some chips may require additional time
2930 * to re-establish a connection after the reset is complete,
2931 * so also wait for the connection to be re-established.
2932 */
2933 if (!(portstatus & USB_PORT_STAT_RESET) &&
2934 (portstatus & USB_PORT_STAT_CONNECTION))
2935 break;
2936
2937 /* switch to the long delay after two short delay failures */
2938 if (delay_time >= 2 * HUB_SHORT_RESET_TIME)
2939 delay = HUB_LONG_RESET_TIME;
2940
2941 dev_dbg(&hub->ports[port1 - 1]->dev,
2942 "not %sreset yet, waiting %dms\n",
2943 warm ? "warm " : "", delay);
2944 }
2945
2946 if ((portstatus & USB_PORT_STAT_RESET))
2947 return -EBUSY;
2948
2949 if (hub_port_warm_reset_required(hub, port1, portstatus))
2950 return -ENOTCONN;
2951
2952 /* Device went away? */
2953 if (!(portstatus & USB_PORT_STAT_CONNECTION))
2954 return -ENOTCONN;
2955
2956 /* Retry if connect change is set but status is still connected.
2957 * A USB 3.0 connection may bounce if multiple warm resets were issued,
2958 * but the device may have successfully re-connected. Ignore it.
2959 */
2960 if (!hub_is_superspeed(hub->hdev) &&
2961 (portchange & USB_PORT_STAT_C_CONNECTION)) {
2962 usb_clear_port_feature(hub->hdev, port1,
2963 USB_PORT_FEAT_C_CONNECTION);
2964 return -EAGAIN;
2965 }
2966
2967 if (!(portstatus & USB_PORT_STAT_ENABLE))
2968 return -EBUSY;
2969
2970 if (!udev)
2971 return 0;
2972
2973 if (hub_is_superspeedplus(hub->hdev)) {
2974 /* extended portstatus Rx and Tx lane count are zero based */
2975 udev->rx_lanes = USB_EXT_PORT_RX_LANES(ext_portstatus) + 1;
2976 udev->tx_lanes = USB_EXT_PORT_TX_LANES(ext_portstatus) + 1;
2977 udev->ssp_rate = get_port_ssp_rate(hub->hdev, ext_portstatus);
2978 } else {
2979 udev->rx_lanes = 1;
2980 udev->tx_lanes = 1;
2981 udev->ssp_rate = USB_SSP_GEN_UNKNOWN;
2982 }
2983 if (hub_is_wusb(hub))
2984 udev->speed = USB_SPEED_WIRELESS;
2985 else if (hub_is_superspeedplus(hub->hdev) &&
2986 port_speed_is_ssp(hub->hdev, ext_portstatus &
2987 USB_EXT_PORT_STAT_RX_SPEED_ID))
2988 udev->speed = USB_SPEED_SUPER_PLUS;
2989 else if (hub_is_superspeed(hub->hdev))
2990 udev->speed = USB_SPEED_SUPER;
2991 else if (portstatus & USB_PORT_STAT_HIGH_SPEED)
2992 udev->speed = USB_SPEED_HIGH;
2993 else if (portstatus & USB_PORT_STAT_LOW_SPEED)
2994 udev->speed = USB_SPEED_LOW;
2995 else
2996 udev->speed = USB_SPEED_FULL;
2997 return 0;
2998 }
2999
3000 /* 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)3001 static int hub_port_reset(struct usb_hub *hub, int port1,
3002 struct usb_device *udev, unsigned int delay, bool warm)
3003 {
3004 int i, status;
3005 u16 portchange, portstatus;
3006 struct usb_port *port_dev = hub->ports[port1 - 1];
3007 int reset_recovery_time;
3008
3009 if (!hub_is_superspeed(hub->hdev)) {
3010 if (warm) {
3011 dev_err(hub->intfdev, "only USB3 hub support "
3012 "warm reset\n");
3013 return -EINVAL;
3014 }
3015 /* Block EHCI CF initialization during the port reset.
3016 * Some companion controllers don't like it when they mix.
3017 */
3018 down_read(&ehci_cf_port_reset_rwsem);
3019 } else if (!warm) {
3020 /*
3021 * If the caller hasn't explicitly requested a warm reset,
3022 * double check and see if one is needed.
3023 */
3024 if (hub_port_status(hub, port1, &portstatus, &portchange) == 0)
3025 if (hub_port_warm_reset_required(hub, port1,
3026 portstatus))
3027 warm = true;
3028 }
3029 clear_bit(port1, hub->warm_reset_bits);
3030
3031 /* Reset the port */
3032 for (i = 0; i < PORT_RESET_TRIES; i++) {
3033 status = set_port_feature(hub->hdev, port1, (warm ?
3034 USB_PORT_FEAT_BH_PORT_RESET :
3035 USB_PORT_FEAT_RESET));
3036 if (status == -ENODEV) {
3037 ; /* The hub is gone */
3038 } else if (status) {
3039 dev_err(&port_dev->dev,
3040 "cannot %sreset (err = %d)\n",
3041 warm ? "warm " : "", status);
3042 } else {
3043 status = hub_port_wait_reset(hub, port1, udev, delay,
3044 warm);
3045 if (status && status != -ENOTCONN && status != -ENODEV)
3046 dev_dbg(hub->intfdev,
3047 "port_wait_reset: err = %d\n",
3048 status);
3049 }
3050
3051 /* Check for disconnect or reset */
3052 if (status == 0 || status == -ENOTCONN || status == -ENODEV) {
3053 usb_clear_port_feature(hub->hdev, port1,
3054 USB_PORT_FEAT_C_RESET);
3055
3056 if (!hub_is_superspeed(hub->hdev))
3057 goto done;
3058
3059 usb_clear_port_feature(hub->hdev, port1,
3060 USB_PORT_FEAT_C_BH_PORT_RESET);
3061 usb_clear_port_feature(hub->hdev, port1,
3062 USB_PORT_FEAT_C_PORT_LINK_STATE);
3063
3064 if (udev)
3065 usb_clear_port_feature(hub->hdev, port1,
3066 USB_PORT_FEAT_C_CONNECTION);
3067
3068 /*
3069 * If a USB 3.0 device migrates from reset to an error
3070 * state, re-issue the warm reset.
3071 */
3072 if (hub_port_status(hub, port1,
3073 &portstatus, &portchange) < 0)
3074 goto done;
3075
3076 if (!hub_port_warm_reset_required(hub, port1,
3077 portstatus))
3078 goto done;
3079
3080 /*
3081 * If the port is in SS.Inactive or Compliance Mode, the
3082 * hot or warm reset failed. Try another warm reset.
3083 */
3084 if (!warm) {
3085 dev_dbg(&port_dev->dev,
3086 "hot reset failed, warm reset\n");
3087 warm = true;
3088 }
3089 }
3090
3091 dev_dbg(&port_dev->dev,
3092 "not enabled, trying %sreset again...\n",
3093 warm ? "warm " : "");
3094 delay = HUB_LONG_RESET_TIME;
3095 }
3096
3097 dev_err(&port_dev->dev, "Cannot enable. Maybe the USB cable is bad?\n");
3098
3099 done:
3100 if (status == 0) {
3101 if (port_dev->quirks & USB_PORT_QUIRK_FAST_ENUM)
3102 usleep_range(10000, 12000);
3103 else {
3104 /* TRSTRCY = 10 ms; plus some extra */
3105 reset_recovery_time = 10 + 40;
3106
3107 /* Hub needs extra delay after resetting its port. */
3108 if (hub->hdev->quirks & USB_QUIRK_HUB_SLOW_RESET)
3109 reset_recovery_time += 100;
3110
3111 msleep(reset_recovery_time);
3112 }
3113
3114 if (udev) {
3115 struct usb_hcd *hcd = bus_to_hcd(udev->bus);
3116
3117 update_devnum(udev, 0);
3118 /* The xHC may think the device is already reset,
3119 * so ignore the status.
3120 */
3121 if (hcd->driver->reset_device)
3122 hcd->driver->reset_device(hcd, udev);
3123
3124 usb_set_device_state(udev, USB_STATE_DEFAULT);
3125 }
3126 } else {
3127 if (udev)
3128 usb_set_device_state(udev, USB_STATE_NOTATTACHED);
3129 }
3130
3131 if (!hub_is_superspeed(hub->hdev))
3132 up_read(&ehci_cf_port_reset_rwsem);
3133
3134 return status;
3135 }
3136
3137 /* Check if a port is power on */
port_is_power_on(struct usb_hub * hub,unsigned portstatus)3138 static int port_is_power_on(struct usb_hub *hub, unsigned portstatus)
3139 {
3140 int ret = 0;
3141
3142 if (hub_is_superspeed(hub->hdev)) {
3143 if (portstatus & USB_SS_PORT_STAT_POWER)
3144 ret = 1;
3145 } else {
3146 if (portstatus & USB_PORT_STAT_POWER)
3147 ret = 1;
3148 }
3149
3150 return ret;
3151 }
3152
usb_lock_port(struct usb_port * port_dev)3153 static void usb_lock_port(struct usb_port *port_dev)
3154 __acquires(&port_dev->status_lock)
3155 {
3156 mutex_lock(&port_dev->status_lock);
3157 __acquire(&port_dev->status_lock);
3158 }
3159
usb_unlock_port(struct usb_port * port_dev)3160 static void usb_unlock_port(struct usb_port *port_dev)
3161 __releases(&port_dev->status_lock)
3162 {
3163 mutex_unlock(&port_dev->status_lock);
3164 __release(&port_dev->status_lock);
3165 }
3166
3167 #ifdef CONFIG_PM
3168
3169 /* 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)3170 static int port_is_suspended(struct usb_hub *hub, unsigned portstatus)
3171 {
3172 int ret = 0;
3173
3174 if (hub_is_superspeed(hub->hdev)) {
3175 if ((portstatus & USB_PORT_STAT_LINK_STATE)
3176 == USB_SS_PORT_LS_U3)
3177 ret = 1;
3178 } else {
3179 if (portstatus & USB_PORT_STAT_SUSPEND)
3180 ret = 1;
3181 }
3182
3183 return ret;
3184 }
3185
3186 /* Determine whether the device on a port is ready for a normal resume,
3187 * is ready for a reset-resume, or should be disconnected.
3188 */
check_port_resume_type(struct usb_device * udev,struct usb_hub * hub,int port1,int status,u16 portchange,u16 portstatus)3189 static int check_port_resume_type(struct usb_device *udev,
3190 struct usb_hub *hub, int port1,
3191 int status, u16 portchange, u16 portstatus)
3192 {
3193 struct usb_port *port_dev = hub->ports[port1 - 1];
3194 int retries = 3;
3195
3196 retry:
3197 /* Is a warm reset needed to recover the connection? */
3198 if (status == 0 && udev->reset_resume
3199 && hub_port_warm_reset_required(hub, port1, portstatus)) {
3200 /* pass */;
3201 }
3202 /* Is the device still present? */
3203 else if (status || port_is_suspended(hub, portstatus) ||
3204 !port_is_power_on(hub, portstatus)) {
3205 if (status >= 0)
3206 status = -ENODEV;
3207 } else if (!(portstatus & USB_PORT_STAT_CONNECTION)) {
3208 if (retries--) {
3209 usleep_range(200, 300);
3210 status = hub_port_status(hub, port1, &portstatus,
3211 &portchange);
3212 goto retry;
3213 }
3214 status = -ENODEV;
3215 }
3216
3217 /* Can't do a normal resume if the port isn't enabled,
3218 * so try a reset-resume instead.
3219 */
3220 else if (!(portstatus & USB_PORT_STAT_ENABLE) && !udev->reset_resume) {
3221 if (udev->persist_enabled)
3222 udev->reset_resume = 1;
3223 else
3224 status = -ENODEV;
3225 }
3226
3227 if (status) {
3228 dev_dbg(&port_dev->dev, "status %04x.%04x after resume, %d\n",
3229 portchange, portstatus, status);
3230 } else if (udev->reset_resume) {
3231
3232 /* Late port handoff can set status-change bits */
3233 if (portchange & USB_PORT_STAT_C_CONNECTION)
3234 usb_clear_port_feature(hub->hdev, port1,
3235 USB_PORT_FEAT_C_CONNECTION);
3236 if (portchange & USB_PORT_STAT_C_ENABLE)
3237 usb_clear_port_feature(hub->hdev, port1,
3238 USB_PORT_FEAT_C_ENABLE);
3239
3240 /*
3241 * Whatever made this reset-resume necessary may have
3242 * turned on the port1 bit in hub->change_bits. But after
3243 * a successful reset-resume we want the bit to be clear;
3244 * if it was on it would indicate that something happened
3245 * following the reset-resume.
3246 */
3247 clear_bit(port1, hub->change_bits);
3248 }
3249
3250 return status;
3251 }
3252
usb_disable_ltm(struct usb_device * udev)3253 int usb_disable_ltm(struct usb_device *udev)
3254 {
3255 struct usb_hcd *hcd = bus_to_hcd(udev->bus);
3256
3257 /* Check if the roothub and device supports LTM. */
3258 if (!usb_device_supports_ltm(hcd->self.root_hub) ||
3259 !usb_device_supports_ltm(udev))
3260 return 0;
3261
3262 /* Clear Feature LTM Enable can only be sent if the device is
3263 * configured.
3264 */
3265 if (!udev->actconfig)
3266 return 0;
3267
3268 return usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
3269 USB_REQ_CLEAR_FEATURE, USB_RECIP_DEVICE,
3270 USB_DEVICE_LTM_ENABLE, 0, NULL, 0,
3271 USB_CTRL_SET_TIMEOUT);
3272 }
3273 EXPORT_SYMBOL_GPL(usb_disable_ltm);
3274
usb_enable_ltm(struct usb_device * udev)3275 void usb_enable_ltm(struct usb_device *udev)
3276 {
3277 struct usb_hcd *hcd = bus_to_hcd(udev->bus);
3278
3279 /* Check if the roothub and device supports LTM. */
3280 if (!usb_device_supports_ltm(hcd->self.root_hub) ||
3281 !usb_device_supports_ltm(udev))
3282 return;
3283
3284 /* Set Feature LTM Enable can only be sent if the device is
3285 * configured.
3286 */
3287 if (!udev->actconfig)
3288 return;
3289
3290 usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
3291 USB_REQ_SET_FEATURE, USB_RECIP_DEVICE,
3292 USB_DEVICE_LTM_ENABLE, 0, NULL, 0,
3293 USB_CTRL_SET_TIMEOUT);
3294 }
3295 EXPORT_SYMBOL_GPL(usb_enable_ltm);
3296
3297 /*
3298 * usb_enable_remote_wakeup - enable remote wakeup for a device
3299 * @udev: target device
3300 *
3301 * For USB-2 devices: Set the device's remote wakeup feature.
3302 *
3303 * For USB-3 devices: Assume there's only one function on the device and
3304 * enable remote wake for the first interface. FIXME if the interface
3305 * association descriptor shows there's more than one function.
3306 */
usb_enable_remote_wakeup(struct usb_device * udev)3307 static int usb_enable_remote_wakeup(struct usb_device *udev)
3308 {
3309 if (udev->speed < USB_SPEED_SUPER)
3310 return usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
3311 USB_REQ_SET_FEATURE, USB_RECIP_DEVICE,
3312 USB_DEVICE_REMOTE_WAKEUP, 0, NULL, 0,
3313 USB_CTRL_SET_TIMEOUT);
3314 else
3315 return usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
3316 USB_REQ_SET_FEATURE, USB_RECIP_INTERFACE,
3317 USB_INTRF_FUNC_SUSPEND,
3318 USB_INTRF_FUNC_SUSPEND_RW |
3319 USB_INTRF_FUNC_SUSPEND_LP,
3320 NULL, 0, USB_CTRL_SET_TIMEOUT);
3321 }
3322
3323 /*
3324 * usb_disable_remote_wakeup - disable remote wakeup for a device
3325 * @udev: target device
3326 *
3327 * For USB-2 devices: Clear the device's remote wakeup feature.
3328 *
3329 * For USB-3 devices: Assume there's only one function on the device and
3330 * disable remote wake for the first interface. FIXME if the interface
3331 * association descriptor shows there's more than one function.
3332 */
usb_disable_remote_wakeup(struct usb_device * udev)3333 static int usb_disable_remote_wakeup(struct usb_device *udev)
3334 {
3335 if (udev->speed < USB_SPEED_SUPER)
3336 return usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
3337 USB_REQ_CLEAR_FEATURE, USB_RECIP_DEVICE,
3338 USB_DEVICE_REMOTE_WAKEUP, 0, NULL, 0,
3339 USB_CTRL_SET_TIMEOUT);
3340 else
3341 return usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
3342 USB_REQ_SET_FEATURE, USB_RECIP_INTERFACE,
3343 USB_INTRF_FUNC_SUSPEND, 0, NULL, 0,
3344 USB_CTRL_SET_TIMEOUT);
3345 }
3346
3347 /* Count of wakeup-enabled devices at or below udev */
usb_wakeup_enabled_descendants(struct usb_device * udev)3348 unsigned usb_wakeup_enabled_descendants(struct usb_device *udev)
3349 {
3350 struct usb_hub *hub = usb_hub_to_struct_hub(udev);
3351
3352 return udev->do_remote_wakeup +
3353 (hub ? hub->wakeup_enabled_descendants : 0);
3354 }
3355 EXPORT_SYMBOL_GPL(usb_wakeup_enabled_descendants);
3356
3357 /*
3358 * usb_port_suspend - suspend a usb device's upstream port
3359 * @udev: device that's no longer in active use, not a root hub
3360 * Context: must be able to sleep; device not locked; pm locks held
3361 *
3362 * Suspends a USB device that isn't in active use, conserving power.
3363 * Devices may wake out of a suspend, if anything important happens,
3364 * using the remote wakeup mechanism. They may also be taken out of
3365 * suspend by the host, using usb_port_resume(). It's also routine
3366 * to disconnect devices while they are suspended.
3367 *
3368 * This only affects the USB hardware for a device; its interfaces
3369 * (and, for hubs, child devices) must already have been suspended.
3370 *
3371 * Selective port suspend reduces power; most suspended devices draw
3372 * less than 500 uA. It's also used in OTG, along with remote wakeup.
3373 * All devices below the suspended port are also suspended.
3374 *
3375 * Devices leave suspend state when the host wakes them up. Some devices
3376 * also support "remote wakeup", where the device can activate the USB
3377 * tree above them to deliver data, such as a keypress or packet. In
3378 * some cases, this wakes the USB host.
3379 *
3380 * Suspending OTG devices may trigger HNP, if that's been enabled
3381 * between a pair of dual-role devices. That will change roles, such
3382 * as from A-Host to A-Peripheral or from B-Host back to B-Peripheral.
3383 *
3384 * Devices on USB hub ports have only one "suspend" state, corresponding
3385 * to ACPI D2, "may cause the device to lose some context".
3386 * State transitions include:
3387 *
3388 * - suspend, resume ... when the VBUS power link stays live
3389 * - suspend, disconnect ... VBUS lost
3390 *
3391 * Once VBUS drop breaks the circuit, the port it's using has to go through
3392 * normal re-enumeration procedures, starting with enabling VBUS power.
3393 * Other than re-initializing the hub (plug/unplug, except for root hubs),
3394 * Linux (2.6) currently has NO mechanisms to initiate that: no hub_wq
3395 * timer, no SRP, no requests through sysfs.
3396 *
3397 * If Runtime PM isn't enabled or used, non-SuperSpeed devices may not get
3398 * suspended until their bus goes into global suspend (i.e., the root
3399 * hub is suspended). Nevertheless, we change @udev->state to
3400 * USB_STATE_SUSPENDED as this is the device's "logical" state. The actual
3401 * upstream port setting is stored in @udev->port_is_suspended.
3402 *
3403 * Returns 0 on success, else negative errno.
3404 */
usb_port_suspend(struct usb_device * udev,pm_message_t msg)3405 int usb_port_suspend(struct usb_device *udev, pm_message_t msg)
3406 {
3407 struct usb_hub *hub = usb_hub_to_struct_hub(udev->parent);
3408 struct usb_port *port_dev = hub->ports[udev->portnum - 1];
3409 int port1 = udev->portnum;
3410 int status;
3411 bool really_suspend = true;
3412
3413 usb_lock_port(port_dev);
3414
3415 /* enable remote wakeup when appropriate; this lets the device
3416 * wake up the upstream hub (including maybe the root hub).
3417 *
3418 * NOTE: OTG devices may issue remote wakeup (or SRP) even when
3419 * we don't explicitly enable it here.
3420 */
3421 if (udev->do_remote_wakeup) {
3422 status = usb_enable_remote_wakeup(udev);
3423 if (status) {
3424 dev_dbg(&udev->dev, "won't remote wakeup, status %d\n",
3425 status);
3426 /* bail if autosuspend is requested */
3427 if (PMSG_IS_AUTO(msg))
3428 goto err_wakeup;
3429 }
3430 }
3431
3432 /* disable USB2 hardware LPM */
3433 usb_disable_usb2_hardware_lpm(udev);
3434
3435 if (usb_disable_ltm(udev)) {
3436 dev_err(&udev->dev, "Failed to disable LTM before suspend\n");
3437 status = -ENOMEM;
3438 if (PMSG_IS_AUTO(msg))
3439 goto err_ltm;
3440 }
3441
3442 /* see 7.1.7.6 */
3443 if (hub_is_superspeed(hub->hdev))
3444 status = hub_set_port_link_state(hub, port1, USB_SS_PORT_LS_U3);
3445
3446 /*
3447 * For system suspend, we do not need to enable the suspend feature
3448 * on individual USB-2 ports. The devices will automatically go
3449 * into suspend a few ms after the root hub stops sending packets.
3450 * The USB 2.0 spec calls this "global suspend".
3451 *
3452 * However, many USB hubs have a bug: They don't relay wakeup requests
3453 * from a downstream port if the port's suspend feature isn't on.
3454 * Therefore we will turn on the suspend feature if udev or any of its
3455 * descendants is enabled for remote wakeup.
3456 */
3457 else if (PMSG_IS_AUTO(msg) || usb_wakeup_enabled_descendants(udev) > 0)
3458 status = set_port_feature(hub->hdev, port1,
3459 USB_PORT_FEAT_SUSPEND);
3460 else {
3461 really_suspend = false;
3462 status = 0;
3463 }
3464 if (status) {
3465 dev_dbg(&port_dev->dev, "can't suspend, status %d\n", status);
3466
3467 /* Try to enable USB3 LTM again */
3468 usb_enable_ltm(udev);
3469 err_ltm:
3470 /* Try to enable USB2 hardware LPM again */
3471 usb_enable_usb2_hardware_lpm(udev);
3472
3473 if (udev->do_remote_wakeup)
3474 (void) usb_disable_remote_wakeup(udev);
3475 err_wakeup:
3476
3477 /* System sleep transitions should never fail */
3478 if (!PMSG_IS_AUTO(msg))
3479 status = 0;
3480 } else {
3481 dev_dbg(&udev->dev, "usb %ssuspend, wakeup %d\n",
3482 (PMSG_IS_AUTO(msg) ? "auto-" : ""),
3483 udev->do_remote_wakeup);
3484 if (really_suspend) {
3485 udev->port_is_suspended = 1;
3486
3487 /* device has up to 10 msec to fully suspend */
3488 msleep(10);
3489 }
3490 usb_set_device_state(udev, USB_STATE_SUSPENDED);
3491 }
3492
3493 if (status == 0 && !udev->do_remote_wakeup && udev->persist_enabled
3494 && test_and_clear_bit(port1, hub->child_usage_bits))
3495 pm_runtime_put_sync(&port_dev->dev);
3496
3497 usb_mark_last_busy(hub->hdev);
3498
3499 usb_unlock_port(port_dev);
3500 return status;
3501 }
3502
3503 /*
3504 * If the USB "suspend" state is in use (rather than "global suspend"),
3505 * many devices will be individually taken out of suspend state using
3506 * special "resume" signaling. This routine kicks in shortly after
3507 * hardware resume signaling is finished, either because of selective
3508 * resume (by host) or remote wakeup (by device) ... now see what changed
3509 * in the tree that's rooted at this device.
3510 *
3511 * If @udev->reset_resume is set then the device is reset before the
3512 * status check is done.
3513 */
finish_port_resume(struct usb_device * udev)3514 static int finish_port_resume(struct usb_device *udev)
3515 {
3516 int status = 0;
3517 u16 devstatus = 0;
3518
3519 /* caller owns the udev device lock */
3520 dev_dbg(&udev->dev, "%s\n",
3521 udev->reset_resume ? "finish reset-resume" : "finish resume");
3522
3523 /* usb ch9 identifies four variants of SUSPENDED, based on what
3524 * state the device resumes to. Linux currently won't see the
3525 * first two on the host side; they'd be inside hub_port_init()
3526 * during many timeouts, but hub_wq can't suspend until later.
3527 */
3528 usb_set_device_state(udev, udev->actconfig
3529 ? USB_STATE_CONFIGURED
3530 : USB_STATE_ADDRESS);
3531
3532 /* 10.5.4.5 says not to reset a suspended port if the attached
3533 * device is enabled for remote wakeup. Hence the reset
3534 * operation is carried out here, after the port has been
3535 * resumed.
3536 */
3537 if (udev->reset_resume) {
3538 /*
3539 * If the device morphs or switches modes when it is reset,
3540 * we don't want to perform a reset-resume. We'll fail the
3541 * resume, which will cause a logical disconnect, and then
3542 * the device will be rediscovered.
3543 */
3544 retry_reset_resume:
3545 if (udev->quirks & USB_QUIRK_RESET)
3546 status = -ENODEV;
3547 else
3548 status = usb_reset_and_verify_device(udev);
3549 }
3550
3551 /* 10.5.4.5 says be sure devices in the tree are still there.
3552 * For now let's assume the device didn't go crazy on resume,
3553 * and device drivers will know about any resume quirks.
3554 */
3555 if (status == 0) {
3556 devstatus = 0;
3557 status = usb_get_std_status(udev, USB_RECIP_DEVICE, 0, &devstatus);
3558
3559 /* If a normal resume failed, try doing a reset-resume */
3560 if (status && !udev->reset_resume && udev->persist_enabled) {
3561 dev_dbg(&udev->dev, "retry with reset-resume\n");
3562 udev->reset_resume = 1;
3563 goto retry_reset_resume;
3564 }
3565 }
3566
3567 if (status) {
3568 dev_dbg(&udev->dev, "gone after usb resume? status %d\n",
3569 status);
3570 /*
3571 * There are a few quirky devices which violate the standard
3572 * by claiming to have remote wakeup enabled after a reset,
3573 * which crash if the feature is cleared, hence check for
3574 * udev->reset_resume
3575 */
3576 } else if (udev->actconfig && !udev->reset_resume) {
3577 if (udev->speed < USB_SPEED_SUPER) {
3578 if (devstatus & (1 << USB_DEVICE_REMOTE_WAKEUP))
3579 status = usb_disable_remote_wakeup(udev);
3580 } else {
3581 status = usb_get_std_status(udev, USB_RECIP_INTERFACE, 0,
3582 &devstatus);
3583 if (!status && devstatus & (USB_INTRF_STAT_FUNC_RW_CAP
3584 | USB_INTRF_STAT_FUNC_RW))
3585 status = usb_disable_remote_wakeup(udev);
3586 }
3587
3588 if (status)
3589 dev_dbg(&udev->dev,
3590 "disable remote wakeup, status %d\n",
3591 status);
3592 status = 0;
3593 }
3594 return status;
3595 }
3596
3597 /*
3598 * There are some SS USB devices which take longer time for link training.
3599 * XHCI specs 4.19.4 says that when Link training is successful, port
3600 * sets CCS bit to 1. So if SW reads port status before successful link
3601 * training, then it will not find device to be present.
3602 * USB Analyzer log with such buggy devices show that in some cases
3603 * device switch on the RX termination after long delay of host enabling
3604 * the VBUS. In few other cases it has been seen that device fails to
3605 * negotiate link training in first attempt. It has been
3606 * reported till now that few devices take as long as 2000 ms to train
3607 * the link after host enabling its VBUS and termination. Following
3608 * routine implements a 2000 ms timeout for link training. If in a case
3609 * link trains before timeout, loop will exit earlier.
3610 *
3611 * There are also some 2.0 hard drive based devices and 3.0 thumb
3612 * drives that, when plugged into a 2.0 only port, take a long
3613 * time to set CCS after VBUS enable.
3614 *
3615 * FIXME: If a device was connected before suspend, but was removed
3616 * while system was asleep, then the loop in the following routine will
3617 * only exit at timeout.
3618 *
3619 * This routine should only be called when persist is enabled.
3620 */
wait_for_connected(struct usb_device * udev,struct usb_hub * hub,int * port1,u16 * portchange,u16 * portstatus)3621 static int wait_for_connected(struct usb_device *udev,
3622 struct usb_hub *hub, int *port1,
3623 u16 *portchange, u16 *portstatus)
3624 {
3625 int status = 0, delay_ms = 0;
3626
3627 while (delay_ms < 2000) {
3628 if (status || *portstatus & USB_PORT_STAT_CONNECTION)
3629 break;
3630 if (!port_is_power_on(hub, *portstatus)) {
3631 status = -ENODEV;
3632 break;
3633 }
3634 msleep(20);
3635 delay_ms += 20;
3636 status = hub_port_status(hub, *port1, portstatus, portchange);
3637 }
3638 dev_dbg(&udev->dev, "Waited %dms for CONNECT\n", delay_ms);
3639 return status;
3640 }
3641
3642 /*
3643 * usb_port_resume - re-activate a suspended usb device's upstream port
3644 * @udev: device to re-activate, not a root hub
3645 * Context: must be able to sleep; device not locked; pm locks held
3646 *
3647 * This will re-activate the suspended device, increasing power usage
3648 * while letting drivers communicate again with its endpoints.
3649 * USB resume explicitly guarantees that the power session between
3650 * the host and the device is the same as it was when the device
3651 * suspended.
3652 *
3653 * If @udev->reset_resume is set then this routine won't check that the
3654 * port is still enabled. Furthermore, finish_port_resume() above will
3655 * reset @udev. The end result is that a broken power session can be
3656 * recovered and @udev will appear to persist across a loss of VBUS power.
3657 *
3658 * For example, if a host controller doesn't maintain VBUS suspend current
3659 * during a system sleep or is reset when the system wakes up, all the USB
3660 * power sessions below it will be broken. This is especially troublesome
3661 * for mass-storage devices containing mounted filesystems, since the
3662 * device will appear to have disconnected and all the memory mappings
3663 * to it will be lost. Using the USB_PERSIST facility, the device can be
3664 * made to appear as if it had not disconnected.
3665 *
3666 * This facility can be dangerous. Although usb_reset_and_verify_device() makes
3667 * every effort to insure that the same device is present after the
3668 * reset as before, it cannot provide a 100% guarantee. Furthermore it's
3669 * quite possible for a device to remain unaltered but its media to be
3670 * changed. If the user replaces a flash memory card while the system is
3671 * asleep, he will have only himself to blame when the filesystem on the
3672 * new card is corrupted and the system crashes.
3673 *
3674 * Returns 0 on success, else negative errno.
3675 */
usb_port_resume(struct usb_device * udev,pm_message_t msg)3676 int usb_port_resume(struct usb_device *udev, pm_message_t msg)
3677 {
3678 struct usb_hub *hub = usb_hub_to_struct_hub(udev->parent);
3679 struct usb_port *port_dev = hub->ports[udev->portnum - 1];
3680 int port1 = udev->portnum;
3681 int status;
3682 u16 portchange, portstatus;
3683
3684 if (!test_and_set_bit(port1, hub->child_usage_bits)) {
3685 status = pm_runtime_resume_and_get(&port_dev->dev);
3686 if (status < 0) {
3687 dev_dbg(&udev->dev, "can't resume usb port, status %d\n",
3688 status);
3689 return status;
3690 }
3691 }
3692
3693 usb_lock_port(port_dev);
3694
3695 /* Skip the initial Clear-Suspend step for a remote wakeup */
3696 status = hub_port_status(hub, port1, &portstatus, &portchange);
3697 if (status == 0 && !port_is_suspended(hub, portstatus)) {
3698 if (portchange & USB_PORT_STAT_C_SUSPEND)
3699 pm_wakeup_event(&udev->dev, 0);
3700 goto SuspendCleared;
3701 }
3702
3703 /* see 7.1.7.7; affects power usage, but not budgeting */
3704 if (hub_is_superspeed(hub->hdev))
3705 status = hub_set_port_link_state(hub, port1, USB_SS_PORT_LS_U0);
3706 else
3707 status = usb_clear_port_feature(hub->hdev,
3708 port1, USB_PORT_FEAT_SUSPEND);
3709 if (status) {
3710 dev_dbg(&port_dev->dev, "can't resume, status %d\n", status);
3711 } else {
3712 /* drive resume for USB_RESUME_TIMEOUT msec */
3713 dev_dbg(&udev->dev, "usb %sresume\n",
3714 (PMSG_IS_AUTO(msg) ? "auto-" : ""));
3715 msleep(USB_RESUME_TIMEOUT);
3716
3717 /* Virtual root hubs can trigger on GET_PORT_STATUS to
3718 * stop resume signaling. Then finish the resume
3719 * sequence.
3720 */
3721 status = hub_port_status(hub, port1, &portstatus, &portchange);
3722 }
3723
3724 SuspendCleared:
3725 if (status == 0) {
3726 udev->port_is_suspended = 0;
3727 if (hub_is_superspeed(hub->hdev)) {
3728 if (portchange & USB_PORT_STAT_C_LINK_STATE)
3729 usb_clear_port_feature(hub->hdev, port1,
3730 USB_PORT_FEAT_C_PORT_LINK_STATE);
3731 } else {
3732 if (portchange & USB_PORT_STAT_C_SUSPEND)
3733 usb_clear_port_feature(hub->hdev, port1,
3734 USB_PORT_FEAT_C_SUSPEND);
3735 }
3736
3737 /* TRSMRCY = 10 msec */
3738 msleep(10);
3739 }
3740
3741 if (udev->persist_enabled)
3742 status = wait_for_connected(udev, hub, &port1, &portchange,
3743 &portstatus);
3744
3745 status = check_port_resume_type(udev,
3746 hub, port1, status, portchange, portstatus);
3747 if (status == 0)
3748 status = finish_port_resume(udev);
3749 if (status < 0) {
3750 dev_dbg(&udev->dev, "can't resume, status %d\n", status);
3751 hub_port_logical_disconnect(hub, port1);
3752 } else {
3753 /* Try to enable USB2 hardware LPM */
3754 usb_enable_usb2_hardware_lpm(udev);
3755
3756 /* Try to enable USB3 LTM */
3757 usb_enable_ltm(udev);
3758 }
3759
3760 usb_unlock_port(port_dev);
3761
3762 return status;
3763 }
3764
usb_remote_wakeup(struct usb_device * udev)3765 int usb_remote_wakeup(struct usb_device *udev)
3766 {
3767 int status = 0;
3768
3769 usb_lock_device(udev);
3770 if (udev->state == USB_STATE_SUSPENDED) {
3771 dev_dbg(&udev->dev, "usb %sresume\n", "wakeup-");
3772 status = usb_autoresume_device(udev);
3773 if (status == 0) {
3774 /* Let the drivers do their thing, then... */
3775 usb_autosuspend_device(udev);
3776 }
3777 }
3778 usb_unlock_device(udev);
3779 return status;
3780 }
3781
3782 /* 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)3783 static int hub_handle_remote_wakeup(struct usb_hub *hub, unsigned int port,
3784 u16 portstatus, u16 portchange)
3785 __must_hold(&port_dev->status_lock)
3786 {
3787 struct usb_port *port_dev = hub->ports[port - 1];
3788 struct usb_device *hdev;
3789 struct usb_device *udev;
3790 int connect_change = 0;
3791 u16 link_state;
3792 int ret;
3793
3794 hdev = hub->hdev;
3795 udev = port_dev->child;
3796 if (!hub_is_superspeed(hdev)) {
3797 if (!(portchange & USB_PORT_STAT_C_SUSPEND))
3798 return 0;
3799 usb_clear_port_feature(hdev, port, USB_PORT_FEAT_C_SUSPEND);
3800 } else {
3801 link_state = portstatus & USB_PORT_STAT_LINK_STATE;
3802 if (!udev || udev->state != USB_STATE_SUSPENDED ||
3803 (link_state != USB_SS_PORT_LS_U0 &&
3804 link_state != USB_SS_PORT_LS_U1 &&
3805 link_state != USB_SS_PORT_LS_U2))
3806 return 0;
3807 }
3808
3809 if (udev) {
3810 /* TRSMRCY = 10 msec */
3811 msleep(10);
3812
3813 usb_unlock_port(port_dev);
3814 ret = usb_remote_wakeup(udev);
3815 usb_lock_port(port_dev);
3816 if (ret < 0)
3817 connect_change = 1;
3818 } else {
3819 ret = -ENODEV;
3820 hub_port_disable(hub, port, 1);
3821 }
3822 dev_dbg(&port_dev->dev, "resume, status %d\n", ret);
3823 return connect_change;
3824 }
3825
check_ports_changed(struct usb_hub * hub)3826 static int check_ports_changed(struct usb_hub *hub)
3827 {
3828 int port1;
3829
3830 for (port1 = 1; port1 <= hub->hdev->maxchild; ++port1) {
3831 u16 portstatus, portchange;
3832 int status;
3833
3834 status = hub_port_status(hub, port1, &portstatus, &portchange);
3835 if (!status && portchange)
3836 return 1;
3837 }
3838 return 0;
3839 }
3840
hub_suspend(struct usb_interface * intf,pm_message_t msg)3841 static int hub_suspend(struct usb_interface *intf, pm_message_t msg)
3842 {
3843 struct usb_hub *hub = usb_get_intfdata(intf);
3844 struct usb_device *hdev = hub->hdev;
3845 unsigned port1;
3846
3847 /*
3848 * Warn if children aren't already suspended.
3849 * Also, add up the number of wakeup-enabled descendants.
3850 */
3851 hub->wakeup_enabled_descendants = 0;
3852 for (port1 = 1; port1 <= hdev->maxchild; port1++) {
3853 struct usb_port *port_dev = hub->ports[port1 - 1];
3854 struct usb_device *udev = port_dev->child;
3855
3856 if (udev && udev->can_submit) {
3857 dev_warn(&port_dev->dev, "device %s not suspended yet\n",
3858 dev_name(&udev->dev));
3859 if (PMSG_IS_AUTO(msg))
3860 return -EBUSY;
3861 }
3862 if (udev)
3863 hub->wakeup_enabled_descendants +=
3864 usb_wakeup_enabled_descendants(udev);
3865 }
3866
3867 if (hdev->do_remote_wakeup && hub->quirk_check_port_auto_suspend) {
3868 /* check if there are changes pending on hub ports */
3869 if (check_ports_changed(hub)) {
3870 if (PMSG_IS_AUTO(msg))
3871 return -EBUSY;
3872 pm_wakeup_event(&hdev->dev, 2000);
3873 }
3874 }
3875
3876 if (hub_is_superspeed(hdev) && hdev->do_remote_wakeup) {
3877 /* Enable hub to send remote wakeup for all ports. */
3878 for (port1 = 1; port1 <= hdev->maxchild; port1++) {
3879 set_port_feature(hdev,
3880 port1 |
3881 USB_PORT_FEAT_REMOTE_WAKE_CONNECT |
3882 USB_PORT_FEAT_REMOTE_WAKE_DISCONNECT |
3883 USB_PORT_FEAT_REMOTE_WAKE_OVER_CURRENT,
3884 USB_PORT_FEAT_REMOTE_WAKE_MASK);
3885 }
3886 }
3887
3888 dev_dbg(&intf->dev, "%s\n", __func__);
3889
3890 /* stop hub_wq and related activity */
3891 hub_quiesce(hub, HUB_SUSPEND);
3892 return 0;
3893 }
3894
3895 /* Report wakeup requests from the ports of a resuming root hub */
report_wakeup_requests(struct usb_hub * hub)3896 static void report_wakeup_requests(struct usb_hub *hub)
3897 {
3898 struct usb_device *hdev = hub->hdev;
3899 struct usb_device *udev;
3900 struct usb_hcd *hcd;
3901 unsigned long resuming_ports;
3902 int i;
3903
3904 if (hdev->parent)
3905 return; /* Not a root hub */
3906
3907 hcd = bus_to_hcd(hdev->bus);
3908 if (hcd->driver->get_resuming_ports) {
3909
3910 /*
3911 * The get_resuming_ports() method returns a bitmap (origin 0)
3912 * of ports which have started wakeup signaling but have not
3913 * yet finished resuming. During system resume we will
3914 * resume all the enabled ports, regardless of any wakeup
3915 * signals, which means the wakeup requests would be lost.
3916 * To prevent this, report them to the PM core here.
3917 */
3918 resuming_ports = hcd->driver->get_resuming_ports(hcd);
3919 for (i = 0; i < hdev->maxchild; ++i) {
3920 if (test_bit(i, &resuming_ports)) {
3921 udev = hub->ports[i]->child;
3922 if (udev)
3923 pm_wakeup_event(&udev->dev, 0);
3924 }
3925 }
3926 }
3927 }
3928
hub_resume(struct usb_interface * intf)3929 static int hub_resume(struct usb_interface *intf)
3930 {
3931 struct usb_hub *hub = usb_get_intfdata(intf);
3932
3933 dev_dbg(&intf->dev, "%s\n", __func__);
3934 hub_activate(hub, HUB_RESUME);
3935
3936 /*
3937 * This should be called only for system resume, not runtime resume.
3938 * We can't tell the difference here, so some wakeup requests will be
3939 * reported at the wrong time or more than once. This shouldn't
3940 * matter much, so long as they do get reported.
3941 */
3942 report_wakeup_requests(hub);
3943 return 0;
3944 }
3945
hub_reset_resume(struct usb_interface * intf)3946 static int hub_reset_resume(struct usb_interface *intf)
3947 {
3948 struct usb_hub *hub = usb_get_intfdata(intf);
3949
3950 dev_dbg(&intf->dev, "%s\n", __func__);
3951 hub_activate(hub, HUB_RESET_RESUME);
3952 return 0;
3953 }
3954
3955 /**
3956 * usb_root_hub_lost_power - called by HCD if the root hub lost Vbus power
3957 * @rhdev: struct usb_device for the root hub
3958 *
3959 * The USB host controller driver calls this function when its root hub
3960 * is resumed and Vbus power has been interrupted or the controller
3961 * has been reset. The routine marks @rhdev as having lost power.
3962 * When the hub driver is resumed it will take notice and carry out
3963 * power-session recovery for all the "USB-PERSIST"-enabled child devices;
3964 * the others will be disconnected.
3965 */
usb_root_hub_lost_power(struct usb_device * rhdev)3966 void usb_root_hub_lost_power(struct usb_device *rhdev)
3967 {
3968 dev_notice(&rhdev->dev, "root hub lost power or was reset\n");
3969 rhdev->reset_resume = 1;
3970 }
3971 EXPORT_SYMBOL_GPL(usb_root_hub_lost_power);
3972
3973 static const char * const usb3_lpm_names[] = {
3974 "U0",
3975 "U1",
3976 "U2",
3977 "U3",
3978 };
3979
3980 /*
3981 * Send a Set SEL control transfer to the device, prior to enabling
3982 * device-initiated U1 or U2. This lets the device know the exit latencies from
3983 * the time the device initiates a U1 or U2 exit, to the time it will receive a
3984 * packet from the host.
3985 *
3986 * This function will fail if the SEL or PEL values for udev are greater than
3987 * the maximum allowed values for the link state to be enabled.
3988 */
usb_req_set_sel(struct usb_device * udev,enum usb3_link_state state)3989 static int usb_req_set_sel(struct usb_device *udev, enum usb3_link_state state)
3990 {
3991 struct usb_set_sel_req *sel_values;
3992 unsigned long long u1_sel;
3993 unsigned long long u1_pel;
3994 unsigned long long u2_sel;
3995 unsigned long long u2_pel;
3996 int ret;
3997
3998 if (udev->state != USB_STATE_CONFIGURED)
3999 return 0;
4000
4001 /* Convert SEL and PEL stored in ns to us */
4002 u1_sel = DIV_ROUND_UP(udev->u1_params.sel, 1000);
4003 u1_pel = DIV_ROUND_UP(udev->u1_params.pel, 1000);
4004 u2_sel = DIV_ROUND_UP(udev->u2_params.sel, 1000);
4005 u2_pel = DIV_ROUND_UP(udev->u2_params.pel, 1000);
4006
4007 /*
4008 * Make sure that the calculated SEL and PEL values for the link
4009 * state we're enabling aren't bigger than the max SEL/PEL
4010 * value that will fit in the SET SEL control transfer.
4011 * Otherwise the device would get an incorrect idea of the exit
4012 * latency for the link state, and could start a device-initiated
4013 * U1/U2 when the exit latencies are too high.
4014 */
4015 if ((state == USB3_LPM_U1 &&
4016 (u1_sel > USB3_LPM_MAX_U1_SEL_PEL ||
4017 u1_pel > USB3_LPM_MAX_U1_SEL_PEL)) ||
4018 (state == USB3_LPM_U2 &&
4019 (u2_sel > USB3_LPM_MAX_U2_SEL_PEL ||
4020 u2_pel > USB3_LPM_MAX_U2_SEL_PEL))) {
4021 dev_dbg(&udev->dev, "Device-initiated %s disabled due to long SEL %llu us or PEL %llu us\n",
4022 usb3_lpm_names[state], u1_sel, u1_pel);
4023 return -EINVAL;
4024 }
4025
4026 /*
4027 * If we're enabling device-initiated LPM for one link state,
4028 * but the other link state has a too high SEL or PEL value,
4029 * just set those values to the max in the Set SEL request.
4030 */
4031 if (u1_sel > USB3_LPM_MAX_U1_SEL_PEL)
4032 u1_sel = USB3_LPM_MAX_U1_SEL_PEL;
4033
4034 if (u1_pel > USB3_LPM_MAX_U1_SEL_PEL)
4035 u1_pel = USB3_LPM_MAX_U1_SEL_PEL;
4036
4037 if (u2_sel > USB3_LPM_MAX_U2_SEL_PEL)
4038 u2_sel = USB3_LPM_MAX_U2_SEL_PEL;
4039
4040 if (u2_pel > USB3_LPM_MAX_U2_SEL_PEL)
4041 u2_pel = USB3_LPM_MAX_U2_SEL_PEL;
4042
4043 /*
4044 * usb_enable_lpm() can be called as part of a failed device reset,
4045 * which may be initiated by an error path of a mass storage driver.
4046 * Therefore, use GFP_NOIO.
4047 */
4048 sel_values = kmalloc(sizeof *(sel_values), GFP_NOIO);
4049 if (!sel_values)
4050 return -ENOMEM;
4051
4052 sel_values->u1_sel = u1_sel;
4053 sel_values->u1_pel = u1_pel;
4054 sel_values->u2_sel = cpu_to_le16(u2_sel);
4055 sel_values->u2_pel = cpu_to_le16(u2_pel);
4056
4057 ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
4058 USB_REQ_SET_SEL,
4059 USB_RECIP_DEVICE,
4060 0, 0,
4061 sel_values, sizeof *(sel_values),
4062 USB_CTRL_SET_TIMEOUT);
4063 kfree(sel_values);
4064 return ret;
4065 }
4066
4067 /*
4068 * Enable or disable device-initiated U1 or U2 transitions.
4069 */
usb_set_device_initiated_lpm(struct usb_device * udev,enum usb3_link_state state,bool enable)4070 static int usb_set_device_initiated_lpm(struct usb_device *udev,
4071 enum usb3_link_state state, bool enable)
4072 {
4073 int ret;
4074 int feature;
4075
4076 switch (state) {
4077 case USB3_LPM_U1:
4078 feature = USB_DEVICE_U1_ENABLE;
4079 break;
4080 case USB3_LPM_U2:
4081 feature = USB_DEVICE_U2_ENABLE;
4082 break;
4083 default:
4084 dev_warn(&udev->dev, "%s: Can't %s non-U1 or U2 state.\n",
4085 __func__, enable ? "enable" : "disable");
4086 return -EINVAL;
4087 }
4088
4089 if (udev->state != USB_STATE_CONFIGURED) {
4090 dev_dbg(&udev->dev, "%s: Can't %s %s state "
4091 "for unconfigured device.\n",
4092 __func__, enable ? "enable" : "disable",
4093 usb3_lpm_names[state]);
4094 return 0;
4095 }
4096
4097 if (enable) {
4098 /*
4099 * Now send the control transfer to enable device-initiated LPM
4100 * for either U1 or U2.
4101 */
4102 ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
4103 USB_REQ_SET_FEATURE,
4104 USB_RECIP_DEVICE,
4105 feature,
4106 0, NULL, 0,
4107 USB_CTRL_SET_TIMEOUT);
4108 } else {
4109 ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
4110 USB_REQ_CLEAR_FEATURE,
4111 USB_RECIP_DEVICE,
4112 feature,
4113 0, NULL, 0,
4114 USB_CTRL_SET_TIMEOUT);
4115 }
4116 if (ret < 0) {
4117 dev_warn(&udev->dev, "%s of device-initiated %s failed.\n",
4118 enable ? "Enable" : "Disable",
4119 usb3_lpm_names[state]);
4120 return -EBUSY;
4121 }
4122 return 0;
4123 }
4124
usb_set_lpm_timeout(struct usb_device * udev,enum usb3_link_state state,int timeout)4125 static int usb_set_lpm_timeout(struct usb_device *udev,
4126 enum usb3_link_state state, int timeout)
4127 {
4128 int ret;
4129 int feature;
4130
4131 switch (state) {
4132 case USB3_LPM_U1:
4133 feature = USB_PORT_FEAT_U1_TIMEOUT;
4134 break;
4135 case USB3_LPM_U2:
4136 feature = USB_PORT_FEAT_U2_TIMEOUT;
4137 break;
4138 default:
4139 dev_warn(&udev->dev, "%s: Can't set timeout for non-U1 or U2 state.\n",
4140 __func__);
4141 return -EINVAL;
4142 }
4143
4144 if (state == USB3_LPM_U1 && timeout > USB3_LPM_U1_MAX_TIMEOUT &&
4145 timeout != USB3_LPM_DEVICE_INITIATED) {
4146 dev_warn(&udev->dev, "Failed to set %s timeout to 0x%x, "
4147 "which is a reserved value.\n",
4148 usb3_lpm_names[state], timeout);
4149 return -EINVAL;
4150 }
4151
4152 ret = set_port_feature(udev->parent,
4153 USB_PORT_LPM_TIMEOUT(timeout) | udev->portnum,
4154 feature);
4155 if (ret < 0) {
4156 dev_warn(&udev->dev, "Failed to set %s timeout to 0x%x,"
4157 "error code %i\n", usb3_lpm_names[state],
4158 timeout, ret);
4159 return -EBUSY;
4160 }
4161 if (state == USB3_LPM_U1)
4162 udev->u1_params.timeout = timeout;
4163 else
4164 udev->u2_params.timeout = timeout;
4165 return 0;
4166 }
4167
4168 /*
4169 * Don't allow device intiated U1/U2 if the system exit latency + one bus
4170 * interval is greater than the minimum service interval of any active
4171 * periodic endpoint. See USB 3.2 section 9.4.9
4172 */
usb_device_may_initiate_lpm(struct usb_device * udev,enum usb3_link_state state)4173 static bool usb_device_may_initiate_lpm(struct usb_device *udev,
4174 enum usb3_link_state state)
4175 {
4176 unsigned int sel; /* us */
4177 int i, j;
4178
4179 if (state == USB3_LPM_U1)
4180 sel = DIV_ROUND_UP(udev->u1_params.sel, 1000);
4181 else if (state == USB3_LPM_U2)
4182 sel = DIV_ROUND_UP(udev->u2_params.sel, 1000);
4183 else
4184 return false;
4185
4186 for (i = 0; i < udev->actconfig->desc.bNumInterfaces; i++) {
4187 struct usb_interface *intf;
4188 struct usb_endpoint_descriptor *desc;
4189 unsigned int interval;
4190
4191 intf = udev->actconfig->interface[i];
4192 if (!intf)
4193 continue;
4194
4195 for (j = 0; j < intf->cur_altsetting->desc.bNumEndpoints; j++) {
4196 desc = &intf->cur_altsetting->endpoint[j].desc;
4197
4198 if (usb_endpoint_xfer_int(desc) ||
4199 usb_endpoint_xfer_isoc(desc)) {
4200 interval = (1 << (desc->bInterval - 1)) * 125;
4201 if (sel + 125 > interval)
4202 return false;
4203 }
4204 }
4205 }
4206 return true;
4207 }
4208
4209 /*
4210 * Enable the hub-initiated U1/U2 idle timeouts, and enable device-initiated
4211 * U1/U2 entry.
4212 *
4213 * We will attempt to enable U1 or U2, but there are no guarantees that the
4214 * control transfers to set the hub timeout or enable device-initiated U1/U2
4215 * will be successful.
4216 *
4217 * If the control transfer to enable device-initiated U1/U2 entry fails, then
4218 * hub-initiated U1/U2 will be disabled.
4219 *
4220 * If we cannot set the parent hub U1/U2 timeout, we attempt to let the xHCI
4221 * driver know about it. If that call fails, it should be harmless, and just
4222 * take up more slightly more bus bandwidth for unnecessary U1/U2 exit latency.
4223 */
usb_enable_link_state(struct usb_hcd * hcd,struct usb_device * udev,enum usb3_link_state state)4224 static void usb_enable_link_state(struct usb_hcd *hcd, struct usb_device *udev,
4225 enum usb3_link_state state)
4226 {
4227 int timeout, ret;
4228 __u8 u1_mel;
4229 __le16 u2_mel;
4230
4231 /* Skip if the device BOS descriptor couldn't be read */
4232 if (!udev->bos)
4233 return;
4234
4235 u1_mel = udev->bos->ss_cap->bU1devExitLat;
4236 u2_mel = udev->bos->ss_cap->bU2DevExitLat;
4237
4238 /* If the device says it doesn't have *any* exit latency to come out of
4239 * U1 or U2, it's probably lying. Assume it doesn't implement that link
4240 * state.
4241 */
4242 if ((state == USB3_LPM_U1 && u1_mel == 0) ||
4243 (state == USB3_LPM_U2 && u2_mel == 0))
4244 return;
4245
4246 /*
4247 * First, let the device know about the exit latencies
4248 * associated with the link state we're about to enable.
4249 */
4250 ret = usb_req_set_sel(udev, state);
4251 if (ret < 0) {
4252 dev_warn(&udev->dev, "Set SEL for device-initiated %s failed.\n",
4253 usb3_lpm_names[state]);
4254 return;
4255 }
4256
4257 /* We allow the host controller to set the U1/U2 timeout internally
4258 * first, so that it can change its schedule to account for the
4259 * additional latency to send data to a device in a lower power
4260 * link state.
4261 */
4262 timeout = hcd->driver->enable_usb3_lpm_timeout(hcd, udev, state);
4263
4264 /* xHCI host controller doesn't want to enable this LPM state. */
4265 if (timeout == 0)
4266 return;
4267
4268 if (timeout < 0) {
4269 dev_warn(&udev->dev, "Could not enable %s link state, "
4270 "xHCI error %i.\n", usb3_lpm_names[state],
4271 timeout);
4272 return;
4273 }
4274
4275 if (usb_set_lpm_timeout(udev, state, timeout)) {
4276 /* If we can't set the parent hub U1/U2 timeout,
4277 * device-initiated LPM won't be allowed either, so let the xHCI
4278 * host know that this link state won't be enabled.
4279 */
4280 hcd->driver->disable_usb3_lpm_timeout(hcd, udev, state);
4281 return;
4282 }
4283
4284 /* Only a configured device will accept the Set Feature
4285 * U1/U2_ENABLE
4286 */
4287 if (udev->actconfig &&
4288 usb_device_may_initiate_lpm(udev, state)) {
4289 if (usb_set_device_initiated_lpm(udev, state, true)) {
4290 /*
4291 * Request to enable device initiated U1/U2 failed,
4292 * better to turn off lpm in this case.
4293 */
4294 usb_set_lpm_timeout(udev, state, 0);
4295 hcd->driver->disable_usb3_lpm_timeout(hcd, udev, state);
4296 return;
4297 }
4298 }
4299
4300 if (state == USB3_LPM_U1)
4301 udev->usb3_lpm_u1_enabled = 1;
4302 else if (state == USB3_LPM_U2)
4303 udev->usb3_lpm_u2_enabled = 1;
4304 }
4305 /*
4306 * Disable the hub-initiated U1/U2 idle timeouts, and disable device-initiated
4307 * U1/U2 entry.
4308 *
4309 * If this function returns -EBUSY, the parent hub will still allow U1/U2 entry.
4310 * If zero is returned, the parent will not allow the link to go into U1/U2.
4311 *
4312 * If zero is returned, device-initiated U1/U2 entry may still be enabled, but
4313 * it won't have an effect on the bus link state because the parent hub will
4314 * still disallow device-initiated U1/U2 entry.
4315 *
4316 * If zero is returned, the xHCI host controller may still think U1/U2 entry is
4317 * possible. The result will be slightly more bus bandwidth will be taken up
4318 * (to account for U1/U2 exit latency), but it should be harmless.
4319 */
usb_disable_link_state(struct usb_hcd * hcd,struct usb_device * udev,enum usb3_link_state state)4320 static int usb_disable_link_state(struct usb_hcd *hcd, struct usb_device *udev,
4321 enum usb3_link_state state)
4322 {
4323 switch (state) {
4324 case USB3_LPM_U1:
4325 case USB3_LPM_U2:
4326 break;
4327 default:
4328 dev_warn(&udev->dev, "%s: Can't disable non-U1 or U2 state.\n",
4329 __func__);
4330 return -EINVAL;
4331 }
4332
4333 if (usb_set_lpm_timeout(udev, state, 0))
4334 return -EBUSY;
4335
4336 usb_set_device_initiated_lpm(udev, state, false);
4337
4338 if (hcd->driver->disable_usb3_lpm_timeout(hcd, udev, state))
4339 dev_warn(&udev->dev, "Could not disable xHCI %s timeout, "
4340 "bus schedule bandwidth may be impacted.\n",
4341 usb3_lpm_names[state]);
4342
4343 /* As soon as usb_set_lpm_timeout(0) return 0, hub initiated LPM
4344 * is disabled. Hub will disallows link to enter U1/U2 as well,
4345 * even device is initiating LPM. Hence LPM is disabled if hub LPM
4346 * timeout set to 0, no matter device-initiated LPM is disabled or
4347 * not.
4348 */
4349 if (state == USB3_LPM_U1)
4350 udev->usb3_lpm_u1_enabled = 0;
4351 else if (state == USB3_LPM_U2)
4352 udev->usb3_lpm_u2_enabled = 0;
4353
4354 return 0;
4355 }
4356
4357 /*
4358 * Disable hub-initiated and device-initiated U1 and U2 entry.
4359 * Caller must own the bandwidth_mutex.
4360 *
4361 * This will call usb_enable_lpm() on failure, which will decrement
4362 * lpm_disable_count, and will re-enable LPM if lpm_disable_count reaches zero.
4363 */
usb_disable_lpm(struct usb_device * udev)4364 int usb_disable_lpm(struct usb_device *udev)
4365 {
4366 struct usb_hcd *hcd;
4367
4368 if (!udev || !udev->parent ||
4369 udev->speed < USB_SPEED_SUPER ||
4370 !udev->lpm_capable ||
4371 udev->state < USB_STATE_CONFIGURED)
4372 return 0;
4373
4374 hcd = bus_to_hcd(udev->bus);
4375 if (!hcd || !hcd->driver->disable_usb3_lpm_timeout)
4376 return 0;
4377
4378 udev->lpm_disable_count++;
4379 if ((udev->u1_params.timeout == 0 && udev->u2_params.timeout == 0))
4380 return 0;
4381
4382 /* If LPM is enabled, attempt to disable it. */
4383 if (usb_disable_link_state(hcd, udev, USB3_LPM_U1))
4384 goto enable_lpm;
4385 if (usb_disable_link_state(hcd, udev, USB3_LPM_U2))
4386 goto enable_lpm;
4387
4388 return 0;
4389
4390 enable_lpm:
4391 usb_enable_lpm(udev);
4392 return -EBUSY;
4393 }
4394 EXPORT_SYMBOL_GPL(usb_disable_lpm);
4395
4396 /* Grab the bandwidth_mutex before calling usb_disable_lpm() */
usb_unlocked_disable_lpm(struct usb_device * udev)4397 int usb_unlocked_disable_lpm(struct usb_device *udev)
4398 {
4399 struct usb_hcd *hcd = bus_to_hcd(udev->bus);
4400 int ret;
4401
4402 if (!hcd)
4403 return -EINVAL;
4404
4405 mutex_lock(hcd->bandwidth_mutex);
4406 ret = usb_disable_lpm(udev);
4407 mutex_unlock(hcd->bandwidth_mutex);
4408
4409 return ret;
4410 }
4411 EXPORT_SYMBOL_GPL(usb_unlocked_disable_lpm);
4412
4413 /*
4414 * Attempt to enable device-initiated and hub-initiated U1 and U2 entry. The
4415 * xHCI host policy may prevent U1 or U2 from being enabled.
4416 *
4417 * Other callers may have disabled link PM, so U1 and U2 entry will be disabled
4418 * until the lpm_disable_count drops to zero. Caller must own the
4419 * bandwidth_mutex.
4420 */
usb_enable_lpm(struct usb_device * udev)4421 void usb_enable_lpm(struct usb_device *udev)
4422 {
4423 struct usb_hcd *hcd;
4424 struct usb_hub *hub;
4425 struct usb_port *port_dev;
4426
4427 if (!udev || !udev->parent ||
4428 udev->speed < USB_SPEED_SUPER ||
4429 !udev->lpm_capable ||
4430 udev->state < USB_STATE_CONFIGURED)
4431 return;
4432
4433 udev->lpm_disable_count--;
4434 hcd = bus_to_hcd(udev->bus);
4435 /* Double check that we can both enable and disable LPM.
4436 * Device must be configured to accept set feature U1/U2 timeout.
4437 */
4438 if (!hcd || !hcd->driver->enable_usb3_lpm_timeout ||
4439 !hcd->driver->disable_usb3_lpm_timeout)
4440 return;
4441
4442 if (udev->lpm_disable_count > 0)
4443 return;
4444
4445 hub = usb_hub_to_struct_hub(udev->parent);
4446 if (!hub)
4447 return;
4448
4449 port_dev = hub->ports[udev->portnum - 1];
4450
4451 if (port_dev->usb3_lpm_u1_permit)
4452 usb_enable_link_state(hcd, udev, USB3_LPM_U1);
4453
4454 if (port_dev->usb3_lpm_u2_permit)
4455 usb_enable_link_state(hcd, udev, USB3_LPM_U2);
4456 }
4457 EXPORT_SYMBOL_GPL(usb_enable_lpm);
4458
4459 /* Grab the bandwidth_mutex before calling usb_enable_lpm() */
usb_unlocked_enable_lpm(struct usb_device * udev)4460 void usb_unlocked_enable_lpm(struct usb_device *udev)
4461 {
4462 struct usb_hcd *hcd = bus_to_hcd(udev->bus);
4463
4464 if (!hcd)
4465 return;
4466
4467 mutex_lock(hcd->bandwidth_mutex);
4468 usb_enable_lpm(udev);
4469 mutex_unlock(hcd->bandwidth_mutex);
4470 }
4471 EXPORT_SYMBOL_GPL(usb_unlocked_enable_lpm);
4472
4473 /* 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)4474 static void hub_usb3_port_prepare_disable(struct usb_hub *hub,
4475 struct usb_port *port_dev)
4476 {
4477 struct usb_device *udev = port_dev->child;
4478 int ret;
4479
4480 if (udev && udev->port_is_suspended && udev->do_remote_wakeup) {
4481 ret = hub_set_port_link_state(hub, port_dev->portnum,
4482 USB_SS_PORT_LS_U0);
4483 if (!ret) {
4484 msleep(USB_RESUME_TIMEOUT);
4485 ret = usb_disable_remote_wakeup(udev);
4486 }
4487 if (ret)
4488 dev_warn(&udev->dev,
4489 "Port disable: can't disable remote wake\n");
4490 udev->do_remote_wakeup = 0;
4491 }
4492 }
4493
4494 #else /* CONFIG_PM */
4495
4496 #define hub_suspend NULL
4497 #define hub_resume NULL
4498 #define hub_reset_resume NULL
4499
hub_usb3_port_prepare_disable(struct usb_hub * hub,struct usb_port * port_dev)4500 static inline void hub_usb3_port_prepare_disable(struct usb_hub *hub,
4501 struct usb_port *port_dev) { }
4502
usb_disable_lpm(struct usb_device * udev)4503 int usb_disable_lpm(struct usb_device *udev)
4504 {
4505 return 0;
4506 }
4507 EXPORT_SYMBOL_GPL(usb_disable_lpm);
4508
usb_enable_lpm(struct usb_device * udev)4509 void usb_enable_lpm(struct usb_device *udev) { }
4510 EXPORT_SYMBOL_GPL(usb_enable_lpm);
4511
usb_unlocked_disable_lpm(struct usb_device * udev)4512 int usb_unlocked_disable_lpm(struct usb_device *udev)
4513 {
4514 return 0;
4515 }
4516 EXPORT_SYMBOL_GPL(usb_unlocked_disable_lpm);
4517
usb_unlocked_enable_lpm(struct usb_device * udev)4518 void usb_unlocked_enable_lpm(struct usb_device *udev) { }
4519 EXPORT_SYMBOL_GPL(usb_unlocked_enable_lpm);
4520
usb_disable_ltm(struct usb_device * udev)4521 int usb_disable_ltm(struct usb_device *udev)
4522 {
4523 return 0;
4524 }
4525 EXPORT_SYMBOL_GPL(usb_disable_ltm);
4526
usb_enable_ltm(struct usb_device * udev)4527 void usb_enable_ltm(struct usb_device *udev) { }
4528 EXPORT_SYMBOL_GPL(usb_enable_ltm);
4529
hub_handle_remote_wakeup(struct usb_hub * hub,unsigned int port,u16 portstatus,u16 portchange)4530 static int hub_handle_remote_wakeup(struct usb_hub *hub, unsigned int port,
4531 u16 portstatus, u16 portchange)
4532 {
4533 return 0;
4534 }
4535
4536 #endif /* CONFIG_PM */
4537
4538 /*
4539 * USB-3 does not have a similar link state as USB-2 that will avoid negotiating
4540 * a connection with a plugged-in cable but will signal the host when the cable
4541 * is unplugged. Disable remote wake and set link state to U3 for USB-3 devices
4542 */
hub_port_disable(struct usb_hub * hub,int port1,int set_state)4543 static int hub_port_disable(struct usb_hub *hub, int port1, int set_state)
4544 {
4545 struct usb_port *port_dev = hub->ports[port1 - 1];
4546 struct usb_device *hdev = hub->hdev;
4547 int ret = 0;
4548
4549 if (!hub->error) {
4550 if (hub_is_superspeed(hub->hdev)) {
4551 hub_usb3_port_prepare_disable(hub, port_dev);
4552 ret = hub_set_port_link_state(hub, port_dev->portnum,
4553 USB_SS_PORT_LS_U3);
4554 } else {
4555 ret = usb_clear_port_feature(hdev, port1,
4556 USB_PORT_FEAT_ENABLE);
4557 }
4558 }
4559 if (port_dev->child && set_state)
4560 usb_set_device_state(port_dev->child, USB_STATE_NOTATTACHED);
4561 if (ret && ret != -ENODEV)
4562 dev_err(&port_dev->dev, "cannot disable (err = %d)\n", ret);
4563 return ret;
4564 }
4565
4566 /*
4567 * usb_port_disable - disable a usb device's upstream port
4568 * @udev: device to disable
4569 * Context: @udev locked, must be able to sleep.
4570 *
4571 * Disables a USB device that isn't in active use.
4572 */
usb_port_disable(struct usb_device * udev)4573 int usb_port_disable(struct usb_device *udev)
4574 {
4575 struct usb_hub *hub = usb_hub_to_struct_hub(udev->parent);
4576
4577 return hub_port_disable(hub, udev->portnum, 0);
4578 }
4579
4580 /* USB 2.0 spec, 7.1.7.3 / fig 7-29:
4581 *
4582 * Between connect detection and reset signaling there must be a delay
4583 * of 100ms at least for debounce and power-settling. The corresponding
4584 * timer shall restart whenever the downstream port detects a disconnect.
4585 *
4586 * Apparently there are some bluetooth and irda-dongles and a number of
4587 * low-speed devices for which this debounce period may last over a second.
4588 * Not covered by the spec - but easy to deal with.
4589 *
4590 * This implementation uses a 1500ms total debounce timeout; if the
4591 * connection isn't stable by then it returns -ETIMEDOUT. It checks
4592 * every 25ms for transient disconnects. When the port status has been
4593 * unchanged for 100ms it returns the port status.
4594 */
hub_port_debounce(struct usb_hub * hub,int port1,bool must_be_connected)4595 int hub_port_debounce(struct usb_hub *hub, int port1, bool must_be_connected)
4596 {
4597 int ret;
4598 u16 portchange, portstatus;
4599 unsigned connection = 0xffff;
4600 int total_time, stable_time = 0;
4601 struct usb_port *port_dev = hub->ports[port1 - 1];
4602
4603 for (total_time = 0; ; total_time += HUB_DEBOUNCE_STEP) {
4604 ret = hub_port_status(hub, port1, &portstatus, &portchange);
4605 if (ret < 0)
4606 return ret;
4607
4608 if (!(portchange & USB_PORT_STAT_C_CONNECTION) &&
4609 (portstatus & USB_PORT_STAT_CONNECTION) == connection) {
4610 if (!must_be_connected ||
4611 (connection == USB_PORT_STAT_CONNECTION))
4612 stable_time += HUB_DEBOUNCE_STEP;
4613 if (stable_time >= HUB_DEBOUNCE_STABLE)
4614 break;
4615 } else {
4616 stable_time = 0;
4617 connection = portstatus & USB_PORT_STAT_CONNECTION;
4618 }
4619
4620 if (portchange & USB_PORT_STAT_C_CONNECTION) {
4621 usb_clear_port_feature(hub->hdev, port1,
4622 USB_PORT_FEAT_C_CONNECTION);
4623 }
4624
4625 if (total_time >= HUB_DEBOUNCE_TIMEOUT)
4626 break;
4627 msleep(HUB_DEBOUNCE_STEP);
4628 }
4629
4630 dev_dbg(&port_dev->dev, "debounce total %dms stable %dms status 0x%x\n",
4631 total_time, stable_time, portstatus);
4632
4633 if (stable_time < HUB_DEBOUNCE_STABLE)
4634 return -ETIMEDOUT;
4635 return portstatus;
4636 }
4637
usb_ep0_reinit(struct usb_device * udev)4638 void usb_ep0_reinit(struct usb_device *udev)
4639 {
4640 usb_disable_endpoint(udev, 0 + USB_DIR_IN, true);
4641 usb_disable_endpoint(udev, 0 + USB_DIR_OUT, true);
4642 usb_enable_endpoint(udev, &udev->ep0, true);
4643 }
4644 EXPORT_SYMBOL_GPL(usb_ep0_reinit);
4645
4646 #define usb_sndaddr0pipe() (PIPE_CONTROL << 30)
4647 #define usb_rcvaddr0pipe() ((PIPE_CONTROL << 30) | USB_DIR_IN)
4648
hub_set_address(struct usb_device * udev,int devnum)4649 static int hub_set_address(struct usb_device *udev, int devnum)
4650 {
4651 int retval;
4652 struct usb_hcd *hcd = bus_to_hcd(udev->bus);
4653
4654 /*
4655 * The host controller will choose the device address,
4656 * instead of the core having chosen it earlier
4657 */
4658 if (!hcd->driver->address_device && devnum <= 1)
4659 return -EINVAL;
4660 if (udev->state == USB_STATE_ADDRESS)
4661 return 0;
4662 if (udev->state != USB_STATE_DEFAULT)
4663 return -EINVAL;
4664 if (hcd->driver->address_device)
4665 retval = hcd->driver->address_device(hcd, udev);
4666 else
4667 retval = usb_control_msg(udev, usb_sndaddr0pipe(),
4668 USB_REQ_SET_ADDRESS, 0, devnum, 0,
4669 NULL, 0, USB_CTRL_SET_TIMEOUT);
4670 if (retval == 0) {
4671 update_devnum(udev, devnum);
4672 /* Device now using proper address. */
4673 usb_set_device_state(udev, USB_STATE_ADDRESS);
4674 usb_ep0_reinit(udev);
4675 }
4676 return retval;
4677 }
4678
4679 /*
4680 * There are reports of USB 3.0 devices that say they support USB 2.0 Link PM
4681 * when they're plugged into a USB 2.0 port, but they don't work when LPM is
4682 * enabled.
4683 *
4684 * Only enable USB 2.0 Link PM if the port is internal (hardwired), or the
4685 * device says it supports the new USB 2.0 Link PM errata by setting the BESL
4686 * support bit in the BOS descriptor.
4687 */
hub_set_initial_usb2_lpm_policy(struct usb_device * udev)4688 static void hub_set_initial_usb2_lpm_policy(struct usb_device *udev)
4689 {
4690 struct usb_hub *hub = usb_hub_to_struct_hub(udev->parent);
4691 int connect_type = USB_PORT_CONNECT_TYPE_UNKNOWN;
4692
4693 if (!udev->usb2_hw_lpm_capable || !udev->bos)
4694 return;
4695
4696 if (hub)
4697 connect_type = hub->ports[udev->portnum - 1]->connect_type;
4698
4699 if ((udev->bos->ext_cap->bmAttributes & cpu_to_le32(USB_BESL_SUPPORT)) ||
4700 connect_type == USB_PORT_CONNECT_TYPE_HARD_WIRED) {
4701 udev->usb2_hw_lpm_allowed = 1;
4702 usb_enable_usb2_hardware_lpm(udev);
4703 }
4704 }
4705
hub_enable_device(struct usb_device * udev)4706 static int hub_enable_device(struct usb_device *udev)
4707 {
4708 struct usb_hcd *hcd = bus_to_hcd(udev->bus);
4709
4710 if (!hcd->driver->enable_device)
4711 return 0;
4712 if (udev->state == USB_STATE_ADDRESS)
4713 return 0;
4714 if (udev->state != USB_STATE_DEFAULT)
4715 return -EINVAL;
4716
4717 return hcd->driver->enable_device(hcd, udev);
4718 }
4719
4720 /*
4721 * Get the bMaxPacketSize0 value during initialization by reading the
4722 * device's device descriptor. Since we don't already know this value,
4723 * the transfer is unsafe and it ignores I/O errors, only testing for
4724 * reasonable received values.
4725 *
4726 * For "old scheme" initialization, size will be 8 so we read just the
4727 * start of the device descriptor, which should work okay regardless of
4728 * the actual bMaxPacketSize0 value. For "new scheme" initialization,
4729 * size will be 64 (and buf will point to a sufficiently large buffer),
4730 * which might not be kosher according to the USB spec but it's what
4731 * Windows does and what many devices expect.
4732 *
4733 * Returns: bMaxPacketSize0 or a negative error code.
4734 */
get_bMaxPacketSize0(struct usb_device * udev,struct usb_device_descriptor * buf,int size,bool first_time)4735 static int get_bMaxPacketSize0(struct usb_device *udev,
4736 struct usb_device_descriptor *buf, int size, bool first_time)
4737 {
4738 int i, rc;
4739
4740 /*
4741 * Retry on all errors; some devices are flakey.
4742 * 255 is for WUSB devices, we actually need to use
4743 * 512 (WUSB1.0[4.8.1]).
4744 */
4745 for (i = 0; i < GET_MAXPACKET0_TRIES; ++i) {
4746 /* Start with invalid values in case the transfer fails */
4747 buf->bDescriptorType = buf->bMaxPacketSize0 = 0;
4748 rc = usb_control_msg(udev, usb_rcvaddr0pipe(),
4749 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
4750 USB_DT_DEVICE << 8, 0,
4751 buf, size,
4752 initial_descriptor_timeout);
4753 switch (buf->bMaxPacketSize0) {
4754 case 8: case 16: case 32: case 64: case 9:
4755 if (buf->bDescriptorType == USB_DT_DEVICE) {
4756 rc = buf->bMaxPacketSize0;
4757 break;
4758 }
4759 fallthrough;
4760 default:
4761 if (rc >= 0)
4762 rc = -EPROTO;
4763 break;
4764 }
4765
4766 /*
4767 * Some devices time out if they are powered on
4768 * when already connected. They need a second
4769 * reset, so return early. But only on the first
4770 * attempt, lest we get into a time-out/reset loop.
4771 */
4772 if (rc > 0 || (rc == -ETIMEDOUT && first_time &&
4773 udev->speed > USB_SPEED_FULL))
4774 break;
4775 }
4776 return rc;
4777 }
4778
4779 #define GET_DESCRIPTOR_BUFSIZE 64
4780
4781 /* Reset device, (re)assign address, get device descriptor.
4782 * Device connection must be stable, no more debouncing needed.
4783 * Returns device in USB_STATE_ADDRESS, except on error.
4784 *
4785 * If this is called for an already-existing device (as part of
4786 * usb_reset_and_verify_device), the caller must own the device lock and
4787 * the port lock. For a newly detected device that is not accessible
4788 * through any global pointers, it's not necessary to lock the device,
4789 * but it is still necessary to lock the port.
4790 *
4791 * For a newly detected device, @dev_descr must be NULL. The device
4792 * descriptor retrieved from the device will then be stored in
4793 * @udev->descriptor. For an already existing device, @dev_descr
4794 * must be non-NULL. The device descriptor will be stored there,
4795 * not in @udev->descriptor, because descriptors for registered
4796 * devices are meant to be immutable.
4797 */
4798 static int
hub_port_init(struct usb_hub * hub,struct usb_device * udev,int port1,int retry_counter,struct usb_device_descriptor * dev_descr)4799 hub_port_init(struct usb_hub *hub, struct usb_device *udev, int port1,
4800 int retry_counter, struct usb_device_descriptor *dev_descr)
4801 {
4802 struct usb_device *hdev = hub->hdev;
4803 struct usb_hcd *hcd = bus_to_hcd(hdev->bus);
4804 struct usb_port *port_dev = hub->ports[port1 - 1];
4805 int retries, operations, retval, i;
4806 unsigned delay = HUB_SHORT_RESET_TIME;
4807 enum usb_device_speed oldspeed = udev->speed;
4808 const char *speed;
4809 int devnum = udev->devnum;
4810 const char *driver_name;
4811 bool do_new_scheme;
4812 const bool initial = !dev_descr;
4813 int maxp0;
4814 struct usb_device_descriptor *buf, *descr;
4815
4816 buf = kmalloc(GET_DESCRIPTOR_BUFSIZE, GFP_NOIO);
4817 if (!buf)
4818 return -ENOMEM;
4819
4820 /* root hub ports have a slightly longer reset period
4821 * (from USB 2.0 spec, section 7.1.7.5)
4822 */
4823 if (!hdev->parent) {
4824 delay = HUB_ROOT_RESET_TIME;
4825 if (port1 == hdev->bus->otg_port)
4826 hdev->bus->b_hnp_enable = 0;
4827 }
4828
4829 /* Some low speed devices have problems with the quick delay, so */
4830 /* be a bit pessimistic with those devices. RHbug #23670 */
4831 if (oldspeed == USB_SPEED_LOW)
4832 delay = HUB_LONG_RESET_TIME;
4833
4834 /* Reset the device; full speed may morph to high speed */
4835 /* FIXME a USB 2.0 device may morph into SuperSpeed on reset. */
4836 retval = hub_port_reset(hub, port1, udev, delay, false);
4837 if (retval < 0) /* error or disconnect */
4838 goto fail;
4839 /* success, speed is known */
4840
4841 retval = -ENODEV;
4842
4843 /* Don't allow speed changes at reset, except usb 3.0 to faster */
4844 if (oldspeed != USB_SPEED_UNKNOWN && oldspeed != udev->speed &&
4845 !(oldspeed == USB_SPEED_SUPER && udev->speed > oldspeed)) {
4846 dev_dbg(&udev->dev, "device reset changed speed!\n");
4847 goto fail;
4848 }
4849 oldspeed = udev->speed;
4850
4851 if (initial) {
4852 /* USB 2.0 section 5.5.3 talks about ep0 maxpacket ...
4853 * it's fixed size except for full speed devices.
4854 * For Wireless USB devices, ep0 max packet is always 512 (tho
4855 * reported as 0xff in the device descriptor). WUSB1.0[4.8.1].
4856 */
4857 switch (udev->speed) {
4858 case USB_SPEED_SUPER_PLUS:
4859 case USB_SPEED_SUPER:
4860 case USB_SPEED_WIRELESS: /* fixed at 512 */
4861 udev->ep0.desc.wMaxPacketSize = cpu_to_le16(512);
4862 break;
4863 case USB_SPEED_HIGH: /* fixed at 64 */
4864 udev->ep0.desc.wMaxPacketSize = cpu_to_le16(64);
4865 break;
4866 case USB_SPEED_FULL: /* 8, 16, 32, or 64 */
4867 /* to determine the ep0 maxpacket size, try to read
4868 * the device descriptor to get bMaxPacketSize0 and
4869 * then correct our initial guess.
4870 */
4871 udev->ep0.desc.wMaxPacketSize = cpu_to_le16(64);
4872 break;
4873 case USB_SPEED_LOW: /* fixed at 8 */
4874 udev->ep0.desc.wMaxPacketSize = cpu_to_le16(8);
4875 break;
4876 default:
4877 goto fail;
4878 }
4879 }
4880
4881 if (udev->speed == USB_SPEED_WIRELESS)
4882 speed = "variable speed Wireless";
4883 else
4884 speed = usb_speed_string(udev->speed);
4885
4886 /*
4887 * The controller driver may be NULL if the controller device
4888 * is the middle device between platform device and roothub.
4889 * This middle device may not need a device driver due to
4890 * all hardware control can be at platform device driver, this
4891 * platform device is usually a dual-role USB controller device.
4892 */
4893 if (udev->bus->controller->driver)
4894 driver_name = udev->bus->controller->driver->name;
4895 else
4896 driver_name = udev->bus->sysdev->driver->name;
4897
4898 if (udev->speed < USB_SPEED_SUPER)
4899 dev_info(&udev->dev,
4900 "%s %s USB device number %d using %s\n",
4901 (initial ? "new" : "reset"), speed,
4902 devnum, driver_name);
4903
4904 if (initial) {
4905 /* Set up TT records, if needed */
4906 if (hdev->tt) {
4907 udev->tt = hdev->tt;
4908 udev->ttport = hdev->ttport;
4909 } else if (udev->speed != USB_SPEED_HIGH
4910 && hdev->speed == USB_SPEED_HIGH) {
4911 if (!hub->tt.hub) {
4912 dev_err(&udev->dev, "parent hub has no TT\n");
4913 retval = -EINVAL;
4914 goto fail;
4915 }
4916 udev->tt = &hub->tt;
4917 udev->ttport = port1;
4918 }
4919 }
4920
4921 /* Why interleave GET_DESCRIPTOR and SET_ADDRESS this way?
4922 * Because device hardware and firmware is sometimes buggy in
4923 * this area, and this is how Linux has done it for ages.
4924 * Change it cautiously.
4925 *
4926 * NOTE: If use_new_scheme() is true we will start by issuing
4927 * a 64-byte GET_DESCRIPTOR request. This is what Windows does,
4928 * so it may help with some non-standards-compliant devices.
4929 * Otherwise we start with SET_ADDRESS and then try to read the
4930 * first 8 bytes of the device descriptor to get the ep0 maxpacket
4931 * value.
4932 */
4933 do_new_scheme = use_new_scheme(udev, retry_counter, port_dev);
4934
4935 for (retries = 0; retries < GET_DESCRIPTOR_TRIES; (++retries, msleep(100))) {
4936 if (do_new_scheme) {
4937 retval = hub_enable_device(udev);
4938 if (retval < 0) {
4939 dev_err(&udev->dev,
4940 "hub failed to enable device, error %d\n",
4941 retval);
4942 goto fail;
4943 }
4944
4945 maxp0 = get_bMaxPacketSize0(udev, buf,
4946 GET_DESCRIPTOR_BUFSIZE, retries == 0);
4947 if (maxp0 > 0 && !initial &&
4948 maxp0 != udev->descriptor.bMaxPacketSize0) {
4949 dev_err(&udev->dev, "device reset changed ep0 maxpacket size!\n");
4950 retval = -ENODEV;
4951 goto fail;
4952 }
4953
4954 retval = hub_port_reset(hub, port1, udev, delay, false);
4955 if (retval < 0) /* error or disconnect */
4956 goto fail;
4957 if (oldspeed != udev->speed) {
4958 dev_dbg(&udev->dev,
4959 "device reset changed speed!\n");
4960 retval = -ENODEV;
4961 goto fail;
4962 }
4963 if (maxp0 < 0) {
4964 if (maxp0 != -ENODEV)
4965 dev_err(&udev->dev, "device descriptor read/64, error %d\n",
4966 maxp0);
4967 retval = maxp0;
4968 continue;
4969 }
4970 }
4971
4972 /*
4973 * If device is WUSB, we already assigned an
4974 * unauthorized address in the Connect Ack sequence;
4975 * authorization will assign the final address.
4976 */
4977 if (udev->wusb == 0) {
4978 for (operations = 0; operations < SET_ADDRESS_TRIES; ++operations) {
4979 retval = hub_set_address(udev, devnum);
4980 if (retval >= 0)
4981 break;
4982 msleep(200);
4983 }
4984 if (retval < 0) {
4985 if (retval != -ENODEV)
4986 dev_err(&udev->dev, "device not accepting address %d, error %d\n",
4987 devnum, retval);
4988 goto fail;
4989 }
4990 if (udev->speed >= USB_SPEED_SUPER) {
4991 devnum = udev->devnum;
4992 dev_info(&udev->dev,
4993 "%s SuperSpeed%s%s USB device number %d using %s\n",
4994 (udev->config) ? "reset" : "new",
4995 (udev->speed == USB_SPEED_SUPER_PLUS) ?
4996 "Plus Gen 2" : " Gen 1",
4997 (udev->rx_lanes == 2 && udev->tx_lanes == 2) ?
4998 "x2" : "",
4999 devnum, driver_name);
5000 }
5001
5002 /* cope with hardware quirkiness:
5003 * - let SET_ADDRESS settle, some device hardware wants it
5004 * - read ep0 maxpacket even for high and low speed,
5005 */
5006 msleep(10);
5007 if (do_new_scheme)
5008 break;
5009 }
5010
5011 /* !do_new_scheme || wusb */
5012 maxp0 = get_bMaxPacketSize0(udev, buf, 8, retries == 0);
5013 if (maxp0 < 0) {
5014 retval = maxp0;
5015 if (retval != -ENODEV)
5016 dev_err(&udev->dev,
5017 "device descriptor read/8, error %d\n",
5018 retval);
5019 } else {
5020 u32 delay;
5021
5022 if (!initial && maxp0 != udev->descriptor.bMaxPacketSize0) {
5023 dev_err(&udev->dev, "device reset changed ep0 maxpacket size!\n");
5024 retval = -ENODEV;
5025 goto fail;
5026 }
5027
5028 delay = udev->parent->hub_delay;
5029 udev->hub_delay = min_t(u32, delay,
5030 USB_TP_TRANSMISSION_DELAY_MAX);
5031 retval = usb_set_isoch_delay(udev);
5032 if (retval) {
5033 dev_dbg(&udev->dev,
5034 "Failed set isoch delay, error %d\n",
5035 retval);
5036 retval = 0;
5037 }
5038 break;
5039 }
5040 }
5041 if (retval)
5042 goto fail;
5043
5044 /*
5045 * Check the ep0 maxpacket guess and correct it if necessary.
5046 * maxp0 is the value stored in the device descriptor;
5047 * i is the value it encodes (logarithmic for SuperSpeed or greater).
5048 */
5049 i = maxp0;
5050 if (udev->speed >= USB_SPEED_SUPER) {
5051 if (maxp0 <= 16)
5052 i = 1 << maxp0;
5053 else
5054 i = 0; /* Invalid */
5055 }
5056 if (usb_endpoint_maxp(&udev->ep0.desc) == i) {
5057 ; /* Initial ep0 maxpacket guess is right */
5058 } else if ((udev->speed == USB_SPEED_FULL ||
5059 udev->speed == USB_SPEED_HIGH) &&
5060 (i == 8 || i == 16 || i == 32 || i == 64)) {
5061 /* Initial guess is wrong; use the descriptor's value */
5062 if (udev->speed == USB_SPEED_FULL)
5063 dev_dbg(&udev->dev, "ep0 maxpacket = %d\n", i);
5064 else
5065 dev_warn(&udev->dev, "Using ep0 maxpacket: %d\n", i);
5066 udev->ep0.desc.wMaxPacketSize = cpu_to_le16(i);
5067 usb_ep0_reinit(udev);
5068 } else {
5069 /* Initial guess is wrong and descriptor's value is invalid */
5070 dev_err(&udev->dev, "Invalid ep0 maxpacket: %d\n", maxp0);
5071 retval = -EMSGSIZE;
5072 goto fail;
5073 }
5074
5075 descr = usb_get_device_descriptor(udev);
5076 if (IS_ERR(descr)) {
5077 retval = PTR_ERR(descr);
5078 if (retval != -ENODEV)
5079 dev_err(&udev->dev, "device descriptor read/all, error %d\n",
5080 retval);
5081 goto fail;
5082 }
5083 if (initial)
5084 udev->descriptor = *descr;
5085 else
5086 *dev_descr = *descr;
5087 kfree(descr);
5088
5089 /*
5090 * Some superspeed devices have finished the link training process
5091 * and attached to a superspeed hub port, but the device descriptor
5092 * got from those devices show they aren't superspeed devices. Warm
5093 * reset the port attached by the devices can fix them.
5094 */
5095 if ((udev->speed >= USB_SPEED_SUPER) &&
5096 (le16_to_cpu(udev->descriptor.bcdUSB) < 0x0300)) {
5097 dev_err(&udev->dev, "got a wrong device descriptor, warm reset device\n");
5098 hub_port_reset(hub, port1, udev, HUB_BH_RESET_TIME, true);
5099 retval = -EINVAL;
5100 goto fail;
5101 }
5102
5103 usb_detect_quirks(udev);
5104
5105 if (udev->wusb == 0 && le16_to_cpu(udev->descriptor.bcdUSB) >= 0x0201) {
5106 retval = usb_get_bos_descriptor(udev);
5107 if (!retval) {
5108 udev->lpm_capable = usb_device_supports_lpm(udev);
5109 usb_set_lpm_parameters(udev);
5110 }
5111 }
5112
5113 retval = 0;
5114 /* notify HCD that we have a device connected and addressed */
5115 if (hcd->driver->update_device)
5116 hcd->driver->update_device(hcd, udev);
5117 hub_set_initial_usb2_lpm_policy(udev);
5118 fail:
5119 if (retval) {
5120 hub_port_disable(hub, port1, 0);
5121 update_devnum(udev, devnum); /* for disconnect processing */
5122 }
5123 kfree(buf);
5124 return retval;
5125 }
5126
5127 static void
check_highspeed(struct usb_hub * hub,struct usb_device * udev,int port1)5128 check_highspeed(struct usb_hub *hub, struct usb_device *udev, int port1)
5129 {
5130 struct usb_qualifier_descriptor *qual;
5131 int status;
5132
5133 if (udev->quirks & USB_QUIRK_DEVICE_QUALIFIER)
5134 return;
5135
5136 qual = kmalloc(sizeof *qual, GFP_KERNEL);
5137 if (qual == NULL)
5138 return;
5139
5140 status = usb_get_descriptor(udev, USB_DT_DEVICE_QUALIFIER, 0,
5141 qual, sizeof *qual);
5142 if (status == sizeof *qual) {
5143 dev_info(&udev->dev, "not running at top speed; "
5144 "connect to a high speed hub\n");
5145 /* hub LEDs are probably harder to miss than syslog */
5146 if (hub->has_indicators) {
5147 hub->indicator[port1-1] = INDICATOR_GREEN_BLINK;
5148 queue_delayed_work(system_power_efficient_wq,
5149 &hub->leds, 0);
5150 }
5151 }
5152 kfree(qual);
5153 }
5154
5155 static unsigned
hub_power_remaining(struct usb_hub * hub)5156 hub_power_remaining(struct usb_hub *hub)
5157 {
5158 struct usb_device *hdev = hub->hdev;
5159 int remaining;
5160 int port1;
5161
5162 if (!hub->limited_power)
5163 return 0;
5164
5165 remaining = hdev->bus_mA - hub->descriptor->bHubContrCurrent;
5166 for (port1 = 1; port1 <= hdev->maxchild; ++port1) {
5167 struct usb_port *port_dev = hub->ports[port1 - 1];
5168 struct usb_device *udev = port_dev->child;
5169 unsigned unit_load;
5170 int delta;
5171
5172 if (!udev)
5173 continue;
5174 if (hub_is_superspeed(udev))
5175 unit_load = 150;
5176 else
5177 unit_load = 100;
5178
5179 /*
5180 * Unconfigured devices may not use more than one unit load,
5181 * or 8mA for OTG ports
5182 */
5183 if (udev->actconfig)
5184 delta = usb_get_max_power(udev, udev->actconfig);
5185 else if (port1 != udev->bus->otg_port || hdev->parent)
5186 delta = unit_load;
5187 else
5188 delta = 8;
5189 if (delta > hub->mA_per_port)
5190 dev_warn(&port_dev->dev, "%dmA is over %umA budget!\n",
5191 delta, hub->mA_per_port);
5192 remaining -= delta;
5193 }
5194 if (remaining < 0) {
5195 dev_warn(hub->intfdev, "%dmA over power budget!\n",
5196 -remaining);
5197 remaining = 0;
5198 }
5199 return remaining;
5200 }
5201
5202
descriptors_changed(struct usb_device * udev,struct usb_device_descriptor * new_device_descriptor,struct usb_host_bos * old_bos)5203 static int descriptors_changed(struct usb_device *udev,
5204 struct usb_device_descriptor *new_device_descriptor,
5205 struct usb_host_bos *old_bos)
5206 {
5207 int changed = 0;
5208 unsigned index;
5209 unsigned serial_len = 0;
5210 unsigned len;
5211 unsigned old_length;
5212 int length;
5213 char *buf;
5214
5215 if (memcmp(&udev->descriptor, new_device_descriptor,
5216 sizeof(*new_device_descriptor)) != 0)
5217 return 1;
5218
5219 if ((old_bos && !udev->bos) || (!old_bos && udev->bos))
5220 return 1;
5221 if (udev->bos) {
5222 len = le16_to_cpu(udev->bos->desc->wTotalLength);
5223 if (len != le16_to_cpu(old_bos->desc->wTotalLength))
5224 return 1;
5225 if (memcmp(udev->bos->desc, old_bos->desc, len))
5226 return 1;
5227 }
5228
5229 /* Since the idVendor, idProduct, and bcdDevice values in the
5230 * device descriptor haven't changed, we will assume the
5231 * Manufacturer and Product strings haven't changed either.
5232 * But the SerialNumber string could be different (e.g., a
5233 * different flash card of the same brand).
5234 */
5235 if (udev->serial)
5236 serial_len = strlen(udev->serial) + 1;
5237
5238 len = serial_len;
5239 for (index = 0; index < udev->descriptor.bNumConfigurations; index++) {
5240 old_length = le16_to_cpu(udev->config[index].desc.wTotalLength);
5241 len = max(len, old_length);
5242 }
5243
5244 buf = kmalloc(len, GFP_NOIO);
5245 if (!buf)
5246 /* assume the worst */
5247 return 1;
5248
5249 for (index = 0; index < udev->descriptor.bNumConfigurations; index++) {
5250 old_length = le16_to_cpu(udev->config[index].desc.wTotalLength);
5251 length = usb_get_descriptor(udev, USB_DT_CONFIG, index, buf,
5252 old_length);
5253 if (length != old_length) {
5254 dev_dbg(&udev->dev, "config index %d, error %d\n",
5255 index, length);
5256 changed = 1;
5257 break;
5258 }
5259 if (memcmp(buf, udev->rawdescriptors[index], old_length)
5260 != 0) {
5261 dev_dbg(&udev->dev, "config index %d changed (#%d)\n",
5262 index,
5263 ((struct usb_config_descriptor *) buf)->
5264 bConfigurationValue);
5265 changed = 1;
5266 break;
5267 }
5268 }
5269
5270 if (!changed && serial_len) {
5271 length = usb_string(udev, udev->descriptor.iSerialNumber,
5272 buf, serial_len);
5273 if (length + 1 != serial_len) {
5274 dev_dbg(&udev->dev, "serial string error %d\n",
5275 length);
5276 changed = 1;
5277 } else if (memcmp(buf, udev->serial, length) != 0) {
5278 dev_dbg(&udev->dev, "serial string changed\n");
5279 changed = 1;
5280 }
5281 }
5282
5283 kfree(buf);
5284 return changed;
5285 }
5286
hub_port_connect(struct usb_hub * hub,int port1,u16 portstatus,u16 portchange)5287 static void hub_port_connect(struct usb_hub *hub, int port1, u16 portstatus,
5288 u16 portchange)
5289 {
5290 int status = -ENODEV;
5291 int i;
5292 unsigned unit_load;
5293 struct usb_device *hdev = hub->hdev;
5294 struct usb_hcd *hcd = bus_to_hcd(hdev->bus);
5295 struct usb_port *port_dev = hub->ports[port1 - 1];
5296 struct usb_device *udev = port_dev->child;
5297 static int unreliable_port = -1;
5298 bool retry_locked;
5299
5300 /* Disconnect any existing devices under this port */
5301 if (udev) {
5302 if (hcd->usb_phy && !hdev->parent)
5303 usb_phy_notify_disconnect(hcd->usb_phy, udev->speed);
5304 usb_disconnect(&port_dev->child);
5305 }
5306
5307 /* We can forget about a "removed" device when there's a physical
5308 * disconnect or the connect status changes.
5309 */
5310 if (!(portstatus & USB_PORT_STAT_CONNECTION) ||
5311 (portchange & USB_PORT_STAT_C_CONNECTION))
5312 clear_bit(port1, hub->removed_bits);
5313
5314 if (portchange & (USB_PORT_STAT_C_CONNECTION |
5315 USB_PORT_STAT_C_ENABLE)) {
5316 status = hub_port_debounce_be_stable(hub, port1);
5317 if (status < 0) {
5318 if (status != -ENODEV &&
5319 port1 != unreliable_port &&
5320 printk_ratelimit())
5321 dev_err(&port_dev->dev, "connect-debounce failed\n");
5322 portstatus &= ~USB_PORT_STAT_CONNECTION;
5323 unreliable_port = port1;
5324 } else {
5325 portstatus = status;
5326 }
5327 }
5328
5329 /* Return now if debouncing failed or nothing is connected or
5330 * the device was "removed".
5331 */
5332 if (!(portstatus & USB_PORT_STAT_CONNECTION) ||
5333 test_bit(port1, hub->removed_bits)) {
5334
5335 /*
5336 * maybe switch power back on (e.g. root hub was reset)
5337 * but only if the port isn't owned by someone else.
5338 */
5339 if (hub_is_port_power_switchable(hub)
5340 && !port_is_power_on(hub, portstatus)
5341 && !port_dev->port_owner)
5342 set_port_feature(hdev, port1, USB_PORT_FEAT_POWER);
5343
5344 if (portstatus & USB_PORT_STAT_ENABLE)
5345 goto done;
5346 return;
5347 }
5348 if (hub_is_superspeed(hub->hdev))
5349 unit_load = 150;
5350 else
5351 unit_load = 100;
5352
5353 status = 0;
5354
5355 for (i = 0; i < PORT_INIT_TRIES; i++) {
5356 usb_lock_port(port_dev);
5357 mutex_lock(hcd->address0_mutex);
5358 retry_locked = true;
5359 /* reallocate for each attempt, since references
5360 * to the previous one can escape in various ways
5361 */
5362 udev = usb_alloc_dev(hdev, hdev->bus, port1);
5363 if (!udev) {
5364 dev_err(&port_dev->dev,
5365 "couldn't allocate usb_device\n");
5366 mutex_unlock(hcd->address0_mutex);
5367 usb_unlock_port(port_dev);
5368 goto done;
5369 }
5370
5371 usb_set_device_state(udev, USB_STATE_POWERED);
5372 udev->bus_mA = hub->mA_per_port;
5373 udev->level = hdev->level + 1;
5374 udev->wusb = hub_is_wusb(hub);
5375
5376 /* Devices connected to SuperSpeed hubs are USB 3.0 or later */
5377 if (hub_is_superspeed(hub->hdev))
5378 udev->speed = USB_SPEED_SUPER;
5379 else
5380 udev->speed = USB_SPEED_UNKNOWN;
5381
5382 choose_devnum(udev);
5383 if (udev->devnum <= 0) {
5384 status = -ENOTCONN; /* Don't retry */
5385 goto loop;
5386 }
5387
5388 /* reset (non-USB 3.0 devices) and get descriptor */
5389 status = hub_port_init(hub, udev, port1, i, NULL);
5390 if (status < 0)
5391 goto loop;
5392
5393 mutex_unlock(hcd->address0_mutex);
5394 usb_unlock_port(port_dev);
5395 retry_locked = false;
5396
5397 if (udev->quirks & USB_QUIRK_DELAY_INIT)
5398 msleep(2000);
5399
5400 /* consecutive bus-powered hubs aren't reliable; they can
5401 * violate the voltage drop budget. if the new child has
5402 * a "powered" LED, users should notice we didn't enable it
5403 * (without reading syslog), even without per-port LEDs
5404 * on the parent.
5405 */
5406 if (udev->descriptor.bDeviceClass == USB_CLASS_HUB
5407 && udev->bus_mA <= unit_load) {
5408 u16 devstat;
5409
5410 status = usb_get_std_status(udev, USB_RECIP_DEVICE, 0,
5411 &devstat);
5412 if (status) {
5413 dev_dbg(&udev->dev, "get status %d ?\n", status);
5414 goto loop_disable;
5415 }
5416 if ((devstat & (1 << USB_DEVICE_SELF_POWERED)) == 0) {
5417 dev_err(&udev->dev,
5418 "can't connect bus-powered hub "
5419 "to this port\n");
5420 if (hub->has_indicators) {
5421 hub->indicator[port1-1] =
5422 INDICATOR_AMBER_BLINK;
5423 queue_delayed_work(
5424 system_power_efficient_wq,
5425 &hub->leds, 0);
5426 }
5427 status = -ENOTCONN; /* Don't retry */
5428 goto loop_disable;
5429 }
5430 }
5431
5432 /* check for devices running slower than they could */
5433 if (le16_to_cpu(udev->descriptor.bcdUSB) >= 0x0200
5434 && udev->speed == USB_SPEED_FULL
5435 && highspeed_hubs != 0)
5436 check_highspeed(hub, udev, port1);
5437
5438 /* Store the parent's children[] pointer. At this point
5439 * udev becomes globally accessible, although presumably
5440 * no one will look at it until hdev is unlocked.
5441 */
5442 status = 0;
5443
5444 mutex_lock(&usb_port_peer_mutex);
5445
5446 /* We mustn't add new devices if the parent hub has
5447 * been disconnected; we would race with the
5448 * recursively_mark_NOTATTACHED() routine.
5449 */
5450 spin_lock_irq(&device_state_lock);
5451 if (hdev->state == USB_STATE_NOTATTACHED)
5452 status = -ENOTCONN;
5453 else
5454 port_dev->child = udev;
5455 spin_unlock_irq(&device_state_lock);
5456 mutex_unlock(&usb_port_peer_mutex);
5457
5458 /* Run it through the hoops (find a driver, etc) */
5459 if (!status) {
5460 status = usb_new_device(udev);
5461 if (status) {
5462 mutex_lock(&usb_port_peer_mutex);
5463 spin_lock_irq(&device_state_lock);
5464 port_dev->child = NULL;
5465 spin_unlock_irq(&device_state_lock);
5466 mutex_unlock(&usb_port_peer_mutex);
5467 } else {
5468 if (hcd->usb_phy && !hdev->parent)
5469 usb_phy_notify_connect(hcd->usb_phy,
5470 udev->speed);
5471 }
5472 }
5473
5474 if (status)
5475 goto loop_disable;
5476
5477 status = hub_power_remaining(hub);
5478 if (status)
5479 dev_dbg(hub->intfdev, "%dmA power budget left\n", status);
5480
5481 return;
5482
5483 loop_disable:
5484 hub_port_disable(hub, port1, 1);
5485 loop:
5486 usb_ep0_reinit(udev);
5487 release_devnum(udev);
5488 hub_free_dev(udev);
5489 if (retry_locked) {
5490 mutex_unlock(hcd->address0_mutex);
5491 usb_unlock_port(port_dev);
5492 }
5493 usb_put_dev(udev);
5494 if ((status == -ENOTCONN) || (status == -ENOTSUPP))
5495 break;
5496
5497 /* When halfway through our retry count, power-cycle the port */
5498 if (i == (PORT_INIT_TRIES - 1) / 2) {
5499 dev_info(&port_dev->dev, "attempt power cycle\n");
5500 usb_hub_set_port_power(hdev, hub, port1, false);
5501 msleep(2 * hub_power_on_good_delay(hub));
5502 usb_hub_set_port_power(hdev, hub, port1, true);
5503 msleep(hub_power_on_good_delay(hub));
5504 }
5505 }
5506 if (hub->hdev->parent ||
5507 !hcd->driver->port_handed_over ||
5508 !(hcd->driver->port_handed_over)(hcd, port1)) {
5509 if (status != -ENOTCONN && status != -ENODEV)
5510 dev_err(&port_dev->dev,
5511 "unable to enumerate USB device\n");
5512 }
5513
5514 done:
5515 hub_port_disable(hub, port1, 1);
5516 if (hcd->driver->relinquish_port && !hub->hdev->parent) {
5517 if (status != -ENOTCONN && status != -ENODEV)
5518 hcd->driver->relinquish_port(hcd, port1);
5519 }
5520 }
5521
5522 /* Handle physical or logical connection change events.
5523 * This routine is called when:
5524 * a port connection-change occurs;
5525 * a port enable-change occurs (often caused by EMI);
5526 * usb_reset_and_verify_device() encounters changed descriptors (as from
5527 * a firmware download)
5528 * caller already locked the hub
5529 */
hub_port_connect_change(struct usb_hub * hub,int port1,u16 portstatus,u16 portchange)5530 static void hub_port_connect_change(struct usb_hub *hub, int port1,
5531 u16 portstatus, u16 portchange)
5532 __must_hold(&port_dev->status_lock)
5533 {
5534 struct usb_port *port_dev = hub->ports[port1 - 1];
5535 struct usb_device *udev = port_dev->child;
5536 struct usb_device_descriptor *descr;
5537 int status = -ENODEV;
5538
5539 dev_dbg(&port_dev->dev, "status %04x, change %04x, %s\n", portstatus,
5540 portchange, portspeed(hub, portstatus));
5541
5542 if (hub->has_indicators) {
5543 set_port_led(hub, port1, HUB_LED_AUTO);
5544 hub->indicator[port1-1] = INDICATOR_AUTO;
5545 }
5546
5547 #ifdef CONFIG_USB_OTG
5548 /* during HNP, don't repeat the debounce */
5549 if (hub->hdev->bus->is_b_host)
5550 portchange &= ~(USB_PORT_STAT_C_CONNECTION |
5551 USB_PORT_STAT_C_ENABLE);
5552 #endif
5553
5554 /* Try to resuscitate an existing device */
5555 if ((portstatus & USB_PORT_STAT_CONNECTION) && udev &&
5556 udev->state != USB_STATE_NOTATTACHED) {
5557 if (portstatus & USB_PORT_STAT_ENABLE) {
5558 /*
5559 * USB-3 connections are initialized automatically by
5560 * the hostcontroller hardware. Therefore check for
5561 * changed device descriptors before resuscitating the
5562 * device.
5563 */
5564 descr = usb_get_device_descriptor(udev);
5565 if (IS_ERR(descr)) {
5566 dev_dbg(&udev->dev,
5567 "can't read device descriptor %ld\n",
5568 PTR_ERR(descr));
5569 } else {
5570 if (descriptors_changed(udev, descr,
5571 udev->bos)) {
5572 dev_dbg(&udev->dev,
5573 "device descriptor has changed\n");
5574 } else {
5575 status = 0; /* Nothing to do */
5576 }
5577 kfree(descr);
5578 }
5579 #ifdef CONFIG_PM
5580 } else if (udev->state == USB_STATE_SUSPENDED &&
5581 udev->persist_enabled) {
5582 /* For a suspended device, treat this as a
5583 * remote wakeup event.
5584 */
5585 usb_unlock_port(port_dev);
5586 status = usb_remote_wakeup(udev);
5587 usb_lock_port(port_dev);
5588 #endif
5589 } else {
5590 /* Don't resuscitate */;
5591 }
5592 }
5593 clear_bit(port1, hub->change_bits);
5594
5595 /* successfully revalidated the connection */
5596 if (status == 0)
5597 return;
5598
5599 usb_unlock_port(port_dev);
5600 hub_port_connect(hub, port1, portstatus, portchange);
5601 usb_lock_port(port_dev);
5602 }
5603
5604 /* Handle notifying userspace about hub over-current events */
port_over_current_notify(struct usb_port * port_dev)5605 static void port_over_current_notify(struct usb_port *port_dev)
5606 {
5607 char *envp[3];
5608 struct device *hub_dev;
5609 char *port_dev_path;
5610
5611 sysfs_notify(&port_dev->dev.kobj, NULL, "over_current_count");
5612
5613 hub_dev = port_dev->dev.parent;
5614
5615 if (!hub_dev)
5616 return;
5617
5618 port_dev_path = kobject_get_path(&port_dev->dev.kobj, GFP_KERNEL);
5619 if (!port_dev_path)
5620 return;
5621
5622 envp[0] = kasprintf(GFP_KERNEL, "OVER_CURRENT_PORT=%s", port_dev_path);
5623 if (!envp[0])
5624 goto exit_path;
5625
5626 envp[1] = kasprintf(GFP_KERNEL, "OVER_CURRENT_COUNT=%u",
5627 port_dev->over_current_count);
5628 if (!envp[1])
5629 goto exit;
5630
5631 envp[2] = NULL;
5632 kobject_uevent_env(&hub_dev->kobj, KOBJ_CHANGE, envp);
5633
5634 kfree(envp[1]);
5635 exit:
5636 kfree(envp[0]);
5637 exit_path:
5638 kfree(port_dev_path);
5639 }
5640
port_event(struct usb_hub * hub,int port1)5641 static void port_event(struct usb_hub *hub, int port1)
5642 __must_hold(&port_dev->status_lock)
5643 {
5644 int connect_change;
5645 struct usb_port *port_dev = hub->ports[port1 - 1];
5646 struct usb_device *udev = port_dev->child;
5647 struct usb_device *hdev = hub->hdev;
5648 u16 portstatus, portchange;
5649
5650 connect_change = test_bit(port1, hub->change_bits);
5651 clear_bit(port1, hub->event_bits);
5652 clear_bit(port1, hub->wakeup_bits);
5653
5654 if (hub_port_status(hub, port1, &portstatus, &portchange) < 0)
5655 return;
5656
5657 if (portchange & USB_PORT_STAT_C_CONNECTION) {
5658 usb_clear_port_feature(hdev, port1, USB_PORT_FEAT_C_CONNECTION);
5659 connect_change = 1;
5660 }
5661
5662 if (portchange & USB_PORT_STAT_C_ENABLE) {
5663 if (!connect_change)
5664 dev_dbg(&port_dev->dev, "enable change, status %08x\n",
5665 portstatus);
5666 usb_clear_port_feature(hdev, port1, USB_PORT_FEAT_C_ENABLE);
5667
5668 /*
5669 * EM interference sometimes causes badly shielded USB devices
5670 * to be shutdown by the hub, this hack enables them again.
5671 * Works at least with mouse driver.
5672 */
5673 if (!(portstatus & USB_PORT_STAT_ENABLE)
5674 && !connect_change && udev) {
5675 dev_err(&port_dev->dev, "disabled by hub (EMI?), re-enabling...\n");
5676 connect_change = 1;
5677 }
5678 }
5679
5680 if (portchange & USB_PORT_STAT_C_OVERCURRENT) {
5681 u16 status = 0, unused;
5682 port_dev->over_current_count++;
5683 port_over_current_notify(port_dev);
5684
5685 dev_dbg(&port_dev->dev, "over-current change #%u\n",
5686 port_dev->over_current_count);
5687 usb_clear_port_feature(hdev, port1,
5688 USB_PORT_FEAT_C_OVER_CURRENT);
5689 msleep(100); /* Cool down */
5690 hub_power_on(hub, true);
5691 hub_port_status(hub, port1, &status, &unused);
5692 if (status & USB_PORT_STAT_OVERCURRENT)
5693 dev_err(&port_dev->dev, "over-current condition\n");
5694 }
5695
5696 if (portchange & USB_PORT_STAT_C_RESET) {
5697 dev_dbg(&port_dev->dev, "reset change\n");
5698 usb_clear_port_feature(hdev, port1, USB_PORT_FEAT_C_RESET);
5699 }
5700 if ((portchange & USB_PORT_STAT_C_BH_RESET)
5701 && hub_is_superspeed(hdev)) {
5702 dev_dbg(&port_dev->dev, "warm reset change\n");
5703 usb_clear_port_feature(hdev, port1,
5704 USB_PORT_FEAT_C_BH_PORT_RESET);
5705 }
5706 if (portchange & USB_PORT_STAT_C_LINK_STATE) {
5707 dev_dbg(&port_dev->dev, "link state change\n");
5708 usb_clear_port_feature(hdev, port1,
5709 USB_PORT_FEAT_C_PORT_LINK_STATE);
5710 }
5711 if (portchange & USB_PORT_STAT_C_CONFIG_ERROR) {
5712 dev_warn(&port_dev->dev, "config error\n");
5713 usb_clear_port_feature(hdev, port1,
5714 USB_PORT_FEAT_C_PORT_CONFIG_ERROR);
5715 }
5716
5717 /* skip port actions that require the port to be powered on */
5718 if (!pm_runtime_active(&port_dev->dev))
5719 return;
5720
5721 if (hub_handle_remote_wakeup(hub, port1, portstatus, portchange))
5722 connect_change = 1;
5723
5724 /*
5725 * Warm reset a USB3 protocol port if it's in
5726 * SS.Inactive state.
5727 */
5728 if (hub_port_warm_reset_required(hub, port1, portstatus)) {
5729 dev_dbg(&port_dev->dev, "do warm reset\n");
5730 if (!udev || !(portstatus & USB_PORT_STAT_CONNECTION)
5731 || udev->state == USB_STATE_NOTATTACHED) {
5732 if (hub_port_reset(hub, port1, NULL,
5733 HUB_BH_RESET_TIME, true) < 0)
5734 hub_port_disable(hub, port1, 1);
5735 } else {
5736 usb_unlock_port(port_dev);
5737 usb_lock_device(udev);
5738 usb_reset_device(udev);
5739 usb_unlock_device(udev);
5740 usb_lock_port(port_dev);
5741 connect_change = 0;
5742 }
5743 }
5744
5745 if (connect_change)
5746 hub_port_connect_change(hub, port1, portstatus, portchange);
5747 }
5748
hub_event(struct work_struct * work)5749 static void hub_event(struct work_struct *work)
5750 {
5751 struct usb_device *hdev;
5752 struct usb_interface *intf;
5753 struct usb_hub *hub;
5754 struct device *hub_dev;
5755 u16 hubstatus;
5756 u16 hubchange;
5757 int i, ret;
5758
5759 hub = container_of(work, struct usb_hub, events);
5760 hdev = hub->hdev;
5761 hub_dev = hub->intfdev;
5762 intf = to_usb_interface(hub_dev);
5763
5764 kcov_remote_start_usb((u64)hdev->bus->busnum);
5765
5766 dev_dbg(hub_dev, "state %d ports %d chg %04x evt %04x\n",
5767 hdev->state, hdev->maxchild,
5768 /* NOTE: expects max 15 ports... */
5769 (u16) hub->change_bits[0],
5770 (u16) hub->event_bits[0]);
5771
5772 /* Lock the device, then check to see if we were
5773 * disconnected while waiting for the lock to succeed. */
5774 usb_lock_device(hdev);
5775 if (unlikely(hub->disconnected))
5776 goto out_hdev_lock;
5777
5778 /* If the hub has died, clean up after it */
5779 if (hdev->state == USB_STATE_NOTATTACHED) {
5780 hub->error = -ENODEV;
5781 hub_quiesce(hub, HUB_DISCONNECT);
5782 goto out_hdev_lock;
5783 }
5784
5785 /* Autoresume */
5786 ret = usb_autopm_get_interface(intf);
5787 if (ret) {
5788 dev_dbg(hub_dev, "Can't autoresume: %d\n", ret);
5789 goto out_hdev_lock;
5790 }
5791
5792 /* If this is an inactive hub, do nothing */
5793 if (hub->quiescing)
5794 goto out_autopm;
5795
5796 if (hub->error) {
5797 dev_dbg(hub_dev, "resetting for error %d\n", hub->error);
5798
5799 ret = usb_reset_device(hdev);
5800 if (ret) {
5801 dev_dbg(hub_dev, "error resetting hub: %d\n", ret);
5802 goto out_autopm;
5803 }
5804
5805 hub->nerrors = 0;
5806 hub->error = 0;
5807 }
5808
5809 /* deal with port status changes */
5810 for (i = 1; i <= hdev->maxchild; i++) {
5811 struct usb_port *port_dev = hub->ports[i - 1];
5812
5813 if (test_bit(i, hub->event_bits)
5814 || test_bit(i, hub->change_bits)
5815 || test_bit(i, hub->wakeup_bits)) {
5816 /*
5817 * The get_noresume and barrier ensure that if
5818 * the port was in the process of resuming, we
5819 * flush that work and keep the port active for
5820 * the duration of the port_event(). However,
5821 * if the port is runtime pm suspended
5822 * (powered-off), we leave it in that state, run
5823 * an abbreviated port_event(), and move on.
5824 */
5825 pm_runtime_get_noresume(&port_dev->dev);
5826 pm_runtime_barrier(&port_dev->dev);
5827 usb_lock_port(port_dev);
5828 port_event(hub, i);
5829 usb_unlock_port(port_dev);
5830 pm_runtime_put_sync(&port_dev->dev);
5831 }
5832 }
5833
5834 /* deal with hub status changes */
5835 if (test_and_clear_bit(0, hub->event_bits) == 0)
5836 ; /* do nothing */
5837 else if (hub_hub_status(hub, &hubstatus, &hubchange) < 0)
5838 dev_err(hub_dev, "get_hub_status failed\n");
5839 else {
5840 if (hubchange & HUB_CHANGE_LOCAL_POWER) {
5841 dev_dbg(hub_dev, "power change\n");
5842 clear_hub_feature(hdev, C_HUB_LOCAL_POWER);
5843 if (hubstatus & HUB_STATUS_LOCAL_POWER)
5844 /* FIXME: Is this always true? */
5845 hub->limited_power = 1;
5846 else
5847 hub->limited_power = 0;
5848 }
5849 if (hubchange & HUB_CHANGE_OVERCURRENT) {
5850 u16 status = 0;
5851 u16 unused;
5852
5853 dev_dbg(hub_dev, "over-current change\n");
5854 clear_hub_feature(hdev, C_HUB_OVER_CURRENT);
5855 msleep(500); /* Cool down */
5856 hub_power_on(hub, true);
5857 hub_hub_status(hub, &status, &unused);
5858 if (status & HUB_STATUS_OVERCURRENT)
5859 dev_err(hub_dev, "over-current condition\n");
5860 }
5861 }
5862
5863 out_autopm:
5864 /* Balance the usb_autopm_get_interface() above */
5865 usb_autopm_put_interface_no_suspend(intf);
5866 out_hdev_lock:
5867 usb_unlock_device(hdev);
5868
5869 /* Balance the stuff in kick_hub_wq() and allow autosuspend */
5870 usb_autopm_put_interface(intf);
5871 kref_put(&hub->kref, hub_release);
5872
5873 kcov_remote_stop();
5874 }
5875
5876 static const struct usb_device_id hub_id_table[] = {
5877 { .match_flags = USB_DEVICE_ID_MATCH_VENDOR
5878 | USB_DEVICE_ID_MATCH_PRODUCT
5879 | USB_DEVICE_ID_MATCH_INT_CLASS,
5880 .idVendor = USB_VENDOR_SMSC,
5881 .idProduct = USB_PRODUCT_USB5534B,
5882 .bInterfaceClass = USB_CLASS_HUB,
5883 .driver_info = HUB_QUIRK_DISABLE_AUTOSUSPEND},
5884 { .match_flags = USB_DEVICE_ID_MATCH_VENDOR
5885 | USB_DEVICE_ID_MATCH_PRODUCT,
5886 .idVendor = USB_VENDOR_CYPRESS,
5887 .idProduct = USB_PRODUCT_CY7C65632,
5888 .driver_info = HUB_QUIRK_DISABLE_AUTOSUSPEND},
5889 { .match_flags = USB_DEVICE_ID_MATCH_VENDOR
5890 | USB_DEVICE_ID_MATCH_INT_CLASS,
5891 .idVendor = USB_VENDOR_GENESYS_LOGIC,
5892 .bInterfaceClass = USB_CLASS_HUB,
5893 .driver_info = HUB_QUIRK_CHECK_PORT_AUTOSUSPEND},
5894 { .match_flags = USB_DEVICE_ID_MATCH_VENDOR
5895 | USB_DEVICE_ID_MATCH_PRODUCT,
5896 .idVendor = USB_VENDOR_TEXAS_INSTRUMENTS,
5897 .idProduct = USB_PRODUCT_TUSB8041_USB2,
5898 .driver_info = HUB_QUIRK_DISABLE_AUTOSUSPEND},
5899 { .match_flags = USB_DEVICE_ID_MATCH_VENDOR
5900 | USB_DEVICE_ID_MATCH_PRODUCT,
5901 .idVendor = USB_VENDOR_TEXAS_INSTRUMENTS,
5902 .idProduct = USB_PRODUCT_TUSB8041_USB3,
5903 .driver_info = HUB_QUIRK_DISABLE_AUTOSUSPEND},
5904 { .match_flags = USB_DEVICE_ID_MATCH_DEV_CLASS,
5905 .bDeviceClass = USB_CLASS_HUB},
5906 { .match_flags = USB_DEVICE_ID_MATCH_INT_CLASS,
5907 .bInterfaceClass = USB_CLASS_HUB},
5908 { } /* Terminating entry */
5909 };
5910
5911 MODULE_DEVICE_TABLE(usb, hub_id_table);
5912
5913 static struct usb_driver hub_driver = {
5914 .name = "hub",
5915 .probe = hub_probe,
5916 .disconnect = hub_disconnect,
5917 .suspend = hub_suspend,
5918 .resume = hub_resume,
5919 .reset_resume = hub_reset_resume,
5920 .pre_reset = hub_pre_reset,
5921 .post_reset = hub_post_reset,
5922 .unlocked_ioctl = hub_ioctl,
5923 .id_table = hub_id_table,
5924 .supports_autosuspend = 1,
5925 };
5926
usb_hub_init(void)5927 int usb_hub_init(void)
5928 {
5929 if (usb_register(&hub_driver) < 0) {
5930 printk(KERN_ERR "%s: can't register hub driver\n",
5931 usbcore_name);
5932 return -1;
5933 }
5934
5935 /*
5936 * The workqueue needs to be freezable to avoid interfering with
5937 * USB-PERSIST port handover. Otherwise it might see that a full-speed
5938 * device was gone before the EHCI controller had handed its port
5939 * over to the companion full-speed controller.
5940 */
5941 hub_wq = alloc_workqueue("usb_hub_wq", WQ_FREEZABLE, 0);
5942 if (hub_wq)
5943 return 0;
5944
5945 /* Fall through if kernel_thread failed */
5946 usb_deregister(&hub_driver);
5947 pr_err("%s: can't allocate workqueue for usb hub\n", usbcore_name);
5948
5949 return -1;
5950 }
5951
usb_hub_cleanup(void)5952 void usb_hub_cleanup(void)
5953 {
5954 destroy_workqueue(hub_wq);
5955
5956 /*
5957 * Hub resources are freed for us by usb_deregister. It calls
5958 * usb_driver_purge on every device which in turn calls that
5959 * devices disconnect function if it is using this driver.
5960 * The hub_disconnect function takes care of releasing the
5961 * individual hub resources. -greg
5962 */
5963 usb_deregister(&hub_driver);
5964 } /* usb_hub_cleanup() */
5965
5966 /**
5967 * usb_reset_and_verify_device - perform a USB port reset to reinitialize a device
5968 * @udev: device to reset (not in SUSPENDED or NOTATTACHED state)
5969 *
5970 * WARNING - don't use this routine to reset a composite device
5971 * (one with multiple interfaces owned by separate drivers)!
5972 * Use usb_reset_device() instead.
5973 *
5974 * Do a port reset, reassign the device's address, and establish its
5975 * former operating configuration. If the reset fails, or the device's
5976 * descriptors change from their values before the reset, or the original
5977 * configuration and altsettings cannot be restored, a flag will be set
5978 * telling hub_wq to pretend the device has been disconnected and then
5979 * re-connected. All drivers will be unbound, and the device will be
5980 * re-enumerated and probed all over again.
5981 *
5982 * Return: 0 if the reset succeeded, -ENODEV if the device has been
5983 * flagged for logical disconnection, or some other negative error code
5984 * if the reset wasn't even attempted.
5985 *
5986 * Note:
5987 * The caller must own the device lock and the port lock, the latter is
5988 * taken by usb_reset_device(). For example, it's safe to use
5989 * usb_reset_device() from a driver probe() routine after downloading
5990 * new firmware. For calls that might not occur during probe(), drivers
5991 * should lock the device using usb_lock_device_for_reset().
5992 *
5993 * Locking exception: This routine may also be called from within an
5994 * autoresume handler. Such usage won't conflict with other tasks
5995 * holding the device lock because these tasks should always call
5996 * usb_autopm_resume_device(), thereby preventing any unwanted
5997 * autoresume. The autoresume handler is expected to have already
5998 * acquired the port lock before calling this routine.
5999 */
usb_reset_and_verify_device(struct usb_device * udev)6000 static int usb_reset_and_verify_device(struct usb_device *udev)
6001 {
6002 struct usb_device *parent_hdev = udev->parent;
6003 struct usb_hub *parent_hub;
6004 struct usb_hcd *hcd = bus_to_hcd(udev->bus);
6005 struct usb_device_descriptor descriptor;
6006 struct usb_host_bos *bos;
6007 int i, j, ret = 0;
6008 int port1 = udev->portnum;
6009
6010 if (udev->state == USB_STATE_NOTATTACHED ||
6011 udev->state == USB_STATE_SUSPENDED) {
6012 dev_dbg(&udev->dev, "device reset not allowed in state %d\n",
6013 udev->state);
6014 return -EINVAL;
6015 }
6016
6017 if (!parent_hdev)
6018 return -EISDIR;
6019
6020 parent_hub = usb_hub_to_struct_hub(parent_hdev);
6021
6022 /* Disable USB2 hardware LPM.
6023 * It will be re-enabled by the enumeration process.
6024 */
6025 usb_disable_usb2_hardware_lpm(udev);
6026
6027 /* Disable LPM while we reset the device and reinstall the alt settings.
6028 * Device-initiated LPM, and system exit latency settings are cleared
6029 * when the device is reset, so we have to set them up again.
6030 */
6031 ret = usb_unlocked_disable_lpm(udev);
6032 if (ret) {
6033 dev_err(&udev->dev, "%s Failed to disable LPM\n", __func__);
6034 goto re_enumerate_no_bos;
6035 }
6036
6037 bos = udev->bos;
6038 udev->bos = NULL;
6039
6040 mutex_lock(hcd->address0_mutex);
6041
6042 for (i = 0; i < PORT_INIT_TRIES; ++i) {
6043
6044 /* ep0 maxpacket size may change; let the HCD know about it.
6045 * Other endpoints will be handled by re-enumeration. */
6046 usb_ep0_reinit(udev);
6047 ret = hub_port_init(parent_hub, udev, port1, i, &descriptor);
6048 if (ret >= 0 || ret == -ENOTCONN || ret == -ENODEV)
6049 break;
6050 }
6051 mutex_unlock(hcd->address0_mutex);
6052
6053 if (ret < 0)
6054 goto re_enumerate;
6055
6056 /* Device might have changed firmware (DFU or similar) */
6057 if (descriptors_changed(udev, &descriptor, bos)) {
6058 dev_info(&udev->dev, "device firmware changed\n");
6059 goto re_enumerate;
6060 }
6061
6062 /* Restore the device's previous configuration */
6063 if (!udev->actconfig)
6064 goto done;
6065
6066 mutex_lock(hcd->bandwidth_mutex);
6067 ret = usb_hcd_alloc_bandwidth(udev, udev->actconfig, NULL, NULL);
6068 if (ret < 0) {
6069 dev_warn(&udev->dev,
6070 "Busted HC? Not enough HCD resources for "
6071 "old configuration.\n");
6072 mutex_unlock(hcd->bandwidth_mutex);
6073 goto re_enumerate;
6074 }
6075 ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
6076 USB_REQ_SET_CONFIGURATION, 0,
6077 udev->actconfig->desc.bConfigurationValue, 0,
6078 NULL, 0, USB_CTRL_SET_TIMEOUT);
6079 if (ret < 0) {
6080 dev_err(&udev->dev,
6081 "can't restore configuration #%d (error=%d)\n",
6082 udev->actconfig->desc.bConfigurationValue, ret);
6083 mutex_unlock(hcd->bandwidth_mutex);
6084 goto re_enumerate;
6085 }
6086 mutex_unlock(hcd->bandwidth_mutex);
6087 usb_set_device_state(udev, USB_STATE_CONFIGURED);
6088
6089 /* Put interfaces back into the same altsettings as before.
6090 * Don't bother to send the Set-Interface request for interfaces
6091 * that were already in altsetting 0; besides being unnecessary,
6092 * many devices can't handle it. Instead just reset the host-side
6093 * endpoint state.
6094 */
6095 for (i = 0; i < udev->actconfig->desc.bNumInterfaces; i++) {
6096 struct usb_host_config *config = udev->actconfig;
6097 struct usb_interface *intf = config->interface[i];
6098 struct usb_interface_descriptor *desc;
6099
6100 desc = &intf->cur_altsetting->desc;
6101 if (desc->bAlternateSetting == 0) {
6102 usb_disable_interface(udev, intf, true);
6103 usb_enable_interface(udev, intf, true);
6104 ret = 0;
6105 } else {
6106 /* Let the bandwidth allocation function know that this
6107 * device has been reset, and it will have to use
6108 * alternate setting 0 as the current alternate setting.
6109 */
6110 intf->resetting_device = 1;
6111 ret = usb_set_interface(udev, desc->bInterfaceNumber,
6112 desc->bAlternateSetting);
6113 intf->resetting_device = 0;
6114 }
6115 if (ret < 0) {
6116 dev_err(&udev->dev, "failed to restore interface %d "
6117 "altsetting %d (error=%d)\n",
6118 desc->bInterfaceNumber,
6119 desc->bAlternateSetting,
6120 ret);
6121 goto re_enumerate;
6122 }
6123 /* Resetting also frees any allocated streams */
6124 for (j = 0; j < intf->cur_altsetting->desc.bNumEndpoints; j++)
6125 intf->cur_altsetting->endpoint[j].streams = 0;
6126 }
6127
6128 done:
6129 /* Now that the alt settings are re-installed, enable LTM and LPM. */
6130 usb_enable_usb2_hardware_lpm(udev);
6131 usb_unlocked_enable_lpm(udev);
6132 usb_enable_ltm(udev);
6133 usb_release_bos_descriptor(udev);
6134 udev->bos = bos;
6135 return 0;
6136
6137 re_enumerate:
6138 usb_release_bos_descriptor(udev);
6139 udev->bos = bos;
6140 re_enumerate_no_bos:
6141 /* LPM state doesn't matter when we're about to destroy the device. */
6142 hub_port_logical_disconnect(parent_hub, port1);
6143 return -ENODEV;
6144 }
6145
6146 /**
6147 * usb_reset_device - warn interface drivers and perform a USB port reset
6148 * @udev: device to reset (not in NOTATTACHED state)
6149 *
6150 * Warns all drivers bound to registered interfaces (using their pre_reset
6151 * method), performs the port reset, and then lets the drivers know that
6152 * the reset is over (using their post_reset method).
6153 *
6154 * Return: The same as for usb_reset_and_verify_device().
6155 * However, if a reset is already in progress (for instance, if a
6156 * driver doesn't have pre_reset() or post_reset() callbacks, and while
6157 * being unbound or re-bound during the ongoing reset its disconnect()
6158 * or probe() routine tries to perform a second, nested reset), the
6159 * routine returns -EINPROGRESS.
6160 *
6161 * Note:
6162 * The caller must own the device lock. For example, it's safe to use
6163 * this from a driver probe() routine after downloading new firmware.
6164 * For calls that might not occur during probe(), drivers should lock
6165 * the device using usb_lock_device_for_reset().
6166 *
6167 * If an interface is currently being probed or disconnected, we assume
6168 * its driver knows how to handle resets. For all other interfaces,
6169 * if the driver doesn't have pre_reset and post_reset methods then
6170 * we attempt to unbind it and rebind afterward.
6171 */
usb_reset_device(struct usb_device * udev)6172 int usb_reset_device(struct usb_device *udev)
6173 {
6174 int ret;
6175 int i;
6176 unsigned int noio_flag;
6177 struct usb_port *port_dev;
6178 struct usb_host_config *config = udev->actconfig;
6179 struct usb_hub *hub = usb_hub_to_struct_hub(udev->parent);
6180
6181 if (udev->state == USB_STATE_NOTATTACHED) {
6182 dev_dbg(&udev->dev, "device reset not allowed in state %d\n",
6183 udev->state);
6184 return -EINVAL;
6185 }
6186
6187 if (!udev->parent) {
6188 /* this requires hcd-specific logic; see ohci_restart() */
6189 dev_dbg(&udev->dev, "%s for root hub!\n", __func__);
6190 return -EISDIR;
6191 }
6192
6193 if (udev->reset_in_progress)
6194 return -EINPROGRESS;
6195 udev->reset_in_progress = 1;
6196
6197 port_dev = hub->ports[udev->portnum - 1];
6198
6199 /*
6200 * Don't allocate memory with GFP_KERNEL in current
6201 * context to avoid possible deadlock if usb mass
6202 * storage interface or usbnet interface(iSCSI case)
6203 * is included in current configuration. The easist
6204 * approach is to do it for every device reset,
6205 * because the device 'memalloc_noio' flag may have
6206 * not been set before reseting the usb device.
6207 */
6208 noio_flag = memalloc_noio_save();
6209
6210 /* Prevent autosuspend during the reset */
6211 usb_autoresume_device(udev);
6212
6213 if (config) {
6214 for (i = 0; i < config->desc.bNumInterfaces; ++i) {
6215 struct usb_interface *cintf = config->interface[i];
6216 struct usb_driver *drv;
6217 int unbind = 0;
6218
6219 if (cintf->dev.driver) {
6220 drv = to_usb_driver(cintf->dev.driver);
6221 if (drv->pre_reset && drv->post_reset)
6222 unbind = (drv->pre_reset)(cintf);
6223 else if (cintf->condition ==
6224 USB_INTERFACE_BOUND)
6225 unbind = 1;
6226 if (unbind)
6227 usb_forced_unbind_intf(cintf);
6228 }
6229 }
6230 }
6231
6232 usb_lock_port(port_dev);
6233 ret = usb_reset_and_verify_device(udev);
6234 usb_unlock_port(port_dev);
6235
6236 if (config) {
6237 for (i = config->desc.bNumInterfaces - 1; i >= 0; --i) {
6238 struct usb_interface *cintf = config->interface[i];
6239 struct usb_driver *drv;
6240 int rebind = cintf->needs_binding;
6241
6242 if (!rebind && cintf->dev.driver) {
6243 drv = to_usb_driver(cintf->dev.driver);
6244 if (drv->post_reset)
6245 rebind = (drv->post_reset)(cintf);
6246 else if (cintf->condition ==
6247 USB_INTERFACE_BOUND)
6248 rebind = 1;
6249 if (rebind)
6250 cintf->needs_binding = 1;
6251 }
6252 }
6253
6254 /* If the reset failed, hub_wq will unbind drivers later */
6255 if (ret == 0)
6256 usb_unbind_and_rebind_marked_interfaces(udev);
6257 }
6258
6259 usb_autosuspend_device(udev);
6260 memalloc_noio_restore(noio_flag);
6261 udev->reset_in_progress = 0;
6262 return ret;
6263 }
6264 EXPORT_SYMBOL_GPL(usb_reset_device);
6265
6266
6267 /**
6268 * usb_queue_reset_device - Reset a USB device from an atomic context
6269 * @iface: USB interface belonging to the device to reset
6270 *
6271 * This function can be used to reset a USB device from an atomic
6272 * context, where usb_reset_device() won't work (as it blocks).
6273 *
6274 * Doing a reset via this method is functionally equivalent to calling
6275 * usb_reset_device(), except for the fact that it is delayed to a
6276 * workqueue. This means that any drivers bound to other interfaces
6277 * might be unbound, as well as users from usbfs in user space.
6278 *
6279 * Corner cases:
6280 *
6281 * - Scheduling two resets at the same time from two different drivers
6282 * attached to two different interfaces of the same device is
6283 * possible; depending on how the driver attached to each interface
6284 * handles ->pre_reset(), the second reset might happen or not.
6285 *
6286 * - If the reset is delayed so long that the interface is unbound from
6287 * its driver, the reset will be skipped.
6288 *
6289 * - This function can be called during .probe(). It can also be called
6290 * during .disconnect(), but doing so is pointless because the reset
6291 * will not occur. If you really want to reset the device during
6292 * .disconnect(), call usb_reset_device() directly -- but watch out
6293 * for nested unbinding issues!
6294 */
usb_queue_reset_device(struct usb_interface * iface)6295 void usb_queue_reset_device(struct usb_interface *iface)
6296 {
6297 if (schedule_work(&iface->reset_ws))
6298 usb_get_intf(iface);
6299 }
6300 EXPORT_SYMBOL_GPL(usb_queue_reset_device);
6301
6302 /**
6303 * usb_hub_find_child - Get the pointer of child device
6304 * attached to the port which is specified by @port1.
6305 * @hdev: USB device belonging to the usb hub
6306 * @port1: port num to indicate which port the child device
6307 * is attached to.
6308 *
6309 * USB drivers call this function to get hub's child device
6310 * pointer.
6311 *
6312 * Return: %NULL if input param is invalid and
6313 * child's usb_device pointer if non-NULL.
6314 */
usb_hub_find_child(struct usb_device * hdev,int port1)6315 struct usb_device *usb_hub_find_child(struct usb_device *hdev,
6316 int port1)
6317 {
6318 struct usb_hub *hub = usb_hub_to_struct_hub(hdev);
6319
6320 if (port1 < 1 || port1 > hdev->maxchild)
6321 return NULL;
6322 return hub->ports[port1 - 1]->child;
6323 }
6324 EXPORT_SYMBOL_GPL(usb_hub_find_child);
6325
usb_hub_adjust_deviceremovable(struct usb_device * hdev,struct usb_hub_descriptor * desc)6326 void usb_hub_adjust_deviceremovable(struct usb_device *hdev,
6327 struct usb_hub_descriptor *desc)
6328 {
6329 struct usb_hub *hub = usb_hub_to_struct_hub(hdev);
6330 enum usb_port_connect_type connect_type;
6331 int i;
6332
6333 if (!hub)
6334 return;
6335
6336 if (!hub_is_superspeed(hdev)) {
6337 for (i = 1; i <= hdev->maxchild; i++) {
6338 struct usb_port *port_dev = hub->ports[i - 1];
6339
6340 connect_type = port_dev->connect_type;
6341 if (connect_type == USB_PORT_CONNECT_TYPE_HARD_WIRED) {
6342 u8 mask = 1 << (i%8);
6343
6344 if (!(desc->u.hs.DeviceRemovable[i/8] & mask)) {
6345 dev_dbg(&port_dev->dev, "DeviceRemovable is changed to 1 according to platform information.\n");
6346 desc->u.hs.DeviceRemovable[i/8] |= mask;
6347 }
6348 }
6349 }
6350 } else {
6351 u16 port_removable = le16_to_cpu(desc->u.ss.DeviceRemovable);
6352
6353 for (i = 1; i <= hdev->maxchild; i++) {
6354 struct usb_port *port_dev = hub->ports[i - 1];
6355
6356 connect_type = port_dev->connect_type;
6357 if (connect_type == USB_PORT_CONNECT_TYPE_HARD_WIRED) {
6358 u16 mask = 1 << i;
6359
6360 if (!(port_removable & mask)) {
6361 dev_dbg(&port_dev->dev, "DeviceRemovable is changed to 1 according to platform information.\n");
6362 port_removable |= mask;
6363 }
6364 }
6365 }
6366
6367 desc->u.ss.DeviceRemovable = cpu_to_le16(port_removable);
6368 }
6369 }
6370
6371 #ifdef CONFIG_ACPI
6372 /**
6373 * usb_get_hub_port_acpi_handle - Get the usb port's acpi handle
6374 * @hdev: USB device belonging to the usb hub
6375 * @port1: port num of the port
6376 *
6377 * Return: Port's acpi handle if successful, %NULL if params are
6378 * invalid.
6379 */
usb_get_hub_port_acpi_handle(struct usb_device * hdev,int port1)6380 acpi_handle usb_get_hub_port_acpi_handle(struct usb_device *hdev,
6381 int port1)
6382 {
6383 struct usb_hub *hub = usb_hub_to_struct_hub(hdev);
6384
6385 if (!hub)
6386 return NULL;
6387
6388 return ACPI_HANDLE(&hub->ports[port1 - 1]->dev);
6389 }
6390 #endif
6391