From nobody Sat Jun 13 06:06:38 2026 Received: from mail.nessuent.net (mail.nessuent.net [188.245.177.90]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 339F62571C7; Sat, 9 May 2026 14:47:43 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=188.245.177.90 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1778338065; cv=none; b=JTHKwDScg0UMvBmIM1MeJSymCL2TbKFqCBRV8O1MeE8yF/FTIHelJVBbsh2pF5pNnsA8lPvwcXCr72S/MZiKn5ugkFG6SkLcxTPQiyhe3nvruIT1qe5ZYNyg5bwsTpXlSgweqI6tGk17t1dI8kZxNKDmked17EQBiOREYXPt22A= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1778338065; c=relaxed/simple; bh=jbzi2Emj0Xf9BmoPlY0PU4j/8PVZ/5uK5OX2z0vqwIQ=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=KAqr9F7NG+8v1XXvrV86kCbcJWsBtYsZf85RzxWHOqgqjQXkCrit7H1440yRxt2+MpOFVhwvOCBcO5A8DnqJZcanQlwzuSBXi+VbfwZwVpFgGCfSf6WLe+ReZQTfrEF9yODl2edn3CkY7lt5A6B5jbtEOUzfQw+HyG2Rai4f7eg= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=pitsidianak.is; spf=pass smtp.mailfrom=pitsidianak.is; dkim=pass (4096-bit key) header.d=pitsidianak.is header.i=@pitsidianak.is header.b=IFWvEHVq; arc=none smtp.client-ip=188.245.177.90 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=pitsidianak.is Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=pitsidianak.is Authentication-Results: smtp.subspace.kernel.org; dkim=pass (4096-bit key) header.d=pitsidianak.is header.i=@pitsidianak.is header.b="IFWvEHVq" DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=pitsidianak.is; s=mailSelector; t=1778338055; bh=jbzi2Emj0Xf9BmoPlY0PU4j/8PVZ/5uK5OX2z0vqwIQ=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From:Subject; b=IFWvEHVqRN+dbqESIEPH8cTPJG/YquOkq1iOSQhwNhJoqAwDsOMD+MocZakkJLfJT f9LPZPOA0r/ODpNCAWtQtwek+6bRf0aIIchTvX9rAqj5tjm87VGlSpmK3Gy1mMH0x+ KCc5deYIUIxNphOrgqlYIlOCaJnT1aZBdI1yhtKLF7xzkdYC0/EwOtYKP0DdcKuKjV K3KPxEiOBYlDZqT2FMzxb4p4u82C3XlR+VsGqNZltGTzG2vWAs9/5n9+ekKuSxUkX2 DA7+cvt+U2MitF+SIrGnvWPuW12JOABcwVRl5n35lBZYlmDsyCwHpRP63i5133vcA1 8NgHjtws5koyhsjMzz+C2RzUTF09Fw981qFvRHoNH1nvGSAi2sW5bUG3jqnTNhZ6oy h3sWx/tfB+R4OEefhOAej30fDTzCOjfXKD0Fyo8lpXZZ7fs7fpejJmMSNdpxHYpmFl I+hbOZ9LL9t84sLWjj7nHzlZriXQlHe69fm6VJlf3E3YgJ2ymvcYU93Bpf1MWaua5R +h6ZTuRIxQvi9qAoYP6q6Y1vO6vDWxbNqkSQvuFohcx7rDgm7BW1yWEDwfVopzHwkS 0CyYOcEHSeo23NBBTXE1XS3y7xtW4BXVbCyX/7cHQch2TBX8gE5/beFo5FNn/WlrRi V/ZvJY3pRggvCK0i0BGZfBJs= From: Manos Pitsidianakis Date: Sat, 09 May 2026 17:46:55 +0300 Subject: [PATCH RFC v2 1/6] rust/bindings: generate virtio bindings Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20260509-rust-virtio-v2-1-c1e30ec2bd21@pitsidianak.is> References: <20260509-rust-virtio-v2-0-c1e30ec2bd21@pitsidianak.is> In-Reply-To: <20260509-rust-virtio-v2-0-c1e30ec2bd21@pitsidianak.is> To: Miguel Ojeda Cc: Manos Pitsidianakis , Peter Hilber , Stefano Garzarella , Stefan Hajnoczi , Viresh Kumar , "Michael S. Tsirkin" , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , rust-for-linux@vger.kernel.org, Jason Wang , Xuan Zhuo , =?utf-8?q?Eugenio_P=C3=A9rez?= , virtualization@lists.linux.dev, linux-kernel@vger.kernel.org, Manos Pitsidianakis X-Developer-Signature: v=1; a=openpgp-sha256; l=834; i=manos@pitsidianak.is; h=from:subject:message-id; bh=jbzi2Emj0Xf9BmoPlY0PU4j/8PVZ/5uK5OX2z0vqwIQ=; b=LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tCgpvd0VCYkFLVC9aQU5Bd0FLQVhjcHgzQi9mZ 25RQWNzbVlnQnAvMGtDUGloZ1VPNXRrc1RZc1hRWDJzQTdsV01VCnA2T2Q0Mm5UZnVBd2RJdnlR d3lKQWpJRUFBRUtBQjBXSVFUTVhCdE9SS0JXODRkd0hSQjNLY2R3ZjM0SjBBVUMKYWY5SkFnQUt DUkIzS2Nkd2YzNEowRHRTRC9VWEhZaEpQNnZnMVY3eER3bWVMMDNPbWNXQ0xPTFd1WWg0VXY2MA preDQxRFU2NC8xb2xDcFk2T2RGb21HV04xOExwSVlMcWsyNk1WNGQvUUd3V2J0UjViZlJOYjhid nBQb3dQNlduCjV0YXBSS0s3Q3l4azgxSXBVelpld3ZuUWRYODhmL01ZcXRiN1BheXVMN1ErN3Bn b21aR0pLd2RoV3pVNEpqR2EKc0Nqd2lhT0pKVDU4Q0loZjUzbXNBdDlzbjlaM0kwMElsTWp0a1h pTHlOSnFRbWo2ZlAvNDJCOUdCSXRoU3lnVQpYK1M2bU1DMXN1S2s3a2pIbkN1VDk0R0U4R2Y3UF dFZW1sQzdyMmwyZVJxc0hRVDRvbjdkWXJ6Tmd6M2lFUnRICnV3U3lqeWN4MHc1RHJxZjY2QktNT UlLK2lTMnZVdDlVVUpIWXV0TktOU3hXbU5acmZUVW02SUdJVWZTaVQ2UUMKbGp6UnJQQW9kbG1O VVI4RE92VmN0cHlMRHV0RHJYR0dMYXdGT1lsQUZNdkk1VVpjdmZGVkpPSGtNRDZlVEVDOApWZkt ka0pjSkRrQzRySnd0N1V0bFFTaDFIUFlId3VLcjhQcjBiNWpUaGdOMTJiZHZSclRDUGRwQnJGNU FEaGI5CjZVbGdCM3VyRWxReDcxU3Z6U2dIT0F6UmJtS1dLbW10UVJ3L1ZuZWJpdVMrdmVWeW1qM DZabHF2TjlRbTlFZm4KSDQzcHlBd29NWjZNSmUwZTlUODVHbjlRRE5HaERES0VDWlNDL2tTV25Y S2hkalUwdHQvdkhNdTdrdi9mVmhkaAo4TTMrSFJvWXMxS1B4UUFXWmZqTUpDQ04yUG5PcnozNkF 1RG1uY3Rrb2c1QUQyYlNRcTlOY2hacDZITWxXZVJZCmtSUE4KPTkxaFUKLS0tLS1FTkQgUEdQIE 1FU1NBR0UtLS0tLQo= X-Developer-Key: i=manos@pitsidianak.is; a=openpgp; fpr=7C721DF9DB3CC7182311C0BF68BC211D47B421E1 Add virtio headers if CONFIG_VIRTIO is enabled. Signed-off-by: Manos Pitsidianakis --- rust/bindings/bindings_helper.h | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helpe= r.h index 083cc44aa952c2b29ab82d5d481063a1cf48bccf..1cbe1a4b5647fd646c1be3c5c80= fb24ae7b97a4a 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -151,3 +151,8 @@ const vm_flags_t RUST_CONST_HELPER_VM_NOHUGEPAGE =3D VM= _NOHUGEPAGE; #include "../../drivers/android/binder/rust_binder_events.h" #include "../../drivers/android/binder/page_range_helper.h" #endif + +#if IS_ENABLED(CONFIG_VIRTIO) +#include +#include +#endif /* IS_ENABLED(CONFIG_VIRTIO) */ --=20 2.47.3 From nobody Sat Jun 13 06:06:38 2026 Received: from mail.nessuent.net (mail.nessuent.net [188.245.177.90]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 22F2E3932E1; Sat, 9 May 2026 14:47:44 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=188.245.177.90 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1778338066; cv=none; b=ATy72i32xz8l9gqvRPTWCuhoOjjUzL55vAEcEupjb2708Mga8aWycoh9vnIri2j1LxoTmoykfIq10B/KeLLh+c+QxvPodhK9xdIYdIc6edt92NGiTrpblZR/Z6/Ndc/I2ucajORARoDvZ+Cuxs5hkwcVU+HC1hpPATpgtSumjCc= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1778338066; c=relaxed/simple; bh=rSVMrHdXXMPOdNSzrMYHYbcWyiA/ND/D3nfYFJ1b2Bw=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=tvyKvCbCoAn4VFsH7mZu3uhDhueOkAqgZpRF2j6IjL8+TZ6BWwQbHihAKVrwFPotbLIe3+YVyPDy94APne6Rf53WSeg58fH10FSXKrqu1R0JhMKdUP/1GezC5ADMHtceYUrayXNlek9vZy81zvLmdmxOd1/xh7XBp7OxEfOaEOg= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=pitsidianak.is; spf=pass smtp.mailfrom=pitsidianak.is; dkim=pass (4096-bit key) header.d=pitsidianak.is header.i=@pitsidianak.is header.b=wBPLPVks; arc=none smtp.client-ip=188.245.177.90 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=pitsidianak.is Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=pitsidianak.is Authentication-Results: smtp.subspace.kernel.org; dkim=pass (4096-bit key) header.d=pitsidianak.is header.i=@pitsidianak.is header.b="wBPLPVks" DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=pitsidianak.is; s=mailSelector; t=1778338057; bh=rSVMrHdXXMPOdNSzrMYHYbcWyiA/ND/D3nfYFJ1b2Bw=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From:Subject; b=wBPLPVkssrX+lU+fe8Z6SpIssvJflNfNz+56bvRhqvoQ29K7OL2k08FT3Qf15mbO9 ieGMGNF9IQwNArNB0FJ5WvYvCfpBdN4vMsQlgXe+etzkTkU+DjbkCBfgYuJqHzVBIb mtrbc+ajaKUmErsLx4rMTEYdkKmhyaEQw9eecS0Eh59lTsGwcgSHMKHBQZU/8e1dTI C/IWpyQweaw5lUkWPry0mEykmsc8I6g3oo5qLbjuQDS1aqhjB/o01B+8/Nifc3pvD+ MJZQt8psdrGydsk15+8hlx8gqdxlWd7JHlIFa9PctdUuT0g3k/AAgVE/mJodXwnfYX LohFPaS7TCJWUluALg35lXyYUM10Sjsh7LzIe6TTSmTWTMSfEjoWclwiv+Xne/kCOs itpdtPd0JQOPT1PZBpyB8obGuvqqwvmsD+AJ8LXb0vBu1M57h3+zPijDP/sMTMYpoM TXPdU03rGrTc62CJ9zopTEk9vyySe9vEsAIWqsHdWHjI11nuUNytOrRAGkwpM8MIH0 wD4fzWSfi7N8ue2AT9AcQ2GthAwFHi5ej54ZVaYyPUeu1Fi0+rvaMtmKVbDM4y2/1W MNiAA9+PJsxsbTHjH+uTlp72Wfi3s43zri4mm7qqbFSvvJgTMePH/pGtXUyaT9pAmS 1Iwg6+ubWbQvQsOhJVLrG8BM= From: Manos Pitsidianakis Date: Sat, 09 May 2026 17:46:56 +0300 Subject: [PATCH RFC v2 2/6] rust/helpers: add virtio.c Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20260509-rust-virtio-v2-2-c1e30ec2bd21@pitsidianak.is> References: <20260509-rust-virtio-v2-0-c1e30ec2bd21@pitsidianak.is> In-Reply-To: <20260509-rust-virtio-v2-0-c1e30ec2bd21@pitsidianak.is> To: Miguel Ojeda Cc: Manos Pitsidianakis , Peter Hilber , Stefano Garzarella , Stefan Hajnoczi , Viresh Kumar , "Michael S. Tsirkin" , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , rust-for-linux@vger.kernel.org, Jason Wang , Xuan Zhuo , =?utf-8?q?Eugenio_P=C3=A9rez?= , virtualization@lists.linux.dev, linux-kernel@vger.kernel.org, Manos Pitsidianakis X-Developer-Signature: v=1; a=openpgp-sha256; l=2591; i=manos@pitsidianak.is; h=from:subject:message-id; bh=rSVMrHdXXMPOdNSzrMYHYbcWyiA/ND/D3nfYFJ1b2Bw=; b=LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tCgpvd0VCYlFLUy9aQU5Bd0FLQVhjcHgzQi9mZ 25RQWNzbVlnQnAvMGtDR1N2V015WlJlRHRsdWp4TVZyOGlHdzFsCnJLYUtMa1dqMEJmT0ZySy9t NFNKQWpNRUFBRUtBQjBXSVFUTVhCdE9SS0JXODRkd0hSQjNLY2R3ZjM0SjBBVUMKYWY5SkFnQUt DUkIzS2Nkd2YzNEowQkx3RC85c3p5dlJVSHpHMVBWNHBIVHlFeWlhQTNoYWRIZ0JIVGlKWUVnNw o2NU1YZTB6RmpEdE9SRFdqZ3FwV0IrVWYvMlZhM3dxRUtwVFZmbkptS0xkVGpaa2orODZRL0tKQ TkvM0NiVDZkCmZEaU54UVFBS2U1Q2hCcFg5eXJJaGIybU5JTTZKeng2dmFBQnJ5a2w1UWpTdlcw d1Q0VGNLVUJkM0lhckMwZUsKTVl2dnExWU13SjlhaERITmxSZlFRSGxHQ0JQMkRsSm81Q3RwM0R acmlXUWlNN2V0OHFYeHVsY3JWL3l6eTA0ZwpRNzloQm1wTE9abGVKb0I4SEswNlg0SmZiYUE2an RSUEhHMWlPZ2xQZmxZeGRHMFU4ODZHRHkrQ2c2TE4xcnIzCnlsYU5GWDZQY0p3aGpDNS82MXpqK 0pJcy8wTW1TSGNCV1pKamVpUkU1R0U0UFVkdC9FMFg3bWpwWmkrVkNsL2wKeHEvMGNoL1F4UU1I SUNtT0ZFL013SFUvQWJjOVFwMDRyc2xCbmI5alBFMjR5YXQ0V09oT0ZTNmxtcGl2R1lnZApBYk8 yVmFOTDFYNUREcHBqbzJKU0QvTTJLYVdIdVpGbTZYcUMwb0dLUFMyaGdCK3NJNjYyV1kxU2p3Z3 QxS2RJCk1WMVZPTkFQQzYzclFncW91WWpLUnplY0xkaFJXVXBwU1FkcjZqTUgzZXhGWFNqNnR2Z Td2bjJFcTZVSXdkMkYKaldNV0ltVFFxRE8rRklaV1kyQ3EzelozcU5sZnQrRVNCRHZtd1AzZUxC ZWlwcU5qc2l3SVJxUncwVDVHSGoyRApEcjBDQUd2UWdhK3VQZU1PamJJZEgxVXpKOUZWaElkM1Q wZ3FrVXFOT1JkbElHeE15dG9sSWF6ajV6ek8wNnlNCkRIbXV6dz09Cj0vSG9zCi0tLS0tRU5EIF BHUCBNRVNTQUdFLS0tLS0K X-Developer-Key: i=manos@pitsidianak.is; a=openpgp; fpr=7C721DF9DB3CC7182311C0BF68BC211D47B421E1 Some internal kernel virtio API functions are inline macros, so define their symbols in a helper file. Signed-off-by: Manos Pitsidianakis --- MAINTAINERS | 6 ++++++ rust/helpers/helpers.c | 1 + rust/helpers/virtio.c | 37 +++++++++++++++++++++++++++++++++++++ 3 files changed, 44 insertions(+) diff --git a/MAINTAINERS b/MAINTAINERS index d1cc0e12fe1f004da89b1aa339116908f642e894..48c9c666d90b5a256ab6fae1f42= 508b789a0ce50 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -27930,6 +27930,12 @@ F: include/uapi/linux/virtio_*.h F: net/vmw_vsock/virtio* F: tools/virtio/ =20 +VIRTIO CORE API BINDINGS [RUST] +M: Manos Pitsidianakis +L: virtualization@lists.linux.dev +S: Maintained +F: rust/helpers/virtio.c + VIRTIO CRYPTO DRIVER M: Gonglei L: virtualization@lists.linux.dev diff --git a/rust/helpers/helpers.c b/rust/helpers/helpers.c index a3c42e51f00a0990bea81ebce6e99bb397ce7533..5dc0d2f2ee6bd2ae8e6abfe4baa= 247c1963967f6 100644 --- a/rust/helpers/helpers.c +++ b/rust/helpers/helpers.c @@ -61,6 +61,7 @@ #include "time.c" #include "uaccess.c" #include "usb.c" +#include "virtio.c" #include "vmalloc.c" #include "wait.c" #include "workqueue.c" diff --git a/rust/helpers/virtio.c b/rust/helpers/virtio.c new file mode 100644 index 0000000000000000000000000000000000000000..92185d7b8bd97b66f7b7b825390= fdd1173de313d --- /dev/null +++ b/rust/helpers/virtio.c @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: GPL-2.0 + +#if IS_ENABLED(CONFIG_VIRTIO) +#include + +__rust_helper bool +rust_helper_virtio_has_feature(const struct virtio_device *vdev, + unsigned int fbit) +{ + return virtio_has_feature(vdev, fbit); +} +__rust_helper void rust_helper_virtio_get_features(struct virtio_device *v= dev, + u64 *features_out) +{ + return virtio_get_features(vdev, features_out); +} + +__rust_helper int rust_helper_virtio_find_vqs(struct virtio_device *vdev, + unsigned int nvqs, + struct virtqueue *vqs[], + struct virtqueue_info vqs_info[], + struct irq_affinity *desc) +{ + return virtio_find_vqs(vdev, nvqs, vqs, vqs_info, desc); +} + +__rust_helper void rust_helper_virtio_device_ready(struct virtio_device *d= ev) +{ + return virtio_device_ready(dev); +} + +__rust_helper bool +rust_helper_virtio_is_little_endian(struct virtio_device *vdev) +{ + return virtio_is_little_endian(vdev); +} +#endif /* IS_ENABLED(CONFIG_VIRTIO) */ --=20 2.47.3 From nobody Sat Jun 13 06:06:38 2026 Received: from mail.nessuent.net (mail.nessuent.net [188.245.177.90]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 3716739A802; Sat, 9 May 2026 14:47:46 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=188.245.177.90 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1778338070; cv=none; b=NbvBoRan41ERiXpESY4Vo0W+SjdAIfMghVGkTiQQf8ieAMbCa1S+7IE12t6BVD4Y02zUtrCMFHXgI4MnhjgDumYkPG7FmRLEoPVNniKxBbAesWpGwzpUfq5X++iiXkSoIPBB88K4bXCe642oN82y5MwWr4D4/x936QHrnogv7uE= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1778338070; c=relaxed/simple; bh=X/WMd1dLY5a+NBAxGfjKhV9Vm2pNv9l7rP1+lBOUCAc=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=Gc1NvqfI6jAKYszXebR+hAMmq1K7afwwNFo+lPkE95y0F81/+07MWNLG7o3TQvhHjxzrs9YL7K3sl2Z0DJy6WGgg4Rj5rHG4bdvENVe9hAHxEEIqVuy9OhsINMQFKWiVcUd0JyKICxGjnLhbOP/lo5G/xFmvge49yl/3UMm36G4= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=pitsidianak.is; spf=pass smtp.mailfrom=pitsidianak.is; dkim=pass (4096-bit key) header.d=pitsidianak.is header.i=@pitsidianak.is header.b=4zAf/o6Q; arc=none smtp.client-ip=188.245.177.90 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=pitsidianak.is Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=pitsidianak.is Authentication-Results: smtp.subspace.kernel.org; dkim=pass (4096-bit key) header.d=pitsidianak.is header.i=@pitsidianak.is header.b="4zAf/o6Q" DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=pitsidianak.is; s=mailSelector; t=1778338058; bh=X/WMd1dLY5a+NBAxGfjKhV9Vm2pNv9l7rP1+lBOUCAc=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From:Subject; b=4zAf/o6Q9BMBAB9horCjGRiDrGiHqNB1AimncfFgG7T9gb7dlERSryVD4+f0nGKBo 7p5gypx5niZY60OAERprgHsCxy3vi1CQb2x7E+gcOqnO8Ncse9v8BSsJxW9fj1wTTW 8RJZfNs1Vr+0xgS/NSVEHb/R62daQjLs/Ux6GdjyI8HaTZ4mR5DtrRBIwY2wbca0T7 llkP+6Z7lzMS4koGSLVKXDv0KTVicE5SF8FjFsGaJpMgdizG9xiSZJkynziKvvf883 7ayNrbWbfKrA2bpY8kGl9nuwtujyKZKFmFcvo4kilO/Hz6grcTAz5x5XA5UFJrHNQ/ vT3u0hAG75+jykqo99NiTlwSGNtC52+o/118RLU+mojCP9elL27+ZTy/dOjsQaqJPN Kda6qs9TW1iChjoJFDOLwkfHjQ63djxRkWXSmq6EoAzT+1k/PwzRchXkwH6My36BKN 43X01xI0DhO5TEluWKS/i2hXIUEmvxCUe7l/XLtmb0b96zi4LzFJXjb6UzWhInAJCn 20g8JlMUINHtl8YVITLvJfFrackfVVO+CsGgjMRF+vLaMjFhhuA7RkQRHtTa44TaZE w4UJ2RJvWUDufmyy+KEY+bu3gB5BVoSqlnfT4IkcS8R8x/RV1gPPohnRSZ91lkAtGv 6UTgBvA/AYnUK4JKQ+JwOT1w= From: Manos Pitsidianakis Date: Sat, 09 May 2026 17:46:57 +0300 Subject: [PATCH RFC v2 3/6] rust: add virtio module Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20260509-rust-virtio-v2-3-c1e30ec2bd21@pitsidianak.is> References: <20260509-rust-virtio-v2-0-c1e30ec2bd21@pitsidianak.is> In-Reply-To: <20260509-rust-virtio-v2-0-c1e30ec2bd21@pitsidianak.is> To: Miguel Ojeda Cc: Manos Pitsidianakis , Peter Hilber , Stefano Garzarella , Stefan Hajnoczi , Viresh Kumar , "Michael S. Tsirkin" , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , rust-for-linux@vger.kernel.org, Jason Wang , Xuan Zhuo , =?utf-8?q?Eugenio_P=C3=A9rez?= , virtualization@lists.linux.dev, linux-kernel@vger.kernel.org, Manos Pitsidianakis X-Developer-Signature: v=1; a=openpgp-sha256; l=28909; i=manos@pitsidianak.is; h=from:subject:message-id; bh=X/WMd1dLY5a+NBAxGfjKhV9Vm2pNv9l7rP1+lBOUCAc=; b=LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tCgpvd0VCYlFLUy9aQU5Bd0FLQVhjcHgzQi9mZ 25RQWNzbVlnQnAvMGtEYTFUTUtlK2dPc2E2amwyU3EvTndLQ09MClhpWC9md1ROWFZxZHYvN3pT QTZKQWpNRUFBRUtBQjBXSVFUTVhCdE9SS0JXODRkd0hSQjNLY2R3ZjM0SjBBVUMKYWY5SkF3QUt DUkIzS2Nkd2YzNEowRDhPRUFDWjB5TjA5UXo5LzZCUCtMMkVvQVBVQkJ1b09GZHZDSTVFTDJpcg o0Q1RUWmJLbDBua3hsdnp0b1dzV3hqdS9nMGkrZVVkL3JiaUFCM2JOZGR3bmtPTUpGL3N4bDRVU XBCanBqazkwClJlTUhYU3hiQ1F4QkorTlFjM3l4c0dGQng0Mm9Cam44dk5vYjNMMTNmcVU0d2t0 Qlk5ajZSWnRUUC9pY1lTOEcKaXhEMHhDRHhISURZMzZQMHZCTmZlZ29CNURtUW55dlNHaDF4dWh ENnJpY2NPMUJxSnRqTGx3cjNFZ2dodzFrZgpnY01FdXMrQ2pJdm1GcS9oUFMreWdpOW5mdjB5Vk tOMi9IblUwMWNJakE1WVh1TVQyR2dlb2VIQXhTbklSWkh4CjBlZjRSbmRwTExzbTJzOEVCRERrU y82SnpzLzVPakkyNFM4OTNuMzhPZEcxVVU1V2IyaUZxL0tmYm5oQVBmb2wKMHUwUGdkSzgzcjRx TndIWUhpSFNvZ3RvRkJHaGRjTlhqMjZwTVpNTWVNSCtyNjFzcnM0VzVRcTJCTGNtWStrUgpDQlA vK01ZUExNa2lIK2ZnbWx1eE1rNlJWbjBvUjVUditYRVdVSThnYzVkbGN1SUd1VTllb01lcWQwdV YrWGFnCmpZM25aZG9kNlBYaTNzUDNvb2hoZjRiT3Vkb3dIYWNnS3BrWExwa0p0czhrY3kxQkxhS nNacGlCalZ3dUNtUk0KUThJNE1adGdjK3I5dmpRYlR6SWdkclUxK3FhemZYTWxHaW9OUzI2UmlY cktMUDJ4RHM5L2lIMERwQWJpU1VUaQpoQWV0MlVXR05FZlMvdno0RjZDRHVIU3ZXWXBEWnBYMWQ 1L0tGZHpldlhUVGhXQnNZWk9tN3cyc1ZnSkhURUN4Cmx1eWtLQT09Cj0rTjM2Ci0tLS0tRU5EIF BHUCBNRVNTQUdFLS0tLS0K X-Developer-Key: i=manos@pitsidianak.is; a=openpgp; fpr=7C721DF9DB3CC7182311C0BF68BC211D47B421E1 Add module that exposes bindings for the virtio API. Signed-off-by: Manos Pitsidianakis --- MAINTAINERS | 2 + rust/kernel/lib.rs | 2 + rust/kernel/scatterlist.rs | 2 +- rust/kernel/virtio.rs | 419 ++++++++++++++++++++++++++++++++++++= ++++ rust/kernel/virtio/utils.rs | 63 ++++++ rust/kernel/virtio/virtqueue.rs | 241 +++++++++++++++++++++++ 6 files changed, 728 insertions(+), 1 deletion(-) diff --git a/MAINTAINERS b/MAINTAINERS index 48c9c666d90b5a256ab6fae1f42508b789a0ce50..e8012f708df5d4ee858c82aec32= 69e615fc8caad 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -27935,6 +27935,8 @@ M: Manos Pitsidianakis L: virtualization@lists.linux.dev S: Maintained F: rust/helpers/virtio.c +F: rust/kernel/virtio.rs +F: rust/kernel/virtio/ =20 VIRTIO CRYPTO DRIVER M: Gonglei diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index d93292d47420f1f298a452ade5feefedce5ade86..061394f441dfa27f99939b5c416= 0e4161a7eaa1e 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -161,6 +161,8 @@ pub mod uaccess; #[cfg(CONFIG_USB =3D "y")] pub mod usb; +#[cfg(CONFIG_VIRTIO =3D "y")] +pub mod virtio; pub mod workqueue; pub mod xarray; =20 diff --git a/rust/kernel/scatterlist.rs b/rust/kernel/scatterlist.rs index b83c468b5c63311f3a6d92f0f1bf05f6dfe12076..146e738cbd4351b41c11dd39a45= e20f404c5cd64 100644 --- a/rust/kernel/scatterlist.rs +++ b/rust/kernel/scatterlist.rs @@ -75,7 +75,7 @@ unsafe fn from_raw<'a>(ptr: *mut bindings::scatterlist) -= > &'a Self { =20 /// Obtain the raw `struct scatterlist *`. #[inline] - fn as_raw(&self) -> *mut bindings::scatterlist { + pub(crate) fn as_raw(&self) -> *mut bindings::scatterlist { self.0.get() } =20 diff --git a/rust/kernel/virtio.rs b/rust/kernel/virtio.rs new file mode 100644 index 0000000000000000000000000000000000000000..c9de5d85c34e79965bd9d52d2f5= 2f2d37cfd72d1 --- /dev/null +++ b/rust/kernel/virtio.rs @@ -0,0 +1,419 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! VIRTIO abstraction. + +use crate::{ + bindings, + device_id::RawDeviceId, + error::{ + from_result, + to_result, + Error, + Result, // + }, + ffi::c_uint, + prelude::*, + types::Opaque, // +}; + +use core::{ + marker::PhantomData, + pin::Pin, // +}; + +pub mod utils; +pub mod virtqueue; + +/// IdTable type for virtio drivers. +pub type IdTable =3D &'static dyn crate::device_id::IdTable; + +/// A VIRTIO device id. +/// +/// [`struct virtio_device_id`]: srctree/include/linux/mod_devicetable.h +#[repr(transparent)] +#[derive(Clone, Copy)] +pub struct DeviceId(bindings::virtio_device_id); + +// SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `struct virti= o_device_id` and +// does not add additional invariants, so it's safe to transmute to `RawTy= pe`. +unsafe impl RawDeviceId for DeviceId { + type RawType =3D bindings::virtio_device_id; +} + +impl DeviceId { + #[inline] + /// Create a new device id + pub const fn new(device: VirtioID) -> Self { + Self::new_with_vendor(device, VIRTIO_DEV_ANY_ID) + } + + /// Create a new device id with vendor + pub const fn new_with_vendor(device: VirtioID, vendor: u32) -> Self { + // Replace with `bindings::of_device_id::default()` once stabilize= d for `const`. + // SAFETY: FFI type is valid to be zero-initialized. + let mut ret: bindings::virtio_device_id =3D unsafe { core::mem::ze= roed() }; + ret.device =3D device as u32; + ret.vendor =3D vendor; + Self(ret) + } +} + +/// Create a virtio `IdTable` with its alias for modpost. +#[macro_export] +macro_rules! virtio_device_table { + ($table_name:ident, $module_table_name:ident, $id_info_type: ty, $tabl= e_data:expr) =3D> { + const $table_name: $crate::device_id::IdArray< + $crate::virtio::DeviceId, + $id_info_type, + { $table_data.len() }, + > =3D $crate::device_id::IdArray::new_without_index($table_data); + + $crate::module_device_table!("virtio", $module_table_name, $table_= name); + }; +} + +/// Declares a kernel module that exposes a single virtio driver. +#[macro_export] +macro_rules! module_virtio_driver { +($($f:tt)*) =3D> { + $crate::module_driver!(, $crate::virtio::Adapter, { $($f)* }); +}; +} + +/// The Virtio driver trait. +/// +/// Drivers must implement this trait in order to get a virtio driver regi= stered. +pub trait Driver: Send { + /// The type holding information about each device id supported by the= driver. + // TODO: Use `associated_type_defaults` once stabilized: + // + // ``` + // type IdInfo: 'static =3D (); + // ``` + type IdInfo: 'static; + + /// The table of device ids supported by the driver. + const ID_TABLE: IdTable; + + /// virtio driver probe. + /// + /// Called when a new virtio device is added or discovered. Implemente= rs should + /// attempt to initialize the device here, but not sleep, since driver= data is set after this + /// method returns successfully. + fn probe(dev: &Device) -> impl PinInit; + + /// virtio driver init. + /// + /// Called after a virtio device is probed successfully, can sleep. + fn init(&self, dev: &Device) -> Result; + + /// virtio driver remove. + /// + /// Called when a [`Device`] is removed from its [`Driver`]. Implement= ing this callback + /// is optional. + /// + /// This callback serves as a place for drivers to perform teardown op= erations that require a + /// `&Device` or `&Device` reference. For instance, drive= rs may try to perform I/O + /// operations to gracefully tear down the device. + /// + /// Otherwise, release operations for driver resources should be perfo= rmed in `Self::drop`. + fn remove(dev: &Device, this: Pin<&Self>); +} + +/// Abstraction for the virtio device structure (`struct virtio_device`). +/// +/// [`struct virtio_device`]: srctree/include/linux/virtio.h +#[repr(transparent)] +pub struct Device( + Opaque, + PhantomData, +); + +impl Device { + #[inline] + fn as_raw(&self) -> *mut bindings::virtio_device { + self.0.get() + } +} + +// SAFETY: `virtio::Device` is a transparent wrapper of `struct virtio_dev= ice`. +// The offset is guaranteed to point to a valid device field inside `virti= o::Device`. +unsafe impl crate::device::AsBusDevice<= Ctx> for Device { + const OFFSET: usize =3D core::mem::offset_of!(bindings::virtio_device,= dev); +} + +// SAFETY: `Device` is a transparent wrapper of a type that doesn't depend= on `Device`'s generic +// argument. +kernel::impl_device_context_deref!(unsafe { Device }); + +impl Device { + // TODO: return VirtioID + /// Returns the virtio device ID. + #[inline] + pub fn device_id(&self) -> u32 { + // SAFETY: By its type invariant `self.as_raw` is always a valid p= ointer to a + // `struct virtio_device`. + unsafe { (*self.as_raw()).id.device } + } + + /// Returns the virtio vendor ID. + #[inline] + pub fn vendor_id(&self) -> u32 { + // SAFETY: `self.as_raw` is a valid pointer to a `struct virtio_de= vice`. + unsafe { (*self.as_raw()).id.vendor } + } + + /// Reset device. + #[doc(alias =3D "virtio_reset_device")] + #[inline] + pub fn reset(&self) { + // SAFETY: By its type invariant `self.as_raw` is always a valid p= ointer to a + // `struct virtio_device`. + unsafe { bindings::virtio_reset_device(self.as_raw()) } + } + + /// Mark device as ready. + #[doc(alias =3D "virtio_device_ready")] + #[inline] + pub fn ready(&self) { + // SAFETY: By its type invariant `self.as_raw` is always a valid p= ointer to a + // `struct virtio_device`. + unsafe { bindings::virtio_device_ready(self.as_raw()) } + } + + /// Return virtqueues for this device. + #[doc(alias =3D "virtio_find_vqs")] + pub fn find_vqs( + &self, + info: &[virtqueue::VirtqueueInfo], + ) -> Result> { + let mut vqs =3D KVec::with_capacity(info.len(), GFP_KERNEL)?; + // SAFETY: By its type invariant `self.as_raw` is always a valid p= ointer to a + // `struct virtio_device`. + to_result(unsafe { + bindings::virtio_find_vqs( + self.as_raw(), + info.len().try_into()?, + vqs.spare_capacity_mut().as_mut_ptr().cast(), + info.as_ptr().cast_mut().cast(), + core::ptr::null_mut(), + ) + })?; + // SAFETY: virtio_find_vqs returned successfully so `vqs` must be = populated. + unsafe { vqs.inc_len(info.len()) }; + Ok(vqs) + } + + /// Delete virtqueues from this device. + pub fn del_vqs(&self) { + // SAFETY: By its type invariant `self.as_raw` is always a valid p= ointer to a + // `struct virtio_device`. + let config =3D unsafe { (*self.as_raw()).config }; + // SAFETY: `config` points to a valid virtqueue config struct. + if let Some(del_vqs) =3D unsafe { (*config).del_vqs } { + // SAFETY: By its type invariant `self.as_raw` is always a val= id pointer to a + // `struct virtio_device`. + unsafe { del_vqs(self.as_raw()) } + } + } + + /// Checks if the device has a feature bit. + #[inline] + pub fn has_feature(&self, fbit: c_uint) -> bool { + // SAFETY: By its type invariant `self.as_raw` is always a valid p= ointer to a + // `struct virtio_device`. + unsafe { bindings::virtio_has_feature(self.as_raw(), fbit) } + } + + /// Return all feature bits for this device. + #[inline] + pub fn get_features(&self) -> u64 { + let mut features =3D 0; + // SAFETY: By its type invariant `self.as_raw` is always a valid p= ointer to a + // `struct virtio_device`. + unsafe { bindings::virtio_get_features(self.as_raw(), &raw mut fea= tures) }; + features + } +} + +impl AsRef> = for Device { + fn as_ref(&self) -> &crate::device::Device { + // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a p= ointer to a valid + // `struct virtio_device`. + let dev =3D unsafe { core::ptr::addr_of_mut!((*self.as_raw()).dev)= }; + + // SAFETY: `dev` points to a valid `struct device`. + unsafe { crate::device::Device::from_raw(dev) } + } +} + +/// An adapter for the registration of virtio drivers. +pub struct Adapter(T); + +// SAFETY: +// - `bindings::virtio_driver` is a C type declared as `repr(C)`. +// - `T` is the type of the driver's device private data. +// - `struct virtio_driver` embeds a `struct device_driver`. +// - `DEVICE_DRIVER_OFFSET` is the correct byte offset to the embedded `st= ruct device_driver`. +unsafe impl crate::driver::DriverLayout for Adapter { + type DriverType =3D bindings::virtio_driver; + type DriverData =3D T; + const DEVICE_DRIVER_OFFSET: usize =3D core::mem::offset_of!(Self::Driv= erType, driver); +} + +// SAFETY: A call to `unregister` for a given instance of `DriverType` is = guaranteed to be valid if +// a preceding call to `register` has been successful. +unsafe impl crate::driver::RegistrationOps for Adapte= r { + unsafe fn register( + vdrv: &Opaque, + name: &'static CStr, + module: &'static ThisModule, + ) -> Result { + // SAFETY: It's safe to set the fields of `struct virtio_driver` o= n initialization. + unsafe { + (*vdrv.get()).driver.name =3D name.as_char_ptr(); + (*vdrv.get()).id_table =3D T::ID_TABLE.as_ptr(); + (*vdrv.get()).probe =3D Some(Self::probe_callback); + (*vdrv.get()).remove =3D Some(Self::remove_callback); + } + + // SAFETY: `vdrv` is guaranteed to be a valid `DriverType`. + to_result(unsafe { bindings::__register_virtio_driver(vdrv.get(), = module.0) }) + } + + unsafe fn unregister(vdrv: &Opaque) { + // SAFETY: `vdrv` is guaranteed to be a valid `DriverType`. + unsafe { bindings::unregister_virtio_driver(vdrv.get()) } + } +} + +impl Adapter { + extern "C" fn probe_callback(vdev: *mut bindings::virtio_device) -> c_= int { + // SAFETY: The kernel only ever calls the probe callback with a va= lid pointer to a `struct + // virtio_device`. + // + // INVARIANT: `vdev` is valid for the duration of `probe_callback(= )`. + let dev =3D unsafe { &*vdev.cast::>() }; + from_result(|| { + let data =3D T::probe(dev); + + dev.as_ref().set_drvdata(data)?; + // SAFETY: `Device::set_drvdata()` was just called so it's saf= e to borrow the data. + let data =3D unsafe { dev.as_ref().drvdata_borrow::() }; + if let Err(err) =3D T::init(&data, dev) { + // SAFETY: `Device::set_drvdata()` was just called so it's= safe to re-obtain the + // data. + let data =3D unsafe { dev.as_ref().drvdata_obtain::() }= .unwrap(); + T::remove(dev, data.as_ref()); + drop(data); + return Err(err); + } + Ok(0) + }) + } + + extern "C" fn remove_callback(vdev: *mut bindings::virtio_device) { + // SAFETY: The kernel only ever calls the remove callback with a v= alid pointer to a `struct + // virtio_device`. + // + // INVARIANT: `vdev` is valid for the duration of `remove_callback= ()`. + let dev =3D unsafe { &*vdev.cast::>() }; + + // SAFETY: `remove_callback` is only ever called after a successfu= l call to + // `probe_callback`, hence it's guaranteed that `Device::set_drvda= ta()` has been called + // and stored a `Pin>`. + let data =3D unsafe { dev.as_ref().drvdata_borrow::() }; + + T::remove(dev, data); + } +} + +/// Any vendor +pub const VIRTIO_DEV_ANY_ID: u32 =3D 0xffffffff; + +/// Virtio IDs +/// +/// C header: [`include/uapi/linux/virtio_ids.h`](srctree/include/uapi/lin= ux/virtio_ids.h) +#[repr(u32)] +pub enum VirtioID { + /// virtio net + Net =3D bindings::VIRTIO_ID_NET, + /// virtio block + Block =3D bindings::VIRTIO_ID_BLOCK, + /// virtio console + Console =3D bindings::VIRTIO_ID_CONSOLE, + /// virtio rng + Rng =3D bindings::VIRTIO_ID_RNG, + /// virtio balloon + Balloon =3D bindings::VIRTIO_ID_BALLOON, + /// virtio ioMemory + IOMem =3D bindings::VIRTIO_ID_IOMEM, + /// virtio remote processor messaging + RPMSG =3D bindings::VIRTIO_ID_RPMSG, + /// virtio scsi + Scsi =3D bindings::VIRTIO_ID_SCSI, + /// 9p virtio console + NineP =3D bindings::VIRTIO_ID_9P, + /// virtio WLAN MAC + Mac80211Wlan =3D bindings::VIRTIO_ID_MAC80211_WLAN, + /// virtio remoteproc serial link + RPROCSerial =3D bindings::VIRTIO_ID_RPROC_SERIAL, + /// Virtio caif + CAIF =3D bindings::VIRTIO_ID_CAIF, + /// virtio memory balloon + MemoryBalloon =3D bindings::VIRTIO_ID_MEMORY_BALLOON, + /// virtio GPU + GPU =3D bindings::VIRTIO_ID_GPU, + /// virtio clock/timer + Clock =3D bindings::VIRTIO_ID_CLOCK, + /// virtio input + Input =3D bindings::VIRTIO_ID_INPUT, + /// virtio vsock transport + VSock =3D bindings::VIRTIO_ID_VSOCK, + /// virtio crypto + Crypto =3D bindings::VIRTIO_ID_CRYPTO, + /// virtio signal distribution device + SignalDist =3D bindings::VIRTIO_ID_SIGNAL_DIST, + /// virtio pstore device + Pstore =3D bindings::VIRTIO_ID_PSTORE, + /// virtio IOMMU + Iommu =3D bindings::VIRTIO_ID_IOMMU, + /// virtio mem + Mem =3D bindings::VIRTIO_ID_MEM, + /// virtio sound + Sound =3D bindings::VIRTIO_ID_SOUND, + /// virtio filesystem + FS =3D bindings::VIRTIO_ID_FS, + /// virtio pmem + PMem =3D bindings::VIRTIO_ID_PMEM, + /// virtio rpmb + RPMB =3D bindings::VIRTIO_ID_RPMB, + /// virtio mac80211-hwsim + Mac80211Hwsim =3D bindings::VIRTIO_ID_MAC80211_HWSIM, + /// virtio video encoder + VideoEncoder =3D bindings::VIRTIO_ID_VIDEO_ENCODER, + /// virtio video decoder + VideoDecoder =3D bindings::VIRTIO_ID_VIDEO_DECODER, + /// virtio SCMI + SCMI =3D bindings::VIRTIO_ID_SCMI, + /// virtio nitro secure module + NitroSecMod =3D bindings::VIRTIO_ID_NITRO_SEC_MOD, + /// virtio i2c adapter + I2CAdapter =3D bindings::VIRTIO_ID_I2C_ADAPTER, + /// virtio watchdog + Watchdog =3D bindings::VIRTIO_ID_WATCHDOG, + /// virtio can + CAN =3D bindings::VIRTIO_ID_CAN, + /// virtio dmabuf + DMABuf =3D bindings::VIRTIO_ID_DMABUF, + /// virtio parameter server + ParamServ =3D bindings::VIRTIO_ID_PARAM_SERV, + /// virtio audio policy + AudioPolicy =3D bindings::VIRTIO_ID_AUDIO_POLICY, + /// virtio bluetooth + BT =3D bindings::VIRTIO_ID_BT, + /// virtio gpio + GPIO =3D bindings::VIRTIO_ID_GPIO, + /// virtio spi + SPI =3D bindings::VIRTIO_ID_SPI, +} diff --git a/rust/kernel/virtio/utils.rs b/rust/kernel/virtio/utils.rs new file mode 100644 index 0000000000000000000000000000000000000000..bec8e0c38d7ada95584b99f70ad= b2328e67ecb02 --- /dev/null +++ b/rust/kernel/virtio/utils.rs @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Helper types and utilities + +macro_rules! endian_type { + (le $old_type:ident, $new_type:ident) =3D> { + endian_type!($old_type, $new_type, to_le, from_le); + }; + (be $old_type:ident, $new_type:ident) =3D> { + endian_type!($old_type, $new_type, to_be, from_be); + }; + ($old_type:ident, $new_type:ident, $to_new:ident, $from_new:ident) =3D= > { + /// An unsigned integer type of with an explicit endianness. + #[derive(Copy, Clone, Eq, PartialEq, Debug, Default, pin_init::Zer= oable)] + #[repr(transparent)] + pub struct $new_type($old_type); + + $crate::static_assert!( + ::core::mem::align_of::<$new_type>() =3D=3D ::core::mem::align= _of::<$old_type>() + ); + $crate::static_assert!( + ::core::mem::size_of::<$new_type>() =3D=3D ::core::mem::size_o= f::<$old_type>() + ); + + impl $new_type { + /// Convert to CPU/native endianness. + pub const fn to_cpu(self) -> $old_type { + $old_type::$from_new(self.0) + } + } + + impl PartialEq<$old_type> for $new_type { + fn eq(&self, other: &$old_type) -> bool { + self.0 =3D=3D $old_type::$to_new(*other) + } + } + + impl PartialEq<$new_type> for $old_type { + fn eq(&self, other: &$new_type) -> bool { + $old_type::$to_new(other.0) =3D=3D *self + } + } + + impl From<$new_type> for $old_type { + fn from(v: $new_type) -> $old_type { + v.to_cpu() + } + } + + impl From<$old_type> for $new_type { + fn from(v: $old_type) -> $new_type { + $new_type($old_type::$to_new(v)) + } + } + }; +} + +endian_type!(u16, Le16, to_le, from_le); +endian_type!(u32, Le32, to_le, from_le); +endian_type!(u64, Le64, to_le, from_le); +endian_type!(u16, Be16, to_be, from_be); +endian_type!(u32, Be32, to_be, from_be); +endian_type!(u64, Be64, to_be, from_be); diff --git a/rust/kernel/virtio/virtqueue.rs b/rust/kernel/virtio/virtqueue= .rs new file mode 100644 index 0000000000000000000000000000000000000000..10186b4fa94be6786a7d203d32d= 4f79c121b5383 --- /dev/null +++ b/rust/kernel/virtio/virtqueue.rs @@ -0,0 +1,241 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Virtqueue functionality. + +use crate::{ + alloc::{ + Flags, // + }, + bindings, + device::Bound, + error::{ + code::{ + EINVAL, + ENOENT, // + }, + to_result, + Result, // + }, + scatterlist::SGEntry, + str::CStr, + types::Opaque, + virtio::Device, // +}; + +use core::{ + ffi::c_uint, + ptr::NonNull, // +}; + +/// Info for a virtqueue. +/// +/// [`struct virtqueue_info`]: srctree/include/linux/virtio_config.h +#[doc(alias =3D "virtqueue_info")] +#[repr(transparent)] +pub struct VirtqueueInfo(Opaque); + +impl VirtqueueInfo { + /// Create a new [`VirtqueueInfo`] + pub const fn new( + name: &'static CStr, + ctx: bool, + callback: Option, + ) -> Self { + Self(Opaque::new(bindings::virtqueue_info { + name: name.as_ptr(), + ctx, + callback, + })) + } +} + +/// An opaque handler for a virtqueue. +/// +/// [`struct virtqueue`]: srctree/include/linux/virtio.h +#[repr(transparent)] +pub struct Virtqueue(Opaque); + +impl Virtqueue { + /// Create a [`Virtqueue`] from a raw pointer. + /// + /// # Safety + /// + /// Callers must ensure that `ptr` is a properly initialized valid `vi= rtqueue` pointer. + #[inline] + pub unsafe fn from_raw<'a>(ptr: *mut bindings::virtqueue) -> &'a Self { + // SAFETY: The safety requirements of this function guarantee that= `ptr` is a valid + // pointer to a `struct virtqueue` for the duration of `'a`. + unsafe { &*ptr.cast() } + } + + /// Obtain the raw `struct virtqueue *`. + #[inline] + pub(crate) fn as_raw(&self) -> *mut bindings::virtqueue { + self.0.get() + } + + /// Get the [`Device`] associated with this virtqueue. + #[inline] + pub fn dev(&self) -> Result<&Device> { + // SAFETY: By the type invariants, `self.as_raw()` is a valid poin= ter to a `struct + // virtqueue`. + if unsafe { (*self.as_raw()).vdev }.is_null() { + return Err(ENOENT); + } + // SAFETY: the pointer has been promised to be valid when self was= created + Ok(unsafe { &*(&*self.as_raw()).vdev.cast::>() }) + } + + /// Get the vring size. + #[inline] + #[doc(alias =3D "virtqueue_get_vring_size")] + pub fn vring_size(&self) -> u32 { + // SAFETY: the pointer has been promised to be valid when self was= created + unsafe { bindings::virtqueue_get_vring_size(self.as_raw()) } + } + + /// Notify virtqueue. + #[inline] + #[doc(alias =3D "virtqueue_notify")] + pub fn notify(&self) -> bool { + // SAFETY: the pointer has been promised to be valid when self was= created + unsafe { bindings::virtqueue_notify(self.as_raw()) } + } + + /// Kick and prepare virtqueue. + #[inline] + #[doc(alias =3D "virtqueue_kick_prepare")] + pub fn kick_prepare(&self) -> bool { + // SAFETY: the pointer has been promised to be valid when self was= created + unsafe { bindings::virtqueue_kick_prepare(self.as_raw()) } + } + + /// Kick virtqueue. + #[inline] + #[doc(alias =3D "virtqueue_kick")] + pub fn kick(&self) -> bool { + // SAFETY: the pointer has been promised to be valid when self was= created + unsafe { bindings::virtqueue_kick(self.as_raw()) } + } + + /// Enable virtqueue's callback. + #[inline] + #[doc(alias =3D "virtqueue_enable_cb")] + pub fn enable_cb(&self) -> bool { + // SAFETY: the pointer has been promised to be valid when self was= created + unsafe { bindings::virtqueue_enable_cb(self.as_raw()) } + } + + /// Disable virtqueue's callback. + #[inline] + #[doc(alias =3D "virtqueue_disable_cb")] + pub fn disable_cb(&self) { + // SAFETY: the pointer has been promised to be valid when self was= created + unsafe { bindings::virtqueue_disable_cb(self.as_raw()) } + } + + /// Get a buffer from the virtqueue, if available. + #[inline] + #[doc(alias =3D "virtqueue_get_buf")] + pub fn get_buf(&'_ self) -> Option<(NonNull, u32)> { + let mut len =3D 0; + // SAFETY: the pointer has been promised to be valid when self was= created + let ptr =3D unsafe { bindings::virtqueue_get_buf(self.as_raw(), &m= ut len) }; + Some((NonNull::new(ptr.cast())?, len)) + } + + /// Make a device write-only buffer available. + /// + /// # Safety + /// + /// Callers must ensure: + /// + /// - the data pointed to by `sg` and `token` will live as long as the= buffer lives in the + /// virtqueue + /// - the driver deallocates any data pointed to by `sg` and `token` o= n error + /// - the driver deallocates any data pointed to by `sg` and `token` w= hen it receives a + /// virtqueue response + /// - the driver deallocates any data pointed to by `sg` and `token` w= hen it resets the device + #[inline] + #[doc(alias =3D "virtqueue_add_inbuf")] + pub unsafe fn add_inbuf(&'_ self, sg: &SGEntry, token: NonNull, gf= p: Flags) -> Result { + // SAFETY: the pointer has been promised to be valid when self was= created + to_result(unsafe { + bindings::virtqueue_add_inbuf( + self.as_raw(), + sg.as_raw(), + 1, + token.as_ptr().cast(), + gfp.as_raw(), + ) + }) + } + + /// Make a device read-only buffer available. + /// + /// # Safety + /// + /// Callers must ensure: + /// + /// - the data pointed to by `sg` and `token` will live as long as the= buffer lives in the + /// virtqueue + /// - the driver deallocates any data pointed to by `sg` and `token` o= n error + /// - the driver deallocates any data pointed to by `sg` and `token` w= hen it receives a + /// virtqueue response + /// - the driver deallocates any data pointed to by `sg` and `token` w= hen it resets the device + #[inline] + #[doc(alias =3D "virtqueue_add_outbuf")] + pub unsafe fn add_outbuf(&'_ self, sg: &SGEntry, token: NonNull, g= fp: Flags) -> Result { + // SAFETY: the pointer has been promised to be valid when self was= created + to_result(unsafe { + bindings::virtqueue_add_outbuf( + self.as_raw(), + sg.as_raw(), + 1, + token.as_ptr().cast(), + gfp.as_raw(), + ) + }) + } + + /// Add a list of scatter-gather lists to virtqueue. + /// + /// # Safety + /// + /// Callers must ensure: + /// + /// - the data pointed to by `sgs` and `token` will live as long as th= e buffer lives in the + /// virtqueue + /// - the driver deallocates any data pointed to by `sgs` and `token` = on error + /// - the driver deallocates any data pointed to by `sgs` and `token` = when it receives a + /// virtqueue response + /// - the driver deallocates any data pointed to by `sgs` and `token` = when it resets the device + #[inline] + #[doc(alias =3D "virtqueue_add_sgs")] + pub unsafe fn add_sgs( + &'_ self, + sgs: &[&SGEntry], + out_sgs: c_uint, + in_sgs: c_uint, + token: NonNull, + gfp: Flags, + ) -> Result { + let Some(total_size) =3D out_sgs.checked_add(in_sgs) else { + return Err(EINVAL); + }; + if usize::try_from(total_size) !=3D Ok(sgs.len()) { + return Err(EINVAL); + } + // SAFETY: the pointer has been promised to be valid when self was= created + to_result(unsafe { + bindings::virtqueue_add_sgs( + self.as_raw(), + sgs.as_ptr().cast_mut().cast(), + out_sgs, + in_sgs, + token.as_ptr().cast(), + gfp.as_raw(), + ) + }) + } +} --=20 2.47.3 From nobody Sat Jun 13 06:06:38 2026 Received: from mail.nessuent.net (mail.nessuent.net [188.245.177.90]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 404083976BB; Sat, 9 May 2026 14:47:47 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=188.245.177.90 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1778338075; cv=none; b=kldln69eOl+95egE3OMeNIb6Mz5jP6UD9fdIeBFtc5pgZMC8jkNXYK3/HbxSswXwBm82XIg/ICFsv/YrmECzQJqj57Ydqu0FIBI5VB5ldVbyMEpVSro12e/lTN6Yaet21Fr3oBj3TVeFMK6wDJtmZke9s6jZA6yILvHCa1PpzEs= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1778338075; c=relaxed/simple; bh=ueMYbnhP380gUpqP1QHJlQrrjstYCaH5Rry1n19OITA=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=dRZnwMV+mTvdbKpJI2PpN/fCu9gZYgHbac5ttF2Zo0OHsoPzlYewpqicWHeIW5zzabm18bwWTpTcIzZA3JrYgZhBeDq4cVpUM1WoGRDSyRnG9O3XLHQrNhKTKm3fUy2RyQBlvCrvGcQqNTxkQLHrD0uDKCZ5dIbi+DUscy8YoQc= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=pitsidianak.is; spf=pass smtp.mailfrom=pitsidianak.is; dkim=pass (4096-bit key) header.d=pitsidianak.is header.i=@pitsidianak.is header.b=041vrqZW; arc=none smtp.client-ip=188.245.177.90 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=pitsidianak.is Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=pitsidianak.is Authentication-Results: smtp.subspace.kernel.org; dkim=pass (4096-bit key) header.d=pitsidianak.is header.i=@pitsidianak.is header.b="041vrqZW" DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=pitsidianak.is; s=mailSelector; t=1778338059; bh=ueMYbnhP380gUpqP1QHJlQrrjstYCaH5Rry1n19OITA=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From:Subject; b=041vrqZWUzBncqPBFlJdGBaf3dfDPmwxTpDAISVR7NztU7ysAFahCK47tD1PwryF1 mducX7RaJSVRH7qAViJWfauPSR5dsSFXThHfYb4j4BXv1xicmwQOU7dqmVtt5IA0Lq OdDNiElXI/BmgK1H/ONaviGaVbWPPgoaRNzykUMzm5GeWheT6SApDWVF2jCvOG67Yu r55k82G6XI8Z8n613pEK7Nx0G7Tq+aiSbbbSX88nPHczcY47AxOuftKTWVs/lmeFCU QG6gFypLWqDHlVMY+cOkaa6LzAePzvcNt46XvLOf2xamo3GXw4PCipTHlOshpTdwlG F7++jPM04aQy/1ogRe5HFpR1aI+53tB9Jd3ZUBD0unbgO2qWGTxOc5Q9hk1NCmMiL8 /LGjYHgKR+je0/X4hgNtqztapwwX/OggNNRs7PKrFRY6xh2sWWeiJig6aC/3En6SRG k/OUZhva4p/sB4K4iLrg/QxCReZmt38L6eeiQvyHm1jrnh1sTKPk4cv3BiRPbHSuwn /vu592zLbCj34neeELnlbW55K7VDGCfGgHTzm0dAOUZvP4da5pUviXxo3CF/nYCG4d jdWHuiq95E7RrKEkDeRNHqaVc+XCiV2ITvClhJOC79A+sB68Mwf7FRjLXuu7PNgoYs JXiUknRouRR+q6YR1SM5cPcA= From: Manos Pitsidianakis Date: Sat, 09 May 2026 17:46:58 +0300 Subject: [PATCH RFC v2 4/6] rust/scatterlist: add SGEntry::init_one Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20260509-rust-virtio-v2-4-c1e30ec2bd21@pitsidianak.is> References: <20260509-rust-virtio-v2-0-c1e30ec2bd21@pitsidianak.is> In-Reply-To: <20260509-rust-virtio-v2-0-c1e30ec2bd21@pitsidianak.is> To: Miguel Ojeda Cc: Manos Pitsidianakis , Peter Hilber , Stefano Garzarella , Stefan Hajnoczi , Viresh Kumar , "Michael S. Tsirkin" , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , rust-for-linux@vger.kernel.org, Jason Wang , Xuan Zhuo , =?utf-8?q?Eugenio_P=C3=A9rez?= , virtualization@lists.linux.dev, linux-kernel@vger.kernel.org, Manos Pitsidianakis X-Developer-Signature: v=1; a=openpgp-sha256; l=1545; i=manos@pitsidianak.is; h=from:subject:message-id; bh=ueMYbnhP380gUpqP1QHJlQrrjstYCaH5Rry1n19OITA=; b=LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tCgpvd0VCYlFLUy9aQU5Bd0FLQVhjcHgzQi9mZ 25RQWNzbVlnQnAvMGtEWEpWU0t5ck92MUF3M1d3d2JZQnBZeHVBClpRVTJlanNMK2djZjVSdEth bGVKQWpNRUFBRUtBQjBXSVFUTVhCdE9SS0JXODRkd0hSQjNLY2R3ZjM0SjBBVUMKYWY5SkF3QUt DUkIzS2Nkd2YzNEowRTRtRC85Z1M4dXpFZ0tzSGV2bXpxcGhoRzI0bmY3MkpIaFI1MHlYQzMrVw podkh4RFp0Q0Nvc1NTM2k1VHhxMFB4Y1BjYU1VV09pTWxGbm9RMGVvWEhZNGF4VnVDNFhQY2gwM TFMS1NhVHpOCnk0TGVSay84SExRUjV3Vlh6R09xbWhzVzlicmF4SmFtTTNmSnJQQVQ4dTZlaFcv Q3BOcEZFQy9rWHExU0FjOEwKNVV1SjZkNWduQm5DSUcxVlQ0OVRCTklIYmVnVWxTVlVqeDlCRnF PTllRcHRVc1NBZ0tLVTUrYUJjbmtjL0pDcgpGTHArUHhhTkNiRTVwUmxOR0FOamZoNklNTUo0U2 VDT1Z1VGs0ZEZIMkpBOU5yV1VuWVlNa1RXdWhDWHc1cytUCnlNT3JlRGdqaFdzcHNoYjVCSGw4R 3ZEdUQrMDQwT3F4ckxtb1k1T0pYSXU3MnBqemlwd0wrSkFrclNhQ2grdDMKczZrcGc3R0l6Q0FI b1paMUV5V0tsWjZmMHQzVms0QitsbllYY0owYTlNSWRFUUtBVGlnakZiQUUyVmI5aFF3Rwp2alF QaGdwMk5MZ1U2VDNydkVyNGpydnRFNzYxVG1wVzM5ekNpM0VOcEF1ZzB2OHB4R3BzZkMrdGg2aD MyOUo1Cmx2R2dCTTNyOVpjM2NhaVR3dGxRa2tIcVBHVGpReThJT25xeUY0UDYyVytQNXVRcjBYT GhaQ2FxM2x3aDRhZC8KMDdLc256cDluUTlWbTAyM1kzUHR5TFdjK2poYjI0ZjFaOTVvaDYyVk1C TFVDUWUzQXlTRkw5YmIzYlhoZEpFdAppY0wxTUJkazJPS3lyY0lqWkRBc2Q0cVp3ZkRUZ09LVTJ YN3c3QTI0QjFpYXM4RUo2djVFUHRqRmlhcmN3dXFXCkVDODZ1dz09Cj1mSVQ5Ci0tLS0tRU5EIF BHUCBNRVNTQUdFLS0tLS0K X-Developer-Key: i=manos@pitsidianak.is; a=openpgp; fpr=7C721DF9DB3CC7182311C0BF68BC211D47B421E1 Add a method to allow creation of an SGEntry with borrowed data. Analogous of `sg_init_one` in C. Signed-off-by: Manos Pitsidianakis --- rust/kernel/scatterlist.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/rust/kernel/scatterlist.rs b/rust/kernel/scatterlist.rs index 146e738cbd4351b41c11dd39a45e20f404c5cd64..b065762af1a734fcdd5d3acde89= 199f1a626fd89 100644 --- a/rust/kernel/scatterlist.rs +++ b/rust/kernel/scatterlist.rs @@ -95,6 +95,24 @@ pub fn dma_len(&self) -> ResourceSize { // SAFETY: `self.as_raw()` is a valid pointer to a `struct scatter= list`. unsafe { bindings::sg_dma_len(self.as_raw()) }.into() } + + /// Initialize a new entry with borrowed data. + /// + /// # Safety + /// + /// Callers must ensure that: + /// - `buf` is a valid pointer + /// - `buf_len` describes a valid allocation size for this pointer + pub unsafe fn init_one( + val: &'_ mut core::mem::MaybeUninit, + buf: NonNull, + buf_len: u32, + ) -> &'_ Self { + // SAFETY: `val` points to a correctly sized `struct scatterlist`. + unsafe { bindings::sg_init_one(val.as_mut_ptr(), buf.as_ptr().cast= (), buf_len) }; + // SAFETY: `val` points to an initialized `struct scatterlist`. + unsafe { Self::from_raw(val.as_mut_ptr()) } + } } =20 /// The borrowed generic type of an [`SGTable`], representing a borrowed o= r externally managed --=20 2.47.3 From nobody Sat Jun 13 06:06:38 2026 Received: from mail.nessuent.net (mail.nessuent.net [188.245.177.90]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id B771739B49C; Sat, 9 May 2026 14:47:46 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=188.245.177.90 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1778338069; cv=none; b=FD2DtLglZdg6QB9VRHerGWVWEWBPjartZQj2B+5eh7mWa7zc0HHNGVtfOJ8805hDA4nJtRqgmAr0tlksXFaWAuq/zejUusIaXSmnlKy5a3246XkxjtrxfGrQzdp4ZwcO/NtjQwPGDbePAjhFJesmdSe1jet8IhJuw/Uz8JpdrOI= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1778338069; c=relaxed/simple; bh=msIA3QDkNRl5CiYMJuFdB8gcwSF6bQ5gs2Bh4tXdmNA=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=r17+zJ1981ebzmbxZnlJGROpxlG2JZ5m/p6q2TvS5GK9XQJL/V6a4Ou/Htz/7lcGSXUBnjHIluvAUeWIOR2DM0ED43DHSrYkgTibBrYm+BsZwpDohqYVMkGT7kvn6drZRLaE/OVNEcDMy+wQOrYxDKK+LZ3Vz9Au3pA9qJdk4Rc= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=pitsidianak.is; spf=pass smtp.mailfrom=pitsidianak.is; dkim=pass (4096-bit key) header.d=pitsidianak.is header.i=@pitsidianak.is header.b=f8/lrKaT; arc=none smtp.client-ip=188.245.177.90 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=pitsidianak.is Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=pitsidianak.is Authentication-Results: smtp.subspace.kernel.org; dkim=pass (4096-bit key) header.d=pitsidianak.is header.i=@pitsidianak.is header.b="f8/lrKaT" DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=pitsidianak.is; s=mailSelector; t=1778338060; bh=msIA3QDkNRl5CiYMJuFdB8gcwSF6bQ5gs2Bh4tXdmNA=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From:Subject; b=f8/lrKaTMcCTii+rlngRlNh/U5wabTkAP2Xy90gmNKBbCkbcQ96TMsjx5BZ7XGzxj QlOCZaOh2H2wPFuRFQfvOJ3FXlYvEg/11tPpq1GmIy1/QmiTMisVQ26O+PCPSnKvC8 RB4rW9dZP7wzfpoOgpExQAuLi65Xo5SzM+IBKFMH6hXFVQUfLVhZWth0lMZX5zGKGp zME9LgNYlmq+8LQ4ndTtKZSFFSjv7SlqmooufOhPRPbmDnycYXuDkDLXyLkVjhVKGt h3P1EHZ1XKfHVPxTBacUc64xm5by3FQZZNTV68XZpTp0acDqr0yFqI0q5lgP775hRW 3ancI9ssStIaHUeoXNf8IaXKLDiMz1J2736m95b43znv/2Ii+oXLHLPaW+8d+z4OxC Z83/GVeCj5eheWylMjgnaTOshBBCUBK5wCkKpwYTlnsVVeuq8Q2qjrGj1h3UwpBuV/ kqutD8jZvNavXnjAA9VTocqbJdVEdPNtVYwlTDTeljTzeiUpfdGMfBx2GyYzv13BtK Z6SEGfLbqPl/i/rglOPMKwsZf1X5Sx7Fr1FfDupCTC4i1IqH3WM3DcaknKPuDXNno5 HdZukFeW93srb5/mF/gUYBAgMXseSJo2PC/2Kb9femNejXwSAOXHpwYDiNk+1UdvDs da9REoOXH3wu8AS3+oG4I+vk= From: Manos Pitsidianakis Date: Sat, 09 May 2026 17:46:59 +0300 Subject: [PATCH RFC v2 5/6] rust: impl interruptible waits for Completion Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20260509-rust-virtio-v2-5-c1e30ec2bd21@pitsidianak.is> References: <20260509-rust-virtio-v2-0-c1e30ec2bd21@pitsidianak.is> In-Reply-To: <20260509-rust-virtio-v2-0-c1e30ec2bd21@pitsidianak.is> To: Miguel Ojeda Cc: Manos Pitsidianakis , Peter Hilber , Stefano Garzarella , Stefan Hajnoczi , Viresh Kumar , "Michael S. Tsirkin" , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , rust-for-linux@vger.kernel.org, Jason Wang , Xuan Zhuo , =?utf-8?q?Eugenio_P=C3=A9rez?= , virtualization@lists.linux.dev, linux-kernel@vger.kernel.org, Manos Pitsidianakis X-Developer-Signature: v=1; a=openpgp-sha256; l=2340; i=manos@pitsidianak.is; h=from:subject:message-id; bh=msIA3QDkNRl5CiYMJuFdB8gcwSF6bQ5gs2Bh4tXdmNA=; b=LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tCgpvd0VCYlFLUy9aQU5Bd0FLQVhjcHgzQi9mZ 25RQWNzbVlnQnAvMGtFRUtzTG1uKzN2dWVTZ1RyQU9UUkRFVUduCjcwSEsrQktpMWdJU2RxWFNo SGlKQWpNRUFBRUtBQjBXSVFUTVhCdE9SS0JXODRkd0hSQjNLY2R3ZjM0SjBBVUMKYWY5SkJBQUt DUkIzS2Nkd2YzNEowQ3M4RUFDUXI1a0FENTIrQS8rOHoxckRPalhoTG56U2FDR2tUWFZpUUJoOA ptT1lOTDRpbFBuNkZ1UER1QWtySkdYRDM3elFJNkhkaUI2ZEVJa1g0VFNsTXI0MG1Sd290TkZjb HRBU0xtNU5jCnlJK3gzWitmdUFtRVFWbUUrWlFMWnFPY1VmU0w4Mkt0VEd1eTZSNFFRWFVqUnly dXl1Q21IMW5KcHpWRXpzSHcKQmFCT1VxMmx1VUR1L1J4OHM4Z004eGNJNVRPTThDZ3haUVl0R3J KNk1VKzhkNmdiMU1QSXgzWTZFS3g1emdVcwovUDNzNWlGQmNTYlh4QzhsakJFK0JkaEt5S2ljZE syUE1WYW5YamtwYnRiWnh1bFZ0V0VvTnNnSWFoTGZieE9NCjJkNUFoNncxd0Y3eUFrTjFxUFRjW TQyTUxkU29zcVI2L1Q5NDlDdUpDS3NlbFp4c1hqWjhlc01zRVYvc241bEsKbGg5bHI5VGVFSkZZ dkNDemg2bzBhYUJpV2dXQjNUcmsybEl2ZEdqcXd6S0FqU0pNSlNWeTRnaWF2SVVZZ0t5TAp2M3J 2YVR6VnJxb3QzQ3B5VVNyaE8zU0MvVkIzUm8rRzh2R1gwUWcxSVRXeG4vOVpHWURXOFBBUnA1bW ZMampnCjV3Vy80TlNzRUtZbG1JMkhWQkFtYytjY3BDNUc5cngrS1ZVSWFSaTVjMDlTZlE1dFdxL zhscEl4MzBtVGJaUXMKanluNUx6SG1KVDh1QkRnS2swdWhMZXNTeWpENUhmdHJ3Q1ZSN2lVN0VF R3NyaG1INHJEdFdUNW85NytWVit5cgpsV09OTmJTbHhpK2RycWJsN3ZzQWJHRThEOHZyYkdncEd SbWpDQm5pVFpKbm1zVnBoazdpR0RBamFLYTcxYnovClpOeCsvdz09Cj1IZk5iCi0tLS0tRU5EIF BHUCBNRVNTQUdFLS0tLS0K X-Developer-Key: i=manos@pitsidianak.is; a=openpgp; fpr=7C721DF9DB3CC7182311C0BF68BC211D47B421E1 Allow Completion to wait interruptibly. Signed-off-by: Manos Pitsidianakis --- rust/kernel/sync/completion.rs | 42 ++++++++++++++++++++++++++++++++++++++= +++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/rust/kernel/sync/completion.rs b/rust/kernel/sync/completion.rs index c50012a940a3c7a3e0edf302c8f833bdc4415200..17c9e48a5359c0c885be9ebf684= 3e74d5abe56e5 100644 --- a/rust/kernel/sync/completion.rs +++ b/rust/kernel/sync/completion.rs @@ -6,7 +6,12 @@ //! //! C header: [`include/linux/completion.h`](srctree/include/linux/complet= ion.h) =20 -use crate::{bindings, prelude::*, types::Opaque}; +use crate::{ + bindings, + prelude::*, + time::Jiffies, + types::Opaque, // +}; =20 /// Synchronization primitive to signal when a certain task has been compl= eted. /// @@ -109,4 +114,39 @@ pub fn wait_for_completion(&self) { // SAFETY: `self.as_raw()` is a pointer to a valid `struct complet= ion`. unsafe { bindings::wait_for_completion(self.as_raw()) }; } + + /// Wait for completion of an interruptible task without a timeout. + /// + /// See also [`Completion::complete_all`]. + #[inline] + pub fn wait_for_completion_interruptible(&self) -> Result { + // SAFETY: `self.as_raw()` is a pointer to a valid `struct complet= ion`. + let err =3D unsafe { bindings::wait_for_completion_interruptible(s= elf.as_raw()) }; + if err < 0 { + Err(Error::from_errno(err)) + } else { + Ok(()) + } + } + + /// Wait for completion of an interruptible task with a timeout. + /// + /// See also [`Completion::complete_all`]. + #[inline] + pub fn wait_for_completion_interruptible_timeout( + &self, + timeout_jiffies: Jiffies, + ) -> Result { + // SAFETY: `self.as_raw()` is a pointer to a valid `struct complet= ion`. + let ret: c_long =3D unsafe { + bindings::wait_for_completion_interruptible_timeout(self.as_ra= w(), timeout_jiffies) + }; + if ret =3D=3D 0 { + return Err(ETIMEDOUT); + } + match Jiffies::try_from(ret) { + Ok(ret) =3D> Ok(ret), + Err(_) =3D> Err(Error::from_errno(ret as c_int)), + } + } } --=20 2.47.3 From nobody Sat Jun 13 06:06:38 2026 Received: from mail.nessuent.net (mail.nessuent.net [188.245.177.90]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id B6FC539B497; Sat, 9 May 2026 14:47:46 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=188.245.177.90 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1778338070; cv=none; b=UBwDSCTjHeqrls3txxS0L1BjAbrGet3P0LgnRRnmlYp0wvhD0ORwdxHsZd8jSYGjwU40ViWiVmgdBoGQm4Sh24bgjskAxXXJdDYExXvhGS4ngSyW0pkAb1B/jtbPHjJ6ZHFZzW14kFLlMx8sWrws6a5zdcGQsvAGzHsr5FYgsMs= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1778338070; c=relaxed/simple; bh=qckb076ZLmkTQMnhHO2Rcg5+MGTrGKXQy+PoUjxrU9U=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=mYISke2win4ZS7CsJwcXwcSYPDFFiqijE78/3QqgG1ZxIMBb9j+w3t/zHVqmK8+WxhA4jwI21C+yG6wXE9mGtm4b7wJLlmOhpV9Szfjjy6oOKZyyAKJBcX/2XrA6Li9wEyjVCqergxMHzSQZqQ2GZpUuuimDjDj/M3xYUjS4glQ= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=pitsidianak.is; spf=pass smtp.mailfrom=pitsidianak.is; dkim=pass (4096-bit key) header.d=pitsidianak.is header.i=@pitsidianak.is header.b=bdk9jD68; arc=none smtp.client-ip=188.245.177.90 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=pitsidianak.is Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=pitsidianak.is Authentication-Results: smtp.subspace.kernel.org; dkim=pass (4096-bit key) header.d=pitsidianak.is header.i=@pitsidianak.is header.b="bdk9jD68" DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=pitsidianak.is; s=mailSelector; t=1778338061; bh=qckb076ZLmkTQMnhHO2Rcg5+MGTrGKXQy+PoUjxrU9U=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From:Subject; b=bdk9jD68JrO/z3i34PuuuegbI3dondByP+6XagvCs945CbpbRJMDpjDlJdZATBevc 2jHcRXT9gZ+4Wq3gCO+g+YuYpRGWkwY9XWrsmzNRQnoRpz5hVx1T5urPk5oIl+aEXP /xOBnnAVQqXYrXUwY/jruqJ9Afd37gA4sIVHPKUa7H1FS53ocLzb31vjhMdztDpLum ZXumQCn4njkqoPSijkp+gEI9BT2APz9LY7XxQZjUoGTNOn2vQCoinij5hJT0Iq4Vfs p65AqurQg5ckQXGL/lFAjhjc6rYeZxFTiLWig5ccYvG8q6R5mveta5/xfW6v4A/A93 IQl74MGDsJpaWjdJ2QE3UsxHXPijNCxp5d8CP55329DMzn1jxs9HHq/6678MLG6ajD lVZmAbWQAV0TI6iQTik1K4uIzGDh8aH3MJLFF849KkU6lC48c+iJz4h1VKZEF5PPD+ Q9LUnCHo9sHbOBpFKtSTqq4s84SvreMhluJciW0fbjjCkspvBD8yDKxVn/GPv7KwNj 2r3yfO0eyKgNr8wqWV+5KQVRceTZB7OaawCIOR3ZLUwt0oqGJfOSNLwafmBT2mY4Bp mdne5N99ZkHJSqii/Ubvgk25Kwmg16/KM+4Vlmios2MimPjoRewJ/CXMwnG068NGoE /AfqXTaVNMufgcl5Vv7ttf48= From: Manos Pitsidianakis Date: Sat, 09 May 2026 17:47:00 +0300 Subject: [PATCH RFC v2 6/6] samples/rust: Add sample virtio-rtc driver [WIP] Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20260509-rust-virtio-v2-6-c1e30ec2bd21@pitsidianak.is> References: <20260509-rust-virtio-v2-0-c1e30ec2bd21@pitsidianak.is> In-Reply-To: <20260509-rust-virtio-v2-0-c1e30ec2bd21@pitsidianak.is> To: Miguel Ojeda Cc: Manos Pitsidianakis , Peter Hilber , Stefano Garzarella , Stefan Hajnoczi , Viresh Kumar , "Michael S. Tsirkin" , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , rust-for-linux@vger.kernel.org, Jason Wang , Xuan Zhuo , =?utf-8?q?Eugenio_P=C3=A9rez?= , virtualization@lists.linux.dev, linux-kernel@vger.kernel.org, Manos Pitsidianakis X-Developer-Signature: v=1; a=openpgp-sha256; l=18156; i=manos@pitsidianak.is; h=from:subject:message-id; bh=qckb076ZLmkTQMnhHO2Rcg5+MGTrGKXQy+PoUjxrU9U=; b=LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tCgpvd0VCYlFLUy9aQU5Bd0FLQVhjcHgzQi9mZ 25RQWNzbVlnQnAvMGtFVmNEYnNZYUVKR1NjcmJrN0RQL1h2Z0ZnCkwwZUlmbHR5dENLNCtiTXNQ V2FKQWpNRUFBRUtBQjBXSVFUTVhCdE9SS0JXODRkd0hSQjNLY2R3ZjM0SjBBVUMKYWY5SkJBQUt DUkIzS2Nkd2YzNEowRGN6RC85dHB0RVQvN2Zlb3FlMEJqU01ITG5DVEtTdU10bWphdGZiZnpDTQ orbHhSNTAvYkM2SW9wK1cxczVvdk42VFFaWWc1TmwrWjNaOXhtNTVyWUxhSTFIbFRuZXVYeFpZO E9JdnV3TU53CkkyWllScWVackRJV0NmNENhMkdvaU1TNGo5VUprUzN4bmdsdnNZdUlEOHNYczZ2 N1kzQWNQM25mQ29VTVAwdEQKSHhzamFab3ZWdDdsYzZWNEJ4YXNLVU56NElZSzZXczBKbUhoZEx mN0NqS0YybmtMaDNYWGZUcCtmcG9YRXl3UApJek9yTTVjOXo3QThCdFp3WU9PTDlLd3JoSU85YV RFazRqMGpqLzQvL1VManR5U1M0TjAwV2Y4Qm9pT1B4QlgxCmNnN1gvbk5DRG5OUDJVNGx1UUNkc Ws0RTU2MXFXWlo5cFBlcWtEOXgyakh3Wk5Ib3Zra2t1ZGQ4dVdoMEg4WGcKZzQwam0wSUxJdXVh ZUJJaW9LM0M2eEYrY3JtSXc2MUFwQkdEeXVydkZlZW5uZWl3M0I0V0VwMkpPOXhWdjErOQo0d2t yZ1FtT3lXRVZzaWVrcXJCZUtneFRRSEFmdnA2bHVJYnM2K0VXc2NrMVBRL015cTlWbkJsYW1ic2 hVdm9pCklJczRIMlVzM3B6RmplaUpuamFHM2JVVzRPRmpOSW5aN2h5ckE4YWJma3FRZEcwRG1MN EpEU2l4UU5iWmJZZzkKdXdhd1BhWHNENzcvUXZCNlBzOUxxNEIydGUvYWZOMTNDMi9TcGpRa05I UXdyZmFNSzVrSnNKVkVOREFpcXY4TgpTOUZBVUJSRWlUeUduVUozdUZGWWtNbVZ0cDB2RmFFWGg 4bWRCVkdHbGhQaTQrL3R6SDNxQ3NsMU9VTHBEYjFCCm9lcGR2dz09Cj0xT2ljCi0tLS0tRU5EIF BHUCBNRVNTQUdFLS0tLS0K X-Developer-Key: i=manos@pitsidianak.is; a=openpgp; fpr=7C721DF9DB3CC7182311C0BF68BC211D47B421E1 While the driver queries clocks and capabilities for each clock, it doesn't actually register them yet (TODO). Until I implement missing functionality, there is some dead code and some missing SAFETY comments. Signed-off-by: Manos Pitsidianakis --- MAINTAINERS | 1 + samples/rust/Kconfig | 15 ++ samples/rust/Makefile | 1 + samples/rust/rust_virtio_rtc.rs | 491 ++++++++++++++++++++++++++++++++++++= ++++ 4 files changed, 508 insertions(+) diff --git a/MAINTAINERS b/MAINTAINERS index e8012f708df5d4ee858c82aec3269e615fc8caad..3ed579e8d3cc64d1749cf261cd6= 8f6338a830c4d 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -27937,6 +27937,7 @@ S: Maintained F: rust/helpers/virtio.c F: rust/kernel/virtio.rs F: rust/kernel/virtio/ +F: samples/rust/rust_virtio_rtc.rs =20 VIRTIO CRYPTO DRIVER M: Gonglei diff --git a/samples/rust/Kconfig b/samples/rust/Kconfig index c49ab910634596aea4a1a73dac87585e084f420a..96a16aecc27198fd99f4ffd0ecd= f0bc0876860c6 100644 --- a/samples/rust/Kconfig +++ b/samples/rust/Kconfig @@ -179,4 +179,19 @@ config SAMPLE_RUST_HOSTPROGS =20 If unsure, say N. =20 +config SAMPLE_RUST_VIRTIO_RTC + tristate "Rust Virtio RTC driver" + depends on VIRTIO + depends on PTP_1588_CLOCK_OPTIONAL + help + This driver provides current time from a Virtio RTC device. The driver + provides the time through one or more clocks. The Virtio RTC PTP + clocks and/or the Real Time Clock driver for Virtio RTC must be + enabled to expose the clocks to userspace. + + To compile this code as a module, choose M here: the module will be + called rust_virtio_rtc. + + If unsure, say M. + endif # SAMPLES_RUST diff --git a/samples/rust/Makefile b/samples/rust/Makefile index 6c0aaa58ccccfd12ef019f68ca784f6d977bc668..0142fd8656bb8cdc95b7ef54e31= 83b5e51358954 100644 --- a/samples/rust/Makefile +++ b/samples/rust/Makefile @@ -16,6 +16,7 @@ obj-$(CONFIG_SAMPLE_RUST_DRIVER_FAUX) +=3D rust_driver_f= aux.o obj-$(CONFIG_SAMPLE_RUST_DRIVER_AUXILIARY) +=3D rust_driver_auxiliary.o obj-$(CONFIG_SAMPLE_RUST_CONFIGFS) +=3D rust_configfs.o obj-$(CONFIG_SAMPLE_RUST_SOC) +=3D rust_soc.o +obj-$(CONFIG_SAMPLE_RUST_VIRTIO_RTC) +=3D rust_virtio_rtc.o =20 rust_print-y :=3D rust_print_main.o rust_print_events.o =20 diff --git a/samples/rust/rust_virtio_rtc.rs b/samples/rust/rust_virtio_rtc= .rs new file mode 100644 index 0000000000000000000000000000000000000000..b12b188d4b1e91546a0c23558d7= 47033747ff3a9 --- /dev/null +++ b/samples/rust/rust_virtio_rtc.rs @@ -0,0 +1,491 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Rust virtio driver sample. + +use core::{ + marker::PhantomData, + ptr::NonNull, // + sync::atomic::{ + AtomicU16, + Ordering, // + }, +}; + +use kernel::{ + device::{ + Bound, + Core, // + }, + new_mutex, // + new_spinlock, // + page, + prelude::*, + scatterlist::SGEntry, + sync::Completion, + sync::{ + Mutex, + SpinLock, // + }, + virtio::{ + self, + utils::*, + virtqueue::*, // + }, +}; + +use pin_init::stack_try_pin_init; + +#[pin_data] +struct Token { + resp_actual_size: u32, + #[pin] + responded: Completion, +} + +#[pin_data] +struct Message { + msg_type: u16, + #[pin] + req: KVec, + #[pin] + resp: KVec, + req_ptr: NonNull, + resp_ptr: NonNull, + #[pin] + token: Token, + _ph_req: PhantomData, + _ph_resp: PhantomData, +} + +#[derive(Copy, Clone, Debug, Zeroable)] +#[repr(C)] +#[doc(alias =3D "virtio_rtc_req_head")] +struct ReqHead { + msg_type: Le16, + reserved: [u8; 6], +} + +#[derive(Copy, Clone, Debug, Zeroable)] +#[repr(C)] +#[doc(alias =3D "virtio_rtc_resp_head")] +struct RespHead { + status: u8, + reserved: [u8; 7], +} + +#[derive(Debug, Zeroable)] +#[repr(C)] +#[doc(alias =3D "virtio_rtc_resp_cfg")] +struct RespCfg { + head: RespHead, + /** # of clocks -> clock ids < num_clocks are valid */ + num_clocks: Le16, + reserved: [u8; 6], +} + +#[derive(Debug, Zeroable)] +#[repr(C)] +#[doc(alias =3D "virtio_rtc_req_clock_cap")] +struct ReqClockCap { + head: ReqHead, + clock_id: Le16, + reserved: [u8; 6], +} + +#[derive(Copy, Clone, Debug, Zeroable)] +#[repr(C)] +#[doc(alias =3D "virtio_rtc_resp_clock_cap")] +struct RespClockCap { + head: RespHead, + clock_type: u8, + leap_second_smearing: u8, + flags: u8, + reserved: [u8; 5], +} + +#[derive(Debug, Zeroable)] +#[repr(C)] +#[doc(alias =3D "virtio_rtc_req_read")] +struct ReqRead { + head: ReqHead, + clock_id: Le16, + reserved: [u8; 6], +} + +#[derive(Copy, Clone, Debug, Zeroable)] +#[repr(C)] +#[doc(alias =3D "virtio_rtc_resp_read")] +struct RespRead { + head: RespHead, + clock_reading: Le64, +} + +#[repr(u8)] +enum ClockType { + #[doc(alias =3D "VIRTIO_RTC_CLOCK_UTC")] + Utc =3D 0, + #[doc(alias =3D "VIRTIO_RTC_CLOCK_TAI")] + Tai =3D 1, + #[doc(alias =3D "VIRTIO_RTC_CLOCK_MONOTONIC")] + Monotonic =3D 2, + #[doc(alias =3D "VIRTIO_RTC_CLOCK_UTC_SMEARED")] + UtcSmeared =3D 3, + #[doc(alias =3D "VIRTIO_RTC_CLOCK_UTC_MAYBE_SMEARED")] + UtcMaybeSmeared =3D 4, +} + +// SAFETY: `Message` is safe to be send to any task. +unsafe impl Send for Message {} + +// SAFETY: `Message` is safe to be accessed concurrently. +unsafe impl Sync for Message {} + +impl Message { + /// Create an initializer for a new [`Message`]. + fn new(req_data: Request, msg_type: u16) -> Result> { + macro_rules! alloc_buf { + ($t:ty) =3D> {{ + let size =3D (core::mem::size_of::<$t>() / page::PAGE_SIZE= + 1) * page::PAGE_SIZE; + KVec::::with_capacity(size, GFP_KERNEL) + }}; + } + let mut req =3D alloc_buf!(Request)?; + let mut resp =3D alloc_buf!(Response)?; + let req_ptr: NonNull =3D NonNull::new(req.as_mut_ptr().ca= st()).unwrap(); + let resp_ptr =3D NonNull::new(resp.as_mut_ptr().cast()).unwrap(); + // SAFETY: `req_ptr` is a valid Request allocation + unsafe { + core::ptr::write(req_ptr.as_ptr(), req_data); + } + Ok(pin_init!(Self { + req, + resp, + msg_type, + req_ptr, + resp_ptr, + token <- pin_init!(Token { + resp_actual_size: 0, + responded <- Completion::new(), + }), + _ph_req: PhantomData, + _ph_resp: PhantomData, + }? Error)) + } + + fn get_response(&self) -> Result<&Response, Error> { + if self.token.resp_actual_size as usize !=3D core::mem::size_of::<= Response>() { + return Err(EINVAL); + } + if self.token.resp_actual_size as usize >=3D core::mem::size_of::<= RespHead>() { + let head: &RespHead =3D unsafe { self.resp_ptr.cast().as_ref()= }; + match head.status { + 0 =3D> { + // OK, do nothing. + } + 1 =3D> return Err(ENOTSUPP), + 2 =3D> return Err(ENODEV), + 3 =3D> return Err(EINVAL), + 4 | 5_u8..=3Du8::MAX =3D> return Err(EIO), + } + } else { + return Err(EINVAL); + } + Ok(unsafe { self.resp_ptr.as_ref() }) + } + + fn send(&self, vq: &SpinLock, timeout_jiffies: c_ulong) -= > Result { + let guard =3D vq.lock(); + + let mut sg_in =3D core::mem::MaybeUninit::zeroed(); + let mut sg_out =3D core::mem::MaybeUninit::zeroed(); + let req =3D unsafe { + SGEntry::init_one( + &mut sg_out, + self.req_ptr.cast(), + core::mem::size_of::() as u32, + ) + }; + let resp =3D unsafe { + SGEntry::init_one( + &mut sg_in, + self.resp_ptr.cast(), + core::mem::size_of::() as u32, + ) + }; + let sgs =3D [req, resp]; + // SAFETY: `self` lives at least as long until `Message::send` ret= urns + unsafe { + guard.as_ref().add_sgs( + &sgs, + 1, + 1, + NonNull::new((&raw const self.token).cast_mut().cast()).un= wrap(), + GFP_ATOMIC, + )?; + } + + if guard.as_ref().kick_prepare() { + guard.as_ref().notify(); + } + drop(guard); + + if timeout_jiffies > 0 { + self.token + .responded + .wait_for_completion_interruptible_timeout(timeout_jiffies= )?; + } else { + self.token.responded.wait_for_completion_interruptible()?; + } + Ok(()) + } +} + +// TODO: use a proper enum + +const VIRTIO_RTC_REQ_READ: u16 =3D 0x0001; +const VIRTIO_RTC_REQ_CFG: u16 =3D 0x1000; +const VIRTIO_RTC_REQ_CLOCK_CAP: u16 =3D 0x1001; + +struct VirtioRtcVq { + ptr: NonNull, +} + +// SAFETY: `VirtioRtcVq` is safe to be send to any task. +unsafe impl Send for VirtioRtcVq {} + +impl VirtioRtcVq { + fn new(ptr: *mut Virtqueue) -> impl PinInit> { + let ptr =3D NonNull::new(ptr).unwrap(); + new_spinlock!(Self { ptr }) + } + + fn as_ref(&self) -> &Virtqueue { + unsafe { self.ptr.as_ref() } + } +} + +struct VirtioRtcDriver { + reqvq: Pin>>, + alarmvq: Option>>>, + num_clocks: AtomicU16, + registered_clocks: Pin>>>, +} + +impl Drop for VirtioRtcDriver { + fn drop(&mut self) { + pr_info!("Remove Rust virtio driver sample.\n"); + } +} + +extern "C" fn vq_requestq_callback(vq: *mut kernel::bindings::virtqueue) { + // SAFETY: The kernel called this virtqueue callback and it must have = provided a valid `vq` + // pointer + let vq =3D unsafe { Virtqueue::from_raw(vq) }; + let dev: &virtio::Device =3D vq.dev().expect("Could not get dev= ice"); + let data =3D dev + .as_ref() + .drvdata::() + .expect("Could not borrow drvdata"); + data.process_requestq(); +} + +impl VirtioRtcDriver { + /// Submit `VIRTIO_RTC_REQ_CFG` and return response (`num_clocks`) + fn req_cfg(&self) -> Result { + let head =3D ReqHead { + msg_type: VIRTIO_RTC_REQ_CFG.into(), + reserved: [0; 6], + }; + stack_try_pin_init!( + let msg: Message:: =3D + Message::new(head, VIRTIO_RTC_REQ_CFG)?); + let msg: core::pin::Pin<&mut Message> =3D msg?; + msg.send(&self.reqvq, 0)?; + pr_info!("Got response! {:?}\n", msg.get_response()); + + let response: &RespCfg =3D msg.get_response()?; + Ok(response.num_clocks.into()) + } + + fn process_requestq(&self) { + let mut cb_enabled =3D true; + loop { + let guard =3D self.reqvq.lock(); + if cb_enabled { + guard.as_ref().disable_cb(); + cb_enabled =3D false; + } + if let Some((token, len)) =3D guard.as_ref().get_buf() { + drop(guard); + pr_info!("process_requestq got buf {len} bytes\n"); + let mut token =3D token.cast::(); + + unsafe { token.as_mut().resp_actual_size =3D len }; + unsafe { token.as_mut().responded.complete_all() }; + } else { + if guard.as_ref().enable_cb() { + return; + } + cb_enabled =3D true; + } + } + } + + fn clock_cap(&self, clock_id: u16) -> Result { + type ClockCapMsg =3D Message; + + let req =3D ReqClockCap { + head: ReqHead { + msg_type: VIRTIO_RTC_REQ_CLOCK_CAP.into(), + reserved: [0; 6], + }, + clock_id: clock_id.into(), + reserved: [0; 6], + }; + stack_try_pin_init!( + let msg: ClockCapMsg =3D Message::new(req, VIRTIO_RTC_REQ_CLOC= K_CAP)? + ); + let msg: core::pin::Pin<&mut ClockCapMsg> =3D msg?; + msg.send(&self.reqvq, 0)?; + pr_info!("Got response! {:?}\n", msg.get_response()); + let response: &RespClockCap =3D msg.get_response()?; + Ok(*response) + } + + fn read(&self, clock_id: u16) -> Result { + type ReadMsg =3D Message; + + let req =3D ReqRead { + head: ReqHead { + msg_type: VIRTIO_RTC_REQ_READ.into(), + reserved: [0; 6], + }, + clock_id: clock_id.into(), + reserved: [0; 6], + }; + stack_try_pin_init!( + let msg: ReadMsg =3D Message::new(req, VIRTIO_RTC_REQ_CLOCK_CA= P)? + ); + let msg: core::pin::Pin<&mut ReadMsg> =3D msg?; + msg.send(&self.reqvq, 0)?; + pr_info!("Got response! {:?}\n", msg.get_response()); + let response: &RespRead =3D msg.get_response()?; + Ok(response.clock_reading.into()) + } +} + +impl virtio::Driver for VirtioRtcDriver { + type IdInfo =3D (); + + /// The table of device ids supported by the driver. + const ID_TABLE: virtio::IdTable =3D &VIRTIO_RTC_TABLE; + + fn probe(vdev: &virtio::Device) -> impl PinInit { + const VQS_INFO: [VirtqueueInfo; 1] =3D [ + VirtqueueInfo::new(c"requestq", false, Some(vq_requestq_callba= ck)), + //VirtqueueInfo::new(c"alarmq", false, vq_callback), + ]; + let init_fn =3D move |slot: *mut Self| { + pr_info!("Probe Rust virtio driver sample.\n"); + let vqs =3D match vdev.find_vqs(&VQS_INFO) { + Ok(vqs) =3D> { + pr_info!("Found {} vqs.\n", vqs.len()); + vqs + } + Err(err) =3D> { + pr_info!("Could not find vqs: {err:?}.\n"); + + return Err(err); + } + }; + let reqvq =3D KBox::pin_init(VirtioRtcVq::new(vqs[0]), GFP_ATO= MIC)?; + let registered_clocks =3D + KBox::pin_init(new_mutex!(KVec::with_capacity(0, GFP_KERNE= L)?), GFP_KERNEL)?; + unsafe { + core::ptr::write( + slot, + Self { + num_clocks: AtomicU16::new(0), + reqvq, + alarmvq: None, + registered_clocks, + }, + ) + }; + Ok(()) + }; + unsafe { pin_init::pin_init_from_closure(init_fn) } + } + + fn init(&self, vdev: &virtio::Device) -> Result { + vdev.ready(); + self.num_clocks.store(self.req_cfg()?, Ordering::SeqCst); + for i in 0..(self.num_clocks.load(Ordering::SeqCst)) { + let mut is_exposed =3D false; + + let resp =3D self.clock_cap(i)?; + let (clock_type, leap_second_smearing, flags) =3D + (resp.clock_type, resp.leap_second_smearing, resp.flags); + if cfg!(CONFIG_VIRTIO_RTC_CLASS) + && (clock_type =3D=3D ClockType::Utc as u8 + || clock_type =3D=3D ClockType::UtcSmeared as u8 + || clock_type =3D=3D ClockType::UtcMaybeSmeared as u8) + { + // TODO: + + // ret =3D viortc_init_rtc_class_clock(viortc, vio_clk_id, + // clock_type, flags); + // if (ret < 0) + // return ret; + // if (ret > 0) + // is_exposed =3D true; + dev_warn!(vdev.as_ref(), "CONFIG_VIRTIO_RTC_CLASS TODO "); + } + + if cfg!(CONFIG_VIRTIO_RTC_PTP) { + // TODO: + + // ret =3D viortc_init_ptp_clock(viortc, vio_clk_id, cloc= k_type, + // leap_second_smearing); + // if (ret < 0) + // return ret; + // if (ret > 0) + // is_exposed =3D true; + // todo!() + dev_warn!(vdev.as_ref(), "CONFIG_VIRTIO_RTC_PTP TODO "); + } + + if !is_exposed { + dev_warn!( + vdev.as_ref(), + "cannot expose clock {i} (type {clock_type}, variant {= leap_second_smearing}, \ + flags {flags}) to userspace\n" + ); + } + let clock_reading =3D self.read(i)?; + pr_info!("#{i} clock reading =3D {clock_reading}\n"); + } + Ok(()) + } + + fn remove(vdev: &virtio::Device, _this: Pin<&Self>) { + pr_info!("Removing Rust virtio driver sample.\n"); + vdev.reset(); + vdev.del_vqs(); + } +} + +kernel::virtio_device_table!( + VIRTIO_RTC_TABLE, + MODULE_VIRTIO_RTC_TABLE, + ::IdInfo, + [(virtio::DeviceId::new(virtio::VirtioID::Clock), ())] +); + +kernel::module_virtio_driver! { + type: VirtioRtcDriver, + name: "rust_virtio_rtc", + authors: ["Manos Pitsidianakis"], + description: "Rust virtio driver", + license: "GPL v2", +} --=20 2.47.3