Skip to contentSkip to conversation

rust: prepare for splitting crates

PATCH In review Paolo Bonzini 2 participants 34 messages Feb 21, 2025 – Feb 25, 2025

Subsystems (2)
lore
Share & tools
lore
#0 lore raw

cover rust: prepare for splitting crates

This series is logically split in two parts. The first one is more strictly tied to the objective of splitting qemu_api into multiple crates, as it breaks the QOM bindings free of the constraints imposed by Rust orphan rules. The second one instead completes another task that was on my todo list, namely ensuring that rustc sees the possible changes that C functions can make when a shared reference &bindings::Foo is passed via *mut bindings::Foo.

More in detail, patches 1-5 redo the QOM class init mechanism so that it does not rely on the ClassInitImpl trait. While ClassInitImpl is very nice in theory, it practice it does not play well with classes defined outside qemu_api (or more precisely, outside the crate that defines ClassInitImpl itself). This is because ClassInitImpl relies on a blanket implementation such as

impl<T> ClassInitImpl<ObjectClass> for T
where
T: ObjectImpl

and this is only possible inside the crate that defines ClassInitImpl. With these patches the class_init methods move from ClassInitImpl<Class> to the Class struct itself. More precisely, before the series you have

<T as ClassInitImpl<ObjectClass>>::class_init

and afterwards

ObjectClass::class_init::<T>

which is assigned to the CLASS_INIT associated const of ObjectImpl. The problem is that even if CLASS_INIT is always defined the same way, i.e.

    const CLASS_INIT: fn(&mut Self::Class) = Self::Class::class_init::<Self>;

there isn't a way to tell the compiler that the above is valid *in the definition of ObjectImpl*. Therefore the above line has to be duplicated in all subclasses; this however is a small issue and in the future it could be handled by #[derive(Object)].

Patches 6-15 instead introduce a third generic type in qemu_api::cell, Opaque<T>. This type is similar to a same-named type in Linux; it is basically a "disable all undefined behavior" switch for the Rust compiler and it helps maintaining safety at the Rust/C boundary, complementing the existing BqlCell and BqlRefCell types.

Apart from making things more formally correct, this makes it possible to implement methods on a struct that is distinct from the one produced by bindgen. This has a couple of advantages:

- you do not have to disable the Copy trait on structs where you want to add a Drop trait. This was already a problem for the Timer struct.

- whether Send and Sync are implemented is entirely a decision of the place that implements the wrapper. Previously, a struct with no pointers for example would have been always both Send and Sync, whereas now that can be adjusted depending on the actual thread-safety of the Rust methods.

- more pertinent to the "multiple crates" plan, you do not have to put the methods in the same crate as the bindgen-generated bindings.inc.rs.

It also makes Debug output a bit less unwieldy, and in the future one might want to add specialized implementations of Display and Debug that are both useful and readable.

Paolo

Paolo Bonzini (15):
rust: add IsA bounds to QOM implementation traits
rust: add SysBusDeviceImpl
rust: qom: add ObjectImpl::CLASS_INIT
rust: pl011, qemu_api tests: do not use ClassInitImpl
rust: qom: get rid of ClassInitImpl
rust: cell: add wrapper for FFI types
rust: qemu_api_macros: add Wrapper derive macro
rust: timer: wrap QEMUTimer with Opaque<>
rust: irq: wrap IRQState with Opaque<>
rust: qom: wrap Object with Opaque<>
rust: qdev: wrap Clock and DeviceState with Opaque<>
rust: sysbus: wrap SysBusDevice with Opaque<>
rust: memory: wrap MemoryRegion with Opaque<>
rust: chardev: wrap Chardev with Opaque<>
rust: bindings: remove more unnecessary Send/Sync impls

 docs/devel/rust.rst              |  36 +++--
 meson.build                      |   7 -
 rust/hw/char/pl011/src/device.rs |  44 +++---
 rust/hw/timer/hpet/src/hpet.rs   |   7 +-
 rust/qemu-api-macros/src/lib.rs  |  82 +++++++++++-
 rust/qemu-api/meson.build        |   7 +-
 rust/qemu-api/src/bindings.rs    |  26 +---
 rust/qemu-api/src/cell.rs        | 222 ++++++++++++++++++++++++++++++-
 rust/qemu-api/src/chardev.rs     |   8 +-
 rust/qemu-api/src/irq.rs         |  15 ++-
 rust/qemu-api/src/memory.rs      |  32 ++---
 rust/qemu-api/src/qdev.rs        | 115 ++++++++++------
 rust/qemu-api/src/qom.rs         | 203 ++++++++++++++--------------
 rust/qemu-api/src/sysbus.rs      |  45 ++++---
 rust/qemu-api/src/timer.rs       |  24 +++-
 rust/qemu-api/src/vmstate.rs     |   2 +-
 rust/qemu-api/tests/tests.rs     |  32 ++---
 17 files changed, 620 insertions(+), 287 deletions(-)
Signature · 1 line
2.48.1
#1 lore raw

PATCH 1/15 rust: add IsA bounds to QOM implementation traits

Check that the right bounds are provided to the qom_isa! macro whenever the class is defined to implement a certain class. This removes the need to add IsA<> bounds together with the *Impl trait bounds.

---
 rust/qemu-api/src/qdev.rs | 2 +-
 rust/qemu-api/src/qom.rs  | 4 +++-
 2 files changed, 4 insertions(+), 2 deletions(-)
rust/qemu-api/src/qdev.rs +1 -1
index 3a7aa4def62..c4dd26b582c 100644
@@ -86,7 +86,7 @@ pub trait ResettablePhasesImpl {
 }
 
 /// Trait providing the contents of [`DeviceClass`].
-pub trait DeviceImpl: ObjectImpl + ResettablePhasesImpl {
+pub trait DeviceImpl: ObjectImpl + ResettablePhasesImpl + IsA<DeviceState> {
     /// _Realization_ is the second stage of device creation. It contains
     /// all operations that depend on device properties and can fail (note:
     /// this is not yet supported for Rust devices).
rust/qemu-api/src/qom.rs +3 -1
index 3d5ab2d9018..10ce359becb 100644
@@ -37,6 +37,8 @@
 //! * a trait for virtual method implementations, for example `DeviceImpl`.
 //!   Child classes implement this trait to provide their own behavior for
 //!   virtual methods. The trait's methods take `&self` to access instance data.
+//!   The traits have the appropriate specialization of `IsA<>` as a supertrait,
+//!   for example `IsA<DeviceState>` for `DeviceImpl`.
 //!
 //! * an implementation of [`ClassInitImpl`], for example
 //!   `ClassInitImpl<DeviceClass>`. This fills the vtable in the class struct;
@@ -497,7 +499,7 @@ impl<T: ObjectType> ObjectDeref for &mut T {}
 impl<T: ObjectType> ObjectCastMut for &mut T {}
 
 /// Trait a type must implement to be registered with QEMU.
-pub trait ObjectImpl: ObjectType + ClassInitImpl<Self::Class> {
+pub trait ObjectImpl: ObjectType + ClassInitImpl<Self::Class> + IsA<Object> {
     /// The parent of the type.  This should match the first field of the
     /// struct that implements `ObjectImpl`, minus the `ParentField<_>` wrapper.
     type ParentType: ObjectType;
Signature · 1 line
2.48.1
Reviewed-by on v1 1/15
#2 lore raw

Re: [PATCH 01/15] rust: add IsA bounds to QOM implementation traits

Quoted 10 lines · Paolo Bonzini

Date: Fri, 21 Feb 2025 18:03:28 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 01/15] rust: add IsA bounds to QOM implementation traits
X-Mailer: git-send-email 2.48.1

Check that the right bounds are provided to the qom_isa! macro whenever the class is defined to implement a certain class. This removes the need to add IsA<> bounds together with the *Impl trait bounds.

Quoted 5 lines
---
 rust/qemu-api/src/qdev.rs | 2 +-
 rust/qemu-api/src/qom.rs  | 4 +++-
 2 files changed, 4 insertions(+), 2 deletions(-)
#3 lore raw

PATCH 2/15 rust: add SysBusDeviceImpl

In reply to Paolo Bonzini

The only function, right now, is to ensure that anything with a SysBusDeviceClass class is a SysBusDevice.

---
 rust/hw/char/pl011/src/device.rs | 5 ++++-
 rust/hw/timer/hpet/src/hpet.rs   | 4 +++-
 rust/qemu-api/src/sysbus.rs      | 8 +++++---
 3 files changed, 12 insertions(+), 5 deletions(-)
rust/hw/char/pl011/src/device.rs +4 -1
index fe73771021e..7063b60c0cc 100644
@@ -20,7 +20,7 @@
     prelude::*,
     qdev::{Clock, ClockEvent, DeviceImpl, DeviceState, Property, ResetType, ResettablePhasesImpl},
     qom::{ClassInitImpl, ObjectImpl, Owned, ParentField},
-    sysbus::{SysBusDevice, SysBusDeviceClass},
+    sysbus::{SysBusDevice, SysBusDeviceClass, SysBusDeviceImpl},
     vmstate::VMStateDescription,
 };
 
@@ -176,6 +176,8 @@ impl ResettablePhasesImpl for PL011State {
     const HOLD: Option<fn(&Self, ResetType)> = Some(Self::reset_hold);
 }
 
+impl SysBusDeviceImpl for PL011State {}
+
 impl PL011Registers {
     pub(self) fn read(&mut self, offset: RegisterOffset) -> (bool, u32) {
         use RegisterOffset::*;
@@ -746,3 +748,4 @@ impl ObjectImpl for PL011Luminary {
 
 impl DeviceImpl for PL011Luminary {}
 impl ResettablePhasesImpl for PL011Luminary {}
+impl SysBusDeviceImpl for PL011Luminary {}
rust/hw/timer/hpet/src/hpet.rs +3 -1
index 75ff5b3e8d6..b4ffccf815f 100644
@@ -23,7 +23,7 @@
     qdev::{DeviceImpl, DeviceMethods, DeviceState, Property, ResetType, ResettablePhasesImpl},
     qom::{ObjectImpl, ObjectType, ParentField},
     qom_isa,
-    sysbus::SysBusDevice,
+    sysbus::{SysBusDevice, SysBusDeviceImpl},
     timer::{Timer, CLOCK_VIRTUAL},
 };
 
@@ -887,3 +887,5 @@ fn properties() -> &'static [Property] {
 impl ResettablePhasesImpl for HPETState {
     const HOLD: Option<fn(&Self, ResetType)> = Some(Self::reset_hold);
 }
+
+impl SysBusDeviceImpl for HPETState {}
rust/qemu-api/src/sysbus.rs +5 -3
index fa36e12178f..fee2e3d478f 100644
@@ -14,7 +14,7 @@
     irq::{IRQState, InterruptSource},
     memory::MemoryRegion,
     prelude::*,
-    qdev::{DeviceClass, DeviceState},
+    qdev::{DeviceClass, DeviceImpl, DeviceState},
     qom::{ClassInitImpl, Owned},
 };
 
@@ -25,10 +25,12 @@ unsafe impl ObjectType for SysBusDevice {
 }
 qom_isa!(SysBusDevice: DeviceState, Object);
 
-// TODO: add SysBusDeviceImpl
+// TODO: add virtual methods
+pub trait SysBusDeviceImpl: DeviceImpl + IsA<SysBusDevice> {}
+
 impl<T> ClassInitImpl<SysBusDeviceClass> for T
 where
-    T: ClassInitImpl<DeviceClass>,
+    T: SysBusDeviceImpl + ClassInitImpl<DeviceClass>,
 {
     fn class_init(sdc: &mut SysBusDeviceClass) {
         <T as ClassInitImpl<DeviceClass>>::class_init(&mut sdc.parent_class);
Signature · 1 line
2.48.1
Reviewed-by on v1 2/15
#4 lore raw

Re: [PATCH 02/15] rust: add SysBusDeviceImpl

Quoted 8 lines · Paolo Bonzini

Date: Fri, 21 Feb 2025 18:03:29 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 02/15] rust: add SysBusDeviceImpl
X-Mailer: git-send-email 2.48.1

The only function, right now, is to ensure that anything with a SysBusDeviceClass class is a SysBusDevice.

Quoted 6 lines
---
 rust/hw/char/pl011/src/device.rs | 5 ++++-
 rust/hw/timer/hpet/src/hpet.rs   | 4 +++-
 rust/qemu-api/src/sysbus.rs      | 8 +++++---
 3 files changed, 12 insertions(+), 5 deletions(-)>
#5 lore raw

PATCH 3/15 rust: qom: add ObjectImpl::CLASS_INIT

In reply to Paolo Bonzini

As shown in the PL011 device, the orphan rules required a manual implementation of ClassInitImpl for anything not in the qemu_api crate; this gets in the way of moving system emulation-specific code (including DeviceClass, which as a blanket ClassInitImpl<DeviceClass> implementation) into its own crate.

Make ClassInitImpl optional, at the cost of having to specify the CLASS_INIT member by hand in every implementation of ObjectImpl. The next commits will get rid of it, replacing all the "impl<T> ClassInitImpl<Class> for T" blocks with a generic class_init<T> method on Class.

Right now the definition is always the same, but do not provide a default as that will not be true once ClassInitImpl goes away.

---
 rust/hw/char/pl011/src/device.rs |  3 +++
 rust/hw/timer/hpet/src/hpet.rs   |  3 ++-
 rust/qemu-api/src/qom.rs         | 14 +++++++++++---
 rust/qemu-api/tests/tests.rs     |  3 +++
 4 files changed, 19 insertions(+), 4 deletions(-)
rust/hw/char/pl011/src/device.rs +3 -0
index 7063b60c0cc..a6da9db0bb0 100644
@@ -160,6 +160,7 @@ impl ObjectImpl for PL011State {
 
     const INSTANCE_INIT: Option<unsafe fn(&mut Self)> = Some(Self::init);
     const INSTANCE_POST_INIT: Option<fn(&Self)> = Some(Self::post_init);
+    const CLASS_INIT: fn(&mut Self::Class) = <Self as ClassInitImpl<Self::Class>>::class_init;
 }
 
 impl DeviceImpl for PL011State {
@@ -744,6 +745,8 @@ unsafe impl ObjectType for PL011Luminary {
 
 impl ObjectImpl for PL011Luminary {
     type ParentType = PL011State;
+
+    const CLASS_INIT: fn(&mut Self::Class) = <Self as ClassInitImpl<Self::Class>>::class_init;
 }
 
 impl DeviceImpl for PL011Luminary {}
rust/hw/timer/hpet/src/hpet.rs +2 -1
index b4ffccf815f..e01b4b67064 100644
@@ -21,7 +21,7 @@
     },
     prelude::*,
     qdev::{DeviceImpl, DeviceMethods, DeviceState, Property, ResetType, ResettablePhasesImpl},
-    qom::{ObjectImpl, ObjectType, ParentField},
+    qom::{ClassInitImpl, ObjectImpl, ObjectType, ParentField},
     qom_isa,
     sysbus::{SysBusDevice, SysBusDeviceImpl},
     timer::{Timer, CLOCK_VIRTUAL},
@@ -836,6 +836,7 @@ impl ObjectImpl for HPETState {
 
     const INSTANCE_INIT: Option<unsafe fn(&mut Self)> = Some(Self::init);
     const INSTANCE_POST_INIT: Option<fn(&Self)> = Some(Self::post_init);
+    const CLASS_INIT: fn(&mut Self::Class) = <Self as ClassInitImpl<Self::Class>>::class_init;
 }
 
 // TODO: Make these properties user-configurable!
rust/qemu-api/src/qom.rs +11 -3
index 10ce359becb..d821ac25acc 100644
@@ -180,7 +180,7 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
     T::INSTANCE_POST_INIT.unwrap()(unsafe { state.as_ref() });
 }
 
-unsafe extern "C" fn rust_class_init<T: ObjectType + ClassInitImpl<T::Class>>(
+unsafe extern "C" fn rust_class_init<T: ObjectType + ObjectImpl>(
     klass: *mut ObjectClass,
     _data: *mut c_void,
 ) {
@@ -190,7 +190,7 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
     // SAFETY: klass is a T::Class, since rust_class_init<T>
     // is called from QOM core as the class_init function
     // for class T
-    T::class_init(unsafe { klass.as_mut() })
+    <T as ObjectImpl>::CLASS_INIT(unsafe { klass.as_mut() })
 }
 
 unsafe extern "C" fn drop_object<T: ObjectImpl>(obj: *mut Object) {
@@ -499,7 +499,7 @@ impl<T: ObjectType> ObjectDeref for &mut T {}
 impl<T: ObjectType> ObjectCastMut for &mut T {}
 
 /// Trait a type must implement to be registered with QEMU.
-pub trait ObjectImpl: ObjectType + ClassInitImpl<Self::Class> + IsA<Object> {
+pub trait ObjectImpl: ObjectType + IsA<Object> {
     /// The parent of the type.  This should match the first field of the
     /// struct that implements `ObjectImpl`, minus the `ParentField<_>` wrapper.
     type ParentType: ObjectType;
@@ -552,6 +552,14 @@ pub trait ObjectImpl: ObjectType + ClassInitImpl<Self::Class> + IsA<Object> {
 
     // methods on ObjectClass
     const UNPARENT: Option<fn(&Self)> = None;
+
+    /// Store into the argument the virtual method implementations
+    /// for `Self`.  On entry, the virtual method pointers are set to
+    /// the default values coming from the parent classes; the function
+    /// can change them to override virtual methods of a parent class.
+    ///
+    /// Usually defined as `<Self as ClassInitImpl<Self::Class>::class_init`.
+    const CLASS_INIT: fn(&mut Self::Class);
 }
 
 /// Internal trait used to automatically fill in a class struct.
rust/qemu-api/tests/tests.rs +3 -0
index 03569e4a44c..9546e9d7963 100644
@@ -60,6 +60,7 @@ unsafe impl ObjectType for DummyState {
 impl ObjectImpl for DummyState {
     type ParentType = DeviceState;
     const ABSTRACT: bool = false;
+    const CLASS_INIT: fn(&mut DummyClass) = <Self as ClassInitImpl<DummyClass>>::class_init;
 }
 
 impl ResettablePhasesImpl for DummyState {}
@@ -102,6 +103,8 @@ unsafe impl ObjectType for DummyChildState {
 impl ObjectImpl for DummyChildState {
     type ParentType = DummyState;
     const ABSTRACT: bool = false;
+    const CLASS_INIT: fn(&mut DummyChildClass) =
+        <Self as ClassInitImpl<DummyChildClass>>::class_init;
 }
 
 impl ResettablePhasesImpl for DummyChildState {}
Signature · 1 line
2.48.1
Reviewed-by on v1 3/15
#6 lore raw

Re: [PATCH 03/15] rust: qom: add ObjectImpl::CLASS_INIT

Quoted 19 lines · Paolo Bonzini

Date: Fri, 21 Feb 2025 18:03:30 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 03/15] rust: qom: add ObjectImpl::CLASS_INIT
X-Mailer: git-send-email 2.48.1

As shown in the PL011 device, the orphan rules required a manual implementation of ClassInitImpl for anything not in the qemu_api crate; this gets in the way of moving system emulation-specific code (including DeviceClass, which as a blanket ClassInitImpl<DeviceClass> implementation) into its own crate.

Make ClassInitImpl optional, at the cost of having to specify the CLASS_INIT member by hand in every implementation of ObjectImpl. The next commits will get rid of it, replacing all the "impl<T> ClassInitImpl<Class> for T" blocks with a generic class_init<T> method on Class.

Right now the definition is always the same, but do not provide a default as that will not be true once ClassInitImpl goes away.

Quoted 7 lines
---
 rust/hw/char/pl011/src/device.rs |  3 +++
 rust/hw/timer/hpet/src/hpet.rs   |  3 ++-
 rust/qemu-api/src/qom.rs         | 14 +++++++++++---
 rust/qemu-api/tests/tests.rs     |  3 +++
 4 files changed, 19 insertions(+), 4 deletions(-)> 
#7 lore raw

PATCH 4/15 rust: pl011, qemu_api tests: do not use ClassInitImpl

In reply to Paolo Bonzini

Outside the qemu_api crate, orphan rules make the usage of ClassInitImpl unwieldy. Now that it is optional, do not use it.

For PL011Class, this makes it easier to provide a PL011Impl trait similar to the ones in the qemu_api crate. The device id consts are moved there.

---
 rust/hw/char/pl011/src/device.rs | 38 ++++++++++++++++----------------
 rust/qemu-api/tests/tests.rs     | 33 ++++++++++-----------------
 2 files changed, 31 insertions(+), 40 deletions(-)
rust/hw/char/pl011/src/device.rs +19 -19
index a6da9db0bb0..fc1c8ec8d6a 100644
@@ -50,11 +50,6 @@ fn index(&self, idx: hwaddr) -> &Self::Output {
     }
 }
 
-impl DeviceId {
-    const ARM: Self = Self(&[0x11, 0x10, 0x14, 0x00, 0x0d, 0xf0, 0x05, 0xb1]);
-    const LUMINARY: Self = Self(&[0x11, 0x00, 0x18, 0x01, 0x0d, 0xf0, 0x05, 0xb1]);
-}
-
 // FIFOs use 32-bit indices instead of usize, for compatibility with
 // the migration stream produced by the C version of this device.
 #[repr(transparent)]
@@ -143,16 +138,24 @@ pub struct PL011Class {
     device_id: DeviceId,
 }
 
+trait PL011Impl: SysBusDeviceImpl + IsA<PL011State> {
+    const DEVICE_ID: DeviceId;
+}
+
+impl PL011Class {
+    fn class_init<T: PL011Impl>(&mut self) {
+        self.device_id = T::DEVICE_ID;
+        <T as ClassInitImpl<SysBusDeviceClass>>::class_init(&mut self.parent_class);
+    }
+}
+
 unsafe impl ObjectType for PL011State {
     type Class = PL011Class;
     const TYPE_NAME: &'static CStr = crate::TYPE_PL011;
 }
 
-impl ClassInitImpl<PL011Class> for PL011State {
-    fn class_init(klass: &mut PL011Class) {
-        klass.device_id = DeviceId::ARM;
-        <Self as ClassInitImpl<SysBusDeviceClass>>::class_init(&mut klass.parent_class);
-    }
+impl PL011Impl for PL011State {
+    const DEVICE_ID: DeviceId = DeviceId(&[0x11, 0x10, 0x14, 0x00, 0x0d, 0xf0, 0x05, 0xb1]);
 }
 
 impl ObjectImpl for PL011State {
@@ -160,7 +163,7 @@ impl ObjectImpl for PL011State {
 
     const INSTANCE_INIT: Option<unsafe fn(&mut Self)> = Some(Self::init);
     const INSTANCE_POST_INIT: Option<fn(&Self)> = Some(Self::post_init);
-    const CLASS_INIT: fn(&mut Self::Class) = <Self as ClassInitImpl<Self::Class>>::class_init;
+    const CLASS_INIT: fn(&mut Self::Class) = Self::Class::class_init::<Self>;
 }
 
 impl DeviceImpl for PL011State {
@@ -729,13 +732,6 @@ pub struct PL011Luminary {
     parent_obj: ParentField<PL011State>,
 }
 
-impl ClassInitImpl<PL011Class> for PL011Luminary {
-    fn class_init(klass: &mut PL011Class) {
-        klass.device_id = DeviceId::LUMINARY;
-        <Self as ClassInitImpl<SysBusDeviceClass>>::class_init(&mut klass.parent_class);
-    }
-}
-
 qom_isa!(PL011Luminary : PL011State, SysBusDevice, DeviceState, Object);
 
 unsafe impl ObjectType for PL011Luminary {
@@ -746,7 +742,11 @@ unsafe impl ObjectType for PL011Luminary {
 impl ObjectImpl for PL011Luminary {
     type ParentType = PL011State;
 
-    const CLASS_INIT: fn(&mut Self::Class) = <Self as ClassInitImpl<Self::Class>>::class_init;
+    const CLASS_INIT: fn(&mut Self::Class) = Self::Class::class_init::<Self>;
+}
+
+impl PL011Impl for PL011Luminary {
+    const DEVICE_ID: DeviceId = DeviceId(&[0x11, 0x00, 0x18, 0x01, 0x0d, 0xf0, 0x05, 0xb1]);
 }
 
 impl DeviceImpl for PL011Luminary {}
rust/qemu-api/tests/tests.rs +12 -21
index 9546e9d7963..93c5637bbc3 100644
@@ -13,7 +13,7 @@
     cell::{self, BqlCell},
     declare_properties, define_property,
     prelude::*,
-    qdev::{DeviceClass, DeviceImpl, DeviceState, Property, ResettablePhasesImpl},
+    qdev::{DeviceImpl, DeviceState, Property, ResettablePhasesImpl},
     qom::{ClassInitImpl, ObjectImpl, ParentField},
     sysbus::SysBusDevice,
     vmstate::VMStateDescription,
@@ -41,6 +41,12 @@ pub struct DummyClass {
     parent_class: <DeviceState as ObjectType>::Class,
 }
 
+impl DummyClass {
+    pub fn class_init<T: DeviceImpl>(self: &mut DummyClass) {
+        <T as ClassInitImpl<DeviceClass>>::class_init(&mut self.parent_class);
+    }
+}
+
 declare_properties! {
     DUMMY_PROPERTIES,
         define_property!(
@@ -60,7 +66,7 @@ unsafe impl ObjectType for DummyState {
 impl ObjectImpl for DummyState {
     type ParentType = DeviceState;
     const ABSTRACT: bool = false;
-    const CLASS_INIT: fn(&mut DummyClass) = <Self as ClassInitImpl<DummyClass>>::class_init;
+    const CLASS_INIT: fn(&mut DummyClass) = DummyClass::class_init::<Self>;
 }
 
 impl ResettablePhasesImpl for DummyState {}
@@ -74,14 +80,6 @@ fn vmsd() -> Option<&'static VMStateDescription> {
     }
 }
 
-// `impl<T> ClassInitImpl<DummyClass> for T` doesn't work since it violates
-// orphan rule.
-impl ClassInitImpl<DummyClass> for DummyState {
-    fn class_init(klass: &mut DummyClass) {
-        <Self as ClassInitImpl<DeviceClass>>::class_init(&mut klass.parent_class);
-    }
-}
-
 #[derive(qemu_api_macros::offsets)]
 #[repr(C)]
 #[derive(qemu_api_macros::Object)]
@@ -103,22 +101,15 @@ unsafe impl ObjectType for DummyChildState {
 impl ObjectImpl for DummyChildState {
     type ParentType = DummyState;
     const ABSTRACT: bool = false;
-    const CLASS_INIT: fn(&mut DummyChildClass) =
-        <Self as ClassInitImpl<DummyChildClass>>::class_init;
+    const CLASS_INIT: fn(&mut DummyChildClass) = DummyChildClass::class_init::<Self>;
 }
 
 impl ResettablePhasesImpl for DummyChildState {}
 impl DeviceImpl for DummyChildState {}
 
-impl ClassInitImpl<DummyClass> for DummyChildState {
-    fn class_init(klass: &mut DummyClass) {
-        <Self as ClassInitImpl<DeviceClass>>::class_init(&mut klass.parent_class);
-    }
-}
-
-impl ClassInitImpl<DummyChildClass> for DummyChildState {
-    fn class_init(klass: &mut DummyChildClass) {
-        <Self as ClassInitImpl<DummyClass>>::class_init(&mut klass.parent_class);
+impl DummyChildClass {
+    pub fn class_init<T: DeviceImpl>(self: &mut DummyChildClass) {
+        self.parent_class.class_init::<T>();
     }
 }
 
Signature · 1 line
2.48.1
Reviewed-by on v1 4/15
#8 lore raw

Re: [PATCH 04/15] rust: pl011, qemu_api tests: do not use ClassInitImpl

Quoted 8 lines · Paolo Bonzini

Date: Fri, 21 Feb 2025 18:03:31 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 04/15] rust: pl011, qemu_api tests: do not use ClassInitImpl
X-Mailer: git-send-email 2.48.1

Outside the qemu_api crate, orphan rules make the usage of ClassInitImpl unwieldy. Now that it is optional, do not use it.

Quoted 8 lines

For PL011Class, this makes it easier to provide a PL011Impl trait similar to the ones in the qemu_api crate. The device id consts are moved there.

---
 rust/hw/char/pl011/src/device.rs | 38 ++++++++++++++++----------------
 rust/qemu-api/tests/tests.rs     | 33 ++++++++++-----------------
 2 files changed, 31 insertions(+), 40 deletions(-)>
#9 lore raw

PATCH 5/15 rust: qom: get rid of ClassInitImpl

In reply to Paolo Bonzini

Complete the conversion from the ClassInitImpl trait to class_init() methods. This will provide more freedom to split the qemu_api crate in separate parts.

---
 rust/hw/char/pl011/src/device.rs |   6 +-
 rust/hw/timer/hpet/src/hpet.rs   |   4 +-
 rust/qemu-api/src/qdev.rs        |  38 ++++---
 rust/qemu-api/src/qom.rs         | 164 +++++++++++++------------------
 rust/qemu-api/src/sysbus.rs      |  15 ++-
 rust/qemu-api/tests/tests.rs     |   4 +-
 6 files changed, 101 insertions(+), 130 deletions(-)
rust/hw/char/pl011/src/device.rs +3 -3
index fc1c8ec8d6a..6896b1026f6 100644
@@ -19,8 +19,8 @@
     memory::{hwaddr, MemoryRegion, MemoryRegionOps, MemoryRegionOpsBuilder},
     prelude::*,
     qdev::{Clock, ClockEvent, DeviceImpl, DeviceState, Property, ResetType, ResettablePhasesImpl},
-    qom::{ClassInitImpl, ObjectImpl, Owned, ParentField},
-    sysbus::{SysBusDevice, SysBusDeviceClass, SysBusDeviceImpl},
+    qom::{ObjectImpl, Owned, ParentField},
+    sysbus::{SysBusDevice, SysBusDeviceImpl},
     vmstate::VMStateDescription,
 };
 
@@ -145,7 +145,7 @@ trait PL011Impl: SysBusDeviceImpl + IsA<PL011State> {
 impl PL011Class {
     fn class_init<T: PL011Impl>(&mut self) {
         self.device_id = T::DEVICE_ID;
-        <T as ClassInitImpl<SysBusDeviceClass>>::class_init(&mut self.parent_class);
+        self.parent_class.class_init::<T>();
     }
 }
 
rust/hw/timer/hpet/src/hpet.rs +2 -2
index e01b4b67064..be27eb0eff4 100644
@@ -21,7 +21,7 @@
     },
     prelude::*,
     qdev::{DeviceImpl, DeviceMethods, DeviceState, Property, ResetType, ResettablePhasesImpl},
-    qom::{ClassInitImpl, ObjectImpl, ObjectType, ParentField},
+    qom::{ObjectImpl, ObjectType, ParentField},
     qom_isa,
     sysbus::{SysBusDevice, SysBusDeviceImpl},
     timer::{Timer, CLOCK_VIRTUAL},
@@ -836,7 +836,7 @@ impl ObjectImpl for HPETState {
 
     const INSTANCE_INIT: Option<unsafe fn(&mut Self)> = Some(Self::init);
     const INSTANCE_POST_INIT: Option<fn(&Self)> = Some(Self::post_init);
-    const CLASS_INIT: fn(&mut Self::Class) = <Self as ClassInitImpl<Self::Class>>::class_init;
+    const CLASS_INIT: fn(&mut Self::Class) = Self::Class::class_init::<Self>;
 }
 
 // TODO: Make these properties user-configurable!
rust/qemu-api/src/qdev.rs +18 -20
index c4dd26b582c..c136457090c 100644
@@ -19,7 +19,7 @@
     chardev::Chardev,
     irq::InterruptSource,
     prelude::*,
-    qom::{ClassInitImpl, ObjectClass, ObjectImpl, Owned},
+    qom::{ObjectClass, ObjectImpl, Owned},
     vmstate::VMStateDescription,
 };
 
@@ -113,7 +113,7 @@ fn vmsd() -> Option<&'static VMStateDescription> {
 /// # Safety
 ///
 /// This function is only called through the QOM machinery and
-/// used by the `ClassInitImpl<DeviceClass>` trait.
+/// used by `DeviceClass::class_init`.
 /// We expect the FFI user of this function to pass a valid pointer that
 /// can be downcasted to type `T`. We also expect the device is
 /// readable/writeable from one thread at any time.
@@ -127,43 +127,41 @@ unsafe impl InterfaceType for ResettableClass {
         unsafe { CStr::from_bytes_with_nul_unchecked(bindings::TYPE_RESETTABLE_INTERFACE) };
 }
 
-impl<T> ClassInitImpl<ResettableClass> for T
-where
-    T: ResettablePhasesImpl,
-{
-    fn class_init(rc: &mut ResettableClass) {
+impl ResettableClass {
+    /// Fill in the virtual methods of `ResettableClass` based on the
+    /// definitions in the `ResettablePhasesImpl` trait.
+    pub fn class_init<T: ResettablePhasesImpl>(&mut self) {
         if <T as ResettablePhasesImpl>::ENTER.is_some() {
-            rc.phases.enter = Some(rust_resettable_enter_fn::<T>);
+            self.phases.enter = Some(rust_resettable_enter_fn::<T>);
         }
         if <T as ResettablePhasesImpl>::HOLD.is_some() {
-            rc.phases.hold = Some(rust_resettable_hold_fn::<T>);
+            self.phases.hold = Some(rust_resettable_hold_fn::<T>);
         }
         if <T as ResettablePhasesImpl>::EXIT.is_some() {
-            rc.phases.exit = Some(rust_resettable_exit_fn::<T>);
+            self.phases.exit = Some(rust_resettable_exit_fn::<T>);
         }
     }
 }
 
-impl<T> ClassInitImpl<DeviceClass> for T
-where
-    T: ClassInitImpl<ObjectClass> + ClassInitImpl<ResettableClass> + DeviceImpl,
-{
-    fn class_init(dc: &mut DeviceClass) {
+impl DeviceClass {
+    /// Fill in the virtual methods of `DeviceClass` based on the definitions in
+    /// the `DeviceImpl` trait.
+    pub fn class_init<T: DeviceImpl>(&mut self) {
         if <T as DeviceImpl>::REALIZE.is_some() {
-            dc.realize = Some(rust_realize_fn::<T>);
+            self.realize = Some(rust_realize_fn::<T>);
         }
         if let Some(vmsd) = <T as DeviceImpl>::vmsd() {
-            dc.vmsd = vmsd;
+            self.vmsd = vmsd;
         }
         let prop = <T as DeviceImpl>::properties();
         if !prop.is_empty() {
             unsafe {
-                bindings::device_class_set_props_n(dc, prop.as_ptr(), prop.len());
+                bindings::device_class_set_props_n(self, prop.as_ptr(), prop.len());
             }
         }
 
-        ResettableClass::interface_init::<T, DeviceState>(dc);
-        <T as ClassInitImpl<ObjectClass>>::class_init(&mut dc.parent_class);
+        ResettableClass::cast::<DeviceState>(self).class_init::<T>();
+        self.parent_class.class_init::<T>();
     }
 }
 
rust/qemu-api/src/qom.rs +69 -95

213 lines not on this page · raw message

rust/qemu-api/src/sysbus.rs +7 -8
index fee2e3d478f..04821a2b9b3 100644
@@ -14,8 +14,8 @@
     irq::{IRQState, InterruptSource},
     memory::MemoryRegion,
     prelude::*,
-    qdev::{DeviceClass, DeviceImpl, DeviceState},
-    qom::{ClassInitImpl, Owned},
+    qdev::{DeviceImpl, DeviceState},
+    qom::Owned,
 };
 
 unsafe impl ObjectType for SysBusDevice {
@@ -28,12 +28,11 @@ unsafe impl ObjectType for SysBusDevice {
 // TODO: add virtual methods
 pub trait SysBusDeviceImpl: DeviceImpl + IsA<SysBusDevice> {}
 
-impl<T> ClassInitImpl<SysBusDeviceClass> for T
-where
-    T: SysBusDeviceImpl + ClassInitImpl<DeviceClass>,
-{
-    fn class_init(sdc: &mut SysBusDeviceClass) {
-        <T as ClassInitImpl<DeviceClass>>::class_init(&mut sdc.parent_class);
+impl SysBusDeviceClass {
+    /// Fill in the virtual methods of `SysBusDeviceClass` based on the
+    /// definitions in the `SysBusDeviceImpl` trait.
+    pub fn class_init<T: SysBusDeviceImpl>(self: &mut SysBusDeviceClass) {
+        self.parent_class.class_init::<T>();
     }
 }
 
rust/qemu-api/tests/tests.rs +2 -2
index 93c5637bbc3..e3985782a38 100644
@@ -14,7 +14,7 @@
     declare_properties, define_property,
     prelude::*,
     qdev::{DeviceImpl, DeviceState, Property, ResettablePhasesImpl},
-    qom::{ClassInitImpl, ObjectImpl, ParentField},
+    qom::{ObjectImpl, ParentField},
     sysbus::SysBusDevice,
     vmstate::VMStateDescription,
     zeroable::Zeroable,
@@ -43,7 +43,7 @@ pub struct DummyClass {
 
 impl DummyClass {
     pub fn class_init<T: DeviceImpl>(self: &mut DummyClass) {
-        <T as ClassInitImpl<DeviceClass>>::class_init(&mut self.parent_class);
+        self.parent_class.class_init::<T>();
     }
 }
 
Signature · 1 line
2.48.1
Reviewed-by on v1 5/15
#10 lore raw

Re: [PATCH 05/15] rust: qom: get rid of ClassInitImpl

Quoted 9 lines · Paolo Bonzini

Date: Fri, 21 Feb 2025 18:03:32 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 05/15] rust: qom: get rid of ClassInitImpl
X-Mailer: git-send-email 2.48.1

Complete the conversion from the ClassInitImpl trait to class_init() methods. This will provide more freedom to split the qemu_api crate in separate parts.

Quoted 8 lines
---
 rust/hw/char/pl011/src/device.rs |   6 +-
 rust/hw/timer/hpet/src/hpet.rs   |   4 +-
 rust/qemu-api/src/qdev.rs        |  38 ++++---
 rust/qemu-api/src/qom.rs         | 164 +++++++++++++------------------
 rust/qemu-api/src/sysbus.rs      |  15 ++-
 rust/qemu-api/tests/tests.rs     |   4 +-
 6 files changed, 101 insertions(+), 130 deletions(-)
#11 lore raw

PATCH 6/15 rust: cell: add wrapper for FFI types

In reply to Paolo Bonzini

Inspired by the same-named type in Linux. This type provides the compiler with a correct view of what goes on with FFI types. In addition, it separates the glue code from the bindgen-generated code, allowing traits such as Send, Sync or Zeroable to be specified independently for C and Rust structs.

---
 docs/devel/rust.rst       |  34 +++++--
 rust/qemu-api/src/cell.rs | 191 ++++++++++++++++++++++++++++++++++++--
 2 files changed, 210 insertions(+), 15 deletions(-)
docs/devel/rust.rst +26 -8
index e3f9e16aacb..9a621648e72 100644
@@ -295,15 +295,33 @@ of ``&mut self``; access to internal fields must use *interior mutability*
 to go from a shared reference to a ``&mut``.
 
 Whenever C code provides you with an opaque ``void *``, avoid converting it
-to a Rust mutable reference, and use a shared reference instead.  Rust code
-will then have to use QEMU's ``BqlRefCell`` and ``BqlCell`` type, which
-enforce that locking rules for the "Big QEMU Lock" are respected.  These cell
-types are also known to the ``vmstate`` crate, which is able to "look inside"
-them when building an in-memory representation of a ``struct``'s layout.
-Note that the same is not true of a ``RefCell`` or ``Mutex``.
+to a Rust mutable reference, and use a shared reference instead.  The
+``qemu_api::cell`` module provides wrappers that can be used to tell the
+Rust compiler about interior mutability, and optionally to enforce locking
+rules for the "Big QEMU Lock".  In the future, similar cell types might
+also be provided for ``AioContext``-based locking as well.
 
-In the future, similar cell types might also be provided for ``AioContext``-based
-locking as well.
+In particular, device code will usually rely on the ``BqlRefCell`` and
+``BqlCell`` type to ensure that data is accessed correctly under the
+"Big QEMU Lock".  These cell types are also known to the ``vmstate``
+crate, which is able to "look inside" them when building an in-memory
+representation of a ``struct``'s layout.  Note that the same is not true
+of a ``RefCell`` or ``Mutex``.
+
+Bindings code instead will usually use the ``Opaque`` type, which hides
+the contents of the underlying struct and can be easily converted to
+a raw pointer, for use in calls to C functions.  It can be used for
+example as follows::
+
+    #[repr(transparent)]
+    #[derive(Debug)]
+    pub struct Object(Opaque<bindings::Object>);
+
+The bindings will then manually check for the big QEMU lock with
+assertions, which allows the wrapper to be declared thread-safe::
+
+    unsafe impl Send for Object {}
+    unsafe impl Sync for Object {}
 
 Writing bindings to C code
 ''''''''''''''''''''''''''
rust/qemu-api/src/cell.rs +184 -7

229 lines not on this page · raw message

Signature · 1 line
2.48.1
Reviewed-by on v1 6/15
#12 lore raw

Re: [PATCH 06/15] rust: cell: add wrapper for FFI types

rust/qemu-api/src/cell.rs fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { · line 975

Quoted 11 lines
rust/qemu-api/src/cell.rs +11 -0
+    /// Creates a new opaque object with zeroed contents.
+    ///
+    /// # Safety
+    ///
+    /// Ultimately the pointer to the returned value will be dereferenced
+    /// in another unsafe block, for example when passing it to a C function.
+    /// However, this function is unsafe to "force" documenting whether a
+    /// zero value is safe.
+    pub const unsafe fn zeroed() -> Self {
+        Self {
+            value: UnsafeCell::new(MaybeUninit::uninit()),

typo? MaybeUninit::zeroed()

rust/qemu-api/src/cell.rs fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { · line 980

Quoted 5 lines
rust/qemu-api/src/cell.rs +5 -0
+            _pin: PhantomPinned,
+        }
+    }
+
+    /// Returns a raw pointer to the opaque data.

Maybe "a raw mutable pointer".

rust/qemu-api/src/cell.rs fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { · line 990

Quoted 10 lines
rust/qemu-api/src/cell.rs +10 -0
+    pub const fn as_mut_ptr(&self) -> *mut T {
+        UnsafeCell::get(&self.value).cast()
+    }
+
+    /// Returns a raw pointer to the opaque data.
+    pub const fn as_ptr(&self) -> *const T {
+        self.as_mut_ptr() as *const _
+    }
+
+    /// Returns a raw pointer to the opaque data.

What about "Returns a raw c_void type pointer"?

(Because the descriptions of these three helpers are exactly the same! We can make them different.)
zeroed

rust/qemu-api/src/cell.rs fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { · line 994

Quoted 4 lines
rust/qemu-api/src/cell.rs +4 -0
+    pub const fn as_void_ptr(&self) -> *mut std::ffi::c_void {
+        UnsafeCell::get(&self.value).cast()
+    }
+}

The whole idea is great! With the nit of zeroed fixed,

#13 lore raw

PATCH 7/15 rust: qemu_api_macros: add Wrapper derive macro

In reply to Paolo Bonzini

Add a derive macro that makes it easy to peel off all the layers of specialness (UnsafeCell, MaybeUninit, etc.) and just get a pointer to the wrapped type; and likewise add them back starting from a *mut.

---
 docs/devel/rust.rst             |  8 ++--
 rust/qemu-api-macros/src/lib.rs | 82 ++++++++++++++++++++++++++++++++-
 rust/qemu-api/meson.build       |  7 +--
 rust/qemu-api/src/cell.rs       | 31 +++++++++++++
 4 files changed, 119 insertions(+), 9 deletions(-)
docs/devel/rust.rst +5 -3
index 9a621648e72..db2b427ebd2 100644
@@ -314,11 +314,13 @@ a raw pointer, for use in calls to C functions.  It can be used for
 example as follows::
 
     #[repr(transparent)]
-    #[derive(Debug)]
+    #[derive(Debug, qemu_api_macros::Wrapper)]
     pub struct Object(Opaque<bindings::Object>);
 
-The bindings will then manually check for the big QEMU lock with
-assertions, which allows the wrapper to be declared thread-safe::
+where the special ``derive`` macro provides useful methods such as
+``from_raw``, ``as_ptr`` and ``as_mut_ptr``.  The bindings will then
+manually check for the big QEMU lock with assertions, which allows
+the wrapper to be declared thread-safe::
 
     unsafe impl Send for Object {}
     unsafe impl Sync for Object {}
rust/qemu-api-macros/src/lib.rs +81 -1

106 lines not on this page · raw message

rust/qemu-api/meson.build +2 -5
index bcf1cf780f3..6e52c4bad74 100644
@@ -42,16 +42,13 @@ _qemu_api_rs = static_library(
   override_options: ['rust_std=2021', 'build.rust_std=2021'],
   rust_abi: 'rust',
   rust_args: _qemu_api_cfg,
-  dependencies: libc_dep,
+  dependencies: [libc_dep, qemu_api_macros],
 )
 
 rust.test('rust-qemu-api-tests', _qemu_api_rs,
           suite: ['unit', 'rust'])
 
-qemu_api = declare_dependency(
-  link_with: _qemu_api_rs,
-  dependencies: qemu_api_macros,
-)
+qemu_api = declare_dependency(link_with: _qemu_api_rs)
 
 # Rust executables do not support objects, so add an intermediate step.
 rust_qemu_api_objs = static_library(
rust/qemu-api/src/cell.rs +31 -0
index 84b9eb07467..c39b9616969 100644
@@ -1017,3 +1017,34 @@ pub fn new() -> Self {
         Self::default()
     }
 }
+
+/// Annotates [`Self`] as a transparent wrapper for another type.
+///
+/// Usually defined via the [`qemu_api_macros::Wrapper`] derive macro.
+///
+/// # Examples
+///
+/// ```
+/// # use std::mem::ManuallyDrop;
+/// # use qemu_api::cell::Wrapper;
+/// #[repr(transparent)]
+/// pub struct Example {
+///     inner: ManuallyDrop<String>,
+/// }
+///
+/// unsafe impl Wrapper for Example {
+///     type Wrapped = String;
+/// }
+/// ```
+///
+/// # Safety
+///
+/// `Self` must be a `#[repr(transparent)]` wrapper for the `Wrapped` type,
+/// whether directly or indirectly.
+pub unsafe trait Wrapper {
+    type Wrapped;
+}
+
+unsafe impl<T> Wrapper for Opaque<T> {
+    type Wrapped = T;
+}
Signature · 1 line
2.48.1
Reviewed-by on v1 7/15
#14 lore raw

Re: [PATCH 07/15] rust: qemu_api_macros: add Wrapper derive macro

Quoted 16 lines
rust/qemu-api-macros/src/lib.rs +16 -0
+fn derive_opaque_or_error(input: DeriveInput) -> Result<proc_macro2::TokenStream, MacroError> {
+    is_transparent_repr(&input, "#[derive(Wrapper)]")?;
+
+    let name = &input.ident;
+    let field = &get_unnamed_field(&input, "#[derive(Wrapper)]")?;
+    let typ = &field.ty;
+
+    // TODO: how to add "::qemu_api"?  For now, this is only used in the
+    // qemu_api crate so it's not a problem.
+    Ok(quote! {
+        unsafe impl crate::cell::Wrapper for #name {
+            type Wrapped = <#typ as crate::cell::Wrapper>::Wrapped;
+        }
+        impl #name {
+            pub unsafe fn from_raw<'a>(ptr: *mut <Self as crate::cell::Wrapper>::Wrapped) -> &'a Self {
+                let ptr = ::std::ptr::NonNull::new(ptr).unwrap().cast::<Self>();

rust/qemu-api-macros/src/lib.rs pub fn derive_object(input: TokenStream) -> TokenStream { · line 142

Quoted 10 lines
rust/qemu-api-macros/src/lib.rs +10 -0
+                unsafe { ptr.as_ref() }
+            }
+
+            pub const fn as_mut_ptr(&self) -> *mut <Self as crate::cell::Wrapper>::Wrapped {
+                self.0.as_mut_ptr()
+            }
+
+            pub const fn as_ptr(&self) -> *const <Self as crate::cell::Wrapper>::Wrapped {
+                self.0.as_ptr()
+            }

What about also adding as_void_ptr? Then DeviceState can benefit from this in qdev_init_clock_in.

rust/qemu-api-macros/src/lib.rs pub fn derive_object(input: TokenStream) -> TokenStream { · line 146

Quoted 4 lines
rust/qemu-api-macros/src/lib.rs +4 -0
+        }
+    })
+}
+

Others are fine for me. Nice improvement!

#15 lore raw

PATCH 8/15 rust: timer: wrap QEMUTimer with Opaque<>

In reply to Paolo Bonzini
---
 meson.build                |  7 -------
 rust/qemu-api/src/timer.rs | 24 +++++++++++++++++-------
 2 files changed, 17 insertions(+), 14 deletions(-)
meson.build +0 -7
index 8ed10b6624e..16c76c493f3 100644
@@ -4087,13 +4087,6 @@ if have_rust
   foreach enum : c_bitfields
     bindgen_args += ['--bitfield-enum', enum]
   endforeach
-  c_nocopy = [
-    'QEMUTimer',
-  ]
-  # Used to customize Drop trait
-  foreach struct : c_nocopy
-    bindgen_args += ['--no-copy', struct]
-  endforeach
 
   # TODO: Remove this comment when the clang/libclang mismatch issue is solved.
   #
rust/qemu-api/src/timer.rs +17 -7
index a593538917a..0305a0385ad 100644
@@ -7,10 +7,23 @@
 use crate::{
     bindings::{self, qemu_clock_get_ns, timer_del, timer_init_full, timer_mod, QEMUClockType},
     callbacks::FnCall,
+    cell::Opaque,
 };
 
-pub type Timer = bindings::QEMUTimer;
-pub type TimerListGroup = bindings::QEMUTimerListGroup;
+/// A safe wrapper around [`bindings::QEMUTimer`].
+#[repr(transparent)]
+#[derive(Debug, Default, qemu_api_macros::Wrapper)]
+pub struct Timer(Opaque<bindings::QEMUTimer>);
+
+unsafe impl Send for Timer {}
+unsafe impl Sync for Timer {}
+
+#[repr(transparent)]
+#[derive(qemu_api_macros::Wrapper)]
+pub struct TimerListGroup(Opaque<bindings::QEMUTimerListGroup>);
+
+unsafe impl Send for TimerListGroup {}
+unsafe impl Sync for TimerListGroup {}
 
 impl Timer {
     pub const MS: u32 = bindings::SCALE_MS;
@@ -21,10 +34,6 @@ pub fn new() -> Self {
         Default::default()
     }
 
-    const fn as_mut_ptr(&self) -> *mut Self {
-        self as *const Timer as *mut _
-    }
-
     pub fn init_full<'timer, 'opaque: 'timer, T, F>(
         &'timer mut self,
         timer_list_group: Option<&TimerListGroup>,
@@ -51,7 +60,7 @@ pub fn init_full<'timer, 'opaque: 'timer, T, F>(
         // SAFETY: the opaque outlives the timer
         unsafe {
             timer_init_full(
-                self,
+                self.as_mut_ptr(),
                 if let Some(g) = timer_list_group {
                     g as *const TimerListGroup as *mut _
                 } else {
@@ -75,6 +84,7 @@ pub fn delete(&self) {
     }
 }
 
+// FIXME: use something like PinnedDrop from the pinned_init crate
 impl Drop for Timer {
     fn drop(&mut self) {
         self.delete()
Signature · 1 line
2.48.1
Reviewed-by on v1 8/15
#16 lore raw

Re: [PATCH 08/15] rust: timer: wrap QEMUTimer with Opaque<>

Quoted 10 lines · Paolo Bonzini

Date: Fri, 21 Feb 2025 18:03:35 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 08/15] rust: timer: wrap QEMUTimer with Opaque<>
X-Mailer: git-send-email 2.48.1

---
 meson.build                |  7 -------
 rust/qemu-api/src/timer.rs | 24 +++++++++++++++++-------
 2 files changed, 17 insertions(+), 14 deletions(-)

Thanks!

#17 lore raw

PATCH 9/15 rust: irq: wrap IRQState with Opaque<>

In reply to Paolo Bonzini
---
 rust/qemu-api/src/irq.rs    | 15 ++++++++++-----
 rust/qemu-api/src/sysbus.rs |  1 +
 2 files changed, 11 insertions(+), 5 deletions(-)
rust/qemu-api/src/irq.rs +10 -5
index d1c9dc96eff..aec2825b2f9 100644
@@ -9,10 +9,16 @@
 
 use crate::{
     bindings::{self, qemu_set_irq},
+    cell::Opaque,
     prelude::*,
     qom::ObjectClass,
 };
 
+/// An opaque wrapper around [`bindings::IRQState`].
+#[repr(transparent)]
+#[derive(Debug, qemu_api_macros::Wrapper)]
+pub struct IRQState(Opaque<bindings::IRQState>);
+
 /// Interrupt sources are used by devices to pass changes to a value (typically
 /// a boolean).  The interrupt sink is usually an interrupt controller or
 /// GPIO controller.
@@ -22,8 +28,7 @@
 /// method sends a `true` value to the sink.  If the guest has to see a
 /// different polarity, that change is performed by the board between the
 /// device and the interrupt controller.
-pub type IRQState = bindings::IRQState;
-
+///
 /// Interrupts are implemented as a pointer to the interrupt "sink", which has
 /// type [`IRQState`].  A device exposes its source as a QOM link property using
 /// a function such as [`SysBusDeviceMethods::init_irq`], and
@@ -41,7 +46,7 @@ pub struct InterruptSource<T = bool>
 where
     c_int: From<T>,
 {
-    cell: BqlCell<*mut IRQState>,
+    cell: BqlCell<*mut bindings::IRQState>,
     _marker: PhantomData<T>,
 }
 
@@ -80,11 +85,11 @@ pub fn set(&self, level: T) {
         }
     }
 
-    pub(crate) const fn as_ptr(&self) -> *mut *mut IRQState {
+    pub(crate) const fn as_ptr(&self) -> *mut *mut bindings::IRQState {
         self.cell.as_ptr()
     }
 
-    pub(crate) const fn slice_as_ptr(slice: &[Self]) -> *mut *mut IRQState {
+    pub(crate) const fn slice_as_ptr(slice: &[Self]) -> *mut *mut bindings::IRQState {
         assert!(!slice.is_empty());
         slice[0].as_ptr()
     }
rust/qemu-api/src/sysbus.rs +1 -0
index 04821a2b9b3..48803a655f9 100644
@@ -79,6 +79,7 @@ fn mmio_map(&self, id: u32, addr: u64) {
     fn connect_irq(&self, id: u32, irq: &Owned<IRQState>) {
         assert!(bql_locked());
         let id: i32 = id.try_into().unwrap();
+        let irq: &IRQState = irq;
         unsafe {
             bindings::sysbus_connect_irq(self.as_mut_ptr(), id, irq.as_mut_ptr());
         }
Signature · 1 line
2.48.1
#18 lore raw

Re: [PATCH 09/15] rust: irq: wrap IRQState with Opaque<>

Quoted 19 lines
rust/qemu-api/src/irq.rs +6 -2
+/// An opaque wrapper around [`bindings::IRQState`].
+#[repr(transparent)]
+#[derive(Debug, qemu_api_macros::Wrapper)]
+pub struct IRQState(Opaque<bindings::IRQState>);
+
 /// Interrupt sources are used by devices to pass changes to a value (typically
 /// a boolean).  The interrupt sink is usually an interrupt controller or
 /// GPIO controller.
@@ -22,8 +28,7 @@
 /// method sends a `true` value to the sink.  If the guest has to see a
 /// different polarity, that change is performed by the board between the
 /// device and the interrupt controller.
-pub type IRQState = bindings::IRQState;
-
+///
 /// Interrupts are implemented as a pointer to the interrupt "sink", which has
 /// type [`IRQState`].  A device exposes its source as a QOM link property using
 /// a function such as [`SysBusDeviceMethods::init_irq`], and

rust/qemu-api/src/irq.rs pub struct InterruptSource<T = bool> · line 49

Quoted 5 lines
rust/qemu-api/src/irq.rs +1 -1
@@ -41,7 +46,7 @@ pub struct InterruptSource<T = bool>
 where
     c_int: From<T>,
 {
-    cell: BqlCell<*mut IRQState>,
+    cell: BqlCell<*mut bindings::IRQState>,

Once we've already wrapper IRQState in Opaque<>, should we still use bindings::IRQState?

Although InterruptSource just stores a pointer. However, I think we can use wrapped IRQState here instead of the native binding type, since this item is also crossing the FFI boundary. What do you think?

Quoted 3 lines
rust/qemu-api/src/irq.rs +0 -0
     _marker: PhantomData<T>,
 }
 
#19 lore raw

Re: [PATCH 09/15] rust: irq: wrap IRQState with Opaque<>

Quoted 28 lines · Zhao Liu
Quoted 19 lines
rust/qemu-api/src/irq.rs +6 -2
+/// An opaque wrapper around [`bindings::IRQState`].
+#[repr(transparent)]
+#[derive(Debug, qemu_api_macros::Wrapper)]
+pub struct IRQState(Opaque<bindings::IRQState>);
+
  /// Interrupt sources are used by devices to pass changes to a value (typically
  /// a boolean).  The interrupt sink is usually an interrupt controller or
  /// GPIO controller.
@@ -22,8 +28,7 @@
  /// method sends a `true` value to the sink.  If the guest has to see a
  /// different polarity, that change is performed by the board between the
  /// device and the interrupt controller.
-pub type IRQState = bindings::IRQState;
-
+///
  /// Interrupts are implemented as a pointer to the interrupt "sink", which has
  /// type [`IRQState`].  A device exposes its source as a QOM link property using
  /// a function such as [`SysBusDeviceMethods::init_irq`], and

rust/qemu-api/src/irq.rs pub struct InterruptSource<T = bool> · line 49

Quoted 5 lines
rust/qemu-api/src/irq.rs +1 -1
@@ -41,7 +46,7 @@ pub struct InterruptSource<T = bool>
  where
      c_int: From<T>,
  {
-    cell: BqlCell<*mut IRQState>,
+    cell: BqlCell<*mut bindings::IRQState>,

Once we've already wrapper IRQState in Opaque<>, should we still use bindings::IRQState?

Quoted 3 lines

Although InterruptSource just stores a pointer. However, I think we can use wrapped IRQState here instead of the native binding type, since this item is also crossing the FFI boundary. What do you think?

Using the wrapped IRQState would be a bit more code because you have to cast the pointer all the time when calling C code. As far as correctness is concerned, it does not really matter because as you said it only stores a pointer.

However, if needed, InterruptSource could have a function that converts from IRQState to Option<&Opaque<irq::IRQState>>. Since the accessor is needed anyway, that would be a good place to put the conversion.

Paolo

#20 lore raw

Re: [PATCH 09/15] rust: irq: wrap IRQState with Opaque<>

Quoted 33 lines · Paolo Bonzini

Date: Tue, 25 Feb 2025 09:28:52 +0100
From: Paolo Bonzini <[email protected]>
Subject: Re: [PATCH 09/15] rust: irq: wrap IRQState with Opaque<>

Quoted 28 lines · Zhao Liu
Quoted 19 lines
rust/qemu-api/src/irq.rs +6 -2
+/// An opaque wrapper around [`bindings::IRQState`].
+#[repr(transparent)]
+#[derive(Debug, qemu_api_macros::Wrapper)]
+pub struct IRQState(Opaque<bindings::IRQState>);
+
  /// Interrupt sources are used by devices to pass changes to a value (typically
  /// a boolean).  The interrupt sink is usually an interrupt controller or
  /// GPIO controller.
@@ -22,8 +28,7 @@
  /// method sends a `true` value to the sink.  If the guest has to see a
  /// different polarity, that change is performed by the board between the
  /// device and the interrupt controller.
-pub type IRQState = bindings::IRQState;
-
+///
  /// Interrupts are implemented as a pointer to the interrupt "sink", which has
  /// type [`IRQState`].  A device exposes its source as a QOM link property using
  /// a function such as [`SysBusDeviceMethods::init_irq`], and

rust/qemu-api/src/irq.rs pub struct InterruptSource<T = bool> · line 49

Quoted 5 lines
rust/qemu-api/src/irq.rs +1 -1
@@ -41,7 +46,7 @@ pub struct InterruptSource<T = bool>
  where
      c_int: From<T>,
  {
-    cell: BqlCell<*mut IRQState>,
+    cell: BqlCell<*mut bindings::IRQState>,

Once we've already wrapper IRQState in Opaque<>, should we still use bindings::IRQState?

Quoted 8 lines
Quoted 3 lines

Although InterruptSource just stores a pointer. However, I think we can use wrapped IRQState here instead of the native binding type, since this item is also crossing the FFI boundary. What do you think?

Using the wrapped IRQState would be a bit more code because you have to cast the pointer all the time when calling C code. As far as correctness is concerned, it does not really matter because as you said it only stores a pointer.

Yes, it makes sense. This conversion doesn't block the current patch. The correctness has been guaranteed.

Quoted 3 lines

However, if needed, InterruptSource could have a function that converts from IRQState to Option<&Opaque<irq::IRQState>>. Since the accessor is needed anyway, that would be a good place to put the conversion.

Then I understand we still need assert!(bql_locked()) in assessor as the doc said: "it is possible to assert in the code that the right lock is taken, to use it together with a custom lock guard type, or to let C code take the lock, as appropriate."

#21 lore raw

PATCH 10/15 rust: qom: wrap Object with Opaque<>

In reply to Paolo Bonzini
---
 rust/qemu-api/src/bindings.rs |  3 ---
 rust/qemu-api/src/memory.rs   |  2 +-
 rust/qemu-api/src/qdev.rs     |  6 +++---
 rust/qemu-api/src/qom.rs      | 35 ++++++++++++++++++++++-------------
 4 files changed, 26 insertions(+), 20 deletions(-)
rust/qemu-api/src/bindings.rs +0 -3
index d2868639ff6..be6dd68c09c 100644
@@ -46,9 +46,6 @@ unsafe impl Sync for MemoryRegion {}
 unsafe impl Send for ObjectClass {}
 unsafe impl Sync for ObjectClass {}
 
-unsafe impl Send for Object {}
-unsafe impl Sync for Object {}
-
 unsafe impl Send for SysBusDevice {}
 unsafe impl Sync for SysBusDevice {}
 
rust/qemu-api/src/memory.rs +1 -1
index 682951ab44e..713c494ca2e 100644
@@ -157,7 +157,7 @@ unsafe fn do_init_io(
             let cstr = CString::new(name).unwrap();
             memory_region_init_io(
                 slot,
-                owner.cast::<Object>(),
+                owner.cast::<bindings::Object>(),
                 ops,
                 owner.cast::<c_void>(),
                 cstr.as_ptr(),
rust/qemu-api/src/qdev.rs +3 -3
index c136457090c..1a4d1f38762 100644
@@ -52,7 +52,7 @@ pub trait ResettablePhasesImpl {
 /// can be downcasted to type `T`. We also expect the device is
 /// readable/writeable from one thread at any time.
 unsafe extern "C" fn rust_resettable_enter_fn<T: ResettablePhasesImpl>(
-    obj: *mut Object,
+    obj: *mut bindings::Object,
     typ: ResetType,
 ) {
     let state = NonNull::new(obj).unwrap().cast::<T>();
@@ -65,7 +65,7 @@ pub trait ResettablePhasesImpl {
 /// can be downcasted to type `T`. We also expect the device is
 /// readable/writeable from one thread at any time.
 unsafe extern "C" fn rust_resettable_hold_fn<T: ResettablePhasesImpl>(
-    obj: *mut Object,
+    obj: *mut bindings::Object,
     typ: ResetType,
 ) {
     let state = NonNull::new(obj).unwrap().cast::<T>();
@@ -78,7 +78,7 @@ pub trait ResettablePhasesImpl {
 /// can be downcasted to type `T`. We also expect the device is
 /// readable/writeable from one thread at any time.
 unsafe extern "C" fn rust_resettable_exit_fn<T: ResettablePhasesImpl>(
-    obj: *mut Object,
+    obj: *mut bindings::Object,
     typ: ResetType,
 ) {
     let state = NonNull::new(obj).unwrap().cast::<T>();
rust/qemu-api/src/qom.rs +22 -13
index 5488643a2fd..0bca36336ba 100644
@@ -101,16 +101,24 @@
     ptr::NonNull,
 };
 
-pub use bindings::{Object, ObjectClass};
+pub use bindings::ObjectClass;
 
 use crate::{
     bindings::{
         self, object_class_dynamic_cast, object_dynamic_cast, object_get_class,
         object_get_typename, object_new, object_ref, object_unref, TypeInfo,
     },
-    cell::bql_locked,
+    cell::{bql_locked, Opaque},
 };
 
+/// A safe wrapper around [`bindings::Object`].
+#[repr(transparent)]
+#[derive(Debug, qemu_api_macros::Wrapper)]
+pub struct Object(Opaque<bindings::Object>);
+
+unsafe impl Send for Object {}
+unsafe impl Sync for Object {}
+
 /// Marker trait: `Self` can be statically upcasted to `P` (i.e. `P` is a direct
 /// or indirect parent of `Self`).
 ///
@@ -199,7 +207,7 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
     }
 }
 
-unsafe extern "C" fn rust_instance_init<T: ObjectImpl>(obj: *mut Object) {
+unsafe extern "C" fn rust_instance_init<T: ObjectImpl>(obj: *mut bindings::Object) {
     let mut state = NonNull::new(obj).unwrap().cast::<T>();
     // SAFETY: obj is an instance of T, since rust_instance_init<T>
     // is called from QOM core as the instance_init function
@@ -209,7 +217,7 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
     }
 }
 
-unsafe extern "C" fn rust_instance_post_init<T: ObjectImpl>(obj: *mut Object) {
+unsafe extern "C" fn rust_instance_post_init<T: ObjectImpl>(obj: *mut bindings::Object) {
     let state = NonNull::new(obj).unwrap().cast::<T>();
     // SAFETY: obj is an instance of T, since rust_instance_post_init<T>
     // is called from QOM core as the instance_post_init function
@@ -230,7 +238,7 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
     <T as ObjectImpl>::CLASS_INIT(unsafe { klass.as_mut() })
 }
 
-unsafe extern "C" fn drop_object<T: ObjectImpl>(obj: *mut Object) {
+unsafe extern "C" fn drop_object<T: ObjectImpl>(obj: *mut bindings::Object) {
     // SAFETY: obj is an instance of T, since drop_object<T> is called
     // from the QOM core function object_deinit() as the instance_finalize
     // function for class T.  Note that while object_deinit() will drop the
@@ -280,14 +288,14 @@ pub unsafe trait ObjectType: Sized {
     /// Return the receiver as an Object.  This is always safe, even
     /// if this type represents an interface.
     fn as_object(&self) -> &Object {
-        unsafe { &*self.as_object_ptr() }
+        unsafe { &*self.as_ptr().cast() }
     }
 
     /// Return the receiver as a const raw pointer to Object.
     /// This is preferrable to `as_object_mut_ptr()` if a C
     /// function only needs a `const Object *`.
-    fn as_object_ptr(&self) -> *const Object {
-        self.as_ptr().cast()
+    fn as_object_ptr(&self) -> *const bindings::Object {
+        self.as_object().as_ptr()
     }
 
     /// Return the receiver as a mutable raw pointer to Object.
@@ -297,8 +305,8 @@ fn as_object_ptr(&self) -> *const Object {
     /// This cast is always safe, but because the result is mutable
     /// and the incoming reference is not, this should only be used
     /// for calls to C functions, and only if needed.
-    unsafe fn as_object_mut_ptr(&self) -> *mut Object {
-        self.as_object_ptr() as *mut _
+    unsafe fn as_object_mut_ptr(&self) -> *mut bindings::Object {
+        self.as_object().as_mut_ptr()
     }
 }
 
@@ -621,7 +629,7 @@ pub trait ObjectImpl: ObjectType + IsA<Object> {
 /// We expect the FFI user of this function to pass a valid pointer that
 /// can be downcasted to type `T`. We also expect the device is
 /// readable/writeable from one thread at any time.
-unsafe extern "C" fn rust_unparent_fn<T: ObjectImpl>(dev: *mut Object) {
+unsafe extern "C" fn rust_unparent_fn<T: ObjectImpl>(dev: *mut bindings::Object) {
     let state = NonNull::new(dev).unwrap().cast::<T>();
     T::UNPARENT.unwrap()(unsafe { state.as_ref() });
 }
@@ -796,8 +804,9 @@ fn new() -> Owned<Self> {
         // SAFETY: the object created by object_new is allocated on
         // the heap and has a reference count of 1
         unsafe {
-            let obj = &*object_new(Self::TYPE_NAME.as_ptr());
-            Owned::from_raw(obj.unsafe_cast::<Self>())
+            let obj = object_new(Self::TYPE_NAME.as_ptr());
+            let obj = Object::from_raw(obj).unsafe_cast::<Self>();
+            Owned::from_raw(obj)
         }
     }
 }
Signature · 1 line
2.48.1
Reviewed-by on v1 10/15
#22 lore raw

Re: [PATCH 10/15] rust: qom: wrap Object with Opaque<>

Quoted 10 lines
rust/qemu-api/src/qom.rs +1 -1
@@ -621,7 +629,7 @@ pub trait ObjectImpl: ObjectType + IsA<Object> {
 /// We expect the FFI user of this function to pass a valid pointer that
 /// can be downcasted to type `T`. We also expect the device is
 /// readable/writeable from one thread at any time.
-unsafe extern "C" fn rust_unparent_fn<T: ObjectImpl>(dev: *mut Object) {
+unsafe extern "C" fn rust_unparent_fn<T: ObjectImpl>(dev: *mut bindings::Object) {
     let state = NonNull::new(dev).unwrap().cast::<T>();
     T::UNPARENT.unwrap()(unsafe { state.as_ref() });
 }

rust/qemu-api/src/qom.rs fn new() -> Owned<Self> { · line 807

Quoted 6 lines
rust/qemu-api/src/qom.rs +1 -2
@@ -796,8 +804,9 @@ fn new() -> Owned<Self> {
         // SAFETY: the object created by object_new is allocated on
         // the heap and has a reference count of 1
         unsafe {
-            let obj = &*object_new(Self::TYPE_NAME.as_ptr());
-            Owned::from_raw(obj.unsafe_cast::<Self>())
+            let obj = object_new(Self::TYPE_NAME.as_ptr());

Having the same name is always not ideal, so let's name the first one raw_obj.

rust/qemu-api/src/qom.rs fn new() -> Owned<Self> { · line 812

Quoted 5 lines
rust/qemu-api/src/qom.rs +2 -0
+            let obj = Object::from_raw(obj).unsafe_cast::<Self>();
+            Owned::from_raw(obj)
         }
     }
 }

Others look good to me,

Quoted 1 line
#23 lore raw

PATCH 11/15 rust: qdev: wrap Clock and DeviceState with Opaque<>

In reply to Paolo Bonzini
---
 rust/qemu-api/src/bindings.rs |  6 ----
 rust/qemu-api/src/qdev.rs     | 68 ++++++++++++++++++++++++-----------
 rust/qemu-api/src/vmstate.rs  |  2 +-
 3 files changed, 49 insertions(+), 27 deletions(-)
rust/qemu-api/src/bindings.rs +0 -6
index be6dd68c09c..6e70a75a0e6 100644
@@ -34,12 +34,6 @@ unsafe impl Sync for CharBackend {}
 unsafe impl Send for Chardev {}
 unsafe impl Sync for Chardev {}
 
-unsafe impl Send for Clock {}
-unsafe impl Sync for Clock {}
-
-unsafe impl Send for DeviceState {}
-unsafe impl Sync for DeviceState {}
-
 unsafe impl Send for MemoryRegion {}
 unsafe impl Sync for MemoryRegion {}
 
rust/qemu-api/src/qdev.rs +48 -20

144 lines not on this page · raw message

rust/qemu-api/src/vmstate.rs +1 -1
index 24a4dc81e7f..b115d1f8742 100644
@@ -469,7 +469,7 @@ macro_rules! vmstate_clock {
                 $crate::assert_field_type!(
                     $struct_name,
                     $field_name,
-                    $crate::qom::Owned<$crate::bindings::Clock>
+                    $crate::qom::Owned<$crate::qdev::Clock>
                 );
                 $crate::offset_of!($struct_name, $field_name)
             },
Signature · 1 line
2.48.1
Reviewed-by on v1 11/15
#24 lore raw

Re: [PATCH 11/15] rust: qdev: wrap Clock and DeviceState with Opaque<>

Quoted 18 lines
rust/qemu-api/src/qdev.rs +5 -2
-unsafe extern "C" fn rust_realize_fn<T: DeviceImpl>(dev: *mut DeviceState, _errp: *mut *mut Error) {
+unsafe extern "C" fn rust_realize_fn<T: DeviceImpl>(
+    dev: *mut bindings::DeviceState,
+    _errp: *mut *mut Error,
+) {
     let state = NonNull::new(dev).unwrap().cast::<T>();
     T::REALIZE.unwrap()(unsafe { state.as_ref() });
 }
@@ -251,7 +270,7 @@ fn init_clock_in<F: for<'a> FnCall<(&'a Self::Target, ClockEvent)>>(
         events: ClockEvent,
     ) -> Owned<Clock> {
         fn do_init_clock_in(
-            dev: *mut DeviceState,
+            dev: &DeviceState,
             name: &str,
             cb: Option<unsafe extern "C" fn(*mut c_void, ClockEvent)>,
             events: ClockEvent,

rust/qemu-api/src/qdev.rs fn do_init_clock_in( · line 287

Quoted 5 lines
rust/qemu-api/src/qdev.rs +1 -1
@@ -265,14 +284,15 @@ fn do_init_clock_in(
             unsafe {
                 let cstr = CString::new(name).unwrap();
                 let clk = bindings::qdev_init_clock_in(
-                    dev,
+                    dev.0.as_mut_ptr(),

This can be simplfied as dev.as_mut_ptr().

rust/qemu-api/src/qdev.rs fn do_init_clock_in( · line 290

Quoted 4 lines
rust/qemu-api/src/qdev.rs +1 -1
                     cstr.as_ptr(),
                     cb,
-                    dev.cast::<c_void>(),
+                    dev.0.as_void_ptr(),

If Wrapper provides as_void_ptr(), then this can also be simplified.

rust/qemu-api/src/qdev.rs fn do_init_clock_in( · line 297

Quoted 8 lines
rust/qemu-api/src/qdev.rs +2 -1
                     events.0,
                 );
 
-                Owned::from(&*clk)
+                let clk: &Clock = Clock::from_raw(clk);
+                Owned::from(clk)
             }
         }

LGTM,

#25 lore raw

PATCH 12/15 rust: sysbus: wrap SysBusDevice with Opaque<>

In reply to Paolo Bonzini
---
 rust/hw/timer/hpet/src/hpet.rs |  2 +-
 rust/qemu-api/src/bindings.rs  |  3 ---
 rust/qemu-api/src/sysbus.rs    | 25 ++++++++++++++++++-------
 3 files changed, 19 insertions(+), 11 deletions(-)
rust/hw/timer/hpet/src/hpet.rs +1 -1
index be27eb0eff4..19e63465cff 100644
@@ -741,7 +741,7 @@ fn reset_hold(&self, _type: ResetType) {
         HPETFwConfig::update_hpet_cfg(
             self.hpet_id.get(),
             self.capability.get() as u32,
-            sbd.mmio[0].addr,
+            unsafe { *sbd.as_ptr() }.mmio[0].addr,
         );
 
         // to document that the RTC lowers its output on reset as well
rust/qemu-api/src/bindings.rs +0 -3
index 6e70a75a0e6..b791ca6d87f 100644
@@ -40,9 +40,6 @@ unsafe impl Sync for MemoryRegion {}
 unsafe impl Send for ObjectClass {}
 unsafe impl Sync for ObjectClass {}
 
-unsafe impl Send for SysBusDevice {}
-unsafe impl Sync for SysBusDevice {}
-
 // SAFETY: this is a pure data struct
 unsafe impl Send for CoalescedMemoryRange {}
 unsafe impl Sync for CoalescedMemoryRange {}
rust/qemu-api/src/sysbus.rs +18 -7
index 48803a655f9..78909fb9931 100644
@@ -6,11 +6,11 @@
 
 use std::{ffi::CStr, ptr::addr_of_mut};
 
-pub use bindings::{SysBusDevice, SysBusDeviceClass};
+pub use bindings::SysBusDeviceClass;
 
 use crate::{
     bindings,
-    cell::bql_locked,
+    cell::{bql_locked, Opaque},
     irq::{IRQState, InterruptSource},
     memory::MemoryRegion,
     prelude::*,
@@ -18,6 +18,14 @@
     qom::Owned,
 };
 
+/// A safe wrapper around [`bindings::SysBusDevice`].
+#[repr(transparent)]
+#[derive(Debug, qemu_api_macros::Wrapper)]
+pub struct SysBusDevice(Opaque<bindings::SysBusDevice>);
+
+unsafe impl Send for SysBusDevice {}
+unsafe impl Sync for SysBusDevice {}
+
 unsafe impl ObjectType for SysBusDevice {
     type Class = SysBusDeviceClass;
     const TYPE_NAME: &'static CStr =
@@ -49,7 +57,7 @@ pub trait SysBusDeviceMethods: ObjectDeref
     fn init_mmio(&self, iomem: &MemoryRegion) {
         assert!(bql_locked());
         unsafe {
-            bindings::sysbus_init_mmio(self.as_mut_ptr(), iomem.as_mut_ptr());
+            bindings::sysbus_init_mmio(self.upcast().as_mut_ptr(), iomem.as_mut_ptr());
         }
     }
 
@@ -60,7 +68,7 @@ fn init_mmio(&self, iomem: &MemoryRegion) {
     fn init_irq(&self, irq: &InterruptSource) {
         assert!(bql_locked());
         unsafe {
-            bindings::sysbus_init_irq(self.as_mut_ptr(), irq.as_ptr());
+            bindings::sysbus_init_irq(self.upcast().as_mut_ptr(), irq.as_ptr());
         }
     }
 
@@ -69,7 +77,7 @@ fn mmio_map(&self, id: u32, addr: u64) {
         assert!(bql_locked());
         let id: i32 = id.try_into().unwrap();
         unsafe {
-            bindings::sysbus_mmio_map(self.as_mut_ptr(), id, addr);
+            bindings::sysbus_mmio_map(self.upcast().as_mut_ptr(), id, addr);
         }
     }
 
@@ -81,7 +89,7 @@ fn connect_irq(&self, id: u32, irq: &Owned<IRQState>) {
         let id: i32 = id.try_into().unwrap();
         let irq: &IRQState = irq;
         unsafe {
-            bindings::sysbus_connect_irq(self.as_mut_ptr(), id, irq.as_mut_ptr());
+            bindings::sysbus_connect_irq(self.upcast().as_mut_ptr(), id, irq.as_mut_ptr());
         }
     }
 
@@ -89,7 +97,10 @@ fn sysbus_realize(&self) {
         // TODO: return an Error
         assert!(bql_locked());
         unsafe {
-            bindings::sysbus_realize(self.as_mut_ptr(), addr_of_mut!(bindings::error_fatal));
+            bindings::sysbus_realize(
+                self.upcast().as_mut_ptr(),
+                addr_of_mut!(bindings::error_fatal),
+            );
         }
     }
 }
Signature · 1 line
2.48.1
Reviewed-by on v1 12/15
#26 lore raw

Re: [PATCH 12/15] rust: sysbus: wrap SysBusDevice with Opaque<>

Quoted 17 lines · Paolo Bonzini

Date: Fri, 21 Feb 2025 18:03:39 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 12/15] rust: sysbus: wrap SysBusDevice with Opaque<>
X-Mailer: git-send-email 2.48.1

---
 rust/hw/timer/hpet/src/hpet.rs |  2 +-
 rust/qemu-api/src/bindings.rs  |  3 ---
 rust/qemu-api/src/sysbus.rs    | 25 ++++++++++++++++++-------
 3 files changed, 19 insertions(+), 11 deletions(-)
rust/hw/timer/hpet/src/hpet.rs +0 -0
index be27eb0eff4..19e63465cff 100644

rust/hw/timer/hpet/src/hpet.rs fn reset_hold(&self, _type: ResetType) { · line 744

Quoted 5 lines
rust/hw/timer/hpet/src/hpet.rs +1 -1
@@ -741,7 +741,7 @@ fn reset_hold(&self, _type: ResetType) {
         HPETFwConfig::update_hpet_cfg(
             self.hpet_id.get(),
             self.capability.get() as u32,
-            sbd.mmio[0].addr,
+            unsafe { *sbd.as_ptr() }.mmio[0].addr,

We can wrap this unsafe code into SysBusDeviceMethods...then the device won't introduce more unsafe code.

rust/hw/timer/hpet/src/hpet.rs fn reset_hold(&self, _type: ResetType) { · line 747

Quoted 3 lines
rust/hw/timer/hpet/src/hpet.rs +0 -0
         );
 
         // to document that the RTC lowers its output on reset as well

Others, fine for me,

#27 lore raw

PATCH 13/15 rust: memory: wrap MemoryRegion with Opaque<>

In reply to Paolo Bonzini
---
 rust/qemu-api/src/bindings.rs |  3 ---
 rust/qemu-api/src/memory.rs   | 30 ++++++++++++++++--------------
 2 files changed, 16 insertions(+), 17 deletions(-)
rust/qemu-api/src/bindings.rs +0 -3
index b791ca6d87f..26cc8de0cf2 100644
@@ -34,9 +34,6 @@ unsafe impl Sync for CharBackend {}
 unsafe impl Send for Chardev {}
 unsafe impl Sync for Chardev {}
 
-unsafe impl Send for MemoryRegion {}
-unsafe impl Sync for MemoryRegion {}
-
 unsafe impl Send for ObjectClass {}
 unsafe impl Sync for ObjectClass {}
 
rust/qemu-api/src/memory.rs +16 -14
index 713c494ca2e..fdb1ea11fcf 100644
@@ -6,9 +6,8 @@
 
 use std::{
     ffi::{CStr, CString},
-    marker::{PhantomData, PhantomPinned},
+    marker::PhantomData,
     os::raw::{c_uint, c_void},
-    ptr::addr_of,
 };
 
 pub use bindings::{hwaddr, MemTxAttrs};
@@ -16,6 +15,7 @@
 use crate::{
     bindings::{self, device_endian, memory_region_init_io},
     callbacks::FnCall,
+    cell::Opaque,
     prelude::*,
     zeroable::Zeroable,
 };
@@ -132,13 +132,13 @@ fn default() -> Self {
     }
 }
 
-/// A safe wrapper around [`bindings::MemoryRegion`].  Compared to the
-/// underlying C struct it is marked as pinned because the QOM tree
-/// contains a pointer to it.
-pub struct MemoryRegion {
-    inner: bindings::MemoryRegion,
-    _pin: PhantomPinned,
-}
+/// A safe wrapper around [`bindings::MemoryRegion`].
+#[repr(transparent)]
+#[derive(qemu_api_macros::Wrapper)]
+pub struct MemoryRegion(Opaque<bindings::MemoryRegion>);
+
+unsafe impl Send for MemoryRegion {}
+unsafe impl Sync for MemoryRegion {}
 
 impl MemoryRegion {
     // inline to ensure that it is not included in tests, which only
@@ -174,13 +174,15 @@ pub fn init_io<T: IsA<Object>>(
         size: u64,
     ) {
         unsafe {
-            Self::do_init_io(&mut self.inner, owner.cast::<Object>(), &ops.0, name, size);
+            Self::do_init_io(
+                self.0.as_mut_ptr(),
+                owner.cast::<Object>(),
+                &ops.0,
+                name,
+                size,
+            );
         }
     }
-
-    pub(crate) const fn as_mut_ptr(&self) -> *mut bindings::MemoryRegion {
-        addr_of!(self.inner) as *mut _
-    }
 }
 
 unsafe impl ObjectType for MemoryRegion {
Signature · 1 line
2.48.1
#28 lore raw

Re: [PATCH 13/15] rust: memory: wrap MemoryRegion with Opaque<>

Review pub fn init_io<T: IsA<Object>>( · line 178

Quoted 9 lines
 impl MemoryRegion {
     // inline to ensure that it is not included in tests, which only
(quoted diff) +2 -1
@@ -174,13 +174,15 @@ pub fn init_io<T: IsA<Object>>(
         size: u64,
     ) {
         unsafe {
-            Self::do_init_io(&mut self.inner, owner.cast::<Object>(), &ops.0, name, size);
+            Self::do_init_io(
+                self.0.as_mut_ptr(),

I'm not sure why the wrapper doesn't work here.

If I change this to self.as_mut_ptr(), then compiler tries to apply ObjectDeref::as_mut_ptr and complains:

the trait qom::ObjectType is not implemented for bindings::MemoryRegion

But when I modify the function signature to &self like:

rust/qemu-api/src/memory.rs +1 -1
index fdb1ea11fcf9..a82348c4a564 100644
@@ -167,7 +167,7 @@ unsafe fn do_init_io(
     }
 
     pub fn init_io<T: IsA<Object>>(
-        &mut self,
+        &self,
         owner: *mut T,
         ops: &'static MemoryRegionOps<T>,
         name: &'static str,

Then the Wrapper's as_mut_ptr() can work.

Quoted 18 lines
(quoted diff) +5 -4
+                owner.cast::<Object>(),
+                &ops.0,
+                name,
+                size,
+            );
         }
     }
-
-    pub(crate) const fn as_mut_ptr(&self) -> *mut bindings::MemoryRegion {
-        addr_of!(self.inner) as *mut _
-    }
 }
 
 unsafe impl ObjectType for MemoryRegion {
Signature · 1 line
2.48.1
#29 lore raw

Re: [PATCH 13/15] rust: memory: wrap MemoryRegion with Opaque<>

Quoted 12 lines · Zhao Liu

Review pub fn init_io<T: IsA<Object>>( · line 178

Quoted 9 lines
  impl MemoryRegion {
      // inline to ensure that it is not included in tests, which only
(quoted diff) +2 -1
@@ -174,13 +174,15 @@ pub fn init_io<T: IsA<Object>>(
          size: u64,
      ) {
          unsafe {
-            Self::do_init_io(&mut self.inner, owner.cast::<Object>(), &ops.0, name, size);
+            Self::do_init_io(
+                self.0.as_mut_ptr(),

I'm not sure why the wrapper doesn't work here.

Quoted 4 lines

If I change this to self.as_mut_ptr(), then compiler tries to apply ObjectDeref::as_mut_ptr and complains:

the trait qom::ObjectType is not implemented for bindings::MemoryRegion

It's because the implementation of ObjectDeref for "&mut MemoryRegion" wins over coercing "&mut MemoryRegion" to "&MemoryRegion" and then calling MemoryRegion::as_mut_ptr().

I added a comment

        // self.0.as_mut_ptr() needed because Rust tries to call
        // ObjectDeref::as_mut_ptr() on "&mut Self", instead of coercing
        // to "&Self" and then calling MemoryRegion::as_mut_ptr().
        // Revisit if/when ObjectCastMut is not needed anymore; it is
        // only used in a couple places for initialization.

Paolo

Quoted 39 lines

But when I modify the function signature to &self like:

rust/qemu-api/src/memory.rs +1 -1
index fdb1ea11fcf9..a82348c4a564 100644
@@ -167,7 +167,7 @@ unsafe fn do_init_io(
      }
 
      pub fn init_io<T: IsA<Object>>(
-        &mut self,
+        &self,
          owner: *mut T,
          ops: &'static MemoryRegionOps<T>,
          name: &'static str,

Then the Wrapper's as_mut_ptr() can work.

Quoted 18 lines
(quoted diff) +5 -4
+                owner.cast::<Object>(),
+                &ops.0,
+                name,
+                size,
+            );
          }
      }
-
-    pub(crate) const fn as_mut_ptr(&self) -> *mut bindings::MemoryRegion {
-        addr_of!(self.inner) as *mut _
-    }
  }
 
  unsafe impl ObjectType for MemoryRegion {
Signature · 1 line
2.48.1
#30 lore raw

PATCH 14/15 rust: chardev: wrap Chardev with Opaque<>

In reply to Paolo Bonzini
---
 rust/qemu-api/src/bindings.rs | 3 ---
 rust/qemu-api/src/chardev.rs  | 8 ++++++--
 rust/qemu-api/src/qdev.rs     | 1 +
 3 files changed, 7 insertions(+), 5 deletions(-)
rust/qemu-api/src/bindings.rs +0 -3
index 26cc8de0cf2..c3f36108bd5 100644
@@ -31,9 +31,6 @@ unsafe impl Sync for BusState {}
 unsafe impl Send for CharBackend {}
 unsafe impl Sync for CharBackend {}
 
-unsafe impl Send for Chardev {}
-unsafe impl Sync for Chardev {}
-
 unsafe impl Send for ObjectClass {}
 unsafe impl Sync for ObjectClass {}
 
rust/qemu-api/src/chardev.rs +6 -2
index 74cfb634e5f..a35b9217e90 100644
@@ -6,9 +6,13 @@
 
 use std::ffi::CStr;
 
-use crate::{bindings, prelude::*};
+use crate::{bindings, cell::Opaque, prelude::*};
+
+/// A safe wrapper around [`bindings::Chardev`].
+#[repr(transparent)]
+#[derive(qemu_api_macros::Wrapper)]
+pub struct Chardev(Opaque<bindings::Chardev>);
 
-pub type Chardev = bindings::Chardev;
 pub type ChardevClass = bindings::ChardevClass;
 
 unsafe impl ObjectType for Chardev {
rust/qemu-api/src/qdev.rs +1 -0
index ed5dce08216..1ff6c1ca7c2 100644
@@ -334,6 +334,7 @@ fn init_clock_out(&self, name: &str) -> Owned<Clock> {
     fn prop_set_chr(&self, propname: &str, chr: &Owned<Chardev>) {
         assert!(bql_locked());
         let c_propname = CString::new(propname).unwrap();
+        let chr: &Chardev = chr;
         unsafe {
             bindings::qdev_prop_set_chr(
                 self.upcast().as_mut_ptr(),
Signature · 1 line
2.48.1
Reviewed-by on v1 14/15
#31 lore raw

Re: [PATCH 14/15] rust: chardev: wrap Chardev with Opaque<>

Quoted 11 lines · Paolo Bonzini

Date: Fri, 21 Feb 2025 18:03:41 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 14/15] rust: chardev: wrap Chardev with Opaque<>
X-Mailer: git-send-email 2.48.1

---
 rust/qemu-api/src/bindings.rs | 3 ---
 rust/qemu-api/src/chardev.rs  | 8 ++++++--
 rust/qemu-api/src/qdev.rs     | 1 +
 3 files changed, 7 insertions(+), 5 deletions(-)
#32 lore raw

PATCH 15/15 rust: bindings: remove more unnecessary Send/Sync impls

In reply to Paolo Bonzini

Send and Sync are now implemented on the opaque wrappers. Remove them from the bindings module, unless the structs are pure data containers and/or have no C functions defined on them.

---
 rust/qemu-api/src/bindings.rs | 8 ++------
 1 file changed, 2 insertions(+), 6 deletions(-)
rust/qemu-api/src/bindings.rs +2 -6
index c3f36108bd5..3c1d297581e 100644
@@ -25,15 +25,11 @@
 
 // SAFETY: these are implemented in C; the bindings need to assert that the
 // BQL is taken, either directly or via `BqlCell` and `BqlRefCell`.
-unsafe impl Send for BusState {}
-unsafe impl Sync for BusState {}
-
+// When bindings for character devices are introduced, this can be
+// moved to the Opaque<> wrapper in src/chardev.rs.
 unsafe impl Send for CharBackend {}
 unsafe impl Sync for CharBackend {}
 
-unsafe impl Send for ObjectClass {}
-unsafe impl Sync for ObjectClass {}
-
 // SAFETY: this is a pure data struct
 unsafe impl Send for CoalescedMemoryRange {}
 unsafe impl Sync for CoalescedMemoryRange {}
Signature · 1 line
2.48.1
Reviewed-by on v1 15/15
#33 lore raw

Re: [PATCH 15/15] rust: bindings: remove more unnecessary Send/Sync impls

Quoted 6 lines · Paolo Bonzini

Date: Fri, 21 Feb 2025 18:03:42 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 15/15] rust: bindings: remove more unnecessary Send/Sync
impls
X-Mailer: git-send-email 2.48.1

Quoted 8 lines

Send and Sync are now implemented on the opaque wrappers. Remove them from the bindings module, unless the structs are pure data containers and/or have no C functions defined on them.

---
 rust/qemu-api/src/bindings.rs | 8 ++------
 1 file changed, 2 insertions(+), 6 deletions(-)