diff options
Diffstat (limited to 'rust')
-rw-r--r-- | rust/Cargo.lock | 3 | ||||
-rw-r--r-- | rust/bql/Cargo.toml | 1 | ||||
-rw-r--r-- | rust/bql/meson.build | 1 | ||||
-rw-r--r-- | rust/bql/src/cell.rs | 23 | ||||
-rw-r--r-- | rust/hw/char/pl011/src/registers.rs | 1 | ||||
-rw-r--r-- | rust/hw/timer/hpet/src/fw_cfg.rs | 4 | ||||
-rw-r--r-- | rust/meson.build | 2 | ||||
-rw-r--r-- | rust/migration/Cargo.toml | 2 | ||||
-rw-r--r-- | rust/migration/meson.build | 7 | ||||
-rw-r--r-- | rust/migration/src/lib.rs | 5 | ||||
-rw-r--r-- | rust/migration/src/migratable.rs | 442 | ||||
-rw-r--r-- | rust/migration/src/vmstate.rs | 86 | ||||
-rw-r--r-- | rust/qemu-macros/src/lib.rs | 97 | ||||
-rw-r--r-- | rust/qemu-macros/src/migration_state.rs | 298 | ||||
-rw-r--r-- | rust/qemu-macros/src/tests.rs | 113 |
15 files changed, 1038 insertions, 47 deletions
diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 1108513..0c1df62 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -59,7 +59,6 @@ name = "bql" version = "0.1.0" dependencies = [ "glib-sys", - "migration", ] [[package]] @@ -198,8 +197,10 @@ checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273" name = "migration" version = "0.1.0" dependencies = [ + "bql", "common", "glib-sys", + "qemu_macros", "util", ] diff --git a/rust/bql/Cargo.toml b/rust/bql/Cargo.toml index d5177e5..8fd8131 100644 --- a/rust/bql/Cargo.toml +++ b/rust/bql/Cargo.toml @@ -13,7 +13,6 @@ repository.workspace = true rust-version.workspace = true [dependencies] -migration = { path = "../migration" } glib-sys.workspace = true [features] diff --git a/rust/bql/meson.build b/rust/bql/meson.build index 22d7c9b..091372d 100644 --- a/rust/bql/meson.build +++ b/rust/bql/meson.build @@ -37,7 +37,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], dependencies: [glib_sys_rs], ) diff --git a/rust/bql/src/cell.rs b/rust/bql/src/cell.rs index 24ab294..8ade7db 100644 --- a/rust/bql/src/cell.rs +++ b/rust/bql/src/cell.rs @@ -151,8 +151,6 @@ use std::{ 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 @@ impl<T: Default> BqlCell<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. /// @@ -580,6 +576,23 @@ impl<T> BqlRefCell<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 { + self.value.get_mut() + } + /// Returns a raw pointer to the underlying data in this cell. /// /// # Examples @@ -674,8 +687,6 @@ impl<T> From<T> for BqlRefCell<T> { } } -impl_vmstate_transparent!(crate::cell::BqlRefCell<T> where T: VMState); - struct BorrowRef<'b> { borrow: &'b Cell<BorrowFlag>, } diff --git a/rust/hw/char/pl011/src/registers.rs b/rust/hw/char/pl011/src/registers.rs index 0c3a4d7..fa57281 100644 --- a/rust/hw/char/pl011/src/registers.rs +++ b/rust/hw/char/pl011/src/registers.rs @@ -255,6 +255,7 @@ pub enum Mode { #[bitsize(2)] #[derive(Clone, Copy, Debug, Eq, FromBits, PartialEq)] +#[allow(clippy::enum_variant_names)] /// `WLEN` Word length, field of [Line Control register](LineControl). /// /// These bits indicate the number of data bits transmitted or received in a diff --git a/rust/hw/timer/hpet/src/fw_cfg.rs b/rust/hw/timer/hpet/src/fw_cfg.rs index e569b57..bb4ea89 100644 --- a/rust/hw/timer/hpet/src/fw_cfg.rs +++ b/rust/hw/timer/hpet/src/fw_cfg.rs @@ -40,7 +40,7 @@ impl HPETFwConfig { assert!(bql::is_locked()); // SAFETY: all accesses go through these methods, which guarantee // that the accesses are protected by the BQL. - let mut fw_cfg = unsafe { *addr_of_mut!(hpet_fw_cfg) }; + let fw_cfg = unsafe { &mut *addr_of_mut!(hpet_fw_cfg) }; if fw_cfg.count == u8::MAX { // first instance @@ -60,7 +60,7 @@ impl HPETFwConfig { assert!(bql::is_locked()); // SAFETY: all accesses go through these methods, which guarantee // that the accesses are protected by the BQL. - let mut fw_cfg = unsafe { *addr_of_mut!(hpet_fw_cfg) }; + let fw_cfg = unsafe { &mut *addr_of_mut!(hpet_fw_cfg) }; fw_cfg.hpet[hpet_id].event_timer_block_id = timer_block_id; fw_cfg.hpet[hpet_id].address = address; diff --git a/rust/meson.build b/rust/meson.build index 6ba075c..76e1069 100644 --- a/rust/meson.build +++ b/rust/meson.build @@ -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') diff --git a/rust/migration/Cargo.toml b/rust/migration/Cargo.toml index 94504f3..4154574 100644 --- a/rust/migration/Cargo.toml +++ b/rust/migration/Cargo.toml @@ -13,7 +13,9 @@ repository.workspace = true rust-version.workspace = true [dependencies] +bql = { path = "../bql" } common = { path = "../common" } +qemu_macros = { path = "../qemu-macros" } util = { path = "../util" } glib-sys.workspace = true diff --git a/rust/migration/meson.build b/rust/migration/meson.build index 18be65c..4444947 100644 --- a/rust/migration/meson.build +++ b/rust/migration/meson.build @@ -31,18 +31,19 @@ _migration_rs = static_library( [ 'src/lib.rs', 'src/bindings.rs', + 'src/migratable.rs', 'src/vmstate.rs', ], {'.' : _migration_bindings_inc_rs}, ), override_options: ['rust_std=2021', 'build.rust_std=2021'], rust_abi: 'rust', - link_with: [_util_rs], - dependencies: [common_rs, glib_sys_rs], + link_with: [_util_rs, _bql_rs], + dependencies: [common_rs, glib_sys_rs, qemu_macros], ) 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 diff --git a/rust/migration/src/lib.rs b/rust/migration/src/lib.rs index 5f51dde..c9bdf0d 100644 --- a/rust/migration/src/lib.rs +++ b/rust/migration/src/lib.rs @@ -2,5 +2,10 @@ pub mod bindings; +pub use qemu_macros::ToMigrationState; + +pub mod migratable; +pub use migratable::*; + pub mod vmstate; pub use vmstate::*; diff --git a/rust/migration/src/migratable.rs b/rust/migration/src/migratable.rs new file mode 100644 index 0000000..ded6fe8 --- /dev/null +++ b/rust/migration/src/migratable.rs @@ -0,0 +1,442 @@ +// Copyright 2025 Red Hat, Inc. +// Author(s): Paolo Bonzini <pbonzini@redhat.com> +// SPDX-License-Identifier: GPL-2.0-or-later + +use std::{ + fmt, + mem::size_of, + ptr::{self, addr_of, NonNull}, + sync::{Arc, Mutex}, +}; + +use bql::{BqlCell, BqlRefCell}; +use common::Zeroable; + +use crate::{ + bindings, vmstate_fields_ref, vmstate_of, InvalidError, VMState, VMStateDescriptionBuilder, +}; + +/// Enables QEMU migration support even when a type is wrapped with +/// synchronization primitives (like `Mutex`) that the C migration +/// code cannot directly handle. The trait provides methods to +/// extract essential state for migration and restore it after +/// migration completes. +/// +/// On top of extracting data from synchronization wrappers during save +/// and restoring it during load, it's also possible to use `ToMigrationState` +/// to convert runtime representations to migration-safe formats. +/// +/// # Examples +/// +/// ``` +/// use bql::BqlCell; +/// use migration::{InvalidError, ToMigrationState, VMState}; +/// # use migration::VMStateField; +/// +/// # #[derive(Debug, PartialEq, Eq)] +/// struct DeviceState { +/// counter: BqlCell<u32>, +/// enabled: bool, +/// } +/// +/// # #[derive(Debug)] +/// #[derive(Default)] +/// struct DeviceMigrationState { +/// counter: u32, +/// enabled: bool, +/// } +/// +/// # unsafe impl VMState for DeviceMigrationState { +/// # const BASE: VMStateField = ::common::Zeroable::ZERO; +/// # } +/// impl ToMigrationState for DeviceState { +/// type Migrated = DeviceMigrationState; +/// +/// fn snapshot_migration_state( +/// &self, +/// target: &mut Self::Migrated, +/// ) -> Result<(), InvalidError> { +/// target.counter = self.counter.get(); +/// target.enabled = self.enabled; +/// Ok(()) +/// } +/// +/// fn restore_migrated_state_mut( +/// &mut self, +/// source: Self::Migrated, +/// _version_id: u8, +/// ) -> Result<(), InvalidError> { +/// self.counter.set(source.counter); +/// self.enabled = source.enabled; +/// Ok(()) +/// } +/// } +/// # bql::start_test(); +/// # let dev = DeviceState { counter: 10.into(), enabled: true }; +/// # let mig = dev.to_migration_state().unwrap(); +/// # assert!(matches!(*mig, DeviceMigrationState { counter: 10, enabled: true })); +/// # let mut dev2 = DeviceState { counter: 42.into(), enabled: false }; +/// # 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; + + /// Capture the current state into a migration-safe format, failing + /// if the state cannot be migrated. + fn snapshot_migration_state(&self, target: &mut Self::Migrated) -> Result<(), InvalidError>; + + /// Restores state from a migrated representation, failing if the + /// state cannot be restored. + fn restore_migrated_state_mut( + &mut self, + source: Self::Migrated, + version_id: u8, + ) -> Result<(), InvalidError>; + + /// Convenience method to combine allocation and state capture + /// into a single operation. + fn to_migration_state(&self) -> Result<Box<Self::Migrated>, InvalidError> { + let mut migrated = Box::<Self::Migrated>::default(); + self.snapshot_migration_state(&mut migrated)?; + Ok(migrated) + } +} + +// Implementations for primitive types. Do not use a blanket implementation +// for all Copy types, because [T; N] is Copy if T is Copy; that would conflict +// with the below implementation for arrays. +macro_rules! impl_for_primitive { + ($($t:ty),*) => { + $( + impl ToMigrationState for $t { + type Migrated = Self; + + fn snapshot_migration_state( + &self, + target: &mut Self::Migrated, + ) -> Result<(), InvalidError> { + *target = *self; + Ok(()) + } + + fn restore_migrated_state_mut( + &mut self, + source: Self::Migrated, + _version_id: u8, + ) -> Result<(), InvalidError> { + *self = source; + Ok(()) + } + } + )* + }; +} + +impl_for_primitive!(u8, u16, u32, u64, i8, i16, i32, i64, bool); + +impl<T: ToMigrationState, const N: usize> ToMigrationState for [T; N] +where + [T::Migrated; N]: Default, +{ + type Migrated = [T::Migrated; N]; + + fn snapshot_migration_state(&self, target: &mut Self::Migrated) -> Result<(), InvalidError> { + for (item, target_item) in self.iter().zip(target.iter_mut()) { + item.snapshot_migration_state(target_item)?; + } + Ok(()) + } + + fn restore_migrated_state_mut( + &mut self, + source: Self::Migrated, + version_id: u8, + ) -> Result<(), InvalidError> { + for (item, source_item) in self.iter_mut().zip(source) { + item.restore_migrated_state_mut(source_item, version_id)?; + } + Ok(()) + } +} + +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) + } + + fn restore_migrated_state_mut( + &mut self, + source: Self::Migrated, + version_id: u8, + ) -> Result<(), InvalidError> { + self.get_mut() + .unwrap() + .restore_migrated_state_mut(source, version_id) + } +} + +impl<T: ToMigrationState> ToMigrationState for BqlRefCell<T> { + type Migrated = T::Migrated; + + fn snapshot_migration_state(&self, target: &mut Self::Migrated) -> Result<(), InvalidError> { + self.borrow().snapshot_migration_state(target) + } + + fn restore_migrated_state_mut( + &mut self, + source: Self::Migrated, + version_id: u8, + ) -> Result<(), InvalidError> { + self.get_mut() + .restore_migrated_state_mut(source, version_id) + } +} + +/// Extension trait for types that support migration state restoration +/// through interior mutability. +/// +/// This trait extends [`ToMigrationState`] for types that can restore +/// their state without requiring mutable access. While user structs +/// will generally use `ToMigrationState`, the device will have multiple +/// references and therefore the device struct has to employ an interior +/// mutability wrapper like [`Mutex`] or [`BqlRefCell`]. +/// +/// Anything that implements this trait can in turn be used within +/// [`Migratable<T>`], which makes no assumptions on how to achieve mutable +/// access to the runtime state. +/// +/// # Examples +/// +/// ``` +/// use std::sync::Mutex; +/// +/// use migration::ToMigrationStateShared; +/// +/// let device_state = Mutex::new(42); +/// // Can restore without &mut access +/// device_state.restore_migrated_state(100, 1).unwrap(); +/// assert_eq!(*device_state.lock().unwrap(), 100); +/// ``` +pub trait ToMigrationStateShared: ToMigrationState { + /// Restores state from a migrated representation to an interior-mutable + /// object. Similar to `restore_migrated_state_mut`, but requires a + /// shared reference; therefore it can be used to restore a device's + /// state even though devices have multiple references to them. + fn restore_migrated_state( + &self, + source: Self::Migrated, + version_id: u8, + ) -> Result<(), InvalidError>; +} + +impl<T: ToMigrationStateShared, const N: usize> ToMigrationStateShared for [T; N] +where + [T::Migrated; N]: Default, +{ + fn restore_migrated_state( + &self, + source: Self::Migrated, + version_id: u8, + ) -> Result<(), InvalidError> { + for (item, source_item) in self.iter().zip(source) { + item.restore_migrated_state(source_item, version_id)?; + } + Ok(()) + } +} + +// Arc requires the contained object to be interior-mutable +impl<T: ToMigrationStateShared> ToMigrationState for Arc<T> { + type Migrated = T::Migrated; + + fn snapshot_migration_state(&self, target: &mut Self::Migrated) -> Result<(), InvalidError> { + (**self).snapshot_migration_state(target) + } + + fn restore_migrated_state_mut( + &mut self, + source: Self::Migrated, + version_id: u8, + ) -> Result<(), InvalidError> { + (**self).restore_migrated_state(source, version_id) + } +} + +impl<T: ToMigrationStateShared> ToMigrationStateShared for Arc<T> { + fn restore_migrated_state( + &self, + source: Self::Migrated, + version_id: u8, + ) -> Result<(), InvalidError> { + (**self).restore_migrated_state(source, version_id) + } +} + +// Interior-mutable types. Note how they only require ToMigrationState for +// the inner type! + +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) + } +} + +impl<T: ToMigrationState> ToMigrationStateShared for BqlRefCell<T> { + fn restore_migrated_state( + &self, + source: Self::Migrated, + version_id: u8, + ) -> Result<(), InvalidError> { + self.borrow_mut() + .restore_migrated_state_mut(source, version_id) + } +} + +/// A wrapper that enables QEMU migration for types with shared state. +/// +/// `Migratable<T>` provides a bridge between Rust types that use interior +/// mutability (like `Mutex<T>`) and QEMU's C-based migration infrastructure. +/// It manages the lifecycle of migration state and provides automatic +/// conversion between runtime and migration representations. +/// +/// ``` +/// # use std::sync::Mutex; +/// # 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 { +/// // ... +/// registers: Migratable<Mutex<DeviceRegs>>, +/// } +/// ``` +#[repr(C)] +pub struct Migratable<T: ToMigrationStateShared> { + /// Pointer to migration state, valid only during migration operations. + /// C vmstate does not support NULL pointers, so no `Option<Box<>>`. + migration_state: BqlCell<*mut T::Migrated>, + + /// The runtime state that can be accessed during normal operation + runtime_state: T, +} + +impl<T: ToMigrationStateShared> std::ops::Deref for Migratable<T> { + type Target = T; + + fn deref(&self) -> &Self::Target { + &self.runtime_state + } +} + +impl<T: ToMigrationStateShared> std::ops::DerefMut for Migratable<T> { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.runtime_state + } +} + +impl<T: ToMigrationStateShared> Migratable<T> { + /// Creates a new `Migratable` wrapper around the given runtime state. + /// + /// # Returns + /// A new `Migratable` instance ready for use and migration + pub fn new(runtime_state: T) -> Self { + Self { + migration_state: BqlCell::new(ptr::null_mut()), + runtime_state, + } + } + + fn pre_save(&self) -> Result<(), InvalidError> { + let state = self.runtime_state.to_migration_state()?; + self.migration_state.set(Box::into_raw(state)); + Ok(()) + } + + fn post_save(&self) -> Result<(), InvalidError> { + let state = unsafe { Box::from_raw(self.migration_state.replace(ptr::null_mut())) }; + drop(state); + Ok(()) + } + + fn pre_load(&self) -> Result<(), InvalidError> { + self.migration_state + .set(Box::into_raw(Box::<T::Migrated>::default())); + Ok(()) + } + + fn post_load(&self, version_id: u8) -> Result<(), InvalidError> { + let state = unsafe { Box::from_raw(self.migration_state.replace(ptr::null_mut())) }; + self.runtime_state + .restore_migrated_state(*state, version_id) + } +} + +impl<T: ToMigrationStateShared + fmt::Debug> fmt::Debug for Migratable<T> +where + T::Migrated: fmt::Debug, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mut struct_f = f.debug_struct("Migratable"); + struct_f.field("runtime_state", &self.runtime_state); + + let state = NonNull::new(self.migration_state.get()).map(|x| unsafe { x.as_ref() }); + struct_f.field("migration_state", &state); + struct_f.finish() + } +} + +impl<T: ToMigrationStateShared + Default> Default for Migratable<T> { + fn default() -> Self { + Self::new(T::default()) + } +} + +impl<T: 'static + ToMigrationStateShared> Migratable<T> { + const FIELD: bindings::VMStateField = vmstate_of!(Self, migration_state); + + const FIELDS: &[bindings::VMStateField] = vmstate_fields_ref! { + Migratable::<T>::FIELD + }; + + const VMSD: &'static bindings::VMStateDescription = VMStateDescriptionBuilder::<Self>::new() + .version_id(1) + .minimum_version_id(1) + .pre_save(&Self::pre_save) + .pre_load(&Self::pre_load) + .post_save(&Self::post_save) + .post_load(&Self::post_load) + .fields(Self::FIELDS) + .build() + .as_ref(); +} + +unsafe impl<T: 'static + ToMigrationStateShared> VMState for Migratable<T> { + const BASE: bindings::VMStateField = { + bindings::VMStateField { + vmsd: addr_of!(*Self::VMSD), + size: size_of::<Self>(), + flags: bindings::VMStateFlags::VMS_STRUCT, + ..Zeroable::ZERO + } + }; +} diff --git a/rust/migration/src/vmstate.rs b/rust/migration/src/vmstate.rs index e04b19b..42e5df8d 100644 --- a/rust/migration/src/vmstate.rs +++ b/rust/migration/src/vmstate.rs @@ -72,6 +72,7 @@ macro_rules! call_func_with_field { ($func:expr, $typ:ty, $($field:tt).+) => { $func(loop { #![allow(unreachable_code)] + #![allow(unused_variables)] const fn phantom__<T>(_: &T) -> ::core::marker::PhantomData<T> { ::core::marker::PhantomData } // Unreachable code is exempt from checks on uninitialized values. // Use that trick to infer the type of this PhantomData. @@ -275,6 +276,8 @@ macro_rules! impl_vmstate_transparent { }; } +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); @@ -293,6 +296,25 @@ macro_rules! impl_vmstate_bitsized { as ::bilge::prelude::Number>::UnderlyingType as $crate::vmstate::VMState>::VARRAY_FLAG; } + + impl $crate::migratable::ToMigrationState for $type { + type Migrated = <<$type as ::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(()) + } + } }; } @@ -411,20 +433,31 @@ macro_rules! vmstate_exist_fn { }}; } +/// 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() + ); + _FIELDS }} } @@ -469,33 +502,21 @@ macro_rules! impl_vmstate_struct { }; } -/// A transparent wrapper type for the `subsections` field of -/// [`VMStateDescription`]. -/// -/// This is necessary to be able to declare subsection descriptions as statics, -/// because the only way to implement `Sync` for a foreign type (and `*const` -/// pointers are foreign types in Rust) is to create a wrapper struct and -/// `unsafe impl Sync` for it. -/// -/// This struct is used in the -/// [`vm_state_subsections`](crate::vmstate_subsections) macro implementation. -#[repr(transparent)] -pub struct VMStateSubsectionsWrapper(pub &'static [*const crate::bindings::VMStateDescription]); - -unsafe impl Sync for VMStateSubsectionsWrapper {} +/// The type returned by [`vmstate_subsections!`](crate::vmstate_subsections). +pub type VMStateSubsections = &'static [Option<&'static crate::bindings::VMStateDescription>]; /// Helper macro to declare a list of subsections ([`VMStateDescription`]) /// into a static and return a pointer to the array of pointers it created. #[macro_export] macro_rules! vmstate_subsections { ($($subsection:expr),*$(,)*) => {{ - static _SUBSECTIONS: $crate::vmstate::VMStateSubsectionsWrapper = $crate::vmstate::VMStateSubsectionsWrapper(&[ + static _SUBSECTIONS: $crate::vmstate::VMStateSubsections = &[ $({ static _SUBSECTION: $crate::bindings::VMStateDescription = $subsection.get(); - ::core::ptr::addr_of!(_SUBSECTION) + Some(&_SUBSECTION) }),*, - ::core::ptr::null() - ]); + None, + ]; &_SUBSECTIONS }} } @@ -676,14 +697,21 @@ impl<T> VMStateDescriptionBuilder<T> { } #[must_use] - pub const fn fields(mut self, fields: *const VMStateField) -> Self { - self.0.fields = fields; + pub const fn fields(mut self, fields: &'static [VMStateField]) -> Self { + if fields[fields.len() - 1].flags.0 != VMStateFlags::VMS_END.0 { + panic!("fields are not terminated, use vmstate_fields!"); + } + self.0.fields = fields.as_ptr(); self } #[must_use] - pub const fn subsections(mut self, subs: &'static VMStateSubsectionsWrapper) -> Self { - self.0.subsections = subs.0.as_ptr(); + pub const fn subsections(mut self, subs: &'static VMStateSubsections) -> Self { + if subs[subs.len() - 1].is_some() { + panic!("subsections are not terminated, use vmstate_subsections!"); + } + let subs: *const Option<&bindings::VMStateDescription> = subs.as_ptr(); + self.0.subsections = subs.cast::<*const bindings::VMStateDescription>(); self } diff --git a/rust/qemu-macros/src/lib.rs b/rust/qemu-macros/src/lib.rs index 3e21b67..50239f2 100644 --- a/rust/qemu-macros/src/lib.rs +++ b/rust/qemu-macros/src/lib.rs @@ -13,9 +13,13 @@ use syn::{ Attribute, Data, DeriveInput, Error, Field, Fields, FieldsUnnamed, Ident, Meta, Path, Token, Variant, }; + mod bits; use bits::BitsConstInternal; +mod migration_state; +use migration_state::MigrationStateDerive; + #[cfg(test)] mod tests; @@ -401,7 +405,98 @@ pub fn bits_const_internal(ts: TokenStream) -> TokenStream { let ts = proc_macro2::TokenStream::from(ts); let mut it = ts.into_iter(); - BitsConstInternal::parse(&mut it) + let out = BitsConstInternal::parse(&mut it).unwrap_or_else(syn::Error::into_compile_error); + + // https://github.com/rust-lang/rust-clippy/issues/15852 + quote! { + { + #[allow(clippy::double_parens)] + #out + } + } + .into() +} + +/// 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: +/// +/// - `#[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. +/// +/// - `#[migration_state(clone)]` - Clones the field value. +/// +/// 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`. +/// +/// # Examples +/// +/// Basic usage: +/// ```ignore +/// #[derive(ToMigrationState)] +/// struct MyStruct { +/// field1: u32, +/// field2: Timer, +/// } +/// ``` +/// +/// With attributes: +/// ```ignore +/// #[derive(ToMigrationState)] +/// #[migration_state(rename = CustomMigration)] +/// struct MyStruct { +/// #[migration_state(omit)] +/// runtime_field: u32, +/// +/// #[migration_state(clone)] +/// shared_data: String, +/// +/// #[migration_state(into(Cow<'static, str>), clone)] +/// converted_field: String, +/// +/// #[migration_state(try_into(i8))] +/// fallible_field: u32, +/// +/// // Default: use ToMigrationState trait recursively +/// nested_field: NestedStruct, +/// +/// // Primitive types have a default implementation of ToMigrationState +/// simple_field: u32, +/// } +/// ``` +#[proc_macro_derive(ToMigrationState, attributes(migration_state))] +pub fn derive_to_migration_state(input: TokenStream) -> TokenStream { + let input = parse_macro_input!(input as DeriveInput); + MigrationStateDerive::expand(input) .unwrap_or_else(syn::Error::into_compile_error) .into() } diff --git a/rust/qemu-macros/src/migration_state.rs b/rust/qemu-macros/src/migration_state.rs new file mode 100644 index 0000000..5edf0ef --- /dev/null +++ b/rust/qemu-macros/src/migration_state.rs @@ -0,0 +1,298 @@ +use std::borrow::Cow; + +use proc_macro2::TokenStream; +use quote::{format_ident, quote, ToTokens}; +use syn::{spanned::Spanned, DeriveInput, Error, Field, Ident, Result, Type}; + +use crate::get_fields; + +#[derive(Debug, Default)] +enum ConversionMode { + #[default] + None, + Omit, + Into(Type), + TryInto(Type), + ToMigrationState, +} + +impl ConversionMode { + fn target_type(&self, original_type: &Type) -> TokenStream { + match self { + ConversionMode::Into(ty) | ConversionMode::TryInto(ty) => ty.to_token_stream(), + ConversionMode::ToMigrationState => { + quote! { <#original_type as ToMigrationState>::Migrated } + } + _ => original_type.to_token_stream(), + } + } +} + +#[derive(Debug, Default)] +struct ContainerAttrs { + rename: Option<Ident>, +} + +impl ContainerAttrs { + fn parse_from(&mut self, attrs: &[syn::Attribute]) -> Result<()> { + use attrs::{set, with, Attrs}; + Attrs::new() + .once("rename", with::eq(set::parse(&mut self.rename))) + .parse_attrs("migration_state", attrs)?; + Ok(()) + } + + fn parse(attrs: &[syn::Attribute]) -> Result<Self> { + let mut container_attrs = Self::default(); + container_attrs.parse_from(attrs)?; + Ok(container_attrs) + } +} + +#[derive(Debug, Default)] +struct FieldAttrs { + conversion: ConversionMode, + clone: bool, +} + +impl FieldAttrs { + fn parse_from(&mut self, attrs: &[syn::Attribute]) -> Result<()> { + let mut omit_flag = false; + let mut into_type: Option<Type> = None; + let mut try_into_type: Option<Type> = None; + + use attrs::{set, with, Attrs}; + Attrs::new() + .once("omit", set::flag(&mut omit_flag)) + .once("into", with::paren(set::parse(&mut into_type))) + .once("try_into", with::paren(set::parse(&mut try_into_type))) + .once("clone", set::flag(&mut self.clone)) + .parse_attrs("migration_state", attrs)?; + + self.conversion = match (omit_flag, into_type, try_into_type, self.clone) { + // Valid combinations of attributes first... + (true, None, None, false) => ConversionMode::Omit, + (false, Some(ty), None, _) => ConversionMode::Into(ty), + (false, None, Some(ty), _) => ConversionMode::TryInto(ty), + (false, None, None, true) => ConversionMode::None, // clone without conversion + (false, None, None, false) => ConversionMode::ToMigrationState, // default behavior + + // ... then the error cases + (true, _, _, _) => { + return Err(Error::new( + attrs[0].span(), + "ToMigrationState: omit cannot be used with other attributes", + )); + } + (_, Some(_), Some(_), _) => { + return Err(Error::new( + attrs[0].span(), + "ToMigrationState: into and try_into attributes cannot be used together", + )); + } + }; + + Ok(()) + } + + fn parse(attrs: &[syn::Attribute]) -> Result<Self> { + let mut field_attrs = Self::default(); + field_attrs.parse_from(attrs)?; + Ok(field_attrs) + } +} + +#[derive(Debug)] +struct MigrationStateField { + name: Ident, + original_type: Type, + attrs: FieldAttrs, +} + +impl MigrationStateField { + fn maybe_clone(&self, mut value: TokenStream) -> TokenStream { + if self.attrs.clone { + value = quote! { #value.clone() }; + } + value + } + + fn generate_migration_state_field(&self) -> TokenStream { + let name = &self.name; + let field_type = self.attrs.conversion.target_type(&self.original_type); + + quote! { + pub #name: #field_type, + } + } + + fn generate_snapshot_field(&self) -> TokenStream { + let name = &self.name; + let value = self.maybe_clone(quote! { self.#name }); + + match &self.attrs.conversion { + ConversionMode::Omit => { + unreachable!("Omitted fields are filtered out during processing") + } + ConversionMode::None => quote! { + target.#name = #value; + }, + ConversionMode::Into(_) => quote! { + target.#name = #value.into(); + }, + ConversionMode::TryInto(_) => quote! { + target.#name = #value.try_into().map_err(|_| migration::InvalidError)?; + }, + ConversionMode::ToMigrationState => quote! { + self.#name.snapshot_migration_state(&mut target.#name)?; + }, + } + } + + fn generate_restore_field(&self) -> TokenStream { + let name = &self.name; + + match &self.attrs.conversion { + ConversionMode::Omit => { + unreachable!("Omitted fields are filtered out during processing") + } + ConversionMode::None => quote! { + self.#name = #name; + }, + ConversionMode::Into(_) => quote! { + self.#name = #name.into(); + }, + ConversionMode::TryInto(_) => quote! { + self.#name = #name.try_into().map_err(|_| migration::InvalidError)?; + }, + ConversionMode::ToMigrationState => quote! { + self.#name.restore_migrated_state_mut(#name, _version_id)?; + }, + } + } +} + +#[derive(Debug)] +pub struct MigrationStateDerive { + input: DeriveInput, + fields: Vec<MigrationStateField>, + container_attrs: ContainerAttrs, +} + +impl MigrationStateDerive { + fn parse(input: DeriveInput) -> Result<Self> { + let container_attrs = ContainerAttrs::parse(&input.attrs)?; + let fields = get_fields(&input, "ToMigrationState")?; + let fields = Self::process_fields(fields)?; + + Ok(Self { + input, + fields, + container_attrs, + }) + } + + fn process_fields( + fields: &syn::punctuated::Punctuated<Field, syn::token::Comma>, + ) -> Result<Vec<MigrationStateField>> { + let processed = fields + .iter() + .map(|field| { + let attrs = FieldAttrs::parse(&field.attrs)?; + Ok((field, attrs)) + }) + .collect::<Result<Vec<_>>>()? + .into_iter() + .filter(|(_, attrs)| !matches!(attrs.conversion, ConversionMode::Omit)) + .map(|(field, attrs)| MigrationStateField { + name: field.ident.as_ref().unwrap().clone(), + original_type: field.ty.clone(), + attrs, + }) + .collect(); + + Ok(processed) + } + + fn migration_state_name(&self) -> Cow<'_, Ident> { + match &self.container_attrs.rename { + Some(rename) => Cow::Borrowed(rename), + None => Cow::Owned(format_ident!("{}Migration", &self.input.ident)), + } + } + + fn generate_migration_state_struct(&self) -> TokenStream { + let name = self.migration_state_name(); + let fields = self + .fields + .iter() + .map(MigrationStateField::generate_migration_state_field); + + quote! { + #[derive(Default)] + pub struct #name { + #(#fields)* + } + } + } + + fn generate_snapshot_migration_state(&self) -> TokenStream { + let fields = self + .fields + .iter() + .map(MigrationStateField::generate_snapshot_field); + + quote! { + fn snapshot_migration_state(&self, target: &mut Self::Migrated) -> Result<(), migration::InvalidError> { + #(#fields)* + Ok(()) + } + } + } + + fn generate_restore_migrated_state(&self) -> TokenStream { + let names: Vec<_> = self.fields.iter().map(|f| &f.name).collect(); + let fields = self + .fields + .iter() + .map(MigrationStateField::generate_restore_field); + + // version_id could be used or not depending on conversion attributes + quote! { + #[allow(clippy::used_underscore_binding)] + fn restore_migrated_state_mut(&mut self, source: Self::Migrated, _version_id: u8) -> Result<(), migration::InvalidError> { + let Self::Migrated { #(#names),* } = source; + #(#fields)* + Ok(()) + } + } + } + + fn generate(&self) -> TokenStream { + let struct_name = &self.input.ident; + let generics = &self.input.generics; + + let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); + let name = self.migration_state_name(); + let migration_state_struct = self.generate_migration_state_struct(); + let snapshot_impl = self.generate_snapshot_migration_state(); + let restore_impl = self.generate_restore_migrated_state(); + + quote! { + #migration_state_struct + + impl #impl_generics ToMigrationState for #struct_name #ty_generics #where_clause { + type Migrated = #name; + + #snapshot_impl + + #restore_impl + } + } + } + + pub fn expand(input: DeriveInput) -> Result<TokenStream> { + let tokens = Self::parse(input)?.generate(); + Ok(tokens) + } +} diff --git a/rust/qemu-macros/src/tests.rs b/rust/qemu-macros/src/tests.rs index ac998d2..6569141 100644 --- a/rust/qemu-macros/src/tests.rs +++ b/rust/qemu-macros/src/tests.rs @@ -7,7 +7,7 @@ use quote::quote; use super::*; macro_rules! derive_compile_fail { - ($derive_fn:ident, $input:expr, $($error_msg:expr),+ $(,)?) => {{ + ($derive_fn:path, $input:expr, $($error_msg:expr),+ $(,)?) => {{ let input: proc_macro2::TokenStream = $input; let error_msg = &[$( quote! { ::core::compile_error! { $error_msg } } ),*]; let derive_fn: fn(input: syn::DeriveInput) -> Result<proc_macro2::TokenStream, syn::Error> = @@ -24,7 +24,7 @@ macro_rules! derive_compile_fail { } macro_rules! derive_compile { - ($derive_fn:ident, $input:expr, $($expected:tt)*) => {{ + ($derive_fn:path, $input:expr, $($expected:tt)*) => {{ let input: proc_macro2::TokenStream = $input; let expected: proc_macro2::TokenStream = $($expected)*; let derive_fn: fn(input: syn::DeriveInput) -> Result<proc_macro2::TokenStream, syn::Error> = @@ -345,3 +345,112 @@ fn test_derive_tryinto() { } ); } + +#[test] +fn test_derive_to_migration_state() { + derive_compile_fail!( + MigrationStateDerive::expand, + quote! { + struct MyStruct { + #[migration_state(omit, clone)] + bad: u32, + } + }, + "ToMigrationState: omit cannot be used with other attributes" + ); + derive_compile_fail!( + MigrationStateDerive::expand, + quote! { + struct MyStruct { + #[migration_state(into)] + bad: u32, + } + }, + "unexpected end of input, expected parentheses" + ); + derive_compile_fail!( + MigrationStateDerive::expand, + quote! { + struct MyStruct { + #[migration_state(into(String), try_into(String))] + bad: &'static str, + } + }, + "ToMigrationState: into and try_into attributes cannot be used together" + ); + derive_compile!( + MigrationStateDerive::expand, + quote! { + #[migration_state(rename = CustomMigration)] + struct MyStruct { + #[migration_state(omit)] + runtime_field: u32, + + #[migration_state(clone)] + shared_data: String, + + #[migration_state(into(Cow<'static, str>), clone)] + converted_field: String, + + #[migration_state(try_into(i8))] + fallible_field: u32, + + nested_field: NestedStruct, + simple_field: u32, + } + }, + 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, + } + impl ToMigrationState for MyStruct { + type Migrated = CustomMigration; + fn snapshot_migration_state( + &self, + target: &mut Self::Migrated + ) -> Result<(), migration::InvalidError> { + target.shared_data = self.shared_data.clone(); + target.converted_field = self.converted_field.clone().into(); + target.fallible_field = self + .fallible_field + .try_into() + .map_err(|_| migration::InvalidError)?; + self.nested_field + .snapshot_migration_state(&mut target.nested_field)?; + self.simple_field + .snapshot_migration_state(&mut target.simple_field)?; + Ok(()) + } + #[allow(clippy::used_underscore_binding)] + fn restore_migrated_state_mut( + &mut self, + source: Self::Migrated, + _version_id: u8 + ) -> Result<(), migration::InvalidError> { + let Self::Migrated { + shared_data, + converted_field, + fallible_field, + nested_field, + simple_field + } = source; + self.shared_data = shared_data; + self.converted_field = converted_field.into(); + self.fallible_field = fallible_field + .try_into() + .map_err(|_| migration::InvalidError)?; + self.nested_field + .restore_migrated_state_mut(nested_field, _version_id)?; + self.simple_field + .restore_migrated_state_mut(simple_field, _version_id)?; + Ok(()) + } + } + } + ); +} |