diff options
| author | Marc-André Lureau <marcandre.lureau@redhat.com> | 2025-09-08 12:49:54 +0200 |
|---|---|---|
| committer | Paolo Bonzini <pbonzini@redhat.com> | 2025-09-17 19:00:57 +0200 |
| commit | fef932ef09c82c3831ff3336d1b2d566cd6ccae4 (patch) | |
| tree | a1fcffd6045a1370769858bdf891f6f469998f9c /rust/qemu-api/src | |
| parent | fcf4c00b4d73185db9239b1a6f03289f6211e142 (diff) | |
| download | focaccia-qemu-fef932ef09c82c3831ff3336d1b2d566cd6ccae4.tar.gz focaccia-qemu-fef932ef09c82c3831ff3336d1b2d566cd6ccae4.zip | |
rust: split "chardev" crate
Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com> Link: https://lore.kernel.org/r/20250827104147.717203-14-marcandre.lureau@redhat.com Reviewed-by: Zhao Liu <zhao1.liu@intel.com> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
Diffstat (limited to 'rust/qemu-api/src')
| -rw-r--r-- | rust/qemu-api/src/bindings.rs | 9 | ||||
| -rw-r--r-- | rust/qemu-api/src/chardev.rs | 261 | ||||
| -rw-r--r-- | rust/qemu-api/src/lib.rs | 1 | ||||
| -rw-r--r-- | rust/qemu-api/src/qdev.rs | 6 |
4 files changed, 4 insertions, 273 deletions
diff --git a/rust/qemu-api/src/bindings.rs b/rust/qemu-api/src/bindings.rs index 525f136ae2..526bcf8e31 100644 --- a/rust/qemu-api/src/bindings.rs +++ b/rust/qemu-api/src/bindings.rs @@ -20,6 +20,7 @@ //! `bindgen`-generated declarations. +use chardev::bindings::Chardev; use common::Zeroable; use migration::bindings::VMStateDescription; use qom::bindings::ObjectClass; @@ -31,13 +32,6 @@ include!("bindings.inc.rs"); #[cfg(not(MESON))] include!(concat!(env!("OUT_DIR"), "/bindings.inc.rs")); -// SAFETY: these are implemented in C; the bindings need to assert that the -// BQL is taken, either directly or via `BqlCell` and `BqlRefCell`. -// When bindings for character devices are introduced, this can be -// moved to the Opaque<> wrapper in src/chardev.rs. -unsafe impl Send for CharBackend {} -unsafe impl Sync for CharBackend {} - // SAFETY: this is a pure data struct unsafe impl Send for CoalescedMemoryRange {} unsafe impl Sync for CoalescedMemoryRange {} @@ -59,4 +53,3 @@ unsafe impl Zeroable for crate::bindings::MemoryRegionOps__bindgen_ty_1 {} unsafe impl Zeroable for crate::bindings::MemoryRegionOps__bindgen_ty_2 {} unsafe impl Zeroable for crate::bindings::MemoryRegionOps {} unsafe impl Zeroable for crate::bindings::MemTxAttrs {} -unsafe impl Zeroable for crate::bindings::CharBackend {} diff --git a/rust/qemu-api/src/chardev.rs b/rust/qemu-api/src/chardev.rs deleted file mode 100644 index 072d806e4a..0000000000 --- a/rust/qemu-api/src/chardev.rs +++ /dev/null @@ -1,261 +0,0 @@ -// Copyright 2024 Red Hat, Inc. -// Author(s): Paolo Bonzini <pbonzini@redhat.com> -// SPDX-License-Identifier: GPL-2.0-or-later - -//! Bindings for character devices -//! -//! Character devices in QEMU can run under the big QEMU lock or in a separate -//! `GMainContext`. Here we only support the former, because the bindings -//! enforce that the BQL is taken whenever the functions in [`CharBackend`] are -//! called. - -use std::{ - ffi::{c_int, c_void, CStr}, - fmt::{self, Debug}, - io::{self, ErrorKind, Write}, - marker::PhantomPinned, - ptr::addr_of_mut, - slice, -}; - -use bql::{BqlRefCell, BqlRefMut}; -use common::{callbacks::FnCall, errno, Opaque}; -use qom::prelude::*; - -use crate::bindings; - -/// A safe wrapper around [`bindings::Chardev`]. -#[repr(transparent)] -#[derive(qemu_api_macros::Wrapper)] -pub struct Chardev(Opaque<bindings::Chardev>); - -pub type ChardevClass = bindings::ChardevClass; -pub type Event = bindings::QEMUChrEvent; - -/// A safe wrapper around [`bindings::CharBackend`], denoting the character -/// back-end that is used for example by a device. Compared to the -/// underlying C struct it adds BQL protection, and is marked as pinned -/// because the QOM object ([`bindings::Chardev`]) contains a pointer to -/// the `CharBackend`. -pub struct CharBackend { - inner: BqlRefCell<bindings::CharBackend>, - _pin: PhantomPinned, -} - -pub struct CharBackendMut<'a>(BqlRefMut<'a, bindings::CharBackend>); - -impl Write for CharBackendMut<'_> { - fn flush(&mut self) -> io::Result<()> { - Ok(()) - } - - fn write(&mut self, buf: &[u8]) -> io::Result<usize> { - let chr: &mut bindings::CharBackend = &mut self.0; - - let len = buf.len().try_into().unwrap(); - let r = unsafe { bindings::qemu_chr_fe_write(addr_of_mut!(*chr), buf.as_ptr(), len) }; - errno::into_io_result(r).map(|cnt| cnt as usize) - } - - fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { - let chr: &mut bindings::CharBackend = &mut self.0; - - let len = buf.len().try_into().unwrap(); - let r = unsafe { bindings::qemu_chr_fe_write_all(addr_of_mut!(*chr), buf.as_ptr(), len) }; - errno::into_io_result(r).and_then(|cnt| { - if cnt as usize == buf.len() { - Ok(()) - } else { - Err(ErrorKind::WriteZero.into()) - } - }) - } -} - -impl Debug for CharBackend { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - // SAFETY: accessed just to print the values - let chr = self.inner.as_ptr(); - Debug::fmt(unsafe { &*chr }, f) - } -} - -// FIXME: use something like PinnedDrop from the pinned_init crate -impl Drop for CharBackend { - fn drop(&mut self) { - self.disable_handlers(); - } -} - -impl CharBackend { - /// Enable the front-end's character device handlers, if there is an - /// associated `Chardev`. - pub fn enable_handlers< - 'chardev, - 'owner: 'chardev, - T, - CanReceiveFn: for<'a> FnCall<(&'a T,), u32>, - ReceiveFn: for<'a, 'b> FnCall<(&'a T, &'b [u8])>, - EventFn: for<'a> FnCall<(&'a T, Event)>, - >( - // When "self" is dropped, the handlers are automatically disabled. - // However, this is not necessarily true if the owner is dropped. - // So require the owner to outlive the character device. - &'chardev self, - owner: &'owner T, - _can_receive: CanReceiveFn, - _receive: ReceiveFn, - _event: EventFn, - ) { - unsafe extern "C" fn rust_can_receive_cb<T, F: for<'a> FnCall<(&'a T,), u32>>( - opaque: *mut c_void, - ) -> c_int { - // SAFETY: the values are safe according to the contract of - // enable_handlers() and qemu_chr_fe_set_handlers() - let owner: &T = unsafe { &*(opaque.cast::<T>()) }; - let r = F::call((owner,)); - r.try_into().unwrap() - } - - unsafe extern "C" fn rust_receive_cb<T, F: for<'a, 'b> FnCall<(&'a T, &'b [u8])>>( - opaque: *mut c_void, - buf: *const u8, - size: c_int, - ) { - // SAFETY: the values are safe according to the contract of - // enable_handlers() and qemu_chr_fe_set_handlers() - let owner: &T = unsafe { &*(opaque.cast::<T>()) }; - let buf = unsafe { slice::from_raw_parts(buf, size.try_into().unwrap()) }; - F::call((owner, buf)) - } - - unsafe extern "C" fn rust_event_cb<T, F: for<'a> FnCall<(&'a T, Event)>>( - opaque: *mut c_void, - event: Event, - ) { - // SAFETY: the values are safe according to the contract of - // enable_handlers() and qemu_chr_fe_set_handlers() - let owner: &T = unsafe { &*(opaque.cast::<T>()) }; - F::call((owner, event)) - } - - const { assert!(CanReceiveFn::IS_SOME) }; - let receive_cb: Option<unsafe extern "C" fn(*mut c_void, *const u8, c_int)> = - if ReceiveFn::is_some() { - Some(rust_receive_cb::<T, ReceiveFn>) - } else { - None - }; - let event_cb: Option<unsafe extern "C" fn(*mut c_void, Event)> = if EventFn::is_some() { - Some(rust_event_cb::<T, EventFn>) - } else { - None - }; - - let mut chr = self.inner.borrow_mut(); - // SAFETY: the borrow promises that the BQL is taken - unsafe { - bindings::qemu_chr_fe_set_handlers( - addr_of_mut!(*chr), - Some(rust_can_receive_cb::<T, CanReceiveFn>), - receive_cb, - event_cb, - None, - (owner as *const T).cast_mut().cast::<c_void>(), - core::ptr::null_mut(), - true, - ); - } - } - - /// Disable the front-end's character device handlers. - pub fn disable_handlers(&self) { - let mut chr = self.inner.borrow_mut(); - // SAFETY: the borrow promises that the BQL is taken - unsafe { - bindings::qemu_chr_fe_set_handlers( - addr_of_mut!(*chr), - None, - None, - None, - None, - core::ptr::null_mut(), - core::ptr::null_mut(), - true, - ); - } - } - - /// Notify that the frontend is ready to receive data. - pub fn accept_input(&self) { - let mut chr = self.inner.borrow_mut(); - // SAFETY: the borrow promises that the BQL is taken - unsafe { bindings::qemu_chr_fe_accept_input(addr_of_mut!(*chr)) } - } - - /// Temporarily borrow the character device, allowing it to be used - /// as an implementor of `Write`. Note that it is not valid to drop - /// the big QEMU lock while the character device is borrowed, as - /// that might cause C code to write to the character device. - pub fn borrow_mut(&self) -> impl Write + '_ { - CharBackendMut(self.inner.borrow_mut()) - } - - /// Send a continuous stream of zero bits on the line if `enabled` is - /// true, or a short stream if `enabled` is false. - pub fn send_break(&self, long: bool) -> io::Result<()> { - let mut chr = self.inner.borrow_mut(); - let mut duration: c_int = long.into(); - // SAFETY: the borrow promises that the BQL is taken - let r = unsafe { - bindings::qemu_chr_fe_ioctl( - addr_of_mut!(*chr), - bindings::CHR_IOCTL_SERIAL_SET_BREAK as i32, - addr_of_mut!(duration).cast::<c_void>(), - ) - }; - - errno::into_io_result(r).map(|_| ()) - } - - /// Write data to a character backend from the front end. This function - /// will send data from the front end to the back end. Unlike - /// `write`, this function will block if the back end cannot - /// consume all of the data attempted to be written. - /// - /// Returns the number of bytes consumed (0 if no associated Chardev) or an - /// error. - pub fn write(&self, buf: &[u8]) -> io::Result<usize> { - let len = buf.len().try_into().unwrap(); - // SAFETY: qemu_chr_fe_write is thread-safe - let r = unsafe { bindings::qemu_chr_fe_write(self.inner.as_ptr(), buf.as_ptr(), len) }; - errno::into_io_result(r).map(|cnt| cnt as usize) - } - - /// Write data to a character backend from the front end. This function - /// will send data from the front end to the back end. Unlike - /// `write`, this function will block if the back end cannot - /// consume all of the data attempted to be written. - /// - /// Returns the number of bytes consumed (0 if no associated Chardev) or an - /// error. - pub fn write_all(&self, buf: &[u8]) -> io::Result<()> { - let len = buf.len().try_into().unwrap(); - // SAFETY: qemu_chr_fe_write_all is thread-safe - let r = unsafe { bindings::qemu_chr_fe_write_all(self.inner.as_ptr(), buf.as_ptr(), len) }; - errno::into_io_result(r).and_then(|cnt| { - if cnt as usize == buf.len() { - Ok(()) - } else { - Err(ErrorKind::WriteZero.into()) - } - }) - } -} - -unsafe impl ObjectType for Chardev { - type Class = ChardevClass; - const TYPE_NAME: &'static CStr = - unsafe { CStr::from_bytes_with_nul_unchecked(bindings::TYPE_CHARDEV) }; -} -qom_isa!(Chardev: Object); diff --git a/rust/qemu-api/src/lib.rs b/rust/qemu-api/src/lib.rs index 0541050e66..d96096899d 100644 --- a/rust/qemu-api/src/lib.rs +++ b/rust/qemu-api/src/lib.rs @@ -13,7 +13,6 @@ pub mod bindings; #[rustfmt::skip] pub mod prelude; -pub mod chardev; pub mod irq; pub mod memory; pub mod qdev; diff --git a/rust/qemu-api/src/qdev.rs b/rust/qemu-api/src/qdev.rs index 3daf9dda2b..7efc796f50 100644 --- a/rust/qemu-api/src/qdev.rs +++ b/rust/qemu-api/src/qdev.rs @@ -10,6 +10,7 @@ use std::{ }; pub use bindings::{ClockEvent, DeviceClass, Property, ResetType}; +use chardev::Chardev; use common::{callbacks::FnCall, Opaque}; use migration::{impl_vmstate_c_struct, VMStateDescription}; use qom::{prelude::*, ObjectClass, ObjectImpl, Owned, ParentInit}; @@ -17,7 +18,6 @@ use util::{Error, Result}; use crate::{ bindings::{self, qdev_init_gpio_in, qdev_init_gpio_out, ResettableClass}, - chardev::Chardev, irq::InterruptSource, }; @@ -137,8 +137,8 @@ unsafe impl QDevProp for u64 { const VALUE: *const bindings::PropertyInfo = unsafe { &bindings::qdev_prop_uint64 }; } -/// Use [`bindings::qdev_prop_chr`] for [`crate::chardev::CharBackend`]. -unsafe impl QDevProp for crate::chardev::CharBackend { +/// Use [`bindings::qdev_prop_chr`] for [`chardev::CharBackend`]. +unsafe impl QDevProp for chardev::CharBackend { const VALUE: *const bindings::PropertyInfo = unsafe { &bindings::qdev_prop_chr }; } |