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