rust: allow minimum version of 1.83
Subsystems (2)
cover rust: allow minimum version of 1.83
This is the preview of moving the minimum supported Rust version forward to 1.83.0, which is the target for QEMU due to its support for the const_refs_to_static feature.
Being able to autogenerate all the reflection-like structs in qdev and VMState improves the type safety, but also requires annotating the types with the information needed to generate the structs. The const_refs_to_static feature is needed because this information resides in constants that refer to global variables (of types such as PropertyInfo, VMStateField or VMStateDescription).
This series does not cover enabling the newer compiler in CI because, while both Debian and Ubuntu have a new-enough Rust compiler to support 1.77, they pose problems for this further bump. For Debian, the bookworm release probably will not have new compilers and is supported by QEMU for roughly two more years. For Ubuntu, the situation is a bit weird because while Ubuntu 22.04 had new Rust compilers added until the summer of 2024, Ubuntu 24.04 is not adding packages for new versions.
A possible plan here is to split the configuration between "enable Rust" and "enable all devices written in Rust" as soon as new devices are contributed that are written in Rust. This way, the C versions of the pl011 and HPET devices can be used but the new boards/devices would only be available on Debian or Ubuntu by using rustup.
This series does not use *all* features enabled between 1.77 and 1.83; in particular it does not replace addr_of!/addr_of_mut! with "&raw" expressions.
Paolo
Paolo Bonzini (5):
meson, cargo: require Rust 1.83.0
rust: use inline const expressions
rust: vmstate: convert to use builder pattern
rust: vmstate: use const_refs_to_static
rust: qdev: const_refs_to_static
docs/devel/rust.rst | 30 +- meson.build | 6 +- rust/Cargo.toml | 2 +- rust/clippy.toml | 2 +- rust/hw/char/pl011/src/device.rs | 20 +- rust/hw/char/pl011/src/device_class.rs | 123 +++---- rust/hw/timer/hpet/src/hpet.rs | 173 ++++------ rust/qemu-api/src/assertions.rs | 4 - rust/qemu-api/src/callbacks.rs | 27 +- rust/qemu-api/src/chardev.rs | 2 +- rust/qemu-api/src/qdev.rs | 16 +- rust/qemu-api/src/timer.rs | 2 +- rust/qemu-api/src/vmstate.rs | 432 +++++++++++++++---------- rust/qemu-api/tests/tests.rs | 20 +- rust/qemu-api/tests/vmstate_tests.rs | 155 +++++---- 15 files changed, 517 insertions(+), 497 deletions(-)
Signature · 1 line
2.49.0
PATCH 1/5 meson, cargo: require Rust 1.83.0
--- docs/devel/rust.rst | 14 +++++--------- meson.build | 6 +++--- rust/Cargo.toml | 2 +- rust/clippy.toml | 2 +- 4 files changed, 10 insertions(+), 14 deletions(-)
docs/devel/rust.rst +5 -9
@@ -71,21 +71,17 @@ Building Rust code with ``--enable-modules`` is not supported yet. Supported tools ''''''''''''''' -QEMU supports rustc version 1.77.0 and newer. Notably, the following features -are missing: +QEMU supports rustc version 1.83.0 and newer. The following features +from relatively new versions of Rust are not used for historical reasons; +patches are welcome: * inline const expression (stable in 1.79.0), currently worked around with associated constants in the ``FnCall`` trait. -* associated constants have to be explicitly marked ``'static`` (`changed in +* associated constants are still explicitly marked ``'static`` (`changed in 1.81.0`__) -* ``&raw`` (stable in 1.82.0). Use ``addr_of!`` and ``addr_of_mut!`` instead, - though hopefully the need for raw pointers will go down over time. - -* ``new_uninit`` (stable in 1.82.0). This is used internally by the ``pinned_init`` - crate, which is planned for inclusion in QEMU, but it can be easily patched - out. +* ``&raw`` (stable in 1.82.0). * referencing statics in constants (stable in 1.83.0). For now use a const function; this is an important limitation for QEMU's migration stream
meson.build +3 -3
@@ -94,12 +94,12 @@ have_rust = have_rust and add_languages('rust', native: true, required: get_option('rust').disable_auto_if(not have_system)) if have_rust rustc = meson.get_compiler('rust') - if rustc.version().version_compare('<1.77.0') + if rustc.version().version_compare('<1.83.0') if get_option('rust').enabled() - error('rustc version ' + rustc.version() + ' is unsupported. Please upgrade to at least 1.77.0') + error('rustc version ' + rustc.version() + ' is unsupported. Please upgrade to at least 1.83.0') else warning('rustc version ' + rustc.version() + ' is unsupported, disabling Rust compilation.') - message('Please upgrade to at least 1.77.0 to use Rust.') + message('Please upgrade to at least 1.83.0 to use Rust.') have_rust = false endif endif
rust/Cargo.toml +1 -1
@@ -12,7 +12,7 @@ edition = "2021" homepage = "https://www.qemu.org" license = "GPL-2.0-or-later" repository = "https://gitlab.com/qemu-project/qemu/" -rust-version = "1.77.0" +rust-version = "1.83.0" [workspace.lints.rust] unexpected_cfgs = { level = "deny", check-cfg = [
rust/clippy.toml +1 -1
@@ -1,2 +1,2 @@ doc-valid-idents = ["PrimeCell", ".."] -msrv = "1.77.0" +msrv = "1.83.0"
Signature · 1 line
2.49.0
PATCH 2/5 rust: use inline const expressions
In reply to Paolo BonziniThey were stabilized in Rust 1.79.0.
--- docs/devel/rust.rst | 9 +++------ rust/qemu-api/src/callbacks.rs | 27 +-------------------------- rust/qemu-api/src/chardev.rs | 2 +- rust/qemu-api/src/qdev.rs | 2 +- rust/qemu-api/src/timer.rs | 2 +- rust/qemu-api/src/vmstate.rs | 2 +- 6 files changed, 8 insertions(+), 36 deletions(-)
docs/devel/rust.rst +3 -6
@@ -75,9 +75,6 @@ QEMU supports rustc version 1.83.0 and newer. The following features from relatively new versions of Rust are not used for historical reasons; patches are welcome: -* inline const expression (stable in 1.79.0), currently worked around with - associated constants in the ``FnCall`` trait. - * associated constants are still explicitly marked ``'static`` (`changed in 1.81.0`__)
@@ -88,9 +85,9 @@ patches are welcome: architecture (VMState). Right now, VMState lacks type safety because it is hard to place the ``VMStateField`` definitions in traits. -* associated const equality would be nice to have for some users of - ``callbacks::FnCall``, but is still experimental. ``ASSERT_IS_SOME`` - replaces it. +Associated const equality would be nice to have for some users of +``callbacks::FnCall``, but is still experimental. Const assertions +are used instead. __ https://github.com/rust-lang/rust/pull/125258
rust/qemu-api/src/callbacks.rs +1 -26
@@ -113,31 +113,6 @@/// This is always true for zero-capture closures and function pointers, as long /// as the code is able to name the function in the first place. pub unsafe trait FnCall <Args ,R = ()>: 'static +Sync +Sized { -/// Referring to this internal constant asserts that the `Self` type is -/// zero-sized. Can be replaced by an inline const expression in -/// Rust 1.79.0+. -const ASSERT_ZERO_SIZED : () = {assert! (mem::size_of ::<Self >() ==0 ) }; - -/// Referring to this constant asserts that the `Self` type is an actual -/// function type, which can be used to catch incorrect use of `()` -/// at compile time. -/// -/// # Examples -/// -/// ```compile_fail -/// # use qemu_api::callbacks::FnCall; -/// fn call_it<F: for<'a> FnCall<(&'a str,), String>>(_f: &F, s: &str) -> String { -/// let _: () = F::ASSERT_IS_SOME; -/// F::call((s,)) -/// } -/// -/// let s: String = call_it((), "hello world"); // does not compile -/// ``` -/// -/// Note that this can be more simply `const { assert!(F::IS_SOME) }` in -/// Rust 1.79.0 or newer. -const ASSERT_IS_SOME : () = {assert! (Self ::IS_SOME ) }; -/// `true` if `Self` is an actual function type and not `()`. /// /// # Examples
@@ -195,7 +170,7 @@ unsafe impl<F, $($args,)* R> FnCall<($($args,)*), R> for F#[inline(always)] fn call(a: ($($args,)*)) -> R { -let _: () =Self ::ASSERT_ZERO_SIZED ; +const {assert! (mem::size_of ::<Self >() ==0 ) };// SAFETY: the safety of this method is the condition for implementing // `FnCall`. As to the `NonNull` idiom to create a zero-sized type,
rust/qemu-api/src/chardev.rs +1 -1
@@ -138,7 +138,7 @@ pub fn enable_handlers<F ::call ((owner, event)) } -let _: () =CanReceiveFn ::ASSERT_IS_SOME ; +const {assert! (CanReceiveFn ::IS_SOME ) };let receive_cb:Option <unsafe extern "C" fn (*mut c_void , *const u8 ,c_int )> =if ReceiveFn ::is_some () {Some (rust_receive_cb ::<T ,ReceiveFn >)
rust/qemu-api/src/qdev.rs +1 -1
@@ -358,7 +358,7 @@ fn do_init_gpio_in( } } -let _: () =F ::ASSERT_IS_SOME ; +const {assert! (F ::IS_SOME ) };unsafe extern "C" fn rust_irq_handler <T ,F :for <'a>FnCall <(&'aT ,u32 ,u32 )>>( opaque: *mut c_void , line: c_int,
rust/qemu-api/src/timer.rs +1 -1
@@ -56,7 +56,7 @@ pub fn init_full<'timer, 'opaque: 'timer, T, F>( ) whereF :for <'a>FnCall <(&'aT ,)>, { -let _: () =F ::ASSERT_IS_SOME ; +const {assert! (F ::IS_SOME ) };/// timer expiration callback unsafe extern "C" fn rust_timer_handler<T, F: for<'a> FnCall<(&'a T,)>>(
rust/qemu-api/src/vmstate.rs +1 -1
@@ -457,7 +457,7 @@ macro_rules! vmstate_exist_fn {const fn test_cb_builder__ <T ,F :for <'a> $crate::callbacks::FnCall <(&'aT ,u8 ),bool >>( _phantom: ::core::marker::PhantomData <F >, ) -> $crate::vmstate::VMSFieldExistCb { -let _: () =F ::ASSERT_IS_SOME ; +const {assert! (F ::IS_SOME ) }; $crate::vmstate::rust_vms_test_field_exists ::<T ,F > }
Signature · 1 line
2.49.0
Re: [PATCH 2/5] rust: use inline const expressions
Quoted 16 lines · Paolo Bonzini
Date: Mon, 5 May 2025 12:08:51 +0200
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 2/5] rust: use inline const expressions
X-Mailer: git-send-email 2.49.0They were stabilized in Rust 1.79.0.
Signed-off-by Paolo Bonzini <[email protected]>--- docs/devel/rust.rst | 9 +++------ rust/qemu-api/src/callbacks.rs | 27 +-------------------------- rust/qemu-api/src/chardev.rs | 2 +- rust/qemu-api/src/qdev.rs | 2 +- rust/qemu-api/src/timer.rs | 2 +- rust/qemu-api/src/vmstate.rs | 2 +- 6 files changed, 8 insertions(+), 36 deletions(-)
...
rust/qemu-api/src/chardev.rs pub fn enable_handlers< · line 141
Quoted 10 lines
rust/qemu-api/src/chardev.rs +1
-1@@ -138,7 +138,7 @@ pub fn enable_handlers<F ::call ((owner, event)) } -let _: () =CanReceiveFn ::ASSERT_IS_SOME ; +const {assert! (CanReceiveFn ::IS_SOME ) };
Do you think it's a good idea to warp this as a helper for easy callback calls?
rust/qemu-api/src/chardev.rs pub fn enable_handlers< · line 144
Quoted 3 lines
rust/qemu-api/src/chardev.rs +0
-0let receive_cb:Option <unsafe extern "C" fn (*mut c_void , *const u8 ,c_int )> =if ReceiveFn ::is_some () {Some (rust_receive_cb ::<T ,ReceiveFn >)
Thanks,
Zhao
Re: [PATCH 2/5] rust: use inline const expressions
Quoted 5 lines · Zhao Liu
rust/qemu-api/src/chardev.rs pub fn enable_handlers< · line 141
Quoted 2 lines
rust/qemu-api/src/chardev.rs +1
-1-let _: () =CanReceiveFn ::ASSERT_IS_SOME ; +const {assert! (CanReceiveFn ::IS_SOME ) };Do you think it's a good idea to warp this as a helper for easy callback calls?
I think the wrapper would be very similar to what exists before this patch, wouldn't it? The const { assert!(...) } seems clear enough and not too verbose.
Paolo
PATCH 3/5 rust: vmstate: convert to use builder pattern
In reply to Paolo BonziniSimilar to MemoryRegionOps, the builder pattern has two advantages:
1) it makes it possible to build a VMStateDescription that knows which types it will be invoked on; 2) it provides a way to wrap the callbacks and let devices avoid "unsafe".
Unfortunately, building a static VMStateDescription requires the builder methods to be "const", and because the VMStateFields are *also* static, this requires const_refs_to_static. So this requires Rust 1.83.0.
--- docs/devel/rust.rst | 2 +- rust/hw/char/pl011/src/device.rs | 16 +- rust/hw/char/pl011/src/device_class.rs | 117 ++++++-------- rust/hw/timer/hpet/src/hpet.rs | 163 ++++++++----------- rust/qemu-api/src/qdev.rs | 6 +- rust/qemu-api/src/vmstate.rs | 214 ++++++++++++++++++++++++- rust/qemu-api/tests/tests.rs | 16 +- rust/qemu-api/tests/vmstate_tests.rs | 124 +++++++------- 8 files changed, 413 insertions(+), 245 deletions(-)
docs/devel/rust.rst +1 -1
@@ -152,7 +152,7 @@ module status ``qom`` stable ``sysbus`` stable ``timer`` stable -``vmstate`` proof of concept +``vmstate`` stable ``zeroable`` stable ================ ======================
rust/hw/char/pl011/src/device.rs +10 -6
@@ -2,7 +2,7 @@// Author(s): Manos Pitsidianakis <[email protected]> // SPDX-License-Identifier: GPL-2.0-or-later -use std::{ffi::CStr , mem::size_of, ptr::addr_of_mut}; +use std::{ffi::CStr , io, mem::size_of, ptr::addr_of_mut};use qemu_api::{ chardev::{CharBackend ,Chardev ,Event },
@@ -172,8 +172,8 @@ impl DeviceImpl for PL011State {fn properties () -> &'static [Property ] { &device_class::PL011_PROPERTIES } -fn vmsd () ->Option <&'staticVMStateDescription > { -Some (&device_class::VMSTATE_PL011 ) +fn vmsd () ->Option <VMStateDescription <Self >> { +Some (device_class::VMSTATE_PL011 ) }const REALIZE :Option <fn (&Self )> =Some (Self ::realize); }
@@ -457,10 +457,10 @@ pub fn put_fifo(&mut self, value: registers::Data) -> bool {false } -pub fn post_load (&mut self) ->Result <(), ()> { +pub fn post_load (&mut self) ->Result <(), io::ErrorKind > {/* Sanity-check input state */ if self.read_pos >= self.read_fifo.len () || self.read_count > self.read_fifo.len () { -return Err (()); +return Err (io::ErrorKind ::InvalidInput ); }if !self.fifo_enabled () && self.read_count >0 && self.read_pos >0 {
@@ -524,6 +524,10 @@ const fn clock_update(&self, _event: ClockEvent) {/* pl011_trace_baudrate_change(s); */ } +pub fn clock_needed (&self) ->bool { + self.migrate_clock + } +fn post_init (&self) { self.init_mmio (&self.iomem);for irqin self.interrupts.iter () {
@@ -629,7 +633,7 @@ fn update(&self) { } } -pub fn post_load (&self, _version_id:u32 ) ->Result <(), ()> { +pub fn post_load (&self, _version_id:u8 ) ->Result <(), io::ErrorKind > { self.regs.borrow_mut ().post_load () } }
rust/hw/char/pl011/src/device_class.rs +48 -69
134 lines not on this page · raw message
rust/hw/timer/hpet/src/hpet.rs +68 -95
219 lines not on this page · raw message
rust/qemu-api/src/qdev.rs +4 -2
@@ -120,7 +120,7 @@ fn properties() -> &'static [Property] {/// A `VMStateDescription` providing the migration format for the device /// Not a `const` because referencing statics in constants is unstable /// until Rust 1.83.0. -fn vmsd () ->Option <&'staticVMStateDescription > { +fn vmsd () ->Option <VMStateDescription <Self >> {None } }
@@ -169,7 +169,9 @@ pub fn class_init<T: DeviceImpl>(&mut self) { self.realize =Some (rust_realize_fn ::<T >); }if let Some (vmsd) = <T as DeviceImpl >::vmsd () { - self.vmsd = vmsd; +// Give a 'static lifetime to the return value of vmsd(). +// Temporary until vmsd() can be changed into a const. + self.vmsd =Box ::leak (Box ::new (vmsd.get ())); }let prop = <T as DeviceImpl >::properties ();if !prop.is_empty () {
rust/qemu-api/src/vmstate.rs +207 -7
243 lines not on this page · raw message
rust/qemu-api/tests/tests.rs +7 -9
@@ -12,18 +12,16 @@ qdev::{DeviceImpl, DeviceState, Property, ResettablePhasesImpl}, qom::{ObjectImpl, ParentField}, sysbus::SysBusDevice, - vmstate::VMStateDescription, - zeroable::Zeroable, + vmstate::{VMStateDescription, VMStateDescriptionBuilder}, };mod vmstate_tests;// Test that macros can compile. -pub static VMSTATE :VMStateDescription =VMStateDescription { - name:c"name" .as_ptr (), - unmigratable:true , - ..Zeroable ::ZERO -}; +pub const VMSTATE :VMStateDescription <DummyState > =VMStateDescriptionBuilder ::<DummyState >::new () + .name (c"name" ) + .unmigratable () + .build ();#[repr( C )] #[derive(qemu_api_macros:: Object )]
@@ -72,8 +70,8 @@ impl DeviceImpl for DummyState {fn properties () -> &'static [Property ] { &DUMMY_PROPERTIES } -fn vmsd () ->Option <&'staticVMStateDescription > { -Some (&VMSTATE ) +fn vmsd () ->Option <VMStateDescription <Self >> { +Some (VMSTATE ) } }
rust/qemu-api/tests/vmstate_tests.rs +68 -56
252 lines not on this page · raw message
Signature · 1 line
2.49.0
Re: [PATCH 3/5] rust: vmstate: convert to use builder pattern
rust/qemu-api/src/vmstate.rs macro_rules! vmstate_subsections { · line 629
Quoted 9 lines
rust/qemu-api/src/vmstate.rs +9
-0+unsafe extern "C" fn vmstate_pre_load_cb < +T , +F :for <'a>FnCall <(&'aT ,),Result <(),impl Into <Errno >>>, +>( + opaque: *mut c_void , +) ->c_int { +// SAFETY: assumes vmstate_struct! is used correctly +let result =F ::call ((unsafe { &*(opaque.cast ::<T >()) },)); +into_neg_errno (result)
Thanks! Now I see why you used io::ErrorKind.
Quoted 1 line
+}
...
rust/qemu-api/src/vmstate.rs macro_rules! vmstate_subsections { · line 723
Quoted 5 lines
rust/qemu-api/src/vmstate.rs +5
-0+#[must_use] +pub const fn pre_load <F :for <'a>FnCall <(&'aT ,),Result <(),impl Into <Errno >>>>( +mut self, + _f: &F , + ) ->Self {
Do we need to assert F is not ()?
const { assert!(F::IS_SOME) };
And I think all the other callbacks need to be checked as well.
rust/qemu-api/src/vmstate.rs macro_rules! vmstate_subsections { · line 726
Quoted 3 lines
rust/qemu-api/src/vmstate.rs +3
-0+ self.0 .pre_load =Some (vmstate_pre_load_cb ::<T ,F >); + self + }
Thank you :-) ! And though it's a preview,
Re: [PATCH 3/5] rust: vmstate: convert to use builder pattern
Quoted 23 lines · Zhao Liu
rust/qemu-api/src/vmstate.rs macro_rules! vmstate_subsections { · line 629
Quoted 10 lines
rust/qemu-api/src/vmstate.rs +9
-0+unsafe extern "C" fn vmstate_pre_load_cb < +T , +F :for <'a>FnCall <(&'aT ,),Result <(),impl Into <Errno >>>, +>( + opaque: *mut c_void , +) ->c_int { +// SAFETY: assumes vmstate_struct! is used correctly +let result =F ::call ((unsafe { &*(opaque.cast ::<T >()) },)); +into_neg_errno (result)Thanks! Now I see why you used
io::ErrorKind.Quoted 1 line
+}
...
rust/qemu-api/src/vmstate.rs macro_rules! vmstate_subsections { · line 723
Quoted 5 lines
rust/qemu-api/src/vmstate.rs +5
-0+#[must_use] +pub const fn pre_load <F :for <'a>FnCall <(&'aT ,),Result <(),impl Into <Errno >>>>( +mut self, + _f: &F , + ) ->Self {
Quoted 3 lines
Do we need to assert F is not ()?
const { assert!(F::IS_SOME) };
A NULL callback (i.e. ".pre_load(())") is a bit weird but acceptable. So the assertion if not needed, but indeed there should be an "if" that stores "ptr::null()" instead of vmstate_pre_load_cb::<F>.
Paolo
PATCH 4/5 rust: vmstate: use const_refs_to_static
In reply to Paolo BonziniThe VMStateDescriptionBuilder already needs const_refs_to_static, so use it to remove the need for vmstate_clock! and vmstate_struct!, as well as to simplify the implementation for scalars.
If the consts in the VMState trait can reference to static VMStateDescription, scalars do not need the info_enum_to_ref! indirection and structs can implement the VMState trait themselves.
--- docs/devel/rust.rst | 5 - rust/hw/char/pl011/src/device_class.rs | 14 +- rust/hw/timer/hpet/src/hpet.rs | 8 +- rust/qemu-api/src/assertions.rs | 4 - rust/qemu-api/src/vmstate.rs | 232 +++++++------------------ rust/qemu-api/tests/vmstate_tests.rs | 65 ++++--- 6 files changed, 116 insertions(+), 212 deletions(-)
docs/devel/rust.rst +0 -5
@@ -80,11 +80,6 @@ patches are welcome: * ``&raw`` (stable in 1.82.0). -* referencing statics in constants (stable in 1.83.0). For now use a const - function; this is an important limitation for QEMU's migration stream - architecture (VMState). Right now, VMState lacks type safety because - it is hard to place the ``VMStateField`` definitions in traits. - Associated const equality would be nice to have for some users of ``callbacks::FnCall``, but is still experimental. Const assertions are used instead.
rust/hw/char/pl011/src/device_class.rs +8 -6
@@ -4,9 +4,9 @@use qemu_api::{ bindings::{qdev_prop_bool, qdev_prop_chr}, - prelude::*, + impl_vmstate_struct, vmstate::{VMStateDescription ,VMStateDescriptionBuilder }, - vmstate_clock, vmstate_fields, vmstate_of, vmstate_struct, vmstate_subsections, vmstate_unused, + vmstate_fields, vmstate_of, vmstate_subsections, vmstate_unused, };use crate ::device::{PL011Registers ,PL011State };
@@ -19,11 +19,12 @@ .minimum_version_id(1) .needed (&PL011State ::clock_needed) .fields (vmstate_fields! { -vmstate_clock! (PL011State , clock), +vmstate_of! (PL011State , clock), }) .build (); -static VMSTATE_PL011_REGS :VMStateDescription <PL011Registers > = +impl_vmstate_struct! ( +PL011Registers ,VMStateDescriptionBuilder ::<PL011Registers >::new () .name (c"pl011/regs" ) .version_id (2 )
@@ -45,7 +46,8 @@ vmstate_of!(PL011Registers, read_count),vmstate_of! (PL011Registers , read_trigger), }) - .build (); + .build () +);pub const VMSTATE_PL011 :VMStateDescription <PL011State > =VMStateDescriptionBuilder ::<PL011State >::new ()
@@ -55,7 +57,7 @@ .post_load(&PL011State::post_load) .fields (vmstate_fields! {vmstate_unused! (core::mem::size_of ::<u32 >()), -vmstate_struct! (PL011State , regs, &VMSTATE_PL011_REGS ,BqlRefCell <PL011Registers >), +vmstate_of! (PL011State , regs), }) .subsections (vmstate_subsections! {VMSTATE_PL011_CLOCK
rust/hw/timer/hpet/src/hpet.rs +5 -3
@@ -16,6 +16,7 @@ qdev_prop_uint32, qdev_prop_uint8, }, cell::{BqlCell, BqlRefCell}, + impl_vmstate_struct, irq::InterruptSource, memory::{ hwaddr,MemoryRegion ,MemoryRegionOps ,MemoryRegionOpsBuilder ,MEMTXATTRS_UNSPECIFIED ,
@@ -27,7 +28,7 @@ sysbus::{SysBusDevice, SysBusDeviceImpl}, timer::{Timer, CLOCK_VIRTUAL, NANOSECONDS_PER_SECOND}, vmstate::{VMStateDescription, VMStateDescriptionBuilder}, - vmstate_fields, vmstate_of, vmstate_struct, vmstate_subsections, vmstate_validate, + vmstate_fields, vmstate_of, vmstate_subsections, vmstate_validate, };use crate ::fw_cfg::HPETFwConfig ;
@@ -967,7 +968,7 @@ impl ObjectImpl for HPETState { }) .build (); -static VMSTATE_HPET_TIMER :VMStateDescription <HPETTimer > = +const VMSTATE_HPET_TIMER :VMStateDescription <HPETTimer > =VMStateDescriptionBuilder ::<HPETTimer >::new () .name (c"hpet_timer" ) .version_id (1 )
@@ -982,6 +983,7 @@ impl ObjectImpl for HPETState { vmstate_of!(HPETTimer, qemu_timer), }) .build (); +impl_vmstate_struct! (HPETTimer ,VMSTATE_HPET_TIMER );const VALIDATE_TIMERS_NAME : &CStr =c"num_timers must match" ;
@@ -998,7 +1000,7 @@ impl ObjectImpl for HPETState { vmstate_of!(HPETState, counter), vmstate_of!(HPETState, num_timers_save).with_version_id(2), vmstate_validate!(HPETState, VALIDATE_TIMERS_NAME, HPETState::validate_num_timers), - vmstate_struct!(HPETState, timers[0 .. num_timers], &VMSTATE_HPET_TIMER, BqlRefCell<HPETTimer>, HPETState::validate_num_timers).with_version_id(0), + vmstate_of!(HPETState, timers[0 .. num_timers], HPETState::validate_num_timers).with_version_id(0), }) .subsections(vmstate_subsections!( VMSTATE_HPET_RTC_IRQ_LEVEL,
rust/qemu-api/src/assertions.rs +0 -4
@@ -95,10 +95,6 @@ fn types_must_be_equal<T, U>(_: &T) ($t:ty, $i:tt, $ti:ty) => { $crate::assert_field_type!(@internal v, $ti, $t, v.$i); }; - - ($t:ty, $i:tt, $ti:ty, num = $num:ident) => { - $crate::assert_field_type!(@internal v, $ti, $t, v.$i[0 ]); - }; }/// Assert that an expression matches a pattern. This can also be
rust/qemu-api/src/vmstate.rs +59 -173
378 lines not on this page · raw message
rust/qemu-api/tests/vmstate_tests.rs +44 -21
102 lines not on this page · raw message
Signature · 1 line
2.49.0
Re: [PATCH 4/5] rust: vmstate: use const_refs_to_static
rust/hw/timer/hpet/src/hpet.rs impl ObjectImpl for HPETState { · line 1004
Quoted 7 lines
rust/hw/timer/hpet/src/hpet.rs +1
-1@@ -998,7 +1000,7 @@ impl ObjectImpl for HPETState { vmstate_of!(HPETState, counter),vmstate_of! (HPETState , num_timers_save).with_version_id (2 ),vmstate_validate! (HPETState ,VALIDATE_TIMERS_NAME ,HPETState ::validate_num_timers), -vmstate_struct! (HPETState , timers[0 .. num_timers], &VMSTATE_HPET_TIMER ,BqlRefCell <HPETTimer >,HPETState ::validate_num_timers).with_version_id (0 ), +vmstate_of! (HPETState , timers[0 .. num_timers],HPETState ::validate_num_timers).with_version_id (0 ), })
The unified vmstate_of is indeed clean... it's more concise and easier to use than the C version.
PATCH 5/5 rust: qdev: const_refs_to_static
In reply to Paolo BonziniNow that const_refs_to_static can be assumed, convert the members of the DeviceImpl trait from functions to constants. This lets the compiler know that they have a 'static lifetime, and removes the need for the weird "Box::leak()".
--- rust/hw/char/pl011/src/device.rs | 8 ++------ rust/hw/timer/hpet/src/hpet.rs | 10 ++-------- rust/qemu-api/src/qdev.rs | 16 +++++----------- rust/qemu-api/tests/tests.rs | 8 ++------ 4 files changed, 11 insertions(+), 31 deletions(-)
rust/hw/char/pl011/src/device.rs +2 -6
@@ -169,12 +169,8 @@ impl ObjectImpl for PL011State { }impl DeviceImpl for PL011State { -fn properties () -> &'static [Property ] { - &device_class::PL011_PROPERTIES - } -fn vmsd () ->Option <VMStateDescription <Self >> { -Some (device_class::VMSTATE_PL011 ) - } +const PROPERTIES : &'static [Property ] = &device_class::PL011_PROPERTIES ; +const VMSTATE :Option <VMStateDescription <Self >> =Some (device_class::VMSTATE_PL011 );const REALIZE :Option <fn (&Self )> =Some (Self ::realize); }
rust/hw/timer/hpet/src/hpet.rs +2 -8
@@ -1009,14 +1009,8 @@ impl ObjectImpl for HPETState { .build();impl DeviceImpl for HPETState { -fn properties () -> &'static [Property ] { - &HPET_PROPERTIES - } - -fn vmsd () ->Option <VMStateDescription <Self >> { -Some (VMSTATE_HPET ) - } - +const PROPERTIES : &'static [Property ] = &HPET_PROPERTIES ; +const VMSTATE :Option <VMStateDescription <Self >> =Some (VMSTATE_HPET );const REALIZE :Option <fn (&Self )> =Some (Self ::realize); }
rust/qemu-api/src/qdev.rs +5 -11
@@ -113,16 +113,12 @@ pub trait DeviceImpl: ObjectImpl + ResettablePhasesImpl + IsA<DeviceState> {/// An array providing the properties that the user can set on the /// device. Not a `const` because referencing statics in constants /// is unstable until Rust 1.83.0. -fn properties () -> &'static [Property ] { - &[] - } +const PROPERTIES : &'static [Property ] = &[];/// A `VMStateDescription` providing the migration format for the device /// Not a `const` because referencing statics in constants is unstable /// until Rust 1.83.0. -fn vmsd () ->Option <VMStateDescription <Self >> { -None - } +const VMSTATE :Option <VMStateDescription <Self >> =None ; }/// # Safety
@@ -168,12 +164,10 @@ pub fn class_init<T: DeviceImpl>(&mut self) {if <T as DeviceImpl >::REALIZE .is_some () { self.realize =Some (rust_realize_fn ::<T >); } -if let Some (vmsd) = <T as DeviceImpl >::vmsd () { -// Give a 'static lifetime to the return value of vmsd(). -// Temporary until vmsd() can be changed into a const. - self.vmsd =Box ::leak (Box ::new (vmsd.get ())); +if let Some (ref vmsd) = <T as DeviceImpl >::VMSTATE { + self.vmsd = vmsd.as_ref (); } -let prop = <T as DeviceImpl >::properties (); +let prop = <T as DeviceImpl >::PROPERTIES ;if !prop.is_empty () {unsafe { bindings::device_class_set_props_n (self, prop.as_ptr (), prop.len ());
rust/qemu-api/tests/tests.rs +2 -6
@@ -67,12 +67,8 @@ impl ObjectImpl for DummyState {impl ResettablePhasesImpl for DummyState {}impl DeviceImpl for DummyState { -fn properties () -> &'static [Property ] { - &DUMMY_PROPERTIES - } -fn vmsd () ->Option <VMStateDescription <Self >> { -Some (VMSTATE ) - } +const PROPERTIES : &'static [Property ] = &DUMMY_PROPERTIES ; +const VMSTATE :Option <VMStateDescription <Self >> =Some (VMSTATE ); }#[repr( C )]
Signature · 1 line
2.49.0
Quoted 8 lines
This series does not cover enabling the newer compiler in CI because, while both Debian and Ubuntu have a new-enough Rust compiler to support 1.77, they pose problems for this further bump. For Debian, the bookworm release probably will not have new compilers and is supported by QEMU for roughly two more years. For Ubuntu, the situation is a bit weird because while Ubuntu 22.04 had new Rust compilers added until the summer of 2024, Ubuntu 24.04 is not adding packages for new versions.
Quoted 5 lines
A possible plan here is to split the configuration between "enable Rust" and "enable all devices written in Rust" as soon as new devices are contributed that are written in Rust. This way, the C versions of the pl011 and HPET devices can be used but the new boards/devices would only be available on Debian or Ubuntu by using rustup.
"enable Rust" supports v1.77 and "enable all devices written in Rust" supports v1.83, correct?
If so, do we need two versions of vmstate? one is for v1.77 (that HPET & pl011 can use), and another one is for v1.83 (newer devices based on v1.83 can use).
The current vmstate builder is excellent, but I'm concerned it might not land soon. Can we find a compromise?
Thanks,
Zhao
Quoted 9 lines · Zhao Liu
Quoted 9 lines
This series does not cover enabling the newer compiler in CI because, while both Debian and Ubuntu have a new-enough Rust compiler to support 1.77, they pose problems for this further bump. For Debian, the bookworm release probably will not have new compilers and is supported by QEMU for roughly two more years. For Ubuntu, the situation is a bit weird because while Ubuntu 22.04 had new Rust compilers added until the summer of 2024, Ubuntu 24.04 is not adding packages for new versions.
Quoted 8 lines
Quoted 5 lines
A possible plan here is to split the configuration between "enable Rust" and "enable all devices written in Rust" as soon as new devices are contributed that are written in Rust. This way, the C versions of the pl011 and HPET devices can be used but the new boards/devices would only be available on Debian or Ubuntu by using rustup.
"enable Rust" supports v1.77 and "enable all devices written in Rust" supports v1.83, correct?
Both support v1.83 only. However, if Rust is missing or old, "enable all devices written in Rust" will fail compilation (e.g. Kconfig would fail for ARM/x86 targets due to unsatisfiable CONFIG_PL011); "enable Rust" will simply pick the C version of the PL011 and HPET devices.
Quoted 2 lines
The current vmstate builder is excellent, but I'm concerned it might not land soon. Can we find a compromise?
Do you think the above would be a good compromise?
Paolo
Quoted 6 lines
Quoted 2 lines
"enable Rust" supports v1.77 and "enable all devices written in Rust" supports v1.83, correct?
Both support v1.83 only. However, if Rust is missing or old, "enable all devices written in Rust" will fail compilation (e.g.
Kconfigwould fail for ARM/x86 targets due to unsatisfiableCONFIG_PL011);
In this case, a brand new Rust device (without a corresponding C version) would be unable to compile on the above platforms which don't support v1.83. I'm not sure if this is an acceptable limitation or policy. (Has there been a similar case in history?)
Quoted 1 line
"enable Rust" will simply pick the C version of the PL011 and HPET devices.
I support this, at least the compatibility with the old QEMU won't be broken! Then all C devices rewritten in Rust can be covered by this category.
Quoted 4 lines
Quoted 2 lines
The current vmstate builder is excellent, but I'm concerned it might not land soon. Can we find a compromise?
Do you think the above would be a good compromise?
Overall, I think it's OK (it's not even a compromise).
Thanks,
Zhao
Quoted 11 lines · Zhao Liu
Quoted 6 lines
Quoted 2 lines
"enable Rust" supports v1.77 and "enable all devices written in Rust" supports v1.83, correct?
Both support v1.83 only. However, if Rust is missing or old, "enable all devices written in Rust" will fail compilation (e.g.
Kconfigwould fail for ARM/x86 targets due to unsatisfiableCONFIG_PL011);In this case, a brand new Rust device (without a corresponding C version) would be unable to compile on the above platforms which don't support v1.83. I'm not sure if this is an acceptable limitation or policy. (Has there been a similar case in history?)
Brand new features are not required to support all existing QEMU build targets, they can set whatever baseline is appropriate given the external dependencies they have.
With regards,
Daniel
Signature · 3 lines
|: https://berrange.com -o- https://www.flickr.com/photos/dberrange :| |: https://libvirt.org -o- https://fstop138.berrange.com :| |: https://entangle-photo.org -o- https://www.instagram.com/dberrange :|
Quoted 12 lines · Zhao Liu
Quoted 6 lines
Quoted 2 lines
"enable Rust" supports v1.77 and "enable all devices written in Rust" supports v1.83, correct?
Both support v1.83 only. However, if Rust is missing or old, "enable all devices written in Rust" will fail compilation (e.g.
Kconfigwould fail for ARM/x86 targets due to unsatisfiableCONFIG_PL011);In this case, a brand new Rust device (without a corresponding C version) would be unable to compile on the above platforms which don't support v1.83. I'm not sure if this is an acceptable limitation or policy. (Has there been a similar case in history?)
Quoted 5 lines
Quoted 1 line
"enable Rust" will simply pick the C version of the PL011 and HPET devices.
I support this, at least the compatibility with the old QEMU won't be broken! Then all C devices rewritten in Rust can be covered by this category.
I don't really like this because it perpetuates a state where we have parallel implementations of devices that have to be kept in sync.
If we're re-writing C devices in Rust, we need to be able to promptly drop the C impl once the Rust impl is feature complete. Keeping 2 impls is a general maint burden, as well as an ongoing vmstate compatibility danger if a change in one impl is not matched by an identical change in the other impl.
IMHO having Rust declared supported in QEMU should be aligned with being able to drop C impls of any ported devices.
With regards,
Daniel
Signature · 3 lines
|: https://berrange.com -o- https://www.flickr.com/photos/dberrange :| |: https://libvirt.org -o- https://fstop138.berrange.com :| |: https://entangle-photo.org -o- https://www.instagram.com/dberrange :|
Quoted 7 lines · Daniel P. Berrangé
Quoted 4 lines
Quoted 4 lines
[...] If Rust is missing or old, "enable
all devices written in Rust" will fail compilation (e.g.Kconfigwould fail for ARM/x86 targets due to unsatisfiableCONFIG_PL011); "enable Rust" will simply pick the C version of the PL011 and HPET devices.I don't really like this because it perpetuates a state where we have parallel implementations of devices that have to be kept in sync.
Me neither (see for example the Meson transition which avoided parallel implementations at all costs).
On the other hand, this series shows that it's hard to have a baseline version earlier than 1.83. The bindings got pretty far while supporting older versions, and the few hacks needed were nice testbeds for the build system and the procedural macro infrastructure, but the improvements that const_refs_to_static provides for reflection are just too big. And for Debian that means waiting until July 2027 before making Rust mandatory, and for Ubuntu that's April 2028 based on the current situation. I hope that the effort proves itself either valid or unviable in less than 2-3 years. :)
Now, it's certainly not the only possibility:
1) If someone contributes devices that are written in Rust then we could just drop the PL011 and/or HPET sample device. That's a pity but they would survive in git history and could be resurrected later.
2) Using RUSTC_BOOTSTRAP[1] allows enabling unstable features even in versions older than 1.83. Disadvantage: build system changes that will be obsolete soon(ish), plus the relevant compiler code obviously wasn't as tested as after stabilization. I'd prefer to avoid that, but hey---Linux does it.
3) Affected distros could use RUSTC_BOOTSTRAP themselves if they want, while upstream QEMU would only support rustup toolchains for Debian bookworm and Ubuntu up to 24.10. This only requires tests/lcitool/refresh changes, the disadvantage is that the project would renege on the general promise that we make on platform support.
Quoted 5 lines
If we're re-writing C devices in Rust, we need to be able to promptly drop the C impl once the Rust impl is feature complete. Keeping 2 impls is a general maint burden, as well as an ongoing vmstate compatibility danger if a change in one impl is not matched by an identical change in the other impl.
I agree. One more reason why "Let's Rewrite It In Rust" is more of a necessary evil to bootstrap the creation of bindings, and not a good idea in general.
Quoted 2 lines
IMHO having Rust declared supported in QEMU should be aligned with being able to drop C impls of any ported devices.
I agree in principle, though theory and practice may diverge.
Paolo
Quoted 12 lines · Paolo Bonzini
Quoted 7 lines · Daniel P. Berrangé
Quoted 4 lines
Quoted 4 lines
[...] If Rust is missing or old, "enable
all devices written in Rust" will fail compilation (e.g.Kconfigwould fail for ARM/x86 targets due to unsatisfiableCONFIG_PL011); "enable Rust" will simply pick the C version of the PL011 and HPET devices.I don't really like this because it perpetuates a state where we have parallel implementations of devices that have to be kept in sync.
Me neither (see for example the Meson transition which avoided parallel implementations at all costs).
Quoted 6 lines
On the other hand, this series shows that it's hard to have a baseline version earlier than 1.83. The bindings got pretty far while supporting older versions, and the few hacks needed were nice testbeds for the build system and the procedural macro infrastructure, but the improvements that
const_refs_to_staticprovides for reflection are just too big.
Admittedly I'm not actively working on the QEMU Rust code, but to me to feels the opposite - we've shown it is possible to write useful Rust code with the older version baseline. It may not be the ideal way we want the code to look, but that's a tradeoff we can make.
I very much worry that at any point in time there is *always* going to be something in a newer Rust that is very attractive to use, so we end up on a slippery slope where we're always going to be chasing the latest version to get a better way.
We've had the same situation with Meson where we initially set a temporary newer baseline to get some critical features we could not do without, and now have ended up in a situation where we are continually pushing newer & newer versions, because there is always something attractive in the new release.
Quoted 5 lines
Now, it's certainly not the only possibility:
1) If someone contributes devices that are written in Rust then we could just drop the PL011 and/or HPET sample device. That's a pity but they would survive in git history and could be resurrected later.
IMHO for Rust in QEMU we should be targetting both new features and existing feature ports - excluding existing feature ports would be tieing one of our hands behind our back limiting the potential benefits we can see.
Quoted 11 lines
2) Using RUSTC_BOOTSTRAP[1] allows enabling unstable features even in versions older than 1.83. Disadvantage: build system changes that will be obsolete soon(ish), plus the relevant compiler code obviously wasn't as tested as after stabilization. I'd prefer to avoid that, but hey---Linux does it.
3) Affected distros could use
RUSTC_BOOTSTRAPthemselves if they want, while upstream QEMU would only support rustup toolchains for Debian bookworm and Ubuntu up to 24.10. This only requires tests/lcitool/refresh changes, the disadvantage is that the project would renege on the general promise that we make on platform support.
Yes, this increasing defeats the benefit of defining our distro target. We wanted to set a clear baseline that we could unambiguously target, to give clarity to both users & contributors on when we could/ would impose new version requirements.
We've made exceptions for python, and then meson, and now Rust. We can rationalize it is as "users only need to do x, y & z to get newer stuff", but as we make more & more exceptions, this is a game of death by a 1000 cuts.
With regards,
Daniel
Signature · 3 lines
|: https://berrange.com -o- https://www.flickr.com/photos/dberrange :| |: https://libvirt.org -o- https://fstop138.berrange.com :| |: https://entangle-photo.org -o- https://www.instagram.com/dberrange :|
Il mar 6 mag 2025, 13:52 Daniel P. Berrangé <[email protected]> ha scritto:
Quoted 7 lines
Quoted 6 lines
On the other hand, this series shows that it's hard to have a baseline version earlier than 1.83. The bindings got pretty far while supporting older versions, and the few hacks needed were nice testbeds for the build system and the procedural macro infrastructure, but the improvements that
const_refs_to_staticprovides for reflection are just too big.
Quoted 5 lines
Admittedly I'm not actively working on the QEMU Rust code, but to me to feels the opposite - we've shown it is possible to write useful Rust code with the older version baseline. It may not be the ideal way we want the code to look, but that's a tradeoff we can make.
Yes it did go pretty far. But VMState is where you hit the barrier for a very specific reason: the thing that you want to produce (structs with pointers to other structs) isn't supported by compile time execution until that version, so you're stuck writing C-style code for migration. These structs have been very central to how QEMU does reflection, for more than 15 years, and there's no real workaround for that.
It's certainly possible to delay fully safe VMState some more, but perhaps not 2-3 years.
We've had the same situation with Meson where we initially set a
Quoted 5 lines
temporary newer baseline to get some critical features we could not do without, and now have ended up in a situation where we are continually pushing newer & newer versions, because there is always something attractive in the new release.
Most of the updates to Meson were done in the first year after switching, because of new features in Meson that were contributed specifically for use in QEMU. For example, "meson test" was improved to include all the features of the preexisting "make check" (and many more), which benefited all users of Meson. Since then we have only had one bleeding edge update in 2023, when Apple messed up their linker's --version and we had to update in order to help our macOS users (issue 1939).
Rust support does require more frequent updates to Meson because QEMU is actually quite an early adopter among large C projects. Apart from juggernauts like Firefox or Linux, I can only think of three: librsvg, GStreamer and Mesa. Even Chromium (which builds with GN) only uses it for some vendored third party libraries, with C++ bindings to Rust code. But I can make these updates optional for people that don't --enable-rust; at the same time I have no interest in building a pile of workarounds for those that do.
Anyhow while I am contributing Rust-related improvements to Meson, I have no plans, time or ability to contribute to Rust. :)
Quoted 11 lines
Now, it's certainly not the only possibility:
Quoted 4 lines
1) If someone contributes devices that are written in Rust then we could just drop the PL011 and/or HPET sample device. That's a pity but they would survive in git history and could be resurrected later.
IMHO for Rust in QEMU we should be targetting both new features and existing feature ports - excluding existing feature ports would be tieing one of our hands behind our back limiting the potential benefits we can see.
I agree.
Yes, this increasing defeats the benefit of defining our distro
Quoted 5 lines
target. We wanted to set a clear baseline that we could unambiguously target, to give clarity to both users & contributors on when we could/ would impose new version requirements.
We've made exceptions for python, and then meson, and now Rust.
We've never made exceptions for Python in the sense of requiring a custom Python interpreter. The interpreters we require have always been available in all supported distros. What we did is not using the distro's *sphinx* on enterprise distros whose default Python interpreter was way past EOL. (IMHO shipping in /usr/bin anything that can run user Python code is a mistake, because it conflicts with the idea that /usr/libexec/platform-python is invisible to the user).
That came a few years *after* Meson and it happened because it's harder and harder to support both very new and very old versions of Python, especially after EOL. Our desires in that respect conflict very much with how the Python community operates, unfortunately.
We can rationalize it is as "users only need to do x, y & z to get newer
Quoted 4 lines
stuff",
but as we make more & more exceptions, this is a game of death by a 1000 cuts.
I agree. But the Python change is mostly water under the bridge, and the bleeding edge Meson requirements could be made optional for those that don't use Rust, so I don't think it's too bad.
For Rust, this submission shows exactly what the benefit would be and the current status of the code shows how far you get without it. I don't want to sneak in anything, I have posted it for transparency and it's up to the community to discuss how to proceed. We can do so at the community call or wait until KVM Forum.
Thanks,
Paolo
Quoted 11 lines
With regards,
Daniel
--
|: https://berrange.com -o-
https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org -o-
https://fstop138.berrange.com :|
|: https://entangle-photo.org -o-
https://www.instagram.com/dberrange :|
Quoted 9 lines
Quoted 5 lines
If we're re-writing C devices in Rust, we need to be able to promptly drop the C impl once the Rust impl is feature complete. Keeping 2 impls is a general maint burden, as well as an ongoing vmstate compatibility danger if a change in one impl is not matched by an identical change in the other impl.
I agree. One more reason why "Let's Rewrite It In Rust" is more of a necessary evil to bootstrap the creation of bindings, and not a good idea in general.
Hi Paolo and Daniel, about this point, what things can be done to help the community move towards dropping duplicate impl?
For example, about HPET, add test cases (similar to tests/qtest/m48t59-test.c) to check register read/write to prove that the two impls are consistent?
Thanks,
Zhao