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