/* *TheSET_ADDRESSrequesttimeoutwillbe500mswhen *USB_QUIRK_SHORT_SET_ADDRESS_REQ_TIMEOUTquirkflagisset.
*/ #define USB_SHORT_SET_ADDRESS_REQ_TIMEOUT 500/* ms */
/* *GiveSShubs200mstimeafterwaketotraindownstreamlinksbefore *assumingnoportactivityandallowinghubtoruntimesuspendback.
*/ #define USB_SS_PORT_U0_WAKE_TIME 200/* ms */
/* Protect struct usb_device->state and ->children members *Note:Botharealsoprotectedby->dev.sem,exceptthat->statecan
* change to USB_STATE_NOTATTACHED even when the semaphore isn't held. */ static DEFINE_SPINLOCK(device_state_lock);
/* workqueue to process hub events */ staticstruct workqueue_struct *hub_wq; staticvoid hub_event(struct work_struct *work);
/* synchronize hub-port add/remove and peering operations */
DEFINE_MUTEX(usb_port_peer_mutex);
/* cycle leds on hubs that aren't blinking for attention */ staticbool blinkenlights;
module_param(blinkenlights, bool, S_IRUGO);
MODULE_PARM_DESC(blinkenlights, "true to cycle leds on hubs");
/* *Asof2.6.10weintroduceanewUSBdeviceinitializationschemewhich *closelyresemblesthewayWindowsworks.Hopefullyitwillbecompatible *withawiderrangeofdevicesthantheoldscheme.Howeversomepreviously *workingdevicesmaystartgivingriseto"devicenotacceptingaddress" *errors;ifthathappenstheusercantrytheoldschemebyadjustingthe *followingmoduleparameters. * *Formaximumflexibilitytherearetwobooleanparameterstocontrolthe *hubdriver'sbehavior.Onthefirstinitializationattempt,ifthe *"old_scheme_first"parameterissetthentheoldschemewillbeused, *otherwisethenewschemeisused.Ifthatfailsand"use_both_schemes" *isset,thenthedriverwillmakeanotherattempt,usingtheotherscheme.
*/ staticbool old_scheme_first;
module_param(old_scheme_first, bool, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(old_scheme_first, "start with the old device initialization scheme");
staticbool use_both_schemes = true;
module_param(use_both_schemes, bool, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(use_both_schemes, "try the other device initialization scheme if the " "first one fails");
/* Mutual exclusion for EHCI CF initialization. This interferes with *portresetonsomecompanioncontrollers.
*/
DECLARE_RWSEM(ehci_cf_port_reset_rwsem);
EXPORT_SYMBOL_GPL(ehci_cf_port_reset_rwsem);
staticint usb_reset_and_verify_device(struct usb_device *udev); staticint hub_port_disable(struct usb_hub *hub, int port1, int set_state); staticbool hub_port_warm_reset_required(struct usb_hub *hub, int port1,
u16 portstatus);
staticinlinechar *portspeed(struct usb_hub *hub, int portstatus)
{ if (hub_is_superspeedplus(hub->hdev)) return"10.0 Gb/s"; if (hub_is_superspeed(hub->hdev)) return"5.0 Gb/s"; if (portstatus & USB_PORT_STAT_HIGH_SPEED) return"480 Mb/s"; elseif (portstatus & USB_PORT_STAT_LOW_SPEED) return"1.5 Mb/s"; else return"12 Mb/s";
}
/* Note that hdev or one of its children must be locked! */ struct usb_hub *usb_hub_to_struct_hub(struct usb_device *hdev)
{ if (!hdev || !hdev->actconfig || !hdev->maxchild) return NULL; return usb_get_intfdata(hdev->actconfig->interface[0]);
}
int usb_device_supports_lpm(struct usb_device *udev)
{ /* Some devices have trouble with LPM */ if (udev->quirks & USB_QUIRK_NO_LPM) return0;
/* Skip if the device BOS descriptor couldn't be read */ if (!udev->bos) return0;
/* USB 2.1 (and greater) devices indicate LPM support through *theirUSB2.0ExtendedCapabilitiesBOSdescriptor.
*/ if (udev->speed == USB_SPEED_HIGH || udev->speed == USB_SPEED_FULL) { if (udev->bos->ext_cap &&
(USB_LPM_SUPPORT &
le32_to_cpu(udev->bos->ext_cap->bmAttributes))) return1; return0;
}
/* *AccordingtotheUSB3.0spec,allUSB3.0devicesmustsupportLPM. *However,therearesomethatdon't,andtheysettheU1/U2exit *latenciestozero.
*/ if (!udev->bos->ss_cap) {
dev_info(&udev->dev, "No LPM exit latency info found, disabling LPM.\n"); return0;
}
if (udev->bos->ss_cap->bU1devExitLat == 0 &&
udev->bos->ss_cap->bU2DevExitLat == 0) { if (udev->parent)
dev_info(&udev->dev, "LPM exit latency is zeroed, disabling LPM.\n"); else
dev_info(&udev->dev, "We don't know the algorithms for LPM for this host, disabling LPM.\n"); return0;
}
if (!udev->parent || udev->parent->lpm_capable) return1; return0;
}
if (!udev->lpm_capable || udev->speed < USB_SPEED_SUPER) return;
/* Skip if the device BOS descriptor couldn't be read */ if (!udev->bos) return;
hub = usb_hub_to_struct_hub(udev->parent); /* It doesn't take time to transition the roothub into U0, since it *doesn'thaveanupstreamlink.
*/ if (!hub) return;
/* completion function, fires on port status changes and various faults */ staticvoid hub_irq(struct urb *urb)
{ struct usb_hub *hub = urb->context; int status = urb->status; unsigned i; unsignedlong bits;
switch (status) { case -ENOENT: /* synchronous unlink */ case -ECONNRESET: /* async unlink */ case -ESHUTDOWN: /* hardware going away */ return;
default: /* presumably an error */ /* Cause a hub reset after 10 consecutive errors */
dev_dbg(hub->intfdev, "transfer --> %d\n", status); if ((++hub->nerrors < 10) || hub->error) goto resubmit;
hub->error = status;
fallthrough;
/* let hub_wq handle things */ case0: /* we got data: port status changed */
bits = 0; for (i = 0; i < urb->actual_length; ++i)
bits |= ((unsignedlong) ((*hub->buffer)[i]))
<< (i*8);
hub->event_bits[0] = bits; break;
}
hub->nerrors = 0;
/* Something happened, let hub_wq figure it out */
kick_hub_wq(hub);
resubmit:
hub_resubmit_irq_urb(hub);
}
/* USB 2.0 spec Section 11.24.2.3 */ staticinlineint
hub_clear_tt_buffer(struct usb_device *hdev, u16 devinfo, u16 tt)
{ /* Need to clear both directions for control ep */ if (((devinfo >> 11) & USB_ENDPOINT_XFERTYPE_MASK) ==
USB_ENDPOINT_XFER_CONTROL) { int status = usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
HUB_CLEAR_TT_BUFFER, USB_RT_PORT,
devinfo ^ 0x8000, tt, NULL, 0, 1000); if (status) return status;
} return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
HUB_CLEAR_TT_BUFFER, USB_RT_PORT, devinfo,
tt, NULL, 0, 1000);
}
next = hub->tt.clear_list.next;
clear = list_entry(next, struct usb_tt_clear, clear_list);
list_del(&clear->clear_list);
/* drop lock so HCD can concurrently report other TT errors */
spin_unlock_irqrestore(&hub->tt.lock, flags);
status = hub_clear_tt_buffer(hdev, clear->devinfo, clear->tt); if (status && status != -ENODEV)
dev_err(&hdev->dev, "clear tt %d (%04x) error %d\n",
clear->tt, clear->devinfo, status);
/* Tell the HCD, even if the operation failed */
drv = clear->hcd->driver; if (drv->clear_tt_buffer_complete)
(drv->clear_tt_buffer_complete)(clear->hcd, clear->ep);
/* info for completion callback */
clear->hcd = bus_to_hcd(udev->bus);
clear->ep = urb->ep;
/* tell keventd to clear state for this TT */
spin_lock_irqsave(&tt->lock, flags);
list_add_tail(&clear->clear_list, &tt->clear_list);
schedule_work(&tt->clear_work);
spin_unlock_irqrestore(&tt->lock, flags); return0;
}
EXPORT_SYMBOL_GPL(usb_hub_clear_tt_buffer);
staticvoid hub_power_on(struct usb_hub *hub, bool do_delay)
{ int port1;
/* Enable power on each port. Some hubs have reserved values *ofLPSM(>2)intheirdescriptors,eventhoughtheyare *USB2.0hubs.Somehubsdonotimplementport-powerswitching *butonlyemulateit.Inallcases,theportswon'twork *unlesswesendthesemessagestothehub.
*/ if (hub_is_port_power_switchable(hub))
dev_dbg(hub->intfdev, "enabling power on all ports\n"); else
dev_dbg(hub->intfdev, "trying to enable port power on " "non-switchable hub\n"); for (port1 = 1; port1 <= hub->hdev->maxchild; port1++) if (test_bit(port1, hub->power_bits))
set_port_feature(hub->hdev, port1, USB_PORT_FEAT_POWER); else
usb_clear_port_feature(hub->hdev, port1,
USB_PORT_FEAT_POWER); if (do_delay)
msleep(hub_power_on_good_delay(hub));
}
/* FIXME let caller ask to power down the port: *-somedeviceswon'tenumeratewithoutaVBUSpowercycle *-SRPsavespowerthatway *-...newcall,TBD... *That'seasyifthishubcanswitchpowerper-port,and *hub_wqreactivatestheportlater(timer,SRP,etc). *Powerdownmustbeoptional,becauseofreset/DFU.
*/
staticvoid hub_activate(struct usb_hub *hub, enum hub_activation_type type)
{ struct usb_device *hdev = hub->hdev; struct usb_hcd *hcd; int ret; int port1; int status; bool need_debounce_delay = false; unsigned delay;
/* Continue a partial initialization */ if (type == HUB_INIT2 || type == HUB_INIT3) {
device_lock(&hdev->dev);
/* Was the hub disconnected while we were waiting? */ if (hub->disconnected) goto disconnected; if (type == HUB_INIT2) goto init2; goto init3;
}
hub_get(hub);
/* The superspeed hub except for root hub has to use Hub Depth *valueasanoffsetintotheroutestringtolocatethebits *itusestodeterminethedownstreamportnumber.Sohubdriver *shouldsendasethubdepthrequesttosuperspeedhubafter *thesuperspeedhubissetconfigurationininitializationor *resetprocedure. * *Afteraresume,portpowershouldstillbeon. *Foranyothertypeofactivation,turniton.
*/ if (type != HUB_RESUME) { if (hdev->parent && hub_is_superspeed(hdev)) {
ret = usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
HUB_SET_DEPTH, USB_RT_HUB,
hdev->level - 1, 0, NULL, 0,
USB_CTRL_SET_TIMEOUT); if (ret < 0)
dev_err(hub->intfdev, "set hub depth failed\n");
}
/* Speed up system boot by using a delayed_work for the *hub'sinitialpower-updelays.Thisisprettyawkward *andtheimplementationlookslikeahome-brewedsortof *setjmp/longjmp,butitsavesatleast100msforeach *roothub(assumingusbcoreiscompiledintothekernel *ratherthanasamodule).Itaddsup. * *Thiscan'tbedoneforHUB_RESUMEorHUB_RESET_RESUME *becauseforthoseactivationtypestheportshavetobe *operationalwhenwereturn.Intheorythiscouldbedone *forHUB_POST_RESET,butit'seasiernotto.
*/ if (type == HUB_INIT) {
delay = hub_power_on_good_delay(hub);
/* Suppress autosuspend until init is done */
usb_autopm_get_interface_no_resume(
to_usb_interface(hub->intfdev)); return; /* Continues at init2: below */
} elseif (type == HUB_RESET_RESUME) { /* The internal host controller state for the hub device *maybegoneafterahostpowerlossonsystemresume. *Updatethedevice'sinfosotheHWknowsit'sahub.
*/
hcd = bus_to_hcd(hdev->bus); if (hcd->driver->update_hub_device) {
ret = hcd->driver->update_hub_device(hcd, hdev,
&hub->tt, GFP_NOIO); if (ret < 0) {
dev_err(hub->intfdev, "Host not accepting hub info update\n");
dev_err(hub->intfdev, "LS/FS devices and hubs may not work under this hub\n");
}
}
hub_power_on(hub, true);
} else {
hub_power_on(hub, true);
} /* Give some time on remote wakeup to let links to transit to U0 */
} elseif (hub_is_superspeed(hub->hdev))
msleep(20);
/* Make sure a warm-reset request is handled by port_event */ if (type == HUB_RESUME &&
hub_port_warm_reset_required(hub, port1, portstatus))
set_bit(port1, hub->event_bits);
/* Clear status-change flags; we'll debounce later */ if (portchange & USB_PORT_STAT_C_CONNECTION) {
need_debounce_delay = true;
usb_clear_port_feature(hub->hdev, port1,
USB_PORT_FEAT_C_CONNECTION);
} if (portchange & USB_PORT_STAT_C_ENABLE) {
need_debounce_delay = true;
usb_clear_port_feature(hub->hdev, port1,
USB_PORT_FEAT_C_ENABLE);
} if (portchange & USB_PORT_STAT_C_RESET) {
need_debounce_delay = true;
usb_clear_port_feature(hub->hdev, port1,
USB_PORT_FEAT_C_RESET);
} if ((portchange & USB_PORT_STAT_C_BH_RESET) &&
hub_is_superspeed(hub->hdev)) {
need_debounce_delay = true;
usb_clear_port_feature(hub->hdev, port1,
USB_PORT_FEAT_C_BH_PORT_RESET);
} /* We can forget about a "removed" device when there's a *physicaldisconnectortheconnectstatuschanges.
*/ if (!(portstatus & USB_PORT_STAT_CONNECTION) ||
(portchange & USB_PORT_STAT_C_CONNECTION))
clear_bit(port1, hub->removed_bits);
if (!udev || udev->state == USB_STATE_NOTATTACHED) { /* Tell hub_wq to disconnect the device or *checkforanewconnectionorovercurrentcondition. *BasedonUSB2.0SpecSection11.12.5, *C_PORT_OVER_CURRENTcouldbesetwhile *PORT_OVER_CURRENTisnot.Socheckforanyofthem.
*/ if (udev || (portstatus & USB_PORT_STAT_CONNECTION) ||
(portchange & USB_PORT_STAT_C_CONNECTION) ||
(portstatus & USB_PORT_STAT_OVERCURRENT) ||
(portchange & USB_PORT_STAT_C_OVERCURRENT))
set_bit(port1, hub->change_bits);
} elseif (portstatus & USB_PORT_STAT_ENABLE) { bool port_resumed = (portstatus &
USB_PORT_STAT_LINK_STATE) ==
USB_SS_PORT_LS_U0; /* The power session apparently survived the resume. *Iftherewasanovercurrentorsuspendchange *(i.e.,remotewakeuprequest),havehub_wq *takecareofit.Lookattheportlinkstate *forUSB3.0hubs,sincetheydon'thaveasuspend *changebit,andtheydon'tsettheportlinkchange *bitondevice-initiatedresume.
*/ if (portchange || (hub_is_superspeed(hub->hdev) &&
port_resumed))
set_bit(port1, hub->event_bits);
} elseif (udev->persist_enabled) { #ifdef CONFIG_PM
udev->reset_resume = 1; #endif /* Don't set the change_bits when the device *waspoweredoff.
*/ if (test_bit(port1, hub->power_bits))
set_bit(port1, hub->change_bits);
} else { /* The power session is gone; tell hub_wq */
usb_set_device_state(udev, USB_STATE_NOTATTACHED);
set_bit(port1, hub->change_bits);
}
}
/* If no port-status-change flags were set, we don't need any *debouncing.Ifflagsweresetwecantrytodebouncethe *portsallatoncerightnow,insteadoflettinghub_wqdothem *oneatatimelateron. * *Ifanyport-statuschangesdooccurduringthisdelay,hub_wq *willseethemlaterandhandlethemnormally.
*/ if (need_debounce_delay) {
delay = HUB_DEBOUNCE_STABLE;
/* Don't do a long sleep inside a workqueue routine */ if (type == HUB_INIT2) {
INIT_DELAYED_WORK(&hub->init_work, hub_init_func3);
queue_delayed_work(system_power_efficient_wq,
&hub->init_work,
msecs_to_jiffies(delay));
device_unlock(&hdev->dev); return; /* Continues at init3: below */
} else {
msleep(delay);
}
}
init3:
hub->quiescing = 0;
status = usb_submit_urb(hub->urb, GFP_NOIO); if (status < 0)
dev_err(hub->intfdev, "activate --> %d\n", status); if (hub->has_indicators && blinkenlights)
queue_delayed_work(system_power_efficient_wq,
&hub->leds, LED_CYCLE_PERIOD);
/* Scan all ports that need attention */
kick_hub_wq(hub);
abort: if (type == HUB_INIT2 || type == HUB_INIT3) { /* Allow autosuspend if it was suppressed */
disconnected:
usb_autopm_put_interface_async(to_usb_interface(hub->intfdev));
device_unlock(&hdev->dev);
}
if (type == HUB_RESUME && hub_is_superspeed(hub->hdev)) { /* give usb3 downstream links training time after hub resume */
usb_autopm_get_interface_no_resume(
to_usb_interface(hub->intfdev));
/* hub_wq and related activity won't re-trigger */
spin_lock_irqsave(&hub->irq_urb_lock, flags);
hub->quiescing = 1;
spin_unlock_irqrestore(&hub->irq_urb_lock, flags);
if (type != HUB_SUSPEND) { /* Disconnect all the children */ for (i = 0; i < hdev->maxchild; ++i) { if (hub->ports[i]->child)
usb_disconnect(&hub->ports[i]->child);
}
}
/* Stop hub_wq and related activity */
timer_delete_sync(&hub->irq_urb_retry);
flush_delayed_work(&hub->post_resume_work);
usb_kill_urb(hub->urb); if (hub->has_indicators)
cancel_delayed_work_sync(&hub->leds); if (hub->tt.hub)
flush_work(&hub->tt.clear_work);
}
staticvoid hub_pm_barrier_for_all_ports(struct usb_hub *hub)
{ int i;
for (i = 0; i < hub->hdev->maxchild; ++i)
pm_runtime_barrier(&hub->ports[i]->dev);
}
/* caller has locked the hub device */ staticint hub_pre_reset(struct usb_interface *intf)
{ struct usb_hub *hub = usb_get_intfdata(intf);
hub->buffer = kmalloc(sizeof(*hub->buffer), GFP_KERNEL); if (!hub->buffer) {
ret = -ENOMEM; goto fail;
}
hub->status = kmalloc(sizeof(*hub->status), GFP_KERNEL); if (!hub->status) {
ret = -ENOMEM; goto fail;
}
mutex_init(&hub->status_mutex);
hub->descriptor = kzalloc(sizeof(*hub->descriptor), GFP_KERNEL); if (!hub->descriptor) {
ret = -ENOMEM; goto fail;
}
/* Request the entire hub descriptor. *hub->descriptorcanhandleUSB_MAXCHILDRENports, *buta(non-SS)hubcan/willreturnfewerbyteshere.
*/
ret = get_hub_descriptor(hdev, hub->descriptor); if (ret < 0) {
message = "can't read hub descriptor"; goto fail;
}
maxchild = USB_MAXCHILDREN; if (hub_is_superspeed(hdev))
maxchild = min_t(unsigned, maxchild, USB_SS_MAXPORTS);
if (hub->descriptor->bNbrPorts > maxchild) {
message = "hub has too many ports!";
ret = -ENODEV; goto fail;
} elseif (hub->descriptor->bNbrPorts == 0) {
message = "hub doesn't have any ports!";
ret = -ENODEV; goto fail;
}
/* FIXME for USB 3.0, skip for now */ if ((wHubCharacteristics & HUB_CHAR_COMPOUND) &&
!(hub_is_superspeed(hdev))) { char portstr[USB_MAXCHILDREN + 1];
switch (wHubCharacteristics & HUB_CHAR_LPSM) { case HUB_CHAR_COMMON_LPSM:
dev_dbg(hub_dev, "ganged power switching\n"); break; case HUB_CHAR_INDV_PORT_LPSM:
dev_dbg(hub_dev, "individual port power switching\n"); break; case HUB_CHAR_NO_LPSM: case HUB_CHAR_LPSM:
dev_dbg(hub_dev, "no power switching (usb 1.0)\n"); break;
}
switch (wHubCharacteristics & HUB_CHAR_OCPM) { case HUB_CHAR_COMMON_OCPM:
dev_dbg(hub_dev, "global over-current protection\n"); break; case HUB_CHAR_INDV_PORT_OCPM:
dev_dbg(hub_dev, "individual port over-current protection\n"); break; case HUB_CHAR_NO_OCPM: case HUB_CHAR_OCPM:
dev_dbg(hub_dev, "no over-current protection\n"); break;
}
spin_lock_init(&hub->tt.lock);
INIT_LIST_HEAD(&hub->tt.clear_list);
INIT_WORK(&hub->tt.clear_work, hub_tt_work); switch (hdev->descriptor.bDeviceProtocol) { case USB_HUB_PR_FS: break; case USB_HUB_PR_HS_SINGLE_TT:
dev_dbg(hub_dev, "Single TT\n");
hub->tt.hub = hdev; break; case USB_HUB_PR_HS_MULTI_TT:
ret = usb_set_interface(hdev, 0, 1); if (ret == 0) {
dev_dbg(hub_dev, "TT per port\n");
hub->tt.multi = 1;
} else
dev_err(hub_dev, "Using single TT (err %d)\n",
ret);
hub->tt.hub = hdev; break; case USB_HUB_PR_SS: /* USB 3.0 hubs don't have a TT */ break; default:
dev_dbg(hub_dev, "Unrecognized hub protocol %d\n",
hdev->descriptor.bDeviceProtocol); break;
}
/* Note 8 FS bit times == (8 bits / 12000000 bps) ~= 666ns */ switch (wHubCharacteristics & HUB_CHAR_TTTT) { case HUB_TTTT_8_BITS: if (hdev->descriptor.bDeviceProtocol != 0) {
hub->tt.think_time = 666;
dev_dbg(hub_dev, "TT requires at most %d " "FS bit times (%d ns)\n", 8, hub->tt.think_time);
} break; case HUB_TTTT_16_BITS:
hub->tt.think_time = 666 * 2;
dev_dbg(hub_dev, "TT requires at most %d " "FS bit times (%d ns)\n", 16, hub->tt.think_time); break; case HUB_TTTT_24_BITS:
hub->tt.think_time = 666 * 3;
dev_dbg(hub_dev, "TT requires at most %d " "FS bit times (%d ns)\n", 24, hub->tt.think_time); break; case HUB_TTTT_32_BITS:
hub->tt.think_time = 666 * 4;
dev_dbg(hub_dev, "TT requires at most %d " "FS bit times (%d ns)\n", 32, hub->tt.think_time); break;
}
/* probe() zeroes hub->indicator[] */ if (wHubCharacteristics & HUB_CHAR_PORTIND) {
hub->has_indicators = 1;
dev_dbg(hub_dev, "Port indicators are supported\n");
}
dev_dbg(hub_dev, "power on to power good time: %dms\n",
hub->descriptor->bPwrOn2PwrGood * 2);
/* power budgeting mostly matters with bus-powered hubs, *andbattery-poweredroothubs(mayprovidejust8mA).
*/
ret = usb_get_std_status(hdev, USB_RECIP_DEVICE, 0, &hubstatus); if (ret) {
message = "can't get hub status"; goto fail;
}
hcd = bus_to_hcd(hdev->bus); if (hdev == hdev->bus->root_hub) { if (hcd->power_budget > 0)
hdev->bus_mA = hcd->power_budget; else
hdev->bus_mA = full_load * maxchild; if (hdev->bus_mA >= full_load)
hub->mA_per_port = full_load; else {
hub->mA_per_port = hdev->bus_mA;
hub->limited_power = 1;
}
} elseif ((hubstatus & (1 << USB_DEVICE_SELF_POWERED)) == 0) { int remaining = hdev->bus_mA -
hub->descriptor->bHubContrCurrent;
dev_dbg(hub_dev, "hub controller current requirement: %dmA\n",
hub->descriptor->bHubContrCurrent);
hub->limited_power = 1;
if (remaining < maxchild * unit_load)
dev_warn(hub_dev, "insufficient power available " "to use all downstream ports\n");
hub->mA_per_port = unit_load; /* 7.2.1 */
} else { /* Self-powered external hub */ /* FIXME: What about battery-powered external hubs that
* provide less current per port? */
hub->mA_per_port = full_load;
} if (hub->mA_per_port < full_load)
dev_dbg(hub_dev, "%umA bus power budget for each child\n",
hub->mA_per_port);
ret = hub_hub_status(hub, &hubstatus, &hubchange); if (ret < 0) {
message = "can't get hub status"; goto fail;
}
/* local power status reports aren't always correct */ if (hdev->actconfig->desc.bmAttributes & USB_CONFIG_ATT_SELFPOWER)
dev_dbg(hub_dev, "local power source is %s\n",
(hubstatus & HUB_STATUS_LOCAL_POWER)
? "lost (inactive)" : "good");
if ((wHubCharacteristics & HUB_CHAR_OCPM) == 0)
dev_dbg(hub_dev, "%sover-current condition exists\n",
(hubstatus & HUB_STATUS_OVERCURRENT) ? "" : "no ");
/* set up the interrupt endpoint *WeusetheEP'smaxpacketsizeinsteadof(PORTS+1+7)/8 *bytesasUSB2.0[11.12.3]saysbecausesomehubsareknown *tosendmoredata(andthuscauseoverflow).Forroothubs, *maxpktsizeisdefinedinhcd.c'sfakeendpointdescriptors
* to be big enough for at least USB_MAXCHILDREN ports. */
pipe = usb_rcvintpipe(hdev, endpoint->bEndpointAddress);
maxp = usb_maxpacket(hdev, pipe);
if (maxp > sizeof(*hub->buffer))
maxp = sizeof(*hub->buffer);
hub->urb = usb_alloc_urb(0, GFP_KERNEL); if (!hub->urb) {
ret = -ENOMEM; goto fail;
}
/* maybe cycle the hub leds */ if (hub->has_indicators && blinkenlights)
hub->indicator[0] = INDICATOR_CYCLE;
mutex_lock(&usb_port_peer_mutex); for (i = 0; i < maxchild; i++) {
ret = usb_hub_create_port_device(hub, i + 1); if (ret < 0) {
dev_err(hub->intfdev, "couldn't create port%d device.\n", i + 1); break;
}
}
hdev->maxchild = i; for (i = 0; i < hdev->maxchild; i++) { struct usb_port *port_dev = hub->ports[i];
pm_runtime_put(&port_dev->dev);
}
mutex_unlock(&usb_port_peer_mutex); if (ret < 0) goto fail;
/* Update the HCD's internal representation of this hub before hub_wq *startsgettingportstatuschangesfordevicesunderthehub.
*/ if (hcd->driver->update_hub_device) {
ret = hcd->driver->update_hub_device(hcd, hdev,
&hub->tt, GFP_KERNEL); if (ret < 0) {
message = "can't update HCD hub info"; goto fail;
}
}
if (hub->quirk_disable_autosuspend)
usb_autopm_put_interface(intf);
onboard_dev_destroy_pdevs(&hub->onboard_devs);
hub_put(hub);
}
staticbool hub_descriptor_is_sane(struct usb_host_interface *desc)
{ /* Some hubs have a subclass of 1, which AFAICT according to the */ /* specs is not defined, but it works */ if (desc->desc.bInterfaceSubClass != 0 &&
desc->desc.bInterfaceSubClass != 1) returnfalse;
/* Multiple endpoints? What kind of mutant ninja-hub is this? */ if (desc->desc.bNumEndpoints != 1) returnfalse;
/* If the first endpoint is not interrupt IN, we'd better punt! */ if (!usb_endpoint_is_int_in(&desc->endpoint[0].desc)) returnfalse;
/* *TheUSB2.0specprohibitshubsfromhavingmorethanone *configurationorinterface,andwerelyonthisprohibition. *Refusetoacceptadevicethatviolatesit.
*/ if (hdev->descriptor.bNumConfigurations > 1 ||
hdev->actconfig->desc.bNumInterfaces > 1) {
dev_err(&intf->dev, "Invalid hub with more than one config or interface\n"); return -EINVAL;
}
if (hdev->state == USB_STATE_NOTATTACHED) return -ENODEV; if (port1 == 0 || port1 > hdev->maxchild) return -EINVAL;
/* Devices not managed by the hub driver *willalwayshavemaxchildequalto0.
*/
*ppowner = &(hub->ports[port1 - 1]->port_owner); return0;
}
/* In the following three functions, the caller must hold hdev's lock */ int usb_hub_claim_port(struct usb_device *hdev, unsigned port1, struct usb_dev_state *owner)
{ int rc; struct usb_dev_state **powner;
rc = find_port_owner(hdev, port1, &powner); if (rc) return rc; if (*powner) return -EBUSY;
*powner = owner; return rc;
}
EXPORT_SYMBOL_GPL(usb_hub_claim_port);
int usb_hub_release_port(struct usb_device *hdev, unsigned port1, struct usb_dev_state *owner)
{ int rc; struct usb_dev_state **powner;
for (i = 0; i < udev->maxchild; ++i) { if (hub->ports[i]->child)
recursively_mark_NOTATTACHED(hub->ports[i]->child);
} if (udev->state == USB_STATE_SUSPENDED)
udev->active_duration -= jiffies;
udev->state = USB_STATE_NOTATTACHED;
update_port_device_state(udev);
}
/* Free up all the children before we remove this device */ for (i = 0; i < udev->maxchild; i++) { if (hub->ports[i]->child)
usb_disconnect(&hub->ports[i]->child);
}
}
/* mark the device as inactive, so any further urb submissions for *thisdevice(andanyofitschildren)willfailimmediately. *thisquiesceseverythingexceptpendingurbs.
*/
usb_set_device_state(udev, USB_STATE_NOTATTACHED);
dev_info(&udev->dev, "USB disconnect, device number %d\n",
udev->devnum);
/* deallocate hcd/hardware state ... nuking all pending urbs and *cleaningupallstateassociatedwiththecurrentconfiguration *sothatthehardwareisnowfullyquiesced.
*/
dev_dbg(&udev->dev, "unregistering device\n");
usb_disable_device(udev, 0);
usb_hcd_synchronize_unlinks(udev);
if (udev->usb4_link)
device_link_del(udev->usb4_link);
/* Unregister the device. The device driver is responsible *forde-configuringthedeviceandinvokingtheremove-device *notifierchain(usedbyusbfsandpossiblyothers).
*/
device_del(&udev->dev);
/* Free the device number and delete the parent's children[] *(orroot_hub)pointer.
*/
release_devnum(udev);
if (udev->config == NULL) {
err = usb_get_configuration(udev); if (err < 0) { if (err != -ENODEV)
dev_err(&udev->dev, "can't read configurations, error %d\n",
err); return err;
}
}
/* read the standard strings and cache them if present */
udev->product = usb_cache_string(udev, udev->descriptor.iProduct);
udev->manufacturer = usb_cache_string(udev,
udev->descriptor.iManufacturer);
udev->serial = usb_cache_string(udev, udev->descriptor.iSerialNumber);
err = usb_enumerate_device_otg(udev); if (err < 0) return err;
if (IS_ENABLED(CONFIG_USB_OTG_PRODUCTLIST) && hcd->tpl_support &&
!is_targeted(udev)) { /* Maybe it can talk to us, though we can't talk to it. *(IncludesHNPtestdevice.)
*/ if (IS_ENABLED(CONFIG_USB_OTG) && (udev->bus->b_hnp_enable
|| udev->bus->is_b_host)) {
err = usb_port_suspend(udev, PMSG_AUTO_SUSPEND); if (err < 0)
dev_dbg(&udev->dev, "HNP fail, %d\n", err);
} return -ENOTSUPP;
}
if (udev->parent) { /* Initialize non-root-hub device wakeup to disabled; *device(un)configurationcontrolswakeupcapable *sysfspower/wakeupcontrolswakeupenabled/disabled
*/
device_init_wakeup(&udev->dev, 0);
}
/* Tell the runtime-PM framework the device is active */
pm_runtime_set_active(&udev->dev);
pm_runtime_get_noresume(&udev->dev);
pm_runtime_use_autosuspend(&udev->dev);
pm_runtime_enable(&udev->dev);
/* By default, forbid autosuspend for all devices. It will be *allowedforhubsduringbinding.
*/
usb_disable_autosuspend(udev);
if (udev->serial)
add_device_randomness(udev->serial, strlen(udev->serial)); if (udev->product)
add_device_randomness(udev->product, strlen(udev->product)); if (udev->manufacturer)
add_device_randomness(udev->manufacturer,
strlen(udev->manufacturer));
device_enable_async_suspend(&udev->dev);
/* check whether the hub or firmware marks this port as non-removable */
set_usb_port_removable(udev);
/* Register the device. The device driver is responsible *forconfiguringthedeviceandinvokingtheadd-device *notifierchain(usedbyusbfsandpossiblyothers).
*/
err = device_add(&udev->dev); if (err) {
dev_err(&udev->dev, "can't device_add, error %d\n", err); goto fail;
}
/* Create link files between child device and usb port device. */ if (udev->parent) { struct usb_hub *hub = usb_hub_to_struct_hub(udev->parent); int port1 = udev->portnum; struct usb_port *port_dev = hub->ports[port1 - 1];
err = sysfs_create_link(&udev->dev.kobj,
&port_dev->dev.kobj, "port"); if (err) goto out_del_dev;
int usb_authorize_device(struct usb_device *usb_dev)
{ int result = 0, c;
usb_lock_device(usb_dev); if (usb_dev->authorized == 1) goto out_authorized;
result = usb_autoresume_device(usb_dev); if (result < 0) {
dev_err(&usb_dev->dev, "can't autoresume for authorization: %d\n", result); goto error_autoresume;
}
usb_dev->authorized = 1; /* Choose and set the configuration. This registers the interfaces *withthedrivercoreandletsinterfacedriversbindtothem.
*/
c = usb_choose_configuration(usb_dev); if (c >= 0) {
result = usb_set_configuration(usb_dev, c); if (result) {
dev_err(&usb_dev->dev, "can't set config #%d, error %d\n", c, result); /* This need not be fatal. The user can try to
* set other configurations. */
}
}
dev_info(&usb_dev->dev, "authorized to connect\n");
/* *Ifuse_both_schemesisset,usethefirstscheme(whichever *itis)forthelargerhalfoftheretries,thenusetheother *scheme.Otherwise,usethefirstschemeforalltheretries.
*/ if (use_both_schemes && retry >= (PORT_INIT_TRIES + 1) / 2) return old_scheme_first_port; /* Second half */ return !old_scheme_first_port; /* First half or all */
}
/* Is a USB 3.0 port in the Inactive or Compliance Mode state? *Portwarmresetisrequiredtorecover
*/ staticbool hub_port_warm_reset_required(struct usb_hub *hub, int port1,
u16 portstatus)
{
u16 link_state;
if (!hub_is_superspeed(hub->hdev)) returnfalse;
if (test_bit(port1, hub->warm_reset_bits)) returntrue;
for (delay_time = 0;
delay_time < HUB_RESET_TIMEOUT;
delay_time += delay) { /* wait to give the device a chance to reset */
msleep(delay);
/* read and decode port status */ if (hub_is_superspeedplus(hub->hdev))
ret = hub_ext_port_status(hub, port1,
HUB_EXT_PORT_STATUS,
&portstatus, &portchange,
&ext_portstatus); else
ret = usb_hub_port_status(hub, port1, &portstatus,
&portchange); if (ret < 0) return ret;
if ((portstatus & USB_PORT_STAT_RESET)) return -EBUSY;
if (hub_port_warm_reset_required(hub, port1, portstatus)) return -ENOTCONN;
/* Device went away? */ if (!(portstatus & USB_PORT_STAT_CONNECTION)) return -ENOTCONN;
/* Retry if connect change is set but status is still connected. *AUSB3.0connectionmaybounceifmultiplewarmresetswereissued, *butthedevicemayhavesuccessfullyre-connected.Ignoreit.
*/ if (!hub_is_superspeed(hub->hdev) &&
(portchange & USB_PORT_STAT_C_CONNECTION)) {
usb_clear_port_feature(hub->hdev, port1,
USB_PORT_FEAT_C_CONNECTION); return -EAGAIN;
}
if (!(portstatus & USB_PORT_STAT_ENABLE)) return -EBUSY;
dev_err(&port_dev->dev, "Cannot enable. Maybe the USB cable is bad?\n");
done: if (status == 0) { if (port_dev->quirks & USB_PORT_QUIRK_FAST_ENUM)
usleep_range(10000, 12000); else { /* TRSTRCY = 10 ms; plus some extra */
reset_recovery_time = 10 + 40;
/* Hub needs extra delay after resetting its port. */ if (hub->hdev->quirks & USB_QUIRK_HUB_SLOW_RESET)
reset_recovery_time += 100;
msleep(reset_recovery_time);
}
if (udev) { struct usb_hcd *hcd = bus_to_hcd(udev->bus);
update_devnum(udev, 0); /* The xHC may think the device is already reset, *soignorethestatus.
*/ if (hcd->driver->reset_device)
hcd->driver->reset_device(hcd, udev);
/* Check if a port is suspended(USB2.0 port) or in U3 state(USB3.0 port) */ staticint port_is_suspended(struct usb_hub *hub, unsigned portstatus)
{ int ret = 0;
if (hub_is_superspeed(hub->hdev)) { if ((portstatus & USB_PORT_STAT_LINK_STATE)
== USB_SS_PORT_LS_U3)
ret = 1;
} else { if (portstatus & USB_PORT_STAT_SUSPEND)
ret = 1;
}
return ret;
}
/* Determine whether the device on a port is ready for a normal resume, *isreadyforareset-resume,orshouldbedisconnected.
*/ staticint check_port_resume_type(struct usb_device *udev, struct usb_hub *hub, int port1, int status, u16 portchange, u16 portstatus)
{ struct usb_port *port_dev = hub->ports[port1 - 1]; int retries = 3;
retry: /* Is a warm reset needed to recover the connection? */ if (status == 0 && udev->reset_resume
&& hub_port_warm_reset_required(hub, port1, portstatus)) { /* pass */;
} /* Is the device still present? */ elseif (status || port_is_suspended(hub, portstatus) ||
!usb_port_is_power_on(hub, portstatus)) { if (status >= 0)
status = -ENODEV;
} elseif (!(portstatus & USB_PORT_STAT_CONNECTION)) { if (retries--) {
usleep_range(200, 300);
status = usb_hub_port_status(hub, port1, &portstatus,
&portchange); goto retry;
}
status = -ENODEV;
}
/* Can't do a normal resume if the port isn't enabled, *sotryareset-resumeinstead.
*/ elseif (!(portstatus & USB_PORT_STAT_ENABLE) && !udev->reset_resume) { if (udev->persist_enabled)
udev->reset_resume = 1; else
status = -ENODEV;
}
if (status) {
dev_dbg(&port_dev->dev, "status %04x.%04x after resume, %d\n",
portchange, portstatus, status);
} elseif (udev->reset_resume) {
/* Late port handoff can set status-change bits */ if (portchange & USB_PORT_STAT_C_CONNECTION)
usb_clear_port_feature(hub->hdev, port1,
USB_PORT_FEAT_C_CONNECTION); if (portchange & USB_PORT_STAT_C_ENABLE)
usb_clear_port_feature(hub->hdev, port1,
USB_PORT_FEAT_C_ENABLE);
/* enable remote wakeup when appropriate; this lets the device *wakeuptheupstreamhub(includingmaybetheroothub). * *NOTE:OTGdevicesmayissueremotewakeup(orSRP)evenwhen *wedon'texplicitlyenableithere.
*/ if (udev->do_remote_wakeup) {
status = usb_enable_remote_wakeup(udev); if (status) {
dev_dbg(&udev->dev, "won't remote wakeup, status %d\n",
status); /* bail if autosuspend is requested */ if (PMSG_IS_AUTO(msg)) goto err_wakeup;
}
}
if (usb_disable_ltm(udev)) {
dev_err(&udev->dev, "Failed to disable LTM before suspend\n");
status = -ENOMEM; if (PMSG_IS_AUTO(msg)) goto err_ltm;
}
/* see 7.1.7.6 */ if (hub_is_superspeed(hub->hdev))
status = hub_set_port_link_state(hub, port1, USB_SS_PORT_LS_U3);
/* *Forsystemsuspend,wedonotneedtoenablethesuspendfeature *onindividualUSB-2ports.Thedeviceswillautomaticallygo *intosuspendafewmsaftertheroothubstopssendingpackets. *TheUSB2.0speccallsthis"globalsuspend". * *However,manyUSBhubshaveabug:Theydon'trelaywakeuprequests *fromadownstreamportiftheport'ssuspendfeatureisn'ton. *Thereforewewillturnonthesuspendfeatureifudevoranyofits *descendantsisenabledforremotewakeup.
*/ elseif (PMSG_IS_AUTO(msg) || usb_wakeup_enabled_descendants(udev) > 0)
status = set_port_feature(hub->hdev, port1,
USB_PORT_FEAT_SUSPEND); else {
really_suspend = false;
status = 0;
} if (status) { /* Check if the port has been suspended for the timeout case *topreventthesuspendedportfromincorrecthandling.
*/ if (status == -ETIMEDOUT) { int ret;
u16 portstatus, portchange;
/* usb ch9 identifies four variants of SUSPENDED, based on what *statethedeviceresumesto.Linuxcurrentlywon'tseethe *firsttwoonthehostside;they'dbeinsidehub_port_init() *duringmanytimeouts,buthub_wqcan'tsuspenduntillater.
*/
usb_set_device_state(udev, udev->actconfig
? USB_STATE_CONFIGURED
: USB_STATE_ADDRESS);
/* 10.5.4.5 says not to reset a suspended port if the attached *deviceisenabledforremotewakeup.Hencethereset *operationiscarriedouthere,aftertheporthasbeen *resumed.
*/ if (udev->reset_resume) { /* *Ifthedevicemorphsorswitchesmodeswhenitisreset, *wedon'twanttoperformareset-resume.We'llfailthe *resume,whichwillcausealogicaldisconnect,andthen *thedevicewillberediscovered.
*/
retry_reset_resume: if (udev->quirks & USB_QUIRK_RESET)
status = -ENODEV; else
status = usb_reset_and_verify_device(udev);
}
/* 10.5.4.5 says be sure devices in the tree are still there. *Fornowlet'sassumethedevicedidn'tgocrazyonresume, *anddevicedriverswillknowaboutanyresumequirks.
*/ if (status == 0) {
devstatus = 0;
status = usb_get_std_status(udev, USB_RECIP_DEVICE, 0, &devstatus);
/* If a normal resume failed, try doing a reset-resume */ if (status && !udev->reset_resume && udev->persist_enabled) {
dev_dbg(&udev->dev, "retry with reset-resume\n");
udev->reset_resume = 1; goto retry_reset_resume;
}
}
if (status) {
dev_dbg(&udev->dev, "gone after usb resume? status %d\n",
status); /* *Thereareafewquirkydeviceswhichviolatethestandard *byclaimingtohaveremotewakeupenabledafterareset, *whichcrashifthefeatureiscleared,hencecheckfor *udev->reset_resume
*/
} elseif (udev->actconfig && !udev->reset_resume) { if (udev->speed < USB_SPEED_SUPER) { if (devstatus & (1 << USB_DEVICE_REMOTE_WAKEUP))
status = usb_disable_remote_wakeup(udev);
} else {
status = usb_get_std_status(udev, USB_RECIP_INTERFACE, 0,
&devstatus); if (!status && devstatus & (USB_INTRF_STAT_FUNC_RW_CAP
| USB_INTRF_STAT_FUNC_RW))
status = usb_disable_remote_wakeup(udev);
}
if (status)
dev_dbg(&udev->dev, "disable remote wakeup, status %d\n",
status);
status = 0;
} return status;
}
if (!test_and_set_bit(port1, hub->child_usage_bits)) {
status = pm_runtime_resume_and_get(&port_dev->dev); if (status < 0) {
dev_dbg(&udev->dev, "can't resume usb port, status %d\n",
status); return status;
}
}
usb_lock_port(port_dev);
/* Skip the initial Clear-Suspend step for a remote wakeup */
status = usb_hub_port_status(hub, port1, &portstatus, &portchange); if (status == 0 && !port_is_suspended(hub, portstatus)) { if (portchange & USB_PORT_STAT_C_SUSPEND)
pm_wakeup_event(&udev->dev, 0); goto SuspendCleared;
}
/* see 7.1.7.7; affects power usage, but not budgeting */ if (hub_is_superspeed(hub->hdev))
status = hub_set_port_link_state(hub, port1, USB_SS_PORT_LS_U0); else
status = usb_clear_port_feature(hub->hdev,
port1, USB_PORT_FEAT_SUSPEND); if (status) {
dev_dbg(&port_dev->dev, "can't resume, status %d\n", status);
} else { /* drive resume for USB_RESUME_TIMEOUT msec */
dev_dbg(&udev->dev, "usb %sresume\n",
(PMSG_IS_AUTO(msg) ? "auto-" : ""));
msleep(USB_RESUME_TIMEOUT);
/* Virtual root hubs can trigger on GET_PORT_STATUS to *stopresumesignaling.Thenfinishtheresume *sequence.
*/
status = usb_hub_port_status(hub, port1, &portstatus, &portchange);
}
SuspendCleared: if (status == 0) {
udev->port_is_suspended = 0; if (hub_is_superspeed(hub->hdev)) { if (portchange & USB_PORT_STAT_C_LINK_STATE)
usb_clear_port_feature(hub->hdev, port1,
USB_PORT_FEAT_C_PORT_LINK_STATE);
} else { if (portchange & USB_PORT_STAT_C_SUSPEND)
usb_clear_port_feature(hub->hdev, port1,
USB_PORT_FEAT_C_SUSPEND);
}
/* TRSMRCY = 10 msec */
msleep(10);
}
if (udev->persist_enabled)
status = wait_for_connected(udev, hub, port1, &portchange,
&portstatus);
status = check_port_resume_type(udev,
hub, port1, status, portchange, portstatus); if (status == 0)
status = finish_port_resume(udev); if (status < 0) {
dev_dbg(&udev->dev, "can't resume, status %d\n", status);
hub_port_logical_disconnect(hub, port1);
} else { /* Try to enable USB2 hardware LPM */
usb_enable_usb2_hardware_lpm(udev);
/* Try to enable USB3 LTM */
usb_enable_ltm(udev);
}
usb_unlock_port(port_dev);
return status;
}
int usb_remote_wakeup(struct usb_device *udev)
{ int status = 0;
usb_lock_device(udev); if (udev->state == USB_STATE_SUSPENDED) {
dev_dbg(&udev->dev, "usb %sresume\n", "wakeup-");
status = usb_autoresume_device(udev); if (status == 0) { /* Let the drivers do their thing, then... */
usb_autosuspend_device(udev);
}
}
usb_unlock_device(udev); return status;
}
/* Returns 1 if there was a remote wakeup and a connect status change. */ staticint hub_handle_remote_wakeup(struct usb_hub *hub, unsignedint port,
u16 portstatus, u16 portchange)
__must_hold(&port_dev->status_lock)
{ struct usb_port *port_dev = hub->ports[port - 1]; struct usb_device *hdev; struct usb_device *udev; int connect_change = 0;
u16 link_state; int ret;
if (udev && udev->can_submit) {
dev_warn(&port_dev->dev, "device %s not suspended yet\n",
dev_name(&udev->dev)); if (PMSG_IS_AUTO(msg)) return -EBUSY;
} if (udev)
hub->wakeup_enabled_descendants +=
usb_wakeup_enabled_descendants(udev);
}
if (hdev->do_remote_wakeup && hub->quirk_check_port_auto_suspend) { /* check if there are changes pending on hub ports */ if (check_ports_changed(hub)) { if (PMSG_IS_AUTO(msg)) return -EBUSY;
pm_wakeup_event(&hdev->dev, 2000);
}
}
if (hub_is_superspeed(hdev) && hdev->do_remote_wakeup) { /* Enable hub to send remote wakeup for all ports. */ for (port1 = 1; port1 <= hdev->maxchild; port1++) {
set_port_feature(hdev,
port1 |
USB_PORT_FEAT_REMOTE_WAKE_CONNECT |
USB_PORT_FEAT_REMOTE_WAKE_DISCONNECT |
USB_PORT_FEAT_REMOTE_WAKE_OVER_CURRENT,
USB_PORT_FEAT_REMOTE_WAKE_MASK);
}
}
dev_dbg(&intf->dev, "%s\n", __func__);
/* stop hub_wq and related activity */
hub_quiesce(hub, HUB_SUSPEND); return0;
}
/* Report wakeup requests from the ports of a resuming root hub */ staticvoid report_wakeup_requests(struct usb_hub *hub)
{ struct usb_device *hdev = hub->hdev; struct usb_device *udev; struct usb_hcd *hcd; unsignedlong resuming_ports; int i;
if (hdev->parent) return; /* Not a root hub */
hcd = bus_to_hcd(hdev->bus); if (hcd->driver->get_resuming_ports) {
/* *Theget_resuming_ports()methodreturnsabitmap(origin0) *ofportswhichhavestartedwakeupsignalingbuthavenot *yetfinishedresuming.Duringsystemresumewewill *resumealltheenabledports,regardlessofanywakeup *signals,whichmeansthewakeuprequestswouldbelost. *Topreventthis,reportthemtothePMcorehere.
*/
resuming_ports = hcd->driver->get_resuming_ports(hcd); for (i = 0; i < hdev->maxchild; ++i) { if (test_bit(i, &resuming_ports)) {
udev = hub->ports[i]->child; if (udev)
pm_wakeup_event(&udev->dev, 0);
}
}
}
}
if (!udev->parent || udev->speed < USB_SPEED_SUPER || !udev->lpm_capable) return0;
/* Convert SEL and PEL stored in ns to us */
u1_sel = DIV_ROUND_UP(udev->u1_params.sel, 1000);
u1_pel = DIV_ROUND_UP(udev->u1_params.pel, 1000);
u2_sel = DIV_ROUND_UP(udev->u2_params.sel, 1000);
u2_pel = DIV_ROUND_UP(udev->u2_params.pel, 1000);
/* *MakesurethatthecalculatedSELandPELvaluesforthelink *statewe'reenablingaren'tbiggerthanthemaxSEL/PEL *valuethatwillfitintheSETSELcontroltransfer. *Otherwisethedevicewouldgetanincorrectideaoftheexit *latencyforthelinkstate,andcouldstartadevice-initiated *U1/U2whentheexitlatenciesaretoohigh.
*/ if (u1_sel > USB3_LPM_MAX_U1_SEL_PEL ||
u1_pel > USB3_LPM_MAX_U1_SEL_PEL ||
u2_sel > USB3_LPM_MAX_U2_SEL_PEL ||
u2_pel > USB3_LPM_MAX_U2_SEL_PEL) {
dev_dbg(&udev->dev, "Device-initiated U1/U2 disabled due to long SEL or PEL\n"); return -EINVAL;
}
staticint usb_set_lpm_timeout(struct usb_device *udev, enum usb3_link_state state, int timeout)
{ int ret; int feature;
switch (state) { case USB3_LPM_U1:
feature = USB_PORT_FEAT_U1_TIMEOUT; break; case USB3_LPM_U2:
feature = USB_PORT_FEAT_U2_TIMEOUT; break; default:
dev_warn(&udev->dev, "%s: Can't set timeout for non-U1 or U2 state.\n",
__func__); return -EINVAL;
}
if (state == USB3_LPM_U1 && timeout > USB3_LPM_U1_MAX_TIMEOUT &&
timeout != USB3_LPM_DEVICE_INITIATED) {
dev_warn(&udev->dev, "Failed to set %s timeout to 0x%x, " "which is a reserved value.\n",
usb3_lpm_names[state], timeout); return -EINVAL;
}
ret = set_port_feature(udev->parent,
USB_PORT_LPM_TIMEOUT(timeout) | udev->portnum,
feature); if (ret < 0) {
dev_warn(&udev->dev, "Failed to set %s timeout to 0x%x," "error code %i\n", usb3_lpm_names[state],
timeout, ret); return -EBUSY;
} if (state == USB3_LPM_U1)
udev->u1_params.timeout = timeout; else
udev->u2_params.timeout = timeout; return0;
}
/* *Don'tallowdeviceintiatedU1/U2ifdeviceisn'tintheconfiguredstate, *orthesystemexitlatency+onebusintervalisgreaterthantheminimum *serviceintervalofanyactiveperiodicendpoint.SeeUSB3.2section9.4.9
*/ staticbool usb_device_may_initiate_lpm(struct usb_device *udev, enum usb3_link_state state)
{ unsignedint sel; /* us */ int i, j;
if (!udev->lpm_devinit_allow || !udev->actconfig) returnfalse;
if (state == USB3_LPM_U1)
sel = DIV_ROUND_UP(udev->u1_params.sel, 1000); elseif (state == USB3_LPM_U2)
sel = DIV_ROUND_UP(udev->u2_params.sel, 1000); else returnfalse;
for (i = 0; i < udev->actconfig->desc.bNumInterfaces; i++) { struct usb_interface *intf; struct usb_endpoint_descriptor *desc; unsignedint interval;
intf = udev->actconfig->interface[i]; if (!intf) continue;
/* If the device says it doesn't have *any* exit latency to come out of *U1orU2,it'sprobablylying.Assumeitdoesn'timplementthatlink *state.
*/ if ((state == USB3_LPM_U1 && u1_mel == 0) ||
(state == USB3_LPM_U2 && u2_mel == 0)) return -EINVAL;
/* We allow the host controller to set the U1/U2 timeout internally *first,sothatitcanchangeitsscheduletoaccountforthe *additionallatencytosenddatatoadeviceinalowerpower *linkstate.
*/
timeout = hcd->driver->enable_usb3_lpm_timeout(hcd, udev, state);
/* xHCI host controller doesn't want to enable this LPM state. */ if (timeout == 0) return -EINVAL;
if (timeout < 0) {
dev_warn(&udev->dev, "Could not enable %s link state, " "xHCI error %i.\n", usb3_lpm_names[state],
timeout); return timeout;
}
if (usb_set_lpm_timeout(udev, state, timeout)) { /* If we can't set the parent hub U1/U2 timeout, *device-initiatedLPMwon'tbeallowedeither,soletthexHCI *hostknowthatthislinkstatewon'tbeenabled.
*/
hcd->driver->disable_usb3_lpm_timeout(hcd, udev, state); return -EBUSY;
}
if (usb_set_lpm_timeout(udev, state, 0)) return -EBUSY;
if (hcd->driver->disable_usb3_lpm_timeout(hcd, udev, state))
dev_warn(&udev->dev, "Could not disable xHCI %s timeout, " "bus schedule bandwidth may be impacted.\n",
usb3_lpm_names[state]);
/* As soon as usb_set_lpm_timeout(0) return 0, hub initiated LPM *isdisabled.HubwilldisallowslinktoenterU1/U2aswell, *evendeviceisinitiatingLPM.HenceLPMisdisabledifhubLPM *timeoutsetto0,nomatterdevice-initiatedLPMisdisabledor *not.
*/ if (state == USB3_LPM_U1)
udev->usb3_lpm_u1_enabled = 0; elseif (state == USB3_LPM_U2)
udev->usb3_lpm_u2_enabled = 0;
return0;
}
/* *Disablehub-initiatedanddevice-initiatedU1andU2entry. *Callermustownthebandwidth_mutex. * *Thiswillcallusb_enable_lpm()onfailure,whichwilldecrement *lpm_disable_count,andwillre-enableLPMiflpm_disable_countreacheszero.
*/ int usb_disable_lpm(struct usb_device *udev)
{ struct usb_hcd *hcd; int err;
hcd = bus_to_hcd(udev->bus); if (!hcd || !hcd->driver->disable_usb3_lpm_timeout) return0;
udev->lpm_disable_count++; if ((udev->u1_params.timeout == 0 && udev->u2_params.timeout == 0)) return0;
/* If LPM is enabled, attempt to disable it. */ if (usb_disable_link_state(hcd, udev, USB3_LPM_U1)) goto disable_failed; if (usb_disable_link_state(hcd, udev, USB3_LPM_U2)) goto disable_failed;
err = usb_set_device_initiated_lpm(udev, USB3_LPM_U1, false); if (!err)
usb_set_device_initiated_lpm(udev, USB3_LPM_U2, false);
/* Grab the bandwidth_mutex before calling usb_disable_lpm() */ int usb_unlocked_disable_lpm(struct usb_device *udev)
{ struct usb_hcd *hcd = bus_to_hcd(udev->bus); int ret;
if (!hcd) return -EINVAL;
mutex_lock(hcd->bandwidth_mutex);
ret = usb_disable_lpm(udev);
mutex_unlock(hcd->bandwidth_mutex);
udev->lpm_disable_count--;
hcd = bus_to_hcd(udev->bus); /* Double check that we can both enable and disable LPM. *DevicemustbeconfiguredtoacceptsetfeatureU1/U2timeout.
*/ if (!hcd || !hcd->driver->enable_usb3_lpm_timeout ||
!hcd->driver->disable_usb3_lpm_timeout) return;
if (udev->lpm_disable_count > 0) return;
hub = usb_hub_to_struct_hub(udev->parent); if (!hub) return;
port_dev = hub->ports[udev->portnum - 1];
if (port_dev->usb3_lpm_u1_permit) if (usb_enable_link_state(hcd, udev, USB3_LPM_U1)) return;
if (port_dev->usb3_lpm_u2_permit) if (usb_enable_link_state(hcd, udev, USB3_LPM_U2)) return;
/* *EnabledeviceinitiatedU1/U2withaSetFeature(U1/U2_ENABLE)request *ifsystemexitlatencyisshortenoughanddeviceisconfigured
*/ if (usb_device_may_initiate_lpm(udev, USB3_LPM_U1)) { if (usb_set_device_initiated_lpm(udev, USB3_LPM_U1, true)) return;
if (usb_device_may_initiate_lpm(udev, USB3_LPM_U2))
usb_set_device_initiated_lpm(udev, USB3_LPM_U2, true);
}
}
EXPORT_SYMBOL_GPL(usb_enable_lpm);
/* Grab the bandwidth_mutex before calling usb_enable_lpm() */ void usb_unlocked_enable_lpm(struct usb_device *udev)
{ struct usb_hcd *hcd = bus_to_hcd(udev->bus);
buf = kmalloc(GET_DESCRIPTOR_BUFSIZE, GFP_NOIO); if (!buf) return -ENOMEM;
/* root hub ports have a slightly longer reset period *(fromUSB2.0spec,section7.1.7.5)
*/ if (!hdev->parent) {
delay = HUB_ROOT_RESET_TIME; if (port1 == hdev->bus->otg_port)
hdev->bus->b_hnp_enable = 0;
}
/* Some low speed devices have problems with the quick delay, so */ /* be a bit pessimistic with those devices. RHbug #23670 */ if (oldspeed == USB_SPEED_LOW)
delay = HUB_LONG_RESET_TIME;
/* Reset the device; full speed may morph to high speed */ /* FIXME a USB 2.0 device may morph into SuperSpeed on reset. */
retval = hub_port_reset(hub, port1, udev, delay, false); if (retval < 0) /* error or disconnect */ goto fail; /* success, speed is known */
retval = 0; /* notify HCD that we have a device connected and addressed */ if (hcd->driver->update_device)
hcd->driver->update_device(hcd, udev);
hub_set_initial_usb2_lpm_policy(udev);
fail: if (retval) {
hub_port_disable(hub, port1, 0);
update_devnum(udev, devnum); /* for disconnect processing */
}
kfree(buf); return retval;
}
staticvoid
check_highspeed(struct usb_hub *hub, struct usb_device *udev, int port1)
{ struct usb_qualifier_descriptor *qual; int status;
if (udev->quirks & USB_QUIRK_DEVICE_QUALIFIER) return;
qual = kmalloc(sizeof *qual, GFP_KERNEL); if (qual == NULL) return;
status = usb_get_descriptor(udev, USB_DT_DEVICE_QUALIFIER, 0,
qual, sizeof *qual); if (status == sizeof *qual) {
dev_info(&udev->dev, "not running at top speed; " "connect to a high speed hub\n"); /* hub LEDs are probably harder to miss than syslog */ if (hub->has_indicators) {
hub->indicator[port1-1] = INDICATOR_GREEN_BLINK;
queue_delayed_work(system_power_efficient_wq,
&hub->leds, 0);
}
}
kfree(qual);
}
staticunsigned
hub_power_remaining(struct usb_hub *hub)
{ struct usb_device *hdev = hub->hdev; int remaining; int port1;
if (memcmp(&udev->descriptor, new_device_descriptor, sizeof(*new_device_descriptor)) != 0) return1;
if ((old_bos && !udev->bos) || (!old_bos && udev->bos)) return1; if (udev->bos) {
len = le16_to_cpu(udev->bos->desc->wTotalLength); if (len != le16_to_cpu(old_bos->desc->wTotalLength)) return1; if (memcmp(udev->bos->desc, old_bos->desc, len)) return1;
}
/* Since the idVendor, idProduct, and bcdDevice values in the *devicedescriptorhaven'tchanged,wewillassumethe *ManufacturerandProductstringshaven'tchangedeither. *ButtheSerialNumberstringcouldbedifferent(e.g.,a *differentflashcardofthesamebrand).
*/ if (udev->serial)
serial_len = strlen(udev->serial) + 1;
len = serial_len; for (index = 0; index < udev->descriptor.bNumConfigurations; index++) {
old_length = le16_to_cpu(udev->config[index].desc.wTotalLength);
len = max(len, old_length);
}
buf = kmalloc(len, GFP_NOIO); if (!buf) /* assume the worst */ return1;
/* Disconnect any existing devices under this port */ if (udev) { if (hcd->usb_phy && !hdev->parent)
usb_phy_notify_disconnect(hcd->usb_phy, udev->speed);
usb_disconnect(&port_dev->child);
}
/* We can forget about a "removed" device when there's a physical *disconnectortheconnectstatuschanges.
*/ if (!(portstatus & USB_PORT_STAT_CONNECTION) ||
(portchange & USB_PORT_STAT_C_CONNECTION))
clear_bit(port1, hub->removed_bits);
/* Return now if debouncing failed or nothing is connected or *thedevicewas"removed".
*/ if (!(portstatus & USB_PORT_STAT_CONNECTION) ||
test_bit(port1, hub->removed_bits)) {
/* Devices connected to SuperSpeed hubs are USB 3.0 or later */ if (hub_is_superspeed(hub->hdev))
udev->speed = USB_SPEED_SUPER; else
udev->speed = USB_SPEED_UNKNOWN;
choose_devnum(udev); if (udev->devnum <= 0) {
status = -ENOTCONN; /* Don't retry */ goto loop;
}
/* reset (non-USB 3.0 devices) and get descriptor */
status = hub_port_init(hub, udev, port1, i, NULL); if (status < 0) goto loop;
if (udev->quirks & USB_QUIRK_DELAY_INIT)
msleep(2000);
/* consecutive bus-powered hubs aren't reliable; they can *violatethevoltagedropbudget.ifthenewchildhas *a"powered"LED,usersshouldnoticewedidn'tenableit *(withoutreadingsyslog),evenwithoutper-portLEDs *ontheparent.
*/ if (udev->descriptor.bDeviceClass == USB_CLASS_HUB
&& udev->bus_mA <= unit_load) {
u16 devstat;
status = usb_get_std_status(udev, USB_RECIP_DEVICE, 0,
&devstat); if (status) {
dev_dbg(&udev->dev, "get status %d ?\n", status); goto loop_disable;
} if ((devstat & (1 << USB_DEVICE_SELF_POWERED)) == 0) {
dev_err(&udev->dev, "can't connect bus-powered hub " "to this port\n"); if (hub->has_indicators) {
hub->indicator[port1-1] =
INDICATOR_AMBER_BLINK;
queue_delayed_work(
system_power_efficient_wq,
&hub->leds, 0);
}
status = -ENOTCONN; /* Don't retry */ goto loop_disable;
}
}
/* check for devices running slower than they could */ if (le16_to_cpu(udev->descriptor.bcdUSB) >= 0x0200
&& udev->speed == USB_SPEED_FULL
&& highspeed_hubs != 0)
check_highspeed(hub, udev, port1);
/* Store the parent's children[] pointer. At this point *udevbecomesgloballyaccessible,althoughpresumably *noonewilllookatituntilhdevisunlocked.
*/
status = 0;
mutex_lock(&usb_port_peer_mutex);
/* We mustn't add new devices if the parent hub has *beendisconnected;wewouldracewiththe *recursively_mark_NOTATTACHED()routine.
*/
spin_lock_irq(&device_state_lock); if (hdev->state == USB_STATE_NOTATTACHED)
status = -ENOTCONN; else
port_dev->child = udev;
spin_unlock_irq(&device_state_lock);
mutex_unlock(&usb_port_peer_mutex);
/* Run it through the hoops (find a driver, etc) */ if (!status) {
status = usb_new_device(udev); if (status) {
mutex_lock(&usb_port_peer_mutex);
spin_lock_irq(&device_state_lock);
port_dev->child = NULL;
spin_unlock_irq(&device_state_lock);
mutex_unlock(&usb_port_peer_mutex);
} else { if (hcd->usb_phy && !hdev->parent)
usb_phy_notify_connect(hcd->usb_phy,
udev->speed);
}
}
if (status) goto loop_disable;
status = hub_power_remaining(hub); if (status)
dev_dbg(hub->intfdev, "%dmA power budget left\n", status);
/* Lock the device, then check to see if we were
* disconnected while waiting for the lock to succeed. */
usb_lock_device(hdev); if (unlikely(hub->disconnected)) goto out_hdev_lock;
/* If the hub has died, clean up after it */ if (hdev->state == USB_STATE_NOTATTACHED) {
hub->error = -ENODEV;
hub_quiesce(hub, HUB_DISCONNECT); goto out_hdev_lock;
}
/* Autoresume */
ret = usb_autopm_get_interface(intf); if (ret) {
dev_dbg(hub_dev, "Can't autoresume: %d\n", ret); goto out_hdev_lock;
}
/* If this is an inactive hub, do nothing */ if (hub->quiescing) goto out_autopm;
if (hub->error) {
dev_dbg(hub_dev, "resetting for error %d\n", hub->error);
ret = usb_reset_device(hdev); if (ret) {
dev_dbg(hub_dev, "error resetting hub: %d\n", ret); goto out_autopm;
}
hub->nerrors = 0;
hub->error = 0;
}
/* deal with port status changes */ for (i = 1; i <= hdev->maxchild; i++) { struct usb_port *port_dev = hub->ports[i - 1];
/* Release up resources for all children before this device */ for (i = 0; i < udev->maxchild; i++) if (hub->ports[i]->child)
hub_hc_release_resources(hub->ports[i]->child);
if (hcd->driver->reset_device)
hcd->driver->reset_device(hcd, udev);
}
if (udev->reset_resume)
hub_hc_release_resources(udev);
mutex_lock(hcd->address0_mutex);
for (i = 0; i < PORT_INIT_TRIES; ++i) { if (hub_port_stop_enumerate(parent_hub, port1, i)) {
ret = -ENODEV; break;
}
/* ep0 maxpacket size may change; let the HCD know about it.
* Other endpoints will be handled by re-enumeration. */
usb_ep0_reinit(udev);
ret = hub_port_init(parent_hub, udev, port1, i, &descriptor); if (ret >= 0 || ret == -ENOTCONN || ret == -ENODEV) break;
}
mutex_unlock(hcd->address0_mutex);
if (ret < 0) goto re_enumerate;
/* Device might have changed firmware (DFU or similar) */ if (descriptors_changed(udev, &descriptor, bos)) {
dev_info(&udev->dev, "device firmware changed\n"); goto re_enumerate;
}
/* Restore the device's previous configuration */ if (!udev->actconfig) goto done;
/* *Somedevicescan'thandlesettingdefaultaltsetting0witha *Set-Interfacerequest.Disablehost-sideendpointsofthose *interfaceshere.Enableandresetthembackafterhosthasset *itsinternalendpointstructuresduringusb_hcd_alloc_bandwith()
*/ for (i = 0; i < udev->actconfig->desc.bNumInterfaces; i++) {
intf = udev->actconfig->interface[i]; if (intf->cur_altsetting->desc.bAlternateSetting == 0)
usb_disable_interface(udev, intf, true);
}
mutex_lock(hcd->bandwidth_mutex);
ret = usb_hcd_alloc_bandwidth(udev, udev->actconfig, NULL, NULL); if (ret < 0) {
dev_warn(&udev->dev, "Busted HC? Not enough HCD resources for " "old configuration.\n");
mutex_unlock(hcd->bandwidth_mutex); goto re_enumerate;
}
ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
USB_REQ_SET_CONFIGURATION, 0,
udev->actconfig->desc.bConfigurationValue, 0,
NULL, 0, USB_CTRL_SET_TIMEOUT); if (ret < 0) {
dev_err(&udev->dev, "can't restore configuration #%d (error=%d)\n",
udev->actconfig->desc.bConfigurationValue, ret);
mutex_unlock(hcd->bandwidth_mutex); goto re_enumerate;
}
mutex_unlock(hcd->bandwidth_mutex);
usb_set_device_state(udev, USB_STATE_CONFIGURED);
/* Put interfaces back into the same altsettings as before. *Don'tbothertosendtheSet-Interfacerequestforinterfaces *thatwerealreadyinaltsetting0;besidesbeingunnecessary, *manydevicescan'thandleit.Insteadjustresetthehost-side *endpointstate.
*/ for (i = 0; i < udev->actconfig->desc.bNumInterfaces; i++) { struct usb_host_config *config = udev->actconfig; struct usb_interface_descriptor *desc;
intf = config->interface[i];
desc = &intf->cur_altsetting->desc; if (desc->bAlternateSetting == 0) {
usb_enable_interface(udev, intf, true);
ret = 0;
} else { /* Let the bandwidth allocation function know that this *devicehasbeenreset,anditwillhavetouse *alternatesetting0asthecurrentalternatesetting.
*/
intf->resetting_device = 1;
ret = usb_set_interface(udev, desc->bInterfaceNumber,
desc->bAlternateSetting);
intf->resetting_device = 0;
} if (ret < 0) {
dev_err(&udev->dev, "failed to restore interface %d " "altsetting %d (error=%d)\n",
desc->bInterfaceNumber,
desc->bAlternateSetting,
ret); goto re_enumerate;
} /* Resetting also frees any allocated streams */ for (j = 0; j < intf->cur_altsetting->desc.bNumEndpoints; j++)
intf->cur_altsetting->endpoint[j].streams = 0;
}
done: /* Now that the alt settings are re-installed, enable LTM and LPM. */
usb_enable_usb2_hardware_lpm(udev);
usb_unlocked_enable_lpm(udev);
usb_enable_ltm(udev);
usb_release_bos_descriptor(udev);
udev->bos = bos; return0;
/* Prevent autosuspend during the reset */
usb_autoresume_device(udev);
if (config) { for (i = 0; i < config->desc.bNumInterfaces; ++i) { struct usb_interface *cintf = config->interface[i]; struct usb_driver *drv; int unbind = 0;
if (cintf->dev.driver) {
drv = to_usb_driver(cintf->dev.driver); if (drv->pre_reset && drv->post_reset)
unbind = (drv->pre_reset)(cintf); elseif (cintf->condition ==
USB_INTERFACE_BOUND)
unbind = 1; if (unbind)
usb_forced_unbind_intf(cintf);
}
}
}
usb_lock_port(port_dev);
ret = usb_reset_and_verify_device(udev);
usb_unlock_port(port_dev);
if (config) { for (i = config->desc.bNumInterfaces - 1; i >= 0; --i) { struct usb_interface *cintf = config->interface[i]; struct usb_driver *drv; int rebind = cintf->needs_binding;
if (!rebind && cintf->dev.driver) {
drv = to_usb_driver(cintf->dev.driver); if (drv->post_reset)
rebind = (drv->post_reset)(cintf); elseif (cintf->condition ==
USB_INTERFACE_BOUND)
rebind = 1; if (rebind)
cintf->needs_binding = 1;
}
}
/* If the reset failed, hub_wq will unbind drivers later */ if (ret == 0)
usb_unbind_and_rebind_marked_interfaces(udev);
}
if (!(port_removable & mask)) {
dev_dbg(&port_dev->dev, "DeviceRemovable is changed to 1 according to platform information.\n");
port_removable |= mask;
}
}
}
¤ Diese beiden folgenden Angebotsgruppen bietet das Unternehmen0.510Angebot
(Wie Sie bei der Firma Beratungs- und Dienstleistungen beauftragen können 2026-09-28)
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.