From mboxrd@z Thu Jan 1 00:00:00 1970 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=205.220.180.131 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1796146575; b=1SWqT83zBfqy0xRLH7matYnZgYtVaHTKpFCwx0wQfcEOlD4A5s2+EXYrl446A1ZdxIiq 9AgwTq1zyXM2ehKPF5DbTPoou88TcpzDjOH/kov1oBmODXbQraHOuYe78/trvUfB1IL95 RyqpeTdurCDfFRPBBQMAFJn8KhFgejZCx/pzlX8c5MOTkn6U2cHH7XblNESp7lJVDWLnw fb3RUApYE52bOVuxObDM6jlrnOE30zOlmx2GNvx0judXufEDy0e/oNdu2+KqpR0xbNXs+ +y2l6Eg6tfzwTu02TIZZVLveEyIb46qltJhqfGN5OmFt2ukhKFHDx5RGNIlpQAIclXw== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1796146575; h=DMARC-Filter:Received:DKIM-Signature:Received:Received: DKIM-Signature:X-Google-DKIM-Signature:X-Forwarded-Encrypted: X-Gm-Message-State:X-Gm-Gg:X-Received:X-Received:Received:From:To:Cc: Subject:Date:Message-ID:X-Mailer:In-Reply-To:References:MIME-Version: Content-Transfer-Encoding:X-Proofpoint-Spam-Details-Enc: X-Proofpoint-ORIG-GUID:X-Proofpoint-GUID:X-Proofpoint-Spam-Info: X-Authority-Analysis:X-Proofpoint-Virus-Version: X-Proofpoint-Spam-Details; bh=L7B1JKtyWJaYpp0tIhjO1V+P+3D9dw98w4TB5mYVyPg=; b=ragqytw4Wk60ZJu7pjbT1qajUjEprb1IF/JofoelX0W/EM7DbDUg7CaT5RNkvnx2u0JZ 1c5iUQEv7jiJq+VaUhYUPBW1eOL4yO0GoeIlfR4E87Yr2ZtUNID4NZw4UtYH3YuWORdcr Y74ztPdorlwGbM7oIp8dtA6HgzRveQME2ozXtb4OYFvgt/DMCBOc8jH2H5Gaj+1DXN2Yp Ptu5jfGvEnws36FZ6VwOx4QMHp/mWUSBlzFes+kXYGKh/qS5WDB80uqpBwPPW70wn8r/l zuq+XLAO7BxKRQ9El/8Xex+KyRC6KpTxFQh2Sx1F0w95jRlA02VGJPmPtpekZ2h8Z9A== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=oss.qualcomm.com; spf=pass smtp.mailfrom=oss.qualcomm.com; dkim=pass header.d=qualcomm.com header.i=@qualcomm.com header.a=rsa-sha256 header.s=qcppdkim1 header.b=h0hFFvTJ; dkim=pass header.d=oss.qualcomm.com header.i=@oss.qualcomm.com header.a=rsa-sha256 header.s=google header.b=ijDeE81j; arc=none smtp.remote-ip=205.220.180.131 Received: from mx0b-0031df01.pphosted.com (mx0b-0031df01.pphosted.com [205.220.180.131]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 781BE606A6A1 for ; Tue, 1 Dec 2026 17:36:13 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 781BE606A6A1 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=oss.qualcomm.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=oss.qualcomm.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=qualcomm.com header.i=@qualcomm.com header.a=rsa-sha256 header.s=qcppdkim1 header.b=h0hFFvTJ; dkim=pass (2048-bit key) header.d=oss.qualcomm.com header.i=@oss.qualcomm.com header.a=rsa-sha256 header.s=google header.b=ijDeE81j Received: from pps.filterd (m0279873.ppops.net [127.0.0.1]) by mx0a-0031df01.pphosted.com (8.18.1.11/8.18.1.11) with ESMTP id 6B1F6jjJ085455 for ; Tue, 1 Dec 2026 17:36:12 GMT DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=qualcomm.com; h= cc:content-transfer-encoding:date:from:in-reply-to:message-id :mime-version:references:subject:to; s=qcppdkim1; bh=L7B1JKtyWJa Ypp0tIhjO1V+P+3D9dw98w4TB5mYVyPg=; b=h0hFFvTJkagRd3f9+lsBQdOwcdc JtqBulsZ0LTQMDL5hdWd/z/EGFQ0FEdpY8+Vpm9sMGN5/K2IVRiGTyfiRY+Tn+C3 Aa1fKsDnAnrS6tV5GMVyXaHvPQDJ47C8Z1b7opshPitubhW5ettZfgeZ8WEaqPXb 6B1c1JwqCWrrUYPJw3lHm1RN/U7cz2iNuuMR1HeDLYC2buCmotHJSWUENfD2wEZQ eQAOHpRWre5POZBFDJTnrtrnb7eo5+mLXGlp47jPHGhxHCYzG1jvXDPQoIA26GpO gQy4zL+0HepFJHVZe018r3seU+BDjib9zXVtxM5sGCY+XD4zujfoWvN8Y4Q== Received: from mail-ua1-f69.google.com (mail-ua1-f69.google.com [209.85.222.69]) by mx0a-0031df01.pphosted.com (PPS) with ESMTPS id 4j9vw79qm1-1 (version=TLSv1.3 cipher=TLS_AES_128_GCM_SHA256 bits=128 verify=NOT) for ; Tue, 01 Dec 2026 17:36:12 +0000 (GMT) Received: by mail-ua1-f69.google.com with SMTP id a1e0cc1a2514c-99082f450bfso7170799241.2 for ; Tue, 01 Dec 2026 09:36:12 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=oss.qualcomm.com; s=google; t=1796146571; x=1796751371; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to:content-type; bh=L7B1JKtyWJaYpp0tIhjO1V+P+3D9dw98w4TB5mYVyPg=; b=ijDeE81jw/x6Yc2mD1ztL86fKL25wss8eaMsQnri7noqTySWHka2kIzWBvUoaeYKcT dwra9YRSbXTsZWbVELnbCdbgC5HLoe3WB5DPcVXT1YwMiRNAwbVH6nMZ85runM+GzWNo 7a7PS+OpTvdkjnLyo6iLyG9H8vjKFcLjGpObfdUOlvu0ucmoRVXQgHeWHJIL8jkM3nk8 cbYM1B5766zgQ51ae5aboe4BEKFEo8DJrTe/fXgNlZrm99cMQ+P9lIqm3RgE7GDqfPcg 1+knITK/EkAQK/q8vAGcnnJipSg47tTB2PhSnZxZu4rFUBfZ2sOoCADuVBPvoysRnkMS AIBA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1796146571; x=1796751371; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-gg:x-gm-message-state:from :to:cc:subject:date:message-id:reply-to:content-type; bh=L7B1JKtyWJaYpp0tIhjO1V+P+3D9dw98w4TB5mYVyPg=; b=G16ugoYghMUcm/6JsJU+xmzHzmxVHzu3l2cj7qk0NVZJwQBgXLBvtcRyYuWPtyS5Wt j99y4H3A3hXFBwdKKDRGrLdFeHrIRi8o5rQ6fE0TJV49qf3tAlv3a7i+5neXpdDrmjXq CwwesCrEIkd7CFdzN/p5qZL7/Pviflxl3KTspDqVf9d5h2PNZjNRbDSj3msi7o2Cyo9r Fu3p2buo8QglwpbqdyfXqNEAo622iXDLbrdsf1Oual1n3pHM9HwI0U9PwGzEFioqiwHs m8UJqSI2dayf1ENBPnCXBOwVRu8hR9wnSe3c6JvmbRDzjx87BFQawKIhpDEeTRozYNJi 44NQ== X-Forwarded-Encrypted: i=1; AL+hErHHk0F1uab3ciXRchAAqNEl0q9CrwN29IbLmO8uU68W5OsP7sZkxATs4F7fbAMy/FZKObWaB9gc/hsl1vw=@vger.kernel.org X-Gm-Message-State: APuU4Z+hY3Bb/I+tjTRdFMNV9lTKWWuGn1c2Ux6ONGhNXHbSITNCbVpW pmyB2sg1GEg+si2zTL2pg3zp8XyNwVdksd9l32suuf0mei8WKjAeAgKJwR2bE7WvZAETlAaHq0i LVS0fO7bViu6wUSdJfLYa7gd2BnVqrRmOjfETpfQTeZawWFWcvUjFf9cgrjA4n2q1W/g= X-Gm-Gg: AZFdTZfh7+4n6ArECTLt9/yaH10yGq0Ir4NTlwUJkXkLlnwy79LfyR+7mnWLs0/ISoK cdqQ41nclIlYLz7s8xvjN/nlMt7Tnw+ErN1IC7yNWfMYPjLodkC+VGSDy/9vaBbFIJcI4iNRnaP qri7OHp5HXqfRF7xmNLy4uvhY64d1cpvu48UzqLr8yL+CEgJCSj6kiOUWjZNoAXzDjJpO18kBf9 BnSDaS/xYp1EoHLcGNzYhJ92sQJh8MBrZ4BSc15HlX4qaKOHmBqT09oPBeppqDvfd9oK8Us1aUW FtRzC8tvF2Q83j6DEfCoqT5W86UFGWmybqX3WqatB7Iz9xE5Cd7ia0lOp180G4DjIX6fCPGgArk voJUEj/wv48BRnmJ8xEA9Z3Ge4SqGwoPRtr6heNjkase+LwTkl+0kXOHggccUPr17RbLeiSUkY8 hzgzmu X-Received: by 2002:a05:6102:14a3:b0:7d2:c903:515d with SMTP id ada2fe7eead31-7d7393ae1e1mr28536554137.7.1796146570875; Tue, 01 Dec 2026 09:36:10 -0800 (PST) X-Received: by 2002:a05:6102:14a3:b0:7d2:c903:515d with SMTP id ada2fe7eead31-7d7393ae1e1mr28536482137.7.1796146569996; Tue, 01 Dec 2026 09:36:09 -0800 (PST) Received: from QCOM-WFsSr66Fqw.qualcomm.com ([212.136.9.4]) by smtp.gmail.com with ESMTPSA id 5b1f17b1804b1-4bbb39dd4e7sm339386455e9.0.2026.12.01.09.36.08 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 01 Dec 2026 09:36:09 -0800 (PST) From: Igor Skalkin To: "Michael S . Tsirkin" , Jason Wang , Greg Kroah-Hartman Cc: virtualization@lists.linux.dev, linux-usb@vger.kernel.org, linux-kernel@vger.kernel.org, Eugenio Perez , Xuan Zhuo , Vasilii Ianikeev , Aiswarya Cyriac , Anton Yakovlev , Trilok Soni , Matias Ezequiel Vara Larsen , Igor Skalkin Subject: [RFC PATCH v2 6/7] virtio-usb: add host/device role switch support Date: Tue, 1 Dec 2026 18:35:35 +0100 Message-ID: X-Mailer: git-send-email 2.53.0 In-Reply-To: References: <20260924160907.145405-1-igor.skalkin@oss.qualcomm.com> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Proofpoint-Spam-Details-Enc: AW1haW4tMjYxMjAxMDA3MCBTYWx0ZWRfX18O7JyK36W29 fHaekqJJXJV5msBQoMOLxzICGS9BZdVbAtsg/Tzr6zXoT69BhX6vAvsAOVtI5tHJulxwHYOnSsI wWLXxWUFAKL3V9b3+34JiM0emQ50J8X86MUjk6T8miUujHq2ugLtm/MQwF8bsPO9tbSC1LaNWxV 7I6ZpPe0zjtbEeDmZmQxXU7N4X0p2hiK1eoQfU5DzoK8+srPXSZlSb4LweJfVsjreoCMTvHl1tv Mss/sMpE9Lbzv6rs+fDV0IL1P9BA43uUMPKd+8+UJClIQWN7DljVZxnVC9ymbe8fyF+tFcRwd+n sDS0oEj8xzk5OOk/AOsU3IlcvLyUS6qGWMfC7VEezU6nbe1Tl0PJV7C3dg4YssmSyNT308vO7RN 1kaZWguVzH5UtVvhfSAI7fOFbf/36xRgKL6JTh04Q6+QXCn1nZ3xnWmssxqV0rb87sMvhKoofmp rDWjdjpv04kgkMdVayA== X-Proofpoint-ORIG-GUID: BXZNWHYMcdEsTG3X2STiWF_3IcrHaSo6 X-Proofpoint-GUID: BXZNWHYMcdEsTG3X2STiWF_3IcrHaSo6 X-Proofpoint-Spam-Info: AW1haW4tMjYxMjAxMDA3MCBTYWx0ZWRfX2panDtOoGOUO 3MQ3emhN3F6yc4lzf7nuUxcvQ9ZK0xuaNIg6bgBOq64FrzJdlGnVfxQjeeM4rvtiHOfS5obX26o WID3RaQfG83vOjikM8N9A/laeRNE2uw= X-Authority-Analysis: v=2.4 cv=AItH9idw c=1 sm=1 tr=0 ts=6b0f058c cx=c_pps a=UbhLPJ621ZpgOD2l3yZY1w==:117 a=dNlqnMcrdpbb+gQrTujlOQ==:17 a=pUM-KoujPXoA:10 a=s4-Qcg_JpJYA:10 a=VkNPw1HP01LnGYTKEx00:22 a=u7WPNUs3qKkmUXheDGA7:22 a=rJkE3RaqiGZ5pbrm-msn:22 a=EUspDBNiAAAA:8 a=H-k_g9NV3VHAMnKWahcA:9 a=TOPH6uDL9cOC6tEoww4z:22 X-Proofpoint-Virus-Version: vendor=baseguard engine=ICAP:2.0.293,Aquarius:18.0.1176,Hydra:6.1.138,FMLib:17.12.100.49 definitions=2026-12-01_03,2026-12-01_01,2025-10-01_01 X-Proofpoint-Spam-Details: rule=outbound_notspam policy=outbound score=0 impostorscore=0 adultscore=0 lowpriorityscore=0 spamscore=0 suspectscore=0 malwarescore=0 phishscore=0 priorityscore=1501 bulkscore=0 clxscore=1015 classifier=typeunknown authscore=0 authtc= authcc= route=outbound adjust=0 reason=mlx scancount=1 engine=8.22.0-2611040001 definitions=main-2612010070 Add support for ports that can switch between the host and device roles at runtime. This is a device-driven role switch, not USB On-The-Go: there is no HNP/SRP, ID pin or OTG descriptor involved. Negotiate VIRTIO_USB_F_SWITCH_ROLE during probe (only valid together with both host and device roles), extend virtio_usb_rsw_get_role() to also report each port's supported roles (is_dual_role), and register a USB Role Switch class device per dual-role port so userspace can observe and control the port's role. A role write is sent to the device as VIRTIO_USB_CMD_ROLE_SET carrying the target role. The command is idempotent: the device completes the whole transition before it replies, and replies OK without doing anything if the port is already in the requested role. So the switch is done synchronously in the role switch set callback: send ROLE_SET, even if the cached role already matches, then read the role back with ROLE_GET and follow it. A ROLE_SET error is returned to the caller. The role is read back in that case too: after a timeout or a signal the device may still have switched, and the guest must follow the role the device reports. The device also sends VIRTIO_USB_EVT_ROLE_CHANGE, both when the role was switched on the host side and as an echo of a guest request. The event goes through the same ROLE_GET resync, which does nothing if the role did not change. A per-port mutex held over the whole transition serializes guest requests and events. Events for an invalid port or for a port without a role switch are ignored. A port's HCD and root hub only exist while the port is in host role, so they are created or torn down when the resync finds a new role. A per-port vhc_lock protects the vhc pointer against the host event worker, which may run concurrently with the role switch. Whether a port is dual-role is decided at probe time, where the role switch is registered based on it, and is not changed by a later ROLE_GET. vport->rsw is set before the role switch is registered, as the set callback may run as soon as it is. On remove, the role switches are unregistered and the role event work is cancelled first, so a switch in progress cannot create or destroy an HCD after the queues are stopped or the host VPs are torn down. Role commands now go through the common, timeout-protected virtio_usb_cmd_send_sync() path instead of the role code's own completion wait, so a stalled device can no longer block the event worker forever. A started flag keeps queue notify callbacks from scheduling work before probe has finished or after remove has begun, and the device event queue is now populated before virtio_device_ready(). The event queues are populated, and the device notified, before started is set. The device may deliver a pending event right away - e.g. PORT_CONNECTED for a device already plugged at boot - and its notification is dropped while started is false. With EVENT_IDX the device is not asked to notify again until the used ring is consumed, so later events would go unnoticed as well. Probe therefore runs the host, device and role event workers once after setting started. Signed-off-by: Igor Skalkin --- drivers/usb/virtio_usb/Kconfig | 4 +- drivers/usb/virtio_usb/controller.c | 118 +++++-- drivers/usb/virtio_usb/controller.h | 31 +- drivers/usb/virtio_usb/device.c | 8 + drivers/usb/virtio_usb/host.c | 104 +++++- drivers/usb/virtio_usb/role_switch.c | 502 ++++++++++++++++++++++----- drivers/usb/virtio_usb/role_switch.h | 19 +- 7 files changed, 660 insertions(+), 126 deletions(-) diff --git a/drivers/usb/virtio_usb/Kconfig b/drivers/usb/virtio_usb/Kconfig index 0cc5df26151c..c89b88da8c34 100644 --- a/drivers/usb/virtio_usb/Kconfig +++ b/drivers/usb/virtio_usb/Kconfig @@ -3,11 +3,13 @@ config USB_VIRTIO tristate "Virtio USB controller support" depends on VIRTIO && USB && USB_GADGET + select USB_ROLE_SWITCH help This driver supports the virtio USB device, a paravirtualized dual-role USB controller. Each port of the device acts either as a USB host controller port or as a USB device controller - (UDC). + (UDC), and a dual-role port can be switched between the two + roles at runtime through the USB role switch class. To compile this driver as a module, choose M here: the module will be called virtio-usb. diff --git a/drivers/usb/virtio_usb/controller.c b/drivers/usb/virtio_usb/controller.c index 9f875a127f67..b0ce6b70c0b1 100644 --- a/drivers/usb/virtio_usb/controller.c +++ b/drivers/usb/virtio_usb/controller.c @@ -9,8 +9,8 @@ #include #include "controller.h" -#include "host.h" #include "device.h" +#include "host.h" #include "role_switch.h" #include "vq_common.h" @@ -81,6 +81,14 @@ static int virtio_usb_validate(struct virtio_device *vdev) return -EINVAL; } + if ((!(virtio_has_feature(vdev, VIRTIO_USB_F_HOST)) || + !(virtio_has_feature(vdev, VIRTIO_USB_F_DEVICE))) && + virtio_has_feature(vdev, VIRTIO_USB_F_SWITCH_ROLE)) { + dev_err(&vdev->dev, + "role switching requires both (host and device) roles support\n"); + return -EINVAL; + } + return 0; } @@ -119,6 +127,12 @@ static int virtio_usb_probe(struct virtio_device *vdev) if (virtio_has_feature(vdev, VIRTIO_USB_F_DEVICE)) vusb->device_role = 1; + if (virtio_has_feature(vdev, VIRTIO_USB_F_SWITCH_ROLE)) + vusb->switch_role = 1; + + dev_info(&vdev->dev, "%s nports %d (h_role %d dev_role %d)\n", __func__, + vusb->nports, vusb->host_role, vusb->device_role); + /* Only allocate/negotiate the virtqueue triplets this instance * actually needs: HOST_* only exists when host_role is negotiated, * DEV_* only when device_role is negotiated, ROLE_* only when both @@ -210,20 +224,45 @@ static int virtio_usb_probe(struct virtio_device *vdev) } } + if (vusb->device_role) { + INIT_WORK(&vusb->vq_dev_event_work, virtio_usb_dc_event_work); + INIT_WORK(&vusb->vq_dev_data_rx_work, virtio_usb_dc_data_work); + + /* Populate the shared device event queue before telling the + * backend we are ready, so a DEV_CONNECTED event can never + * race ahead of the driver having posted receive buffers. + */ + rc = virtio_usb_dc_event_populate(vusb); + if (rc) { + dev_err(&vdev->dev, + "%s virtio_usb_dc_event_populate() error(%d)\n", + __func__, rc); + goto on_error; + } + } + + virtio_device_ready(vdev); + /* Resolve every port's role. With only one role negotiated, every * port unambiguously has that role. With both negotiated, query - * each port's actual role individually via virtio_usb_rsw_get_role(), since - * it is otherwise ambiguous (host|device). + * each port's actual role - and, if switch_role is negotiated, + * whether the port supports switching - individually via + * virtio_usb_rsw_get_role(), since a port's own role is otherwise ambiguous + * (host|device). */ for (i = 0; i < vusb->nports; i++) { + vusb->vports[i].vusb = vusb; + spin_lock_init(&vusb->vports[i].vhc_lock); + if (vusb->host_role && !vusb->device_role) { vusb->vports[i].role = VIRTIO_USB_ROLE_HOST; } else if (vusb->device_role && !vusb->host_role) { vusb->vports[i].role = VIRTIO_USB_ROLE_DEVICE; } else { - u32 status, role; + u32 status, role, supported_role; - status = virtio_usb_rsw_get_role(vusb, i, &role); + status = virtio_usb_rsw_get_role(vusb, i, &role, + &supported_role); if (status != VIRTIO_USB_S_OK) { dev_err(&vdev->dev, "%s status(%d)\n", __func__, status); @@ -238,9 +277,27 @@ static int virtio_usb_probe(struct virtio_device *vdev) goto on_error; } vusb->vports[i].role = role; + vusb->vports[i].is_dual_role = + supported_role & + (1UL << VIRTIO_USB_F_SWITCH_ROLE); + + if (vusb->vports[i].is_dual_role && + !vusb->switch_role) { + dev_err(&vdev->dev, + "%s port%d switch_role not supported\n", + __func__, i); + rc = -EIO; + goto on_error; + } } } + for (i = 0; i < vusb->nports; i++) + dev_info(&vdev->dev, + "%s port[%d] VIRTIO_USB_F_%s is_dual_role %s\n", + __func__, i, vusb->vports[i].role ? "DEVICE" : "HOST", + vusb->vports[i].is_dual_role ? "TRUE" : "FALSE"); + if (vusb->host_role) { INIT_WORK(&vusb->vq_host_data_rx_work, virtio_usb_hc_rx_work); INIT_WORK(&vusb->vq_host_evt_work, virtio_usb_hc_evt_work); @@ -269,13 +326,9 @@ static int virtio_usb_probe(struct virtio_device *vdev) } } - if (vusb->device_role) { - INIT_WORK(&vusb->vq_dev_data_rx_work, virtio_usb_dc_data_work); - INIT_WORK(&vusb->vq_dev_event_work, virtio_usb_dc_event_work); - - for (i = 0; i < vusb->nports; i++) { - if (vusb->vports[i].role != VIRTIO_USB_ROLE_DEVICE) - continue; + for (i = 0; i < vusb->nports; i++) { + if (vusb->vports[i].is_dual_role || + vusb->vports[i].role == VIRTIO_USB_ROLE_DEVICE) { rc = virtio_usb_dc_init(vusb, i); if (rc) { dev_err(&vdev->dev, @@ -284,17 +337,27 @@ static int virtio_usb_probe(struct virtio_device *vdev) goto on_error; } } - rc = virtio_usb_dc_event_populate(vusb); - if (rc) { - dev_err(&vdev->dev, - "%s virtio_usb_dc_event_populate() error(%d)\n", - __func__, rc); - goto on_error; - } } - virtio_device_ready(vdev); + if (vusb->host_role && vusb->device_role) + if (virtio_usb_rsw_sysfs_init(vusb)) + goto on_error; + WRITE_ONCE(vusb->started, true); + /* The event queues are populated, and the device notified, before + * started is set. An event the device delivers in that window has + * its notification dropped by the notify callback, and with + * EVENT_IDX no further notification follows until the used ring is + * drained. Run the event workers once so it is not lost. + */ + if (vusb->host_role) + schedule_work(&vusb->vq_host_evt_work); + if (vusb->device_role) + schedule_work(&vusb->vq_dev_event_work); + if (vusb->rsw) + schedule_work(&vusb->rsw->event_process_work); + + dev_info(&vdev->dev, "%s returns %d\n", __func__, rc); return rc; on_error: @@ -314,6 +377,20 @@ static void virtio_usb_remove(struct virtio_device *vdev) struct virtio_usb *vusb = vdev->priv; int i; + /* Stop queue-driven workers from scheduling new activity. */ + WRITE_ONCE(vusb->started, false); + + /* Before the queues stop and the host VPs go away: a role switch + * in progress, from sysfs or from a ROLE_CHANGE event, may still + * create or destroy an HCD. started is already false, so the + * event work cannot be scheduled again; the role command queue is + * still running, so a role command it waits for completes or + * times out. + */ + virtio_usb_rsw_sysfs_deinit(vusb); + if (vusb->rsw) + cancel_work_sync(&vusb->rsw->event_process_work); + for (i = 0; i < vusb->nvqs; i++) vusb->vqueues[i].stop(vusb, &vusb->vqueues[i]); @@ -335,6 +412,7 @@ static void virtio_usb_remove(struct virtio_device *vdev) static const unsigned int virtio_usb_features[] = { VIRTIO_USB_F_HOST, VIRTIO_USB_F_DEVICE, + VIRTIO_USB_F_SWITCH_ROLE, }; static const struct virtio_device_id id_table[] = { diff --git a/drivers/usb/virtio_usb/controller.h b/drivers/usb/virtio_usb/controller.h index 6f39e4c5a4aa..d58cc09ee8fc 100644 --- a/drivers/usb/virtio_usb/controller.h +++ b/drivers/usb/virtio_usb/controller.h @@ -19,8 +19,9 @@ struct virtio_usb_hc_vp; /* Forward declaration - full definition in device.h */ struct virtio_usb_dc; -/* Forward declaration - full definition in role_switch.h */ +/* Forward declaration - full definitions in role_switch.h */ struct virtio_usb_rsw; +struct virtio_usb_port_rsw; #define VIRTIO_USB_VQ_COMMAND_IDX 0 #define VIRTIO_USB_VQ_EVENT_IDX 1 @@ -32,14 +33,35 @@ struct virtio_usb_rsw; /** * struct virtio_usb_port - Per-virtual-port state. + * @vusb: VirtIO usb device this port belongs to. + * @is_dual_role: True if this port supports dynamic role switching. * @role: Role of this port (VIRTIO_USB_ROLE_HOST or _DEVICE). + * @vhc_lock: Protects @vhc against concurrent role-switch init/deinit + * while the host event-processing worker is reading it, and + * protects @pending_evt and @pending_evt_mask. Only guards the + * pointer itself: the sleeping work of virtio_usb_hc_vp_init() + * and virtio_usb_hc_vp_deinit() (devm_kzalloc(), usb_add_hcd(), + * usb_remove_hcd()) happens outside this lock. * @vhc: Host controller - non-NULL when role is HOST. + * @pending_evt: Latest host port event per leaf port that arrived while + * @vhc was NULL. On a switch to host role the device may + * report the port as connected before the role switch path + * has installed @vhc; virtio_usb_hc_vp_init() replays these + * when it does. + * @pending_evt_mask: Bitmask of the valid @pending_evt slots. * @vudc: Device controller - non-NULL when role is DEVICE. + * @rsw: Per-port role-switch state - non-NULL when is_dual_role. */ struct virtio_usb_port { + struct virtio_usb *vusb; + bool is_dual_role; unsigned int role; + spinlock_t vhc_lock; struct virtio_usb_hc_vp *vhc; + struct virtio_usb_host_port_event pending_evt[VIRTIO_USB_VP_MAX_PORTS]; + unsigned long pending_evt_mask; struct virtio_usb_dc *vudc; + struct virtio_usb_port_rsw *rsw; }; /** @@ -64,6 +86,9 @@ struct virtio_usb_port { * virtio_usb_rsw_get_role(), since with both host_role and * device_role negotiated a port's own role is otherwise * ambiguous. + * @switch_role: flag indicating support for dynamically switching roles + * @started: True once probe() has finished bringing up every VP - guards + * notify callbacks against running before setup is complete. * @vq_host_data_rx_work: Kernel work draining the host data queue, shared * across every host-role VP. * @vq_host_evt_work: Kernel work draining the host event queue, shared @@ -79,13 +104,15 @@ struct virtio_usb { struct virtio_device *vdev; struct virtio_usb_queue *vqueues; struct virtio_usb_port *vports; - unsigned int nports; + u32 nports; u32 nvqs; bool host_role; bool device_role; int host_vq_base; int dev_vq_base; int role_vq_base; + bool switch_role; + bool started; struct work_struct vq_host_data_rx_work; struct work_struct vq_host_evt_work; struct work_struct vq_dev_data_rx_work; diff --git a/drivers/usb/virtio_usb/device.c b/drivers/usb/virtio_usb/device.c index af82a0e7e27e..0d44cb1dce6e 100644 --- a/drivers/usb/virtio_usb/device.c +++ b/drivers/usb/virtio_usb/device.c @@ -1644,6 +1644,8 @@ static void virtio_usb_dc_event_process(struct virtio_usb_event *event) break; } case VIRTIO_USB_EVT_DEV_DISCONNECTED: { + pr_info("%s port_id %d VIRTIO_USB_EVT_DEV_DISCONNECTED\n", + __func__, port_id); if (vudc->driver && vudc->driver->disconnect) vudc->driver->disconnect(&vudc->gadget); if (vudc->registered) @@ -1676,16 +1678,19 @@ static void virtio_usb_dc_event_process(struct virtio_usb_event *event) break; } case VIRTIO_USB_EVT_DEV_RESET: { + pr_info("%s VIRTIO_USB_EVT_DEV_RESET\n", __func__); if (driver) usb_gadget_udc_reset(&vudc->gadget, driver); break; } case VIRTIO_USB_EVT_DEV_SUSPEND: { + pr_info("%s VIRTIO_USB_EVT_DEV_SUSPEND\n", __func__); if (driver && driver->suspend) driver->suspend(&vudc->gadget); break; } case VIRTIO_USB_EVT_DEV_RESUME: { + pr_info("%s VIRTIO_USB_EVT_DEV_RESUME\n", __func__); if (driver && driver->resume) driver->resume(&vudc->gadget); break; @@ -1968,6 +1973,9 @@ static void virtio_usb_dc_evt_notify_cb(struct virtqueue *vqueue) { struct virtio_usb *vusb = vqueue->vdev->priv; + if (!READ_ONCE(vusb->started)) + return; + schedule_work(&vusb->vq_dev_event_work); } diff --git a/drivers/usb/virtio_usb/host.c b/drivers/usb/virtio_usb/host.c index b072c32ac0ee..27b45774b105 100644 --- a/drivers/usb/virtio_usb/host.c +++ b/drivers/usb/virtio_usb/host.c @@ -1116,6 +1116,10 @@ void virtio_usb_hc_rx_work(struct work_struct *work) spin_unlock_irq(&dataq->lock); } +static void +virtio_usb_hc_port_event_apply(struct virtio_usb_hc_vp *vhcd_vp, + const struct virtio_usb_host_port_event *evt); + /** * virtio_usb_hc_vp_init() - Initialize the host controller for one VP. * @vusb: VirtIO USB device @@ -1126,6 +1130,7 @@ void virtio_usb_hc_rx_work(struct work_struct *work) */ int virtio_usb_hc_vp_init(struct virtio_usb *vusb, unsigned int vp_idx) { + struct virtio_usb_port *vport = &vusb->vports[vp_idx]; struct virtio_usb_hc_vp *vhcd_vp; unsigned int i; int rc; @@ -1151,13 +1156,26 @@ int virtio_usb_hc_vp_init(struct virtio_usb *vusb, unsigned int vp_idx) for (i = 0; i < VIRTIO_USB_VQ_HOST_MAX; i++) vhcd_vp->hcqs[i] = &vusb->vqueues[vusb->host_vq_base + i]; - /* Install into the port before add_hcd so vhcd_vp->vusb is set */ - vusb->vports[vp_idx].vhc = vhcd_vp; + /* Install into the port before add_hcd so vhcd_vp->vusb is set. + * Replay any port event that arrived before this, under the same + * lock, so that it is applied before any event that sees vhc. + * hs/ss do not exist yet, so the replay only sets port status; + * the hub driver reads it when usb_add_hcd() registers the root + * hub. + */ + spin_lock(&vport->vhc_lock); + vport->vhc = vhcd_vp; + for_each_set_bit(i, &vport->pending_evt_mask, VIRTIO_USB_VP_MAX_PORTS) + virtio_usb_hc_port_event_apply(vhcd_vp, &vport->pending_evt[i]); + vport->pending_evt_mask = 0; + spin_unlock(&vport->vhc_lock); /* Add HCDs first so hs/ss are valid before any PORT_CONNECTED event */ rc = virtio_usb_add_hcd(vusb, vhcd_vp); if (rc) { + spin_lock(&vusb->vports[vp_idx].vhc_lock); vusb->vports[vp_idx].vhc = NULL; + spin_unlock(&vusb->vports[vp_idx].vhc_lock); return rc; } @@ -1173,7 +1191,11 @@ int virtio_usb_hc_vp_init(struct virtio_usb *vusb, unsigned int vp_idx) */ int virtio_usb_hc_vp_deinit(struct virtio_usb *vusb, unsigned int vp_idx) { - struct virtio_usb_hc_vp *vhcd_vp = vusb->vports[vp_idx].vhc; + struct virtio_usb_hc_vp *vhcd_vp; + + spin_lock(&vusb->vports[vp_idx].vhc_lock); + vhcd_vp = vusb->vports[vp_idx].vhc; + spin_unlock(&vusb->vports[vp_idx].vhc_lock); if (!vhcd_vp) return 0; @@ -1186,7 +1208,9 @@ int virtio_usb_hc_vp_deinit(struct virtio_usb *vusb, unsigned int vp_idx) vhcd_vp->ss = NULL; vhcd_vp->hs = NULL; + spin_lock(&vusb->vports[vp_idx].vhc_lock); vusb->vports[vp_idx].vhc = NULL; + spin_unlock(&vusb->vports[vp_idx].vhc_lock); return 0; } @@ -1202,9 +1226,6 @@ static void virtio_usb_hc_evt_process_one(struct virtio_usb_event *uevent) struct virtio_usb_host_port_event *evt; unsigned int vp_idx, port_id; struct virtio_usb_hc_vp *vhcd_vp; - struct virtio_usb_hc_port *port; - struct usb_hcd *hcd = NULL; - unsigned long iflags; evt = (struct virtio_usb_host_port_event *)virtio_usb_event_buf(uevent); vp_idx = le32_to_cpu(evt->vp_idx); @@ -1226,16 +1247,55 @@ static void virtio_usb_hc_evt_process_one(struct virtio_usb_event *uevent) return; } + /* vhc can be concurrently init/deinit'd by a role switch + * (virtio_usb_rsw_event_process() runs on its own workqueue) - + * vhc_lock protects only the pointer read itself; the vhcd_vp it + * points to remains valid for as long as we hold a reference to + * it here, since virtio_usb_hc_vp_deinit() only clears the + * vports[vp_idx].vhc pointer under the same lock, it does not + * free vhcd_vp itself (devm-managed, freed at device teardown). + */ + spin_lock(&vusb->vports[vp_idx].vhc_lock); vhcd_vp = vusb->vports[vp_idx].vhc; if (!vhcd_vp) { - dev_err_ratelimited( - &vusb->vdev->dev, - "virtio_usb: PORT event vp_idx %u not host-role, ignoring\n", - vp_idx); + /* No HCD (yet): on a switch to host role the device can + * report the port before the role switch path has created + * it. Keep the latest event per port for + * virtio_usb_hc_vp_init() to replay. + */ + vusb->vports[vp_idx].pending_evt[port_id] = *evt; + __set_bit(port_id, &vusb->vports[vp_idx].pending_evt_mask); + spin_unlock(&vusb->vports[vp_idx].vhc_lock); + dev_dbg(&vusb->vdev->dev, + "PORT event vp_idx %u port %u before HCD, deferred\n", + vp_idx, port_id); return; } + spin_unlock(&vusb->vports[vp_idx].vhc_lock); - port = &vhcd_vp->ports[port_id]; + virtio_usb_hc_port_event_apply(vhcd_vp, evt); +} + +/** + * virtio_usb_hc_port_event_apply() - Update a root hub port from an event. + * @vhcd_vp: host controller of the event's VP + * @evt: VIRTIO_USB_EVT_HOST_PORT_CONNECTED or _DISCONNECTED, validated + * + * Polls the root hub only if the HCD for the port's speed exists; when + * called from virtio_usb_hc_vp_init() before the HCDs are added, the + * hub driver reads the port status when the root hub is registered. + * + * Context: Any context. + */ +static void +virtio_usb_hc_port_event_apply(struct virtio_usb_hc_vp *vhcd_vp, + const struct virtio_usb_host_port_event *evt) +{ + struct virtio_usb_hc_port *port; + struct usb_hcd *hcd = NULL; + unsigned long iflags; + + port = &vhcd_vp->ports[le32_to_cpu(evt->port)]; spin_lock_irqsave(&port->lock, iflags); switch (le32_to_cpu(evt->code)) { @@ -1315,10 +1375,12 @@ static void virtio_usb_hc_evt_process_one(struct virtio_usb_event *uevent) * @work: kernel work item embedded in struct virtio_usb. * * The host event queue is shared across all host-role VPs and its VP - * may not even exist yet at probe time (e.g. a dual-role instance - * where every port currently reports device role), so events are - * drained and processed here, in process context, rather than - * directly inside the interrupt-context notify callback. + * may not even exist yet (or may be concurrently torn down by a + * role switch), so events are drained and processed here, in process + * context, instead of directly inside the interrupt-context notify + * callback - this lets virtio_usb_hc_evt_process_one() safely take + * vhc_lock without needing an atomic-context-safe primitive on the + * writer side (virtio_usb_hc_vp_init()/_deinit() sleep). * * Context: Process context. */ @@ -1358,7 +1420,11 @@ static void virtio_usb_hc_dataq_stop_cb(struct virtio_usb *vusb, cancel_work_sync(&vusb->vq_host_data_rx_work); for (vp_idx = 0; vp_idx < vusb->nports; vp_idx++) { - struct virtio_usb_hc_vp *vhcd_vp = vusb->vports[vp_idx].vhc; + struct virtio_usb_hc_vp *vhcd_vp; + + spin_lock(&vusb->vports[vp_idx].vhc_lock); + vhcd_vp = vusb->vports[vp_idx].vhc; + spin_unlock(&vusb->vports[vp_idx].vhc_lock); if (!vhcd_vp) continue; @@ -1429,6 +1495,9 @@ static void virtio_usb_hc_evt_notify_cb(struct virtqueue *vqueue) { struct virtio_usb *vusb = vqueue->vdev->priv; + if (!READ_ONCE(vusb->started)) + return; + schedule_work(&vusb->vq_host_evt_work); } @@ -1458,6 +1527,9 @@ static void virtio_usb_host_data_notify_cb(struct virtqueue *vqueue) { struct virtio_usb *vusb = vqueue->vdev->priv; + if (!READ_ONCE(vusb->started)) + return; + schedule_work(&vusb->vq_host_data_rx_work); } diff --git a/drivers/usb/virtio_usb/role_switch.c b/drivers/usb/virtio_usb/role_switch.c index 50b5d645abf4..84387d20b96c 100644 --- a/drivers/usb/virtio_usb/role_switch.c +++ b/drivers/usb/virtio_usb/role_switch.c @@ -7,11 +7,341 @@ #include #include "controller.h" +#include "host.h" #include "role_switch.h" #include "vq_common.h" +// for usb_role enum from include/linux/usb/role.h +static const char * const role_switch_role_names[] = { + "USB_ROLE_NONE", "USB_ROLE_HOST", "USB_ROLE_DEVICE" +}; + +/** + * virtio_usb_rsw_role_set() - Ask the device to put a port into a role. + * @vusb: VirtIO USB device. + * @port_id: Dual-role port. + * @role: Target role, VIRTIO_USB_ROLE_HOST or VIRTIO_USB_ROLE_DEVICE. + * + * ROLE_SET is idempotent: the device performs the whole transition before it + * replies, and replies OK without doing anything if the port is already in + * @role. + * + * Context: Process context. + * Return: 0 on success, -errno on failure. + */ +static int virtio_usb_rsw_role_set(struct virtio_usb *vusb, u32 port_id, + u32 role) +{ + struct virtio_usb_role_set *request; + struct virtio_usb_cmd *cmd; + int rc; + + cmd = virtio_usb_cmd_alloc(sizeof(*request), + sizeof(struct virtio_usb_cmd_status), + GFP_KERNEL); + if (!cmd) + return -ENOMEM; + + request = virtio_usb_cmd_request(cmd); + request->hdr.code = cpu_to_le32(VIRTIO_USB_CMD_ROLE_SET); + request->hdr.port = cpu_to_le32(port_id); + request->role = cpu_to_le32(role); + cmd->msg.queue = vusb->rsw->oqs[VIRTIO_USB_VQ_COMMAND_IDX]; + + rc = virtio_usb_cmd_send_sync(vusb, NULL, NULL, cmd); + if (rc) + pr_err("%s port %u: virtio_usb_cmd_send_sync() error %d\n", + __func__, port_id, rc); + + return rc; +} + +/** + * virtio_usb_rsw_sync_locked() - Bring a port in line with the device's role. + * @vusb: VirtIO USB device. + * @port_id: Dual-role port. + * + * Reads the port's role from the device and, if it differs from the cached + * one, creates or destroys the port's HCD accordingly. Used both after a + * guest ROLE_SET and for a ROLE_CHANGE event; if the role did not change it + * does nothing, so handling the same transition twice is harmless. + * + * Whether the port is dual-role is fixed at probe time and not updated + * here: the role switch was registered based on it, and is unregistered + * on remove regardless of what the device reports later. + * + * Context: Process context, vport->rsw->lock held. + * Return: 0 on success, -errno on failure. + */ +static int virtio_usb_rsw_sync_locked(struct virtio_usb *vusb, u32 port_id) +{ + struct virtio_usb_port *vport = &vusb->vports[port_id]; + u32 status, role, supported_role, old_role = vport->role; + int rc; + + lockdep_assert_held(&vport->rsw->lock); + + status = virtio_usb_rsw_get_role(vusb, port_id, &role, &supported_role); + if (status != VIRTIO_USB_S_OK) { + pr_err("%s port %u: virtio_usb_rsw_get_role status %d\n", + __func__, port_id, status); + return -EIO; + } + if (role != VIRTIO_USB_ROLE_HOST && role != VIRTIO_USB_ROLE_DEVICE) + return -EIO; + + /* A port's usb_hcd/root hub is only supposed to exist while that + * port is actually in host role - it's immediately visible to the + * rest of the kernel (lsusb, udev, ...) the moment usb_add_hcd() + * runs, unlike the device-role side's vudc, which stays dormant + * and kernel-invisible until a later BIND event. So, unlike vudc + * (already unconditionally pre-allocated for every dual-role + * port at probe time, regardless of its current role - see + * virtio_usb_probe()), vhc must be created/destroyed dynamically, + * exactly at the moment a port's role actually changes. + */ + if (role != old_role && role == VIRTIO_USB_ROLE_HOST) { + rc = virtio_usb_hc_vp_init(vusb, port_id); + if (rc) { + pr_err("%s virtio_usb_hc_vp_init() port=%u error(%d)\n", + __func__, port_id, rc); + /* Leave vport->role at its old value: reporting a + * host role with no working HCD behind it would be + * worse than not switching at all. + */ + return rc; + } + } else if (role != old_role && old_role == VIRTIO_USB_ROLE_HOST) { + virtio_usb_hc_vp_deinit(vusb, port_id); + } + + WRITE_ONCE(vport->role, role); + if (role != old_role) + pr_info("%s port %u: the new role (%s) is set\n", __func__, + port_id, + role == VIRTIO_USB_ROLE_DEVICE ? + "VIRTIO_USB_ROLE_DEVICE" : + "VIRTIO_USB_ROLE_HOST"); + + return 0; +} + +static int vusb_set_role_cb(struct usb_role_switch *sw, enum usb_role role) +{ + struct virtio_usb_port *vport = usb_role_switch_get_drvdata(sw); + struct virtio_usb_port_rsw *vport_rsw = vport->rsw; + int rc, sync_rc; + u32 target; + + pr_info("%s set_role to %s\n", __func__, role_switch_role_names[role]); + + switch (role) { + case USB_ROLE_HOST: + target = VIRTIO_USB_ROLE_HOST; + break; + case USB_ROLE_DEVICE: + target = VIRTIO_USB_ROLE_DEVICE; + break; + default: + /* A virtio-usb port is always either host or device. */ + return -EINVAL; + } + + /* The device completes the transition before it answers ROLE_SET, + * so do the whole switch here, under the port lock: a concurrent + * request or ROLE_CHANGE event waits for it and then sees the new + * role. ROLE_SET is sent even if the cached role already matches, + * so a role change whose event was lost is picked up here too. + * + * Resync even if ROLE_SET failed: on a timeout or a signal the + * device may still have switched (or be about to), and the cached + * role and the HCD must follow what the device actually reports. + * Report the ROLE_SET error to the caller in that case. + */ + mutex_lock(&vport_rsw->lock); + rc = virtio_usb_rsw_role_set(vport_rsw->vusb, vport_rsw->port_id, + target); + sync_rc = + virtio_usb_rsw_sync_locked(vport_rsw->vusb, vport_rsw->port_id); + mutex_unlock(&vport_rsw->lock); + + return rc ? rc : sync_rc; +} + +static enum usb_role vusb_get_role_cb(struct usb_role_switch *sw) +{ + struct virtio_usb_port *vport = usb_role_switch_get_drvdata(sw); + + switch (READ_ONCE(vport->role)) { + case VIRTIO_USB_ROLE_HOST: + return USB_ROLE_HOST; + case VIRTIO_USB_ROLE_DEVICE: + return USB_ROLE_DEVICE; + default: + return USB_ROLE_NONE; + } +} + +static void virtio_usb_rsw_event_process(struct virtio_usb_event *event) +{ + struct virtio_usb *vusb = event->vusb; + struct virtio_usb_role_event *evt = virtio_usb_event_buf(event); + u32 port_id = le32_to_cpu(evt->port); + struct virtio_usb_port *vport; + int rc; + + if (le32_to_cpu(evt->code) != VIRTIO_USB_EVT_ROLE_CHANGE) { + pr_err("%s wrong event code %d\n", __func__, + le32_to_cpu(evt->code)); + return; + } + + if (!vusb->vports || port_id >= vusb->nports) { + pr_err("%s port %u invalid (nports=%u)\n", __func__, port_id, + vusb->nports); + return; + } + vport = &vusb->vports[port_id]; + + /* A role switch only exists for ports that support switching (see + * virtio_usb_rsw_sysfs_init()); a ROLE_CHANGE for any other port is + * a backend bug - ignore it rather than dereferencing NULL. + */ + if (!vport->rsw || !vport->rsw->sw) { + pr_err("%s ROLE_CHANGE for non-switchable port %u\n", __func__, + port_id); + return; + } + + pr_info("%s port %u VIRTIO_USB_EVT_ROLE_CHANGE\n", __func__, port_id); + + /* Either a device-initiated switch, or the echo of a guest ROLE_SET + * that vusb_set_role_cb() has already handled. + */ + mutex_lock(&vport->rsw->lock); + rc = virtio_usb_rsw_sync_locked(vusb, port_id); + mutex_unlock(&vport->rsw->lock); + if (rc) + pr_err("%s port %u: sync error %d\n", __func__, port_id, rc); +} + +/** + * virtio_usb_rsw_event_work() - role event queue receive worker. + * @work: Kernel work to handle event completion. + * + * Context: Process context. + */ +static void virtio_usb_rsw_event_work(struct work_struct *work) +{ + struct virtio_usb_rsw *rsw = + container_of(work, struct virtio_usb_rsw, event_process_work); + struct virtio_usb_queue *evtq = rsw->oqs[VIRTIO_USB_VQ_EVENT_IDX]; + + virtio_usb_evt_work(evtq, virtio_usb_rsw_event_process); +} + +/** + * virtio_usb_rsw_event_populate() - Add events to the role event queue. + * @vusb: VirtIO USB device. + * + * Context: Any context. + * Return: 0 on success -errno on failure. + */ +static int virtio_usb_rsw_event_populate(struct virtio_usb *vusb) +{ + struct virtio_usb_queue *evt_queue = + vusb->rsw->oqs[VIRTIO_USB_VQ_EVENT_IDX]; + struct virtio_usb_event *events; + + events = virtio_usb_events_alloc(vusb, evt_queue, + sizeof(struct virtio_usb_role_event)); + if (!events) + return -ENOMEM; + + return virtio_usb_events_populate(events); +} + +/** + * virtio_usb_rsw_sysfs_deinit() - Unregister the per-port role switches. + * @vusb: VirtIO USB device. + * + * Must run before the host VPs are torn down: unregistering waits for a + * vusb_set_role_cb() in progress, which may create or destroy a port's HCD, + * and no new one can start afterwards. + * + * Context: Process context. + */ +void virtio_usb_rsw_sysfs_deinit(struct virtio_usb *vusb) +{ + if (!vusb->vports) + return; + + for (int i = 0; i < vusb->nports; ++i) { + struct virtio_usb_port *vport = &vusb->vports[i]; + + /* Only what was actually registered: a probe failure before + * virtio_usb_rsw_sysfs_init() leaves rsw NULL, a failed or + * earlier deinit leaves sw NULL. + */ + if (!vport->rsw || !vport->rsw->sw) + continue; + + usb_role_switch_unregister(vport->rsw->sw); + vport->rsw->sw = NULL; + kfree(vport->rsw->sysfs_name); + vport->rsw->sysfs_name = NULL; + } +} + +static int rsw_vport_init(struct virtio_usb *vusb, int port_id) +{ + struct device *dev = &vusb->vdev->dev; + struct virtio_usb_port *vport = &vusb->vports[port_id]; + struct virtio_usb_port_rsw *vport_rsw = vport->rsw; + struct usb_role_switch_desc desc = { 0 }; + + /* Reuse the devm allocation of an earlier probe of this device. */ + if (!vport_rsw) { + vport_rsw = devm_kzalloc(dev, sizeof(*vport_rsw), GFP_KERNEL); + if (!vport_rsw) + return -ENOMEM; + mutex_init(&vport_rsw->lock); + } + + vport_rsw->vusb = vusb; + vport_rsw->port_id = port_id; + vport_rsw->sysfs_name = kasprintf(GFP_KERNEL, "port%u", port_id); + + desc.name = vport_rsw->sysfs_name; + desc.set = vusb_set_role_cb; + desc.get = vusb_get_role_cb; + desc.driver_data = vport; + desc.fwnode = NULL; + desc.allow_userspace_control = true; + + /* vusb_set_role_cb() can be called as soon as the switch is + * registered, so vport->rsw must already be set. + */ + vport->rsw = vport_rsw; + vport_rsw->sw = usb_role_switch_register(dev, &desc); + if (IS_ERR(vport_rsw->sw)) { + int rc = PTR_ERR(vport_rsw->sw); + + dev_err(dev, "port%u: usb_role_switch_register() failed: %d\n", + port_id, rc); + vport_rsw->sw = NULL; + kfree(vport_rsw->sysfs_name); + vport_rsw->sysfs_name = NULL; + vport->rsw = NULL; + return rc; + } + + return 0; +} + int virtio_usb_rsw_init(struct virtio_usb *vusb) { + int rc; struct virtio_usb_rsw *rsw = devm_kzalloc(&vusb->vdev->dev, sizeof(*rsw), GFP_KERNEL); unsigned int i; @@ -24,9 +354,35 @@ int virtio_usb_rsw_init(struct virtio_usb *vusb) for (i = 0; i < VIRTIO_USB_VQ_ROLE_MAX; i++) rsw->oqs[i] = &vusb->vqueues[vusb->role_vq_base + i]; - mutex_init(&rsw->lock); - init_completion(&rsw->completion); + INIT_WORK((struct work_struct *)&rsw->event_process_work, + virtio_usb_rsw_event_work); + + rc = virtio_usb_rsw_event_populate(vusb); + if (rc) + return rc; + + return 0; +} +int virtio_usb_rsw_sysfs_init(struct virtio_usb *vusb) +{ + int i, rc; + + for (i = 0; i < vusb->nports; i++) + if (vusb->vports[i].is_dual_role) { + /* Skip if still registered - probe may be retried + * after a Virtio reset and the role switch device + * persists across retries. Calling + * usb_role_switch_register() again would return + * -EEXIST from device_register(). If it was + * unregistered, register it again. + */ + if (vusb->vports[i].rsw && vusb->vports[i].rsw->sw) + continue; + rc = rsw_vport_init(vusb, i); + if (rc) + return rc; + } return 0; } @@ -37,55 +393,72 @@ void virtio_usb_rsw_deinit(struct virtio_usb *vusb) if (!rsw) return; - /* Wake potential role command waiters before releasing role objects. */ - complete_all(&rsw->completion); - + /* + * The role switches are already unregistered by + * virtio_usb_rsw_sysfs_deinit(), and event_process_work is already + * cancelled, both earlier in virtio_usb_remove(). + */ vusb->rsw = NULL; } +/** + * virtio_usb_rsw_evt_notify_cb() - role event virtqueue notification callback + * @vqueue: Underlying event virtqueue. + * + * This callback function is called upon a vring interrupt request from the + * device. + * + * Context: Interrupt context. + */ +static void virtio_usb_rsw_evt_notify_cb(struct virtqueue *vqueue) +{ + struct virtio_usb *vusb = vqueue->vdev->priv; + + if (!READ_ONCE(vusb->started) || !vusb->rsw) + return; + + schedule_work(&vusb->rsw->event_process_work); +} + /* Send a role command and get a response. * * The function is implemented as synchronous. Design pattern is * virtio_can.c/virtio_can_send_ctrl_msg() */ -u32 virtio_usb_rsw_get_role(struct virtio_usb *vusb, int port_id, u32 *role) +u32 virtio_usb_rsw_get_role(struct virtio_usb *vusb, int port_id, u32 *role, + u32 *supported_role) { - struct scatterlist sg_out, sg_in, *sgs[2] = { &sg_out, &sg_in }; - struct virtqueue *vq = - vusb->rsw->oqs[VIRTIO_USB_VQ_COMMAND_IDX]->vqueue; - unsigned int len; + struct virtio_usb_role_cmd_hdr *hdr; + struct virtio_usb_role_info *resp; + struct virtio_usb_cmd *cmd; u32 status = VIRTIO_USB_S_ERR_INTERNAL; + int rc; - struct role_get_msg { - struct virtio_usb_role_cmd_hdr cmd_hdr; - struct virtio_usb_role_info cmd_role; - } *msg = kzalloc(sizeof(*msg), GFP_KERNEL); - - if (!msg) + cmd = virtio_usb_cmd_alloc(sizeof(*hdr), sizeof(*resp), GFP_KERNEL); + if (!cmd) return status; - msg->cmd_hdr.code = cpu_to_le32(VIRTIO_USB_CMD_ROLE_GET); - msg->cmd_hdr.port = cpu_to_le32(port_id); - sg_init_one(&sg_out, &msg->cmd_hdr, sizeof(msg->cmd_hdr)); - sg_init_one(&sg_in, &msg->cmd_role, sizeof(msg->cmd_role)); + hdr = virtio_usb_cmd_request(cmd); + hdr->code = cpu_to_le32(VIRTIO_USB_CMD_ROLE_GET); + hdr->port = cpu_to_le32(port_id); + cmd->msg.queue = vusb->rsw->oqs[VIRTIO_USB_VQ_COMMAND_IDX]; - mutex_lock(&vusb->rsw->lock); + virtio_usb_cmd_ref(cmd); - if (virtqueue_add_sgs(vq, sgs, 1u, 1u, msg, GFP_ATOMIC)) { - pr_err("%s virtqueue_add_sgs error\n", __func__); - goto exit; - } + rc = virtio_usb_cmd_send_sync(vusb, NULL, NULL, cmd); - if (!virtqueue_kick(vq)) { - pr_err("%s virtqueue_kick error\n", __func__); - goto exit; + if (rc) { + pr_err("%s virtio_usb_cmd_send_sync() error %d\n", __func__, + rc); + virtio_usb_cmd_unref(cmd); + return status; } - while (!virtqueue_get_buf(vq, &len) && !virtqueue_is_broken(vq)) - wait_for_completion(&vusb->rsw->completion); - - status = le32_to_cpu(msg->cmd_role.status.code); - *role = le32_to_cpu(msg->cmd_role.role); + resp = virtio_usb_cmd_response(cmd); + status = le32_to_cpu(resp->status.code); + *role = le32_to_cpu(resp->role); + *supported_role = le32_to_cpu(resp->supported_role); + virtio_usb_cmd_unref(cmd); if (*role != VIRTIO_USB_ROLE_HOST && *role != VIRTIO_USB_ROLE_DEVICE) { pr_err("%s - wrong role (%d)\n", __func__, *role); @@ -96,71 +469,32 @@ u32 virtio_usb_rsw_get_role(struct virtio_usb *vusb, int port_id, u32 *role) "VIRTIO_USB_ROLE_DEVICE"); } -exit: - kfree(msg); - mutex_unlock(&vusb->rsw->lock); return status; } -static void virtio_usb_rsw_cmd_notify_cb(struct virtqueue *vqueue) -{ - struct virtio_usb *vusb = vqueue->vdev->priv; - - if (!vusb->rsw) - return; - - complete(&vusb->rsw->completion); -} - -static void virtio_usb_rsw_cmdq_stop_cb(struct virtio_usb *vusb, - struct virtio_usb_queue *vq) -{ - unsigned long flags; - - if (!vusb->rsw || !vq->vqueue) - return; - - /* - * Wake sleepers in role synchronous command paths so they can - * observe started=false and exit. - */ - complete_all(&vusb->rsw->completion); - - spin_lock_irqsave(&vq->lock, flags); - virtqueue_disable_cb(vq->vqueue); - spin_unlock_irqrestore(&vq->lock, flags); -} - static void virtio_usb_rsw_evtq_stop_cb(struct virtio_usb *vusb, struct virtio_usb_queue *vq) { - unsigned long flags; - u32 length; - void *buf; - - if (!vq->vqueue) - return; - - /* The role event queue is not populated yet at this stage (no - * VIRTIO_USB_F_SWITCH_ROLE negotiation, no ROLE_CHANGE events), - * so this only has to make sure del_vqs() finds the ring empty. + /* + * Now that virtio_usb_rsw_get_role()/virtio_usb_rsw_role_set() go + * through the common, timeout-protected virtio_usb_cmd_send_sync() + * instead of blocking indefinitely on virtqueue_is_broken(), it's + * safe to cancel event_process_work directly here, same as every + * other role's own evtq stop callback. */ - spin_lock_irqsave(&vq->lock, flags); - virtqueue_disable_cb(vq->vqueue); - while ((buf = virtqueue_get_buf(vq->vqueue, &length))) - ; - spin_unlock_irqrestore(&vq->lock, flags); + virtio_usb_evt_drain_stop_cb( + vq, vusb->rsw ? &vusb->rsw->event_process_work : NULL); } const struct virtio_usb_vq_desc role_vqueues[VIRTIO_USB_VQ_ROLE_MAX] = { [VIRTIO_USB_VQ_COMMAND_IDX] = { - .callback = virtio_usb_rsw_cmd_notify_cb, + .callback = virtio_usb_cmd_notify_cb, .name = "virtusb-role-cmd", - .process = NULL, - .stop = virtio_usb_rsw_cmdq_stop_cb, + .process = virtio_usb_cmd_process_cb, + .stop = virtio_usb_cmdq_stop_cb, }, [VIRTIO_USB_VQ_EVENT_IDX] = { - .callback = NULL, + .callback = virtio_usb_rsw_evt_notify_cb, .name = "virtusb-role-evt", .process = NULL, .stop = virtio_usb_rsw_evtq_stop_cb, diff --git a/drivers/usb/virtio_usb/role_switch.h b/drivers/usb/virtio_usb/role_switch.h index e3c8031686c3..13b270f315c6 100644 --- a/drivers/usb/virtio_usb/role_switch.h +++ b/drivers/usb/virtio_usb/role_switch.h @@ -8,18 +8,31 @@ #ifndef VIRTIO_USB_ROLE_SWITCH_H #define VIRTIO_USB_ROLE_SWITCH_H +#include #include "controller.h" int virtio_usb_rsw_init(struct virtio_usb *vusb); +int virtio_usb_rsw_sysfs_init(struct virtio_usb *vusb); +void virtio_usb_rsw_sysfs_deinit(struct virtio_usb *vusb); void virtio_usb_rsw_deinit(struct virtio_usb *vusb); u32 virtio_usb_rsw_get_role(struct virtio_usb *vusb, int port_id, - u32 *role); + u32 *role, u32 *supported_role); -struct virtio_usb_rsw { +struct virtio_usb_port_rsw { struct virtio_usb *vusb; + /* Serializes role transitions of this port (guest ROLE_SET and + * ROLE_CHANGE events); protects the port's role and HCD lifecycle. + */ struct mutex lock; - struct completion completion; + struct usb_role_switch *sw; + char *sysfs_name; + int port_id; +}; + +struct virtio_usb_rsw { + struct virtio_usb *vusb; struct virtio_usb_queue *oqs[VIRTIO_USB_VQ_ROLE_MAX]; + struct work_struct event_process_work; }; extern const struct virtio_usb_vq_desc role_vqueues[VIRTIO_USB_VQ_ROLE_MAX]; -- 2.49.0