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, ParentInit},
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 /// Initialization methods take a [`ParentInit`] and can be called as
251 /// associated functions.
252 impl DeviceState {
253 /// Add an input clock named `name`. Invoke the callback with
254 /// `self` as the first parameter for the events that are requested.
255 ///
256 /// The resulting clock is added as a child of `self`, but it also
257 /// stays alive until after `Drop::drop` is called because C code
258 /// keeps an extra reference to it until `device_finalize()` calls
259 /// `qdev_finalize_clocklist()`. Therefore (unlike most cases in
260 /// which Rust code has a reference to a child object) it would be
261 /// possible for this function to return a `&Clock` too.
262 #[inline]
init_clock_in<T: DeviceImpl, F: for<'a> FnCall<(&'a T, ClockEvent)>>( this: &mut ParentInit<T>, name: &str, _cb: &F, events: ClockEvent, ) -> Owned<Clock> where T::ParentType: IsA<DeviceState>,263 pub fn init_clock_in<T: DeviceImpl, F: for<'a> FnCall<(&'a T, ClockEvent)>>(
264 this: &mut ParentInit<T>,
265 name: &str,
266 _cb: &F,
267 events: ClockEvent,
268 ) -> Owned<Clock>
269 where
270 T::ParentType: IsA<DeviceState>,
271 {
272 fn do_init_clock_in(
273 dev: &DeviceState,
274 name: &str,
275 cb: Option<unsafe extern "C" fn(*mut c_void, ClockEvent)>,
276 events: ClockEvent,
277 ) -> Owned<Clock> {
278 assert!(bql_locked());
279
280 // SAFETY: the clock is heap allocated, but qdev_init_clock_in()
281 // does not gift the reference to its caller; so use Owned::from to
282 // add one. The callback is disabled automatically when the clock
283 // is unparented, which happens before the device is finalized.
284 unsafe {
285 let cstr = CString::new(name).unwrap();
286 let clk = bindings::qdev_init_clock_in(
287 dev.0.as_mut_ptr(),
288 cstr.as_ptr(),
289 cb,
290 dev.0.as_void_ptr(),
291 events.0,
292 );
293
294 let clk: &Clock = Clock::from_raw(clk);
295 Owned::from(clk)
296 }
297 }
298
299 let cb: Option<unsafe extern "C" fn(*mut c_void, ClockEvent)> = if F::is_some() {
300 unsafe extern "C" fn rust_clock_cb<T, F: for<'a> FnCall<(&'a T, ClockEvent)>>(
301 opaque: *mut c_void,
302 event: ClockEvent,
303 ) {
304 // SAFETY: the opaque is "this", which is indeed a pointer to T
305 F::call((unsafe { &*(opaque.cast::<T>()) }, event))
306 }
307 Some(rust_clock_cb::<T, F>)
308 } else {
309 None
310 };
311
312 do_init_clock_in(unsafe { this.upcast_mut() }, name, cb, events)
313 }
314
315 /// Add an output clock named `name`.
316 ///
317 /// The resulting clock is added as a child of `self`, but it also
318 /// stays alive until after `Drop::drop` is called because C code
319 /// keeps an extra reference to it until `device_finalize()` calls
320 /// `qdev_finalize_clocklist()`. Therefore (unlike most cases in
321 /// which Rust code has a reference to a child object) it would be
322 /// possible for this function to return a `&Clock` too.
323 #[inline]
init_clock_out<T: DeviceImpl>(this: &mut ParentInit<T>, name: &str) -> Owned<Clock> where T::ParentType: IsA<DeviceState>,324 pub fn init_clock_out<T: DeviceImpl>(this: &mut ParentInit<T>, name: &str) -> Owned<Clock>
325 where
326 T::ParentType: IsA<DeviceState>,
327 {
328 unsafe {
329 let cstr = CString::new(name).unwrap();
330 let dev: &mut DeviceState = this.upcast_mut();
331 let clk = bindings::qdev_init_clock_out(dev.0.as_mut_ptr(), cstr.as_ptr());
332
333 let clk: &Clock = Clock::from_raw(clk);
334 Owned::from(clk)
335 }
336 }
337 }
338
339 /// Trait for methods exposed by the [`DeviceState`] class. The methods can be
340 /// called on all objects that have the trait `IsA<DeviceState>`.
341 ///
342 /// The trait should only be used through the blanket implementation,
343 /// which guarantees safety via `IsA`.
344 pub trait DeviceMethods: ObjectDeref
345 where
346 Self::Target: IsA<DeviceState>,
347 {
prop_set_chr(&self, propname: &str, chr: &Owned<Chardev>)348 fn prop_set_chr(&self, propname: &str, chr: &Owned<Chardev>) {
349 assert!(bql_locked());
350 let c_propname = CString::new(propname).unwrap();
351 let chr: &Chardev = chr;
352 unsafe {
353 bindings::qdev_prop_set_chr(
354 self.upcast().as_mut_ptr(),
355 c_propname.as_ptr(),
356 chr.as_mut_ptr(),
357 );
358 }
359 }
360
init_gpio_in<F: for<'a> FnCall<(&'a Self::Target, u32, u32)>>( &self, num_lines: u32, _cb: F, )361 fn init_gpio_in<F: for<'a> FnCall<(&'a Self::Target, u32, u32)>>(
362 &self,
363 num_lines: u32,
364 _cb: F,
365 ) {
366 fn do_init_gpio_in(
367 dev: &DeviceState,
368 num_lines: u32,
369 gpio_in_cb: unsafe extern "C" fn(*mut c_void, c_int, c_int),
370 ) {
371 unsafe {
372 qdev_init_gpio_in(dev.as_mut_ptr(), Some(gpio_in_cb), num_lines as c_int);
373 }
374 }
375
376 let _: () = F::ASSERT_IS_SOME;
377 unsafe extern "C" fn rust_irq_handler<T, F: for<'a> FnCall<(&'a T, u32, u32)>>(
378 opaque: *mut c_void,
379 line: c_int,
380 level: c_int,
381 ) {
382 // SAFETY: the opaque was passed as a reference to `T`
383 F::call((unsafe { &*(opaque.cast::<T>()) }, line as u32, level as u32))
384 }
385
386 let gpio_in_cb: unsafe extern "C" fn(*mut c_void, c_int, c_int) =
387 rust_irq_handler::<Self::Target, F>;
388
389 do_init_gpio_in(self.upcast(), num_lines, gpio_in_cb);
390 }
391
init_gpio_out(&self, pins: &[InterruptSource])392 fn init_gpio_out(&self, pins: &[InterruptSource]) {
393 unsafe {
394 qdev_init_gpio_out(
395 self.upcast().as_mut_ptr(),
396 InterruptSource::slice_as_ptr(pins),
397 pins.len() as c_int,
398 );
399 }
400 }
401 }
402
403 impl<R: ObjectDeref> DeviceMethods for R where R::Target: IsA<DeviceState> {}
404
405 unsafe impl ObjectType for Clock {
406 type Class = ObjectClass;
407 const TYPE_NAME: &'static CStr =
408 unsafe { CStr::from_bytes_with_nul_unchecked(bindings::TYPE_CLOCK) };
409 }
410 qom_isa!(Clock: Object);
411