xref: /qemu/rust/qemu-api/src/qdev.rs (revision f75fb90ff2af75cd4405fe4c6ba0c0c38a120590)
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     zeroable::Zeroable,
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         &[Zeroable::ZERO; 1]
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         bindings::device_class_set_props(dc, <T as DeviceImpl>::properties().as_ptr());
90     }
91 }
92 
93 #[macro_export]
94 macro_rules! impl_device_class {
95     ($type:ty) => {
96         impl $crate::definitions::ClassInitImpl for $type {
97             const CLASS_INIT: Option<
98                 unsafe extern "C" fn(klass: *mut ObjectClass, data: *mut ::std::os::raw::c_void),
99             > = Some($crate::device_class::rust_device_class_init::<$type>);
100             const CLASS_BASE_INIT: Option<
101                 unsafe extern "C" fn(klass: *mut ObjectClass, data: *mut ::std::os::raw::c_void),
102             > = None;
103         }
104     };
105 }
106 
107 #[macro_export]
108 macro_rules! define_property {
109     ($name:expr, $state:ty, $field:ident, $prop:expr, $type:ty, default = $defval:expr$(,)*) => {
110         $crate::bindings::Property {
111             // use associated function syntax for type checking
112             name: ::std::ffi::CStr::as_ptr($name),
113             info: $prop,
114             offset: $crate::offset_of!($state, $field) as isize,
115             set_default: true,
116             defval: $crate::bindings::Property__bindgen_ty_1 { u: $defval as u64 },
117             ..$crate::zeroable::Zeroable::ZERO
118         }
119     };
120     ($name:expr, $state:ty, $field:ident, $prop:expr, $type:ty$(,)*) => {
121         $crate::bindings::Property {
122             // use associated function syntax for type checking
123             name: ::std::ffi::CStr::as_ptr($name),
124             info: $prop,
125             offset: $crate::offset_of!($state, $field) as isize,
126             set_default: false,
127             ..$crate::zeroable::Zeroable::ZERO
128         }
129     };
130 }
131 
132 #[macro_export]
133 macro_rules! declare_properties {
134     ($ident:ident, $($prop:expr),*$(,)*) => {
135         pub static $ident: [$crate::bindings::Property; {
136             let mut len = 1;
137             $({
138                 _ = stringify!($prop);
139                 len += 1;
140             })*
141             len
142         }] = [
143             $($prop),*,
144             $crate::zeroable::Zeroable::ZERO,
145         ];
146     };
147 }
148 
149 // workaround until we can use --generate-cstr in bindgen.
150 pub const TYPE_DEVICE: &CStr =
151     unsafe { CStr::from_bytes_with_nul_unchecked(bindings::TYPE_DEVICE) };
152 pub const TYPE_SYS_BUS_DEVICE: &CStr =
153     unsafe { CStr::from_bytes_with_nul_unchecked(bindings::TYPE_SYS_BUS_DEVICE) };
154