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