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