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