usb: dwc3: Fix race between dwc3_set_mode and __dwc3_set_mode
authorSven Peter <sven@svenpeter.dev>
Mon, 28 Nov 2022 16:15:26 +0000 (17:15 +0100)
committerGreg Kroah-Hartman <gregkh@linuxfoundation.org>
Sat, 31 Dec 2022 12:33:09 +0000 (13:33 +0100)
commitd2837c6a1dbc4f7e3bb27ce9f42118dc55c2d5cd
treedee465b0cbc8af2fc5c7014db3ff0ac221f44c4d
parent1ba53c9c79951d221f3e29af008ce3d8f98f13b4
usb: dwc3: Fix race between dwc3_set_mode and __dwc3_set_mode

commit 62c73bfea048e66168df09da6d3e4510ecda40bb upstream.

dwc->desired_dr_role is changed by dwc3_set_mode inside a spinlock but
then read by __dwc3_set_mode outside of that lock. This can lead to a
race condition when very quick successive role switch events happen:

CPU A
dwc3_set_mode(DWC3_GCTL_PRTCAP_HOST) // first role switch event
spin_lock_irqsave(&dwc->lock, flags);
dwc->desired_dr_role = mode; // DWC3_GCTL_PRTCAP_HOST
spin_unlock_irqrestore(&dwc->lock, flags);
queue_work(system_freezable_wq, &dwc->drd_work);

CPU B
__dwc3_set_mode
// ....
spin_lock_irqsave(&dwc->lock, flags);
// desired_dr_role is DWC3_GCTL_PRTCAP_HOST
dwc3_set_prtcap(dwc, dwc->desired_dr_role);
spin_unlock_irqrestore(&dwc->lock, flags);

CPU A
dwc3_set_mode(DWC3_GCTL_PRTCAP_DEVICE) // second event
spin_lock_irqsave(&dwc->lock, flags);
dwc->desired_dr_role = mode; // DWC3_GCTL_PRTCAP_DEVICE
spin_unlock_irqrestore(&dwc->lock, flags);

CPU B (continues running __dwc3_set_mode)
switch (dwc->desired_dr_role) { // DWC3_GCTL_PRTCAP_DEVICE
// ....
case DWC3_GCTL_PRTCAP_DEVICE:
// ....
ret = dwc3_gadget_init(dwc);

We then have DWC3_GCTL.DWC3_GCTL_PRTCAPDIR = DWC3_GCTL_PRTCAP_HOST and
dwc->current_dr_role = DWC3_GCTL_PRTCAP_HOST but initialized the
controller in device mode. It's also possible to get into a state
where both host and device are intialized at the same time.
Fix this race by creating a local copy of desired_dr_role inside
__dwc3_set_mode while holding dwc->lock.

Fixes: 41ce1456e1db ("usb: dwc3: core: make dwc3_set_mode() work properly")
Cc: stable <stable@kernel.org>
Acked-by: Thinh Nguyen <Thinh.Nguyen@synopsys.com>
Signed-off-by: Sven Peter <sven@svenpeter.dev>
Link: https://lore.kernel.org/r/20221128161526.79730-1-sven@svenpeter.dev
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
drivers/usb/dwc3/core.c