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