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