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