virtio-usb: add dual-role virtio USB driver
Subsystems (2)
cover virtio-usb: add dual-role virtio USB driver
This series adds a new virtio-usb driver: a dual-role virtio device capable of acting as a USB host controller, a USB device controller, or both simultaneously with runtime role switching between the two (USB OTG-style role switching) on ports that support it.
The corresponding virtio-usb device specification has been posted to virtio-comment for review. This series matches the v2 revision of that spec, which reconciles a small number of protocol details (per-role virtqueue presentation, host-role vp_idx for hub/multi-VP support, and the device-role BIND/UNBIND event split) that were clarified while integrating and testing this driver against the spec:
[RFC PATCH v2] virtio-usb: Add initial virtio-usb specification Igor Skalkin <[email protected]> [email protected]
https://lore.kernel.org/virtio-comment/[email protected]/
This driver has been tested end-to-end against our own userspace virtio-usb device implementation (host-side backend) in two setups:
- arm64 hardware with a type-1 hypervisor, exercising a real dwc3 USB controller on the host side.
- x86 with a type-2 hypervisor (QEMU/KVM), using dummy_hcd/dummy_udc on the host side in place of real USB hardware.
Host role and device role were exercised in both setups: testusb on the guest, over a virtualized host port, against g_zero running on a real hardware UDC or on dummy UDC on the host side (host role); and testusb on the host side, against g_zero running on a virtualized UDC on the guest (device role); plus real USB mass-storage hardware/gadgets and iperf3 over usbnet. Role switching was exercised in both setups as well, but not with a real OTG cable/ID-pin connection:
on dwc3, role switching was driven through its "role-switch" sysfs configuration; on dummy_hcd, it was emulated by toggling between two simultaneously-configured dummy_hcd instances on the same port. Testing with a real OTG connection is planned as a follow-up.
Known scope: this driver virtualizes an entire UDC per device-role port, with each port owned by a single guest. USB function-level virtualization - a single physical UDC exposing a composite gadget whose individual functions are routed to different guests - is a separate approach currently being explored, and is out of scope for this series.
Patch summary:
1: protocol header and skeleton dual-role driver (probe/remove
plumbing, no role support yet).
2: USB host controller (HCD) role support.
3: USB device controller (UDC) role support.
4-5: USB OTG-style role query and role-switching support.
6: endpoint-lifecycle robustness rework (async split-phase state
machine, replacing an earlier out-of-tree gadget.nonatomic patch that didn't pass upstream review).
7: SuperSpeed device-role support.
8: guest UDC naming fix (name prefix from the bind event).
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 (5):
virtio-usb: add OTG role query support
virtio-usb: add USB On-The-Go role-switching support
virtio-usb: rework endpoint lifecycle to an async split-phase state
machine
virtio-usb: add SuperSpeed device-role 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 | 21 + drivers/usb/virtio_usb/Makefile | 9 + drivers/usb/virtio_usb/controller.c | 422 ++++++++ drivers/usb/virtio_usb/controller.h | 152 +++ drivers/usb/virtio_usb/device.c | 1893 +++++++++++++++++++++++++++++++++++ drivers/usb/virtio_usb/device.h | 115 +++ drivers/usb/virtio_usb/host.c | 1368 +++++++++++++++++++++++++ drivers/usb/virtio_usb/host.h | 203 ++++ drivers/usb/virtio_usb/otg.c | 403 ++++++++ drivers/usb/virtio_usb/otg.h | 38 + drivers/usb/virtio_usb/vq_common.c | 740 ++++++++++++++ drivers/usb/virtio_usb/vq_common.h | 163 +++ include/uapi/linux/virtio_usb.h | 346 +++++++ 16 files changed, 5886 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/otg.c create mode 100644 drivers/usb/virtio_usb/otg.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
Signature · 1 line
2.49.0
PATCH 1/8 virtio-usb: add protocol header and skeleton dual-role driver
From: Aiswarya Cyriac <[email protected]>
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, device, OTG) builds on this same array from the start, instead of the host, device, and OTG subsystems each growing their own separate port-indexed storage that later has to be reconciled.
Wire the new drivers/usb/virtio_usb/ directory into the USB subsystem's build (drivers/usb/Kconfig, drivers/usb/Makefile) as a new CONFIG_USB_VIRTIO option, listed alongside the other USB dual-mode controller drivers.
--- MAINTAINERS | 10 + drivers/usb/Kconfig | 2 drivers/usb/Makefile | 1 drivers/usb/virtio_usb/Kconfig | 21 ++ 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 | 302 ++++++++++++++++++++++++++++++++++++ 8 files changed, 580 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
MAINTAINERS +10 -0
@@ -28450,6 +28450,16 @@ F: drivers/media/usb/uvc/ F: include/linux/usb/uvc.h F: include/uapi/linux/uvcvideo.h +USB VIRTIO DRIVER +M: Igor Skalkin <[email protected]> +R: Aiswarya Cyriac <[email protected]> +R: Vasilii Ianikeev <[email protected]> +L: [email protected] +L: [email protected] +S: Maintained +F: drivers/usb/virtio_usb/ +F: include/uapi/linux/virtio_usb.h + USB WEBCAM GADGET L: [email protected] S: Orphan
drivers/usb/Kconfig +2 -0
@@ -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
drivers/usb/Makefile +1 -0
@@ -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/
drivers/usb/virtio_usb/Kconfig new file +21 -0
@@ -0,0 +1,21 @@ +config USB_VIRTIO + tristate "Virtio USB device support" + depends on USB_SUPPORT && VIRTIO + depends on USB || USB_GADGET + depends on USB if !USB_GADGET + depends on USB_GADGET if !USB + select USB_ROLE_SWITCH + help + Say Y here if you want to support a virtio-usb device: a virtio + transport for USB that can present itself to the guest as a USB + host controller, a USB device controller (UDC), or both, with + each port independently configurable and, on ports where the + virtio-usb device advertises support for it, capable of + switching between the host and device role at runtime (USB + OTG-style role switching), backed by the standard USB Role + Switch class. + + To compile this driver as a module, choose M here: the module + will be called virtio-usb. + + If unsure, say N.
drivers/usb/virtio_usb/Makefile new file +5 -0
@@ -0,0 +1,5 @@ +# SPDX-License-Identifier: GPL-2.0-or-later + +virtio-usb-y := controller.o + +obj-$(CONFIG_USB_VIRTIO) += virtio-usb.o
drivers/usb/virtio_usb/controller.c new file +155 -0
155 lines not on this page · raw message
drivers/usb/virtio_usb/controller.h new file +84 -0
84 lines not on this page · raw message
include/uapi/linux/virtio_usb.h new file +302 -0
302 lines not on this page · raw message
[email protected]
AI reviewRe: [PATCH 1/8] virtio-usb: add protocol header and skeleton dual-role driver
Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider: - [High] usb: virtio_usb Kconfig allows built-in driver with modular gadget subsystem - [Medium]…
Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider:
- [High] usb: virtio_usb Kconfig allows built-in driver with modular gadget subsystem
- [Medium] virtio-usb: 16-bit port ID in device UAPI structures truncates 32-bit index
- [Medium] virtio-usb: missing bounds check on untrusted nports causes huge allocation
- [Low] virtio-usb: redundant USB prefix in UAPI SuperSpeed enum constant
- [Low] virtio-usb: missing error check after virtio_find_vqs() copies stale pointer --
commit 326b99edf62be9a25cd868d49b2b33423f8607c9
Author: Aiswarya Cyriac <[email protected]>
virtio-usb: add protocol header and skeleton dual-role driver
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.
drivers/usb/virtio_usb/Kconfig line 6
Quoted 12 lines
drivers/usb/virtio_usb/Kconfig new file +6
-0@@ -0,0 +1,21 @@ +config USB_VIRTIO + tristate "Virtio USB device support" + depends on USB_SUPPORT && VIRTIO + depends on USB || USB_GADGET + depends on USB if !USB_GADGET + depends on USB_GADGET if !USB
[Severity: High]
Does this logic allow CONFIG_USB_VIRTIO to be built-in while the gadget subsystem is modular?
If CONFIG_USB=y and CONFIG_USB_GADGET=m, it looks like 'depends on USB if !USB_GADGET' evaluates to ignored, permitting CONFIG_USB_VIRTIO=y. Because device.o is unconditionally compiled into the driver, could this cause undefined references to modular gadget APIs from built-in code, breaking the vmlinux link?
[ ... ]
Quoted 5 lines
drivers/usb/virtio_usb/controller.c new file +0
-0
[ ... ]
Quoted 18 lines
drivers/usb/virtio_usb/controller.c new file +18
-0+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;
drivers/usb/virtio_usb/controller.c line 47
Quoted 10 lines
drivers/usb/virtio_usb/controller.c new file +10
-0+ 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); + }
[Severity: Low]
Is there a missing error check for 'rc' here?
If virtio_find_vqs() fails and returns an error code, the code seems to fall through to the loop and blindly assign vusb->vqueues[i].vqueue = vqs[i] using uninitialized or dangling pointers from the vqs array before exiting via 'on_exit'.
Should there be an 'if (rc) goto on_exit;' before the loop?
Quoted 4 lines
drivers/usb/virtio_usb/controller.c new file +4
-0+on_exit: +kfree (vqs); +return rc; +}
[ ... ]
Quoted 7 lines
drivers/usb/virtio_usb/controller.c new file +7
-0+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 );
drivers/usb/virtio_usb/controller.c line 99
Quoted 10 lines
drivers/usb/virtio_usb/controller.c new file +10
-0+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 );
[Severity: Medium]
Does this allocation need a bounds check?
The untrusted value 'vusb->nports' is read directly from the device config space and passed to devm_kcalloc() with GFP_KERNEL.
Since there is no architectural cap checked, could a malicious host or hypervisor supply a massive value (e.g., 100M) and trigger OOM killer activity or large allocation warnings?
[ ... ]
Quoted 5 lines
include/uapi/linux/virtio_usb.h new file +0
-0
[ ... ]
include/uapi/linux/virtio_usb.h line 116
Quoted 7 lines
include/uapi/linux/virtio_usb.h new file +7
-0+enum { +VIRTIO_USB_SPEED_UNKNOWN =0 , +VIRTIO_USB_SPEED_LOW , +VIRTIO_USB_SPEED_FULL ,/* usb 1.1 */ +VIRTIO_USB_SPEED_HIGH ,/* usb 2.0 */ +VIRTIO_USB_SPEED_WIRELESS ,/* wireless (usb 2.5) */ +VIRTIO_USB_USB_SPEED_SUPER ,/* usb 3.0 */
[Severity: Low]
Is the "USB" prefix redundant here?
This defines VIRTIO_USB_USB_SPEED_SUPER instead of VIRTIO_USB_SPEED_SUPER, breaking naming consistency and forcing userspace to use the flawed macro name.
Quoted 2 lines
include/uapi/linux/virtio_usb.h new file +2
-0+ VIRTIO_USB_SPEED_SUPER_PLUS, /* usb 3.1 */ +};
[ ... ]
include/uapi/linux/virtio_usb.h line 146
Quoted 5 lines
include/uapi/linux/virtio_usb.h new file +5
-0+struct virtio_usb_dev_cmd_hdr { +__le32 code;/* VIRTIO_USB_CMD_DEV_XXX */ +__le16 port;/* Port ID */ +__le16 endpoint;/* Endpoint ID */ +};
[Severity: Medium]
Will this 16-bit port ID correctly route commands for all virtual ports?
Since 'virtio_usb_config.ports' and host UAPI structures define the port count and IDs as 32-bit (__le32), a 16-bit port field here silently truncates the index for any port >= 65536.
[ ... ]
include/uapi/linux/virtio_usb.h line 216
Quoted 6 lines
include/uapi/linux/virtio_usb.h new file +6
-0+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 */
[Severity: Medium]
Similar to 'virtio_usb_dev_cmd_hdr' above, does this 16-bit port ID truncate the 32-bit port index?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
Greg Kroah-Hartman
maintainerRe: [PATCH 1/8] virtio-usb: add protocol header and skeleton dual-role driver
In reply to Igor SkalkinQuoted 13 lines · Igor Skalkin
From: Aiswarya Cyriac <[email protected]>
Add the
virtio_usbdevice 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_portarray (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, device, OTG) builds on this same array from the start, instead of the host, device, and OTG subsystems each growing their own separate port-indexed storage that later has to be reconciled.
Quoted 6 lines
Wire the new
drivers/usb/virtio_usb/directory into the USB subsystem's build (drivers/usb/Kconfig,drivers/usb/Makefile) as a newCONFIG_USB_VIRTIOoption, listed alongside the other USB dual-mode controller drivers.Signed-off-by Igor Skalkin <[email protected]>
Why does this not match the author name?
thanks,
greg k-h
Re: [PATCH 1/8] virtio-usb: add protocol header and skeleton dual-role driver
Quoted 14 lines · Greg Kroah-Hartman
Quoted 13 lines · Igor Skalkin
From: Aiswarya Cyriac <[email protected]>
Add the
virtio_usbdevice 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_portarray (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, device, OTG) builds on this same array from the start, instead of the host, device, and OTG subsystems each growing their own separate port-indexed storage that later has to be reconciled.
Quoted 9 lines
Quoted 6 lines
Wire the new
drivers/usb/virtio_usb/directory into the USB subsystem's build (drivers/usb/Kconfig,drivers/usb/Makefile) as a newCONFIG_USB_VIRTIOoption, listed alongside the other USB dual-mode controller drivers.Signed-off-by Igor Skalkin <[email protected]>Why does this not match the author name?
Sorry, this is an artifact of squashing a much larger internal history (100+ commits) down to this 8-commit series. Will be fixed.
Quoted 3 lines
thanks,
greg k-h
Thanks,
Igor
Greg Kroah-Hartman
maintainerRe: [PATCH 1/8] virtio-usb: add protocol header and skeleton dual-role driver
In reply to Igor Skalkininclude/uapi/linux/virtio_usb.h line 117
Quoted 9 lines · Igor Skalkin
include/uapi/linux/virtio_usb.h new file +9
-0+/* VIRTIO_USB_EVT_HOST_PORT_CONNECTED/DISCONNECTED */ +enum { +VIRTIO_USB_SPEED_UNKNOWN =0 , +VIRTIO_USB_SPEED_LOW , +VIRTIO_USB_SPEED_FULL ,/* usb 1.1 */ +VIRTIO_USB_SPEED_HIGH ,/* usb 2.0 */ +VIRTIO_USB_SPEED_WIRELESS ,/* wireless (usb 2.5) */ +VIRTIO_USB_USB_SPEED_SUPER ,/* usb 3.0 */ +VIRTIO_USB_SPEED_SUPER_PLUS ,/* usb 3.1 */
Please enumerate all of your enums with explicit values as these are going to userspace.
include/uapi/linux/virtio_usb.h line 124
Quoted 7 lines
include/uapi/linux/virtio_usb.h new file +7
-0+}; + +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;
All of your padding fields MUST be verified to only be set to 0.
These are basic "how to write a uapi" things, did you all not read the in-kernel documentation for this?
thanks,
greg k-h
Re: [PATCH 1/8] virtio-usb: add protocol header and skeleton dual-role driver
Quoted 14 lines · Greg Kroah-Hartman
include/uapi/linux/virtio_usb.h line 117
Quoted 9 lines · Igor Skalkin
include/uapi/linux/virtio_usb.h new file +9
-0+/* VIRTIO_USB_EVT_HOST_PORT_CONNECTED/DISCONNECTED */ +enum { +VIRTIO_USB_SPEED_UNKNOWN =0 , +VIRTIO_USB_SPEED_LOW , +VIRTIO_USB_SPEED_FULL ,/* usb 1.1 */ +VIRTIO_USB_SPEED_HIGH ,/* usb 2.0 */ +VIRTIO_USB_SPEED_WIRELESS ,/* wireless (usb 2.5) */ +VIRTIO_USB_USB_SPEED_SUPER ,/* usb 3.0 */ +VIRTIO_USB_SPEED_SUPER_PLUS ,/* usb 3.1 */ Please enumerate all of your enums with explicit values as these are going to userspace.
Will convert these to #define constants.
Quoted 10 lines
include/uapi/linux/virtio_usb.h line 124
Quoted 7 lines
include/uapi/linux/virtio_usb.h new file +7
-0+}; + +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;All of your padding fields MUST be verified to only be set to 0.
Quoted 3 lines
These are basic "how to write a uapi" things, did you all not read the in-kernel documentation for this?
Agreed, will be fixed.
Quoted 3 lines
thanks,
greg k-h
Thanks,
Igor
PATCH 2/8 virtio-usb: add host role (USB Host Controller) support
In reply to Igor SkalkinFrom: Aiswarya Cyriac <[email protected]>
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 OTG-based role resolution.
--- drivers/usb/virtio_usb/Makefile | 4 drivers/usb/virtio_usb/controller.c | 105 ++ drivers/usb/virtio_usb/controller.h | 35 drivers/usb/virtio_usb/host.c | 1335 ++++++++++++++++++++++++++++++++++++ drivers/usb/virtio_usb/host.h | 203 +++++ drivers/usb/virtio_usb/vq_common.c | 740 +++++++++++++++++++ drivers/usb/virtio_usb/vq_common.h | 163 ++++ include/uapi/linux/virtio_usb.h | 16 8 files changed, 2585 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
drivers/usb/virtio_usb/controller.c +100 -5
@@ -6,9 +6,16 @@*/ #include <linux/module.h> +#include <linux/moduleparam.h> #include <uapi/linux/virtio_ids.h> #include "controller.h" +#include "host.h" +#include "vq_common.h" + +u32 virtio_usb_cmd_timeout_ms =MSEC_PER_SEC ; +module_param_named (cmd_timeout_ms, virtio_usb_cmd_timeout_ms, uint,0644 ); +MODULE_PARM_DESC (cmd_timeout_ms,"Command completion timeout in milliseconds" );/** * virtio_usb_find_vqs() - Enumerate and initialize all virtqueues.
@@ -70,9 +77,22 @@ 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 ; + } + +if (!virtio_usb_cmd_timeout_ms) { +dev_err (&vdev->dev,"msg_timeout_ms value cannot be zero\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 +104,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 +120,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, OTG) 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 +143,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 +211,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 +235,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,
drivers/usb/virtio_usb/controller.h +28 -7
@@ -14,18 +14,23 @@#include <uapi/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, OTG) 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 +40,15 @@ 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. */ struct virtio_usb {struct virtio_device *vdev;
@@ -42,6 +56,10 @@ 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; };/**
@@ -81,4 +99,7 @@ struct virtio_usb_vq_desc { void (*stop)(struct virtio_usb *vusb, struct virtio_usb_queue *vq); }; +/* Command completion timeout in milliseconds (module parameter). */ +extern u32 virtio_usb_cmd_timeout_ms; +#endif /* VIRTIO_USB_CONTROLLER_H */
drivers/usb/virtio_usb/Makefile +3 -1
@@ -1,5 +1,7 @@ # SPDX-License-Identifier: GPL-2.0-or-later -virtio-usb-y := controller.o +virtio-usb-y := controller.o \ + vq_common.o \ + host.o obj-$(CONFIG_USB_VIRTIO) += virtio-usb.o
drivers/usb/virtio_usb/host.c new file +1335 -0
1,335 lines not on this page · raw message
drivers/usb/virtio_usb/host.h new file +203 -0
203 lines not on this page · raw message
include/uapi/linux/virtio_usb.h +13 -3
@@ -106,6 +106,14 @@ enum { VIRTIO_USB_EVT_HOST_PORT_DISCONNECTED, }; +/* 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 */ enum {VIRTIO_USB_SPEED_UNKNOWN =0 ,
@@ -119,9 +127,9 @@ enum {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_id;/* leaf slot within VP, 0..VIRTIO_USB_VP_MAX_PORTS-1 */ __le32 speed;/* VIRTIO_USB_SPEED_XXX */ -__le32 padding; };/*****************************************************************************
@@ -210,10 +218,12 @@ enum { 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 {
drivers/usb/virtio_usb/vq_common.c new file +740 -0
740 lines not on this page · raw message
drivers/usb/virtio_usb/vq_common.h new file +163 -0
163 lines not on this page · raw message
[email protected]
AI reviewRe: [PATCH 2/8] virtio-usb: add host role (USB Host Controller) support
Thank you for your contribution! Sashiko AI review found 12 potential issue(s) to consider: - [Critical] virtio-usb: missing bounds check on actual_length enables OOB memory access - [High]…
Thank you for your contribution! Sashiko AI review found 12 potential issue(s) to consider:
- [Critical] virtio-usb: missing bounds check on actual_length enables OOB memory access
- [High] virtio-usb: host dataq cancel_work_sync() on uninitialized work_struct
- [High] virtio-usb: missing sg_mark_end() in virtio_usb_hc_set_urb_sgs()
- [High] virtio-usb: invalid sg_virt() on Highmem pages crashes DMA mapping
- [High] virtio-usb: virtqueue teardown before virtio_reset_device() causes UAF
- [High] virtio-usb: virtio_usb_port_from_urb() misroutes URBs for devices behind hubs
- [High] virtio-usb: virtio_usb_data_send() enables interrupts in atomic context
- [High] virtio-usb: leaking vurb heap address as tag breaks KASLR and causes ABA
- [High] virtio-usb: heap overflow in virtio_usb_hub_control() when wLength is small
- [Medium] virtio-usb: missing NULL check on events array causes panic during init
- [Medium] virtio-usb: virtio_usb_evt_drain_stop_cb() leaks pending buffers on teardown
- [Medium] virtio-usb: bitfield usage in port status breaks big-endian hosts --
commit 89dd2308fe62a55b4cf51aa86800ab5c1ff53727
Author: Aiswarya Cyriac <[email protected]>
virtio-usb: add host role (USB Host Controller) support
Adds common virtqueue handling code and the virtio-usb host controller implementation. Host virtual ports are initialized with pre-allocated leaf slots, and role resolution is initially hardcoded to the host role.
Quoted 4 lines
drivers/usb/virtio_usb/controller.c +0
-0
[ ... ]
Quoted 2 lines
drivers/usb/virtio_usb/controller.c +2
-0+static int virtio_usb_probe (struct virtio_device *vdev) +{
[ ... ]
drivers/usb/virtio_usb/controller.c static int virtio_usb_probe(struct virtio_device *vdev) · line 166
Quoted 9 lines
drivers/usb/virtio_usb/controller.c +9
-0+ rc =virtio_usb_find_vqs (vusb); +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);
[Severity: High]
Does this code call cancel_work_sync() on an uninitialized work_struct if probe fails?
If virtio_usb_find_vqs() returns an error, the driver jumps to the error path and calls virtio_usb_remove(), which eventually invokes virtio_usb_hc_dataq_stop_cb(). That function unconditionally calls cancel_work_sync(&vusb->vq_host_data_rx_work). Since INIT_WORK hasn't been called yet, could this trigger a kernel panic or lockdep warning?
[ ... ]
Quoted 4 lines
drivers/usb/virtio_usb/controller.c +4
-0+static void virtio_usb_remove (struct virtio_device *vdev) +{ +struct virtio_usb *vusb = vdev->priv; +int i;
drivers/usb/virtio_usb/controller.c
Quoted 10 lines
drivers/usb/virtio_usb/controller.c +10
-0+ +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);
[Severity: High]
Can this order of operations cause a use-after-free?
The stop() callbacks (like virtio_usb_hc_dataq_stop_cb()) unlink all pending URBs and free their associated memory while the virtio device is still active. Since virtio_reset_device() is called afterward, could the hardware concurrently complete a pending request and DMA-write the response into the just-freed memory?
Quoted 5 lines
drivers/usb/virtio_usb/host.c new file +0
-0
[ ... ]
drivers/usb/virtio_usb/host.c line 161
Quoted 13 lines
drivers/usb/virtio_usb/host.c new file +13
-0+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 ));
[Severity: High]
Can this memset() overflow the provided buffer?
The buffer size is determined by the wLength parameter. If userspace submits a control transfer via usbfs with a wLength smaller than sizeof(struct usb_hub_descriptor), will this unconditional memset() write past the allocated buffer bounds?
[ ... ]
Quoted 2 lines
drivers/usb/virtio_usb/host.c new file +2
-0+static void virtio_usb_hc_complete_urb (struct virtio_usb_data *vurb) +{
[ ... ]
drivers/usb/virtio_usb/host.c line 447
Quoted 1 line
drivers/usb/virtio_usb/host.c new file +1
-0+ urb->actual_length =le32_to_cpu (response->actual_length);
[Severity: Critical]
Is it safe to trust the actual_length provided by the virtio device without bounds checking?
If the untrusted response->actual_length exceeds urb->transfer_buffer_length, can subsequent USB class drivers use this value to read or write past the end of the transfer buffer?
Quoted 1 line
drivers/usb/virtio_usb/host.c new file +1
-0+if (urb->status == -EINVAL )
[ ... ]
drivers/usb/virtio_usb/host.c line 466
Quoted 10 lines
drivers/usb/virtio_usb/host.c new file +10
-0+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);
[Severity: Critical]
Does this code also need bounds checking against the expected isochronous frame lengths to prevent out-of-bounds memory accesses?
[ ... ]
Quoted 3 lines
drivers/usb/virtio_usb/host.c new file +3
-0+static struct scatterlist * +virtio_usb_hc_set_urb_sgs (struct virtio_usb_hc_priv *priv,gfp_t gfp) +{
[ ... ]
drivers/usb/virtio_usb/host.c line 519
Quoted 13 lines
drivers/usb/virtio_usb/host.c new file +13
-0+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 ; + }
[Severity: High]
When breaking early from this loop, does the code miss marking the end of the new scatterlist?
Without calling sg_mark_end(&sgs[i]), passing this array to virtqueue_add_sgs() could cause the iterator to walk past the valid elements into the zero-initialized remainder, leading to DMA mapping crashes.
[ ... ]
Quoted 4 lines
drivers/usb/virtio_usb/host.c new file +4
-0+static struct virtio_usb_data * +virtio_usb_hc_data_alloc (struct virtio_usb_hc_port *port,struct urb *urb, +gfp_t gfp) +{
[ ... ]
drivers/usb/virtio_usb/host.c line 573
Quoted 1 line
drivers/usb/virtio_usb/host.c new file +1
-0+ request->tag =cpu_to_le64 ((uintptr_t )vurb);
[Severity: High]
Is it intended to expose a raw kernel heap address to the virtio backend?
Leaking this pointer breaks KASLR. Additionally, in virtio_usb_hc_dequeue(), this same pointer is used as the cancellation tag. If the URB is concurrently completed and its memory freed and reallocated for a new URB, could the delayed cancel command erroneously cancel the new URB (the ABA problem)?
[ ... ]
drivers/usb/virtio_usb/host.c line 682
Quoted 10 lines
drivers/usb/virtio_usb/host.c new file +10
-0+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]; +}
[Severity: High]
Does this logic assume that all URBs target a device directly connected to the root hub?
If a guest enumerates a USB hub, urb->dev->portnum would correspond to the parent hub's port rather than the root hub. Could this misroute requests to the wrong port slot on the virtio backend?
[ ... ]
Quoted 3 lines
drivers/usb/virtio_usb/host.c new file +3
-0+static int virtio_usb_hc_enqueue (struct usb_hcd *hcd,struct urb *urb, +gfp_t mem_flags) +{
[ ... ]
Quoted 5 lines
drivers/usb/virtio_usb/host.c new file +5
-0+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);
drivers/usb/virtio_usb/host.c line 729
Quoted 10 lines
drivers/usb/virtio_usb/host.c new file +10
-0+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 ; + }
[Severity: High]
Is it safe to use sg_virt() on an arbitrary scatterlist element here?
The USB core allows URB scatterlists to reference HIGHMEM pages, for which page_address() returns NULL. In that case, sg_virt() would calculate an invalid virtual address (NULL + offset), potentially crashing the system during DMA mapping.
[ ... ]
Quoted 2 lines
drivers/usb/virtio_usb/host.c new file +2
-0+int virtio_usb_hc_event_populate (struct virtio_usb *vusb) +{
[ ... ]
drivers/usb/virtio_usb/host.c line 945
Quoted 7 lines
drivers/usb/virtio_usb/host.c new file +7
-0+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); +}
[Severity: Medium]
Does this code dereference the events array without checking for NULL?
If virtio_usb_events_alloc() fails to allocate memory and returns NULL, passing it directly to virtio_usb_events_populate() will cause a kernel panic when the array is dereferenced.
Quoted 5 lines
drivers/usb/virtio_usb/host.h new file +0
-0
[ ... ]
Quoted 4 lines
drivers/usb/virtio_usb/host.h new file +4
-0+struct virtio_usb_port_hs_status { +u16 connect :1 ; +u16 enable :1 ; +u16 suspend :1 ;
drivers/usb/virtio_usb/host.h line 38
Quoted 10 lines
drivers/usb/virtio_usb/host.h new file +10
-0+ 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; +};
[Severity: Medium]
Can this bitfield definition break hub emulation on big-endian architectures?
Memory layout for C bitfields is implementation-defined and reversed on big-endian systems. Since the values are written directly to a u16 buffer in virtio_usb_hub_control(), could this cause the USB core to observe scrambled port status bits?
Quoted 5 lines
drivers/usb/virtio_usb/vq_common.c new file +0
-0
[ ... ]
Quoted 4 lines
drivers/usb/virtio_usb/vq_common.c new file +4
-0+int virtio_usb_data_send (struct virtio_usb *vusb,struct virtio_usb_data *data, +struct scatterlist *out_sgs, +struct scatterlist *in_sgs) +{
[ ... ]
drivers/usb/virtio_usb/vq_common.c line 576
Quoted 6 lines
drivers/usb/virtio_usb/vq_common.c new file +6
-0+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);
[Severity: High]
Does spin_unlock_irq() incorrectly re-enable hardware interrupts when called from atomic context?
This function is invoked by virtio_usb_hc_enqueue() (the urb_enqueue HCD callback), which is often executed in atomic hardirq context when USB drivers submit URBs from their completion handlers. Unconditionally enabling interrupts here can lead to nested interrupts or stack overflows.
[ ... ]
Quoted 3 lines
drivers/usb/virtio_usb/vq_common.c new file +3
-0+void virtio_usb_evt_drain_stop_cb (struct virtio_usb_queue *vq, +struct work_struct *work) +{
[ ... ]
drivers/usb/virtio_usb/vq_common.c line 740
Quoted 6 lines
drivers/usb/virtio_usb/vq_common.c new file +6
-0+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); +}
[Severity: Medium]
Should this loop use virtqueue_detach_unused_buf() instead of virtqueue_get_buf()?
Because virtqueue_get_buf() only returns buffers that have been completed by the device, preallocated event buffers might remain stuck on the vring. When the virtio core destroys the queues, it expects all buffers to be properly detached, potentially leading to leaked descriptor slots and core warnings.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
Greg Kroah-Hartman
maintainerRe: [PATCH 2/8] virtio-usb: add host role (USB Host Controller) support
In reply to Igor SkalkinQuoted 57 lines · Igor Skalkin
From: Aiswarya Cyriac <[email protected]>
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_hcdpair and its own root hub (structvirtio_usb_hc_vp), with a fixedVIRTIO_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 HCDbus_namefrom the parentvirtio_devicewithdevm_kasprintf()rather than a stack buffer, since usb_create_hcd()/usb_create_shared_hcd() store that pointer as-is inhcd->self.bus_namewithout 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 OTG-based role resolution.
Signed-off-by Aiswarya Cyriac <[email protected]>Co-developed-by Anton Yakovlev <[email protected]>Signed-off-by Anton Yakovlev <[email protected]>Signed-off-by Vasilii Ianikeev <[email protected]>Co-developed-by Igor Skalkin <[email protected]>Signed-off-by Igor Skalkin <[email protected]>--- drivers/usb/virtio_usb/Makefile | 4 drivers/usb/virtio_usb/controller.c | 105 ++ drivers/usb/virtio_usb/controller.h | 35 drivers/usb/virtio_usb/host.c | 1335 ++++++++++++++++++++++++++++++++++++ drivers/usb/virtio_usb/host.h | 203 +++++ drivers/usb/virtio_usb/vq_common.c | 740 +++++++++++++++++++ drivers/usb/virtio_usb/vq_common.h | 163 ++++ include/uapi/linux/virtio_usb.h | 16 8 files changed, 2585 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.hdrivers/usb/virtio_usb/controller.c +0
-0@@ -6,9 +6,16 @@*/ #include <linux/module.h>
drivers/usb/virtio_usb/controller.c line 18
Quoted 10 lines
drivers/usb/virtio_usb/controller.c +7
-0+#include <linux/moduleparam.h> #include <uapi/linux/virtio_ids.h> #include "controller.h" +#include "host.h" +#include "vq_common.h" + +u32 virtio_usb_cmd_timeout_ms =MSEC_PER_SEC ; +module_param_named (cmd_timeout_ms, virtio_usb_cmd_timeout_ms, uint,0644 ); +MODULE_PARM_DESC (cmd_timeout_ms,"Command completion timeout in milliseconds" );
This is not the 1990's, please do not add new module parameters. Just make it work without manual configuration at module load time.
If you really need a configuration option, make it per-device and use the correct, modern, apis for it.
thanks,
greg k-h
Re: [PATCH 2/8] virtio-usb: add host role (USB Host Controller) support
Quoted 72 lines · Greg Kroah-Hartman
Quoted 57 lines · Igor Skalkin
From: Aiswarya Cyriac <[email protected]>
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_hcdpair and its own root hub (structvirtio_usb_hc_vp), with a fixedVIRTIO_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 HCDbus_namefrom the parentvirtio_devicewithdevm_kasprintf()rather than a stack buffer, since usb_create_hcd()/usb_create_shared_hcd() store that pointer as-is inhcd->self.bus_namewithout 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 OTG-based role resolution.
Signed-off-by Aiswarya Cyriac <[email protected]>Co-developed-by Anton Yakovlev <[email protected]>Signed-off-by Anton Yakovlev <[email protected]>Signed-off-by Vasilii Ianikeev <[email protected]>Co-developed-by Igor Skalkin <[email protected]>Signed-off-by Igor Skalkin <[email protected]>--- drivers/usb/virtio_usb/Makefile | 4 drivers/usb/virtio_usb/controller.c | 105 ++ drivers/usb/virtio_usb/controller.h | 35 drivers/usb/virtio_usb/host.c | 1335 ++++++++++++++++++++++++++++++++++++ drivers/usb/virtio_usb/host.h | 203 +++++ drivers/usb/virtio_usb/vq_common.c | 740 +++++++++++++++++++ drivers/usb/virtio_usb/vq_common.h | 163 ++++ include/uapi/linux/virtio_usb.h | 16 8 files changed, 2585 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.hdrivers/usb/virtio_usb/controller.c +0
-0@@ -6,9 +6,16 @@*/ #include <linux/module.h> drivers/usb/virtio_usb/controller.c line 18
Quoted 10 lines
drivers/usb/virtio_usb/controller.c +7
-0+#include <linux/moduleparam.h> #include <uapi/linux/virtio_ids.h> #include "controller.h" +#include "host.h" +#include "vq_common.h" + +u32 virtio_usb_cmd_timeout_ms =MSEC_PER_SEC ; +module_param_named (cmd_timeout_ms, virtio_usb_cmd_timeout_ms, uint,0644 ); +MODULE_PARM_DESC (cmd_timeout_ms,"Command completion timeout in milliseconds" );This is not the 1990's, please do not add new module parameters. Just make it work without manual configuration at module load time.
Quoted 3 lines
If you really need a configuration option, make it per-device and use the correct, modern, apis for it.
Agreed, will remove it.
Quoted 3 lines
thanks,
greg k-h
PATCH 3/8 virtio-usb: add device role (USB Device Controller) support
In reply to Igor SkalkinFrom: Aiswarya Cyriac <[email protected]>
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.
The UDC driver is marked nonatomic, since some gadget API calls performed under a spinlock cannot be completed atomically due to the round trip over virtio to the backend.
With both host_role and device_role negotiated, a port's actual role is ambiguous until a later commit adds an OTG-based per-port query - every port defaults to DEVICE for now as a placeholder.
--- 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 | 1356 ++++++++++++++++++++++++++++++++++++ drivers/usb/virtio_usb/device.h | 91 ++ include/uapi/linux/virtio_usb.h | 37 6 files changed, 1566 insertions(+), 13 deletions(-) create mode 100644 drivers/usb/virtio_usb/device.c create mode 100644 drivers/usb/virtio_usb/device.h
drivers/usb/virtio_usb/controller.c +70 -5
@@ -11,6 +11,7 @@#include "controller.h" #include "host.h" +#include "device.h" #include "vq_common.h" u32 virtio_usb_cmd_timeout_ms =MSEC_PER_SEC ;
@@ -77,7 +78,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 ;
@@ -123,17 +125,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, OTG) 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 an OTG-based +* per-port 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),
@@ -155,6 +180,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",
@@ -190,6 +227,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;
@@ -219,6 +280,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);
@@ -226,6 +290,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[] = {
drivers/usb/virtio_usb/controller.h +17 -0
@@ -16,21 +16,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; };/**
@@ -41,14 +46,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. */ struct virtio_usb {struct virtio_device *vdev;
@@ -57,9 +70,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; };/**
drivers/usb/virtio_usb/Makefile +2 -1
@@ -1,7 +1,8 @@ # SPDX-License-Identifier: GPL-2.0-or-later virtio-usb-y := controller.o \ vq_common.o \ - host.o + host.o \ + device.o obj-$(CONFIG_USB_VIRTIO) += virtio-usb.o
drivers/usb/virtio_usb/device.c new file +1356 -0
1,356 lines not on this page · raw message
drivers/usb/virtio_usb/device.h new file +91 -0
91 lines not on this page · raw message
include/uapi/linux/virtio_usb.h +30 -7
@@ -64,12 +64,11 @@ enum {VIRTIO_USB_S_ERR_STALL ,VIRTIO_USB_S_ERR_SHORT_PKT , VIRTIO_USB_S_ERR_CANCELLED, - VIRTIO_USB_S_ERR_HOST, };struct virtio_usb_cmd_status {__le32 code;/* VIRTIO_USB_S_XXX */ -}; +} __packed;/***************************************************************************** * HOST COMMAND MESSAGES
@@ -145,6 +144,8 @@ enum {VIRTIO_USB_CMD_DEV_EP_SET_HALT ,VIRTIO_USB_CMD_DEV_EP_SET_WEDGE ,VIRTIO_USB_CMD_DEV_CANCEL , +VIRTIO_USB_CMD_DEV_GET_FRAME_NUMBER , + VIRTIO_USB_CMD_DEV_SET_SELF_POWERED, }; struct virtio_usb_dev_cmd_hdr {
@@ -153,12 +154,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; +}; +enum {VIRTIO_USB_DIR_OUT =0 ,VIRTIO_USB_DIR_IN ,
@@ -176,35 +195,39 @@ enum {* struct virtio_usb_cmd_status * struct virtio_usb_dev_cmd_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 */ enum { -VIRTIO_USB_EVT_DEV_CONNECTED =0 , +VIRTIO_USB_EVT_DEV_BIND =0 ,VIRTIO_USB_EVT_DEV_DISCONNECTED ,VIRTIO_USB_EVT_DEV_SETUP ,VIRTIO_USB_EVT_DEV_RESET ,VIRTIO_USB_EVT_DEV_SUSPEND ,VIRTIO_USB_EVT_DEV_RESUME , +VIRTIO_USB_EVT_DEV_UNBIND , };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_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 ]; };/*******************************************************************************
[email protected]
AI reviewRe: [PATCH 3/8] virtio-usb: add device role (USB Device Controller) support
Thank you for your contribution! Sashiko AI review found 14 potential issue(s) to consider: - [Critical] usb: virtio_usb: Use-After-Free of vudc->veps array during asynchronous UNBIND - [Critical]…
Thank you for your contribution! Sashiko AI review found 14 potential issue(s) to consider:
- [Critical] usb: virtio_usb: Use-After-Free of vudc->veps array during asynchronous UNBIND
- [Critical] usb: virtio_usb: NULL pointer dereference handling events on a host-role port
- [Critical] usb: virtio_usb: Host-provided actual_length enables out-of-bounds reads in gadget drivers
- [High] usb: virtio_usb: Use-After-Free of virtio command response buffer in virtio_usb_dc_get_frame()
- [High] usb: virtio_usb: Memory corruption from zeroing a refcounted struct device
- [High] usb: virtio_usb: Invalid DMA mapping of .rodata for endpoint descriptor
- [High] usb: virtio_usb: Scatter-gather list ignored if req->buf is populated
- [High] usb: virtio_usb: ABA pointer race in virtio_ep_dequeue causes Use-After-Free
- [High] usb: virtio_usb: Lockless req_queue mutation causes list corruption in teardown
- [High] usb: virtio_usb: Endpoint operations sleep in atomic context
- [High] usb: virtio_usb: TOCTOU race invokes setup() on an unloaded driver module
- [Medium] usb: virtio_usb: Global namespace collision for multiple virtio-usb controllers
- [Medium] usb: virtio_usb: Unconditional NULL pointer dereference in virtio_usb_dc_dataq_stop_cb()
- [Medium] usb: virtio_usb: Memory leak of gadget name string during teardown
--
commit a6cc5b6e920b40a9b504189953adff7fa11229be
Author: Aiswarya Cyriac <[email protected]>
virtio-usb: add device role (USB Device Controller) support
This commit adds device (UDC) role support to the virtio-usb driver. It implements the gadget and endpoint callback sets to interact with the UDC core, passing lifecycle events and endpoint requests over virtqueues to the host backend.
Quoted 6 lines
drivers/usb/virtio_usb/device.c new file +0
-0@@ -0,0 +1,1356 @@
[ ... ]
drivers/usb/virtio_usb/device.c line 93
Quoted 13 lines
drivers/usb/virtio_usb/device.c new file +13
-0+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; + +spin_lock_irqsave (&vudc->lock, flags);
[Severity: Critical]
Can this asynchronous completion race with the UNBIND event handler? The UNBIND handler in virtio_usb_dc_event_process() frees the vudc->veps array unconditionally without draining in-flight virtqueue data. If this completion executes after the array is freed, dereferencing priv->vep to access the lock and req_queue would result in a Use-After-Free.
[ ... ]
drivers/usb/virtio_usb/device.c line 108
Quoted 4 lines
drivers/usb/virtio_usb/device.c new file +4
-0+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);
[Severity: Critical]
Is it possible for the host to provide an actual_length larger than the original request length? Since req->actual is updated without bounds checking against req->length, could a malicious host backend trick gadget drivers into reading out-of-bounds memory?
[ ... ]
Quoted 3 lines
drivers/usb/virtio_usb/device.c new file +3
-0+static int virtio_ep_enable (struct usb_ep *ep, +const struct usb_endpoint_descriptor *desc) +{
[ ... ]
drivers/usb/virtio_usb/device.c line 294
Quoted 10 lines
drivers/usb/virtio_usb/device.c new file +10
-0+ cmd =virtio_usb_dc_cmd_alloc (vudc,VIRTIO_USB_CMD_DEV_EP_ENABLE , +GFP_ATOMIC ); +if (!cmd) +return -ENOMEM ; + +sg_init_one (psg_data, desc,sizeof (*desc)); + hdr =virtio_usb_cmd_request (cmd); + hdr->endpoint =cpu_to_le16 (endpoint); + + rc =virtio_usb_cmd_send_sync (vudc->vusb, psg_data,NULL , cmd);
[Severity: High]
Does this map a static endpoint descriptor for DMA? Gadget drivers often pass endpoint descriptors located in static const (.rodata) memory. The DMA API does not permit mapping .rodata memory, so passing it to sg_init_one() here could cause a BUG_ON or silent DMA corruption.
[ ... ]
Quoted 3 lines
drivers/usb/virtio_usb/device.c new file +3
-0+static int virtio_ep_queue (struct usb_ep *ep,struct usb_request *req, +gfp_t mem_flags) +{
[ ... ]
drivers/usb/virtio_usb/device.c line 441
Quoted 6 lines
drivers/usb/virtio_usb/device.c new file +6
-0+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->sg) {
[Severity: High]
Will multi-page scatter-gather transfers be silently ignored if a gadget driver populates both req->buf (as a fallback) and req->sg? The first condition matches if req->buf is present, breaking the scatter-gather transfer logic.
[ ... ]
Quoted 2 lines
drivers/usb/virtio_usb/device.c new file +2
-0+static int virtio_ep_dequeue (struct usb_ep *ep,struct usb_request *req) +{
[ ... ]
Quoted 6 lines
drivers/usb/virtio_usb/device.c new file +6
-0+spin_unlock_irqrestore (&vudc->lock, flags); + +if (rc) +return rc; + + vreq = priv->vreq;
drivers/usb/virtio_usb/device.c line 522
Quoted 10 lines
drivers/usb/virtio_usb/device.c new file +10
-0+ + cmd =virtio_usb_dc_cmd_alloc (vudc,VIRTIO_USB_CMD_DEV_CANCEL , +GFP_KERNEL ); +if (!cmd) +return -ENOMEM ; + + 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 ((uintptr_t )vreq);
[Severity: High]
Could priv be accessed after it is freed here? The vudc->lock is dropped prior to accessing priv->vreq. If the completion handler concurrently gives back the request and frees the associated vreq, this would result in a Use-After-Free and cancel the wrong tag.
[ ... ]
Quoted 2 lines
drivers/usb/virtio_usb/device.c new file +2
-0+static int virtio_ep_set_halt (struct usb_ep *ep,int value) +{
[ ... ]
drivers/usb/virtio_usb/device.c line 579
Quoted 10 lines
drivers/usb/virtio_usb/device.c new file +10
-0+ 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);
[Severity: High]
Does virtio_usb_cmd_send_sync() sleep? The gadget API allows usb_ep_set_halt() to be called in atomic context (e.g. from an interrupt handler or while holding a spinlock). If virtio_usb_cmd_send_sync() blocks waiting for a completion, this will trigger scheduling while atomic panics.
[ ... ]
Quoted 2 lines
drivers/usb/virtio_usb/device.c new file +2
-0+static int virtio_usb_dc_get_frame (struct usb_gadget *gadget) +{
[ ... ]
drivers/usb/virtio_usb/device.c line 827
Quoted 10 lines
drivers/usb/virtio_usb/device.c new file +10
-0+ 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);
[Severity: High]
Is the command buffer freed during virtio_usb_cmd_send_sync()? If the send function drops the final reference and frees the message upon returning, accessing resp->frame_number here would be a Use-After-Free.
[ ... ]
drivers/usb/virtio_usb/device.c line 954
Quoted 5 lines
drivers/usb/virtio_usb/device.c new file +5
-0+static int virtio_usb_dc_parent_create (struct virtio_usb_dc *vudc) +{ +int rc; + + vudc->pdev =platform_device_alloc (GADGET_NAME , vudc->port);
[Severity: Medium]
Will this cause a sysfs naming conflict if multiple virtio-usb controllers are present in the system? The port number is zero-indexed per controller, so multiple instances could attempt to register devices with identical names.
[ ... ]
Quoted 2 lines
drivers/usb/virtio_usb/device.c new file +2
-0+static void virtio_usb_dc_event_process (struct virtio_usb_event *event) +{
[ ... ]
drivers/usb/virtio_usb/device.c line 995
Quoted 10 lines
drivers/usb/virtio_usb/device.c new file +10
-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 ; + } + + vudc = vusb->vports[port_id].vudc; + driver = vudc->driver;
[Severity: Critical]
What happens if the host backend sends a device-role event for a host-role port? Since virtio_usb_dc_init() is only called for device-role ports, vudc will be NULL for host-role ports, resulting in a NULL pointer dereference here.
[ ... ]
drivers/usb/virtio_usb/device.c line 1007
Quoted 11 lines
drivers/usb/virtio_usb/device.c new file +11
-0+switch (le32_to_cpu (evt->code)) { +case VIRTIO_USB_EVT_DEV_BIND : { +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 ));
[Severity: High]
Does zeroing the entire gadget structure destroy the active kobject state if it is still refcounted? If a user-space process (like udev) still holds an open sysfs reference from a previous BIND/UNBIND cycle, zeroing the embedded struct device can cause kobject refcount corruption and kernel panics.
[ ... ]
drivers/usb/virtio_usb/device.c line 1077
Quoted 12 lines
drivers/usb/virtio_usb/device.c new file +12
-0+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); + +memcpy (&vep->setup, setup_evt->setup, +sizeof (struct usb_ctrlrequest )); + + rc = driver->setup (&vudc->gadget, + (struct usb_ctrlrequest *)setup_evt->setup);
[Severity: High]
Could the cached driver pointer point to an unloaded module here? If a user removes the gadget driver concurrently with the host backend sending a SETUP event, this could invoke setup() on an unloaded driver, causing a kernel crash.
[ ... ]
Quoted 2 lines
drivers/usb/virtio_usb/device.c new file +2
-0+int virtio_usb_dc_deinit (struct virtio_usb *vusb) +{
[ ... ]
drivers/usb/virtio_usb/device.c line 1227
Quoted 5 lines
drivers/usb/virtio_usb/device.c new file +5
-0+if (registered) +usb_del_gadget_udc (&vudc->gadget); + +kfree (vudc->veps); + vudc->veps =NULL ;
[Severity: Medium]
Should vudc->gadget.name be freed here? While the UNBIND event correctly frees it, virtio_usb_dc_deinit() appears to omit the kfree(), leading to a permanent memory leak of the kasprintf-allocated string.
[ ... ]
Quoted 3 lines
drivers/usb/virtio_usb/device.c new file +3
-0+static void virtio_usb_dc_dataq_stop_cb (struct virtio_usb *vusb, +struct virtio_usb_queue *dataq) +{
[ ... ]
drivers/usb/virtio_usb/device.c line 1269
Quoted 3 lines
drivers/usb/virtio_usb/device.c new file +3
-0+for (i =0 ; i < vudc->neps; i++) { + list_for_each_entry_safe(vreq, vreq_tmp, + &vudc->veps[i].req_queue,
[Severity: Medium]
Could vudc->veps be NULL here? If a BIND event fails or an UNBIND event successfully completes, vudc->neps could be > 0 while vudc->veps is NULL, resulting in a NULL pointer dereference when the module is unloaded.
[Severity: High]
Is it safe to mutate this linked list without acquiring the vudc->lock? The gadget driver could be concurrently queuing or dequeuing requests. Modifying the req_queue with list_del_init() locklessly could corrupt the list and cause a kernel panic.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
PATCH 4/8 virtio-usb: add OTG role query support
In reply to Igor SkalkinWith 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 OTG command/event queue pair (otg_vq_base, otg_vqueues[], otg_init()/otg_deinit()) and otg_get_role(), a synchronous VIRTIO_USB_CMD_OTG_GET_ROLE 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.
--- drivers/usb/virtio_usb/Makefile | 3 drivers/usb/virtio_usb/controller.c | 87 +++++++++++++++--- drivers/usb/virtio_usb/controller.h | 11 ++ drivers/usb/virtio_usb/otg.c | 168 ++++++++++++++++++++++++++++++++++++ drivers/usb/virtio_usb/otg.h | 26 +++++ 5 files changed, 277 insertions(+), 18 deletions(-) create mode 100644 drivers/usb/virtio_usb/otg.c create mode 100644 drivers/usb/virtio_usb/otg.h
drivers/usb/virtio_usb/controller.c +70 -17
@@ -12,6 +12,7 @@#include "controller.h" #include "host.h" #include "device.h" +#include "otg.h" #include "vq_common.h" u32 virtio_usb_cmd_timeout_ms =MSEC_PER_SEC ;
@@ -130,12 +131,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, OTG_* 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 ;
@@ -148,17 +149,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 an OTG-based -* per-port 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 OTG command/event queue pair is needed whenever both +* roles are negotiated - it is how the driver asks each +* port for its actual role via otg_get_role() below, since +* a port's own role is otherwise ambiguous (host|device) +* until then. +*/ + vusb->otg_vq_base = nvqs; + nvqs +=VIRTIO_USB_VQ_OTG_MAX ; } vusb->vqueues = devm_kcalloc(&vdev->dev, nvqs, sizeof(*vusb->vqueues),
@@ -192,6 +191,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_OTG_MAX ; i++) { + vusb->vqueues[vusb->otg_vq_base + i].name = + otg_vqueues[i].name; + vusb->vqueues[vusb->otg_vq_base + i].callback = + otg_vqueues[i].callback; + vusb->vqueues[vusb->otg_vq_base + i].process = + otg_vqueues[i].process; + vusb->vqueues[vusb->otg_vq_base + i].stop = + otg_vqueues[i].stop; + } + rc =virtio_usb_find_vqs (vusb);if (rc) { dev_err(&vdev->dev, "%s virtio_usb_find_vqs() error(%d)\n",
@@ -199,6 +210,46 @@ static int virtio_usb_probe(struct virtio_device *vdev) goto on_error; } +if (vusb->host_role && vusb->device_role) { + rc =otg_init (vusb); +if (rc) { +dev_err (&vdev->dev,"%s otg_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 otg_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 =otg_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);
@@ -286,6 +337,8 @@ static void virtio_usb_remove(struct virtio_device *vdev)virtio_reset_device (vdev); vdev->config->del_vqs (vdev); + +otg_deinit (vusb); }static const unsigned int virtio_usb_features[] = {
drivers/usb/virtio_usb/controller.h +11 -0
@@ -18,6 +18,8 @@struct virtio_usb_hc_vp ;/* Forward declaration - full definition in device.h */ struct virtio_usb_dc ; +/* Forward declaration - full definition in otg.h */ +struct virtio_usb_otg ;#define VIRTIO_USB_VQ_COMMAND_IDX 0#define VIRTIO_USB_VQ_EVENT_IDX 1
@@ -25,6 +27,7 @@ struct virtio_usb_dc;#define VIRTIO_USB_VQ_HOST_MAX 3#define VIRTIO_USB_VQ_DEV_MAX 3 +#define VIRTIO_USB_VQ_OTG_MAX 2/** * struct virtio_usb_port - Per-virtual-port state.
@@ -54,6 +57,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. +* @otg_vq_base: index into vqueues[] where the OTG_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 +* otg_get_role() below, 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
@@ -73,10 +82,12 @@ struct virtio_usb {bool device_role;int host_vq_base;int dev_vq_base; +int otg_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_otg *otg; };/**
drivers/usb/virtio_usb/Makefile +2 -1
@@ -1,8 +1,9 @@ # SPDX-License-Identifier: GPL-2.0-or-later virtio-usb-y := controller.o \ vq_common.o \ host.o \ - device.o + device.o \ + otg.o obj-$(CONFIG_USB_VIRTIO) += virtio-usb.o
drivers/usb/virtio_usb/otg.c new file +168 -0
168 lines not on this page · raw message
drivers/usb/virtio_usb/otg.h new file +26 -0
@@ -0,0 +1,26 @@ +// 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_OTG_H +#define VIRTIO_USB_OTG_H + +#include "controller.h" + +extern int otg_init (struct virtio_usb *vusb); +extern void otg_deinit (struct virtio_usb *vusb); +extern u32 otg_get_role (struct virtio_usb *vusb,int port_id,u32 *role); + +struct virtio_usb_otg { +struct virtio_usb *vusb; +struct mutex lock; +struct completion completion; +struct virtio_usb_queue *oqs[VIRTIO_USB_VQ_OTG_MAX ]; +}; + +extern const struct virtio_usb_vq_desc otg_vqueues[VIRTIO_USB_VQ_OTG_MAX ]; + +#endif /* VIRTIO_USB_OTG_H */
[email protected]
AI reviewRe: [PATCH 4/8] virtio-usb: add OTG role query support
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 9 lines
With both
host_roleanddevice_rolenegotiated, a port's own role is ambiguous (host|device) - determining it requires more than reading the two feature bits. Introduce a minimal OTG command/event queue pair (otg_vq_base, otg_vqueues[], otg_init()/otg_deinit()) andotg_get_role(), a synchronousVIRTIO_USB_CMD_OTG_GET_ROLErequest/ 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.
Quoted 4 lines
This replaces the previous commit's DEVICE-only placeholder for the both-roles-negotiated case with the real per-port answer.
Signed-off-by Igor Skalkin <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
PATCH 5/8 virtio-usb: add USB On-The-Go role-switching support
In reply to Igor SkalkinAdd support for ports that can switch between the host and device roles at runtime (USB OTG-style role switching): negotiate VIRTIO_USB_F_SWITCH_ROLE support during probe, extend otg_get_role() to also report each port's supported roles (is_otg), and register a USB Role Switch class device so userspace can observe and control the role and be notified of role changes via VIRTIO_USB_EVT_OTG_CHANGE_ROLE.
This is a proof-of-concept for internal demo purposes; the two directions currently work quite differently and neither is fully guest-initiated:
- Device-to-host: the guest writes the new role to its own USB Role Switch sysfs entry. The driver sends a switch command to the host device; the host device performs the switch and sends back a VIRTIO_USB_EVT_OTG_CHANGE_ROLE event, which is what actually updates the guest's role.
- Host-to-device: cannot be initiated from the guest at all. The host kernel driver switches role on its own, either from an OTG interrupt or a manual sysfs role write on the host side. The host virtio device notices the USB port disappearing, checks the role via sysfs, and if it changed, sends the guest a VIRTIO_USB_EVT_OTG_CHANGE_ROLE event; the guest driver just reacts to it.
Real USB OTG separates this into two signals: bus_req, asserted by a B-device (peripheral) to request becoming host, and bus_drop, asserted by the current host to grant permission for the role swap - without bus_drop, the peripheral's request cannot succeed. VIRTIO_USB_CMD_OTG_SWITCH_ROLE only implements the bus_req side; there is no bus_drop equivalent, so the current host's permission is implicitly always granted. Fine for a first version; can be revisited if a real use case needs the host to refuse a switch.
--- drivers/usb/virtio_usb/controller.c | 94 ++++++-- drivers/usb/virtio_usb/controller.h | 21 + drivers/usb/virtio_usb/device.c | 8 drivers/usb/virtio_usb/host.c | 45 +++- drivers/usb/virtio_usb/otg.c | 401 ++++++++++++++++++++++++++++-------- drivers/usb/virtio_usb/otg.h | 16 + include/uapi/linux/virtio_usb.h | 1 7 files changed, 474 insertions(+), 112 deletions(-)
drivers/usb/virtio_usb/controller.c +74 -20
@@ -10,8 +10,8 @@#include <uapi/linux/virtio_ids.h> #include "controller.h" -#include "host.h" #include "device.h" +#include "host.h" #include "otg.h" #include "vq_common.h"
@@ -86,6 +86,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, +"OTG requires both (host and device) roles support\n" ); +return -EINVAL ; + } +if (!virtio_usb_cmd_timeout_ms) {dev_err (&vdev->dev,"msg_timeout_ms value cannot be zero\n" );return -EINVAL ;
@@ -129,6 +137,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, OTG_* only when both
@@ -219,20 +233,44 @@ 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 otg_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 +* otg_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 =otg_get_role (vusb, i, &role); + status =otg_get_role (vusb, i, &role, &supported_role);if (status !=VIRTIO_USB_S_OK ) {dev_err (&vdev->dev,"%s status(%d)\n" , __func__, status);
@@ -247,9 +285,25 @@ static int virtio_usb_probe(struct virtio_device *vdev) goto on_error; } vusb->vports[i].role = role; + vusb->vports[i].is_otg = + supported_role & + (1UL <<VIRTIO_USB_F_SWITCH_ROLE ); + +if (vusb->vports[i].is_otg && !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_otg %s\n" , + __func__, i, vusb->vports[i].role ?"DEVICE" :"HOST" , + vusb->vports[i].is_otg ?"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);
@@ -278,13 +332,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_otg || + vusb->vports[i].role ==VIRTIO_USB_ROLE_DEVICE ) { rc =virtio_usb_dc_init (vusb, i);if (rc) { dev_err(&vdev->dev,
@@ -293,17 +343,17 @@ 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 (otg_sysfs_init (vusb)) + goto on_error; + +WRITE_ONCE (vusb->started, true); +if (vusb->device_role) +schedule_work (&vusb->vq_dev_event_work); +dev_info (&vdev->dev,"%s returns %d\n" , __func__, rc);return rc; on_error:
@@ -323,6 +373,9 @@ 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); +for (i =0 ; i < vusb->nvqs; i++) vusb->vqueues[i].stop (vusb, &vusb->vqueues[i]);
@@ -344,6 +397,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[] = {
drivers/usb/virtio_usb/controller.h +20 -1
@@ -20,6 +20,7 @@ struct virtio_usb_hc_vp;struct virtio_usb_dc ;/* Forward declaration - full definition in otg.h */ struct virtio_usb_otg ; +struct virtio_usb_port_otg ;#define VIRTIO_USB_VQ_COMMAND_IDX 0#define VIRTIO_USB_VQ_EVENT_IDX 1
@@ -31,14 +32,27 @@ struct virtio_usb_otg;/** * struct virtio_usb_port - Per-virtual-port state. +* @vusb: VirtIO usb device this port belongs to. +* @is_otg: True if this port supports dynamic role switching. * @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. +* @otg: Per-port OTG role-switching state - non-NULL when is_otg. */ struct virtio_usb_port { +struct virtio_usb *vusb; +bool is_otg;unsigned int role; +/*! Protects vhc against concurrent OTG-triggered init/deinit while +* the host event-processing worker is reading it. Only needs to +* guard the pointer itself: virtio_usb_hc_vp_init()/_deinit()'s +* sleeping work (devm_kzalloc(), usb_add_hcd(), usb_remove_hcd()) +* happens outside this lock. +*/ +spinlock_t vhc_lock;struct virtio_usb_hc_vp *vhc;struct virtio_usb_dc *vudc; +struct virtio_usb_port_otg *otg; };/**
@@ -63,6 +77,9 @@ struct virtio_usb_port {* otg_get_role() below, 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
@@ -76,13 +93,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 otg_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;
drivers/usb/virtio_usb/device.c +8 -0
@@ -1056,6 +1056,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)
@@ -1080,16 +1082,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 ;
@@ -1308,6 +1313,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); }
drivers/usb/virtio_usb/host.c +39 -6
101 lines not on this page · raw message
include/uapi/linux/virtio_usb.h +1 -0
@@ -318,6 +318,7 @@ enum {struct virtio_usb_otg_cmd_role {struct virtio_usb_cmd_status status;__le32 role;/* VIRTIO_USB_ROLE_XXX */ +__le32 supported_role;/* VIRTIO_USB_F_[HOST|DEVICE|SWITCH_ROLE] */ };/*****************************************************************************
drivers/usb/virtio_usb/otg.c +318 -83
467 lines not on this page · raw message
drivers/usb/virtio_usb/otg.h +14 -2
@@ -8,17 +8,29 @@#ifndef VIRTIO_USB_OTG_H #define VIRTIO_USB_OTG_H +#include <linux/usb/role.h> #include "controller.h" extern int otg_init (struct virtio_usb *vusb); +extern int otg_sysfs_init (struct virtio_usb *vusb);extern void otg_deinit (struct virtio_usb *vusb); -extern u32 otg_get_role (struct virtio_usb *vusb,int port_id,u32 *role); +extern u32 otg_get_role (struct virtio_usb *vusb,int port_id,u32 *role, +u32 *supported_role); + +struct virtio_usb_port_otg { +struct virtio_usb *vusb; +struct mutex lock; +struct usb_role_switch *sw; +char *sysfs_name; +struct work_struct set_role_work; +int port_id; +};struct virtio_usb_otg {struct virtio_usb *vusb;struct mutex lock; -struct completion completion;struct virtio_usb_queue *oqs[VIRTIO_USB_VQ_OTG_MAX ]; +struct work_struct event_process_work; };extern const struct virtio_usb_vq_desc otg_vqueues[VIRTIO_USB_VQ_OTG_MAX ];
[email protected]
AI reviewRe: [PATCH 5/8] virtio-usb: add USB On-The-Go role-switching support
Thank you for your contribution! Sashiko AI review found 7 potential issue(s) to consider: - [High] usb: virtio_usb: unbounded memory leak of devm-managed structures on OTG switch - [High] usb…
Thank you for your contribution! Sashiko AI review found 7 potential issue(s) to consider:
- [High] usb: virtio_usb: unbounded memory leak of devm-managed structures on OTG switch
- [High] usb: virtio_usb: race in otg_vports_deinit causes UAF of otg port structures
- [High] usb: virtio_usb: missing bounds check on port_id allows OOB access from untrusted backend
- [High] usb: virtio_usb: race between event processing and deinit causes UAF on usb_hcd
- [High] usb: virtio_usb: premature publication of vhc pointer exposes uninitialized HCDs
- [Medium] usb: virtio_usb: sysfs name collision prevents probing multiple OTG controllers
- [Medium] usb: virtio_usb: missing NULL check for kasprintf leads to fallback name collision --
commit 43ad38d6c9bfbe93bb71ee47b756c85a12c14c6b
Author: Igor Skalkin <[email protected]>
virtio-usb: add USB On-The-Go role-switching support
This commit adds runtime role-switching (OTG) support to virtio-usb. It negotiates VIRTIO_USB_F_SWITCH_ROLE, registers a USB Role Switch class device, and processes VIRTIO_USB_EVT_OTG_CHANGE_ROLE events.
Quoted 5 lines
drivers/usb/virtio_usb/host.c +0
-0
drivers/usb/virtio_usb/host.c int virtio_usb_hc_vp_init(struct virtio_usb *vusb, unsigned int vp_idx) · line 1021
Quoted 9 lines
drivers/usb/virtio_usb/host.c +2
-0@@ -1013,12 +1013,16 @@ int virtio_usb_hc_vp_init(struct virtio_usb *vusb, unsigned int vp_idx) vhcd_vp->hcqs[i] = &vusb->vqueues[vusb->host_vq_base + i];/* Install into the port before add_hcd so vhcd_vp->vusb is set */ +spin_lock (&vusb->vports[vp_idx].vhc_lock); vusb->vports[vp_idx].vhc = vhcd_vp; +spin_unlock (&vusb->vports[vp_idx].vhc_lock);/* Add HCDs first so hs/ss are valid before any PORT_CONNECTED event */ rc =virtio_usb_add_hcd (vusb, vhcd_vp);
[Severity: High]
Does publishing this vhc pointer here expose uninitialized HCDs?
If a concurrent VIRTIO_USB_EVT_HOST_PORT_CONNECTED event is processed by virtio_usb_hc_evt_process_one() after vhc is set but before virtio_usb_add_hcd() finishes, the event handler will see the published pointer and attempt to access uninitialized HCDs.
Could this pointer be published only after the HCDs are fully initialized?
Quoted 6 lines
drivers/usb/virtio_usb/host.c +2
-0if (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; }
[ ... ]
Quoted 14 lines
drivers/usb/virtio_usb/host.c +5
-1@@ -1032,7 +1036,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 ;
drivers/usb/virtio_usb/host.c int virtio_usb_hc_vp_deinit(struct virtio_usb *vusb, unsigned int vp_idx) · line 1060
Quoted 8 lines
drivers/usb/virtio_usb/host.c +2
-0@@ -1045,7 +1053,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 ; }
[Severity: High]
Does this deinit path leak devm-allocated structures during OTG role switches?
The dynamic OTG role switching from device to host calls virtio_usb_hc_vp_init(), which uses devm_kzalloc() and devm_kasprintf() to allocate vhcd_vp and its name string.
When switching back to device role, this deinit function is called but does not free these devres-managed objects.
Since the devm allocations are tied to the parent virtio device's lifetime, repeatedly toggling the role will indefinitely consume memory until the whole driver is unbound.
Should these structures be explicitly freed or managed differently?
[ ... ]
Quoted 8 lines
drivers/usb/virtio_usb/host.c +4
-0@@ -1085,7 +1095,18 @@ static void virtio_usb_hc_evt_process_one(struct virtio_usb_event *uevent)return ; } +/* vhc can be concurrently init/deinit'd by an OTG role switch +* (virtio_usb_otg_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
drivers/usb/virtio_usb/host.c static void virtio_usb_hc_evt_process_one(struct virtio_usb_event *uevent) · line 1111
Quoted 10 lines
drivers/usb/virtio_usb/host.c +7
-0+* 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; +spin_unlock (&vusb->vports[vp_idx].vhc_lock); +if (!vhcd_vp) { dev_err_ratelimited(
[Severity: High]
Does dropping vhc_lock here open a race window that leads to a use-after-free on the usb_hcd pointer?
While the comment notes that vhcd_vp itself won't be freed because it is devm-managed, virtio_usb_hc_vp_deinit() can be executed concurrently and will call usb_remove_hcd() and usb_put_hcd() to dynamically free the HCDs.
Later in virtio_usb_hc_evt_process_one(), the code calls:
if (hcd)
usb_hcd_poll_rh_status(hcd);If deinit frees the HCD while this event processing thread is running, passing it to usb_hcd_poll_rh_status() will dereference freed memory.
Is an extended lock or refcount needed to protect the HCD?
Quoted 12 lines
drivers/usb/virtio_usb/otg.c +1
-0@@ -7,11 +7,238 @@#include <linux/mutex.h> #include "controller.h" +#include "host.h" #include "otg.h" #include "vq_common.h"
[ ... ]
drivers/usb/virtio_usb/otg.c line 52
Quoted 6 lines
drivers/usb/virtio_usb/otg.c +6
-0+static void virtio_usb_otg_event_process (struct virtio_usb_event *event) +{ +struct virtio_usb *vusb = event->vusb; +struct virtio_usb_otg_event *evt =virtio_usb_event_buf (event); +int port_id =le32_to_cpu (evt->port); +struct virtio_usb_port *vport = &vusb->vports[port_id];
[Severity: High]
Does this missing bounds check on port_id allow out-of-bounds array accesses?
The port_id is extracted from the untrusted virtio event buffer and immediately used to index the vusb->vports[] array.
If a buggy or malicious virtio backend provides a port_id greater than or equal to vusb->nports, this will lead to out-of-bounds pointer reads and writes.
[ ... ]
Quoted 7 lines
drivers/usb/virtio_usb/otg.c +7
-0+static void otg_vports_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];
drivers/usb/virtio_usb/otg.c line 192
Quoted 10 lines
drivers/usb/virtio_usb/otg.c +10
-0+/* is_otg is set before otg_sysfs_init() runs (which is +* where vport->otg actually gets allocated) - a probe +* failure in between the two would otherwise leave +* is_otg true but otg still NULL here. +*/ +if (!vport->is_otg || !vport->otg) +continue ; + +cancel_work_sync (&vport->otg->set_role_work); +usb_role_switch_unregister (vport->otg->sw);
[Severity: High]
Does cancelling the work before unregistering the sysfs interface cause a use-after-free race?
If a concurrent sysfs write to the switch's role file occurs after cancel_work_sync() returns but before usb_role_switch_unregister() finishes, vusb_set_role_cb() will schedule set_role_work anew.
Once the teardown completes and frees vport->otg, the re-queued work could execute and dereference the freed memory.
Should the sysfs interface be unregistered first to prevent new requests from being scheduled?
[ ... ]
Quoted 4 lines
drivers/usb/virtio_usb/otg.c +4
-0+static int otg_vport_init (struct virtio_usb *vusb,int port_id) +{ +struct device *dev = &vusb->vdev->dev; +struct virtio_usb_port *vport = &vusb->vports[port_id];
drivers/usb/virtio_usb/otg.c line 212
Quoted 10 lines
drivers/usb/virtio_usb/otg.c +10
-0+struct virtio_usb_port_otg *vport_otg; +struct usb_role_switch_desc desc = {0 }; + + vport_otg =devm_kzalloc (dev,sizeof (*vport_otg),GFP_KERNEL ); +if (!vport_otg) +return -ENOMEM ; + + vport_otg->vusb = vusb; + vport_otg->port_id = port_id; + vport_otg->sysfs_name =kasprintf (GFP_KERNEL ,"port%u" , port_id);
[Severity: Medium]
Will this hardcoded naming scheme cause a sysfs name collision if multiple virtio-usb controllers with OTG support are probed?
The static name format "port%u" is registered directly to the /sys/class/usb_role/ global namespace.
The second device probed will fail with -EEXIST.
Could the name be scoped by the parent device name (e.g., %s-port%u) to ensure uniqueness?
[Severity: Medium]
Does the lack of a NULL check on kasprintf() here lead to fallback name collisions?
If kasprintf() fails under memory pressure, it returns NULL which is then assigned to desc.name.
The USB role switch core will detect the NULL name and fallback to using the parent device's name.
If a second port on the same controller also fails allocation, it will also fallback to the parent name, causing an -EEXIST conflict.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
PATCH 6/8 virtio-usb: rework endpoint lifecycle to an async split-phase state machine
In reply to Igor SkalkinThe 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.
We previously worked around this with a small out-of-tree patch to the gadget core itself: a gadget.nonatomic flag that, when set, swapped the UDC core's spinlocks for mutexes so a driver could sleep in these callbacks. That patch was never going to pass upstream review, so it had to go - which meant this driver needed to actually honor the atomic contract instead of relying on a modified core.
This commit is that fix: an explicit endpoint state machine (EP_DISABLED, EP_ENABLING, EP_ENABLED, EP_HALTED) plus 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 move to this split-phase pattern; ep_queue()/ep_dequeue() are reworked on top of the same state machine. gadget.nonatomic itself is removed, since nothing needs it anymore.
Also fixes a handful of bugs found while doing this: preserve -ECONNRESET/-ESHUTDOWN completion statuses instead of always overwriting them, support early-completed requests without a double giveback(), serialize SETUP handling against in-flight EP0 completions and still-EP_ENABLING endpoints to avoid overlapping control transfers exposed by dummy_hcd's tighter timing, and fix EP0's descriptor initialization and a spinlock-unbalance bug in ep_enable().
--- drivers/usb/virtio_usb/device.c | 774 +++++++++++++++++++++++++++++++--------- drivers/usb/virtio_usb/device.h | 24 + 2 files changed, 639 insertions(+), 159 deletions(-)
drivers/usb/virtio_usb/device.c +615 -159
@@ -11,6 +11,7 @@#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
@@ -23,6 +24,8 @@ 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; };/**
@@ -72,6 +75,34 @@ static struct virtio_usb_data *usb_req_to_virtio_data(struct usb_request *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.
@@ -89,6 +120,8 @@ static void virtio_usb_dc_complete_req(struct virtio_usb_data *vreq)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);
@@ -98,10 +131,15 @@ static void virtio_usb_dc_complete_req(struct virtio_usb_data *vreq)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)
@@ -109,9 +147,17 @@ static void virtio_usb_dc_complete_req(struct virtio_usb_data *vreq) }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); -usb_gadget_giveback_request (&vep->ep, req); }/**
@@ -128,22 +174,24 @@ void virtio_usb_dc_data_work(struct work_struct *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_irq (&dataq->lock); +spin_lock_irqsave (&dataq->lock, flags);do {virtqueue_disable_cb (dataq->vqueue);while ((vreq =virtqueue_get_buf (dataq->vqueue, &length))) { -spin_unlock_irq (&dataq->lock); +spin_unlock_irqrestore (&dataq->lock, flags);virtio_usb_dc_complete_req (vreq); -spin_lock_irq (&dataq->lock); +spin_lock_irqsave (&dataq->lock, flags); }if (unlikely (virtqueue_is_broken (dataq->vqueue)))break ; }while (!virtqueue_enable_cb (dataq->vqueue)); -spin_unlock_irq (&dataq->lock); +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.
@@ -174,6 +222,8 @@ static struct virtio_usb_data *virtio_usb_dc_data_alloc(struct usb_ep *ep, 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 ];
@@ -242,6 +292,264 @@ virtio_usb_dc_cmd_alloc(struct virtio_usb_dc *vudc, unsigned int command,/* Endpoint callbacks */ +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 ; +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; + req->actual =0 ; + req->status = -EINPROGRESS ; +list_add_tail (&vreq->list, &vep->req_queue); +spin_unlock_irqrestore (&vudc->lock, flags); + + 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); +return rc; + } + +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; +struct scatterlist sg; +struct scatterlist *psg_data = &sg; +struct virtio_usb_dev_cmd_hdr *hdr; +struct virtio_usb_cmd *cmd; +unsigned long flags; +u16 endpoint; +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; + } + +sg_init_one (psg_data, desc,sizeof (*desc)); + 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.
@@ -256,44 +564,30 @@ static int virtio_ep_enable(struct usb_ep *ep, {struct virtio_usb_ep *vep =usb_ep_to_virtio_ep (ep);struct virtio_usb_dc *vudc = vep->vudc; -struct scatterlist sg; -struct scatterlist *psg_data = &sg; -struct virtio_usb_dev_cmd_hdr *hdr; -struct virtio_usb_cmd *cmd;unsigned long flags; -u16 endpoint; -int rc; - -if (!vudc->driver) -return -ESHUTDOWN ;spin_lock_irqsave (&vudc->lock, flags); -if (!ep || !desc || ep->caps.type_control || +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 ; + } + ep->desc = desc; ep->maxpacket =usb_endpoint_maxp (desc); - 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_ENABLE , -GFP_ATOMIC ); -if (!cmd) -return -ENOMEM ; + vep->state =EP_ENABLING ; -sg_init_one (psg_data, desc,sizeof (*desc)); - hdr =virtio_usb_cmd_request (cmd); - hdr->endpoint =cpu_to_le16 (endpoint); +queue_work (vudc->ep_cmd_wq, &vep->enable_work); - rc =virtio_usb_cmd_send_sync (vudc->vusb, psg_data,NULL , cmd); +spin_unlock_irqrestore (&vudc->lock, flags); -return rc; +return 0 ; }/**
@@ -311,42 +605,82 @@ static int virtio_ep_disable(struct usb_ep *ep)struct virtio_usb_data *vreq =NULL , *vreq_tmp;struct virtio_usb_dc *vudc = vep->vudc;struct virtio_usb_dc_priv *priv =NULL ; -struct virtio_usb_dev_cmd_hdr *hdr; -struct virtio_usb_cmd *cmd; +LIST_HEAD (giveback_inflight); +LIST_HEAD (giveback_pended);unsigned long flags; -u16 endpoint; -int rc; -if (!ep || ep->caps.type_control) +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); -/** -* When endpoint is disabled, completion handler for all pending -* requests will be called. Make the request status to -ESHUTDOWN -* to prevent requests completes even before the endpoint disable -* is send to the controller. -*/ priv->req.status = -ESHUTDOWN ; + priv->completed_early = true; +list_del_init (&vreq->list); +list_add_tail (&vreq->list, &giveback_inflight); } - 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_DISABLE , -GFP_ATOMIC ); -if (!cmd) -return -ENOMEM ; +/* 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); - hdr =virtio_usb_cmd_request (cmd); - hdr->endpoint =cpu_to_le16 (endpoint); +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() */ + } - rc =virtio_usb_cmd_send_sync (vudc->vusb,NULL ,NULL , cmd); +/* 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); -return rc; +list_del_init (&vreq->list); +usb_gadget_giveback_request (&vep->ep, &p->req); + } + +queue_work (vudc->ep_cmd_wq, &vep->disable_work); + +return 0 ; }/**
@@ -395,75 +729,52 @@ static void virtio_ep_free_request(struct usb_ep *ep, struct usb_request *req)static int virtio_ep_queue (struct usb_ep *ep,struct usb_request *req,gfp_t mem_flags) { -struct scatterlist *out_sgs =NULL , *in_sgs =NULL , *psg_data;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; -struct virtio_usb_response *response; -struct virtio_usb_request *request; -u16 transfer_flags =0 ; -struct scatterlist sg;unsigned long flags; -u16 endpoint; -int rc; - -virtio_usb_data_ref (vreq); +int rc =0 ;spin_lock_irqsave (&vudc->lock, flags); - req->actual =0 ; - req->status = -EINPROGRESS ; - -list_add_tail (&vreq->list, &vep->req_queue); - 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); - - 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 ); +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; -if (req->short_not_ok) - transfer_flags |=VIRTIO_USB_FLAG_SHORT_NOT_OK ; -else if (req->zero) - transfer_flags |=VIRTIO_USB_FLAG_ZERO_PACKET ; +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 ; - request->transfer_flags =cpu_to_le16 (transfer_flags); - request->endpoint =cpu_to_le16 (endpoint); - request->port =cpu_to_le16 (vudc->port); +case EP_HALTED : +spin_unlock_irqrestore (&vudc->lock, flags); + req->status = vep->last_err ? vep->last_err : -EPIPE ; +usb_gadget_giveback_request (&vep->ep, req); +return req->status; -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->sg) { - psg_data = &sg; -sg_init_one (psg_data,sg_virt (req->sg), req->length); - }else { - psg_data =NULL ; +case EP_DISABLED : +default : +spin_unlock_irqrestore (&vudc->lock, flags); +return -ESHUTDOWN ; } - -if (usb_ep_dir_in (ep)) - out_sgs = psg_data; -else - in_sgs = psg_data; - - rc =virtio_usb_data_send (vudc->vusb, vreq, out_sgs, in_sgs); -if (rc) - goto on_error_vq; - -return rc; - -on_error_vq: -spin_lock_irqsave (&vudc->lock, flags); -list_del_init (&vreq->list); -spin_unlock_irqrestore (&vudc->lock, flags); - -virtio_usb_data_unref (vreq); - -return rc; }/**
@@ -477,20 +788,32 @@ on_error_vq: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_dev_cmd_cancel *cancel;struct virtio_usb_dc *vudc = vep->vudc;struct virtio_usb_dc_priv *priv;struct virtio_usb_data *vreq; -struct virtio_usb_cmd *cmd;unsigned long flags;int rc = -EINVAL ; -u16 endpoint;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) {
@@ -502,28 +825,14 @@ static int virtio_ep_dequeue(struct usb_ep *ep, struct usb_request *req)break ; } } - 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); -if (rc) +if (rc)// request not found in req_queue return rc; - vreq = priv->vreq; +schedule_work (&priv->cancel_work); - cmd =virtio_usb_dc_cmd_alloc (vudc,VIRTIO_USB_CMD_DEV_CANCEL , -GFP_KERNEL ); -if (!cmd) -return -ENOMEM ; - - 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 ((uintptr_t )vreq); - - rc =virtio_usb_cmd_send_sync (vudc->vusb,NULL ,NULL , cmd); - -return rc; +return 0 ; }/**
@@ -633,6 +942,109 @@ static const struct usb_ep_ops virtio_usb_ep_ops = {/*-------------------------------------------------------------------------*/ /* 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; + +spin_lock_irqsave (&vudc->lock, flags); + +list_for_each_entry (iter, &vep->req_queue, list) { +if (iter == vreq) { + found = true; +break ; + } + } +if (!found) { +spin_unlock_irqrestore (&vudc->lock, flags); +return ; + } + endpoint = vep->ep_id | + (usb_ep_dir_in (&vep->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_CANCEL , +GFP_KERNEL ); +if (!cmd) +return ; + + 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 ((uintptr_t )vreq); + + (void )virtio_usb_cmd_send_sync (vudc->vusb,NULL ,NULL , cmd); +} + +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
@@ -645,18 +1057,11 @@ static int virtio_usb_dc_set_selfpowered(struct usb_gadget *gadget, {struct virtio_usb_dc *vudc = container_of(gadget, struct virtio_usb_dc, gadget); -unsigned int code =VIRTIO_USB_CMD_DEV_SET_SELF_POWERED ; -struct virtio_usb_dev_cmd_set_value *req; -struct virtio_usb_cmd *cmd; - 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_selfpowered); +atomic_set (&vudc->pending_self_pwr, is_selfpowered ?1 :0 ); +queue_work (vudc->dc_cmd_wq, &vudc->dc_cmd_work); -return virtio_usb_cmd_send_sync (vudc->vusb,NULL ,NULL , cmd); +return 0 ; }/**
@@ -774,29 +1179,18 @@ static int virtio_usb_dc_stop(struct usb_gadget *gadget)/** * 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. +* @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) +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); -unsigned int code =VIRTIO_USB_CMD_DEV_VBUS_DRAW ; -struct virtio_usb_dev_cmd_set_value *req; -struct virtio_usb_cmd *cmd; -int rc; - - 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 (mA); - - rc =virtio_usb_cmd_send_sync (vudc->vusb,NULL ,NULL , cmd); -return rc; +atomic_set (&vudc->pending_vbus_ma, ma); +queue_work (vudc->dc_cmd_wq, &vudc->dc_cmd_work); +return 0 ; }/**
@@ -930,6 +1324,11 @@ static int virtio_usb_dc_get_endpoint_info(struct virtio_usb_dc *vudc) 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);
@@ -1038,7 +1437,6 @@ static void virtio_usb_dc_event_process(struct virtio_usb_event *event) } vudc->gadget.ops = &virtio_gadget_ops; vudc->gadget.max_speed =USB_SPEED_HIGH ; - vudc->gadget.nonatomic =1 ;//vudc->gadget.dev.init_name = gadget_name; vudc->gadget.dev.parent = &vudc->pdev->dev;
@@ -1071,6 +1469,14 @@ static void virtio_usb_dc_event_process(struct virtio_usb_event *event) 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 ));
@@ -1102,6 +1508,9 @@ static void virtio_usb_dc_event_process(struct virtio_usb_event *event)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 ;
@@ -1113,8 +1522,14 @@ static void virtio_usb_dc_event_process(struct virtio_usb_event *event) vudc->gadget.name =NULL ; } -kfree (vudc->veps); - vudc->veps =NULL ; +if (vudc->veps) { +unsigned int i; + +for (i =0 ; i < vudc->neps; i++) +cancel_work_sync (&vudc->veps[i].enable_work); +kfree (vudc->veps); + vudc->veps =NULL ; + }if (vudc->pdev) {platform_device_unregister (vudc->pdev);
@@ -1141,7 +1556,6 @@ void virtio_usb_dc_event_work(struct work_struct *work) 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); }
@@ -1186,13 +1600,39 @@ int virtio_usb_dc_init(struct virtio_usb *vusb, int port_id)if (!vudc)return -ENOMEM ; - vusb->vports[port_id].vudc = vudc; 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 ;
@@ -1228,6 +1668,22 @@ int virtio_usb_dc_deinit(struct virtio_usb *vusb)if (registered)usb_del_gadget_udc (&vudc->gadget); +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 ;
drivers/usb/virtio_usb/device.h +24 -0
@@ -11,6 +11,7 @@#include <linux/usb.h> #include <linux/list.h> #include <linux/platform_device.h> +#include <linux/wait.h> #include <uapi/linux/usb/ch11.h> #include <uapi/linux/usb/ch9.h> #include <linux/usb/gadget.h>
@@ -37,12 +38,19 @@ .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 * @vusb: VirtIO usb device * @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 */
@@ -51,6 +59,11 @@ struct virtio_usb_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 ]; };
@@ -66,6 +79,7 @@ struct virtio_usb_ep {* @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 */ struct virtio_usb_dc {struct platform_device *pdev;
@@ -79,6 +93,16 @@ struct virtio_usb_dc { unsigned registered : 1; unsigned pullup : 1;spinlock_t lock; +wait_queue_head_t ep0_idle; +/* Workqueue for EP enable/disable/cancel commands */ +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 ];
[email protected]
AI reviewRe: [PATCH 6/8] virtio-usb: rework endpoint lifecycle to an async split-phase state machine
Thank you for your contribution! Sashiko AI review found 10 potential issue(s) to consider: - [Critical] usb: virtio: DMA race and use-after-free due to fake early giveback - [Critical] usb: virtio…
Thank you for your contribution! Sashiko AI review found 10 potential issue(s) to consider:
- [Critical] usb: virtio: DMA race and use-after-free due to fake early giveback
- [Critical] usb: virtio: use-after-free of vudc->veps during device unbind
- [Critical] usb: virtio: use-after-free in async cancel work due to missing refcount
- [Critical] usb: virtio: list corruption between do_real_queue() and ep_disable
- [High] usb: virtio: sleep in atomic context in virtio_ep_disable()
- [High] usb: virtio: SETUP serialization fails due to un-checked pend_queue
- [High] usb: virtio: deadlock and double-free on queueing to halted endpoint
- [High] usb: virtio: vep_disable_work() disables wrong endpoint on host
- [High] usb: virtio: TOCTOU race queues requests after endpoint disable
- [High] usb: virtio: EP0 permanently hangs if enable_work is cancelled
--
commit e8d36f763a91b5d6a7067cc2771333012c0636ae
Author: Igor Skalkin <[email protected]>
virtio-usb: rework endpoint lifecycle to an async split-phase state machine
This commit changes the virtio-usb gadget driver's endpoint lifecycle to an asynchronous state machine to avoid sleeping in atomic gadget callbacks. Endpoint enable, disable, and queue operations now rely on workqueues and split-phase request handling.
Quoted 4 lines
drivers/usb/virtio_usb/device.c +0
-0
[ ... ]
drivers/usb/virtio_usb/device.c static struct virtio_usb_data *usb_req_to_virtio_data(struct usb_request *req) · line 89
Quoted 12 lines
drivers/usb/virtio_usb/device.c +12
-0+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; +}
[Severity: High]
Does this logic ignore the pend_queue entirely?
If another endpoint is EP_ENABLING, EP0 requests are deferred into pend_queue. Could virtio_usb_dc_wait_ep0_idle() mistakenly see an empty req_queue and allow a new SETUP packet to overwrite the previous control transfer state while it is still legitimately pending?
[ ... ]
Quoted 2 lines
drivers/usb/virtio_usb/device.c +2
-0+static int do_real_queue (struct virtio_usb_ep *vep,struct usb_request *req) +{
[ ... ]
drivers/usb/virtio_usb/device.c virtio_usb_dc_cmd_alloc(struct virtio_usb_dc *vudc, unsigned int command, · line 374
Quoted 5 lines
drivers/usb/virtio_usb/device.c +5
-0+ 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);
[Severity: Critical]
Can this error path corrupt the list if it races with virtio_ep_disable()?
If virtio_usb_data_send() fails concurrently, virtio_ep_disable() might have already moved vreq into a local stack list (giveback_inflight) and dropped the lock to iterate over it locklessly. Calling list_del_init() here on vreq->list would mutate the elements of that local list, destroying the pointers.
[ ... ]
drivers/usb/virtio_usb/device.c virtio_usb_dc_cmd_alloc(struct virtio_usb_dc *vudc, unsigned int command, · line 536
Quoted 11 lines
drivers/usb/virtio_usb/device.c +11
-0+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 ;
[Severity: Critical]
Is it possible for vep to be a dangling pointer here?
During device unbind (VIRTIO_USB_EVT_DEV_UNBIND), the driver calls kfree(vudc->veps) after cancelling only enable_work. If a disable_work was already queued, the workqueue could execute this function after vudc->veps has been freed, resulting in a use-after-free.
drivers/usb/virtio_usb/device.c virtio_usb_dc_cmd_alloc(struct virtio_usb_dc *vudc, unsigned int command, · line 325
Quoted 3 lines
drivers/usb/virtio_usb/device.c +3
-0+ endpoint = vep->ep_id | + (usb_ep_dir_in (&vep->ep) ?VIRTIO_USB_EP_DIR_IN : +VIRTIO_USB_EP_DIR_OUT );
[Severity: High]
Can usb_ep_dir_in() safely calculate the direction here?
Gadget drivers generally clear ep->desc to NULL immediately after returning from usb_ep_disable(). Because this block runs asynchronously, ep->desc will likely be NULL, causing usb_ep_dir_in() to fall back to the OUT direction (0). If the target was an IN endpoint, won't this send the disable command for the wrong endpoint on the host?
[ ... ]
Quoted 2 lines
static int
virtio_ep_disable(struct usb_ep *ep)
{
[ ... ]
drivers/usb/virtio_usb/device.c static int virtio_ep_disable(struct usb_ep *ep) · line 628
Quoted 12 lines
drivers/usb/virtio_usb/device.c +12
-0+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); + }
[Severity: High]
Is it safe to call cancel_work_sync() here?
The USB gadget API specifies that usb_ep_ops->disable is atomic and can be called from interrupt context. Calling cancel_work_sync(), which can sleep, violates this API contract and can trigger a scheduling while atomic bug.
[Severity: High]
Additionally, if enable_work is forcefully cancelled here, how do the EP0 requests deferred into pend_queue get flushed?
Does this leave EP0 permanently hung since virtio_usb_dc_flush_ep0_pend() is never called to release the stranded requests?
[ ... ]
Quoted 12 lines
drivers/usb/virtio_usb/device.c +9
-0+/* +* 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); }
[ ... ]
drivers/usb/virtio_usb/device.c static int virtio_ep_disable(struct usb_ep *ep) · line 679
Quoted 8 lines
drivers/usb/virtio_usb/device.c +6
-1+/* 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); - rc =virtio_usb_cmd_send_sync (vudc->vusb,NULL ,NULL , cmd); +list_del_init (&vreq->list); +usb_gadget_giveback_request (&vep->ep, &p->req); + }
[Severity: Critical]
Could this early giveback result in immediate hardware memory corruption?
By handing the requests back to the gadget driver via usb_gadget_giveback_request() before the hardware backend processes the async disable command, the gadget driver may reuse or free the DMA buffers while the virtqueue is still actively reading or writing to them.
[ ... ]
Quoted 3 lines
static int virtio_ep_queue(struct
usb_ep*ep, structusb_request*req,
gfp_tmem_flags)
{
[ ... ]
Quoted 2 lines
drivers/usb/virtio_usb/device.c +2
-0+case EP_ENABLED : +if (!vep->ep_id &&virtio_usb_dc_ep_enabling_locked (vudc)) {
[ ... ]
drivers/usb/virtio_usb/device.c static void virtio_ep_free_request(struct usb_ep *ep, struct usb_request *req) · line 755
Quoted 7 lines
drivers/usb/virtio_usb/device.c +7
-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;
[Severity: High]
Does this lock drop introduce a Time-of-Check to Time-of-Use race?
Because the lock is dropped before do_real_queue() re-acquires it to add the request, a concurrent virtio_ep_disable() could mark the endpoint disabled and flush the queues. The queued request would then be blindly sent to the hardware anyway.
[ ... ]
drivers/usb/virtio_usb/device.c static void virtio_ep_free_request(struct usb_ep *ep, struct usb_request *req) · line 771
Quoted 5 lines
drivers/usb/virtio_usb/device.c +5
-0+case EP_HALTED : +spin_unlock_irqrestore (&vudc->lock, flags); + req->status = vep->last_err ? vep->last_err : -EPIPE ; +usb_gadget_giveback_request (&vep->ep, req); +return req->status;
[Severity: High]
Does returning an error code while also performing a giveback violate the gadget API?
The USB gadget API expects that if queue() returns an error, the controller did not take ownership and must not call the completion callback. The synchronous giveback could cause a deadlock if it attempts to re-acquire the caller's locks, and returning an error will likely cause the caller to free the request, resulting in a double-free.
[ ... ]
Quoted 2 lines
static int
virtio_ep_dequeue(struct usb_ep *ep, struct usb_request *req){
[ ... ]
drivers/usb/virtio_usb/device.c static int virtio_ep_dequeue(struct usb_ep *ep, struct usb_request *req) · line 515
Quoted 9 lines
drivers/usb/virtio_usb/device.c +2
-4-if (rc) +if (rc)// request not found in req_queue return rc; - vreq = priv->vreq; +schedule_work (&priv->cancel_work); - cmd =virtio_usb_dc_cmd_alloc (vudc,VIRTIO_USB_CMD_DEV_CANCEL , -GFP_KERNEL );
[Severity: Critical]
Does scheduling priv->cancel_work without taking a reference to vreq risk a use-after-free?
If the hardware naturally completes the request before this async cancel work executes, the completion handler will drop the final reference and the gadget driver will free the request. When virtio_usb_dc_cancel_work() later runs, it would access the freed priv memory.
[ ... ]
Quoted 2 lines
static void
virtio_usb_dc_event_process(struct virtio_usb_event *event){
[ ... ]
drivers/usb/virtio_usb/device.c static void virtio_usb_dc_event_process(struct virtio_usb_event *event) · line 1532
Quoted 8 lines
drivers/usb/virtio_usb/device.c +8
-0+if (vudc->veps) { +unsigned int i; + +for (i =0 ; i < vudc->neps; i++) +cancel_work_sync (&vudc->veps[i].enable_work); +kfree (vudc->veps); + vudc->veps =NULL ; + }
(For context with the dangling pointer concern in vep_disable_work) This is where vudc->veps is freed during VIRTIO_USB_EVT_DEV_UNBIND without cancelling disable_work or flushing ep_cmd_wq.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
PATCH 7/8 virtio-usb: add SuperSpeed device-role support
In reply to Igor SkalkinStop hardcoding the gadget's max_speed to USB_SPEED_HIGH on DEV_BIND; parse max_speed from the bind event sent by the host backend and clamp it to a supported set (LOW/FULL/HIGH/SUPER/SUPER_PLUS), defaulting to HIGH on invalid data. Update set_speed() to clamp the negotiated speed against gadget.max_speed and configure the EP0 max packet size for SuperSpeed and SuperSpeed Plus (512 bytes both, per USB 3.1), while preserving existing HS/FS behavior.
Also send the SuperSpeed endpoint companion descriptor together with the endpoint descriptor on EP_ENABLE, as an additional scatter-gather payload, so the host backend can configure burst/mult parameters instead of relying on the endpoint descriptor alone.
This aligns the guest-side speed configuration with the host's capability and enables SuperSpeed path bring-up.
--- drivers/usb/virtio_usb/device.c | 54 +++++++++++++++++++++++++++++++++++----- include/uapi/linux/virtio_usb.h | 8 +++++ 2 files changed, 56 insertions(+), 6 deletions(-)
drivers/usb/virtio_usb/device.c +48 -6
@@ -439,12 +439,14 @@ static void vep_enable_work(struct work_struct *work) 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; -struct scatterlist sg; -struct scatterlist *psg_data = &sg; +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)
@@ -461,7 +463,13 @@ static void vep_enable_work(struct work_struct *work) goto done; } -sg_init_one (psg_data, desc,sizeof (*desc)); +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);
@@ -564,6 +572,7 @@ static int virtio_ep_enable(struct usb_ep *ep, {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);
@@ -579,6 +588,16 @@ static int virtio_ep_enable(struct usb_ep *ep,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 ;
@@ -1119,9 +1138,13 @@ static void virtio_usb_dc_set_speed(struct usb_gadget *gadget,struct virtio_usb_dc *vudc = container_of(gadget, struct virtio_usb_dc, gadget); - vudc->gadget.speed =min_t (u8,USB_SPEED_HIGH , speed); + vudc->gadget.speed =min_t (u8, vudc->gadget.max_speed, speed); -switch (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 ;
@@ -1375,6 +1398,8 @@ static int virtio_usb_dc_parent_create(struct virtio_usb_dc *vudc)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;
@@ -1395,6 +1420,8 @@ 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; +if (vudc->registered) { dev_err(&vusb->vdev->dev, "port %d: BIND while still registered, ignoring\n",
@@ -1405,6 +1432,8 @@ static void virtio_usb_dc_event_process(struct virtio_usb_event *event)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,
@@ -1436,7 +1465,20 @@ static void virtio_usb_dc_event_process(struct virtio_usb_event *event)break ; } vudc->gadget.ops = &virtio_gadget_ops; - vudc->gadget.max_speed =USB_SPEED_HIGH ; +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;
include/uapi/linux/virtio_usb.h +8 -0
@@ -222,6 +222,14 @@ struct virtio_usb_dev_event {__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 */
[email protected]
AI reviewRe: [PATCH 7/8] virtio-usb: add SuperSpeed device-role support
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] usb: payload corruption due to oversized endpoint descriptor mapping --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] usb: payload corruption due to oversized endpoint descriptor mapping --
commit 3644614322079b958f1f64d6f45046b653de97cb
Author: Igor Skalkin <[email protected]>
virtio-usb: add SuperSpeed device-role support
This commit updates virtio-usb to dynamically parse the maximum supported speed from the host backend's bind event rather than hardcoding it. It also configures endpoint packet sizes accordingly and includes the companion descriptor alongside the endpoint descriptor for SuperSpeed bring-up.
Quoted 4 lines
drivers/usb/virtio_usb/device.c +0
-0
[ ... ]
drivers/usb/virtio_usb/device.c static void vep_enable_work(struct work_struct *work) · line 470
Quoted 10 lines
drivers/usb/virtio_usb/device.c +5
-1@@ -461,7 +463,13 @@ static void vep_enable_work(struct work_struct *work) goto done; } -sg_init_one (psg_data, desc,sizeof (*desc)); +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));
[Severity: High]
Does mapping sizeof(*desc) misalign the payload sent to the host backend?
Since sizeof(struct usb_endpoint_descriptor) is 9 bytes (which includes audio-only fields) and desc->bLength is typically 7, appending the companion descriptor immediately after this 9-byte chunk might shift it by 2 bytes in the resulting payload.
When the host backend parses the descriptors sequentially by advancing bLength bytes, could this cause it to parse misaligned data instead of the companion descriptor, causing the SuperSpeed endpoint configuration to fail?
Quoted 5 lines
drivers/usb/virtio_usb/device.c +2
-0+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);
[ ... ]
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
PATCH 8/8 virtio-usb: support a guest UDC name prefix from the bind event
In reply to Igor SkalkinLet 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.
--- drivers/usb/virtio_usb/device.c | 47 +++++++++++++++++++++++++++++++++------- include/uapi/linux/virtio_usb.h | 4 ++- 2 files changed, 42 insertions(+), 9 deletions(-)
drivers/usb/virtio_usb/device.c +39 -8
@@ -1369,11 +1369,26 @@ on_error: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 ;
@@ -1421,6 +1436,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,
@@ -1447,7 +1463,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" );
@@ -1456,8 +1473,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);
@@ -1480,7 +1507,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) {
@@ -1612,11 +1638,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 ;
include/uapi/linux/virtio_usb.h +3 -1
@@ -216,6 +216,8 @@ enum { VIRTIO_USB_EVT_DEV_UNBIND, }; +#define VIRTIO_USB_UDC_NAME_PREFIX_MAX 64 +struct virtio_usb_dev_event {__le32 code;/* VIRTIO_USB_EVT_DEV_XXX */ __le16 port;/* Device ID */
@@ -227,7 +229,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 */
[email protected]
AI reviewRe: [PATCH 8/8] virtio-usb: support a guest UDC name prefix from the bind event
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [High] usb: virtio_usb: missing sanitization of host-provided UDC name - [Low] usb: virtio_usb: stale…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] usb: virtio_usb: missing sanitization of host-provided UDC name
- [Low] usb: virtio_usb: stale parent device name retained on BIND retry
--
commit b4fd3e9cac2d1567822e6a554abe7a7e1afb42b9
Author: Igor Skalkin <[email protected]>
virtio-usb: support a guest UDC name prefix from the bind event
This commit allows the host backend to supply a name prefix for a port's UDC parent platform_device via the bind event. If the prefix is present, it is used as the parent device's name and to construct the gadget name; otherwise, it falls back to the generic GADGET_NAME.
Quoted 12 lines
drivers/usb/virtio_usb/device.c +2
-1@@ -1369,11 +1369,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) {
drivers/usb/virtio_usb/device.c static int virtio_usb_dc_get_endpoint_info(struct virtio_usb_dc *vudc) · line 1383
Quoted 10 lines
drivers/usb/virtio_usb/device.c +7
-1+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);
[Severity: High]
Does this code adequately sanitize the host-provided udc_prefix string?
If a malicious host supplies a string with invalid characters (such as '/'), passing this unsanitized string directly into kasprintf to construct the parent platform device name could trigger a kernel WARN in kobject_add(), which would panic the guest if panic_on_warn is enabled.
Quoted 10 lines
drivers/usb/virtio_usb/device.c +8
-0+ }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 ;
[ ... ]
drivers/usb/virtio_usb/device.c static void virtio_usb_dc_event_process(struct virtio_usb_event *event) · line 1467
Quoted 7 lines
drivers/usb/virtio_usb/device.c +2
-1@@ -1447,7 +1463,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);
[Severity: Low]
If a previous BIND event failed later in this function, could vudc->pdev still be populated here?
If it was left populated by a prior failed BIND, the new prefix is ignored, and the parent platform device will retain a stale name from the previous BIND event.
Quoted 7 lines
drivers/usb/virtio_usb/device.c +0
-0if (rc) {dev_err (&vusb->vdev->dev,"Failed to create UDC parent device\n" );@@ -1456,8 +1473,18 @@ static void virtio_usb_dc_event_process(struct virtio_usb_event *event)break ; } }
drivers/usb/virtio_usb/device.c static void virtio_usb_dc_event_process(struct virtio_usb_event *event) · line 1483
Quoted 10 lines
drivers/usb/virtio_usb/device.c +8
-2- 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);
[Severity: High]
Are there any missing sanitization checks on the host-provided bind_evt->udc_name_prefix here?
This unsanitized string is used to build the gadget name, which will also be passed to device registration APIs. Similar to the parent_name, a malicious host supplying invalid characters can trigger a kernel WARN or panic.
Quoted 15 lines
drivers/usb/virtio_usb/device.c +4
-1+ }else { + vudc->gadget.name =kasprintf (GFP_KERNEL ,"%s_%d" , +GADGET_NAME , port_id); + }if (!vudc->gadget.name) { rc = -ENOMEM ;kfree (vudc->veps);@@ -1480,7 +1507,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) {
drivers/usb/virtio_usb/device.c
Quoted 6 lines
drivers/usb/virtio_usb/device.c +0
-0dev_err (&vudc->pdev->dev,"Failed to add udc\n" );kfree (vudc->veps); vudc->veps =NULL ;kfree (vudc->gadget.name);break ; }
[Severity: Low]
Does this error path fail to unregister vudc->pdev?
By not unregistering vudc->pdev, it is left for the next BIND event to wrongly reuse. This creates a mismatch between the parent device name and the new gadget name in sysfs on a BIND retry.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
Greg Kroah-Hartman
maintainerQuoted 5 lines · Igor Skalkin
This series adds a new virtio-usb driver: a dual-role virtio device capable of acting as a USB host controller, a USB device controller, or both simultaneously with runtime role switching between the two (USB OTG-style role switching) on ports that support it.
Quoted 7 lines
The corresponding virtio-usb device specification has been posted to virtio-comment for review. This series matches the v2 revision of that spec, which reconciles a small number of protocol details (per-role virtqueue presentation, host-role
vp_idxfor hub/multi-VP support, and the device-role BIND/UNBIND event split) that were clarified while integrating and testing this driver against the spec:
Why do we need this at all when we have other ways of doing usb devices through virtio?
Why is a USB virtio spec needed at all, who is going to use it?
Quoted 8 lines
[RFC PATCH v2] virtio-usb: Add initial virtio-usb specification Igor Skalkin <[email protected]> [email protected]
https://lore.kernel.org/virtio-comment/[email protected]/This driver has been tested end-to-end against our own userspace virtio-usb device implementation (host-side backend) in two setups:
Where is that code and why isn't it part of this submission?
Quoted 1 line
4-5: USB OTG-style role query and role-switching support.
There's a reason OTG isn't used anymore by devices, how have you addressed those problems here? And why duplicate the failures of the past?
Quoted 4 lines
6: endpoint-lifecycle robustness rework (async split-phase state
machine, replacing an earlier out-of-tree gadget.nonatomic patch that didn't pass upstream review).
7: SuperSpeed device-role support.
Why should speed settings matter to a virtual connection?
thanks,
greg k-h
Quoted 14 lines · Greg Kroah-Hartman
Quoted 5 lines · Igor Skalkin
This series adds a new virtio-usb driver: a dual-role virtio device capable of acting as a USB host controller, a USB device controller, or both simultaneously with runtime role switching between the two (USB OTG-style role switching) on ports that support it.
Quoted 7 lines
The corresponding virtio-usb device specification has been posted to virtio-comment for review. This series matches the v2 revision of that spec, which reconciles a small number of protocol details (per-role virtqueue presentation, host-role
vp_idxfor hub/multi-VP support, and the device-role BIND/UNBIND event split) that were clarified while integrating and testing this driver against the spec:
Quoted 6 lines
Why do we need this at all when we have other ways of doing usb devices through virtio?
Why is a USB virtio spec needed at all, who is going to use it?
For device classes that already have a virtio equivalent (storage, HID, video, audio) there's no need for virtio-usb: we can use virtio-blk/virtio-input/virtio-video/virtio-snd directly. What virtio-usb actually addresses is different: protocols that are about raw USB semantics itself, not about any particular device class. Two concrete cases we care about. ADB (Android Debug Bridge), a specific USB interface/vendor-class protocol used throughout Android development and debugging, with no meaningful way to express it as a block or HID device. And Android Auto (AOA) / Apple CarPlay, USB-level control-transfer and vendor-negotiation protocols used when a phone is plugged into an automotive head unit.
Our motivating use case is automotive cockpit virtualization: a physical USB port where a phone is plugged in needs to be handed to a guest VM running the head-unit stack, and that guest needs to run one of these USB-native protocols. The existing software on both sides already speaks raw USB and works unmodified if it sees a real-looking USB device. virtio-usb lets that keep working, instead of needing a new bespoke virtio spec for every such protocol as new USB-based ecosystems show up.
Quoted 11 lines
Quoted 8 lines
[RFC PATCH v2] virtio-usb: Add initial virtio-usb specification Igor Skalkin <[email protected]> [email protected]
https://lore.kernel.org/virtio-comment/[email protected]/This driver has been tested end-to-end against our own userspace virtio-usb device implementation (host-side backend) in two setups:
Where is that code and why isn't it part of this submission?
The backend we used for the testing described above is an internal implementation that we're not releasing as part of this submission - it integrates with some systems that aren't ready to be public. We recognize that limits independent verification of our specific test results, and we don't think that's an ideal situation.
Quoted 6 lines
Quoted 1 line
4-5: USB OTG-style role query and role-switching support.
There's a reason OTG isn't used anymore by devices, how have you addressed those problems here? And why duplicate the failures of the past?
We're not implementing ID-pin detection, HNP, or SRP - none of that. "OTG" here is just a reused name for something much simpler: an explicit role-switch command exposed to the guest via sysfs. Device-to-host is driver-initiated (guest writes to that sysfs entry); host-to-device is host-initiated (the host switches on its own and notifies the guest). Either direction is always granted - no negotiation step to get wrong. Happy to rename the OTG-tagged commands/constants if the naming is causing confusion.
Quoted 7 lines
Quoted 4 lines
6: endpoint-lifecycle robustness rework (async split-phase state
machine, replacing an earlier out-of-tree gadget.nonatomic patch that didn't pass upstream review).
7: SuperSpeed device-role support.Why should speed settings matter to a virtual connection?
Because the kernel APIs we're implementing on top of are inherently speed-typed, not because of any real electrical/physical constraint. usb_hcd (host role) and the USB Gadget API (device role) both bake speed into their core design - it drives enumeration, bandwidth scheduling, and descriptor selection (e.g. SuperSpeed companion descriptors) in the USB core and in gadget function drivers. dummy_hcd is a good precedent:
it's also a purely virtual host controller with no real signaling, and it still has to declare and support different speed configurations, because the framework requires it. We're in the same position - unmodified guest USB class drivers and gadget function drivers depend on accurate speed information regardless of what's actually behind the interface.
Quoted 3 lines
thanks,
greg k-h
Thanks,
Igor
Greg Kroah-Hartman
maintainerQuoted 33 lines · Igor Skalkin
Quoted 14 lines · Greg Kroah-Hartman
Quoted 5 lines · Igor Skalkin
This series adds a new virtio-usb driver: a dual-role virtio device capable of acting as a USB host controller, a USB device controller, or both simultaneously with runtime role switching between the two (USB OTG-style role switching) on ports that support it.
Quoted 7 lines
The corresponding virtio-usb device specification has been posted to virtio-comment for review. This series matches the v2 revision of that spec, which reconciles a small number of protocol details (per-role virtqueue presentation, host-role
vp_idxfor hub/multi-VP support, and the device-role BIND/UNBIND event split) that were clarified while integrating and testing this driver against the spec:Quoted 6 lines
Why do we need this at all when we have other ways of doing usb devices through virtio?
Why is a USB virtio spec needed at all, who is going to use it?
For device classes that already have a virtio equivalent (storage, HID, video, audio) there's no need for virtio-usb: we can use virtio-blk/virtio-input/virtio-video/virtio-snd directly. What virtio-usb actually addresses is different: protocols that are about raw USB semantics itself, not about any particular device class. Two concrete cases we care about. ADB (Android Debug Bridge), a specific USB interface/vendor-class protocol used throughout Android development and debugging, with no meaningful way to express it as a block or HID device. And Android Auto (AOA) / Apple CarPlay, USB-level control-transfer and vendor-negotiation protocols used when a phone is
Quoted 8 lines
plugged into an automotive head unit.
Our motivating use case is automotive cockpit virtualization: a physical USB port where a phone is plugged in needs to be handed to a guest VM running the head-unit stack, and that guest needs to run one of these USB-native protocols. The existing software on both sides already speaks raw USB and works unmodified if it sees a real-looking USB device. virtio-usb lets that keep working, instead of needing a new bespoke virtio spec for every such protocol as new USB-based ecosystems show up.
So you just want "raw" usb, then why not use usb-ip? Isn't that what it's there for? Or just mount usbfs and expose that to the host as that's what adb is using already, right?
Quoted 8 lines
Quoted 8 lines
Quoted 7 lines
[RFC PATCH v2] virtio-usb: Add initial virtio-usb specification Igor Skalkin <[email protected]> [email protected]
https://lore.kernel.org/virtio-comment/[email protected]/This driver has been tested end-to-end against our own userspace virtio-usb device implementation (host-side backend) in two setups:
Quoted 7 lines
Quoted 2 lines
Where is that code and why isn't it part of this submission?
The backend we used for the testing described above is an internal implementation that we're not releasing as part of this submission - it integrates with some systems that aren't ready to be public. We recognize that limits independent verification of our specific test results, and we don't think that's an ideal situation.
Then we can't even review this at all, sorry, you all know better than that.
Quoted 6 lines
Quoted 6 lines
Quoted 1 line
4-5: USB OTG-style role query and role-switching support.
There's a reason OTG isn't used anymore by devices, how have you addressed those problems here? And why duplicate the failures of the past?
Quoted 8 lines
We're not implementing ID-pin detection, HNP, or SRP - none of that. "OTG" here is just a reused name for something much simpler: an explicit role-switch command exposed to the guest via sysfs. Device-to-host is driver-initiated (guest writes to that sysfs entry); host-to-device is host-initiated (the host switches on its own and notifies the guest). Either direction is always granted - no negotiation step to get wrong. Happy to rename the OTG-tagged commands/constants if the naming is causing confusion.
"OTG" has a _VERY_ specific definition in the USB world, don't attempt to re-define it please. That way lies madness...
Quoted 7 lines
Quoted 7 lines
Quoted 4 lines
6: endpoint-lifecycle robustness rework (async split-phase state
machine, replacing an earlier out-of-tree gadget.nonatomic patch that didn't pass upstream review).
7: SuperSpeed device-role support.Why should speed settings matter to a virtual connection?
Quoted 12 lines
Because the kernel APIs we're implementing on top of are inherently speed-typed, not because of any real electrical/physical constraint.
usb_hcd(host role) and the USB Gadget API (device role) both bake speed into their core design - it drives enumeration, bandwidth scheduling, and descriptor selection (e.g. SuperSpeed companion descriptors) in the USB core and in gadget function drivers.dummy_hcdis a good precedent:
it's also a purely virtual host controller with no real signaling, and it still has to declare and support different speed configurations, because the framework requires it. We're in the same position - unmodified guest USB class drivers and gadget function drivers depend on accurate speed information regardless of what's actually behind the interface.
This is a virtual connection, speed means nothing here other than some descriptor stuff in a few places.
Again, try using the existing code, usb-ip or usbfs, don't invent something new, especially when it's not even visable to anyone. Would you want to attempt to review something like this in that situation?
thanks,
greg k-h
Quoted 43 lines · Greg Kroah-Hartman
Quoted 33 lines · Igor Skalkin
Quoted 14 lines · Greg Kroah-Hartman
Quoted 5 lines · Igor Skalkin
This series adds a new virtio-usb driver: a dual-role virtio device capable of acting as a USB host controller, a USB device controller, or both simultaneously with runtime role switching between the two (USB OTG-style role switching) on ports that support it.
Quoted 7 lines
The corresponding virtio-usb device specification has been posted to virtio-comment for review. This series matches the v2 revision of that spec, which reconciles a small number of protocol details (per-role virtqueue presentation, host-role
vp_idxfor hub/multi-VP support, and the device-role BIND/UNBIND event split) that were clarified while integrating and testing this driver against the spec:Quoted 6 lines
Why do we need this at all when we have other ways of doing usb devices through virtio?
Why is a USB virtio spec needed at all, who is going to use it?
For device classes that already have a virtio equivalent (storage, HID, video, audio) there's no need for virtio-usb: we can use virtio-blk/virtio-input/virtio-video/virtio-snd directly. What virtio-usb actually addresses is different: protocols that are about raw USB semantics itself, not about any particular device class. Two concrete cases we care about. ADB (Android Debug Bridge), a specific USB interface/vendor-class protocol used throughout Android development and debugging, with no meaningful way to express it as a block or HID device. And Android Auto (AOA) / Apple CarPlay, USB-level control-transfer and vendor-negotiation protocols used when a phone is
Quoted 8 lines
plugged into an automotive head unit.
Our motivating use case is automotive cockpit virtualization: a physical USB port where a phone is plugged in needs to be handed to a guest VM running the head-unit stack, and that guest needs to run one of these USB-native protocols. The existing software on both sides already speaks raw USB and works unmodified if it sees a real-looking USB device. virtio-usb lets that keep working, instead of needing a new bespoke virtio spec for every such protocol as new USB-based ecosystems show up.
Quoted 4 lines
So you just want "raw" usb, then why not use usb-ip? Isn't that what it's there for? Or just mount usbfs and expose that to the host as that's what adb is using already, right?
usb-ip's host and guest sides are both Linux-specific - in some of our target deployments the host OS isn't Linux at all (e.g. QNX), so there's no usb-ip host-side implementation to use in the first place. virtio-usb's backend only needs to speak the virtio transport, which is host-OS-agnostic.
Separately, usb-ip requires explicit manual configuration on both sides for every device. Its own checklist also calls for disabling SELinux and opening a TCP port. We're trying to avoid that operational overhead (ideally - fully virtualized vanilla Android as a guest). usbfs is a different layer - it lets a local process talk to a locally-attached device (how the ADB host daemon works today), but doesn't address getting the USB device into the guest in the first place. And usbfs is Linux-specific too.
Quoted 10 lines
Quoted 10 lines
Quoted 10 lines
Quoted 7 lines
[RFC PATCH v2] virtio-usb: Add initial virtio-usb specification Igor Skalkin <[email protected]> [email protected]
https://lore.kernel.org/virtio-comment/[email protected]/This driver has been tested end-to-end against our own userspace virtio-usb device implementation (host-side backend) in two setups:
Where is that code and why isn't it part of this submission?
Quoted 8 lines
Quoted 5 lines
The backend we used for the testing described above is an internal implementation that we're not releasing as part of this submission - it integrates with some systems that aren't ready to be public. We recognize that limits independent verification of our specific test results, and we don't think that's an ideal situation.
Then we can't even review this at all, sorry, you all know better than that.
We're considering publishing a virtio-usb test device for QEMU to make independent testing easier.>
Quoted 38 lines
Quoted 6 lines
Quoted 6 lines
Quoted 1 line
4-5: USB OTG-style role query and role-switching support.
There's a reason OTG isn't used anymore by devices, how have you addressed those problems here? And why duplicate the failures of the past?
Quoted 8 lines
We're not implementing ID-pin detection, HNP, or SRP - none of that. "OTG" here is just a reused name for something much simpler: an explicit role-switch command exposed to the guest via sysfs. Device-to-host is driver-initiated (guest writes to that sysfs entry); host-to-device is host-initiated (the host switches on its own and notifies the guest). Either direction is always granted - no negotiation step to get wrong. Happy to rename the OTG-tagged commands/constants if the naming is causing confusion.
"OTG" has a _VERY_ specific definition in the USB world, don't attempt to re-define it please. That way lies madness...
Quoted 7 lines
Quoted 7 lines
Quoted 4 lines
6: endpoint-lifecycle robustness rework (async split-phase state
machine, replacing an earlier out-of-tree gadget.nonatomic patch that didn't pass upstream review).
7: SuperSpeed device-role support.Why should speed settings matter to a virtual connection?
Quoted 12 lines
Because the kernel APIs we're implementing on top of are inherently speed-typed, not because of any real electrical/physical constraint.
usb_hcd(host role) and the USB Gadget API (device role) both bake speed into their core design - it drives enumeration, bandwidth scheduling, and descriptor selection (e.g. SuperSpeed companion descriptors) in the USB core and in gadget function drivers.dummy_hcdis a good precedent:
it's also a purely virtual host controller with no real signaling, and it still has to declare and support different speed configurations, because the framework requires it. We're in the same position - unmodified guest USB class drivers and gadget function drivers depend on accurate speed information regardless of what's actually behind the interface.
Quoted 3 lines
This is a virtual connection, speed means nothing here other than some descriptor stuff in a few places.
OK, will change commit message. In this commit I just add some SS specific details to EP0 processing and fix SS issues.
Quoted 4 lines
Again, try using the existing code, usb-ip or usbfs, don't invent something new, especially when it's not even visable to anyone. Would you want to attempt to review something like this in that situation?
Answered both points above (usb-ip/usbfs, and the backend visibility question) - happy to go deeper on either if those answers don't address your concern.
Quoted 3 lines
thanks,
greg k-h
Thanks,
Igor
Greg Kroah-Hartman
maintainerQuoted 50 lines · Igor Skalkin
Quoted 43 lines · Greg Kroah-Hartman
Quoted 33 lines · Igor Skalkin
Quoted 14 lines · Greg Kroah-Hartman
Quoted 5 lines · Igor Skalkin
This series adds a new virtio-usb driver: a dual-role virtio device capable of acting as a USB host controller, a USB device controller, or both simultaneously with runtime role switching between the two (USB OTG-style role switching) on ports that support it.
Quoted 7 lines
The corresponding virtio-usb device specification has been posted to virtio-comment for review. This series matches the v2 revision of that spec, which reconciles a small number of protocol details (per-role virtqueue presentation, host-role
vp_idxfor hub/multi-VP support, and the device-role BIND/UNBIND event split) that were clarified while integrating and testing this driver against the spec:Quoted 6 lines
Why do we need this at all when we have other ways of doing usb devices through virtio?
Why is a USB virtio spec needed at all, who is going to use it?
For device classes that already have a virtio equivalent (storage, HID, video, audio) there's no need for virtio-usb: we can use virtio-blk/virtio-input/virtio-video/virtio-snd directly. What virtio-usb actually addresses is different: protocols that are about raw USB semantics itself, not about any particular device class. Two concrete cases we care about. ADB (Android Debug Bridge), a specific USB interface/vendor-class protocol used throughout Android development and debugging, with no meaningful way to express it as a block or HID device. And Android Auto (AOA) / Apple CarPlay, USB-level control-transfer and vendor-negotiation protocols used when a phone is
Quoted 8 lines
plugged into an automotive head unit.
Our motivating use case is automotive cockpit virtualization: a physical USB port where a phone is plugged in needs to be handed to a guest VM running the head-unit stack, and that guest needs to run one of these USB-native protocols. The existing software on both sides already speaks raw USB and works unmodified if it sees a real-looking USB device. virtio-usb lets that keep working, instead of needing a new bespoke virtio spec for every such protocol as new USB-based ecosystems show up.Quoted 4 lines
So you just want "raw" usb, then why not use usb-ip? Isn't that what it's there for? Or just mount usbfs and expose that to the host as that's what adb is using already, right?
Quoted 5 lines
usb-ip's host and guest sides are both Linux-specific - in some of our target deployments the host OS isn't Linux at all (e.g. QNX), so there's no usb-ip host-side implementation to use in the first place. virtio-usb's backend only needs to speak the virtio transport, which is host-OS-agnostic.
But you are making a brand new virtio transport, which will have to be written for all OSes. usb-ip already works on other operating systems today. Same for usbfs through libusb.
Quoted 8 lines
Separately, usb-ip requires explicit manual configuration on both sides for every device. Its own checklist also calls for disabling SELinux and opening a TCP port. We're trying to avoid that operational overhead (ideally - fully virtualized vanilla Android as a guest). usbfs is a different layer - it lets a local process talk to a locally-attached device (how the ADB host daemon works today), but doesn't address getting the USB device into the guest in the first place. And usbfs is Linux-specific too.
No, see libusb, it abstracts that away.
And really, why do you want to do anything other than Linux. Or more realisticly, why should _I_ care about anything other than Linux? :)
Again, mount usbfs and away you go, libusb is your friend :)
thanks,
greg k-h
Michael S. Tsirkin
maintainerQuoted 9 lines · Igor Skalkin
Quoted 9 lines
Quoted 8 lines
[RFC PATCH v2] virtio-usb: Add initial virtio-usb specification Igor Skalkin <[email protected]> [email protected]
https://lore.kernel.org/virtio-comment/[email protected]/This driver has been tested end-to-end against our own userspace virtio-usb device implementation (host-side backend) in two setups:
Quoted 7 lines
Quoted 2 lines
Where is that code and why isn't it part of this submission?
The backend we used for the testing described above is an internal implementation that we're not releasing as part of this submission - it integrates with some systems that aren't ready to be public. We recognize that limits independent verification of our specific test results, and we don't think that's an ideal situation.
Supporting vhost-user with a backend doing pass-through shouldn't be too hard.
Signature · 1 line
MST
Greg Kroah-Hartman
maintainerQuoted 12 lines · Michael S. Tsirkin
Quoted 11 lines · Igor Skalkin
Quoted 11 lines
Quoted 8 lines
[RFC PATCH v2] virtio-usb: Add initial virtio-usb specification Igor Skalkin <[email protected]> [email protected]
https://lore.kernel.org/virtio-comment/[email protected]/This driver has been tested end-to-end against our own userspace virtio-usb device implementation (host-side backend) in two setups:
Where is that code and why isn't it part of this submission?
Quoted 7 lines
Quoted 5 lines
The backend we used for the testing described above is an internal implementation that we're not releasing as part of this submission - it integrates with some systems that aren't ready to be public. We recognize that limits independent verification of our specific test results, and we don't think that's an ideal situation.
Supporting vhost-user with a backend doing pass-through shouldn't be too hard.
Wait, if all you want is adb to work, why not just use it in network mode? That should work find across a virtual machine, right?
thanks,
greg k-h
Hi all,
I'd like to join the discussion and share my perspective.
Greg's main concern is: "Why is this needed at all?" Let me explain.
First of all, our primary focus is embedded systems, including the automotive
industry, particularly infotainment systems. In this area, the easiest way to
provide USB access to a GVM is to pass the USB device directly through to the
guest. This is even simpler than usb-ip, since we can rely on the standard Linux
USB driver.
And it works well until we need more flexibility, such as:
- Sharing different USB devices connected to the same USB host among multiple
VMs (for instance, assigning one USB stick to the AGL GVM, another to the Android GVM, and a sound card to the PVM).
- Sharing multiple USB gadget functions from several VMs through the same USB
gadget port (for instance, providing ADB connectivity to all VMs, including
the PVM and both GVMs).
Once this level of flexibility is required, simple passthrough is no longer sufficient, and we have to rely on USB sharing mechanisms.
And this brings us to your main concern: Why not simply use usb-ip to share USB devices between the PVM and GVMs? Why introduce an entirely new transport for USB virtualization instead of relying on existing solutions?
There are several reasons for this.
First, we aim to support not only Linux-based hosts. The host could be running
QNX or even a bare-metal (no-OS) environment, where usb-ip and usbfs are not available. Igor has already explained this point. However, as you rightly pointed out:
Quoted 1 line
Or more realisticly, why should _I_ care about anything other than
Linux? :)
It seems, you are right: why you should pay efforts reviewing our patches, while
no one except us will be able to utilize this for non-Linux based workspaces. In
reality, the opposite is true: if VirtIO USB becomes a standard part of the open-source Linux kernel, USB virtualization will become hypervisor-agnostic.
For end users who rely on open-source or commercial hypervisors, it will not matter which hypervisor is running under the hood (for example, QNX or QEMU).
They will be able to use the open-source Linux kernel out of the box, without
any modifications. If they later decide to migrate to a different hypervisor that supports the standard, the transition will require little to no effort. Therefore, the Linux community should, in principle, be interested in supporting
this effort.
Furthermore, this is not only about host OS, this also about guests. Let's imagine
you want to run QNX or VxWorks image under qemu on Linux Host. Both GVM OS supports OASIS Virtio Standard, but does not support usb-ip. Therefore, we would
like to introduce a common approach that works across all operating systems.
And we also plan to add virtio-usb support to QEMU as well. This approach will
be available to the broader community as well, not just as a proprietary solution.
The second important reason is that one of the key virtio-usb features we need,
and which partially motivated this work, is support for a dual-role USB controller for Apple CarPlay. usb-ip cannot provide this because it lacks OTG
support.
Third, performance is another reason for introducing a new solution. Igor has
already partially explained this point. Existing solutions such as usb-ip rely on sockets and therefore introduce additional overhead. This becomes
particularly important in resource-constrained embedded systems. With our own
implementation, we can avoid this overhead.
Fourth, as Igor has already mentioned, usb-ip and usbfs do not work out of the
box. They still require additional configuration on the GVM side to function properly. Yes, this is standard Linux administration, but it still requires additional configuration and maintenance effort. In contrast, a vanilla Linux
kernel with VirtIO USB support will boot and operate as is, requiring zero additional effort.
And last but not least, let's be honest: usb-ip is not really about virtualization.
Its primary goal is to share USB devices over a network. This is a perfectly valid solution, but it serves a different purpose than virtio-usb. By the same
reasoning, one could ask: "Why do we need virtio-gpu when we can simply use RDP
over IP?". In other words, this is not about inventing a brand-new transport. It
is about defining and standardizing an existing approach as an open industry standard.
Thanks,
Vasilii Ianikeev
Quoted 23 lines · Greg Kroah-Hartman
Quoted 8 lines · Michael S. Tsirkin
Quoted 7 lines · Igor Skalkin
Quoted 7 lines
Quoted 7 lines
[RFC PATCH v2] virtio-usb: Add initial virtio-usb specification Igor Skalkin <[email protected]> [email protected]
https://lore.kernel.org/virtio-comment/[email protected]/This driver has been tested end-to-end against our own userspace virtio-usb device implementation (host-side backend) in two setups:
Quoted 8 lines
Quoted 7 lines
Quoted 2 lines
Where is that code and why isn't it part of this submission?
The backend we used for the testing described above is an internal implementation that we're not releasing as part of this submission - it integrates with some systems that aren't ready to be public. We recognize that limits independent verification of our specific test results, and we don't think that's an ideal situation.
Supporting vhost-user with a backend doing pass-through shouldn't be too hard.
Wait, if all you want is adb to work, why not just use it in network mode? That should work find across a virtual machine, right?
thanks,
greg k-h
Hi all,
Sorry for the formatting issues.
I'd like to join the discussion and share my perspective.
Greg's main concern is: "Why is this needed at all?" Let me explain.
First of all, our primary focus is embedded systems, including the automotive industry, particularly infotainment systems. In this area, the easiest way to provide USB access to a GVM is to pass the USB device directly through to the guest. This is even simpler than usb-ip, since we can rely on the standard Linux USB driver.
And it works well until we need more flexibility, such as:
- Sharing different USB devices connected to the same USB host among multiple VMs (for instance, assigning one USB stick to the AGL GVM, another to the Android GVM, and a sound card to the PVM).
- Sharing multiple USB gadget functions from several VMs through the same USB gadget port (for instance, providing ADB connectivity to all VMs, including the PVM and both GVMs).
Once this level of flexibility is required, simple passthrough is no longer sufficient, and we have to rely on USB sharing mechanisms.
And this brings us to Greg's main concern: Why not simply use usb-ip to share USB devices between the PVM and GVMs? Why introduce an entirely new transport for USB virtualization instead of relying on existing solutions?
There are several reasons for this.
First, we aim to support not only Linux-based hosts. The host could be running QNX or even a bare-metal (no-OS) environment, where usb-ip and usbfs are not available. Igor has already explained this point. However, as you rightly pointed out:
Quoted 1 line
Or more realisticly, why should _I_ care about anything other than Linux? :)
It seems, you are right: why you should pay efforts reviewing our patches, while nonone excpet us will be able to utilize this for non-Linux based workpaces. In reality, the opposite is true: if VirtIO USB becomes a standard part of the open-source Linux kernel, USB virtualization will become hypervisor-agnostic. For end users who rely on open-source or commercial hypervisors, it will not matter which hypervisor is running under the hood (for example, QNX or QEMU). They will be able to use the open-source Linux kernel out of the box, without any modifications. If they later decide to migrate to a different hypervisor that supports the standard, the transition will require little to no effort. Therefore, the Linux community should, in principle, be interested in supporting this effort.
Furthmore, this is not only about host OS, this also about guests. Let's imagine you want to run QNX or VxWorks image under qemu on Linux Host. Both GVM OS supports OASIS Virtio Standard, but does not support usb-ip. Therefore, we would like to introduce a common approach that works across all operating systems.
And we also plan to add virtio-usb support to QEMU as well. This approach will be available to the broader community as well, not just as a proprietary solution.
The second important reason is that one of the key virtio-usb features we need, and which partially motivated this work, is support for a dual-role USB controller for Apple CarPlay. usb-ip cannot provide this because it lacks OTG support.
Third, performance is another reason for introducing a new solution. Igor has already partially explained this point. Existing solutions such as usb-ip rely on sockets and therefore introduce additional overhead. This becomes particularly important in resource-constrained embedded systems. With our own implementation, we can avoid this overhead.
Fourth, as Igor has already mentioned, usb-ip and usbfs do not work out of the box. They still require additional configuration on the GVM side to function properly. Yes, this is standard Linux administration, but it still requires additional configuration and maintenance effort.. In contrast, a vanilla Linux kernel with VirtIO USB support will boot and operate as is, requiring zero additional effort.
Last but not least, let's be honest: usb-ip is not really about virtualization. Its primary goal is to share USB devices over a network. This is a perfectly valid solution, but it serves a different purpose than virtio-usb. By the same reasoning, one could ask: "Why do we need virtio-gpu when we can simply use RDP over IP?". In other words, this is not about inventing a brand-new transport. It is about defining and standardizing an existing approach as an open industry standard.
Best Regards,
Vasilii
Quoted 23 lines · Greg Kroah-Hartman
Quoted 8 lines · Michael S. Tsirkin
Quoted 7 lines · Igor Skalkin
Quoted 7 lines
Quoted 7 lines
[RFC PATCH v2] virtio-usb: Add initial virtio-usb specification Igor Skalkin <[email protected]> [email protected]
https://lore.kernel.org/virtio-comment/[email protected]/This driver has been tested end-to-end against our own userspace virtio-usb device implementation (host-side backend) in two setups:
Quoted 8 lines
Quoted 7 lines
Quoted 2 lines
Where is that code and why isn't it part of this submission?
The backend we used for the testing described above is an internal implementation that we're not releasing as part of this submission - it integrates with some systems that aren't ready to be public. We recognize that limits independent verification of our specific test results, and we don't think that's an ideal situation.
Supporting vhost-user with a backend doing pass-through shouldn't be too hard.
Wait, if all you want is adb to work, why not just use it in network mode? That should work find across a virtual machine, right?
thanks,
greg k-h