rust/hpet: Initial support for migration
cover rust/hpet: Initial support for migration
Hi all,
This series add the *initial* support for HPET migration.
This is *initial* because the current migration implementation introduces multiple *unsafe* callbacks (please refer Patch 8).
Before the vmstate builder, one possible cleanup approach is to wrap callbacks in the vmstate binding using a method similar to the vmstate_exist_fn macro.
However, this approach would also create a lot of repetitive code (since vmstate has so many callbacks: pre_load, post_load, pre_save, post_save, needed and dev_unplug_pending). Although it would be cleaner, it would somewhat deviate from the path of the vmstate builder.
Therefore, firstly focus on completing the functionality of HPET, and those current unsafe callbacks can at least clearly indicate the needed functionality of vmstate. The next step is to consider refactoring vmstate to move towards the vmstate builder direction.
Test this series with 3 migration cases:
* q35 (Rust HPET) -> q35 (Rust HPET)
* q35 (Rust HPET) -> q35 (C HPET)
* q35 (C HPET) -> q35 (Rust HPET)
Thanks and Best Regards,
Zhao
---
Zhao Liu (9):
rust/vmstate: Support field_exists check in vmstate_struct macro rust/vmstate: Support varray's num field wrapped in BqlCell rust/vmstate_test: Test varray with num field wrapped in BqlCell rust/vmstate_test: Fix typo in
test_vmstate_macro_array_of_pointer_wrapped()
rust/timer: Define NANOSECONDS_PER_SECOND binding as u64 rust/hpet: convert num_timers to u8 type
rust/hpet: convert HPETTimer index to u8 type rust/hpet: Support migration
rust/hpet: Fix a clippy error
docs/devel/rust.rst | 3 +- rust/hw/timer/hpet/src/hpet.rs | 189 ++++++++++++++++++++++++--- rust/qemu-api/src/assertions.rs | 30 ++++- rust/qemu-api/src/cell.rs | 23 ++++ rust/qemu-api/src/timer.rs | 2 + rust/qemu-api/src/vmstate.rs | 67 +++++----- rust/qemu-api/tests/vmstate_tests.rs | 45 +++++-- 7 files changed, 294 insertions(+), 65 deletions(-)
Signature · 1 line
2.34.1
PATCH 1/9 rust/vmstate: Support field_exists check in vmstate_struct macro
Unfortunately, at present it's not possible to have a const "with_exist_check" method to append test_fn after vmstate_struct (due to error on "constant functions cannot evaluate destructors" for F).
Before the vmstate builder, the only way to support "test_fn" is to extend vmstate_struct macro to add the such new optional member (and fortunately, Rust can still parse the current expansion!).
Abstract the previous callback implementation of vmstate_validate into a separate macro, and moves it before vmstate_struct for vmstate_struct to call.
Note that there's no need to add any extra flag for a new test_fn added in the VMStateField.
--- rust/qemu-api/src/vmstate.rs | 67 +++++++++++++++++++----------------- 1 file changed, 35 insertions(+), 32 deletions(-)
rust/qemu-api/src/vmstate.rs +35 -32
@@ -435,6 +435,38 @@ macro_rules! vmstate_unused { }}; } +pub extern "C" fn rust_vms_test_field_exists <T ,F :for <'a>FnCall <(&'aT ,u8 ),bool >>( + opaque: *mut c_void , + version_id:c_int , +) ->bool { +// SAFETY: the opaque was passed as a reference to `T`. +let owner: &T =unsafe { &*(opaque.cast ::<T >()) }; +let version:u8 = version_id.try_into ().unwrap (); +F ::call ((owner, version)) +} + +pub type VMSFieldExistCb =unsafe extern "C" fn ( + opaque: *mut std::os::raw::c_void , + version_id: std::os::raw::c_int , +) ->bool ; + +#[macro_export] +macro_rules! vmstate_exist_fn { + ($struct_name:ty, $test_fn:expr) => {{ +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 ; + $crate::vmstate::rust_vms_test_field_exists ::<T ,F > + } + +const fn phantom__ <T >(_: &T ) -> ::core::marker::PhantomData <T > { + ::core::marker::PhantomData + } +Some (test_cb_builder__ ::<$struct_name,_ >(phantom__ (&$test_fn))) + }}; +} +// FIXME: including the `vmsd` field in a `const` is not possible without // the const_refs_static feature (stabilized in Rust 1.83.0). Without it, // it is not possible to use VMS_STRUCT in a transparent manner using
@@ -445,7 +477,7 @@ macro_rules! vmstate_unused {#[doc(alias = "VMSTATE_STRUCT" )] #[macro_export] macro_rules! vmstate_struct { - ($struct_name:ty, $field_name:ident $([0 .. $num:ident $(* $factor:expr)?])?, $vmsd:expr, $type:ty $(,)?) => { + ($struct_name:ty, $field_name:ident $([0 .. $num:ident $(* $factor:expr)?])?, $vmsd:expr, $type:ty $(, $test_fn:expr)? $(,)?) => { $crate::bindings::VMStateField { name: ::core::concat!(::core::stringify!($field_name),"\0" ) .as_bytes ()
@@ -458,6 +490,7 @@ macro_rules! vmstate_struct { size: ::core::mem::size_of::<$type>(), flags: $crate::bindings::VMStateFlags::VMS_STRUCT, vmsd: $vmsd, + $(field_exists: $crate::vmstate_exist_fn!($struct_name, $test_fn),)? ..$crate::zeroable::Zeroable ::ZERO } $(.with_varray_flag_unchecked( $crate::call_func_with_field!(
@@ -514,43 +547,13 @@ macro_rules! vmstate_fields { }} } -pub extern "C" fn rust_vms_test_field_exists <T ,F :for <'a>FnCall <(&'aT ,u8 ),bool >>( - opaque: *mut c_void , - version_id:c_int , -) ->bool { -let owner: &T =unsafe { &*(opaque.cast ::<T >()) }; -let version:u8 = version_id.try_into ().unwrap (); -// SAFETY: the opaque was passed as a reference to `T`. -F ::call ((owner, version)) -} - -pub type VMSFieldExistCb =unsafe extern "C" fn ( - opaque: *mut std::os::raw::c_void , - version_id: std::os::raw::c_int , -) ->bool ; -#[doc(alias = "VMSTATE_VALIDATE" )] #[macro_export] macro_rules! vmstate_validate { ($struct_name:ty, $test_name:expr, $test_fn:expr $(,)?) => { $crate::bindings::VMStateField { name: ::std::ffi::CStr ::as_ptr ($test_name), - field_exists: { -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 ; - $crate::vmstate::rust_vms_test_field_exists ::<T ,F > - } - -const fn phantom__ <T >(_: &T ) -> ::core::marker::PhantomData <T > { - ::core::marker::PhantomData - } -Some (test_cb_builder__ ::<$struct_name,_ >(phantom__ (&$test_fn))) - }, + field_exists: $crate::vmstate_exist_fn!($struct_name, $test_fn), flags: $crate::bindings::VMStateFlags ( $crate::bindings::VMStateFlags ::VMS_MUST_EXIST .0 | $crate::bindings::VMStateFlags ::VMS_ARRAY .0 ,
Signature · 1 line
2.34.1
Re: [PATCH 1/9] rust/vmstate: Support field_exists check in vmstate_struct macro
Quoted 4 lines · Zhao Liu
Unfortunately, at present it's not possible to have a const "
with_exist_check" method to appendtest_fnaftervmstate_struct(due to error on "constant functions cannot evaluate destructors" forF).
Nothing that std::mem::forget() can't fix. ;) We know that the destructor is a no-op because FnCall is only implemented on zero-sized functions.
Another problem with such a method, however, is that you need VMStateField<T> for it to be type-safe. Implementing it on bindings::VMStateField gives no guarantee that the type of the argument to the function is the correct one. So this patch is okay too, but perhaps add a comment (not necessarily a doc comment) mentioning that VMStateField<T> is planned in order to remove the extra argument?
Thanks,
Paolo
PATCH 2/9 rust/vmstate: Support varray's num field wrapped in BqlCell
In reply to Zhao LiuCurrently, if the num field of a varray is not a numeric type, such as being placed in a wrapper, the array variant of assert_field_type will fail the check.
HPET currently wraps num_timers in BqlCell<>. Although BqlCell<> is not necessary from strictly speaking, it makes sense for vmstate to respect BqlCell.
The failure of assert_field_type is because it cannot convert BqlCell<T> into usize for use as the index.
Therefore, first, implement From trait for common numeric types on BqlCell<>. Then, abstract the wrapper and non-wrapper cases uniformly into a IntoUsize trait and make assert_field_type to get usize type index via IntoUsize trait.
--- rust/qemu-api/src/assertions.rs | 30 +++++++++++++++++++++++++++++- rust/qemu-api/src/cell.rs | 23 +++++++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-)
rust/qemu-api/src/assertions.rs +29 -1
@@ -22,6 +22,34 @@ impl<T> EqType for T {type Itself =T ; } +pub trait IntoUsize { +fn into_usize (v:Self ) ->usize ; +} + +macro_rules! impl_into_usize { + ($type:ty) => { +impl IntoUsize for $type { +fn into_usize (v:Self ) ->usize { + v.try_into ().unwrap () + } + } + +impl IntoUsize for crate ::cell::BqlCell <$type> { +fn into_usize (v:Self ) ->usize { +let tmp: $type = v.try_into ().unwrap (); + tmp.try_into ().unwrap () + } + } + }; +} + +// vmstate_n_elems() in C side supports such types. +impl_into_usize! (u8 ); +impl_into_usize! (u16 ); +impl_into_usize! (i32 ); +impl_into_usize! (u32 ); +impl_into_usize! (u64 ); +/// Assert that two types are the same. /// /// # Examples
@@ -101,7 +129,7 @@ fn types_must_be_equal<T, U>(_: T) T: $crate::assertions::EqType<Itself = U>, { } - let index: usize = v.$num.try_into().unwrap(); + let index: usize = $crate::assertions::IntoUsize::into_usize(v.$num); types_must_be_equal::<_, &$ti>(&v.$i[index]); } };
rust/qemu-api/src/cell.rs +23 -0
@@ -309,6 +309,29 @@ fn from(t: T) -> BqlCell<T> { } } +// Orphan rules don't like something like `impl<T> From<BqlCell<T>> for T`. +// It's enough to just implement Into for common types. +macro_rules! impl_into_inner { + ($type:ty) => { +impl From <BqlCell <$type>>for $type { +fn from (c:BqlCell <$type>) -> $type { + c.get () + } + } + }; +} + +impl_into_inner! (bool ); +impl_into_inner! (i8 ); +impl_into_inner! (i16 ); +impl_into_inner! (i32 ); +impl_into_inner! (i64 ); +impl_into_inner! (u8 ); +impl_into_inner! (u16 ); +impl_into_inner! (u32 ); +impl_into_inner! (u64 ); +impl_into_inner! (usize ); +impl <T : fmt::Debug +Copy > fmt::Debug for BqlCell <T > {fn fmt (&self, f: &mut fmt::Formatter <'_>) -> fmt::Result { self.get ().fmt (f)
Signature · 1 line
2.34.1
Re: [PATCH 2/9] rust/vmstate: Support varray's num field wrapped in BqlCell
Quoted 7 lines · Zhao Liu
Currently, if the
numfield of a varray is not a numeric type, such as being placed in a wrapper, the array variant ofassert_field_typewill fail the check.HPET currently wraps
num_timersin BqlCell<>. Although BqlCell<> is not necessary from strictly speaking, it makes sense for vmstate to respect BqlCell.
Dropping BqlCell<> from num_timers is indeed possible. But I agree that getting BqlCell<> varrays to work is a good thing anyway; then you can separately decide whether to drop BqlCell<> from num_timers.
Quoted 8 lines
The failure of
assert_field_typeis because it cannot convert BqlCell<T> into usize for use as the index.Therefore, first, implement
Fromtrait for common numeric types on BqlCell<>. Then, abstract the wrapper and non-wrapper cases uniformly into aIntoUsizetrait and makeassert_field_typeto get usize type index viaIntoUsizetrait.
Quoted 5 lines
Signed-off-by Zhao Liu <[email protected]>--- rust/qemu-api/src/assertions.rs | 30 +++++++++++++++++++++++++++++- rust/qemu-api/src/cell.rs | 23 +++++++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-)
I think you can drop the "num=" case of assert_field_type!, and use something like this macro:
/// Drop everything up to the colon, with the intention that /// if_present! is called inside an optional macro substitution /// (such as $(... $arg ...)? or $(... $arg ...)*). This allows /// expanding $result depending on the presence of an argument, /// even if the argument itself is not included in $result. ///
/// # Examples
///
/// ```
/// # use qemu_api::if_present;
/// macro_rules! is_present {
/// ($($cond:expr)?) => {
/// loop {
/// $(if_present!([$cond]: break true;);)? /// #[allow(unreachable_code)] /// break false;
/// }
/// }
/// }
///
/// assert!(!is_present!());
/// assert!(is_present!("abc"));
/// ```
#[macro_export]
macro_rules! if_present {
([$($cond:tt)*]: $($result:tt)*) => { $($result)* };
}to expand the array part of the access:
assert_field_type!(...
$($crate::if_present!([$num]: [0]))?;
);
With this change, assert_field_type! is nicer and at least the trait you're introducing in assertions.rs goes away...
rust/qemu-api/src/cell.rs fn from(t: T) -> BqlCell<T> { · line 322
Quoted 11 lines
rust/qemu-api/src/cell.rs +11
-0+// Orphan rules don't like something like `impl<T> From<BqlCell<T>> for T`. +// It's enough to just implement Into for common types. +macro_rules! impl_into_inner { + ($type:ty) => { +impl From <BqlCell <$type>>for $type { +fn from (c:BqlCell <$type>) -> $type { + c.get () + } + } + }; +}
... and it's not clear to me whether this is needed with the change above? Would impl_vmstate_transparent!'s definition of VARRAY_FLAG be enough?
If not, I *think* you can do a blanket implementation of Into<T> for BqlCell<T>. Maybe that's nicer, you can decide.
Paolo
Re: [PATCH 2/9] rust/vmstate: Support varray's num field wrapped in BqlCell
Quoted 10 lines · Paolo Bonzini
Date: Tue, 15 Apr 2025 12:54:51 +0200
From: Paolo Bonzini <[email protected]>
Subject: Re: [PATCH 2/9]rust/vmstate: Support varray's num field wrapped
in BqlCellQuoted 4 lines · Zhao Liu
Currently, if the
numfield of a varray is not a numeric type, such as being placed in a wrapper, the array variant ofassert_field_typewill fail the check.
Quoted 5 lines
Quoted 3 lines
HPET currently wraps
num_timersin BqlCell<>. Although BqlCell<> is not necessary from strictly speaking, it makes sense for vmstate to respect BqlCell.Dropping BqlCell<> from
num_timersis indeed possible.
I can move the num_timers adjustment from realize() into init().
Quoted 1 line
But I agree that getting BqlCell<> varrays to work is a good thing anyway;
While num_timers can get out of BqlCell<>, num_timers_save is still needed to stay in BqlCell<>, since I understand pre_save - as a callback of the vmstate - still needs the bql protection.
So this patch is still necessary to support migration for HPET.
Quoted 1 line
then you can separately decide whether to drop BqlCell<> from
num_timers.
Yes. In the next version, I can drop BqlCell<> and adjust the C version as well. But then I can't update the document at the same time, because the document needs to list the synchronized commit ID. I can update the document after the HPET migration is able to be merged.
Quoted 17 lines
Quoted 8 lines
The failure of
assert_field_typeis because it cannot convert BqlCell<T> into usize for use as the index.Therefore, first, implement
Fromtrait for common numeric types on BqlCell<>. Then, abstract the wrapper and non-wrapper cases uniformly into aIntoUsizetrait and makeassert_field_typeto get usize type index viaIntoUsizetrait.Quoted 5 lines
Signed-off-by Zhao Liu <[email protected]>--- rust/qemu-api/src/assertions.rs | 30 +++++++++++++++++++++++++++++- rust/qemu-api/src/cell.rs | 23 +++++++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-)I think you can drop the "num=" case of
assert_field_type!, and use something like this macro:
Quoted 11 lines
/// Drop everything up to the colon, with the intention that ///
if_present!is called inside an optional macro substitution /// (such as$(... $arg ...)?or$(... $arg ...)*). This allows /// expanding$resultdepending on the presence of an argument, /// even if the argument itself is not included in$result. ///
/// # Examples
///
/// ```
/// # useqemu_api::if_present;
///macro_rules!is_present{
I understand this is_present could have another name to avoid confusion with our real is_present macro.
Quoted 13 lines
/// ($($cond:expr)?) => {
/// loop {/// $(if_present!([$cond]: break true;);)? /// #[allow(unreachable_code)] /// break false;/// }
/// }
/// }
///
/// assert!(!is_present!());
/// assert!(is_present!("abc"));
/// ```
#[macro_export]
Quoted 8 lines
macro_rules! if_present { ([$($cond:tt)*]: $($result:tt)*) => { $($result)* }; }to expand the array part of the access:
assert_field_type!(...
$($crate::if_present!([$num]: [0]))?;
This example remind me that I introduced a bug into array part:
let index: usize = v.$num.try_into().unwrap();
types_must_be_equal::<_, &$ti>(&v.$i[index]);In the current code, actually it accesses v[num], but when num stores the length of the whole array, it will cause index out of bounds.
So for current code, at least it should access v.i[num - 1]:
let index: usize = v.$num.try_into().unwrap() - 1; // access the last element. types_must_be_equal::<_, &$ti>(&v.$i[index]);
Quoted 4 lines
);
With this change,
assert_field_type! is nicer and at least the trait you're introducing inassertions.rsgoes away...
Yes! Great idea.
Then with your help, we could integrate the array part like:
#[macro_export]
macro_rules! if_present {
([$($cond:tt)*]: $($result:tt)*) => { $($result)* };
}...
#[macro_export]
macro_rules! assert_field_type {
($t:ty, $i:tt, $ti:ty $(, $num:ident)?) => {
const _: () = {
#[allow(unused)]
fn assert_field_type(v: $t) {
fn types_must_be_equal<T, U>(_: T)
where
T: $crate::assertions::EqType<Itself = U>,
{
}
let access = v.$i$($crate::if_present!([$num]: [v.$num - 1])])?;
types_must_be_equal::<_, $ti>(access);
}
};
};
}Quoted 6 lines
Quoted 6 lines
rust/qemu-api/src/cell.rs +6
-0+// Orphan rules don't like something like `impl<T> From<BqlCell<T>> for T`. +// It's enough to just implement Into for common types. +macro_rules! impl_into_inner { + ($type:ty) => { +impl From <BqlCell <$type>>for $type { +fn from (c:BqlCell <$type>) -> $type {
Quoted 8 lines
rust/qemu-api/src/cell.rs fn from(t: T) -> BqlCell<T> { · line 322
Quoted 5 lines
rust/qemu-api/src/cell.rs +5
-0+ c.get () + } + } + }; +}... and it's not clear to me whether this is needed with the change above? Would impl_vmstate_transparent!'s definition of
VARRAY_FLAGbe enough?
If I change the array part like (the change is needed because: cannot subtract {integer} from BqlCell<u8>):
- let access = v.$i$([$crate::if_present!([$num]: v.$num) - 1])?;
+ let access = v.$i$([$crate::if_present!([$num]: v.$num).into() - 1])?;
Then there'll be an error:
85 | macro_rules! assert_field_type {
| ------------------------------ in this expansion of `$crate::assert_field_type!` (#2)...
96 | let access = v.$i$([$crate::if_present!([$num]: v.$num).into() - 1])?;
| ^^^^ cannot infer type
This is because I want to also check whether "num" would cause index out of bounds. If we just check the [0] element, then everything is OK...
Quoted 2 lines
If not, I *think* you can do a blanket implementation of Into<T> for BqlCell<T>. Maybe that's nicer, you can decide.
I tired this way, but there's 2 difficulities:
* Into<T> for BqlCell<T> will violate coherence rules:
error[E0119]: conflicting implementations of trait Into<_> for type cell::BqlCell<_>
--> qemu-api/src/cell.rs:312:1
|
312 | impl<T> Into<T> for BqlCell<T> {}
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| = note: conflicting implementation in crate core:
- impl<T, U> Into<U> for T
where U: From<T>;
* As index, we need to convert BqlCell<T> into T and then convert T into usize. :-(
Do you think there is a better way to check array[num -1]? (array's len() method also returns usize).
Or do you think whether it's necessary to check array[num -1]? (referring to C version, for example, VMSTATE_STRUCT_VARRAY_UINT8, it doesn't check the array's out of bounds case.)
Thanks,
Zhao
Re: [PATCH 2/9] rust/vmstate: Support varray's num field wrapped in BqlCell
Quoted 15 lines
Quoted 9 lines
#[macro_export]
macro_rules! if_present { ([$($cond:tt)*]: $($result:tt)*) => { $($result)* }; }to expand the array part of the access:
assert_field_type!(...
$($crate::if_present!([$num]: [0]))?;This example remind me that I introduced a bug into array part:
let index: usize = v.$num.try_into().unwrap(); types_must_be_equal::<_, &$ti>(&v.$i[index]);
Quoted 7 lines
In the current code, actually it accesses v[num], but when num stores the length of the whole array, it will cause index out of bounds.
So for current code, at least it should access
v.i[num - 1]:let index: usize = v.$num.try_into().unwrap() - 1; // access the last element. types_must_be_equal::<_, &$ti>(&v.$i[index]);
I realize that my thinking was wrong here! The v (with specific type) isn't a valid instance, and the variable num being passed isn't correctly initialized. Therefore, checking num's value here is meaningless; it's enough to just check if the type matches!
Quoted 17 lines
Quoted 4 lines
);
With this change,
assert_field_type! is nicer and at least the trait you're introducing inassertions.rsgoes away...Yes! Great idea.
Then with your help, we could integrate the array part like:
#[macro_export]
macro_rules! if_present { ([$($cond:tt)*]: $($result:tt)*) => { $($result)* }; }...
#[macro_export]
Quoted 12 lines
macro_rules! assert_field_type {
($t:ty, $i:tt, $ti:ty $(, $num:ident)?) => {
const _: () = {
#[allow(unused)]
fn assert_field_type(v: $t) {
fn types_must_be_equal<T, U>(_: T)
where
T: $crate::assertions::EqType<Itself = U>,
{
}
let access = v.$i$($crate::if_present!([$num]: [v.$num - 1])])?;So, the correct code should just check array[0] as you said:
let access = v.$i$($crate::if_present!([$num]: [0])])?;
Based on this, there's no need for anything else such as Into.
Quoted 5 lines
types_must_be_equal::<_, $ti>(access);
}
};
};
}Thanks,
Zhao
Re: [PATCH 2/9] rust/vmstate: Support varray's num field wrapped in BqlCell
Il mer 16 apr 2025, 14:14 Zhao Liu <[email protected]> ha scritto:
Quoted 7 lines
Quoted 1 line
let access = v.$i$($crate::if_present!([$num]: [v.$num -1])])?;
So, the correct code should just check array[0] as you said:
let access = v.$i$($crate::if_present!([$num]: [0])])?;
Except I think the if_present! call would not be in assert_field_type; it would be in the caller, i.e. vmstate.rs.
Paolo
Based on this, there's no need for anything else such as Into.
Quoted 11 lines
Quoted 6 lines
types_must_be_equal::<_, $ti>(access); } }; }; }Thanks,
Zhao
Re: [PATCH 2/9] rust/vmstate: Support varray's num field wrapped in BqlCell
In reply to Paolo BonziniQuoted 5 lines
Quoted 3 lines
HPET currently wraps
num_timersin BqlCell<>. Although BqlCell<> is not necessary from strictly speaking, it makes sense for vmstate to respect BqlCell.Dropping BqlCell<> from
num_timersis indeed possible.
Hi Paolo,
I would like to further discuss whether there's any safe issues.
num_timers is a property:
qemu_api::define_property!(
c"timers",
HPETState,
num_timers,
unsafe { &qdev_prop_uint8 },
u8,
default = HPET_MIN_TIMERS
),Then this means someone could set this property in C side or Rust side by:
DeviceState *hpet = qdev_new(TYPE_HPET);qdev_prop_set_uint8(hpet, "timers", 8);
(Though we haven't provide safe interface at Rust side to set property.)
Whatever this happens at C side or Rust side, this depends on QOM core code (in C) to overwrite the HPETState::num_timers directly.
Then after the call to qdev_prop_set_uint8() starts, all subsequent processes happen on the C side, so even though the rewriting of num_timers is runtime, there are no additional safety considerations because it doesn't cross FFI boundaries. Am I understanding this correctly?
Thanks,
Zhao
PATCH 3/9 rust/vmstate_test: Test varray with num field wrapped in BqlCell
In reply to Zhao Liu--- rust/qemu-api/tests/vmstate_tests.rs | 41 ++++++++++++++++++++++------ 1 file changed, 33 insertions(+), 8 deletions(-)
rust/qemu-api/tests/vmstate_tests.rs +33 -8
@@ -28,7 +28,7 @@// - VMSTATE_VARRAY_UINT16_UNSAFE // - VMSTATE_VARRAY_MULTIPLY #[repr( C )] -#[derive(qemu_api_macros::offsets)] +#[derive( Default , qemu_api_macros::offsets)] struct FooA { arr: [u8 ;FOO_ARRAY_MAX ], num:u16 ,
@@ -147,8 +147,9 @@ fn test_vmstate_varray_multiply() {// - VMSTATE_STRUCT_VARRAY_UINT8 // - (no C version) MULTIPLY variant of VMSTATE_STRUCT_VARRAY_UINT32 // - VMSTATE_ARRAY +// - VMSTATE_STRUCT_VARRAY_UINT8 with BqlCell wrapper & test_fn #[repr( C )] -#[derive(qemu_api_macros::offsets)] +#[derive( Default , qemu_api_macros::offsets)] struct FooB { arr_a: [FooA ;FOO_ARRAY_MAX ], num_a:u8 ,
@@ -158,6 +159,12 @@ struct FooB { val: bool,// FIXME: Use Timer array. Now we can't since it's hard to link savevm.c to test. arr_i64: [i64; FOO_ARRAY_MAX], + arr_a_wrap: [FooA; FOO_ARRAY_MAX], + num_a_wrap: BqlCell<u32>, +} + +fn validate_foob (_state: &FooB , _version_id:u8 ) ->bool { +true }static VMSTATE_FOOB :VMStateDescription =VMStateDescription {
@@ -170,13 +177,14 @@ struct FooB { vmstate_struct!(FooB, arr_a[0 .. num_a], &VMSTATE_FOOA, FooA).with_version_id(1), vmstate_struct!(FooB, arr_a_mul[0 .. num_a_mul * 32], &VMSTATE_FOOA, FooA).with_version_id(2), vmstate_of!(FooB, arr_i64), +vmstate_struct! (FooB , arr_a_wrap[0 .. num_a_wrap], &VMSTATE_FOOA ,FooA , validate_foob), }, ..Zeroable ::ZERO };#[test] fn test_vmstate_bool_v () { -let foo_fields: &[VMStateField ] =unsafe { slice::from_raw_parts (VMSTATE_FOOB .fields,6 ) }; +let foo_fields: &[VMStateField ] =unsafe { slice::from_raw_parts (VMSTATE_FOOB .fields,7 ) };// 1st VMStateField ("val") in VMSTATE_FOOB (corresponding to VMSTATE_BOOL_V) assert_eq! (
@@ -196,7 +204,7 @@ fn test_vmstate_bool_v() {#[test] fn test_vmstate_uint64 () { -let foo_fields: &[VMStateField ] =unsafe { slice::from_raw_parts (VMSTATE_FOOB .fields,6 ) }; +let foo_fields: &[VMStateField ] =unsafe { slice::from_raw_parts (VMSTATE_FOOB .fields,7 ) };// 2nd VMStateField ("wrap") in VMSTATE_FOOB (corresponding to VMSTATE_U64) assert_eq! (
@@ -216,7 +224,7 @@ fn test_vmstate_uint64() {#[test] fn test_vmstate_struct_varray_uint8 () { -let foo_fields: &[VMStateField ] =unsafe { slice::from_raw_parts (VMSTATE_FOOB .fields,6 ) }; +let foo_fields: &[VMStateField ] =unsafe { slice::from_raw_parts (VMSTATE_FOOB .fields,7 ) };// 3rd VMStateField ("arr_a") in VMSTATE_FOOB (corresponding to // VMSTATE_STRUCT_VARRAY_UINT8)
@@ -240,7 +248,7 @@ fn test_vmstate_struct_varray_uint8() {#[test] fn test_vmstate_struct_varray_uint32_multiply () { -let foo_fields: &[VMStateField ] =unsafe { slice::from_raw_parts (VMSTATE_FOOB .fields,6 ) }; +let foo_fields: &[VMStateField ] =unsafe { slice::from_raw_parts (VMSTATE_FOOB .fields,7 ) };// 4th VMStateField ("arr_a_mul") in VMSTATE_FOOB (corresponding to // (no C version) MULTIPLY variant of VMSTATE_STRUCT_VARRAY_UINT32)
@@ -266,7 +274,7 @@ fn test_vmstate_struct_varray_uint32_multiply() {#[test] fn test_vmstate_macro_array () { -let foo_fields: &[VMStateField ] =unsafe { slice::from_raw_parts (VMSTATE_FOOB .fields,6 ) }; +let foo_fields: &[VMStateField ] =unsafe { slice::from_raw_parts (VMSTATE_FOOB .fields,7 ) };// 5th VMStateField ("arr_i64") in VMSTATE_FOOB (corresponding to // VMSTATE_ARRAY)
@@ -283,9 +291,26 @@ fn test_vmstate_macro_array() {assert_eq! (foo_fields[4 ].flags,VMStateFlags ::VMS_ARRAY );assert! (foo_fields[4 ].vmsd.is_null ());assert! (foo_fields[4 ].field_exists.is_none ()); +} + +#[test] +fn test_vmstate_struct_varray_uint8_wrapper () { +let foo_fields: &[VMStateField ] =unsafe { slice::from_raw_parts (VMSTATE_FOOB .fields,7 ) }; +let mut foo_b:FooB =Default ::default (); +let foo_b_p = std::ptr::addr_of_mut!(foo_b).cast ::<c_void >(); + +// 6th VMStateField ("arr_a_wrap") in VMSTATE_FOOB (corresponding to +// VMSTATE_STRUCT_VARRAY_UINT8). Other fields are checked in +// test_vmstate_struct_varray_uint8. +assert_eq! ( +unsafe {CStr ::from_ptr (foo_fields[5 ].name) }.to_bytes_with_nul (), +b"arr_a_wrap\0" + ); +assert_eq! (foo_fields[5 ].num_offset,228 ); +assert! (unsafe { foo_fields[5 ].field_exists.unwrap ()(foo_b_p,0 ) });// The last VMStateField in VMSTATE_FOOB. -assert_eq! (foo_fields[5 ].flags,VMStateFlags ::VMS_END ); +assert_eq! (foo_fields[6 ].flags,VMStateFlags ::VMS_END ); }// =========================== Test VMSTATE_FOOC ===========================
Signature · 1 line
2.34.1
PATCH 4/9 rust/vmstate_test: Fix typo in test_vmstate_macro_array_of_pointer_wrapped()
In reply to Zhao Liutest_vmstate_macro_array_of_pointer_wrapped() tests the 3rd element, so fix the index.
--- rust/qemu-api/tests/vmstate_tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
rust/qemu-api/tests/vmstate_tests.rs +2 -2
@@ -408,12 +408,12 @@ fn test_vmstate_macro_array_of_pointer_wrapped() { );assert_eq! (foo_fields[3 ].offset, (FOO_ARRAY_MAX +2 ) *PTR_SIZE );assert_eq! (foo_fields[3 ].num_offset,0 ); -assert_eq! (foo_fields[2 ].info,unsafe { &vmstate_info_uint8 }); +assert_eq! (foo_fields[3 ].info,unsafe { &vmstate_info_uint8 });assert_eq! (foo_fields[3 ].version_id,0 );assert_eq! (foo_fields[3 ].size,PTR_SIZE );assert_eq! (foo_fields[3 ].num,FOO_ARRAY_MAX as i32 );assert_eq! ( - foo_fields[2 ].flags.0 , + foo_fields[3 ].flags.0 ,VMStateFlags ::VMS_ARRAY .0 |VMStateFlags ::VMS_ARRAY_OF_POINTER .0 );assert! (foo_fields[3 ].vmsd.is_null ());
Signature · 1 line
2.34.1
PATCH 5/9 rust/timer: Define NANOSECONDS_PER_SECOND binding as u64
In reply to Zhao LiuNANOSECONDS_PER_SECOND is often used in operations with get_ns(), which currently returns a u64.
Therefore, define a new NANOSECONDS_PER_SECOND binding is with u64 type to eliminate unnecessary type conversions (from u32 to u64).
--- rust/qemu-api/src/timer.rs | 2 ++ 1 file changed, 2 insertions(+)
rust/qemu-api/src/timer.rs +2 -0
@@ -121,3 +121,5 @@ pub fn get_ns(&self) -> u64 {pub const CLOCK_VIRTUAL :ClockType =ClockType { id:QEMUClockType ::QEMU_CLOCK_VIRTUAL , }; + +pub const NANOSECONDS_PER_SECOND :u64 =1000000000 ;
Signature · 1 line
2.34.1
PATCH 6/9 rust/hpet: convert num_timers to u8 type
In reply to Zhao LiuThe C version of HPET uses the uint8_t type for num_timers, and usize type in Rust version will break migration between the C and Rust versions.
So convert num_timers' type to u8 (consistent with the C version of HPET) to make it friendly for vmstate support.
Note the commit 7bda68e8e2b0 ("qdev, rust/hpet: fix type of HPET 'timers property") supports the usize type property, but the uint8 property has to be re-supported now.
--- rust/hw/timer/hpet/src/hpet.rs | 31 ++++++++++++++++++------------- 1 file changed, 18 insertions(+), 13 deletions(-)
rust/hw/timer/hpet/src/hpet.rs +18 -13
@@ -12,7 +12,7 @@use qemu_api::{ bindings::{ address_space_memory, address_space_stl_le, qdev_prop_bit, qdev_prop_bool, - qdev_prop_uint32, qdev_prop_usize, + qdev_prop_uint32, qdev_prop_uint8, }, c_str, cell::{BqlCell ,BqlRefCell },
@@ -34,9 +34,9 @@const HPET_REG_SPACE_LEN :u64 =0x400 ;// 1024 bytes /// Minimum recommended hardware implementation. -const HPET_MIN_TIMERS :usize =3 ; +const HPET_MIN_TIMERS :u8 =3 ;/// Maximum timers in each timer block. -const HPET_MAX_TIMERS :usize =32 ; +const HPET_MAX_TIMERS :u8 =32 ;/// Flags that HPETState.flags supports. const HPET_FLAG_MSI_SUPPORT_SHIFT :usize =0 ;
@@ -559,14 +559,19 @@ pub struct HPETState {/// HPET timer array managed by this timer block. #[doc(alias = "timer" )] - timers: [BqlRefCell<HPETTimer>; HPET_MAX_TIMERS], - num_timers: BqlCell<usize>, + timers: [BqlRefCell<HPETTimer>; HPET_MAX_TIMERS as usize], + num_timers: BqlCell<u8>,/// Instance id (HPET timer block ID). hpet_id: BqlCell<usize>, }impl HPETState { +// Get num_timers with `usize` type, which is useful to play with array index. +fn get_num_timers (&self) ->usize { + self.num_timers.get ().into () + } +const fn has_msi_flag (&self) ->bool { self.flags & (1 <<HPET_FLAG_MSI_SUPPORT_SHIFT ) !=0 }
@@ -628,7 +633,7 @@ fn set_cfg_reg(&self, shift: u32, len: u32, val: u64) { self.hpet_offset .set (ticks_to_ns (self.counter.get ()) -CLOCK_VIRTUAL .get_ns ()); -for timerin self.timers.iter ().take (self.num_timers.get ()) { +for timerin self.timers.iter ().take (self.get_num_timers ()) {let mut t = timer.borrow_mut ();if t.is_int_enabled () && t.is_int_active () {
@@ -640,7 +645,7 @@ fn set_cfg_reg(&self, shift: u32, len: u32, val: u64) {// Halt main counter and disable interrupt generation. self.counter.set (self.get_ticks ()); -for timerin self.timers.iter ().take (self.num_timers.get ()) { +for timerin self.timers.iter ().take (self.get_num_timers ()) { timer.borrow_mut ().del_timer (); } }
@@ -663,7 +668,7 @@ fn set_int_status_reg(&self, shift: u32, _len: u32, val: u64) {let new_val = val << shift;let cleared = new_val & self.int_status.get (); -for (index, timer)in self.timers.iter ().take (self.num_timers.get ()).enumerate () { +for (index, timer)in self.timers.iter ().take (self.get_num_timers ()).enumerate () {if cleared & (1 << index) !=0 { timer.borrow_mut ().update_irq (false ); }
@@ -737,7 +742,7 @@ fn realize(&self) {1 <<HPET_CAP_COUNT_SIZE_CAP_SHIFT |1 <<HPET_CAP_LEG_RT_CAP_SHIFT |HPET_CAP_VENDER_ID_VALUE <<HPET_CAP_VENDER_ID_SHIFT | - ((self.num_timers.get () -1 )as u64 ) <<HPET_CAP_NUM_TIM_SHIFT |// indicate the last timer + ((self.get_num_timers () -1 )as u64 ) <<HPET_CAP_NUM_TIM_SHIFT |// indicate the last timer (HPET_CLK_PERIOD * FS_PER_NS) << HPET_CAP_CNT_CLK_PERIOD_SHIFT, // 10 ns );
@@ -746,7 +751,7 @@ fn realize(&self) { }fn reset_hold (&self, _type:ResetType ) { -for timerin self.timers.iter ().take (self.num_timers.get ()) { +for timerin self.timers.iter ().take (self.get_num_timers ()) { timer.borrow_mut ().reset (); }
@@ -774,7 +779,7 @@ fn decode(&self, mut addr: hwaddr, size: u32) -> HPETAddrDecode {GlobalRegister ::try_from (addr).map (HPETRegister ::Global ) }else {let timer_id:usize = ((addr -0x100 ) /0x20 )as usize ; -if timer_id <= self.num_timers.get () { +if timer_id <= self.get_num_timers () {// TODO: Add trace point - trace_hpet_ram_[read|write]_timer_id(timer_id) TimerRegister ::try_from (addr &0x18 ) .map (|reg|HPETRegister ::Timer (&self.timers[timer_id], reg))
@@ -859,8 +864,8 @@ impl ObjectImpl for HPETState { c_str!("timers"),HPETState , num_timers, -unsafe { &qdev_prop_usize }, -usize , +unsafe { &qdev_prop_uint8 }, +u8 ,default =HPET_MIN_TIMERS ), qemu_api::define_property!(
Signature · 1 line
2.34.1
PATCH 7/9 rust/hpet: convert HPETTimer index to u8 type
In reply to Zhao LiuThe C version of HPET uses the uint8_t type for timer index ("tn"), and usize type in Rust version will break migration between the C and Rust versions.
So convert HPETTimer index' type to u8 (consistent with the C version of HPET) to make it friendly for vmstate support.
--- rust/hw/timer/hpet/src/hpet.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-)
rust/hw/timer/hpet/src/hpet.rs +5 -5
@@ -184,7 +184,7 @@ fn timer_handler(timer_cell: &BqlRefCell<HPETTimer>) {pub struct HPETTimer {/// timer N index within the timer block (`HPETState`) #[doc(alias = "tn" )] - index:usize , + index:u8 , qemu_timer:Timer ,/// timer block abstraction containing this timer state:NonNull <HPETState >,
@@ -210,7 +210,7 @@ pub struct HPETTimer { }impl HPETTimer { -fn init (&mut self, index:usize , state: &HPETState ) { +fn init (&mut self, index:u8 , state: &HPETState ) { *self =HPETTimer { index,// SAFETY: the HPETTimer will only be used after the timer
@@ -235,7 +235,7 @@ fn init(&mut self, index: usize, state: &HPETState) { Timer::NS, 0, timer_handler, - &state.timers[self.index], + &state.timers[self.index as usize], ) }
@@ -246,7 +246,7 @@ fn get_state(&self) -> &HPETState { }fn is_int_active (&self) ->bool { - self.get_state ().is_timer_int_active (self.index) + self.get_state ().is_timer_int_active (self.index.into ()) }const fn is_fsb_route_enabled (&self) ->bool {
@@ -611,7 +611,7 @@ fn handle_legacy_irq(&self, irq: u32, level: u32) {fn init_timer (&self) {for (index, timer)in self.timers.iter ().enumerate () { - timer.borrow_mut ().init (index, self); + timer.borrow_mut ().init (index.try_into ().unwrap (), self); } }
Signature · 1 line
2.34.1
PATCH 8/9 rust/hpet: Support migration
In reply to Zhao LiuBased on commit 1433e38cc8 ("hpet: do not overwrite properties on post_load"), add the basic migration support to Rust HPET.
The current migration implementation introduces multiple unsafe callbacks. Before the vmstate builder, one possible cleanup approach is to wrap callbacks in the vmstate binding using a method similar to the vmstate_exist_fn macro.
However, this approach would also create a lot of repetitive code (since vmstate has so many callbacks: pre_load, post_load, pre_save, post_save, needed and dev_unplug_pending). Although it would be cleaner, it would somewhat deviate from the path of the vmstate builder.
Therefore, firstly focus on completing the functionality of HPET, and those current unsafe callbacks can at least clearly indicate the needed functionality of vmstate. The next step is to consider refactoring vmstate to move towards the vmstate builder direction.
Additionally, update rust.rst about Rust HPET can support migration.
--- docs/devel/rust.rst | 3 +- rust/hw/timer/hpet/src/hpet.rs | 146 ++++++++++++++++++++++++++++++++- 2 files changed, 146 insertions(+), 3 deletions(-)
docs/devel/rust.rst +1 -2
@@ -153,8 +153,7 @@ QEMU includes four crates: .. [#issues] The ``pl011`` crate is synchronized with ``hw/char/pl011.c`` as of commit 02b1f7f61928. The ``hpet`` crate is synchronized as of - commit f32352ff9e. Both are lacking tracing functionality; ``hpet`` - is also lacking support for migration. + commit 1433e38cc8. Both are lacking tracing functionality. This section explains how to work with them.
rust/hw/timer/hpet/src/hpet.rs +145 -1
181 lines not on this page · raw message
Signature · 1 line
2.34.1
Re: [PATCH 8/9] rust/hpet: Support migration
Hi Paolo,
Based on the this patch, I simply copied your MemoryRegionOpsBuilder and quickly tried out the vmstate builder over a few cups of tea.
Although it can handle callbacks well, I found that the difficulty still lies in the fact that the vmstate_fields and vmstate_subsections macros cannot be eliminated, because any dynamic creation of arrays is not allowed in a static context! (As I understand it, lazy_static might still be needed.)
An additional difficult case is vmsd(). Passing the raw VMStateDescription looks not good, while passing the VMStateDescription<> wrapper requires bounding DeviceImpl with 'static. Ultimately, I added an extra StaticVMStateDescription trait to successfully compile... In any case, it's definitely still rough, but hope it helps and takes a small step forward.
(Thanks for the patch 2 comment, I'll reply later!)
Thanks,
Zhao
---
rust/hw/timer/hpet/src/hpet.rs +59 -91
@@ -4,7 +4,6 @@use std::{ ffi::CStr , - os::raw::{c_int, c_void}, pin::Pin , ptr::{addr_of_mut, null_mut,NonNull }, slice::from_ref,
@@ -27,9 +26,8 @@ qom_isa, sysbus::{SysBusDevice, SysBusDeviceImpl}, timer::{Timer, CLOCK_VIRTUAL, NANOSECONDS_PER_SECOND}, - vmstate::VMStateDescription, + vmstate::{StaticVMStateDescription, VMStateDescription, VMStateDescriptionBuilder}, vmstate_fields, vmstate_of, vmstate_struct, vmstate_subsections, vmstate_validate, - zeroable::Zeroable, };use crate ::fw_cfg::HPETFwConfig ;
@@ -943,104 +941,73 @@ impl ObjectImpl for HPETState { ), } -unsafe extern "C" fn hpet_rtc_irq_level_needed (opaque: *mut c_void ) ->bool { -// SAFETY: -// the pointer is convertible to a reference -let state: &HPETState =unsafe {NonNull ::new (opaque.cast ::<HPETState >()).unwrap ().as_ref () }; - state.is_rtc_irq_level_needed () -} - -unsafe extern "C" fn hpet_offset_needed (opaque: *mut c_void ) ->bool { -// SAFETY: -// the pointer is convertible to a reference -let state: &HPETState =unsafe {NonNull ::new (opaque.cast ::<HPETState >()).unwrap ().as_ref () }; - state.is_offset_needed () -} -unsafe extern "C" fn hpet_pre_save (opaque: *mut c_void ) ->c_int { -// SAFETY: -// the pointer is convertible to a reference -let state: &mut HPETState = -unsafe {NonNull ::new (opaque.cast ::<HPETState >()).unwrap ().as_mut () }; - state.pre_save ()as c_int -} - -unsafe extern "C" fn hpet_post_load (opaque: *mut c_void , version_id:c_int ) ->c_int { -// SAFETY: -// the pointer is convertible to a reference -let state: &mut HPETState = -unsafe {NonNull ::new (opaque.cast ::<HPETState >()).unwrap ().as_mut () }; -let version:u8 = version_id.try_into ().unwrap (); - state.post_load (version)as c_int -} - -static VMSTATE_HPET_RTC_IRQ_LEVEL :VMStateDescription =VMStateDescription { - name:c_str! ("hpet/rtc_irq_level" ).as_ptr (), - version_id:1 , - minimum_version_id:1 , - needed:Some (hpet_rtc_irq_level_needed), - fields:vmstate_fields! { -vmstate_of! (HPETState , rtc_irq_level), - }, - ..Zeroable ::ZERO -}; - -static VMSTATE_HPET_OFFSET :VMStateDescription =VMStateDescription { - name:c_str! ("hpet/offset" ).as_ptr (), - version_id:1 , - minimum_version_id:1 , - needed:Some (hpet_offset_needed), - fields:vmstate_fields! { -vmstate_of! (HPETState , hpet_offset), - }, - ..Zeroable ::ZERO -}; - -static VMSTATE_HPET_TIMER :VMStateDescription =VMStateDescription { - name:c_str! ("hpet_timer" ).as_ptr (), - version_id:1 , - minimum_version_id:1 , - fields:vmstate_fields! { -vmstate_of! (HPETTimer , index), -vmstate_of! (HPETTimer , config), -vmstate_of! (HPETTimer , cmp), -vmstate_of! (HPETTimer , fsb), -vmstate_of! (HPETTimer , period), -vmstate_of! (HPETTimer , wrap_flag), -vmstate_of! (HPETTimer , qemu_timer), - }, - ..Zeroable ::ZERO -}; +static VMSTATE_HPET_RTC_IRQ_LEVEL :VMStateDescription <HPETState > = +VMStateDescriptionBuilder ::<HPETState >::new () + .name (c_str! ("hpet/rtc_irq_level" )) + .version_id (1 ) + .minimum_version_id (1 ) + .needed (&HPETState ::is_rtc_irq_level_needed) + .fields (vmstate_fields! { +vmstate_of! (HPETState , rtc_irq_level), + }) + .build (); + +static VMSTATE_HPET_OFFSET :VMStateDescription <HPETState > = +VMStateDescriptionBuilder ::<HPETState >::new () + .name (c_str! ("hpet/offset" )) + .version_id (1 ) + .minimum_version_id (1 ) + .needed (&HPETState ::is_offset_needed) + .fields (vmstate_fields! { +vmstate_of! (HPETState , hpet_offset), + }) + .build (); + +static VMSTATE_HPET_TIMER :VMStateDescription <BqlRefCell <HPETTimer >> = +VMStateDescriptionBuilder ::<BqlRefCell <HPETTimer >>::new () + .name (c_str! ("hpet_timer" )) + .version_id (1 ) + .minimum_version_id (1 ) + .fields (vmstate_fields! { +vmstate_of! (HPETTimer , index), +vmstate_of! (HPETTimer , config), +vmstate_of! (HPETTimer , cmp), +vmstate_of! (HPETTimer , fsb), +vmstate_of! (HPETTimer , period), +vmstate_of! (HPETTimer , wrap_flag), +vmstate_of! (HPETTimer , qemu_timer), + }) + .build ();const VALIDATE_TIMERS_NAME : &CStr =c_str! ("num_timers must match" ); -static VMSTATE_HPET :VMStateDescription =VMStateDescription { - name:c_str! ("hpet" ).as_ptr (), - version_id:2 , - minimum_version_id:1 , - pre_save:Some (hpet_pre_save), - post_load:Some (hpet_post_load), - fields:vmstate_fields! { -vmstate_of! (HPETState , config), -vmstate_of! (HPETState , int_status), -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 ), - }, - subsections:vmstate_subsections! { -VMSTATE_HPET_RTC_IRQ_LEVEL , -VMSTATE_HPET_OFFSET , - }, - ..Zeroable ::ZERO -}; +static VMSTATE_HPET :VMStateDescription <HPETState > = +VMStateDescriptionBuilder ::<HPETState >::new () + .name (c_str! ("hpet" )) + .version_id (2 ) + .minimum_version_id (1 ) + .pre_save (&HPETState ::pre_save) + .post_load (&HPETState ::post_load) + .fields (vmstate_fields! { +vmstate_of! (HPETState , config), +vmstate_of! (HPETState , int_status), +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 ), + }) + .subsections (vmstate_subsections! ( +VMSTATE_HPET_RTC_IRQ_LEVEL , +VMSTATE_HPET_OFFSET , + )) + .build ();impl DeviceImpl for HPETState {fn properties () -> &'static [Property ] { &HPET_PROPERTIES } -fn vmsd () ->Option <&'staticVMStateDescription > { +fn vmsd () ->Option <&'staticdyn StaticVMStateDescription > {Some (&VMSTATE_HPET ) }
rust/qemu-api/src/qdev.rs +3 -3
@@ -20,7 +20,7 @@ irq::InterruptSource, prelude::*, qom::{ObjectClass, ObjectImpl, Owned}, - vmstate::VMStateDescription, + vmstate::{StaticVMStateDescription, VMStateDescription}, };/// A safe wrapper around [`bindings::Clock`].
@@ -121,7 +121,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 <&'staticdyn StaticVMStateDescription > {None } }
@@ -170,7 +170,7 @@ 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; + self.vmsd = vmsd.get_vmsd_ptr (); }let prop = <T as DeviceImpl >::properties ();if !prop.is_empty () {
rust/qemu-api/src/vmstate.rs +190 -6
219 lines not on this page · raw message
Re: [PATCH 8/9] rust/hpet: Support migration
Quoted 4 lines · Zhao Liu
Hi Paolo,
Based on the this patch, I simply copied your MemoryRegionOpsBuilder and quickly tried out the vmstate builder over a few cups of tea.
Good idea (the tea :)).
Quoted 4 lines
Although it can handle callbacks well, I found that the difficulty still lies in the fact that the
vmstate_fieldsandvmstate_subsectionsmacros cannot be eliminated, because any dynamic creation of arrays is not allowed in a static context!
Yes, this makes sense. Array size must be known inside a const function and the extra terminator at the end of fields and subsections cannot be added by the builder itself. c_str! has the same issue for the name, if I understand correctly.
Quoted 4 lines
An additional difficult case is
vmsd(). Passing the raw VMStateDescription looks not good, while passing the VMStateDescription<> wrapper requires bounding DeviceImpl with 'static. Ultimately, I added an extra StaticVMStateDescription trait to successfully compile...
Hmm I cannot fully understand it so I'll check it out later.
Quoted 2 lines
In any case, it's definitely still rough, but hope it helps and takes a small step forward.
Yes, of course---this:
+static VMSTATE_HPET_RTC_IRQ_LEVEL: VMStateDescription<HPETState> =
+ VMStateDescriptionBuilder::<HPETState>::new()
+ .name(c_str!("hpet/rtc_irq_level"))
+ .version_id(1)
+ .minimum_version_id(1)
+ .needed(&HPETState::is_rtc_irq_level_needed)
+ .fields(vmstate_fields! {+ vmstate_of!(HPETState, rtc_irq_level),
+ })
+ .build();
+
is readable, not foreign (it's similar to the MemoryRegionOps) and provides an easy way to insert FFI wrappers.
Right now it's now fully typesafe, because the VMStateField returned by vmstate_of! (as well as the arrays returned by vmstate_fields! and vmstate_subsections!) does not track that it's for an HPETState; but that's a small thing overall and getting the basic builder right is more important.
I also made a note to check which callbacks could have a Result<> as the return type, possibly reusing the Errno module (Result<(), ()> looks a bit silly); but that is also not needed for this early stage.
Just a couple notes:
Quoted 1 line
+ bindings::{VMStateDescription as RawVMStateDescription, VMStateFlags},
I would use bindings::VMStateDescription throughout, similar to how it's done in memory.rs.
rust/qemu-api/src/vmstate.rs macro_rules! vmstate_subsections { · line 663
Quoted 2 lines
rust/qemu-api/src/vmstate.rs +2
-0+pub const fn name (mut self, name_str: &CStr ) ->Self { + self.0 .name = ::std::ffi::CStr ::as_ptr (name_str);
This can use "name_str.as_ptr()" because the type of name_str is known (unlike in macros, such as define_property! or vmstate_validate!).
(By the way, talking about macros, I have just stumbled on the attrs crate, which is something to keep an eye on for when QOM/qdev bindings are extended along the lines of https://lore.kernel.org/qemu-devel/[email protected]/T/.
But I don't think procedural macros are a good match for VMState).
Paolo
Quoted 453 lines
(Thanks for the patch 2 comment, I'll reply later!)
Thanks,
Zhao---
rust/hw/timer/hpet/src/hpet.rs +59
-91@@ -4,7 +4,6 @@use std::{ ffi::CStr , - os::raw::{c_int, c_void}, pin::Pin , ptr::{addr_of_mut, null_mut,NonNull }, slice::from_ref,@@ -27,9 +26,8 @@ qom_isa, sysbus::{SysBusDevice, SysBusDeviceImpl}, timer::{Timer, CLOCK_VIRTUAL, NANOSECONDS_PER_SECOND}, - vmstate::VMStateDescription, + vmstate::{StaticVMStateDescription, VMStateDescription, VMStateDescriptionBuilder}, vmstate_fields, vmstate_of, vmstate_struct, vmstate_subsections, vmstate_validate, - zeroable::Zeroable, };use crate ::fw_cfg::HPETFwConfig ;@@ -943,104 +941,73 @@ impl ObjectImpl for HPETState { ), } -unsafe extern "C" fn hpet_rtc_irq_level_needed (opaque: *mut c_void ) ->bool { -// SAFETY: -// the pointer is convertible to a reference -let state: &HPETState =unsafe {NonNull ::new (opaque.cast ::<HPETState >()).unwrap ().as_ref () }; - state.is_rtc_irq_level_needed () -} - -unsafe extern "C" fn hpet_offset_needed (opaque: *mut c_void ) ->bool { -// SAFETY: -// the pointer is convertible to a reference -let state: &HPETState =unsafe {NonNull ::new (opaque.cast ::<HPETState >()).unwrap ().as_ref () }; - state.is_offset_needed () -} -unsafe extern "C" fn hpet_pre_save (opaque: *mut c_void ) ->c_int { -// SAFETY: -// the pointer is convertible to a reference -let state: &mut HPETState = -unsafe {NonNull ::new (opaque.cast ::<HPETState >()).unwrap ().as_mut () }; - state.pre_save ()as c_int -} - -unsafe extern "C" fn hpet_post_load (opaque: *mut c_void , version_id:c_int ) ->c_int { -// SAFETY: -// the pointer is convertible to a reference -let state: &mut HPETState = -unsafe {NonNull ::new (opaque.cast ::<HPETState >()).unwrap ().as_mut () }; -let version:u8 = version_id.try_into ().unwrap (); - state.post_load (version)as c_int -} - -static VMSTATE_HPET_RTC_IRQ_LEVEL :VMStateDescription =VMStateDescription { - name:c_str! ("hpet/rtc_irq_level" ).as_ptr (), - version_id:1 , - minimum_version_id:1 , - needed:Some (hpet_rtc_irq_level_needed), - fields:vmstate_fields! { -vmstate_of! (HPETState , rtc_irq_level), - }, - ..Zeroable ::ZERO -}; - -static VMSTATE_HPET_OFFSET :VMStateDescription =VMStateDescription { - name:c_str! ("hpet/offset" ).as_ptr (), - version_id:1 , - minimum_version_id:1 , - needed:Some (hpet_offset_needed), - fields:vmstate_fields! { -vmstate_of! (HPETState , hpet_offset), - }, - ..Zeroable ::ZERO -}; - -static VMSTATE_HPET_TIMER :VMStateDescription =VMStateDescription { - name:c_str! ("hpet_timer" ).as_ptr (), - version_id:1 , - minimum_version_id:1 , - fields:vmstate_fields! { -vmstate_of! (HPETTimer , index), -vmstate_of! (HPETTimer , config), -vmstate_of! (HPETTimer , cmp), -vmstate_of! (HPETTimer , fsb), -vmstate_of! (HPETTimer , period), -vmstate_of! (HPETTimer , wrap_flag), -vmstate_of! (HPETTimer , qemu_timer), - }, - ..Zeroable ::ZERO -}; +static VMSTATE_HPET_RTC_IRQ_LEVEL :VMStateDescription <HPETState > = +VMStateDescriptionBuilder ::<HPETState >::new () + .name (c_str! ("hpet/rtc_irq_level" )) + .version_id (1 ) + .minimum_version_id (1 ) + .needed (&HPETState ::is_rtc_irq_level_needed) + .fields (vmstate_fields! { +vmstate_of! (HPETState , rtc_irq_level), + }) + .build (); + +static VMSTATE_HPET_OFFSET :VMStateDescription <HPETState > = +VMStateDescriptionBuilder ::<HPETState >::new () + .name (c_str! ("hpet/offset" )) + .version_id (1 ) + .minimum_version_id (1 ) + .needed (&HPETState ::is_offset_needed) + .fields (vmstate_fields! { +vmstate_of! (HPETState , hpet_offset), + }) + .build (); + +static VMSTATE_HPET_TIMER :VMStateDescription <BqlRefCell <HPETTimer >> = +VMStateDescriptionBuilder ::<BqlRefCell <HPETTimer >>::new () + .name (c_str! ("hpet_timer" )) + .version_id (1 ) + .minimum_version_id (1 ) + .fields (vmstate_fields! { +vmstate_of! (HPETTimer , index), +vmstate_of! (HPETTimer , config), +vmstate_of! (HPETTimer , cmp), +vmstate_of! (HPETTimer , fsb), +vmstate_of! (HPETTimer , period), +vmstate_of! (HPETTimer , wrap_flag), +vmstate_of! (HPETTimer , qemu_timer), + }) + .build ();const VALIDATE_TIMERS_NAME : &CStr =c_str! ("num_timers must match" ); -static VMSTATE_HPET :VMStateDescription =VMStateDescription { - name:c_str! ("hpet" ).as_ptr (), - version_id:2 , - minimum_version_id:1 , - pre_save:Some (hpet_pre_save), - post_load:Some (hpet_post_load), - fields:vmstate_fields! { -vmstate_of! (HPETState , config), -vmstate_of! (HPETState , int_status), -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 ), - }, - subsections:vmstate_subsections! { -VMSTATE_HPET_RTC_IRQ_LEVEL , -VMSTATE_HPET_OFFSET , - }, - ..Zeroable ::ZERO -}; +static VMSTATE_HPET :VMStateDescription <HPETState > = +VMStateDescriptionBuilder ::<HPETState >::new () + .name (c_str! ("hpet" )) + .version_id (2 ) + .minimum_version_id (1 ) + .pre_save (&HPETState ::pre_save) + .post_load (&HPETState ::post_load) + .fields (vmstate_fields! { +vmstate_of! (HPETState , config), +vmstate_of! (HPETState , int_status), +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 ), + }) + .subsections (vmstate_subsections! ( +VMSTATE_HPET_RTC_IRQ_LEVEL , +VMSTATE_HPET_OFFSET , + )) + .build ();impl DeviceImpl for HPETState {fn properties () -> &'static [Property ] { &HPET_PROPERTIES } -fn vmsd () ->Option <&'staticVMStateDescription > { +fn vmsd () ->Option <&'staticdyn StaticVMStateDescription > {Some (&VMSTATE_HPET ) }rust/qemu-api/src/qdev.rs +3
-3@@ -20,7 +20,7 @@ irq::InterruptSource, prelude::*, qom::{ObjectClass, ObjectImpl, Owned}, - vmstate::VMStateDescription, + vmstate::{StaticVMStateDescription, VMStateDescription}, };/// A safe wrapper around [`bindings::Clock`]. @@ -121,7 +121,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 <&'staticdyn StaticVMStateDescription > {None } }@@ -170,7 +170,7 @@ 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; + self.vmsd = vmsd.get_vmsd_ptr (); }let prop = <T as DeviceImpl >::properties ();if !prop.is_empty () {rust/qemu-api/src/vmstate.rs +190
-6@@ -25,11 +25,18 @@//! functionality that is missing from `vmstate_of!`. use core::{marker::PhantomData , mem, ptr::NonNull }; -use std::os::raw::{c_int, c_void}; +use std::{ + ffi::CStr , + os::raw::{c_int, c_void}, +}; -pub use crate ::bindings::{VMStateDescription ,VMStateField }; +pub use crate ::bindings::{MigrationPriority ,VMStateField };use crate ::{ - bindings::VMStateFlags , callbacks::FnCall , prelude::*, qom::Owned , zeroable::Zeroable , + bindings::{VMStateDescription as RawVMStateDescription ,VMStateFlags }, + callbacks::FnCall , + prelude::*, + qom::Owned , + zeroable::Zeroable , };/// This macro is used to call a function with a generic argument bound @@ -489,7 +496,7 @@ macro_rules! vmstate_struct { }, size: ::core::mem::size_of::<$type>(), flags: $crate::bindings::VMStateFlags::VMS_STRUCT, - vmsd: $vmsd, + vmsd: $vmsd.get_vmsd_ptr(), $(field_exists: $crate::vmstate_exist_fn!($struct_name, $test_fn),)? ..$crate::zeroable::Zeroable ::ZERO } $(.with_varray_flag_unchecked(@@ -586,11 +593,188 @@ macro_rules! vmstate_subsections { ($($subsection:expr),*$(,)*) => {{static _SUBSECTIONS: $crate::vmstate::VMStateSubsectionsWrapper = $crate::vmstate::VMStateSubsectionsWrapper (&[ $({ -static _SUBSECTION: $crate::bindings::VMStateDescription = $subsection; +static _SUBSECTION: $crate::bindings::VMStateDescription = $subsection.get_vmsd (); ::core::ptr::addr_of!(_SUBSECTION) }),*, ::core::ptr::null () ]); - _SUBSECTIONS.0 .as_ptr () + &_SUBSECTIONS }} } + +pub struct VMStateDescription <T >(RawVMStateDescription ,PhantomData <fn (&T )>); + +// SAFETY: When a *const T is passed to the callbacks, the call itself +// is done in a thread-safe manner. The invocation is okay as long as +// T itself is `Sync`. +unsafe impl <T :Sync >Sync for VMStateDescription <T > {} + +#[derive( Clone )] +pub struct VMStateDescriptionBuilder <T >(RawVMStateDescription ,PhantomData <fn (&T )>); + +unsafe extern "C" fn vmstate_pre_load_cb <T ,F :for <'a>FnCall <(&'aT ,),i32 >>( + opaque: *mut c_void , +) ->c_int { +// SAFETY: the opaque was passed as a reference to `T`. +F ::call ((unsafe { &*(opaque.cast ::<T >()) },))as c_int +} + +unsafe extern "C" fn vmstate_post_load_cb <T ,F :for <'a>FnCall <(&'aT ,u8 ),i32 >>( + opaque: *mut c_void , + version_id:c_int , +) ->c_int { +// SAFETY: the opaque was passed as a reference to `T`. +let owner: &T =unsafe { &*(opaque.cast ::<T >()) }; +let version:u8 = version_id.try_into ().unwrap (); +F ::call ((owner, version))as c_int +} + +unsafe extern "C" fn vmstate_pre_save_cb <T ,F :for <'a>FnCall <(&'aT ,),i32 >>( + opaque: *mut c_void , +) ->c_int { +// SAFETY: the opaque was passed as a reference to `T`. +F ::call ((unsafe { &*(opaque.cast ::<T >()) },))as c_int +} + +unsafe extern "C" fn vmstate_post_save_cb <T ,F :for <'a>FnCall <(&'aT ,),i32 >>( + opaque: *mut c_void , +) ->c_int { +// SAFETY: the opaque was passed as a reference to `T`. +F ::call ((unsafe { &*(opaque.cast ::<T >()) },))as c_int +} + +unsafe extern "C" fn vmstate_needed_cb <T ,F :for <'a>FnCall <(&'aT ,),bool >>( + opaque: *mut c_void , +) ->bool { +// SAFETY: the opaque was passed as a reference to `T`. +F ::call ((unsafe { &*(opaque.cast ::<T >()) },)) +} + +unsafe extern "C" fn vmstate_dev_unplug_pending_cb <T ,F :for <'a>FnCall <(&'aT ,),bool >>( + opaque: *mut c_void , +) ->bool { +// SAFETY: the opaque was passed as a reference to `T`. +F ::call ((unsafe { &*(opaque.cast ::<T >()) },)) +} + +impl <T >VMStateDescriptionBuilder <T > { +#[must_use] +pub const fn name (mut self, name_str: &CStr ) ->Self { + self.0 .name = ::std::ffi::CStr ::as_ptr (name_str); + self + } + +#[must_use] +pub const fn unmigratable (mut self) ->Self { + self.0 .unmigratable =true ; + self + } + +#[must_use] +pub const fn early_setup (mut self) ->Self { + self.0 .early_setup =true ; + self + } + +#[must_use] +pub const fn version_id (mut self, version:u8 ) ->Self { + self.0 .version_id = versionas c_int ; + self + } + +#[must_use] +pub const fn minimum_version_id (mut self, min_version:u8 ) ->Self { + self.0 .minimum_version_id = min_versionas c_int ; + self + } + +#[must_use] +pub const fn priority (mut self, priority:MigrationPriority ) ->Self { + self.0 .priority = priority; + self + } + +#[must_use] +pub const fn pre_load <F :for <'a>FnCall <(&'aT ,),i32 >>(mut self, _f: &F ) ->Self { + self.0 .pre_load =Some (vmstate_pre_load_cb ::<T ,F >); + self + } + +#[must_use] +pub const fn post_load <F :for <'a>FnCall <(&'aT ,u8 ),i32 >>(mut self, _f: &F ) ->Self { + self.0 .post_load =Some (vmstate_post_load_cb ::<T ,F >); + self + } + +#[must_use] +pub const fn pre_save <F :for <'a>FnCall <(&'aT ,),i32 >>(mut self, _f: &F ) ->Self { + self.0 .pre_save =Some (vmstate_pre_save_cb ::<T ,F >); + self + } + +#[must_use] +pub const fn post_save <F :for <'a>FnCall <(&'aT ,),i32 >>(mut self, _f: &F ) ->Self { + self.0 .post_save =Some (vmstate_post_save_cb ::<T ,F >); + self + } + +#[must_use] +pub const fn needed <F :for <'a>FnCall <(&'aT ,),bool >>(mut self, _f: &F ) ->Self { + self.0 .needed =Some (vmstate_needed_cb ::<T ,F >); + self + } + +#[must_use] +pub const fn unplug_pending <F :for <'a>FnCall <(&'aT ,),bool >>(mut self, _f: &F ) ->Self { + self.0 .dev_unplug_pending =Some (vmstate_dev_unplug_pending_cb ::<T ,F >); + self + } + +#[must_use] +pub const fn fields (mut self, fields: *const VMStateField ) ->Self { + self.0 .fields = fields; + self + } + +#[must_use] +pub const fn subsections (mut self, subs: &'staticVMStateSubsectionsWrapper ) ->Self { + self.0 .subsections = subs.0 .as_ptr (); + self + } + +#[must_use] +pub const fn build (self) ->VMStateDescription <T > { +VMStateDescription ::<T >(self.0 ,PhantomData ) + } + +#[must_use] +pub const fn new () ->Self { +Self (RawVMStateDescription ::ZERO ,PhantomData ) + } +} + +impl <T >Default for VMStateDescriptionBuilder <T > { +fn default () ->Self { +Self ::new () + } +} + +impl <T >VMStateDescription <T > { +pub const fn get_vmsd (&self) ->RawVMStateDescription { + self.0 + } + +pub const fn get_vmsd_ptr (&self) -> *const RawVMStateDescription { + &self.0 as *const _ as *const RawVMStateDescription + } +} + +pub trait StaticVMStateDescription { +fn get_vmsd_ptr (&'static self) -> *const RawVMStateDescription ; +} + +impl <T >StaticVMStateDescription for VMStateDescription <T > { +fn get_vmsd_ptr (&'static self) -> *const RawVMStateDescription { + self.get_vmsd_ptr () + } +}
Re: [PATCH 8/9] rust/hpet: Support migration
Quoted 6 lines · Paolo Bonzini
Quoted 4 lines
An additional difficult case is
vmsd(). Passing the raw VMStateDescription looks not good, while passing the VMStateDescription<> wrapper requires bounding DeviceImpl with 'static. Ultimately, I added an extra StaticVMStateDescription trait to successfully compile...Hmm I cannot fully understand it so I'll check it out later.
So the problem is that, in a "&'a Foo<T>", T must also be "T: 'a". One solution is for vmsd() to return an Option<VMStateDescription<Self>>, and do Box::into_raw(Box::new(vmsd)) in the class_init method. Once we have const_refs_static, "fn vmsd()" can become a const and the Box is not needed anymore.
Also please turn get_vmsd_ptr() into get_vmsd_ref() so that we get more checks that things are not copied behind our back (leaving behind a dangling pointer)
I attach the conversion I did of the other devices and tests. I am not sure if it's possible to avoid having a huge patch to do everything at once (except HPET since that can be added separately).
Paolo
From d67d96e4da714b1ce6676c642dba28ff589c8902 Mon Sep 17 00:00:00 2001
From: Paolo Bonzini <[email protected]>
Date: Tue, 15 Apr 2025 17:29:24 +0200
Subject: [PATCH] convert everything to VMStateBuilder
--- rust/hw/char/pl011/src/device.rs | 17 ++- rust/hw/char/pl011/src/device_class.rs | 117 ++++++++----------- rust/hw/timer/hpet/src/hpet.rs | 149 ++++++++++--------------- rust/qemu-api/tests/tests.rs | 17 ++- rust/qemu-api/tests/vmstate_tests.rs | 139 +++++++++++------------ 5 files changed, 197 insertions(+), 242 deletions(-)
rust/hw/char/pl011/src/device.rs +13 -4
@@ -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); }
@@ -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,8 +633,13 @@ fn update(&self) { } } -pub fn post_load (&self, _version_id:u32 ) ->Result <(), ()> { - self.regs.borrow_mut ().post_load () +pub fn post_load (&self, _version_id:u8 ) ->i32 { +let result = self.regs.borrow_mut ().post_load (); +if result.is_err () { + -1 + }else { +0 + } } }
rust/hw/char/pl011/src/device_class.rs +48 -69
135 lines not on this page · raw message
rust/hw/timer/hpet/src/hpet.rs +58 -91
179 lines not on this page · raw message
rust/qemu-api/tests/tests.rs +8 -9
@@ -13,18 +13,17 @@ 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_str! ("name" ).as_ptr (), - unmigratable:true , - ..Zeroable ::ZERO -}; +pub const VMSTATE :VMStateDescription <DummyState > = +VMStateDescriptionBuilder ::<DummyState >::new () + .name (c_str! ("name" )) + .unmigratable () + .build ();#[derive(qemu_api_macros::offsets)] #[repr( C )]
@@ -74,8 +73,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 +70 -69
254 lines not on this page · raw message
Signature · 1 line
2.49.0
Re: [PATCH 8/9] rust/hpet: Support migration
Quoted 10 lines · Paolo Bonzini
Date: Tue, 15 Apr 2025 19:43:00 +0200
From: Paolo Bonzini <[email protected]>
Subject: Re: [PATCH 8/9]rust/hpet: Support migrationQuoted 5 lines · Paolo Bonzini
Quoted 4 lines
An additional difficult case is
vmsd(). Passing the raw VMStateDescription looks not good, while passing the VMStateDescription<> wrapper requires bounding DeviceImpl with 'static. Ultimately, I added an extra StaticVMStateDescription trait to successfully compile...
Quoted 7 lines
Quoted 1 line
Hmm I cannot fully understand it so I'll check it out later.
So the problem is that, in a "&'a Foo<T>", T must also be "T: 'a". One solution is for
vmsd()to return an Option<VMStateDescription<Self>>, and do Box::into_raw(Box::new(vmsd)) in theclass_initmethod. Once we haveconst_refs_static, "fnvmsd()" can become a const and the Box is not needed anymore.
Thanks so much, that's a good idea!
About Box::into_raw(Box::new(vmsd)), do you think it's necessary to use Box::leak(Box::new(*))? (though the Box<> isn't actively dropped during the class's existence)
pub fn class_init<T: DeviceImpl>(&mut self) {
...
if let Some(vmsd) = <T as DeviceImpl>::vmsd() {
let static_vmsd: &'static mut bindings::VMStateDescription = Box::leak(Box::new(vmsd.get_vmsd()));
self.vmsd = static_vmsd;
}
}Quoted 3 lines
Also please turn
get_vmsd_ptr()intoget_vmsd_ref()so that we get more checks that things are not copied behind our back (leaving behind a dangling pointer)
Sure!
Quoted 3 lines
I attach the conversion I did of the other devices and tests. I am not sure if it's possible to avoid having a huge patch to do everything at once (except HPET since that can be added separately).
Thank you again! From my initial thoughts: Splitting is also possible, but it requires first renaming VMStateDescription<T> to VMStateDescriptionWrapper<T>, then replacing it in pl011 and test (and hpet) one by one, and finally renaming it back to VMStateDescription<T>. If you prefer this approach, I can help you split your patch below.
Quoted 4 lines
rust/hw/timer/hpet/src/hpet.rs +4
-0+const VMSTATE_HPET :VMStateDescription <HPETState > = +VMStateDescriptionBuilder ::<HPETState >::new () + .name (c_str! ("hpet" )) + .version_id (2 )
rust/hw/timer/hpet/src/hpet.rs impl ObjectImpl for HPETState { · line 997
Quoted 10 lines
rust/hw/timer/hpet/src/hpet.rs +10
-0+ .minimum_version_id(1) + .pre_save (&HPETState ::pre_save) + .post_load (&HPETState ::post_load) + .fields (vmstate_fields! { +vmstate_of! (HPETState , config), +vmstate_of! (HPETState , int_status), +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 ),
And it seems like you don't oppose the hack in patch 1? ;-)
rust/hw/timer/hpet/src/hpet.rs impl ObjectImpl for HPETState { · line 1003
Quoted 6 lines
rust/hw/timer/hpet/src/hpet.rs +6
-0+ }) + .subsections (vmstate_subsections! ( +VMSTATE_HPET_RTC_IRQ_LEVEL , +VMSTATE_HPET_OFFSET , + )) + .build ();
Thanks,
Zhao
Re: [PATCH 8/9] rust/hpet: Support migration
Il mer 16 apr 2025, 12:00 Zhao Liu <[email protected]> ha scritto:
Quoted 3 lines
So the problem is that, in a "&'a Foo<T>", T must also be "T: 'a". One solution is for
vmsd()to return an Option<VMStateDescription<Self>>, and do
Box::into_raw(Box::new(vmsd))
Quoted 2 lines
in the
class_initmethod. Once we haveconst_refs_static, "fnvmsd()" can become a const and the Box is not needed anymore.
Thanks so much, that's a good idea!
About Box::into_raw(Box::new(vmsd)), do you think it's necessary to use
Box::leak(Box::new(*))? (though the Box<> isn't actively dropped during the class's existence)
It's the same; leak and into_raw only differ in the return type. You can use leak if you prefer.
Quoted 1 line
I attach the conversion I did of the other devices and tests. I
am not
Quoted 1 line
sure if it's possible to avoid having a huge patch to do
everything at
Quoted 1 line
once (except HPET since that can be added separately).
Thank you again! From my initial thoughts: Splitting is also possible, but it requires first renaming VMStateDescription<T> to VMStateDescriptionWrapper<T>, then replacing it in pl011 and test (and hpet) one by one, and finally renaming it back to VMStateDescription<T>. If you prefer this approach, I can help you split your patch below.
Or maybe first you keepvmsd() return Option<&bindings::VMStateDescription> and stick a get_vmsd_ref() in "fn vmsd()", then in a final patch you make it return Option<VMStateDescription<T>> and introduce the Box::leak(Box::new(...)) trick.
Quoted 4 lines
Quoted 1 line
+ vmstate_struct!(HPETState, timers[0 ..
num_timers],
&VMSTATE_HPET_TIMER, BqlRefCell<HPETTimer>, HPETState::validate_num_timers).with_version_id(0),And it seems like you don't oppose the hack in patch 1? ;-)
It's not bad, but I haven't looked at why it's needed yet (i.e. why a constant function would be evaluating a destructor).
Paolo
Re: [PATCH 8/9] rust/hpet: Support migration
In reply to Paolo BonziniQuoted 9 lines
Quoted 4 lines
Although it can handle callbacks well, I found that the difficulty still lies in the fact that the
vmstate_fieldsandvmstate_subsectionsmacros cannot be eliminated, because any dynamic creation of arrays is not allowed in a static context!Yes, this makes sense. Array size must be known inside a const function and the extra terminator at the end of fields and subsections cannot be added by the builder itself.
c_str! has the same issue for the name, if I understand correctly.
Yes, I have to use c_str! in name().
Quoted 17 lines
Quoted 2 lines
In any case, it's definitely still rough, but hope it helps and takes a small step forward.
Yes, of course---this:
rust/hw/timer/hpet/src/hpet.rs +11
-0+static VMSTATE_HPET_RTC_IRQ_LEVEL :VMStateDescription <HPETState > = +VMStateDescriptionBuilder ::<HPETState >::new () + .name (c_str! ("hpet/rtc_irq_level" )) + .version_id (1 ) + .minimum_version_id (1 ) + .needed (&HPETState ::is_rtc_irq_level_needed) + .fields (vmstate_fields! { +vmstate_of! (HPETState , rtc_irq_level), + }) + .build (); +
Quoted 7 lines
is readable, not foreign (it's similar to the MemoryRegionOps) and provides an easy way to insert FFI wrappers.
Right now it's now fully typesafe, because the VMStateField returned by
vmstate_of! (as well as the arrays returned byvmstate_fields! andvmstate_subsections!) does not track that it's for an HPETState; but that's a small thing overall and getting the basic builder right is more important.
I agree, additional consideration is needed here. Currently it is vmstate_fields! that limits changes to vmstate_of!.
Quoted 10 lines
I also made a note to check which callbacks could have a Result<> as the return type, possibly reusing the Errno module (Result<(), ()> looks a bit silly); but that is also not needed for this early stage.
Just a couple notes:
Quoted 1 line
+ bindings::{VMStateDescription as RawVMStateDescription, VMStateFlags},
I would use
bindings::VMStateDescriptionthroughout, similar to how it's done inmemory.rs.
Sure, will fix.
Quoted 6 lines
rust/qemu-api/src/vmstate.rs macro_rules! vmstate_subsections { · line 663
Quoted 2 lines
rust/qemu-api/src/vmstate.rs +2
-0+pub const fn name (mut self, name_str: &CStr ) ->Self { + self.0 .name = ::std::ffi::CStr ::as_ptr (name_str);This can use "
name_str.as_ptr()" because the type ofname_stris known (unlike in macros, such asdefine_property! orvmstate_validate!).
I see and will fix.
Quoted 4 lines
(By the way, talking about macros, I have just stumbled on the attrs crate,
which is something to keep an eye on for when QOM/qdev bindings are extended
along the lines of https://lore.kernel.org/qemu-devel/[email protected]/T/.
But I don't think procedural macros are a good match for VMState).
I didn't have a deep understanding of this previously :-(. I'll take a closer look at this.
Thanks,
Zhao
PATCH 9/9 rust/hpet: Fix a clippy error
In reply to Zhao LiuCarge clippy complained about:
error: casts from u8 to u32 can be expressed infallibly using From
So use From to convert u8 to u32.
--- rust/hw/timer/hpet/src/hpet.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
rust/hw/timer/hpet/src/hpet.rs +1 -1
@@ -357,7 +357,7 @@ fn update_irq(&mut self, set: bool) {// still operate and generate appropriate status bits, but // will not cause an interrupt" self.get_state () - .update_int_status (self.indexas u32 , set && self.is_int_level_triggered ()); + .update_int_status (u32::from (self.index), set && self.is_int_level_triggered ()); self.set_irq (set); }
Signature · 1 line
2.34.1
Quoted 16 lines · Zhao Liu
Hi all,
This series add the *initial* support for HPET migration.
This is *initial* because the current migration implementation introduces multiple *unsafe* callbacks (please refer Patch 8).
Before the vmstate builder, one possible cleanup approach is to wrap callbacks in the vmstate binding using a method similar to the
vmstate_exist_fnmacro.However, this approach would also create a lot of repetitive code (since vmstate has so many callbacks:
pre_load,post_load,pre_save,post_save, needed anddev_unplug_pending). Although it would be cleaner, it would somewhat deviate from the path of the vmstate builder.
Quoted 4 lines
Therefore, firstly focus on completing the functionality of HPET, and those current unsafe callbacks can at least clearly indicate the needed functionality of vmstate. The next step is to consider refactoring vmstate to move towards the vmstate builder direction.
Merged 4/6/7/9 for now, thanks! I'll reply to patch 2 with a review.
Paolo
Quoted 29 lines
Test this series with 3 migration cases:
* q35 (Rust HPET) -> q35 (Rust HPET)
* q35 (Rust HPET) -> q35 (C HPET)
* q35 (C HPET) -> q35 (Rust HPET)Thanks and Best Regards,
Zhao
---
Zhao Liu (9):
rust/vmstate: Supportfield_existscheck invmstate_structmacrorust/vmstate: Support varray's num field wrapped in BqlCellrust/vmstate_test: Test varray with num field wrapped in BqlCellrust/vmstate_test: Fix typo in
test_vmstate_macro_array_of_pointer_wrapped()
rust/timer: DefineNANOSECONDS_PER_SECONDbinding as u64rust/hpet: convertnum_timersto u8 type
rust/hpet: convert HPETTimer index to u8 typerust/hpet: Support migration
rust/hpet: Fix a clippy errordocs/devel/rust.rst | 3 +- rust/hw/timer/hpet/src/hpet.rs | 189 ++++++++++++++++++++++++--- rust/qemu-api/src/assertions.rs | 30 ++++- rust/qemu-api/src/cell.rs | 23 ++++ rust/qemu-api/src/timer.rs | 2 + rust/qemu-api/src/vmstate.rs | 67 +++++----- rust/qemu-api/tests/vmstate_tests.rs | 45 +++++-- 7 files changed, 294 insertions(+), 65 deletions(-)