rust: bundle of prerequisites for HPET implementation
Subsystems (2)
cover rust: bundle of prerequisites for HPET implementation
These are the initial set of bindings and support code that are needed to apply Zhao's posted HPET implementation, and for him to apply my review comments. They include:
- QOM cleanups (already posted)
- interrupts sources and cells (posted and reviewed)
- bit deposit and extract operations (new)
- QOM generalization beyond DeviceState (new)
- callbacks system (new)
This is the code that I aim at integrating in QEMU 10.0, and is also what is needed to develop additional bindings (for e.g. timers) more or less independently. I'll focus here on the changes to QOM because they represent the bulk of the patches. The bit operations and callbacks are just one or two patches each, and better explained by the doc comments in the patch itself.
With respect to qdev, some of this was already explained in the "Rust in QEMU roadmap". The patches are split in two series, corresponding to patches 7-14 and 15-24.
The first and previously posted part mostly removes code duplication, while keeping the focus very much on four elements of DeviceClass (realize, legacy reset, properties, vmstate).
The second instead starts to establish a correspondence between the QOM class hierarchy and the Rust trait system. The hierarchy of classes is visible as an ObjectImpl::ParentType associated type, and also present in the implementation of the ClassInitImpl<ClassType> trait. The ClassInitImpl trait is implemented for each Rust-defined QOM class as before, but now its implementation is split over multiple blanket impls, one for each superclass. This allows code reuse of the class_init wrappers, and is implemented in patches 15-18.
After a brief cleanup intermission in patches 19-21, patches 22-23 provide the method invocation infrastructure. Taking inspiration from glib-rs's GObject bindings, an IsA<> trait declares what is a subclass of what, which allows two things:
- safe and efficient typecasts, which are compile-time checked so that it is an error if the destination type is not a superclass.
- automatically making methods available to all subclasses. This is done through another blanket implementation of a trait, as in glib-rs (see
https://gtk-rs.org/gtk4-rs/stable/latest/docs/src/gtk4/auto/widget.rs.html#5377),
though the details are a bit different.
The differences with glib-rs are not small, but fortunately it is the QEMU version that is simpler. QEMU does not use a complicated macro like glib's
(https://gtk-rs.org/gtk-rs-core/git/docs/glib/macro.wrapper.html) to wrap all subclasses of GObject with an opaque Rust type. While macros in general, and procedural macros in particular, may be a useful tool(*), for now I prefer to ensure that the infrastructure is usable and readable even without any macro magic.
The two pieces allow defining QOM class hierarchies entirely in Rust; patch 24 for example gives TYPE_PL011 its own class type PL011Class, and stores the device id in PL011Class instead of PL011State.
I understand that this is a lot of code, and a lot of added lines in particular. Fortunately about 40% of it is docs, which is definitely a change for QEMU's standards. :) Also all except the last two patches have already been used by Zhao, who did not report any particular problem adopting them.
Excepting the docs, the bulk of the new code is in the BqlCell and BqlRefCell implementations, as well as in patch 22. Fortunately these patches are also relatively boring. The more interesting patches to review are patch 15-18 for QOM, and 25 for the callbacks. Patch 25 is also the trickiest to explain from the point of view of using advanced language features; (**) I tried to explain that in the doc comments and commit messages but please ask for more if necessary.
This series is available at branch rust-next of
https://gitlab.com/bonzini/qemu.git.
Thanks,
Paolo
(*) For example they could automate the declaration of various traits, many of which are "unsafe" as a reminder that they interact with C code. This should be pretty easy, considering that the amount of code required to write QOM types is already smaller in Rust than in C. qdev properties are also a useful target, as exemplified by Manos's previously posted series.
(**) In particular, zero-sized types and the Fn trait.
Paolo Bonzini (26):
bql: check that the BQL is not dropped within marked sections
rust: cell: add BQL-enforcing Cell variant
rust: cell: add BQL-enforcing RefCell variant
rust: define prelude
rust: add bindings for interrupt sources
rust: add a bit operation module
rust: qom: add default definitions for ObjectImpl
rust: qom: rename Class trait to ClassInitImpl
rust: qom: convert type_info! macro to an associated const
rust: qom: move ClassInitImpl to the instance side
rust: qdev: move device_class_init! body to generic function,
ClassInitImpl implementation to macro
rust: qdev: move bridge for realize and reset functions out of pl011
rust: qom: automatically use Drop trait to implement instance_finalize
rust: qom: move bridge for TypeInfo functions out of pl011
rust: qom: split ObjectType from ObjectImpl trait
rust: qom: change the parent type to an associated type
rust: qom: put class_init together from multiple ClassInitImpl<>
rust: qom: add possibility of overriding unparent
rust: rename qemu-api modules to follow C code a bit more
rust: re-export C types from qemu-api submodules
rust: tests: allow writing more than one test
rust: qom: add casting functionality
rust: qom: add initial subset of methods on Object
rust: qom: move device_id to PL011 class side
rust: qemu-api: add a module to wrap functions and zero-sized closures
rust: callbacks: allow passing optional callbacks as ()
include/qemu/main-loop.h | 15 + stubs/iothread-lock.c | 15 + system/cpus.c | 15 + rust/Cargo.toml | 1 + rust/hw/char/pl011/src/device.rs | 156 ++--- rust/hw/char/pl011/src/device_class.rs | 34 - rust/qemu-api-macros/src/lib.rs | 2 +- rust/qemu-api/Cargo.toml | 3 +- rust/qemu-api/meson.build | 14 +- rust/qemu-api/src/bitops.rs | 119 ++++ rust/qemu-api/src/callbacks.rs | 238 +++++++ rust/qemu-api/src/cell.rs | 822 +++++++++++++++++++++++++ rust/qemu-api/src/definitions.rs | 91 --- rust/qemu-api/src/device_class.rs | 74 --- rust/qemu-api/src/irq.rs | 91 +++ rust/qemu-api/src/lib.rs | 15 +- rust/qemu-api/src/module.rs | 43 ++ rust/qemu-api/src/prelude.rs | 18 + rust/qemu-api/src/qdev.rs | 146 +++++ rust/qemu-api/src/qom.rs | 556 +++++++++++++++++ rust/qemu-api/src/sysbus.rs | 51 ++ rust/qemu-api/src/vmstate.rs | 9 +- rust/qemu-api/tests/tests.rs | 208 +++++-- 23 files changed, 2374 insertions(+), 362 deletions(-) create mode 100644 rust/qemu-api/src/bitops.rs create mode 100644 rust/qemu-api/src/callbacks.rs create mode 100644 rust/qemu-api/src/cell.rs delete mode 100644 rust/qemu-api/src/definitions.rs delete mode 100644 rust/qemu-api/src/device_class.rs create mode 100644 rust/qemu-api/src/irq.rs create mode 100644 rust/qemu-api/src/module.rs create mode 100644 rust/qemu-api/src/prelude.rs create mode 100644 rust/qemu-api/src/qdev.rs create mode 100644 rust/qemu-api/src/qom.rs create mode 100644 rust/qemu-api/src/sysbus.rs
Signature · 1 line
2.47.1
PATCH 1/26 bql: check that the BQL is not dropped within marked sections
The Big QEMU Lock (BQL) is used to provide interior mutability to Rust code. While BqlCell performs indivisible accesses, an equivalent of RefCell will allow the borrower to hold to the interior content for a long time. If the BQL is dropped, another thread could come and mutate the data from C code (Rust code would panic on borrow_mut() instead). In order to prevent this, add a new BQL primitive that can mark BQL-atomic sections and aborts if the BQL is dropped within them.
--- include/qemu/main-loop.h | 15 +++++++++++++++ stubs/iothread-lock.c | 15 +++++++++++++++ system/cpus.c | 15 +++++++++++++++ 3 files changed, 45 insertions(+)
include/qemu/main-loop.h +15 -0
@@ -262,6 +262,21 @@ AioContext *iohandler_get_aio_context(void);*/ bool bql_locked (void ); +/** +* bql_block: Allow/deny releasing the BQL +* +* The Big QEMU Lock (BQL) is used to provide interior mutability to +* Rust code, but this only works if other threads cannot run while +* the Rust code has an active borrow. This is because C code in +* other threads could come in and mutate data under the Rust code's +* feet. +* +* @increase: Whether to increase or decrease the blocking counter. +* Releasing the BQL while the counter is nonzero triggers +* an assertion failure. +*/ +void bql_block_unlock (bool increase); +/** * qemu_in_main_thread: return whether it's possible to safely access * the global state of the block layer.
stubs/iothread-lock.c +15 -0
@@ -1,6 +1,8 @@#include "qemu/osdep.h" #include "qemu/main-loop.h" +static uint32_t bql_unlock_blocked; +bool bql_locked (void ) {return false;
@@ -12,4 +14,17 @@ void bql_lock_impl(const char *file, int line)void bql_unlock (void ) { +assert (!bql_unlock_blocked); +} + +void bql_block_unlock (bool increase) +{ +uint32_t new_value; + +assert (bql_locked ()); + +/* check for overflow! */ + new_value = bql_unlock_blocked + increase - !increase; +assert ((new_value > bql_unlock_blocked) == increase); + bql_unlock_blocked = new_value; }
system/cpus.c +15 -0
@@ -514,6 +514,20 @@ bool qemu_in_vcpu_thread(void) QEMU_DEFINE_STATIC_CO_TLS(bool, bql_locked) +static uint32_t bql_unlock_blocked; + +void bql_block_unlock (bool increase) +{ +uint32_t new_value; + +assert (bql_locked ()); + +/* check for overflow! */ + new_value = bql_unlock_blocked + increase - !increase; +assert ((new_value > bql_unlock_blocked) == increase); + bql_unlock_blocked = new_value; +} +bool bql_locked (void ) {return get_bql_locked ();
@@ -540,6 +554,7 @@ void bql_lock_impl(const char *file, int line)void bql_unlock (void ) {g_assert (bql_locked ()); +g_assert (!bql_unlock_blocked);set_bql_locked (false);qemu_mutex_unlock (&bql); }
Signature · 1 line
2.47.1
PATCH 2/26 rust: cell: add BQL-enforcing Cell variant
In reply to Paolo BonziniQEMU objects usually have their pointer shared with the "outside world" very early in their lifetime, for example when they create their MemoryRegions. Because at this point it is not valid anymore to create a &mut reference to the device, individual parts of the device struct must be made mutable in a controlled manner.
QEMU's Big Lock (BQL) effectively turns multi-threaded code into single-threaded code while device code runs, as long as the BQL is not released while the device is borrowed (because C code could sneak in and mutate the device). We can then introduce custom interior mutability primitives that are semantically similar to the standard library's (single-threaded) Cell and RefCell, but account for QEMU's threading model. Accessing the "BqlCell" or borrowing the "BqlRefCell" requires proving that the BQL is held, and attempting to access without the BQL is a runtime panic, similar to RefCell's already-borrowed panic.
With respect to naming I also considered omitting the "Bql" prefix or moving it to the module, e.g. qemu_api::bql::{Cell, RefCell}. However, this could easily lead to mistakes and confusion; for example rustc could suggest the wrong import, leading to subtle bugs.
As a start introduce the an equivalent of Cell. Almost all of the code was taken from Rust's standard library, while removing unstable features and probably-unnecessary functionality that constitute a large of the original code. A lot of what's left is documentation, as well as unit tests in the form of doctests. These are not yet integrated in "make check" but can be run with "cargo test --doc".
--- rust/qemu-api/meson.build | 1 + rust/qemu-api/src/cell.rs | 298 ++++++++++++++++++++++++++++++++++++++ rust/qemu-api/src/lib.rs | 1 + 3 files changed, 300 insertions(+) create mode 100644 rust/qemu-api/src/cell.rs
rust/qemu-api/meson.build +1 -0
@@ -13,6 +13,7 @@ _qemu_api_rs = static_library( [ 'src/lib.rs', 'src/bindings.rs', + 'src/cell.rs', 'src/c_str.rs', 'src/definitions.rs', 'src/device_class.rs',
rust/qemu-api/src/cell.rs new file +298 -0
298 lines not on this page · raw message
rust/qemu-api/src/lib.rs +1 -0
@@ -8,6 +8,7 @@pub mod bindings;pub mod c_str; +pub mod cell;pub mod definitions;pub mod device_class;pub mod offset_of;
Signature · 1 line
2.47.1
PATCH 3/26 rust: cell: add BQL-enforcing RefCell variant
In reply to Paolo BonziniSimilar to the existing BqlCell, introduce a custom interior mutability primitive that resembles RefCell but accounts for QEMU's threading model. Borrowing the RefCell requires proving that the BQL is held, and attempting to access without the BQL is a runtime panic.
Almost all of the code was taken from Rust's standard library, while removing unstable features and probably-unnecessary functionality that amounts to 60% of the original code. A lot of what's left is documentation, as well as unit tests in the form of doctests. These are not yet integrated in "make check" but can be run with "cargo test --doc".
--- rust/qemu-api/Cargo.toml | 3 +- rust/qemu-api/meson.build | 3 + rust/qemu-api/src/cell.rs | 544 +++++++++++++++++++++++++++++++++++++- 3 files changed, 539 insertions(+), 11 deletions(-)
rust/qemu-api/Cargo.toml +2 -1
@@ -20,8 +20,9 @@ qemu_api_macros = { path = "../qemu-api-macros" } version_check = "~0.9" [features] -default = [] +default = ["debug_cell"] allocator = [] +debug_cell = [] [lints] workspace = true
rust/qemu-api/meson.build +3 -0
@@ -6,6 +6,9 @@ _qemu_api_cfg = run_command(rustc_args, if rustc.version().version_compare('>=1.77.0') _qemu_api_cfg += ['--cfg', 'has_offset_of'] endif +if get_option('debug_mutex') + _qemu_api_cfg += ['--feature', 'debug_cell'] +endif _qemu_api_rs = static_library( 'qemu_api',
rust/qemu-api/src/cell.rs +534 -10
571 lines not on this page · raw message
Signature · 1 line
2.47.1
PATCH 4/26 rust: define prelude
In reply to Paolo BonziniAdd a module that will contain frequently used traits and occasionally structs. They can be included quickly with "use qemu_api::prelude::*".
--- rust/qemu-api/meson.build | 1 + rust/qemu-api/src/lib.rs | 5 +++++ rust/qemu-api/src/prelude.rs | 6 ++++++ 3 files changed, 12 insertions(+) create mode 100644 rust/qemu-api/src/prelude.rs
rust/qemu-api/meson.build +1 -0
@@ -21,6 +21,7 @@ _qemu_api_rs = static_library( 'src/definitions.rs', 'src/device_class.rs', 'src/offset_of.rs', + 'src/prelude.rs', 'src/vmstate.rs', 'src/zeroable.rs', ],
rust/qemu-api/src/lib.rs +5 -0
@@ -7,6 +7,11 @@#[rustfmt::skip] pub mod bindings; +// preserve one-item-per-"use" syntax, it is clearer +// for prelude-like modules +#[rustfmt::skip] +pub mod prelude; +pub mod c_str;pub mod cell;pub mod definitions;
rust/qemu-api/src/prelude.rs new file +6 -0
@@ -0,0 +1,6 @@ +// Copyright 2024 Red Hat, Inc. +// Author(s): Paolo Bonzini <[email protected]> +// SPDX-License-Identifier: GPL-2.0-or-later + +pub use crate ::cell::BqlCell ; +pub use crate ::cell::BqlRefCell ;
Signature · 1 line
2.47.1
Re: [PATCH 04/26] rust: define prelude
Quoted 9 lines · Paolo Bonzini
Date: Mon, 9 Dec 2024 13:36:55 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 04/26] rust: define prelude
X-Mailer: git-send-email 2.47.1Add a module that will contain frequently used traits and occasionally structs. They can be included quickly with "use qemu_api::prelude::*".
Quoted 7 lines
Signed-off-by Paolo Bonzini <[email protected]>--- rust/qemu-api/meson.build | 1 + rust/qemu-api/src/lib.rs | 5 +++++ rust/qemu-api/src/prelude.rs | 6 ++++++ 3 files changed, 12 insertions(+) create mode 100644 rust/qemu-api/src/prelude.rs
PATCH 5/26 rust: add bindings for interrupt sources
In reply to Paolo BonziniThe InterruptSource bindings let us call qemu_set_irq() and sysbus_init_irq() as safe code.
Interrupt sources, qemu_irq in C code, are pointers to IRQState objects. They are QOM link properties and can be written to outside the control of the device (i.e. from a shared reference); therefore they must be interior-mutable in Rust. Since thread-safety is provided by the BQL, what we want here is the newly-introduced BqlCell. A pointer to the contents of the BqlCell (an IRQState**, or equivalently qemu_irq*) is then passed to the C sysbus_init_irq function.
--- rust/hw/char/pl011/src/device.rs | 22 ++++---- rust/qemu-api/meson.build | 2 + rust/qemu-api/src/irq.rs | 91 ++++++++++++++++++++++++++++++++ rust/qemu-api/src/lib.rs | 2 + rust/qemu-api/src/sysbus.rs | 27 ++++++++++ 5 files changed, 134 insertions(+), 10 deletions(-) create mode 100644 rust/qemu-api/src/irq.rs create mode 100644 rust/qemu-api/src/sysbus.rs
rust/hw/char/pl011/src/device.rs +12 -10
@@ -13,6 +13,7 @@ c_str, definitions::ObjectImpl, device_class::TYPE_SYS_BUS_DEVICE, + irq::InterruptSource, };use crate ::{
@@ -94,7 +95,7 @@ pub struct PL011State {/// * sysbus IRQ 5: `UARTEINTR` (error interrupt line) /// ``` #[doc(alias = "irq" )] - pub interrupts: [qemu_irq; 6usize], + pub interrupts: [InterruptSource; IRQMASK.len()],#[doc(alias = "clk" )] pub clock: NonNull<Clock>,#[doc(alias = "migrate_clk" )]
@@ -139,7 +140,8 @@ impl PL011State {unsafe fn init (&mut self) {const CLK_NAME : &CStr =c_str! ("clk" ); -let dev =addr_of_mut! (*self).cast ::<DeviceState >(); +let sbd =unsafe { &mut *(addr_of_mut! (*self).cast ::<SysBusDevice >()) }; +// SAFETY: // // self and self.iomem are guaranteed to be valid at this point since callers
@@ -153,12 +155,15 @@ unsafe fn init(&mut self) { Self::TYPE_INFO.name, 0x1000, ); -let sbd =addr_of_mut! (*self).cast ::<SysBusDevice >();sysbus_init_mmio (sbd,addr_of_mut! (self.iomem)); -for irqin self.interrupts.iter_mut () { -sysbus_init_irq (sbd, irq); - } } + +for irqin self.interrupts.iter () { + sbd.init_irq (irq); + } + +let dev =addr_of_mut! (*self).cast ::<DeviceState >(); +// SAFETY: // // self.clock is not initialized at this point; but since `NonNull<_>` is Copy,
@@ -498,10 +503,7 @@ pub fn put_fifo(&mut self, value: c_uint) {pub fn update (&self) {let flags = self.int_level & self.int_enabled;for (irq, i)in self.interrupts.iter ().zip (IRQMASK ) { -// SAFETY: self.interrupts have been initialized in init(). -unsafe { -qemu_set_irq (*irq, i32::from (flags & i !=0 )); - } + irq.set (flags & i !=0 ); } }
rust/qemu-api/meson.build +2 -0
@@ -20,8 +20,10 @@ _qemu_api_rs = static_library( 'src/c_str.rs', 'src/definitions.rs', 'src/device_class.rs', + 'src/irq.rs', 'src/offset_of.rs', 'src/prelude.rs', + 'src/sysbus.rs', 'src/vmstate.rs', 'src/zeroable.rs', ],
rust/qemu-api/src/irq.rs new file +91 -0
91 lines not on this page · raw message
rust/qemu-api/src/lib.rs +2 -0
@@ -16,7 +16,9 @@pub mod cell;pub mod definitions;pub mod device_class; +pub mod irq;pub mod offset_of; +pub mod sysbus;pub mod vmstate;pub mod zeroable;
rust/qemu-api/src/sysbus.rs new file +27 -0
@@ -0,0 +1,27 @@ +// Copyright 2024 Red Hat, Inc. +// Author(s): Paolo Bonzini <[email protected]> +// SPDX-License-Identifier: GPL-2.0-or-later + +use std::ptr::addr_of; + +pub use bindings::{SysBusDevice ,SysBusDeviceClass }; + +use crate ::{bindings, cell::bql_locked, irq::InterruptSource }; + +impl SysBusDevice { +/// Return `self` cast to a mutable pointer, for use in calls to C code. +const fn as_mut_ptr (&self) -> *mut SysBusDevice { +addr_of! (*self)as *mut _ + } + +/// Expose an interrupt source outside the device as a qdev GPIO output. +/// Note that the ordering of calls to `init_irq` is important, since +/// whoever creates the sysbus device will refer to the interrupts with +/// a number that corresponds to the order of calls to `init_irq`. +pub fn init_irq (&self, irq: &InterruptSource ) { +assert! (bql_locked ()); +unsafe { + bindings::sysbus_init_irq (self.as_mut_ptr (), irq.as_ptr ()); + } + } +}
Signature · 1 line
2.47.1
Re: [PATCH 05/26] rust: add bindings for interrupt sources
Quoted 17 lines · Paolo Bonzini
Date: Mon, 9 Dec 2024 13:36:56 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 05/26] rust: add bindings for interrupt sources
X-Mailer: git-send-email 2.47.1The InterruptSource bindings let us call
qemu_set_irq()andsysbus_init_irq()as safe code.Interrupt sources,
qemu_irqin C code, are pointers to IRQState objects. They are QOM link properties and can be written to outside the control of the device (i.e. from a shared reference); therefore they must be interior-mutable in Rust. Since thread-safety is provided by the BQL, what we want here is the newly-introduced BqlCell. A pointer to the contents of the BqlCell (an IRQState**, or equivalently qemu_irq*) is then passed to the Csysbus_init_irqfunction.Signed-off-by Paolo Bonzini <[email protected]>
Quoted 10 lines
--- rust/hw/char/pl011/src/device.rs | 22 ++++---- rust/qemu-api/meson.build | 2 + rust/qemu-api/src/irq.rs | 91 ++++++++++++++++++++++++++++++++ rust/qemu-api/src/lib.rs | 2 + rust/qemu-api/src/sysbus.rs | 27 ++++++++++ 5 files changed, 134 insertions(+), 10 deletions(-) create mode 100644 rust/qemu-api/src/irq.rs create mode 100644 rust/qemu-api/src/sysbus.rs
PATCH 6/26 rust: add a bit operation module
In reply to Paolo BonziniThe bindgen supports static inline function binding since v0.64.0 as an experimental feature (--wrap-static-fns), and stabilizes it after v0.70.0.
But the oldest version of bindgen supported by QEMU is v0.60.1, so there's no way to generate the binding for deposit64() which is static inline (in include/qemu/bitops.h).
Instead, implement it by hand in Rust and make it available for all unsigned types through an IntegerExt trait. Since it only involves bit operations, the Rust version of the code is almost identical to the original C version, but it applies to more types than just u64.
--- rust/qemu-api/meson.build | 1 + rust/qemu-api/src/bitops.rs | 119 +++++++++++++++++++++++++++++++++++ rust/qemu-api/src/lib.rs | 1 + rust/qemu-api/src/prelude.rs | 2 + 4 files changed, 123 insertions(+) create mode 100644 rust/qemu-api/src/bitops.rs
rust/qemu-api/meson.build +1 -0
@@ -16,6 +16,7 @@ _qemu_api_rs = static_library( [ 'src/lib.rs', 'src/bindings.rs', + 'src/bitops.rs', 'src/cell.rs', 'src/c_str.rs', 'src/definitions.rs',
rust/qemu-api/src/bitops.rs new file +119 -0
119 lines not on this page · raw message
rust/qemu-api/src/lib.rs +1 -0
@@ -12,6 +12,7 @@#[rustfmt::skip] pub mod prelude; +pub mod bitops;pub mod c_str;pub mod cell;pub mod definitions;
rust/qemu-api/src/prelude.rs +2 -0
@@ -2,5 +2,7 @@// Author(s): Paolo Bonzini <[email protected]> // SPDX-License-Identifier: GPL-2.0-or-later +pub use crate ::bitops::IntegerExt ; +pub use crate ::cell::BqlCell ;pub use crate ::cell::BqlRefCell ;
Signature · 1 line
2.47.1
Re: [PATCH 06/26] rust: add a bit operation module
Quoted 47 lines · Paolo Bonzini
Date: Mon, 9 Dec 2024 13:36:57 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 06/26] rust: add a bit operation module
X-Mailer: git-send-email 2.47.1The bindgen supports
static inlinefunction binding since v0.64.0 as an experimental feature (--wrap-static-fns), and stabilizes it after v0.70.0.But the oldest version of bindgen supported by QEMU is v0.60.1, so there's no way to generate the binding for
deposit64()which isstatic inline(ininclude/qemu/bitops.h).Instead, implement it by hand in Rust and make it available for all unsigned types through an IntegerExt trait. Since it only involves bit operations, the Rust version of the code is almost identical to the original C version, but it applies to more types than just u64.
Signed-off-by Zhao Liu <[email protected]>Co-authored-by Paolo Bonzini <[email protected]>Signed-off-by Paolo Bonzini <[email protected]>--- rust/qemu-api/meson.build | 1 + rust/qemu-api/src/bitops.rs | 119 +++++++++++++++++++++++++++++++++++ rust/qemu-api/src/lib.rs | 1 + rust/qemu-api/src/prelude.rs | 2 + 4 files changed, 123 insertions(+) create mode 100644 rust/qemu-api/src/bitops.rsrust/qemu-api/meson.build +1
-0@@ -16,6 +16,7 @@ _qemu_api_rs = static_library( [ 'src/lib.rs', 'src/bindings.rs', + 'src/bitops.rs', 'src/cell.rs', 'src/c_str.rs', 'src/definitions.rs',rust/qemu-api/src/bitops.rs new file +0
-0
rust/qemu-api/src/bitops.rs line 2
Quoted 2 lines
rust/qemu-api/src/bitops.rs new file +2
-0@@ -0,0 +1,119 @@ +// Copyright (C) 2024 Intel Corporation. +// Author(s): Zhao Liu <[email protected]>
You deserve to be the author!
Quoted 14 lines
rust/qemu-api/src/bitops.rs new file +14
-0+// SPDX-License-Identifier: GPL-2.0-or-later + +//! This module provides bit operation extensions to integer types. +//! It is usually included via the `qemu_api` prelude. + +use std::ops::{ +Add ,AddAssign ,BitAnd ,BitAndAssign ,BitOr ,BitOrAssign ,BitXor ,BitXorAssign ,Div ,DivAssign , +Mul ,MulAssign ,Not ,Rem ,RemAssign ,Shl ,ShlAssign ,Shr ,ShrAssign , +}; + +/// Trait for extensions to integer types +pub trait IntegerExt: + Add<Self, Output = Self> + AddAssign<Self> + + BitAnd<Self, Output = Self> + BitAndAssign<Self> +
rust/qemu-api/src/bitops.rs line 26
Quoted 10 lines
rust/qemu-api/src/bitops.rs new file +10
-0+ BitOr<Self, Output = Self> + BitOrAssign<Self> + + BitXor<Self, Output = Self> + BitXorAssign<Self> + +Copy + + Div<Self, Output = Self> + DivAssign<Self> + +Eq + + Mul<Self, Output = Self> + MulAssign<Self> + + Not<Output = Self> + Ord + PartialOrd + + Rem<Self, Output = Self> + RemAssign<Self> + + Shl<Self, Output = Self> + ShlAssign<Self> + + Shl<u32, Output = Self> + ShlAssign<u32> + // add more as needed
Ah, I used to define shift bits as usize. I can change the bit shift type back to u32 in HPET.
Quoted 7 lines
rust/qemu-api/src/bitops.rs new file +7
-0+ Shr<Self, Output = Self> + ShrAssign<Self> + + Shr<u32, Output = Self> + ShrAssign<u32> // add more as needed +{ +const BITS :u32 ; +const MAX :Self ; +const MIN :Self ; +const ONE :Self ;
rust/qemu-api/src/bitops.rs line 43
Quoted 10 lines
rust/qemu-api/src/bitops.rs new file +10
-0+const ZERO :Self ; + +#[inline] +#[must_use] +fn bit (start:u32 ) ->Self + { +assert! (start <=Self ::BITS ); + +Self ::ONE << start + }
I think with this helper, I can add activating_bit() and deactivating_bit() bindings, as they are also commonly used operations.
I will rename them to activate_bit and deactivate_bit, if no one has any objections.
rust/qemu-api/src/bitops.rs line 49
Quoted 5 lines
rust/qemu-api/src/bitops.rs new file +5
-0+#[inline] +#[must_use] +fn mask (start:u32 , length:u32 ) ->Self + { +/* FIXME: Implement a more elegant check with error handling support? */
I think current design is elegant enough, and this FIXME is not needed.
rust/qemu-api/src/bitops.rs line 61
Quoted 12 lines
rust/qemu-api/src/bitops.rs new file +12
-0+assert! (length >0 && length <=Self ::BITS - start); + + (Self ::MAX >> (Self ::BITS - length)) << start + } + +#[inline] +#[must_use] +fn deposit <U :IntegerExt >(self, start:u32 , length:u32 , + fieldval:U ) ->Self +where Self :From <U > + { +debug_assert! (length <=U ::BITS );
assert? as you've already replaced debug_assert with assert in BqlCell.
rust/qemu-api/src/bitops.rs line 66
Quoted 4 lines
rust/qemu-api/src/bitops.rs new file +4
-0+let mask =Self ::mask (start, length); + (self & !mask) | ((Self ::from (fieldval) << start) & mask) + } +
Very useful for HPET! Thanks.
Re: [PATCH 06/26] rust: add a bit operation module
Quoted 10 lines · Zhao Liu
rust/qemu-api/src/bitops.rs line 2
Quoted 8 lines
rust/qemu-api/src/bitops.rs new file +2
-0@@ -0,0 +1,119 @@ +// Copyright (C) 2024 Intel Corporation. +// Author(s): Zhao Liu <[email protected]> You deserve to be the author!
I'll add both of us. At this stage even identifying a need is an important step.
Quoted 19 lines
Quoted 19 lines
rust/qemu-api/src/bitops.rs new file +19
-0+// SPDX-License-Identifier: GPL-2.0-or-later + +//! This module provides bit operation extensions to integer types. +//! It is usually included via the `qemu_api` prelude. + +use std::ops::{ +Add ,AddAssign ,BitAnd ,BitAndAssign ,BitOr ,BitOrAssign ,BitXor ,BitXorAssign ,Div ,DivAssign , +Mul ,MulAssign ,Not ,Rem ,RemAssign ,Shl ,ShlAssign ,Shr ,ShrAssign , +}; + +/// Trait for extensions to integer types +pub trait IntegerExt: + Add<Self, Output = Self> + AddAssign<Self> + + BitAnd<Self, Output = Self> + BitAndAssign<Self> + + BitOr<Self, Output = Self> + BitOrAssign<Self> + + BitXor<Self, Output = Self> + BitXorAssign<Self> + + Copy + + Div<Self, Output = Self> + DivAssign<Self> + + Eq +
Quoted 8 lines
rust/qemu-api/src/bitops.rs line 26
Quoted 5 lines
rust/qemu-api/src/bitops.rs new file +5
-0+ Mul<Self, Output = Self> + MulAssign<Self> + + Not<Output = Self> + Ord + PartialOrd + + Rem<Self, Output = Self> + RemAssign<Self> + + Shl<Self, Output = Self> + ShlAssign<Self> + + Shl<u32, Output = Self> + ShlAssign<u32> + // add more as neededAh, I used to define shift bits as usize. I can change the bit shift type back to u32 in HPET.
I used u32 because BITS is u32 in the standard library, so probably better to change it in HPET.
Quoted 21 lines
Quoted 7 lines
rust/qemu-api/src/bitops.rs new file +7
-0+ Shr<Self, Output = Self> + ShrAssign<Self> + + Shr<u32, Output = Self> + ShrAssign<u32> // add more as needed +{ +const BITS :u32 ; +const MAX :Self ; +const MIN :Self ; +const ONE :Self ;rust/qemu-api/src/bitops.rs line 43
Quoted 10 lines
rust/qemu-api/src/bitops.rs new file +10
-0+const ZERO :Self ; + +#[inline] +#[must_use] +fn bit (start:u32 ) ->Self + { +assert! (start <=Self ::BITS ); + +Self ::ONE << start + }I think with this helper, I can add
activating_bit()anddeactivating_bit()bindings, as they are also commonly used operations.
Quoted 2 lines
I will rename them to
activate_bitanddeactivate_bit, if no one has any objections.
I think "-ing" is correct because it looks at a change between two values. Or another possibility is putting the mask as "self":
fn bits_activated(from: Self, to: Self) -> bool {
(to & !from & self) != 0
}
fn bits_deactivated(from: Self, to: Self) -> bool {
(from & !to & self) != 0
}Anyhow feel free to pick something you like and add it to IntegerExt.
Quoted 9 lines
rust/qemu-api/src/bitops.rs line 61
Quoted 7 lines
rust/qemu-api/src/bitops.rs new file +7
-0+#[inline] +#[must_use] +fn deposit <U :IntegerExt >(self, start:u32 , length:u32 , + fieldval:U ) ->Self +where Self :From <U > + { +debug_assert! (length <=U ::BITS );assert? as you've already replaced
debug_assertwith assert in BqlCell.
No, not this time :) Rust has checks for overflow in debug mode but not in release mode, so (independent of how Meson handles debug assertions) debug_assert is the right one here.
Paolo
Quoted 11 lines
rust/qemu-api/src/bitops.rs line 66
Quoted 4 lines
rust/qemu-api/src/bitops.rs new file +4
-0+let mask =Self ::mask (start, length); + (self & !mask) | ((Self ::from (fieldval) << start) & mask) + } +Very useful for HPET! Thanks.
Reviewed-by Zhao Liu <[email protected]>
PATCH 7/26 rust: qom: add default definitions for ObjectImpl
In reply to Paolo BonziniRemove a bunch of duplicate const definitions.
--- rust/hw/char/pl011/src/device.rs | 6 ------ rust/qemu-api/src/definitions.rs | 8 ++++---- rust/qemu-api/tests/tests.rs | 4 ---- 3 files changed, 4 insertions(+), 14 deletions(-)
rust/hw/char/pl011/src/device.rs +0 -6
@@ -109,10 +109,7 @@ impl ObjectImpl for PL011State {const TYPE_INFO : qemu_api::bindings::TypeInfo = qemu_api::type_info! {Self };const TYPE_NAME : &'staticCStr =crate ::TYPE_PL011 ;const PARENT_TYPE_NAME :Option <&'staticCStr > =Some (TYPE_SYS_BUS_DEVICE ); -const ABSTRACT :bool =false ;const INSTANCE_INIT :Option <unsafe extern "C" fn (obj: *mut Object )> =Some (pl011_init); -const INSTANCE_POST_INIT :Option <unsafe extern "C" fn (obj: *mut Object )> =None ; -const INSTANCE_FINALIZE :Option <unsafe extern "C" fn (obj: *mut Object )> =None ; }#[repr( C )]
@@ -666,8 +663,5 @@ impl ObjectImpl for PL011Luminary {const TYPE_INFO : qemu_api::bindings::TypeInfo = qemu_api::type_info! {Self };const TYPE_NAME : &'staticCStr =crate ::TYPE_PL011_LUMINARY ;const PARENT_TYPE_NAME :Option <&'staticCStr > =Some (crate ::TYPE_PL011 ); -const ABSTRACT :bool =false ;const INSTANCE_INIT :Option <unsafe extern "C" fn (obj: *mut Object )> =Some (pl011_luminary_init); -const INSTANCE_POST_INIT :Option <unsafe extern "C" fn (obj: *mut Object )> =None ; -const INSTANCE_FINALIZE :Option <unsafe extern "C" fn (obj: *mut Object )> =None ; }
rust/qemu-api/src/definitions.rs +4 -4
@@ -14,10 +14,10 @@ pub trait ObjectImpl {const TYPE_INFO :TypeInfo ;const TYPE_NAME : &'staticCStr ;const PARENT_TYPE_NAME :Option <&'staticCStr >; -const ABSTRACT :bool ; -const INSTANCE_INIT :Option <unsafe extern "C" fn (obj: *mut Object )>; -const INSTANCE_POST_INIT :Option <unsafe extern "C" fn (obj: *mut Object )>; -const INSTANCE_FINALIZE :Option <unsafe extern "C" fn (obj: *mut Object )>; +const ABSTRACT :bool =false ; +const INSTANCE_INIT :Option <unsafe extern "C" fn (obj: *mut Object )> =None ; +const INSTANCE_POST_INIT :Option <unsafe extern "C" fn (obj: *mut Object )> =None ; +const INSTANCE_FINALIZE :Option <unsafe extern "C" fn (obj: *mut Object )> =None ; }pub trait Class {
rust/qemu-api/tests/tests.rs +0 -4
@@ -58,10 +58,6 @@ impl ObjectImpl for DummyState {const TYPE_INFO : qemu_api::bindings::TypeInfo = qemu_api::type_info! {Self };const TYPE_NAME : &'staticCStr =c_str! ("dummy" );const PARENT_TYPE_NAME :Option <&'staticCStr > =Some (device_class::TYPE_DEVICE ); -const ABSTRACT :bool =false ; -const INSTANCE_INIT :Option <unsafe extern "C" fn (obj: *mut Object )> =None ; -const INSTANCE_POST_INIT :Option <unsafe extern "C" fn (obj: *mut Object )> =None ; -const INSTANCE_FINALIZE :Option <unsafe extern "C" fn (obj: *mut Object )> =None ; }impl Class for DummyClass {
Signature · 1 line
2.47.1
Re: [PATCH 07/26] rust: qom: add default definitions for ObjectImpl
Quoted 5 lines · Paolo Bonzini
Date: Mon, 9 Dec 2024 13:36:58 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 07/26] rust: qom: add default definitions for ObjectImpl
X-Mailer: git-send-email 2.47.1
Quoted 8 lines
Remove a bunch of duplicate const definitions.
Signed-off-by Paolo Bonzini <[email protected]>--- rust/hw/char/pl011/src/device.rs | 6 ------ rust/qemu-api/src/definitions.rs | 8 ++++---- rust/qemu-api/tests/tests.rs | 4 ---- 3 files changed, 4 insertions(+), 14 deletions(-)
PATCH 8/26 rust: qom: rename Class trait to ClassInitImpl
In reply to Paolo BonziniWhile at it, document it.
--- rust/hw/char/pl011/src/device.rs | 4 ++-- rust/qemu-api/src/definitions.rs | 25 ++++++++++++++++++++++--- rust/qemu-api/tests/tests.rs | 4 ++-- 3 files changed, 26 insertions(+), 7 deletions(-)
rust/hw/char/pl011/src/device.rs +2 -2
@@ -117,7 +117,7 @@ pub struct PL011Class { _inner: [u8; 0], } -impl qemu_api::definitions::Class for PL011Class { +impl qemu_api::definitions::ClassInitImpl for PL011Class {const CLASS_INIT :Option <unsafe extern "C" fn (klass: *mut ObjectClass , data: *mut c_void )> =Some (crate ::device_class::pl011_class_init); const CLASS_BASE_INIT: Option<
@@ -650,7 +650,7 @@ pub struct PL011LuminaryClass { } } -impl qemu_api::definitions::Class for PL011LuminaryClass { +impl qemu_api::definitions::ClassInitImpl for PL011LuminaryClass {const CLASS_INIT :Option <unsafe extern "C" fn (klass: *mut ObjectClass , data: *mut c_void )> =None ; const CLASS_BASE_INIT: Option<
rust/qemu-api/src/definitions.rs +22 -3
@@ -20,8 +20,27 @@ pub trait ObjectImpl {const INSTANCE_FINALIZE :Option <unsafe extern "C" fn (obj: *mut Object )> =None ; } -pub trait Class { +/// Trait used to fill in a class struct. +/// +/// Each QOM class that has virtual methods describes them in a +/// _class struct_. Class structs include a parent field corresponding +/// to the vtable of the parent class, all the way up to [`ObjectClass`]. +/// Each QOM type has one such class struct. +/// +/// The Rust implementation of methods will usually come from a trait +/// like [`ObjectImpl`]. +pub trait ClassInitImpl { +/// Function that is called after all parent class initialization +/// has occurred. On entry, the virtual method pointers are set to +/// the default values coming from the parent classes; the function +/// can change them to override virtual methods of a parent class. const CLASS_INIT :Option <unsafe extern "C" fn (klass: *mut ObjectClass , data: *mut c_void )>; + +/// Called on descendent classes after all parent class initialization +/// has occurred, but before the class itself is initialized. This +/// is only useful if a class is not a leaf, and can be used to undo +/// the effects of copying the contents of the parent's class struct +/// to the descendants. const CLASS_BASE_INIT :Option <unsafe extern "C" fn (klass: *mut ObjectClass , data: *mut c_void ), >;
@@ -82,8 +101,8 @@ macro_rules! type_info { instance_finalize: <$t as $crate::definitions::ObjectImpl>::INSTANCE_FINALIZE, abstract_: <$t as $crate::definitions::ObjectImpl>::ABSTRACT, class_size: ::core::mem::size_of::<<$t as $crate::definitions::ObjectImpl>::Class>(), - class_init: <<$t as $crate::definitions::ObjectImpl>::Class as $crate::definitions::Class>::CLASS_INIT, - class_base_init: <<$t as $crate::definitions::ObjectImpl>::Class as $crate::definitions::Class>::CLASS_BASE_INIT, + class_init: <<$t as $crate::definitions::ObjectImpl>::Class as $crate::definitions::ClassInitImpl>::CLASS_INIT, + class_base_init: <<$t as $crate::definitions::ObjectImpl>::Class as $crate::definitions::ClassInitImpl>::CLASS_BASE_INIT, class_data: ::core::ptr::null_mut(), interfaces: ::core::ptr::null_mut(), };
rust/qemu-api/tests/tests.rs +2 -2
@@ -7,7 +7,7 @@use qemu_api::{ bindings::*, c_str, declare_properties, define_property, - definitions::{Class ,ObjectImpl }, + definitions::{ClassInitImpl ,ObjectImpl }, device_class, device_class_init, zeroable::Zeroable , };
@@ -60,7 +60,7 @@ impl ObjectImpl for DummyState {const PARENT_TYPE_NAME :Option <&'staticCStr > =Some (device_class::TYPE_DEVICE ); } -impl Class for DummyClass { +impl ClassInitImpl for DummyClass {const CLASS_INIT :Option <unsafe extern "C" fn (klass: *mut ObjectClass , data: *mut c_void )> =Some (dummy_class_init); const CLASS_BASE_INIT: Option<
Signature · 1 line
2.47.1
Re: [PATCH 08/26] rust: qom: rename Class trait to ClassInitImpl
Quoted 5 lines · Paolo Bonzini
Date: Mon, 9 Dec 2024 13:36:59 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 08/26] rust: qom: rename Class trait to ClassInitImpl
X-Mailer: git-send-email 2.47.1
Quoted 8 lines
While at it, document it.
Signed-off-by Paolo Bonzini <[email protected]>--- rust/hw/char/pl011/src/device.rs | 4 ++-- rust/qemu-api/src/definitions.rs | 25 ++++++++++++++++++++++--- rust/qemu-api/tests/tests.rs | 4 ++-- 3 files changed, 26 insertions(+), 7 deletions(-)
LGTM,
PATCH 9/26 rust: qom: convert type_info! macro to an associated const
In reply to Paolo Bonzinitype_info! is only used in the definition of ObjectImpl::TYPE_INFO, and in fact in all of them. Pull type_info!'s definition into the ObjectImpl trait, thus simplifying the external interface of qemu_api::definitions.
--- rust/hw/char/pl011/src/device.rs | 6 ++-- rust/qemu-api/src/definitions.rs | 50 ++++++++++++++------------------ rust/qemu-api/tests/tests.rs | 1 - 3 files changed, 24 insertions(+), 33 deletions(-)
rust/hw/char/pl011/src/device.rs +2 -4
@@ -106,7 +106,6 @@ pub struct PL011State {impl ObjectImpl for PL011State {type Class =PL011Class ; -const TYPE_INFO : qemu_api::bindings::TypeInfo = qemu_api::type_info! {Self };const TYPE_NAME : &'staticCStr =crate ::TYPE_PL011 ;const PARENT_TYPE_NAME :Option <&'staticCStr > =Some (TYPE_SYS_BUS_DEVICE );const INSTANCE_INIT :Option <unsafe extern "C" fn (obj: *mut Object )> =Some (pl011_init);
@@ -149,7 +148,7 @@ unsafe fn init(&mut self) { addr_of_mut!(*self).cast::<Object>(), &PL011_OPS, addr_of_mut!(*self).cast::<c_void>(), - Self::TYPE_INFO.name, + Self::TYPE_NAME.as_ptr(), 0x1000, );sysbus_init_mmio (sbd,addr_of_mut! (self.iomem));
@@ -598,7 +597,7 @@ pub fn post_load(&mut self, _version_id: u32) -> Result<(), ()> { chr: *mut Chardev, ) -> *mut DeviceState {unsafe { -let dev: *mut DeviceState =qdev_new (PL011State ::TYPE_INFO .name); +let dev: *mut DeviceState =qdev_new (PL011State ::TYPE_NAME .as_ptr ());let sysbus: *mut SysBusDevice = dev.cast ::<SysBusDevice >();qdev_prop_set_chr (dev,c_str! ("chardev" ).as_ptr (), chr);
@@ -660,7 +659,6 @@ impl qemu_api::definitions::ClassInitImpl for PL011LuminaryClass {impl ObjectImpl for PL011Luminary {type Class =PL011LuminaryClass ; -const TYPE_INFO : qemu_api::bindings::TypeInfo = qemu_api::type_info! {Self };const TYPE_NAME : &'staticCStr =crate ::TYPE_PL011_LUMINARY ;const PARENT_TYPE_NAME :Option <&'staticCStr > =Some (crate ::TYPE_PL011 );const INSTANCE_INIT :Option <unsafe extern "C" fn (obj: *mut Object )> =Some (pl011_luminary_init);
rust/qemu-api/src/definitions.rs +22 -28
65 lines not on this page · raw message
rust/qemu-api/tests/tests.rs +0 -1
@@ -55,7 +55,6 @@ pub struct DummyClass {impl ObjectImpl for DummyState {type Class =DummyClass ; -const TYPE_INFO : qemu_api::bindings::TypeInfo = qemu_api::type_info! {Self };const TYPE_NAME : &'staticCStr =c_str! ("dummy" );const PARENT_TYPE_NAME :Option <&'staticCStr > =Some (device_class::TYPE_DEVICE ); }
Signature · 1 line
2.47.1
Re: [PATCH 09/26] rust: qom: convert type_info! macro to an associated const
Quoted 10 lines · Paolo Bonzini
Date: Mon, 9 Dec 2024 13:37:00 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 09/26] rust: qom: converttype_info! macro to an associated
const
X-Mailer: git-send-email 2.47.1
type_info! is only used in the definition ofObjectImpl::TYPE_INFO, and in fact in all of them. Pull type_info!'s definition into the ObjectImpl trait, thus simplifying the external interface ofqemu_api::definitions.
Quoted 6 lines
Signed-off-by Paolo Bonzini <[email protected]>--- rust/hw/char/pl011/src/device.rs | 6 ++-- rust/qemu-api/src/definitions.rs | 50 ++++++++++++++------------------ rust/qemu-api/tests/tests.rs | 1 - 3 files changed, 24 insertions(+), 33 deletions(-)
PATCH 10/26 rust: qom: move ClassInitImpl to the instance side
In reply to Paolo BonziniPut all traits on the instance struct, which makes it possible to reuse class structs if no new virtual methods or class fields are added. This is almost always the case for devices (because they are leaf classes), which is the primary use case for Rust.
This is also simpler: soon we will find the implemented methods without macros, and this removes the need to go from the class struct to the instance struct to find the implementation of the *Impl traits.
--- rust/hw/char/pl011/src/device.rs | 4 ++-- rust/qemu-api/src/definitions.rs | 8 ++++---- rust/qemu-api/tests/tests.rs | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-)
rust/hw/char/pl011/src/device.rs +2 -2
@@ -116,7 +116,7 @@ pub struct PL011Class { _inner: [u8; 0], } -impl qemu_api::definitions::ClassInitImpl for PL011Class { +impl qemu_api::definitions::ClassInitImpl for PL011State {const CLASS_INIT :Option <unsafe extern "C" fn (klass: *mut ObjectClass , data: *mut c_void )> =Some (crate ::device_class::pl011_class_init); const CLASS_BASE_INIT: Option<
@@ -649,7 +649,7 @@ pub struct PL011LuminaryClass { } } -impl qemu_api::definitions::ClassInitImpl for PL011LuminaryClass { +impl qemu_api::definitions::ClassInitImpl for PL011Luminary {const CLASS_INIT :Option <unsafe extern "C" fn (klass: *mut ObjectClass , data: *mut c_void )> =None ; const CLASS_BASE_INIT: Option<
rust/qemu-api/src/definitions.rs +4 -4
@@ -9,8 +9,8 @@use crate ::bindings::{Object ,ObjectClass ,TypeInfo };/// Trait a type must implement to be registered with QEMU. -pub trait ObjectImpl :Sized { -type Class :ClassInitImpl ; +pub trait ObjectImpl :ClassInitImpl +Sized { +type Class ;const TYPE_NAME : &'staticCStr ;const PARENT_TYPE_NAME :Option <&'staticCStr >;const ABSTRACT :bool =false ;
@@ -32,8 +32,8 @@ pub trait ObjectImpl: Sized { instance_finalize: Self::INSTANCE_FINALIZE, abstract_: Self::ABSTRACT, class_size: core::mem::size_of::<Self::Class>(), - class_init: <Self::Class as ClassInitImpl>::CLASS_INIT, - class_base_init: <Self::Class as ClassInitImpl>::CLASS_BASE_INIT, + class_init: <Self as ClassInitImpl>::CLASS_INIT, + class_base_init: <Self as ClassInitImpl>::CLASS_BASE_INIT, class_data: core::ptr::null_mut(), interfaces: core::ptr::null_mut(), };
rust/qemu-api/tests/tests.rs +1 -1
@@ -59,7 +59,7 @@ impl ObjectImpl for DummyState {const PARENT_TYPE_NAME :Option <&'staticCStr > =Some (device_class::TYPE_DEVICE ); } -impl ClassInitImpl for DummyClass { +impl ClassInitImpl for DummyState {const CLASS_INIT :Option <unsafe extern "C" fn (klass: *mut ObjectClass , data: *mut c_void )> =Some (dummy_class_init); const CLASS_BASE_INIT: Option<
Signature · 1 line
2.47.1
Re: [PATCH 10/26] rust: qom: move ClassInitImpl to the instance side
Quoted 14 lines · Paolo Bonzini
Date: Mon, 9 Dec 2024 13:37:01 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 10/26] rust: qom: move ClassInitImpl to the instance side
X-Mailer: git-send-email 2.47.1Put all traits on the instance struct, which makes it possible to reuse class structs if no new virtual methods or class fields are added. This is almost always the case for devices (because they are leaf classes), which is the primary use case for Rust.
This is also simpler: soon we will find the implemented methods without macros, and this removes the need to go from the class struct to the instance struct to find the implementation of the *Impl traits.
Quoted 6 lines
Signed-off-by Paolo Bonzini <[email protected]>--- rust/hw/char/pl011/src/device.rs | 4 ++-- rust/qemu-api/src/definitions.rs | 8 ++++---- rust/qemu-api/tests/tests.rs | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-)
PATCH 11/26 rust: qdev: move device_class_init! body to generic function, ClassInitImpl implementation to macro
In reply to Paolo BonziniUse a trait to access the former parameters to device_class_init!. This allows hiding the details of the class_init implementation behind a generic function and makes higher-level functionality available from qemu_api.
The implementation of ClassInitImpl is then the same for all devices and is easily macroized. Later on, we can remove the need to implement ClassInitImpl by hand for all device types, and stop making rust_device_class_init<>() public.
While at it, document the members of DeviceImpl.
--- rust/hw/char/pl011/src/device.rs | 34 +++++----- rust/hw/char/pl011/src/device_class.rs | 8 --- rust/qemu-api/src/device_class.rs | 87 +++++++++++++++++++++----- rust/qemu-api/tests/tests.rs | 30 ++++----- 4 files changed, 103 insertions(+), 56 deletions(-)
rust/hw/char/pl011/src/device.rs +19 -15
@@ -12,11 +12,13 @@ bindings::{self, *}, c_str, definitions::ObjectImpl, - device_class::TYPE_SYS_BUS_DEVICE, + device_class::{DeviceImpl, TYPE_SYS_BUS_DEVICE}, + impl_device_class, irq::InterruptSource, };use crate ::{ + device_class, memory_ops::PL011_OPS , registers::{self,Interrupt },RegisterOffset ,
@@ -116,14 +118,20 @@ pub struct PL011Class { _inner: [u8; 0], } -impl qemu_api::definitions::ClassInitImpl for PL011State { -const CLASS_INIT :Option <unsafe extern "C" fn (klass: *mut ObjectClass , data: *mut c_void )> = -Some (crate ::device_class::pl011_class_init); -const CLASS_BASE_INIT :Option < -unsafe extern "C" fn (klass: *mut ObjectClass , data: *mut c_void ), - > =None ; +impl DeviceImpl for PL011State { +fn properties () -> &'static [Property ] { + &device_class::PL011_PROPERTIES + } +fn vmsd () ->Option <&'staticVMStateDescription > { +Some (&device_class::VMSTATE_PL011 ) + } +const REALIZE :Option <unsafe extern "C" fn (*mut DeviceState , *mut *mut Error )> = +Some (device_class::pl011_realize); +const RESET :Option <unsafe extern "C" fn (*mut DeviceState )> =Some (device_class::pl011_reset); } +impl_device_class! (PL011State ); +impl PL011State {/// Initializes a pre-allocated, unitialized instance of `PL011State`. ///
@@ -649,17 +657,13 @@ pub struct PL011LuminaryClass { } } -impl qemu_api::definitions::ClassInitImpl for PL011Luminary { -const CLASS_INIT :Option <unsafe extern "C" fn (klass: *mut ObjectClass , data: *mut c_void )> = -None ; -const CLASS_BASE_INIT :Option < -unsafe extern "C" fn (klass: *mut ObjectClass , data: *mut c_void ), - > =None ; -} -impl ObjectImpl for PL011Luminary {type Class =PL011LuminaryClass ;const TYPE_NAME : &'staticCStr =crate ::TYPE_PL011_LUMINARY ;const PARENT_TYPE_NAME :Option <&'staticCStr > =Some (crate ::TYPE_PL011 );const INSTANCE_INIT :Option <unsafe extern "C" fn (obj: *mut Object )> =Some (pl011_luminary_init); } + +impl DeviceImpl for PL011Luminary {} + +impl_device_class! (PL011Luminary );
rust/hw/char/pl011/src/device_class.rs +0 -8
@@ -93,14 +93,6 @@ extern "C" fn pl011_post_load(opaque: *mut c_void, version_id: c_int) -> c_int { ), } -qemu_api::device_class_init! { - pl011_class_init, - props =>PL011_PROPERTIES , - realize_fn =>Some (pl011_realize), - legacy_reset_fn =>Some (pl011_reset), - vmsd =>VMSTATE_PL011 , -} -/// # Safety /// /// We expect the FFI user of this function to pass a valid pointer, that has
rust/qemu-api/src/device_class.rs +71 -16
96 lines not on this page · raw message
rust/qemu-api/tests/tests.rs +13 -17
@@ -2,13 +2,14 @@// Author(s): Manos Pitsidianakis <[email protected]> // SPDX-License-Identifier: GPL-2.0-or-later -use std::{ffi::CStr , os::raw::c_void}; +use std::ffi::CStr ;use qemu_api::{ bindings::*, c_str, declare_properties, define_property, - definitions::{ClassInitImpl ,ObjectImpl }, - device_class, device_class_init, + definitions::ObjectImpl , + device_class::{self,DeviceImpl }, + impl_device_class, zeroable::Zeroable , };
@@ -45,28 +46,23 @@ pub struct DummyClass { ), } -device_class_init! { - dummy_class_init, - props =>DUMMY_PROPERTIES , - realize_fn =>None , - legacy_reset_fn =>None , - vmsd =>VMSTATE , - } -impl ObjectImpl for DummyState {type Class =DummyClass ;const TYPE_NAME : &'staticCStr =c_str! ("dummy" );const PARENT_TYPE_NAME :Option <&'staticCStr > =Some (device_class::TYPE_DEVICE ); } -impl ClassInitImpl for DummyState { -const CLASS_INIT :Option <unsafe extern "C" fn (klass: *mut ObjectClass , data: *mut c_void )> = -Some (dummy_class_init); -const CLASS_BASE_INIT :Option < -unsafe extern "C" fn (klass: *mut ObjectClass , data: *mut c_void ), - > =None ; +impl DeviceImpl for DummyState { +fn properties () -> &'static [Property ] { + &DUMMY_PROPERTIES + } +fn vmsd () ->Option <&'staticVMStateDescription > { +Some (&VMSTATE ) + } } +impl_device_class! (DummyState ); +unsafe {module_call_init (module_init_type::MODULE_INIT_QOM );object_unref (object_new (DummyState ::TYPE_NAME .as_ptr ()).cast ());
Signature · 1 line
2.47.1
Re: [PATCH 11/26] rust: qdev: move device_class_init! body to generic function, ClassInitImpl implementation to macro
Quoted 18 lines · Paolo Bonzini
Date: Mon, 9 Dec 2024 13:37:02 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 11/26] rust: qdev: movedevice_class_init! body to generic
function, ClassInitImpl implementation to macro
X-Mailer: git-send-email 2.47.1Use a trait to access the former parameters to
device_class_init!. This allows hiding the details of theclass_initimplementation behind a generic function and makes higher-level functionality available fromqemu_api.The implementation of ClassInitImpl is then the same for all devices and is easily macroized. Later on, we can remove the need to implement ClassInitImpl by hand for all device types, and stop making rust_device_class_init<>() public.
While at it, document the members of DeviceImpl.
Quoted 7 lines
Signed-off-by Paolo Bonzini <[email protected]>--- rust/hw/char/pl011/src/device.rs | 34 +++++----- rust/hw/char/pl011/src/device_class.rs | 8 --- rust/qemu-api/src/device_class.rs | 87 +++++++++++++++++++++----- rust/qemu-api/tests/tests.rs | 30 ++++----- 4 files changed, 103 insertions(+), 56 deletions(-)
PATCH 12/26 rust: qdev: move bridge for realize and reset functions out of pl011
In reply to Paolo BonziniAllow the DeviceImpl trait to expose safe Rust functions. rust_device_class_init<> adds thunks around the functions in DeviceImpl.
--- rust/hw/char/pl011/src/device.rs | 5 ++-- rust/hw/char/pl011/src/device_class.rs | 26 ------------------- rust/qemu-api/src/definitions.rs | 2 +- rust/qemu-api/src/device_class.rs | 36 +++++++++++++++++++++----- 4 files changed, 33 insertions(+), 36 deletions(-)
rust/hw/char/pl011/src/device.rs +2 -3
@@ -125,9 +125,8 @@ fn properties() -> &'static [Property] {fn vmsd () ->Option <&'staticVMStateDescription > {Some (&device_class::VMSTATE_PL011 ) } -const REALIZE :Option <unsafe extern "C" fn (*mut DeviceState , *mut *mut Error )> = -Some (device_class::pl011_realize); -const RESET :Option <unsafe extern "C" fn (*mut DeviceState )> =Some (device_class::pl011_reset); +const REALIZE :Option <fn (&mut Self )> =Some (Self ::realize); +const RESET :Option <fn (&mut Self )> =Some (Self ::reset); }impl_device_class! (PL011State );
rust/hw/char/pl011/src/device_class.rs +0 -26
@@ -92,29 +92,3 @@ extern "C" fn pl011_post_load(opaque: *mut c_void, version_id: c_int) -> c_int { default =true ), } - -/// # Safety -/// -/// We expect the FFI user of this function to pass a valid pointer, that has -/// the same size as [`PL011State`]. We also expect the device is -/// readable/writeable from one thread at any time. -pub unsafe extern "C" fn pl011_realize (dev: *mut DeviceState , _errp: *mut *mut Error ) { -unsafe { -assert! (!dev.is_null ()); -let mut state =NonNull ::new_unchecked (dev.cast ::<PL011State >()); - state.as_mut ().realize (); - } -} - -/// # Safety -/// -/// We expect the FFI user of this function to pass a valid pointer, that has -/// the same size as [`PL011State`]. We also expect the device is -/// readable/writeable from one thread at any time. -pub unsafe extern "C" fn pl011_reset (dev: *mut DeviceState ) { -unsafe { -assert! (!dev.is_null ()); -let mut state =NonNull ::new_unchecked (dev.cast ::<PL011State >()); - state.as_mut ().reset (); - } -}
rust/qemu-api/src/definitions.rs +1 -1
@@ -47,7 +47,7 @@ pub trait ObjectImpl: ClassInitImpl + Sized {/// Each QOM type has one such class struct. /// /// The Rust implementation of methods will usually come from a trait -/// like [`ObjectImpl`]. +/// like [`ObjectImpl`] or [`DeviceImpl`](crate::device_class::DeviceImpl). pub trait ClassInitImpl {/// Function that is called after all parent class initialization /// has occurred. On entry, the virtual method pointers are set to
rust/qemu-api/src/device_class.rs +30 -6
@@ -17,14 +17,14 @@ pub trait DeviceImpl {/// /// If not `None`, the parent class's `realize` method is overridden /// with the function pointed to by `REALIZE`. -const REALIZE :Option <unsafe extern "C" fn (*mut DeviceState , *mut *mut Error )> =None ; +const REALIZE :Option <fn (&mut Self )> =None ;/// If not `None`, the parent class's `reset` method is overridden /// with the function pointed to by `RESET`. /// /// Rust does not yet support the three-phase reset protocol; this is /// usually okay for leaf classes. -const RESET :Option <unsafe extern "C" fn (dev: *mut DeviceState )> =None ; +const RESET :Option <fn (&mut Self )> =None ;/// An array providing the properties that the user can set on the /// device. Not a `const` because referencing statics in constants
@@ -41,6 +41,30 @@ fn vmsd() -> Option<&'static VMStateDescription> { } } +/// # Safety +/// +/// This function is only called through the QOM machinery and +/// the `impl_device_class!` macro. +/// We expect the FFI user of this function to pass a valid pointer that +/// can be downcasted to type `T`. We also expect the device is +/// readable/writeable from one thread at any time. +unsafe extern "C" fn rust_realize_fn <T :DeviceImpl >(dev: *mut DeviceState , _errp: *mut *mut Error ) { +assert! (!dev.is_null ()); +let state = dev.cast ::<T >(); +T ::REALIZE .unwrap ()(unsafe { &mut *state }); +} + +/// # Safety +/// +/// We expect the FFI user of this function to pass a valid pointer that +/// can be downcasted to type `T`. We also expect the device is +/// readable/writeable from one thread at any time. +unsafe extern "C" fn rust_reset_fn <T :DeviceImpl >(dev: *mut DeviceState ) { +assert! (!dev.is_null ()); +let state = dev.cast ::<T >(); +T ::RESET .unwrap ()(unsafe { &mut *state }); +} +/// # Safety /// /// We expect the FFI user of this function to pass a valid pointer that
@@ -53,11 +77,11 @@ fn vmsd() -> Option<&'static VMStateDescription> {let mut dc = ::core::ptr::NonNull ::new (klass.cast ::<DeviceClass >()).unwrap ();unsafe {let dc = dc.as_mut (); -if let Some (realize_fn) = <T as DeviceImpl >::REALIZE { - dc.realize =Some (realize_fn); +if <T as DeviceImpl >::REALIZE .is_some () { + dc.realize =Some (rust_realize_fn ::<T >); } -if let Some (reset_fn) = <T as DeviceImpl >::RESET { - bindings::device_class_set_legacy_reset (dc,Some (reset_fn)); +if <T as DeviceImpl >::RESET .is_some () { + bindings::device_class_set_legacy_reset (dc,Some (rust_reset_fn ::<T >)); }if let Some (vmsd) = <T as DeviceImpl >::vmsd () { dc.vmsd = vmsd;
Signature · 1 line
2.47.1
Re: [PATCH 12/26] rust: qdev: move bridge for realize and reset functions out of pl011
Quoted 10 lines · Paolo Bonzini
Date: Mon, 9 Dec 2024 13:37:03 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 12/26] rust: qdev: move bridge for realize and reset
functions out of pl011
X-Mailer: git-send-email 2.47.1Allow the DeviceImpl trait to expose safe Rust functions. rust_device_class_init<> adds thunks around the functions in DeviceImpl.
Quoted 8 lines
Signed-off-by Paolo Bonzini <[email protected]>--- rust/hw/char/pl011/src/device.rs | 5 ++-- rust/hw/char/pl011/src/device_class.rs | 26 ------------------- rust/qemu-api/src/definitions.rs | 2 +- rust/qemu-api/src/device_class.rs | 36 +++++++++++++++++++++----- 4 files changed, 33 insertions(+), 36 deletions(-)
PATCH 13/26 rust: qom: automatically use Drop trait to implement instance_finalize
In reply to Paolo BonziniReplace the customizable INSTANCE_FINALIZE with a generic function that drops the Rust object.
--- rust/qemu-api/src/definitions.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-)
rust/qemu-api/src/definitions.rs +8 -2
@@ -8,6 +8,13 @@use crate ::bindings::{Object ,ObjectClass ,TypeInfo }; +unsafe extern "C" fn drop_object <T :ObjectImpl >(obj: *mut Object ) { +// SAFETY: obj is an instance of T, since drop_object<T> +// is called from QOM core as the instance_finalize function +// for class T +unsafe { std::ptr::drop_in_place (obj.cast ::<T >()) } +} +/// Trait a type must implement to be registered with QEMU. pub trait ObjectImpl :ClassInitImpl +Sized {type Class ;
@@ -16,7 +23,6 @@ pub trait ObjectImpl: ClassInitImpl + Sized {const ABSTRACT :bool =false ;const INSTANCE_INIT :Option <unsafe extern "C" fn (obj: *mut Object )> =None ;const INSTANCE_POST_INIT :Option <unsafe extern "C" fn (obj: *mut Object )> =None ; -const INSTANCE_FINALIZE :Option <unsafe extern "C" fn (obj: *mut Object )> =None ;const TYPE_INFO :TypeInfo =TypeInfo { name:Self ::TYPE_NAME .as_ptr (),
@@ -29,7 +35,7 @@ pub trait ObjectImpl: ClassInitImpl + Sized { instance_align: core::mem::align_of::<Self>(), instance_init: Self::INSTANCE_INIT, instance_post_init: Self::INSTANCE_POST_INIT, - instance_finalize: Self::INSTANCE_FINALIZE, + instance_finalize: Some(drop_object::<Self>), abstract_: Self::ABSTRACT, class_size: core::mem::size_of::<Self::Class>(), class_init: <Self as ClassInitImpl>::CLASS_INIT,
Signature · 1 line
2.47.1
Re: [PATCH 13/26] rust: qom: automatically use Drop trait to implement instance_finalize
Quoted 6 lines · Paolo Bonzini
Date: Mon, 9 Dec 2024 13:37:04 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 13/26] rust: qom: automatically use Drop trait to implement
instance_finalize
X-Mailer: git-send-email 2.47.1
Quoted 8 lines
Replace the customizable
INSTANCE_FINALIZEwith a generic function that drops the Rust object.Signed-off-by Paolo Bonzini <[email protected]>--- rust/qemu-api/src/definitions.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-)
Great idea. It nicely balances the differences between Rust and C QOM conventions.
Re: [PATCH 13/26] rust: qom: automatically use Drop trait to implement instance_finalize
Quoted 2 lines · Zhao Liu
Great idea. It nicely balances the differences between Rust and C QOM conventions.
Except it does not work. :( Suppose you have
pub struct MySuperclass {
parent: DeviceState,
field: Box<MyData>,
...
}
impl Drop for MySuperclass {
...
}
pub struct MySubclass {
parent: MySuperclass,
...
}When instance_finalize is called for MySubclass, it will walk the struct's list of fields and call the drop method for MySuperclass. Then, object_deinit recurses to the superclass and calls the same drop method again. This will cause double-freeing of the Box<MyData>, or more in general double-dropping.
What's happening here is that QOM wants to control the drop order of MySuperclass and MySubclass's fields. To do so, the parent field must be marked ManuallyDrop<>, which is quite ugly. Perhaps we can add a wrapper type ParentField<> that is specific to QOM. This hides the implementation detail of *what* is special about the ParentField, and it will also be easy to check for in the #[derive(Object)] macro. Maybe in the future it will even make sense to have special functions implemented on ParentField, I don't know...
Paolo
Re: [PATCH 13/26] rust: qom: automatically use Drop trait to implement instance_finalize
Quoted 26 lines · Paolo Bonzini
Date: Wed, 11 Dec 2024 13:42:32 +0100
From: Paolo Bonzini <[email protected]>
Subject: Re: [PATCH 13/26] rust: qom: automatically use Drop trait to
implementinstance_finalizeQuoted 2 lines · Zhao Liu
Great idea. It nicely balances the differences between Rust and C QOM conventions.
Except it does not work. :( Suppose you have
pub struct MySuperclass { parent: DeviceState, field: Box<MyData>, ... } impl Drop for MySuperclass { ... } pub struct MySubclass { parent: MySuperclass, ... }
Quoted 5 lines
When
instance_finalizeis called for MySubclass, it will walk the struct's list of fields and call the drop method for MySuperclass. Then,object_deinitrecurses to the superclass and calls the same drop method again. This will cause double-freeing of the Box<MyData>, or more in general double-dropping.
Good catch! Yes, there is indeed such an issue... The above example could become a test case :-), which I supposed could trigger a double- dropping error when compiling.
Quoted 8 lines
What's happening here is that QOM wants to control the drop order of MySuperclass and MySubclass's fields. To do so, the parent field must be marked ManuallyDrop<>, which is quite ugly. Perhaps we can add a wrapper type ParentField<> that is specific to QOM. This hides the implementation detail of *what* is special about the ParentField, and it will also be easy to check for in the #[derive(Object)] macro. Maybe in the future it will even make sense to have special functions implemented on ParentField, I don't know...
I also looked into the implementation of ManuallyDrop, and I agree with a new ParentField (or simply ObjectParent). This wrapper is simple enough but also useful for QOM. I will pay more attention to the recursed relationships in QOM in review as well...
Thanks,
Zhao
PATCH 14/26 rust: qom: move bridge for TypeInfo functions out of pl011
In reply to Paolo BonziniAllow the ObjectImpl trait to expose Rust functions that avoid raw pointers (though INSTANCE_INIT for example is still unsafe). ObjectImpl::TYPE_INFO adds thunks around the functions in ObjectImpl.
While at it, document TypeInfo.
--- rust/hw/char/pl011/src/device.rs | 40 +++++++-------------- rust/qemu-api/src/definitions.rs | 61 +++++++++++++++++++++++++++++--- 2 files changed, 69 insertions(+), 32 deletions(-)
rust/hw/char/pl011/src/device.rs +12 -28
@@ -110,7 +110,7 @@ impl ObjectImpl for PL011State {type Class =PL011Class ;const TYPE_NAME : &'staticCStr =crate ::TYPE_PL011 ;const PARENT_TYPE_NAME :Option <&'staticCStr > =Some (TYPE_SYS_BUS_DEVICE ); -const INSTANCE_INIT :Option <unsafe extern "C" fn (obj: *mut Object )> =Some (pl011_init); +const INSTANCE_INIT :Option <unsafe fn (&mut Self )> =Some (Self ::init); }#[repr( C )]
@@ -615,19 +615,6 @@ pub fn post_load(&mut self, _version_id: u32) -> Result<(), ()> { } } -/// # Safety -/// -/// We expect the FFI user of this function to pass a valid pointer, that has -/// the same size as [`PL011State`]. We also expect the device is -/// readable/writeable from one thread at any time. -pub unsafe extern "C" fn pl011_init (obj: *mut Object ) { -unsafe { -debug_assert! (!obj.is_null ()); -let mut state =NonNull ::new_unchecked (obj.cast ::<PL011State >()); - state.as_mut ().init (); - } -} -#[repr( C )] #[derive( Debug , qemu_api_macros:: Object )] /// PL011 Luminary device model.
@@ -640,19 +627,16 @@ pub struct PL011LuminaryClass { _inner: [u8; 0], } -/// Initializes a pre-allocated, unitialized instance of `PL011Luminary`. -/// -/// # Safety -/// -/// We expect the FFI user of this function to pass a valid pointer, that has -/// the same size as [`PL011Luminary`]. We also expect the device is -/// readable/writeable from one thread at any time. -pub unsafe extern "C" fn pl011_luminary_init (obj: *mut Object ) { -unsafe { -debug_assert! (!obj.is_null ()); -let mut state =NonNull ::new_unchecked (obj.cast ::<PL011Luminary >()); -let state = state.as_mut (); - state.parent_obj.device_id =DeviceId ::Luminary ; +impl PL011Luminary { +/// Initializes a pre-allocated, unitialized instance of `PL011Luminary`. +/// +/// # Safety +/// +/// We expect the FFI user of this function to pass a valid pointer, that +/// has the same size as [`PL011Luminary`]. We also expect the device is +/// readable/writeable from one thread at any time. +unsafe fn init (&mut self) { + self.parent_obj.device_id =DeviceId ::Luminary ; } }
@@ -660,7 +644,7 @@ impl ObjectImpl for PL011Luminary {type Class =PL011LuminaryClass ;const TYPE_NAME : &'staticCStr =crate ::TYPE_PL011_LUMINARY ;const PARENT_TYPE_NAME :Option <&'staticCStr > =Some (crate ::TYPE_PL011 ); -const INSTANCE_INIT :Option <unsafe extern "C" fn (obj: *mut Object )> =Some (pl011_luminary_init); +const INSTANCE_INIT :Option <unsafe fn (&mut Self )> =Some (Self ::init); }impl DeviceImpl for PL011Luminary {}
rust/qemu-api/src/definitions.rs +57 -4
84 lines not on this page · raw message
Signature · 1 line
2.47.1
Re: [PATCH 14/26] rust: qom: move bridge for TypeInfo functions out of pl011
Quoted 24 lines · Paolo Bonzini
Date: Mon, 9 Dec 2024 13:37:05 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 14/26] rust: qom: move bridge for TypeInfo functions out of
pl011
X-Mailer: git-send-email 2.47.1Allow the ObjectImpl trait to expose Rust functions that avoid raw pointers (though
INSTANCE_INITfor example is still unsafe).ObjectImpl::TYPE_INFOadds thunks around the functions in ObjectImpl.While at it, document
TypeInfo.Signed-off-by Paolo Bonzini <[email protected]>--- rust/hw/char/pl011/src/device.rs | 40 +++++++-------------- rust/qemu-api/src/definitions.rs | 61 +++++++++++++++++++++++++++++--- 2 files changed, 69 insertions(+), 32 deletions(-)rust/hw/char/pl011/src/device.rs +0
-0
rust/hw/char/pl011/src/device.rs impl ObjectImpl for PL011State { · line 113
Quoted 5 lines
rust/hw/char/pl011/src/device.rs +1
-1@@ -110,7 +110,7 @@ impl ObjectImpl for PL011State {type Class =PL011Class ;const TYPE_NAME : &'staticCStr =crate ::TYPE_PL011 ;const PARENT_TYPE_NAME :Option <&'staticCStr > =Some (TYPE_SYS_BUS_DEVICE ); -const INSTANCE_INIT :Option <unsafe extern "C" fn (obj: *mut Object )> =Some (pl011_init); +const INSTANCE_INIT :Option <unsafe fn (&mut Self )> =Some (Self ::init);
No need to keep unsafe here?
Quoted 22 lines
rust/hw/char/pl011/src/device.rs +17
-0+/// +/// - the struct must be `#[repr(C)]` +/// +/// - `Class` and `TYPE` must match the data in the `TypeInfo` (this is +/// automatic if the class is defined via `ObjectImpl`). +/// +/// - the first field of the struct must be of the instance struct corresponding +/// to the superclass declared as `PARENT_TYPE_NAME` pub trait ObjectImpl :ClassInitImpl +Sized { +/// The QOM class object corresponding to this struct. Not used yet. type Class ; + +/// The name of the type, which can be passed to `object_new()` to +/// generate an instance of this type. const TYPE_NAME : &'staticCStr ; + +/// The parent of the type. This should match the first field of +/// the struct that implements `ObjectImpl`: const PARENT_TYPE_NAME :Option <&'staticCStr >; + +/// Whether the object can be instantiated const ABSTRACT :bool =false ;
rust/hw/char/pl011/src/device.rs impl ObjectImpl for PL011State {
Quoted 10 lines
rust/hw/char/pl011/src/device.rs +8
-2-const INSTANCE_INIT :Option <unsafe extern "C" fn (obj: *mut Object )> =None ; -const INSTANCE_POST_INIT :Option <unsafe extern "C" fn (obj: *mut Object )> =None ; + +/// Function that is called to initialize an object. The parent class will +/// have already been initialized so the type is only responsible for +/// initializing its own members. +/// +/// FIXME: The argument is not really a valid reference. `&mut +/// MaybeUninit<Self>` would be a better description. +const INSTANCE_INIT :Option <unsafe fn (&mut Self )> =None ;
And here.
rust/hw/char/pl011/src/device.rs
Quoted 4 lines
rust/hw/char/pl011/src/device.rs +3
-0+/// Function that is called to finish initialization of an object, once +/// `INSTANCE_INIT` functions have been called. +const INSTANCE_POST_INIT :Option <fn (&mut Self )> =None ;
Otherwise,
Re: [PATCH 14/26] rust: qom: move bridge for TypeInfo functions out of pl011
Quoted 20 lines · Zhao Liu
Quoted 19 lines · Paolo Bonzini
Date: Mon, 9 Dec 2024 13:37:05 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 14/26] rust: qom: move bridge for TypeInfo functions out of
pl011
X-Mailer: git-send-email 2.47.1Allow the ObjectImpl trait to expose Rust functions that avoid raw pointers (though
INSTANCE_INITfor example is still unsafe).ObjectImpl::TYPE_INFOadds thunks around the functions in ObjectImpl.While at it, document
TypeInfo.Signed-off-by Paolo Bonzini <[email protected]>--- rust/hw/char/pl011/src/device.rs | 40 +++++++-------------- rust/qemu-api/src/definitions.rs | 61 +++++++++++++++++++++++++++++--- 2 files changed, 69 insertions(+), 32 deletions(-)
Quoted 12 lines
rust/hw/char/pl011/src/device.rs impl ObjectImpl for PL011State { · line 113
Quoted 10 lines
rust/hw/char/pl011/src/device.rs +1
-1@@ -110,7 +110,7 @@ impl ObjectImpl for PL011State {type Class =PL011Class ;const TYPE_NAME : &'staticCStr =crate ::TYPE_PL011 ;const PARENT_TYPE_NAME :Option <&'staticCStr > =Some (TYPE_SYS_BUS_DEVICE ); -const INSTANCE_INIT :Option <unsafe extern "C" fn (obj: *mut Object )> =Some (pl011_init); +const INSTANCE_INIT :Option <unsafe fn (&mut Self )> =Some (Self ::init);No need to keep
unsafehere?
Right now instance_init is called with only the parent initialized, and the remaining memory zeroed; its purpose is to prepare things for instance_post_init which can then be safe (it's also kind of wrong for instance_post_init to receive a &mut Self, because instance_init will create other pointers to the object, for example in a MemoryRegion's "parent" field).
The right thing to do would be to have an argument of type &mut MaybeUninit<Self>. Then the caller would do something like
let maybe_uninit = obj as *mut MaybeUninit<Self>;
unsafe {
Self::INSTANCE_INIT(&mut *maybe_uninit);
maybe_uninit.assume_init_mut();
}Note however that INSTANCE_INIT would still be unsafe, because its safety promise is that it prepares things for the caller's assume_init_mut().
The way that this will become safe is to use the pinned_init crate from Linux: instance_init returns the initialization as an "impl PinInit<Self>", and then instance_post_init can run with a &self. Until then, however, instance_init has to remain unsafe.
Paolo
Re: [PATCH 14/26] rust: qom: move bridge for TypeInfo functions out of pl011
Quoted 11 lines
Quoted 4 lines
rust/hw/char/pl011/src/device.rs impl ObjectImpl for PL011State { · line 113
Quoted 2 lines
rust/hw/char/pl011/src/device.rs +1
-1-const INSTANCE_INIT :Option <unsafe extern "C" fn (obj: *mut Object )> =Some (pl011_init); +const INSTANCE_INIT :Option <unsafe fn (&mut Self )> =Some (Self ::init);No need to keep
unsafehere?Right now
instance_initis called with only the parent initialized, and the remaining memory zeroed; its purpose is to prepare things forinstance_post_initwhich can then be safe (it's also kind of wrong forinstance_post_initto receive a &mut Self, becauseinstance_initwill create other pointers to the object, for example in a MemoryRegion's "parent" field).
Thank you for explanation. It makes a lot of sense.
Quoted 11 lines
The right thing to do would be to have an argument of type &mut MaybeUninit<Self>. Then the caller would do something like
let maybe_uninit = obj as *mut MaybeUninit<Self>; unsafe { Self::INSTANCE_INIT(&mut *maybe_uninit); maybe_uninit.assume_init_mut(); }Note however that
INSTANCE_INITwould still be unsafe, because its safety promise is that it prepares things for the caller'sassume_init_mut().
Yes, I feel that this approach more clearly explains the purpose of QOM init.
And since we are talking about the safety of INSTANCE_INIT, I think we should add some safety guidelines here, like:
* Proper Initialization of pointers and references
* Explicit initialization of Non-Zero Fields
* In placed memory region is correctly initialized.
(Or do you have any additional or clearer guidelines?)
This could be the reference when adding SAFETY comment for the device's own unsafe init(). :-)
And this is also a good explanation to distinguish between initialization in init() and realize(). For example, HPET attempts to initialize the timer array in realize().
Quoted 2 lines
The way that this will become safe is to use the
pinned_initcrate from
Linux:instance_initreturns the initialization as an "impl PinInit<Self>",
Then do we need to place OBJECT in some suitable memory location (Box or something) for Rust implementation?
Quoted 2 lines
and then
instance_post_initcan run with a &self. Until then, however,instance_inithas to remain unsafe.
Thanks for sharing! It's a very reasonable direction.
Regards,
Zhao
Re: [PATCH 14/26] rust: qom: move bridge for TypeInfo functions out of pl011
Il mer 11 dic 2024, 08:41 Zhao Liu <[email protected]> ha scritto:
Quoted 6 lines
And since we are talking about the safety of
INSTANCE_INIT, I think we should add some safety guidelines here, like:
* Proper Initialization of pointers and references
* Explicit initialization of Non-Zero Fields
* In placed memory region is correctly initialized.
Yes that's pretty much it.
(Or do you have any additional or clearer guidelines?)
Quoted 8 lines
This could be the reference when adding SAFETY comment for the device's own
unsafeinit(). :-)And this is also a good explanation to distinguish between initialization in
init()andrealize(). For example, HPET attempts to initialize the timer array inrealize().
Generally:
- embedded objects will have to be initialized in instance_init unless they are Options
- sysbus_init_irq and sysbus_init_mmio can be called in both instance_init and instance_post_init for now, but they will have to be in post_init once the signature of init changes to return impl PinInit
- if you don't need properties you can choose between post_init and realize, if you need properties you need to initialize in realize (and then, unlike C, you might need to explicitly allow the pre-realize state; for example using Option<&...> instead of just a reference; or Vec<> instead of an array).
Quoted 8 lines
Quoted 3 lines
The way that this will become safe is to use the
pinned_initcrate from
Linux:instance_initreturns the initialization as an "implPinInit<Self>",
Then do we need to place OBJECT in some suitable memory location (Box or something) for Rust implementation?
Allocation is still done by the C code, so I am not sure I understand the question. Rust code allocates QOM objects with object_new() so they are malloc-ed. I discussed it with Manos some time ago and in principle you could use a Box (QOM supports custom freeing functions) but it's a bit complex because the freeing function would have to free the memory without dropping the contents of the Box (the drop is done by QOM via instance_finalize).
If you want to allocate the HPETTimers at realize time, I think you can place them in a Vec. I think you won't need NonNull for this, but I am not 100% sure. Alternatively if you want to always prepare all MAX_TIMERS of them and then only use a subset, you can use an array.
Either way, probably it makes sense for you to have an "fn timers_iter(&self) -> impl Iter<Item = &BqlRefCell<HPETTimer>>" in HPETState, or something like that. Then you can easily use for loops to walk all timers between 0 and self.num_timers-1.
Paolo
Quoted 9 lines
and then
instance_post_initcan run with a &self. Until then, however,Quoted 1 line
instance_inithas to remain unsafe.Thanks for sharing! It's a very reasonable direction.
Regards,
Zhao
Re: [PATCH 14/26] rust: qom: move bridge for TypeInfo functions out of pl011
Quoted 4 lines
Generally:
- embedded objects will have to be initialized in
instance_initunless they are Options
I see, at least for HPETTimer array, I need to prepare all of them in instance_init()...
Quoted 5 lines
- if you don't need properties you can choose between
post_initand realize, if you need properties you need to initialize in realize (and then, unlike C, you might need to explicitly allow the pre-realize state; for example using Option<&...> instead of just a reference; or Vec<> instead of an array).
...in realize(), also need to handle the "timers" property to enable the timers that property requires.
Quoted 3 lines
-
sysbus_init_irqandsysbus_init_mmiocan be called in bothinstance_initandinstance_post_initfor now, but they will have to be inpost_initonce the signature of init changes to return impl PinInit
make sense, thanks!
Quoted 5 lines
Quoted 5 lines
Quoted 3 lines
The way that this will become safe is to use the
pinned_initcrate from
Linux:instance_initreturns the initialization as an "implPinInit<Self>",
Quoted 7 lines
Quoted 3 lines
Then do we need to place OBJECT in some suitable memory location (Box or something) for Rust implementation?
Allocation is still done by the C code, so I am not sure I understand the question. Rust code allocates QOM objects with
object_new()so they are malloc-ed.
Sorry, I'm not familiar enough with this piece...I have the question because PinInit doc said "you will need a suitable memory location that can hold a T. This can be KBox<T>, Arc<T>, UniqueArc<T> or even the stack (see stack_pin_init!)."
I see that the core point is ensuring that structures cannot be moved. Given that object_new() on the C side ensures that the allocated object will not be moved, Rust side does not need to worry about pinning, correct?
Quoted 10 lines
I discussed it with Manos some time ago and in principle you could use a Box (QOM supports custom freeing functions) but it's a bit complex because the freeing function would have to free the memory without dropping the contents of the Box (the drop is done by QOM via
instance_finalize).If you want to allocate the HPETTimers at realize time, I think you can place them in a Vec. I think you won't need NonNull for this, but I am not 100% sure. Alternatively if you want to always prepare all
MAX_TIMERSof them and then only use a subset, you can use an array.
Vec seems to lack proper vmstate support. I understand that we need to modify VMSTATE_STRUCT_VARRAY_POINTER_* to introduce a variant for Vec.
Since the array support is already available, I chose to use an array instead (although vmstate is disabled for now).
Quoted 4 lines
Either way, probably it makes sense for you to have an "fn
timers_iter(&self)-> impl Iter<Item = &BqlRefCell<HPETTimer>>" in HPETState, or something like that. Then you can easily use for loops to walk all timers between 0 and self.num_timers-1.
Good idea, yes, will do.
Thanks,
Zhao
Re: [PATCH 14/26] rust: qom: move bridge for TypeInfo functions out of pl011
Quoted 11 lines · Zhao Liu
Quoted 5 lines
Generally:
- embedded objects will have to be initialized in
instance_initunless they are OptionsI see, at least for HPETTimer array, I need to prepare all of them in
instance_init()......in
realize(), also need to handle the "timers" property to enable the timers that property requires.
I see -- though, thinking more about it, since you have
fn init_timer(&mut self) {
let raw_ptr: *mut HPETState = self;
for i in 0..HPET_MAX_TIMERS {
let mut timer = self.get_timer(i).borrow_mut();
timer.init(i, raw_ptr).init_timer_with_state();
}
}It seems to me that you can do everything in instance_init. Later on a function like the above
will become something like
impl HPETTimer {
fn init_timer(hpet: NonNull<HPETState>, n: usize) -> impl PinInit<Self> {
pin_init!(&this in HPETTimer {
index: n,
qemu_timer <- Timer::init_ns(...),
state: hpet,
config: 0,
cmp: 0,
fsb: 0,
cmp64: 0,
period: 0,
wrap_flag: false,
last: 0,
}
}
}But even now you can write something that takes a &mut self as the first argument. It's undefined behavior but it's okay as long as we have a path forward.
Quoted 8 lines
Quoted 8 lines
Quoted 7 lines
Quoted 2 lines
The way that this will become safe is to use the
pinned_initcrate from
Linux:instance_initreturns the initialization as an "implPinInit<Self>",
Then do we need to place OBJECT in some suitable memory location (Box or something) for Rust implementation?
Quoted 8 lines
Quoted 3 lines
Allocation is still done by the C code, so I am not sure I understand the question. Rust code allocates QOM objects with
object_new()so they are malloc-ed.Sorry, I'm not familiar enough with this piece...I have the question because PinInit doc said "you will need a suitable memory location that can hold a T. This can be KBox<T>, Arc<T>, UniqueArc<T> or even the stack (see
stack_pin_init!)."
Ah, I see. You can use __pinned_init directly on the memory that is passed to rust_instance_init. See for example the implementation of InPlaceWrite for Box
(https://docs.rs/pinned-init/latest/src/pinned_init/lib.rs.html#1307).
Quoted 3 lines
I see that the core point is ensuring that structures cannot be moved. Given that
object_new()on the C side ensures that the allocated object will not be moved, Rust side does not need to worry about pinning, correct?
Sort of... You still need to worry about it for two reasons:
1) if you have &mut Self you can move values out of the object using e.g. mem::replace or mem::swap. Those would move the value in memory and cause trouble (think of moving a QEMUTimer while it is pointed to by the QEMUTimerList). This is solved by 1) using &Self all the time + interior mutability 2) using pinned_init's "PinnedDrop" functionality, because &Self can be used in QEMU-specific APIs but (obviously) not in the built-in Drop trait.
2) right now marking something as pinned is an indirect way to tell the compiler and miri that there are external references to it. For a longer discussion you can read
https://crates.io/crates/pinned-aliasable or
https://gist.github.com/Darksonn/1567538f56af1a8038ecc3c664a42462.
Linux does this with a wrapper type similar to the one in pinned-aliasable:
/// Stores an opaque value.
///
/// This is meant to be used with FFI objects that are never interpreted by Rust code.
#[repr(transparent)]
pub struct Opaque<T> {
value: UnsafeCell<MaybeUninit<T>>,
_pin: PhantomPinned,
}
It's on my todo list to introduce it in qemu_api::cell and (for example) change qom::Object from
pub use bindings::Object
to
pub type Object = Opaque<bindings::Object>;
Or something like that.
Quoted 5 lines
Vec seems to lack proper vmstate support. I understand that we need to modify VMSTATE_STRUCT_VARRAY_POINTER_* to introduce a variant for Vec.
Since the array support is already available, I chose to use an array instead (although vmstate is disabled for now).
Yes, you're right.
Palo
Re: [PATCH 14/26] rust: qom: move bridge for TypeInfo functions out of pl011
Quoted 11 lines
I see -- though, thinking more about it, since you have
fn init_timer(&mut self) { let raw_ptr: *mut HPETState = self; for i in 0..HPET_MAX_TIMERS { let mut timer = self.get_timer(i).borrow_mut(); timer.init(i, raw_ptr).init_timer_with_state(); } }
Quoted 6 lines
It seems to me that you can do everything in
instance_init. Later on a function like the above
will become something likeimpl HPETTimer { fn init_timer(hpet: NonNull<HPETState>, n: usize) -> impl PinInit<Self> {
Thank you! I should pass NonNull type other than *mut HPETState for now :-)
Quoted 6 lines
pin_init!(&this in HPETTimer {
index: n,
qemu_timer <- Timer::init_ns(...),
state: hpet,
config: 0,
cmp: 0,Quoted 8 lines
fsb: 0,
cmp64: 0,
period: 0,
wrap_flag: false,
last: 0,
}
}
}That's the right and ideal way, and I like it.
Quoted 3 lines
But even now you can write something that takes a &mut self as the first argument. It's undefined behavior but it's okay as long as we have a path forward.
Yes, I agree. In the next version, I can follow your suggestion and put these embedded items into instance_init(), to be better prepared for the next step.
Quoted 17 lines
Quoted 8 lines
Quoted 8 lines
Quoted 7 lines
Quoted 2 lines
The way that this will become safe is to use the
pinned_initcrate from
Linux:instance_initreturns the initialization as an "implPinInit<Self>",
Then do we need to place OBJECT in some suitable memory location (Box or something) for Rust implementation?
Quoted 8 lines
Quoted 3 lines
Allocation is still done by the C code, so I am not sure I understand the question. Rust code allocates QOM objects with
object_new()so they are malloc-ed.Sorry, I'm not familiar enough with this piece...I have the question because PinInit doc said "you will need a suitable memory location that can hold a T. This can be KBox<T>, Arc<T>, UniqueArc<T> or even the stack (see
stack_pin_init!)."
Quoted 4 lines
Ah, I see. You can use
__pinned_initdirectly on the memory that is passed torust_instance_init. See for example the implementation of InPlaceWrite for Box
(https://docs.rs/pinned-init/latest/src/pinned_init/lib.rs.html#1307).
Thank you! I understand your intention. A similar implementation would also be quite natural in rust_instance_init.
Quoted 11 lines
Quoted 3 lines
I see that the core point is ensuring that structures cannot be moved. Given that
object_new()on the C side ensures that the allocated object will not be moved, Rust side does not need to worry about pinning, correct?Sort of... You still need to worry about it for two reasons:
1) if you have &mut Self you can move values out of the object using e.g.
mem::replaceormem::swap. Those would move the value in memory and cause trouble (think of moving a QEMUTimer while it is pointed to by the QEMUTimerList). This is solved by 1) using &Self all the time + interior mutability
With your help and through our discussions, I have gained a clearer understanding of this intention.
Quoted 9 lines
2) using pinned_init's "PinnedDrop" functionality,
because &Self can be used in QEMU-specific APIs but (obviously) not in the built-in Drop trait.2) right now marking something as pinned is an indirect way to tell the compiler and miri that there are external references to it. For a longer discussion you can read
https://crates.io/crates/pinned-aliasable or
https://gist.github.com/Darksonn/1567538f56af1a8038ecc3c664a42462.
Thanks for sharing!
Quoted 15 lines
Linux does this with a wrapper type similar to the one in pinned-aliasable:
/// Stores an opaque value.
///
/// This is meant to be used with FFI objects that are never interpreted by Rust code.
#[repr(transparent)]
pub struct Opaque<T> {
value: UnsafeCell<MaybeUninit<T>>,
_pin: PhantomPinned,
}It's on my todo list to introduce it in
qemu_api::celland (for example) changeqom::Objectfrom
Quoted 7 lines
pub use
bindings::Objectto
pub type Object = Opaque<bindings::Object>;Or something like that.
Yes, I agree with this idea. It's what we need.
Regards,
Zhao
Re: [PATCH 14/26] rust: qom: move bridge for TypeInfo functions out of pl011
In reply to Paolo Bonzinirust/qemu-api/src/definitions.rs line 16
Quoted 6 lines
rust/qemu-api/src/definitions.rs +6
-0+unsafe extern "C" fn rust_instance_init <T :ObjectImpl >(obj: *mut Object ) { +// SAFETY: obj is an instance of T, since rust_instance_init<T> +// is called from QOM core as the instance_init function +// for class T +unsafe {T ::INSTANCE_INIT .unwrap ()(&mut *obj.cast ::<T >()) } +}
Here's the difference, why doesn't init() narrow the unsafe scope like post_init() does?
Quoted 11 lines
rust/qemu-api/src/definitions.rs +11
-0+unsafe extern "C" fn rust_instance_post_init <T :ObjectImpl >(obj: *mut Object ) { +// SAFETY: obj is an instance of T, since rust_instance_post_init<T> +// is called from QOM core as the instance_post_init function +// for class T +// +// FIXME: it's not really guaranteed that there are no backpointers to +// obj; it's quite possible that they have been created by instance_init(). +// The receiver should be &self, not &mut self. +T ::INSTANCE_POST_INIT .unwrap ()(unsafe { &mut *obj.cast ::<T >() }) +} +
PATCH 15/26 rust: qom: split ObjectType from ObjectImpl trait
In reply to Paolo BonziniDefine a separate trait for fields that also applies to classes that are defined by C code. This makes it possible to add metadata to core classes, which has multiple uses:
- it makes it possible to access the parent struct's TYPE_* for types that are defined in Rust code, and to avoid repeating it in every subclass
- implementors of ObjectType will be allowed to implement the IsA<> trait and therefore to perform typesafe casts from one class to another.
- in the future, an ObjectType could be created with Foo::new() in a type-safe manner, without having to pass a TYPE_* constant.
--- rust/hw/char/pl011/src/device.rs | 17 ++++++++++++----- rust/qemu-api/src/definitions.rs | 9 ++++++--- rust/qemu-api/src/device_class.rs | 11 ++++++----- rust/qemu-api/src/prelude.rs | 2 ++ rust/qemu-api/src/sysbus.rs | 10 ++++++++-- rust/qemu-api/tests/tests.rs | 12 +++++++++--- 6 files changed, 43 insertions(+), 18 deletions(-)
rust/hw/char/pl011/src/device.rs +12 -5
@@ -12,9 +12,10 @@ bindings::{self, *}, c_str, definitions::ObjectImpl, - device_class::{DeviceImpl, TYPE_SYS_BUS_DEVICE}, + device_class::DeviceImpl, impl_device_class, irq::InterruptSource, + prelude::*, };use crate ::{
@@ -106,10 +107,13 @@ pub struct PL011State { device_id: DeviceId, } -impl ObjectImpl for PL011State { +unsafe impl ObjectType for PL011State {type Class =PL011Class ;const TYPE_NAME : &'staticCStr =crate ::TYPE_PL011 ; -const PARENT_TYPE_NAME :Option <&'staticCStr > =Some (TYPE_SYS_BUS_DEVICE ); +} + +impl ObjectImpl for PL011State { +const PARENT_TYPE_NAME :Option <&'staticCStr > =Some (<SysBusDevice as ObjectType >::TYPE_NAME );const INSTANCE_INIT :Option <unsafe fn (&mut Self )> =Some (Self ::init); }
@@ -640,10 +644,13 @@ unsafe fn init(&mut self) { } } -impl ObjectImpl for PL011Luminary { +unsafe impl ObjectType for PL011Luminary {type Class =PL011LuminaryClass ;const TYPE_NAME : &'staticCStr =crate ::TYPE_PL011_LUMINARY ; -const PARENT_TYPE_NAME :Option <&'staticCStr > =Some (crate ::TYPE_PL011 ); +} + +impl ObjectImpl for PL011Luminary { +const PARENT_TYPE_NAME :Option <&'staticCStr > =Some (<PL011State as ObjectType >::TYPE_NAME );const INSTANCE_INIT :Option <unsafe fn (&mut Self )> =Some (Self ::init); }
rust/qemu-api/src/definitions.rs +6 -3
@@ -33,7 +33,7 @@unsafe { std::ptr::drop_in_place (obj.cast ::<T >()) } } -/// Trait a type must implement to be registered with QEMU. +/// Trait exposed by all structs corresponding to QOM objects. /// /// # Safety ///
@@ -43,15 +43,18 @@/// automatic if the class is defined via `ObjectImpl`). /// /// - the first field of the struct must be of the instance struct corresponding -/// to the superclass declared as `PARENT_TYPE_NAME` -pub trait ObjectImpl :ClassInitImpl +Sized { +/// to the superclass declared in the `TypeInfo` +pub unsafe trait ObjectType :Sized {/// The QOM class object corresponding to this struct. Not used yet. type Class ;/// The name of the type, which can be passed to `object_new()` to /// generate an instance of this type. const TYPE_NAME : &'staticCStr ; +} +/// Trait a type must implement to be registered with QEMU. +pub trait ObjectImpl :ObjectType +ClassInitImpl {/// The parent of the type. This should match the first field of /// the struct that implements `ObjectImpl`: const PARENT_TYPE_NAME :Option <&'staticCStr >;
rust/qemu-api/src/device_class.rs +6 -5
@@ -6,6 +6,7 @@use crate ::{ bindings::{self,DeviceClass ,DeviceState ,Error ,ObjectClass ,Property ,VMStateDescription }, + prelude::*, zeroable::Zeroable , };
@@ -146,8 +147,8 @@ macro_rules! declare_properties { }; } -// workaround until we can use --generate-cstr in bindgen. -pub const TYPE_DEVICE : &CStr = -unsafe {CStr ::from_bytes_with_nul_unchecked (bindings::TYPE_DEVICE ) }; -pub const TYPE_SYS_BUS_DEVICE : &CStr = -unsafe {CStr ::from_bytes_with_nul_unchecked (bindings::TYPE_SYS_BUS_DEVICE ) }; +unsafe impl ObjectType for bindings::DeviceState { +type Class = bindings::DeviceClass ; +const TYPE_NAME : &'staticCStr = +unsafe {CStr ::from_bytes_with_nul_unchecked (bindings::TYPE_DEVICE ) }; +}
rust/qemu-api/src/prelude.rs +2 -0
@@ -6,3 +6,5 @@pub use crate ::cell::BqlCell ;pub use crate ::cell::BqlRefCell ; + +pub use crate ::definitions::ObjectType ;
rust/qemu-api/src/sysbus.rs +8 -2
@@ -2,11 +2,17 @@// Author(s): Paolo Bonzini <[email protected]> // SPDX-License-Identifier: GPL-2.0-or-later -use std::ptr::addr_of; +use std::{ffi::CStr , ptr::addr_of};pub use bindings::{SysBusDevice ,SysBusDeviceClass }; -use crate ::{bindings, cell::bql_locked, irq::InterruptSource }; +use crate ::{bindings, cell::bql_locked, irq::InterruptSource , prelude::*}; + +unsafe impl ObjectType for SysBusDevice { +type Class =SysBusDeviceClass ; +const TYPE_NAME : &'staticCStr = +unsafe {CStr ::from_bytes_with_nul_unchecked (bindings::TYPE_SYS_BUS_DEVICE ) }; +}impl SysBusDevice {/// Return `self` cast to a mutable pointer, for use in calls to C code.
rust/qemu-api/tests/tests.rs +9 -3
@@ -8,8 +8,9 @@ bindings::*, c_str, declare_properties, define_property, definitions::ObjectImpl, - device_class::{self, DeviceImpl}, + device_class::DeviceImpl, impl_device_class, + prelude::*, zeroable::Zeroable, };
@@ -46,10 +47,15 @@ pub struct DummyClass { ), } -impl ObjectImpl for DummyState { +unsafe impl ObjectType for DummyState {type Class =DummyClass ;const TYPE_NAME : &'staticCStr =c_str! ("dummy" ); -const PARENT_TYPE_NAME :Option <&'staticCStr > =Some (device_class::TYPE_DEVICE ); + } + +impl ObjectImpl for DummyState { +const PARENT_TYPE_NAME :Option <&'staticCStr > = +Some (<DeviceState as ObjectType >::TYPE_NAME ); +const ABSTRACT :bool =false ; }impl DeviceImpl for DummyState {
Signature · 1 line
2.47.1
Re: [PATCH 15/26] rust: qom: split ObjectType from ObjectImpl trait
Quoted 19 lines · Paolo Bonzini
Date: Mon, 9 Dec 2024 13:37:06 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 15/26] rust: qom: split ObjectType from ObjectImpl trait
X-Mailer: git-send-email 2.47.1Define a separate trait for fields that also applies to classes that are defined by C code. This makes it possible to add metadata to core classes, which has multiple uses:
- it makes it possible to access the parent struct's TYPE_* for types that are defined in Rust code, and to avoid repeating it in every subclass
- implementors of ObjectType will be allowed to implement the IsA<> trait and therefore to perform typesafe casts from one class to another.
- in the future, an ObjectType could be created with
Foo::new()in a type-safe manner, without having to pass a TYPE_* constant.Signed-off-by Paolo Bonzini <[email protected]>
Quoted 8 lines
--- rust/hw/char/pl011/src/device.rs | 17 ++++++++++++----- rust/qemu-api/src/definitions.rs | 9 ++++++--- rust/qemu-api/src/device_class.rs | 11 ++++++----- rust/qemu-api/src/prelude.rs | 2 ++ rust/qemu-api/src/sysbus.rs | 10 ++++++++-- rust/qemu-api/tests/tests.rs | 12 +++++++++--- 6 files changed, 43 insertions(+), 18 deletions(-)
PATCH 16/26 rust: qom: change the parent type to an associated type
In reply to Paolo BonziniAvoid duplicated code to retrieve the QOM type strings from the Rust type.
--- rust/hw/char/pl011/src/device.rs | 6 ++++-- rust/qemu-api/src/definitions.rs | 8 ++------ rust/qemu-api/tests/tests.rs | 3 +-- 3 files changed, 7 insertions(+), 10 deletions(-)
rust/hw/char/pl011/src/device.rs +4 -2
@@ -113,7 +113,8 @@ unsafe impl ObjectType for PL011State { }impl ObjectImpl for PL011State { -const PARENT_TYPE_NAME :Option <&'staticCStr > =Some (<SysBusDevice as ObjectType >::TYPE_NAME ); +type ParentType =SysBusDevice ; +const INSTANCE_INIT :Option <unsafe fn (&mut Self )> =Some (Self ::init); }
@@ -650,7 +651,8 @@ unsafe impl ObjectType for PL011Luminary { }impl ObjectImpl for PL011Luminary { -const PARENT_TYPE_NAME :Option <&'staticCStr > =Some (<PL011State as ObjectType >::TYPE_NAME ); +type ParentType =PL011State ; +const INSTANCE_INIT :Option <unsafe fn (&mut Self )> =Some (Self ::init); }
rust/qemu-api/src/definitions.rs +2 -6
@@ -57,7 +57,7 @@ pub unsafe trait ObjectType: Sized {pub trait ObjectImpl :ObjectType +ClassInitImpl {/// The parent of the type. This should match the first field of /// the struct that implements `ObjectImpl`: -const PARENT_TYPE_NAME :Option <&'staticCStr >; +type ParentType :ObjectType ;/// Whether the object can be instantiated const ABSTRACT :bool =false ;
@@ -76,11 +76,7 @@ pub trait ObjectImpl: ObjectType + ClassInitImpl {const TYPE_INFO :TypeInfo =TypeInfo { name:Self ::TYPE_NAME .as_ptr (), - parent:if let Some (pname) =Self ::PARENT_TYPE_NAME { - pname.as_ptr () - }else { - core::ptr::null_mut () - }, + parent:Self ::ParentType ::TYPE_NAME .as_ptr (), instance_size: core::mem::size_of ::<Self >(), instance_align: core::mem::align_of ::<Self >(), instance_init:match Self ::INSTANCE_INIT {
rust/qemu-api/tests/tests.rs +1 -2
@@ -53,8 +53,7 @@ unsafe impl ObjectType for DummyState { }impl ObjectImpl for DummyState { -const PARENT_TYPE_NAME :Option <&'staticCStr > = -Some (<DeviceState as ObjectType >::TYPE_NAME ); +type ParentType =DeviceState ;const ABSTRACT :bool =false ; }
Signature · 1 line
2.47.1
Re: [PATCH 16/26] rust: qom: change the parent type to an associated type
Quoted 16 lines · Paolo Bonzini
Date: Mon, 9 Dec 2024 13:37:07 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 16/26] rust: qom: change the parent type to an associated
type
X-Mailer: git-send-email 2.47.1Avoid duplicated code to retrieve the QOM type strings from the Rust type.
Signed-off-by Paolo Bonzini <[email protected]>--- rust/hw/char/pl011/src/device.rs | 6 ++++-- rust/qemu-api/src/definitions.rs | 8 ++------ rust/qemu-api/tests/tests.rs | 3 +-- 3 files changed, 7 insertions(+), 10 deletions(-)
...
rust/qemu-api/src/definitions.rs pub trait ObjectImpl: ObjectType + ClassInitImpl { · line 79
Quoted 10 lines
rust/qemu-api/src/definitions.rs +1
-5@@ -76,11 +76,7 @@ pub trait ObjectImpl: ObjectType + ClassInitImpl {const TYPE_INFO :TypeInfo =TypeInfo { name:Self ::TYPE_NAME .as_ptr (), - parent:if let Some (pname) =Self ::PARENT_TYPE_NAME { - pname.as_ptr () - }else { - core::ptr::null_mut () - }, + parent:Self ::ParentType ::TYPE_NAME .as_ptr (),
Object is implemented at C side, so at leaset the ParentType should be TYPE_OBJECT.
rust/qemu-api/src/definitions.rs pub trait ObjectImpl: ObjectType + ClassInitImpl { · line 82
Quoted 3 lines
rust/qemu-api/src/definitions.rs +0
-0instance_size: core::mem::size_of::<Self>(), instance_align: core::mem::align_of::<Self>(), instance_init: match Self::INSTANCE_INIT {
Great!
PATCH 17/26 rust: qom: put class_init together from multiple ClassInitImpl<>
In reply to Paolo BonziniParameterize the implementation of ClassInitImpl so that it is possible to call up the chain of implementations, one superclass at a time starting at ClassInitImpl<Self::Class>.
In order to avoid having to implement (for example) ClassInitImpl<PL011Class>, also remove the dummy PL011Class and PL011LuminaryClass structs and specify the same ObjectType::Class as the superclass. In the future this default behavior can be handled by a procedural macro, by looking at the first field in the struct.
Note that the new trait is safe: the calls are started by rust_class_init<>(), which is not public and can convert the class pointer to a Rust reference.
Since CLASS_BASE_INIT applies to the type that is being defined, and only to it, move it to ObjectImpl.
--- rust/hw/char/pl011/src/device.rs | 19 +------ rust/qemu-api/src/definitions.rs | 85 +++++++++++++++++++++++-------- rust/qemu-api/src/device_class.rs | 50 +++++++----------- rust/qemu-api/src/sysbus.rs | 18 ++++++- rust/qemu-api/tests/tests.rs | 9 +--- 5 files changed, 101 insertions(+), 80 deletions(-)
rust/hw/char/pl011/src/device.rs +2 -17
@@ -13,7 +13,6 @@ c_str, definitions::ObjectImpl, device_class::DeviceImpl, - impl_device_class, irq::InterruptSource, prelude::*, };
@@ -108,7 +107,7 @@ pub struct PL011State { }unsafe impl ObjectType for PL011State { -type Class =PL011Class ; +type Class = <SysBusDevice as ObjectType >::Class ;const TYPE_NAME : &'staticCStr =crate ::TYPE_PL011 ; }
@@ -118,11 +117,6 @@ impl ObjectImpl for PL011State {const INSTANCE_INIT :Option <unsafe fn (&mut Self )> =Some (Self ::init); } -#[repr( C )] -pub struct PL011Class { - _inner: [u8 ;0 ], -} -impl DeviceImpl for PL011State {fn properties () -> &'static [Property ] { &device_class::PL011_PROPERTIES
@@ -134,8 +128,6 @@ fn vmsd() -> Option<&'static VMStateDescription> {const RESET :Option <fn (&mut Self )> =Some (Self ::reset); } -impl_device_class! (PL011State ); -impl PL011State {/// Initializes a pre-allocated, unitialized instance of `PL011State`. ///
@@ -627,11 +619,6 @@ pub struct PL011Luminary { parent_obj: PL011State, } -#[repr( C )] -pub struct PL011LuminaryClass { - _inner: [u8 ;0 ], -} -impl PL011Luminary {/// Initializes a pre-allocated, unitialized instance of `PL011Luminary`. ///
@@ -646,7 +633,7 @@ unsafe fn init(&mut self) { }unsafe impl ObjectType for PL011Luminary { -type Class =PL011LuminaryClass ; +type Class = <PL011State as ObjectType >::Class ;const TYPE_NAME : &'staticCStr =crate ::TYPE_PL011_LUMINARY ; }
@@ -657,5 +644,3 @@ impl ObjectImpl for PL011Luminary { }impl DeviceImpl for PL011Luminary {} - -impl_device_class! (PL011Luminary );
rust/qemu-api/src/definitions.rs +64 -21
127 lines not on this page · raw message
rust/qemu-api/src/device_class.rs +17 -33
85 lines not on this page · raw message
rust/qemu-api/src/sysbus.rs +17 -1
@@ -6,7 +6,13 @@pub use bindings::{SysBusDevice ,SysBusDeviceClass }; -use crate ::{bindings, cell::bql_locked, irq::InterruptSource , prelude::*}; +use crate ::{ + bindings::{self,DeviceClass }, + cell::bql_locked, + definitions::ClassInitImpl , + irq::InterruptSource , + prelude::*, +};unsafe impl ObjectType for SysBusDevice {type Class =SysBusDeviceClass ;
@@ -14,6 +20,16 @@ unsafe impl ObjectType for SysBusDevice {unsafe {CStr ::from_bytes_with_nul_unchecked (bindings::TYPE_SYS_BUS_DEVICE ) }; } +// TODO: add SysBusDeviceImpl +impl <T >ClassInitImpl <SysBusDeviceClass >for T +where +T :ClassInitImpl <DeviceClass >, +{ +fn class_init (sdc: &mut SysBusDeviceClass ) { + <T as ClassInitImpl <DeviceClass >>::class_init (&mut sdc.parent_class); + } +} +impl SysBusDevice {/// Return `self` cast to a mutable pointer, for use in calls to C code. const fn as_mut_ptr (&self) -> *mut SysBusDevice {
rust/qemu-api/tests/tests.rs +1 -8
@@ -31,11 +31,6 @@ pub struct DummyState { pub migrate_clock: bool, } -#[repr( C )] -pub struct DummyClass { -pub _parent:DeviceClass , - } -declare_properties! {DUMMY_PROPERTIES ,define_property! (
@@ -48,7 +43,7 @@ pub struct DummyClass { }unsafe impl ObjectType for DummyState { -type Class =DummyClass ; +type Class = <DeviceState as ObjectType >::Class ;const TYPE_NAME : &'staticCStr =c_str! ("dummy" ); }
@@ -66,8 +61,6 @@ fn vmsd() -> Option<&'static VMStateDescription> { } } -impl_device_class! (DummyState ); -unsafe {module_call_init (module_init_type::MODULE_INIT_QOM );object_unref (object_new (DummyState ::TYPE_NAME .as_ptr ()).cast ());
Signature · 1 line
2.47.1
Re: [PATCH 17/26] rust: qom: put class_init together from multiple ClassInitImpl<>
Quoted 2 lines
Since
CLASS_BASE_INITapplies to the type that is being defined, and only to it, move it to ObjectImpl.
It makes sense since class_base_init() is used when subclass is being initialized.
Quoted 8 lines
Signed-off-by Paolo Bonzini <[email protected]>--- rust/hw/char/pl011/src/device.rs | 19 +------ rust/qemu-api/src/definitions.rs | 85 +++++++++++++++++++++++-------- rust/qemu-api/src/device_class.rs | 50 +++++++----------- rust/qemu-api/src/sysbus.rs | 18 ++++++- rust/qemu-api/tests/tests.rs | 9 +--- 5 files changed, 101 insertions(+), 80 deletions(-)
PATCH 18/26 rust: qom: add possibility of overriding unparent
In reply to Paolo BonziniAdd a blanket definition of ClassInitImpl<ObjectClass> that thunks ObjectImpl::UNPARENT and overrides it in ObjectClass if it is not None.
ClassInitImpl<DeviceClass> can now call its superclass's ClassInitImpl, so that the C and Rust hierarchies match more closely.
This is mostly done as an example of implementing the metaclass hierarchy under ClassInitImpl.
--- rust/qemu-api/src/definitions.rs | 44 ++++++++++++++++++++++++++++--- rust/qemu-api/src/device_class.rs | 6 +++-- 2 files changed, 45 insertions(+), 5 deletions(-)
rust/qemu-api/src/definitions.rs +41 -3
@@ -6,7 +6,7 @@use std::{ffi::CStr , os::raw::c_void}; -use crate ::bindings::{Object ,ObjectClass ,TypeInfo }; +use crate ::bindings::{self,Object ,ObjectClass ,TypeInfo };unsafe extern "C" fn rust_instance_init <T :ObjectImpl >(obj: *mut Object ) {// SAFETY: obj is an instance of T, since rust_instance_init<T>
@@ -115,6 +115,9 @@ pub trait ObjectImpl: ObjectType + ClassInitImpl<Self::Class> { class_data: core::ptr::null_mut(), interfaces: core::ptr::null_mut(), }; + +// methods on ObjectClass +const UNPARENT :Option <fn (&mut Self )> =None ; }/// Internal trait used to automatically fill in a class struct.
@@ -128,7 +131,8 @@ pub trait ObjectImpl: ObjectType + ClassInitImpl<Self::Class> {/// /// Each struct will implement this trait with `T` equal to each /// superclass. For example, a device should implement at least -/// `ClassInitImpl<`[`DeviceClass`](crate::bindings::DeviceClass)`>`. +/// `ClassInitImpl<`[`DeviceClass`](crate::bindings::DeviceClass)`>` and +/// `ClassInitImpl<`[`ObjectClass`](crate::bindings::ObjectClass)`>`. /// /// Fortunately, this is almost never necessary. Instead, the Rust /// implementation of methods will usually come from a trait like
@@ -139,9 +143,13 @@ pub trait ObjectImpl: ObjectType + ClassInitImpl<Self::Class> {/// ```ignore /// impl<T> ClassInitImpl<DeviceClass> for T /// where -/// T: DeviceImpl, +/// T: ClassInitImpl<ObjectClass> + DeviceImpl, /// ``` /// +/// The bound on `ClassInitImpl<ObjectClass>` is needed so that, +/// after initializing the `DeviceClass` part of the class struct, +/// the parent [`ObjectClass`] is initialized as well. +/// /// The only case in which a manual implementation of the trait is needed /// is for interfaces (note that there is no Rust example yet for using /// interfaces). In this case, unlike the C case, the Rust class _has_
@@ -203,3 +211,33 @@ extern "C" fn ctor_fn() { } }; } + +/// # Safety +/// +/// We expect the FFI user of this function to pass a valid pointer that +/// can be downcasted to type `T`. We also expect the device is +/// readable/writeable from one thread at any time. +unsafe extern "C" fn rust_unparent_fn <T :ObjectImpl >(dev: *mut Object ) { +unsafe { +assert! (!dev.is_null ()); +let mut state = core::ptr::NonNull ::new_unchecked (dev.cast ::<T >()); +T ::UNPARENT .unwrap ()(state.as_mut ()); + } +} + +impl <T >ClassInitImpl <ObjectClass >for T +where +T :ObjectImpl , +{ +fn class_init (oc: &mut ObjectClass ) { +if <T as ObjectImpl >::UNPARENT .is_some () { + oc.unparent =Some (rust_unparent_fn ::<T >); + } + } +} + +unsafe impl ObjectType for Object { +type Class =ObjectClass ; +const TYPE_NAME : &'staticCStr = +unsafe {CStr ::from_bytes_with_nul_unchecked (bindings::TYPE_OBJECT ) }; +}
rust/qemu-api/src/device_class.rs +4 -2
@@ -5,7 +5,7 @@use std::ffi::CStr ;use crate ::{ - bindings::{self,DeviceClass ,DeviceState ,Error ,Property ,VMStateDescription }, + bindings::{self,DeviceClass ,DeviceState ,Error ,ObjectClass ,Property ,VMStateDescription }, definitions::ClassInitImpl , prelude::*, zeroable::Zeroable ,
@@ -69,7 +69,7 @@ fn vmsd() -> Option<&'static VMStateDescription> {impl <T >ClassInitImpl <DeviceClass >for T where -T :DeviceImpl , +T :ClassInitImpl <ObjectClass > +DeviceImpl , {fn class_init (dc: &mut DeviceClass ) {if <T as DeviceImpl >::REALIZE .is_some () {
@@ -86,6 +86,8 @@ fn class_init(dc: &mut DeviceClass) {unsafe { bindings::device_class_set_props (dc, <T as DeviceImpl >::properties ().as_ptr ()); } + + <T as ClassInitImpl <ObjectClass >>::class_init (&mut dc.parent_class); } }
Signature · 1 line
2.47.1
Re: [PATCH 18/26] rust: qom: add possibility of overriding unparent
Quoted 12 lines · Paolo Bonzini
Date: Mon, 9 Dec 2024 13:37:09 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 18/26] rust: qom: add possibility of overriding unparent
X-Mailer: git-send-email 2.47.1Add a blanket definition of ClassInitImpl<ObjectClass> that thunks
ObjectImpl::UNPARENTand overrides it in ObjectClass if it is not None.ClassInitImpl<DeviceClass> can now call its superclass's ClassInitImpl, so that the C and Rust hierarchies match more closely.
Quoted 8 lines
This is mostly done as an example of implementing the metaclass hierarchy under ClassInitImpl.
Signed-off-by Paolo Bonzini <[email protected]>--- rust/qemu-api/src/definitions.rs | 44 ++++++++++++++++++++++++++++--- rust/qemu-api/src/device_class.rs | 6 +++-- 2 files changed, 45 insertions(+), 5 deletions(-)
(with an additional comment below...)
Quoted 14 lines
rust/qemu-api/src/definitions.rs +1
-1@@ -6,7 +6,7 @@use std::{ffi::CStr , os::raw::c_void}; -use crate ::bindings::{Object ,ObjectClass ,TypeInfo }; +use crate ::bindings::{self,Object ,ObjectClass ,TypeInfo };unsafe extern "C" fn rust_instance_init <T :ObjectImpl >(obj: *mut Object ) {// SAFETY: obj is an instance of T, since rust_instance_init<T>
rust/qemu-api/src/definitions.rs pub trait ObjectImpl: ObjectType + ClassInitImpl<Self::Class> { · line 121
Quoted 7 lines
rust/qemu-api/src/definitions.rs +3
-0@@ -115,6 +115,9 @@ pub trait ObjectImpl: ObjectType + ClassInitImpl<Self::Class> { class_data: core::ptr::null_mut(), interfaces: core::ptr::null_mut(), }; + +// methods on ObjectClass +const UNPARENT :Option <fn (&mut Self )> =None ; }
Will we change &mut Self to an immutable reference in the future?
IIUC, the parent on the C side also has a pointer to current object.
Re: [PATCH 18/26] rust: qom: add possibility of overriding unparent
Quoted 37 lines · Zhao Liu
Quoted 12 lines · Paolo Bonzini
Date: Mon, 9 Dec 2024 13:37:09 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 18/26] rust: qom: add possibility of overriding unparent
X-Mailer: git-send-email 2.47.1Add a blanket definition of ClassInitImpl<ObjectClass> that thunks
ObjectImpl::UNPARENTand overrides it in ObjectClass if it is not None.ClassInitImpl<DeviceClass> can now call its superclass's ClassInitImpl, so that the C and Rust hierarchies match more closely.
Quoted 8 lines
This is mostly done as an example of implementing the metaclass hierarchy under ClassInitImpl.
Signed-off-by Paolo Bonzini <[email protected]>--- rust/qemu-api/src/definitions.rs | 44 ++++++++++++++++++++++++++++--- rust/qemu-api/src/device_class.rs | 6 +++-- 2 files changed, 45 insertions(+), 5 deletions(-)Reviewed-by Zhao Liu <[email protected]>(with an additional comment below...)
Quoted 11 lines
rust/qemu-api/src/definitions.rs +1
-1@@ -6,7 +6,7 @@use std::{ffi::CStr , os::raw::c_void}; -use crate ::bindings::{Object ,ObjectClass ,TypeInfo }; +use crate ::bindings::{self,Object ,ObjectClass ,TypeInfo };
Quoted 12 lines
rust/qemu-api/src/definitions.rs pub trait ObjectImpl: ObjectType + ClassInitImpl<Self::Class> { · line 121
Quoted 10 lines
rust/qemu-api/src/definitions.rs +3
-0unsafe extern "C" fn rust_instance_init <T :ObjectImpl >(obj: *mut Object ) {// SAFETY: obj is an instance of T, since rust_instance_init<T> @@ -115,6 +115,9 @@ pub trait ObjectImpl: ObjectType + ClassInitImpl<Self::Class> { class_data: core::ptr::null_mut(), interfaces: core::ptr::null_mut(), }; + +// methods on ObjectClass +const UNPARENT :Option <fn (&mut Self )> =None ; }Will we change
&mut Selfto an immutable reference in the future?
Good point, let's do it now since anyway UNPARENT is unused.
Paolo
PATCH 19/26 rust: rename qemu-api modules to follow C code a bit more
In reply to Paolo BonziniA full match would mean calling them qom::object and hw::core::qdev. For now, keep the names shorter but still a bit easier to find.
---
rust/hw/char/pl011/src/device.rs | 4 +-
rust/qemu-api-macros/src/lib.rs | 2 +-
rust/qemu-api/meson.build | 5 +-
rust/qemu-api/src/lib.rs | 5 +-
rust/qemu-api/src/module.rs | 43 +++++++++++
rust/qemu-api/src/prelude.rs | 2 +-
.../qemu-api/src/{device_class.rs => qdev.rs} | 4 +-
rust/qemu-api/src/{definitions.rs => qom.rs} | 74 +++++++++----------
rust/qemu-api/src/sysbus.rs | 2 +-
rust/qemu-api/tests/tests.rs | 5 +-
10 files changed, 92 insertions(+), 54 deletions(-)
create mode 100644 rust/qemu-api/src/module.rs
rename rust/qemu-api/src/{device_class.rs => qdev.rs} (97%)
rename rust/qemu-api/src/{definitions.rs => qom.rs} (83%)rust/hw/char/pl011/src/device.rs +2 -2
@@ -11,10 +11,10 @@use qemu_api::{ bindings::{self, *}, c_str, - definitions::ObjectImpl , - device_class::DeviceImpl , irq::InterruptSource , prelude::*, + qdev::DeviceImpl , + qom::ObjectImpl , };use crate ::{
rust/qemu-api-macros/src/lib.rs +1 -1
@@ -40,7 +40,7 @@ pub fn derive_object(input: TokenStream) -> TokenStream {let expanded =quote! { ::qemu_api::module_init! {MODULE_INIT_QOM =>unsafe { - ::qemu_api::bindings::type_register_static (&<#name as ::qemu_api::definitions::ObjectImpl >::TYPE_INFO ); + ::qemu_api::bindings::type_register_static (&<#name as ::qemu_api::qom::ObjectImpl >::TYPE_INFO ); } } };
rust/qemu-api/meson.build +3 -2
@@ -19,11 +19,12 @@ _qemu_api_rs = static_library( 'src/bitops.rs', 'src/cell.rs', 'src/c_str.rs', - 'src/definitions.rs', - 'src/device_class.rs', 'src/irq.rs', + 'src/module.rs', 'src/offset_of.rs', 'src/prelude.rs', + 'src/qdev.rs', + 'src/qom.rs', 'src/sysbus.rs', 'src/vmstate.rs', 'src/zeroable.rs',
rust/qemu-api/src/lib.rs +3 -2
@@ -15,10 +15,11 @@pub mod bitops;pub mod c_str;pub mod cell; -pub mod definitions; -pub mod device_class;pub mod irq; +pub mod module;pub mod offset_of; +pub mod qdev; +pub mod qom;pub mod sysbus;pub mod vmstate;pub mod zeroable;
rust/qemu-api/src/module.rs new file +43 -0
43 lines not on this page · raw message
rust/qemu-api/src/prelude.rs +1 -1
@@ -7,4 +7,4 @@pub use crate ::cell::BqlCell ;pub use crate ::cell::BqlRefCell ; -pub use crate ::definitions::ObjectType ; +pub use crate ::qom::ObjectType ;
rust/qemu-api/src/qdev.rs renamed from rust/qemu-api/src/device_class.rs +3 -1
@@ -2,12 +2,14 @@// Author(s): Manos Pitsidianakis <[email protected]> // SPDX-License-Identifier: GPL-2.0-or-later +//! Bindings to create devices and access device functionality from Rust. +use std::ffi::CStr ;use crate ::{ bindings::{self,DeviceClass ,DeviceState ,Error ,ObjectClass ,Property ,VMStateDescription }, - definitions::ClassInitImpl , prelude::*, + qom::ClassInitImpl , zeroable::Zeroable , };
rust/qemu-api/src/qom.rs renamed from rust/qemu-api/src/definitions.rs +33 -41
98 lines not on this page · raw message
rust/qemu-api/src/sysbus.rs +1 -1
@@ -9,9 +9,9 @@use crate ::{ bindings::{self,DeviceClass }, cell::bql_locked, - definitions::ClassInitImpl , irq::InterruptSource , prelude::*, + qom::ClassInitImpl , };unsafe impl ObjectType for SysBusDevice {
rust/qemu-api/tests/tests.rs +2 -3
@@ -7,10 +7,9 @@use qemu_api::{ bindings::*, c_str, declare_properties, define_property, - definitions::ObjectImpl , - device_class::DeviceImpl , - impl_device_class, prelude::*, + qdev::DeviceImpl , + qom::ObjectImpl , zeroable::Zeroable , };
Signature · 1 line
2.47.1
Re: [PATCH 19/26] rust: rename qemu-api modules to follow C code a bit more
Quoted 34 lines · Paolo Bonzini
Date: Mon, 9 Dec 2024 13:37:10 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 19/26] rust: rename qemu-api modules to follow C code a bit
more
X-Mailer: git-send-email 2.47.1A full match would mean calling them
qom::objectandhw::core::qdev. For now, keep the names shorter but still a bit easier to find.Signed-off-by Paolo Bonzini <[email protected]>--- rust/hw/char/pl011/src/device.rs | 4 +- rust/qemu-api-macros/src/lib.rs | 2 +- rust/qemu-api/meson.build | 5 +- rust/qemu-api/src/lib.rs | 5 +- rust/qemu-api/src/module.rs | 43 +++++++++++ rust/qemu-api/src/prelude.rs | 2 +- .../qemu-api/src/{device_class.rs => qdev.rs} | 4 +- rust/qemu-api/src/{definitions.rs => qom.rs} | 74 +++++++++---------- rust/qemu-api/src/sysbus.rs | 2 +- rust/qemu-api/tests/tests.rs | 5 +- 10 files changed, 92 insertions(+), 54 deletions(-) create mode 100644 rust/qemu-api/src/module.rs rename rust/qemu-api/src/{device_class.rs => qdev.rs} (97%) rename rust/qemu-api/src/{definitions.rs => qom.rs} (83%)rust/qemu-api/src/qom.rs renamed from rust/qemu-api/src/definitions.rs +1
-1@@ -2,7 +2,37 @@// Author(s): Manos Pitsidianakis <[email protected]> // SPDX-License-Identifier: GPL-2.0-or-later -//! Definitions required by QEMU when registering a device. +//! Bindings to access QOM functionality from Rust.
rust/qemu-api/src/qom.rs line 15
Quoted 10 lines
rust/qemu-api/src/qom.rs renamed from rust/qemu-api/src/definitions.rs +10
-0+//! +//! This module provides automatic creation and registration of `TypeInfo` +//! for classes that are written in Rust, and mapping between Rust traits +//! and QOM vtables. +//! +//! # Structure of a class +//! +//! A concrete class only needs a struct holding instance state. The struct must +//! implement the [`ObjectType`] and [`IsA`] traits, as well as any `*Impl` +//! traits provided by its superclasses.
In this commit, this comment is a bit ahead, but I think it's okay.
qom and qdev are both good names. In addition, we can rename the files of PL011 as well. Perhaps device_class.rs could be merged into device.rs (and eventually renamed to pl011.rs). I guess you might be planning to keep it until the cleanup of vmstate and property is done.
Re: [PATCH 19/26] rust: rename qemu-api modules to follow C code a bit more
Quoted 48 lines · Zhao Liu
Quoted 34 lines · Paolo Bonzini
Date: Mon, 9 Dec 2024 13:37:10 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 19/26] rust: rename qemu-api modules to follow C code a bit
more
X-Mailer: git-send-email 2.47.1A full match would mean calling them
qom::objectandhw::core::qdev. For now, keep the names shorter but still a bit easier to find.Signed-off-by Paolo Bonzini <[email protected]>--- rust/hw/char/pl011/src/device.rs | 4 +- rust/qemu-api-macros/src/lib.rs | 2 +- rust/qemu-api/meson.build | 5 +- rust/qemu-api/src/lib.rs | 5 +- rust/qemu-api/src/module.rs | 43 +++++++++++ rust/qemu-api/src/prelude.rs | 2 +- .../qemu-api/src/{device_class.rs => qdev.rs} | 4 +- rust/qemu-api/src/{definitions.rs => qom.rs} | 74 +++++++++---------- rust/qemu-api/src/sysbus.rs | 2 +- rust/qemu-api/tests/tests.rs | 5 +- 10 files changed, 92 insertions(+), 54 deletions(-)create mode 100644
rust/qemu-api/src/module.rsrenamerust/qemu-api/src/{device_class.rs=>qdev.rs} (97%) renamerust/qemu-api/src/{definitions.rs=>qom.rs} (83%)rust/qemu-api/src/qom.rs renamed from rust/qemu-api/src/definitions.rs +1
-1@@ -2,7 +2,37 @@// Author(s): Manos Pitsidianakis <[email protected]> // SPDX-License-Identifier: GPL-2.0-or-later -//! Definitions required by QEMU when registering a device. +//! Bindings to access QOM functionality from Rust. rust/qemu-api/src/qom.rs line 15
Quoted 10 lines
rust/qemu-api/src/qom.rs renamed from rust/qemu-api/src/definitions.rs +10
-0+//! +//! This module provides automatic creation and registration of `TypeInfo` +//! for classes that are written in Rust, and mapping between Rust traits +//! and QOM vtables. +//! +//! # Structure of a class +//! +//! A concrete class only needs a struct holding instance state. The struct must +//! implement the [`ObjectType`] and [`IsA`] traits, as well as any `*Impl` +//! traits provided by its superclasses. In this commit, this comment is a bit ahead, but I think it's okay.
Quoted 4 lines
qom and qdev are both good names. In addition, we can rename the files of PL011 as well. Perhaps
device_class.rscould be merged intodevice.rs(and eventually renamed topl011.rs). I guess you might be planning to keep it until the cleanup of vmstate and property is done.
Yeah, I don't have any specific plans but memory_ops will certainly go away. device_class doesn't do much, but keeping it separate is a reminder for things that are still there to be cleaned up.
As to VMState, there are two parts. One is the vmstate_description macro, probably it has to be replaced with something else to incorporate the trampolines for pre_save/post_load/... I haven't looked at it but it should not be a lot of work.
The second is VMStateFields, for which my idea is to implement a trait on types to retrieve a basic VMStateField (for example something like vmstate_uint32 would become an implementation of the VMState trait on u32). Then you'd write something like "vmstate_of!(Type, field).with_version_id(2)" (i.e. vmstate_of retrieves the basic field and fills in the offset, then you apply more changes on top). But that may take a while, and I think it cannot be done without the const_refs_to_static feature, which is only stable in 1.83.0.
Paolo
Re: [PATCH 19/26] rust: rename qemu-api modules to follow C code a bit more
Quoted 8 lines
Quoted 6 lines
In this commit, this comment is a bit ahead, but I think it's okay.
qom and qdev are both good names. In addition, we can rename the files of PL011 as well. Perhaps
device_class.rscould be merged intodevice.rs(and eventually renamed topl011.rs). I guess you might be planning to keep it until the cleanup of vmstate and property is done.Yeah, I don't have any specific plans but
memory_opswill certainly go away.
This depends on MemoryRegionOps binding. I will see how much HPET can do, and I'm sorry for not being able to review the remaining patches yet in this week, especially the last two. I will continue next week (my machine will be powered down until next Monday :( ).
Quoted 9 lines
device_classdoesn't do much, but keeping it separate is a reminder for things that are still there to be cleaned up.As to VMState, there are two parts. One is the
vmstate_descriptionmacro, probably it has to be replaced with something else to incorporate the trampolines for pre_save/post_load/... I haven't looked at it but it should not be a lot of work.The second is VMStateFields,
I found vmstate_array_of_pointer_to_struct missed a info field, and I could submit a patch to fix this nit next week (along with other cleanup you and other miantainers suggested for HPET).
I'd also like to try apply zeroable to VMStateField to avoid missing any items...
Quoted 3 lines
for which my idea is to implement a trait on
types to retrieve a basic VMStateField (for example something likevmstate_uint32would become an implementation of the VMState trait on u32).
This makes sense.
Quoted 5 lines
Then you'd write something like "vmstate_of!(Type, field).with_version_id(2)" (i.e.
vmstate_ofretrieves the basic field and fills in the offset, then you apply more changes on top). But that may take a while, and I think it cannot be done without theconst_refs_to_staticfeature, which is only stable in 1.83.0.
I also like this idea!
Thanks,
Zhao
Re: [PATCH 19/26] rust: rename qemu-api modules to follow C code a bit more
Il ven 13 dic 2024, 10:01 Zhao Liu <[email protected]> ha scritto:
Quoted 4 lines
I found
vmstate_array_of_pointer_to_structmissed ainfofield, and I could submit a patch to fix this nit next week (along with other cleanup you and other miantainers suggested for HPET).
I wouldn't worry too much about VMState, it's not in its final form and anything that isn't needed to pass qtests can wait.
Paolo
Quoted 21 lines
for which my idea is to implement a trait on
Quoted 2 lines
types to retrieve a basic VMStateField (for example something like
vmstate_uint32would become an implementation of the VMState trait onu32).
This makes sense.
Quoted 3 lines
Then you'd write something like "vmstate_of!(Type, field).with_version_id(2)" (i.e.
vmstate_ofretrieves the basic field and fills in the offset, then you apply more changes on top). But that maytake
Quoted 2 lines
a while, and I think it cannot be done without the
const_refs_to_staticfeature, which is only stable in 1.83.0.I also like this idea!
Thanks,
Zhao
PATCH 20/26 rust: re-export C types from qemu-api submodules
In reply to Paolo BonziniLong term we do not want device code to use "bindings" at all, so make it possible to get the relevant types from the other modules of qemu-api.
--- rust/qemu-api/src/qdev.rs | 7 +++++-- rust/qemu-api/src/qom.rs | 10 ++++++---- rust/qemu-api/src/sysbus.rs | 3 ++- rust/qemu-api/src/vmstate.rs | 9 +++++---- rust/qemu-api/tests/tests.rs | 3 ++- 5 files changed, 20 insertions(+), 12 deletions(-)
rust/qemu-api/src/qdev.rs +5 -2
@@ -6,10 +6,13 @@use std::ffi::CStr ; +pub use bindings::{DeviceClass ,DeviceState ,Property }; +use crate ::{ - bindings::{self,DeviceClass ,DeviceState ,Error ,ObjectClass ,Property ,VMStateDescription }, + bindings::{self,Error }, prelude::*, - qom::ClassInitImpl , + qom::{ClassInitImpl ,ObjectClass }, + vmstate::VMStateDescription , zeroable::Zeroable , };
rust/qemu-api/src/qom.rs +6 -4
@@ -36,7 +36,9 @@use std::{ffi::CStr , os::raw::c_void}; -use crate ::bindings::{self,Object ,ObjectClass ,TypeInfo }; +pub use bindings::{Object ,ObjectClass }; + +use crate ::bindings::{self,TypeInfo };unsafe extern "C" fn rust_instance_init <T :ObjectImpl >(obj: *mut Object ) {// SAFETY: obj is an instance of T, since rust_instance_init<T>
@@ -161,8 +163,8 @@ pub trait ObjectImpl: ObjectType + ClassInitImpl<Self::Class> {/// /// Each struct will implement this trait with `T` equal to each /// superclass. For example, a device should implement at least -/// `ClassInitImpl<`[`DeviceClass`](crate::bindings::DeviceClass)`>` and -/// `ClassInitImpl<`[`ObjectClass`](crate::bindings::ObjectClass)`>`. +/// `ClassInitImpl<`[`DeviceClass`](crate::qdev::DeviceClass)`>` and +/// `ClassInitImpl<`[`ObjectClass`]`>`. /// /// Fortunately, this is almost never necessary. Instead, the Rust /// implementation of methods will usually come from a trait like
@@ -193,7 +195,7 @@ pub trait ClassInitImpl<T> {/// /// The virtual method implementations usually come from another /// trait, for example [`DeviceImpl`](crate::qdev::DeviceImpl) -/// when `T` is [`DeviceClass`](crate::bindings::DeviceClass). +/// when `T` is [`DeviceClass`](crate::qdev::DeviceClass). /// /// On entry, `klass`'s parent class is initialized, while the other fields /// are all zero; it is therefore assumed that all fields in `T` can be
rust/qemu-api/src/sysbus.rs +2 -1
@@ -7,10 +7,11 @@pub use bindings::{SysBusDevice ,SysBusDeviceClass };use crate ::{ - bindings::{self,DeviceClass }, + bindings, cell::bql_locked, irq::InterruptSource , prelude::*, + qdev::DeviceClass , qom::ClassInitImpl , };
rust/qemu-api/src/vmstate.rs +5 -4
@@ -10,6 +10,8 @@//! [`vmstate_fields`](crate::vmstate_fields) are meant to be used when //! declaring a device model state struct. +pub use crate ::bindings::VMStateDescription ; +#[doc(alias = "VMSTATE_UNUSED_BUFFER" )] #[macro_export] macro_rules! vmstate_unused_buffer {
@@ -328,7 +330,7 @@ macro_rules! vmstate_fields { }/// A transparent wrapper type for the `subsections` field of -/// [`VMStateDescription`](crate::bindings::VMStateDescription). +/// [`VMStateDescription`]. /// /// This is necessary to be able to declare subsection descriptions as statics, /// because the only way to implement `Sync` for a foreign type (and `*const`
@@ -342,9 +344,8 @@ macro_rules! vmstate_fields {unsafe impl Sync for VMStateSubsectionsWrapper {} -/// Helper macro to declare a list of subsections -/// ([`VMStateDescription`](`crate::bindings::VMStateDescription`)) into a -/// static and return a pointer to the array of pointers it created. +/// Helper macro to declare a list of subsections ([`VMStateDescription`]) +/// into a static and return a pointer to the array of pointers it created. #[macro_export] macro_rules! vmstate_subsections { ($($subsection:expr),*$(,)*) => {{
rust/qemu-api/tests/tests.rs +2 -1
@@ -8,8 +8,9 @@ bindings::*, c_str, declare_properties, define_property, prelude::*, - qdev::DeviceImpl, + qdev::{DeviceImpl, DeviceState, Property}, qom::ObjectImpl, + vmstate::VMStateDescription, zeroable::Zeroable, };
Signature · 1 line
2.47.1
Re: [PATCH 20/26] rust: re-export C types from qemu-api submodules
Quoted 8 lines · Paolo Bonzini
Date: Mon, 9 Dec 2024 13:37:11 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 20/26] rust: re-export C types from qemu-api submodules
X-Mailer: git-send-email 2.47.1Long term we do not want device code to use "bindings" at all, so make it possible to get the relevant types from the other modules of qemu-api.
Quoted 8 lines
Signed-off-by Paolo Bonzini <[email protected]>--- rust/qemu-api/src/qdev.rs | 7 +++++-- rust/qemu-api/src/qom.rs | 10 ++++++---- rust/qemu-api/src/sysbus.rs | 3 ++- rust/qemu-api/src/vmstate.rs | 9 +++++---- rust/qemu-api/tests/tests.rs | 3 ++- 5 files changed, 20 insertions(+), 12 deletions(-)
PATCH 21/26 rust: tests: allow writing more than one test
In reply to Paolo Bonzini--- rust/qemu-api/tests/tests.rs | 109 ++++++++++++++++++++--------------- 1 file changed, 61 insertions(+), 48 deletions(-)
rust/qemu-api/tests/tests.rs +61 -48
@@ -2,7 +2,7 @@// Author(s): Manos Pitsidianakis <[email protected]> // SPDX-License-Identifier: GPL-2.0-or-later -use std::ffi::CStr ; +use std::{cell::Cell , ffi::CStr , sync::Mutex };use qemu_api::{ bindings::*,
@@ -14,55 +14,68 @@ zeroable::Zeroable, }; +// Test that macros can compile. +pub static VMSTATE :VMStateDescription =VMStateDescription { + name:c_str! ("name" ).as_ptr (), + unmigratable:true , + ..Zeroable ::ZERO +}; + +#[derive(qemu_api_macros::offsets)] +#[repr( C )] +#[derive(qemu_api_macros:: Object )] +pub struct DummyState { + parent:DeviceState , + migrate_clock:bool , +} + +declare_properties! { +DUMMY_PROPERTIES , +define_property! ( +c_str! ("migrate-clk" ), +DummyState , + migrate_clock, +unsafe { &qdev_prop_bool }, +bool + ), +} + +unsafe impl ObjectType for DummyState { +type Class = <DeviceState as ObjectType >::Class ; +const TYPE_NAME : &'staticCStr =c_str! ("dummy" ); +} + +impl ObjectImpl for DummyState { +type ParentType =DeviceState ; +const ABSTRACT :bool =false ; +} + +impl DeviceImpl for DummyState { +fn properties () -> &'static [Property ] { + &DUMMY_PROPERTIES + } +fn vmsd () ->Option <&'staticVMStateDescription > { +Some (&VMSTATE ) + } +} + +fn init_qom () { +static ONCE :Mutex <Cell <bool >> =Mutex ::new (Cell ::new (false )); + +let g =ONCE .lock ().unwrap (); +if !g.get () { +unsafe { +module_call_init (module_init_type::MODULE_INIT_QOM ); + } + g.set (true ); + } +} +#[test] -fn test_device_decl_macros () { -// Test that macros can compile. -pub static VMSTATE :VMStateDescription =VMStateDescription { - name:c_str! ("name" ).as_ptr (), - unmigratable:true , - ..Zeroable ::ZERO - }; - -#[derive(qemu_api_macros::offsets)] -#[repr( C )] -#[derive(qemu_api_macros:: Object )] -pub struct DummyState { -pub _parent:DeviceState , -pub migrate_clock:bool , - } - -declare_properties! { -DUMMY_PROPERTIES , -define_property! ( -c_str! ("migrate-clk" ), -DummyState , - migrate_clock, -unsafe { &qdev_prop_bool }, -bool - ), - } - -unsafe impl ObjectType for DummyState { -type Class = <DeviceState as ObjectType >::Class ; -const TYPE_NAME : &'staticCStr =c_str! ("dummy" ); - } - -impl ObjectImpl for DummyState { -type ParentType =DeviceState ; -const ABSTRACT :bool =false ; - } - -impl DeviceImpl for DummyState { -fn properties () -> &'static [Property ] { - &DUMMY_PROPERTIES - } -fn vmsd () ->Option <&'staticVMStateDescription > { -Some (&VMSTATE ) - } - } - +/// Create and immediately drop an instance. +fn test_object_new () { +init_qom ();unsafe { -module_call_init (module_init_type::MODULE_INIT_QOM );object_unref (object_new (DummyState ::TYPE_NAME .as_ptr ()).cast ()); } }
Signature · 1 line
2.47.1
Re: [PATCH 21/26] rust: tests: allow writing more than one test
rust/qemu-api/tests/tests.rs line 72
Quoted 11 lines
rust/qemu-api/tests/tests.rs +11
-0+fn init_qom () { +static ONCE :Mutex <Cell <bool >> =Mutex ::new (Cell ::new (false )); + +let g =ONCE .lock ().unwrap (); +if !g.get () { +unsafe { +module_call_init (module_init_type::MODULE_INIT_QOM ); + } + g.set (true ); + } +}
Only one question: what is the purpose of using a Mutex here?
Others LGTM,
Re: [PATCH 21/26] rust: tests: allow writing more than one test
Quoted 14 lines · Zhao Liu
rust/qemu-api/tests/tests.rs line 72
Quoted 12 lines
rust/qemu-api/tests/tests.rs +11
-0+fn init_qom () { +static ONCE :Mutex <Cell <bool >> =Mutex ::new (Cell ::new (false )); + +let g =ONCE .lock ().unwrap (); +if !g.get () { +unsafe { +module_call_init (module_init_type::MODULE_INIT_QOM ); + } + g.set (true ); + } +}Only one question: what is the purpose of using a Mutex here?
Different #[test] functions can be run in parallel. For now there is nothing that needs the BQL in the tests, so I used an independent Mutex (which could become a LazyLock later when the minimum supported Rust version is bumped).
It could also use unsafe { bql_lock(); } and a BqlCell. I left that for when there will be a way to lock the BQL from safe Rust code, but I can also do that now already.
Paolo
PATCH 22/26 rust: qom: add casting functionality
In reply to Paolo BonziniAdd traits that let client cast typecast safely between object types. In particular, an upcast is compile-time guaranteed to succeed, and a YOLO C-style downcast must be marked as unsafe.
The traits are based on an IsA<> trait that declares what is a subclass of what, which is an idea taken from glib-rs
(https://docs.rs/glib/latest/glib/object/trait.IsA.html).
The four primitives are also taken from there
(https://docs.rs/glib/latest/glib/object/trait.Cast.html). However, the implementation of casting itself is a bit different and uses the Deref trait.
This removes some pointer arithmetic from the pl011 device; it is also a prerequisite for the definition of methods, so that they can be invoked on all subclass structs. This will use the IsA<> trait to detect the structs that support the methods.
glib also has a "monadic" casting trait which could be implemented on Option (as in https://docs.rs/glib/latest/glib/object/trait.CastNone.html)
and perhaps even Result. For now I'm leaving it out, as the patch is already big enough and the benefit seems debatable.
--- rust/Cargo.toml | 1 + rust/hw/char/pl011/src/device.rs | 12 +- rust/qemu-api/src/prelude.rs | 7 + rust/qemu-api/src/qdev.rs | 1 + rust/qemu-api/src/qom.rs | 279 ++++++++++++++++++++++++++++++- rust/qemu-api/src/sysbus.rs | 3 +- rust/qemu-api/tests/tests.rs | 70 +++++++- 7 files changed, 362 insertions(+), 11 deletions(-)
rust/Cargo.toml +1 -0
@@ -38,6 +38,7 @@ should_implement_trait = "deny" unused_self = "allow" # default-allow lints +as_ptr_cast_mut = "deny" as_underscore = "deny" assertions_on_result_states = "deny" bool_to_int_with_if = "deny"
rust/hw/char/pl011/src/device.rs +8 -4
@@ -106,6 +106,8 @@ pub struct PL011State { device_id: DeviceId, } +qom_isa! (PL011State :SysBusDevice ,DeviceState ,Object ); +unsafe impl ObjectType for PL011State {type Class = <SysBusDevice as ObjectType >::Class ;const TYPE_NAME : &'staticCStr =crate ::TYPE_PL011 ;
@@ -140,8 +142,6 @@ impl PL011State {unsafe fn init (&mut self) {const CLK_NAME : &CStr =c_str! ("clk" ); -let sbd =unsafe { &mut *(addr_of_mut! (*self).cast ::<SysBusDevice >()) }; -// SAFETY: // // self and self.iomem are guaranteed to be valid at this point since callers
@@ -155,15 +155,16 @@ unsafe fn init(&mut self) { Self::TYPE_NAME.as_ptr(), 0x1000, ); + +let sbd: &mut SysBusDevice = self.upcast_mut ();sysbus_init_mmio (sbd,addr_of_mut! (self.iomem)); }for irqin self.interrupts.iter () { +let sbd: &SysBusDevice = self.upcast (); sbd.init_irq (irq); } -let dev =addr_of_mut! (*self).cast ::<DeviceState >(); -// SAFETY: // // self.clock is not initialized at this point; but since `NonNull<_>` is Copy,
@@ -172,6 +173,7 @@ unsafe fn init(&mut self) {// 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(),
@@ -632,6 +634,8 @@ unsafe fn init(&mut self) { } } +qom_isa! (PL011Luminary :PL011State ,SysBusDevice ,DeviceState ,Object ); +unsafe impl ObjectType for PL011Luminary {type Class = <PL011State as ObjectType >::Class ;const TYPE_NAME : &'staticCStr =crate ::TYPE_PL011_LUMINARY ;
rust/qemu-api/src/prelude.rs +7 -0
@@ -7,4 +7,11 @@pub use crate ::cell::BqlCell ;pub use crate ::cell::BqlRefCell ; +pub use crate ::qom::IsA ; +pub use crate ::qom::Object ; +pub use crate ::qom::ObjectCast ; +pub use crate ::qom::ObjectCastMut ; +pub use crate ::qom::ObjectDeref ;pub use crate ::qom::ObjectType ; + +pub use crate ::qom_isa;
rust/qemu-api/src/qdev.rs +1 -0
@@ -143,3 +143,4 @@ unsafe impl ObjectType for DeviceState {const TYPE_NAME : &'staticCStr =unsafe {CStr ::from_bytes_with_nul_unchecked (bindings::TYPE_DEVICE ) }; } +qom_isa! (DeviceState :Object );
rust/qemu-api/src/qom.rs +274 -5
302 lines not on this page · raw message
rust/qemu-api/src/sysbus.rs +2 -1
@@ -11,7 +11,7 @@ cell::bql_locked, irq::InterruptSource, prelude::*, - qdev::DeviceClass, + qdev::{DeviceClass, DeviceState}, qom::ClassInitImpl, };
@@ -20,6 +20,7 @@ unsafe impl ObjectType for SysBusDevice {const TYPE_NAME : &'staticCStr =unsafe {CStr ::from_bytes_with_nul_unchecked (bindings::TYPE_SYS_BUS_DEVICE ) }; } +qom_isa! (SysBusDevice :DeviceState ,Object );// TODO: add SysBusDeviceImpl impl <T >ClassInitImpl <SysBusDeviceClass >for T
rust/qemu-api/tests/tests.rs +69 -1
85 lines not on this page · raw message
Signature · 1 line
2.47.1
Re: [PATCH 22/26] rust: qom: add casting functionality
rust/qemu-api/src/qom.rs line 78
Quoted 12 lines
rust/qemu-api/src/qom.rs +12
-0+/// Macro to mark superclasses of QOM classes. This enables type-safe +/// up- and downcasting. +/// +/// # Safety +/// +/// This macro is a thin wrapper around the [`IsA`] trait and performs +/// no checking whatsoever of what is declared. It is the caller's +/// responsibility to have $struct begin, directly or indirectly, with +/// a field of type `$parent`. +#[macro_export] +macro_rules! qom_isa { + ($struct:ty : $($parent:ty),* ) => {
This macro is quite good, but it requires specifying all the parents... So I am thinking if it is possible to move ParentType to ObjectType, and then try to traverse the ParentType in the macro, implementing IsA for each ParentType... However, the first difficulty has already stopped me:
I cannot define ParentType for Object itself.
Quoted 20 lines
rust/qemu-api/src/qom.rs +16
-0+ $( + // SAFETY: it is the caller responsibility to have $parent as the + // first field + unsafe impl $crate::qom::IsA<$parent> for $struct {} + +impl AsRef <$parent>for $struct { +fn as_ref (&self) -> &$parent { +// SAFETY: follows the same rules as for IsA<U>, which is +// declared above. +let ptr: *const Self = self; +unsafe { &*ptr.cast ::<$parent>() } + } + } + )* + }; +}unsafe extern "C" fn rust_instance_init <T :ObjectImpl >(obj: *mut Object ) {// SAFETY: obj is an instance of T, since rust_instance_init<T>
rust/qemu-api/src/qom.rs pub unsafe trait ObjectType: Sized { · line 152
Quoted 6 lines
rust/qemu-api/src/qom.rs +3
-0@@ -94,8 +147,224 @@ pub unsafe trait ObjectType: Sized {/// The name of the type, which can be passed to `object_new()` to /// generate an instance of this type. const TYPE_NAME : &'staticCStr ; + +/// Return the receiver as an Object. This is always safe, even +/// if this type represents an interface.
This comment is a bit confusing to me... EMM, why mention the interface? I understand if something implements ObjectType, then it should be an Object, so deref/cast here would be valid. And if it is an interface, it would need to implement the corresponding trait.
...
This cast idea is nice! In the future, class might also need to implement similar cast support (e.g., class_init in virtio).
Re: [PATCH 22/26] rust: qom: add casting functionality
Quoted 11 lines · Zhao Liu
Quoted 11 lines
rust/qemu-api/src/qom.rs +10
-0+/// Macro to mark superclasses of QOM classes. This enables type-safe +/// up- and downcasting. +/// +/// # Safety +/// +/// This macro is a thin wrapper around the [`IsA`] trait and performs +/// no checking whatsoever of what is declared. It is the caller's +/// responsibility to have $struct begin, directly or indirectly, with +/// a field of type `$parent`. +#[macro_export]
Quoted 8 lines
rust/qemu-api/src/qom.rs line 78
Quoted 2 lines
rust/qemu-api/src/qom.rs +2
-0+macro_rules! qom_isa { + ($struct:ty : $($parent:ty),* ) => {This macro is quite good, but it requires specifying all the parents... So I am thinking if it is possible to move ParentType to ObjectType, and then try to traverse the ParentType in the macro, implementing IsA for each ParentType... However, the first difficulty has already stopped me:
I cannot define ParentType for Object itself.
I am not sure how that could be done, but I've seen people implementing boolean logic purely with types, like
pub struct True;
pub struct False;
pub trait Boolean {}
impl Boolean for True;
impl Boolean for False;
pub trait Or<T: Boolean>: Boolean {
type Result: Boolean;
}
impl<T: Boolean> Or<T> for True {
type Result = True;
}
impl<T: Boolean> Or<T> for False {
type Result = T;
}and I think that can be used to implement recursive IsA, but that is a bit too magic for this first step. QEMU class hierarchies are relatively shallow.
Quoted 4 lines
Quoted 4 lines
rust/qemu-api/src/qom.rs +0
-0@@ -94,8 +147,224 @@ pub unsafe trait ObjectType: Sized {/// The name of the type, which can be passed to `object_new()` to /// generate an instance of this type. const TYPE_NAME : &'staticCStr ;
Quoted 8 lines
rust/qemu-api/src/qom.rs pub unsafe trait ObjectType: Sized { · line 152
Quoted 3 lines
rust/qemu-api/src/qom.rs +3
-0+ +/// Return the receiver as an Object. This is always safe, even +/// if this type represents an interface. This comment is a bit confusing to me... EMM, why mention the interface? I understand if something implements ObjectType, then it should be an Object, so deref/cast here would be valid. And if it is an interface, it would need to implement the corresponding trait.
What I meant is that interfaces do (will) not implement IsA<Object>, but they are ObjectTypes. So if you have let's say an "&impl UserCreatable" argument, you could use as_object() to obtain an &Object.
Quoted 2 lines
This cast idea is nice! In the future, class might also need to implement= similar cast support (e.g.,
class_initin virtio).
Ok, good!
Paolo
PATCH 23/26 rust: qom: add initial subset of methods on Object
In reply to Paolo BonziniAdd an example of implementing instance methods and converting the result back to a Rust type. In this case the returned types are a string (actually a Cow<str>; but that's transparent as long as it derefs to &str) and a QOM class.
--- rust/qemu-api/src/prelude.rs | 1 + rust/qemu-api/src/qom.rs | 56 ++++++++++++++++++++++++++++++++++-- rust/qemu-api/tests/tests.rs | 12 ++++++++ 3 files changed, 66 insertions(+), 3 deletions(-)
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::ObjectMethods ;pub use crate ::qom::ObjectType ;pub use crate ::qom_isa;
rust/qemu-api/src/qom.rs +53 -3
83 lines not on this page · raw message
rust/qemu-api/tests/tests.rs +12 -0
@@ -88,6 +88,18 @@ fn test_object_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 >()); + } +} +// a note on all "cast" tests: usually, especially for downcasts the desired // class would be placed on the right, for example: //
Signature · 1 line
2.47.1
Re: [PATCH 23/26] rust: qom: add initial subset of methods on Object
Quoted 10 lines · Paolo Bonzini
Date: Mon, 9 Dec 2024 13:37:14 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 23/26] rust: qom: add initial subset of methods on Object
X-Mailer: git-send-email 2.47.1Add an example of implementing instance methods and converting the result back to a Rust type. In this case the returned types are a string (actually a Cow<str>; but that's transparent as long as it derefs to &str) and a QOM class.
Quoted 7 lines
Signed-off-by Paolo Bonzini <[email protected]>--- rust/qemu-api/src/prelude.rs | 1 + rust/qemu-api/src/qom.rs | 56 ++++++++++++++++++++++++++++++++++-- rust/qemu-api/tests/tests.rs | 12 ++++++++ 3 files changed, 66 insertions(+), 3 deletions(-)
Good example!
PATCH 24/26 rust: qom: move device_id to PL011 class side
In reply to Paolo BonziniThere is no need to monkeypatch DeviceId::Luminary into the already-initialized PL011State. Instead, now that we can define a class hierarchy, we can define PL011Class and make device_id a field in there.
There is also no need anymore to have "Arm" as zero, so change DeviceId into a wrapper for the array; all it does is provide an Index<hwaddr> implementation because arrays can only be indexed by usize.
--- rust/hw/char/pl011/src/device.rs | 59 +++++++++++++++----------------- 1 file changed, 28 insertions(+), 31 deletions(-)
rust/hw/char/pl011/src/device.rs +28 -31
@@ -5,7 +5,7 @@use core::ptr::{addr_of_mut,NonNull };use std::{ ffi::CStr , - os::raw::{c_int, c_uchar, c_uint, c_void}, + os::raw::{c_int, c_uint, c_void}, };use qemu_api::{
@@ -14,7 +14,7 @@ irq::InterruptSource, prelude::*, qdev::DeviceImpl, - qom::ObjectImpl, + qom::{ClassInitImpl, ObjectImpl}, };use crate ::{
@@ -35,27 +35,20 @@/// QEMU sourced constant. pub const PL011_FIFO_DEPTH :usize =16_usize ; -#[derive( Clone , Copy , Debug )] -enum DeviceId { -#[allow(dead_code)] -Arm =0 , -Luminary , -} +#[derive( Clone , Copy )] +struct DeviceId (&'static [u8 ;8 ]);impl std::ops::Index <hwaddr >for DeviceId { -type Output =c_uchar ; +type Output =u8 ;fn index (&self, idx:hwaddr ) -> &Self ::Output { -match self { -Self ::Arm => &Self ::PL011_ID_ARM [idxas usize ], -Self ::Luminary => &Self ::PL011_ID_LUMINARY [idxas usize ], - } + &self.0 [idxas usize ] } }impl DeviceId { -const PL011_ID_ARM : [c_uchar ;8 ] = [0x11 ,0x10 ,0x14 ,0x00 ,0x0d ,0xf0 ,0x05 ,0xb1 ]; -const PL011_ID_LUMINARY : [c_uchar ;8 ] = [0x11 ,0x00 ,0x18 ,0x01 ,0x0d ,0xf0 ,0x05 ,0xb1 ]; +const ARM :Self =Self (&[0x11 ,0x10 ,0x14 ,0x00 ,0x0d ,0xf0 ,0x05 ,0xb1 ]); +const LUMINARY :Self =Self (&[0x11 ,0x00 ,0x18 ,0x01 ,0x0d ,0xf0 ,0x05 ,0xb1 ]); }#[repr( C )]
@@ -102,17 +95,28 @@ pub struct PL011State { pub clock: NonNull<Clock>,#[doc(alias = "migrate_clk" )] pub migrate_clock: bool, -/// The byte string that identifies the device. - device_id: DeviceId, }qom_isa! (PL011State :SysBusDevice ,DeviceState ,Object ); +pub struct PL011Class { + parent_class: <SysBusDevice as ObjectType >::Class , +/// The byte string that identifies the device. + device_id:DeviceId , +} +unsafe impl ObjectType for PL011State { -type Class = <SysBusDevice as ObjectType >::Class ; +type Class =PL011Class ;const TYPE_NAME : &'staticCStr =crate ::TYPE_PL011 ; } +impl ClassInitImpl <PL011Class >for PL011State { +fn class_init (klass: &mut PL011Class ) { + klass.device_id =DeviceId ::ARM ; + <Self as ClassInitImpl <SysBusDeviceClass >>::class_init (&mut klass.parent_class); + } +} +impl ObjectImpl for PL011State {type ParentType =SysBusDevice ;
@@ -190,7 +194,8 @@ pub fn read(&mut self, offset: hwaddr, _size: c_uint) -> std::ops::ControlFlow<u std::ops::ControlFlow ::Break (match RegisterOffset ::try_from (offset) {Err (v)if (0x3f8 ..0x400 ).contains (&(v >>2 )) => { - u64::from (self.device_id[(offset -0xfe0 ) >>2 ]) +let device_id = self.get_class ().device_id; + u64::from (device_id[(offset -0xfe0 ) >>2 ]) }Err (_) => {// qemu_log_mask(LOG_GUEST_ERROR, "pl011_read: Bad offset 0x%x\n", (int)offset);
@@ -621,16 +626,10 @@ pub struct PL011Luminary { parent_obj: PL011State, } -impl PL011Luminary { -/// Initializes a pre-allocated, unitialized instance of `PL011Luminary`. -/// -/// # Safety -/// -/// We expect the FFI user of this function to pass a valid pointer, that -/// has the same size as [`PL011Luminary`]. We also expect the device is -/// readable/writeable from one thread at any time. -unsafe fn init (&mut self) { - self.parent_obj.device_id =DeviceId ::Luminary ; +impl ClassInitImpl <PL011Class >for PL011Luminary { +fn class_init (klass: &mut PL011Class ) { + klass.device_id =DeviceId ::LUMINARY ; + <Self as ClassInitImpl <SysBusDeviceClass >>::class_init (&mut klass.parent_class); } }
@@ -643,8 +642,6 @@ unsafe impl ObjectType for PL011Luminary {impl ObjectImpl for PL011Luminary {type ParentType =PL011State ; - -const INSTANCE_INIT :Option <unsafe fn (&mut Self )> =Some (Self ::init); }impl DeviceImpl for PL011Luminary {}
Signature · 1 line
2.47.1
Re: [PATCH 24/26] rust: qom: move device_id to PL011 class side
rust/hw/char/pl011/src/device.rs pub struct PL011State { · line 116
Quoted 4 lines
rust/hw/char/pl011/src/device.rs +4
-0+impl ClassInitImpl <PL011Class >for PL011State { +fn class_init (klass: &mut PL011Class ) { + klass.device_id =DeviceId ::ARM ; + <Self as ClassInitImpl <SysBusDeviceClass >>::class_init (&mut klass.parent_class);
This seems a bit of a conflict with the C version of QOM semantics. In C, class_init is registered in TypeInfo, and then the QOM code will automatically call the parent's class_init without needing to explicitly call the parent's in the child's class_init.
However, SysBusDevice (and Device) is a bit different. Its TypeInfo is registered on the C side, and the class_init method on the Rust side is not actually a real QOM class_init (because it is not registered on the Rust side).
Therefore, the call here seems valid from the code logic's perspective. But, when there is deeper class inheritance, it seems impossible to prevent class_init from being called both by the C side's QOM code and by this kind of recursive case on the Rust side.
So, for devices like SysBusDevice that are registered on the C side, should we not implement class_init and also not call it explicitly?
Or should we distinguish between two different usages of class_init? One is registered in TypeInfo (only as a callback in rust_class_init) - perhaps rename it as qom_class_init, and the other is used as a helper for Rust-side calls (similar to the recursive usage here) - maybe rename it as class_inter_init.
Quoted 2 lines
(quoted diff) +2
-0+ } +}
Re: [PATCH 24/26] rust: qom: move device_id to PL011 class side
Il mar 17 dic 2024, 04:39 Zhao Liu <[email protected]> ha scritto:
Quoted 11 lines
rust/hw/char/pl011/src/device.rs pub struct PL011State {
Quoted 4 lines
rust/hw/char/pl011/src/device.rs +4
-0+impl ClassInitImpl <PL011Class >for PL011State { +fn class_init (klass: &mut PL011Class ) { + klass.device_id =DeviceId ::ARM ; + <Self as ClassInitImpl<SysBusDeviceClass>>::class_init(&mutklass.parent_class);
This seems a bit of a conflict with the C version of QOM semantics. In C,
class_initis registered in TypeInfo, and then the QOM code will automatically call the parent'sclass_initwithout needing to explicitly call the parent's in the child'sclass_init.
This is the same in Rust.
The difference is that in C you have a single class_init function that sets all members of ObjectClass, DeviceClass, etc. In Rust each class has one trait and there is a chain of ClassInitImpl implementations—one filling in "oc" from ObjectImpl, one filling in "dc" from DeviceImpl and so on.
But in both cases you get a chain of calls from qom/object.c.
Therefore, the call here seems valid from the code logic's perspective.
Quoted 4 lines
But, when there is deeper class inheritance, it seems impossible to prevent
class_initfrom being called both by the C side's QOM code and by this kind of recursive case on the Rust side.
Note that here you have two parameters: what class is being filled (the argument C of ClassInitImpl<C>) *and* what type is being initialized (that's Self).
The "recursion" is only on the argument C, and matches the way C code implements class_init.
Maybe the confusion is because I implemented class_init twice instead of using a separate trait "PL011Impl"?
Paolo
So, for devices like SysBusDevice that are registered on the C side,
Quoted 13 lines
should we not implement
class_initand also not call it explicitly?Or should we distinguish between two different usages of
class_init? One is registered in TypeInfo (only as a callback inrust_class_init) - perhaps rename it asqom_class_init, and the other is used as a helper for Rust-side
calls (similar to the recursive usage here) - maybe rename it asclass_inter_init.Quoted 2 lines
(quoted diff) +2
-0+ } +}
Re: [PATCH 24/26] rust: qom: move device_id to PL011 class side
Quoted 20 lines · Paolo Bonzini
Date: Tue, 17 Dec 2024 17:50:09 +0100
From: Paolo Bonzini <[email protected]>
Subject: Re: [PATCH 24/26] rust: qom: movedevice_idto PL011 class sideIl mar 17 dic 2024, 04:39 Zhao Liu <[email protected]> ha scritto:
Quoted 11 lines
Review
Quoted 4 lines
(quoted diff) +4
-0+impl ClassInitImpl<PL011Class> for PL011State { + fn class_init(klass: &mut PL011Class) { + klass.device_id = DeviceId::ARM; + <Self as ClassInitImpl<SysBusDeviceClass>>::class_init(&mutklass.parent_class);
This seems a bit of a conflict with the C version of QOM semantics. In C,
class_initis registered in TypeInfo, and then the QOM code will automatically call the parent'sclass_initwithout needing to explicitly call the parent's in the child'sclass_init.This is the same in Rust.
Quoted 8 lines
The difference is that in C you have a single
class_initfunction that sets all members of ObjectClass, DeviceClass, etc. In Rust each class has one trait and there is a chain of ClassInitImpl implementations—one filling in "oc" from ObjectImpl, one filling in "dc" from DeviceImpl and so on.But in both cases you get a chain of calls from
qom/object.c.Therefore, the call here seems valid from the code logic's perspective.
I supposed a case, where there is such a QOM (QEMU Object Model) structure relationship:
* DummyState / DummyClass: defined in Rust side, and registered the TypeInfo by Object macro.
- So its class_init will be called by C QOM code.
* DummyChildState / DummyChildClass: defined in Rust side as the child-object of DummyState, and registered the TypeInfo by Object macro. And suppose it can inherit the trait of DummyClass - ClassInitImpl<DummyClass> (but I found a gap here, as detailed later; I expect it should be able to inherit normally).
- So its class_init will be called by C QOM code. In C code call chain, its parent's class_init should be called by C before its own class_init.
- However, note that according to the Rust class initialization call chain, it should also call the parent's class_init within its own class_init.
- :( the parent's class_init gets called twice.
If you agree this case indeed exists, then I think we should distinguish between different class_init methods for the Rust and C call chains.
Moving on to another topic, about the gap (or question :-)) where a child class inherits the ClassInitImpl trait from the parent, please see my test case example below: Doing something similar to SysBusDevice and DeviceState using a generic T outside of the QOM library would violate the orphan rule.
rust/qemu-api/tests/tests.rs +53 -3
@@ -13,8 +13,8 @@use qemu_api::{ bindings::*, c_str, declare_properties, define_property, - qdev::{DeviceImpl ,DeviceState ,Property }, - qom::{ObjectCast ,ObjectCastMut ,ObjectImpl ,ObjectMethods ,ObjectType }, + qdev::{DeviceClass ,DeviceImpl ,DeviceState ,Property }, + qom::{ClassInitImpl ,ObjectCast ,ObjectCastMut ,ObjectImpl ,ObjectMethods ,ObjectType }, qom_isa, 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:DummyState , + migrate_clock:bool , +} + +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 :Mutex <Cell <bool >> =Mutex ::new (Cell ::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 ()); } }
Quoted 11 lines
Quoted 4 lines
But, when there is deeper class inheritance, it seems impossible to prevent
class_initfrom being called both by the C side's QOM code and by this kind of recursive case on the Rust side.Note that here you have two parameters: what class is being filled (the argument C of ClassInitImpl<C>) *and* what type is being initialized (that's Self).
The "recursion" is only on the argument C, and matches the way C code implements
class_init.
For Rust side, PL011Class' class_init calls SysBusDeviceClass' class_init, and SysBusDeviceClass will also call DeviceClass' class_init. So this is also recursion, right?
Quoted 2 lines
Maybe the confusion is because I implemented
class_inittwice instead of using a separate trait "PL011Impl"?
Ah, yes! But I think the Rust call chain should not use class_init anymore but should use a different method. This way, the original class_init would only serve the C QOM. A separate trait might break the inheritance relationship similar to ClassInitImpl.
Regards,
Zhao
Re: [PATCH 24/26] rust: qom: move device_id to PL011 class side
Il mer 18 dic 2024, 07:39 Zhao Liu <[email protected]> ha scritto:
Quoted 14 lines
I supposed a case, where there is such a QOM (QEMU Object Model) structure relationship:
* DummyState / DummyClass: defined in Rust side, and registered the TypeInfo by
Objectmacro.- So its
class_initwill be called by C QOM code.* DummyChildState / DummyChildClass: defined in Rust side as the child-object of DummyState, and registered the TypeInfo by
Objectmacro. And suppose it can inherit the trait of DummyClass - ClassInitImpl<DummyClass> (but I found a gap here, as detailed later; I expect it should be able to inherit normally).
Quoted 8 lines
- So its
class_initwill be called by C QOM code. In C code call chain, its parent'sclass_initshould be called by C before its ownclass_init.
- However, note that according to the Rust class initialization call chain, it should also call the parent'sclass_initwithin its ownclass_init.
- :( the parent'sclass_initgets called twice.
No, I don't think so. You have the same thing already with PL011State/PL011Luminary.
There, you have
* object_class_init
* device_class_init
* sysbus_device_class_init
* <PL011State as ClassInitImpl<PL011Class>>::class_init
* <PL011State as ClassInitImpl<SysBusDeviceClass>>::class_init
* <PL011State as ClassInitImpl<DeviceClass>>::class_init
* <PL011State as ClassInitImpl<ObjectClass>>::class_init
* <PL011Luminary as ClassInitImpl<PL011Class>>::class_init
* <PL011Luminary as ClassInitImpl<SysBusDeviceClass>>::class_init
* <PL011Luminary as ClassInitImpl<DeviceClass>>::class_init
* <PL011Luminary as ClassInitImpl<ObjectClass>>::class_init
But note that these calls are all different and indeed the last three are empty (all vtable entries are None). This is like a C class_init implementation that does not set any of sdc, dc or oc.
Moving on to another topic, about the gap (or question :-)) where a
Quoted 5 lines
child class inherits the ClassInitImpl trait from the parent, please see my test case example below: Doing something similar to SysBusDevice and DeviceState using a generic T outside of the QOM library would violate the orphan rule.
Ugh, you're right. Maybe ClassInitImpl should just be merged into ObjectImpl etc. as a default method implementation. I will check.
Quoted 10 lines
Quoted 2 lines
But, when there is deeper class inheritance, it seems impossible to
Quoted 1 line
prevent
class_initfrom being called both by the C side's QOM code andby
Quoted 7 lines
Quoted 2 lines
this kind of recursive case on the Rust side.
Note that here you have two parameters: what class is being filled (the argument C of ClassInitImpl<C>) *and* what type is being initialized (that's Self).
Quoted 7 lines
Quoted 2 lines
The "recursion" is only on the argument C, and matches the way C code implements
class_init.For Rust side, PL011Class'
class_initcalls SysBusDeviceClass'class_init, and SysBusDeviceClass will also call DeviceClass'class_init. So this is also recursion, right?
No, Self is not PL011Class. Self is PL011State (or PL011Luminary/ and it always remains the same. What changes is *what part* of the class is overwritten, but the order of calls from qom/object.c follows the same logic in both C and Rust.
Quoted 8 lines
Maybe the confusion is because I implemented
class_inittwice instead ofQuoted 1 line
using a separate trait "PL011Impl"?
Ah, yes! But I think the Rust call chain should not use
class_initanymore but should use a different method. This way, the originalclass_initwould only serve the C QOM. A separate trait might break the inheritance relationship similar to ClassInitImpl.
Do you still think that this is the case? I will look into how to avoid the problem with the orphan rule, but otherwise I think things are fine.
Paolo
Quoted 1 line
Re: [PATCH 24/26] rust: qom: move device_id to PL011 class side
Quoted 7 lines · Paolo Bonzini
Moving on to another topic, about the gap (or question :-)) where a child class inherits the ClassInitImpl trait from the parent, please see my test case example below: Doing something similar to SysBusDevice and DeviceState using a generic T outside of the QOM library would violate the orphan rule.
Ugh, you're right. Maybe ClassInitImpl should just be merged into ObjectImpl etc. as a default method implementation. I will check.
Ok, I think we can make it mostly a documentation issue:
rust/qemu-api/src/qom.rs +38 -11
@@ -451,13 +451,14 @@ pub trait ObjectImpl: ObjectType + ClassInitImpl<Self::Class> {/// Each struct will implement this trait with `T` equal to each /// superclass. For example, a device should implement at least /// `ClassInitImpl<`[`DeviceClass`](crate::qdev::DeviceClass)`>` and -/// `ClassInitImpl<`[`ObjectClass`]`>`. +/// `ClassInitImpl<`[`ObjectClass`]`>`. Such implementations are +/// made in one of two ways. /// -/// Fortunately, this is almost never necessary. Instead, the Rust -/// implementation of methods will usually come from a trait like -/// [`ObjectImpl`] or [`DeviceImpl`](crate::qdev::DeviceImpl). -/// `ClassInitImpl` then can be provided by blanket implementations -/// that operate on all implementors of the `*Impl`* trait. For example: +/// For most superclasses, `ClassInitImpl` is provided by the `qemu-api` +/// crate itself. The Rust implementation of methods will come from a +/// trait like [`ObjectImpl`] or [`DeviceImpl`](crate::qdev::DeviceImpl), +/// and `ClassInitImpl` is provided by blanket implementations that +/// operate on all implementors of the `*Impl`* trait. For example: /// /// ```ignore /// impl<T> ClassInitImpl<DeviceClass> for T
@@ -469,11 +470,37 @@ pub trait ObjectImpl: ObjectType + ClassInitImpl<Self::Class> {/// after initializing the `DeviceClass` part of the class struct, /// the parent [`ObjectClass`] is initialized as well. /// -/// The only case in which a manual implementation of the trait is needed -/// is for interfaces (note that there is no Rust example yet for using -/// interfaces). In this case, unlike the C case, the Rust class _has_ -/// to define its own class struct `FooClass` to go together with -/// `ClassInitImpl<FooClass>`. +/// In some other cases, manual implementation of the trait is needed. +/// These are the following: +/// +/// * for classes that implement interfaces, the Rust code _has_ +/// to define its own class struct `FooClass` and implement +/// `ClassInitImpl<FooClass>`. `ClassInitImpl<FooClass>`'s +/// `class_init` method will then forward to multiple other +/// `class_init`s, for the interfaces as well as the superclass. +/// (Note that there is no Rust example yet for using +/// interfaces). +/// +/// * for classes implemented outside the ``qemu-api`` crate, it's +/// not possible to add blanket implementations like the above one, +/// due to orphan rules. In that case, the easiest solution is to +/// implement `ClassInitImpl<YourSuperclass>` for each subclass, +/// and not have a `YourSuperclassImpl` trait at all: +/// +/// ```ignore +/// impl ClassInitImpl<YourSuperclass> for YourSubclass { +/// fn class_init(klass: &mut YourSuperclass) { +/// klass.some_method = Some(Self::some_method); +/// <Self as ClassInitImpl<SysBusDeviceClass>>::class_init(&mut klass.parent_class); +/// } +/// } +/// ``` +/// +/// While this method incurs a small amount of code duplication, +/// it is generally limited to the recursive call on the last line. +/// This is because classes defined in Rust do not need the same +/// glue code that is needed when the classes are defined in C code. +/// You may consider using a macro if you have many subclasses. pub trait ClassInitImpl <T > {/// Initialize `klass` to point to the virtual method implementations /// for `Self`. On entry, the virtual method pointers are set to
Optionally, something like this can be squashed in this patch, but I do not think it's worth the savings of... 3 lines of code:
rust/hw/char/pl011/src/device.rs +4 -7
@@ -46,11 +46,6 @@ fn index(&self, idx: hwaddr) -> &Self::Output { } } -impl DeviceId { -const ARM :Self =Self (&[0x11 ,0x10 ,0x14 ,0x00 ,0x0d ,0xf0 ,0x05 ,0xb1 ]); -const LUMINARY :Self =Self (&[0x11 ,0x00 ,0x18 ,0x01 ,0x0d ,0xf0 ,0x05 ,0xb1 ]); -} -#[repr( C )] #[derive( Debug , qemu_api_macros:: Object , qemu_api_macros::offsets)] /// PL011 Device Model in QEMU
@@ -112,7 +107,8 @@ unsafe impl ObjectType for PL011State {impl ClassInitImpl <PL011Class >for PL011State {fn class_init (klass: &mut PL011Class ) { - klass.device_id =DeviceId ::ARM ; + klass.device_id =DeviceId (&[0x11 ,0x10 ,0x14 ,0x00 ,0x0d ,0xf0 ,0x05 ,0xb1 ]); + <Self as ClassInitImpl <SysBusDeviceClass >>::class_init (&mut klass.parent_class); } }
@@ -628,7 +624,8 @@ pub struct PL011Luminary {impl ClassInitImpl <PL011Class >for PL011Luminary {fn class_init (klass: &mut PL011Class ) { - klass.device_id =DeviceId ::LUMINARY ; + klass.device_id =DeviceId (&[0x11 ,0x00 ,0x18 ,0x01 ,0x0d ,0xf0 ,0x05 ,0xb1 ]); + <Self as ClassInitImpl <SysBusDeviceClass >>::class_init (&mut klass.parent_class); } }
Re: [PATCH 24/26] rust: qom: move device_id to PL011 class side
Quoted 65 lines · Paolo Bonzini
Date: Wed, 18 Dec 2024 11:26:35 +0100
From: Paolo Bonzini <[email protected]>
Subject: Re: [PATCH 24/26] rust: qom: movedevice_idto PL011 class sideQuoted 8 lines · Paolo Bonzini
Moving on to another topic, about the gap (or question :-)) where a child class inherits the ClassInitImpl trait from the parent, please see my test case example below: Doing something similar to SysBusDevice and DeviceState using a generic T outside of the QOM library would violate the orphan rule.
Ugh, you're right. Maybe ClassInitImpl should just be merged into ObjectImpl etc. as a default method implementation. I will check.
Ok, I think we can make it mostly a documentation issue:
rust/qemu-api/src/qom.rs +22
-11@@ -451,13 +451,14 @@ pub trait ObjectImpl: ObjectType + ClassInitImpl<Self::Class> {/// Each struct will implement this trait with `T` equal to each /// superclass. For example, a device should implement at least /// `ClassInitImpl<`[`DeviceClass`](crate::qdev::DeviceClass)`>` and -/// `ClassInitImpl<`[`ObjectClass`]`>`. +/// `ClassInitImpl<`[`ObjectClass`]`>`. Such implementations are +/// made in one of two ways. /// -/// Fortunately, this is almost never necessary. Instead, the Rust -/// implementation of methods will usually come from a trait like -/// [`ObjectImpl`] or [`DeviceImpl`](crate::qdev::DeviceImpl). -/// `ClassInitImpl` then can be provided by blanket implementations -/// that operate on all implementors of the `*Impl`* trait. For example: +/// For most superclasses, `ClassInitImpl` is provided by the `qemu-api` +/// crate itself. The Rust implementation of methods will come from a +/// trait like [`ObjectImpl`] or [`DeviceImpl`](crate::qdev::DeviceImpl), +/// and `ClassInitImpl` is provided by blanket implementations that +/// operate on all implementors of the `*Impl`* trait. For example: /// /// ```ignore /// impl<T> ClassInitImpl<DeviceClass> for T @@ -469,11 +470,37 @@ pub trait ObjectImpl: ObjectType + ClassInitImpl<Self::Class> {/// after initializing the `DeviceClass` part of the class struct, /// the parent [`ObjectClass`] is initialized as well. /// -/// The only case in which a manual implementation of the trait is needed -/// is for interfaces (note that there is no Rust example yet for using -/// interfaces). In this case, unlike the C case, the Rust class _has_ -/// to define its own class struct `FooClass` to go together with -/// `ClassInitImpl<FooClass>`. +/// In some other cases, manual implementation of the trait is needed. +/// These are the following: +/// +/// * for classes that implement interfaces, the Rust code _has_ +/// to define its own class struct `FooClass` and implement +/// `ClassInitImpl<FooClass>`. `ClassInitImpl<FooClass>`'s +/// `class_init` method will then forward to multiple other +/// `class_init`s, for the interfaces as well as the superclass. +/// (Note that there is no Rust example yet for using +/// interfaces). +/// +/// * for classes implemented outside the ``qemu-api`` crate, it's +/// not possible to add blanket implementations like the above one, +/// due to orphan rules. In that case, the easiest solution is to +/// implement `ClassInitImpl<YourSuperclass>` for each subclass,
rust/qemu-api/src/qom.rs pub trait ObjectImpl: ObjectType + ClassInitImpl<Self::Class> { · line 497
Quoted 10 lines
rust/qemu-api/src/qom.rs +10
-0+/// and not have a `YourSuperclassImpl` trait at all: +/// +/// ```ignore +/// impl ClassInitImpl<YourSuperclass> for YourSubclass { +/// fn class_init(klass: &mut YourSuperclass) { +/// klass.some_method = Some(Self::some_method); +/// <Self as ClassInitImpl<SysBusDeviceClass>>::class_init(&mut klass.parent_class); +/// } +/// } +/// ```
BTW, maybe we could also squash my previous example in test? :-)
rust/qemu-api/src/qom.rs pub trait ObjectImpl: ObjectType + ClassInitImpl<Self::Class> { · line 502
Quoted 5 lines
rust/qemu-api/src/qom.rs +5
-0+/// +/// While this method incurs a small amount of code duplication, +/// it is generally limited to the recursive call on the last line. +/// This is because classes defined in Rust do not need the same +/// glue code that is needed when the classes are defined in C code.
Now I understand this advantage.
rust/qemu-api/src/qom.rs pub trait ObjectImpl: ObjectType + ClassInitImpl<Self::Class> { · line 503
Quoted 1 line
rust/qemu-api/src/qom.rs +1
-0+/// You may consider using a macro if you have many subclasses.
Yes, a custom macro is enough!
rust/qemu-api/src/qom.rs pub trait ObjectImpl: ObjectType + ClassInitImpl<Self::Class> { · line 506
Quoted 3 lines
rust/qemu-api/src/qom.rs +0
-0pub trait ClassInitImpl <T > {/// Initialize `klass` to point to the virtual method implementations /// for `Self`. On entry, the virtual method pointers are set to
All the above changes look good to me!
Quoted 28 lines
Optionally, something like this can be squashed in this patch, but I do not think it's worth the savings of... 3 lines of code:
rust/hw/char/pl011/src/device.rs +2
-6@@ -46,11 +46,6 @@ fn index(&self, idx: hwaddr) -> &Self::Output { } } -impl DeviceId { -const ARM :Self =Self (&[0x11 ,0x10 ,0x14 ,0x00 ,0x0d ,0xf0 ,0x05 ,0xb1 ]); -const LUMINARY :Self =Self (&[0x11 ,0x00 ,0x18 ,0x01 ,0x0d ,0xf0 ,0x05 ,0xb1 ]); -} -#[repr( C )] #[derive( Debug , qemu_api_macros:: Object , qemu_api_macros::offsets)] /// PL011 Device Model in QEMU @@ -112,7 +107,8 @@ unsafe impl ObjectType for PL011State {impl ClassInitImpl <PL011Class >for PL011State {fn class_init (klass: &mut PL011Class ) { - klass.device_id =DeviceId ::ARM ; + klass.device_id =DeviceId (&[0x11 ,0x10 ,0x14 ,0x00 ,0x0d ,0xf0 ,0x05 ,0xb1 ]); + <Self as ClassInitImpl <SysBusDeviceClass >>::class_init (&mut klass.parent_class); } }
rust/hw/char/pl011/src/device.rs pub struct PL011Luminary { · line 630
Quoted 8 lines
rust/hw/char/pl011/src/device.rs +2
-1@@ -628,7 +624,8 @@ pub struct PL011Luminary {impl ClassInitImpl <PL011Class >for PL011Luminary {fn class_init (klass: &mut PL011Class ) { - klass.device_id =DeviceId ::LUMINARY ; + klass.device_id =DeviceId (&[0x11 ,0x00 ,0x18 ,0x01 ,0x0d ,0xf0 ,0x05 ,0xb1 ]); + <Self as ClassInitImpl <SysBusDeviceClass >>::class_init (&mut klass.parent_class); } }
Still fine for me. :-)
Regards,
Zhao
Re: [PATCH 24/26] rust: qom: move device_id to PL011 class side
Il mer 18 dic 2024, 15:32 Zhao Liu <[email protected]> ha scritto:
Quoted 8 lines · Paolo Bonzini
Quoted 7 lines
Date: Wed, 18 Dec 2024 11:26:35 +0100
From: Paolo Bonzini <[email protected]>
Subject: Re: [PATCH 24/26] rust: qom: movedevice_idto PL011 class sideQuoted 2 lines · Paolo Bonzini
Moving on to another topic, about the gap (or question :-)) where a child class inherits the ClassInitImpl trait from the parent,
Quoted 9 lines
please see
Quoted 1 line
Quoted 1 line
my test case example below: Doing something similar to
SysBusDevice and
Quoted 1 line
Quoted 1 line
DeviceState using a generic T outside of the QOM library would
violate
Quoted 1 line
Quoted 1 line
the orphan rule.
BTW, maybe we could also squash my previous example in test? :-)
Sure.
Paolo
Re: [PATCH 24/26] rust: qom: move device_id to PL011 class side
In reply to Paolo BonziniQuoted 4 lines
No, Self is not PL011Class. Self is PL011State (or PL011Luminary/ and it always remains the same. What changes is *what part* of the class is overwritten, but the order of calls from
qom/object.cfollows the same logic in both C and Rust.
Thanks! Now I feel I see!
For C side, type_initialize() will allocate a new class instance by ti->class = g_malloc0(ti->class_size), then actually C side's parent class_init will initialize that new class instance.
For Rust side, the initialization call chain will initialize Self's embedded parent class, one by one.
So that's fine!
Quoted 10 lines
Quoted 8 lines
Maybe the confusion is because I implemented
class_inittwice instead ofQuoted 1 line
using a separate trait "PL011Impl"?
Ah, yes! But I think the Rust call chain should not use
class_initanymore but should use a different method. This way, the originalclass_initwould only serve the C QOM. A separate trait might break the inheritance relationship similar to ClassInitImpl.Do you still think that this is the case?
No, now this patch is fine for me!
Thanks,
Zhao
Re: [PATCH 24/26] rust: qom: move device_id to PL011 class side
In reply to Paolo BonziniQuoted 9 lines · Paolo Bonzini
Date: Mon, 9 Dec 2024 13:37:15 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 24/26] rust: qom: movedevice_idto PL011 class side
X-Mailer: git-send-email 2.47.1There is no need to monkeypatch
DeviceId::Luminaryinto the already-initialized PL011State. Instead, now that we can define a class hierarchy, we can define PL011Class and makedevice_ida field in there.
Quoted 7 lines
There is also no need anymore to have "Arm" as zero, so change DeviceId into a wrapper for the array; all it does is provide an Index<hwaddr> implementation because arrays can only be indexed by usize.
Signed-off-by Paolo Bonzini <[email protected]>--- rust/hw/char/pl011/src/device.rs | 59 +++++++++++++++----------------- 1 file changed, 28 insertions(+), 31 deletions(-)
PATCH 25/26 rust: qemu-api: add a module to wrap functions and zero-sized closures
In reply to Paolo BonziniOne recurring issue when writing Rust bindings is how to convert a Rust function ("fn" or "impl Fn") to a C function, and how to pass around "self" to a C function that only takes a void*.
An easy solution would be to store on the heap a pair consisting of a pointer to the Rust function and the pointer to "self", but it is possible to do better. If an "Fn" has zero size (that is, if it is a zero-capture closures or a function pointer---which in turn includes all methods), it is possible to build a generic Rust function that calls it even if you only have the type; you don't need either the pointer to the function itself (because the address of the code is part of the type) or any closure data (because it has size zero).
Introduce a wrapper that provides the functionality of calling the function given only its type.
--- rust/qemu-api/meson.build | 1 + rust/qemu-api/src/callbacks.rs | 141 +++++++++++++++++++++++++++++++++ rust/qemu-api/src/lib.rs | 1 + 3 files changed, 143 insertions(+) create mode 100644 rust/qemu-api/src/callbacks.rs
rust/qemu-api/meson.build +1 -0
@@ -17,6 +17,7 @@ _qemu_api_rs = static_library( 'src/lib.rs', 'src/bindings.rs', 'src/bitops.rs', + 'src/callbacks.rs', 'src/cell.rs', 'src/c_str.rs', 'src/irq.rs',
rust/qemu-api/src/callbacks.rs new file +144 -0
144 lines not on this page · raw message
rust/qemu-api/src/lib.rs +1 -0
@@ -14,6 +14,7 @@pub mod bitops;pub mod c_str; +pub mod callbacks;pub mod cell;pub mod irq;pub mod module;
Signature · 1 line
2.47.1
Re: [PATCH 25/26] rust: qemu-api: add a module to wrap functions and zero-sized closures
Quoted 17 lines
rust/qemu-api/src/callbacks.rs new file +17
-0+pub unsafe trait FnCall <Args ,R = ()>: 'static +Sync +Sized { +/// Referring to this internal constant asserts that the `Self` type is +/// zero-sized. Can be replaced by an inline const expression in +/// Rust 1.79.0+. +const ASSERT_ZERO_SIZED : () = {assert! (mem::size_of ::<Self >() ==0 ) }; + +/// Call the function with the arguments in args. +fn call (a:Args ) ->R ; +} + +macro_rules! impl_call { + ($($args:ident,)* ) => ( +// SAFETY: because each function is treated as a separate type, +// accessing `FnCall` is only possible in code that would be +// allowed to call the function. +unsafe impl <F , $($args,)*R >FnCall <($($args,)*),R >for F +where
rust/qemu-api/src/callbacks.rs line 116
Quoted 10 lines
rust/qemu-api/src/callbacks.rs new file +10
-0+ F: 'static + Sync + Sized + Fn($($args, )*) -> R, + { +#[inline(always)] + fn call(a: ($($args,)*)) -> R { +let _: () =Self ::ASSERT_ZERO_SIZED ; + +// SAFETY: the safety of this method is the condition for implementing +// `FnCall`. As to the `NonNull` idiom to create a zero-sized type, +// see https://github.com/rust-lang/libs-team/issues/292. +let f: &'staticF =unsafe { &*NonNull ::<Self >::dangling ().as_ptr () };
Awesome! The definition of FnCall and this trick are both very elegant! I've learned a lot.
rust/qemu-api/src/callbacks.rs line 123
Quoted 7 lines
rust/qemu-api/src/callbacks.rs new file +7
-0+ let ($($args,)*) = a; + f($($args,)*) + } + } + ) +} +
The examples and test both show the power of this callback pattern,
PATCH 26/26 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
@@ -76,6 +76,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
@@ -90,10 +115,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,
@@ -103,6 +188,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 ;
@@ -138,4 +225,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_eq! (F ::is_some (),true ); + } + +#[test] +fn test_is_some () { +do_test_is_some (&str::to_owned); + } }
Signature · 1 line
2.47.1
Re: [PATCH 26/26] rust: callbacks: allow passing optional callbacks as ()
Quoted 9 lines · Paolo Bonzini
Date: Mon, 9 Dec 2024 13:37:17 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 26/26] 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>".
I understand the direct use case is MemoryRegionOps, which has optional callbacks. However, I'm not quite sure how exactly it should be applied to C bindings and how it will play with Option<callback>.
Could u pls provide a simple example?
Quoted 14 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(+)rust/qemu-api/src/callbacks.rs +0
-0
rust/qemu-api/src/callbacks.rs line 76
Quoted 1 line
rust/qemu-api/src/callbacks.rs +0
-0@@ -76,6 +76,31 @@/// call_it(&move |_| String::from(x), "hello workd");
typo: s/workd/word/ (in previous patch :-))
Re: [PATCH 26/26] rust: callbacks: allow passing optional callbacks as ()
Il mar 17 dic 2024, 16:55 Zhao Liu <[email protected]> ha scritto:
Quoted 8 lines · Paolo Bonzini
Quoted 3 lines
Date: Mon, 9 Dec 2024 13:37:17 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 26/26] rust: callbacks: allow passing optional callbacksas
Quoted 3 lines
()
X-Mailer: git-send-email 2.47.1
Quoted 8 lines
Quoted 3 lines
In 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>".
I understand the direct use case is MemoryRegionOps, which has optional callbacks. However, I'm not quite sure how exactly it should be applied to C bindings and how it will play with Option<callback>.
You wouldn't use Option<callback> at all, using () instead of None; the difference is that () does not have a parameter while None does (and the compiler cannot infer it). But I am okay with leaving this patch behind until there's a need.
Paolo
Could u pls provide a simple example?
Quoted 22 lines
Quoted 3 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
rust/qemu-api/src/
Quoted 8 lines
the invocation of
F::call.Signed-off-by Paolo Bonzini <[email protected]>--- rust/qemu-api/src/callbacks.rs | 97 ++++++++++++++++++++++++++++++++++ 1 file changed, 97 insertions(+)rust/qemu-api/src/ renamed from rust/qemu-api/src/callbacks.rs +0
-0
callbacks.rsrust/qemu-api/src/callbacks.rs line 76
Quoted 5 lines
index
6401d807198..83c681d6478100644rust/qemu-api/src/callbacks.rs +0
-0@@ -76,6 +76,31 @@/// call_it(&move |_| String::from(x), "hello workd"); typo: s/workd/word/ (in previous patch :-))
Re: [PATCH 26/26] rust: callbacks: allow passing optional callbacks as ()
Quoted 24 lines · Paolo Bonzini
Date: Tue, 17 Dec 2024 17:40:14 +0100
From: Paolo Bonzini <[email protected]>
Subject: Re: [PATCH 26/26] rust: callbacks: allow passing optional
callbacks as ()Il mar 17 dic 2024, 16:55 Zhao Liu <[email protected]> ha scritto:
Quoted 8 lines · Paolo Bonzini
Quoted 3 lines
Date: Mon, 9 Dec 2024 13:37:17 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 26/26] rust: callbacks: allow passing optional callbacksas
Quoted 3 lines
()
X-Mailer: git-send-email 2.47.1Quoted 8 lines
Quoted 3 lines
In 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>".
I understand the direct use case is MemoryRegionOps, which has optional callbacks. However, I'm not quite sure how exactly it should be applied to C bindings and how it will play with Option<callback>.
Quoted 4 lines
You wouldn't use Option<callback> at all, using () instead of None; the difference is that () does not have a parameter while None does (and the compiler cannot infer it). But I am okay with leaving this patch behind until there's a need.
Am I using the wrong terminology? Function pointers in a structure should be called a vtable, rather than callbacks (for example, methods in TypeInfo, read/write methods in MemoryRegionOps). Callbacks are typically function pointers used as function parameters (for example, timer/gpio). So, is the callback implementation here only used for the latter case?
Thanks,
Zhao
Re: [PATCH 26/26] rust: callbacks: allow passing optional callbacks as ()
Il mer 18 dic 2024, 07:50 Zhao Liu <[email protected]> ha scritto:
Quoted 7 lines
Am I using the wrong terminology? Function pointers in a structure should be called a vtable, rather than callbacks (for example, methods in TypeInfo,
read/write methods in MemoryRegionOps). Callbacks are typically function pointers used as function parameters (for example, timer/gpio). So, is the callback implementation here only used for the latter case?
The callback implementation is not used for QOM indeed. In that case, using FnCall would require something like
const UNPARENT: impl FnCall((&Self,));
which does not exist as far as I know?
MemoryRegionOps is a mix of callbacks and a vtable. From the Rust point of view, with the API that uses the builder pattern, MemoryRegionOps (and VMStateDescription too) would be closer to callbacks. Instead when you use traits and fill in the class object, that's clearly a vtable.
But in this sense MemoryRegionOps do not need optional callbacks. You just don't call the ops.read() method if you don't need to set a read callback for example. So I am not sure if anything that is planned right now needs the optional callbacks. It's good to have the patch for the future but it's not necessary right now.
Paolo
Re: [PATCH 26/26] rust: callbacks: allow passing optional callbacks as ()
Quoted 15 lines · Paolo Bonzini
Date: Wed, 18 Dec 2024 08:32:59 +0100
From: Paolo Bonzini <[email protected]>
Subject: Re: [PATCH 26/26] rust: callbacks: allow passing optional
callbacks as ()Il mer 18 dic 2024, 07:50 Zhao Liu <[email protected]> ha scritto:
Quoted 7 lines
Am I using the wrong terminology? Function pointers in a structure should be called a vtable, rather than callbacks (for example, methods in TypeInfo,
read/write methods in MemoryRegionOps). Callbacks are typically function pointers used as function parameters (for example, timer/gpio). So, is the callback implementation here only used for the latter case?
Quoted 6 lines
The callback implementation is not used for QOM indeed. In that case, using FnCall would require something like
const UNPARENT: impl FnCall((&Self,));
which does not exist as far as I know?
Yes, it's incorrect. (I know you have some magic, so I have this question to see your idea.)
Quoted 10 lines
MemoryRegionOps is a mix of callbacks and a vtable. From the Rust point of view, with the API that uses the builder pattern, MemoryRegionOps (and VMStateDescription too) would be closer to callbacks. Instead when you use traits and fill in the class object, that's clearly a vtable.
But in this sense MemoryRegionOps do not need optional callbacks. You just don't call the
ops.read()method if you don't need to set a read callback for example. So I am not sure if anything that is planned right now needs the optional callbacks. It's good to have the patch for the future but it's not necessary right now.
Thanks for your explaination. I agree your plan. I also think it will be useful in the future.
Regards,
Zhao
Quoted 20 lines · Paolo Bonzini
Paolo Bonzini (26):
bql: check that the BQL is not dropped within marked sections
rust: cell: add BQL-enforcing Cell variant
rust: cell: add BQL-enforcing RefCell variant
rust: define prelude
rust: add bindings for interrupt sources
rust: add a bit operation module
rust: qom: add default definitions for ObjectImpl
rust: qom: rename Class trait to ClassInitImpl
rust: qom: converttype_info! macro to an associated const
rust: qom: move ClassInitImpl to the instance side
rust: qdev: movedevice_class_init! body to generic function,
ClassInitImpl implementation to macro
rust: qdev: move bridge for realize and reset functions out of pl011
rust: qom: automatically use Drop trait to implementinstance_finalize
rust: qom: move bridge for TypeInfo functions out of pl011
rust: qom: split ObjectType from ObjectImpl trait
rust: qom: change the parent type to an associated type
rust: qom: putclass_inittogether from multiple ClassInitImpl<>
rust: qom: add possibility of overriding unparent
Quoted 8 lines
rust: rename qemu-api modules to follow C code a bit more
rust: re-export C types from qemu-api submodules
rust: tests: allow writing more than one test
rust: qom: add casting functionality
rust: qom: add initial subset of methods on Object
rust: qom: movedevice_idto PL011 class side
rust: qemu-api: add a module to wrap functions and zero-sized closures
rust: callbacks: allow passing optional callbacks as ()
Am I correct some patches are from Zhao Liu and got the authorship inadvertently removed?
Quoted 32 lines · Philippe Mathieu-Daudé
Quoted 20 lines · Paolo Bonzini
Paolo Bonzini (26):
bql: check that the BQL is not dropped within marked sections
rust: cell: add BQL-enforcing Cell variant
rust: cell: add BQL-enforcing RefCell variant
rust: define prelude
rust: add bindings for interrupt sources
rust: add a bit operation module
rust: qom: add default definitions for ObjectImpl
rust: qom: rename Class trait to ClassInitImpl
rust: qom: converttype_info! macro to an associated const
rust: qom: move ClassInitImpl to the instance side
rust: qdev: movedevice_class_init! body to generic function,
ClassInitImpl implementation to macro
rust: qdev: move bridge for realize and reset functions out of pl011
rust: qom: automatically use Drop trait to implementinstance_finalize
rust: qom: move bridge for TypeInfo functions out of pl011
rust: qom: split ObjectType from ObjectImpl trait
rust: qom: change the parent type to an associated type
rust: qom: putclass_inittogether from multiple ClassInitImpl<>
rust: qom: add possibility of overriding unparentQuoted 8 lines
rust: rename qemu-api modules to follow C code a bit more
rust: re-export C types from qemu-api submodules
rust: tests: allow writing more than one test
rust: qom: add casting functionality
rust: qom: add initial subset of methods on Object
rust: qom: movedevice_idto PL011 class side
rust: qemu-api: add a module to wrap functions and zero-sized closures
rust: callbacks: allow passing optional callbacks as ()
Quoted 2 lines
Am I correct some patches are from Zhao Liu and got the authorship inadvertently removed?
Just one, which is co-authored; it has
So I should have put either Co-authored-by him or left him as the primary author.
Paolo
Quoted 41 lines · Paolo Bonzini
Date: Mon, 9 Dec 2024 18:23:21 +0100
From: Paolo Bonzini <[email protected]>
Subject: Re: [PATCH 00/26] rust: bundle of prerequisites for HPET
implementationQuoted 32 lines · Philippe Mathieu-Daudé
Quoted 20 lines · Paolo Bonzini
Paolo Bonzini (26):
bql: check that the BQL is not dropped within marked sections
rust: cell: add BQL-enforcing Cell variant
rust: cell: add BQL-enforcing RefCell variant
rust: define prelude
rust: add bindings for interrupt sources
rust: add a bit operation module
rust: qom: add default definitions for ObjectImpl
rust: qom: rename Class trait to ClassInitImpl
rust: qom: converttype_info! macro to an associated const
rust: qom: move ClassInitImpl to the instance side
rust: qdev: movedevice_class_init! body to generic function,
ClassInitImpl implementation to macro
rust: qdev: move bridge for realize and reset functions out of pl011
rust: qom: automatically use Drop trait to implementinstance_finalize
rust: qom: move bridge for TypeInfo functions out of pl011
rust: qom: split ObjectType from ObjectImpl trait
rust: qom: change the parent type to an associated type
rust: qom: putclass_inittogether from multiple ClassInitImpl<>
rust: qom: add possibility of overriding unparentQuoted 8 lines
rust: rename qemu-api modules to follow C code a bit more
rust: re-export C types from qemu-api submodules
rust: tests: allow writing more than one test
rust: qom: add casting functionality
rust: qom: add initial subset of methods on Object
rust: qom: movedevice_idto PL011 class side
rust: qemu-api: add a module to wrap functions and zero-sized closures
rust: callbacks: allow passing optional callbacks as ()Quoted 2 lines
Am I correct some patches are from Zhao Liu and got the authorship inadvertently removed?
Quoted 9 lines
Just one, which is co-authored; it has
Signed-off-by Zhao Liu <[email protected]>Co-authored-by Paolo Bonzini <[email protected]>Signed-off-by Paolo Bonzini <[email protected]>So I should have put either Co-authored-by him or left him as the primary author.
Thank you Paolo! You deserve to be credited as the author. It's completely different from my previous solution, so it's all your work! HPET will be a user.
Regards,
Zhao