rust: remaining part of qdev bindings
Subsystems (2)
cover rust: remaining part of qdev bindings
This is what I have left for qdev bindings, including 1) reference counting and object creation 2) clocks 3) Resettable 4) MemoryRegionOps. I have no rush for this series, and I expect HPET to be merged before it. The documentation is not yet complete (will be fixed) and the API is limited to what is needed for pl011 (which I am not considering a bug, since the QEMU API is so large), but I think it's already ready for an initial review.
The most interesting part is perhaps the usage of the builder pattern for MemoryRegionOps:
static PL011_OPS: MemoryRegionOps<PL011State> = MemoryRegionOpsBuilder::<PL011State>::new()
.read(&PL011State::read)
.write(&PL011State::write)
.native_endian()
.impl_sizes(4, 4)
.build();The code is getting closer to the synopsis at
https://lists.nongnu.org/archive/html/qemu-rust/2024-12/msg00006.html,
except that it works (at least as far as CI is concerned) instead of just compiling. :) And since I'm citing it, a reminder that it may still be worth asking your Rust questions as replies to that message.
You can find the code in the rust-next branch of
https://gitlab.com/bonzini/qemu/, where it passed CI.
Paolo
Paolo Bonzini (9):
rust: qom: add reference counting functionality
rust: qom: add object creation functionality
rust: callbacks: allow passing optional callbacks as ()
rust: qdev: add clock creation
rust: qom: allow initializing interface vtables
rust: qdev: make ObjectImpl a supertrait of DeviceImpl
rust: qdev: switch from legacy reset to Resettable
rust: bindings: add Sync markers to types referred to by
MemoryRegionOps
rust: bindings for MemoryRegionOps
Zhao Liu (1):
rust: qemu-api: add sub-subclass to the integration tests
meson.build | 1 + rust/hw/char/pl011/src/device.rs | 88 ++++++++-------- rust/hw/char/pl011/src/lib.rs | 1 - rust/hw/char/pl011/src/memory_ops.rs | 36 ------- rust/qemu-api/meson.build | 1 + rust/qemu-api/src/bindings.rs | 19 +++- rust/qemu-api/src/callbacks.rs | 97 ++++++++++++++++++ rust/qemu-api/src/irq.rs | 3 + rust/qemu-api/src/lib.rs | 1 + rust/qemu-api/src/memory.rs | 191 +++++++++++++++++++++++++++++++++++ rust/qemu-api/src/prelude.rs | 4 + rust/qemu-api/src/qdev.rs | 188 +++++++++++++++++++++++++++++----- rust/qemu-api/src/qom.rs | 181 ++++++++++++++++++++++++++++++++- rust/qemu-api/src/sysbus.rs | 7 +- rust/qemu-api/src/vmstate.rs | 10 +- rust/qemu-api/src/zeroable.rs | 12 +++ rust/qemu-api/tests/tests.rs | 87 ++++++++++++---- 17 files changed, 793 insertions(+), 134 deletions(-) delete mode 100644 rust/hw/char/pl011/src/memory_ops.rs create mode 100644 rust/qemu-api/src/memory.rs
Signature · 1 line
2.47.1
PATCH 1/10 rust: qemu-api: add sub-subclass to the integration tests
From: Zhao Liu <[email protected]>
missing signed-off-by from zhao
--- rust/qemu-api/tests/tests.rs | 56 ++++++++++++++++++++++++++++++++++-- 1 file changed, 53 insertions(+), 3 deletions(-)
rust/qemu-api/tests/tests.rs +53 -3
@@ -14,8 +14,8 @@ cell::{self, BqlCell}, declare_properties, define_property, prelude::*, - qdev::{DeviceImpl, DeviceState, Property}, - qom::{ObjectImpl, ParentField}, + qdev::{DeviceClass, DeviceImpl, DeviceState, Property}, + qom::{ClassInitImpl, ObjectImpl, ParentField}, vmstate::VMStateDescription, zeroable::Zeroable, };
@@ -37,6 +37,10 @@ pub struct DummyState {qom_isa! (DummyState :Object ,DeviceState ); +pub struct DummyClass { + parent_class: <DeviceState as ObjectType >::Class , +} +declare_properties! {DUMMY_PROPERTIES ,define_property! (
@@ -49,7 +53,7 @@ pub struct DummyState { }unsafe impl ObjectType for DummyState { -type Class = <DeviceState as ObjectType >::Class ; +type Class =DummyClass ;const TYPE_NAME : &'staticCStr =c_str! ("dummy" ); }
@@ -67,6 +71,51 @@ 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 )] +pub struct DummyChildState { + parent:ParentField <DummyState >, +} + +qom_isa! (DummyChildState :Object ,DeviceState ,DummyState ); + +pub struct DummyChildClass { + parent_class: <DummyState as ObjectType >::Class , +} + +unsafe impl ObjectType for DummyChildState { +type Class =DummyChildClass ; +const TYPE_NAME : &'staticCStr =c_str! ("dummy_child" ); +} + +impl ObjectImpl for DummyChildState { +type ParentType =DummyState ; +const ABSTRACT :bool =false ; +} + +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); + } +} +fn init_qom () {static ONCE :BqlCell <bool > =BqlCell ::new (false );
@@ -85,6 +134,7 @@ fn test_object_new() {init_qom ();unsafe {object_unref (object_new (DummyState ::TYPE_NAME .as_ptr ()).cast ()); +object_unref (object_new (DummyChildState ::TYPE_NAME .as_ptr ()).cast ()); } }
Signature · 1 line
2.47.1
Re: [PATCH 01/10] rust: qemu-api: add sub-subclass to the integration tests
Quoted 9 lines · Paolo Bonzini
Date: Fri, 17 Jan 2025 20:39:54 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 01/10] rust: qemu-api: add sub-subclass to the integration
tests
X-Mailer: git-send-email 2.47.1From: Zhao Liu <[email protected]>
missing signed-off-by from zhao
Thanks a lot!
Quoted 4 lines
--- rust/qemu-api/tests/tests.rs | 56 ++++++++++++++++++++++++++++++++++-- 1 file changed, 53 insertions(+), 3 deletions(-)
PATCH 2/10 rust: qom: add reference counting functionality
In reply to Paolo BonziniAdd a smart pointer that allows to add and remove references from QOM objects. It's important to note that while all QOM objects have a reference count, in practice not all of them have their lifetime guarded by it. Embedded objects, specifically, are confined to the lifetime of the owner.
When writing Rust bindings this is important, because embedded objects are *never* used through the "Owned<>" smart pointer that is introduced here.
--- rust/qemu-api/src/qom.rs | 121 ++++++++++++++++++++++++++++++++++- rust/qemu-api/src/vmstate.rs | 6 +- 2 files changed, 125 insertions(+), 2 deletions(-)
rust/qemu-api/src/qom.rs +120 -1
@@ -56,13 +56,21 @@use std::{ ffi::CStr , fmt, + mem::ManuallyDrop , ops::{Deref ,DerefMut }, os::raw::c_void, + ptr::NonNull , };pub use bindings::{Object ,ObjectClass }; -use crate ::bindings::{self, object_dynamic_cast, object_get_class, object_get_typename,TypeInfo }; +use crate ::{ + bindings::{ + self, object_dynamic_cast, object_get_class, object_get_typename, object_ref, object_unref, +TypeInfo , + }, + cell::bql_locked, +};/// Marker trait: `Self` can be statically upcasted to `P` (i.e. `P` is a direct /// or indirect parent of `Self`).
@@ -605,6 +613,110 @@ unsafe impl ObjectType for Object {unsafe {CStr ::from_bytes_with_nul_unchecked (bindings::TYPE_OBJECT ) }; } +/// A reference-counted pointer to a QOM object. +/// +/// `Owned<T>` wraps `T` with automatic reference counting. It increases the +/// reference count when created via [`Owned::from`] and decreases it when +/// dropped. This ensures that the reference count remains elevated as long as +/// any `Owned<T>` references to it exist. Note that however the object may +/// disappear if it is *embedded* within a larger object. For more information +/// see the [`Owned::from`]. +/// +/// It is *not* safe to send `Owned<T>` to another thread, because currently +/// `object_unref` requires the Big QEMU Lock. +#[repr(transparent)] +#[derive( PartialEq , Eq , Hash , PartialOrd , Ord )] +pub struct Owned <T :ObjectType >(NonNull <T >); + +// SAFETY: the implementation asserts via `bql_locked` that the BQL is taken +unsafe impl <T :ObjectType +Sync >Sync for Owned <T > {} + +impl <T :ObjectType >Owned <T > { +/// Convert a raw C pointer into an owned reference to the QOM +/// object it points to. The object's reference count will be +/// decreased when the `Owned` is dropped. +/// +/// # Panics +/// +/// Panics if `ptr` is NULL. +/// +/// # Safety +/// +/// The caller must indeed own a reference to the QOM object. +/// The object must not be embedded in another unless the outer +/// object is guaranteed to have a longer lifetime. +/// +/// A raw pointer obtained via [`Owned::into_raw()`] can always be passed +/// back to `from_raw()` (assuming the original `Owned` was valid!), +/// since the owned reference remains there between the calls to +/// `into_raw()` and `from_raw()`. +#[allow(clippy::missing_const_for_fn)] +pub unsafe fn from_raw (ptr: *const T ) ->Self { +// SAFETY NOTE: while NonNull requires a mutable pointer, only +// Deref is implemented so the pointer passed to from_raw +// remains const +Owned (NonNull ::new (ptras *mut T ).unwrap ()) + } + +/// Obtain a raw C pointer from a reference. `src` is consumed +/// and the reference is leaked. +#[allow(clippy::missing_const_for_fn)] +pub fn into_raw (src:Owned <T >) -> *mut T { +let src =ManuallyDrop ::new (src); + src.0 .as_ptr () + } + +/// Increase the reference count of a QOM object and return +/// a new owned reference to it. +/// +/// # Safety +/// +/// The object must not be embedded in another, unless the outer +/// object is guaranteed to have a longer lifetime. +pub unsafe fn from (obj: &T ) ->Self { +unsafe { +object_ref (obj.as_object_mut_ptr ().cast ::<c_void >()); + +// SAFETY NOTE: while NonNull requires a mutable pointer, only +// Deref is implemented so the reference passed to from_raw +// remains shared +Owned (NonNull ::new_unchecked (obj.as_mut_ptr ())) + } + } +} + +impl <T :ObjectType >Deref for Owned <T > { +type Target =T ; + +fn deref (&self) -> &Self ::Target { +// SAFETY: creation method is unsafe; whoever calls it has +// responsibility that the pointer is valid, and remains valid +// throughout the lifetime of the `Owned<T>`. +// With that guarantee, reference counting ensures that +// the object remains alive. +unsafe { &*self.0 .as_ptr () } + } +} +impl <T :ObjectType >ObjectDeref for Owned <T > {} + +impl <T :ObjectType >Drop for Owned <T > { +fn drop (&mut self) { +assert! (bql_locked ()); +// SAFETY: creation method is unsafe, and whoever calls it has +// responsibility that the pointer is valid, and remains valid +// throughout the lifetime of the `Owned<T>`. +unsafe { +object_unref (self.as_object_mut_ptr ().cast ::<c_void >()); + } + } +} + +impl <T :IsA <Object >> fmt::Debug for Owned <T > { +fn fmt (&self, f: &mut fmt::Formatter ) -> fmt::Result { + self.deref ().debug_fmt (f) + } +} +/// Trait for methods exposed by the Object class. The methods can be /// called on all objects that have the trait `IsA<Object>`. ///
@@ -636,6 +748,13 @@ fn get_class(&self) -> &'static <Self::Target as ObjectType>::Class { klass } + +/// Convenience function for implementing the Debug trait +fn debug_fmt (&self, f: &mut fmt::Formatter ) -> fmt::Result { + f.debug_tuple (&self.typename ()) + .field (&(selfas *const Self )) + .finish () + } }impl <R :ObjectDeref >ObjectMethods for R where R ::Target :IsA <Object > {}
rust/qemu-api/src/vmstate.rs +5 -1
@@ -29,6 +29,8 @@pub use crate ::bindings::{VMStateDescription ,VMStateField };use crate ::{ bindings::{self,VMStateFlags }, + prelude::*, + qom::Owned , zeroable::Zeroable , };
@@ -191,7 +193,8 @@ pub const fn vmstate_varray_flag<T: VMState>(_: PhantomData<T>) -> VMStateFlags/// * a transparent wrapper for any of the above (`Cell`, `UnsafeCell`, /// [`BqlCell`](crate::cell::BqlCell), [`BqlRefCell`](crate::cell::BqlRefCell) /// * a raw pointer to any of the above -/// * a `NonNull` pointer or a `Box` for any of the above +/// * a `NonNull` pointer, a `Box` or an [`Owned`](crate::qom::Owned) for any of +/// the above /// * an array of any of the above /// /// In order to support other types, the trait `VMState` must be implemented
@@ -398,6 +401,7 @@ unsafe impl<$base> VMState for $type where $base: VMState $($where)* {// Unlike C pointers, Box is always non-null therefore there is no need // to specify VMS_ALLOC. impl_vmstate_pointer! (Box <T >where T :VMState ); +impl_vmstate_pointer! (Owned <T >where T :VMState +ObjectType );// Arrays using the underlying type's VMState plus // VMS_ARRAY/VMS_ARRAY_OF_POINTER
Signature · 1 line
2.47.1
Re: [PATCH 02/10] rust: qom: add reference counting functionality
Hi Paolo,
Quoted 9 lines · Paolo Bonzini
Date: Fri, 17 Jan 2025 20:39:55 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 02/10] rust: qom: add reference counting functionality
X-Mailer: git-send-email 2.47.1Add a smart pointer that allows to add and remove references from QOM objects. It's important to note that while all QOM objects have a reference count, in practice not all of them have their lifetime guarded by it.
About the background, I have a maybe common question...why Rust needs extra reference count guarding?
For C side, I notice for child objects, which may be totally embedded in parent object, or may be pointed to by a pointer member in parent object (like pl011's clock), they usually become the Child<> property of their parents by object_initialize_child() (for embedded child) or object_property_add_child() (for child pointer).
And both these 2 interfaces will increase the ref count in object_property_try_add_child(). With ref count increasing, it seems that the Child<> property also express the meaning like "the child object is 'owned' by its parent".
So, what are the benefits of Owned when we also creates Child<> relationship?
Additionally, I felt that the ref count may be a bit confusing. After creating Child<> property, the child object's ref count is sometimes 1, and other times it's 2:
* With object_initialize_child(), child's ref count is 1.
* With object_property_add_child() (usually after a object_new() to create child first):
- sometimes user will call object_unref(), and then the ref count is 1.
E.g., x86_cpu_apic_create() in target/i386/cpu-apic.c.
- sometimes no object_unref(), then ref count is 2.
E.g., exynos4210_realize() in hw/arm/exynos4210.c, creats "cortex-a9".
Quoted 5 lines
Embedded objects, specifically, are confined to the lifetime of the owner.
When writing Rust bindings this is important, because embedded objects are *never* used through the "Owned<>" smart pointer that is introduced here.
From this description, I understand your goal is:
* For embedded child object, its lifetimer is managed by its parent object, through Child<> for the most cases.
* For non-embedded child - a pointer/reference in parent object, its lifetimer is managed by Owned<> (and with Child<>).
Am I right?
Thanks,
Zhao
Re: [PATCH 02/10] rust: qom: add reference counting functionality
Quoted 9 lines · Zhao Liu
Hi Paolo,
Quoted 5 lines · Paolo Bonzini
Date: Fri, 17 Jan 2025 20:39:55 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 02/10] rust: qom: add reference counting functionality
X-Mailer: git-send-email 2.47.1
Quoted 7 lines
Quoted 4 lines
Add a smart pointer that allows to add and remove references from QOM objects. It's important to note that while all QOM objects have a reference count, in practice not all of them have their lifetime guarded by it.
About the background, I have a maybe common question...why Rust needs extra reference count guarding?
Children properties are removed, and thus their reference is dropped, before instance_finalize() is called (see object_finalize() in qom/object.c). This is not valid in Rust, you need to keep the object alive until the last line of Rust code has run - which is after Drop::drop() has run.
Quoted 6 lines
Additionally, I felt that the ref count may be a bit confusing. After creating Child<> property, the child object's ref count is sometimes 1, and other times it's 2:
* With
object_initialize_child(), child's ref count is 1.
Quoted 8 lines
* With
object_property_add_child()(usually after aobject_new()to create child first):- sometimes user will call
object_unref(), and then the ref count is 1.E.g., x86_cpu_apic_create() in target/i386/cpu-apic.c.- sometimes no
object_unref(), then ref count is 2.E.g., exynos4210_realize() in hw/arm/exynos4210.c, creats "cortex-a9".
In C, having a ref count of 2 is usually a latent memory leak (because most of the time there's not going to be an object_unref() in the instance_finalize() method). In this case the leak is latent, because TYPE_EXYNOS4210_SOC is not hot-unpluggable and thus will never really go away once realized.
In Rust, this class of leaks simply does not exist with the right API. ObjectMethods::property_add_child() could either:
- take an Owned<T> and consume it, thus always giving a ref count of 1 on exit. If you want to keep the object you would have to clone it.
- take "&'owner self, &'child T where 'owner: 'child", then you can pass an embedded object like object_initialize_child().
In the latter case however you *still* need to keep the reference count elevated until Drop runs. That is, unlike C, Rust code will always have a ref count of 2 for children. For this reason, instead of having a "T" in the struct you would have another wrapper---something like Child<'owner, T>. This wrapper cannot be cloned but it does an unref when dropped.
My expectation is that property_add_child() will be used exclusivel for the first case, i.e. it will take an Owned<T>. If you want to create a child property from an embedded object, something like object_initialize_child() can be used once pinned-init is used to rewrite how instance_init is used. It will look something like
pin_init! {
&this in MyClass {
...,
iomem <- MemoryRegion::init_io(
this,
&MY_MR_OPS,
"memory-region-name",
0x1000,
),
child_obj <- ChildClass::init().to_child(this, "prop-name") }
}
where to_child() wraps an "impl PinInit<T>" and turns it into an "impl PinInit<Child<'a, T>>". Or something like that. :)
Quoted 9 lines
From this description, I understand your goal is:
* For embedded child object, its lifetimer is managed by its parent object, through Child<> for the most cases.
* For non-embedded child - a pointer/reference in parent object, its lifetimer is managed by
Owned<>(and with Child<>).Am I right?
Yes, you're right.
I am not sure if you meant Child<> as the QOM concept, or as a Rust struct. If the latter, you're really really right.
Paolo
Re: [PATCH 02/10] rust: qom: add reference counting functionality
Quoted 19 lines · Paolo Bonzini
Date: Wed, 29 Jan 2025 11:03:31 +0100
From: Paolo Bonzini <[email protected]>
Subject: Re: [PATCH 02/10] rust: qom: add reference counting functionalityQuoted 14 lines · Zhao Liu
Hi Paolo,
Quoted 9 lines · Paolo Bonzini
Date: Fri, 17 Jan 2025 20:39:55 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 02/10] rust: qom: add reference counting functionality
X-Mailer: git-send-email 2.47.1Add a smart pointer that allows to add and remove references from QOM objects. It's important to note that while all QOM objects have a reference count, in practice not all of them have their lifetime guarded by it.
Quoted 8 lines
Quoted 2 lines
About the background, I have a maybe common question...why Rust needs extra reference count guarding?
Children properties are removed, and thus their reference is dropped, before
instance_finalize()is called (seeobject_finalize()inqom/object.c). This is not valid in Rust, you need to keep the object alive until the last line of Rust code has run - which is afterDrop::drop()has run.
I see, this is also a typical effort to eliminate unsafe crossing of FFI boundaries.
Quoted 12 lines
Quoted 12 lines
Additionally, I felt that the ref count may be a bit confusing. After creating Child<> property, the child object's ref count is sometimes 1, and other times it's 2:
* With
object_initialize_child(), child's ref count is 1.* With
object_property_add_child()(usually after aobject_new()to create child first):- sometimes user will call
object_unref(), and then the ref count is 1.E.g., x86_cpu_apic_create() in target/i386/cpu-apic.c.
Quoted 8 lines
Quoted 2 lines
- sometimes no
object_unref(), then ref count is 2.E.g., exynos4210_realize() in hw/arm/exynos4210.c, creats "cortex-a9".In C, having a ref count of 2 is usually a latent memory leak (because most of the time there's not going to be an
object_unref()in theinstance_finalize()method). In this case the leak is latent, becauseTYPE_EXYNOS4210_SOCis not hot-unpluggable and thus will never really go away once realized.
Further, what about doing object_unref() in object_property_add_child() or object_property_try_add_child()?
Then we can ensure the object will have ref count of 1 on the exit of object_property_add_child() and people will no longer miss object_unref().
Although, there are a few more devices involved to fix similar issues.
Quoted 9 lines
In Rust, this class of leaks simply does not exist with the right API.
ObjectMethods::property_add_child()could either:- take an Owned<T> and consume it, thus always giving a ref count of 1 on exit. If you want to keep the object you would have to clone it.
- take "&'owner self, &'child T where 'owner: 'child", then you can pass an embedded object like
object_initialize_child().
Quoted 6 lines
In the latter case however you *still* need to keep the reference count elevated until Drop runs. That is, unlike C, Rust code will always have a ref count of 2 for children. For this reason, instead of having a "T" in the struct you would have another wrapper---something like Child<'owner, T>. This wrapper cannot be cloned but it does an unref when dropped.
Thanks, the whole picture is nice.
Quoted 16 lines
My expectation is that
property_add_child()will be used exclusivel for the first case, i.e. it will take an Owned<T>. If you want to create a child property from an embedded object, something likeobject_initialize_child()can be used once pinned-init is used to rewrite howinstance_initis used. It will look something like
pin_init! {&this in MyClass { ..., iomem <- MemoryRegion::init_io( this, &MY_MR_OPS, "memory-region-name", 0x1000, ), child_obj <- ChildClass::init().to_child(this, "prop-name")
Quoted 5 lines
}
}where
to_child()wraps an "impl PinInit<T>" and turns it into an "impl PinInit<Child<'a, T>>". Or something like that. :)
Elegant code design, looking forward to pin_init.
Quoted 8 lines
Quoted 8 lines
From this description, I understand your goal is:
* For embedded child object, its lifetimer is managed by its parent object, through Child<> for the most cases.
* For non-embedded child - a pointer/reference in parent object, its lifetimer is managed by
Owned<>(and with Child<>).
Quoted 7 lines
Quoted 1 line
Am I right?
Yes, you're right.
I am not sure if you meant Child<> as the QOM concept, or as a Rust struct. If the latter, you're really really right.
Thank you :-) It seems virtio device will have an embedded case to adopt Child<> struct (virtio_instance_init_common()).
Regards,
Zhao
Re: [PATCH 02/10] rust: qom: add reference counting functionality
In reply to Paolo BonziniQuoted 26 lines
rust/qemu-api/src/qom.rs +26
-0+impl <T :ObjectType >Owned <T > { +/// Convert a raw C pointer into an owned reference to the QOM +/// object it points to. The object's reference count will be +/// decreased when the `Owned` is dropped. +/// +/// # Panics +/// +/// Panics if `ptr` is NULL. +/// +/// # Safety +/// +/// The caller must indeed own a reference to the QOM object. +/// The object must not be embedded in another unless the outer +/// object is guaranteed to have a longer lifetime. +/// +/// A raw pointer obtained via [`Owned::into_raw()`] can always be passed +/// back to `from_raw()` (assuming the original `Owned` was valid!), +/// since the owned reference remains there between the calls to +/// `into_raw()` and `from_raw()`. +#[allow(clippy::missing_const_for_fn)] +pub unsafe fn from_raw (ptr: *const T ) ->Self { +// SAFETY NOTE: while NonNull requires a mutable pointer, only +// Deref is implemented so the pointer passed to from_raw +// remains const +Owned (NonNull ::new (ptras *mut T ).unwrap ()) + }
...
Quoted 9 lines
rust/qemu-api/src/qom.rs +9
-0+/// Increase the reference count of a QOM object and return +/// a new owned reference to it. +/// +/// # Safety +/// +/// The object must not be embedded in another, unless the outer +/// object is guaranteed to have a longer lifetime. +pub unsafe fn from (obj: &T ) ->Self { +unsafe {
rust/qemu-api/src/qom.rs unsafe impl ObjectType for Object { · line 687
Quoted 10 lines
rust/qemu-api/src/qom.rs +10
-0+object_ref (obj.as_object_mut_ptr ().cast ::<c_void >()); + +// SAFETY NOTE: while NonNull requires a mutable pointer, only +// Deref is implemented so the reference passed to from_raw +// remains shared +Owned (NonNull ::new_unchecked (obj.as_mut_ptr ())) + } + } +} +
About the difference between from_raw() and from(), I understand if the C side also holds a pointer, the Rust side must increase the reference count (using Owned::from), and If the C side does not have any other pointers, Rust can directly use Owned::from_raw. Am I right?
* The use of from():
fn do_init_clock_in(
dev: *mut DeviceState,
name: &str,
cb: Option<unsafe extern "C" fn(*mut c_void, ClockEvent)>,
events: ClockEvent,
) -> Owned<Clock> {
assert!(bql_locked());
// SAFETY: the clock is heap allocated and does not have a reference, so
// Owned::from adds one. the callback is disabled automatically
// when the clock is unparented, which happens before the device is
// finalized.
unsafe {
let cstr = CString::new(name).unwrap();
let clk = bindings::qdev_init_clock_in(
dev,
cstr.as_ptr(),
cb,
dev.cast::<c_void>(),
events.0,
);
Owned::from(&*clk)
}
}* The use of from_raw():
fn new() -> Owned<Self> {
assert!(bql_locked());
// 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>())
}
}Comparing with these 2 use cases, I find the difference is qdev_init_clock_in() creates a pointer in qdev_init_clocklist().
Then the comment "the clock is heap allocated and does not have a reference" sounds like a conflict. I'm sure I'm missing something. :-(
Thanks,
Zhao
Re: [PATCH 02/10] rust: qom: add reference counting functionality
Quoted 46 lines · Zhao Liu
Quoted 27 lines
rust/qemu-api/src/qom.rs +26
-0+impl <T :ObjectType >Owned <T > { +/// Convert a raw C pointer into an owned reference to the QOM +/// object it points to. The object's reference count will be +/// decreased when the `Owned` is dropped. +/// +/// # Panics +/// +/// Panics if `ptr` is NULL. +/// +/// # Safety +/// +/// The caller must indeed own a reference to the QOM object. +/// The object must not be embedded in another unless the outer +/// object is guaranteed to have a longer lifetime. +/// +/// A raw pointer obtained via [`Owned::into_raw()`] can always be passed +/// back to `from_raw()` (assuming the original `Owned` was valid!), +/// since the owned reference remains there between the calls to +/// `into_raw()` and `from_raw()`. +#[allow(clippy::missing_const_for_fn)] +pub unsafe fn from_raw (ptr: *const T ) ->Self { +// SAFETY NOTE: while NonNull requires a mutable pointer, only +// Deref is implemented so the pointer passed to from_raw +// remains const +Owned (NonNull ::new (ptras *mut T ).unwrap ()) + }...
Quoted 16 lines
rust/qemu-api/src/qom.rs +16
-0+/// Increase the reference count of a QOM object and return +/// a new owned reference to it. +/// +/// # Safety +/// +/// The object must not be embedded in another, unless the outer +/// object is guaranteed to have a longer lifetime. +pub unsafe fn from (obj: &T ) ->Self { +unsafe { +object_ref (obj.as_object_mut_ptr ().cast ::<c_void >()); + +// SAFETY NOTE: while NonNull requires a mutable pointer, only +// Deref is implemented so the reference passed to from_raw +// remains shared +Owned (NonNull ::new_unchecked (obj.as_mut_ptr ())) + }
Quoted 8 lines
rust/qemu-api/src/qom.rs unsafe impl ObjectType for Object { · line 668
Quoted 3 lines
rust/qemu-api/src/qom.rs +3
-0+ } +} +About the difference between
from_raw()andfrom(), I understand if the C side also holds a pointer, the Rust side must increase the reference count (usingOwned::from), and If the C side does not have any other pointers, Rust can directly useOwned::from_raw. Am I right?
Pretty much - more precisely you use Object::from_raw 1) if the C side gifts a reference 2) if you got the pointer from Owned::into_raw. The second case is similar to Arc::from_raw, which expects that you got a reference from Arc::into_raw. The first is the more common case.
Quoted 5 lines
* The use of
from():let clk = bindings::qdev_init_clock_in(...) Owned::from(&*clk)
In this case the C side wants to manage the reference that qdev_init_clock_in() returns; it is dropped in qdev_finalize_clocklist(). So Rust code needs to increase the refcount.
Quoted 11 lines
* The use of
from_raw():fn new() -> Owned<Self> { assert!(bql_locked()); // 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>()) } }
In this case the C side lets the caller manage the (only) reference when object_new returns, so you must not increase the refcount.
Owned::from() is slightly less efficient, though that almost never matters. If it does you can use ManuallyDrop::new(Owned::from_raw(p)).
Quoted 2 lines
Comparing with these 2 use cases, I find the difference is
qdev_init_clock_in()creates a pointer inqdev_init_clocklist().
That is related, but more precisely the difference is that qdev_init_clock_in() wants to unref that pointer later.
Quoted 2 lines
Then the comment "the clock is heap allocated and does not have a reference" sounds like a conflict. I'm sure I'm missing something. :-(
Changed:
// SAFETY: the clock is heap allocated, but qdev_init_clock_in()
// does not gift the reference to its caller; so use Owned::from to
// add one. the callback is disabled automatically when the clock
// is unparented, which happens before the device is finalized.Thanks for the review!
Paolo
Re: [PATCH 02/10] rust: qom: add reference counting functionality
Quoted 9 lines
Quoted 4 lines
* The use of
from():let clk = bindings::qdev_init_clock_in(...) Owned::from(&*clk)In this case the C side wants to manage the reference that
qdev_init_clock_in()returns; it is dropped inqdev_finalize_clocklist(). So Rust code needs to increase the refcount.
Pls forgive me for one more question about qdev_init_clock_in() on the C side. :-)
qdev_init_clock_in() didn't unref clk after object_property_add_child(), so it is intentional, to make the ref count of clk be 2:
* 1 count is held by clocklist until qdev_finalize_clocklist().
* another 1 is held by its parent via QOM Child<>.
Am I understanding it correctly?
Quoted 9 lines
Quoted 2 lines
Then the comment "the clock is heap allocated and does not have a reference" sounds like a conflict. I'm sure I'm missing something. :-(
Changed:
// SAFETY: the clock is heap allocated, but qdev_init_clock_in() // does not gift the reference to its caller; so use Owned::from to // add one. the callback is disabled automatically when the clock // is unparented, which happens before the device is finalized.
LGTM.
Thank you very much for your patience. I think I understand ref count now.
Regards,
Zhao
Re: [PATCH 02/10] rust: qom: add reference counting functionality
Quoted 13 lines · Zhao Liu
Quoted 9 lines
Quoted 4 lines
* The use of
from():let clk = bindings::qdev_init_clock_in(...) Owned::from(&*clk)In this case the C side wants to manage the reference that
qdev_init_clock_in()returns; it is dropped inqdev_finalize_clocklist(). So Rust code needs to increase the refcount.Pls forgive me for one more question about
qdev_init_clock_in()on the C side. :-)
Quoted 6 lines
qdev_init_clock_in()didn't unrefclkafterobject_property_add_child(), so it is intentional, to make the ref count ofclkbe 2:
* 1 count is held by clocklist untilqdev_finalize_clocklist().
* another 1 is held by its parent via QOM Child<>.Am I understanding it correctly?
Yes, that's more precise. In Rust it will be 3, the two above plus the Owned<Clock>.
Ah wait... qdev_finalize_clocklist() is only called _after_ the Rust struct is Drop::drop-ped, because device_finalize() is called after the subclass's instance_finalize.
So the result of qdev_init_clock_in(), strictly speaking, does not have to be an Owned<Clock>. It can also be a &'device Clock; either is possible. Would you prefer that, or do you think it's enough to add a comment?
Paolo
Quoted 21 lines
Quoted 9 lines
Quoted 2 lines
Then the comment "the clock is heap allocated and does not have a reference" sounds like a conflict. I'm sure I'm missing something. :-(
Changed:
// SAFETY: the clock is heap allocated, but qdev_init_clock_in() // does not gift the reference to its caller; so use Owned::from to // add one. the callback is disabled automatically when the clock // is unparented, which happens before the device is finalized.LGTM.
Thank you very much for your patience. I think I understand ref count now.
Regards,
Zhao
Re: [PATCH 02/10] rust: qom: add reference counting functionality
Quoted 23 lines · Paolo Bonzini
Date: Wed, 5 Feb 2025 10:10:01 +0100
From: Paolo Bonzini <[email protected]>
Subject: Re: [PATCH 02/10] rust: qom: add reference counting functionalityQuoted 18 lines · Zhao Liu
Quoted 9 lines
Quoted 4 lines
* The use of
from():let clk = bindings::qdev_init_clock_in(...) Owned::from(&*clk)In this case the C side wants to manage the reference that
qdev_init_clock_in()returns; it is dropped inqdev_finalize_clocklist(). So Rust code needs to increase the refcount.Pls forgive me for one more question about
qdev_init_clock_in()on the C side. :-)
qdev_init_clock_in()didn't unrefclkafterobject_property_add_child(), so it is intentional, to make the ref count ofclkbe 2:
* 1 count is held by clocklist untilqdev_finalize_clocklist().
* another 1 is held by its parent via QOM Child<>.
Quoted 4 lines
Quoted 1 line
Am I understanding it correctly?
Yes, that's more precise. In Rust it will be 3, the two above plus the Owned<Clock>.
Thanks!
Quoted 8 lines
Ah wait...
qdev_finalize_clocklist()is only called _after_ the Rust struct is Drop::drop-ped, becausedevice_finalize()is called after the subclass'sinstance_finalize.So the result of
qdev_init_clock_in(), strictly speaking, does not have to be an Owned<Clock>. It can also be a &'device Clock; either is possible. Would you prefer that, or do you think it's enough to add a comment?
I prefer the latter, i.e., keep current Owned<Clock> and add a comment to mention something like "Although strictly speaking, it does not have to be an Owned<Clock>. Owned<> is still worth favor to use to protect Rust code from FFI. When unsure whether to use Owned<>, then use Owned<>."
-Zhao
Re: [PATCH 02/10] rust: qom: add reference counting functionality
In reply to Paolo BonziniQuoted 11 lines · Paolo Bonzini
Date: Fri, 17 Jan 2025 20:39:55 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 02/10] rust: qom: add reference counting functionality
X-Mailer: git-send-email 2.47.1Add a smart pointer that allows to add and remove references from QOM objects. It's important to note that while all QOM objects have a reference count, in practice not all of them have their lifetime guarded by it. Embedded objects, specifically, are confined to the lifetime of the owner.
Quoted 9 lines
When writing Rust bindings this is important, because embedded objects are *never* used through the "Owned<>" smart pointer that is introduced here.
Signed-off-by Paolo Bonzini <[email protected]>--- rust/qemu-api/src/qom.rs | 121 ++++++++++++++++++++++++++++++++++- rust/qemu-api/src/vmstate.rs | 6 +- 2 files changed, 125 insertions(+), 2 deletions(-)
Revisit this patch (with Paolo's explaination), LGTM,
PATCH 3/10 rust: qom: add object creation functionality
In reply to Paolo BonziniThe basic object lifecycle test can now be implemented using safe code!
--- rust/hw/char/pl011/src/device.rs | 13 ++++++++----- rust/qemu-api/src/prelude.rs | 1 + rust/qemu-api/src/qom.rs | 23 +++++++++++++++++++++-- rust/qemu-api/tests/tests.rs | 30 +++++++++++------------------- 4 files changed, 41 insertions(+), 26 deletions(-)
rust/hw/char/pl011/src/device.rs +8 -5
@@ -690,15 +690,18 @@ pub fn post_load(&self, _version_id: u32) -> Result<(), ()> { irq: qemu_irq, chr: *mut Chardev, ) -> *mut DeviceState { +let pl011 =PL011State ::new ();unsafe { -let dev: *mut DeviceState =qdev_new (PL011State ::TYPE_NAME .as_ptr ()); -let sysbus: *mut SysBusDevice = dev.cast ::<SysBusDevice >(); - +let dev = pl011.as_mut_ptr ::<DeviceState >();qdev_prop_set_chr (dev,c_str! ("chardev" ).as_ptr (), chr); -sysbus_realize_and_unref (sysbus,addr_of_mut! (error_fatal)); + +let sysbus = pl011.as_mut_ptr ::<SysBusDevice >(); +sysbus_realize (sysbus,addr_of_mut! (error_fatal));sysbus_mmio_map (sysbus,0 , addr);sysbus_connect_irq (sysbus,0 , irq); - dev + +// return the pointer, which is kept alive by the QOM tree; drop owned ref + pl011.as_mut_ptr () } }
rust/qemu-api/src/prelude.rs +1 -0
@@ -12,6 +12,7 @@pub use crate ::qom::ObjectCast ;pub use crate ::qom::ObjectCastMut ;pub use crate ::qom::ObjectDeref ; +pub use crate ::qom::ObjectClassMethods ;pub use crate ::qom::ObjectMethods ;pub use crate ::qom::ObjectType ;
rust/qemu-api/src/qom.rs +21 -2
@@ -66,8 +66,8 @@use crate ::{ bindings::{ - self, object_dynamic_cast, object_get_class, object_get_typename, object_ref, object_unref, -TypeInfo , + self, object_dynamic_cast, object_get_class, object_get_typename, object_new, object_ref, + object_unref,TypeInfo , }, cell::bql_locked, };
@@ -717,6 +717,24 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { } } +/// Trait for class methods exposed by the Object class. The methods can be +/// called on all objects that have the trait `IsA<Object>`. +/// +/// The trait should only be used through the blanket implementation, +/// which guarantees safety via `IsA` +pub trait ObjectClassMethods :IsA <Object > { +/// Return a new reference counted instance of this class +fn new () ->Owned <Self > { +assert! (bql_locked ()); +// 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 >()) + } + } +} +/// Trait for methods exposed by the Object class. The methods can be /// called on all objects that have the trait `IsA<Object>`. ///
@@ -757,4 +775,5 @@ fn debug_fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { } } +impl <T >ObjectClassMethods for T where T :IsA <Object > {}impl <R :ObjectDeref >ObjectMethods for R where R ::Target :IsA <Object > {}
rust/qemu-api/tests/tests.rs +11 -19
@@ -3,8 +3,7 @@// SPDX-License-Identifier: GPL-2.0-or-later use std::{ - ffi::CStr , - os::raw::c_void, + ffi::{c_void,CStr }, ptr::{addr_of, addr_of_mut}, };
@@ -132,22 +131,16 @@ fn init_qom() {/// Create and immediately drop an instance. fn test_object_new () {init_qom (); -unsafe { -object_unref (object_new (DummyState ::TYPE_NAME .as_ptr ()).cast ()); -object_unref (object_new (DummyChildState ::TYPE_NAME .as_ptr ()).cast ()); - } +drop (DummyState ::new ()); +drop (DummyChildState ::new ()); }#[test] /// Try invoking a method on an object. fn test_typename () {init_qom (); -let p: *mut DummyState =unsafe {object_new (DummyState ::TYPE_NAME .as_ptr ()).cast () }; -let p_ref: &DummyState =unsafe { &*p }; -assert_eq! (p_ref.typename (),"dummy" ); -unsafe { -object_unref (p_ref.as_object_mut_ptr ().cast ::<c_void >()); - } +let p =DummyState ::new (); +assert_eq! (p.typename (),"dummy" ); }// a note on all "cast" tests: usually, especially for downcasts the desired
@@ -162,24 +155,23 @@ fn test_typename() {/// Test casts on shared references. fn test_cast () {init_qom (); -let p: *mut DummyState =unsafe {object_new (DummyState ::TYPE_NAME .as_ptr ()).cast () }; +let p =DummyState ::new (); +let p_ptr: *mut DummyState =unsafe { p.as_mut_ptr () }; +let p_ref: &mut DummyState =unsafe { &mut *p_ptr }; -let p_ref: &DummyState =unsafe { &*p };let obj_ref: &Object = p_ref.upcast (); -assert_eq! (addr_of! (*obj_ref), p.cast ()); +assert_eq! (addr_of! (*obj_ref), p_ptr.cast ());let sbd_ref:Option <&SysBusDevice > = obj_ref.dynamic_cast ();assert! (sbd_ref.is_none ());let dev_ref:Option <&DeviceState > = obj_ref.downcast (); -assert_eq! (addr_of! (*dev_ref.unwrap ()), p.cast ()); +assert_eq! (addr_of! (*dev_ref.unwrap ()), p_ptr.cast ());// SAFETY: the cast is wrong, but the value is only used for comparison unsafe {let sbd_ref: &SysBusDevice = obj_ref.unsafe_cast (); -assert_eq! (addr_of! (*sbd_ref), p.cast ()); - -object_unref (p_ref.as_object_mut_ptr ().cast ::<c_void >()); +assert_eq! (addr_of! (*sbd_ref), p_ptr.cast ()); } }
Signature · 1 line
2.47.1
Re: [PATCH 03/10] rust: qom: add object creation functionality
Quoted 30 lines · Paolo Bonzini
Date: Fri, 17 Jan 2025 20:39:56 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 03/10] rust: qom: add object creation functionality
X-Mailer: git-send-email 2.47.1The basic object lifecycle test can now be implemented using safe code!
Signed-off-by Paolo Bonzini <[email protected]>--- rust/hw/char/pl011/src/device.rs | 13 ++++++++----- rust/qemu-api/src/prelude.rs | 1 + rust/qemu-api/src/qom.rs | 23 +++++++++++++++++++++-- rust/qemu-api/tests/tests.rs | 30 +++++++++++------------------- 4 files changed, 41 insertions(+), 26 deletions(-)rust/hw/char/pl011/src/device.rs +2
-3@@ -690,15 +690,18 @@ pub fn post_load(&self, _version_id: u32) -> Result<(), ()> { irq: qemu_irq, chr: *mut Chardev, ) -> *mut DeviceState { +let pl011 =PL011State ::new ();unsafe { -let dev: *mut DeviceState =qdev_new (PL011State ::TYPE_NAME .as_ptr ()); -let sysbus: *mut SysBusDevice = dev.cast ::<SysBusDevice >(); - +let dev = pl011.as_mut_ptr ::<DeviceState >();qdev_prop_set_chr (dev,c_str! ("chardev" ).as_ptr (), chr);
rust/hw/char/pl011/src/device.rs pub fn post_load(&self, _version_id: u32) -> Result<(), ()> { · line 704
Quoted 10 lines
rust/hw/char/pl011/src/device.rs +6
-2-sysbus_realize_and_unref (sysbus,addr_of_mut! (error_fatal)); + +let sysbus = pl011.as_mut_ptr ::<SysBusDevice >(); +sysbus_realize (sysbus,addr_of_mut! (error_fatal));sysbus_mmio_map (sysbus,0 , addr);sysbus_connect_irq (sysbus,0 , irq); - dev + +// return the pointer, which is kept alive by the QOM tree; drop owned ref + pl011.as_mut_ptr ()
The ref count of Owned<> is decreased on exit, so we need to use sysbus_realize() instead of sysbus_realize_and_unref() to ensure ref count is correct at C side.
Initially, I hesitated here for an entire morning because this didn't seem to conform to the usual usage of sysbus_realize_and_unref() (or, further, qdev_realize_and_unref()).
But now I realize that qdev_realize() is used for embedded objects, while qdev_realize_and_unref() is used for non-embedded cases. Therefore, moving forward, perhaps qdev_realize_and_unref() should not exist on the Rust side.
Owned<> will automatically drop and thus automatically unref, while Child<> will not unref. Based on this consideration, I am now convincing myself that this change (using sysbus_realize()) is reasonable. :-)
In the future, maybe we need some wrappers on qdev_realize()/sysbus_realize().
rust/hw/char/pl011/src/device.rs pub fn post_load(&self, _version_id: u32) -> Result<(), ()> { · line 706
Quoted 2 lines
rust/hw/char/pl011/src/device.rs +0
-0} }
Overall, still fine for me,
Re: [PATCH 03/10] rust: qom: add object creation functionality
Quoted 4 lines · Zhao Liu
The ref count of Owned<> is decreased on exit, so we need to use
sysbus_realize()instead ofsysbus_realize_and_unref()to ensure ref count is correct at C side.
Quoted 8 lines
Initially, I hesitated here for an entire morning because this didn't seem to conform to the usual usage of
sysbus_realize_and_unref()(or, further,qdev_realize_and_unref()).But now I realize that
qdev_realize()is used for embedded objects, whileqdev_realize_and_unref()is used for non-embedded cases. Therefore, moving forward, perhapsqdev_realize_and_unref()should not exist on the Rust side.
Correct, all unref() operations are handled implicitly by the Drop implementation of Owned<>
Quoted 2 lines
Owned<> will automatically drop and thus automatically unref, while Child<> will not unref.
No, Child<> will also unref. The point of Child<> is to prolong the life of the child object, so that it dies after instance_finalize instead() of dying during object_property_del_all(). In C that has to be done manually (as is the case in the clock creation functions), in Rust it will be enforced by the type system.
Quoted 1 line
In the future, maybe we need some wrappers on qdev_realize()/sysbus_realize().
Yep, I'll add a conversion of pl011_create to safe Rust to clarify the rules around usage of Owned<>.
Paolo
PATCH 4/10 rust: callbacks: allow passing optional callbacks as ()
In reply to Paolo BonziniIn some cases, callbacks are optional. Using "Some(function)" and "None" does not work well, because when someone writes "None" the compiler does not know what to use for "F" in "Option<F>".
Therefore, adopt () to mean a "null" callback. It is possible to enforce that a callback is valid by adding a "let _: () = F::ASSERT_IS_SOME" before the invocation of F::call.
--- rust/qemu-api/src/callbacks.rs | 97 ++++++++++++++++++++++++++++++++++ 1 file changed, 97 insertions(+)
rust/qemu-api/src/callbacks.rs +97 -0
@@ -79,6 +79,31 @@/// call_it(&move |_| String::from(x), "hello workd"); /// ``` /// +/// `()` can be used to indicate "no function": +/// +/// ``` +/// # use qemu_api::callbacks::FnCall; +/// fn optional<F: for<'a> FnCall<(&'a str,), String>>(_f: &F, s: &str) -> Option<String> { +/// if F::IS_SOME { +/// Some(F::call((s,))) +/// } else { +/// None +/// } +/// } +/// +/// assert!(optional(&(), "hello world").is_none()); +/// ``` +/// +/// Invoking `F::call` will then be a run-time error. +/// +/// ```should_panic +/// # use qemu_api::callbacks::FnCall; +/// # fn call_it<F: for<'a> FnCall<(&'a str,), String>>(_f: &F, s: &str) -> String { +/// # F::call((s,)) +/// # } +/// let s: String = call_it(&(), "hello world"); // panics +/// ``` +/// /// # Safety /// /// Because `Self` is a zero-sized type, all instances of the type are
@@ -93,10 +118,70 @@ pub unsafe trait FnCall<Args, R = ()>: 'static + Sync + Sized {/// Rust 1.79.0+. const ASSERT_ZERO_SIZED : () = {assert! (mem::size_of ::<Self >() ==0 ) }; +/// Referring to this constant asserts that the `Self` type is an actual +/// function type, which can be used to catch incorrect use of `()` +/// at compile time. +/// +/// # Examples +/// +/// ```compile_fail +/// # use qemu_api::callbacks::FnCall; +/// fn call_it<F: for<'a> FnCall<(&'a str,), String>>(_f: &F, s: &str) -> String { +/// let _: () = F::ASSERT_IS_SOME; +/// F::call((s,)) +/// } +/// +/// let s: String = call_it((), "hello world"); // does not compile +/// ``` +/// +/// Note that this use more simply `const { assert!(F::IS_SOME) }` in +/// Rust 1.79.0 or newer. +const ASSERT_IS_SOME : () = {assert! (Self ::IS_SOME ) }; + +/// `true` if `Self` is an actual function type and not `()`. +/// +/// # Examples +/// +/// You can use `IS_SOME` to catch this at compile time: +/// +/// ```compile_fail +/// # use qemu_api::callbacks::FnCall; +/// fn call_it<F: for<'a> FnCall<(&'a str,), String>>(_f: &F, s: &str) -> String { +/// const { assert!(F::IS_SOME) } +/// F::call((s,)) +/// } +/// +/// let s: String = call_it((), "hello world"); // does not compile +/// ``` +const IS_SOME :bool ; + +/// `false` if `Self` is an actual function type, `true` if it is `()`. +fn is_none () ->bool { + !Self ::IS_SOME + } + +/// `true` if `Self` is an actual function type, `false` if it is `()`. +fn is_some () ->bool { +Self ::IS_SOME + } +/// Call the function with the arguments in args. fn call (a:Args ) ->R ; } +/// `()` acts as a "null" callback. Using `()` and `function` is nicer +/// than `None` and `Some(function)`, because the compiler is unable to +/// infer the type of just `None`. Therefore, the trait itself acts as the +/// option type, with functions [`FnCall::is_some`] and [`FnCall::is_none`]. +unsafe impl <Args ,R >FnCall <Args ,R >for () { +const IS_SOME :bool =false ; + +/// Call the function with the arguments in args. +fn call (_a:Args ) ->R { +panic! ("callback not specified" ) + } +} +macro_rules! impl_call { ($($args:ident,)* ) => (// SAFETY: because each function is treated as a separate type,
@@ -106,6 +191,8 @@ unsafe impl<F, $($args,)* R> FnCall<($($args,)*), R> for F where F: 'static + Sync + Sized + Fn($($args, )*) -> R, { +const IS_SOME :bool =true ; +#[inline(always)] fn call(a: ($($args,)*)) -> R {let _: () =Self ::ASSERT_ZERO_SIZED ;
@@ -141,4 +228,14 @@ fn do_test_call<'a, F: FnCall<(&'a str,), String>>(_f: &F) -> String {fn test_call () {assert_eq! (do_test_call (&str ::to_owned),"hello world" ) } + +// The `_f` parameter is unused but it helps the compiler infer `F`. +fn do_test_is_some <'a,F :FnCall <(&'astr ,),String >>(_f: &F ) { +assert! (F ::is_some ()); + } + +#[test] +fn test_is_some () { +do_test_is_some (&str::to_owned); + } }
Signature · 1 line
2.47.1
Re: [PATCH 04/10] rust: callbacks: allow passing optional callbacks as ()
Quoted 10 lines
Date: Fri, 17 Jan 2025 20:39:57 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 04/10] rust: callbacks: allow passing optional callbacks as
()
X-Mailer: git-send-email 2.47.1In some cases, callbacks are optional. Using "Some(function)" and "None" does not work well, because when someone writes "None" the compiler does not know what to use for "F" in "Option<F>".
Quoted 8 lines
Therefore, adopt () to mean a "null" callback. It is possible to enforce that a callback is valid by adding a "let _: () =
F::ASSERT_IS_SOME" before the invocation ofF::call.Signed-off-by Paolo Bonzini <[email protected]>--- rust/qemu-api/src/callbacks.rs | 97 ++++++++++++++++++++++++++++++++++ 1 file changed, 97 insertions(+)
Awesome trick.
rust/qemu-api/src/callbacks.rs pub unsafe trait FnCall<Args, R = ()>: 'static + Sync + Sized { · line 123
Quoted 3 lines
rust/qemu-api/src/callbacks.rs +3
-0+/// Referring to this constant asserts that the `Self` type is an actual +/// function type, which can be used to catch incorrect use of `()` +/// at compile time.
An extra whitespace.
PATCH 5/10 rust: qdev: add clock creation
In reply to Paolo BonziniAdd a Rust version of qdev_init_clock_in, which can be used in instance_init. There are a couple differences with the C version:
- in Rust the object keeps its own reference to the clock (in addition to the one embedded in the NamedClockList), and the reference is dropped automatically by instance_finalize(); this is encoded in the signature of DeviceClassMethods::init_clock_in, which makes the lifetime of the clock independent of that of the object it holds. This goes unnoticed in the C version and is due to the existence of aliases.
- also, anything that happens during instance_init uses the pinned_init framework to operate on a partially initialized object, and is done through class methods (i.e. through DeviceClassMethods rather than DeviceMethods) because the device does not exist yet. Therefore, Rust code *must* create clocks from instance_init, which is stricter than C.
--- rust/hw/char/pl011/src/device.rs | 28 +++++------- rust/qemu-api/src/prelude.rs | 2 + rust/qemu-api/src/qdev.rs | 76 ++++++++++++++++++++++++++++++-- rust/qemu-api/src/vmstate.rs | 4 +- 4 files changed, 87 insertions(+), 23 deletions(-)
rust/hw/char/pl011/src/device.rs +10 -18
@@ -13,8 +13,8 @@ c_str, impl_vmstate_forward, irq::InterruptSource, prelude::*, - qdev::DeviceImpl, - qom::{ClassInitImpl, ObjectImpl, ParentField}, + qdev::{Clock, ClockEvent, DeviceImpl}, + qom::{ClassInitImpl, ObjectImpl, Owned, ParentField}, };use crate ::{
@@ -123,7 +123,7 @@ pub struct PL011State {#[doc(alias = "irq" )] pub interrupts: [InterruptSource; IRQMASK.len()],#[doc(alias = "clk" )] - pub clock: NonNull<Clock>, + pub clock: Owned<Clock>,#[doc(alias = "migrate_clk" )] pub migrate_clock: bool, }
@@ -487,8 +487,6 @@ impl PL011State {/// location/instance. All its fields are expected to hold unitialized /// values with the sole exception of `parent_obj`. unsafe fn init (&mut self) { -const CLK_NAME : &CStr =c_str! ("clk" ); -// SAFETY: // // self and self.iomem are guaranteed to be valid at this point since callers
@@ -508,22 +506,16 @@ unsafe fn init(&mut self) {// SAFETY: // -// self.clock is not initialized at this point; but since `NonNull<_>` is Copy, -// we can overwrite the undefined value without side effects. This is +// self.clock is not initialized at this point; but since `NonNull<_>` is +// not Drop, we can overwrite the undefined value without side effects. This is // safe since all PL011State instances are created by QOM code which // calls this function to initialize the fields; therefore no code is // able to access an invalid self.clock value. -unsafe { -let dev: &mut DeviceState = self.upcast_mut (); - self.clock =NonNull ::new (qdev_init_clock_in ( - dev, -CLK_NAME .as_ptr (), -None ,/* pl011_clock_update */ -addr_of_mut! (*self).cast ::<c_void >(), -ClockEvent ::ClockUpdate .0 , - )) - .unwrap (); - } + self.clock = self.init_clock_in ("clk" , &Self ::clock_update,ClockEvent ::ClockUpdate ); + } + +const fn clock_update (&self, _event:ClockEvent ) { +/* pl011_trace_baudrate_change(s); */ }fn post_init (&self) {
rust/qemu-api/src/prelude.rs +2 -0
@@ -7,6 +7,8 @@pub use crate ::cell::BqlCell ;pub use crate ::cell::BqlRefCell ; +pub use crate ::qdev::DeviceMethods ; +pub use crate ::qom::IsA ;pub use crate ::qom::Object ;pub use crate ::qom::ObjectCast ;
rust/qemu-api/src/qdev.rs +73 -3
90 lines not on this page · raw message
rust/qemu-api/src/vmstate.rs +2 -2
@@ -470,11 +470,11 @@ macro_rules! vmstate_clock { $crate::assert_field_type!( $struct_name, $field_name, - core::ptr::NonNull <$crate ::bindings::Clock > + $crate ::qom::Owned <$crate ::bindings::Clock > ); $crate::offset_of!($struct_name, $field_name) }, - size: ::core::mem::size_of::<*const $crate::bindings::Clock>(), + size: ::core::mem::size_of::<*const $crate::qdev::Clock>(), flags: VMStateFlags(VMStateFlags::VMS_STRUCT.0 | VMStateFlags::VMS_POINTER.0), vmsd: unsafe { ::core::ptr::addr_of!($crate::bindings::vmstate_clock) }, ..$crate::zeroable::Zeroable ::ZERO
Signature · 1 line
2.47.1
Re: [PATCH 05/10] rust: qdev: add clock creation
rust/hw/char/pl011/src/device.rs unsafe fn init(&mut self) { · line 509
Quoted 5 lines
// SAFETY: //rust/hw/char/pl011/src/device.rs +1
-2-// self.clock is not initialized at this point; but since `NonNull<_>` is Copy, -// we can overwrite the undefined value without side effects. This is +// self.clock is not initialized at this point; but since `NonNull<_>` is
s/NonNull<_>/Owned<_>/
Quoted 8 lines
rust/hw/char/pl011/src/device.rs +1
-4+// not Drop, we can overwrite the undefined value without side effects. This is // safe since all PL011State instances are created by QOM code which // calls this function to initialize the fields; therefore no code is // able to access an invalid self.clock value. - unsafe { - let dev: &mut DeviceState = self.upcast_mut(); - self.clock = NonNull::new(qdev_init_clock_in( - dev,
rust/hw/char/pl011/src/device.rs unsafe fn init(&mut self) { · line 516
Quoted 10 lines
rust/hw/char/pl011/src/device.rs +3
-7- CLK_NAME.as_ptr(), - None, /* pl011_clock_update */ - addr_of_mut!(*self).cast::<c_void>(), - ClockEvent::ClockUpdate.0, - )) - .unwrap (); - } + self.clock = self.init_clock_in ("clk" , &Self ::clock_update,ClockEvent ::ClockUpdate ); + } +
PATCH 6/10 rust: qom: allow initializing interface vtables
In reply to Paolo BonziniUnlike regular classes, interface vtables can only be obtained via object_class_dynamic_cast. Provide a wrapper that allows accessing the vtable and pass it to a ClassInitImpl implementation, for example ClassInitImpl<ResettableClass>.
--- rust/qemu-api/src/prelude.rs | 1 + rust/qemu-api/src/qom.rs | 45 ++++++++++++++++++++++++++++++++++-- 2 files changed, 44 insertions(+), 2 deletions(-)
rust/qemu-api/src/prelude.rs +1 -0
@@ -9,6 +9,7 @@pub use crate ::qdev::DeviceMethods ; +pub use crate ::qom::InterfaceType ;pub use crate ::qom::IsA ;pub use crate ::qom::Object ;pub use crate ::qom::ObjectCast ;
rust/qemu-api/src/qom.rs +43 -2
57 lines not on this page · raw message
Signature · 1 line
2.47.1
Re: [PATCH 06/10] rust: qom: allow initializing interface vtables
Quoted 10 lines · Paolo Bonzini
Date: Fri, 17 Jan 2025 20:39:59 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 06/10] rust: qom: allow initializing interface vtables
X-Mailer: git-send-email 2.47.1Unlike regular classes, interface vtables can only be obtained via
object_class_dynamic_cast. Provide a wrapper that allows accessing the vtable and pass it to a ClassInitImpl implementation, for example ClassInitImpl<ResettableClass>.
Quoted 6 lines
Signed-off-by Paolo Bonzini <[email protected]>--- rust/qemu-api/src/prelude.rs | 1 + rust/qemu-api/src/qom.rs | 45 ++++++++++++++++++++++++++++++++++-- 2 files changed, 44 insertions(+), 2 deletions(-)
PATCH 7/10 rust: qdev: make ObjectImpl a supertrait of DeviceImpl
In reply to Paolo BonziniIn practice it has to be implemented always in order to access an implementation of ClassInitImpl<ObjectClass>. Make the relationship explicit in the code.
--- rust/qemu-api/src/qdev.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
rust/qemu-api/src/qdev.rs +1 -1
@@ -21,7 +21,7 @@ };/// Trait providing the contents of [`DeviceClass`]. -pub trait DeviceImpl { +pub trait DeviceImpl :ObjectImpl {/// _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).
Signature · 1 line
2.47.1
Re: [PATCH 07/10] rust: qdev: make ObjectImpl a supertrait of DeviceImpl
Quoted 6 lines · Paolo Bonzini
Date: Fri, 17 Jan 2025 20:40:00 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 07/10] rust: qdev: make ObjectImpl a supertrait of
DeviceImpl
X-Mailer: git-send-email 2.47.1
Quoted 9 lines
In practice it has to be implemented always in order to access an implementation of ClassInitImpl<ObjectClass>. Make the relationship explicit in the code.
Signed-off-by Paolo Bonzini <[email protected]>--- rust/qemu-api/src/qdev.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
Re: [PATCH 07/10] rust: qdev: make ObjectImpl a supertrait of DeviceImpl
In reply to Paolo BonziniQuoted 8 lines · Paolo Bonzini
In practice it has to be implemented always in order to access an implementation of ClassInitImpl<ObjectClass>. Make the relationship explicit in the code.
Signed-off-by Paolo Bonzini <[email protected]>--- rust/qemu-api/src/qdev.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
PATCH 8/10 rust: qdev: switch from legacy reset to Resettable
In reply to Paolo Bonzini--- meson.build | 1 + rust/hw/char/pl011/src/device.rs | 10 ++- rust/qemu-api/src/qdev.rs | 116 ++++++++++++++++++++++++------- rust/qemu-api/tests/tests.rs | 5 +- 4 files changed, 102 insertions(+), 30 deletions(-)
meson.build +1 -0
@@ -4065,6 +4065,7 @@ if have_rust 'MigrationPriority', 'QEMUChrEvent', 'QEMUClockType', + 'ResetType', 'device_endian', 'module_init_type', ]
rust/hw/char/pl011/src/device.rs +7 -3
@@ -13,7 +13,7 @@ c_str, impl_vmstate_forward, irq::InterruptSource, prelude::*, - qdev::{Clock, ClockEvent, DeviceImpl}, + qdev::{Clock, ClockEvent, DeviceImpl, ResettablePhasesImpl, ResetType}, qom::{ClassInitImpl, ObjectImpl, Owned, ParentField}, };
@@ -164,7 +164,10 @@ fn vmsd() -> Option<&'static VMStateDescription> {Some (&device_class::VMSTATE_PL011 ) }const REALIZE :Option <fn (&mut Self )> =Some (Self ::realize); -const RESET :Option <fn (&Self )> =Some (Self ::reset); +} + +impl ResettablePhasesImpl for PL011State { +const HOLD :Option <fn (&Self ,ResetType )> =Some (Self ::reset_hold); }impl PL011Registers {
@@ -601,7 +604,7 @@ pub fn realize(&mut self) { } } -pub fn reset (&self) { +pub fn reset_hold (&self, _type:ResetType ) { self.regs.borrow_mut ().reset (); }
@@ -723,3 +726,4 @@ impl ObjectImpl for PL011Luminary { }impl DeviceImpl for PL011Luminary {} +impl ResettablePhasesImpl for PL011Luminary {}
rust/qemu-api/src/qdev.rs +90 -26
158 lines not on this page · raw message
rust/qemu-api/tests/tests.rs +4 -1
@@ -13,7 +13,7 @@ cell::{self, BqlCell}, declare_properties, define_property, prelude::*, - qdev::{DeviceClass, DeviceImpl, DeviceState, Property}, + qdev::{DeviceClass, DeviceImpl, DeviceState, Property, ResettablePhasesImpl}, qom::{ClassInitImpl, ObjectImpl, ParentField}, vmstate::VMStateDescription, zeroable::Zeroable,
@@ -61,6 +61,8 @@ impl ObjectImpl for DummyState {const ABSTRACT :bool =false ; } +impl ResettablePhasesImpl for DummyState {} +impl DeviceImpl for DummyState {fn properties () -> &'static [Property ] { &DUMMY_PROPERTIES
@@ -101,6 +103,7 @@ impl ObjectImpl for DummyChildState {const ABSTRACT :bool =false ; } +impl ResettablePhasesImpl for DummyChildState {}impl DeviceImpl for DummyChildState {}impl ClassInitImpl <DummyClass >for DummyChildState {
Signature · 1 line
2.47.1
Re: [PATCH 08/10] rust: qdev: switch from legacy reset to Resettable
Review
Quoted 12 lines
(quoted diff) +12
-0+/// Trait providing the contents of [`ResettablePhases`]. +pub trait ResettablePhasesImpl { + /// If not None, this is called when the object enters reset. It + /// can reset local state of the object, but it must not do anything that + /// has a side-effect on other objects, such as raising or lowering a + /// [`qemu_irq`] line or reading or writing guest memory. It takes the + /// reset's type as argument. + const ENTER: Option<fn(&Self, ResetType)> = None; + + /// If not None, this is called when the object for entry into reset, once + /// every object in the system which is being reset has had its + /// @phases.enter method called. At this point devices can do actions
Maybe s/@phases.enter/ResettablePhasesImpl::ENTER/?
Quoted 10 lines
(quoted diff) +10
-0+ /// that affect other objects. + /// + /// If in doubt, implement this method. + const HOLD: Option<fn(&Self, ResetType)> = None; + + /// If not None, this phase is called when the object leaves the reset + /// state. Actions affecting other objects are permitted. + const EXIT: Option<fn(&Self, ResetType)> = None; +} +
...
Review
Quoted 4 lines
impl<T> ClassInitImpl<DeviceClass> for T
where(quoted diff) +1
-1- T: ClassInitImpl<ObjectClass> + DeviceImpl, + T: ClassInitImpl<ObjectClass> + ClassInitImpl<ResettableClass> + DeviceImpl,
This constraint requires each device to explicitly implement ResettablePhasesImpl, even the device doesn't want to do anything for reset.
So what about the following changes:
* Define 3-Phases methods in DeviceImpl.
* Implement ResettablePhasesImpl for all devices by passing their 3-Phases methods to ResettablePhasesImpl's.
Then device doesn't need to implement this reset trait if unnecessary.
For example:
rust/qemu-api/src/qdev.rs +13 -1
@@ -84,7 +84,7 @@ pub trait ResettablePhasesImpl { }/// Trait providing the contents of [`DeviceClass`]. -pub trait DeviceImpl :ObjectImpl +ResettablePhasesImpl { +pub trait DeviceImpl :ObjectImpl {/// _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).
@@ -106,6 +106,18 @@ fn properties() -> &'static [Property] {fn vmsd () ->Option <&'staticVMStateDescription > {None } + +const RESET_ENTER :Option <fn (&Self ,ResetType )> =None ; +const RESET_HOLD :Option <fn (&Self ,ResetType )> =None ; +const RESET_EXIT :Option <fn (&Self ,ResetType )> =None ; +} + +impl <T >ResettablePhasesImpl for T +where T :DeviceImpl +{ +const ENTER :Option <fn (&Self ,ResetType )> =T ::RESET_ENTER ; +const HOLD :Option <fn (&Self ,ResetType )> =T ::RESET_HOLD ; +const EXIT :Option <fn (&Self ,ResetType )> =T ::RESET_EXIT ; }/// # Safety
---
Though this way add duplicate methods, it reduces the burden on the device developer.
Regards,
Zhao
Quoted 21 lines
{ fn class_init(dc: &mut DeviceClass) { if <T as DeviceImpl>::REALIZE.is_some() { dc.realize = Some(rust_realize_fn::<T>); }(quoted diff) +1
-5- if <T as DeviceImpl>::RESET.is_some() { - unsafe { - bindings::device_class_set_legacy_reset(dc, Some(rust_reset_fn::<T>)); - } - } if let Some(vmsd) = <T as DeviceImpl>::vmsd() { dc.vmsd = vmsd; }@@ -99,6 +162,7 @@ fn class_init(dc: &mut DeviceClass) { } } + ResettableClass::interface_init::<T, DeviceState>(dc); <T as ClassInitImpl<ObjectClass>>::class_init(&mut dc.parent_class); } }
Re: [PATCH 08/10] rust: qdev: switch from legacy reset to Resettable
Quoted 5 lines · Zhao Liu
Review
Quoted 3 lines
(quoted diff) +3
-0+ /// If not None, this is called when the object for entry into reset, once + /// every object in the system which is being reset has had its + /// @phases.enter method called. At this point devices can do actionsMaybe s/@phases.enter/ResettablePhasesImpl::ENTER/?
Yes.
Quoted 2 lines
This constraint requires each device to explicitly implement ResettablePhasesImpl, even the device doesn't want to do anything for reset.
Yes, that's true but it's just a line of code. Almost all devices *will* want to do
something with reset.
Quoted 17 lines
So what about the following changes:
* Define 3-Phases methods in DeviceImpl.
* Implement ResettablePhasesImpl for all devices by passing their 3-Phases methods to ResettablePhasesImpl's.rust/qemu-api/src/qdev.rs +6
-1+impl <T >ResettablePhasesImpl for T +where T :DeviceImpl +{ +const ENTER :Option <fn (&Self ,ResetType )> =T ::RESET_ENTER ; +const HOLD :Option <fn (&Self ,ResetType )> =T ::RESET_HOLD ; +const EXIT :Option <fn (&Self ,ResetType )> =T ::RESET_EXIT ; }/// # Safety ---
Quoted 3 lines
Then device doesn't need to implement this reset trait if unnecessary. Though this way add duplicate methods, it reduces the burden on the device developer.
For now I prefer to make things homogeneous... this way if someone has to copy the code into a wrapper for a new interface they don't have to wonder about small differences.
(This by the way will also be a reason to use function pointers for character devices as well, instead of the trait approach that I used in https://lists.nongnu.org/archive/html/qemu-rust/2024-12/msg00006.html).
Paolo
Re: [PATCH 08/10] rust: qdev: switch from legacy reset to Resettable
Quoted 3 lines
For now I prefer to make things homogeneous... this way if someone has to copy the code into a wrapper for a new interface they don't have to wonder about small differences.
Yes.
Quoted 4 lines
(This by the way will also be a reason to use function pointers for character devices as well, instead of the trait approach that I used in https://lists.nongnu.org/archive/html/qemu-rust/2024-12/msg00006.html).
Got it.
Thanks,
Zhao
Re: [PATCH 08/10] rust: qdev: switch from legacy reset to Resettable
In reply to Paolo BonziniQuoted 5 lines · Paolo Bonzini
Date: Fri, 17 Jan 2025 20:40:01 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 08/10] rust: qdev: switch from legacy reset to Resettable
X-Mailer: git-send-email 2.47.1
Quoted 8 lines
Signed-off-by Paolo Bonzini <[email protected]>--- meson.build | 1 + rust/hw/char/pl011/src/device.rs | 10 ++- rust/qemu-api/src/qdev.rs | 116 ++++++++++++++++++++++++------- rust/qemu-api/tests/tests.rs | 5 +- 4 files changed, 102 insertions(+), 30 deletions(-)
Add my R/b tag,
PATCH 9/10 rust: bindings: add Sync markers to types referred to by MemoryRegionOps
In reply to Paolo BonziniThis is needed for the MemoryRegionOps<T> to be declared as static; Rust requires static elements to be Sync.
--- rust/qemu-api/src/bindings.rs | 19 ++++++++++++++++++- rust/qemu-api/src/irq.rs | 3 +++ 2 files changed, 21 insertions(+), 1 deletion(-)
rust/qemu-api/src/bindings.rs +18 -1
@@ -21,7 +21,24 @@#[cfg(not( MESON ))] include! (concat! (env! ("OUT_DIR" ),"/bindings.inc.rs" )); -unsafe impl Send for Property {} +// 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 Sync for BusState {} +unsafe impl Sync for CharBackend {} +unsafe impl Sync for Chardev {} +unsafe impl Sync for Clock {} +unsafe impl Sync for DeviceState {} +unsafe impl Sync for MemoryRegion {} +unsafe impl Sync for ObjectClass {} +unsafe impl Sync for Object {} +unsafe impl Sync for SysBusDevice {} + +// SAFETY: this is a pure data struct +unsafe impl Sync for CoalescedMemoryRange {} + +// SAFETY: these are constants and vtables; the Sync requirements are deferred +// to the unsafe callbacks that they contain +unsafe impl Sync for MemoryRegionOps {}unsafe impl Sync for Property {}unsafe impl Sync for TypeInfo {}unsafe impl Sync for VMStateDescription {}
rust/qemu-api/src/irq.rs +3 -0
@@ -43,6 +43,9 @@ pub struct InterruptSource<T = bool> _marker: PhantomData<T>, } +// SAFETY: the implementation asserts via `BqlCell` that the BQL is taken +unsafe impl <T >Sync for InterruptSource <T >where c_int :From <T > {} +impl InterruptSource <bool > {/// Send a low (`false`) value to the interrupt sink. pub fn lower (&self) {
Signature · 1 line
2.47.1
Re: [PATCH 09/10] rust: bindings: add Sync markers to types referred to by MemoryRegionOps
Quoted 6 lines · Paolo Bonzini
Date: Fri, 17 Jan 2025 20:40:02 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 09/10] rust: bindings: add Sync markers to types referred
to by MemoryRegionOps
X-Mailer: git-send-email 2.47.1
Quoted 8 lines
This is needed for the MemoryRegionOps<T> to be declared as static; Rust requires static elements to be Sync.
Signed-off-by Paolo Bonzini <[email protected]>--- rust/qemu-api/src/bindings.rs | 19 ++++++++++++++++++- rust/qemu-api/src/irq.rs | 3 +++ 2 files changed, 21 insertions(+), 1 deletion(-)
rust/qemu-api/src/bindings.rs line 24
Quoted 9 lines
rust/qemu-api/src/bindings.rs +0
-1@@ -21,7 +21,24 @@#[cfg(not( MESON ))] include! (concat! (env! ("OUT_DIR" ),"/bindings.inc.rs" )); -unsafe impl Send for Property {}
I guess this is a rebase mistake since latest rust-next drops this change :-).
rust/qemu-api/src/bindings.rs line 26
Quoted 3 lines
rust/qemu-api/src/bindings.rs +3
-0+// 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 Sync for BusState {}
We haven't used BusState but it's fine, as the basic support, and after all bindings file has this type.
PATCH 10/10 rust: bindings for MemoryRegionOps
In reply to Paolo Bonzini--- rust/hw/char/pl011/src/device.rs | 43 +++--- rust/hw/char/pl011/src/lib.rs | 1 - rust/hw/char/pl011/src/memory_ops.rs | 36 ----- rust/qemu-api/meson.build | 1 + rust/qemu-api/src/lib.rs | 1 + rust/qemu-api/src/memory.rs | 191 +++++++++++++++++++++++++++ rust/qemu-api/src/sysbus.rs | 7 +- rust/qemu-api/src/zeroable.rs | 12 ++ 8 files changed, 234 insertions(+), 58 deletions(-) delete mode 100644 rust/hw/char/pl011/src/memory_ops.rs create mode 100644 rust/qemu-api/src/memory.rs
rust/hw/char/pl011/src/device.rs +25 -18
@@ -2,7 +2,7 @@// Author(s): Manos Pitsidianakis <[email protected]> // SPDX-License-Identifier: GPL-2.0-or-later -use core::ptr::{addr_of_mut,NonNull }; +use core::ptr::{addr_of, addr_of_mut,NonNull };use std::{ ffi::CStr , os::raw::{c_int, c_void},
@@ -12,14 +12,14 @@ bindings::{self, *}, c_str, impl_vmstate_forward, irq::InterruptSource, + memory::{hwaddr, MemoryRegion, MemoryRegionOps, MemoryRegionOpsBuilder}, prelude::*, - qdev::{Clock, ClockEvent, DeviceImpl, ResettablePhasesImpl, ResetType}, + qdev::{Clock, ClockEvent, DeviceImpl, ResetType, ResettablePhasesImpl}, qom::{ClassInitImpl, ObjectImpl, Owned, ParentField}, };use crate ::{ device_class, - memory_ops::PL011_OPS , registers::{self,Interrupt },RegisterOffset , };
@@ -490,20 +490,24 @@ impl PL011State {/// location/instance. All its fields are expected to hold unitialized /// values with the sole exception of `parent_obj`. unsafe fn init (&mut self) { +static PL011_OPS :MemoryRegionOps <PL011State > =MemoryRegionOpsBuilder ::<PL011State >::new () + .read (&PL011State ::read) + .write (&PL011State ::write) + .native_endian () + .impl_sizes (4 ,4 ) + .build (); +// SAFETY: // // self and self.iomem are guaranteed to be valid at this point since callers // must make sure the `self` reference is valid. -unsafe { -memory_region_init_io ( -addr_of_mut! (self.iomem), -addr_of_mut! (*self).cast ::<Object >(), - &PL011_OPS , -addr_of_mut! (*self).cast ::<c_void >(), -Self ::TYPE_NAME .as_ptr (), -0x1000 , - ); - } +MemoryRegion ::init_io ( +unsafe { &mut *addr_of_mut! (self.iomem) }, +addr_of_mut! (*self), + &PL011_OPS , +"pl011" , +0x1000 , + ); self.regs =Default ::default ();
@@ -528,8 +532,7 @@ fn post_init(&self) { } } -#[allow(clippy::needless_pass_by_ref_mut)] -pub fn read (&mut self, offset:hwaddr , _size:u32 ) ->u64 { +pub fn read (&self, offset:hwaddr , _size:u32 ) ->u64 {let (update_irq, result) =match RegisterOffset ::try_from (offset) {Err (v)if (0x3f8 ..0x400 ).contains (&(v >>2 )) => {let device_id = self.get_class ().device_id;
@@ -544,16 +547,20 @@ pub fn read(&mut self, offset: hwaddr, _size: u32) -> u64 {if update_irq { self.update ();unsafe { -qemu_chr_fe_accept_input (&mut self.char_backend); +qemu_chr_fe_accept_input (addr_of! (self.char_backend)as *mut _ ); } } result.into () } -pub fn write (&mut self, offset:hwaddr , value:u64 ) { +pub fn write (&self, offset:hwaddr , value:u64 , _size:u32 ) {let mut update_irq =false ;if let Ok (field) =RegisterOffset ::try_from (offset) { - update_irq = self.regs.borrow_mut ().write (field, valueas u32 , &mut self.char_backend); + update_irq = self.regs.borrow_mut ().write ( + field, + valueas u32 , +addr_of! (self.char_backend)as *mut _ , + ); }else {eprintln! ("write bad offset {offset} value {value}" ); }
rust/hw/char/pl011/src/lib.rs +0 -1
@@ -29,7 +29,6 @@mod device;mod device_class; -mod memory_ops;pub use device::pl011_create;
rust/hw/char/pl011/src/memory_ops.rs deleted +0 -36
@@ -1,36 +0,0 @@ -// Copyright 2024, Linaro Limited -// Author(s): Manos Pitsidianakis <[email protected]> -// SPDX-License-Identifier: GPL-2.0-or-later - -use core::ptr::NonNull ; -use std::os::raw::{c_uint, c_void}; - -use qemu_api::{bindings::*, zeroable::Zeroable }; - -use crate ::device::PL011State ; - -pub static PL011_OPS :MemoryRegionOps =MemoryRegionOps { - read:Some (pl011_read), - write:Some (pl011_write), - read_with_attrs:None , - write_with_attrs:None , - endianness: device_endian::DEVICE_NATIVE_ENDIAN , - valid:Zeroable ::ZERO , - impl_:MemoryRegionOps__bindgen_ty_2 { - min_access_size:4 , - max_access_size:4 , - ..Zeroable ::ZERO - }, -}; - -unsafe extern "C" fn pl011_read (opaque: *mut c_void , addr:hwaddr , size:c_uint ) ->u64 { -assert! (!opaque.is_null ()); -let mut state =unsafe {NonNull ::new_unchecked (opaque.cast ::<PL011State >()) }; -unsafe { state.as_mut () }.read (addr, size) -} - -unsafe extern "C" fn pl011_write (opaque: *mut c_void , addr:hwaddr , data:u64 , _size:c_uint ) { -assert! (!opaque.is_null ()); -let mut state =unsafe {NonNull ::new_unchecked (opaque.cast ::<PL011State >()) }; -unsafe { state.as_mut () }.write (addr, data); -}
rust/qemu-api/meson.build +1 -0
@@ -22,6 +22,7 @@ _qemu_api_rs = static_library( 'src/cell.rs', 'src/c_str.rs', 'src/irq.rs', + 'src/memory.rs', 'src/module.rs', 'src/offset_of.rs', 'src/prelude.rs',
rust/qemu-api/src/lib.rs +1 -0
@@ -18,6 +18,7 @@pub mod callbacks;pub mod cell;pub mod irq; +pub mod memory;pub mod module;pub mod offset_of;pub mod qdev;
rust/qemu-api/src/memory.rs new file +191 -0
191 lines not on this page · raw message
rust/qemu-api/src/sysbus.rs +4 -3
@@ -2,7 +2,7 @@// Author(s): Paolo Bonzini <[email protected]> // SPDX-License-Identifier: GPL-2.0-or-later -use std::{ffi::CStr , ptr::addr_of}; +use std::ffi::CStr ;pub use bindings::{SysBusDevice ,SysBusDeviceClass };
@@ -10,6 +10,7 @@ bindings, cell::bql_locked, irq::InterruptSource, + memory::MemoryRegion, prelude::*, qdev::{DeviceClass, DeviceState}, qom::ClassInitImpl,
@@ -42,10 +43,10 @@ pub trait SysBusDeviceMethods: ObjectDeref/// important, since whoever creates the sysbus device will refer to the /// region with a number that corresponds to the order of calls to /// `init_mmio`. -fn init_mmio (&self, iomem: &bindings::MemoryRegion ) { +fn init_mmio (&self, iomem: &MemoryRegion ) {assert! (bql_locked ());unsafe { - bindings::sysbus_init_mmio (self.as_mut_ptr (),addr_of! (*iomem)as *mut _ ); + bindings::sysbus_init_mmio (self.as_mut_ptr (), iomem.as_mut_ptr ()); } }
rust/qemu-api/src/zeroable.rs +12 -0
@@ -99,6 +99,18 @@ unsafe impl Zeroable for crate::bindings::VMStateDescription { }; } +unsafe impl Zeroable for crate ::bindings::MemoryRegionOps { +const ZERO :Self =Self { + read:None , + write:None , + read_with_attrs:None , + write_with_attrs:None , + endianness:crate ::bindings::device_endian::DEVICE_NATIVE_ENDIAN , + valid:Zeroable ::ZERO , + impl_:Zeroable ::ZERO , + }; +} +unsafe impl Zeroable for crate ::bindings::MemoryRegionOps__bindgen_ty_1 {const ZERO :Self =Self { min_access_size:0 ,
Signature · 1 line
2.47.1
Re: [PATCH 10/10] rust: bindings for MemoryRegionOps
Quoted 18 lines · Paolo Bonzini
Date: Fri, 17 Jan 2025 20:40:03 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 10/10] rust: bindings for MemoryRegionOps
X-Mailer: git-send-email 2.47.1Signed-off-by Paolo Bonzini <[email protected]>--- rust/hw/char/pl011/src/device.rs | 43 +++--- rust/hw/char/pl011/src/lib.rs | 1 - rust/hw/char/pl011/src/memory_ops.rs | 36 ----- rust/qemu-api/meson.build | 1 + rust/qemu-api/src/lib.rs | 1 + rust/qemu-api/src/memory.rs | 191 +++++++++++++++++++++++++++ rust/qemu-api/src/sysbus.rs | 7 +- rust/qemu-api/src/zeroable.rs | 12 ++ 8 files changed, 234 insertions(+), 58 deletions(-) delete mode 100644 rust/hw/char/pl011/src/memory_ops.rs create mode 100644 rust/qemu-api/src/memory.rs
...
rust/hw/char/pl011/src/device.rs impl PL011State { · line 499
Quoted 11 lines
rust/hw/char/pl011/src/device.rs +7
-0@@ -490,20 +490,24 @@ impl PL011State {/// location/instance. All its fields are expected to hold unitialized /// values with the sole exception of `parent_obj`. unsafe fn init (&mut self) { +static PL011_OPS :MemoryRegionOps <PL011State > =MemoryRegionOpsBuilder ::<PL011State >::new () + .read (&PL011State ::read) + .write (&PL011State ::write) + .native_endian () + .impl_sizes (4 ,4 ) + .build (); +
Nice design. Everything was done smoothly in one go.
rust/qemu-api/src/memory.rs line 34
Quoted 12 lines
rust/qemu-api/src/memory.rs new file +12
-0+pub struct MemoryRegionOps <T >( + bindings::MemoryRegionOps , +// Note: quite often you'll see PhantomData<fn(&T)> mentioned when discussing +// covariance and contravariance; you don't need any of those to understand +// this usage of PhantomData. Quite simply, MemoryRegionOps<T> *logically* +// holds callbacks that take an argument of type &T, except the type is erased +// before the callback is stored in the bindings::MemoryRegionOps field. +// The argument of PhantomData is a function pointer in order to represent +// that relationship; while that will also provide desirable and safe variance +// for T, variance is not the point but just a consequence. +PhantomData <fn (&T )>, +);
Wow, it can be wrapped like this!
Quoted 5 lines
rust/qemu-api/src/memory.rs new file +5
-0+} + +/// 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.
rust/qemu-api/src/memory.rs line 147
Quoted 10 lines
rust/qemu-api/src/memory.rs new file +10
-0+pub struct MemoryRegion { + inner: bindings::MemoryRegion , + _pin:PhantomPinned , +} + +impl MemoryRegion { +// inline to ensure that it is not included in tests, which only +// link to hwcore and qom. FIXME: inlining is actually the opposite +// of what we want, since this is the type-erased version of the +// init_io function below. Look into splitting the qemu_api crate.
Ah, I didn't understand the issue described in this comment. Why would inlining affect the linking of tests?
Quoted 16 lines
rust/qemu-api/src/memory.rs new file +16
-0+#[inline(always)] +unsafe fn do_init_io ( + slot: *mut bindings::MemoryRegion , + owner: *mut Object , + ops: &'static bindings::MemoryRegionOps , + name: &'staticstr , + size:u64 , + ) { +unsafe { +let cstr =CString ::new (name).unwrap (); +memory_region_init_io ( + slot, + owner.cast ::<Object >(), + ops, + owner.cast ::<c_void >(), + cstr.as_ptr(),
rust/qemu-api/src/memory.rs line 173
Quoted 10 lines
rust/qemu-api/src/memory.rs new file +10
-0+ size, + ); + } + } + +pub fn init_io <T :IsA <Object >>( + &mut self, + owner: *mut T , + ops: &'staticMemoryRegionOps <T >, + name: &'static str,
What about &'static CStr?
Then pl011 could pass c_str!("pl011") or Self::TYPE_NAMSelf::TYPE_NAME.
Otherwise,
Re: [PATCH 10/10] rust: bindings for MemoryRegionOps
Quoted 5 lines · Zhao Liu
Quoted 5 lines
rust/hw/char/pl011/src/device.rs +1
-0@@ -490,20 +490,24 @@ impl PL011State {/// location/instance. All its fields are expected to hold unitialized /// values with the sole exception of `parent_obj`. unsafe fn init (&mut self) { +static PL011_OPS :MemoryRegionOps <PL011State > =MemoryRegionOpsBuilder ::<PL011State >::new ()
Quoted 8 lines
rust/hw/char/pl011/src/device.rs impl PL011State { · line 499
Quoted 6 lines
rust/hw/char/pl011/src/device.rs +6
-0+ .read(&PL011State::read) + .write (&PL011State ::write) + .native_endian () + .impl_sizes (4 ,4 ) + .build (); +Nice design. Everything was done smoothly in one go.
I hope something similar can be done with VMStateDescription too...
Quoted 6 lines
Quoted 6 lines
rust/qemu-api/src/memory.rs new file +6
-0+pub struct MemoryRegionOps <T >( + bindings::MemoryRegionOps , +// Note: quite often you'll see PhantomData<fn(&T)> mentioned when discussing +// covariance and contravariance; you don't need any of those to understand +// this usage of PhantomData. Quite simply, MemoryRegionOps<T> *logically* + // holds callbacks that take an argument of type &T, except the type is erased
Quoted 8 lines
rust/qemu-api/src/memory.rs line 34
Quoted 6 lines
rust/qemu-api/src/memory.rs new file +6
-0+// before the callback is stored in the bindings::MemoryRegionOps field. +// The argument of PhantomData is a function pointer in order to represent +// that relationship; while that will also provide desirable and safe variance +// for T, variance is not the point but just a consequence. + PhantomData<fn(&T)>, +);Wow, it can be wrapped like this!
I like your enthusiasm but I'm not sure what you refer to. ;) Maybe it's worth documenting this pattern, so please tell me more (after your holidays).
Quoted 8 lines
rust/qemu-api/src/memory.rs line 147
Quoted 5 lines
rust/qemu-api/src/memory.rs new file +5
-0+impl MemoryRegion { +// inline to ensure that it is not included in tests, which only +// link to hwcore and qom. FIXME: inlining is actually the opposite +// of what we want, since this is the type-erased version of the +// init_io function below. Look into splitting the qemu_api crate. Ah, I didn't understand the issue described in this comment. Why would inlining affect the linking of tests?
If you don't inline it, do_init_io will always be linked into the tests because it is a non-generic function. The tests then fail to link, because memory_region_init_io is undefined.
This is ugly because do_init_io exists *exactly* to extract the part that is not generic. (See
https://users.rust-lang.org/t/soft-question-significantly-improve-rust-compile-time-via-minimizing-generics/103632/8
for an example of this; I think there's even a procedural macro crate that does that for you, but I can't find it right now).
Quoted 9 lines
rust/qemu-api/src/memory.rs line 173
Quoted 5 lines
rust/qemu-api/src/memory.rs new file +5
-0+pub fn init_io <T :IsA <Object >>( + &mut self, + owner: *mut T , + ops: &'staticMemoryRegionOps <T >, + name: &'static str,What about &'static CStr?
Then pl011 could pass
c_str!("pl011")orSelf::TYPE_NAME.
I think it's better to use a Rust string; there's no reason why the name of the memory region has to match Self::TYPE_NAME; unlike the name of the device, the name of the memory region is not visible on the command line for example.
Thanks,
Paolo
Quoted 5 lines
Otherwise,
Reviewed-by Zhao Liu <[email protected]>
Re: [PATCH 10/10] rust: bindings for MemoryRegionOps
Quoted 15 lines
Quoted 6 lines
Quoted 6 lines
rust/qemu-api/src/memory.rs new file +6
-0+pub struct MemoryRegionOps <T >( + bindings::MemoryRegionOps , +// Note: quite often you'll see PhantomData<fn(&T)> mentioned when discussing +// covariance and contravariance; you don't need any of those to understand +// this usage of PhantomData. Quite simply, MemoryRegionOps<T> *logically* + // holds callbacks that take an argument of type &T, except the type is erasedQuoted 8 lines
rust/qemu-api/src/memory.rs line 34
Quoted 6 lines
rust/qemu-api/src/memory.rs new file +6
-0+// before the callback is stored in the bindings::MemoryRegionOps field. +// The argument of PhantomData is a function pointer in order to represent +// that relationship; while that will also provide desirable and safe variance +// for T, variance is not the point but just a consequence. + PhantomData<fn(&T)>, +);Wow, it can be wrapped like this!
Quoted 3 lines
I like your enthusiasm but I'm not sure what you refer to. ;) Maybe it's worth documenting this pattern, so please tell me more (after your holidays).
Throughout the entire holiday, I couldn't think of a better way to express this. I find it particularly useful when wrapping multiple callbacks. In the future, I want to explore more use cases where this pattern can be applied.
Quoted 6 lines
Quoted 6 lines
Quoted 5 lines
rust/qemu-api/src/memory.rs new file +5
-0+impl MemoryRegion { +// inline to ensure that it is not included in tests, which only +// link to hwcore and qom. FIXME: inlining is actually the opposite +// of what we want, since this is the type-erased version of the +// init_io function below. Look into splitting the qemu_api crate.
Quoted 6 lines
Quoted 2 lines
Ah, I didn't understand the issue described in this comment. Why would inlining affect the linking of tests?
If you don't inline it,
do_init_iowill always be linked into the tests because it is a non-generic function. The tests then fail to link, becausememory_region_init_iois undefined.
I find even if I drop the inline attribution, the test.rs can still be compiled (by make check), I think it's because test.rs hasn't involved memory related tests so that do_init_io isn't linked into test.rs.
Quoted 5 lines
This is ugly because
do_init_ioexists *exactly* to extract the part that is not generic. (See
https://users.rust-lang.org/t/soft-question-significantly-improve-rust-compile-time-via-minimizing-generics/103632/8
for an example of this; I think there's even a procedural macro crate that does that for you, but I can't find it right now).
Thanks! I see. I agree to keep inline anyway.
Re: [PATCH 10/10] rust: bindings for MemoryRegionOps
Quoted 4 lines · Zhao Liu
Throughout the entire holiday, I couldn't think of a better way to express this. I find it particularly useful when wrapping multiple callbacks. In the future, I want to explore more use cases where this pattern can be applied.
Thanks very much. Despite having written most of the bindings code, I don't want to give the impression that everything that I send to the mailing list is gold. So it matters to me that you send serious reviews, and that you can learn something but also suggest clarifications and improvements.
Quoted 3 lines
I find even if I drop the
inlineattribution, thetest.rscan still be compiled (bymake check), I think it's becausetest.rshasn't involved memory related tests so thatdo_init_ioisn't linked intotest.rs.
Hmm, maybe it's only with some linkers. I don't remember.
Quoted 7 lines
Quoted 5 lines
This is ugly because
do_init_ioexists *exactly* to extract the part that is not generic. (See
https://users.rust-lang.org/t/soft-question-significantly-improve-rust-compile-time-via-minimizing-generics/103632/8
for an example of this; I think there's even a procedural macro crate that does that for you, but I can't find it right now).Thanks! I see. I agree to keep
inlineanyway.
In the meanwhile I found it, it's https://github.com/llogiq/momo/blob/master/wasm/src/lib.rs. QEMU could add something like that macro to qemu_api_macros, so that
#[qemu_api_macros::upcast]
fn foo<T>(t: &T) where T: IsA<U> {
}
could be converted to
#[inline(always)]
fn foo<T>(&self) where T: IsA<U> {
fn inner_foo(u: &U) {
}
inner_foo(self.upcast())
}Paolo
Re: [PATCH 10/10] rust: bindings for MemoryRegionOps
In reply to Paolo BonziniHi Paolo,
Quoted 45 lines · Paolo Bonzini
Signed-off-by Paolo Bonzini <[email protected]>--- rust/hw/char/pl011/src/device.rs | 43 +++--- rust/hw/char/pl011/src/lib.rs | 1 - rust/hw/char/pl011/src/memory_ops.rs | 36 ----- rust/qemu-api/meson.build | 1 + rust/qemu-api/src/lib.rs | 1 + rust/qemu-api/src/memory.rs | 191 +++++++++++++++++++++++++++ rust/qemu-api/src/sysbus.rs | 7 +- rust/qemu-api/src/zeroable.rs | 12 ++ 8 files changed, 234 insertions(+), 58 deletions(-)delete mode 100644
rust/hw/char/pl011/src/memory_ops.rscreate mode 100644rust/qemu-api/src/memory.rsrust/hw/char/pl011/src/device.rs +3
-3@@ -2,7 +2,7 @@// Author(s): Manos Pitsidianakis <[email protected]> // SPDX-License-Identifier: GPL-2.0-or-later -use core::ptr::{addr_of_mut,NonNull }; +use core::ptr::{addr_of, addr_of_mut,NonNull };use std::{ ffi::CStr , os::raw::{c_int, c_void},@@ -12,14 +12,14 @@ bindings::{self, *}, c_str, impl_vmstate_forward, irq::InterruptSource, + memory::{hwaddr, MemoryRegion, MemoryRegionOps, MemoryRegionOpsBuilder}, prelude::*, - qdev::{Clock, ClockEvent, DeviceImpl, ResettablePhasesImpl, ResetType}, + qdev::{Clock, ClockEvent, DeviceImpl, ResetType, ResettablePhasesImpl}, qom::{ClassInitImpl, ObjectImpl, Owned, ParentField}, };use crate ::{ device_class, - memory_ops::PL011_OPS , registers::{self,Interrupt },RegisterOffset , };
rust/hw/char/pl011/src/device.rs impl PL011State { · line 496
Quoted 7 lines
rust/hw/char/pl011/src/device.rs +4
-0@@ -490,20 +490,24 @@ impl PL011State {/// location/instance. All its fields are expected to hold unitialized /// values with the sole exception of `parent_obj`. unsafe fn init (&mut self) { +static PL011_OPS :MemoryRegionOps <PL011State > =MemoryRegionOpsBuilder ::<PL011State >::new () + .read (&PL011State ::read) + .write (&PL011State ::write) + .native_endian ()
Could we always make .valid_sizes() explicit?
Quoted 68 lines
rust/hw/char/pl011/src/device.rs +10
-10+ .impl_sizes(4, 4) + .build (); +// SAFETY: // // self and self.iomem are guaranteed to be valid at this point since callers // must make sure the `self` reference is valid. -unsafe { -memory_region_init_io ( -addr_of_mut! (self.iomem), -addr_of_mut! (*self).cast ::<Object >(), - &PL011_OPS , -addr_of_mut! (*self).cast ::<c_void >(), -Self ::TYPE_NAME .as_ptr (), -0x1000 , - ); - } +MemoryRegion ::init_io ( +unsafe { &mut *addr_of_mut! (self.iomem) }, +addr_of_mut! (*self), + &PL011_OPS , +"pl011" , +0x1000 , + );rust/hw/char/pl011/src/lib.rs +0
-1@@ -29,7 +29,6 @@mod device;mod device_class; -mod memory_ops;pub use device::pl011_create;rust/hw/char/pl011/src/memory_ops.rs deleted +0
-24@@ -1,36 +0,0 @@ -// Copyright 2024, Linaro Limited -// Author(s): Manos Pitsidianakis <[email protected]> -// SPDX-License-Identifier: GPL-2.0-or-later - -use core::ptr::NonNull ; -use std::os::raw::{c_uint, c_void}; - -use qemu_api::{bindings::*, zeroable::Zeroable }; - -use crate ::device::PL011State ; - -pub static PL011_OPS :MemoryRegionOps =MemoryRegionOps { - read:Some (pl011_read), - write:Some (pl011_write), - read_with_attrs:None , - write_with_attrs:None , - endianness: device_endian::DEVICE_NATIVE_ENDIAN , - valid:Zeroable ::ZERO , - impl_:MemoryRegionOps__bindgen_ty_2 { - min_access_size:4 , - max_access_size:4 , - ..Zeroable ::ZERO - }, -};
Re: [PATCH 10/10] rust: bindings for MemoryRegionOps
Quoted 42 lines · Philippe Mathieu-Daudé
Hi Paolo,
Quoted 38 lines · Paolo Bonzini
Signed-off-by Paolo Bonzini <[email protected]>--- rust/hw/char/pl011/src/device.rs | 43 +++--- rust/hw/char/pl011/src/lib.rs | 1 - rust/hw/char/pl011/src/memory_ops.rs | 36 ----- rust/qemu-api/meson.build | 1 + rust/qemu-api/src/lib.rs | 1 + rust/qemu-api/src/memory.rs | 191 +++++++++++++++++++++++++++ rust/qemu-api/src/sysbus.rs | 7 +- rust/qemu-api/src/zeroable.rs | 12 ++ 8 files changed, 234 insertions(+), 58 deletions(-)delete mode 100644
rust/hw/char/pl011/src/memory_ops.rscreate mode 100644rust/qemu-api/src/memory.rsrust/hw/char/pl011/src/device.rs +3
-2@@ -2,7 +2,7 @@// Author(s): Manos Pitsidianakis <[email protected]> // SPDX-License-Identifier: GPL-2.0-or-later -use core::ptr::{addr_of_mut,NonNull }; +use core::ptr::{addr_of, addr_of_mut,NonNull };use std::{ ffi::CStr , os::raw::{c_int, c_void},@@ -12,14 +12,14 @@ bindings::{self, *}, c_str, impl_vmstate_forward, irq::InterruptSource, + memory::{hwaddr, MemoryRegion, MemoryRegionOps, MemoryRegionOpsBuilder}, prelude::*, - qdev::{Clock, ClockEvent, DeviceImpl, ResettablePhasesImpl, ResetType}, + qdev::{Clock, ClockEvent, DeviceImpl, ResetType, ResettablePhasesImpl}, qom::{ClassInitImpl, ObjectImpl, Owned, ParentField}, };
Quoted 16 lines
Quoted 7 lines
rust/hw/char/pl011/src/device.rs +0
-1use crate ::{ device_class, - memory_ops::PL011_OPS , registers::{self,Interrupt },RegisterOffset , };rust/hw/char/pl011/src/device.rs impl PL011State { · line 496
Quoted 7 lines
rust/hw/char/pl011/src/device.rs +4
-0@@ -490,20 +490,24 @@ impl PL011State {/// location/instance. All its fields are expected to hold unitialized /// values with the sole exception of `parent_obj`. unsafe fn init (&mut self) { +static PL011_OPS :MemoryRegionOps <PL011State > =MemoryRegionOpsBuilder ::<PL011State >::new () + .read (&PL011State ::read) + .write (&PL011State ::write) + .native_endian ()Could we always make .valid_sizes() explicit?
Yes (for example build() could even fail to compile if you don't have impl_sizes/valid_sizes set), but why do you want that? I'm not even sure that all cases of .valid.max_access_size=4 are correct...
Paolo
Re: [PATCH 10/10] rust: bindings for MemoryRegionOps
Quoted 60 lines · Paolo Bonzini
Quoted 42 lines · Philippe Mathieu-Daudé
Hi Paolo,
Quoted 38 lines · Paolo Bonzini
Signed-off-by Paolo Bonzini <[email protected]>--- rust/hw/char/pl011/src/device.rs | 43 +++--- rust/hw/char/pl011/src/lib.rs | 1 - rust/hw/char/pl011/src/memory_ops.rs | 36 ----- rust/qemu-api/meson.build | 1 + rust/qemu-api/src/lib.rs | 1 + rust/qemu-api/src/memory.rs | 191 +++++++++++++++++++++++++++ rust/qemu-api/src/sysbus.rs | 7 +- rust/qemu-api/src/zeroable.rs | 12 ++ 8 files changed, 234 insertions(+), 58 deletions(-)delete mode 100644
rust/hw/char/pl011/src/memory_ops.rscreate mode 100644rust/qemu-api/src/memory.rsrust/hw/char/pl011/src/device.rs +3
-2@@ -2,7 +2,7 @@// Author(s): Manos Pitsidianakis <[email protected]> // SPDX-License-Identifier: GPL-2.0-or-later -use core::ptr::{addr_of_mut,NonNull }; +use core::ptr::{addr_of, addr_of_mut,NonNull };use std::{ ffi::CStr , os::raw::{c_int, c_void},@@ -12,14 +12,14 @@ bindings::{self, *}, c_str, impl_vmstate_forward, irq::InterruptSource, + memory::{hwaddr, MemoryRegion, MemoryRegionOps, MemoryRegionOpsBuilder}, prelude::*, - qdev::{Clock, ClockEvent, DeviceImpl, ResettablePhasesImpl, ResetType}, + qdev::{Clock, ClockEvent, DeviceImpl, ResetType, ResettablePhasesImpl}, qom::{ClassInitImpl, ObjectImpl, Owned, ParentField}, };Quoted 16 lines
Quoted 7 lines
rust/hw/char/pl011/src/device.rs +0
-1use crate ::{ device_class, - memory_ops::PL011_OPS , registers::{self,Interrupt },RegisterOffset , };rust/hw/char/pl011/src/device.rs impl PL011State { · line 496
Quoted 7 lines
rust/hw/char/pl011/src/device.rs +4
-0@@ -490,20 +490,24 @@ impl PL011State {/// location/instance. All its fields are expected to hold unitialized /// values with the sole exception of `parent_obj`. unsafe fn init (&mut self) { +static PL011_OPS :MemoryRegionOps <PL011State > =MemoryRegionOpsBuilder ::<PL011State >::new () + .read (&PL011State ::read) + .write (&PL011State ::write) + .native_endian ()Could we always make .valid_sizes() explicit?
Quoted 3 lines
Yes (for example
build()could even fail to compile if you don't have impl_sizes/valid_sizes set), but why do you want that? I'm not even sure that all cases of .valid.max_access_size=4 are correct...
Exactly for that :) Not have implicit default values, so correct values are reviewed when models are added.
Re: [PATCH 10/10] rust: bindings for MemoryRegionOps
Quoted 8 lines · Philippe Mathieu-Daudé
Quoted 5 lines
Quoted 1 line
Could we always make .valid_sizes() explicit?
Yes (for example
build()could even fail to compile if you don't have impl_sizes/valid_sizes set), but why do you want that? I'm not even sure that all cases of .valid.max_access_size=4 are correct...Exactly for that :) Not have implicit default values, so correct values are reviewed when models are added.
But I wouldn't bet that those that we have in C are reviewed and correct... They are incorrect if the hardware accepts 8-byte writes, either discarding the top 4 bytes (then impl must both be 8) or writing to both registers (then impl must be 4).
Paolo
Re: [PATCH 10/10] rust: bindings for MemoryRegionOps
Quoted 11 lines · Paolo Bonzini
Quoted 8 lines · Philippe Mathieu-Daudé
Quoted 5 lines
Quoted 1 line
Could we always make .valid_sizes() explicit?
Yes (for example
build()could even fail to compile if you don't have impl_sizes/valid_sizes set), but why do you want that? I'm not even sure that all cases of .valid.max_access_size=4 are correct...Exactly for that :) Not have implicit default values, so correct values are reviewed when models are added.
But I wouldn't bet that those that we have in C are reviewed and correct... They are incorrect if the hardware accepts 8-byte writes, either discarding the top 4 bytes (then impl must both be 8) or writing to both registers (then impl must be 4).
Are you saying in general or for the pl011 model?
What I'm asking is to have all rust models explicit the min/max sizes, regardless of whether the C implementations are correct or not. For rust models, we won't rely on default and will have to check the valid range in the specs.
Quoted 8 lines · Paolo Bonzini
Date: Fri, 17 Jan 2025 20:39:53 +0100
From: Paolo Bonzini <[email protected]>
Subject: [RFC PATCH 00/10] rust: remaining part of qdev bindings
X-Mailer: git-send-email 2.47.1This is what I have left for qdev bindings, including 1) reference counting and object creation 2) clocks 3) Resettable 4) MemoryRegionOps. I have no rush for this series, and I expect HPET to be merged before it.
I'll get HPET v2 sorted out and sent quickly (in the this weekend), then I'll go through this series. :-)
Regards,
Zhao