xref: /qemu/rust/qemu-api/src/qdev.rs (revision 7bd8e3ef63330e870cf4644d21c285cce35c703d)
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, os::raw::c_void};
6 
7 use crate::{
8     bindings::{self, DeviceClass, DeviceState, Error, ObjectClass, Property, VMStateDescription},
9     prelude::*,
10     zeroable::Zeroable,
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         &[Zeroable::ZERO; 1]
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 /// the `impl_device_class!` macro.
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 /// # Safety
70 ///
71 /// We expect the FFI user of this function to pass a valid pointer that
72 /// can be downcasted to type `DeviceClass`, because `T` implements
73 /// `DeviceImpl`.
74 pub unsafe extern "C" fn rust_device_class_init<T: DeviceImpl>(
75     klass: *mut ObjectClass,
76     _: *mut c_void,
77 ) {
78     let mut dc = ::core::ptr::NonNull::new(klass.cast::<DeviceClass>()).unwrap();
79     unsafe {
80         let dc = dc.as_mut();
81         if <T as DeviceImpl>::REALIZE.is_some() {
82             dc.realize = Some(rust_realize_fn::<T>);
83         }
84         if <T as DeviceImpl>::RESET.is_some() {
85             bindings::device_class_set_legacy_reset(dc, Some(rust_reset_fn::<T>));
86         }
87         if let Some(vmsd) = <T as DeviceImpl>::vmsd() {
88             dc.vmsd = vmsd;
89         }
90         bindings::device_class_set_props(dc, <T as DeviceImpl>::properties().as_ptr());
91     }
92 }
93 
94 #[macro_export]
95 macro_rules! impl_device_class {
96     ($type:ty) => {
97         impl $crate::definitions::ClassInitImpl for $type {
98             const CLASS_INIT: Option<
99                 unsafe extern "C" fn(klass: *mut ObjectClass, data: *mut ::std::os::raw::c_void),
100             > = Some($crate::device_class::rust_device_class_init::<$type>);
101             const CLASS_BASE_INIT: Option<
102                 unsafe extern "C" fn(klass: *mut ObjectClass, data: *mut ::std::os::raw::c_void),
103             > = None;
104         }
105     };
106 }
107 
108 #[macro_export]
109 macro_rules! define_property {
110     ($name:expr, $state:ty, $field:ident, $prop:expr, $type:ty, default = $defval:expr$(,)*) => {
111         $crate::bindings::Property {
112             // use associated function syntax for type checking
113             name: ::std::ffi::CStr::as_ptr($name),
114             info: $prop,
115             offset: $crate::offset_of!($state, $field) as isize,
116             set_default: true,
117             defval: $crate::bindings::Property__bindgen_ty_1 { u: $defval as u64 },
118             ..$crate::zeroable::Zeroable::ZERO
119         }
120     };
121     ($name:expr, $state:ty, $field:ident, $prop:expr, $type:ty$(,)*) => {
122         $crate::bindings::Property {
123             // use associated function syntax for type checking
124             name: ::std::ffi::CStr::as_ptr($name),
125             info: $prop,
126             offset: $crate::offset_of!($state, $field) as isize,
127             set_default: false,
128             ..$crate::zeroable::Zeroable::ZERO
129         }
130     };
131 }
132 
133 #[macro_export]
134 macro_rules! declare_properties {
135     ($ident:ident, $($prop:expr),*$(,)*) => {
136         pub static $ident: [$crate::bindings::Property; {
137             let mut len = 1;
138             $({
139                 _ = stringify!($prop);
140                 len += 1;
141             })*
142             len
143         }] = [
144             $($prop),*,
145             $crate::zeroable::Zeroable::ZERO,
146         ];
147     };
148 }
149 
150 unsafe impl ObjectType for bindings::DeviceState {
151     type Class = bindings::DeviceClass;
152     const TYPE_NAME: &'static CStr =
153         unsafe { CStr::from_bytes_with_nul_unchecked(bindings::TYPE_DEVICE) };
154 }
155