summary refs log tree commit diff stats
path: root/rust/qemu-api/src/chardev.rs
diff options
context:
space:
mode:
authorRichard Henderson <richard.henderson@linaro.org>2025-09-18 07:05:58 -0700
committerRichard Henderson <richard.henderson@linaro.org>2025-09-18 07:05:59 -0700
commitccafa85a97e38698b798115bba6c18c849846e25 (patch)
treea7d4941f050d4b621cffe2a71657a1bd39c35d4b /rust/qemu-api/src/chardev.rs
parentf0007b7f03e2d7fc33e71c3a582f2364c51a226b (diff)
parent00c0911c68e5bd664de1a261b74c390f4c0be83d (diff)
downloadfocaccia-qemu-ccafa85a97e38698b798115bba6c18c849846e25.tar.gz
focaccia-qemu-ccafa85a97e38698b798115bba6c18c849846e25.zip
Merge tag 'for-upstream' of https://gitlab.com/bonzini/qemu into staging
* cpu-exec: more cleanups to CPU loop exits
* python: bump bundled Meson to 1.9.0
* rust: require Rust 1.83.0
* rust: temporarily remove from Ubuntu CI
* rust: vmstate: convert to use builder pattern
* rust: split "qemu-api" crate
* rust: rename qemu_api_macros -> qemu_macros
* rust: re-export qemu macros from other crates
* x86: fix functional test failure for Xen emulation
* x86: cleanups

# -----BEGIN PGP SIGNATURE-----
#
# iQFIBAABCgAyFiEE8TM4V0tmI4mGbHaCv/vSX3jHroMFAmjK6ZsUHHBib256aW5p
# QHJlZGhhdC5jb20ACgkQv/vSX3jHroNBKwf/aadInCT4vASOfpxbwZgYfYgR2m2m
# BJE9oYKxZJ6MlEOU/1Wfywf9fg4leMSh3XxkDKkEIL19yS6emwin8n3SNYrdAFn3
# 6u4IIWO4NI1Ht3NKytrqFk9wtbH9pAs/gVHLlnmpMxIqtOtZLumPAKNz8rlantmK
# UVDYL3Y0L4pD9i5FK1ObMNpk5AsWNr8Tr64fmb+nTkHutld3sBrEMCLI0+EByGyN
# lQ16sLn9PGqHOr210zuQP7wP2T3NCI3YokFSPQrUUL8LZGxRdXoNF4hI4uZDKGdn
# UbtRu9EkM052qzfsFMrEw5JSbdxEfIjKlPoFKseMv+aWvNAuximAraD3Vg==
# =Lr+x
# -----END PGP SIGNATURE-----
# gpg: Signature made Wed 17 Sep 2025 10:02:19 AM PDT
# gpg:                using RSA key F13338574B662389866C7682BFFBD25F78C7AE83
# gpg:                issuer "pbonzini@redhat.com"
# gpg: Good signature from "Paolo Bonzini <bonzini@gnu.org>" [unknown]
# gpg:                 aka "Paolo Bonzini <pbonzini@redhat.com>" [unknown]
# gpg: WARNING: The key's User ID is not certified with a trusted signature!
# gpg:          There is no indication that the signature belongs to the owner.
# Primary key fingerprint: 46F5 9FBD 57D6 12E7 BFD4  E2F7 7E15 100C CD36 69B1
#      Subkey fingerprint: F133 3857 4B66 2389 866C  7682 BFFB D25F 78C7 AE83

* tag 'for-upstream' of https://gitlab.com/bonzini/qemu: (60 commits)
  accel/kvm: Set guest_memfd_offset to non-zero value only when guest_memfd is valid
  accel/kvm: Zero out mem explicitly in kvm_set_user_memory_region()
  accel/kvm: Switch to check KVM_CAP_GUEST_MEMFD and KVM_CAP_USER_MEMORY2 on VM
  i386/kvm: Drop KVM_CAP_X86_SMM check in kvm_arch_init()
  multiboot: Fix the split lock
  target/i386: Define enum X86ASIdx for x86's address spaces
  i386/cpu: Enable SMM cpu address space under KVM
  hpet: guard IRQ handling with BQL
  rust: do not inline do_init_io
  rust: meson: remove unnecessary complication in device crates
  docs: update rust.rst
  rust: re-export qemu macros from common/qom/hwcore
  rust: re-export qemu_macros internal helper in "bits"
  rust: repurpose qemu_api -> tests
  rust/pl011: drop dependency on qemu_api
  rust/hpet: drop now unneeded qemu_api dep
  rust: rename qemu_api_macros -> qemu_macros
  rust: split "hwcore" crate
  rust: split "system" crate
  rust: split "chardev" crate
  ...

Signed-off-by: Richard Henderson <richard.henderson@linaro.org>
Diffstat (limited to 'rust/qemu-api/src/chardev.rs')
-rw-r--r--rust/qemu-api/src/chardev.rs260
1 files changed, 0 insertions, 260 deletions
diff --git a/rust/qemu-api/src/chardev.rs b/rust/qemu-api/src/chardev.rs
deleted file mode 100644
index 6e0590d758..0000000000
--- a/rust/qemu-api/src/chardev.rs
+++ /dev/null
@@ -1,260 +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 crate::{
-    bindings,
-    callbacks::FnCall,
-    cell::{BqlRefMut, Opaque},
-    prelude::*,
-};
-
-/// 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,
-}
-
-impl Write for BqlRefMut<'_, bindings::CharBackend> {
-    fn flush(&mut self) -> io::Result<()> {
-        Ok(())
-    }
-
-    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
-        let chr: &mut bindings::CharBackend = self;
-
-        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 = self;
-
-        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))
-        }
-
-        let _: () = CanReceiveFn::ASSERT_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 + '_ {
-        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);