* [RFC PATCH v2 0/7] virtio-usb: add dual-role virtio USB driver
[not found] <20260924160907.145405-1-igor.skalkin@oss.qualcomm.com>
@ 2026-12-01 17:35 ` Igor Skalkin
2026-12-01 17:35 ` [RFC PATCH v2 1/7] uapi: virtio_ids: reserve ID for virtio USB device Igor Skalkin
` (7 more replies)
0 siblings, 8 replies; 9+ messages in thread
From: Igor Skalkin @ 2026-12-01 17:35 UTC (permalink / raw)
To: Michael S . Tsirkin, Jason Wang, Greg Kroah-Hartman
Cc: virtualization, linux-usb, linux-kernel, Eugenio Perez, Xuan Zhuo,
Vasilii Ianikeev, Aiswarya Cyriac, Anton Yakovlev, Trilok Soni,
Matias Ezequiel Vara Larsen, Igor Skalkin
This series adds a driver for the virtio USB device: a dual-role
paravirtualized USB controller. Each port of the device is either a
USB host controller port, backed by a per-port HS+SS usb_hcd pair, or
a USB device controller (UDC). Dual-role ports can switch between the
two roles at runtime, and the switch is exposed through the USB role
switch class. This is a device-driven role switch, not USB OTG:
there is no HNP/SRP, ID pin or OTG descriptor involved.
The device is described in the virtio-usb specification proposal,
currently at RFC v3 on virtio-comment:
https://lore.kernel.org/virtio-comment/20260611130826.287372-1-vasilii.ianikeev@oss.qualcomm.com/T/
This series is an RFC because the specification is still under
review. The protocol header in patch 2 follows spec RFC v3.
The driver was tested against two device backends: a proprietary one
and one based on QEMU. The QEMU backend is currently under review and
will be sent upstream soon.
Series layout:
- 1/7 syncs the device ID (49) from the virtio specification into
virtio_ids.h. The driver does not build without it.
- 2/7 adds the protocol header and the driver skeleton.
- 3/7 and 4/7 add the host and the device role.
- 5/7 adds the per-port role query, which is needed when the device
offers both roles.
- 6/7 adds runtime host/device role switching.
- 7/7 lets the device supply a name prefix for a port's UDC.
Changes since v1:
- Marked as RFC, since the specification is still under review.
- Rebased onto v7.4-rc5. The virtio_ids.h patch is now part of the
series (1/7).
- Series restructured: v1 6/8 ("rework endpoint lifecycle to an
async split-phase state machine") and v1 7/8 ("add SuperSpeed
device-role support") are folded into the device role patch
(4/7). The OTG patches are renamed to "per-port role query" (5/7)
and "host/device role switch" (6/7).
- checkpatch, sparse and kernel-doc cleanups throughout.
[2/7] protocol header and skeleton
- uapi enums converted to explicit #defines.
- OTG naming replaced by role naming: VIRTIO_USB_VQ_ROLE_*,
VIRTIO_USB_CMD_ROLE_GET/SET, struct virtio_usb_role_set carrying
the target role, struct virtio_usb_role_info,
VIRTIO_USB_EVT_ROLE_CHANGE.
- Host port event field port_id renamed to port.
- VIRTIO_USB_SPEED_WIRELESS dropped; VIRTIO_USB_USB_SPEED_SUPER
renamed to VIRTIO_USB_SPEED_SUPER.
- uapi header relicensed from BSD-3-Clause to GPL-2.0-or-later
WITH Linux-syscall-note, like the rest of the driver.
[3/7] host role
- The cmd_timeout_ms module parameter is removed; the command
timeout is the constant VIRTIO_USB_CMD_TIMEOUT_MS (1 s).
- Each data submission gets a tag from a per-device 64-bit counter,
and HOST_CANCEL refers to that tag instead of the URB address,
which could match a reused allocation.
- Fixed a race where dequeue ran before the URB was on the data
virtqueue: the HOST_CANCEL matched nothing on the device, so the
URB was never cancelled. Dequeue now only records the cancel, and
enqueue sends it once the URB is queued.
- skip_phy_initialization is now also set on the SuperSpeed HCD.
[4/7] device role
- Folds in v1 6/8: an explicit endpoint state machine, with
workqueues and a pending request queue, so that the
usb_ep_ops/usb_gadget_ops callbacks never sleep. No gadget core
change is needed.
- Folds in v1 7/8: max_speed is taken from the BIND event, EP0
maxpacket is set for SS/SSP, and the SS endpoint companion
descriptor is validated and sent with EP_ENABLE.
- DEV_CANCEL uses a per-submission tag instead of the request
address.
- Fixed the same early-cancel race as on the host side. A stale
cancel is dropped if the request has completed and been queued
again.
- ep_queue() on a halted endpoint returns the error without giving
the request back, which avoids recursion with gadget drivers that
resubmit from their completion handler.
- Events with non-zero reserved padding are rejected.
- UNBIND flushes the endpoint work before freeing the endpoints
(use-after-free fix).
[5/7] per-port role query (was: OTG role query)
- otg.c/otg.h renamed to role_switch.c/role_switch.h, otg_* to
virtio_usb_rsw_*, is_otg to is_dual_role.
- The ROLE_* queues are created only when both roles are
negotiated.
[6/7] host/device role switch (was: OTG role-switching)
- Role switches work in both directions from the guest. The role
switch set callback sends ROLE_SET with the target role, then
reads the role back with ROLE_GET and follows it, even if
ROLE_SET failed. v1 could only request device-to-host,
asynchronously, and carried no target role.
- ROLE_CHANGE events and guest requests share one resync path,
serialized by a per-port mutex.
- Host port events that arrive before the HCD is installed are
stored per port and replayed once it is. v1 dropped them.
- On remove, the role switches are unregistered and the role event
work is cancelled before the queues are stopped.
- Probe runs the event workers once after setting started, so
events delivered during probe are not lost.
[7/7] UDC name prefix
- No functional change.
v1: https://lore.kernel.org/all/20260924160907.145405-1-igor.skalkin@oss.qualcomm.com/
Aiswarya Cyriac (3):
virtio-usb: add protocol header and skeleton dual-role driver
virtio-usb: add host role (USB Host Controller) support
virtio-usb: add device role (USB Device Controller) support
Igor Skalkin (4):
uapi: virtio_ids: reserve ID for virtio USB device
virtio-usb: add per-port role query support
virtio-usb: add host/device role switch support
virtio-usb: support a guest UDC name prefix from the bind event
MAINTAINERS | 10 +
drivers/usb/Kconfig | 2 +
drivers/usb/Makefile | 1 +
drivers/usb/virtio_usb/Kconfig | 15 +
drivers/usb/virtio_usb/Makefile | 9 +
drivers/usb/virtio_usb/controller.c | 437 ++++++
drivers/usb/virtio_usb/controller.h | 185 +++
drivers/usb/virtio_usb/device.c | 2055 ++++++++++++++++++++++++++
drivers/usb/virtio_usb/device.h | 126 ++
drivers/usb/virtio_usb/host.c | 1555 +++++++++++++++++++
drivers/usb/virtio_usb/host.h | 244 +++
drivers/usb/virtio_usb/role_switch.c | 502 +++++++
drivers/usb/virtio_usb/role_switch.h | 40 +
drivers/usb/virtio_usb/vq_common.c | 747 ++++++++++
drivers/usb/virtio_usb/vq_common.h | 163 ++
include/uapi/linux/virtio_ids.h | 1 +
include/uapi/linux/virtio_usb.h | 321 ++++
17 files changed, 6413 insertions(+)
create mode 100644 drivers/usb/virtio_usb/Kconfig
create mode 100644 drivers/usb/virtio_usb/Makefile
create mode 100644 drivers/usb/virtio_usb/controller.c
create mode 100644 drivers/usb/virtio_usb/controller.h
create mode 100644 drivers/usb/virtio_usb/device.c
create mode 100644 drivers/usb/virtio_usb/device.h
create mode 100644 drivers/usb/virtio_usb/host.c
create mode 100644 drivers/usb/virtio_usb/host.h
create mode 100644 drivers/usb/virtio_usb/role_switch.c
create mode 100644 drivers/usb/virtio_usb/role_switch.h
create mode 100644 drivers/usb/virtio_usb/vq_common.c
create mode 100644 drivers/usb/virtio_usb/vq_common.h
create mode 100644 include/uapi/linux/virtio_usb.h
base-commit: fe6ff8d5d675c01793b9f051d16055dd4aa75244
--
2.49.0
^ permalink raw reply [flat|nested] 9+ messages in thread
* [RFC PATCH v2 1/7] uapi: virtio_ids: reserve ID for virtio USB device
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 ` Igor Skalkin
2026-12-01 17:35 ` [RFC PATCH v2 2/7] virtio-usb: add protocol header and skeleton dual-role driver Igor Skalkin
` (6 subsequent siblings)
7 siblings, 0 replies; 9+ messages in thread
From: Igor Skalkin @ 2026-12-01 17:35 UTC (permalink / raw)
To: Michael S . Tsirkin, Jason Wang, Greg Kroah-Hartman
Cc: virtualization, linux-usb, linux-kernel, Eugenio Perez, Xuan Zhuo,
Vasilii Ianikeev, Aiswarya Cyriac, Anton Yakovlev, Trilok Soni,
Matias Ezequiel Vara Larsen, Igor Skalkin
Device ID 49 was reserved for the virtio USB controller device in
the virtio specification [1][2].
Sync this one addition into Linux, matching prior precedent
(commit d5a8680dfab0 ("uapi: virtio_ids: Sync ids with
specification")).
[1] https://github.com/oasis-tcs/virtio-spec/issues/211
[2] https://lore.kernel.org/r/20241129111325.952-1-quic_acyriac@quicinc.com
Signed-off-by: Igor Skalkin <igor.skalkin@oss.qualcomm.com>
---
include/uapi/linux/virtio_ids.h | 1 +
1 file changed, 1 insertion(+)
diff --git a/include/uapi/linux/virtio_ids.h b/include/uapi/linux/virtio_ids.h
index f9056af0c622..a3bc54602679 100644
--- a/include/uapi/linux/virtio_ids.h
+++ b/include/uapi/linux/virtio_ids.h
@@ -70,6 +70,7 @@
#define VIRTIO_ID_GPIO 41 /* virtio gpio */
#define VIRTIO_ID_SPI 45 /* virtio spi */
#define VIRTIO_ID_MEDIA 48 /* virtio media */
+#define VIRTIO_ID_USB 49 /* virtio USB controller */
/*
* Virtio Transitional IDs
--
2.49.0
^ permalink raw reply related [flat|nested] 9+ messages in thread
* [RFC PATCH v2 2/7] virtio-usb: add protocol header and skeleton dual-role driver
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 ` Igor Skalkin
2026-12-01 17:35 ` [RFC PATCH v2 3/7] virtio-usb: add host role (USB Host Controller) support Igor Skalkin
` (5 subsequent siblings)
7 siblings, 0 replies; 9+ messages in thread
From: Igor Skalkin @ 2026-12-01 17:35 UTC (permalink / raw)
To: Michael S . Tsirkin, Jason Wang, Greg Kroah-Hartman
Cc: virtualization, linux-usb, linux-kernel, Eugenio Perez, Xuan Zhuo,
Vasilii Ianikeev, Aiswarya Cyriac, Anton Yakovlev, Trilok Soni,
Matias Ezequiel Vara Larsen, Igor Skalkin
From: Aiswarya Cyriac <aiswarya.cyriac@oss.qualcomm.com>
Add the virtio_usb device and virtqueue-wrapper skeleton, the
protocol header shared with the vhost gadget driver and userspace
backend, and probe()/remove() plumbing with no role support yet.
Introduce a per-port virtio_usb_port array (vports[]), sized to the
device's negotiated port count, ahead of any code that actually
populates or reads it. Every later commit that adds a role to a port
(host or device) or role switching builds on this same array from
the start, instead of the host, device, and role-switch code each
growing their own separate port-indexed storage that later has to
be reconciled.
All wire-protocol constants in the uapi header use explicit #define
values rather than enums, matching virtio_rtc.h's style, since these
values go out over the wire and must not depend on implicit
enum auto-increment (Documentation/process/botching-up-ioctls.rst).
Signed-off-by: Aiswarya Cyriac <aiswarya.cyriac@oss.qualcomm.com>
Co-developed-by: Igor Skalkin <igor.skalkin@oss.qualcomm.com>
Signed-off-by: Igor Skalkin <igor.skalkin@oss.qualcomm.com>
---
MAINTAINERS | 10 +
drivers/usb/Kconfig | 2 +
drivers/usb/Makefile | 1 +
drivers/usb/virtio_usb/Kconfig | 13 ++
drivers/usb/virtio_usb/Makefile | 5 +
drivers/usb/virtio_usb/controller.c | 155 ++++++++++++++++
drivers/usb/virtio_usb/controller.h | 84 +++++++++
include/uapi/linux/virtio_usb.h | 278 ++++++++++++++++++++++++++++
8 files changed, 548 insertions(+)
create mode 100644 drivers/usb/virtio_usb/Kconfig
create mode 100644 drivers/usb/virtio_usb/Makefile
create mode 100644 drivers/usb/virtio_usb/controller.c
create mode 100644 drivers/usb/virtio_usb/controller.h
create mode 100644 include/uapi/linux/virtio_usb.h
diff --git a/MAINTAINERS b/MAINTAINERS
index 84cb98ef4c49..845bc1842249 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -29809,6 +29809,16 @@ S: Maintained
F: drivers/spi/spi-virtio.c
F: include/uapi/linux/virtio_spi.h
+VIRTIO USB DRIVER
+M: Igor Skalkin <igor.skalkin@oss.qualcomm.com>
+M: Aiswarya Cyriac <aiswarya.cyriac@oss.qualcomm.com>
+M: Vasilii Ianikeev <vasilii.ianikeev@oss.qualcomm.com>
+L: virtualization@lists.linux.dev
+L: linux-usb@vger.kernel.org
+S: Maintained
+F: drivers/usb/virtio_usb/
+F: include/uapi/linux/virtio_usb.h
+
VIRTUAL BOX GUEST DEVICE DRIVER
M: Hans de Goede <hansg@kernel.org>
M: Arnd Bergmann <arnd@arndb.de>
diff --git a/drivers/usb/Kconfig b/drivers/usb/Kconfig
index abf8c6cdea9e..68076db03203 100644
--- a/drivers/usb/Kconfig
+++ b/drivers/usb/Kconfig
@@ -139,6 +139,8 @@ source "drivers/usb/chipidea/Kconfig"
source "drivers/usb/isp1760/Kconfig"
+source "drivers/usb/virtio_usb/Kconfig"
+
comment "USB port drivers"
if USB
diff --git a/drivers/usb/Makefile b/drivers/usb/Makefile
index eecbd631fdab..f28a4b7989bf 100644
--- a/drivers/usb/Makefile
+++ b/drivers/usb/Makefile
@@ -12,6 +12,7 @@ obj-$(CONFIG_USB_SUPPORT) += phy/
obj-$(CONFIG_USB_DWC3) += dwc3/
obj-$(CONFIG_USB_DWC2) += dwc2/
obj-$(CONFIG_USB_ISP1760) += isp1760/
+obj-$(CONFIG_USB_VIRTIO) += virtio_usb/
obj-$(CONFIG_USB_CDNS_SUPPORT) += cdns3/
diff --git a/drivers/usb/virtio_usb/Kconfig b/drivers/usb/virtio_usb/Kconfig
new file mode 100644
index 000000000000..0cc5df26151c
--- /dev/null
+++ b/drivers/usb/virtio_usb/Kconfig
@@ -0,0 +1,13 @@
+# SPDX-License-Identifier: GPL-2.0-or-later
+
+config USB_VIRTIO
+ tristate "Virtio USB controller support"
+ depends on VIRTIO && USB && USB_GADGET
+ 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).
+
+ To compile this driver as a module, choose M here: the module
+ will be called virtio-usb.
diff --git a/drivers/usb/virtio_usb/Makefile b/drivers/usb/virtio_usb/Makefile
new file mode 100644
index 000000000000..38aa6a822366
--- /dev/null
+++ b/drivers/usb/virtio_usb/Makefile
@@ -0,0 +1,5 @@
+# SPDX-License-Identifier: GPL-2.0-or-later
+
+obj-$(CONFIG_USB_VIRTIO) += virtio-usb.o
+
+virtio-usb-y := controller.o
diff --git a/drivers/usb/virtio_usb/controller.c b/drivers/usb/virtio_usb/controller.c
new file mode 100644
index 000000000000..4fcf3d7a6107
--- /dev/null
+++ b/drivers/usb/virtio_usb/controller.c
@@ -0,0 +1,155 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+/*
+ * virtio_usb: VirtIO USB device
+ *
+ * Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.
+ */
+
+#include <linux/module.h>
+#include <linux/virtio_ids.h>
+
+#include "controller.h"
+
+/**
+ * virtio_usb_find_vqs() - Enumerate and initialize all virtqueues.
+ * @vusb: VirtIO usb device.
+ *
+ * Context: Any context.
+ * Return: 0 on success, -errno on failure.
+ */
+static int virtio_usb_find_vqs(struct virtio_usb *vusb)
+{
+ unsigned int nvqs = vusb->nvqs, i;
+ struct virtqueue **vqs = NULL;
+ int rc = -ENOMEM;
+
+ vqs = kcalloc(nvqs, sizeof(void *), GFP_KERNEL);
+ if (!vqs)
+ return -ENOMEM;
+
+ struct virtqueue_info *vqs_info =
+ kcalloc(nvqs, sizeof(*vqs_info), GFP_KERNEL);
+ if (!vqs_info) {
+ rc = -ENOMEM;
+ goto on_exit;
+ }
+ for (i = 0; i < nvqs; i++) {
+ vqs_info[i].name = vusb->vqueues[i].name;
+ vqs_info[i].callback = vusb->vqueues[i].callback;
+ }
+ rc = virtio_find_vqs(vusb->vdev, nvqs, vqs, vqs_info, NULL);
+
+ kfree(vqs_info);
+
+ for (i = 0; i < nvqs; i++) {
+ vusb->vqueues[i].vqueue = vqs[i];
+ spin_lock_init(&vusb->vqueues[i].lock);
+ }
+on_exit:
+ kfree(vqs);
+ return rc;
+}
+
+/**
+ * virtio_usb_validate() - Validate if the device can be started.
+ * @vdev: VirtIO parent device.
+ *
+ * Context: Any context.
+ * Return: 0 on success, -EINVAL on failure.
+ */
+static int virtio_usb_validate(struct virtio_device *vdev)
+{
+ if (!vdev->config->get) {
+ dev_err(&vdev->dev, "configuration access disabled\n");
+ return -EINVAL;
+ }
+
+ if (!virtio_has_feature(vdev, VIRTIO_F_VERSION_1)) {
+ dev_err(&vdev->dev,
+ "device does not comply with spec version 1.x\n");
+ return -EINVAL;
+ }
+
+ return 0;
+}
+
+/**
+ * virtio_usb_probe() - Probe VirtIO usb controller.
+ * @vdev: VirtIO parent device.
+ *
+ * Context: Any context that permits to sleep.
+ * Return: 0 on success, -errno on failure.
+ */
+static int virtio_usb_probe(struct virtio_device *vdev)
+{
+ struct virtio_usb *vusb;
+ unsigned int nvqs = 0;
+ int rc = 0;
+
+ vusb = devm_kzalloc(&vdev->dev, sizeof(*vusb), GFP_KERNEL);
+ if (!vusb)
+ return -ENOMEM;
+
+ vusb->vdev = vdev;
+ vdev->priv = vusb;
+
+ virtio_cread_le(vdev, struct virtio_usb_config, ports, &vusb->nports);
+
+ vusb->vports = devm_kcalloc(&vdev->dev, vusb->nports,
+ sizeof(*vusb->vports), GFP_KERNEL);
+ if (!vusb->vports)
+ return -ENOMEM;
+
+ vusb->vqueues = devm_kcalloc(&vdev->dev, nvqs, sizeof(*vusb->vqueues),
+ GFP_KERNEL);
+ if (!vusb->vqueues)
+ return -ENOMEM;
+
+ vusb->nvqs = nvqs;
+
+ rc = virtio_usb_find_vqs(vusb);
+ if (rc)
+ goto on_exit;
+
+ virtio_device_ready(vdev);
+
+on_exit:
+ return rc;
+}
+
+/**
+ * virtio_usb_remove() - Remove VirtIO usb device.
+ * @vdev: VirtIO parent device.
+ *
+ * Context: Any context that permits to sleep.
+ */
+static void virtio_usb_remove(struct virtio_device *vdev)
+{
+ struct virtio_usb *vusb = vdev->priv;
+ int i;
+
+ virtio_reset_device(vdev);
+ for (i = 0; i < vusb->nvqs; i++)
+ vusb->vqueues[i].stop(vusb, &vusb->vqueues[i]);
+
+ vdev->config->del_vqs(vdev);
+}
+
+static const struct virtio_device_id id_table[] = {
+ { VIRTIO_ID_USB, VIRTIO_DEV_ANY_ID },
+ { 0 },
+};
+
+static struct virtio_driver virtio_usb_driver = {
+ .driver.name = KBUILD_MODNAME,
+ .id_table = id_table,
+ .validate = virtio_usb_validate,
+ .probe = virtio_usb_probe,
+ .remove = virtio_usb_remove,
+};
+
+module_virtio_driver(virtio_usb_driver);
+
+MODULE_DEVICE_TABLE(virtio, id_table);
+MODULE_DESCRIPTION("Dual-role virtio-usb controller driver");
+MODULE_LICENSE("GPL");
diff --git a/drivers/usb/virtio_usb/controller.h b/drivers/usb/virtio_usb/controller.h
new file mode 100644
index 000000000000..5a47c9ca52ad
--- /dev/null
+++ b/drivers/usb/virtio_usb/controller.h
@@ -0,0 +1,84 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+/*
+ * virtio-usb: Virtio usb device
+ *
+ * Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.
+ */
+
+#ifndef VIRTIO_USB_CONTROLLER_H
+#define VIRTIO_USB_CONTROLLER_H
+
+#include <linux/slab.h>
+#include <linux/virtio.h>
+#include <linux/virtio_config.h>
+
+#include <linux/virtio_usb.h>
+
+/**
+ * struct virtio_usb_port - Per-virtual-port state.
+ * @role: Role of this port (VIRTIO_USB_ROLE_HOST or _DEVICE), once a
+ * role-providing commit has assigned it. Unused for now - this
+ * struct is deliberately introduced ahead of any code that
+ * populates or reads @role, so that every later commit that adds
+ * a role (host, device) or role switching can build on this same
+ * per-port array from the start instead of each reinventing its
+ * own port-indexed storage.
+ */
+struct virtio_usb_port {
+ unsigned int role;
+};
+
+/**
+ * struct virtio_usb - VirtIO USB device.
+ * @vdev: Underlying virtio device
+ * @vqueues: Array of virtqueue wrappers.
+ * @vports: Array of per-port structures, one entry per virtual port.
+ * @nports: number of supported ports
+ * @nvqs: number of virtqueues for the device
+ */
+struct virtio_usb {
+ struct virtio_device *vdev;
+ struct virtio_usb_queue *vqueues;
+ struct virtio_usb_port *vports;
+ unsigned int nports;
+ u32 nvqs;
+};
+
+/**
+ * struct virtio_usb_queue - Virtqueue wrapper structure.
+ * @name: Name of the virtqueue.
+ * @callback: Used to synchronize access to a virtqueue.
+ * @vqueue: Underlying virtqueue.
+ * @lock: Used to synchronize access to a virtqueue.
+ * @process: queue process callback function
+ * @stop: queue stop callback function
+ */
+struct virtio_usb_queue {
+ const char *name;
+ vq_callback_t *callback;
+ struct virtqueue *vqueue;
+ spinlock_t lock;
+ void (*process)(struct virtio_usb *vusb, void *buf);
+ void (*stop)(struct virtio_usb *vusb, struct virtio_usb_queue *vq);
+};
+
+/**
+ * struct virtio_usb_vq_desc - Read-only virtqueue template.
+ * @name: Name of the virtqueue.
+ * @callback: Virtqueue notification callback function.
+ * @process: queue process callback function.
+ * @stop: queue stop callback function.
+ *
+ * Immutable per-role virtqueue description, copied into a fresh
+ * per-instance struct virtio_usb_queue during probe() instead of being
+ * shared directly - so that multiple probed virtio_usb instances never
+ * alias the same struct virtqueue.
+ */
+struct virtio_usb_vq_desc {
+ const char *name;
+ vq_callback_t *callback;
+ void (*process)(struct virtio_usb *vusb, void *buf);
+ void (*stop)(struct virtio_usb *vusb, struct virtio_usb_queue *vq);
+};
+
+#endif /* VIRTIO_USB_CONTROLLER_H */
diff --git a/include/uapi/linux/virtio_usb.h b/include/uapi/linux/virtio_usb.h
new file mode 100644
index 000000000000..c494ca94d1ff
--- /dev/null
+++ b/include/uapi/linux/virtio_usb.h
@@ -0,0 +1,278 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later WITH Linux-syscall-note */
+/*
+ * Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.
+ */
+
+#ifndef _UAPI_LINUX_VIRTIO_USB_H
+#define _UAPI_LINUX_VIRTIO_USB_H
+
+#include <linux/virtio_types.h>
+
+/*****************************************************************************
+ * FEATURE BITS
+ */
+/* Host controller is supported */
+#define VIRTIO_USB_F_HOST 0
+/* Device controller is supported */
+#define VIRTIO_USB_F_DEVICE 1
+/* Role switching is supported */
+#define VIRTIO_USB_F_SWITCH_ROLE 2
+
+/*****************************************************************************
+ * CONFIGURATION SPACE
+ */
+struct virtio_usb_config {
+ /* # of available ports */
+ __le32 ports;
+};
+
+/*****************************************************************************
+ * COMMON DEFINITIONS
+ */
+#define VIRTIO_USB_VQ_HOST_COMMAND 0
+#define VIRTIO_USB_VQ_HOST_EVENT 1
+#define VIRTIO_USB_VQ_HOST_DATA 2
+#define VIRTIO_USB_VQ_DEV_COMMAND 3
+#define VIRTIO_USB_VQ_DEV_EVENT 4
+#define VIRTIO_USB_VQ_DEV_DATA 5
+#define VIRTIO_USB_VQ_ROLE_COMMAND 6
+#define VIRTIO_USB_VQ_ROLE_EVENT 7
+#define VIRTIO_USB_VQ_MAX 8
+
+#define VIRTIO_USB_EP_CONTROL 0
+#define VIRTIO_USB_EP_INTERRUPT 1
+#define VIRTIO_USB_EP_BULK 2
+#define VIRTIO_USB_EP_ISOCHRONOUS 3
+
+#define VIRTIO_USB_S_OK 0
+#define VIRTIO_USB_S_ERR_BAD_MSG 1
+#define VIRTIO_USB_S_ERR_INTERNAL 2
+#define VIRTIO_USB_S_ERR_NO_DEVICE 3
+#define VIRTIO_USB_S_ERR_ISO_XFER 4
+#define VIRTIO_USB_S_ERR_ISO_BIG 5
+#define VIRTIO_USB_S_ERR_DATA_IN 6
+#define VIRTIO_USB_S_ERR_DATA_OUT 7
+#define VIRTIO_USB_S_ERR_MSG_SIZE 8
+#define VIRTIO_USB_S_ERR_OVERFLOW 9
+#define VIRTIO_USB_S_ERR_STALL 10
+#define VIRTIO_USB_S_ERR_SHORT_PKT 11
+#define VIRTIO_USB_S_ERR_CANCELLED 12
+#define VIRTIO_USB_S_ERR_HOST 13
+
+struct virtio_usb_cmd_status {
+ __le32 code; /* VIRTIO_USB_S_XXX */
+};
+
+/*****************************************************************************
+ * HOST COMMAND MESSAGES
+ */
+#define VIRTIO_USB_CMD_HOST_CANCEL 0
+#define VIRTIO_USB_CMD_HOST_STREAMS_ALLOC 1
+#define VIRTIO_USB_CMD_HOST_STREAMS_FREE 2
+
+struct virtio_usb_host_cmd_hdr {
+ __le32 code; /* VIRTIO_USB_CMD_HOST_XXX */
+ __le32 port; /* Port ID */
+};
+
+/* VIRTIO_USB_CMD_HOST_CANCEL */
+struct virtio_usb_host_cmd_cancel {
+ struct virtio_usb_host_cmd_hdr hdr;
+ __le64 tag;
+};
+
+/* VIRTIO_USB_CMD_HOST_STREAMS_ALLOC/FREE */
+struct virtio_usb_host_cmd_streams {
+ struct virtio_usb_host_cmd_hdr hdr;
+ __le32 number_of_streams;
+ __le32 number_of_eps;
+};
+
+/*****************************************************************************
+ * HOST EVENT MESSAGES
+ */
+#define VIRTIO_USB_EVT_HOST_PORT_CONNECTED 0
+#define VIRTIO_USB_EVT_HOST_PORT_DISCONNECTED 1
+
+/* VIRTIO_USB_EVT_HOST_PORT_CONNECTED/DISCONNECTED */
+#define VIRTIO_USB_SPEED_UNKNOWN 0
+#define VIRTIO_USB_SPEED_LOW 1
+#define VIRTIO_USB_SPEED_FULL 2 /* usb 1.1 */
+#define VIRTIO_USB_SPEED_HIGH 3 /* usb 2.0 */
+#define VIRTIO_USB_SPEED_SUPER 5 /* usb 3.0 */
+#define VIRTIO_USB_SPEED_SUPER_PLUS 6 /* usb 3.1 */
+
+struct virtio_usb_host_port_event {
+ __le32 code; /* VIRTIO_USB_EVT_HOST_PORT_XXX */
+ __le32 port_id;
+ __le32 speed; /* VIRTIO_USB_SPEED_XXX */
+ __le32 padding;
+};
+
+/*****************************************************************************
+ * DEVICE COMMAND MESSAGES
+ */
+#define VIRTIO_USB_CMD_DEV_GET_ENDPOINT_COUNT 0
+#define VIRTIO_USB_CMD_DEV_GET_ENDPOINT_INFO 1
+#define VIRTIO_USB_CMD_DEV_PULLUP 2
+#define VIRTIO_USB_CMD_DEV_VBUS_DRAW 3
+#define VIRTIO_USB_CMD_DEV_EP_ENABLE 4
+#define VIRTIO_USB_CMD_DEV_EP_DISABLE 5
+#define VIRTIO_USB_CMD_DEV_EP_SET_HALT 6
+#define VIRTIO_USB_CMD_DEV_EP_SET_WEDGE 7
+#define VIRTIO_USB_CMD_DEV_CANCEL 8
+
+struct virtio_usb_dev_cmd_hdr {
+ __le32 code; /* VIRTIO_USB_CMD_DEV_XXX */
+ __le16 port; /* Port ID */
+ __le16 endpoint; /* Endpoint ID */
+};
+
+/* VIRTIO_USB_CMD_DEV_GET_ENDPOINT_COUNT */
+struct virtio_usb_dev_cmd_ep_count {
+ struct virtio_usb_cmd_status status;
+ __le32 count; /* # of supported endpoints */
+};
+
+#define VIRTIO_USB_DIR_OUT 0
+#define VIRTIO_USB_DIR_IN 1
+
+#define VIRTIO_USB_EP_DIR_OUT 0
+#define VIRTIO_USB_EP_DIR_IN 0x80
+
+/*
+ * VIRTIO_USB_CMD_DEV_GET_ENDPOINT_INFO
+ *
+ * Response:
+ * struct virtio_usb_cmd_status
+ * struct virtio_usb_dev_ep_info [count]
+ */
+struct virtio_usb_dev_cmd_ep_info {
+ __le16 types; /* supported type bit map (1 << VIRTIO_USB_EP_XXX) */
+ __le16 directions; /* supported direction bit map (1 << VIRTIO_USB_DIR_XXX) */
+ __le16 maxpacket_limit;
+ __le16 max_streams;
+};
+
+/*******************************************************************************
+ * DEVICE EVENT MESSAGES
+ */
+#define VIRTIO_USB_EVT_DEV_CONNECTED 0
+#define VIRTIO_USB_EVT_DEV_DISCONNECTED 1
+#define VIRTIO_USB_EVT_DEV_SETUP 2
+#define VIRTIO_USB_EVT_DEV_RESET 3
+#define VIRTIO_USB_EVT_DEV_SUSPEND 4
+#define VIRTIO_USB_EVT_DEV_RESUME 5
+
+struct virtio_usb_dev_event {
+ __le32 code; /* VIRTIO_USB_EVT_DEV_XXX */
+ __u8 padding[12];
+};
+
+/* VIRTIO_USB_EVT_DEV_SETUP */
+struct virtio_usb_dev_setup_event {
+ __le32 code; /* VIRTIO_USB_EVT_DEV_SETUP */
+ __u8 setup[8]; /* setup packet contents */
+ __u8 padding[4];
+};
+
+/*******************************************************************************
+ * HOST/DEVICE DATA MESSAGES
+ */
+#define VIRTIO_USB_FLAG_SHORT_NOT_OK (1 << 0)
+#define VIRTIO_USB_FLAG_ISO_ASAP (1 << 1)
+#define VIRTIO_USB_FLAG_ZERO_PACKET (1 << 2)
+
+struct virtio_usb_request {
+ __le64 tag;
+ __le16 port; /* Port ID */
+ __le16 endpoint; /* Endpoint ID */
+ __le16 transfer_type; /* VIRTIO_USB_EP_XXX */
+ __le16 transfer_flags; /* VIRTIO_USB_FLAG_XXX */
+ union {
+ /* transfer_type = VIRTIO_USB_EP_CONTROL */
+ struct {
+ __u8 setup[8];
+ } control;
+ /* transfer_type = VIRTIO_USB_EP_INTERRUPT */
+ struct {
+ __le32 interval;
+ } interrupt;
+ /* transfer_type = VIRTIO_USB_EP_BULK */
+ struct {
+ __le32 stream_id;
+ } bulk;
+ /* transfer_type = VIRTIO_USB_EP_ISOCHRONOUS */
+ struct {
+ __le32 interval;
+ __le32 start_frame;
+ __le32 number_of_packets;
+ __le32 padding;
+ } iso;
+ };
+};
+
+struct virtio_usb_response {
+ __le32 status; /* VIRTIO_USB_S_XXX */
+ __le32 actual_length;
+ __le32 interval; /* type = VIRTIO_USB_EP_INTERRUPT/ISOCHRONOUS */
+ __le32 start_frame; /* type = VIRTIO_USB_EP_ISOCHRONOUS */
+};
+
+/*
+ * ISO request:
+ * struct virtio_usb_request
+ * struct virtio_usb_iso_packet [number_of_packets]
+ * ISO response:
+ * struct virtio_usb_response
+ * struct virtio_usb_iso_status [number_of_packets]
+ */
+struct virtio_usb_iso_packet {
+ __le32 offset;
+ __le32 length;
+};
+
+struct virtio_usb_iso_status {
+ __le32 status; /* VIRTIO_USB_S_XXX */
+ __le32 actual_length;
+};
+
+/*****************************************************************************
+ * ROLE COMMAND MESSAGES
+ */
+#define VIRTIO_USB_CMD_ROLE_GET 0
+/* If VIRTIO_USB_F_SWITCH_ROLE is negotiated */
+#define VIRTIO_USB_CMD_ROLE_SET 1
+
+struct virtio_usb_role_cmd_hdr {
+ __le32 code; /* VIRTIO_USB_CMD_ROLE_XXX */
+ __le32 port; /* Port ID */
+};
+
+/* VIRTIO_USB_CMD_ROLE_SET */
+struct virtio_usb_role_set {
+ struct virtio_usb_role_cmd_hdr hdr;
+ __le32 role; /* VIRTIO_USB_ROLE_XXX */
+};
+
+/* VIRTIO_USB_CMD_ROLE_GET */
+#define VIRTIO_USB_ROLE_HOST 0
+#define VIRTIO_USB_ROLE_DEVICE 1
+
+struct virtio_usb_role_info {
+ struct virtio_usb_cmd_status status;
+ __le32 role; /* VIRTIO_USB_ROLE_XXX */
+ __le32 supported_role; /* VIRTIO_USB_F_[HOST|DEVICE|SWITCH_ROLE] */
+};
+
+/*****************************************************************************
+ * ROLE EVENT MESSAGES
+ */
+#define VIRTIO_USB_EVT_ROLE_CHANGE 0
+
+struct virtio_usb_role_event {
+ __le32 code; /* VIRTIO_USB_EVT_ROLE_XXX */
+ __le32 port; /* Port ID */
+};
+
+#endif /* _UAPI_LINUX_VIRTIO_USB_H */
--
2.49.0
^ permalink raw reply related [flat|nested] 9+ messages in thread
* [RFC PATCH v2 3/7] virtio-usb: add host role (USB Host Controller) support
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 ` Igor Skalkin
2026-12-01 17:35 ` [RFC PATCH v2 4/7] virtio-usb: add device role (USB Device " Igor Skalkin
` (4 subsequent siblings)
7 siblings, 0 replies; 9+ messages in thread
From: Igor Skalkin @ 2026-12-01 17:35 UTC (permalink / raw)
To: Michael S . Tsirkin, Jason Wang, Greg Kroah-Hartman
Cc: virtualization, linux-usb, linux-kernel, Eugenio Perez, Xuan Zhuo,
Vasilii Ianikeev, Aiswarya Cyriac, Anton Yakovlev, Trilok Soni,
Matias Ezequiel Vara Larsen, Igor Skalkin
From: Aiswarya Cyriac <aiswarya.cyriac@oss.qualcomm.com>
Add the common virtqueue handling code (command, event and data
queues) shared by every role, and the virtio-usb host controller
(HCD) implementation, wiring it up as the host role of the dual-role
driver on top of that common code.
Each host-role virtual port gets its own HS+SS usb_hcd pair and its
own root hub (struct virtio_usb_hc_vp), with a fixed
VIRTIO_USB_VP_MAX_PORTS (8) leaf slots pre-allocated at VP init time
and reused across connect/disconnect - never dynamically alloc'd or
freed. This lets the backend forward more than one physical socket -
and, for host ports behind a physical hub, more than one leaf device
per socket - as independent virtual ports from the start, instead of
collapsing everything onto a single shared root hub and having to
revisit that decision once more than one host-role port needs to
exist at the same time.
virtio_usb_add_hcd() derives each VP's HCD bus_name from the parent
virtio_device with devm_kasprintf() rather than a stack buffer, since
usb_create_hcd()/usb_create_shared_hcd() store that pointer as-is in
hcd->self.bus_name without copying it - it must outlive the HCD
itself.
Every port is host-role for now, since no other role exists yet;
vports[].role is populated unconditionally until later commits add
device role and per-port role resolution.
Command completion timeout is a compile-time constant
(VIRTIO_USB_CMD_TIMEOUT_MS), not a module parameter: one second is
enough for everything the command queue is used for, and there is no
real use case for changing it at load time.
Every data request submission gets its own tag from a per-device
64-bit counter, which HOST_CANCEL refers to. The address of the
request does not identify a submission: a request is freed when its
URB is given back, and the next allocation of the same size often
gets the same memory, so a cancel still in flight could match an
unrelated new URB.
urb->hcpriv is published before the request is placed on the data
virtqueue, so virtio_usb_hc_dequeue() can run before the device has
seen the request. A HOST_CANCEL sent at that point would not match
anything, would be answered with success and dropped, and
usb_kill_urb() would wait forever for the URB queued right after. So
dequeue only records the cancel in that case, and the enqueue path
sends it once the request is queued. Enqueue holds a reference on the
request across that window, and tracks completion in the private
data so it does not look at an URB that has already been given back.
Dequeue reads the tag under the port lock, since the request can
complete and be freed as soon as the lock is dropped.
Signed-off-by: Aiswarya Cyriac <aiswarya.cyriac@oss.qualcomm.com>
Co-developed-by: Anton Yakovlev <anton.yakovlev@oss.qualcomm.com>
Signed-off-by: Anton Yakovlev <anton.yakovlev@oss.qualcomm.com>
Signed-off-by: Vasilii Ianikeev <vasilii.ianikeev@oss.qualcomm.com>
Co-developed-by: Igor Skalkin <igor.skalkin@oss.qualcomm.com>
Signed-off-by: Igor Skalkin <igor.skalkin@oss.qualcomm.com>
---
drivers/usb/virtio_usb/Makefile | 4 +-
drivers/usb/virtio_usb/controller.c | 95 +-
drivers/usb/virtio_usb/controller.h | 59 +-
drivers/usb/virtio_usb/host.c | 1483 +++++++++++++++++++++++++++
drivers/usb/virtio_usb/host.h | 244 +++++
drivers/usb/virtio_usb/vq_common.c | 747 ++++++++++++++
drivers/usb/virtio_usb/vq_common.h | 163 +++
include/uapi/linux/virtio_usb.h | 16 +-
8 files changed, 2795 insertions(+), 16 deletions(-)
create mode 100644 drivers/usb/virtio_usb/host.c
create mode 100644 drivers/usb/virtio_usb/host.h
create mode 100644 drivers/usb/virtio_usb/vq_common.c
create mode 100644 drivers/usb/virtio_usb/vq_common.h
diff --git a/drivers/usb/virtio_usb/Makefile b/drivers/usb/virtio_usb/Makefile
index 38aa6a822366..c6951c68b8c2 100644
--- a/drivers/usb/virtio_usb/Makefile
+++ b/drivers/usb/virtio_usb/Makefile
@@ -2,4 +2,6 @@
obj-$(CONFIG_USB_VIRTIO) += virtio-usb.o
-virtio-usb-y := controller.o
+virtio-usb-y := controller.o \
+ vq_common.o \
+ host.o
diff --git a/drivers/usb/virtio_usb/controller.c b/drivers/usb/virtio_usb/controller.c
index 4fcf3d7a6107..eb343f026a46 100644
--- a/drivers/usb/virtio_usb/controller.c
+++ b/drivers/usb/virtio_usb/controller.c
@@ -9,6 +9,8 @@
#include <linux/virtio_ids.h>
#include "controller.h"
+#include "host.h"
+#include "vq_common.h"
/**
* virtio_usb_find_vqs() - Enumerate and initialize all virtqueues.
@@ -70,9 +72,17 @@ static int virtio_usb_validate(struct virtio_device *vdev)
return -EINVAL;
}
+ if (!virtio_has_feature(vdev, VIRTIO_USB_F_HOST)) {
+ dev_err(&vdev->dev,
+ "device should support at least one usb role\n");
+ return -EINVAL;
+ }
+
return 0;
}
+static void virtio_usb_remove(struct virtio_device *vdev);
+
/**
* virtio_usb_probe() - Probe VirtIO usb controller.
* @vdev: VirtIO parent device.
@@ -84,7 +94,7 @@ static int virtio_usb_probe(struct virtio_device *vdev)
{
struct virtio_usb *vusb;
unsigned int nvqs = 0;
- int rc = 0;
+ int rc = 0, i = 0;
vusb = devm_kzalloc(&vdev->dev, sizeof(*vusb), GFP_KERNEL);
if (!vusb)
@@ -100,6 +110,22 @@ static int virtio_usb_probe(struct virtio_device *vdev)
if (!vusb->vports)
return -ENOMEM;
+ if (virtio_has_feature(vdev, VIRTIO_USB_F_HOST))
+ vusb->host_role = 1;
+
+ /* Only host_role exists so far, so every port is unambiguously a
+ * host-role port. Later commits (device role, per-port role
+ * query) will replace this with real per-port role resolution.
+ */
+ vusb->host_vq_base = -1;
+ if (vusb->host_role) {
+ vusb->host_vq_base = nvqs;
+ nvqs += VIRTIO_USB_VQ_HOST_MAX;
+
+ for (i = 0; i < vusb->nports; i++)
+ vusb->vports[i].role = VIRTIO_USB_ROLE_HOST;
+ }
+
vusb->vqueues = devm_kcalloc(&vdev->dev, nvqs, sizeof(*vusb->vqueues),
GFP_KERNEL);
if (!vusb->vqueues)
@@ -107,13 +133,60 @@ static int virtio_usb_probe(struct virtio_device *vdev)
vusb->nvqs = nvqs;
+ if (vusb->host_vq_base >= 0)
+ for (i = 0; i < VIRTIO_USB_VQ_HOST_MAX; i++) {
+ vusb->vqueues[vusb->host_vq_base + i].name =
+ host_vqueues[i].name;
+ vusb->vqueues[vusb->host_vq_base + i].callback =
+ host_vqueues[i].callback;
+ vusb->vqueues[vusb->host_vq_base + i].process =
+ host_vqueues[i].process;
+ vusb->vqueues[vusb->host_vq_base + i].stop =
+ host_vqueues[i].stop;
+ }
+
rc = virtio_usb_find_vqs(vusb);
- if (rc)
- goto on_exit;
+ if (rc) {
+ dev_err(&vdev->dev, "%s virtio_usb_find_vqs() error(%d)\n",
+ __func__, rc);
+ goto on_error;
+ }
+
+ 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);
+
+ /* Initialize one HCD pair per host-role VP. */
+ for (i = 0; i < vusb->nports; i++) {
+ if (vusb->vports[i].role != VIRTIO_USB_ROLE_HOST)
+ continue;
+ rc = virtio_usb_hc_vp_init(vusb, i);
+ if (rc) {
+ dev_err(&vdev->dev,
+ "%s virtio_usb_hc_vp_init() port=%d error(%d)\n",
+ __func__, i, rc);
+ goto on_error;
+ }
+ }
+ /* Populate the shared host event queue once, after every
+ * VP is initialized.
+ */
+ rc = virtio_usb_hc_event_populate(vusb);
+ if (rc) {
+ dev_err(&vdev->dev,
+ "%s virtio_usb_hc_event_populate() error(%d)\n",
+ __func__, rc);
+ goto on_error;
+ }
+ }
virtio_device_ready(vdev);
-on_exit:
+ return rc;
+
+on_error:
+ dev_err(&vdev->dev, "%s failed(%d)\n", __func__, rc);
+ virtio_usb_remove(vdev);
return rc;
}
@@ -128,13 +201,23 @@ static void virtio_usb_remove(struct virtio_device *vdev)
struct virtio_usb *vusb = vdev->priv;
int i;
- virtio_reset_device(vdev);
for (i = 0; i < vusb->nvqs; i++)
vusb->vqueues[i].stop(vusb, &vusb->vqueues[i]);
+ if (vusb->host_role && vusb->vports) {
+ for (i = 0; i < (int)vusb->nports; i++)
+ virtio_usb_hc_vp_deinit(vusb, i);
+ }
+
+ virtio_reset_device(vdev);
+
vdev->config->del_vqs(vdev);
}
+static const unsigned int virtio_usb_features[] = {
+ VIRTIO_USB_F_HOST,
+};
+
static const struct virtio_device_id id_table[] = {
{ VIRTIO_ID_USB, VIRTIO_DEV_ANY_ID },
{ 0 },
@@ -142,6 +225,8 @@ static const struct virtio_device_id id_table[] = {
static struct virtio_driver virtio_usb_driver = {
.driver.name = KBUILD_MODNAME,
+ .feature_table = virtio_usb_features,
+ .feature_table_size = ARRAY_SIZE(virtio_usb_features),
.id_table = id_table,
.validate = virtio_usb_validate,
.probe = virtio_usb_probe,
diff --git a/drivers/usb/virtio_usb/controller.h b/drivers/usb/virtio_usb/controller.h
index 5a47c9ca52ad..dfa16a3d42a8 100644
--- a/drivers/usb/virtio_usb/controller.h
+++ b/drivers/usb/virtio_usb/controller.h
@@ -8,24 +8,30 @@
#ifndef VIRTIO_USB_CONTROLLER_H
#define VIRTIO_USB_CONTROLLER_H
+#include <linux/atomic.h>
#include <linux/slab.h>
#include <linux/virtio.h>
#include <linux/virtio_config.h>
#include <linux/virtio_usb.h>
+/* Forward declaration - full definition in host.h */
+struct virtio_usb_hc_vp;
+
+#define VIRTIO_USB_VQ_COMMAND_IDX 0
+#define VIRTIO_USB_VQ_EVENT_IDX 1
+#define VIRTIO_USB_VQ_DATA_IDX 2
+
+#define VIRTIO_USB_VQ_HOST_MAX 3
+
/**
* struct virtio_usb_port - Per-virtual-port state.
- * @role: Role of this port (VIRTIO_USB_ROLE_HOST or _DEVICE), once a
- * role-providing commit has assigned it. Unused for now - this
- * struct is deliberately introduced ahead of any code that
- * populates or reads @role, so that every later commit that adds
- * a role (host, device) or role switching can build on this same
- * per-port array from the start instead of each reinventing its
- * own port-indexed storage.
+ * @role: Role of this port (VIRTIO_USB_ROLE_HOST or _DEVICE).
+ * @vhc: Host controller - non-NULL when role is HOST.
*/
struct virtio_usb_port {
unsigned int role;
+ struct virtio_usb_hc_vp *vhc;
};
/**
@@ -35,6 +41,16 @@ struct virtio_usb_port {
* @vports: Array of per-port structures, one entry per virtual port.
* @nports: number of supported ports
* @nvqs: number of virtqueues for the device
+ * @host_role: flag indicating support for host role
+ * @host_vq_base: index into vqueues[] where the HOST_COMMAND/EVENT/DATA
+ * triplet starts, or -1 if this instance has no host-role
+ * VP (in which case those queues do not exist on the wire
+ * and must not be negotiated).
+ * @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
+ * across every host-role VP.
+ * @data_tag_seq: Source of data request tags, see virtio_usb_data_tag_next().
*/
struct virtio_usb {
struct virtio_device *vdev;
@@ -42,8 +58,32 @@ struct virtio_usb {
struct virtio_usb_port *vports;
unsigned int nports;
u32 nvqs;
+ bool host_role;
+ int host_vq_base;
+ struct work_struct vq_host_data_rx_work;
+ struct work_struct vq_host_evt_work;
+ atomic64_t data_tag_seq;
};
+/**
+ * virtio_usb_data_tag_next() - Get a tag for a new data request submission.
+ * @vusb: VirtIO USB device.
+ *
+ * The tag identifies one submission of a data request to the device and is
+ * what a HOST_CANCEL/DEV_CANCEL refers to. It must not be derived from the
+ * request's address: a usb_request is queued again with the same address,
+ * and a freed request's memory is soon reused for the next one, so a cancel
+ * still in flight for an earlier submission would match the new one and
+ * cancel it. A 64-bit counter never repeats in practice.
+ *
+ * Context: Any context.
+ * Return: A tag not used by any earlier submission.
+ */
+static inline u64 virtio_usb_data_tag_next(struct virtio_usb *vusb)
+{
+ return (u64)atomic64_inc_return(&vusb->data_tag_seq);
+}
+
/**
* struct virtio_usb_queue - Virtqueue wrapper structure.
* @name: Name of the virtqueue.
@@ -81,4 +121,9 @@ struct virtio_usb_vq_desc {
void (*stop)(struct virtio_usb *vusb, struct virtio_usb_queue *vq);
};
+/* Command completion timeout in milliseconds. One second is enough for
+ * everything the command queue is used for.
+ */
+#define VIRTIO_USB_CMD_TIMEOUT_MS MSEC_PER_SEC
+
#endif /* VIRTIO_USB_CONTROLLER_H */
diff --git a/drivers/usb/virtio_usb/host.c b/drivers/usb/virtio_usb/host.c
new file mode 100644
index 000000000000..b072c32ac0ee
--- /dev/null
+++ b/drivers/usb/virtio_usb/host.c
@@ -0,0 +1,1483 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+/*
+ * virtio_usb: VirtIO USB device
+ *
+ * Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.
+ */
+
+#include "controller.h"
+
+#include "host.h"
+#include "vq_common.h"
+
+/**
+ * virtio_usb_hc_reset() - Reset the host controller.
+ * @hcd: USB host controller device.
+ *
+ * Context: Any context
+ * Return: 0 on success, -errno on failure.
+ */
+static int virtio_usb_hc_reset(struct usb_hcd *hcd)
+{
+ struct virtio_usb_hc_vp *vhcd_vp = vhcd_get(hcd);
+
+ if (hcd == vhcd_vp->hs) {
+ hcd->speed = HCD_USB2;
+ hcd->self.root_hub->speed = USB_SPEED_HIGH;
+ hcd->has_tt = 1;
+ } else {
+ hcd->speed = HCD_USB3;
+ hcd->self.root_hub->speed = USB_SPEED_SUPER;
+ }
+
+ hcd->self.sg_tablesize = ~0;
+ return 0;
+}
+
+/**
+ * virtio_usb_hc_start() - Start the host controller.
+ * @hcd: USB host controller device
+ *
+ * Context: Any context
+ * Return: 0 on success, -errno on failure.
+ */
+static int virtio_usb_hc_start(struct usb_hcd *hcd)
+{
+ struct virtio_usb_hc_vp *vhcd_vp = vhcd_get(hcd);
+ unsigned long iflags;
+
+ hcd->uses_new_polling = 1;
+ clear_bit(HCD_FLAG_POLL_RH, &hcd->flags);
+
+ spin_lock_irqsave(&vhcd_vp->lock, iflags);
+ hcd->state = HC_STATE_RUNNING;
+ spin_unlock_irqrestore(&vhcd_vp->lock, iflags);
+ hcd->self.no_sg_constraint = 1;
+
+ return 0;
+}
+
+/**
+ * virtio_usb_hc_stop() - Stop the host controller.
+ * @hcd: USB host controller device
+ *
+ * Context: Any context
+ */
+static void virtio_usb_hc_stop(struct usb_hcd *hcd)
+{
+ struct virtio_usb_hc_vp *vhcd_vp = vhcd_get(hcd);
+ unsigned long iflags;
+
+ spin_lock_irqsave(&vhcd_vp->lock, iflags);
+ hcd->state = HC_STATE_HALT;
+ spin_unlock_irqrestore(&vhcd_vp->lock, iflags);
+}
+
+/**
+ * virtio_usb_hub_status_data() - Get the hub status data for the root hub.
+ * @vhcd_vp: per-VP VirtIO USB host controller
+ * @buffer: status buffer in which the hub status need to be updated
+ * @ss_mode: indicates if the root hub is a super speed hub.
+ *
+ * Context: Any context
+ * Return: 0 if the status hasn't changed, or the number of bytes in buffer.
+ */
+static int virtio_usb_hub_status_data(struct virtio_usb_hc_vp *vhcd_vp,
+ char *buffer, bool ss_mode)
+{
+ unsigned int i;
+ unsigned int nbytes = DIV_ROUND_UP(VIRTIO_USB_VP_MAX_PORTS + 1, 8);
+ int changed = 0;
+ unsigned long iflags;
+ struct usb_hcd *hcd = ss_mode ? vhcd_vp->ss : vhcd_vp->hs;
+
+ memset(buffer, 0, nbytes);
+
+ for (i = 0; i < VIRTIO_USB_VP_MAX_PORTS; i++) {
+ struct virtio_usb_hc_port *port = &vhcd_vp->ports[i];
+ u16 value;
+
+ spin_lock_irqsave(&port->lock, iflags);
+ value = ss_mode ? port->ss.change.value : port->hs.change.value;
+ spin_unlock_irqrestore(&port->lock, iflags);
+
+ if (value) {
+ buffer[(i + 1) / 8] |= 1 << ((i + 1) % 8);
+ changed = 1;
+ }
+ }
+ if (changed) {
+ spin_lock_irqsave(&vhcd_vp->lock, iflags);
+ if (hcd->state == HC_STATE_SUSPENDED)
+ usb_hcd_resume_root_hub(hcd);
+ spin_unlock_irqrestore(&vhcd_vp->lock, iflags);
+ }
+
+ return changed ? nbytes : 0;
+}
+
+static int virtio_usb_hs_hub_status_data(struct usb_hcd *hcd, char *buffer)
+{
+ return virtio_usb_hub_status_data(vhcd_get(hcd), buffer, false);
+}
+
+static int virtio_usb_ss_hub_status_data(struct usb_hcd *hcd, char *buffer)
+{
+ return virtio_usb_hub_status_data(vhcd_get(hcd), buffer, true);
+}
+
+/**
+ * virtio_usb_windex_to_port - Map wIndex to a host controller port.
+ * @vhcd_vp: per-VP host controller
+ * @wIndex: low byte contains the 1-based port number
+ *
+ * Return: pointer to port on success, NULL if out of range.
+ */
+static struct virtio_usb_hc_port *
+virtio_usb_windex_to_port(struct virtio_usb_hc_vp *vhcd_vp, u16 wIndex)
+{
+ u16 pIndex = wIndex & 0xFF;
+
+ if (pIndex == 0 || pIndex > VIRTIO_USB_VP_MAX_PORTS)
+ return NULL;
+ return &vhcd_vp->ports[pIndex - 1];
+}
+
+/**
+ * virtio_usb_hub_control() - Hub control request callback (shared HS/SS).
+ * @hcd: usb_hcd the request is for
+ * @type: Request type (bRequest combined with bmRequestType)
+ * @wValue: Request wValue
+ * @wIndex: Request wIndex, the port number for port requests
+ * @buffer: Buffer for the request data
+ * @wLength: Length of @buffer
+ * @ss_mode: True for the SuperSpeed root hub
+ *
+ * Return: 0 on success, -EPIPE for an unsupported request.
+ */
+static int virtio_usb_hub_control(struct usb_hcd *hcd, u16 type, u16 wValue,
+ u16 wIndex, char *buffer, u16 wLength,
+ bool ss_mode)
+{
+ struct virtio_usb_hc_port *port;
+ struct virtio_usb_hc_vp *vhcd_vp = vhcd_get(hcd);
+
+ switch (type) {
+ case GetHubDescriptor: {
+ struct usb_hub_descriptor *dsc =
+ (struct usb_hub_descriptor *)buffer;
+
+ memset(dsc, 0, sizeof(struct usb_hub_descriptor));
+
+ if (ss_mode) {
+ dsc->bDescLength = USB_DT_SS_HUB_SIZE;
+ dsc->bDescriptorType = USB_DT_SS_HUB;
+ } else {
+ dsc->bDescLength = 9;
+ dsc->bDescriptorType = USB_DT_HUB;
+ }
+
+ /* Fixed port count per VP - always within USB_MAXCHILDREN (31)
+ * and USB_SS_MAXPORTS (15).
+ */
+ dsc->bNbrPorts = VIRTIO_USB_VP_MAX_PORTS;
+
+ return 0;
+ }
+ case GetHubStatus: {
+ *((u32 *)buffer) = 0;
+ return 0;
+ }
+ case GetPortStatus: {
+ u16 *status = (u16 *)buffer;
+ unsigned long iflags;
+
+ memset(status, 0, wLength);
+
+ port = virtio_usb_windex_to_port(vhcd_vp, wIndex);
+ if (port) {
+ spin_lock_irqsave(&port->lock, iflags);
+ if (ss_mode) {
+ status[0] = port->ss.status.value;
+ status[1] = port->ss.change.value;
+ } else {
+ status[0] = port->hs.status.value;
+ status[1] = port->hs.change.value;
+ }
+ spin_unlock_irqrestore(&port->lock, iflags);
+ }
+
+ return 0;
+ }
+ }
+
+ return -EPIPE;
+}
+
+/**
+ * virtio_usb_hs_hub_control() - VirtIO USB High speed hub control request.
+ * @hcd: usb_hcd the request is for
+ * @type: Request type (bRequest combined with bmRequestType)
+ * @wValue: Request wValue
+ * @wIndex: Request wIndex, the port number for port requests
+ * @buffer: Buffer for the request data
+ * @wLength: Length of @buffer
+ *
+ * Return: 0 on success, -EPIPE for an unsupported request or port.
+ */
+static int virtio_usb_hs_hub_control(struct usb_hcd *hcd, u16 type, u16 wValue,
+ u16 wIndex, char *buffer, u16 wLength)
+{
+ struct virtio_usb_hc_vp *vhcd_vp = vhcd_get(hcd);
+ struct virtio_usb_hc_port *port;
+ unsigned long iflags;
+ int rc = 0;
+
+ switch (type) {
+ case ClearPortFeature:
+ port = virtio_usb_windex_to_port(vhcd_vp, wIndex);
+ if (!port)
+ return -EPIPE;
+
+ spin_lock_irqsave(&port->lock, iflags);
+ switch (wValue) {
+ case USB_PORT_FEAT_ENABLE:
+ if (port->hs.status.bits.enable) {
+ port->hs.status.bits.enable = 0;
+ port->hs.change.bits.enable = 1;
+ }
+ break;
+ case USB_PORT_FEAT_C_CONNECTION:
+ port->hs.change.bits.connect = 0;
+ break;
+ case USB_PORT_FEAT_C_ENABLE:
+ port->hs.change.bits.enable = 0;
+ break;
+ case USB_PORT_FEAT_C_RESET:
+ port->hs.change.bits.reset = 0;
+ break;
+ default:
+ rc = -EPIPE;
+ break;
+ }
+ spin_unlock_irqrestore(&port->lock, iflags);
+ break;
+ case SetPortFeature:
+ port = virtio_usb_windex_to_port(vhcd_vp, wIndex);
+ if (!port)
+ return -EPIPE;
+
+ spin_lock_irqsave(&port->lock, iflags);
+ switch (wValue) {
+ case USB_PORT_FEAT_RESET:
+ if (!port->hs.status.bits.enable) {
+ port->hs.status.bits.enable = 1;
+ port->hs.change.bits.enable = 1;
+ }
+ port->hs.change.bits.reset = 1;
+ break;
+ case USB_PORT_FEAT_POWER:
+ port->hs.status.bits.power = 1;
+ break;
+ default:
+ rc = -EPIPE;
+ break;
+ }
+ spin_unlock_irqrestore(&port->lock, iflags);
+ break;
+ default:
+ rc = virtio_usb_hub_control(hcd, type, wValue, wIndex, buffer,
+ wLength, false);
+ break;
+ }
+
+ return rc;
+}
+
+/* Super speed root hub device descriptor */
+static struct {
+ struct usb_bos_descriptor bos;
+ struct usb_ss_cap_descriptor ss_cap;
+} __packed ss_bos_desc = {
+ .bos = {
+ .bLength = USB_DT_BOS_SIZE,
+ .bDescriptorType = USB_DT_BOS,
+ .wTotalLength = cpu_to_le16(sizeof(ss_bos_desc)),
+ .bNumDeviceCaps = 1,
+ },
+ .ss_cap = {
+ .bLength = USB_DT_USB_SS_CAP_SIZE,
+ .bDescriptorType = USB_DT_DEVICE_CAPABILITY,
+ .bDevCapabilityType = USB_SS_CAP_TYPE,
+ .bmAttributes = 0x00,
+ .wSpeedSupported = cpu_to_le16(USB_5GBPS_OPERATION),
+ .bFunctionalitySupport = ilog2(USB_5GBPS_OPERATION),
+ .bU1devExitLat = 0x00,
+ .bU2DevExitLat = 0x00,
+ },
+};
+
+/**
+ * virtio_usb_ss_hub_control() - VirtIO USB Super speed hub control request.
+ * @hcd: usb_hcd the request is for
+ * @type: Request type (bRequest combined with bmRequestType)
+ * @wValue: Request wValue
+ * @wIndex: Request wIndex, the port number for port requests
+ * @buffer: Buffer for the request data
+ * @wLength: Length of @buffer
+ *
+ * Return: 0 on success, -EPIPE for an unsupported request or port.
+ */
+static int virtio_usb_ss_hub_control(struct usb_hcd *hcd, u16 type, u16 wValue,
+ u16 wIndex, char *buffer, u16 wLength)
+{
+ struct virtio_usb_hc_vp *vhcd_vp = vhcd_get(hcd);
+ struct virtio_usb_hc_port *port;
+ unsigned long iflags;
+ int rc = 0;
+
+ switch (type) {
+ case ClearPortFeature:
+ port = virtio_usb_windex_to_port(vhcd_vp, wIndex);
+ if (!port)
+ return -EPIPE;
+
+ spin_lock_irqsave(&port->lock, iflags);
+ switch (wValue) {
+ case USB_PORT_FEAT_C_CONNECTION:
+ port->ss.change.bits.connect = 0;
+ break;
+ case USB_PORT_FEAT_C_RESET:
+ port->ss.change.bits.reset = 0;
+ break;
+ case USB_PORT_FEAT_C_PORT_LINK_STATE:
+ port->ss.change.bits.link_state = 0;
+ break;
+ case USB_PORT_FEAT_C_BH_PORT_RESET:
+ port->ss.change.bits.bh_reset = 0;
+ break;
+ default:
+ rc = -EPIPE;
+ break;
+ }
+ spin_unlock_irqrestore(&port->lock, iflags);
+ break;
+ case DeviceRequest | USB_REQ_GET_DESCRIPTOR: {
+ u8 dtype = (wValue >> 8) & 0xff;
+
+ if (dtype == USB_DT_BOS) {
+ u16 bos_length = sizeof(ss_bos_desc);
+
+ if (bos_length > wLength)
+ bos_length = wLength;
+
+ memcpy(buffer, &ss_bos_desc, bos_length);
+
+ rc = bos_length;
+ } else {
+ rc = -EPIPE;
+ }
+
+ break;
+ }
+ case SetPortFeature: {
+ port = virtio_usb_windex_to_port(vhcd_vp, wIndex);
+ if (!port)
+ return -EPIPE;
+
+ spin_lock_irqsave(&port->lock, iflags);
+ switch (wValue) {
+ case USB_PORT_FEAT_RESET:
+ case USB_PORT_FEAT_BH_PORT_RESET:
+ port->ss.status.bits.enable = 1;
+
+ if (port->ss.status.bits.link_state != 0x00) {
+ port->ss.status.bits.link_state = 0x00;
+ port->ss.change.bits.link_state = 1;
+ }
+
+ port->ss.status.bits.reset = 0;
+ port->ss.change.bits.reset = 1;
+
+ if (wValue == USB_PORT_FEAT_BH_PORT_RESET)
+ port->ss.change.bits.bh_reset = 1;
+
+ break;
+ case USB_PORT_FEAT_POWER:
+ port->ss.status.bits.power = 1;
+ break;
+ default:
+ rc = -EPIPE;
+ break;
+ }
+ spin_unlock_irqrestore(&port->lock, iflags);
+ break;
+ }
+ default:
+ rc = virtio_usb_hub_control(hcd, type, wValue, wIndex, buffer,
+ wLength, true);
+ break;
+ }
+
+ return rc;
+}
+
+/* virtio usb host controller priv structure */
+struct virtio_usb_hc_priv {
+ struct virtio_usb_hc_port *port;
+ struct urb *urb;
+ struct scatterlist *sgs;
+ /* true once the request has been placed on the data virtqueue.
+ * Protected by port->lock.
+ */
+ bool submitted;
+ /* set by virtio_usb_hc_dequeue() when it was called before the
+ * request reached the data virtqueue; the enqueue path sends the
+ * HOST_CANCEL instead. Protected by port->lock.
+ */
+ bool cancel_pending;
+ /* true once the URB has been unlinked and given back, after which
+ * priv->urb must not be dereferenced anymore. Protected by
+ * port->lock.
+ */
+ bool completed;
+ /* Tag of this submission, see virtio_usb_data_tag_next(). */
+ u64 tag;
+};
+
+/**
+ * virtio_usb_hc_complete_urb() - Completes a URB
+ * @vurb: virtio_usb_data message.
+ *
+ * Context: Process context.
+ */
+static void virtio_usb_hc_complete_urb(struct virtio_usb_data *vurb)
+{
+ struct virtio_usb_hc_priv *priv =
+ (struct virtio_usb_hc_priv *)vurb->priv;
+ struct virtio_usb_response *response;
+ struct virtio_usb_iso_status *iso_urb_status;
+ struct virtio_usb_hc_port *port = priv->port;
+ struct urb *urb = priv->urb;
+ struct usb_hcd *hcd;
+ unsigned long flags;
+ int i;
+ unsigned int status;
+
+ if (unlikely(!urb || !urb->dev || !urb->dev->bus)) {
+ kfree(priv->sgs);
+ virtio_usb_data_unref(vurb);
+ return;
+ }
+
+ hcd = bus_to_hcd(urb->dev->bus);
+
+ response = virtio_usb_data_response(vurb);
+
+ status = le32_to_cpu(response->status);
+
+ spin_lock_irqsave(&port->lock, flags);
+
+ usb_hcd_unlink_urb_from_ep(hcd, urb);
+ urb->hcpriv = NULL;
+ priv->completed = true;
+ list_del(&vurb->list);
+
+ spin_unlock_irqrestore(&port->lock, flags);
+
+ urb->status = virtio_error_to_usb(status);
+ urb->actual_length = le32_to_cpu(response->actual_length);
+ if (urb->status == -EINVAL)
+ dev_err(&urb->dev->dev,
+ "URB ep%02x status -EINVAL from virtio status %u actual=%d\n",
+ urb->ep->desc.bEndpointAddress, status,
+ urb->actual_length);
+
+ if (usb_pipeisoc(urb->pipe) || usb_pipeint(urb->pipe))
+ urb->interval = le32_to_cpu(response->interval);
+
+ if (usb_pipeisoc(urb->pipe)) {
+ iso_urb_status = (void *)response + sizeof(*response);
+
+ for (i = 0; i < urb->number_of_packets; i++) {
+ struct virtio_usb_iso_status *iso_status =
+ &iso_urb_status[i];
+ status = le32_to_cpu(iso_status->status);
+
+ urb->iso_frame_desc[i].actual_length =
+ le32_to_cpu(iso_status->actual_length);
+ urb->iso_frame_desc[i].status =
+ virtio_error_to_usb(status);
+
+ if (iso_status->status)
+ urb->error_count++;
+ }
+
+ urb->start_frame = le32_to_cpu(response->start_frame);
+ }
+ local_bh_disable();
+ usb_hcd_giveback_urb(hcd, urb, urb->status);
+ local_bh_enable();
+ kfree(priv->sgs);
+ virtio_usb_data_unref(vurb);
+}
+
+/**
+ * virtio_usb_hc_set_urb_sgs() - Set urb sgs when total sg elements > 1.
+ * @priv: Host controller data of the request
+ * @gfp: Kernel flags for memory allocation.
+ *
+ * If the URB's scatterlist is longer than its transfer buffer, build a
+ * trimmed copy in @priv->sgs.
+ *
+ * Return: the scatterlist to use, or NULL on allocation failure.
+ */
+static struct scatterlist *
+virtio_usb_hc_set_urb_sgs(struct virtio_usb_hc_priv *priv, gfp_t gfp)
+{
+ struct scatterlist *sg = NULL, *sgs = NULL;
+ struct urb *urb = priv->urb;
+ unsigned int nsgs, i = 0;
+ unsigned int buffer_length = urb->transfer_buffer_length;
+ unsigned int sg_length = 0;
+
+ nsgs = urb->num_sgs;
+
+ for_each_sg(urb->sg, sg, nsgs, i) {
+ sg_length += sg->length;
+ }
+ if (sg_length > buffer_length) {
+ sgs = kcalloc(nsgs, sizeof(*sgs), gfp);
+ if (!sgs)
+ return NULL;
+
+ sg_init_table(sgs, nsgs);
+
+ for_each_sg(urb->sg, sg, nsgs, i) {
+ sg_length = sg->length;
+
+ if (sg_length > buffer_length)
+ sg_length = buffer_length;
+
+ sg_set_page(&sgs[i], sg_page(sg), sg_length,
+ sg->offset);
+
+ buffer_length -= sg_length;
+ if (!buffer_length)
+ break;
+ }
+ priv->sgs = sgs;
+ return sgs;
+ }
+ return urb->sg;
+}
+
+/**
+ * virtio_usb_hc_data_alloc() - Allocates a virtio usb data for the host
+ * @port: VirtIO USB HC port
+ * @urb: The urb request
+ * @gfp: Kernel flags for memory allocation.
+ *
+ * Return: the allocated data message, or NULL on failure.
+ */
+static struct virtio_usb_data *
+virtio_usb_hc_data_alloc(struct virtio_usb_hc_port *port, struct urb *urb,
+ gfp_t gfp)
+{
+ struct virtio_usb_data *vurb;
+ struct virtio_usb_hc_priv *priv;
+ struct virtio_usb_request *request;
+ struct virtio_usb_response *response;
+ struct virtio_usb_iso_packet *iso_packet;
+ struct virtio_usb_iso_status *iso_status;
+ size_t request_size = sizeof(*request);
+ size_t response_size = sizeof(*response);
+ u16 ep, transfer_flags = 0;
+
+ if (usb_pipeisoc(urb->pipe)) {
+ request_size += sizeof(*iso_packet) * urb->number_of_packets;
+ response_size += sizeof(*iso_status) * urb->number_of_packets;
+ }
+
+ vurb = virtio_usb_data_alloc(request_size, response_size,
+ sizeof(struct virtio_usb_hc_priv), gfp);
+
+ if (!vurb)
+ return NULL;
+
+ priv = vurb->priv;
+ priv->port = port;
+ priv->urb = urb;
+ vurb->msg.queue = port->vhcd_vp->hcqs[VIRTIO_USB_VQ_DATA_IDX];
+
+ INIT_LIST_HEAD(&vurb->list);
+
+ request = virtio_usb_data_request(vurb);
+ response = virtio_usb_data_response(vurb);
+
+ response->status = cpu_to_le32(VIRTIO_USB_S_ERR_CANCELLED);
+
+ if (usb_pipeisoc(urb->pipe)) {
+ iso_packet = (void *)request + sizeof(*request);
+ iso_status = (void *)response + sizeof(*response);
+ }
+ priv->tag = virtio_usb_data_tag_next(port->vhcd_vp->vusb);
+ request->tag = cpu_to_le64(priv->tag);
+ ep = usb_pipeendpoint(urb->pipe);
+ if (usb_pipein(urb->pipe))
+ ep |= VIRTIO_USB_EP_DIR_IN;
+
+ request->endpoint = cpu_to_le16(ep);
+ request->vp_idx = cpu_to_le16((u16)port->vhcd_vp->vp_idx);
+ request->port = cpu_to_le16((u16)port->port_id);
+
+ if (urb->transfer_flags & URB_SHORT_NOT_OK)
+ transfer_flags |= VIRTIO_USB_FLAG_SHORT_NOT_OK;
+ if (urb->transfer_flags & URB_ISO_ASAP)
+ transfer_flags |= VIRTIO_USB_FLAG_ISO_ASAP;
+ if (urb->transfer_flags & URB_ZERO_PACKET)
+ transfer_flags |= VIRTIO_USB_FLAG_ZERO_PACKET;
+ request->transfer_flags = cpu_to_le16(transfer_flags);
+
+ switch (usb_pipetype(urb->pipe)) {
+ case PIPE_ISOCHRONOUS: {
+ int i;
+
+ request->transfer_type = cpu_to_le16(VIRTIO_USB_EP_ISOCHRONOUS);
+ request->iso.start_frame = cpu_to_le32(urb->start_frame);
+ request->iso.interval = cpu_to_le32(urb->interval);
+ request->iso.number_of_packets =
+ cpu_to_le32(urb->number_of_packets);
+
+ for (i = 0; i < urb->number_of_packets; i++) {
+ struct virtio_usb_iso_packet *packet = &iso_packet[i];
+
+ packet->offset =
+ cpu_to_le32(urb->iso_frame_desc[i].offset);
+ packet->length =
+ cpu_to_le32(urb->iso_frame_desc[i].length);
+ }
+
+ break;
+ }
+ case PIPE_INTERRUPT:
+ request->transfer_type = cpu_to_le16(VIRTIO_USB_EP_INTERRUPT);
+ request->interrupt.interval = cpu_to_le32(urb->interval);
+ break;
+ case PIPE_CONTROL:
+ request->transfer_type = cpu_to_le16(VIRTIO_USB_EP_CONTROL);
+ memcpy(request->control.setup, urb->setup_packet, 8);
+ break;
+ case PIPE_BULK:
+ request->transfer_type = cpu_to_le16(VIRTIO_USB_EP_BULK);
+ break;
+ }
+ return vurb;
+}
+
+/**
+ * virtio_usb_hc_cmd_alloc() - Allocate and initialize a host command message.
+ * @vusb: VirtIO usb device
+ * @vp_idx: Index of the VP the command is for
+ * @command: Command code (VIRTIO_USB_CMD_HOST_*)
+ * @gfp: Kernel flags for memory allocation.
+ *
+ * Return: the allocated command message, or NULL on failure.
+ */
+static struct virtio_usb_cmd *virtio_usb_hc_cmd_alloc(struct virtio_usb *vusb,
+ unsigned int vp_idx,
+ unsigned int command,
+ gfp_t gfp)
+{
+ size_t request_size = sizeof(struct virtio_usb_host_cmd_hdr);
+ size_t response_size = sizeof(struct virtio_usb_cmd_status);
+ struct virtio_usb_cmd *cmd;
+
+ switch (command) {
+ case VIRTIO_USB_CMD_HOST_CANCEL:
+ request_size = sizeof(struct virtio_usb_host_cmd_cancel);
+ break;
+ case VIRTIO_USB_CMD_HOST_STREAMS_ALLOC:
+ case VIRTIO_USB_CMD_HOST_STREAMS_FREE:
+ request_size = sizeof(struct virtio_usb_host_cmd_streams);
+ break;
+ default:
+ break;
+ }
+
+ cmd = virtio_usb_cmd_alloc(request_size, response_size, gfp);
+ if (cmd) {
+ struct virtio_usb_host_cmd_hdr *hdr =
+ virtio_usb_cmd_request(cmd);
+ struct virtio_usb_cmd_status *status =
+ virtio_usb_cmd_response(cmd);
+
+ hdr->code = cpu_to_le32(command);
+ cmd->msg.queue = vusb->vports[vp_idx]
+ .vhc->hcqs[VIRTIO_USB_VQ_COMMAND_IDX];
+ status->code = cpu_to_le32(VIRTIO_USB_S_ERR_CANCELLED);
+ }
+ return cmd;
+}
+
+/**
+ * virtio_usb_port_from_urb() - Look up the port for a URB.
+ * @hcd: usb_hcd the URB was submitted to
+ * @urb: The urb request
+ *
+ * urb->dev->portnum is the 1-based port number on the root hub, which
+ * equals port_id + 1. The HCD identifies which VP.
+ *
+ * Return: the port, or NULL if the slot is out of range.
+ */
+static struct virtio_usb_hc_port *virtio_usb_port_from_urb(struct usb_hcd *hcd,
+ struct urb *urb)
+{
+ struct virtio_usb_hc_vp *vhcd_vp = vhcd_get(hcd);
+ int slot = urb->dev->portnum - 1;
+
+ if (slot < 0 || slot >= VIRTIO_USB_VP_MAX_PORTS)
+ return NULL;
+ return &vhcd_vp->ports[slot];
+}
+
+/**
+ * virtio_usb_hc_cancel_send() - Send a HOST_CANCEL for a request.
+ * @vusb: VirtIO usb device
+ * @port: VirtIO USB HC port
+ * @vp_idx: Virtual port index
+ * @tag: Tag of the submission to cancel
+ * @gfp: Kernel flags for memory allocation.
+ *
+ * Context: Any context
+ * Return: 0 on success -errno on failure
+ */
+static int virtio_usb_hc_cancel_send(struct virtio_usb *vusb,
+ struct virtio_usb_hc_port *port,
+ unsigned int vp_idx, u64 tag, gfp_t gfp)
+{
+ struct virtio_usb_host_cmd_cancel *cancel;
+ struct virtio_usb_cmd *cmd;
+
+ cmd = virtio_usb_hc_cmd_alloc(vusb, vp_idx, VIRTIO_USB_CMD_HOST_CANCEL,
+ gfp);
+ if (!cmd)
+ return -ENOMEM;
+
+ cancel = virtio_usb_cmd_request(cmd);
+ cancel->hdr.port = cpu_to_le32(port->port_id);
+ cancel->tag = cpu_to_le64(tag);
+
+ return virtio_usb_cmd_send_async(vusb, NULL, NULL, cmd);
+}
+
+/**
+ * virtio_usb_hc_enqueue() - Enqueue a URB.
+ * @hcd: USB host controller device
+ * @urb: URB
+ * @mem_flags: Kernel flags for memory allocation.
+ *
+ * Context: Any context
+ * Return: 0 on success -errno on failure
+ */
+static int virtio_usb_hc_enqueue(struct usb_hcd *hcd, struct urb *urb,
+ gfp_t mem_flags)
+{
+ struct virtio_usb_hc_vp *vhcd_vp = vhcd_get(hcd);
+ struct virtio_usb *vusb = vhcd_vp->vusb;
+ struct virtio_usb_hc_port *port;
+ struct virtio_usb_data *vurb;
+ struct virtio_usb_hc_priv *priv;
+ struct scatterlist sg;
+ struct scatterlist *psg_data = &sg, *out_sgs = NULL, *in_sgs = NULL;
+ unsigned long flags;
+ bool cancel_pending;
+ int rc = 0;
+
+ port = virtio_usb_port_from_urb(hcd, urb);
+ if (!port)
+ return -ENODEV;
+
+ vurb = virtio_usb_hc_data_alloc(port, urb, mem_flags);
+ if (!vurb)
+ return -ENOMEM;
+ priv = vurb->priv;
+
+ if (urb->transfer_buffer) {
+ sg_init_one(psg_data, urb->transfer_buffer,
+ urb->transfer_buffer_length);
+ } else if (urb->num_sgs > 1) {
+ psg_data = virtio_usb_hc_set_urb_sgs(priv, mem_flags);
+ if (!psg_data) {
+ rc = -ENOMEM;
+ goto on_exit;
+ }
+ } else if (urb->transfer_buffer_length && urb->sg) {
+ sg_init_one(psg_data, sg_virt(urb->sg),
+ urb->transfer_buffer_length);
+ } else {
+ psg_data = NULL;
+ }
+
+ spin_lock_irqsave(&port->lock, flags);
+ rc = usb_hcd_link_urb_to_ep(port_vhcd_get(port), urb);
+ if (rc) {
+ spin_unlock_irqrestore(&port->lock, flags);
+ goto on_exit;
+ }
+ urb->hcpriv = vurb;
+ list_add_tail(&vurb->list, &port->pending_urb_list);
+ spin_unlock_irqrestore(&port->lock, flags);
+
+ if (usb_pipeout(urb->pipe))
+ out_sgs = psg_data;
+ else
+ in_sgs = psg_data;
+
+ /*
+ * virtio_usb_hc_dequeue() may run as soon as urb->hcpriv is visible,
+ * i.e. before the request reaches the data virtqueue. A HOST_CANCEL
+ * sent that early would be unmatched on the device side, replied to
+ * with success and dropped, and the URB submitted right after would
+ * never be cancelled - usb_kill_urb() would wait forever. In that
+ * case dequeue only records the cancel and this path sends it once
+ * the request is actually queued.
+ *
+ * Hold a reference across the window: without it the request could
+ * be completed and freed between virtio_usb_data_send() and the
+ * check below.
+ */
+ virtio_usb_data_ref(vurb);
+
+ rc = virtio_usb_data_send(vusb, vurb, out_sgs, in_sgs);
+ if (rc) {
+ virtio_usb_data_unref(vurb);
+ goto on_error_vq;
+ }
+
+ spin_lock_irqsave(&port->lock, flags);
+ priv->submitted = true;
+ /* Only cancel if the request has not been completed yet: once it has,
+ * the URB is already given back and the device side has nothing left
+ * to cancel.
+ */
+ cancel_pending = priv->cancel_pending && !priv->completed;
+ spin_unlock_irqrestore(&port->lock, flags);
+
+ if (cancel_pending)
+ (void)virtio_usb_hc_cancel_send(vusb, port, vhcd_vp->vp_idx,
+ priv->tag, GFP_ATOMIC);
+
+ virtio_usb_data_unref(vurb);
+
+ return 0;
+
+on_error_vq:
+ spin_lock_irqsave(&port->lock, flags);
+ usb_hcd_unlink_urb_from_ep(port_vhcd_get(port), urb);
+ urb->hcpriv = NULL;
+ list_del(&vurb->list);
+ spin_unlock_irqrestore(&port->lock, flags);
+
+on_exit:
+ kfree(priv->sgs);
+ virtio_usb_data_unref(vurb);
+ return rc;
+}
+
+/**
+ * virtio_usb_hc_dequeue() - Dequeue a URB.
+ * @hcd: USB host controller device
+ * @urb: URB
+ * @status: status of the URB.
+ *
+ * Context: Any context
+ * Return: 0 on success -errno on failure
+ */
+static int virtio_usb_hc_dequeue(struct usb_hcd *hcd, struct urb *urb,
+ int status)
+{
+ struct virtio_usb_hc_vp *vhcd_vp = vhcd_get(hcd);
+ struct virtio_usb *vusb = vhcd_vp->vusb;
+ struct virtio_usb_hc_port *port;
+ struct virtio_usb_hc_priv *priv;
+ struct virtio_usb_data *vurb;
+ int rc;
+ unsigned long flags;
+ u64 tag;
+
+ port = virtio_usb_port_from_urb(hcd, urb);
+ if (!port)
+ return -ENODEV;
+
+ spin_lock_irqsave(&port->lock, flags);
+
+ vurb = urb->hcpriv;
+ if (!vurb) {
+ spin_unlock_irqrestore(&port->lock, flags);
+ return -EIDRM;
+ }
+
+ rc = usb_hcd_check_unlink_urb(port_vhcd_get(port), urb, status);
+ if (rc) {
+ spin_unlock_irqrestore(&port->lock, flags);
+ return rc;
+ }
+
+ /*
+ * urb->hcpriv is published before the request is placed on the data
+ * virtqueue, so the request may not be visible to the device yet. A
+ * HOST_CANCEL sent now would not match anything, would be answered
+ * with success and dropped, and the URB submitted right after would
+ * run to completion with nobody waiting for it. Let the enqueue path
+ * send the cancel once the request is queued.
+ */
+ priv = vurb->priv;
+ if (!priv->submitted) {
+ priv->cancel_pending = true;
+ spin_unlock_irqrestore(&port->lock, flags);
+ return 0;
+ }
+ /* The request may complete and be freed once the lock is dropped. */
+ tag = priv->tag;
+ spin_unlock_irqrestore(&port->lock, flags);
+
+ return virtio_usb_hc_cancel_send(vusb, port, vhcd_vp->vp_idx, tag,
+ GFP_ATOMIC);
+}
+
+/**
+ * virtio_usb_hc_get_frame() - Get the current hw frame number
+ * @hcd: usb_hcd
+ *
+ * Return: always 0, there is no frame counter.
+ */
+static int virtio_usb_hc_get_frame(struct usb_hcd *hcd)
+{
+ return 0;
+}
+
+/* Virtio USB high speed host controller driver */
+static struct hc_driver virtio_usb_hs_hc_driver = {
+ .description = "virtio-usb-hc",
+ .product_desc = "VirtIO USB2 Host Controller",
+ .hcd_priv_size = sizeof(void *),
+ .flags = HCD_USB2 | HCD_SHARED,
+
+ .reset = virtio_usb_hc_reset,
+ .start = virtio_usb_hc_start,
+ .stop = virtio_usb_hc_stop,
+
+ .hub_status_data = virtio_usb_hs_hub_status_data,
+ .hub_control = virtio_usb_hs_hub_control,
+
+ .urb_enqueue = virtio_usb_hc_enqueue,
+ .urb_dequeue = virtio_usb_hc_dequeue,
+
+ .get_frame_number = virtio_usb_hc_get_frame,
+};
+
+/* Virtio USB super speed host controller driver */
+static struct hc_driver virtio_usb_ss_hc_driver = {
+ .description = "virtio-usb-hc",
+ .product_desc = "VirtIO USB3 Host Controller",
+ .hcd_priv_size = sizeof(void *),
+ .flags = HCD_USB3 | HCD_SHARED,
+
+ .reset = virtio_usb_hc_reset,
+ .start = virtio_usb_hc_start,
+ .stop = virtio_usb_hc_stop,
+
+ .hub_status_data = virtio_usb_ss_hub_status_data,
+ .hub_control = virtio_usb_ss_hub_control,
+
+ .urb_enqueue = virtio_usb_hc_enqueue,
+ .urb_dequeue = virtio_usb_hc_dequeue,
+
+ .get_frame_number = virtio_usb_hc_get_frame,
+};
+
+/**
+ * virtio_usb_add_hcd() - Add HS and SS HCDs for one VP.
+ * @vusb: VirtIO usb device.
+ * @vhcd_vp: per-VP host controller to populate.
+ *
+ * Return: 0 on success, -errno on failure.
+ */
+static int virtio_usb_add_hcd(struct virtio_usb *vusb,
+ struct virtio_usb_hc_vp *vhcd_vp)
+{
+ struct virtio_device *vdev = vusb->vdev;
+ struct device *dev = &vdev->dev;
+ const char *name;
+ int rc;
+
+ /* usb_create_hcd()/usb_create_shared_hcd() store this pointer as-is
+ * in hcd->self.bus_name (no copy is made) - it must stay valid for
+ * the lifetime of the HCD, so it cannot be a stack buffer. Allocate
+ * it from the parent virtio device, which outlives the HCDs.
+ */
+ name = devm_kasprintf(&vusb->vdev->dev, GFP_KERNEL, "%s-vp%u",
+ dev_name(dev), vhcd_vp->vp_idx);
+ if (!name)
+ return -ENOMEM;
+
+ vhcd_vp->hs = usb_create_hcd(&virtio_usb_hs_hc_driver, dev, name);
+ if (!vhcd_vp->hs)
+ return -ENOMEM;
+
+ vhcd_set(vhcd_vp->hs, vhcd_vp);
+
+ vhcd_vp->hs->skip_phy_initialization = 1;
+ rc = usb_add_hcd(vhcd_vp->hs, 0, 0);
+ if (rc)
+ goto on_put_hs;
+
+ vhcd_vp->ss = usb_create_shared_hcd(&virtio_usb_ss_hc_driver, dev, name,
+ vhcd_vp->hs);
+ if (!vhcd_vp->ss) {
+ rc = -ENOMEM;
+ goto on_remove_hs;
+ }
+
+ vhcd_set(vhcd_vp->ss, vhcd_vp);
+
+ vhcd_vp->ss->skip_phy_initialization = 1;
+ rc = usb_add_hcd(vhcd_vp->ss, 0, 0);
+ if (rc)
+ goto on_put_ss;
+
+ return 0;
+
+on_put_ss:
+ usb_put_hcd(vhcd_vp->ss);
+on_remove_hs:
+ usb_remove_hcd(vhcd_vp->hs);
+on_put_hs:
+ usb_put_hcd(vhcd_vp->hs);
+
+ return rc;
+}
+
+/**
+ * virtio_usb_hc_event_populate() - Add events to the host event queue.
+ * @vusb: VirtIO USB device
+ *
+ * Context: Any context.
+ * Return: 0 on success -errno on failure
+ */
+int virtio_usb_hc_event_populate(struct virtio_usb *vusb)
+{
+ /* The host event queue is shared across every host-role VP and
+ * lives at the struct virtio_usb level - not owned by any single
+ * VP - since a host-role VP may not exist yet (e.g. a dual-role
+ * instance where every port currently reports device role).
+ */
+ struct virtio_usb_queue *evt_queue =
+ &vusb->vqueues[vusb->host_vq_base + VIRTIO_USB_VQ_EVENT_IDX];
+ struct virtio_usb_event *events;
+
+ events = virtio_usb_events_alloc(
+ vusb, evt_queue, sizeof(struct virtio_usb_host_port_event));
+
+ return virtio_usb_events_populate(events);
+}
+
+/**
+ * virtio_usb_hc_rx_work() - Worker to drain completed data messages.
+ * @work: kernel work item embedded in struct virtio_usb.
+ *
+ * The data virtqueue is shared across all host-role VPs, so the work
+ * item that drains it lives on struct virtio_usb itself instead of on
+ * any single VP (mirrors vq_dev_data_rx_work on the device-role side).
+ *
+ * Context: Process context.
+ */
+void virtio_usb_hc_rx_work(struct work_struct *work)
+{
+ struct virtio_usb *vusb =
+ container_of(work, struct virtio_usb, vq_host_data_rx_work);
+ struct virtio_usb_queue *dataq =
+ &vusb->vqueues[vusb->host_vq_base + VIRTIO_USB_VQ_DATA_IDX];
+ u32 length;
+ struct virtio_usb_data *vurb;
+
+ spin_lock_irq(&dataq->lock);
+ do {
+ virtqueue_disable_cb(dataq->vqueue);
+ while ((vurb = virtqueue_get_buf(dataq->vqueue, &length))) {
+ spin_unlock_irq(&dataq->lock);
+ virtio_usb_hc_complete_urb(vurb);
+ spin_lock_irq(&dataq->lock);
+ }
+ if (unlikely(virtqueue_is_broken(dataq->vqueue)))
+ break;
+ } while (!virtqueue_enable_cb(dataq->vqueue));
+ spin_unlock_irq(&dataq->lock);
+}
+
+/**
+ * virtio_usb_hc_vp_init() - Initialize the host controller for one VP.
+ * @vusb: VirtIO USB device
+ * @vp_idx: VP index (0..nports-1)
+ *
+ * Context: Any context.
+ * Return: 0 on success -errno on failure
+ */
+int virtio_usb_hc_vp_init(struct virtio_usb *vusb, unsigned int vp_idx)
+{
+ struct virtio_usb_hc_vp *vhcd_vp;
+ unsigned int i;
+ int rc;
+
+ vhcd_vp = devm_kzalloc(&vusb->vdev->dev, sizeof(*vhcd_vp), GFP_KERNEL);
+ if (!vhcd_vp)
+ return -ENOMEM;
+
+ vhcd_vp->vusb = vusb;
+ vhcd_vp->vp_idx = vp_idx;
+ spin_lock_init(&vhcd_vp->lock);
+
+ /* Pre-allocate all port structs. Reused across connect/disconnect. */
+ for (i = 0; i < VIRTIO_USB_VP_MAX_PORTS; i++) {
+ struct virtio_usb_hc_port *port = &vhcd_vp->ports[i];
+
+ port->vhcd_vp = vhcd_vp;
+ INIT_LIST_HEAD(&port->pending_urb_list);
+ spin_lock_init(&port->lock);
+ port->port_id = i;
+ port->ss.status.bits.link_state = 0x05; /* RX_DETECT */
+ }
+ 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;
+
+ /* Add HCDs first so hs/ss are valid before any PORT_CONNECTED event */
+ rc = virtio_usb_add_hcd(vusb, vhcd_vp);
+ if (rc) {
+ vusb->vports[vp_idx].vhc = NULL;
+ return rc;
+ }
+
+ return 0;
+}
+
+/**
+ * virtio_usb_hc_vp_deinit() - Deinitialize the host controller for one VP.
+ * @vusb: VirtIO USB device
+ * @vp_idx: VP index
+ *
+ * Return: always 0.
+ */
+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;
+
+ if (!vhcd_vp)
+ return 0;
+
+ usb_remove_hcd(vhcd_vp->ss);
+ usb_put_hcd(vhcd_vp->ss);
+ usb_remove_hcd(vhcd_vp->hs);
+ usb_put_hcd(vhcd_vp->hs);
+
+ vhcd_vp->ss = NULL;
+ vhcd_vp->hs = NULL;
+
+ vusb->vports[vp_idx].vhc = NULL;
+ return 0;
+}
+
+/**
+ * virtio_usb_hc_evt_process_one() - Process a single host port event.
+ * @uevent: VirtIO usb host controller event.
+ *
+ * Context: Process context (called from virtio_usb_hc_evt_work()).
+ */
+static void virtio_usb_hc_evt_process_one(struct virtio_usb_event *uevent)
+{
+ struct virtio_usb *vusb = uevent->vusb;
+ 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);
+ port_id = le32_to_cpu(evt->port);
+
+ if (vp_idx >= vusb->nports || !vusb->vports) {
+ dev_err_ratelimited(
+ &vusb->vdev->dev,
+ "virtio_usb: PORT event vp_idx %u invalid (nports=%u), ignoring\n",
+ vp_idx, vusb->nports);
+ return;
+ }
+
+ if (port_id >= VIRTIO_USB_VP_MAX_PORTS) {
+ dev_err_ratelimited(
+ &vusb->vdev->dev,
+ "virtio_usb: PORT event port_id %u >= VP_MAX_PORTS %u, ignoring\n",
+ port_id, VIRTIO_USB_VP_MAX_PORTS);
+ return;
+ }
+
+ 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);
+ return;
+ }
+
+ port = &vhcd_vp->ports[port_id];
+
+ spin_lock_irqsave(&port->lock, iflags);
+ switch (le32_to_cpu(evt->code)) {
+ case VIRTIO_USB_EVT_HOST_PORT_CONNECTED:
+ /* Reinitialize the pre-allocated port struct in place */
+ memset(&port->hs, 0, sizeof(port->hs));
+ memset(&port->ss, 0, sizeof(port->ss));
+ port->ss.status.bits.link_state = 0x05; /* RX_DETECT */
+
+ switch (le32_to_cpu(evt->speed)) {
+ case USB_SPEED_SUPER_PLUS:
+ case USB_SPEED_SUPER:
+ port->ss.status.bits.connect = 1;
+ port->ss.status.bits.enable = 1;
+ port->ss.status.bits.link_state = 0x00; /* U0 */
+ port->ss.change.bits.connect = 1;
+ port->ss.change.bits.link_state = 1;
+ hcd = vhcd_vp->ss;
+ break;
+ case USB_SPEED_HIGH:
+ case USB_SPEED_FULL:
+ case USB_SPEED_LOW:
+ port->hs.status.bits.connect = 1;
+ port->hs.change.bits.connect = 1;
+ if (le32_to_cpu(evt->speed) == USB_SPEED_HIGH)
+ port->hs.status.bits.high_speed = 1;
+ if (le32_to_cpu(evt->speed) == USB_SPEED_LOW)
+ port->hs.status.bits.low_speed = 1;
+ hcd = vhcd_vp->hs;
+ break;
+ default:
+ break;
+ }
+ port->speed = le32_to_cpu(evt->speed);
+ break;
+
+ case VIRTIO_USB_EVT_HOST_PORT_DISCONNECTED:
+ switch (port->speed) {
+ case USB_SPEED_SUPER_PLUS:
+ case USB_SPEED_SUPER:
+ port->ss.status.bits.connect = 0;
+ port->ss.status.bits.enable = 0;
+ port->ss.status.bits.link_state = 0x05; /* RX_DETECT */
+ port->ss.change.bits.connect = 1;
+ port->ss.change.bits.link_state = 1;
+ hcd = vhcd_vp->ss;
+ break;
+ case USB_SPEED_HIGH:
+ case USB_SPEED_FULL:
+ case USB_SPEED_LOW:
+ port->hs.status.bits.connect = 0;
+ port->hs.status.bits.enable = 0;
+ port->hs.status.bits.low_speed = 0;
+ port->hs.status.bits.high_speed = 0;
+ port->hs.change.bits.connect = 1;
+ port->hs.change.bits.enable = 1;
+ if (port->hs.status.bits.suspend) {
+ port->hs.status.bits.suspend = 0;
+ port->hs.change.bits.suspend = 1;
+ }
+ hcd = vhcd_vp->hs;
+ break;
+ default:
+ break;
+ }
+ port->speed = USB_SPEED_UNKNOWN;
+ break;
+ }
+ spin_unlock_irqrestore(&port->lock, iflags);
+
+ if (hcd)
+ usb_hcd_poll_rh_status(hcd);
+}
+
+/**
+ * virtio_usb_hc_evt_work() - Host event queue receive worker.
+ * @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.
+ *
+ * Context: Process context.
+ */
+void virtio_usb_hc_evt_work(struct work_struct *work)
+{
+ struct virtio_usb *vusb =
+ container_of(work, struct virtio_usb, vq_host_evt_work);
+ struct virtio_usb_queue *evtq =
+ &vusb->vqueues[vusb->host_vq_base + VIRTIO_USB_VQ_EVENT_IDX];
+
+ virtio_usb_evt_work(evtq, virtio_usb_hc_evt_process_one);
+}
+
+/**
+ * virtio_usb_hc_dataq_stop_cb() - Stop data virtqueue, force-complete all
+ * pending URBs with -ESHUTDOWN.
+ * @vusb: VirtIO usb device
+ * @dataq: Host data virtqueue
+ */
+static void virtio_usb_hc_dataq_stop_cb(struct virtio_usb *vusb,
+ struct virtio_usb_queue *dataq)
+{
+ struct virtio_usb_data *vurb, *vurb_tmp;
+ struct virtio_usb_hc_priv *priv;
+ struct usb_hcd *hcd;
+ unsigned int vp_idx, slot;
+ unsigned long flags;
+
+ virtio_usb_dataq_stop_cb(vusb, dataq);
+
+ if (!vusb->vports)
+ return;
+
+ /* The data virtqueue is shared across all host-role VPs, so the
+ * work item that drains it lives on struct virtio_usb itself.
+ */
+ 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;
+
+ if (!vhcd_vp)
+ continue;
+
+ for (slot = 0; slot < VIRTIO_USB_VP_MAX_PORTS; slot++) {
+ struct virtio_usb_hc_port *port = &vhcd_vp->ports[slot];
+ LIST_HEAD(giveback_list);
+
+ spin_lock_irqsave(&port->lock, flags);
+ list_for_each_entry_safe(
+ vurb, vurb_tmp, &port->pending_urb_list, list) {
+ priv = (struct virtio_usb_hc_priv *)vurb->priv;
+ priv->completed = true;
+ if (!priv->urb) {
+ list_move_tail(&vurb->list,
+ &giveback_list);
+ continue;
+ }
+ if (!priv->urb->dev) {
+ usb_hcd_unlink_urb_from_ep(
+ port_vhcd_get(port), priv->urb);
+ priv->urb->hcpriv = NULL;
+ list_move_tail(&vurb->list,
+ &giveback_list);
+ continue;
+ }
+ hcd = bus_to_hcd(priv->urb->dev->bus);
+ usb_hcd_unlink_urb_from_ep(hcd, priv->urb);
+ priv->urb->hcpriv = NULL;
+ list_move_tail(&vurb->list, &giveback_list);
+ }
+ spin_unlock_irqrestore(&port->lock, flags);
+
+ list_for_each_entry_safe(vurb, vurb_tmp, &giveback_list,
+ list) {
+ priv = (struct virtio_usb_hc_priv *)vurb->priv;
+ if (!priv->urb || !priv->urb->dev) {
+ list_del(&vurb->list);
+ kfree(priv->sgs);
+ virtio_usb_data_unref(vurb);
+ continue;
+ }
+ hcd = bus_to_hcd(priv->urb->dev->bus);
+ priv->urb->status = -ESHUTDOWN;
+ list_del(&vurb->list);
+ local_bh_disable();
+ usb_hcd_giveback_urb(hcd, priv->urb,
+ priv->urb->status);
+ local_bh_enable();
+ kfree(priv->sgs);
+ virtio_usb_data_unref(vurb);
+ }
+ }
+ }
+}
+
+/**
+ * virtio_usb_hc_evt_notify_cb() - Event virtqueue notification callback.
+ * @vqueue: Host event virtqueue
+ *
+ * Just schedules virtio_usb_hc_evt_work() - the actual event processing
+ * needs process context, since it may end up reading vhc concurrently
+ * with a role-switch-triggered virtio_usb_hc_vp_init()/_deinit(), which sleep.
+ *
+ * Context: Interrupt context.
+ */
+static void virtio_usb_hc_evt_notify_cb(struct virtqueue *vqueue)
+{
+ struct virtio_usb *vusb = vqueue->vdev->priv;
+
+ schedule_work(&vusb->vq_host_evt_work);
+}
+
+/**
+ * virtio_usb_hc_evtq_stop_cb() - Stop the host event virtqueue.
+ * @vusb: VirtIO usb device
+ * @vq: Host event virtqueue
+ *
+ * Do not process host port events during teardown - the vhc they'd
+ * reference may already be gone. Just cancel the (idempotent)
+ * work item and drain the used ring so del_vqs() finds it empty.
+ */
+static void virtio_usb_hc_evtq_stop_cb(struct virtio_usb *vusb,
+ struct virtio_usb_queue *vq)
+{
+ virtio_usb_evt_drain_stop_cb(vq, &vusb->vq_host_evt_work);
+}
+
+/**
+ * virtio_usb_host_data_notify_cb() - Data virtqueue notification callback.
+ * @vqueue: Host data virtqueue
+ *
+ * The data virtqueue is shared across all host-role VPs; the work item
+ * that drains it lives on struct virtio_usb, not on any specific VP.
+ */
+static void virtio_usb_host_data_notify_cb(struct virtqueue *vqueue)
+{
+ struct virtio_usb *vusb = vqueue->vdev->priv;
+
+ schedule_work(&vusb->vq_host_data_rx_work);
+}
+
+const struct virtio_usb_vq_desc host_vqueues[VIRTIO_USB_VQ_HOST_MAX] = {
+ [VIRTIO_USB_VQ_COMMAND_IDX] = {
+ .callback = virtio_usb_cmd_notify_cb,
+ .name = "virtusb-host-cmd",
+ .process = virtio_usb_cmd_process_cb,
+ .stop = virtio_usb_cmdq_stop_cb,
+ },
+ [VIRTIO_USB_VQ_EVENT_IDX] = {
+ .callback = virtio_usb_hc_evt_notify_cb,
+ .name = "virtusb-host-evt",
+ .process = NULL,
+ .stop = virtio_usb_hc_evtq_stop_cb,
+ },
+ [VIRTIO_USB_VQ_DATA_IDX] = {
+ .callback = virtio_usb_host_data_notify_cb,
+ .name = "virtusb-host-data",
+ .process = NULL,
+ .stop = virtio_usb_hc_dataq_stop_cb,
+ },
+};
diff --git a/drivers/usb/virtio_usb/host.h b/drivers/usb/virtio_usb/host.h
new file mode 100644
index 000000000000..58837d1f31c1
--- /dev/null
+++ b/drivers/usb/virtio_usb/host.h
@@ -0,0 +1,244 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+/*
+ * virtio_usb: VirtIO USB device
+ *
+ * Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.
+ */
+
+#ifndef VIRTIO_USB_HOST_H
+#define VIRTIO_USB_HOST_H
+
+#include <linux/slab.h>
+#include <linux/usb.h>
+#include <linux/usb/hcd.h>
+#include <linux/virtio.h>
+
+#include <linux/usb/ch11.h>
+#include <linux/usb/ch9.h>
+
+#include "controller.h"
+
+/**
+ * struct virtio_usb_port_hs_status - High speed port wPortStatus
+ * @connect: PORT_CONNECTION
+ * @enable: PORT_ENABLE
+ * @suspend: PORT_SUSPEND
+ * @over_current: PORT_OVER_CURRENT
+ * @reset: PORT_RESET
+ * @reserved0: Reserved
+ * @power: PORT_POWER
+ * @low_speed: PORT_LOW_SPEED
+ * @high_speed: PORT_HIGH_SPEED
+ * @test_mode: PORT_TEST
+ * @indicator_control: PORT_INDICATOR
+ * @reserved1: Reserved
+ *
+ * See USB 2.0 spec Table 11-21.
+ */
+struct virtio_usb_port_hs_status {
+ u16 connect : 1;
+ u16 enable : 1;
+ u16 suspend : 1;
+ u16 over_current : 1;
+ u16 reset : 1;
+ u16 reserved0 : 3;
+ u16 power : 1;
+ u16 low_speed : 1;
+ u16 high_speed : 1;
+ u16 test_mode : 1;
+ u16 indicator_control : 1;
+ u16 reserved1 : 3;
+};
+
+/**
+ * struct virtio_usb_port_hs_change - High speed port wPortChange
+ * @connect: C_PORT_CONNECTION
+ * @enable: C_PORT_ENABLE
+ * @suspend: C_PORT_SUSPEND
+ * @over_current: C_PORT_OVER_CURRENT
+ * @reset: C_PORT_RESET
+ * @reserved: Reserved
+ *
+ * See USB 2.0 spec Table 11-22.
+ */
+struct virtio_usb_port_hs_change {
+ u16 connect : 1;
+ u16 enable : 1;
+ u16 suspend : 1;
+ u16 over_current : 1;
+ u16 reset : 1;
+ u16 reserved : 11;
+};
+
+/**
+ * struct virtio_usb_port_ss_status - Super speed port wPortStatus
+ * @connect: PORT_CONNECTION
+ * @enable: PORT_ENABLE
+ * @reserved0: Reserved
+ * @over_current: PORT_OVER_CURRENT
+ * @reset: PORT_RESET
+ * @link_state: PORT_LINK_STATE
+ * @power: PORT_POWER
+ * @speed: Negotiated speed
+ * @reserved1: Reserved
+ *
+ * See USB 3.1 spec Table 10-13.
+ */
+struct virtio_usb_port_ss_status {
+ u16 connect : 1;
+ u16 enable : 1;
+ u16 reserved0 : 1;
+ u16 over_current : 1;
+ u16 reset : 1;
+ u16 link_state : 4;
+ u16 power : 1;
+ u16 speed : 3;
+ u16 reserved1 : 3;
+};
+
+/**
+ * struct virtio_usb_port_ss_change - Super speed port wPortChange
+ * @connect: C_PORT_CONNECTION
+ * @reserved0: Reserved
+ * @over_current: C_PORT_OVER_CURRENT
+ * @reset: C_PORT_RESET
+ * @bh_reset: C_BH_PORT_RESET
+ * @link_state: C_PORT_LINK_STATE
+ * @config_error: C_PORT_CONFIG_ERROR
+ * @reserved1: Reserved
+ *
+ * See USB 3.1 spec Table 10-14.
+ */
+struct virtio_usb_port_ss_change {
+ u16 connect : 1;
+ u16 reserved0 : 2;
+ u16 over_current : 1;
+ u16 reset : 1;
+ u16 bh_reset : 1;
+ u16 link_state : 1;
+ u16 config_error : 1;
+ u16 reserved1 : 8;
+};
+
+/**
+ * struct virtio_usb_hc_port - VirtIO USB host controller port.
+ *
+ * One slot in a VP's root hub. Pre-allocated at VP init time and reused
+ * across connect/disconnect cycles - never dynamically freed.
+ *
+ * @vhcd_vp: Per-VP host controller this port belongs to
+ * @pending_urb_list: Pending URB list to the port
+ * @speed: Speed of current device connected to the port
+ * @port_id: Slot index within the VP (0..VIRTIO_USB_VP_MAX_PORTS-1)
+ * @lock: Spinlock that protects fields shared by interrupt handlers and
+ * hcd operation callback
+ * @hs: High speed Port Status and Port Change structure
+ * @ss: Super speed Port Status and Port Change structure
+ */
+struct virtio_usb_hc_port {
+ struct virtio_usb_hc_vp *vhcd_vp;
+ struct list_head pending_urb_list;
+ enum usb_device_speed speed;
+ u32 port_id;
+ spinlock_t lock;
+ struct {
+ /* USB 2.0 port status bits */
+ union {
+ struct virtio_usb_port_hs_status bits;
+ u16 value;
+ } status;
+ /* USB 2.0 port status change bits */
+ union {
+ struct virtio_usb_port_hs_change bits;
+ u16 value;
+ } change;
+ } hs;
+ struct {
+ /* USB 3.0 port status bits */
+ union {
+ struct virtio_usb_port_ss_status bits;
+ u16 value;
+ } status;
+ /* USB 3.0 port status change bits */
+ union {
+ struct virtio_usb_port_ss_change bits;
+ u16 value;
+ } change;
+ } ss;
+};
+
+/**
+ * struct virtio_usb_hc_vp - Per-VP VirtIO USB Host controller.
+ *
+ * One instance per host-role virtual port (physical USB socket).
+ * Pointed to by virtio_usb_port.vhc - NULL for device-role VPs,
+ * mirroring how virtio_usb_port.vudc works for device-role VPs.
+ *
+ * All VIRTIO_USB_VP_MAX_PORTS port structs are pre-allocated at init
+ * time and reused across connect/disconnect cycles.
+ *
+ * @vusb: VirtIO usb device
+ * @vp_idx: Index of this VP in vusb->vports[]
+ * @hs: High speed usb_hcd for this VP
+ * @ss: Super speed usb_hcd for this VP
+ * @ports: Pre-allocated port state array, one entry per slot
+ * @hcqs: Host virtqueue wrappers, indexed by VIRTIO_USB_VQ_*_IDX
+ * (shared across VPs)
+ * @lock: Spinlock protecting HC state for this VP
+ */
+struct virtio_usb_hc_vp {
+ struct virtio_usb *vusb;
+ unsigned int vp_idx;
+ struct usb_hcd *hs;
+ struct usb_hcd *ss;
+ struct virtio_usb_hc_port ports[VIRTIO_USB_VP_MAX_PORTS];
+ struct virtio_usb_queue *hcqs[VIRTIO_USB_VQ_HOST_MAX];
+ spinlock_t lock;
+};
+
+extern const struct virtio_usb_vq_desc host_vqueues[VIRTIO_USB_VQ_HOST_MAX];
+
+/**
+ * vhcd_get() - Get pointer to per-VP host controller stored in hcd_priv.
+ * @hcd: usb_hcd
+ *
+ * Return: the per-VP host controller that owns @hcd.
+ */
+static inline struct virtio_usb_hc_vp *vhcd_get(struct usb_hcd *hcd)
+{
+ return ((void **)hcd->hcd_priv)[0];
+}
+
+/**
+ * vhcd_set() - Store per-VP host controller pointer in hcd_priv.
+ * @hcd: usb_hcd
+ * @vhcd_vp: per-VP host controller
+ */
+static inline void vhcd_set(struct usb_hcd *hcd,
+ struct virtio_usb_hc_vp *vhcd_vp)
+{
+ ((void **)hcd->hcd_priv)[0] = vhcd_vp;
+}
+
+/**
+ * port_vhcd_get() - Get the usb_hcd that owns this port's speed.
+ * @port: VirtIO usb host controller port
+ *
+ * Return: the SS hcd for SuperSpeed and SuperSpeed+ devices, the HS hcd
+ * for everything else.
+ */
+static inline struct usb_hcd *port_vhcd_get(struct virtio_usb_hc_port *port)
+{
+ return (port->speed == USB_SPEED_SUPER ||
+ port->speed == USB_SPEED_SUPER_PLUS) ?
+ port->vhcd_vp->ss :
+ port->vhcd_vp->hs;
+}
+
+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);
+int virtio_usb_hc_event_populate(struct virtio_usb *vusb);
+void virtio_usb_hc_rx_work(struct work_struct *work);
+void virtio_usb_hc_evt_work(struct work_struct *work);
+
+#endif
diff --git a/drivers/usb/virtio_usb/vq_common.c b/drivers/usb/virtio_usb/vq_common.c
new file mode 100644
index 000000000000..c45f86982a2e
--- /dev/null
+++ b/drivers/usb/virtio_usb/vq_common.c
@@ -0,0 +1,747 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+/*
+ * virtio-usb: Virtio usb device
+ *
+ * Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.
+ */
+
+#include "controller.h"
+#include "vq_common.h"
+
+/**
+ * struct virtio_usb_cmd_generic_hdr - Generic command header
+ * for the command
+ * @code: command code
+ * @value: value for the command
+ */
+struct virtio_usb_cmd_generic_hdr {
+ __le32 code;
+ __le32 value;
+};
+
+/**
+ * virtio_error_to_usb - Convert virtio error to usb error
+ * @error: virtio error code
+ *
+ * Context: Any context.
+ * Return: virtio error converted to usb error code
+ */
+int virtio_error_to_usb(unsigned int error)
+{
+ int status;
+
+ switch (error) {
+ case VIRTIO_USB_S_OK:
+ status = 0;
+ break;
+ case VIRTIO_USB_S_ERR_CANCELLED:
+ /* cancelled */
+ status = -ECONNRESET;
+ break;
+ /* device shutdown or removal*/
+ case VIRTIO_USB_S_ERR_NO_DEVICE:
+ status = -ESHUTDOWN;
+ break;
+ case VIRTIO_USB_S_ERR_STALL:
+ status = -EPIPE;
+ break;
+ case VIRTIO_USB_S_ERR_OVERFLOW:
+ status = -EOVERFLOW;
+ break;
+ case VIRTIO_USB_S_ERR_SHORT_PKT:
+ /* short packet */
+ status = -EREMOTEIO;
+ break;
+ case VIRTIO_USB_S_ERR_BAD_MSG:
+ status = -EINVAL;
+ break;
+ case VIRTIO_USB_S_ERR_DATA_IN:
+ status = -ECOMM;
+ break;
+ case VIRTIO_USB_S_ERR_DATA_OUT:
+ status = -ENOSR;
+ break;
+ case VIRTIO_USB_S_ERR_ISO_XFER:
+ status = -EXDEV;
+ break;
+ case VIRTIO_USB_S_ERR_ISO_BIG:
+ status = -EFBIG;
+ break;
+ case VIRTIO_USB_S_ERR_MSG_SIZE:
+ status = -EMSGSIZE;
+ break;
+ case VIRTIO_USB_S_ERR_INTERNAL:
+ default:
+ status = -EPROTO;
+ break;
+ }
+ return status;
+}
+
+/**
+ * virtio_usb_msg_ref() - Increment reference counter for the message.
+ * @msg: common message.
+ *
+ * Context: Any context.
+ */
+static void virtio_usb_msg_ref(struct virtio_usb_msg_common *msg)
+{
+ refcount_inc(&msg->ref_count);
+}
+
+/**
+ * virtio_usb_msg_unref() - Decrement reference counter for the message.
+ * @msg: common message.
+ *
+ * The message will be freed when the ref_count value is 0.
+ *
+ * Context: Any context.
+ */
+static void virtio_usb_msg_unref(struct virtio_usb_msg_common *msg)
+{
+ if (refcount_dec_and_test(&msg->ref_count))
+ kfree(msg);
+}
+
+/**
+ * virtio_usb_msg_request() - Get a pointer to the request header.
+ * @msg: common message.
+ *
+ * Context: Any context.
+ * Return: pointer to the request header.
+ */
+static void *virtio_usb_msg_request(struct virtio_usb_msg_common *msg)
+{
+ return sg_virt(&msg->sg_request);
+}
+
+/**
+ * virtio_usb_msg_response() - Get a pointer to the response header.
+ * @msg: common message.
+ *
+ * Context: Any context.
+ * Return: pointer to the response header.
+ */
+static void *virtio_usb_msg_response(struct virtio_usb_msg_common *msg)
+{
+ return sg_virt(&msg->sg_response);
+}
+
+/**
+ * virtio_usb_msg_alloc() - Allocate and initialize a message.
+ * @msg_size: Size of the requested message.
+ * @request_size: Size of request header.
+ * @response_size: Size of response header.
+ * @gfp: Kernel flags for memory allocation.
+ *
+ * The message will be automatically freed when the ref_count value is 0.
+ *
+ * Context: Any context. May sleep if @gfp flags permit.
+ * Return: Allocated message on success, NULL on failure.
+ */
+static void *virtio_usb_msg_alloc(size_t msg_size, size_t request_size,
+ size_t response_size, gfp_t gfp)
+{
+ struct virtio_usb_msg_common *msg;
+
+ if (!msg_size || !request_size || !response_size)
+ return NULL;
+
+ msg = kzalloc(msg_size + request_size + response_size, gfp);
+ if (!msg)
+ return NULL;
+
+ sg_init_one(&msg->sg_request, (u8 *)msg + msg_size, request_size);
+ sg_init_one(&msg->sg_response, (u8 *)msg + msg_size + request_size,
+ response_size);
+
+ refcount_set(&msg->ref_count, 1);
+
+ return msg;
+}
+
+/**
+ * virtio_usb_cmd_ref() - Increment reference counter for the command.
+ * @cmd: Command message.
+ *
+ * Context: Any context.
+ */
+void virtio_usb_cmd_ref(struct virtio_usb_cmd *cmd)
+{
+ virtio_usb_msg_ref((struct virtio_usb_msg_common *)cmd);
+}
+
+/**
+ * virtio_usb_cmd_unref() - Decrement reference counter for the command.
+ * @cmd: Command message.
+ *
+ * The message will be freed when the ref_count value is 0.
+ *
+ * Context: Any context.
+ */
+void virtio_usb_cmd_unref(struct virtio_usb_cmd *cmd)
+{
+ virtio_usb_msg_unref((struct virtio_usb_msg_common *)cmd);
+}
+
+/**
+ * virtio_usb_cmd_request() - Get a pointer to the request header.
+ * @cmd: Command msg.
+ *
+ * Context: Any context.
+ * Return: pointer to the request header.
+ */
+void *virtio_usb_cmd_request(struct virtio_usb_cmd *cmd)
+{
+ return virtio_usb_msg_request((struct virtio_usb_msg_common *)cmd);
+}
+
+/**
+ * virtio_usb_cmd_response() - Get a pointer to the response header.
+ * @cmd: command message.
+ *
+ * Context: Any context.
+ * Return: pointer to the response header.
+ */
+void *virtio_usb_cmd_response(struct virtio_usb_cmd *cmd)
+{
+ return virtio_usb_msg_response((struct virtio_usb_msg_common *)cmd);
+}
+
+/**
+ * virtio_usb_cmd_alloc() - Allocate and initialize a control message.
+ * @request_size: Size of request header.
+ * @response_size: Size of response header.
+ * @gfp: Kernel flags for memory allocation.
+ *
+ * The message will be automatically freed when the ref_count value is 0.
+ *
+ * Context: Any context. May sleep if @gfp flags permit.
+ * Return: Allocated message on success, NULL on failure.
+ */
+struct virtio_usb_cmd *virtio_usb_cmd_alloc(size_t request_size,
+ size_t response_size, gfp_t gfp)
+{
+ struct virtio_usb_cmd *cmd;
+
+ if (!request_size || !response_size)
+ return NULL;
+
+ cmd = virtio_usb_msg_alloc(sizeof(*cmd), request_size, response_size,
+ gfp);
+ if (!cmd)
+ return NULL;
+
+ init_completion(&cmd->notify);
+
+ return cmd;
+}
+
+/**
+ * virtio_usb_cmd_msg_send() - Function to send command message to the
+ * command virtqueue
+ * @vusb: VirtIO usb device.
+ * @msg: common message.
+ * @out_sgs: Additional sg-list to attach to the request header (may be NULL).
+ * @in_sgs: Additional sg-list to attach to the response header (may be NULL).
+ *
+ * Context: Any context. Takes and releases the command queue spinlock.
+ * Return: 0 on success, -errno on failure.
+ */
+static int virtio_usb_cmd_msg_send(struct virtio_usb *vusb,
+ struct virtio_usb_msg_common *msg,
+ struct scatterlist *out_sgs,
+ struct scatterlist *in_sgs)
+{
+ struct virtio_usb_queue *queue = msg->queue;
+ unsigned int nouts = 0, nins = 0;
+ struct scatterlist *psgs[4];
+ bool notify = false;
+ unsigned long flags;
+ int rc = 0;
+
+ psgs[nouts++] = &msg->sg_request;
+ if (out_sgs)
+ psgs[nouts++] = out_sgs;
+
+ psgs[nouts + nins++] = &msg->sg_response;
+ if (in_sgs)
+ psgs[nouts + nins++] = in_sgs;
+
+ spin_lock_irqsave(&queue->lock, flags);
+ rc = virtqueue_add_sgs(queue->vqueue, psgs, nouts, nins, msg,
+ GFP_ATOMIC);
+ if (!rc)
+ notify = virtqueue_kick_prepare(queue->vqueue);
+ spin_unlock_irqrestore(&queue->lock, flags);
+
+ if (rc)
+ goto on_exit;
+
+ if (notify)
+ virtqueue_notify(queue->vqueue);
+
+on_exit:
+ return rc;
+}
+
+/**
+ * virtio_usb_cmd_send() - Send a command to the command virtqueue
+ * @vusb: VirtIO usb device.
+ * @cmd: command message.
+ * @out_sgs: Additional sg-list to attach to the request header (may be NULL).
+ * @in_sgs: Additional sg-list to attach to the response header (may be NULL).
+ * @nowait: Flag indicating whether to wait for completion.
+ *
+ * Context: Any context. Takes and releases the command queue spinlock.
+ * May sleep if @nowait is false.
+ * Return: The return value is a message status code (VIRTIO_USB_S_XXX) converted to an
+ * appropriate -errno value.
+ */
+int virtio_usb_cmd_send(struct virtio_usb *vusb, struct virtio_usb_cmd *cmd,
+ struct scatterlist *out_sgs, struct scatterlist *in_sgs,
+ bool nowait)
+{
+ unsigned int js = msecs_to_jiffies(VIRTIO_USB_CMD_TIMEOUT_MS);
+ struct virtio_usb_cmd_generic_hdr *request =
+ virtio_usb_cmd_request(cmd);
+ struct virtio_usb_cmd_status *response = virtio_usb_cmd_response(cmd);
+ struct virtio_device *vdev = vusb->vdev;
+ int rc;
+ u32 code;
+
+ /* Set the default status in case the command was canceled. */
+ response->code = cpu_to_le32(VIRTIO_USB_S_ERR_CANCELLED);
+
+ virtio_usb_cmd_ref(cmd);
+
+ rc = virtio_usb_cmd_msg_send(vusb, (struct virtio_usb_msg_common *)cmd,
+ out_sgs, in_sgs);
+ if (rc) {
+ dev_err(&vdev->dev, "failed to send control message (0x%08x)\n",
+ le32_to_cpu(request->code));
+
+ /*
+ * Since in this case virtio_usb_cmd_process_cb() will not be
+ * called, it is necessary to decrement the reference count.
+ */
+ virtio_usb_cmd_unref(cmd);
+ goto on_exit;
+ }
+
+ if (nowait)
+ goto on_exit;
+
+ rc = wait_for_completion_interruptible_timeout(&cmd->notify, js);
+ if (rc <= 0) {
+ if (!rc) {
+ dev_err(&vdev->dev,
+ "control message (0x%08x) timeout\n",
+ le32_to_cpu(request->code));
+ rc = -ETIMEDOUT;
+ }
+
+ goto on_exit;
+ }
+
+ code = le32_to_cpu(response->code);
+
+ rc = virtio_error_to_usb(code);
+
+on_exit:
+ virtio_usb_cmd_unref(cmd);
+ return rc;
+}
+
+/**
+ * virtio_usb_events_alloc() - Allocates the events.
+ * @vusb: VirtIO USB device
+ * @vq: event virtqueue to which events need to be populated.
+ * @evt_size: Size of the event structure.
+ *
+ * Context: Any context.
+ * Return: 0 on success -errno on failure
+ */
+struct virtio_usb_event *virtio_usb_events_alloc(struct virtio_usb *vusb,
+ struct virtio_usb_queue *vq,
+ size_t evt_size)
+{
+ unsigned int n = virtqueue_get_vring_size(vq->vqueue);
+ struct virtio_device *vdev = vusb->vdev;
+ struct virtio_usb_event *events, *event;
+ unsigned int i;
+
+ events = devm_kcalloc(&vdev->dev, n, (sizeof(*events) + evt_size),
+ GFP_KERNEL);
+ if (!events)
+ return NULL;
+
+ for (i = 0; i < n; i++) {
+ event = (void *)events + i * (sizeof(*event) + evt_size);
+ event->evt_size = evt_size;
+ event->queue = vq;
+ sg_init_one(&event->sg_event, (void *)event + sizeof(*event),
+ evt_size);
+ event->vusb = vusb;
+ }
+ return events;
+}
+
+/**
+ * virtio_usb_events_populate() - Add preallocated events to the event queue.
+ * @events: Pointer to preallocated virtio usb events
+ *
+ * Context: Any context.
+ * Return: 0 on success -errno on failure
+ */
+int virtio_usb_events_populate(struct virtio_usb_event *events)
+{
+ unsigned int n = virtqueue_get_vring_size(events[0].queue->vqueue);
+ size_t evt_size = events[0].evt_size;
+ struct virtio_usb_event *event;
+ unsigned int i, rc = 0;
+
+ for (i = 0; i < n; i++) {
+ event = (void *)events + i * (sizeof(*event) + evt_size);
+ rc = virtqueue_add_inbuf(event->queue->vqueue, &event->sg_event,
+ 1, event, GFP_KERNEL);
+ if (rc)
+ return rc;
+ }
+ /* Notify the backend that event buffers are available so it can
+ * deliver any pending PORT_CONNECTED events immediately.
+ */
+ virtqueue_notify(events[0].queue->vqueue);
+ return rc;
+}
+
+/**
+ * virtio_usb_event_buf() - Get the event buffer.
+ * @event: The virtio_usb_event
+ *
+ * Context: Any context.
+ * Return: Pointer to the event buffer
+ */
+void *virtio_usb_event_buf(struct virtio_usb_event *event)
+{
+ return sg_virt(&event->sg_event);
+}
+
+/**
+ * virtio_usb_event_send() - Send an event to the specified event queue.
+ * @event: The event that needs to be send
+ *
+ *
+ * Context: Any context which expects the event queue spinlock to be held by
+ * caller.
+ * Return: 0 on success -errno on failure
+ */
+int virtio_usb_event_send(struct virtio_usb_event *event)
+{
+ int rc = 0;
+ void *event_buf = virtio_usb_event_buf(event);
+
+ /* reset event content */
+ memset(event_buf, 0, event->evt_size);
+
+ rc = virtqueue_add_inbuf(event->queue->vqueue, &event->sg_event, 1,
+ event, GFP_ATOMIC);
+ if (rc)
+ return rc;
+
+ if (virtqueue_kick_prepare(event->queue->vqueue))
+ virtqueue_notify(event->queue->vqueue);
+ return rc;
+}
+
+/**
+ * virtio_usb_data_ref() - Increment reference counter for the data.
+ * @data: Data message.
+ *
+ * Context: Any context.
+ */
+void virtio_usb_data_ref(struct virtio_usb_data *data)
+{
+ virtio_usb_msg_ref((struct virtio_usb_msg_common *)data);
+}
+
+/**
+ * virtio_usb_data_unref() - Decrement reference counter for the data.
+ * @data: Data message.
+ *
+ * The data will be freed when the ref_count value is 0.
+ *
+ * Context: Any context.
+ */
+void virtio_usb_data_unref(struct virtio_usb_data *data)
+{
+ virtio_usb_msg_unref((struct virtio_usb_msg_common *)data);
+}
+
+/**
+ * virtio_usb_data_request() - Get a pointer to the request header.
+ * @data: Data message.
+ *
+ * Context: Any context.
+ * Return: pointer to the request header.
+ */
+void *virtio_usb_data_request(struct virtio_usb_data *data)
+{
+ return virtio_usb_msg_request((struct virtio_usb_msg_common *)data);
+}
+
+/**
+ * virtio_usb_data_priv() - Get a pointer to the data priv.
+ * @data: Data message.
+ *
+ * Context: Any context.
+ * Return: pointer to the data priv, or NULL if @data is NULL.
+ */
+void *virtio_usb_data_priv(struct virtio_usb_data *data)
+{
+ if (!data)
+ return NULL;
+
+ return data->priv;
+}
+
+/**
+ * virtio_usb_data_response() - Get a pointer to the response header.
+ * @data: Data message.
+ *
+ * Context: Any context.
+ * Return: pointer to the response header.
+ */
+void *virtio_usb_data_response(struct virtio_usb_data *data)
+{
+ return virtio_usb_msg_response((struct virtio_usb_msg_common *)data);
+}
+
+/**
+ * virtio_usb_data_alloc() - Allocate and initialize a data message.
+ * @request_size: Size of request header.
+ * @response_size: Size of response header.
+ * @priv_size: Size of priv context of the data.
+ * @gfp: Kernel flags for memory allocation.
+ *
+ * The message will be automatically freed when the ref_count value is 0.
+ *
+ * Context: Any context. May sleep if @gfp flags permit.
+ * Return: Allocated message on success, NULL on failure.
+ */
+struct virtio_usb_data *virtio_usb_data_alloc(size_t request_size,
+ size_t response_size,
+ size_t priv_size, gfp_t gfp)
+{
+ struct virtio_usb_data *data;
+
+ if (!request_size || !response_size || !priv_size)
+ return NULL;
+
+ data = virtio_usb_msg_alloc(sizeof(*data) + priv_size, request_size,
+ response_size, gfp);
+ if (!data)
+ return NULL;
+ data->priv = (u8 *)data + sizeof(*data);
+
+ return data;
+}
+
+/**
+ * virtio_usb_data_send() - Send a data message
+ * @vusb: VirtIO usb device.
+ * @data: Data message.
+ * @out_sgs: Additional sg-list to attach to the request header
+ * @in_sgs: Additional sg-list to attach to the response header
+ *
+ * Context: Any context. Takes and releases the data queue spinlock.
+ * Return: 0 on success, -errno on failure.
+ */
+int virtio_usb_data_send(struct virtio_usb *vusb, struct virtio_usb_data *data,
+ struct scatterlist *out_sgs,
+ struct scatterlist *in_sgs)
+{
+ struct virtio_usb_queue *queue = data->msg.queue;
+ struct scatterlist *psgs[4] = { NULL };
+ unsigned int nouts = 0, nins = 0;
+ bool notify = false;
+ int rc = 0;
+
+ psgs[nouts++] = &data->msg.sg_request;
+ if (out_sgs)
+ psgs[nouts++] = out_sgs;
+
+ psgs[nouts + nins++] = &data->msg.sg_response;
+ if (in_sgs)
+ psgs[nouts + nins++] = in_sgs;
+
+ spin_lock_irq(&queue->lock);
+ rc = virtqueue_add_sgs(queue->vqueue, psgs, nouts, nins, data,
+ GFP_ATOMIC);
+ if (!rc)
+ notify = virtqueue_kick_prepare(queue->vqueue);
+ spin_unlock_irq(&queue->lock);
+
+ if (rc)
+ goto on_exit;
+
+ if (notify)
+ virtqueue_notify(queue->vqueue);
+
+on_exit:
+ return rc;
+}
+
+/**
+ * virtio_usb_cmd_notify_cb() - command virtqueue
+ * notification callback
+ * @vqueue: Underlying virtqueue.
+ *
+ * This callback function is called upon a vring interrupt request from the
+ * device.
+ *
+ * Context: Interrupt context.
+ */
+void virtio_usb_cmd_notify_cb(struct virtqueue *vqueue)
+{
+ struct virtio_usb *vusb = vqueue->vdev->priv;
+ struct virtio_usb_queue *vq = &vusb->vqueues[vqueue->index];
+ unsigned long flags;
+ u32 length;
+ void *buf;
+
+ spin_lock_irqsave(&vq->lock, flags);
+ do {
+ virtqueue_disable_cb(vqueue);
+ while ((buf = virtqueue_get_buf(vqueue, &length)))
+ vq->process(vusb, buf);
+ if (unlikely(virtqueue_is_broken(vqueue)))
+ break;
+ } while (!virtqueue_enable_cb(vqueue));
+ spin_unlock_irqrestore(&vq->lock, flags);
+}
+
+/**
+ * virtio_usb_cmd_process_cb() - process callback for commands.
+ * @vusb: VirtIO usb device.
+ * @buf: Pointer to the command message
+ *
+ * Context: Interrupt context. Expects the command queue spinlock to be held by
+ * caller.
+ */
+void virtio_usb_cmd_process_cb(struct virtio_usb *vusb, void *buf)
+{
+ struct virtio_usb_cmd *cmd = (struct virtio_usb_cmd *)buf;
+
+ complete(&cmd->notify);
+ virtio_usb_cmd_unref(cmd);
+}
+
+/**
+ * virtio_usb_cmdq_stop_cb() - Stops the command virtqueue
+ * @vusb: VirtIO usb device.
+ * @cmdq: The command virtqueue to be stopped
+ *
+ * Context: Any context.
+ */
+void virtio_usb_cmdq_stop_cb(struct virtio_usb *vusb,
+ struct virtio_usb_queue *cmdq)
+{
+ struct virtio_usb_cmd *cmd;
+ unsigned long flags;
+
+ if (cmdq->vqueue) {
+ spin_lock_irqsave(&cmdq->lock, flags);
+ virtqueue_disable_cb(cmdq->vqueue);
+
+ while ((cmd = virtqueue_detach_unused_buf(cmdq->vqueue)))
+ cmdq->process(vusb, cmd);
+
+ spin_unlock_irqrestore(&cmdq->lock, flags);
+ }
+}
+
+/**
+ * virtio_usb_dataq_stop_cb() - Stops the data virtqueue
+ * @vusb: VirtIO usb device.
+ * @dataq: The data virtqueue to be stopped.
+ *
+ * Context: Any context.
+ */
+void virtio_usb_dataq_stop_cb(struct virtio_usb *vusb,
+ struct virtio_usb_queue *dataq)
+{
+ if (dataq->vqueue) {
+ spin_lock_irq(&dataq->lock);
+ virtqueue_disable_cb(dataq->vqueue);
+ spin_unlock_irq(&dataq->lock);
+ }
+}
+
+/**
+ * virtio_usb_evt_work() - Generic event queue receive worker.
+ * @evtq: The event virtqueue to drain.
+ * @process_one: Callback invoked for each dequeued event, with the
+ * queue's own lock released (the callback is free to
+ * sleep / send further virtio commands).
+ *
+ * Common drain loop shared by every role's own event queue: dequeue
+ * completed event buffers, hand each one to @process_one, then
+ * immediately re-arm and resend it via virtio_usb_event_send() so the
+ * backend always has a full set of event buffers available.
+ *
+ * Context: Process context.
+ */
+void virtio_usb_evt_work(struct virtio_usb_queue *evtq,
+ void (*process_one)(struct virtio_usb_event *event))
+{
+ u32 length;
+ struct virtio_usb_event *event;
+
+ spin_lock(&evtq->lock);
+ do {
+ while ((event = virtqueue_get_buf(evtq->vqueue, &length))) {
+ spin_unlock(&evtq->lock);
+ process_one(event);
+ spin_lock(&evtq->lock);
+ virtio_usb_event_send(event);
+ }
+ if (unlikely(virtqueue_is_broken(evtq->vqueue)))
+ break;
+ } while (!virtqueue_enable_cb(evtq->vqueue));
+ spin_unlock(&evtq->lock);
+}
+
+/**
+ * virtio_usb_evt_drain_stop_cb() - Generic event queue stop callback.
+ * @vq: The event virtqueue to stop.
+ * @work: The work item that drains @vq via virtio_usb_evt_work(), to
+ * be cancelled before draining (may be NULL if the caller has
+ * already cancelled it, or must defer cancellation itself).
+ *
+ * Do not process events during teardown - whatever state process_one()
+ * would touch may already be partially torn down (probe failure) or
+ * gone (remove path). Just drain the used ring without processing, so
+ * virtio core's del_vqs() finds it empty.
+ *
+ * Context: Any context that permits to sleep (if @work is non-NULL).
+ */
+void virtio_usb_evt_drain_stop_cb(struct virtio_usb_queue *vq,
+ struct work_struct *work)
+{
+ unsigned long flags;
+ u32 length;
+ void *buf;
+
+ if (!vq->vqueue)
+ return;
+
+ if (work)
+ cancel_work_sync(work);
+
+ 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);
+}
diff --git a/drivers/usb/virtio_usb/vq_common.h b/drivers/usb/virtio_usb/vq_common.h
new file mode 100644
index 000000000000..28755f383dfa
--- /dev/null
+++ b/drivers/usb/virtio_usb/vq_common.h
@@ -0,0 +1,163 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+/*
+ * virtio-usb: Virtio usb device
+ *
+ * Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.
+ */
+
+#ifndef VIRTIO_USB_COMMON_H
+#define VIRTIO_USB_COMMON_H
+
+#include <linux/atomic.h>
+#include <linux/virtio.h>
+
+#include "controller.h"
+
+/**
+ * struct virtio_usb_msg_common - Common message structure
+ * for command and data message
+ * @sg_request: Scattergather list containing a device request (header).
+ * @sg_response: Scattergather list containing a device response (status).
+ * @queue: Virtqueue wrapper
+ * @ref_count: Reference count used to manage a message lifetime.
+ */
+struct virtio_usb_msg_common {
+ struct scatterlist sg_request;
+ struct scatterlist sg_response;
+ struct virtio_usb_queue *queue;
+ refcount_t ref_count;
+};
+
+/**
+ * struct virtio_usb_cmd - Command message
+ * @msg: Common message
+ * @notify: Request completed notification.
+ */
+struct virtio_usb_cmd {
+ struct virtio_usb_msg_common msg;
+ struct completion notify;
+};
+
+void virtio_usb_cmd_ref(struct virtio_usb_cmd *cmd);
+void virtio_usb_cmd_unref(struct virtio_usb_cmd *cmd);
+void *virtio_usb_cmd_request(struct virtio_usb_cmd *cmd);
+void *virtio_usb_cmd_response(struct virtio_usb_cmd *cmd);
+
+struct virtio_usb_cmd *virtio_usb_cmd_alloc(size_t request_size,
+ size_t response_size, gfp_t gfp);
+int virtio_usb_cmd_send(struct virtio_usb *vusb, struct virtio_usb_cmd *cmd,
+ struct scatterlist *out_sgs, struct scatterlist *in_sgs,
+ bool nowait);
+
+/**
+ * virtio_usb_cmd_send_sync - Simplified sending of synchronous message.
+ * @vusb: VirtIO usb device.
+ * @out_sgs: Additional sg-list to attach to the request header (may be NULL).
+ * @in_sgs: Additional sg-list to attach to the response header (may be NULL).
+ * @cmd: Command message.
+ *
+ * After returning from this function, the message will be deleted. If message
+ * content is still needed, the caller must additionally to
+ * virtio_usb_cmd_ref/unref() it.
+ *
+ * The msg_timeout_ms module parameter defines the message completion timeout.
+ * If the message is not completed within this time, the function will return an
+ * error.
+ *
+ * Context: Any context that permits to sleep.
+ * Return: 0 on success, -errno on failure.
+ *
+ * The return value is a message status code (VIRTIO_USB_S_XXX) converted to an
+ * appropriate -errno value.
+ */
+static inline int virtio_usb_cmd_send_sync(struct virtio_usb *vusb,
+ struct scatterlist *out_sgs,
+ struct scatterlist *in_sgs,
+ struct virtio_usb_cmd *cmd)
+{
+ return virtio_usb_cmd_send(vusb, cmd, out_sgs, in_sgs, false);
+}
+
+/**
+ * virtio_usb_cmd_send_async() - Simplified sending of asynchronous message.
+ * @vusb: VirtIO usb device.
+ * @out_sgs: Additional sg-list to attach to the request header (may be NULL).
+ * @in_sgs: Additional sg-list to attach to the response header (may be NULL).
+ * @cmd: Command message..
+ *
+ * Context: Any context.
+ * Return: 0 on success, -errno on failure.
+ */
+static inline int virtio_usb_cmd_send_async(struct virtio_usb *vusb,
+ struct scatterlist *out_sgs,
+ struct scatterlist *in_sgs,
+ struct virtio_usb_cmd *cmd)
+{
+ return virtio_usb_cmd_send(vusb, cmd, out_sgs, in_sgs, true);
+}
+
+/**
+ * struct virtio_usb_data - Data message.
+ * @msg: Common message
+ * @list: VirtIO usb data list entry.
+ * @priv: Pointer to priv structure.
+ */
+struct virtio_usb_data {
+ struct virtio_usb_msg_common msg;
+ struct list_head list;
+ void *priv;
+};
+
+void *virtio_usb_data_request(struct virtio_usb_data *data);
+void *virtio_usb_data_response(struct virtio_usb_data *data);
+void *virtio_usb_data_priv(struct virtio_usb_data *data);
+void virtio_usb_data_ref(struct virtio_usb_data *data);
+void virtio_usb_data_unref(struct virtio_usb_data *data);
+
+struct virtio_usb_data *virtio_usb_data_alloc(size_t request_size,
+ size_t response_size,
+ size_t priv_size, gfp_t gfp);
+
+int virtio_usb_data_send(struct virtio_usb *vusb, struct virtio_usb_data *data,
+ struct scatterlist *out_sgs,
+ struct scatterlist *in_sgs);
+
+void virtio_usb_cmd_notify_cb(struct virtqueue *vqueue);
+
+void virtio_usb_cmd_process_cb(struct virtio_usb *vusb, void *value);
+
+void virtio_usb_cmdq_stop_cb(struct virtio_usb *vusb,
+ struct virtio_usb_queue *vq);
+void virtio_usb_dataq_stop_cb(struct virtio_usb *vusb,
+ struct virtio_usb_queue *vq);
+
+/**
+ * struct virtio_usb_event - Event message.
+ * @work: Optional Kernel work to handle the event.
+ * @sg_event: Scattergather list containing a event.
+ * @queue: Virtqueue wrqapper
+ * @vusb: Virtio usb device
+ * @evt_size: size of event buffer
+ */
+struct virtio_usb_event {
+ struct work_struct work;
+ struct scatterlist sg_event;
+ struct virtio_usb_queue *queue;
+ struct virtio_usb *vusb;
+ size_t evt_size;
+};
+
+struct virtio_usb_event *virtio_usb_events_alloc(struct virtio_usb *vusb,
+ struct virtio_usb_queue *vq,
+ size_t evt_size);
+int virtio_usb_events_populate(struct virtio_usb_event *events);
+int virtio_usb_event_send(struct virtio_usb_event *event);
+void *virtio_usb_event_buf(struct virtio_usb_event *event);
+int virtio_error_to_usb(unsigned int error);
+
+void virtio_usb_evt_work(struct virtio_usb_queue *evtq,
+ void (*process_one)(struct virtio_usb_event *event));
+void virtio_usb_evt_drain_stop_cb(struct virtio_usb_queue *vq,
+ struct work_struct *work);
+
+#endif /* VIRTIO_USB_COMMON_H */
diff --git a/include/uapi/linux/virtio_usb.h b/include/uapi/linux/virtio_usb.h
index c494ca94d1ff..b601c88f1c7e 100644
--- a/include/uapi/linux/virtio_usb.h
+++ b/include/uapi/linux/virtio_usb.h
@@ -94,6 +94,14 @@ struct virtio_usb_host_cmd_streams {
#define VIRTIO_USB_EVT_HOST_PORT_CONNECTED 0
#define VIRTIO_USB_EVT_HOST_PORT_DISCONNECTED 1
+/* Maximum number of leaf-device slots per virtual port (physical socket).
+ * Each VP's root hub advertises exactly this many ports to the guest hub
+ * driver. Leaf devices (direct or behind a physical hub) are flattened
+ * into slots 0..VIRTIO_USB_VP_MAX_PORTS-1 of their VP's root hub.
+ * Must be <= USB_MAXCHILDREN (31) and <= USB_SS_MAXPORTS (15).
+ */
+#define VIRTIO_USB_VP_MAX_PORTS 8
+
/* VIRTIO_USB_EVT_HOST_PORT_CONNECTED/DISCONNECTED */
#define VIRTIO_USB_SPEED_UNKNOWN 0
#define VIRTIO_USB_SPEED_LOW 1
@@ -104,9 +112,9 @@ struct virtio_usb_host_cmd_streams {
struct virtio_usb_host_port_event {
__le32 code; /* VIRTIO_USB_EVT_HOST_PORT_XXX */
- __le32 port_id;
+ __le32 vp_idx; /* virtual port (physical socket) index, 0..nports-1 */
+ __le32 port; /* leaf slot within VP, 0..VIRTIO_USB_VP_MAX_PORTS-1 */
__le32 speed; /* VIRTIO_USB_SPEED_XXX */
- __le32 padding;
};
/*****************************************************************************
@@ -185,10 +193,12 @@ struct virtio_usb_dev_setup_event {
struct virtio_usb_request {
__le64 tag;
- __le16 port; /* Port ID */
+ __le16 vp_idx; /* virtual port (physical socket) index, host role only */
+ __le16 port; /* Port ID (leaf slot within vp_idx for host role) */
__le16 endpoint; /* Endpoint ID */
__le16 transfer_type; /* VIRTIO_USB_EP_XXX */
__le16 transfer_flags; /* VIRTIO_USB_FLAG_XXX */
+ __le16 padding;
union {
/* transfer_type = VIRTIO_USB_EP_CONTROL */
struct {
--
2.49.0
^ permalink raw reply related [flat|nested] 9+ messages in thread
* [RFC PATCH v2 4/7] virtio-usb: add device role (USB Device Controller) support
2026-12-01 17:35 ` [RFC PATCH v2 0/7] virtio-usb: add dual-role virtio USB driver Igor Skalkin
` (2 preceding siblings ...)
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 ` Igor Skalkin
2026-12-01 17:35 ` [RFC PATCH v2 5/7] virtio-usb: add per-port role query support Igor Skalkin
` (3 subsequent siblings)
7 siblings, 0 replies; 9+ messages in thread
From: Igor Skalkin @ 2026-12-01 17:35 UTC (permalink / raw)
To: Michael S . Tsirkin, Jason Wang, Greg Kroah-Hartman
Cc: virtualization, linux-usb, linux-kernel, Eugenio Perez, Xuan Zhuo,
Vasilii Ianikeev, Aiswarya Cyriac, Anton Yakovlev, Trilok Soni,
Matias Ezequiel Vara Larsen, Igor Skalkin
From: Aiswarya Cyriac <aiswarya.cyriac@oss.qualcomm.com>
Add the device (UDC) role: implement the usb_gadget_ops and
usb_ep_ops callback sets, handle BIND/UNBIND/DISCONNECTED events
from the host backend and forward setup/suspend/resume/reset
notifications to the UDC core, and extend the protocol header with
the endpoint and command messages the device role needs.
Each device-role virtual port gets its own struct virtio_usb_dc and
UDC registration, one per vports[] entry, instead of a single global
device controller - mirroring the per-VP model host role already
uses, since a device-role port is just as independent as a host-role
one. Each gadget gets a name derived from its port index, and its
endpoint name buffer is allocated dynamically instead of using a
stack variable that would outlive the calling function.
This driver virtualizes an entire UDC per device-role port: each port
maps 1:1 to a single struct usb_gadget/UDC instance owned by exactly
one guest. A separate approach - USB function-level virtualization,
where a single physical UDC hosts a composite gadget whose
individual functions are each routed to a different guest - is
currently being explored and is out of scope for this driver.
Hardware endpoint names are used directly as the virtual endpoint
names, since the endpoint name has a relation with the endpoint
address.
Keep the device lifecycle separate from link-state notifications
from the start: BIND registers the UDC and UNBIND tears it down,
while DISCONNECTED is only a transient link-state notification (a
disconnect may be followed by SETUP without a new bind, so it must
not free UDC resources). This aligns the guest-side lifecycle with
the host-side callbacks: BIND -> (SETUP / DISCONNECT / RESET /
SUSPEND / RESUME)* -> UNBIND.
Each port also registers its UDC under its own intermediate
platform_device instead of the shared virtio_device, created on BIND
and torn down on the matching UNBIND. usb_add_gadget_udc() derives
the UDC's class name from its parent kobject's name, and every
device-role port registering under the same shared parent would
collide.
With both host_role and device_role negotiated, a port's actual role
is ambiguous until a later commit adds a per-port role query -
every port defaults to DEVICE for now as a placeholder.
Parse the gadget's max_speed from the BIND event's new max_speed
field instead of hardcoding USB_SPEED_HIGH, clamping to a supported
set (LOW/FULL/HIGH/SUPER/SUPER_PLUS) and defaulting to HIGH on
invalid data, so the EP0 max packet size set_speed() configures
matches what the host backend actually negotiated instead of always
assuming High-Speed.
Every submission of a usb_request gets a new tag from the per-device
counter the host role uses. A gadget driver queues the same request
again with the same address, so the address cannot tell a DEV_CANCEL
for an earlier submission from one for the current one.
The USB gadget API's usb_ep_ops/usb_gadget_ops callbacks are documented
as atomic - they must not sleep. This driver's endpoint and command
handling needs to send a virtio command and wait for the backend's
response, which is exactly what those callbacks cannot do.
The driver therefore honors the atomic contract itself, without
requiring any change to the gadget core.
The endpoint lifecycle is an explicit state machine (EP_DISABLED,
EP_ENABLING, EP_ENABLED, EP_HALTED) with per-UDC/per-request work
items and a pending-request queue, so every usb_ep_ops/usb_gadget_ops
callback returns immediately and the actual virtio round trip happens
asynchronously on a workqueue. ep_enable()/ep_disable()/
set_selfpowered()/vbus_draw() all follow this split-phase pattern;
ep_queue()/ep_dequeue() are built on top of the same state machine.
ep_enable() validates the endpoint and SuperSpeed companion
descriptors under the UDC lock, and returns -EBUSY for an endpoint
that is not disabled.
ep_dequeue() schedules a cancel work that sends DEV_CANCEL. The work
holds its own reference on the request, since the function driver can
complete and free the request before the work runs. A request is on
req_queue before it reaches the data virtqueue, and a DEV_CANCEL sent
in that window would not match anything on the device side, would be
answered with success and dropped. So the cancel work only records the
cancel while the request is not submitted yet, and do_real_queue()
schedules it again once the request is queued. The work also records
which submission it was asked to cancel and does nothing if the
request completed and was queued again in the meantime;
do_real_queue() likewise only updates the state if it still belongs
to the submission it queued.
Completion keeps -ECONNRESET/-ESHUTDOWN statuses set by dequeue or
disable rather than overwriting them, and a request that completes
before its queue path has finished is given back exactly once. SETUP
handling waits for in-flight EP0 requests and holds new EP0 requests
while any endpoint is still EP_ENABLING, so control transfers never
overlap; if EP0 does not become idle in time, EP0 is halted.
Signed-off-by: Aiswarya Cyriac <aiswarya.cyriac@oss.qualcomm.com>
Co-developed-by: Anton Yakovlev <anton.yakovlev@oss.qualcomm.com>
Signed-off-by: Anton Yakovlev <anton.yakovlev@oss.qualcomm.com>
Co-developed-by: Igor Skalkin <igor.skalkin@oss.qualcomm.com>
Signed-off-by: Igor Skalkin <igor.skalkin@oss.qualcomm.com>
---
drivers/usb/virtio_usb/Makefile | 3 +-
drivers/usb/virtio_usb/controller.c | 75 +-
drivers/usb/virtio_usb/controller.h | 17 +
drivers/usb/virtio_usb/device.c | 2016 +++++++++++++++++++++++++++
drivers/usb/virtio_usb/device.h | 126 ++
include/uapi/linux/virtio_usb.h | 45 +-
6 files changed, 2269 insertions(+), 13 deletions(-)
create mode 100644 drivers/usb/virtio_usb/device.c
create mode 100644 drivers/usb/virtio_usb/device.h
diff --git a/drivers/usb/virtio_usb/Makefile b/drivers/usb/virtio_usb/Makefile
index c6951c68b8c2..ac382d81d8af 100644
--- a/drivers/usb/virtio_usb/Makefile
+++ b/drivers/usb/virtio_usb/Makefile
@@ -4,4 +4,5 @@ obj-$(CONFIG_USB_VIRTIO) += virtio-usb.o
virtio-usb-y := controller.o \
vq_common.o \
- host.o
+ host.o \
+ device.o
diff --git a/drivers/usb/virtio_usb/controller.c b/drivers/usb/virtio_usb/controller.c
index eb343f026a46..b463513b2da4 100644
--- a/drivers/usb/virtio_usb/controller.c
+++ b/drivers/usb/virtio_usb/controller.c
@@ -10,6 +10,7 @@
#include "controller.h"
#include "host.h"
+#include "device.h"
#include "vq_common.h"
/**
@@ -72,7 +73,8 @@ static int virtio_usb_validate(struct virtio_device *vdev)
return -EINVAL;
}
- if (!virtio_has_feature(vdev, VIRTIO_USB_F_HOST)) {
+ if (!virtio_has_feature(vdev, VIRTIO_USB_F_HOST) &&
+ !virtio_has_feature(vdev, VIRTIO_USB_F_DEVICE)) {
dev_err(&vdev->dev,
"device should support at least one usb role\n");
return -EINVAL;
@@ -113,17 +115,40 @@ static int virtio_usb_probe(struct virtio_device *vdev)
if (virtio_has_feature(vdev, VIRTIO_USB_F_HOST))
vusb->host_role = 1;
- /* Only host_role exists so far, so every port is unambiguously a
- * host-role port. Later commits (device role, per-port role
- * query) will replace this with real per-port role resolution.
+ if (virtio_has_feature(vdev, VIRTIO_USB_F_DEVICE))
+ vusb->device_role = 1;
+
+ /* 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. A pure single-role
+ * instance therefore has exactly VIRTIO_USB_VQ_HOST_MAX (3) or
+ * VIRTIO_USB_VQ_DEV_MAX (3) virtqueues, not a fixed layout - queues
+ * that don't exist on the wire must not be created, since a peer
+ * with no host-role VP has no host command/event/data queues to
+ * negotiate at all.
*/
vusb->host_vq_base = -1;
+ vusb->dev_vq_base = -1;
+
if (vusb->host_role) {
vusb->host_vq_base = nvqs;
nvqs += VIRTIO_USB_VQ_HOST_MAX;
+ }
+ if (vusb->device_role) {
+ vusb->dev_vq_base = nvqs;
+ nvqs += VIRTIO_USB_VQ_DEV_MAX;
+ }
- for (i = 0; i < vusb->nports; i++)
+ /* Resolve every port's role. With only one role negotiated, every
+ * port unambiguously has that role. With both negotiated, a port's
+ * own role is ambiguous until a later commit adds a per-port
+ * role query - default to DEVICE for now as a placeholder.
+ */
+ for (i = 0; i < vusb->nports; i++) {
+ if (vusb->host_role && !vusb->device_role)
vusb->vports[i].role = VIRTIO_USB_ROLE_HOST;
+ else if (vusb->device_role)
+ vusb->vports[i].role = VIRTIO_USB_ROLE_DEVICE;
}
vusb->vqueues = devm_kcalloc(&vdev->dev, nvqs, sizeof(*vusb->vqueues),
@@ -145,6 +170,18 @@ static int virtio_usb_probe(struct virtio_device *vdev)
host_vqueues[i].stop;
}
+ if (vusb->dev_vq_base >= 0)
+ for (i = 0; i < VIRTIO_USB_VQ_DEV_MAX; i++) {
+ vusb->vqueues[vusb->dev_vq_base + i].name =
+ dev_vqueues[i].name;
+ vusb->vqueues[vusb->dev_vq_base + i].callback =
+ dev_vqueues[i].callback;
+ vusb->vqueues[vusb->dev_vq_base + i].process =
+ dev_vqueues[i].process;
+ vusb->vqueues[vusb->dev_vq_base + i].stop =
+ dev_vqueues[i].stop;
+ }
+
rc = virtio_usb_find_vqs(vusb);
if (rc) {
dev_err(&vdev->dev, "%s virtio_usb_find_vqs() error(%d)\n",
@@ -180,6 +217,30 @@ 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;
+ rc = virtio_usb_dc_init(vusb, i);
+ if (rc) {
+ dev_err(&vdev->dev,
+ "%s virtio_usb_dc_init() port=%d error(%d)\n",
+ __func__, i, rc);
+ 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);
return rc;
@@ -209,6 +270,9 @@ static void virtio_usb_remove(struct virtio_device *vdev)
virtio_usb_hc_vp_deinit(vusb, i);
}
+ if (vusb->device_role && vusb->vports)
+ virtio_usb_dc_deinit(vusb);
+
virtio_reset_device(vdev);
vdev->config->del_vqs(vdev);
@@ -216,6 +280,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,
};
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 dfa16a3d42a8..446a9274871c 100644
--- a/drivers/usb/virtio_usb/controller.h
+++ b/drivers/usb/virtio_usb/controller.h
@@ -17,21 +17,26 @@
/* Forward declaration - full definition in host.h */
struct virtio_usb_hc_vp;
+/* Forward declaration - full definition in device.h */
+struct virtio_usb_dc;
#define VIRTIO_USB_VQ_COMMAND_IDX 0
#define VIRTIO_USB_VQ_EVENT_IDX 1
#define VIRTIO_USB_VQ_DATA_IDX 2
#define VIRTIO_USB_VQ_HOST_MAX 3
+#define VIRTIO_USB_VQ_DEV_MAX 3
/**
* struct virtio_usb_port - Per-virtual-port state.
* @role: Role of this port (VIRTIO_USB_ROLE_HOST or _DEVICE).
* @vhc: Host controller - non-NULL when role is HOST.
+ * @vudc: Device controller - non-NULL when role is DEVICE.
*/
struct virtio_usb_port {
unsigned int role;
struct virtio_usb_hc_vp *vhc;
+ struct virtio_usb_dc *vudc;
};
/**
@@ -42,14 +47,22 @@ struct virtio_usb_port {
* @nports: number of supported ports
* @nvqs: number of virtqueues for the device
* @host_role: flag indicating support for host role
+ * @device_role: flag indicating support for device role
* @host_vq_base: index into vqueues[] where the HOST_COMMAND/EVENT/DATA
* triplet starts, or -1 if this instance has no host-role
* VP (in which case those queues do not exist on the wire
* and must not be negotiated).
+ * @dev_vq_base: index into vqueues[] where the DEV_COMMAND/EVENT/DATA
+ * triplet starts, or -1 if this instance has no
+ * device-role VP.
* @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
* across every host-role VP.
+ * @vq_dev_data_rx_work: Kernel work draining the device data queue, shared
+ * across every device-role port.
+ * @vq_dev_event_work: Kernel work draining the device event queue, shared
+ * across every device-role port.
* @data_tag_seq: Source of data request tags, see virtio_usb_data_tag_next().
*/
struct virtio_usb {
@@ -59,9 +72,13 @@ struct virtio_usb {
unsigned int nports;
u32 nvqs;
bool host_role;
+ bool device_role;
int host_vq_base;
+ int dev_vq_base;
struct work_struct vq_host_data_rx_work;
struct work_struct vq_host_evt_work;
+ struct work_struct vq_dev_data_rx_work;
+ struct work_struct vq_dev_event_work;
atomic64_t data_tag_seq;
};
diff --git a/drivers/usb/virtio_usb/device.c b/drivers/usb/virtio_usb/device.c
new file mode 100644
index 000000000000..af82a0e7e27e
--- /dev/null
+++ b/drivers/usb/virtio_usb/device.c
@@ -0,0 +1,2016 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+/*
+ * virtio_usb: VirtIO USB device
+ *
+ * Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.
+ */
+
+#include <linux/virtio_usb.h>
+
+#include "controller.h"
+#include "device.h"
+
+#define GADGET_NAME "virtio_usb_dc"
+#define VIRTIO_USB_EP0_IDLE_TIMEOUT_MS 5000
+
+/**
+ * struct virtio_usb_dc_priv - Device controller data priv
+ * Structure for UDC related data in data messages
+ * @req: usb_request structure
+ * @vep: virtio usb endpoint
+ * @vreq: virtio-usb request
+ * @cancel_work: Sends DEV_CANCEL for this request, see
+ * virtio_usb_dc_cancel_work().
+ * @completed_early: The request was given back by virtio_ep_disable()
+ * while still in flight; the completion handler only
+ * drops the last reference.
+ * @submitted: True once the request has been placed on the data
+ * virtqueue. Protected by vudc->lock.
+ * @cancel_pending: Set by virtio_usb_dc_cancel_work() when the request had
+ * not reached the data virtqueue yet; do_real_queue()
+ * reschedules the cancel work once it has. Protected by
+ * vudc->lock.
+ * @tag: Tag of the current submission, see virtio_usb_data_tag_next().
+ * Protected by vudc->lock.
+ * @cancel_tag: Tag of the submission virtio_ep_dequeue() asked to cancel.
+ * The cancel work only acts while it still equals @tag.
+ * Protected by vudc->lock.
+ */
+struct virtio_usb_dc_priv {
+ struct usb_request req;
+ struct virtio_usb_ep *vep;
+ struct virtio_usb_data *vreq;
+ struct work_struct cancel_work;
+ bool completed_early;
+ bool submitted;
+ bool cancel_pending;
+ u64 tag;
+ u64 cancel_tag;
+};
+
+/**
+ * usb_ep_to_virtio_ep() - Get the virtio usb endpoint from usb endpoint
+ * @ep: usb endpoint
+ *
+ * Context: Any context.
+ * Return: Pointer to virtio_usb_ep
+ */
+static struct virtio_usb_ep *usb_ep_to_virtio_ep(struct usb_ep *ep)
+{
+ return container_of(ep, struct virtio_usb_ep, ep);
+}
+
+/**
+ * usb_ep_dir_in() - check if the endpoint has IN direction
+ * @ep: usb endpoint
+ *
+ * Context: Any context.
+ * Return: 1 if direction is USB_DIR_IN else 0
+ */
+static unsigned int usb_ep_dir_in(struct usb_ep *ep)
+{
+ struct virtio_usb_ep *vep = usb_ep_to_virtio_ep(ep);
+ unsigned int direction = 0;
+
+ if (ep->address == 0)
+ direction = vep->setup.bRequestType & USB_DIR_IN ? 1 : 0;
+ else if (ep->desc && ep->desc->bEndpointAddress)
+ direction = usb_endpoint_dir_in(ep->desc) ? 1 : 0;
+
+ return direction;
+}
+
+/**
+ * usb_req_to_virtio_data() - Get the virtio usb data message from usb_request
+ * @req: usb_request structure
+ *
+ * Context: Any context.
+ * Return: virtio usb data message
+ */
+static struct virtio_usb_data *usb_req_to_virtio_data(struct usb_request *req)
+{
+ struct virtio_usb_dc_priv *priv =
+ container_of(req, struct virtio_usb_dc_priv, req);
+
+ return priv->vreq;
+}
+
+static bool virtio_usb_dc_req_queue_empty(struct virtio_usb_ep *vep)
+{
+ struct virtio_usb_dc *vudc = vep->vudc;
+ unsigned long flags;
+ bool empty;
+
+ spin_lock_irqsave(&vudc->lock, flags);
+ empty = list_empty(&vep->req_queue);
+ spin_unlock_irqrestore(&vudc->lock, flags);
+
+ return empty;
+}
+
+static int virtio_usb_dc_wait_ep0_idle(struct virtio_usb_dc *vudc)
+{
+ struct virtio_usb_ep *vep = usb_ep_to_virtio_ep(vudc->gadget.ep0);
+ long ret;
+
+ if (virtio_usb_dc_req_queue_empty(vep))
+ return 0;
+
+ ret = wait_event_timeout(
+ vudc->ep0_idle, virtio_usb_dc_req_queue_empty(vep),
+ msecs_to_jiffies(VIRTIO_USB_EP0_IDLE_TIMEOUT_MS));
+
+ return ret ? 0 : -ETIMEDOUT;
+}
+
+/**
+ * virtio_usb_dc_complete_req() - Completes a usb request
+ * @vreq: virtio usb data message.
+ *
+ * Context: Process context.
+ */
+static void virtio_usb_dc_complete_req(struct virtio_usb_data *vreq)
+{
+ struct virtio_usb_response *response = virtio_usb_data_response(vreq);
+ struct virtio_usb_dc_priv *priv = virtio_usb_data_priv(vreq);
+ unsigned int status = le32_to_cpu(response->status);
+ struct usb_request *req = &priv->req;
+ struct virtio_usb_ep *vep = priv->vep;
+ struct virtio_usb_dc *vudc = vep->vudc;
+ struct virtio_usb_data *vreq_iter;
+ unsigned int found = 0;
+ unsigned long flags;
+ bool wake_ep0 = false;
+ bool early;
+
+ spin_lock_irqsave(&vudc->lock, flags);
+
+ list_for_each_entry(vreq_iter, &vep->req_queue, list) {
+ if (vreq_iter == vreq) {
+ found = 1;
+ break;
+ }
+ }
+ early = priv->completed_early;
+ if (!found) {
+ spin_unlock_irqrestore(&vudc->lock, flags);
+ /* Arrived after ep_disable() already gave back */
+ if (early)
+ virtio_usb_data_unref(vreq);
+ return;
+ }
+ /* Common case - request still belongs to in-flight queue */
+ if (req->status != -ECONNRESET && req->status != -ESHUTDOWN) {
+ req->status = virtio_error_to_usb(status);
+ if (!req->status)
+ req->actual = le32_to_cpu(response->actual_length);
+ }
+
+ list_del_init(&vreq->list);
+ wake_ep0 = !vep->ep_id && list_empty(&vep->req_queue);
+ spin_unlock_irqrestore(&vudc->lock, flags);
+ if (wake_ep0)
+ wake_up(&vudc->ep0_idle);
+
+ /* Normal completion: giveback now */
+ if (!early)
+ usb_gadget_giveback_request(&vep->ep, req);
+
+ /* Drop final reference */
+ virtio_usb_data_unref(vreq);
+}
+
+/**
+ * virtio_usb_dc_data_work() - Worker to get all completed data message
+ * from the virtqueue and call the completion handler.
+ * @work: kernel work to handle data message completion.
+ *
+ * Context: Process context.
+ */
+void virtio_usb_dc_data_work(struct work_struct *work)
+{
+ struct virtio_usb *vusb =
+ container_of(work, struct virtio_usb, vq_dev_data_rx_work);
+ struct virtio_usb_queue *dataq =
+ &vusb->vqueues[vusb->dev_vq_base + VIRTIO_USB_VQ_DATA_IDX];
+ struct virtio_usb_data *vreq;
+ unsigned long flags;
+ unsigned int length;
+
+ spin_lock_irqsave(&dataq->lock, flags);
+ do {
+ virtqueue_disable_cb(dataq->vqueue);
+ while ((vreq = virtqueue_get_buf(dataq->vqueue, &length))) {
+ spin_unlock_irqrestore(&dataq->lock, flags);
+ virtio_usb_dc_complete_req(vreq);
+ spin_lock_irqsave(&dataq->lock, flags);
+ }
+ if (unlikely(virtqueue_is_broken(dataq->vqueue)))
+ break;
+ } while (!virtqueue_enable_cb(dataq->vqueue));
+ spin_unlock_irqrestore(&dataq->lock, flags);
+}
+
+static void virtio_usb_dc_cancel_work(struct work_struct *work);
+/**
+ * virtio_usb_dc_data_alloc() - Allocate and initialize a device controller
+ * data message.
+ * @ep: VirtIO usb device
+ * @gfp: Kernel flags for memory allocation.
+ *
+ * The message will be automatically freed when the ref_count value is 0.
+ *
+ * Context: Any context. May sleep if @gfp flags permit.
+ * Return: Allocated data message on success, NULL on failure.
+ */
+static struct virtio_usb_data *virtio_usb_dc_data_alloc(struct usb_ep *ep,
+ gfp_t gfp)
+{
+ struct virtio_usb_ep *vep = usb_ep_to_virtio_ep(ep);
+ size_t request_size = sizeof(struct virtio_usb_request);
+ size_t response_size = sizeof(struct virtio_usb_response);
+ struct virtio_usb_dc_priv *priv;
+ struct virtio_usb_data *vreq;
+
+ vreq = virtio_usb_data_alloc(request_size, response_size,
+ sizeof(struct virtio_usb_dc_priv), gfp);
+ if (!vreq)
+ return NULL;
+
+ priv = virtio_usb_data_priv(vreq);
+ priv->vep = vep;
+ priv->vreq = vreq;
+ priv->completed_early = false;
+ INIT_WORK(&priv->cancel_work, virtio_usb_dc_cancel_work);
+ vreq->msg.queue =
+ &vep->vudc->vusb->vqueues[vep->vudc->vusb->dev_vq_base +
+ VIRTIO_USB_VQ_DATA_IDX];
+
+ return vreq;
+}
+
+/**
+ * virtio_usb_dc_cmd_alloc() - Allocate and initialize the device controller
+ * command message.
+ * @vudc: VirtIO usb device controller
+ * @command: command message
+ * @gfp: Kernel flags for memory allocation.
+ *
+ * The message will be automatically freed when the ref_count value is 0.
+ *
+ * Context: Any context. May sleep if @gfp flags permit.
+ * Return: Allocated command message on success, NULL on failure.
+ */
+static struct virtio_usb_cmd *
+virtio_usb_dc_cmd_alloc(struct virtio_usb_dc *vudc, unsigned int command,
+ gfp_t gfp)
+{
+ size_t request_size = sizeof(struct virtio_usb_dev_cmd_hdr);
+ size_t response_size = sizeof(struct virtio_usb_cmd_status);
+ struct virtio_usb_cmd_status *status;
+ struct virtio_usb_dev_cmd_hdr *hdr;
+ struct virtio_usb_cmd *cmd;
+
+ switch (command) {
+ case VIRTIO_USB_CMD_DEV_GET_ENDPOINT_COUNT:
+ response_size = sizeof(struct virtio_usb_dev_ep_count);
+ break;
+ case VIRTIO_USB_CMD_DEV_GET_FRAME_NUMBER:
+ response_size = sizeof(struct virtio_usb_dev_frame_number);
+ break;
+ case VIRTIO_USB_CMD_DEV_CANCEL:
+ request_size = sizeof(struct virtio_usb_dev_cmd_cancel);
+ break;
+ case VIRTIO_USB_CMD_DEV_VBUS_DRAW:
+ case VIRTIO_USB_CMD_DEV_PULLUP:
+ case VIRTIO_USB_CMD_DEV_EP_SET_HALT:
+ case VIRTIO_USB_CMD_DEV_SET_SELF_POWERED:
+ request_size = sizeof(struct virtio_usb_dev_cmd_set_value);
+ break;
+ }
+
+ cmd = virtio_usb_cmd_alloc(request_size, response_size, gfp);
+ if (!cmd)
+ return NULL;
+
+ hdr = virtio_usb_cmd_request(cmd);
+ status = virtio_usb_cmd_response(cmd);
+
+ hdr->code = cpu_to_le32(command);
+ hdr->port = cpu_to_le16(vudc->port);
+ cmd->msg.queue = &vudc->vusb->vqueues[vudc->vusb->dev_vq_base +
+ VIRTIO_USB_VQ_COMMAND_IDX];
+ status->code = cpu_to_le32(VIRTIO_USB_S_ERR_CANCELLED);
+ return cmd;
+}
+
+/* Endpoint callbacks */
+
+/**
+ * virtio_usb_dc_schedule_cancel() - Schedule the cancel work of a request.
+ * @vreq: virtio usb data message.
+ *
+ * The cancel work dereferences the request, and the request can be
+ * completed and freed by the function driver (usb_ep_free_request()) before
+ * the work runs. Hold a reference for the work; virtio_usb_dc_cancel_work()
+ * drops it.
+ *
+ * Context: Any context. The caller must hold a reference on @vreq.
+ */
+static void virtio_usb_dc_schedule_cancel(struct virtio_usb_data *vreq)
+{
+ struct virtio_usb_dc_priv *priv = virtio_usb_data_priv(vreq);
+
+ virtio_usb_data_ref(vreq);
+ if (!schedule_work(&priv->cancel_work))
+ /* Already pending, that instance owns a reference. */
+ virtio_usb_data_unref(vreq);
+}
+
+static int do_real_queue(struct virtio_usb_ep *vep, struct usb_request *req)
+{
+ struct virtio_usb_dc *vudc = vep->vudc;
+ struct virtio_usb_data *vreq = usb_req_to_virtio_data(req);
+ struct virtio_usb_dc_priv *priv = virtio_usb_data_priv(vreq);
+ struct virtio_usb_request *request;
+ struct virtio_usb_response *response;
+ struct scatterlist *out_sgs = NULL, *in_sgs = NULL, *psg_data = NULL;
+ struct scatterlist sg;
+ unsigned long flags;
+ u16 endpoint;
+ u16 transfer_flags = 0;
+ u16 transfer_type = VIRTIO_USB_EP_CONTROL;
+ bool cancel_pending;
+ u64 tag;
+ int rc;
+
+ virtio_usb_data_ref(vreq);
+
+ request = virtio_usb_data_request(vreq);
+ response = virtio_usb_data_response(vreq);
+ response->actual_length = cpu_to_le32(0);
+ response->status = cpu_to_le32(VIRTIO_USB_S_ERR_INTERNAL);
+
+ if (req->short_not_ok)
+ transfer_flags |= VIRTIO_USB_FLAG_SHORT_NOT_OK;
+ else if (req->zero)
+ transfer_flags |= VIRTIO_USB_FLAG_ZERO_PACKET;
+ request->transfer_flags = cpu_to_le16(transfer_flags);
+
+ endpoint = vep->ep_id |
+ (usb_ep_dir_in(&vep->ep) ? VIRTIO_USB_EP_DIR_IN :
+ VIRTIO_USB_EP_DIR_OUT);
+ request->endpoint = cpu_to_le16(endpoint);
+ request->port = cpu_to_le16(vudc->port);
+ if (vep->ep_id && vep->ep.desc) {
+ switch (usb_endpoint_type(vep->ep.desc)) {
+ case USB_ENDPOINT_XFER_ISOC:
+ transfer_type = VIRTIO_USB_EP_ISOCHRONOUS;
+ break;
+ case USB_ENDPOINT_XFER_BULK:
+ transfer_type = VIRTIO_USB_EP_BULK;
+ break;
+ case USB_ENDPOINT_XFER_INT:
+ transfer_type = VIRTIO_USB_EP_INTERRUPT;
+ break;
+ default:
+ transfer_type = VIRTIO_USB_EP_CONTROL;
+ break;
+ }
+ }
+ request->transfer_type = cpu_to_le16(transfer_type);
+
+ if (req->length && req->buf) {
+ psg_data = &sg;
+ sg_init_one(psg_data, req->buf, req->length);
+ } else if (req->length && req->num_sgs > 0) {
+ psg_data = req->sg;
+ } else if (req->length && req->sg) {
+ psg_data = &sg;
+ sg_init_one(psg_data, sg_virt(req->sg), req->length);
+ } else {
+ psg_data = NULL;
+ }
+
+ if (usb_ep_dir_in(&vep->ep))
+ out_sgs = psg_data;
+ else
+ in_sgs = psg_data;
+
+ spin_lock_irqsave(&vudc->lock, flags);
+ priv->completed_early = false;
+ priv->submitted = false;
+ priv->cancel_pending = false;
+ /* A new tag for every submission: the request may be queued again
+ * while a cancel for its previous submission is still pending or in
+ * flight, and that cancel must not hit this one.
+ */
+ tag = virtio_usb_data_tag_next(vudc->vusb);
+ priv->tag = tag;
+ request->tag = cpu_to_le64(tag);
+ req->actual = 0;
+ req->status = -EINPROGRESS;
+ list_add_tail(&vreq->list, &vep->req_queue);
+ spin_unlock_irqrestore(&vudc->lock, flags);
+
+ /*
+ * virtio_ep_dequeue() can see the request on req_queue and schedule
+ * the cancel work before the request reaches the data virtqueue. A
+ * DEV_CANCEL sent that early would not match anything on the device
+ * side, would be answered with success and dropped, and the request
+ * queued right after would never be cancelled. In that case the
+ * cancel work only records the request and this path reschedules it.
+ *
+ * Hold a reference across the window so the request cannot be
+ * completed and freed while this is being decided.
+ */
+ virtio_usb_data_ref(vreq);
+
+ rc = virtio_usb_data_send(vudc->vusb, vreq, out_sgs, in_sgs);
+ if (rc) {
+ spin_lock_irqsave(&vudc->lock, flags);
+ list_del_init(&vreq->list);
+ spin_unlock_irqrestore(&vudc->lock, flags);
+
+ virtio_usb_data_unref(vreq);
+ virtio_usb_data_unref(vreq);
+ return rc;
+ }
+
+ /*
+ * The request may already have completed and, from its completion
+ * callback, been queued again by the function driver. The flags then
+ * belong to that newer submission, which handles them itself.
+ */
+ spin_lock_irqsave(&vudc->lock, flags);
+ cancel_pending = false;
+ if (priv->tag == tag) {
+ priv->submitted = true;
+ cancel_pending = priv->cancel_pending;
+ }
+ spin_unlock_irqrestore(&vudc->lock, flags);
+
+ if (cancel_pending)
+ virtio_usb_dc_schedule_cancel(vreq);
+
+ virtio_usb_data_unref(vreq);
+
+ return 0;
+}
+
+static bool virtio_usb_dc_ep_enabling_locked(struct virtio_usb_dc *vudc)
+{
+ u32 i;
+
+ for (i = 1; i < vudc->neps; i++) {
+ if (vudc->veps[i].state == EP_ENABLING)
+ return true;
+ }
+
+ return false;
+}
+
+static void virtio_usb_dc_flush_ep0_pend(struct virtio_usb_dc *vudc)
+{
+ struct virtio_usb_ep *vep = &vudc->veps[0];
+ struct virtio_usb_data *vreq;
+ unsigned long flags;
+
+ spin_lock_irqsave(&vudc->lock, flags);
+ if (virtio_usb_dc_ep_enabling_locked(vudc)) {
+ spin_unlock_irqrestore(&vudc->lock, flags);
+ return;
+ }
+
+ while (!list_empty(&vep->pend_queue)) {
+ struct virtio_usb_dc_priv *priv;
+ int qrc;
+
+ vreq = list_first_entry(&vep->pend_queue,
+ struct virtio_usb_data, list);
+ priv = virtio_usb_data_priv(vreq);
+ list_del_init(&vreq->list);
+ spin_unlock_irqrestore(&vudc->lock, flags);
+
+ qrc = do_real_queue(vep, &priv->req);
+ virtio_usb_data_unref(vreq);
+ if (qrc) {
+ priv->req.status = qrc;
+ usb_gadget_giveback_request(&vep->ep, &priv->req);
+ }
+
+ spin_lock_irqsave(&vudc->lock, flags);
+ }
+ spin_unlock_irqrestore(&vudc->lock, flags);
+}
+
+static bool
+virtio_usb_ep_comp_valid(const struct usb_ss_ep_comp_descriptor *comp)
+{
+ return comp && comp->bLength == USB_DT_SS_EP_COMP_SIZE &&
+ comp->bDescriptorType == USB_DT_SS_ENDPOINT_COMP;
+}
+
+static void vep_enable_work(struct work_struct *work)
+{
+ struct virtio_usb_ep *vep =
+ container_of(work, struct virtio_usb_ep, enable_work);
+ struct virtio_usb_dc *vudc = vep->vudc;
+ const struct usb_endpoint_descriptor *desc = vep->ep.desc;
+ const struct usb_ss_ep_comp_descriptor *comp = vep->ep.comp_desc;
+ struct scatterlist sgs[2];
+ struct scatterlist *psg_data = sgs;
+ struct virtio_usb_dev_cmd_hdr *hdr;
+ struct virtio_usb_cmd *cmd;
+ unsigned long flags;
+ u16 endpoint;
+ u8 n_sgs = 1;
+ int rc;
+
+ if (!desc)
+ return;
+
+ endpoint = vep->ep_id |
+ (usb_ep_dir_in(&vep->ep) ? VIRTIO_USB_EP_DIR_IN :
+ VIRTIO_USB_EP_DIR_OUT);
+
+ cmd = virtio_usb_dc_cmd_alloc(vudc, VIRTIO_USB_CMD_DEV_EP_ENABLE,
+ GFP_KERNEL);
+ if (!cmd) {
+ rc = -ENOMEM;
+ goto done;
+ }
+
+ if (virtio_usb_ep_comp_valid(comp))
+ n_sgs = 2;
+
+ sg_init_table(psg_data, n_sgs);
+ sg_set_buf(&psg_data[0], desc, sizeof(*desc));
+ if (n_sgs == 2)
+ sg_set_buf(&psg_data[1], comp, sizeof(*comp));
+ hdr = virtio_usb_cmd_request(cmd);
+ hdr->endpoint = cpu_to_le16(endpoint);
+
+ rc = virtio_usb_cmd_send_sync(vudc->vusb, psg_data, NULL, cmd);
+
+done:
+ spin_lock_irqsave(&vudc->lock, flags);
+ if (!rc) {
+ vep->state = EP_ENABLED;
+ vep->last_err = 0;
+ /* Flush pend_queue */
+ while (!list_empty(&vep->pend_queue)) {
+ struct virtio_usb_data *vreq = list_first_entry(
+ &vep->pend_queue, struct virtio_usb_data, list);
+ struct virtio_usb_dc_priv *priv =
+ virtio_usb_data_priv(vreq);
+ int qrc;
+
+ list_del_init(&vreq->list);
+ spin_unlock_irqrestore(&vudc->lock, flags);
+ qrc = do_real_queue(vep, &priv->req);
+ /*
+ * do_real_queue() takes its own ref for the
+ * in-flight/vring lifetime; drop the ref that kept
+ * vreq alive while it was parked in pend_queue.
+ */
+ virtio_usb_data_unref(vreq);
+ if (qrc) {
+ /*
+ * Request was accepted while EP was ENABLING.
+ * If forwarding now fails, complete it with
+ * error instead of silently dropping it.
+ */
+ priv->req.status = qrc;
+ usb_gadget_giveback_request(&vep->ep,
+ &priv->req);
+ }
+ spin_lock_irqsave(&vudc->lock, flags);
+ }
+ } else {
+ vep->state = EP_HALTED;
+ vep->last_err = rc;
+
+ while (!list_empty(&vep->pend_queue)) {
+ struct virtio_usb_data *vreq = list_first_entry(
+ &vep->pend_queue, struct virtio_usb_data, list);
+ struct virtio_usb_dc_priv *priv =
+ virtio_usb_data_priv(vreq);
+
+ list_del_init(&vreq->list);
+ priv->req.status = rc;
+ spin_unlock_irqrestore(&vudc->lock, flags);
+ virtio_usb_data_unref(vreq);
+ usb_gadget_giveback_request(&vep->ep, &priv->req);
+ spin_lock_irqsave(&vudc->lock, flags);
+ }
+ }
+ spin_unlock_irqrestore(&vudc->lock, flags);
+ virtio_usb_dc_flush_ep0_pend(vudc);
+}
+
+static void vep_disable_work(struct work_struct *work)
+{
+ struct virtio_usb_ep *vep =
+ container_of(work, struct virtio_usb_ep, disable_work);
+ struct virtio_usb_dc *vudc = vep->vudc;
+ struct virtio_usb_cmd *cmd;
+ struct virtio_usb_dev_cmd_hdr *hdr;
+ u16 endpoint;
+
+ if (!READ_ONCE(vudc->driver) || !vudc->registered)
+ return;
+
+ endpoint = vep->ep_id |
+ (usb_ep_dir_in(&vep->ep) ? VIRTIO_USB_EP_DIR_IN :
+ VIRTIO_USB_EP_DIR_OUT);
+
+ cmd = virtio_usb_dc_cmd_alloc(vudc, VIRTIO_USB_CMD_DEV_EP_DISABLE,
+ GFP_KERNEL);
+ if (!cmd)
+ return;
+
+ hdr = virtio_usb_cmd_request(cmd);
+ hdr->endpoint = cpu_to_le16(endpoint);
+
+ (void)virtio_usb_cmd_send_sync(vudc->vusb, NULL, NULL, cmd);
+}
+
+/**
+ * virtio_ep_enable() - Enable endpoint
+ * This callback is called to configure endpoint and make it usable.
+ * It is called to enable all endpoints except ep0
+ * @ep: endpoint object
+ * @desc: endpoint descriptor
+ *
+ * Context: Any context.
+ * Return: 0 on success, -errno on failure.
+ */
+static int virtio_ep_enable(struct usb_ep *ep,
+ const struct usb_endpoint_descriptor *desc)
+{
+ struct virtio_usb_ep *vep = usb_ep_to_virtio_ep(ep);
+ struct virtio_usb_dc *vudc = vep->vudc;
+ const struct usb_ss_ep_comp_descriptor *comp = ep->comp_desc;
+ unsigned long flags;
+
+ spin_lock_irqsave(&vudc->lock, flags);
+
+ if (!vudc->driver || !ep || !desc || ep->caps.type_control ||
+ desc->bDescriptorType != USB_DT_ENDPOINT) {
+ spin_unlock_irqrestore(&vudc->lock, flags);
+ return -EINVAL;
+ }
+
+ if (vep->state != EP_DISABLED) {
+ spin_unlock_irqrestore(&vudc->lock, flags);
+ return -EBUSY;
+ }
+
+ if (comp) {
+ if (!virtio_usb_ep_comp_valid(comp) || comp->bMaxBurst > 15) {
+ spin_unlock_irqrestore(&vudc->lock, flags);
+ return -EINVAL;
+ }
+ } else if (vudc->gadget.speed >= USB_SPEED_SUPER) {
+ spin_unlock_irqrestore(&vudc->lock, flags);
+ return -EINVAL;
+ }
+
+ ep->desc = desc;
+ ep->maxpacket = usb_endpoint_maxp(desc);
+ vep->state = EP_ENABLING;
+
+ queue_work(vudc->ep_cmd_wq, &vep->enable_work);
+
+ spin_unlock_irqrestore(&vudc->lock, flags);
+
+ return 0;
+}
+
+/**
+ * virtio_ep_disable() - Disable endpoint
+ * This callback is called to disable endpoint which was
+ * enabled using ep_enable callback
+ * @ep: endpoint object
+ *
+ * Context: Any context.
+ * Return: 0 on success, -errno on failure.
+ */
+static int virtio_ep_disable(struct usb_ep *ep)
+{
+ struct virtio_usb_ep *vep = usb_ep_to_virtio_ep(ep);
+ struct virtio_usb_data *vreq = NULL, *vreq_tmp;
+ struct virtio_usb_dc *vudc = vep->vudc;
+ struct virtio_usb_dc_priv *priv = NULL;
+ LIST_HEAD(giveback_inflight);
+ LIST_HEAD(giveback_pended);
+ unsigned long flags;
+
+ if (!ep || ep->caps.type_control) // EP0 not called disable
+ return -EINVAL;
+
+ spin_lock_irqsave(&vudc->lock, flags);
+
+ if (vep->state == EP_ENABLING) {
+ /*
+ * cancel_work_sync() can sleep and must not be called while
+ * holding vudc->lock: vep_enable_work() only re-acquires
+ * this same lock after its (possibly blocking) virtio
+ * command completes, so holding the lock here across
+ * cancel_work_sync() would deadlock against it.
+ */
+ spin_unlock_irqrestore(&vudc->lock, flags);
+ cancel_work_sync(&vep->enable_work);
+ spin_lock_irqsave(&vudc->lock, flags);
+ }
+
+ if (vep->state == EP_DISABLED) {
+ spin_unlock_irqrestore(&vudc->lock, flags);
+ return 0;
+ }
+
+ vep->state = EP_DISABLED;
+
+ /*
+ * All pending (waiting for the ENABLING) - put to local list for
+ * giveback(-ESHUTDOWN). These requests are not in the virtqueue,
+ * can be unref now.
+ */
+ list_for_each_entry_safe(vreq, vreq_tmp, &vep->pend_queue, list) {
+ list_del_init(&vreq->list);
+ list_add_tail(&vreq->list, &giveback_pended);
+ }
+
+ /*
+ * in-flight requests - make early giveback, remove from req_queue,
+ * mark completed_early, but do not unref: unref will be in complete
+ * handler.
+ */
+ list_for_each_entry_safe(vreq, vreq_tmp, &vep->req_queue, list) {
+ priv = virtio_usb_data_priv(vreq);
+ priv->req.status = -ESHUTDOWN;
+ priv->completed_early = true;
+ list_del_init(&vreq->list);
+ list_add_tail(&vreq->list, &giveback_inflight);
+ }
+
+ spin_unlock_irqrestore(&vudc->lock, flags);
+
+ /* pending: just giveback and unref */
+ list_for_each_entry_safe(vreq, vreq_tmp, &giveback_pended, list) {
+ struct virtio_usb_dc_priv *p = virtio_usb_data_priv(vreq);
+
+ list_del_init(&vreq->list);
+ p->req.status = -ESHUTDOWN;
+ usb_gadget_giveback_request(&vep->ep, &p->req);
+ virtio_usb_data_unref(
+ vreq); /* drop the pend_queue ref taken in virtio_ep_queue() */
+ }
+
+ /* in-flight: giveback now, unref will be in complete_req */
+ list_for_each_entry_safe(vreq, vreq_tmp, &giveback_inflight, list) {
+ struct virtio_usb_dc_priv *p = virtio_usb_data_priv(vreq);
+
+ list_del_init(&vreq->list);
+ usb_gadget_giveback_request(&vep->ep, &p->req);
+ }
+
+ queue_work(vudc->ep_cmd_wq, &vep->disable_work);
+
+ return 0;
+}
+
+/**
+ * virtio_ep_alloc_request() - Allocates request
+ * @ep: Endpoint object associated with request
+ * @mem_flags: mem flags
+ *
+ * Return: allocated request address, NULL on allocation error
+ */
+static struct usb_request *virtio_ep_alloc_request(struct usb_ep *ep,
+ gfp_t mem_flags)
+{
+ struct virtio_usb_dc_priv *priv;
+ struct virtio_usb_data *vreq;
+
+ vreq = virtio_usb_dc_data_alloc(ep, mem_flags);
+ if (!vreq)
+ return NULL;
+
+ priv = virtio_usb_data_priv(vreq);
+
+ return &priv->req;
+}
+
+/**
+ * virtio_ep_free_request() - Free memory occupied by request
+ * @ep: Endpoint object associated with request
+ * @req: Request to be freed
+ */
+static void virtio_ep_free_request(struct usb_ep *ep, struct usb_request *req)
+{
+ struct virtio_usb_data *vreq = usb_req_to_virtio_data(req);
+
+ virtio_usb_data_unref(vreq);
+}
+
+/**
+ * virtio_ep_queue() - Transfer data on and endpoint
+ * @ep: Pointer to endpoint object
+ * @req: Pointer to request object
+ * @mem_flags: gfp flags
+ *
+ * Context: Any context.
+ * Return: 0 on success, -errno on failure.
+ */
+static int virtio_ep_queue(struct usb_ep *ep, struct usb_request *req,
+ gfp_t mem_flags)
+{
+ struct virtio_usb_data *vreq = usb_req_to_virtio_data(req);
+ struct virtio_usb_ep *vep = usb_ep_to_virtio_ep(ep);
+ struct virtio_usb_dc *vudc = vep->vudc;
+ unsigned long flags;
+ int rc = 0;
+
+ spin_lock_irqsave(&vudc->lock, flags);
+
+ switch (vep->state) {
+ case EP_ENABLED:
+ if (!vep->ep_id && virtio_usb_dc_ep_enabling_locked(vudc)) {
+ virtio_usb_data_ref(vreq);
+ req->actual = 0;
+ req->status = -EINPROGRESS;
+ list_add_tail(&vreq->list, &vep->pend_queue);
+ spin_unlock_irqrestore(&vudc->lock, flags);
+ return 0;
+ }
+ spin_unlock_irqrestore(&vudc->lock, flags);
+ rc = do_real_queue(vep, req);
+ /* if rc==0 - unref will be in completion, on failure
+ * do_real_queue() has already dropped its own ref
+ */
+ return rc;
+
+ case EP_ENABLING:
+ /* Waiting for ENABLED state */
+ virtio_usb_data_ref(vreq);
+ req->actual = 0;
+ req->status = -EINPROGRESS;
+ list_add_tail(&vreq->list, &vep->pend_queue);
+ spin_unlock_irqrestore(&vudc->lock, flags);
+ // Additional ref waited for the enable_work()
+ return 0;
+
+ case EP_HALTED:
+ /*
+ * Endpoint enable failed. Fail the submission without calling
+ * the completion: gadget drivers commonly resubmit from their
+ * completion handler, so a giveback here would recurse.
+ */
+ rc = vep->last_err ? vep->last_err : -EPIPE;
+ spin_unlock_irqrestore(&vudc->lock, flags);
+ return rc;
+
+ case EP_DISABLED:
+ default:
+ spin_unlock_irqrestore(&vudc->lock, flags);
+ return -ESHUTDOWN;
+ }
+}
+
+/**
+ * virtio_ep_dequeue() - Remove request from transfer queue
+ * @ep: Endpoint object associated with request
+ * @req: Request object
+ *
+ * Context: Any context.
+ * Return: 0 on success, -errno on failure.
+ */
+static int virtio_ep_dequeue(struct usb_ep *ep, struct usb_request *req)
+{
+ struct virtio_usb_ep *vep = usb_ep_to_virtio_ep(ep);
+ struct virtio_usb_dc *vudc = vep->vudc;
+ struct virtio_usb_dc_priv *priv;
+ struct virtio_usb_data *vreq;
+ unsigned long flags;
+ int rc = -EINVAL;
+
+ if (!vudc->driver)
+ return -ESHUTDOWN;
+
+ spin_lock_irqsave(&vudc->lock, flags);
+
+ /* If request is still pending (ENABLING) */
+ list_for_each_entry(vreq, &vep->pend_queue, list) {
+ priv = virtio_usb_data_priv(vreq);
+ if (&priv->req == req) {
+ list_del_init(&vreq->list);
+ req->status = -ECONNRESET;
+ spin_unlock_irqrestore(&vudc->lock, flags);
+
+ virtio_usb_data_unref(vreq);
+ usb_gadget_giveback_request(ep, req);
+ return 0;
+ }
+ }
+
+ /* in-flight - schedule async cancel */
+ list_for_each_entry(vreq, &vep->req_queue, list) {
+ priv = virtio_usb_data_priv(vreq);
+ if (req == &priv->req) {
+ pr_debug("dequeue for vreq = %p, tag %llu\n", vreq,
+ priv->tag);
+ // request will be completed from the completion handler
+ priv->req.status = -ECONNRESET;
+ priv->cancel_tag = priv->tag;
+ virtio_usb_dc_schedule_cancel(vreq);
+ rc = 0;
+ break;
+ }
+ }
+ spin_unlock_irqrestore(&vudc->lock, flags);
+
+ return rc;
+}
+
+/**
+ * virtio_ep_set_halt() - Sets/clears stall on selected endpoint
+ * @ep: Endpoint object to set/clear stall on
+ * @value: 1 for set stall, 0 for clear stall
+ *
+ * Context: Any context.
+ * Return: 0 on success, -errno on failure.
+ */
+static int virtio_ep_set_halt(struct usb_ep *ep, int value)
+{
+ struct virtio_usb_ep *vep = usb_ep_to_virtio_ep(ep);
+ struct virtio_usb_dev_cmd_set_value *req;
+ struct virtio_usb_dc *vudc = vep->vudc;
+ struct virtio_usb_cmd *cmd;
+ unsigned long flags;
+ u16 endpoint;
+ int rc;
+
+ spin_lock_irqsave(&vudc->lock, flags);
+
+ /*
+ * EP0 MUST NOT STALL if a control request is still pending.
+ * Composite expects -EAGAIN instead of a forced STALL, otherwise
+ * status stage collapses and the host sees EPROTO/EPIPE.
+ */
+ if (&vep->ep == vudc->gadget.ep0) {
+ if (value && !list_empty(&vep->req_queue)) {
+ spin_unlock_irqrestore(&vudc->lock, flags);
+ return -EAGAIN;
+ }
+ }
+
+ if (value && ep->desc && usb_ep_dir_in(ep) &&
+ !list_empty(&vep->req_queue)) {
+ spin_unlock_irqrestore(&vudc->lock, flags);
+ return -EAGAIN;
+ }
+ endpoint = vep->ep_id | (usb_ep_dir_in(ep) ? VIRTIO_USB_EP_DIR_IN :
+ VIRTIO_USB_EP_DIR_OUT);
+ spin_unlock_irqrestore(&vudc->lock, flags);
+
+ cmd = virtio_usb_dc_cmd_alloc(vudc, VIRTIO_USB_CMD_DEV_EP_SET_HALT,
+ GFP_ATOMIC);
+ if (!cmd)
+ return -ENOMEM;
+
+ req = virtio_usb_cmd_request(cmd);
+ req->value = cpu_to_le32(value);
+ req->hdr.endpoint = cpu_to_le16(endpoint);
+
+ rc = virtio_usb_cmd_send_sync(vudc->vusb, NULL, NULL, cmd);
+
+ return rc;
+}
+
+/**
+ * virtio_ep_set_wedge() - Set wedge on selected endpoint
+ * @ep: Endpoint object
+ *
+ * Context: Any context.
+ * Return: 0 on success, -errno on failure.
+ */
+static int virtio_ep_set_wedge(struct usb_ep *ep)
+{
+ struct virtio_usb_ep *vep = usb_ep_to_virtio_ep(ep);
+ struct virtio_usb_dc *vudc = vep->vudc;
+ struct virtio_usb_dev_cmd_hdr *hdr;
+ struct virtio_usb_cmd *cmd;
+ unsigned long flags;
+ u16 endpoint;
+ int rc;
+
+ spin_lock_irqsave(&vudc->lock, flags);
+ endpoint = vep->ep_id | (usb_ep_dir_in(ep) ? VIRTIO_USB_EP_DIR_IN :
+ VIRTIO_USB_EP_DIR_OUT);
+ spin_unlock_irqrestore(&vudc->lock, flags);
+
+ cmd = virtio_usb_dc_cmd_alloc(vudc, VIRTIO_USB_CMD_DEV_EP_SET_WEDGE,
+ GFP_ATOMIC);
+ if (!cmd)
+ return -ENOMEM;
+
+ hdr = virtio_usb_cmd_request(cmd);
+ hdr->endpoint = cpu_to_le16(endpoint);
+
+ rc = virtio_usb_cmd_send_sync(vudc->vusb, NULL, NULL, cmd);
+
+ return rc;
+}
+
+static const struct usb_ep_ops virtio_usb_ep_ops = {
+ .enable = virtio_ep_enable,
+ .disable = virtio_ep_disable,
+
+ .alloc_request = virtio_ep_alloc_request,
+ .free_request = virtio_ep_free_request,
+
+ .queue = virtio_ep_queue,
+ .dequeue = virtio_ep_dequeue,
+
+ .set_halt = virtio_ep_set_halt,
+ .set_wedge = virtio_ep_set_wedge,
+};
+
+/*-------------------------------------------------------------------------*/
+/* UDC callbacks */
+
+static void virtio_usb_dc_cancel_work(struct work_struct *work)
+{
+ struct virtio_usb_dc_priv *priv =
+ container_of(work, struct virtio_usb_dc_priv, cancel_work);
+ struct virtio_usb_ep *vep = priv->vep;
+ struct virtio_usb_dc *vudc = vep->vudc;
+ struct virtio_usb_cmd *cmd;
+ struct virtio_usb_dev_cmd_cancel *cancel;
+ struct virtio_usb_data *vreq = priv->vreq;
+ unsigned long flags;
+ u16 endpoint;
+ struct virtio_usb_data *iter;
+ bool found = false;
+ u64 tag;
+
+ spin_lock_irqsave(&vudc->lock, flags);
+
+ list_for_each_entry(iter, &vep->req_queue, list) {
+ if (iter == vreq) {
+ found = true;
+ break;
+ }
+ }
+ /*
+ * The request may have completed and been queued again since
+ * virtio_ep_dequeue() scheduled this work. Then the submission to
+ * cancel is gone and the one on req_queue must be left alone.
+ */
+ if (!found || priv->cancel_tag != priv->tag) {
+ spin_unlock_irqrestore(&vudc->lock, flags);
+ goto out;
+ }
+ /*
+ * The request is on req_queue but may not have reached the data
+ * virtqueue yet, in which case the device side cannot match the tag:
+ * it would answer the DEV_CANCEL with success and drop it, and the
+ * request queued right after would never be cancelled. Let
+ * do_real_queue() reschedule this work once the request is queued.
+ */
+ if (!priv->submitted) {
+ priv->cancel_pending = true;
+ spin_unlock_irqrestore(&vudc->lock, flags);
+ goto out;
+ }
+ endpoint = vep->ep_id |
+ (usb_ep_dir_in(&vep->ep) ? VIRTIO_USB_EP_DIR_IN :
+ VIRTIO_USB_EP_DIR_OUT);
+ /*
+ * Once the lock is dropped the request can still complete and be
+ * queued again before the DEV_CANCEL reaches the device. The cancel
+ * carries the tag of the dequeued submission, so the device side
+ * does not find it and answers with success, leaving the new
+ * submission alone.
+ */
+ tag = priv->tag;
+ spin_unlock_irqrestore(&vudc->lock, flags);
+
+ cmd = virtio_usb_dc_cmd_alloc(vudc, VIRTIO_USB_CMD_DEV_CANCEL,
+ GFP_KERNEL);
+ if (!cmd)
+ goto out;
+
+ cancel = virtio_usb_cmd_request(cmd);
+ cancel->hdr.endpoint = cpu_to_le16(endpoint);
+ cancel->hdr.port = cpu_to_le16(vudc->port);
+ cancel->tag = cpu_to_le64(tag);
+
+ (void)virtio_usb_cmd_send_sync(vudc->vusb, NULL, NULL, cmd);
+
+out:
+ /* Taken by virtio_usb_dc_schedule_cancel(). May free the request,
+ * and with it this work item, so nothing may touch priv after this.
+ */
+ virtio_usb_data_unref(vreq);
+}
+
+static int virtio_usb_dc_send_cmd(struct virtio_usb_dc *vudc,
+ unsigned int cmd_code, unsigned int val)
+{
+ struct virtio_usb_dev_cmd_set_value *req;
+ struct virtio_usb_cmd *cmd;
+
+ cmd = virtio_usb_dc_cmd_alloc(vudc, cmd_code, GFP_ATOMIC);
+ if (!cmd)
+ return -ENOMEM;
+
+ req = virtio_usb_cmd_request(cmd);
+ req->value = cpu_to_le32(val);
+
+ return virtio_usb_cmd_send_sync(vudc->vusb, NULL, NULL, cmd);
+}
+
+static void virtio_usb_dc_work(struct work_struct *work)
+{
+ struct virtio_usb_dc *vudc =
+ container_of(work, struct virtio_usb_dc, dc_cmd_work);
+ int sp, ma;
+
+ mutex_lock(&vudc->dc_cmd_work_lock);
+
+ sp = atomic_xchg(&vudc->pending_self_pwr, -1);
+ ma = atomic_xchg(&vudc->pending_vbus_ma, -1);
+
+ if (sp >= 0) {
+ bool new_sp = (sp != 0);
+
+ if (new_sp != vudc->cur_self_pwr) {
+ (void)virtio_usb_dc_send_cmd(
+ vudc, VIRTIO_USB_CMD_DEV_SET_SELF_POWERED,
+ new_sp);
+ vudc->cur_self_pwr = new_sp;
+ }
+ }
+
+ if (ma >= 0) {
+ unsigned int new_ma = (unsigned int)ma;
+
+ if (vudc->cur_self_pwr)
+ new_ma = 0;
+
+ if (new_ma != vudc->cur_vbus_ma) {
+ (void)virtio_usb_dc_send_cmd(
+ vudc, VIRTIO_USB_CMD_DEV_VBUS_DRAW, new_ma);
+ vudc->cur_vbus_ma = new_ma;
+ }
+ }
+
+ mutex_unlock(&vudc->dc_cmd_work_lock);
+
+ if (atomic_read(&vudc->pending_self_pwr) >= 0 ||
+ atomic_read(&vudc->pending_vbus_ma) >= 0) {
+ queue_work(vudc->dc_cmd_wq, &vudc->dc_cmd_work);
+ }
+}
+
+/**
+ * virtio_usb_dc_set_selfpowered() - Sets the device selfpowered feature.
+ * @gadget: The device being declared as self-powered
+ * @is_selfpowered: Flag indicates if gadget is selfpowered
+ *
+ * Return: 0 on success, -errno on failure.
+ */
+static int virtio_usb_dc_set_selfpowered(struct usb_gadget *gadget,
+ int is_selfpowered)
+{
+ struct virtio_usb_dc *vudc =
+ container_of(gadget, struct virtio_usb_dc, gadget);
+
+ atomic_set(&vudc->pending_self_pwr, is_selfpowered ? 1 : 0);
+ queue_work(vudc->dc_cmd_wq, &vudc->dc_cmd_work);
+
+ return 0;
+}
+
+/**
+ * virtio_usb_dc_pullup() - Software-controlled connect/disconnect to USB host
+ * @gadget: Pointer to the usb gadget structure.
+ * @is_on: flag to start or stop
+ *
+ * Return: 0 on success, -errno on failure.
+ */
+static int virtio_usb_dc_pullup(struct usb_gadget *gadget, int is_on)
+{
+ struct virtio_usb_dc *vudc =
+ container_of(gadget, struct virtio_usb_dc, gadget);
+ unsigned int code = VIRTIO_USB_CMD_DEV_PULLUP;
+ struct virtio_usb_dev_cmd_set_value *req;
+ struct virtio_usb_cmd *cmd;
+ unsigned long flags;
+ int rc;
+
+ spin_lock_irqsave(&vudc->lock, flags);
+ is_on = !!is_on;
+ if (is_on == vudc->pullup) {
+ rc = -EALREADY;
+ goto on_unlock;
+ }
+
+ vudc->pullup = is_on;
+ spin_unlock_irqrestore(&vudc->lock, flags);
+
+ cmd = virtio_usb_dc_cmd_alloc(vudc, code, GFP_ATOMIC);
+ if (!cmd)
+ return -ENOMEM;
+
+ req = virtio_usb_cmd_request(cmd);
+ req->value = cpu_to_le32(is_on);
+
+ rc = virtio_usb_cmd_send_sync(vudc->vusb, NULL, NULL, cmd);
+
+ return rc;
+
+on_unlock:
+ spin_unlock_irqrestore(&vudc->lock, flags);
+
+ return rc;
+}
+
+/**
+ * virtio_usb_dc_set_speed() - Sets maximum speed supported by gadget
+ * @gadget: Pointer to the usb gadget structure.
+ * @speed: The maximum speed to allowed to run
+ */
+static void virtio_usb_dc_set_speed(struct usb_gadget *gadget,
+ enum usb_device_speed speed)
+{
+ struct virtio_usb_dc *vudc =
+ container_of(gadget, struct virtio_usb_dc, gadget);
+
+ vudc->gadget.speed = min_t(u8, vudc->gadget.max_speed, speed);
+
+ switch (vudc->gadget.speed) {
+ case USB_SPEED_SUPER_PLUS:
+ case USB_SPEED_SUPER:
+ vudc->veps[0].ep.maxpacket = 512;
+ break;
+ case USB_SPEED_HIGH:
+ case USB_SPEED_FULL:
+ vudc->veps[0].ep.maxpacket = 64;
+ break;
+ case USB_SPEED_LOW:
+ vudc->veps[0].ep.maxpacket = 8;
+ break;
+ default:
+ break;
+ }
+}
+
+/**
+ * virtio_usb_dc_start() - Starts the device controller.
+ * @gadget: Pointer to the usb gadget structure
+ * @driver: Pointer to gadget driver structure
+ *
+ * Return: zero always
+ */
+static int virtio_usb_dc_start(struct usb_gadget *gadget,
+ struct usb_gadget_driver *driver)
+{
+ struct virtio_usb_dc *vudc =
+ container_of(gadget, struct virtio_usb_dc, gadget);
+ unsigned long flags;
+
+ spin_lock_irqsave(&vudc->lock, flags);
+ vudc->driver = driver;
+ vudc->pullup = 0;
+ spin_unlock_irqrestore(&vudc->lock, flags);
+
+ return 0;
+}
+
+/**
+ * virtio_usb_dc_stop() - Stops the device controller.
+ * @gadget: Pointer to the usb gadget structure
+ *
+ * Return: zero always
+ */
+static int virtio_usb_dc_stop(struct usb_gadget *gadget)
+{
+ struct virtio_usb_dc *vudc =
+ container_of(gadget, struct virtio_usb_dc, gadget);
+ unsigned long flags;
+
+ spin_lock_irqsave(&vudc->lock, flags);
+ vudc->driver = NULL;
+ vudc->pullup = 0;
+ spin_unlock_irqrestore(&vudc->lock, flags);
+
+ return 0;
+}
+
+/**
+ * virtio_usb_dc_vbus_draw() - Constrain controller's VBUS power usage
+ * @gadget: The device whose VBUS usage is being described
+ * @ma: How much current to draw, in milliAmperes.
+ *
+ * Return: 0 on success, -errno on failure.
+ */
+static int virtio_usb_dc_vbus_draw(struct usb_gadget *gadget, unsigned int ma)
+{
+ struct virtio_usb_dc *vudc =
+ container_of(gadget, struct virtio_usb_dc, gadget);
+
+ atomic_set(&vudc->pending_vbus_ma, ma);
+ queue_work(vudc->dc_cmd_wq, &vudc->dc_cmd_work);
+ return 0;
+}
+
+/**
+ * virtio_usb_dc_get_frame() - returns the current frame number
+ * @gadget: controller that reports the frame number
+ *
+ * Return: Returns the usb frame number, normally eleven bits from
+ * a SOF packet, or -errno on failure.
+ */
+static int virtio_usb_dc_get_frame(struct usb_gadget *gadget)
+{
+ struct virtio_usb_dc *vudc =
+ container_of(gadget, struct virtio_usb_dc, gadget);
+ unsigned int code = VIRTIO_USB_CMD_DEV_GET_FRAME_NUMBER;
+ struct virtio_usb_dev_frame_number *resp;
+ struct virtio_usb_cmd *cmd;
+ int rc;
+
+ cmd = virtio_usb_dc_cmd_alloc(vudc, code, GFP_ATOMIC);
+ if (!cmd)
+ return -ENOMEM;
+
+ rc = virtio_usb_cmd_send_sync(vudc->vusb, NULL, NULL, cmd);
+ if (rc)
+ return rc;
+
+ resp = virtio_usb_cmd_response(cmd);
+ rc = le32_to_cpu(resp->frame_number);
+
+ return rc;
+}
+
+static const struct usb_gadget_ops virtio_gadget_ops = {
+ .set_selfpowered = virtio_usb_dc_set_selfpowered,
+ .pullup = virtio_usb_dc_pullup,
+ .udc_start = virtio_usb_dc_start,
+ .udc_stop = virtio_usb_dc_stop,
+ .vbus_draw = virtio_usb_dc_vbus_draw,
+ .udc_set_speed = virtio_usb_dc_set_speed,
+ .get_frame = virtio_usb_dc_get_frame,
+};
+
+/*-------------------------------------------------------------------------*/
+
+/**
+ * virtio_usb_dc_get_endpoint_count() - Function to get the number of
+ * endpoints from the virtio-usb device
+ * @vudc: VirtIO usb device controller
+ *
+ * Context: Process context.
+ * Return: 0 on success, -errno on failure.
+ */
+static int virtio_usb_dc_get_endpoint_count(struct virtio_usb_dc *vudc)
+{
+ unsigned int code = VIRTIO_USB_CMD_DEV_GET_ENDPOINT_COUNT;
+ struct virtio_usb_dev_ep_count *ep_count;
+ struct virtio_usb_cmd *cmd;
+ int rc;
+
+ cmd = virtio_usb_dc_cmd_alloc(vudc, code, GFP_KERNEL);
+ if (!cmd)
+ return -ENOMEM;
+
+ virtio_usb_cmd_ref(cmd);
+ rc = virtio_usb_cmd_send_sync(vudc->vusb, NULL, NULL, cmd);
+ if (rc)
+ goto on_exit;
+
+ ep_count = virtio_usb_cmd_response(cmd);
+ vudc->neps = le32_to_cpu(ep_count->count);
+ if (!vudc->neps)
+ rc = -EINVAL;
+
+on_exit:
+ virtio_usb_cmd_unref(cmd);
+ return rc;
+}
+
+/**
+ * virtio_usb_dc_get_endpoint_info() - Function to get the endpoint
+ * info from virtio-usb device.
+ * @vudc: VirtIO usb device controller
+ *
+ * Context: Process context.
+ * Return: 0 on success, -errno on failure.
+ */
+static int virtio_usb_dc_get_endpoint_info(struct virtio_usb_dc *vudc)
+{
+ unsigned int code = VIRTIO_USB_CMD_DEV_GET_ENDPOINT_INFO;
+ struct virtio_usb_dev_ep_info *epinfo;
+ struct virtio_usb_cmd *cmd;
+ struct scatterlist sg;
+ struct scatterlist *psg_data = &sg;
+ int rc, i;
+
+ vudc->veps = kcalloc(vudc->neps, sizeof(*vudc->veps) + sizeof(*epinfo),
+ GFP_KERNEL);
+ if (!vudc->veps)
+ return -ENOMEM;
+
+ epinfo = (void *)vudc->veps + (sizeof(*vudc->veps) * vudc->neps);
+
+ cmd = virtio_usb_dc_cmd_alloc(vudc, code, GFP_KERNEL);
+ if (!cmd) {
+ rc = -ENOMEM;
+ goto on_error;
+ }
+ virtio_usb_cmd_ref(cmd);
+
+ sg_init_one(psg_data, epinfo, sizeof(*epinfo) * vudc->neps);
+
+ rc = virtio_usb_cmd_send_sync(vudc->vusb, NULL, psg_data, cmd);
+ if (rc) {
+ virtio_usb_cmd_unref(cmd);
+ goto on_error;
+ }
+
+ INIT_LIST_HEAD(&vudc->gadget.ep_list);
+
+ for (i = 0; i < vudc->neps; i++) {
+ struct virtio_usb_ep *vep = &vudc->veps[i];
+ u16 types = le16_to_cpu(epinfo[i].types);
+ u16 directions = le16_to_cpu(epinfo[i].directions);
+ struct usb_ep_caps caps = VIRTIO_USB_EP_CAPS(types, directions);
+ unsigned int maxpacket_limit =
+ le16_to_cpu(epinfo[i].maxpacket_limit);
+
+ strscpy(vep->name, epinfo[i].name, sizeof(vep->name));
+ vep->ep_id = i;
+ vep->ep.caps = caps;
+ vep->ep.name = vep->name;
+ vep->ep.ops = &virtio_usb_ep_ops;
+ INIT_LIST_HEAD(&vep->req_queue);
+ INIT_LIST_HEAD(&vep->pend_queue);
+ vep->state = i ? EP_DISABLED : EP_ENABLED; // EP0 always enabled
+ INIT_WORK(&vep->enable_work, vep_enable_work);
+ INIT_WORK(&vep->disable_work, vep_disable_work);
+ vep->last_err = 0;
+ list_add_tail(&vep->ep.ep_list, &vudc->gadget.ep_list);
+ usb_ep_set_maxpacket_limit(&vep->ep, maxpacket_limit);
+ vep->ep.max_streams = le16_to_cpu(epinfo[i].max_streams);
+ vep->vudc = vudc;
+ }
+ virtio_usb_cmd_unref(cmd);
+ vudc->gadget.ep0 = &vudc->veps[0].ep;
+ list_del_init(&vudc->veps[0].ep.ep_list);
+
+ return rc;
+
+on_error:
+ kfree(vudc->veps);
+ vudc->veps = NULL;
+ return rc;
+}
+
+static int virtio_usb_dc_parent_create(struct virtio_usb_dc *vudc)
+{
+ int rc;
+
+ vudc->pdev = platform_device_alloc(GADGET_NAME, vudc->port);
+ if (!vudc->pdev)
+ return -ENOMEM;
+
+ vudc->pdev->dev.parent = &vudc->vusb->vdev->dev;
+ rc = platform_device_add(vudc->pdev);
+ if (rc) {
+ platform_device_put(vudc->pdev);
+ vudc->pdev = NULL;
+ return rc;
+ }
+
+ return 0;
+}
+
+/**
+ * virtio_usb_dc_event_padding_ok() - Check that reserved event bytes are zero.
+ * @evt: Received device event buffer.
+ *
+ * The padding fields are reserved for future extensions. Rejecting
+ * non-zero values now keeps them usable later without a feature bit.
+ * BIND uses those bytes for max_speed/udc_name_prefix and has no
+ * padding.
+ *
+ * Context: Any context.
+ * Return: true if all reserved bytes for the event code are zero.
+ */
+static bool virtio_usb_dc_event_padding_ok(struct virtio_usb_dev_event *evt)
+{
+ struct virtio_usb_dev_setup_event *setup_evt =
+ (struct virtio_usb_dev_setup_event *)evt;
+
+ switch (le32_to_cpu(evt->code)) {
+ case VIRTIO_USB_EVT_DEV_BIND:
+ return true;
+ case VIRTIO_USB_EVT_DEV_SETUP:
+ return !memchr_inv(setup_evt->padding, 0,
+ sizeof(setup_evt->padding));
+ default:
+ return !memchr_inv(evt->padding, 0, sizeof(evt->padding));
+ }
+}
+
+/**
+ * virtio_usb_dc_event_process() - Event process function
+ * @event: virtio_usb_event
+ *
+ * Context: Process context.
+ * Return: 0 on success, -errno on failure.
+ */
+static void virtio_usb_dc_event_process(struct virtio_usb_event *event)
+{
+ struct virtio_usb_dev_event *evt = virtio_usb_event_buf(event);
+ struct virtio_usb_dev_bind_event *bind_evt =
+ (struct virtio_usb_dev_bind_event *)evt;
+ struct virtio_usb_dev_setup_event *setup_evt;
+ struct virtio_usb *vusb = event->vusb;
+ struct virtio_usb_dc *vudc;
+ struct usb_gadget_driver *driver;
+ struct virtio_usb_ep *vep;
+ unsigned long flags;
+ int rc = 0;
+ unsigned short port_id = le16_to_cpu(evt->port);
+
+ if (!vusb->nports || port_id >= vusb->nports) {
+ dev_err(&vusb->vdev->dev, "%s port[%d] index out of range\n",
+ __func__, port_id);
+ return;
+ }
+
+ if (!virtio_usb_dc_event_padding_ok(evt)) {
+ dev_err(&vusb->vdev->dev,
+ "port %d: event %u with non-zero padding, ignoring\n",
+ port_id, le32_to_cpu(evt->code));
+ return;
+ }
+
+ vudc = vusb->vports[port_id].vudc;
+ driver = vudc->driver;
+
+ switch (le32_to_cpu(evt->code)) {
+ case VIRTIO_USB_EVT_DEV_BIND: {
+ u8 max_speed;
+
+ if (vudc->registered) {
+ dev_err(&vusb->vdev->dev,
+ "port %d: BIND while still registered, ignoring\n",
+ port_id);
+ rc = -EBUSY;
+ break;
+ }
+
+ memzero_explicit(&vudc->gadget, sizeof(struct usb_gadget));
+ vudc->gadget.sg_supported = 1;
+ max_speed = bind_evt->max_speed;
+
+ rc = virtio_usb_dc_get_endpoint_count(vudc);
+ if (rc) {
+ dev_err(&vusb->vdev->dev,
+ "Failed to get endpoint count\n");
+ break;
+ }
+ rc = virtio_usb_dc_get_endpoint_info(vudc);
+ if (rc) {
+ dev_err(&vusb->vdev->dev,
+ "Failed to get endpoint info\n");
+ break;
+ }
+ if (!vudc->pdev) {
+ rc = virtio_usb_dc_parent_create(vudc);
+ if (rc) {
+ dev_err(&vusb->vdev->dev,
+ "Failed to create UDC parent device\n");
+ kfree(vudc->veps);
+ vudc->veps = NULL;
+ break;
+ }
+ }
+ vudc->gadget.name =
+ kasprintf(GFP_KERNEL, "%s_%d", GADGET_NAME, port_id);
+ if (!vudc->gadget.name) {
+ rc = -ENOMEM;
+ kfree(vudc->veps);
+ vudc->veps = NULL;
+ break;
+ }
+ vudc->gadget.ops = &virtio_gadget_ops;
+ switch (max_speed) {
+ case USB_SPEED_LOW:
+ case USB_SPEED_FULL:
+ case USB_SPEED_HIGH:
+ case USB_SPEED_SUPER:
+ case USB_SPEED_SUPER_PLUS:
+ vudc->gadget.max_speed = max_speed;
+ break;
+ default:
+ pr_info("virtio-usb: unrecognized max_speed %u from host, defaulting to HIGH\n",
+ max_speed);
+ vudc->gadget.max_speed = USB_SPEED_HIGH;
+ break;
+ }
+
+ //vudc->gadget.dev.init_name = gadget_name;
+ vudc->gadget.dev.parent = &vudc->pdev->dev;
+ rc = usb_add_gadget_udc(&vudc->pdev->dev, &vudc->gadget);
+ if (rc) {
+ dev_err(&vudc->pdev->dev, "Failed to add udc\n");
+ kfree(vudc->veps);
+ vudc->veps = NULL;
+ kfree(vudc->gadget.name);
+ vudc->gadget.name = NULL;
+ break;
+ }
+ spin_lock_irqsave(&vudc->lock, flags);
+ vudc->registered = 1;
+ spin_unlock_irqrestore(&vudc->lock, flags);
+ break;
+ }
+ case VIRTIO_USB_EVT_DEV_DISCONNECTED: {
+ if (vudc->driver && vudc->driver->disconnect)
+ vudc->driver->disconnect(&vudc->gadget);
+ if (vudc->registered)
+ usb_gadget_set_state(&vudc->gadget,
+ USB_STATE_NOTATTACHED);
+ break;
+ }
+ case VIRTIO_USB_EVT_DEV_SETUP: {
+ if (!driver)
+ break;
+
+ vep = usb_ep_to_virtio_ep(vudc->gadget.ep0);
+ setup_evt = virtio_usb_event_buf(event);
+ rc = virtio_usb_dc_wait_ep0_idle(vudc);
+ if (rc) {
+ dev_warn(
+ &vusb->vdev->dev,
+ "SETUP while ep0 request is still pending, timing out\n");
+ virtio_ep_set_halt(vudc->gadget.ep0, 1);
+ break;
+ }
+
+ memcpy(&vep->setup, setup_evt->setup,
+ sizeof(struct usb_ctrlrequest));
+
+ rc = driver->setup(&vudc->gadget,
+ (struct usb_ctrlrequest *)setup_evt->setup);
+ if (rc < 0 && rc != -ESHUTDOWN)
+ virtio_ep_set_halt(vudc->gadget.ep0, 1);
+ break;
+ }
+ case VIRTIO_USB_EVT_DEV_RESET: {
+ if (driver)
+ usb_gadget_udc_reset(&vudc->gadget, driver);
+ break;
+ }
+ case VIRTIO_USB_EVT_DEV_SUSPEND: {
+ if (driver && driver->suspend)
+ driver->suspend(&vudc->gadget);
+ break;
+ }
+ case VIRTIO_USB_EVT_DEV_RESUME: {
+ if (driver && driver->resume)
+ driver->resume(&vudc->gadget);
+ break;
+ }
+ case VIRTIO_USB_EVT_DEV_UNBIND: {
+ unsigned int registered;
+
+ pr_info("%s port_id %d VIRTIO_USB_EVT_DEV_UNBIND\n", __func__,
+ port_id);
+
+ spin_lock_irqsave(&vudc->lock, flags);
+ registered = vudc->registered;
+ vudc->registered = 0;
+ spin_unlock_irqrestore(&vudc->lock, flags);
+
+ if (registered) {
+ usb_del_gadget_udc(&vudc->gadget);
+ kfree(vudc->gadget.name);
+ vudc->gadget.name = NULL;
+ }
+
+ if (vudc->veps) {
+ unsigned int i;
+
+ /*
+ * usb_del_gadget_udc() disabled every endpoint, and
+ * virtio_ep_disable() queued each one's disable_work
+ * on ep_cmd_wq. Those work items live in veps, so let
+ * them run (they return at once now that registered
+ * is 0) before freeing it.
+ */
+ flush_workqueue(vudc->ep_cmd_wq);
+ for (i = 0; i < vudc->neps; i++) {
+ cancel_work_sync(&vudc->veps[i].enable_work);
+ cancel_work_sync(&vudc->veps[i].disable_work);
+ }
+ kfree(vudc->veps);
+ vudc->veps = NULL;
+ }
+
+ if (vudc->pdev) {
+ platform_device_unregister(vudc->pdev);
+ vudc->pdev = NULL;
+ }
+ break;
+ }
+ default:
+ rc = -EINVAL;
+ break;
+ }
+}
+
+/**
+ * virtio_usb_dc_event_work() - Worker to get all events
+ * from the virtqueue and process them.
+ * @work: Kernel work to handle event completion.
+ *
+ * Context: Process context.
+ */
+void virtio_usb_dc_event_work(struct work_struct *work)
+{
+ struct virtio_usb *vusb =
+ container_of(work, struct virtio_usb, vq_dev_event_work);
+ struct virtio_usb_queue *evtq =
+ &vusb->vqueues[vusb->dev_vq_base + VIRTIO_USB_VQ_EVENT_IDX];
+ virtio_usb_evt_work(evtq, virtio_usb_dc_event_process);
+}
+
+/**
+ * virtio_usb_dc_event_populate() - Add events to the device event queue.
+ * @vusb: VirtIO USB device
+ *
+ * Context: Any context.
+ * Return: 0 on success -errno on failure
+ */
+int virtio_usb_dc_event_populate(struct virtio_usb *vusb)
+{
+ struct virtio_usb_queue *evt_queue =
+ &vusb->vqueues[vusb->dev_vq_base + VIRTIO_USB_VQ_EVENT_IDX];
+ struct virtio_usb_event *events;
+ int rc;
+
+ events = virtio_usb_events_alloc(vusb, evt_queue,
+ sizeof(struct virtio_usb_dev_event));
+
+ if (!events)
+ return -ENOMEM;
+
+ rc = virtio_usb_events_populate(events);
+
+ return rc;
+}
+
+/**
+ * virtio_usb_dc_init() - Initializes the device role.
+ * @vusb: VirtIO USB device
+ * @port_id: Index of the virtual port to initialize
+ *
+ * Context: Any context.
+ * Return: 0 on success -errno on failure
+ */
+int virtio_usb_dc_init(struct virtio_usb *vusb, int port_id)
+{
+ struct virtio_usb_dc *vudc;
+ unsigned int i;
+
+ vudc = devm_kzalloc(&vusb->vdev->dev, sizeof(*vudc), GFP_KERNEL);
+ if (!vudc)
+ return -ENOMEM;
+
+ vudc->vusb = vusb;
+ vudc->port = port_id;
+ for (i = 0; i < VIRTIO_USB_VQ_DEV_MAX; i++)
+ vudc->dcqs[i] = &vusb->vqueues[vusb->dev_vq_base + i];
+
+ vudc->ep_cmd_wq = alloc_ordered_workqueue(
+ "vudc_ep_work_%d", WQ_MEM_RECLAIM | WQ_UNBOUND, port_id);
+ vudc->dc_cmd_wq = alloc_ordered_workqueue(
+ "vudc_dc_work_%d", WQ_MEM_RECLAIM | WQ_UNBOUND, port_id);
+ if (!vudc->ep_cmd_wq || !vudc->dc_cmd_wq) {
+ if (vudc->ep_cmd_wq)
+ destroy_workqueue(vudc->ep_cmd_wq);
+ if (vudc->dc_cmd_wq)
+ destroy_workqueue(vudc->dc_cmd_wq);
+ devm_kfree(&vusb->vdev->dev, vudc);
+ return -ENOMEM;
+ }
+
+ /* Publish only once fully initialized - vports[port_id].vudc must
+ * never point at a partially-constructed (or already-freed, on the
+ * failure path above) struct virtio_usb_dc.
+ */
+ vusb->vports[port_id].vudc = vudc;
+
+ INIT_WORK(&vudc->dc_cmd_work, virtio_usb_dc_work);
+ mutex_init(&vudc->dc_cmd_work_lock);
+ atomic_set(&vudc->pending_self_pwr, -1);
+ atomic_set(&vudc->pending_vbus_ma, -1);
+ vudc->cur_vbus_ma = 0;
+ vudc->cur_self_pwr = false;
+
+ spin_lock_init(&vudc->lock);
+ init_waitqueue_head(&vudc->ep0_idle);
+
+ vudc->registered = 0;
+
+ return 0;
+}
+
+/**
+ * virtio_usb_dc_deinit() - Deinitialize the device role.
+ * @vusb: VirtIO USB device
+ *
+ * Context: Any context.
+ * Return: 0 on success -errno on failure
+ */
+int virtio_usb_dc_deinit(struct virtio_usb *vusb)
+{
+ int port_id;
+
+ if (!vusb->device_role)
+ return -ENODEV;
+
+ for (port_id = 0; port_id < vusb->nports; port_id++) {
+ struct virtio_usb_dc *vudc = vusb->vports[port_id].vudc;
+ unsigned int registered;
+ unsigned long flags;
+
+ if (!vudc)
+ continue;
+
+ spin_lock_irqsave(&vudc->lock, flags);
+ registered = vudc->registered;
+ spin_unlock_irqrestore(&vudc->lock, flags);
+
+ if (registered) {
+ usb_del_gadget_udc(&vudc->gadget);
+ kfree(vudc->gadget.name);
+ vudc->gadget.name = NULL;
+ }
+
+ if (vudc->dc_cmd_wq) {
+ cancel_work_sync(&vudc->dc_cmd_work);
+ destroy_workqueue(vudc->dc_cmd_wq);
+ }
+
+ if (vudc->ep_cmd_wq) {
+ flush_workqueue(vudc->ep_cmd_wq);
+ if (vudc->veps) {
+ unsigned int i;
+
+ for (i = 0; i < vudc->neps; i++)
+ cancel_work_sync(
+ &vudc->veps[i].enable_work);
+ }
+ destroy_workqueue(vudc->ep_cmd_wq);
+ }
+ kfree(vudc->veps);
+ vudc->veps = NULL;
+
+ if (vudc->pdev) {
+ platform_device_unregister(vudc->pdev);
+ vudc->pdev = NULL;
+ }
+
+ vusb->vports[port_id].vudc = NULL;
+ }
+
+ return 0;
+}
+
+/**
+ * virtio_usb_dc_dataq_stop_cb() - Stops the data virtqueue
+ * @vusb: VirtIO usb device.
+ * @dataq: data virtqueue wrapper
+ *
+ * Context: Any context.
+ */
+static void virtio_usb_dc_dataq_stop_cb(struct virtio_usb *vusb,
+ struct virtio_usb_queue *dataq)
+{
+ int port_id;
+
+ if (!vusb->device_role)
+ return;
+
+ virtio_usb_dataq_stop_cb(vusb, dataq);
+ cancel_work_sync(&vusb->vq_dev_data_rx_work);
+
+ for (port_id = 0; port_id < vusb->nports; port_id++) {
+ struct virtio_usb_dc *vudc = vusb->vports[port_id].vudc;
+ struct virtio_usb_data *vreq, *vreq_tmp;
+ struct virtio_usb_dc_priv *priv;
+ unsigned int i;
+
+ if (!vudc)
+ continue;
+
+ for (i = 0; i < vudc->neps; i++) {
+ list_for_each_entry_safe(vreq, vreq_tmp,
+ &vudc->veps[i].req_queue,
+ list) {
+ priv = virtio_usb_data_priv(vreq);
+ priv->req.status = -ESHUTDOWN;
+ list_del_init(&vreq->list);
+ virtio_usb_data_unref(vreq);
+ usb_gadget_giveback_request(&priv->vep->ep,
+ &priv->req);
+ }
+ }
+ }
+}
+
+/**
+ * virtio_usb_dc_data_notify_cb() - Data 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_dc_data_notify_cb(struct virtqueue *vqueue)
+{
+ struct virtio_usb *vusb = vqueue->vdev->priv;
+
+ schedule_work(&vusb->vq_dev_data_rx_work);
+}
+
+/**
+ * virtio_usb_dc_evt_notify_cb() - 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_dc_evt_notify_cb(struct virtqueue *vqueue)
+{
+ struct virtio_usb *vusb = vqueue->vdev->priv;
+
+ schedule_work(&vusb->vq_dev_event_work);
+}
+
+/**
+ * virtio_usb_dc_evtq_stop_cb() - Stops the event virtqueue.
+ * @vusb: VirtIO usb device.
+ * @vq: virtio usb vq wrapper
+ *
+ * Context: Any context.
+ */
+static void virtio_usb_dc_evtq_stop_cb(struct virtio_usb *vusb,
+ struct virtio_usb_queue *vq)
+{
+ /*
+ * Unlike the host evtq stop path (which safely updates in-memory
+ * port status bits), dc event processing drives the UDC state
+ * machine and calls back into gadget drivers and UDC core. Doing
+ * so here, when the UDC may be only partially initialized (probe
+ * failure) or already torn down (remove path), risks
+ * use-after-free and crashes - virtio_usb_evt_drain_stop_cb()
+ * drains without processing for exactly this reason.
+ */
+ cancel_work_sync((struct work_struct *)&vusb->vq_dev_event_work);
+ virtio_usb_evt_drain_stop_cb(vq, NULL);
+}
+
+const struct virtio_usb_vq_desc dev_vqueues[VIRTIO_USB_VQ_DEV_MAX] = {
+ [VIRTIO_USB_VQ_COMMAND_IDX] = {
+ .callback = virtio_usb_cmd_notify_cb,
+ .name = "virtusb-dev-cmd",
+ .process = virtio_usb_cmd_process_cb,
+ .stop = virtio_usb_cmdq_stop_cb,
+ },
+ [VIRTIO_USB_VQ_EVENT_IDX] = {
+ .callback = virtio_usb_dc_evt_notify_cb,
+ .name = "virtusb-dev-evt",
+ .process = NULL,
+ .stop = virtio_usb_dc_evtq_stop_cb,
+ },
+ [VIRTIO_USB_VQ_DATA_IDX] = {
+ .callback = virtio_usb_dc_data_notify_cb,
+ .name = "virtusb-dev-data",
+ .process = NULL,
+ .stop = virtio_usb_dc_dataq_stop_cb,
+ },
+};
diff --git a/drivers/usb/virtio_usb/device.h b/drivers/usb/virtio_usb/device.h
new file mode 100644
index 000000000000..e4132741fe7f
--- /dev/null
+++ b/drivers/usb/virtio_usb/device.h
@@ -0,0 +1,126 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+/*
+ * virtio-usb: Virtio usb device
+ *
+ * Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.
+ */
+
+#ifndef VIRTIO_USB_DC_H
+#define VIRTIO_USB_DC_H
+
+#include <linux/usb.h>
+#include <linux/list.h>
+#include <linux/platform_device.h>
+#include <linux/wait.h>
+#include <linux/usb/ch11.h>
+#include <linux/usb/ch9.h>
+#include <linux/usb/gadget.h>
+
+#include "vq_common.h"
+
+#include <linux/virtio_usb.h>
+
+#define VIRTIO_USB_EP_CAPS_TYPE_CONTROL 0x01
+#define VIRTIO_USB_EP_CAPS_TYPE_INTERRUPT 0x02
+#define VIRTIO_USB_EP_CAPS_TYPE_BULK 0x04
+#define VIRTIO_USB_EP_CAPS_TYPE_ISOCHRONOUS 0x08
+
+#define VIRTIO_USB_EP_CAPS_DIR_IN 0x02
+#define VIRTIO_USB_EP_CAPS_DIR_OUT 0x01
+
+#define VIRTIO_USB_EP_CAPS(_type, _dir) \
+ { \
+ .type_control = !!((_type) & VIRTIO_USB_EP_CAPS_TYPE_CONTROL), \
+ .type_iso = !!((_type) & VIRTIO_USB_EP_CAPS_TYPE_ISOCHRONOUS), \
+ .type_bulk = !!((_type) & VIRTIO_USB_EP_CAPS_TYPE_BULK), \
+ .type_int = !!((_type) & VIRTIO_USB_EP_CAPS_TYPE_INTERRUPT), \
+ .dir_in = !!((_dir) & VIRTIO_USB_EP_CAPS_DIR_IN), \
+ .dir_out = !!((_dir) & VIRTIO_USB_EP_CAPS_DIR_OUT), \
+ }
+
+enum vep_state { EP_DISABLED, EP_ENABLING, EP_ENABLED, EP_HALTED };
+
+/**
+ * struct virtio_usb_ep - virtio usb device endpoint
+ * @ep: usb ep
+ * @vudc: Device controller this endpoint belongs to
+ * @setup: setup packet for control endpoint
+ * @req_queue: list of usb requests submitted to ep awaiting response
+ * @pend_queue: list of usb requests waiting for submit while EP is ENABLING
+ * @state: endpoint state (necessary to support split-phase async processing)
+ * @enable_work: workstruct for the async ep_enable()
+ * @disable_work: workstruct for the async ep_disable()
+ * @last_err: error code if async processeing brings us to HALTED state
+ * @ep_id: Id of the endpoint
+ * @name: Endpoint name
+ */
+struct virtio_usb_ep {
+ struct usb_ep ep;
+ struct virtio_usb_dc *vudc;
+ struct usb_ctrlrequest setup;
+ struct list_head req_queue;
+ struct list_head pend_queue;
+ enum vep_state state;
+ struct work_struct enable_work;
+ struct work_struct disable_work;
+ int last_err;
+ u16 ep_id;
+ char name[16];
+};
+
+/**
+ * struct virtio_usb_dc - VirtIO USB Device controller (USBDC) device.
+ * @pdev: Platform device that is the parent of the gadget's UDC
+ * @port: Index of the virtual port this controller serves
+ * @gadget: Pointer to the usb gadget structure
+ * @driver: Pointer to the usb gadget driver structure
+ * @veps: Virtual endpoints
+ * @neps: Number of virtual endpoints
+ * @dcqs: Device virtqueue wrappers, indexed by VIRTIO_USB_VQ_*_IDX.
+ * @vusb: VirtIO usb device
+ * @registered: Flag indicating registration status to the UDC core.
+ * @pullup: Software-controlled connect/disconnect status USB host.
+ * @lock: Spinlock that protects device state
+ * @ep0_idle: Wait queue for SETUP serialization while ep0 has an in-flight req
+ * @ep_cmd_wq: Ordered workqueue for endpoint enable/disable/cancel commands
+ * @dc_cmd_wq: Ordered workqueue for @dc_cmd_work
+ * @dc_cmd_work: Sends the latest pending self-powered and VBUS draw
+ * settings to the device
+ * @dc_cmd_work_lock: Serializes @dc_cmd_work and protects @cur_vbus_ma
+ * and @cur_self_pwr
+ * @pending_self_pwr: Self-powered state to send (0 or 1), or -1 if none
+ * @pending_vbus_ma: VBUS draw in mA to send, or -1 if none
+ * @cur_vbus_ma: VBUS draw last sent to the device
+ * @cur_self_pwr: Self-powered state last sent to the device
+ */
+struct virtio_usb_dc {
+ struct platform_device *pdev;
+ u16 port;
+ struct usb_gadget gadget;
+ struct usb_gadget_driver *driver;
+ struct virtio_usb_ep *veps;
+ u32 neps;
+ struct virtio_usb_queue *dcqs[VIRTIO_USB_VQ_DEV_MAX];
+ struct virtio_usb *vusb;
+ unsigned registered : 1;
+ unsigned pullup : 1;
+ spinlock_t lock;
+ wait_queue_head_t ep0_idle;
+ struct workqueue_struct *ep_cmd_wq;
+ struct workqueue_struct *dc_cmd_wq;
+ struct work_struct dc_cmd_work;
+ struct mutex dc_cmd_work_lock;
+ atomic_t pending_self_pwr;
+ atomic_t pending_vbus_ma;
+ unsigned int cur_vbus_ma;
+ bool cur_self_pwr;
+};
+
+extern const struct virtio_usb_vq_desc dev_vqueues[VIRTIO_USB_VQ_DEV_MAX];
+
+int virtio_usb_dc_init(struct virtio_usb *vusb, int port_id);
+int virtio_usb_dc_deinit(struct virtio_usb *vusb);
+void virtio_usb_dc_event_work(struct work_struct *work);
+void virtio_usb_dc_data_work(struct work_struct *work);
+int virtio_usb_dc_event_populate(struct virtio_usb *vusb);
+#endif /* VIRTIO_USB_DC_H */
diff --git a/include/uapi/linux/virtio_usb.h b/include/uapi/linux/virtio_usb.h
index b601c88f1c7e..238052b4f0a9 100644
--- a/include/uapi/linux/virtio_usb.h
+++ b/include/uapi/linux/virtio_usb.h
@@ -57,11 +57,10 @@ struct virtio_usb_config {
#define VIRTIO_USB_S_ERR_STALL 10
#define VIRTIO_USB_S_ERR_SHORT_PKT 11
#define VIRTIO_USB_S_ERR_CANCELLED 12
-#define VIRTIO_USB_S_ERR_HOST 13
struct virtio_usb_cmd_status {
__le32 code; /* VIRTIO_USB_S_XXX */
-};
+} __packed;
/*****************************************************************************
* HOST COMMAND MESSAGES
@@ -129,6 +128,8 @@ struct virtio_usb_host_port_event {
#define VIRTIO_USB_CMD_DEV_EP_SET_HALT 6
#define VIRTIO_USB_CMD_DEV_EP_SET_WEDGE 7
#define VIRTIO_USB_CMD_DEV_CANCEL 8
+#define VIRTIO_USB_CMD_DEV_GET_FRAME_NUMBER 9
+#define VIRTIO_USB_CMD_DEV_SET_SELF_POWERED 10
struct virtio_usb_dev_cmd_hdr {
__le32 code; /* VIRTIO_USB_CMD_DEV_XXX */
@@ -136,12 +137,30 @@ struct virtio_usb_dev_cmd_hdr {
__le16 endpoint; /* Endpoint ID */
};
+/* VIRTIO_USB_CMD_DEV_CANCEL */
+struct virtio_usb_dev_cmd_cancel {
+ struct virtio_usb_dev_cmd_hdr hdr;
+ __le64 tag;
+};
+
/* VIRTIO_USB_CMD_DEV_GET_ENDPOINT_COUNT */
-struct virtio_usb_dev_cmd_ep_count {
+struct virtio_usb_dev_ep_count {
struct virtio_usb_cmd_status status;
__le32 count; /* # of supported endpoints */
};
+struct virtio_usb_dev_cmd_set_value {
+ struct virtio_usb_dev_cmd_hdr hdr;
+ __le32 value;
+ __le32 padding;
+};
+
+/* VIRTIO_USB_CMD_DEV_GET_FRAME_NUMBER */
+struct virtio_usb_dev_frame_number {
+ struct virtio_usb_cmd_status status;
+ __le32 frame_number;
+};
+
#define VIRTIO_USB_DIR_OUT 0
#define VIRTIO_USB_DIR_IN 1
@@ -155,33 +174,45 @@ struct virtio_usb_dev_cmd_ep_count {
* struct virtio_usb_cmd_status
* struct virtio_usb_dev_ep_info [count]
*/
-struct virtio_usb_dev_cmd_ep_info {
+struct virtio_usb_dev_ep_info {
__le16 types; /* supported type bit map (1 << VIRTIO_USB_EP_XXX) */
__le16 directions; /* supported direction bit map (1 << VIRTIO_USB_DIR_XXX) */
__le16 maxpacket_limit;
__le16 max_streams;
+ __u8 name[16];
};
/*******************************************************************************
* DEVICE EVENT MESSAGES
*/
-#define VIRTIO_USB_EVT_DEV_CONNECTED 0
+#define VIRTIO_USB_EVT_DEV_BIND 0
#define VIRTIO_USB_EVT_DEV_DISCONNECTED 1
#define VIRTIO_USB_EVT_DEV_SETUP 2
#define VIRTIO_USB_EVT_DEV_RESET 3
#define VIRTIO_USB_EVT_DEV_SUSPEND 4
#define VIRTIO_USB_EVT_DEV_RESUME 5
+#define VIRTIO_USB_EVT_DEV_UNBIND 6
struct virtio_usb_dev_event {
__le32 code; /* VIRTIO_USB_EVT_DEV_XXX */
- __u8 padding[12];
+ __le16 port; /* Device ID */
+ __u8 padding[10];
+};
+
+/* VIRTIO_USB_EVT_DEV_BIND */
+struct virtio_usb_dev_bind_event {
+ __le32 code; /* VIRTIO_USB_EVT_DEV_BIND */
+ __le16 port; /* Device ID */
+ __u8 max_speed; /* enum usb_device_speed */
+ __u8 padding[9];
};
/* VIRTIO_USB_EVT_DEV_SETUP */
struct virtio_usb_dev_setup_event {
__le32 code; /* VIRTIO_USB_EVT_DEV_SETUP */
+ __le16 port; /* Device ID */
__u8 setup[8]; /* setup packet contents */
- __u8 padding[4];
+ __u8 padding[2];
};
/*******************************************************************************
--
2.49.0
^ permalink raw reply related [flat|nested] 9+ messages in thread
* [RFC PATCH v2 5/7] virtio-usb: add per-port role query support
2026-12-01 17:35 ` [RFC PATCH v2 0/7] virtio-usb: add dual-role virtio USB driver Igor Skalkin
` (3 preceding siblings ...)
2026-12-01 17:35 ` [RFC PATCH v2 4/7] virtio-usb: add device role (USB Device " Igor Skalkin
@ 2026-12-01 17:35 ` Igor Skalkin
2026-12-01 17:35 ` [RFC PATCH v2 6/7] virtio-usb: add host/device role switch support Igor Skalkin
` (2 subsequent siblings)
7 siblings, 0 replies; 9+ messages in thread
From: Igor Skalkin @ 2026-12-01 17:35 UTC (permalink / raw)
To: Michael S . Tsirkin, Jason Wang, Greg Kroah-Hartman
Cc: virtualization, linux-usb, linux-kernel, Eugenio Perez, Xuan Zhuo,
Vasilii Ianikeev, Aiswarya Cyriac, Anton Yakovlev, Trilok Soni,
Matias Ezequiel Vara Larsen, Igor Skalkin
With both host_role and device_role negotiated, a port's own role is
ambiguous (host|device) - determining it requires more than reading
the two feature bits. Introduce a minimal role command/event queue
pair (role_vq_base, role_vqueues[], virtio_usb_rsw_init()/
virtio_usb_rsw_deinit()) and virtio_usb_rsw_get_role(), a synchronous
VIRTIO_USB_CMD_ROLE_GET request/response exchange, and query every
port's role individually during probe instead of the alternative of
overloading the config space ports field with role bits.
This replaces the previous commit's DEVICE-only placeholder for the
both-roles-negotiated case with the real per-port answer.
The code lives in role_switch.c, since the next commit builds runtime
role switching on top of the same queue pair.
Signed-off-by: Igor Skalkin <igor.skalkin@oss.qualcomm.com>
---
drivers/usb/virtio_usb/Makefile | 3 +-
drivers/usb/virtio_usb/controller.c | 88 +++++++++++---
drivers/usb/virtio_usb/controller.h | 12 ++
drivers/usb/virtio_usb/role_switch.c | 168 +++++++++++++++++++++++++++
drivers/usb/virtio_usb/role_switch.h | 27 +++++
5 files changed, 280 insertions(+), 18 deletions(-)
create mode 100644 drivers/usb/virtio_usb/role_switch.c
create mode 100644 drivers/usb/virtio_usb/role_switch.h
diff --git a/drivers/usb/virtio_usb/Makefile b/drivers/usb/virtio_usb/Makefile
index ac382d81d8af..081d67323d9d 100644
--- a/drivers/usb/virtio_usb/Makefile
+++ b/drivers/usb/virtio_usb/Makefile
@@ -5,4 +5,5 @@ obj-$(CONFIG_USB_VIRTIO) += virtio-usb.o
virtio-usb-y := controller.o \
vq_common.o \
host.o \
- device.o
+ device.o \
+ role_switch.o
diff --git a/drivers/usb/virtio_usb/controller.c b/drivers/usb/virtio_usb/controller.c
index b463513b2da4..9f875a127f67 100644
--- a/drivers/usb/virtio_usb/controller.c
+++ b/drivers/usb/virtio_usb/controller.c
@@ -11,6 +11,7 @@
#include "controller.h"
#include "host.h"
#include "device.h"
+#include "role_switch.h"
#include "vq_common.h"
/**
@@ -120,12 +121,12 @@ static int virtio_usb_probe(struct virtio_device *vdev)
/* 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. A pure single-role
- * instance therefore has exactly VIRTIO_USB_VQ_HOST_MAX (3) or
- * VIRTIO_USB_VQ_DEV_MAX (3) virtqueues, not a fixed layout - queues
- * that don't exist on the wire must not be created, since a peer
- * with no host-role VP has no host command/event/data queues to
- * negotiate at all.
+ * DEV_* only when device_role is negotiated, ROLE_* only when both
+ * roles are negotiated. A pure single-role instance therefore has
+ * exactly VIRTIO_USB_VQ_HOST_MAX (3) or VIRTIO_USB_VQ_DEV_MAX (3)
+ * virtqueues, not a fixed layout - queues that don't exist on the
+ * wire must not be created, since a peer with no host-role VP has
+ * no host command/event/data queues to negotiate at all.
*/
vusb->host_vq_base = -1;
vusb->dev_vq_base = -1;
@@ -138,17 +139,15 @@ static int virtio_usb_probe(struct virtio_device *vdev)
vusb->dev_vq_base = nvqs;
nvqs += VIRTIO_USB_VQ_DEV_MAX;
}
-
- /* Resolve every port's role. With only one role negotiated, every
- * port unambiguously has that role. With both negotiated, a port's
- * own role is ambiguous until a later commit adds a per-port
- * role query - default to DEVICE for now as a placeholder.
- */
- for (i = 0; i < vusb->nports; i++) {
- if (vusb->host_role && !vusb->device_role)
- vusb->vports[i].role = VIRTIO_USB_ROLE_HOST;
- else if (vusb->device_role)
- vusb->vports[i].role = VIRTIO_USB_ROLE_DEVICE;
+ if (vusb->host_role && vusb->device_role) {
+ /* The role command/event queue pair is needed whenever both
+ * roles are negotiated - it is how the driver asks each
+ * port for its actual role via virtio_usb_rsw_get_role() below, since
+ * a port's own role is otherwise ambiguous (host|device)
+ * until then.
+ */
+ vusb->role_vq_base = nvqs;
+ nvqs += VIRTIO_USB_VQ_ROLE_MAX;
}
vusb->vqueues = devm_kcalloc(&vdev->dev, nvqs, sizeof(*vusb->vqueues),
@@ -182,6 +181,18 @@ static int virtio_usb_probe(struct virtio_device *vdev)
dev_vqueues[i].stop;
}
+ if (vusb->host_role && vusb->device_role)
+ for (i = 0; i < VIRTIO_USB_VQ_ROLE_MAX; i++) {
+ vusb->vqueues[vusb->role_vq_base + i].name =
+ role_vqueues[i].name;
+ vusb->vqueues[vusb->role_vq_base + i].callback =
+ role_vqueues[i].callback;
+ vusb->vqueues[vusb->role_vq_base + i].process =
+ role_vqueues[i].process;
+ vusb->vqueues[vusb->role_vq_base + i].stop =
+ role_vqueues[i].stop;
+ }
+
rc = virtio_usb_find_vqs(vusb);
if (rc) {
dev_err(&vdev->dev, "%s virtio_usb_find_vqs() error(%d)\n",
@@ -189,6 +200,47 @@ static int virtio_usb_probe(struct virtio_device *vdev)
goto on_error;
}
+ if (vusb->host_role && vusb->device_role) {
+ rc = virtio_usb_rsw_init(vusb);
+ if (rc) {
+ dev_err(&vdev->dev,
+ "%s virtio_usb_rsw_init() error(%d)\n",
+ __func__, rc);
+ goto on_error;
+ }
+ }
+
+ /* 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).
+ */
+ for (i = 0; i < vusb->nports; i++) {
+ 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;
+
+ status = virtio_usb_rsw_get_role(vusb, i, &role);
+ if (status != VIRTIO_USB_S_OK) {
+ dev_err(&vdev->dev, "%s status(%d)\n", __func__,
+ status);
+ rc = -EIO;
+ goto on_error;
+ }
+ if (role != VIRTIO_USB_ROLE_HOST &&
+ role != VIRTIO_USB_ROLE_DEVICE) {
+ dev_err(&vdev->dev, "%s port%d wrong role %d\n",
+ __func__, i, role);
+ rc = -EIO;
+ goto on_error;
+ }
+ vusb->vports[i].role = role;
+ }
+ }
+
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);
@@ -276,6 +328,8 @@ static void virtio_usb_remove(struct virtio_device *vdev)
virtio_reset_device(vdev);
vdev->config->del_vqs(vdev);
+
+ virtio_usb_rsw_deinit(vusb);
}
static const unsigned int virtio_usb_features[] = {
diff --git a/drivers/usb/virtio_usb/controller.h b/drivers/usb/virtio_usb/controller.h
index 446a9274871c..6f39e4c5a4aa 100644
--- a/drivers/usb/virtio_usb/controller.h
+++ b/drivers/usb/virtio_usb/controller.h
@@ -19,6 +19,8 @@
struct virtio_usb_hc_vp;
/* Forward declaration - full definition in device.h */
struct virtio_usb_dc;
+/* Forward declaration - full definition in role_switch.h */
+struct virtio_usb_rsw;
#define VIRTIO_USB_VQ_COMMAND_IDX 0
#define VIRTIO_USB_VQ_EVENT_IDX 1
@@ -26,6 +28,7 @@ struct virtio_usb_dc;
#define VIRTIO_USB_VQ_HOST_MAX 3
#define VIRTIO_USB_VQ_DEV_MAX 3
+#define VIRTIO_USB_VQ_ROLE_MAX 2
/**
* struct virtio_usb_port - Per-virtual-port state.
@@ -55,6 +58,12 @@ struct virtio_usb_port {
* @dev_vq_base: index into vqueues[] where the DEV_COMMAND/EVENT/DATA
* triplet starts, or -1 if this instance has no
* device-role VP.
+ * @role_vq_base: index into vqueues[] where the ROLE_COMMAND/EVENT pair
+ * starts, or -1 if this instance has neither a host-role
+ * nor a device-role VP. Used to query each port's role via
+ * virtio_usb_rsw_get_role(), since with both host_role and
+ * device_role negotiated a port's own role is otherwise
+ * ambiguous.
* @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
@@ -63,6 +72,7 @@ struct virtio_usb_port {
* across every device-role port.
* @vq_dev_event_work: Kernel work draining the device event queue, shared
* across every device-role port.
+ * @rsw: Device-wide role-switch state, see role_switch.h.
* @data_tag_seq: Source of data request tags, see virtio_usb_data_tag_next().
*/
struct virtio_usb {
@@ -75,10 +85,12 @@ struct virtio_usb {
bool device_role;
int host_vq_base;
int dev_vq_base;
+ int role_vq_base;
struct work_struct vq_host_data_rx_work;
struct work_struct vq_host_evt_work;
struct work_struct vq_dev_data_rx_work;
struct work_struct vq_dev_event_work;
+ struct virtio_usb_rsw *rsw;
atomic64_t data_tag_seq;
};
diff --git a/drivers/usb/virtio_usb/role_switch.c b/drivers/usb/virtio_usb/role_switch.c
new file mode 100644
index 000000000000..50b5d645abf4
--- /dev/null
+++ b/drivers/usb/virtio_usb/role_switch.c
@@ -0,0 +1,168 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+/*
+ * virtio_usb: VirtIO USB device
+ *
+ * Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.
+ */
+
+#include <linux/mutex.h>
+#include "controller.h"
+#include "role_switch.h"
+#include "vq_common.h"
+
+int virtio_usb_rsw_init(struct virtio_usb *vusb)
+{
+ struct virtio_usb_rsw *rsw =
+ devm_kzalloc(&vusb->vdev->dev, sizeof(*rsw), GFP_KERNEL);
+ unsigned int i;
+
+ if (!rsw)
+ return -ENOMEM;
+
+ rsw->vusb = vusb;
+ vusb->rsw = rsw;
+ 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);
+
+ return 0;
+}
+
+void virtio_usb_rsw_deinit(struct virtio_usb *vusb)
+{
+ struct virtio_usb_rsw *rsw = vusb->rsw;
+
+ if (!rsw)
+ return;
+
+ /* Wake potential role command waiters before releasing role objects. */
+ complete_all(&rsw->completion);
+
+ vusb->rsw = NULL;
+}
+
+/* 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)
+{
+ 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;
+ u32 status = VIRTIO_USB_S_ERR_INTERNAL;
+
+ 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)
+ 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));
+
+ mutex_lock(&vusb->rsw->lock);
+
+ if (virtqueue_add_sgs(vq, sgs, 1u, 1u, msg, GFP_ATOMIC)) {
+ pr_err("%s virtqueue_add_sgs error\n", __func__);
+ goto exit;
+ }
+
+ if (!virtqueue_kick(vq)) {
+ pr_err("%s virtqueue_kick error\n", __func__);
+ goto exit;
+ }
+
+ 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);
+
+ if (*role != VIRTIO_USB_ROLE_HOST && *role != VIRTIO_USB_ROLE_DEVICE) {
+ pr_err("%s - wrong role (%d)\n", __func__, *role);
+ } else {
+ pr_info("%s role %s\n", __func__,
+ *role == VIRTIO_USB_ROLE_HOST ?
+ "VIRTIO_USB_ROLE_HOST" :
+ "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.
+ */
+ 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);
+}
+
+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,
+ .name = "virtusb-role-cmd",
+ .process = NULL,
+ .stop = virtio_usb_rsw_cmdq_stop_cb,
+ },
+ [VIRTIO_USB_VQ_EVENT_IDX] = {
+ .callback = NULL,
+ .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
new file mode 100644
index 000000000000..e3c8031686c3
--- /dev/null
+++ b/drivers/usb/virtio_usb/role_switch.h
@@ -0,0 +1,27 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+/*
+ * virtio_usb: VirtIO USB device
+ *
+ * Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.
+ */
+
+#ifndef VIRTIO_USB_ROLE_SWITCH_H
+#define VIRTIO_USB_ROLE_SWITCH_H
+
+#include "controller.h"
+
+int virtio_usb_rsw_init(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);
+
+struct virtio_usb_rsw {
+ struct virtio_usb *vusb;
+ struct mutex lock;
+ struct completion completion;
+ struct virtio_usb_queue *oqs[VIRTIO_USB_VQ_ROLE_MAX];
+};
+
+extern const struct virtio_usb_vq_desc role_vqueues[VIRTIO_USB_VQ_ROLE_MAX];
+
+#endif /* VIRTIO_USB_ROLE_SWITCH_H */
--
2.49.0
^ permalink raw reply related [flat|nested] 9+ messages in thread
* [RFC PATCH v2 6/7] virtio-usb: add host/device role switch support
2026-12-01 17:35 ` [RFC PATCH v2 0/7] virtio-usb: add dual-role virtio USB driver Igor Skalkin
` (4 preceding siblings ...)
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
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
7 siblings, 0 replies; 9+ messages in thread
From: Igor Skalkin @ 2026-12-01 17:35 UTC (permalink / raw)
To: Michael S . Tsirkin, Jason Wang, Greg Kroah-Hartman
Cc: virtualization, linux-usb, linux-kernel, Eugenio Perez, Xuan Zhuo,
Vasilii Ianikeev, Aiswarya Cyriac, Anton Yakovlev, Trilok Soni,
Matias Ezequiel Vara Larsen, Igor Skalkin
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
^ permalink raw reply related [flat|nested] 9+ messages in thread
* [RFC PATCH v2 7/7] virtio-usb: support a guest UDC name prefix from the bind event
2026-12-01 17:35 ` [RFC PATCH v2 0/7] virtio-usb: add dual-role virtio USB driver Igor Skalkin
` (5 preceding siblings ...)
2026-12-01 17:35 ` [RFC PATCH v2 6/7] virtio-usb: add host/device role switch support Igor Skalkin
@ 2026-12-01 17:35 ` Igor Skalkin
2026-12-01 17:49 ` [RFC PATCH v2 0/7] virtio-usb: add dual-role virtio USB driver Michael S. Tsirkin
7 siblings, 0 replies; 9+ messages in thread
From: Igor Skalkin @ 2026-12-01 17:35 UTC (permalink / raw)
To: Michael S . Tsirkin, Jason Wang, Greg Kroah-Hartman
Cc: virtualization, linux-usb, linux-kernel, Eugenio Perez, Xuan Zhuo,
Vasilii Ianikeev, Aiswarya Cyriac, Anton Yakovlev, Trilok Soni,
Matias Ezequiel Vara Larsen, Igor Skalkin
Let the host backend supply a name prefix for a port's UDC parent
platform_device via the bind event, instead of always using the
generic GADGET_NAME. When present, the prefix is used verbatim as
the parent device's name and the gadget name becomes
"<prefix>_p<port>"; when empty, behavior is unchanged.
Signed-off-by: Igor Skalkin <igor.skalkin@oss.qualcomm.com>
---
drivers/usb/virtio_usb/device.c | 47 +++++++++++++++++++++++++++------
include/uapi/linux/virtio_usb.h | 4 ++-
2 files changed, 42 insertions(+), 9 deletions(-)
diff --git a/drivers/usb/virtio_usb/device.c b/drivers/usb/virtio_usb/device.c
index 0d44cb1dce6e..d6fc1cc19713 100644
--- a/drivers/usb/virtio_usb/device.c
+++ b/drivers/usb/virtio_usb/device.c
@@ -1481,11 +1481,26 @@ static int virtio_usb_dc_get_endpoint_info(struct virtio_usb_dc *vudc)
return rc;
}
-static int virtio_usb_dc_parent_create(struct virtio_usb_dc *vudc)
+static int virtio_usb_dc_parent_create(struct virtio_usb_dc *vudc,
+ const unsigned char *udc_prefix)
{
+ size_t prefix_len;
+ char *parent_name;
int rc;
- vudc->pdev = platform_device_alloc(GADGET_NAME, vudc->port);
+ prefix_len = strnlen((const char *)udc_prefix,
+ VIRTIO_USB_UDC_NAME_PREFIX_MAX);
+ if (prefix_len) {
+ parent_name = kasprintf(GFP_KERNEL, "%.*s", (int)prefix_len,
+ (const char *)udc_prefix);
+ } else {
+ parent_name = kstrdup(GADGET_NAME, GFP_KERNEL);
+ }
+ if (!parent_name)
+ return -ENOMEM;
+
+ vudc->pdev = platform_device_alloc(parent_name, vudc->port);
+ kfree(parent_name);
if (!vudc->pdev)
return -ENOMEM;
@@ -1568,6 +1583,7 @@ static void virtio_usb_dc_event_process(struct virtio_usb_event *event)
switch (le32_to_cpu(evt->code)) {
case VIRTIO_USB_EVT_DEV_BIND: {
u8 max_speed;
+ size_t udc_prefix_len;
if (vudc->registered) {
dev_err(&vusb->vdev->dev,
@@ -1594,7 +1610,8 @@ static void virtio_usb_dc_event_process(struct virtio_usb_event *event)
break;
}
if (!vudc->pdev) {
- rc = virtio_usb_dc_parent_create(vudc);
+ rc = virtio_usb_dc_parent_create(
+ vudc, bind_evt->udc_name_prefix);
if (rc) {
dev_err(&vusb->vdev->dev,
"Failed to create UDC parent device\n");
@@ -1603,8 +1620,18 @@ static void virtio_usb_dc_event_process(struct virtio_usb_event *event)
break;
}
}
- vudc->gadget.name =
- kasprintf(GFP_KERNEL, "%s_%d", GADGET_NAME, port_id);
+ udc_prefix_len =
+ strnlen((const char *)bind_evt->udc_name_prefix,
+ VIRTIO_USB_UDC_NAME_PREFIX_MAX);
+ if (udc_prefix_len) {
+ vudc->gadget.name = kasprintf(
+ GFP_KERNEL, "%.*s_p%d", (int)udc_prefix_len,
+ (const char *)bind_evt->udc_name_prefix,
+ port_id);
+ } else {
+ vudc->gadget.name = kasprintf(GFP_KERNEL, "%s_%d",
+ GADGET_NAME, port_id);
+ }
if (!vudc->gadget.name) {
rc = -ENOMEM;
kfree(vudc->veps);
@@ -1627,7 +1654,6 @@ static void virtio_usb_dc_event_process(struct virtio_usb_event *event)
break;
}
- //vudc->gadget.dev.init_name = gadget_name;
vudc->gadget.dev.parent = &vudc->pdev->dev;
rc = usb_add_gadget_udc(&vudc->pdev->dev, &vudc->gadget);
if (rc) {
@@ -1770,11 +1796,16 @@ int virtio_usb_dc_event_populate(struct virtio_usb *vusb)
{
struct virtio_usb_queue *evt_queue =
&vusb->vqueues[vusb->dev_vq_base + VIRTIO_USB_VQ_EVENT_IDX];
+ size_t evt_size;
struct virtio_usb_event *events;
int rc;
- events = virtio_usb_events_alloc(vusb, evt_queue,
- sizeof(struct virtio_usb_dev_event));
+ evt_size = max_t(size_t, sizeof(struct virtio_usb_dev_event),
+ sizeof(struct virtio_usb_dev_setup_event));
+ evt_size = max_t(size_t, evt_size,
+ sizeof(struct virtio_usb_dev_bind_event));
+
+ events = virtio_usb_events_alloc(vusb, evt_queue, evt_size);
if (!events)
return -ENOMEM;
diff --git a/include/uapi/linux/virtio_usb.h b/include/uapi/linux/virtio_usb.h
index 238052b4f0a9..d3199cbd7d10 100644
--- a/include/uapi/linux/virtio_usb.h
+++ b/include/uapi/linux/virtio_usb.h
@@ -193,6 +193,8 @@ struct virtio_usb_dev_ep_info {
#define VIRTIO_USB_EVT_DEV_RESUME 5
#define VIRTIO_USB_EVT_DEV_UNBIND 6
+#define VIRTIO_USB_UDC_NAME_PREFIX_MAX 64
+
struct virtio_usb_dev_event {
__le32 code; /* VIRTIO_USB_EVT_DEV_XXX */
__le16 port; /* Device ID */
@@ -204,7 +206,7 @@ struct virtio_usb_dev_bind_event {
__le32 code; /* VIRTIO_USB_EVT_DEV_BIND */
__le16 port; /* Device ID */
__u8 max_speed; /* enum usb_device_speed */
- __u8 padding[9];
+ __u8 udc_name_prefix[VIRTIO_USB_UDC_NAME_PREFIX_MAX];
};
/* VIRTIO_USB_EVT_DEV_SETUP */
--
2.49.0
^ permalink raw reply related [flat|nested] 9+ messages in thread
* Re: [RFC PATCH v2 0/7] virtio-usb: add dual-role virtio USB driver
2026-12-01 17:35 ` [RFC PATCH v2 0/7] virtio-usb: add dual-role virtio USB driver Igor Skalkin
` (6 preceding siblings ...)
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 ` Michael S. Tsirkin
7 siblings, 0 replies; 9+ messages in thread
From: Michael S. Tsirkin @ 2026-12-01 17:49 UTC (permalink / raw)
To: Igor Skalkin
Cc: Jason Wang, Greg Kroah-Hartman, virtualization, linux-usb,
linux-kernel, Eugenio Perez, Xuan Zhuo, Vasilii Ianikeev,
Aiswarya Cyriac, Anton Yakovlev, Trilok Soni,
Matias Ezequiel Vara Larsen
On Tue, Dec 01, 2026 at 06:35:29PM +0100, Igor Skalkin wrote:
> This series adds a driver for the virtio USB device: a dual-role
> paravirtualized USB controller. Each port of the device is either a
> USB host controller port, backed by a per-port HS+SS usb_hcd pair, or
> a USB device controller (UDC). Dual-role ports can switch between the
> two roles at runtime, and the switch is exposed through the USB role
> switch class. This is a device-driven role switch, not USB OTG:
> there is no HNP/SRP, ID pin or OTG descriptor involved.
Thanks!
Process: pls start a new thread with each revision, not as reply
to old one.
^ permalink raw reply [flat|nested] 9+ messages in thread
end of thread, other threads:[~2026-12-01 17:49 UTC | newest]
Thread overview: 9+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
[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 ` [RFC PATCH v2 6/7] virtio-usb: add host/device role switch support Igor Skalkin
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
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox