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::{
8 ffi::{c_int, c_void, CStr, CString},
9 ptr::NonNull,
10 };
11
12 pub use bindings::{ClockEvent, DeviceClass, Property, ResetType};
13
14 use crate::{
15 bindings::{self, qdev_init_gpio_in, qdev_init_gpio_out, ResettableClass},
16 callbacks::FnCall,
17 cell::{bql_locked, Opaque},
18 chardev::Chardev,
19 error::{Error, Result},
20 irq::InterruptSource,
21 prelude::*,
22 qom::{ObjectClass, ObjectImpl, Owned},
23 vmstate::VMStateDescription,
24 };
25
26 /// A safe wrapper around [`bindings::Clock`].
27 #[repr(transparent)]
28 #[derive(Debug, qemu_api_macros::Wrapper)]
29 pub struct Clock(Opaque<bindings::Clock>);
30
31 unsafe impl Send for Clock {}
32 unsafe impl Sync for Clock {}
33
34 /// A safe wrapper around [`bindings::DeviceState`].
35 #[repr(transparent)]
36 #[derive(Debug, qemu_api_macros::Wrapper)]
37 pub struct DeviceState(Opaque<bindings::DeviceState>);
38
39 unsafe impl Send for DeviceState {}
40 unsafe impl Sync for DeviceState {}
41
42 /// Trait providing the contents of the `ResettablePhases` struct,
43 /// which is part of the QOM `Resettable` interface.
44 pub trait ResettablePhasesImpl {
45 /// If not None, this is called when the object enters reset. It
46 /// can reset local state of the object, but it must not do anything that
47 /// has a side-effect on other objects, such as raising or lowering an
48 /// [`InterruptSource`], or reading or writing guest memory. It takes the
49 /// reset's type as argument.
50 const ENTER: Option<fn(&Self, ResetType)> = None;
51
52 /// If not None, this is called when the object for entry into reset, once
53 /// every object in the system which is being reset has had its
54 /// `ResettablePhasesImpl::ENTER` method called. At this point devices
55 /// can do actions that affect other objects.
56 ///
57 /// If in doubt, implement this method.
58 const HOLD: Option<fn(&Self, ResetType)> = None;
59
60 /// If not None, this phase is called when the object leaves the reset
61 /// state. Actions affecting other objects are permitted.
62 const EXIT: Option<fn(&Self, ResetType)> = None;
63 }
64
65 /// # Safety
66 ///
67 /// We expect the FFI user of this function to pass a valid pointer that
68 /// can be downcasted to type `T`. We also expect the device is
69 /// readable/writeable from one thread at any time.
rust_resettable_enter_fn<T: ResettablePhasesImpl>( obj: *mut bindings::Object, typ: ResetType, )70 unsafe extern "C" fn rust_resettable_enter_fn<T: ResettablePhasesImpl>(
71 obj: *mut bindings::Object,
72 typ: ResetType,
73 ) {
74 let state = NonNull::new(obj).unwrap().cast::<T>();
75 T::ENTER.unwrap()(unsafe { state.as_ref() }, typ);
76 }
77
78 /// # Safety
79 ///
80 /// We expect the FFI user of this function to pass a valid pointer that
81 /// can be downcasted to type `T`. We also expect the device is
82 /// readable/writeable from one thread at any time.
rust_resettable_hold_fn<T: ResettablePhasesImpl>( obj: *mut bindings::Object, typ: ResetType, )83 unsafe extern "C" fn rust_resettable_hold_fn<T: ResettablePhasesImpl>(
84 obj: *mut bindings::Object,
85 typ: ResetType,
86 ) {
87 let state = NonNull::new(obj).unwrap().cast::<T>();
88 T::HOLD.unwrap()(unsafe { state.as_ref() }, typ);
89 }
90
91 /// # Safety
92 ///
93 /// We expect the FFI user of this function to pass a valid pointer that
94 /// can be downcasted to type `T`. We also expect the device is
95 /// readable/writeable from one thread at any time.
rust_resettable_exit_fn<T: ResettablePhasesImpl>( obj: *mut bindings::Object, typ: ResetType, )96 unsafe extern "C" fn rust_resettable_exit_fn<T: ResettablePhasesImpl>(
97 obj: *mut bindings::Object,
98 typ: ResetType,
99 ) {
100 let state = NonNull::new(obj).unwrap().cast::<T>();
101 T::EXIT.unwrap()(unsafe { state.as_ref() }, typ);
102 }
103
104 /// Trait providing the contents of [`DeviceClass`].
105 pub trait DeviceImpl: ObjectImpl + ResettablePhasesImpl + IsA<DeviceState> {
106 /// _Realization_ is the second stage of device creation. It contains
107 /// all operations that depend on device properties and can fail (note:
108 /// this is not yet supported for Rust devices).
109 ///
110 /// If not `None`, the parent class's `realize` method is overridden
111 /// with the function pointed to by `REALIZE`.
112 const REALIZE: Option<fn(&Self) -> Result<()>> = None;
113
114 /// An array providing the properties that the user can set on the
115 /// device. Not a `const` because referencing statics in constants
116 /// is unstable until Rust 1.83.0.
properties() -> &'static [Property]117 fn properties() -> &'static [Property] {
118 &[]
119 }
120
121 /// A `VMStateDescription` providing the migration format for the device
122 /// Not a `const` because referencing statics in constants is unstable
123 /// until Rust 1.83.0.
vmsd() -> Option<&'static VMStateDescription>124 fn vmsd() -> Option<&'static VMStateDescription> {
125 None
126 }
127 }
128
129 /// # Safety
130 ///
131 /// This function is only called through the QOM machinery and
132 /// used by `DeviceClass::class_init`.
133 /// We expect the FFI user of this function to pass a valid pointer that
134 /// can be downcasted to type `T`. We also expect the device is
135 /// readable/writeable from one thread at any time.
rust_realize_fn<T: DeviceImpl>( dev: *mut bindings::DeviceState, errp: *mut *mut bindings::Error, )136 unsafe extern "C" fn rust_realize_fn<T: DeviceImpl>(
137 dev: *mut bindings::DeviceState,
138 errp: *mut *mut bindings::Error,
139 ) {
140 let state = NonNull::new(dev).unwrap().cast::<T>();
141 let result = T::REALIZE.unwrap()(unsafe { state.as_ref() });
142 unsafe {
143 Error::ok_or_propagate(result, errp);
144 }
145 }
146
147 unsafe impl InterfaceType for ResettableClass {
148 const TYPE_NAME: &'static CStr =
149 unsafe { CStr::from_bytes_with_nul_unchecked(bindings::TYPE_RESETTABLE_INTERFACE) };
150 }
151
152 impl ResettableClass {
153 /// Fill in the virtual methods of `ResettableClass` based on the
154 /// definitions in the `ResettablePhasesImpl` trait.
class_init<T: ResettablePhasesImpl>(&mut self)155 pub fn class_init<T: ResettablePhasesImpl>(&mut self) {
156 if <T as ResettablePhasesImpl>::ENTER.is_some() {
157 self.phases.enter = Some(rust_resettable_enter_fn::<T>);
158 }
159 if <T as ResettablePhasesImpl>::HOLD.is_some() {
160 self.phases.hold = Some(rust_resettable_hold_fn::<T>);
161 }
162 if <T as ResettablePhasesImpl>::EXIT.is_some() {
163 self.phases.exit = Some(rust_resettable_exit_fn::<T>);
164 }
165 }
166 }
167
168 impl DeviceClass {
169 /// Fill in the virtual methods of `DeviceClass` based on the definitions in
170 /// the `DeviceImpl` trait.
class_init<T: DeviceImpl>(&mut self)171 pub fn class_init<T: DeviceImpl>(&mut self) {
172 if <T as DeviceImpl>::REALIZE.is_some() {
173 self.realize = Some(rust_realize_fn::<T>);
174 }
175 if let Some(vmsd) = <T as DeviceImpl>::vmsd() {
176 self.vmsd = vmsd;
177 }
178 let prop = <T as DeviceImpl>::properties();
179 if !prop.is_empty() {
180 unsafe {
181 bindings::device_class_set_props_n(self, prop.as_ptr(), prop.len());
182 }
183 }
184
185 ResettableClass::cast::<DeviceState>(self).class_init::<T>();
186 self.parent_class.class_init::<T>();
187 }
188 }
189
190 #[macro_export]
191 macro_rules! define_property {
192 ($name:expr, $state:ty, $field:ident, $prop:expr, $type:ty, bit = $bitnr:expr, default = $defval:expr$(,)*) => {
193 $crate::bindings::Property {
194 // use associated function syntax for type checking
195 name: ::std::ffi::CStr::as_ptr($name),
196 info: $prop,
197 offset: ::std::mem::offset_of!($state, $field) as isize,
198 bitnr: $bitnr,
199 set_default: true,
200 defval: $crate::bindings::Property__bindgen_ty_1 { u: $defval as u64 },
201 ..$crate::zeroable::Zeroable::ZERO
202 }
203 };
204 ($name:expr, $state:ty, $field:ident, $prop:expr, $type:ty, default = $defval:expr$(,)*) => {
205 $crate::bindings::Property {
206 // use associated function syntax for type checking
207 name: ::std::ffi::CStr::as_ptr($name),
208 info: $prop,
209 offset: ::std::mem::offset_of!($state, $field) as isize,
210 set_default: true,
211 defval: $crate::bindings::Property__bindgen_ty_1 { u: $defval as u64 },
212 ..$crate::zeroable::Zeroable::ZERO
213 }
214 };
215 ($name:expr, $state:ty, $field:ident, $prop:expr, $type:ty$(,)*) => {
216 $crate::bindings::Property {
217 // use associated function syntax for type checking
218 name: ::std::ffi::CStr::as_ptr($name),
219 info: $prop,
220 offset: ::std::mem::offset_of!($state, $field) as isize,
221 set_default: false,
222 ..$crate::zeroable::Zeroable::ZERO
223 }
224 };
225 }
226
227 #[macro_export]
228 macro_rules! declare_properties {
229 ($ident:ident, $($prop:expr),*$(,)*) => {
230 pub static $ident: [$crate::bindings::Property; {
231 let mut len = 0;
232 $({
233 _ = stringify!($prop);
234 len += 1;
235 })*
236 len
237 }] = [
238 $($prop),*,
239 ];
240 };
241 }
242
243 unsafe impl ObjectType for DeviceState {
244 type Class = DeviceClass;
245 const TYPE_NAME: &'static CStr =
246 unsafe { CStr::from_bytes_with_nul_unchecked(bindings::TYPE_DEVICE) };
247 }
248 qom_isa!(DeviceState: Object);
249
250 /// Trait for methods exposed by the [`DeviceState`] class. The methods can be
251 /// called on all objects that have the trait `IsA<DeviceState>`.
252 ///
253 /// The trait should only be used through the blanket implementation,
254 /// which guarantees safety via `IsA`.
255 pub trait DeviceMethods: ObjectDeref
256 where
257 Self::Target: IsA<DeviceState>,
258 {
259 /// Add an input clock named `name`. Invoke the callback with
260 /// `self` as the first parameter for the events that are requested.
261 ///
262 /// The resulting clock is added as a child of `self`, but it also
263 /// stays alive until after `Drop::drop` is called because C code
264 /// keeps an extra reference to it until `device_finalize()` calls
265 /// `qdev_finalize_clocklist()`. Therefore (unlike most cases in
266 /// which Rust code has a reference to a child object) it would be
267 /// possible for this function to return a `&Clock` too.
268 #[inline]
init_clock_in<F: for<'a> FnCall<(&'a Self::Target, ClockEvent)>>( &self, name: &str, _cb: &F, events: ClockEvent, ) -> Owned<Clock>269 fn init_clock_in<F: for<'a> FnCall<(&'a Self::Target, ClockEvent)>>(
270 &self,
271 name: &str,
272 _cb: &F,
273 events: ClockEvent,
274 ) -> Owned<Clock> {
275 fn do_init_clock_in(
276 dev: &DeviceState,
277 name: &str,
278 cb: Option<unsafe extern "C" fn(*mut c_void, ClockEvent)>,
279 events: ClockEvent,
280 ) -> Owned<Clock> {
281 assert!(bql_locked());
282
283 // SAFETY: the clock is heap allocated, but qdev_init_clock_in()
284 // does not gift the reference to its caller; so use Owned::from to
285 // add one. The callback is disabled automatically when the clock
286 // is unparented, which happens before the device is finalized.
287 unsafe {
288 let cstr = CString::new(name).unwrap();
289 let clk = bindings::qdev_init_clock_in(
290 dev.as_mut_ptr(),
291 cstr.as_ptr(),
292 cb,
293 dev.as_void_ptr(),
294 events.0,
295 );
296
297 let clk: &Clock = Clock::from_raw(clk);
298 Owned::from(clk)
299 }
300 }
301
302 let cb: Option<unsafe extern "C" fn(*mut c_void, ClockEvent)> = if F::is_some() {
303 unsafe extern "C" fn rust_clock_cb<T, F: for<'a> FnCall<(&'a T, ClockEvent)>>(
304 opaque: *mut c_void,
305 event: ClockEvent,
306 ) {
307 // SAFETY: the opaque is "this", which is indeed a pointer to T
308 F::call((unsafe { &*(opaque.cast::<T>()) }, event))
309 }
310 Some(rust_clock_cb::<Self::Target, F>)
311 } else {
312 None
313 };
314
315 do_init_clock_in(self.upcast(), name, cb, events)
316 }
317
318 /// Add an output clock named `name`.
319 ///
320 /// The resulting clock is added as a child of `self`, but it also
321 /// stays alive until after `Drop::drop` is called because C code
322 /// keeps an extra reference to it until `device_finalize()` calls
323 /// `qdev_finalize_clocklist()`. Therefore (unlike most cases in
324 /// which Rust code has a reference to a child object) it would be
325 /// possible for this function to return a `&Clock` too.
326 #[inline]
init_clock_out(&self, name: &str) -> Owned<Clock>327 fn init_clock_out(&self, name: &str) -> Owned<Clock> {
328 unsafe {
329 let cstr = CString::new(name).unwrap();
330 let clk = bindings::qdev_init_clock_out(self.upcast().as_mut_ptr(), cstr.as_ptr());
331
332 let clk: &Clock = Clock::from_raw(clk);
333 Owned::from(clk)
334 }
335 }
336
prop_set_chr(&self, propname: &str, chr: &Owned<Chardev>)337 fn prop_set_chr(&self, propname: &str, chr: &Owned<Chardev>) {
338 assert!(bql_locked());
339 let c_propname = CString::new(propname).unwrap();
340 let chr: &Chardev = chr;
341 unsafe {
342 bindings::qdev_prop_set_chr(
343 self.upcast().as_mut_ptr(),
344 c_propname.as_ptr(),
345 chr.as_mut_ptr(),
346 );
347 }
348 }
349
init_gpio_in<F: for<'a> FnCall<(&'a Self::Target, u32, u32)>>( &self, num_lines: u32, _cb: F, )350 fn init_gpio_in<F: for<'a> FnCall<(&'a Self::Target, u32, u32)>>(
351 &self,
352 num_lines: u32,
353 _cb: F,
354 ) {
355 fn do_init_gpio_in(
356 dev: &DeviceState,
357 num_lines: u32,
358 gpio_in_cb: unsafe extern "C" fn(*mut c_void, c_int, c_int),
359 ) {
360 unsafe {
361 qdev_init_gpio_in(dev.as_mut_ptr(), Some(gpio_in_cb), num_lines as c_int);
362 }
363 }
364
365 let _: () = F::ASSERT_IS_SOME;
366 unsafe extern "C" fn rust_irq_handler<T, F: for<'a> FnCall<(&'a T, u32, u32)>>(
367 opaque: *mut c_void,
368 line: c_int,
369 level: c_int,
370 ) {
371 // SAFETY: the opaque was passed as a reference to `T`
372 F::call((unsafe { &*(opaque.cast::<T>()) }, line as u32, level as u32))
373 }
374
375 let gpio_in_cb: unsafe extern "C" fn(*mut c_void, c_int, c_int) =
376 rust_irq_handler::<Self::Target, F>;
377
378 do_init_gpio_in(self.upcast(), num_lines, gpio_in_cb);
379 }
380
init_gpio_out(&self, pins: &[InterruptSource])381 fn init_gpio_out(&self, pins: &[InterruptSource]) {
382 unsafe {
383 qdev_init_gpio_out(
384 self.upcast().as_mut_ptr(),
385 InterruptSource::slice_as_ptr(pins),
386 pins.len() as c_int,
387 );
388 }
389 }
390 }
391
392 impl<R: ObjectDeref> DeviceMethods for R where R::Target: IsA<DeviceState> {}
393
394 unsafe impl ObjectType for Clock {
395 type Class = ObjectClass;
396 const TYPE_NAME: &'static CStr =
397 unsafe { CStr::from_bytes_with_nul_unchecked(bindings::TYPE_CLOCK) };
398 }
399 qom_isa!(Clock: Object);
400