xref: /qemu/rust/qemu-api/src/qdev.rs (revision 6dd818fbbbe3efc63889e7d811ac6b70e788c629)
1 // Copyright 2024, Linaro Limited
2 // Author(s): Manos Pitsidianakis <manos.pitsidianakis@linaro.org>
3 // SPDX-License-Identifier: GPL-2.0-or-later
4 
5 use std::ffi::CStr;
6 
7 use crate::{
8     bindings::{self, DeviceClass, DeviceState, Error, Property, VMStateDescription},
9     definitions::ClassInitImpl,
10     prelude::*,
11 };
12 
13 /// Trait providing the contents of [`DeviceClass`].
14 pub trait DeviceImpl {
15     /// _Realization_ is the second stage of device creation. It contains
16     /// all operations that depend on device properties and can fail (note:
17     /// this is not yet supported for Rust devices).
18     ///
19     /// If not `None`, the parent class's `realize` method is overridden
20     /// with the function pointed to by `REALIZE`.
21     const REALIZE: Option<fn(&mut Self)> = None;
22 
23     /// If not `None`, the parent class's `reset` method is overridden
24     /// with the function pointed to by `RESET`.
25     ///
26     /// Rust does not yet support the three-phase reset protocol; this is
27     /// usually okay for leaf classes.
28     const RESET: Option<fn(&mut Self)> = None;
29 
30     /// An array providing the properties that the user can set on the
31     /// device.  Not a `const` because referencing statics in constants
32     /// is unstable until Rust 1.83.0.
33     fn properties() -> &'static [Property] {
34         &[]
35     }
36 
37     /// A `VMStateDescription` providing the migration format for the device
38     /// Not a `const` because referencing statics in constants is unstable
39     /// until Rust 1.83.0.
40     fn vmsd() -> Option<&'static VMStateDescription> {
41         None
42     }
43 }
44 
45 /// # Safety
46 ///
47 /// This function is only called through the QOM machinery and
48 /// used by the `ClassInitImpl<DeviceClass>` trait.
49 /// We expect the FFI user of this function to pass a valid pointer that
50 /// can be downcasted to type `T`. We also expect the device is
51 /// readable/writeable from one thread at any time.
52 unsafe extern "C" fn rust_realize_fn<T: DeviceImpl>(dev: *mut DeviceState, _errp: *mut *mut Error) {
53     assert!(!dev.is_null());
54     let state = dev.cast::<T>();
55     T::REALIZE.unwrap()(unsafe { &mut *state });
56 }
57 
58 /// # Safety
59 ///
60 /// We expect the FFI user of this function to pass a valid pointer that
61 /// can be downcasted to type `T`. We also expect the device is
62 /// readable/writeable from one thread at any time.
63 unsafe extern "C" fn rust_reset_fn<T: DeviceImpl>(dev: *mut DeviceState) {
64     assert!(!dev.is_null());
65     let state = dev.cast::<T>();
66     T::RESET.unwrap()(unsafe { &mut *state });
67 }
68 
69 impl<T> ClassInitImpl<DeviceClass> for T
70 where
71     T: DeviceImpl,
72 {
73     fn class_init(dc: &mut DeviceClass) {
74         if <T as DeviceImpl>::REALIZE.is_some() {
75             dc.realize = Some(rust_realize_fn::<T>);
76         }
77         if <T as DeviceImpl>::RESET.is_some() {
78             unsafe {
79                 bindings::device_class_set_legacy_reset(dc, Some(rust_reset_fn::<T>));
80             }
81         }
82         if let Some(vmsd) = <T as DeviceImpl>::vmsd() {
83             dc.vmsd = vmsd;
84         }
85         let prop = <T as DeviceImpl>::properties();
86         if !prop.is_empty() {
87             unsafe {
88                 bindings::device_class_set_props_n(dc, prop.as_ptr(), prop.len());
89             }
90         }
91     }
92 }
93 
94 #[macro_export]
95 macro_rules! define_property {
96     ($name:expr, $state:ty, $field:ident, $prop:expr, $type:ty, default = $defval:expr$(,)*) => {
97         $crate::bindings::Property {
98             // use associated function syntax for type checking
99             name: ::std::ffi::CStr::as_ptr($name),
100             info: $prop,
101             offset: $crate::offset_of!($state, $field) as isize,
102             set_default: true,
103             defval: $crate::bindings::Property__bindgen_ty_1 { u: $defval as u64 },
104             ..$crate::zeroable::Zeroable::ZERO
105         }
106     };
107     ($name:expr, $state:ty, $field:ident, $prop:expr, $type:ty$(,)*) => {
108         $crate::bindings::Property {
109             // use associated function syntax for type checking
110             name: ::std::ffi::CStr::as_ptr($name),
111             info: $prop,
112             offset: $crate::offset_of!($state, $field) as isize,
113             set_default: false,
114             ..$crate::zeroable::Zeroable::ZERO
115         }
116     };
117 }
118 
119 #[macro_export]
120 macro_rules! declare_properties {
121     ($ident:ident, $($prop:expr),*$(,)*) => {
122         pub static $ident: [$crate::bindings::Property; {
123             let mut len = 0;
124             $({
125                 _ = stringify!($prop);
126                 len += 1;
127             })*
128             len
129         }] = [
130             $($prop),*,
131         ];
132     };
133 }
134 
135 unsafe impl ObjectType for DeviceState {
136     type Class = DeviceClass;
137     const TYPE_NAME: &'static CStr =
138         unsafe { CStr::from_bytes_with_nul_unchecked(bindings::TYPE_DEVICE) };
139 }
140