rust: migration: add high-level migration wrappers
Subsystems (2)
cover rust: migration: add high-level migration wrappers
This series adds high-level wrappers to handle migration state; they consist of a Migratable<> type that implements the snapshotting technique mentioned at KVM Forum. The concepts are also discussed at
https://lore.kernel.org/qemu-devel/[email protected]/T/
The wrappers (should) make it possible to easily implement migration of thread-safe devices. I say "should" because, even though there are tests included in the series, they are anything but "battle tested". The first device to use this will be HPET.
This is an interesting step in enabling usage of Rust in QEMU; instead of just wrapping existing C APIs, it provides a new interface that deals better with unique features of the Rust language. In other words, something like Migratable<> and ToMigrationState might hypothetically exist even if QEMU was written in Rust from scratch.
Paolo
Paolo Bonzini (7):
rust: bql: add BqlRefCell::get_mut()
rust: move VMState from bql to migration
rust: migration: extract vmstate_fields_ref
rust: migration: add high-level migration wrappers
rust: qemu-macros: add ToMigrationState derive macro
rust: migration: implement ToMigrationState for Timer
rust: migration: implement ToMigrationState as part of
impl_vmstate_bitsized
rust/Cargo.lock | 5 +- rust/bql/Cargo.toml | 3 - rust/bql/meson.build | 1 - rust/bql/src/cell.rs | 25 +- rust/meson.build | 2 +- rust/migration/Cargo.toml | 2 + rust/migration/meson.build | 7 +- rust/migration/src/lib.rs | 5 + rust/migration/src/migratable.rs | 469 ++++++++++++++++++++++++ rust/migration/src/vmstate.rs | 44 ++- rust/qemu-macros/src/lib.rs | 88 +++++ rust/qemu-macros/src/migration_state.rs | 296 +++++++++++++++ rust/qemu-macros/src/tests.rs | 112 +++++- 13 files changed, 1034 insertions(+), 25 deletions(-) create mode 100644 rust/migration/src/migratable.rs create mode 100644 rust/qemu-macros/src/migration_state.rs
Signature · 1 line
2.51.0
PATCH 1/7 rust: bql: add BqlRefCell::get_mut()
This method is rarely useful in QEMU due to the pervasiveness of shared references, but add it for when a &mut BqlRefCell<> is used.
--- rust/bql/src/cell.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+)
rust/bql/src/cell.rs +19 -0
@@ -580,6 +580,25 @@ pub fn borrow_mut(&self) -> BqlRefMut<'_, T> { } } +/// Returns a mutable reference to the underlying data in this cell, +/// while the owner already has a mutable reference to the cell. +/// +/// # Examples +/// +/// ``` +/// use bql::BqlRefCell; +/// +/// let mut c = BqlRefCell::new(5); +/// +/// *c.get_mut() = 10; +/// ``` +#[inline] +pub const fn get_mut (&mut self) -> &mut T { +// SAFETY: there cannot be any outstanding borrow, +// since `self` is mutably owned. +unsafe { &mut *self.as_ptr () } + } +/// Returns a raw pointer to the underlying data in this cell. /// /// # Examples
Signature · 1 line
2.51.0
Re: [PATCH 1/7] rust: bql: add BqlRefCell::get_mut()
Quoted 28 lines · Paolo Bonzini
Date: Sat, 20 Sep 2025 16:29:52 +0200
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 1/7] rust: bql: addBqlRefCell::get_mut()
X-Mailer: git-send-email 2.51.0This method is rarely useful in QEMU due to the pervasiveness of shared references, but add it for when a &mut BqlRefCell<> is used.
Signed-off-by Paolo Bonzini <[email protected]>--- rust/bql/src/cell.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+)rust/bql/src/cell.rs +7
-0@@ -580,6 +580,25 @@ pub fn borrow_mut(&self) -> BqlRefMut<'_, T> { } } +/// Returns a mutable reference to the underlying data in this cell, +/// while the owner already has a mutable reference to the cell. +/// +/// # Examples +/// +/// ``` +/// use bql::BqlRefCell;
rust/bql/src/cell.rs pub fn borrow_mut(&self) -> BqlRefMut<'_, T> { · line 599
Quoted 10 lines
rust/bql/src/cell.rs +10
-0+/// +/// let mut c = BqlRefCell::new(5); +/// +/// *c.get_mut() = 10; +/// ``` +#[inline] +pub const fn get_mut (&mut self) -> &mut T { +// SAFETY: there cannot be any outstanding borrow, +// since `self` is mutably owned. +unsafe { &mut *self.as_ptr () }
Why not use UnsafeCell::get_mut?
self.value.get_mut()
Regards,
Zhao
Re: [PATCH 1/7] rust: bql: add BqlRefCell::get_mut()
Quoted 9 lines · On Tue, Sep 23, 2025, 16:50 Zhao Liu <[email protected]> wrote:
rust/bql/src/cell.rs pub fn borrow_mut(&self) -> BqlRefMut<'_, T> { · line 599
Quoted 4 lines
rust/bql/src/cell.rs +4
-0+pub const fn get_mut (&mut self) -> &mut T { +// SAFETY: there cannot be any outstanding borrow, +// since `self` is mutably owned. +unsafe { &mut *self.as_ptr () }Why not use
UnsafeCell::get_mut?
self.value.get_mut()
Uh, of course. I thought it was too new, but it's even available as const in 1.83.
Paolo
Regards,
Quoted 3 lines
Zhao
PATCH 2/7 rust: move VMState from bql to migration
In reply to Paolo BonziniThe high-level wrapper Migratable<T> will contain a BqlCell, which would introduce a circular dependency betwen the bql and migration crates. Move the implementation of VMState for cells to "migration", together with the implementation for std types.
--- rust/Cargo.lock | 4 +--- rust/bql/Cargo.toml | 3 --- rust/bql/meson.build | 1 - rust/bql/src/cell.rs | 6 ------ rust/meson.build | 2 +- rust/migration/Cargo.toml | 1 + rust/migration/meson.build | 4 ++-- rust/migration/src/vmstate.rs | 2 ++ 8 files changed, 7 insertions(+), 16 deletions(-)
rust/Cargo.lock +1 -3
@@ -57,9 +57,6 @@ dependencies = [ [[package]] name = "bql" version = "0.1.0" -dependencies = [ - "migration", -] [[package]] name = "chardev"
@@ -141,6 +138,7 @@ checksum = "18d287de67fe55fd7e1581fe933d965a5a9477b38e949cfa9f8574ef01506398" name = "migration" version = "0.1.0" dependencies = [ + "bql", "common", "util", ]
rust/bql/Cargo.toml +0 -3
@@ -12,9 +12,6 @@ license.workspace = true repository.workspace = true rust-version.workspace = true -[dependencies] -migration = { path = "../migration" } - [features] default = ["debug_cell"] debug_cell = []
rust/bql/meson.build +0 -1
@@ -36,7 +36,6 @@ _bql_rs = static_library( override_options: ['rust_std=2021', 'build.rust_std=2021'], rust_abi: 'rust', rust_args: _bql_cfg, - link_with: [_migration_rs], ) bql_rs = declare_dependency(link_with: [_bql_rs],
rust/bql/src/cell.rs +0 -6
@@ -151,8 +151,6 @@ ptr::NonNull, }; -use migration::impl_vmstate_transparent; -/// A mutable memory location that is protected by the Big QEMU Lock. /// /// # Memory layout
@@ -364,8 +362,6 @@ pub fn take(&self) -> T { } } -impl_vmstate_transparent! (crate ::cell::BqlCell <T >where T :VMState ); -/// A mutable memory location with dynamically checked borrow rules, /// protected by the Big QEMU Lock. ///
@@ -693,8 +689,6 @@ fn from(t: T) -> BqlRefCell<T> { } } -impl_vmstate_transparent! (crate ::cell::BqlRefCell <T >where T :VMState ); -struct BorrowRef <'b> { borrow: &'bCell <BorrowFlag >, }
rust/meson.build +1 -1
@@ -29,8 +29,8 @@ subdir('qemu-macros') subdir('common') subdir('bits') subdir('util') -subdir('migration') subdir('bql') +subdir('migration') subdir('qom') subdir('system') subdir('chardev')
rust/migration/Cargo.toml +1 -0
@@ -13,6 +13,7 @@ repository.workspace = true rust-version.workspace = true [dependencies] +bql = { path = "../bql" } common = { path = "../common" } util = { path = "../util" }
rust/migration/meson.build +2 -2
@@ -36,12 +36,12 @@ _migration_rs = static_library( ), override_options: ['rust_std=2021', 'build.rust_std=2021'], rust_abi: 'rust', - link_with: [_util_rs], + link_with: [_util_rs, _bql_rs], dependencies: [common_rs], ) migration_rs = declare_dependency(link_with: [_migration_rs], - dependencies: [migration, qemuutil]) + dependencies: [bql_rs, migration, qemuutil]) # Doctests are essentially integration tests, so they need the same dependencies. # Note that running them requires the object files for C code, so place them
rust/migration/src/vmstate.rs +2 -0
@@ -275,6 +275,8 @@ unsafe impl<$base> $crate::vmstate::VMState for $type where $base: $crate::vmsta }; } +impl_vmstate_transparent! (bql::BqlCell <T >where T :VMState ); +impl_vmstate_transparent! (bql::BqlRefCell <T >where T :VMState );impl_vmstate_transparent! (std::cell::Cell <T >where T :VMState );impl_vmstate_transparent! (std::cell::UnsafeCell <T >where T :VMState );impl_vmstate_transparent! (std::pin::Pin <T >where T :VMState );
Signature · 1 line
2.51.0
Re: [PATCH 2/7] rust: move VMState from bql to migration
Quoted 11 lines · Paolo Bonzini
Date: Sat, 20 Sep 2025 16:29:53 +0200
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 2/7] rust: move VMState from bql to migration
X-Mailer: git-send-email 2.51.0The high-level wrapper Migratable<T> will contain a BqlCell, which would introduce a circular dependency betwen the bql and migration crates. Move the implementation of VMState for cells to "migration", together with the implementation for std types.
Signed-off-by Paolo Bonzini <[email protected]>
Quoted 10 lines
--- rust/Cargo.lock | 4 +--- rust/bql/Cargo.toml | 3 --- rust/bql/meson.build | 1 - rust/bql/src/cell.rs | 6 ------ rust/meson.build | 2 +- rust/migration/Cargo.toml | 1 + rust/migration/meson.build | 4 ++-- rust/migration/src/vmstate.rs | 2 ++ 8 files changed, 7 insertions(+), 16 deletions(-)
PATCH 3/7 rust: migration: extract vmstate_fields_ref
In reply to Paolo BonziniThis is useful when building a VMState for generic structs, because you have to avoid nested statics. Using vmstate_fields! will fail in the likely case where the _FIELDS static uses Self from an outer item, because that is forbidden.
I also looked into returning a &'static [VMStateField] from vmstate_fields!, but that also fails; the fields are not promoted to static, which is unfortunate but intentional (https://github.com/rust-lang/rust/issues/60502):
error[E0716]: temporary value dropped while borrowed
--> rust/hw/char/pl011/libpl011.rlib.p/structured/device.rs:743:17
|
738 | / VMStateDescriptionBuilder::<PL011State>::new()
739 | | .name(c"pl011/clock")
740 | | .version_id(1)
741 | | .minimum_version_id(1)
742 | | .needed(&PL011State::clock_needed)
743 | | .fields(vmstate_fields! {
| | _________________^
744 | || vmstate_of!(PL011State, clock),
745 | || })
| ||_________^- argument requires that borrow lasts for `'static`
| |_________|
| creates a temporary value which is freed while still in use
746 | .build();
| - temporary value is freed at the end of this statement--- rust/migration/src/vmstate.rs | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-)
rust/migration/src/vmstate.rs +17 -6
@@ -413,19 +413,30 @@ const fn phantom__<T>(_: &T) -> ::core::marker::PhantomData<T> { }}; } +/// Add a terminator to the fields in the arguments, and return +/// a reference to the resulting array of values. +#[macro_export] +macro_rules! vmstate_fields_ref { + ($($field:expr),*$(,)*) => { + &[ + $($field),*, + $crate::bindings::VMStateField { + flags: $crate::bindings::VMStateFlags ::VMS_END , + ..::common::zeroable::Zeroable ::ZERO + } + ] + } +} +/// Helper macro to declare a list of /// ([`VMStateField`](`crate::bindings::VMStateField`)) into a static and return /// a pointer to the array of values it created. #[macro_export] macro_rules! vmstate_fields { ($($field:expr),*$(,)*) => {{ -static _FIELDS: &[$crate::bindings::VMStateField ] = &[ +static _FIELDS: &[$crate::bindings::VMStateField ] = $crate::vmstate_fields_ref!( $($field),*, - $crate::bindings::VMStateField { - flags: $crate::bindings::VMStateFlags ::VMS_END , - ..::common::zeroable::Zeroable ::ZERO - } - ]; + ); _FIELDS.as_ptr () }} }
Signature · 1 line
2.51.0
Re: [PATCH 3/7] rust: migration: extract vmstate_fields_ref
Hi Paolo,
Quoted 9 lines · Paolo Bonzini
Date: Sat, 20 Sep 2025 16:29:54 +0200
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 3/7] rust: migration: extractvmstate_fields_ref
X-Mailer: git-send-email 2.51.0This is useful when building a VMState for generic structs, because you have to avoid nested statics. Using
vmstate_fields! will fail in the likely case where the_FIELDSstatic uses Self from an outer item, because that is forbidden.
vmstate_fields_ref is good for me.
Quoted 6 lines
I also looked into returning a &'static [VMStateField] from
vmstate_fields!, but that also fails; the fields are not promoted to static, which is unfortunate but intentional (https://github.com/rust-lang/rust/issues/60502):error[E0716]: temporary value dropped while borrowed
-->rust/hw/char/pl011/libpl011.rlib.p/structured/device.rs:743:17
Quoted 15 lines
|
738 | / VMStateDescriptionBuilder::<PL011State>::new()
739 | | .name(c"pl011/clock")
740 | | .version_id(1)
741 | | .minimum_version_id(1)
742 | | .needed(&PL011State::clock_needed)
743 | | .fields(vmstate_fields! {
| | _________________^
744 | || vmstate_of!(PL011State, clock),
745 | || })
| ||_________^- argument requires that borrow lasts for `'static`
| |_________|
| creates a temporary value which is freed while still in use
746 | .build();
| - temporary value is freed at the end of this statementAnd I'm curious what change caused this error... I guess you're indicating the following case?
rust/migration/src/vmstate.rs +2 -3
@@ -417,14 +417,13 @@ const fn phantom__<T>(_: &T) -> ::core::marker::PhantomData<T> {#[macro_export] macro_rules! vmstate_fields { ($($field:expr),*$(,)*) => {{ -static _FIELDS: &[$crate::bindings::VMStateField ] = &[ + &[ $($field),*, $crate::bindings::VMStateField { flags: $crate::bindings::VMStateFlags ::VMS_END , ..::common::zeroable::Zeroable ::ZERO } - ]; - _FIELDS.as_ptr () + ] }} }
Quoted 34 lines
Signed-off-by Paolo Bonzini <[email protected]>--- rust/migration/src/vmstate.rs | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-)rust/migration/src/vmstate.rs +15
-0@@ -413,19 +413,30 @@ const fn phantom__<T>(_: &T) -> ::core::marker::PhantomData<T> { }}; } +/// Add a terminator to the fields in the arguments, and return +/// a reference to the resulting array of values. +#[macro_export] +macro_rules! vmstate_fields_ref { + ($($field:expr),*$(,)*) => { + &[ + $($field),*, + $crate::bindings::VMStateField { + flags: $crate::bindings::VMStateFlags ::VMS_END , + ..::common::zeroable::Zeroable ::ZERO + } + ] + } +} +/// Helper macro to declare a list of /// ([`VMStateField`](`crate::bindings::VMStateField`)) into a static and return /// a pointer to the array of values it created. #[macro_export] macro_rules! vmstate_fields { ($($field:expr),*$(,)*) => {{
rust/migration/src/vmstate.rs const fn phantom__<T>(_: &T) -> ::core::marker::PhantomData<T> { · line 440
Quoted 10 lines
rust/migration/src/vmstate.rs +2
-6-static _FIELDS: &[$crate::bindings::VMStateField ] = &[ +static _FIELDS: &[$crate::bindings::VMStateField ] = $crate::vmstate_fields_ref!( $($field),*, - $crate::bindings::VMStateField { - flags: $crate::bindings::VMStateFlags ::VMS_END , - ..::common::zeroable::Zeroable ::ZERO - } - ]; + ); _FIELDS.as_ptr ()
Considerring the idea about returing &'static [VMStateField], I think at least we could return _FIELDS.as_ptr() directly from vmstate_fields!, and convert &'static [VMStateField] to *const [VMStateField] in fields(), just like subsections() did.
Thanks,
Zhao
Quoted 5 lines
rust/migration/src/vmstate.rs +0
-0}} }Signature · 1 line
2.51.0
Re: [PATCH 3/7] rust: migration: extract vmstate_fields_ref
Quoted 2 lines
Considerring the idea about returing &'static [VMStateField], I think at least we could return
_FIELDS.as_ptr()directly fromvmstate_fields!,
^^^^^^^^^^^^^^^^
Sorry for copy error :(, s/_FIELDS.as_ptr()/_FIELDS/
Quoted 2 lines
and convert &'static [VMStateField] to *const [VMStateField] in
fields(), just likesubsections()did.
Re: [PATCH 3/7] rust: migration: extract vmstate_fields_ref
Quoted 8 lines · On Wed, Sep 24, 2025, 17:06 Zhao Liu <[email protected]> wrote:
Quoted 2 lines
Considerring the idea about returing &'static [VMStateField], I think at least we could return
_FIELDS.as_ptr()directly fromvmstate_fields!,^^^^^^^^^^^^^^^^Sorry for copy error :(, s/_FIELDS.as_ptr()/_FIELDS/
Quoted 2 lines
and convert &'static [VMStateField] to *const [VMStateField] in
fields(), just likesubsections()did.
Yes, that's a good idea. Though subsections() can also be cleaned up a lot to avoid the wrapper. I will include everything in the next version.
Paolo
Quoted 1 line
PATCH 4/7 rust: migration: add high-level migration wrappers
In reply to Paolo BonziniInstead of dealing with pre/post callbacks, allow devices to implement a snapshot/restore mechanism; this has two main advantages:
- it can be easily implemented via procedural macros
- there can be generic implementations to deal with various kinds of interior-mutable containers, from BqlRefCell to Mutex, so that C code does not see Rust concepts such as Mutex<>.
Using it is easy; you can implement the snapshot/restore trait ToMigrationState and declare your state like:
regs: Migratable<Mutex<MyDeviceRegisters>>
Migratable<> allows dereferencing to the underlying object with no run-time cost.
Note that Migratable<> actually does not accept ToMigrationState, only the similar ToMigrationStateShared trait that the user will mostly not care about. This is required by the fact that pre/post callbacks take a &self, and ensures that the argument is a Mutex or BqlRefCell (including an array or Arc<> thereof).
--- rust/Cargo.lock | 1 + rust/migration/Cargo.toml | 1 + rust/migration/meson.build | 1 + rust/migration/src/lib.rs | 3 + rust/migration/src/migratable.rs | 430 +++++++++++++++++++++++++++++++ 5 files changed, 436 insertions(+) create mode 100644 rust/migration/src/migratable.rs
rust/Cargo.lock +1 -0
@@ -140,6 +140,7 @@ version = "0.1.0" dependencies = [ "bql", "common", + "qemu_macros", "util", ]
rust/migration/Cargo.toml +1 -0
@@ -15,6 +15,7 @@ rust-version.workspace = true [dependencies] bql = { path = "../bql" } common = { path = "../common" } +qemu_macros = { path = "../qemu-macros" } util = { path = "../util" } [lints]
rust/migration/meson.build +1 -0
@@ -30,6 +30,7 @@ _migration_rs = static_library( [ 'src/lib.rs', 'src/bindings.rs', + 'src/migratable.rs', 'src/vmstate.rs', ], {'.' : _migration_bindings_inc_rs},
rust/migration/src/lib.rs +3 -0
@@ -2,5 +2,8 @@pub mod bindings; +pub mod migratable; +pub use migratable::*; +pub mod vmstate;pub use vmstate::*;
rust/migration/src/migratable.rs new file +430 -0
430 lines not on this page · raw message
Signature · 1 line
2.51.0
Quoted 30 lines · Paolo Bonzini
Date: Sat, 20 Sep 2025 16:29:55 +0200
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 4/7] rust: migration: add high-level migration wrappers
X-Mailer: git-send-email 2.51.0Instead of dealing with pre/post callbacks, allow devices to implement a snapshot/restore mechanism; this has two main advantages:
- it can be easily implemented via procedural macros
- there can be generic implementations to deal with various kinds of interior-mutable containers, from BqlRefCell to Mutex, so that C code does not see Rust concepts such as Mutex<>.
Using it is easy; you can implement the snapshot/restore trait ToMigrationState and declare your state like:
regs: Migratable<Mutex<MyDeviceRegisters>>
Migratable<> allows dereferencing to the underlying object with no run-time cost.
Note that Migratable<> actually does not accept ToMigrationState, only the similar ToMigrationStateShared trait that the user will mostly not care about. This is required by the fact that pre/post callbacks take a &self, and ensures that the argument is a Mutex or BqlRefCell (including an array or Arc<> thereof).
Signed-off-by Paolo Bonzini <[email protected]>
Quoted 8 lines
--- rust/Cargo.lock | 1 + rust/migration/Cargo.toml | 1 + rust/migration/meson.build | 1 + rust/migration/src/lib.rs | 3 + rust/migration/src/migratable.rs | 430 +++++++++++++++++++++++++++++++ 5 files changed, 436 insertions(+) create mode 100644 rust/migration/src/migratable.rs
The entire wrapper is quite nice. So,
Only a few comments for comments inline:
Review
Quoted 2 lines
(quoted diff) +2
-0+// Interior-mutable types only require ToMigrationState for the inner type! +
extra blank line.
rust/migration/src/migratable.rs line 250
Quoted 6 lines
rust/migration/src/migratable.rs new file +6
-0+impl <T :ToMigrationState >ToMigrationState for Mutex <T > { +type Migrated =T ::Migrated ; + +fn snapshot_migration_state (&self, target: &mut Self ::Migrated ) ->Result <(),InvalidError > { + self.lock ().unwrap ().snapshot_migration_state (target) + }
Or maybe your previous sentence is worth commenting on here:
// For non-BQL-protected device we cannot know that another // thread isn't taking the lock. So, always acquire the lock.
Quoted 21 lines
rust/migration/src/migratable.rs new file +21
-0+fn restore_migrated_state_mut ( + &mut self, + source:Self ::Migrated , + version_id:u8 , + ) ->Result <(),InvalidError > { + self.restore_migrated_state (source, version_id) + } +} + +impl <T :ToMigrationState >ToMigrationStateShared for Mutex <T > { +fn restore_migrated_state ( + &self, + source:Self ::Migrated , + version_id:u8 , + ) ->Result <(),InvalidError > { + self.lock () + .unwrap () + .restore_migrated_state_mut (source, version_id) + } +} +
Quoted 10 lines · On Thu, Sep 25, 2025, 10:43 Zhao Liu <[email protected]> wrote:
Quoted 1 line
+ fn
snapshot_migration_state(&self, target: &mut Self::Migrated)->Result<(), InvalidError> {
Review
Quoted 2 lines
(quoted diff) +2
-0+ self.lock().unwrap().snapshot_migration_state(target) + }Or maybe your previous sentence is worth commenting on here:
// For non-BQL-protected device we cannot know that another // thread isn't taking the lock. So, always acquire the lock.
I don't think here there's any alternative, that is a way to write code without taking the lock. However...
Quoted 8 lines
rust/migration/src/migratable.rs line 257
Quoted 7 lines
rust/migration/src/migratable.rs new file +6
-0+fn restore_migrated_state_mut ( + &mut self, + source:Self ::Migrated , + version_id:u8 , + ) ->Result <(),InvalidError > { + self.restore_migrated_state (source, version_id)
... this could use get_mut().
Paolo
Quoted 17 lines
+ }
Quoted 14 lines
rust/migration/src/migratable.rs new file +14
-0+} + +impl <T :ToMigrationState >ToMigrationStateShared for Mutex <T > { +fn restore_migrated_state ( + &self, + source:Self ::Migrated , + version_id:u8 , + ) ->Result <(),InvalidError > { + self.lock () + .unwrap () + .restore_migrated_state_mut (source, version_id) + } +} +
PATCH 5/7 rust: qemu-macros: add ToMigrationState derive macro
In reply to Paolo BonziniAdd a macro that recursively builds the "migrated" version of a struct.
--- rust/migration/meson.build | 2 +- rust/migration/src/lib.rs | 2 + rust/migration/src/migratable.rs | 12 +- rust/qemu-macros/src/lib.rs | 88 +++++++ rust/qemu-macros/src/migration_state.rs | 296 ++++++++++++++++++++++++ rust/qemu-macros/src/tests.rs | 112 ++++++++- 6 files changed, 507 insertions(+), 5 deletions(-) create mode 100644 rust/qemu-macros/src/migration_state.rs
rust/migration/meson.build +1 -1
@@ -38,7 +38,7 @@ _migration_rs = static_library( override_options: ['rust_std=2021', 'build.rust_std=2021'], rust_abi: 'rust', link_with: [_util_rs, _bql_rs], - dependencies: [common_rs], + dependencies: [common_rs, qemu_macros], ) migration_rs = declare_dependency(link_with: [_migration_rs],
rust/migration/src/lib.rs +2 -0
@@ -2,6 +2,8 @@pub mod bindings; +pub use qemu_macros::ToMigrationState ; +pub mod migratable;pub use migratable::*;
rust/migration/src/migratable.rs +10 -2
@@ -79,6 +79,10 @@/// # dev2.restore_migrated_state_mut(*mig, 1).unwrap(); /// # assert_eq!(dev2, dev); /// ``` +/// +/// More commonly, the trait is derived through the +/// [`derive(ToMigrationState)`](qemu_macros::ToMigrationState) procedural +/// macro. pub trait ToMigrationState {/// The type used to represent the migrated state. type Migrated :Default +VMState ;
@@ -305,13 +309,17 @@ fn restore_migrated_state(/// It manages the lifecycle of migration state and provides automatic /// conversion between runtime and migration representations. /// -/// ```ignore +/// ``` /// # use std::sync::Mutex; -/// # use migration::Migratable; +/// # use migration::{Migratable, ToMigrationState, VMState, VMStateField}; /// +/// #[derive(ToMigrationState)] /// pub struct DeviceRegs { /// status: u32, /// } +/// # unsafe impl VMState for DeviceRegsMigration { +/// # const BASE: VMStateField = ::common::Zeroable::ZERO; +/// # } /// /// pub struct SomeDevice { /// // ...
rust/qemu-macros/src/lib.rs +88 -0
100 lines not on this page · raw message
rust/qemu-macros/src/migration_state.rs new file +296 -0
296 lines not on this page · raw message
rust/qemu-macros/src/tests.rs +110 -2
127 lines not on this page · raw message
Signature · 1 line
2.51.0
Re: [PATCH 5/7] rust: qemu-macros: add ToMigrationState derive macro
Quoted 18 lines · Paolo Bonzini
Date: Sat, 20 Sep 2025 16:29:56 +0200
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 5/7] rust: qemu-macros: add ToMigrationState derive macro
X-Mailer: git-send-email 2.51.0Add a macro that recursively builds the "migrated" version of a struct.
Signed-off-by Paolo Bonzini <[email protected]>--- rust/migration/meson.build | 2 +- rust/migration/src/lib.rs | 2 + rust/migration/src/migratable.rs | 12 +- rust/qemu-macros/src/lib.rs | 88 +++++++ rust/qemu-macros/src/migration_state.rs | 296 ++++++++++++++++++++++++ rust/qemu-macros/src/tests.rs | 112 ++++++++- 6 files changed, 507 insertions(+), 5 deletions(-) create mode 100644 rust/qemu-macros/src/migration_state.rs
...
Quoted 22 lines
rust/migration/src/migratable.rs +5
-1@@ -79,6 +79,10 @@/// # dev2.restore_migrated_state_mut(*mig, 1).unwrap(); /// # assert_eq!(dev2, dev); /// ``` +/// +/// More commonly, the trait is derived through the +/// [`derive(ToMigrationState)`](qemu_macros::ToMigrationState) procedural +/// macro. pub trait ToMigrationState {/// The type used to represent the migrated state. type Migrated :Default +VMState ;@@ -305,13 +309,17 @@ fn restore_migrated_state(/// It manages the lifecycle of migration state and provides automatic /// conversion between runtime and migration representations. /// -/// ```ignore +/// ``` /// # use std::sync::Mutex;
rust/migration/src/migratable.rs fn restore_migrated_state( · line 322
Quoted 10 lines
rust/migration/src/migratable.rs +5
-1-/// # use migration::Migratable; +/// # use migration::{Migratable, ToMigrationState, VMState, VMStateField}; /// +/// #[derive(ToMigrationState)] /// pub struct DeviceRegs { /// status: u32, /// } +/// # unsafe impl VMState for DeviceRegsMigration { +/// # const BASE: VMStateField = ::common::Zeroable::ZERO; +/// # }
Outdated comment? Looks like the DeviceRegsMigration definition is missing.
Quoted 2 lines
rust/migration/src/migratable.rs +0
-0/// pub struct SomeDevice { /// // ...
...
Quoted 19 lines
rust/migration/src/migratable.rs +19
-0+/// Derive macro for generating migration state structures and trait +/// implementations. +/// +/// This macro generates a migration state struct and implements the +/// `ToMigrationState` trait for the annotated struct, enabling state +/// serialization and restoration. Note that defining a `VMStateDescription` +/// for the migration state struct is left to the user. +/// +/// # Container attributes +/// +/// The following attributes can be applied to the struct: +/// +/// - `#[migration_state(rename = CustomName)]` - Customizes the name of the +/// generated migration struct. By default, the generated struct is named +/// `{OriginalName}Migration`. +/// +/// # Field attributes +/// +/// The following attributes can be applied to individual fields:
rust/migration/src/migratable.rs
Quoted 10 lines
rust/migration/src/migratable.rs +10
-0+/// +/// - `#[migration_state(omit)]` - Excludes the field from the migration state +/// entirely. +/// +/// - `#[migration_state(into(Type))]` - Converts the field using `.into()` +/// during both serialization and restoration. +/// +/// - `#[migration_state(try_into(Type))]` - Converts the field using +/// `.try_into()` during both serialization and restoration. Returns +/// `InvalidError` on conversion failure.
Good idea. These conversion modes are very useful, and inspiring.
It may be not necessary for #[property] to integrate into()/try_into() mode, but the below conversion is ugly:
#[property(rename = "msi", bit = HPET_FLAG_MSI_SUPPORT_SHIFT as u8, default = false)]
conversion should happen within the macro parsing process. But unfortunately, try_into() is not const, maybe I could do this for bit property:
rust/qemu-macros/src/lib.rs +4 -1
@@ -275,7 +275,10 @@ macro_rules! str_to_c_str { name: ::std::ffi::CStr::as_ptr(#prop_name), info: #qdev_prop, offset: ::core::mem::offset_of!(#name, #field_name) as isize, - bitnr: #bitnr, + bitnr: { + const _: () = assert!(#bitnr <= u8::MAX as _, "bit exceeds u8 range"); + #bitnr as u8 + }, set_default: #set_default, defval: ::hwcore::bindings::Property__bindgen_ty_1 { u: #defval as u64 }, ..::common::Zeroable ::ZERO
Quoted 1 line
+/// -
#[migration_state(clone)]- Clones the field value.
How about emphasizing the use case?
"Clones the field value, especially for the types don't implement Copy."
rust/migration/src/migratable.rs
Quoted 9 lines
rust/migration/src/migratable.rs +9
-0+/// Fields without any attributes use `ToMigrationState` recursively; note that +/// this is a simple copy for types that implement `Copy`. +/// +/// # Attribute compatibility +/// +/// - `omit` cannot be used with any other attributes +/// - only one of `into(Type)`, `try_into(Type)` can be used, but they can be +/// coupled with `clone`. +///
...
The implementation of the entire macro is great.
Quoted 2 lines
rust/migration/src/migratable.rs +2
-0+#[test] +fn test_derive_to_migration_state () {
...
rust/migration/src/migratable.rs
Quoted 9 lines
rust/migration/src/migratable.rs +9
-0+quote! { +#[derive( Default )] +pub struct CustomMigration { +pub shared_data:String , +pub converted_field:Cow <'static ,str >, +pub fallible_field:i8 , +pub nested_field: <NestedStruct as ToMigrationState >::Migrated , +pub simple_field: <u32 as ToMigrationState >::Migrated , + }
In the production code, CustomMigration still needs to implement VMState trait, so that String & Cow<'static, str> also need to implement VMState trait. This seems like the thing that we are currently missing.
For test, it's enough to show how the macro works.
Re: [PATCH 5/7] rust: qemu-macros: add ToMigrationState derive macro
Quoted 10 lines · Zhao Liu
Review
Quoted 7 lines
(quoted diff) +4
-0+/// #[derive(ToMigrationState)] /// pub struct DeviceRegs { /// status: u32, /// } +/// # unsafe impl VMState for DeviceRegsMigration { +/// # const BASE: VMStateField = ::common::Zeroable::ZERO; +/// # }Outdated comment? Looks like the DeviceRegsMigration definition is missing.
It's defined by the #[derive(ToMigrationState)].
Quoted 12 lines
the below conversion is ugly:>
#[property(rename = "msi", bit =HPET_FLAG_MSI_SUPPORT_SHIFTas u8, default = false)]conversion should happen within the macro parsing process. But unfortunately,
try_into()is not const, maybe I could do this for bit property:rust/qemu-macros/src/lib.rs +0
-0@@ -275,7 +275,10 @@ macro_rules! str_to_c_str { name: ::std::ffi::CStr::as_ptr(#prop_name),
rust/qemu-macros/src/lib.rs macro_rules! str_to_c_str { · line 284
Quoted 10 lines
rust/qemu-macros/src/lib.rs +4
-1info: #qdev_prop, offset: ::core::mem::offset_of!(#name, #field_name) as isize, - bitnr: #bitnr, + bitnr: { + const _: () = assert!(#bitnr <= u8::MAX as _, "bit exceeds u8 range"); + #bitnr as u8 + }, set_default: #set_default, defval: ::hwcore::bindings::Property__bindgen_ty_1 { u: #defval as u64 }, ..::common::Zeroable ::ZERO
Good idea (also testing >= 0 is needed). "const { assert!(...); }" is even simpler.
Quoted 5 lines
Quoted 1 line
+/// -
#[migration_state(clone)]- Clones the field value.How about emphasizing the use case?
"Clones the field value, especially for the types don't implement
Copy."
I don't have a use case yet to be honest, but at the same time I want to help potential device authors and remove the need to muck with the macro.
Quoted 12 lines
Quoted 9 lines
(quoted diff) +9
-0+/// Fields without any attributes use `ToMigrationState` recursively; note that +/// this is a simple copy for types that implement `Copy`. +/// +/// # Attribute compatibility +/// +/// - `omit` cannot be used with any other attributes +/// - only one of `into(Type)`, `try_into(Type)` can be used, but they can be +/// coupled with `clone`. +///...
Quoted 1 line
The implementation of the entire macro is great.
Thanks. :) It's indeed pretty easy to follow, and I like procedural macro code that is simple but powerful.
The attrs crate also helps a lot!
Quoted 15 lines
Quoted 2 lines
(quoted diff) +2
-0+#[test] +fn test_derive_to_migration_state() {...
Review
Quoted 9 lines
(quoted diff) +9
-0+ quote! { + #[derive(Default)] + pub struct CustomMigration { + pub shared_data: String, + pub converted_field: Cow<'static, str>, + pub fallible_field: i8, + pub nested_field: <NestedStruct as ToMigrationState>::Migrated, + pub simple_field: <u32 as ToMigrationState>::Migrated, + }
Quoted 3 lines
In the production code, CustomMigration still needs to implement VMState trait, so that String & Cow<'static, str> also need to implement VMState trait. This seems like the thing that we are currently missing.
Or more simply they're not chosen well. :) For the documentation I will think of better types.
Quoted 1 line
For test, it's enough to show how the macro works.
Yes, for testing it's a lesser deal.
Paolo
PATCH 6/7 rust: migration: implement ToMigrationState for Timer
In reply to Paolo BonziniTimer is a complex struct, allow adding it to a struct that uses #[derive(ToMigrationState)]; similar to vmstate_timer, only the expiration time has to be preserved.
--- rust/migration/src/migratable.rs | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+)
rust/migration/src/migratable.rs +31 -0
@@ -202,6 +202,37 @@ fn restore_migrated_state( ) -> Result<(), InvalidError>; } +impl ToMigrationState for util::timer::Timer { +type Migrated =i64 ; + +fn snapshot_migration_state (&self, target: &mut i64 ) ->Result <(),InvalidError > { +// SAFETY: as_ptr() is unsafe to ensure that the caller reasons about +// the pinning of the data inside the Opaque<>. Here all we do is +// access a field. + *target =unsafe { &*self.as_ptr () }.expire_time; +Ok (()) + } + +fn restore_migrated_state_mut ( + &mut self, + source:Self ::Migrated , + version_id:u8 , + ) ->Result <(),InvalidError > { + self.restore_migrated_state (source, version_id) + } +} + +impl ToMigrationStateShared for util::timer::Timer { +fn restore_migrated_state (&self, source:i64 , _version_id:u8 ) ->Result <(),InvalidError > { +if source >=0 { + self.modify (sourceas u64 ); + }else { + self.delete (); + } +Ok (()) + } +} +impl <T :ToMigrationStateShared ,const N :usize >ToMigrationStateShared for [T ;N ]where [T ::Migrated ;N ]:Default ,
Signature · 1 line
2.51.0
Re: [PATCH 6/7] rust: migration: implement ToMigrationState for Timer
Quoted 19 lines · Paolo Bonzini
Date: Sat, 20 Sep 2025 16:29:57 +0200
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 6/7] rust: migration: implement ToMigrationState for Timer
X-Mailer: git-send-email 2.51.0Timer is a complex struct, allow adding it to a struct that uses #[derive(ToMigrationState)]; similar to
vmstate_timer, only the expiration time has to be preserved.Signed-off-by Paolo Bonzini <[email protected]>--- rust/migration/src/migratable.rs | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+)rust/migration/src/migratable.rs +0
-0
rust/migration/src/migratable.rs fn restore_migrated_state( · line 206
Quoted 5 lines
rust/migration/src/migratable.rs +2
-0@@ -202,6 +202,37 @@ fn restore_migrated_state( ) -> Result<(), InvalidError>; } +impl ToMigrationState for util::timer::Timer { +type Migrated =i64 ;
This converts a Timer to i64, then we don't need vmstate_info_timer anymore. Good idea.
rust/migration/src/migratable.rs fn restore_migrated_state( · line 212
Quoted 5 lines
rust/migration/src/migratable.rs +5
-0+fn snapshot_migration_state (&self, target: &mut i64 ) ->Result <(),InvalidError > { +// SAFETY: as_ptr() is unsafe to ensure that the caller reasons about +// the pinning of the data inside the Opaque<>. Here all we do is +// access a field. + *target =unsafe { &*self.as_ptr () }.expire_time;
C side checks timer_pending(), which ensures when the timer is inactive, it always saves u64::MAX.
But now we save the expire_time directly in Rust. I think this would be possible to break the migration from Rust timer to C timer, because at C side, timer_get() checks whether expire_time is -1 and we can't ensure expire_time won't store -2 (or other unusual negative values).
So maybe it's better to follow C side behavior to return u64::MAX for non-pending case?
Quoted 5 lines
rust/migration/src/migratable.rs +5
-0+Ok (()) + } + +fn restore_migrated_state_mut ( + &mut self,
rust/migration/src/migratable.rs fn restore_migrated_state( · line 227
Quoted 10 lines
rust/migration/src/migratable.rs +10
-0+ source: Self::Migrated, + version_id: u8, + ) -> Result<(), InvalidError> { + self.restore_migrated_state (source, version_id) + } +} + +impl ToMigrationStateShared for util::timer::Timer { +fn restore_migrated_state (&self, source:i64 , _version_id:u8 ) ->Result <(),InvalidError > { +if source >=0 {
This can work for the migration cases of C->Rust and Rust->Rust.
Thanks,
Zhao
Quoted 14 lines
rust/migration/src/migratable.rs +8
-0+ self.modify (sourceas u64 ); + }else { + self.delete (); + } +Ok (()) + } +} +impl <T :ToMigrationStateShared ,const N :usize >ToMigrationStateShared for [T ;N ]where [T ::Migrated ;N ]:Default ,Signature · 1 line
2.51.0
Re: [PATCH 6/7] rust: migration: implement ToMigrationState for Timer
Quoted 6 lines · Zhao Liu
rust/migration/src/migratable.rs fn restore_migrated_state( · line 212
Quoted 5 lines
rust/migration/src/migratable.rs +5
-0+fn snapshot_migration_state (&self, target: &mut i64 ) ->Result <(),InvalidError > { +// SAFETY: as_ptr() is unsafe to ensure that the caller reasons about +// the pinning of the data inside the Opaque<>. Here all we do is +// access a field. + *target =unsafe { &*self.as_ptr () }.expire_time;
Quoted 7 lines
C side checks
timer_pending(), which ensures when the timer is inactive, it always savesu64::MAX.But now we save the
expire_timedirectly in Rust. I think this would be possible to break the migration from Rust timer to C timer, because at C side,timer_get()checks whetherexpire_timeis -1 and we can't ensureexpire_timewon't store -2 (or other unusual negative values).
I think this should work in both cases because timer_pending() checks >= 0 and negative values are extremely far in the future. But I'll change it to timer_expire_time_ns() for safety and clarity.
Paolo
PATCH 7/7 rust: migration: implement ToMigrationState as part of impl_vmstate_bitsized
In reply to Paolo BonziniThis is most likely desirable, and is the easiest way to migrate a bit-sized value without peeking at the innards of the bilge crate.
--- rust/migration/src/vmstate.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+)
rust/migration/src/vmstate.rs +19 -0
@@ -295,6 +295,25 @@ unsafe impl $crate::vmstate::VMState for $type { as ::bilge::prelude::Number >::UnderlyingType as $crate::vmstate::VMState >::VARRAY_FLAG ; } + +impl $crate::migratable::ToMigrationState for $type { +type Migrated = <<$typeas ::bilge::prelude::Bitsized >::ArbitraryInt +as ::bilge::prelude::Number >::UnderlyingType ; + +fn snapshot_migration_state (&self, target: &mut Self ::Migrated ) ->Result <(), $crate::InvalidError > { + *target =Self ::Migrated ::from (*self); +Ok (()) + } + +fn restore_migrated_state_mut ( + &mut self, + source:Self ::Migrated , + version_id:u8 , + ) ->Result <(), $crate::InvalidError > { + *self =Self ::from (source); +Ok (()) + } + } }; }
Signature · 1 line
2.51.0
Re: [PATCH 7/7] rust: migration: implement ToMigrationState as part of impl_vmstate_bitsized
Quoted 6 lines · Paolo Bonzini
Date: Sat, 20 Sep 2025 16:29:58 +0200
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 7/7] rust: migration: implement ToMigrationState as part of
impl_vmstate_bitsized
X-Mailer: git-send-email 2.51.0
Quoted 7 lines
This is most likely desirable, and is the easiest way to migrate a bit-sized value without peeking at the innards of the bilge crate.
Signed-off-by Paolo Bonzini <[email protected]>--- rust/migration/src/vmstate.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+)