| 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::{addr_of, NonNull}, |
| 10 | }; |
| 11 | |
| 12 | use chardev::Chardev; |
| 13 | use common::{callbacks::FnCall, Opaque}; |
| 14 | use migration::{impl_vmstate_c_struct, VMStateDescription}; |
| 15 | use qom::{prelude::*, ObjectClass}; |
| 16 | use util::{Error, Result}; |
| 17 | |
| 18 | pub use crate::bindings::{ClockEvent, ResetType}; |
| 19 | use crate::{ |
| 20 | bindings::{self, qdev_init_gpio_in, qdev_init_gpio_out, DeviceClass, Property}, |
| 21 | irq::InterruptSource, |
| 22 | }; |
| 23 | |
| 24 | /// A safe wrapper around [`bindings::Clock`]. |
| 25 | #[repr(transparent)] |
| 26 | #[derive(Debug, common::Wrapper)] |
| 27 | pub struct Clock(Opaque<bindings::Clock>); |
| 28 | |
| 29 | unsafe impl Send for Clock {} |
| 30 | unsafe impl Sync for Clock {} |
| 31 | |
| 32 | /// A safe wrapper around [`bindings::DeviceState`]. |
| 33 | #[repr(transparent)] |
| 34 | #[derive(Debug, common::Wrapper)] |
| 35 | pub struct DeviceState(Opaque<bindings::DeviceState>); |
| 36 | |
| 37 | unsafe impl Send for DeviceState {} |
| 38 | unsafe impl Sync for DeviceState {} |
| 39 | |
| 40 | /// Trait providing the contents of the `ResettablePhases` struct, |
| 41 | /// which is part of the QOM `Resettable` interface. |
| 42 | pub trait ResettablePhasesImpl { |
| 43 | /// If not None, this is called when the object enters reset. It |
| 44 | /// can reset local state of the object, but it must not do anything that |
| 45 | /// has a side-effect on other objects, such as raising or lowering an |
| 46 | /// [`InterruptSource`], or reading or writing guest memory. It takes the |
| 47 | /// reset's type as argument. |
| 48 | const ENTER: Option<fn(&Self, ResetType)> = None; |
| 49 | |
| 50 | /// If not None, this is called when the object for entry into reset, once |
| 51 | /// every object in the system which is being reset has had its |
| 52 | /// `ResettablePhasesImpl::ENTER` method called. At this point devices |
| 53 | /// can do actions that affect other objects. |
| 54 | /// |
| 55 | /// If in doubt, implement this method. |
| 56 | const HOLD: Option<fn(&Self, ResetType)> = None; |
| 57 | |
| 58 | /// If not None, this phase is called when the object leaves the reset |
| 59 | /// state. Actions affecting other objects are permitted. |
| 60 | const EXIT: Option<fn(&Self, ResetType)> = None; |
| 61 | } |
| 62 | |
| 63 | /// # Safety |
| 64 | /// |
| 65 | /// We expect the FFI user of this function to pass a valid pointer that |
| 66 | /// can be downcasted to type `T`. We also expect the device is |
| 67 | /// readable/writeable from one thread at any time. |
| 68 | unsafe extern "C" fn rust_resettable_enter_fn<T: ResettablePhasesImpl>( |
| 69 | obj: *mut qom::bindings::Object, |
| 70 | typ: ResetType, |
| 71 | ) { |
| 72 | let state = NonNull::new(obj).unwrap().cast::<T>(); |
| 73 | T::ENTER.unwrap()(unsafe { state.as_ref() }, typ); |
| 74 | } |
| 75 | |
| 76 | /// # Safety |
| 77 | /// |
| 78 | /// We expect the FFI user of this function to pass a valid pointer that |
| 79 | /// can be downcasted to type `T`. We also expect the device is |
| 80 | /// readable/writeable from one thread at any time. |
| 81 | unsafe extern "C" fn rust_resettable_hold_fn<T: ResettablePhasesImpl>( |
| 82 | obj: *mut qom::bindings::Object, |
| 83 | typ: ResetType, |
| 84 | ) { |
| 85 | let state = NonNull::new(obj).unwrap().cast::<T>(); |
| 86 | T::HOLD.unwrap()(unsafe { state.as_ref() }, typ); |
| 87 | } |
| 88 | |
| 89 | /// # Safety |
| 90 | /// |
| 91 | /// We expect the FFI user of this function to pass a valid pointer that |
| 92 | /// can be downcasted to type `T`. We also expect the device is |
| 93 | /// readable/writeable from one thread at any time. |
| 94 | unsafe extern "C" fn rust_resettable_exit_fn<T: ResettablePhasesImpl>( |
| 95 | obj: *mut qom::bindings::Object, |
| 96 | typ: ResetType, |
| 97 | ) { |
| 98 | let state = NonNull::new(obj).unwrap().cast::<T>(); |
| 99 | T::EXIT.unwrap()(unsafe { state.as_ref() }, typ); |
| 100 | } |
| 101 | |
| 102 | /// Helper trait to return pointer to a [`bindings::PropertyInfo`] for a type. |
| 103 | /// |
| 104 | /// This trait is used by [`qemu_macros::Device`] derive macro. |
| 105 | /// |
| 106 | /// Base types that already have `qdev_prop_*` globals in the QEMU API should |
| 107 | /// use those values as exported by the [`bindings`] module, instead of |
| 108 | /// redefining them. |
| 109 | /// |
| 110 | /// # Safety |
| 111 | /// |
| 112 | /// This trait is marked as `unsafe` because `BASE_INFO` and `BIT_INFO` must be |
| 113 | /// valid raw references to [`bindings::PropertyInfo`]. |
| 114 | /// |
| 115 | /// Note we could not use a regular reference: |
| 116 | /// |
| 117 | /// ```text |
| 118 | /// const VALUE: &bindings::PropertyInfo = ... |
| 119 | /// ``` |
| 120 | /// |
| 121 | /// because this results in the following compiler error: |
| 122 | /// |
| 123 | /// ```text |
| 124 | /// constructing invalid value: encountered reference to `extern` static in `const` |
| 125 | /// ``` |
| 126 | /// |
| 127 | /// This is because the compiler generally might dereference a normal reference |
| 128 | /// during const evaluation, but not in this case (if it did, it'd need to |
| 129 | /// dereference the raw pointer so using a `*const` would also fail to compile). |
| 130 | /// |
| 131 | /// It is the implementer's responsibility to provide a valid |
| 132 | /// [`bindings::PropertyInfo`] pointer for the trait implementation to be safe. |
| 133 | pub unsafe trait QDevProp { |
| 134 | const BASE_INFO: *const bindings::PropertyInfo; |
| 135 | #[doc(hidden)] // https://github.com/rust-lang/rust/issues/149635 |
| 136 | const BIT_INFO: *const bindings::PropertyInfo = { |
| 137 | panic!("invalid type for bit property"); |
| 138 | }; |
| 139 | } |
| 140 | |
| 141 | macro_rules! impl_qdev_prop { |
| 142 | ($type:ty,$info:ident$(, $bit_info:ident)?) => { |
| 143 | unsafe impl $crate::qdev::QDevProp for $type { |
| 144 | const BASE_INFO: *const $crate::bindings::PropertyInfo = |
| 145 | addr_of!($crate::bindings::$info); |
| 146 | $(const BIT_INFO: *const $crate::bindings::PropertyInfo = |
| 147 | addr_of!($crate::bindings::$bit_info);)? |
| 148 | } |
| 149 | }; |
| 150 | } |
| 151 | |
| 152 | impl_qdev_prop!(bool, qdev_prop_bool); |
| 153 | impl_qdev_prop!(u8, qdev_prop_uint8); |
| 154 | impl_qdev_prop!(u16, qdev_prop_uint16); |
| 155 | impl_qdev_prop!(u32, qdev_prop_uint32, qdev_prop_bit); |
| 156 | impl_qdev_prop!(u64, qdev_prop_uint64, qdev_prop_bit64); |
| 157 | impl_qdev_prop!(usize, qdev_prop_usize); |
| 158 | impl_qdev_prop!(i32, qdev_prop_int32); |
| 159 | impl_qdev_prop!(i64, qdev_prop_int64); |
| 160 | impl_qdev_prop!(chardev::CharFrontend, qdev_prop_chr); |
| 161 | |
| 162 | /// Trait to define device properties. |
| 163 | /// |
| 164 | /// # Safety |
| 165 | /// |
| 166 | /// Caller is responsible for the validity of properties array. |
| 167 | pub unsafe trait DevicePropertiesImpl { |
| 168 | /// An array providing the properties that the user can set on the |
| 169 | /// device. |
| 170 | const PROPERTIES: &'static [Property] = &[]; |
| 171 | } |
| 172 | |
| 173 | /// Trait providing the contents of [`DeviceClass`]. |
| 174 | pub trait DeviceImpl: |
| 175 | ObjectImpl + ResettablePhasesImpl + DevicePropertiesImpl + IsA<DeviceState> |
| 176 | { |
| 177 | /// _Realization_ is the second stage of device creation. It contains |
| 178 | /// all operations that depend on device properties and can fail (note: |
| 179 | /// this is not yet supported for Rust devices). |
| 180 | /// |
| 181 | /// If not `None`, the parent class's `realize` method is overridden |
| 182 | /// with the function pointed to by `REALIZE`. |
| 183 | const REALIZE: Option<fn(&Self) -> Result<()>> = None; |
| 184 | |
| 185 | /// A `VMStateDescription` providing the migration format for the device |
| 186 | /// Not a `const` because referencing statics in constants is unstable |
| 187 | /// until Rust 1.83.0. |
| 188 | const VMSTATE: Option<VMStateDescription<Self>> = None; |
| 189 | } |
| 190 | |
| 191 | /// # Safety |
| 192 | /// |
| 193 | /// This function is only called through the QOM machinery and |
| 194 | /// used by `DeviceClass::class_init`. |
| 195 | /// We expect the FFI user of this function to pass a valid pointer that |
| 196 | /// can be downcasted to type `T`. We also expect the device is |
| 197 | /// readable/writeable from one thread at any time. |
| 198 | unsafe extern "C" fn rust_realize_fn<T: DeviceImpl>( |
| 199 | dev: *mut bindings::DeviceState, |
| 200 | errp: *mut *mut util::bindings::Error, |
| 201 | ) { |
| 202 | let state = NonNull::new(dev).unwrap().cast::<T>(); |
| 203 | let result = T::REALIZE.unwrap()(unsafe { state.as_ref() }); |
| 204 | unsafe { |
| 205 | Error::ok_or_propagate(result, errp); |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | #[repr(transparent)] |
| 210 | pub struct ResettableClass(bindings::ResettableClass); |
| 211 | |
| 212 | unsafe impl InterfaceType for ResettableClass { |
| 213 | const TYPE_NAME: &'static CStr = |
| 214 | unsafe { CStr::from_bytes_with_nul_unchecked(bindings::TYPE_RESETTABLE_INTERFACE) }; |
| 215 | } |
| 216 | |
| 217 | impl ResettableClass { |
| 218 | /// Fill in the virtual methods of `ResettableClass` based on the |
| 219 | /// definitions in the `ResettablePhasesImpl` trait. |
| 220 | fn class_init<T: ResettablePhasesImpl>(&mut self) { |
| 221 | if <T as ResettablePhasesImpl>::ENTER.is_some() { |
| 222 | self.0.phases.enter = Some(rust_resettable_enter_fn::<T>); |
| 223 | } |
| 224 | if <T as ResettablePhasesImpl>::HOLD.is_some() { |
| 225 | self.0.phases.hold = Some(rust_resettable_hold_fn::<T>); |
| 226 | } |
| 227 | if <T as ResettablePhasesImpl>::EXIT.is_some() { |
| 228 | self.0.phases.exit = Some(rust_resettable_exit_fn::<T>); |
| 229 | } |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | pub trait DeviceClassExt { |
| 234 | fn class_init<T: DeviceImpl>(&mut self); |
| 235 | } |
| 236 | |
| 237 | impl DeviceClassExt for DeviceClass { |
| 238 | fn class_init<T: DeviceImpl>(&mut self) { |
| 239 | if <T as DeviceImpl>::REALIZE.is_some() { |
| 240 | self.realize = Some(rust_realize_fn::<T>); |
| 241 | } |
| 242 | if let Some(ref vmsd) = <T as DeviceImpl>::VMSTATE { |
| 243 | self.vmsd = vmsd.as_ref(); |
| 244 | } |
| 245 | let prop = <T as DevicePropertiesImpl>::PROPERTIES; |
| 246 | if !prop.is_empty() { |
| 247 | unsafe { |
| 248 | bindings::device_class_set_props_n(self, prop.as_ptr(), prop.len()); |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | ResettableClass::cast::<DeviceState>(self).class_init::<T>(); |
| 253 | self.parent_class.class_init::<T>(); |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | unsafe impl ObjectType for DeviceState { |
| 258 | type Class = DeviceClass; |
| 259 | const TYPE_NAME: &'static CStr = |
| 260 | unsafe { CStr::from_bytes_with_nul_unchecked(bindings::TYPE_DEVICE) }; |
| 261 | } |
| 262 | |
| 263 | qom_isa!(DeviceState: Object); |
| 264 | |
| 265 | /// Initialization methods take a [`ParentInit`] and can be called as |
| 266 | /// associated functions. |
| 267 | impl DeviceState { |
| 268 | /// Add an input clock named `name`. Invoke the callback with |
| 269 | /// `self` as the first parameter for the events that are requested. |
| 270 | /// |
| 271 | /// The resulting clock is added as a child of `self`, but it also |
| 272 | /// stays alive until after `Drop::drop` is called because C code |
| 273 | /// keeps an extra reference to it until `device_finalize()` calls |
| 274 | /// `qdev_finalize_clocklist()`. Therefore (unlike most cases in |
| 275 | /// which Rust code has a reference to a child object) it would be |
| 276 | /// possible for this function to return a `&Clock` too. |
| 277 | #[inline] |
| 278 | pub fn init_clock_in<T: DeviceImpl, F: for<'a> FnCall<(&'a T, ClockEvent)>>( |
| 279 | this: &mut ParentInit<T>, |
| 280 | name: &str, |
| 281 | _cb: &F, |
| 282 | events: ClockEvent, |
| 283 | ) -> Owned<Clock> |
| 284 | where |
| 285 | T::ParentType: IsA<DeviceState>, |
| 286 | { |
| 287 | fn do_init_clock_in( |
| 288 | dev: &DeviceState, |
| 289 | name: &str, |
| 290 | cb: Option<unsafe extern "C" fn(*mut c_void, ClockEvent)>, |
| 291 | events: ClockEvent, |
| 292 | ) -> Owned<Clock> { |
| 293 | assert!(bql::is_locked()); |
| 294 | |
| 295 | // SAFETY: the clock is heap allocated, but qdev_init_clock_in() |
| 296 | // does not gift the reference to its caller; so use Owned::from to |
| 297 | // add one. The callback is disabled automatically when the clock |
| 298 | // is unparented, which happens before the device is finalized. |
| 299 | unsafe { |
| 300 | let cstr = CString::new(name).unwrap(); |
| 301 | let clk = bindings::qdev_init_clock_in( |
| 302 | dev.0.as_mut_ptr(), |
| 303 | cstr.as_ptr(), |
| 304 | cb, |
| 305 | dev.0.as_void_ptr(), |
| 306 | events.0, |
| 307 | ); |
| 308 | |
| 309 | let clk: &Clock = Clock::from_raw(clk); |
| 310 | Owned::from(clk) |
| 311 | } |
| 312 | } |
| 313 | |
| 314 | let cb: Option<unsafe extern "C" fn(*mut c_void, ClockEvent)> = if F::is_some() { |
| 315 | unsafe extern "C" fn rust_clock_cb<T, F: for<'a> FnCall<(&'a T, ClockEvent)>>( |
| 316 | opaque: *mut c_void, |
| 317 | event: ClockEvent, |
| 318 | ) { |
| 319 | // SAFETY: the opaque is "this", which is indeed a pointer to T |
| 320 | F::call((unsafe { &*(opaque.cast::<T>()) }, event)) |
| 321 | } |
| 322 | Some(rust_clock_cb::<T, F>) |
| 323 | } else { |
| 324 | None |
| 325 | }; |
| 326 | |
| 327 | do_init_clock_in(unsafe { this.upcast_mut() }, name, cb, events) |
| 328 | } |
| 329 | |
| 330 | /// Add an output clock named `name`. |
| 331 | /// |
| 332 | /// The resulting clock is added as a child of `self`, but it also |
| 333 | /// stays alive until after `Drop::drop` is called because C code |
| 334 | /// keeps an extra reference to it until `device_finalize()` calls |
| 335 | /// `qdev_finalize_clocklist()`. Therefore (unlike most cases in |
| 336 | /// which Rust code has a reference to a child object) it would be |
| 337 | /// possible for this function to return a `&Clock` too. |
| 338 | #[inline] |
| 339 | pub fn init_clock_out<T: DeviceImpl>(this: &mut ParentInit<T>, name: &str) -> Owned<Clock> |
| 340 | where |
| 341 | T::ParentType: IsA<DeviceState>, |
| 342 | { |
| 343 | unsafe { |
| 344 | let cstr = CString::new(name).unwrap(); |
| 345 | let dev: &mut DeviceState = this.upcast_mut(); |
| 346 | let clk = bindings::qdev_init_clock_out(dev.0.as_mut_ptr(), cstr.as_ptr()); |
| 347 | |
| 348 | let clk: &Clock = Clock::from_raw(clk); |
| 349 | Owned::from(clk) |
| 350 | } |
| 351 | } |
| 352 | } |
| 353 | |
| 354 | /// Trait for methods exposed by the [`DeviceState`] class. The methods can be |
| 355 | /// called on all objects that have the trait `IsA<DeviceState>`. |
| 356 | /// |
| 357 | /// The trait should only be used through the blanket implementation, |
| 358 | /// which guarantees safety via `IsA`. |
| 359 | pub trait DeviceMethods: ObjectDeref |
| 360 | where |
| 361 | Self::Target: IsA<DeviceState>, |
| 362 | { |
| 363 | fn prop_set_chr(&self, propname: &str, chr: &Owned<Chardev>) { |
| 364 | assert!(bql::is_locked()); |
| 365 | let c_propname = CString::new(propname).unwrap(); |
| 366 | let chr: &Chardev = chr; |
| 367 | unsafe { |
| 368 | bindings::qdev_prop_set_chr( |
| 369 | self.upcast().as_mut_ptr(), |
| 370 | c_propname.as_ptr(), |
| 371 | chr.as_mut_ptr(), |
| 372 | ); |
| 373 | } |
| 374 | } |
| 375 | |
| 376 | fn init_gpio_in<F: for<'a> FnCall<(&'a Self::Target, u32, u32)>>( |
| 377 | &self, |
| 378 | num_lines: u32, |
| 379 | _cb: F, |
| 380 | ) { |
| 381 | fn do_init_gpio_in( |
| 382 | dev: &DeviceState, |
| 383 | num_lines: u32, |
| 384 | gpio_in_cb: unsafe extern "C" fn(*mut c_void, c_int, c_int), |
| 385 | ) { |
| 386 | unsafe { |
| 387 | qdev_init_gpio_in(dev.as_mut_ptr(), Some(gpio_in_cb), num_lines as c_int); |
| 388 | } |
| 389 | } |
| 390 | |
| 391 | const { assert!(F::IS_SOME) }; |
| 392 | unsafe extern "C" fn rust_irq_handler<T, F: for<'a> FnCall<(&'a T, u32, u32)>>( |
| 393 | opaque: *mut c_void, |
| 394 | line: c_int, |
| 395 | level: c_int, |
| 396 | ) { |
| 397 | // SAFETY: the opaque was passed as a reference to `T` |
| 398 | F::call((unsafe { &*(opaque.cast::<T>()) }, line as u32, level as u32)) |
| 399 | } |
| 400 | |
| 401 | let gpio_in_cb: unsafe extern "C" fn(*mut c_void, c_int, c_int) = |
| 402 | rust_irq_handler::<Self::Target, F>; |
| 403 | |
| 404 | do_init_gpio_in(self.upcast(), num_lines, gpio_in_cb); |
| 405 | } |
| 406 | |
| 407 | fn init_gpio_out(&self, pins: &[InterruptSource]) { |
| 408 | unsafe { |
| 409 | qdev_init_gpio_out( |
| 410 | self.upcast().as_mut_ptr(), |
| 411 | InterruptSource::slice_as_ptr(pins), |
| 412 | pins.len() as c_int, |
| 413 | ); |
| 414 | } |
| 415 | } |
| 416 | } |
| 417 | |
| 418 | impl<R: ObjectDeref> DeviceMethods for R where R::Target: IsA<DeviceState> {} |
| 419 | |
| 420 | impl Clock { |
| 421 | pub const PERIOD_1SEC: u64 = bindings::CLOCK_PERIOD_1SEC; |
| 422 | |
| 423 | pub const fn period_from_ns(ns: u64) -> u64 { |
| 424 | ns * Self::PERIOD_1SEC / 1_000_000_000 |
| 425 | } |
| 426 | |
| 427 | pub const fn period_from_hz(hz: u64) -> u64 { |
| 428 | match Self::PERIOD_1SEC.checked_div(hz) { |
| 429 | Some(value) => value, |
| 430 | None => 0, |
| 431 | } |
| 432 | } |
| 433 | |
| 434 | pub const fn period_to_hz(period: u64) -> u64 { |
| 435 | match Self::PERIOD_1SEC.checked_div(period) { |
| 436 | Some(value) => value, |
| 437 | None => 0, |
| 438 | } |
| 439 | } |
| 440 | |
| 441 | pub const fn period(&self) -> u64 { |
| 442 | // SAFETY: Clock is returned by init_clock_in with zero value for period |
| 443 | unsafe { &*self.0.as_ptr() }.period |
| 444 | } |
| 445 | |
| 446 | pub const fn hz(&self) -> u64 { |
| 447 | Self::period_to_hz(self.period()) |
| 448 | } |
| 449 | } |
| 450 | |
| 451 | unsafe impl ObjectType for Clock { |
| 452 | type Class = ObjectClass; |
| 453 | const TYPE_NAME: &'static CStr = |
| 454 | unsafe { CStr::from_bytes_with_nul_unchecked(bindings::TYPE_CLOCK) }; |
| 455 | } |
| 456 | |
| 457 | qom_isa!(Clock: Object); |
| 458 | |
| 459 | impl_vmstate_c_struct!(Clock, bindings::vmstate_clock); |