mirror of https://lore.kernel.org/lkml/
 help / color / mirror / Atom feed
From: Igor Skalkin <igor.skalkin@oss.qualcomm.com>
To: "Michael S . Tsirkin" <mst@redhat.com>,
	Jason Wang <jasowangio@gmail.com>,
	Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Cc: virtualization@lists.linux.dev, linux-usb@vger.kernel.org,
	linux-kernel@vger.kernel.org, Eugenio Perez <eperezma@redhat.com>,
	Xuan Zhuo <xuanzhuo@linux.alibaba.com>,
	Vasilii Ianikeev <vasilii.ianikeev@oss.qualcomm.com>,
	Aiswarya Cyriac <aiswarya.cyriac@oss.qualcomm.com>,
	Anton Yakovlev <anton.yakovlev@oss.qualcomm.com>,
	Trilok Soni <trilok.soni@oss.qualcomm.com>,
	Matias Ezequiel Vara Larsen <mvaralar@redhat.com>,
	Igor Skalkin <igor.skalkin@oss.qualcomm.com>
Subject: [RFC PATCH v2 6/7] virtio-usb: add host/device role switch support
Date: Tue,  1 Dec 2026 18:35:35 +0100	[thread overview]
Message-ID: <c139d48a347eaa45c4b6cadb1a71ec0e4c77463b.1796144390.git.igor.skalkin@oss.qualcomm.com> (raw)
In-Reply-To: <cover.1796144390.git.igor.skalkin@oss.qualcomm.com>

Add support for ports that can switch between the host and device
roles at runtime. This is a device-driven role switch, not USB
On-The-Go: there is no HNP/SRP, ID pin or OTG descriptor involved.

Negotiate VIRTIO_USB_F_SWITCH_ROLE during probe (only valid together
with both host and device roles), extend virtio_usb_rsw_get_role() to
also report each port's supported roles (is_dual_role), and register a
USB Role Switch class device per dual-role port so userspace can
observe and control the port's role.

A role write is sent to the device as VIRTIO_USB_CMD_ROLE_SET
carrying the target role. The command is idempotent: the device
completes the whole transition before it replies, and replies OK
without doing anything if the port is already in the requested role.
So the switch is done synchronously in the role switch set callback:
send ROLE_SET, even if the cached role already matches, then read the
role back with ROLE_GET and follow it. A ROLE_SET error is returned
to the caller. The role is read back in that case too: after a
timeout or a signal the device may still have switched, and the
guest must follow the role the device reports.

The device also sends VIRTIO_USB_EVT_ROLE_CHANGE, both when the role
was switched on the host side and as an echo of a guest request. The
event goes through the same ROLE_GET resync, which does nothing if the
role did not change. A per-port mutex held over the whole transition
serializes guest requests and events. Events for an invalid port or
for a port without a role switch are ignored.

A port's HCD and root hub only exist while the port is in host role,
so they are created or torn down when the resync finds a new role.
A per-port vhc_lock protects the vhc pointer against the host event
worker, which may run concurrently with the role switch.

Whether a port is dual-role is decided at probe time, where the role
switch is registered based on it, and is not changed by a later
ROLE_GET. vport->rsw is set before the role switch is registered, as
the set callback may run as soon as it is. On remove, the role
switches are unregistered and the role event work is cancelled first,
so a switch in progress cannot create or destroy an HCD after the
queues are stopped or the host VPs are torn down.

Role commands now go through the common, timeout-protected
virtio_usb_cmd_send_sync() path instead of the role code's own
completion wait, so a stalled device can no longer block the event
worker forever. A started flag keeps queue notify callbacks from
scheduling work before probe has finished or after remove has begun,
and the device event queue is now populated before
virtio_device_ready().

The event queues are populated, and the device notified, before
started is set. The device may deliver a pending event right away -
e.g. PORT_CONNECTED for a device already plugged at boot - and its
notification is dropped while started is false. With EVENT_IDX the
device is not asked to notify again until the used ring is consumed,
so later events would go unnoticed as well. Probe therefore runs the
host, device and role event workers once after setting started.

Signed-off-by: Igor Skalkin <igor.skalkin@oss.qualcomm.com>
---
 drivers/usb/virtio_usb/Kconfig       |   4 +-
 drivers/usb/virtio_usb/controller.c  | 118 +++++--
 drivers/usb/virtio_usb/controller.h  |  31 +-
 drivers/usb/virtio_usb/device.c      |   8 +
 drivers/usb/virtio_usb/host.c        | 104 +++++-
 drivers/usb/virtio_usb/role_switch.c | 502 ++++++++++++++++++++++-----
 drivers/usb/virtio_usb/role_switch.h |  19 +-
 7 files changed, 660 insertions(+), 126 deletions(-)

diff --git a/drivers/usb/virtio_usb/Kconfig b/drivers/usb/virtio_usb/Kconfig
index 0cc5df26151c..c89b88da8c34 100644
--- a/drivers/usb/virtio_usb/Kconfig
+++ b/drivers/usb/virtio_usb/Kconfig
@@ -3,11 +3,13 @@
 config USB_VIRTIO
 	tristate "Virtio USB controller support"
 	depends on VIRTIO && USB && USB_GADGET
+	select USB_ROLE_SWITCH
 	help
 	  This driver supports the virtio USB device, a paravirtualized
 	  dual-role USB controller. Each port of the device acts either
 	  as a USB host controller port or as a USB device controller
-	  (UDC).
+	  (UDC), and a dual-role port can be switched between the two
+	  roles at runtime through the USB role switch class.
 
 	  To compile this driver as a module, choose M here: the module
 	  will be called virtio-usb.
diff --git a/drivers/usb/virtio_usb/controller.c b/drivers/usb/virtio_usb/controller.c
index 9f875a127f67..b0ce6b70c0b1 100644
--- a/drivers/usb/virtio_usb/controller.c
+++ b/drivers/usb/virtio_usb/controller.c
@@ -9,8 +9,8 @@
 #include <linux/virtio_ids.h>
 
 #include "controller.h"
-#include "host.h"
 #include "device.h"
+#include "host.h"
 #include "role_switch.h"
 #include "vq_common.h"
 
@@ -81,6 +81,14 @@ static int virtio_usb_validate(struct virtio_device *vdev)
 		return -EINVAL;
 	}
 
+	if ((!(virtio_has_feature(vdev, VIRTIO_USB_F_HOST)) ||
+	     !(virtio_has_feature(vdev, VIRTIO_USB_F_DEVICE))) &&
+	    virtio_has_feature(vdev, VIRTIO_USB_F_SWITCH_ROLE)) {
+		dev_err(&vdev->dev,
+			"role switching requires both (host and device) roles support\n");
+		return -EINVAL;
+	}
+
 	return 0;
 }
 
@@ -119,6 +127,12 @@ static int virtio_usb_probe(struct virtio_device *vdev)
 	if (virtio_has_feature(vdev, VIRTIO_USB_F_DEVICE))
 		vusb->device_role = 1;
 
+	if (virtio_has_feature(vdev, VIRTIO_USB_F_SWITCH_ROLE))
+		vusb->switch_role = 1;
+
+	dev_info(&vdev->dev, "%s nports %d (h_role %d dev_role %d)\n", __func__,
+		 vusb->nports, vusb->host_role, vusb->device_role);
+
 	/* Only allocate/negotiate the virtqueue triplets this instance
 	 * actually needs: HOST_* only exists when host_role is negotiated,
 	 * DEV_* only when device_role is negotiated, ROLE_* only when both
@@ -210,20 +224,45 @@ static int virtio_usb_probe(struct virtio_device *vdev)
 		}
 	}
 
+	if (vusb->device_role) {
+		INIT_WORK(&vusb->vq_dev_event_work, virtio_usb_dc_event_work);
+		INIT_WORK(&vusb->vq_dev_data_rx_work, virtio_usb_dc_data_work);
+
+		/* Populate the shared device event queue before telling the
+		 * backend we are ready, so a DEV_CONNECTED event can never
+		 * race ahead of the driver having posted receive buffers.
+		 */
+		rc = virtio_usb_dc_event_populate(vusb);
+		if (rc) {
+			dev_err(&vdev->dev,
+				"%s virtio_usb_dc_event_populate() error(%d)\n",
+				__func__, rc);
+			goto on_error;
+		}
+	}
+
+	virtio_device_ready(vdev);
+
 	/* Resolve every port's role. With only one role negotiated, every
 	 * port unambiguously has that role. With both negotiated, query
-	 * each port's actual role individually via virtio_usb_rsw_get_role(), since
-	 * it is otherwise ambiguous (host|device).
+	 * each port's actual role - and, if switch_role is negotiated,
+	 * whether the port supports switching - individually via
+	 * virtio_usb_rsw_get_role(), since a port's own role is otherwise ambiguous
+	 * (host|device).
 	 */
 	for (i = 0; i < vusb->nports; i++) {
+		vusb->vports[i].vusb = vusb;
+		spin_lock_init(&vusb->vports[i].vhc_lock);
+
 		if (vusb->host_role && !vusb->device_role) {
 			vusb->vports[i].role = VIRTIO_USB_ROLE_HOST;
 		} else if (vusb->device_role && !vusb->host_role) {
 			vusb->vports[i].role = VIRTIO_USB_ROLE_DEVICE;
 		} else {
-			u32 status, role;
+			u32 status, role, supported_role;
 
-			status = virtio_usb_rsw_get_role(vusb, i, &role);
+			status = virtio_usb_rsw_get_role(vusb, i, &role,
+							 &supported_role);
 			if (status != VIRTIO_USB_S_OK) {
 				dev_err(&vdev->dev, "%s status(%d)\n", __func__,
 					status);
@@ -238,9 +277,27 @@ static int virtio_usb_probe(struct virtio_device *vdev)
 				goto on_error;
 			}
 			vusb->vports[i].role = role;
+			vusb->vports[i].is_dual_role =
+				supported_role &
+				(1UL << VIRTIO_USB_F_SWITCH_ROLE);
+
+			if (vusb->vports[i].is_dual_role &&
+			    !vusb->switch_role) {
+				dev_err(&vdev->dev,
+					"%s port%d switch_role not supported\n",
+					__func__, i);
+				rc = -EIO;
+				goto on_error;
+			}
 		}
 	}
 
+	for (i = 0; i < vusb->nports; i++)
+		dev_info(&vdev->dev,
+			 "%s port[%d] VIRTIO_USB_F_%s is_dual_role %s\n",
+			 __func__, i, vusb->vports[i].role ? "DEVICE" : "HOST",
+			 vusb->vports[i].is_dual_role ? "TRUE" : "FALSE");
+
 	if (vusb->host_role) {
 		INIT_WORK(&vusb->vq_host_data_rx_work, virtio_usb_hc_rx_work);
 		INIT_WORK(&vusb->vq_host_evt_work, virtio_usb_hc_evt_work);
@@ -269,13 +326,9 @@ static int virtio_usb_probe(struct virtio_device *vdev)
 		}
 	}
 
-	if (vusb->device_role) {
-		INIT_WORK(&vusb->vq_dev_data_rx_work, virtio_usb_dc_data_work);
-		INIT_WORK(&vusb->vq_dev_event_work, virtio_usb_dc_event_work);
-
-		for (i = 0; i < vusb->nports; i++) {
-			if (vusb->vports[i].role != VIRTIO_USB_ROLE_DEVICE)
-				continue;
+	for (i = 0; i < vusb->nports; i++) {
+		if (vusb->vports[i].is_dual_role ||
+		    vusb->vports[i].role == VIRTIO_USB_ROLE_DEVICE) {
 			rc = virtio_usb_dc_init(vusb, i);
 			if (rc) {
 				dev_err(&vdev->dev,
@@ -284,17 +337,27 @@ static int virtio_usb_probe(struct virtio_device *vdev)
 				goto on_error;
 			}
 		}
-		rc = virtio_usb_dc_event_populate(vusb);
-		if (rc) {
-			dev_err(&vdev->dev,
-				"%s virtio_usb_dc_event_populate() error(%d)\n",
-				__func__, rc);
-			goto on_error;
-		}
 	}
 
-	virtio_device_ready(vdev);
+	if (vusb->host_role && vusb->device_role)
+		if (virtio_usb_rsw_sysfs_init(vusb))
+			goto on_error;
 
+	WRITE_ONCE(vusb->started, true);
+	/* The event queues are populated, and the device notified, before
+	 * started is set. An event the device delivers in that window has
+	 * its notification dropped by the notify callback, and with
+	 * EVENT_IDX no further notification follows until the used ring is
+	 * drained. Run the event workers once so it is not lost.
+	 */
+	if (vusb->host_role)
+		schedule_work(&vusb->vq_host_evt_work);
+	if (vusb->device_role)
+		schedule_work(&vusb->vq_dev_event_work);
+	if (vusb->rsw)
+		schedule_work(&vusb->rsw->event_process_work);
+
+	dev_info(&vdev->dev, "%s returns %d\n", __func__, rc);
 	return rc;
 
 on_error:
@@ -314,6 +377,20 @@ static void virtio_usb_remove(struct virtio_device *vdev)
 	struct virtio_usb *vusb = vdev->priv;
 	int i;
 
+	/* Stop queue-driven workers from scheduling new activity. */
+	WRITE_ONCE(vusb->started, false);
+
+	/* Before the queues stop and the host VPs go away: a role switch
+	 * in progress, from sysfs or from a ROLE_CHANGE event, may still
+	 * create or destroy an HCD. started is already false, so the
+	 * event work cannot be scheduled again; the role command queue is
+	 * still running, so a role command it waits for completes or
+	 * times out.
+	 */
+	virtio_usb_rsw_sysfs_deinit(vusb);
+	if (vusb->rsw)
+		cancel_work_sync(&vusb->rsw->event_process_work);
+
 	for (i = 0; i < vusb->nvqs; i++)
 		vusb->vqueues[i].stop(vusb, &vusb->vqueues[i]);
 
@@ -335,6 +412,7 @@ static void virtio_usb_remove(struct virtio_device *vdev)
 static const unsigned int virtio_usb_features[] = {
 	VIRTIO_USB_F_HOST,
 	VIRTIO_USB_F_DEVICE,
+	VIRTIO_USB_F_SWITCH_ROLE,
 };
 
 static const struct virtio_device_id id_table[] = {
diff --git a/drivers/usb/virtio_usb/controller.h b/drivers/usb/virtio_usb/controller.h
index 6f39e4c5a4aa..d58cc09ee8fc 100644
--- a/drivers/usb/virtio_usb/controller.h
+++ b/drivers/usb/virtio_usb/controller.h
@@ -19,8 +19,9 @@
 struct virtio_usb_hc_vp;
 /* Forward declaration - full definition in device.h */
 struct virtio_usb_dc;
-/* Forward declaration - full definition in role_switch.h */
+/* Forward declaration - full definitions in role_switch.h */
 struct virtio_usb_rsw;
+struct virtio_usb_port_rsw;
 
 #define VIRTIO_USB_VQ_COMMAND_IDX 0
 #define VIRTIO_USB_VQ_EVENT_IDX 1
@@ -32,14 +33,35 @@ struct virtio_usb_rsw;
 
 /**
  * struct virtio_usb_port - Per-virtual-port state.
+ * @vusb: VirtIO usb device this port belongs to.
+ * @is_dual_role: True if this port supports dynamic role switching.
  * @role: Role of this port (VIRTIO_USB_ROLE_HOST or _DEVICE).
+ * @vhc_lock: Protects @vhc against concurrent role-switch init/deinit
+ *            while the host event-processing worker is reading it, and
+ *            protects @pending_evt and @pending_evt_mask. Only guards the
+ *            pointer itself: the sleeping work of virtio_usb_hc_vp_init()
+ *            and virtio_usb_hc_vp_deinit() (devm_kzalloc(), usb_add_hcd(),
+ *            usb_remove_hcd()) happens outside this lock.
  * @vhc: Host controller - non-NULL when role is HOST.
+ * @pending_evt: Latest host port event per leaf port that arrived while
+ *               @vhc was NULL. On a switch to host role the device may
+ *               report the port as connected before the role switch path
+ *               has installed @vhc; virtio_usb_hc_vp_init() replays these
+ *               when it does.
+ * @pending_evt_mask: Bitmask of the valid @pending_evt slots.
  * @vudc: Device controller - non-NULL when role is DEVICE.
+ * @rsw: Per-port role-switch state - non-NULL when is_dual_role.
  */
 struct virtio_usb_port {
+	struct virtio_usb *vusb;
+	bool is_dual_role;
 	unsigned int role;
+	spinlock_t vhc_lock;
 	struct virtio_usb_hc_vp *vhc;
+	struct virtio_usb_host_port_event pending_evt[VIRTIO_USB_VP_MAX_PORTS];
+	unsigned long pending_evt_mask;
 	struct virtio_usb_dc *vudc;
+	struct virtio_usb_port_rsw *rsw;
 };
 
 /**
@@ -64,6 +86,9 @@ struct virtio_usb_port {
  *               virtio_usb_rsw_get_role(), since with both host_role and
  *               device_role negotiated a port's own role is otherwise
  *               ambiguous.
+ * @switch_role: flag indicating support for dynamically switching roles
+ * @started: True once probe() has finished bringing up every VP - guards
+ *           notify callbacks against running before setup is complete.
  * @vq_host_data_rx_work: Kernel work draining the host data queue, shared
  *                        across every host-role VP.
  * @vq_host_evt_work: Kernel work draining the host event queue, shared
@@ -79,13 +104,15 @@ struct virtio_usb {
 	struct virtio_device *vdev;
 	struct virtio_usb_queue *vqueues;
 	struct virtio_usb_port *vports;
-	unsigned int nports;
+	u32 nports;
 	u32 nvqs;
 	bool host_role;
 	bool device_role;
 	int host_vq_base;
 	int dev_vq_base;
 	int role_vq_base;
+	bool switch_role;
+	bool started;
 	struct work_struct vq_host_data_rx_work;
 	struct work_struct vq_host_evt_work;
 	struct work_struct vq_dev_data_rx_work;
diff --git a/drivers/usb/virtio_usb/device.c b/drivers/usb/virtio_usb/device.c
index af82a0e7e27e..0d44cb1dce6e 100644
--- a/drivers/usb/virtio_usb/device.c
+++ b/drivers/usb/virtio_usb/device.c
@@ -1644,6 +1644,8 @@ static void virtio_usb_dc_event_process(struct virtio_usb_event *event)
 		break;
 	}
 	case VIRTIO_USB_EVT_DEV_DISCONNECTED: {
+		pr_info("%s port_id %d VIRTIO_USB_EVT_DEV_DISCONNECTED\n",
+			__func__, port_id);
 		if (vudc->driver && vudc->driver->disconnect)
 			vudc->driver->disconnect(&vudc->gadget);
 		if (vudc->registered)
@@ -1676,16 +1678,19 @@ static void virtio_usb_dc_event_process(struct virtio_usb_event *event)
 		break;
 	}
 	case VIRTIO_USB_EVT_DEV_RESET: {
+		pr_info("%s VIRTIO_USB_EVT_DEV_RESET\n", __func__);
 		if (driver)
 			usb_gadget_udc_reset(&vudc->gadget, driver);
 		break;
 	}
 	case VIRTIO_USB_EVT_DEV_SUSPEND: {
+		pr_info("%s VIRTIO_USB_EVT_DEV_SUSPEND\n", __func__);
 		if (driver && driver->suspend)
 			driver->suspend(&vudc->gadget);
 		break;
 	}
 	case VIRTIO_USB_EVT_DEV_RESUME: {
+		pr_info("%s VIRTIO_USB_EVT_DEV_RESUME\n", __func__);
 		if (driver && driver->resume)
 			driver->resume(&vudc->gadget);
 		break;
@@ -1968,6 +1973,9 @@ static void virtio_usb_dc_evt_notify_cb(struct virtqueue *vqueue)
 {
 	struct virtio_usb *vusb = vqueue->vdev->priv;
 
+	if (!READ_ONCE(vusb->started))
+		return;
+
 	schedule_work(&vusb->vq_dev_event_work);
 }
 
diff --git a/drivers/usb/virtio_usb/host.c b/drivers/usb/virtio_usb/host.c
index b072c32ac0ee..27b45774b105 100644
--- a/drivers/usb/virtio_usb/host.c
+++ b/drivers/usb/virtio_usb/host.c
@@ -1116,6 +1116,10 @@ void virtio_usb_hc_rx_work(struct work_struct *work)
 	spin_unlock_irq(&dataq->lock);
 }
 
+static void
+virtio_usb_hc_port_event_apply(struct virtio_usb_hc_vp *vhcd_vp,
+			       const struct virtio_usb_host_port_event *evt);
+
 /**
  * virtio_usb_hc_vp_init() - Initialize the host controller for one VP.
  * @vusb:    VirtIO USB device
@@ -1126,6 +1130,7 @@ void virtio_usb_hc_rx_work(struct work_struct *work)
  */
 int virtio_usb_hc_vp_init(struct virtio_usb *vusb, unsigned int vp_idx)
 {
+	struct virtio_usb_port *vport = &vusb->vports[vp_idx];
 	struct virtio_usb_hc_vp *vhcd_vp;
 	unsigned int i;
 	int rc;
@@ -1151,13 +1156,26 @@ int virtio_usb_hc_vp_init(struct virtio_usb *vusb, unsigned int vp_idx)
 	for (i = 0; i < VIRTIO_USB_VQ_HOST_MAX; i++)
 		vhcd_vp->hcqs[i] = &vusb->vqueues[vusb->host_vq_base + i];
 
-	/* Install into the port before add_hcd so vhcd_vp->vusb is set */
-	vusb->vports[vp_idx].vhc = vhcd_vp;
+	/* Install into the port before add_hcd so vhcd_vp->vusb is set.
+	 * Replay any port event that arrived before this, under the same
+	 * lock, so that it is applied before any event that sees vhc.
+	 * hs/ss do not exist yet, so the replay only sets port status;
+	 * the hub driver reads it when usb_add_hcd() registers the root
+	 * hub.
+	 */
+	spin_lock(&vport->vhc_lock);
+	vport->vhc = vhcd_vp;
+	for_each_set_bit(i, &vport->pending_evt_mask, VIRTIO_USB_VP_MAX_PORTS)
+		virtio_usb_hc_port_event_apply(vhcd_vp, &vport->pending_evt[i]);
+	vport->pending_evt_mask = 0;
+	spin_unlock(&vport->vhc_lock);
 
 	/* Add HCDs first so hs/ss are valid before any PORT_CONNECTED event */
 	rc = virtio_usb_add_hcd(vusb, vhcd_vp);
 	if (rc) {
+		spin_lock(&vusb->vports[vp_idx].vhc_lock);
 		vusb->vports[vp_idx].vhc = NULL;
+		spin_unlock(&vusb->vports[vp_idx].vhc_lock);
 		return rc;
 	}
 
@@ -1173,7 +1191,11 @@ int virtio_usb_hc_vp_init(struct virtio_usb *vusb, unsigned int vp_idx)
  */
 int virtio_usb_hc_vp_deinit(struct virtio_usb *vusb, unsigned int vp_idx)
 {
-	struct virtio_usb_hc_vp *vhcd_vp = vusb->vports[vp_idx].vhc;
+	struct virtio_usb_hc_vp *vhcd_vp;
+
+	spin_lock(&vusb->vports[vp_idx].vhc_lock);
+	vhcd_vp = vusb->vports[vp_idx].vhc;
+	spin_unlock(&vusb->vports[vp_idx].vhc_lock);
 
 	if (!vhcd_vp)
 		return 0;
@@ -1186,7 +1208,9 @@ int virtio_usb_hc_vp_deinit(struct virtio_usb *vusb, unsigned int vp_idx)
 	vhcd_vp->ss = NULL;
 	vhcd_vp->hs = NULL;
 
+	spin_lock(&vusb->vports[vp_idx].vhc_lock);
 	vusb->vports[vp_idx].vhc = NULL;
+	spin_unlock(&vusb->vports[vp_idx].vhc_lock);
 	return 0;
 }
 
@@ -1202,9 +1226,6 @@ static void virtio_usb_hc_evt_process_one(struct virtio_usb_event *uevent)
 	struct virtio_usb_host_port_event *evt;
 	unsigned int vp_idx, port_id;
 	struct virtio_usb_hc_vp *vhcd_vp;
-	struct virtio_usb_hc_port *port;
-	struct usb_hcd *hcd = NULL;
-	unsigned long iflags;
 
 	evt = (struct virtio_usb_host_port_event *)virtio_usb_event_buf(uevent);
 	vp_idx = le32_to_cpu(evt->vp_idx);
@@ -1226,16 +1247,55 @@ static void virtio_usb_hc_evt_process_one(struct virtio_usb_event *uevent)
 		return;
 	}
 
+	/* vhc can be concurrently init/deinit'd by a role switch
+	 * (virtio_usb_rsw_event_process() runs on its own workqueue) -
+	 * vhc_lock protects only the pointer read itself; the vhcd_vp it
+	 * points to remains valid for as long as we hold a reference to
+	 * it here, since virtio_usb_hc_vp_deinit() only clears the
+	 * vports[vp_idx].vhc pointer under the same lock, it does not
+	 * free vhcd_vp itself (devm-managed, freed at device teardown).
+	 */
+	spin_lock(&vusb->vports[vp_idx].vhc_lock);
 	vhcd_vp = vusb->vports[vp_idx].vhc;
 	if (!vhcd_vp) {
-		dev_err_ratelimited(
-			&vusb->vdev->dev,
-			"virtio_usb: PORT event vp_idx %u not host-role, ignoring\n",
-			vp_idx);
+		/* No HCD (yet): on a switch to host role the device can
+		 * report the port before the role switch path has created
+		 * it. Keep the latest event per port for
+		 * virtio_usb_hc_vp_init() to replay.
+		 */
+		vusb->vports[vp_idx].pending_evt[port_id] = *evt;
+		__set_bit(port_id, &vusb->vports[vp_idx].pending_evt_mask);
+		spin_unlock(&vusb->vports[vp_idx].vhc_lock);
+		dev_dbg(&vusb->vdev->dev,
+			"PORT event vp_idx %u port %u before HCD, deferred\n",
+			vp_idx, port_id);
 		return;
 	}
+	spin_unlock(&vusb->vports[vp_idx].vhc_lock);
 
-	port = &vhcd_vp->ports[port_id];
+	virtio_usb_hc_port_event_apply(vhcd_vp, evt);
+}
+
+/**
+ * virtio_usb_hc_port_event_apply() - Update a root hub port from an event.
+ * @vhcd_vp: host controller of the event's VP
+ * @evt: VIRTIO_USB_EVT_HOST_PORT_CONNECTED or _DISCONNECTED, validated
+ *
+ * Polls the root hub only if the HCD for the port's speed exists; when
+ * called from virtio_usb_hc_vp_init() before the HCDs are added, the
+ * hub driver reads the port status when the root hub is registered.
+ *
+ * Context: Any context.
+ */
+static void
+virtio_usb_hc_port_event_apply(struct virtio_usb_hc_vp *vhcd_vp,
+			       const struct virtio_usb_host_port_event *evt)
+{
+	struct virtio_usb_hc_port *port;
+	struct usb_hcd *hcd = NULL;
+	unsigned long iflags;
+
+	port = &vhcd_vp->ports[le32_to_cpu(evt->port)];
 
 	spin_lock_irqsave(&port->lock, iflags);
 	switch (le32_to_cpu(evt->code)) {
@@ -1315,10 +1375,12 @@ static void virtio_usb_hc_evt_process_one(struct virtio_usb_event *uevent)
  * @work: kernel work item embedded in struct virtio_usb.
  *
  * The host event queue is shared across all host-role VPs and its VP
- * may not even exist yet at probe time (e.g. a dual-role instance
- * where every port currently reports device role), so events are
- * drained and processed here, in process context, rather than
- * directly inside the interrupt-context notify callback.
+ * may not even exist yet (or may be concurrently torn down by a
+ * role switch), so events are drained and processed here, in process
+ * context, instead of directly inside the interrupt-context notify
+ * callback - this lets virtio_usb_hc_evt_process_one() safely take
+ * vhc_lock without needing an atomic-context-safe primitive on the
+ * writer side (virtio_usb_hc_vp_init()/_deinit() sleep).
  *
  * Context: Process context.
  */
@@ -1358,7 +1420,11 @@ static void virtio_usb_hc_dataq_stop_cb(struct virtio_usb *vusb,
 	cancel_work_sync(&vusb->vq_host_data_rx_work);
 
 	for (vp_idx = 0; vp_idx < vusb->nports; vp_idx++) {
-		struct virtio_usb_hc_vp *vhcd_vp = vusb->vports[vp_idx].vhc;
+		struct virtio_usb_hc_vp *vhcd_vp;
+
+		spin_lock(&vusb->vports[vp_idx].vhc_lock);
+		vhcd_vp = vusb->vports[vp_idx].vhc;
+		spin_unlock(&vusb->vports[vp_idx].vhc_lock);
 
 		if (!vhcd_vp)
 			continue;
@@ -1429,6 +1495,9 @@ static void virtio_usb_hc_evt_notify_cb(struct virtqueue *vqueue)
 {
 	struct virtio_usb *vusb = vqueue->vdev->priv;
 
+	if (!READ_ONCE(vusb->started))
+		return;
+
 	schedule_work(&vusb->vq_host_evt_work);
 }
 
@@ -1458,6 +1527,9 @@ static void virtio_usb_host_data_notify_cb(struct virtqueue *vqueue)
 {
 	struct virtio_usb *vusb = vqueue->vdev->priv;
 
+	if (!READ_ONCE(vusb->started))
+		return;
+
 	schedule_work(&vusb->vq_host_data_rx_work);
 }
 
diff --git a/drivers/usb/virtio_usb/role_switch.c b/drivers/usb/virtio_usb/role_switch.c
index 50b5d645abf4..84387d20b96c 100644
--- a/drivers/usb/virtio_usb/role_switch.c
+++ b/drivers/usb/virtio_usb/role_switch.c
@@ -7,11 +7,341 @@
 
 #include <linux/mutex.h>
 #include "controller.h"
+#include "host.h"
 #include "role_switch.h"
 #include "vq_common.h"
 
+// for usb_role enum from include/linux/usb/role.h
+static const char * const role_switch_role_names[] = {
+	"USB_ROLE_NONE", "USB_ROLE_HOST", "USB_ROLE_DEVICE"
+};
+
+/**
+ * virtio_usb_rsw_role_set() - Ask the device to put a port into a role.
+ * @vusb: VirtIO USB device.
+ * @port_id: Dual-role port.
+ * @role: Target role, VIRTIO_USB_ROLE_HOST or VIRTIO_USB_ROLE_DEVICE.
+ *
+ * ROLE_SET is idempotent: the device performs the whole transition before it
+ * replies, and replies OK without doing anything if the port is already in
+ * @role.
+ *
+ * Context: Process context.
+ * Return: 0 on success, -errno on failure.
+ */
+static int virtio_usb_rsw_role_set(struct virtio_usb *vusb, u32 port_id,
+				   u32 role)
+{
+	struct virtio_usb_role_set *request;
+	struct virtio_usb_cmd *cmd;
+	int rc;
+
+	cmd = virtio_usb_cmd_alloc(sizeof(*request),
+				   sizeof(struct virtio_usb_cmd_status),
+				   GFP_KERNEL);
+	if (!cmd)
+		return -ENOMEM;
+
+	request = virtio_usb_cmd_request(cmd);
+	request->hdr.code = cpu_to_le32(VIRTIO_USB_CMD_ROLE_SET);
+	request->hdr.port = cpu_to_le32(port_id);
+	request->role = cpu_to_le32(role);
+	cmd->msg.queue = vusb->rsw->oqs[VIRTIO_USB_VQ_COMMAND_IDX];
+
+	rc = virtio_usb_cmd_send_sync(vusb, NULL, NULL, cmd);
+	if (rc)
+		pr_err("%s port %u: virtio_usb_cmd_send_sync() error %d\n",
+		       __func__, port_id, rc);
+
+	return rc;
+}
+
+/**
+ * virtio_usb_rsw_sync_locked() - Bring a port in line with the device's role.
+ * @vusb: VirtIO USB device.
+ * @port_id: Dual-role port.
+ *
+ * Reads the port's role from the device and, if it differs from the cached
+ * one, creates or destroys the port's HCD accordingly. Used both after a
+ * guest ROLE_SET and for a ROLE_CHANGE event; if the role did not change it
+ * does nothing, so handling the same transition twice is harmless.
+ *
+ * Whether the port is dual-role is fixed at probe time and not updated
+ * here: the role switch was registered based on it, and is unregistered
+ * on remove regardless of what the device reports later.
+ *
+ * Context: Process context, vport->rsw->lock held.
+ * Return: 0 on success, -errno on failure.
+ */
+static int virtio_usb_rsw_sync_locked(struct virtio_usb *vusb, u32 port_id)
+{
+	struct virtio_usb_port *vport = &vusb->vports[port_id];
+	u32 status, role, supported_role, old_role = vport->role;
+	int rc;
+
+	lockdep_assert_held(&vport->rsw->lock);
+
+	status = virtio_usb_rsw_get_role(vusb, port_id, &role, &supported_role);
+	if (status != VIRTIO_USB_S_OK) {
+		pr_err("%s port %u: virtio_usb_rsw_get_role status %d\n",
+		       __func__, port_id, status);
+		return -EIO;
+	}
+	if (role != VIRTIO_USB_ROLE_HOST && role != VIRTIO_USB_ROLE_DEVICE)
+		return -EIO;
+
+	/* A port's usb_hcd/root hub is only supposed to exist while that
+	 * port is actually in host role - it's immediately visible to the
+	 * rest of the kernel (lsusb, udev, ...) the moment usb_add_hcd()
+	 * runs, unlike the device-role side's vudc, which stays dormant
+	 * and kernel-invisible until a later BIND event. So, unlike vudc
+	 * (already unconditionally pre-allocated for every dual-role
+	 * port at probe time, regardless of its current role - see
+	 * virtio_usb_probe()), vhc must be created/destroyed dynamically,
+	 * exactly at the moment a port's role actually changes.
+	 */
+	if (role != old_role && role == VIRTIO_USB_ROLE_HOST) {
+		rc = virtio_usb_hc_vp_init(vusb, port_id);
+		if (rc) {
+			pr_err("%s virtio_usb_hc_vp_init() port=%u error(%d)\n",
+			       __func__, port_id, rc);
+			/* Leave vport->role at its old value: reporting a
+			 * host role with no working HCD behind it would be
+			 * worse than not switching at all.
+			 */
+			return rc;
+		}
+	} else if (role != old_role && old_role == VIRTIO_USB_ROLE_HOST) {
+		virtio_usb_hc_vp_deinit(vusb, port_id);
+	}
+
+	WRITE_ONCE(vport->role, role);
+	if (role != old_role)
+		pr_info("%s port %u: the new role (%s) is set\n", __func__,
+			port_id,
+			role == VIRTIO_USB_ROLE_DEVICE ?
+				"VIRTIO_USB_ROLE_DEVICE" :
+				"VIRTIO_USB_ROLE_HOST");
+
+	return 0;
+}
+
+static int vusb_set_role_cb(struct usb_role_switch *sw, enum usb_role role)
+{
+	struct virtio_usb_port *vport = usb_role_switch_get_drvdata(sw);
+	struct virtio_usb_port_rsw *vport_rsw = vport->rsw;
+	int rc, sync_rc;
+	u32 target;
+
+	pr_info("%s set_role to %s\n", __func__, role_switch_role_names[role]);
+
+	switch (role) {
+	case USB_ROLE_HOST:
+		target = VIRTIO_USB_ROLE_HOST;
+		break;
+	case USB_ROLE_DEVICE:
+		target = VIRTIO_USB_ROLE_DEVICE;
+		break;
+	default:
+		/* A virtio-usb port is always either host or device. */
+		return -EINVAL;
+	}
+
+	/* The device completes the transition before it answers ROLE_SET,
+	 * so do the whole switch here, under the port lock: a concurrent
+	 * request or ROLE_CHANGE event waits for it and then sees the new
+	 * role. ROLE_SET is sent even if the cached role already matches,
+	 * so a role change whose event was lost is picked up here too.
+	 *
+	 * Resync even if ROLE_SET failed: on a timeout or a signal the
+	 * device may still have switched (or be about to), and the cached
+	 * role and the HCD must follow what the device actually reports.
+	 * Report the ROLE_SET error to the caller in that case.
+	 */
+	mutex_lock(&vport_rsw->lock);
+	rc = virtio_usb_rsw_role_set(vport_rsw->vusb, vport_rsw->port_id,
+				     target);
+	sync_rc =
+		virtio_usb_rsw_sync_locked(vport_rsw->vusb, vport_rsw->port_id);
+	mutex_unlock(&vport_rsw->lock);
+
+	return rc ? rc : sync_rc;
+}
+
+static enum usb_role vusb_get_role_cb(struct usb_role_switch *sw)
+{
+	struct virtio_usb_port *vport = usb_role_switch_get_drvdata(sw);
+
+	switch (READ_ONCE(vport->role)) {
+	case VIRTIO_USB_ROLE_HOST:
+		return USB_ROLE_HOST;
+	case VIRTIO_USB_ROLE_DEVICE:
+		return USB_ROLE_DEVICE;
+	default:
+		return USB_ROLE_NONE;
+	}
+}
+
+static void virtio_usb_rsw_event_process(struct virtio_usb_event *event)
+{
+	struct virtio_usb *vusb = event->vusb;
+	struct virtio_usb_role_event *evt = virtio_usb_event_buf(event);
+	u32 port_id = le32_to_cpu(evt->port);
+	struct virtio_usb_port *vport;
+	int rc;
+
+	if (le32_to_cpu(evt->code) != VIRTIO_USB_EVT_ROLE_CHANGE) {
+		pr_err("%s wrong event code %d\n", __func__,
+		       le32_to_cpu(evt->code));
+		return;
+	}
+
+	if (!vusb->vports || port_id >= vusb->nports) {
+		pr_err("%s port %u invalid (nports=%u)\n", __func__, port_id,
+		       vusb->nports);
+		return;
+	}
+	vport = &vusb->vports[port_id];
+
+	/* A role switch only exists for ports that support switching (see
+	 * virtio_usb_rsw_sysfs_init()); a ROLE_CHANGE for any other port is
+	 * a backend bug - ignore it rather than dereferencing NULL.
+	 */
+	if (!vport->rsw || !vport->rsw->sw) {
+		pr_err("%s ROLE_CHANGE for non-switchable port %u\n", __func__,
+		       port_id);
+		return;
+	}
+
+	pr_info("%s port %u VIRTIO_USB_EVT_ROLE_CHANGE\n", __func__, port_id);
+
+	/* Either a device-initiated switch, or the echo of a guest ROLE_SET
+	 * that vusb_set_role_cb() has already handled.
+	 */
+	mutex_lock(&vport->rsw->lock);
+	rc = virtio_usb_rsw_sync_locked(vusb, port_id);
+	mutex_unlock(&vport->rsw->lock);
+	if (rc)
+		pr_err("%s port %u: sync error %d\n", __func__, port_id, rc);
+}
+
+/**
+ * virtio_usb_rsw_event_work() - role event queue receive worker.
+ * @work: Kernel work to handle event completion.
+ *
+ * Context: Process context.
+ */
+static void virtio_usb_rsw_event_work(struct work_struct *work)
+{
+	struct virtio_usb_rsw *rsw =
+		container_of(work, struct virtio_usb_rsw, event_process_work);
+	struct virtio_usb_queue *evtq = rsw->oqs[VIRTIO_USB_VQ_EVENT_IDX];
+
+	virtio_usb_evt_work(evtq, virtio_usb_rsw_event_process);
+}
+
+/**
+ * virtio_usb_rsw_event_populate() - Add events to the role event queue.
+ * @vusb: VirtIO USB device.
+ *
+ * Context: Any context.
+ * Return: 0 on success -errno on failure.
+ */
+static int virtio_usb_rsw_event_populate(struct virtio_usb *vusb)
+{
+	struct virtio_usb_queue *evt_queue =
+		vusb->rsw->oqs[VIRTIO_USB_VQ_EVENT_IDX];
+	struct virtio_usb_event *events;
+
+	events = virtio_usb_events_alloc(vusb, evt_queue,
+					 sizeof(struct virtio_usb_role_event));
+	if (!events)
+		return -ENOMEM;
+
+	return virtio_usb_events_populate(events);
+}
+
+/**
+ * virtio_usb_rsw_sysfs_deinit() - Unregister the per-port role switches.
+ * @vusb: VirtIO USB device.
+ *
+ * Must run before the host VPs are torn down: unregistering waits for a
+ * vusb_set_role_cb() in progress, which may create or destroy a port's HCD,
+ * and no new one can start afterwards.
+ *
+ * Context: Process context.
+ */
+void virtio_usb_rsw_sysfs_deinit(struct virtio_usb *vusb)
+{
+	if (!vusb->vports)
+		return;
+
+	for (int i = 0; i < vusb->nports; ++i) {
+		struct virtio_usb_port *vport = &vusb->vports[i];
+
+		/* Only what was actually registered: a probe failure before
+		 * virtio_usb_rsw_sysfs_init() leaves rsw NULL, a failed or
+		 * earlier deinit leaves sw NULL.
+		 */
+		if (!vport->rsw || !vport->rsw->sw)
+			continue;
+
+		usb_role_switch_unregister(vport->rsw->sw);
+		vport->rsw->sw = NULL;
+		kfree(vport->rsw->sysfs_name);
+		vport->rsw->sysfs_name = NULL;
+	}
+}
+
+static int rsw_vport_init(struct virtio_usb *vusb, int port_id)
+{
+	struct device *dev = &vusb->vdev->dev;
+	struct virtio_usb_port *vport = &vusb->vports[port_id];
+	struct virtio_usb_port_rsw *vport_rsw = vport->rsw;
+	struct usb_role_switch_desc desc = { 0 };
+
+	/* Reuse the devm allocation of an earlier probe of this device. */
+	if (!vport_rsw) {
+		vport_rsw = devm_kzalloc(dev, sizeof(*vport_rsw), GFP_KERNEL);
+		if (!vport_rsw)
+			return -ENOMEM;
+		mutex_init(&vport_rsw->lock);
+	}
+
+	vport_rsw->vusb = vusb;
+	vport_rsw->port_id = port_id;
+	vport_rsw->sysfs_name = kasprintf(GFP_KERNEL, "port%u", port_id);
+
+	desc.name = vport_rsw->sysfs_name;
+	desc.set = vusb_set_role_cb;
+	desc.get = vusb_get_role_cb;
+	desc.driver_data = vport;
+	desc.fwnode = NULL;
+	desc.allow_userspace_control = true;
+
+	/* vusb_set_role_cb() can be called as soon as the switch is
+	 * registered, so vport->rsw must already be set.
+	 */
+	vport->rsw = vport_rsw;
+	vport_rsw->sw = usb_role_switch_register(dev, &desc);
+	if (IS_ERR(vport_rsw->sw)) {
+		int rc = PTR_ERR(vport_rsw->sw);
+
+		dev_err(dev, "port%u: usb_role_switch_register() failed: %d\n",
+			port_id, rc);
+		vport_rsw->sw = NULL;
+		kfree(vport_rsw->sysfs_name);
+		vport_rsw->sysfs_name = NULL;
+		vport->rsw = NULL;
+		return rc;
+	}
+
+	return 0;
+}
+
 int virtio_usb_rsw_init(struct virtio_usb *vusb)
 {
+	int rc;
 	struct virtio_usb_rsw *rsw =
 		devm_kzalloc(&vusb->vdev->dev, sizeof(*rsw), GFP_KERNEL);
 	unsigned int i;
@@ -24,9 +354,35 @@ int virtio_usb_rsw_init(struct virtio_usb *vusb)
 	for (i = 0; i < VIRTIO_USB_VQ_ROLE_MAX; i++)
 		rsw->oqs[i] = &vusb->vqueues[vusb->role_vq_base + i];
 
-	mutex_init(&rsw->lock);
-	init_completion(&rsw->completion);
+	INIT_WORK((struct work_struct *)&rsw->event_process_work,
+		  virtio_usb_rsw_event_work);
+
+	rc = virtio_usb_rsw_event_populate(vusb);
+	if (rc)
+		return rc;
+
+	return 0;
+}
 
+int virtio_usb_rsw_sysfs_init(struct virtio_usb *vusb)
+{
+	int i, rc;
+
+	for (i = 0; i < vusb->nports; i++)
+		if (vusb->vports[i].is_dual_role) {
+			/* Skip if still registered - probe may be retried
+			 * after a Virtio reset and the role switch device
+			 * persists across retries. Calling
+			 * usb_role_switch_register() again would return
+			 * -EEXIST from device_register(). If it was
+			 * unregistered, register it again.
+			 */
+			if (vusb->vports[i].rsw && vusb->vports[i].rsw->sw)
+				continue;
+			rc = rsw_vport_init(vusb, i);
+			if (rc)
+				return rc;
+		}
 	return 0;
 }
 
@@ -37,55 +393,72 @@ void virtio_usb_rsw_deinit(struct virtio_usb *vusb)
 	if (!rsw)
 		return;
 
-	/* Wake potential role command waiters before releasing role objects. */
-	complete_all(&rsw->completion);
-
+	/*
+	 * The role switches are already unregistered by
+	 * virtio_usb_rsw_sysfs_deinit(), and event_process_work is already
+	 * cancelled, both earlier in virtio_usb_remove().
+	 */
 	vusb->rsw = NULL;
 }
 
+/**
+ * virtio_usb_rsw_evt_notify_cb() - role event virtqueue notification callback
+ * @vqueue: Underlying event virtqueue.
+ *
+ * This callback function is called upon a vring interrupt request from the
+ * device.
+ *
+ * Context: Interrupt context.
+ */
+static void virtio_usb_rsw_evt_notify_cb(struct virtqueue *vqueue)
+{
+	struct virtio_usb *vusb = vqueue->vdev->priv;
+
+	if (!READ_ONCE(vusb->started) || !vusb->rsw)
+		return;
+
+	schedule_work(&vusb->rsw->event_process_work);
+}
+
 /* Send a role command and get a response.
  *
  * The function is implemented as synchronous. Design pattern is
  * virtio_can.c/virtio_can_send_ctrl_msg()
  */
-u32 virtio_usb_rsw_get_role(struct virtio_usb *vusb, int port_id, u32 *role)
+u32 virtio_usb_rsw_get_role(struct virtio_usb *vusb, int port_id, u32 *role,
+			    u32 *supported_role)
 {
-	struct scatterlist sg_out, sg_in, *sgs[2] = { &sg_out, &sg_in };
-	struct virtqueue *vq =
-		vusb->rsw->oqs[VIRTIO_USB_VQ_COMMAND_IDX]->vqueue;
-	unsigned int len;
+	struct virtio_usb_role_cmd_hdr *hdr;
+	struct virtio_usb_role_info *resp;
+	struct virtio_usb_cmd *cmd;
 	u32 status = VIRTIO_USB_S_ERR_INTERNAL;
+	int rc;
 
-	struct role_get_msg {
-		struct virtio_usb_role_cmd_hdr cmd_hdr;
-		struct virtio_usb_role_info cmd_role;
-	} *msg = kzalloc(sizeof(*msg), GFP_KERNEL);
-
-	if (!msg)
+	cmd = virtio_usb_cmd_alloc(sizeof(*hdr), sizeof(*resp), GFP_KERNEL);
+	if (!cmd)
 		return status;
 
-	msg->cmd_hdr.code = cpu_to_le32(VIRTIO_USB_CMD_ROLE_GET);
-	msg->cmd_hdr.port = cpu_to_le32(port_id);
-	sg_init_one(&sg_out, &msg->cmd_hdr, sizeof(msg->cmd_hdr));
-	sg_init_one(&sg_in, &msg->cmd_role, sizeof(msg->cmd_role));
+	hdr = virtio_usb_cmd_request(cmd);
+	hdr->code = cpu_to_le32(VIRTIO_USB_CMD_ROLE_GET);
+	hdr->port = cpu_to_le32(port_id);
+	cmd->msg.queue = vusb->rsw->oqs[VIRTIO_USB_VQ_COMMAND_IDX];
 
-	mutex_lock(&vusb->rsw->lock);
+	virtio_usb_cmd_ref(cmd);
 
-	if (virtqueue_add_sgs(vq, sgs, 1u, 1u, msg, GFP_ATOMIC)) {
-		pr_err("%s virtqueue_add_sgs error\n", __func__);
-		goto exit;
-	}
+	rc = virtio_usb_cmd_send_sync(vusb, NULL, NULL, cmd);
 
-	if (!virtqueue_kick(vq)) {
-		pr_err("%s virtqueue_kick error\n", __func__);
-		goto exit;
+	if (rc) {
+		pr_err("%s virtio_usb_cmd_send_sync() error %d\n", __func__,
+		       rc);
+		virtio_usb_cmd_unref(cmd);
+		return status;
 	}
 
-	while (!virtqueue_get_buf(vq, &len) && !virtqueue_is_broken(vq))
-		wait_for_completion(&vusb->rsw->completion);
-
-	status = le32_to_cpu(msg->cmd_role.status.code);
-	*role = le32_to_cpu(msg->cmd_role.role);
+	resp = virtio_usb_cmd_response(cmd);
+	status = le32_to_cpu(resp->status.code);
+	*role = le32_to_cpu(resp->role);
+	*supported_role = le32_to_cpu(resp->supported_role);
+	virtio_usb_cmd_unref(cmd);
 
 	if (*role != VIRTIO_USB_ROLE_HOST && *role != VIRTIO_USB_ROLE_DEVICE) {
 		pr_err("%s - wrong role (%d)\n", __func__, *role);
@@ -96,71 +469,32 @@ u32 virtio_usb_rsw_get_role(struct virtio_usb *vusb, int port_id, u32 *role)
 				"VIRTIO_USB_ROLE_DEVICE");
 	}
 
-exit:
-	kfree(msg);
-	mutex_unlock(&vusb->rsw->lock);
 	return status;
 }
 
-static void virtio_usb_rsw_cmd_notify_cb(struct virtqueue *vqueue)
-{
-	struct virtio_usb *vusb = vqueue->vdev->priv;
-
-	if (!vusb->rsw)
-		return;
-
-	complete(&vusb->rsw->completion);
-}
-
-static void virtio_usb_rsw_cmdq_stop_cb(struct virtio_usb *vusb,
-					struct virtio_usb_queue *vq)
-{
-	unsigned long flags;
-
-	if (!vusb->rsw || !vq->vqueue)
-		return;
-
-	/*
-	 * Wake sleepers in role synchronous command paths so they can
-	 * observe started=false and exit.
-	 */
-	complete_all(&vusb->rsw->completion);
-
-	spin_lock_irqsave(&vq->lock, flags);
-	virtqueue_disable_cb(vq->vqueue);
-	spin_unlock_irqrestore(&vq->lock, flags);
-}
-
 static void virtio_usb_rsw_evtq_stop_cb(struct virtio_usb *vusb,
 					struct virtio_usb_queue *vq)
 {
-	unsigned long flags;
-	u32 length;
-	void *buf;
-
-	if (!vq->vqueue)
-		return;
-
-	/* The role event queue is not populated yet at this stage (no
-	 * VIRTIO_USB_F_SWITCH_ROLE negotiation, no ROLE_CHANGE events),
-	 * so this only has to make sure del_vqs() finds the ring empty.
+	/*
+	 * Now that virtio_usb_rsw_get_role()/virtio_usb_rsw_role_set() go
+	 * through the common, timeout-protected virtio_usb_cmd_send_sync()
+	 * instead of blocking indefinitely on virtqueue_is_broken(), it's
+	 * safe to cancel event_process_work directly here, same as every
+	 * other role's own evtq stop callback.
 	 */
-	spin_lock_irqsave(&vq->lock, flags);
-	virtqueue_disable_cb(vq->vqueue);
-	while ((buf = virtqueue_get_buf(vq->vqueue, &length)))
-		;
-	spin_unlock_irqrestore(&vq->lock, flags);
+	virtio_usb_evt_drain_stop_cb(
+		vq, vusb->rsw ? &vusb->rsw->event_process_work : NULL);
 }
 
 const struct virtio_usb_vq_desc role_vqueues[VIRTIO_USB_VQ_ROLE_MAX] = {
 	[VIRTIO_USB_VQ_COMMAND_IDX] = {
-		.callback = virtio_usb_rsw_cmd_notify_cb,
+		.callback = virtio_usb_cmd_notify_cb,
 		.name = "virtusb-role-cmd",
-		.process = NULL,
-		.stop = virtio_usb_rsw_cmdq_stop_cb,
+		.process = virtio_usb_cmd_process_cb,
+		.stop = virtio_usb_cmdq_stop_cb,
 	},
 	[VIRTIO_USB_VQ_EVENT_IDX] = {
-		.callback = NULL,
+		.callback = virtio_usb_rsw_evt_notify_cb,
 		.name = "virtusb-role-evt",
 		.process = NULL,
 		.stop = virtio_usb_rsw_evtq_stop_cb,
diff --git a/drivers/usb/virtio_usb/role_switch.h b/drivers/usb/virtio_usb/role_switch.h
index e3c8031686c3..13b270f315c6 100644
--- a/drivers/usb/virtio_usb/role_switch.h
+++ b/drivers/usb/virtio_usb/role_switch.h
@@ -8,18 +8,31 @@
 #ifndef VIRTIO_USB_ROLE_SWITCH_H
 #define VIRTIO_USB_ROLE_SWITCH_H
 
+#include <linux/usb/role.h>
 #include "controller.h"
 
 int virtio_usb_rsw_init(struct virtio_usb *vusb);
+int virtio_usb_rsw_sysfs_init(struct virtio_usb *vusb);
+void virtio_usb_rsw_sysfs_deinit(struct virtio_usb *vusb);
 void virtio_usb_rsw_deinit(struct virtio_usb *vusb);
 u32 virtio_usb_rsw_get_role(struct virtio_usb *vusb, int port_id,
-			    u32 *role);
+			    u32 *role, u32 *supported_role);
 
-struct virtio_usb_rsw {
+struct virtio_usb_port_rsw {
 	struct virtio_usb *vusb;
+	/* Serializes role transitions of this port (guest ROLE_SET and
+	 * ROLE_CHANGE events); protects the port's role and HCD lifecycle.
+	 */
 	struct mutex lock;
-	struct completion completion;
+	struct usb_role_switch *sw;
+	char *sysfs_name;
+	int port_id;
+};
+
+struct virtio_usb_rsw {
+	struct virtio_usb *vusb;
 	struct virtio_usb_queue *oqs[VIRTIO_USB_VQ_ROLE_MAX];
+	struct work_struct event_process_work;
 };
 
 extern const struct virtio_usb_vq_desc role_vqueues[VIRTIO_USB_VQ_ROLE_MAX];
-- 
2.49.0


  parent reply	other threads:[~2026-12-01 17:36 UTC|newest]

Thread overview: 10+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
     [not found] <20260924160907.145405-1-igor.skalkin@oss.qualcomm.com>
2026-12-01 17:35 ` [RFC PATCH v2 0/7] virtio-usb: add dual-role virtio USB driver Igor Skalkin
2026-12-01 17:35   ` [RFC PATCH v2 1/7] uapi: virtio_ids: reserve ID for virtio USB device Igor Skalkin
2026-12-01 17:35   ` [RFC PATCH v2 2/7] virtio-usb: add protocol header and skeleton dual-role driver Igor Skalkin
2026-12-01 17:35   ` [RFC PATCH v2 3/7] virtio-usb: add host role (USB Host Controller) support Igor Skalkin
2026-12-01 17:35   ` [RFC PATCH v2 4/7] virtio-usb: add device role (USB Device " Igor Skalkin
2026-12-01 17:35   ` [RFC PATCH v2 5/7] virtio-usb: add per-port role query support Igor Skalkin
2026-12-01 17:35   ` Igor Skalkin [this message]
2026-12-01 17:35   ` [RFC PATCH v2 7/7] virtio-usb: support a guest UDC name prefix from the bind event Igor Skalkin
2026-12-01 17:49   ` [RFC PATCH v2 0/7] virtio-usb: add dual-role virtio USB driver Michael S. Tsirkin
2026-12-01 20:09   ` Greg Kroah-Hartman

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=c139d48a347eaa45c4b6cadb1a71ec0e4c77463b.1796144390.git.igor.skalkin@oss.qualcomm.com \
    --to=igor.skalkin@oss.qualcomm.com \
    --cc=aiswarya.cyriac@oss.qualcomm.com \
    --cc=anton.yakovlev@oss.qualcomm.com \
    --cc=eperezma@redhat.com \
    --cc=gregkh@linuxfoundation.org \
    --cc=jasowangio@gmail.com \
    --cc=linux-kernel@vger.kernel.org \
    --cc=linux-usb@vger.kernel.org \
    --cc=mst@redhat.com \
    --cc=mvaralar@redhat.com \
    --cc=trilok.soni@oss.qualcomm.com \
    --cc=vasilii.ianikeev@oss.qualcomm.com \
    --cc=virtualization@lists.linux.dev \
    --cc=xuanzhuo@linux.alibaba.com \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox

all inboxes | Powered by JetHome®