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, ObjectImpl, Owned, ParentInit}; 16 use util::{Error, Result}; 17 18 pub use crate::bindings::{ClockEvent, DeviceClass, Property, ResetType}; 19 use crate::{ 20 bindings::{self, qdev_init_gpio_in, qdev_init_gpio_out, ResettableClass}, 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 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 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 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 const BIT_INFO: *const bindings::PropertyInfo = { 136 panic!("invalid type for bit property"); 137 }; 138 } 139 140 macro_rules! impl_qdev_prop { 141 ($type:ty,$info:ident$(, $bit_info:ident)?) => { 142 unsafe impl $crate::qdev::QDevProp for $type { 143 const BASE_INFO: *const $crate::bindings::PropertyInfo = 144 addr_of!($crate::bindings::$info); 145 $(const BIT_INFO: *const $crate::bindings::PropertyInfo = 146 addr_of!($crate::bindings::$bit_info);)? 147 } 148 }; 149 } 150 151 impl_qdev_prop!(bool, qdev_prop_bool); 152 impl_qdev_prop!(u8, qdev_prop_uint8); 153 impl_qdev_prop!(u16, qdev_prop_uint16); 154 impl_qdev_prop!(u32, qdev_prop_uint32, qdev_prop_bit); 155 impl_qdev_prop!(u64, qdev_prop_uint64, qdev_prop_bit64); 156 impl_qdev_prop!(usize, qdev_prop_usize); 157 impl_qdev_prop!(i32, qdev_prop_int32); 158 impl_qdev_prop!(i64, qdev_prop_int64); 159 impl_qdev_prop!(chardev::CharFrontend, qdev_prop_chr); 160 161 /// Trait to define device properties. 162 /// 163 /// # Safety 164 /// 165 /// Caller is responsible for the validity of properties array. 166 pub unsafe trait DevicePropertiesImpl { 167 /// An array providing the properties that the user can set on the 168 /// device. 169 const PROPERTIES: &'static [Property] = &[]; 170 } 171 172 /// Trait providing the contents of [`DeviceClass`]. 173 pub trait DeviceImpl: 174 ObjectImpl + ResettablePhasesImpl + DevicePropertiesImpl + IsA<DeviceState> 175 { 176 /// _Realization_ is the second stage of device creation. It contains 177 /// all operations that depend on device properties and can fail (note: 178 /// this is not yet supported for Rust devices). 179 /// 180 /// If not `None`, the parent class's `realize` method is overridden 181 /// with the function pointed to by `REALIZE`. 182 const REALIZE: Option<fn(&Self) -> Result<()>> = None; 183 184 /// A `VMStateDescription` providing the migration format for the device 185 /// Not a `const` because referencing statics in constants is unstable 186 /// until Rust 1.83.0. 187 const VMSTATE: Option<VMStateDescription<Self>> = None; 188 } 189 190 /// # Safety 191 /// 192 /// This function is only called through the QOM machinery and 193 /// used by `DeviceClass::class_init`. 194 /// We expect the FFI user of this function to pass a valid pointer that 195 /// can be downcasted to type `T`. We also expect the device is 196 /// readable/writeable from one thread at any time. 197 unsafe extern "C" fn rust_realize_fn<T: DeviceImpl>( 198 dev: *mut bindings::DeviceState, 199 errp: *mut *mut util::bindings::Error, 200 ) { 201 let state = NonNull::new(dev).unwrap().cast::<T>(); 202 let result = T::REALIZE.unwrap()(unsafe { state.as_ref() }); 203 unsafe { 204 Error::ok_or_propagate(result, errp); 205 } 206 } 207 208 unsafe impl InterfaceType for ResettableClass { 209 const TYPE_NAME: &'static CStr = 210 unsafe { CStr::from_bytes_with_nul_unchecked(bindings::TYPE_RESETTABLE_INTERFACE) }; 211 } 212 213 impl ResettableClass { 214 /// Fill in the virtual methods of `ResettableClass` based on the 215 /// definitions in the `ResettablePhasesImpl` trait. 216 pub fn class_init<T: ResettablePhasesImpl>(&mut self) { 217 if <T as ResettablePhasesImpl>::ENTER.is_some() { 218 self.phases.enter = Some(rust_resettable_enter_fn::<T>); 219 } 220 if <T as ResettablePhasesImpl>::HOLD.is_some() { 221 self.phases.hold = Some(rust_resettable_hold_fn::<T>); 222 } 223 if <T as ResettablePhasesImpl>::EXIT.is_some() { 224 self.phases.exit = Some(rust_resettable_exit_fn::<T>); 225 } 226 } 227 } 228 229 impl DeviceClass { 230 /// Fill in the virtual methods of `DeviceClass` based on the definitions in 231 /// the `DeviceImpl` trait. 232 pub fn class_init<T: DeviceImpl>(&mut self) { 233 if <T as DeviceImpl>::REALIZE.is_some() { 234 self.realize = Some(rust_realize_fn::<T>); 235 } 236 if let Some(ref vmsd) = <T as DeviceImpl>::VMSTATE { 237 self.vmsd = vmsd.as_ref(); 238 } 239 let prop = <T as DevicePropertiesImpl>::PROPERTIES; 240 if !prop.is_empty() { 241 unsafe { 242 bindings::device_class_set_props_n(self, prop.as_ptr(), prop.len()); 243 } 244 } 245 246 ResettableClass::cast::<DeviceState>(self).class_init::<T>(); 247 self.parent_class.class_init::<T>(); 248 } 249 } 250 251 unsafe impl ObjectType for DeviceState { 252 type Class = DeviceClass; 253 const TYPE_NAME: &'static CStr = 254 unsafe { CStr::from_bytes_with_nul_unchecked(bindings::TYPE_DEVICE) }; 255 } 256 257 qom_isa!(DeviceState: Object); 258 259 /// Initialization methods take a [`ParentInit`] and can be called as 260 /// associated functions. 261 impl DeviceState { 262 /// Add an input clock named `name`. Invoke the callback with 263 /// `self` as the first parameter for the events that are requested. 264 /// 265 /// The resulting clock is added as a child of `self`, but it also 266 /// stays alive until after `Drop::drop` is called because C code 267 /// keeps an extra reference to it until `device_finalize()` calls 268 /// `qdev_finalize_clocklist()`. Therefore (unlike most cases in 269 /// which Rust code has a reference to a child object) it would be 270 /// possible for this function to return a `&Clock` too. 271 #[inline] 272 pub fn init_clock_in<T: DeviceImpl, F: for<'a> FnCall<(&'a T, ClockEvent)>>( 273 this: &mut ParentInit<T>, 274 name: &str, 275 _cb: &F, 276 events: ClockEvent, 277 ) -> Owned<Clock> 278 where 279 T::ParentType: IsA<DeviceState>, 280 { 281 fn do_init_clock_in( 282 dev: &DeviceState, 283 name: &str, 284 cb: Option<unsafe extern "C" fn(*mut c_void, ClockEvent)>, 285 events: ClockEvent, 286 ) -> Owned<Clock> { 287 assert!(bql::is_locked()); 288 289 // SAFETY: the clock is heap allocated, but qdev_init_clock_in() 290 // does not gift the reference to its caller; so use Owned::from to 291 // add one. The callback is disabled automatically when the clock 292 // is unparented, which happens before the device is finalized. 293 unsafe { 294 let cstr = CString::new(name).unwrap(); 295 let clk = bindings::qdev_init_clock_in( 296 dev.0.as_mut_ptr(), 297 cstr.as_ptr(), 298 cb, 299 dev.0.as_void_ptr(), 300 events.0, 301 ); 302 303 let clk: &Clock = Clock::from_raw(clk); 304 Owned::from(clk) 305 } 306 } 307 308 let cb: Option<unsafe extern "C" fn(*mut c_void, ClockEvent)> = if F::is_some() { 309 unsafe extern "C" fn rust_clock_cb<T, F: for<'a> FnCall<(&'a T, ClockEvent)>>( 310 opaque: *mut c_void, 311 event: ClockEvent, 312 ) { 313 // SAFETY: the opaque is "this", which is indeed a pointer to T 314 F::call((unsafe { &*(opaque.cast::<T>()) }, event)) 315 } 316 Some(rust_clock_cb::<T, F>) 317 } else { 318 None 319 }; 320 321 do_init_clock_in(unsafe { this.upcast_mut() }, name, cb, events) 322 } 323 324 /// Add an output clock named `name`. 325 /// 326 /// The resulting clock is added as a child of `self`, but it also 327 /// stays alive until after `Drop::drop` is called because C code 328 /// keeps an extra reference to it until `device_finalize()` calls 329 /// `qdev_finalize_clocklist()`. Therefore (unlike most cases in 330 /// which Rust code has a reference to a child object) it would be 331 /// possible for this function to return a `&Clock` too. 332 #[inline] 333 pub fn init_clock_out<T: DeviceImpl>(this: &mut ParentInit<T>, name: &str) -> Owned<Clock> 334 where 335 T::ParentType: IsA<DeviceState>, 336 { 337 unsafe { 338 let cstr = CString::new(name).unwrap(); 339 let dev: &mut DeviceState = this.upcast_mut(); 340 let clk = bindings::qdev_init_clock_out(dev.0.as_mut_ptr(), cstr.as_ptr()); 341 342 let clk: &Clock = Clock::from_raw(clk); 343 Owned::from(clk) 344 } 345 } 346 } 347 348 /// Trait for methods exposed by the [`DeviceState`] class. The methods can be 349 /// called on all objects that have the trait `IsA<DeviceState>`. 350 /// 351 /// The trait should only be used through the blanket implementation, 352 /// which guarantees safety via `IsA`. 353 pub trait DeviceMethods: ObjectDeref 354 where 355 Self::Target: IsA<DeviceState>, 356 { 357 fn prop_set_chr(&self, propname: &str, chr: &Owned<Chardev>) { 358 assert!(bql::is_locked()); 359 let c_propname = CString::new(propname).unwrap(); 360 let chr: &Chardev = chr; 361 unsafe { 362 bindings::qdev_prop_set_chr( 363 self.upcast().as_mut_ptr(), 364 c_propname.as_ptr(), 365 chr.as_mut_ptr(), 366 ); 367 } 368 } 369 370 fn init_gpio_in<F: for<'a> FnCall<(&'a Self::Target, u32, u32)>>( 371 &self, 372 num_lines: u32, 373 _cb: F, 374 ) { 375 fn do_init_gpio_in( 376 dev: &DeviceState, 377 num_lines: u32, 378 gpio_in_cb: unsafe extern "C" fn(*mut c_void, c_int, c_int), 379 ) { 380 unsafe { 381 qdev_init_gpio_in(dev.as_mut_ptr(), Some(gpio_in_cb), num_lines as c_int); 382 } 383 } 384 385 const { assert!(F::IS_SOME) }; 386 unsafe extern "C" fn rust_irq_handler<T, F: for<'a> FnCall<(&'a T, u32, u32)>>( 387 opaque: *mut c_void, 388 line: c_int, 389 level: c_int, 390 ) { 391 // SAFETY: the opaque was passed as a reference to `T` 392 F::call((unsafe { &*(opaque.cast::<T>()) }, line as u32, level as u32)) 393 } 394 395 let gpio_in_cb: unsafe extern "C" fn(*mut c_void, c_int, c_int) = 396 rust_irq_handler::<Self::Target, F>; 397 398 do_init_gpio_in(self.upcast(), num_lines, gpio_in_cb); 399 } 400 401 fn init_gpio_out(&self, pins: &[InterruptSource]) { 402 unsafe { 403 qdev_init_gpio_out( 404 self.upcast().as_mut_ptr(), 405 InterruptSource::slice_as_ptr(pins), 406 pins.len() as c_int, 407 ); 408 } 409 } 410 } 411 412 impl<R: ObjectDeref> DeviceMethods for R where R::Target: IsA<DeviceState> {} 413 414 impl Clock { 415 pub const PERIOD_1SEC: u64 = bindings::CLOCK_PERIOD_1SEC; 416 417 pub const fn period_from_ns(ns: u64) -> u64 { 418 ns * Self::PERIOD_1SEC / 1_000_000_000 419 } 420 421 pub const fn period_from_hz(hz: u64) -> u64 { 422 if hz == 0 { 423 0 424 } else { 425 Self::PERIOD_1SEC / hz 426 } 427 } 428 429 pub const fn period_to_hz(period: u64) -> u64 { 430 if period == 0 { 431 0 432 } else { 433 Self::PERIOD_1SEC / period 434 } 435 } 436 437 pub const fn period(&self) -> u64 { 438 // SAFETY: Clock is returned by init_clock_in with zero value for period 439 unsafe { &*self.0.as_ptr() }.period 440 } 441 442 pub const fn hz(&self) -> u64 { 443 Self::period_to_hz(self.period()) 444 } 445 } 446 447 unsafe impl ObjectType for Clock { 448 type Class = ObjectClass; 449 const TYPE_NAME: &'static CStr = 450 unsafe { CStr::from_bytes_with_nul_unchecked(bindings::TYPE_CLOCK) }; 451 } 452 453 qom_isa!(Clock: Object); 454 455 impl_vmstate_c_struct!(Clock, bindings::vmstate_clock); 456