From patchwork Thu Feb 27 14:22:08 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Paolo Bonzini X-Patchwork-Id: 13994670 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.lore.kernel.org (Postfix) with ESMTPS id 294A6C19F2E for ; Thu, 27 Feb 2025 14:29:52 +0000 (UTC) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1tnemy-0004th-4B; Thu, 27 Feb 2025 09:23:01 -0500 Received: from eggs.gnu.org ([2001:470:142:3::10]) by lists.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1tnemc-0003q1-IV for qemu-devel@nongnu.org; Thu, 27 Feb 2025 09:22:41 -0500 Received: from us-smtp-delivery-124.mimecast.com ([170.10.133.124]) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1tnemV-00044X-9k for qemu-devel@nongnu.org; Thu, 27 Feb 2025 09:22:35 -0500 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1740666148; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=6iIZDcF/PvBVJf1MmHUhmduGZrGIMJ+/spGBp0GIEiY=; b=UmCubofNsa4YUcIbnnA1KGo6aXG3NWzw+SeQb2/OHFmt4ycGZP0271cR3vEzB0YOGbrc/U S8v6J5SplJDCPLNBMWlSqjU1N9d4RHHb2mbIXLFibRvFXcv3uwtGBJqBm2lJbS2YXnm40h 4tZ+7qvtwVMksR9+Mot5FctGrd5mwh0= Received: from mail-ed1-f69.google.com (mail-ed1-f69.google.com [209.85.208.69]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-648-mLX19pR3Pby_Ian8HE4iWw-1; Thu, 27 Feb 2025 09:22:26 -0500 X-MC-Unique: mLX19pR3Pby_Ian8HE4iWw-1 X-Mimecast-MFC-AGG-ID: mLX19pR3Pby_Ian8HE4iWw_1740666146 Received: by mail-ed1-f69.google.com with SMTP id 4fb4d7f45d1cf-5d9fb24f87bso1245188a12.0 for ; Thu, 27 Feb 2025 06:22:26 -0800 (PST) X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1740666145; x=1741270945; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=6iIZDcF/PvBVJf1MmHUhmduGZrGIMJ+/spGBp0GIEiY=; b=oA87XuUZ7h//yYY1kVwdQsYvdRHZ0WJOysMcyTLJbnAbKhP6vY0gAHi2yPD+jdMCiy mUAbmHKuMu6HpjAHnCYKRy+m6BQ13wkTkiJY6hjrJukKj2d7vOzpjbGKZeo5T5VvdqBU kaEQUPqjygYM1xQsfO175BVEhBA1yvc4gFBv5Rd9xrN+/XFgTf/ct8ntKvK76QBGzsZV 7YNNEveOCq5Ko6jAKNWr1bedz3j9a8tAg3fCjiMaErs79AcEZbMaE37HVUZGJiszDo6d KCvGDSgZKtY6vq307VfdR/n+yU/tg7hy3WmvWd7uH/AOdrv8SjYWZjvAXQe+nhMaX0+V jfiA== X-Gm-Message-State: AOJu0Yy+Yy3PUiMUfJdcr6UKJWt5rK0z8tfN8uuveMwwasEmmRk08Luo fHHK79C4C0YZuzWztSi5IyKZSUhB6N2LStTuYMZYB9IdxCcuHvPl1j09neG+ddegA64qvktNAqd U7DRcPmYjVyFucUU0BCZJ/mv4AcSvkHZir6+b6l9oDFo5Hn4t8oduezMv8/q7Ri+rkLNdU2qL/3 m6QH3ZRWheP+keyOnMnyPP9ADV2Sj5cmcEMiUTb+0= X-Gm-Gg: ASbGncvEL+R8mt5D1MTMxoRDF5lvQEzx4EwqxqSxa1vR2jjvxjVVrvA+osZNKqB57aa ldwyigO/ie1QplZRV+nRzxIcA1dvYgEC1LaTh43N237mwEeALHPcnwdSPI0k5s14QHr1cZvhwsL 1Hv0p2p65xVNHyvyyxmgaGQjH2aIjSAN82Bx/SJiuBJEbuxLlogneLQVqpCheL2Uw1xBWWyGLD5 fLLSriwQ2rR5acdUsR1I9Y0Un0grBvMeXmm7OKWnAQ631cWwerbKpkDLf0rkn9tIi9JDhJTQ0RE dAlUSs4PlRDBLgq7fbvU X-Received: by 2002:a17:906:3291:b0:ab7:eeae:b23e with SMTP id a640c23a62f3a-abeeef74ademr928125166b.47.1740666144356; Thu, 27 Feb 2025 06:22:24 -0800 (PST) X-Google-Smtp-Source: AGHT+IHklFqPVR+3DXJIrGGBuALrOKv7zqbe8KGnQ7eyzk1n4cSghHR9ghnEfklanU7UGHy5Z24EVg== X-Received: by 2002:a17:906:3291:b0:ab7:eeae:b23e with SMTP id a640c23a62f3a-abeeef74ademr928121866b.47.1740666143755; Thu, 27 Feb 2025 06:22:23 -0800 (PST) Received: from [192.168.10.48] ([176.206.102.52]) by smtp.gmail.com with ESMTPSA id a640c23a62f3a-abf0c0ba3dbsm129921666b.22.2025.02.27.06.22.21 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 27 Feb 2025 06:22:21 -0800 (PST) From: Paolo Bonzini To: qemu-devel@nongnu.org Cc: qemu-rust@nongnu.org, zhao1.liu@intel.com Subject: [PATCH 01/12] rust: cell: add wrapper for FFI types Date: Thu, 27 Feb 2025 15:22:08 +0100 Message-ID: <20250227142219.812270-2-pbonzini@redhat.com> X-Mailer: git-send-email 2.48.1 In-Reply-To: <20250227142219.812270-1-pbonzini@redhat.com> References: <20250227142219.812270-1-pbonzini@redhat.com> MIME-Version: 1.0 Received-SPF: pass client-ip=170.10.133.124; envelope-from=pbonzini@redhat.com; helo=us-smtp-delivery-124.mimecast.com X-Spam_score_int: -24 X-Spam_score: -2.5 X-Spam_bar: -- X-Spam_report: (-2.5 / 5.0 requ) BAYES_00=-1.9, DKIMWL_WL_HIGH=-0.438, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_NONE=-0.0001, RCVD_IN_MSPIKE_H2=0.001, RCVD_IN_VALIDITY_CERTIFIED_BLOCKED=0.001, RCVD_IN_VALIDITY_RPBL_BLOCKED=0.001, SPF_HELO_NONE=0.001, SPF_PASS=-0.001 autolearn=ham autolearn_force=no X-Spam_action: no action X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org Sender: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org Inspired by the same-named type in Linux. This type provides the compiler with a correct view of what goes on with FFI types. In addition, it separates the glue code from the bindgen-generated code, allowing traits such as Send, Sync or Zeroable to be specified independently for C and Rust structs. Reviewed-by: Zhao Liu Signed-off-by: Paolo Bonzini --- docs/devel/rust.rst | 34 +++++-- rust/qemu-api/src/cell.rs | 197 ++++++++++++++++++++++++++++++++++++-- 2 files changed, 216 insertions(+), 15 deletions(-) diff --git a/docs/devel/rust.rst b/docs/devel/rust.rst index 5d8aa3a45bc..784c3e40bdc 100644 --- a/docs/devel/rust.rst +++ b/docs/devel/rust.rst @@ -296,15 +296,33 @@ of ``&mut self``; access to internal fields must use *interior mutability* to go from a shared reference to a ``&mut``. Whenever C code provides you with an opaque ``void *``, avoid converting it -to a Rust mutable reference, and use a shared reference instead. Rust code -will then have to use QEMU's ``BqlRefCell`` and ``BqlCell`` type, which -enforce that locking rules for the "Big QEMU Lock" are respected. These cell -types are also known to the ``vmstate`` crate, which is able to "look inside" -them when building an in-memory representation of a ``struct``'s layout. -Note that the same is not true of a ``RefCell`` or ``Mutex``. +to a Rust mutable reference, and use a shared reference instead. The +``qemu_api::cell`` module provides wrappers that can be used to tell the +Rust compiler about interior mutability, and optionally to enforce locking +rules for the "Big QEMU Lock". In the future, similar cell types might +also be provided for ``AioContext``-based locking as well. -In the future, similar cell types might also be provided for ``AioContext``-based -locking as well. +In particular, device code will usually rely on the ``BqlRefCell`` and +``BqlCell`` type to ensure that data is accessed correctly under the +"Big QEMU Lock". These cell types are also known to the ``vmstate`` +crate, which is able to "look inside" them when building an in-memory +representation of a ``struct``'s layout. Note that the same is not true +of a ``RefCell`` or ``Mutex``. + +Bindings code instead will usually use the ``Opaque`` type, which hides +the contents of the underlying struct and can be easily converted to +a raw pointer, for use in calls to C functions. It can be used for +example as follows:: + + #[repr(transparent)] + #[derive(Debug)] + pub struct Object(Opaque); + +The bindings will then manually check for the big QEMU lock with +assertions, which allows the wrapper to be declared thread-safe:: + + unsafe impl Send for Object {} + unsafe impl Sync for Object {} Writing bindings to C code '''''''''''''''''''''''''' diff --git a/rust/qemu-api/src/cell.rs b/rust/qemu-api/src/cell.rs index eae4e2ce786..7c00109d0e9 100644 --- a/rust/qemu-api/src/cell.rs +++ b/rust/qemu-api/src/cell.rs @@ -27,7 +27,7 @@ // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -//! BQL-protected mutable containers. +//! QEMU-specific mutable containers //! //! Rust memory safety is based on this rule: Given an object `T`, it is only //! possible to have one of the following: @@ -43,8 +43,10 @@ //! usually have their pointer shared with the "outside world very early in //! their lifetime", for example when they create their //! [`MemoryRegion`s](crate::bindings::MemoryRegion). Therefore, individual -//! parts of a device must be made mutable in a controlled manner through the -//! use of cell types. +//! parts of a device must be made mutable in a controlled manner; this module +//! provides the tools to do so. +//! +//! ## Cell types //! //! [`BqlCell`] and [`BqlRefCell`] allow doing this via the Big QEMU Lock. //! While they are essentially the same single-threaded primitives that are @@ -71,7 +73,7 @@ //! QEMU device implementations is usually incorrect and can lead to //! thread-safety issues. //! -//! ## `BqlCell` +//! ### `BqlCell` //! //! [`BqlCell`] implements interior mutability by moving values in and out of //! the cell. That is, an `&mut T` to the inner value can never be obtained as @@ -91,7 +93,7 @@ //! - [`set`](BqlCell::set): this method replaces the interior value, //! dropping the replaced value. //! -//! ## `BqlRefCell` +//! ### `BqlRefCell` //! //! [`BqlRefCell`] uses Rust's lifetimes to implement "dynamic borrowing", a //! process whereby one can claim temporary, exclusive, mutable access to the @@ -111,13 +113,82 @@ //! Multiple immutable borrows are allowed via [`borrow`](BqlRefCell::borrow), //! or a single mutable borrow via [`borrow_mut`](BqlRefCell::borrow_mut). The //! thread will panic if these rules are violated or if the BQL is not held. +//! +//! ## Opaque wrappers +//! +//! The cell types from the previous section are useful at the boundaries +//! of code that requires interior mutability. When writing glue code that +//! interacts directly with C structs, however, it is useful to operate +//! at a lower level. +//! +//! C functions often violate Rust's fundamental assumptions about memory +//! safety by modifying memory even if it is shared. Furthermore, C structs +//! often start their life uninitialized and may be populated lazily. +//! +//! For this reason, this module provides the [`Opaque`] type to opt out +//! of Rust's usual guarantees about the wrapped type. Access to the wrapped +//! value is always through raw pointers, obtained via methods like +//! [`as_mut_ptr()`](Opaque::as_mut_ptr) and [`as_ptr()`](Opaque::as_ptr). These +//! pointers can then be passed to C functions or dereferenced; both actions +//! require `unsafe` blocks, making it clear where safety guarantees must be +//! manually verified. For example +//! +//! ```ignore +//! unsafe { +//! let state = Opaque::::uninit(); +//! qemu_struct_init(state.as_mut_ptr()); +//! } +//! ``` +//! +//! [`Opaque`] will usually be wrapped one level further, so that +//! bridge methods can be added to the wrapper: +//! +//! ```ignore +//! pub struct MyStruct(Opaque); +//! +//! impl MyStruct { +//! fn new() -> Pin> { +//! let result = Box::pin(unsafe { Opaque::uninit() }); +//! unsafe { qemu_struct_init(result.as_mut_ptr()) }; +//! result +//! } +//! } +//! ``` +//! +//! This pattern of wrapping bindgen-generated types in [`Opaque`] provides +//! several advantages: +//! +//! * The choice of traits to be implemented is not limited by the +//! bindgen-generated code. For example, [`Drop`] can be added without +//! disabling [`Copy`] on the underlying bindgen type +//! +//! * [`Send`] and [`Sync`] implementations can be controlled by the wrapper +//! type rather than being automatically derived from the C struct's layout +//! +//! * Methods can be implemented in a separate crate from the bindgen-generated +//! bindings +//! +//! * [`Debug`](std::fmt::Debug) and [`Display`](std::fmt::Display) +//! implementations can be customized to be more readable than the raw C +//! struct representation +//! +//! The [`Opaque`] type does not include BQL validation; it is possible to +//! assert in the code that the right lock is taken, to use it together +//! with a custom lock guard type, or to let C code take the lock, as +//! appropriate. It is also possible to use it with non-thread-safe +//! types, since by default (unlike [`BqlCell`] and [`BqlRefCell`] +//! it is neither `Sync` nor `Send`. +//! +//! While [`Opaque`] is necessary for C interop, it should be used sparingly +//! and only at FFI boundaries. For QEMU-specific types that need interior +//! mutability, prefer [`BqlCell`] or [`BqlRefCell`]. use std::{ cell::{Cell, UnsafeCell}, cmp::Ordering, fmt, - marker::PhantomData, - mem, + marker::{PhantomData, PhantomPinned}, + mem::{self, MaybeUninit}, ops::{Deref, DerefMut}, ptr::NonNull, }; @@ -840,3 +911,115 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { (**self).fmt(f) } } + +/// Stores an opaque value that is shared with C code. +/// +/// Often, C structs can changed when calling a C function even if they are +/// behind a shared Rust reference, or they can be initialized lazily and have +/// invalid bit patterns (e.g. `3` for a [`bool`]). This goes against Rust's +/// strict aliasing rules, which normally prevent mutation through shared +/// references. +/// +/// Wrapping the struct with `Opaque` ensures that the Rust compiler does not +/// assume the usual constraints that Rust structs require, and allows using +/// shared references on the Rust side. +/// +/// `Opaque` is `#[repr(transparent)]`, so that it matches the memory layout +/// of `T`. +#[repr(transparent)] +pub struct Opaque { + value: UnsafeCell>, + // PhantomPinned also allows multiple references to the `Opaque`, i.e. + // one `&mut Opaque` can coexist with a `&mut T` or any number of `&T`; + // see https://docs.rs/pinned-aliasable/latest/pinned_aliasable/. + _pin: PhantomPinned, +} + +impl Opaque { + /// Creates a new shared reference from a C pointer + /// + /// # Safety + /// + /// The pointer must be valid, though it need not point to a valid value. + pub unsafe fn from_raw<'a>(ptr: *mut T) -> &'a Self { + let ptr = NonNull::new(ptr).unwrap().cast::(); + // SAFETY: Self is a transparent wrapper over T + unsafe { ptr.as_ref() } + } + + /// Creates a new opaque object with uninitialized contents. + /// + /// # Safety + /// + /// Ultimately the pointer to the returned value will be dereferenced + /// in another `unsafe` block, for example when passing it to a C function, + /// but the functions containing the dereference are usually safe. The + /// value returned from `uninit()` must be initialized and pinned before + /// calling them. + #[allow(clippy::missing_const_for_fn)] + pub unsafe fn uninit() -> Self { + Self { + value: UnsafeCell::new(MaybeUninit::uninit()), + _pin: PhantomPinned, + } + } + + /// Creates a new opaque object with zeroed contents. + /// + /// # Safety + /// + /// Ultimately the pointer to the returned value will be dereferenced + /// in another `unsafe` block, for example when passing it to a C function, + /// but the functions containing the dereference are usually safe. The + /// value returned from `uninit()` must be pinned (and possibly initialized) + /// before calling them. + #[allow(clippy::missing_const_for_fn)] + pub unsafe fn zeroed() -> Self { + Self { + value: UnsafeCell::new(MaybeUninit::zeroed()), + _pin: PhantomPinned, + } + } + + /// Returns a raw mutable pointer to the opaque data. + pub const fn as_mut_ptr(&self) -> *mut T { + UnsafeCell::get(&self.value).cast() + } + + /// Returns a raw pointer to the opaque data. + pub const fn as_ptr(&self) -> *const T { + self.as_mut_ptr() as *const _ + } + + /// Returns a raw pointer to the opaque data that can be passed to a + /// C function as `void *`. + pub const fn as_void_ptr(&self) -> *mut std::ffi::c_void { + UnsafeCell::get(&self.value).cast() + } +} + +impl fmt::Debug for Opaque { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let mut name: String = "Opaque<".to_string(); + name += std::any::type_name::(); + name += ">"; + f.debug_tuple(&name).field(&self.as_ptr()).finish() + } +} + +impl Opaque { + /// Creates a new opaque object with default contents. + /// + /// # Safety + /// + /// Ultimately the pointer to the returned value will be dereferenced + /// in another `unsafe` block, for example when passing it to a C function, + /// but the functions containing the dereference are usually safe. The + /// value returned from `uninit()` must be pinned before calling them. + pub unsafe fn new() -> Self { + Self { + value: UnsafeCell::new(MaybeUninit::new(T::default())), + _pin: PhantomPinned, + } + } +} From patchwork Thu Feb 27 14:22:09 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Paolo Bonzini X-Patchwork-Id: 13994634 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.lore.kernel.org (Postfix) with ESMTPS id 9FAAAC19F2E for ; Thu, 27 Feb 2025 14:25:54 +0000 (UTC) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1tnen5-0005ID-Vy; Thu, 27 Feb 2025 09:23:08 -0500 Received: from eggs.gnu.org ([2001:470:142:3::10]) by lists.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1tnemc-0003qC-KE for qemu-devel@nongnu.org; Thu, 27 Feb 2025 09:22:41 -0500 Received: from us-smtp-delivery-124.mimecast.com ([170.10.133.124]) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1tnemY-00044k-0Q for qemu-devel@nongnu.org; Thu, 27 Feb 2025 09:22:37 -0500 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1740666149; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=DU8RnwXUCUOFmlQq7LelOhzzqajTuinw3yOxvFn4Jv4=; b=EhibYWNi/d12bTzwyHSBJfF9ksaLodeM6ENU+gZFhtmTMjy4txbFFJ4Ch2UA6UhltmgT0k 75At1fMyVF96Ofe6Gq3e4uqZAEg1wXcdN20M4AkcH758bwiUAnlHAiKK1OR0S8O3dPeX7t 6BnW7TBm2V1Owg3VPkj3C5xJCDMWBMI= Received: from mail-ed1-f72.google.com (mail-ed1-f72.google.com [209.85.208.72]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-316-qEoIOJalO4CJ1DBp2bJ3LQ-1; Thu, 27 Feb 2025 09:22:28 -0500 X-MC-Unique: qEoIOJalO4CJ1DBp2bJ3LQ-1 X-Mimecast-MFC-AGG-ID: qEoIOJalO4CJ1DBp2bJ3LQ_1740666147 Received: by mail-ed1-f72.google.com with SMTP id 4fb4d7f45d1cf-5e04de6583bso1482253a12.1 for ; Thu, 27 Feb 2025 06:22:27 -0800 (PST) X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1740666145; x=1741270945; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=DU8RnwXUCUOFmlQq7LelOhzzqajTuinw3yOxvFn4Jv4=; b=d+Lfmk7w7chkMroCjY3sq1o9+1shjwoj+qRxW/QPIoHyOqQoDsnCFadYd4ocXHwB9U gnHmUEWLovch3tSLnkjWUu0f25i0MJJcDIIzORQc2w7pyfXI2Y4xBvFi+5mIraYUXKzI /y+2U3QRFRztQoSgMVPrtQDzqRpKyWvr1ASczmhASyB2ypVM92d4P8balN1BOzmktH6n IJ3g+VxNZBZFJVE83qyF9jY4Kz/CsLyWSwMWwlUxZ+fADDSEh3zaAXuo2hpKnemMFtNA zNE0dM/5JsEMeZgbpTXPc+FD1ZPqhI20lCxMrvbzuMHU7EyAVZz4tEbOh39gJi35m0pi bwVg== X-Gm-Message-State: AOJu0Yz32/JK8eyghBbbQm4f7VzgUKEH9Ztphz51cau2spatxmcJ+FwM Afw2aLd/7XOSMLHNOhtpvQX19IPxR+WVf8un8GCz1NLh1sUUNrueOfDy7Cn/iSaToiGRSdcYSF3 puu8CCddMylbiRfomCT3QedzFjHh1HbDNa552WTDNoltfWj0W9w7ql6WAt0W9LKS0nuAE+Zr/JC Rv4AqfzuzfAFUecJavkiN/5PKJM9gNQQX7joMI1Xo= X-Gm-Gg: ASbGnct3zwxhjYMcCnq6IejMO7w7NHnBIwYUI+KbHBuThdyItO+uKXNKncGbGA0Y2rW /WLT0FFvPpVFYvK18BnZ7HXCMNhZU6tIHv8GTqzNaM8YfGyzuolWqDw8SNxlj55feuvwre6nK5T /jTvzN99RqvTae0FgkUZ4Yp7sjT9AUQvzcC9ue4+dafG35wZCpqbd1EKeIK/6Vu4DI3B+Ee1IO2 jEMey2I72IkrU6q6VfkDOsZPUbFo+mCD2ijQDVKZhDWg4+giuHqlkBdt3OwbhF1LJ9tjeYDVTrq JOz5O7cnxNjGQKk0m1Uf X-Received: by 2002:a05:6402:3595:b0:5e0:8c55:536 with SMTP id 4fb4d7f45d1cf-5e444481531mr13914557a12.4.1740666145476; Thu, 27 Feb 2025 06:22:25 -0800 (PST) X-Google-Smtp-Source: AGHT+IHQEvRXKFNO8uqehyPrMvfwzyUwe/T2t9ikClNPL5YVhQNUna8NZ1lwhLuT9lhaB++h80+AvQ== X-Received: by 2002:a05:6402:3595:b0:5e0:8c55:536 with SMTP id 4fb4d7f45d1cf-5e444481531mr13914532a12.4.1740666145018; Thu, 27 Feb 2025 06:22:25 -0800 (PST) Received: from [192.168.10.48] ([176.206.102.52]) by smtp.gmail.com with ESMTPSA id 4fb4d7f45d1cf-5e4c3fb58f7sm1145654a12.57.2025.02.27.06.22.24 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 27 Feb 2025 06:22:24 -0800 (PST) From: Paolo Bonzini To: qemu-devel@nongnu.org Cc: qemu-rust@nongnu.org, zhao1.liu@intel.com Subject: [PATCH 02/12] rust: qemu_api_macros: add Wrapper derive macro Date: Thu, 27 Feb 2025 15:22:09 +0100 Message-ID: <20250227142219.812270-3-pbonzini@redhat.com> X-Mailer: git-send-email 2.48.1 In-Reply-To: <20250227142219.812270-1-pbonzini@redhat.com> References: <20250227142219.812270-1-pbonzini@redhat.com> MIME-Version: 1.0 Received-SPF: pass client-ip=170.10.133.124; envelope-from=pbonzini@redhat.com; helo=us-smtp-delivery-124.mimecast.com X-Spam_score_int: -24 X-Spam_score: -2.5 X-Spam_bar: -- X-Spam_report: (-2.5 / 5.0 requ) BAYES_00=-1.9, DKIMWL_WL_HIGH=-0.438, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_NONE=-0.0001, RCVD_IN_MSPIKE_H2=0.001, RCVD_IN_VALIDITY_CERTIFIED_BLOCKED=0.001, RCVD_IN_VALIDITY_RPBL_BLOCKED=0.001, SPF_HELO_NONE=0.001, SPF_PASS=-0.001 autolearn=unavailable autolearn_force=no X-Spam_action: no action X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org Sender: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org Add a derive macro that makes it easy to peel off all the layers of specialness (UnsafeCell, MaybeUninit, etc.) and just get a pointer to the wrapped type; and likewise add them back starting from a *mut. Reviewed-by: Zhao Liu Signed-off-by: Paolo Bonzini --- docs/devel/rust.rst | 8 +-- rust/qemu-api-macros/src/lib.rs | 86 ++++++++++++++++++++++++++++++++- rust/qemu-api/meson.build | 7 +-- rust/qemu-api/src/cell.rs | 31 ++++++++++++ 4 files changed, 123 insertions(+), 9 deletions(-) diff --git a/docs/devel/rust.rst b/docs/devel/rust.rst index 784c3e40bdc..64e04bc5c41 100644 --- a/docs/devel/rust.rst +++ b/docs/devel/rust.rst @@ -315,11 +315,13 @@ a raw pointer, for use in calls to C functions. It can be used for example as follows:: #[repr(transparent)] - #[derive(Debug)] + #[derive(Debug, qemu_api_macros::Wrapper)] pub struct Object(Opaque); -The bindings will then manually check for the big QEMU lock with -assertions, which allows the wrapper to be declared thread-safe:: +where the special ``derive`` macro provides useful methods such as +``from_raw``, ``as_ptr`` and ``as_mut_ptr``. The bindings will then +manually check for the big QEMU lock with assertions, which allows +the wrapper to be declared thread-safe:: unsafe impl Send for Object {} unsafe impl Sync for Object {} diff --git a/rust/qemu-api-macros/src/lib.rs b/rust/qemu-api-macros/src/lib.rs index 7ec218202f4..3df9c48035d 100644 --- a/rust/qemu-api-macros/src/lib.rs +++ b/rust/qemu-api-macros/src/lib.rs @@ -6,7 +6,7 @@ use quote::quote; use syn::{ parse_macro_input, parse_quote, punctuated::Punctuated, spanned::Spanned, token::Comma, Data, - DeriveInput, Field, Fields, Ident, Meta, Path, Token, Type, Variant, Visibility, + DeriveInput, Field, Fields, FieldsUnnamed, Ident, Meta, Path, Token, Type, Variant, Visibility, }; mod utils; @@ -33,6 +33,35 @@ fn get_fields<'a>( } } +fn get_unnamed_field<'a>(input: &'a DeriveInput, msg: &str) -> Result<&'a Field, MacroError> { + if let Data::Struct(s) = &input.data { + let unnamed = match &s.fields { + Fields::Unnamed(FieldsUnnamed { + unnamed: ref fields, + .. + }) => fields, + _ => { + return Err(MacroError::Message( + format!("Tuple struct required for {}", msg), + s.fields.span(), + )) + } + }; + if unnamed.len() != 1 { + return Err(MacroError::Message( + format!("A single field is required for {}", msg), + s.fields.span(), + )); + } + Ok(&unnamed[0]) + } else { + Err(MacroError::Message( + format!("Struct required for {}", msg), + input.ident.span(), + )) + } +} + fn is_c_repr(input: &DeriveInput, msg: &str) -> Result<(), MacroError> { let expected = parse_quote! { #[repr(C)] }; @@ -46,6 +75,19 @@ fn is_c_repr(input: &DeriveInput, msg: &str) -> Result<(), MacroError> { } } +fn is_transparent_repr(input: &DeriveInput, msg: &str) -> Result<(), MacroError> { + let expected = parse_quote! { #[repr(transparent)] }; + + if input.attrs.iter().any(|attr| attr == &expected) { + Ok(()) + } else { + Err(MacroError::Message( + format!("#[repr(transparent)] required for {}", msg), + input.ident.span(), + )) + } +} + fn derive_object_or_error(input: DeriveInput) -> Result { is_c_repr(&input, "#[derive(Object)]")?; @@ -72,6 +114,48 @@ pub fn derive_object(input: TokenStream) -> TokenStream { TokenStream::from(expanded) } +fn derive_opaque_or_error(input: DeriveInput) -> Result { + is_transparent_repr(&input, "#[derive(Wrapper)]")?; + + let name = &input.ident; + let field = &get_unnamed_field(&input, "#[derive(Wrapper)]")?; + let typ = &field.ty; + + // TODO: how to add "::qemu_api"? For now, this is only used in the + // qemu_api crate so it's not a problem. + Ok(quote! { + unsafe impl crate::cell::Wrapper for #name { + type Wrapped = <#typ as crate::cell::Wrapper>::Wrapped; + } + impl #name { + pub unsafe fn from_raw<'a>(ptr: *mut ::Wrapped) -> &'a Self { + let ptr = ::std::ptr::NonNull::new(ptr).unwrap().cast::(); + unsafe { ptr.as_ref() } + } + + pub const fn as_mut_ptr(&self) -> *mut ::Wrapped { + self.0.as_mut_ptr() + } + + pub const fn as_ptr(&self) -> *const ::Wrapped { + self.0.as_ptr() + } + + pub const fn as_void_ptr(&self) -> *mut ::core::ffi::c_void { + self.0.as_void_ptr() + } + } + }) +} + +#[proc_macro_derive(Wrapper)] +pub fn derive_opaque(input: TokenStream) -> TokenStream { + let input = parse_macro_input!(input as DeriveInput); + let expanded = derive_opaque_or_error(input).unwrap_or_else(Into::into); + + TokenStream::from(expanded) +} + #[rustfmt::skip::macros(quote)] fn derive_offsets_or_error(input: DeriveInput) -> Result { is_c_repr(&input, "#[derive(offsets)]")?; diff --git a/rust/qemu-api/meson.build b/rust/qemu-api/meson.build index bcf1cf780f3..6e52c4bad74 100644 --- a/rust/qemu-api/meson.build +++ b/rust/qemu-api/meson.build @@ -42,16 +42,13 @@ _qemu_api_rs = static_library( override_options: ['rust_std=2021', 'build.rust_std=2021'], rust_abi: 'rust', rust_args: _qemu_api_cfg, - dependencies: libc_dep, + dependencies: [libc_dep, qemu_api_macros], ) rust.test('rust-qemu-api-tests', _qemu_api_rs, suite: ['unit', 'rust']) -qemu_api = declare_dependency( - link_with: _qemu_api_rs, - dependencies: qemu_api_macros, -) +qemu_api = declare_dependency(link_with: _qemu_api_rs) # Rust executables do not support objects, so add an intermediate step. rust_qemu_api_objs = static_library( diff --git a/rust/qemu-api/src/cell.rs b/rust/qemu-api/src/cell.rs index 7c00109d0e9..24efb3a2f2a 100644 --- a/rust/qemu-api/src/cell.rs +++ b/rust/qemu-api/src/cell.rs @@ -1023,3 +1023,34 @@ pub unsafe fn new() -> Self { } } } + +/// Annotates [`Self`] as a transparent wrapper for another type. +/// +/// Usually defined via the [`qemu_api_macros::Wrapper`] derive macro. +/// +/// # Examples +/// +/// ``` +/// # use std::mem::ManuallyDrop; +/// # use qemu_api::cell::Wrapper; +/// #[repr(transparent)] +/// pub struct Example { +/// inner: ManuallyDrop, +/// } +/// +/// unsafe impl Wrapper for Example { +/// type Wrapped = String; +/// } +/// ``` +/// +/// # Safety +/// +/// `Self` must be a `#[repr(transparent)]` wrapper for the `Wrapped` type, +/// whether directly or indirectly. +pub unsafe trait Wrapper { + type Wrapped; +} + +unsafe impl Wrapper for Opaque { + type Wrapped = T; +} From patchwork Thu Feb 27 14:22:10 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Paolo Bonzini X-Patchwork-Id: 13994688 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.lore.kernel.org (Postfix) with ESMTPS id 54A12C19F32 for ; Thu, 27 Feb 2025 14:33:36 +0000 (UTC) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1tnenZ-0005xW-5L; Thu, 27 Feb 2025 09:23:37 -0500 Received: from eggs.gnu.org ([2001:470:142:3::10]) by lists.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1tnemc-0003q8-VY for qemu-devel@nongnu.org; Thu, 27 Feb 2025 09:22:41 -0500 Received: from us-smtp-delivery-124.mimecast.com ([170.10.133.124]) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1tnemX-00044y-9u for qemu-devel@nongnu.org; Thu, 27 Feb 2025 09:22:36 -0500 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1740666151; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=OAGa/1zAiQKppBasu/YtxlNDeSsZyMqPAmmwgiPHU8k=; b=h3c/d85VvNOczNK81g1iY3ceQjCwzfY1L0e9S2H+HaU5oOV54dosazBvp0QvZTmYvm/Ao6 kslBqmbP+8+UJ21a1Vv66HiUcjm+BqrN1/pN/3Wu+0PFU3JSrdn2ZrkymDunmJpBAUOwzz HhLDZwprip75BcXlSphyj1l6Cs7V6Io= Received: from mail-ej1-f69.google.com (mail-ej1-f69.google.com [209.85.218.69]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-252-Ey703yRpNyOlFO-nX5OZJA-1; Thu, 27 Feb 2025 09:22:30 -0500 X-MC-Unique: Ey703yRpNyOlFO-nX5OZJA-1 X-Mimecast-MFC-AGG-ID: Ey703yRpNyOlFO-nX5OZJA_1740666149 Received: by mail-ej1-f69.google.com with SMTP id a640c23a62f3a-abb7e837a7aso112964866b.3 for ; Thu, 27 Feb 2025 06:22:30 -0800 (PST) X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1740666148; x=1741270948; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=OAGa/1zAiQKppBasu/YtxlNDeSsZyMqPAmmwgiPHU8k=; b=UiHKzC+iBFhKE7DP+v+svtInU1xKNurDrP+JJN1722e2cTcOQisXmJgfPfApxldcPU I1gcLdRck/1lQU97Rar0uFpUbM7GIBrf2YcCQ6CwiJLzHHkR7gHnr6WTRX78SI2L4k2E rQ3lw0x7lXICDHBw1752tWPxmayVFIhtE/BXHZv8tOEHLLAnGkssiX9/BtgCZR4YZufm XwcsMWpQGtv5qQMNM7bgnPwDuzsHfQF8XZPbpLXPxi8b0+gC3KHB+pUU0YvrsA+n8YUp JfuTwbAKtsYOMeIjeFPSpTrEyQQSsoEda752JcTmk1FdLxunTl838cJJEe2VQmOTRY5J 8g+Q== X-Gm-Message-State: AOJu0YwX+14B/eLfz5aFf5i2OydknkLqURd8XCGAzvcCsHGRK4jZe/+2 TfHNlTXczAm3Fitn2v5hO3l6/Cii8m0U7SZPDn0q802G1yMgJx0M+70G8YIKVXslLF08+nsRUYo ExHpqkzaHD6DlxKbTyEPXiBjVYlZQQh4VVDZIMRViH5CsfBE3YbdoS7q1qmUXwBTZn79cXLx4i+ FMcDVBpGuYqjj8kdhmSPcAWYaHOFRh5PyrUS3H4bw= X-Gm-Gg: ASbGncurjxlTM+c79haZgXiawBt8V28EWT75UMnuuq8TpBOM+u6JJKy1rYhUAuL9yEt kudCQ2iDLrQlu8XH8Ini9MU4eibAvZ8xyDmDRxxzAv3LPxG3FbkplRZedT9WAi7CAO4pq1YJoX5 9IniasC86K9+Grw+GHyKF0Pco/uQa5GuEQRkZ6ECekB1wBSV8xFBT3m4J1CfxKatQn/f0HRGMOz lgJ1gH3wWhP7Xv76+EOc5elkBixKsx11XMaXVeMnYQ776jDaSn2Kq1PN4fTFKQzvOhbSHy0Q+AJ Phx+UOckrlB5KrKXiMHc X-Received: by 2002:a17:907:c0f:b0:ab6:d47a:9b20 with SMTP id a640c23a62f3a-abc09a8a15cmr3264750966b.31.1740666148365; Thu, 27 Feb 2025 06:22:28 -0800 (PST) X-Google-Smtp-Source: AGHT+IE4daWnQQOCN1bWh3SugyKqQgpaK2V8VPcdTd6AzyLvPLm6JBm1RPxBjICn07Gp4GTaMSKIQg== X-Received: by 2002:a17:907:c0f:b0:ab6:d47a:9b20 with SMTP id a640c23a62f3a-abc09a8a15cmr3264746266b.31.1740666147824; Thu, 27 Feb 2025 06:22:27 -0800 (PST) Received: from [192.168.10.48] ([176.206.102.52]) by smtp.gmail.com with ESMTPSA id a640c23a62f3a-abf0c75bffcsm130517966b.143.2025.02.27.06.22.25 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 27 Feb 2025 06:22:25 -0800 (PST) From: Paolo Bonzini To: qemu-devel@nongnu.org Cc: qemu-rust@nongnu.org, zhao1.liu@intel.com Subject: [PATCH 03/12] rust: vmstate: add std::pin::Pin as transparent wrapper Date: Thu, 27 Feb 2025 15:22:10 +0100 Message-ID: <20250227142219.812270-4-pbonzini@redhat.com> X-Mailer: git-send-email 2.48.1 In-Reply-To: <20250227142219.812270-1-pbonzini@redhat.com> References: <20250227142219.812270-1-pbonzini@redhat.com> MIME-Version: 1.0 Received-SPF: pass client-ip=170.10.133.124; envelope-from=pbonzini@redhat.com; helo=us-smtp-delivery-124.mimecast.com X-Spam_score_int: -24 X-Spam_score: -2.5 X-Spam_bar: -- X-Spam_report: (-2.5 / 5.0 requ) BAYES_00=-1.9, DKIMWL_WL_HIGH=-0.438, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_NONE=-0.0001, RCVD_IN_MSPIKE_H2=0.001, RCVD_IN_VALIDITY_CERTIFIED_BLOCKED=0.001, RCVD_IN_VALIDITY_RPBL_BLOCKED=0.001, SPF_HELO_NONE=0.001, SPF_PASS=-0.001 autolearn=unavailable autolearn_force=no X-Spam_action: no action X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org Sender: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org Signed-off-by: Paolo Bonzini --- rust/qemu-api/src/vmstate.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/rust/qemu-api/src/vmstate.rs b/rust/qemu-api/src/vmstate.rs index 24a4dc81e7f..1e7ba531e2a 100644 --- a/rust/qemu-api/src/vmstate.rs +++ b/rust/qemu-api/src/vmstate.rs @@ -330,6 +330,7 @@ unsafe impl<$base> VMState for $type where $base: VMState $($where)* { impl_vmstate_transparent!(std::cell::Cell where T: VMState); impl_vmstate_transparent!(std::cell::UnsafeCell where T: VMState); +impl_vmstate_transparent!(std::pin::Pin where T: VMState); impl_vmstate_transparent!(crate::cell::BqlCell where T: VMState); impl_vmstate_transparent!(crate::cell::BqlRefCell where T: VMState); From patchwork Thu Feb 27 14:22:11 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Paolo Bonzini X-Patchwork-Id: 13994657 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.lore.kernel.org (Postfix) with ESMTPS id C8D36C19F2E for ; Thu, 27 Feb 2025 14:27:26 +0000 (UTC) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1tnenA-0005RM-Fu; Thu, 27 Feb 2025 09:23:12 -0500 Received: from eggs.gnu.org ([2001:470:142:3::10]) by lists.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1tnemc-0003qD-Ib for qemu-devel@nongnu.org; Thu, 27 Feb 2025 09:22:41 -0500 Received: from us-smtp-delivery-124.mimecast.com ([170.10.129.124]) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1tnemY-00045V-F8 for qemu-devel@nongnu.org; Thu, 27 Feb 2025 09:22:37 -0500 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1740666153; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=nk4rG8BvOrBCUFxfsl3zj+sJAUqBN7gnD9BX4ggHZ8E=; b=Of8fQR6DKSW+gy895Yp1/se+99G5E6TNzTqqJkpPGZXjS1C51yISSv7maC7ZEj3gTWO6NQ C7RKOltVVUvI1TFlcQi0ARbEM6jNhkQyCqGLMLfpghsZgUlA9W06iPYYusFUaiKeXUqM0A tgGMdHVH5jLfvZBNS1GtIObdVrhjVhI= Received: from mail-ej1-f70.google.com (mail-ej1-f70.google.com [209.85.218.70]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-423-cX38hNcHNGmPKacPrlPRLg-1; Thu, 27 Feb 2025 09:22:32 -0500 X-MC-Unique: cX38hNcHNGmPKacPrlPRLg-1 X-Mimecast-MFC-AGG-ID: cX38hNcHNGmPKacPrlPRLg_1740666151 Received: by mail-ej1-f70.google.com with SMTP id a640c23a62f3a-abb86503062so118528066b.2 for ; Thu, 27 Feb 2025 06:22:32 -0800 (PST) X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1740666151; x=1741270951; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=nk4rG8BvOrBCUFxfsl3zj+sJAUqBN7gnD9BX4ggHZ8E=; b=gTCPcEwIMt6uw/xPUbXTTPYCI0G/fsfPk1HrnYfar0PaHNdRDmOtYuxS7h3IOwBRog H0lqk4wIsTAVOqLhJbmVDEJUsQo2PyNtat0xelkMIM7jDMOx9oLK0x3tykdzbjvfMzO3 hmE7WsXkT5WjFL+hWfykZcCb/pOLyy3LayoqJvJ0//M7sMmr/wnDVDm9ukKbpo8OqPai A1pSdo8H6kuxJSTPg4uyq16ZLG+qh6YZARIFIXGPnWORFeYHbrS15N3eGEKNwL8E6vnJ x9jL/c3Zc0eVTCb4f3rSO7fvoLoozY4i06/OzRAKbdgSWCEbY7vmrMCPnk3KDqsAhANA 1p4A== X-Gm-Message-State: AOJu0YyiBlpvs3FkBLxwnu/UAIwCUN9HpYyGXvj/dFvgCBB1mrYkxxsT eq8VKfx5Z/s5JzH/JKYOqW//T2+gdg95wDMIC5KKsAyq7Zd3mRobXoKqgNFT3TnHAbeAxSMXQxM NObgzvY6YzZYnhtGdNrU3Imp7soI+0Ut9ZmrIeXIdgMBnmcDXxutNbGCtTTj8mwsOmq7NVp1jKq SW32W/TUxa5Mb7+VVMFhSG3rqPoGn0uezuNY+zJXQ= X-Gm-Gg: ASbGncuJ+Hx6grhmsEeGNTsGeGvWqjidFd6MoErQKcRDX3G5nPdcC0VfDTCtumzInD9 NLKXd+nzpPDh4MOxWqKyRtSTOYyp+XYyBauftDyGbJOa3gxneqF/Tbw8SHOBF4vGKgW6ioxp8vK byivXn7hiNVT6awQvk55WviypX8Z4YH7P7KVjiv+E49DMay6nHbFx6y5qLjOqw1xCOEAS4/ug2e 9v/IHztnGeyvX1VcADfc9MT+4adIifRSK+IoNHsacboj6vLtIXlQo3ChQQXHnykh0jr3Wd675Rq Fuo36rgk6C+qQypAD9/S X-Received: by 2002:a17:906:318a:b0:abb:fcbb:ab20 with SMTP id a640c23a62f3a-abeeed8bfdcmr836456366b.22.1740666150635; Thu, 27 Feb 2025 06:22:30 -0800 (PST) X-Google-Smtp-Source: AGHT+IEre39vytYWAHhZhXaM95fI3eTfMy8Xz3vq9jO0H3LoqMNmrk3eKo/DJWQnPtAQh4wcgpPdlg== X-Received: by 2002:a17:906:318a:b0:abb:fcbb:ab20 with SMTP id a640c23a62f3a-abeeed8bfdcmr836454166b.22.1740666150047; Thu, 27 Feb 2025 06:22:30 -0800 (PST) Received: from [192.168.10.48] ([176.206.102.52]) by smtp.gmail.com with ESMTPSA id 4fb4d7f45d1cf-5e4c3fb4384sm1176263a12.49.2025.02.27.06.22.28 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 27 Feb 2025 06:22:28 -0800 (PST) From: Paolo Bonzini To: qemu-devel@nongnu.org Cc: qemu-rust@nongnu.org, zhao1.liu@intel.com Subject: [PATCH 04/12] rust: timer: wrap QEMUTimer with Opaque<> and express pinning requirements Date: Thu, 27 Feb 2025 15:22:11 +0100 Message-ID: <20250227142219.812270-5-pbonzini@redhat.com> X-Mailer: git-send-email 2.48.1 In-Reply-To: <20250227142219.812270-1-pbonzini@redhat.com> References: <20250227142219.812270-1-pbonzini@redhat.com> MIME-Version: 1.0 Received-SPF: pass client-ip=170.10.129.124; envelope-from=pbonzini@redhat.com; helo=us-smtp-delivery-124.mimecast.com X-Spam_score_int: -24 X-Spam_score: -2.5 X-Spam_bar: -- X-Spam_report: (-2.5 / 5.0 requ) BAYES_00=-1.9, DKIMWL_WL_HIGH=-0.438, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_NONE=-0.0001, RCVD_IN_MSPIKE_H5=0.001, RCVD_IN_MSPIKE_WL=0.001, RCVD_IN_VALIDITY_CERTIFIED_BLOCKED=0.001, RCVD_IN_VALIDITY_RPBL_BLOCKED=0.001, SPF_HELO_NONE=0.001, SPF_PASS=-0.001 autolearn=unavailable autolearn_force=no X-Spam_action: no action X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org Sender: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org Timers must be pinned in memory, because modify() stores a pointer to them in the TimerList. To ensure this is the case, replace the separate new() and init_full() with a single function that returns a pinned box. Because the only way to obtain a Timer is through Timer::new_full(), modify() knows that the timer it got is also pinned. In the future the pinning requirement will be expressed through the pin_init crate instead. Note that Timer is a bit different from other users of Opaque, in that it is created in Rust code rather than C code. This is why it has to use the unsafe Opaque::new() function. Signed-off-by: Paolo Bonzini --- meson.build | 7 ----- rust/hw/timer/hpet/src/hpet.rs | 23 ++++++++--------- rust/qemu-api/src/timer.rs | 47 ++++++++++++++++++++++------------ 3 files changed, 41 insertions(+), 36 deletions(-) // SAFETY: the opaque outlives the timer unsafe { timer_init_full( - self, + t.as_mut_ptr(), if let Some(g) = timer_list_group { g as *const TimerListGroup as *mut _ } else { @@ -62,11 +73,14 @@ pub fn init_full<'timer, 'opaque: 'timer, T, F>( attributes as c_int, Some(timer_cb), (opaque as *const T).cast::() as *mut c_void, - ) + ); } + t } pub fn modify(&self, expire_time: u64) { + // SAFETY: the only way to obtain a Timer is via methods that return a + // Pin>, therefore the timer is pinned unsafe { timer_mod(self.as_mut_ptr(), expire_time as i64) } } @@ -75,6 +89,7 @@ pub fn delete(&self) { } } +// FIXME: use something like PinnedDrop from the pinned_init crate impl Drop for Timer { fn drop(&mut self) { self.delete() diff --git a/meson.build b/meson.build index 0a2c61d2bfa..fc02e5fc763 100644 --- a/meson.build +++ b/meson.build @@ -4098,13 +4098,6 @@ if have_rust foreach enum : c_bitfields bindgen_args += ['--bitfield-enum', enum] endforeach - c_nocopy = [ - 'QEMUTimer', - ] - # Used to customize Drop trait - foreach struct : c_nocopy - bindgen_args += ['--no-copy', struct] - endforeach # TODO: Remove this comment when the clang/libclang mismatch issue is solved. # diff --git a/rust/hw/timer/hpet/src/hpet.rs b/rust/hw/timer/hpet/src/hpet.rs index be27eb0eff4..ce4b289d0c8 100644 --- a/rust/hw/timer/hpet/src/hpet.rs +++ b/rust/hw/timer/hpet/src/hpet.rs @@ -4,6 +4,7 @@ use std::{ ffi::CStr, + pin::Pin, ptr::{addr_of_mut, null_mut, NonNull}, slice::from_ref, }; @@ -156,7 +157,7 @@ pub struct HPETTimer { /// timer N index within the timer block (`HPETState`) #[doc(alias = "tn")] index: usize, - qemu_timer: Option>, + qemu_timer: Option>>, /// timer block abstraction containing this timer state: Option>, @@ -189,18 +190,14 @@ fn init(&mut self, index: usize, state_ptr: *mut HPETState) -> &mut Self { } fn init_timer_with_state(&mut self) { - self.qemu_timer = Some(Box::new({ - let mut t = Timer::new(); - t.init_full( - None, - CLOCK_VIRTUAL, - Timer::NS, - 0, - timer_handler, - &self.get_state().timers[self.index], - ); - t - })); + self.qemu_timer = Some(Timer::new_full( + None, + CLOCK_VIRTUAL, + Timer::NS, + 0, + timer_handler, + &self.get_state().timers[self.index], + )); } fn get_state(&self) -> &HPETState { diff --git a/rust/qemu-api/src/timer.rs b/rust/qemu-api/src/timer.rs index a593538917a..a8b2ab058b6 100644 --- a/rust/qemu-api/src/timer.rs +++ b/rust/qemu-api/src/timer.rs @@ -2,40 +2,51 @@ // Author(s): Zhao Liu // SPDX-License-Identifier: GPL-2.0-or-later -use std::os::raw::{c_int, c_void}; +use std::{ + os::raw::{c_int, c_void}, + pin::Pin, +}; use crate::{ bindings::{self, qemu_clock_get_ns, timer_del, timer_init_full, timer_mod, QEMUClockType}, callbacks::FnCall, + cell::Opaque, }; -pub type Timer = bindings::QEMUTimer; -pub type TimerListGroup = bindings::QEMUTimerListGroup; +/// A safe wrapper around [`bindings::QEMUTimer`]. +#[repr(transparent)] +#[derive(Debug, qemu_api_macros::Wrapper)] +pub struct Timer(Opaque); + +unsafe impl Send for Timer {} +unsafe impl Sync for Timer {} + +#[repr(transparent)] +#[derive(qemu_api_macros::Wrapper)] +pub struct TimerListGroup(Opaque); + +unsafe impl Send for TimerListGroup {} +unsafe impl Sync for TimerListGroup {} impl Timer { pub const MS: u32 = bindings::SCALE_MS; pub const US: u32 = bindings::SCALE_US; pub const NS: u32 = bindings::SCALE_NS; - pub fn new() -> Self { - Default::default() - } - - const fn as_mut_ptr(&self) -> *mut Self { - self as *const Timer as *mut _ - } - - pub fn init_full<'timer, 'opaque: 'timer, T, F>( - &'timer mut self, + pub fn new_full<'opaque, T, F>( timer_list_group: Option<&TimerListGroup>, clk_type: ClockType, scale: u32, attributes: u32, _cb: F, opaque: &'opaque T, - ) where + ) -> Pin> F: for<'a> FnCall<(&'a T,)>, { + // SAFETY: returning a pinned box makes it certain that the object + // will not move when added to a TimerList with `modify()`. + let t = unsafe { Box::pin(Self(Opaque::new())) }; let _: () = F::ASSERT_IS_SOME; /// timer expiration callback @@ -51,7 +62,7 @@ pub fn init_full<'timer, 'opaque: 'timer, T, F>( From patchwork Thu Feb 27 14:22:12 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Paolo Bonzini X-Patchwork-Id: 13994669 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.lore.kernel.org (Postfix) with ESMTPS id A168CC19F2E for ; Thu, 27 Feb 2025 14:29:21 +0000 (UTC) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1tneo9-0006dY-8M; Thu, 27 Feb 2025 09:24:15 -0500 Received: from eggs.gnu.org ([2001:470:142:3::10]) by lists.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1tnemc-0003qG-Kj for qemu-devel@nongnu.org; Thu, 27 Feb 2025 09:22:42 -0500 Received: from us-smtp-delivery-124.mimecast.com ([170.10.129.124]) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1tnema-000460-GJ for qemu-devel@nongnu.org; Thu, 27 Feb 2025 09:22:37 -0500 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1740666155; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=rpP0mKR1bYf8x/BopqJJucrB8oxIRdemZl6JUWYmoLk=; b=FOpKrbpxgszyryqLe4YdgRxtHnZDr6wwya219/k1IYQOZ3NoVlpXlPMlVsw4fUctGXEUjt e5xK3A/BeV8FTE+37SYZTieqGOWV5yT6ZUBpRDupVOFAJQyBcdNom9Dlq+z68vtYXDiQqv 9rQNjFhxzU2idMMThHOW5RTRqdn+cv0= Received: from mail-ej1-f72.google.com (mail-ej1-f72.google.com [209.85.218.72]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-679-CIdWP2I5P8ij9o5Mj7lbqg-1; Thu, 27 Feb 2025 09:22:34 -0500 X-MC-Unique: CIdWP2I5P8ij9o5Mj7lbqg-1 X-Mimecast-MFC-AGG-ID: CIdWP2I5P8ij9o5Mj7lbqg_1740666153 Received: by mail-ej1-f72.google.com with SMTP id a640c23a62f3a-abecbdb4272so119852666b.0 for ; Thu, 27 Feb 2025 06:22:34 -0800 (PST) X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1740666152; x=1741270952; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=rpP0mKR1bYf8x/BopqJJucrB8oxIRdemZl6JUWYmoLk=; b=icSwCFl6mNFBE5aXiQYzBBKtrKnlS3Vrl1617s+jz1197CBD1sr48Tr2Je1YYbZs/W 88g9VTMBSl5TJLi1nAnR6IYVj5KTx679LvftcaCol98gP8nvlt2qXRnV716qDtXUbu2o Vo7OmkzEyV83aewObYIBjfe0t6zjlEtHaH4pR3sqF6yKQ0nOWgeiPW2kNmgkdM0XwtQz MjvbqNn8qF9EIDPq8XQoGDBOZgNFF+K9wVcTV4VCMWeccmd3I+6Pl01pjS5hkLn3Ffu1 MiY1Egm9TRK5uigfB2aLQIVrQRmmhZfaR4CE2dFjmv48uMOULMp6q6DjCVQNjqSNtex4 kkHg== X-Gm-Message-State: AOJu0YyZBSSwkZlb4W/52vUUNd0bEkVECpwSOemT77F++D7eRX30Lem8 76SXEyMIBSw/mGBf7q5OrBqYTUds63KtCbuuSQC8nCAaLVLy5vqVmnrOP+MQwGVNspwCc3bQWz6 OEUKcXfIE32MwC5MA0V03qUdgq5tU9GqCp8Kjntf1YLI3bgpxOIEj1i0Pt9NPCT2r0Yv0QvF5j1 NNXuYCtPWwv1W5GCyfZHAOTgQrVLl+hvFDgcRMBbM= X-Gm-Gg: ASbGncuH3Cj77cwYA0YFOsVqbtjDzZhRWcA906FaEYAOF20bkpqHIuUbRS90HlezwAi hHmVRupSYi1wpqJk1hiVFPARz5r2fF0dPzZmLIr6f5MZDz0QiMg0bbYcji4kxv8grEEqHq2t+NT 69J0bN+VUnfwB5Ae2js11ok9NmUZoRZ+GllJ3U7x4Hmpcvx8odlBM2LxwK2OXFREKWkRYMPLKIP hVrUEOUrQW6/4me3vYUtwgHnUXzAvw427N44mgT00SGExQD8JzxbyPR+TqYS61MtPR+TvVV51m/ QrF24JIeDF0Y3NgbNsrs X-Received: by 2002:a17:907:9686:b0:ab7:d7fd:6250 with SMTP id a640c23a62f3a-abed1015488mr1399571166b.43.1740666152606; Thu, 27 Feb 2025 06:22:32 -0800 (PST) X-Google-Smtp-Source: AGHT+IFvCk74a5ejhjBllkAOfm++110zW0HlAe/VNXfUAjWC6HXkOqOgZGXaU+RkRq9U/kJeZk+vSA== X-Received: by 2002:a17:907:9686:b0:ab7:d7fd:6250 with SMTP id a640c23a62f3a-abed1015488mr1399568666b.43.1740666152200; Thu, 27 Feb 2025 06:22:32 -0800 (PST) Received: from [192.168.10.48] ([176.206.102.52]) by smtp.gmail.com with ESMTPSA id a640c23a62f3a-abf0c0dbc43sm131935466b.51.2025.02.27.06.22.30 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 27 Feb 2025 06:22:30 -0800 (PST) From: Paolo Bonzini To: qemu-devel@nongnu.org Cc: qemu-rust@nongnu.org, zhao1.liu@intel.com Subject: [PATCH 05/12] rust: irq: wrap IRQState with Opaque<> Date: Thu, 27 Feb 2025 15:22:12 +0100 Message-ID: <20250227142219.812270-6-pbonzini@redhat.com> X-Mailer: git-send-email 2.48.1 In-Reply-To: <20250227142219.812270-1-pbonzini@redhat.com> References: <20250227142219.812270-1-pbonzini@redhat.com> MIME-Version: 1.0 Received-SPF: pass client-ip=170.10.129.124; envelope-from=pbonzini@redhat.com; helo=us-smtp-delivery-124.mimecast.com X-Spam_score_int: -24 X-Spam_score: -2.5 X-Spam_bar: -- X-Spam_report: (-2.5 / 5.0 requ) BAYES_00=-1.9, DKIMWL_WL_HIGH=-0.438, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_NONE=-0.0001, RCVD_IN_MSPIKE_H5=0.001, RCVD_IN_MSPIKE_WL=0.001, RCVD_IN_VALIDITY_CERTIFIED_BLOCKED=0.001, RCVD_IN_VALIDITY_RPBL_BLOCKED=0.001, SPF_HELO_NONE=0.001, SPF_PASS=-0.001 autolearn=ham autolearn_force=no X-Spam_action: no action X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org Sender: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org Signed-off-by: Paolo Bonzini --- rust/qemu-api/src/irq.rs | 15 ++++++++++----- rust/qemu-api/src/sysbus.rs | 1 + 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/rust/qemu-api/src/irq.rs b/rust/qemu-api/src/irq.rs index 34c19263c23..1222d4fde30 100644 --- a/rust/qemu-api/src/irq.rs +++ b/rust/qemu-api/src/irq.rs @@ -8,10 +8,16 @@ use crate::{ bindings::{self, qemu_set_irq}, + cell::Opaque, prelude::*, qom::ObjectClass, }; +/// An opaque wrapper around [`bindings::IRQState`]. +#[repr(transparent)] +#[derive(Debug, qemu_api_macros::Wrapper)] +pub struct IRQState(Opaque); + /// Interrupt sources are used by devices to pass changes to a value (typically /// a boolean). The interrupt sink is usually an interrupt controller or /// GPIO controller. @@ -21,8 +27,7 @@ /// method sends a `true` value to the sink. If the guest has to see a /// different polarity, that change is performed by the board between the /// device and the interrupt controller. -pub type IRQState = bindings::IRQState; - +/// /// Interrupts are implemented as a pointer to the interrupt "sink", which has /// type [`IRQState`]. A device exposes its source as a QOM link property using /// a function such as [`SysBusDeviceMethods::init_irq`], and @@ -40,7 +45,7 @@ pub struct InterruptSource where c_int: From, { - cell: BqlCell<*mut IRQState>, + cell: BqlCell<*mut bindings::IRQState>, _marker: PhantomData, } @@ -79,11 +84,11 @@ pub fn set(&self, level: T) { } } - pub(crate) const fn as_ptr(&self) -> *mut *mut IRQState { + pub(crate) const fn as_ptr(&self) -> *mut *mut bindings::IRQState { self.cell.as_ptr() } - pub(crate) const fn slice_as_ptr(slice: &[Self]) -> *mut *mut IRQState { + pub(crate) const fn slice_as_ptr(slice: &[Self]) -> *mut *mut bindings::IRQState { assert!(!slice.is_empty()); slice[0].as_ptr() } diff --git a/rust/qemu-api/src/sysbus.rs b/rust/qemu-api/src/sysbus.rs index 04821a2b9b3..48803a655f9 100644 --- a/rust/qemu-api/src/sysbus.rs +++ b/rust/qemu-api/src/sysbus.rs @@ -79,6 +79,7 @@ fn mmio_map(&self, id: u32, addr: u64) { fn connect_irq(&self, id: u32, irq: &Owned) { assert!(bql_locked()); let id: i32 = id.try_into().unwrap(); + let irq: &IRQState = irq; unsafe { bindings::sysbus_connect_irq(self.as_mut_ptr(), id, irq.as_mut_ptr()); } From patchwork Thu Feb 27 14:22:13 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Paolo Bonzini X-Patchwork-Id: 13994667 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.lore.kernel.org (Postfix) with ESMTPS id 6EA0AC19F32 for ; Thu, 27 Feb 2025 14:29:18 +0000 (UTC) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1tneoD-0006gP-1w; Thu, 27 Feb 2025 09:24:21 -0500 Received: from eggs.gnu.org ([2001:470:142:3::10]) by lists.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1tnemh-0003t5-CT for qemu-devel@nongnu.org; Thu, 27 Feb 2025 09:22:44 -0500 Received: from us-smtp-delivery-124.mimecast.com ([170.10.129.124]) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1tnemf-00047c-0j for qemu-devel@nongnu.org; Thu, 27 Feb 2025 09:22:42 -0500 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1740666159; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=tXHZ7ahE0SuDjTAp4gMKpg+0aMsCMDD4X5FjTPi4lj4=; b=V1VlqHXcsqUEgl4q5+CkWsZKQcR+SFgUIeJEM84JUIreNB9fNFrpYy+VQZb4X79/jOwLap 0FcqR468zMa+3kD5spH10vFmAIKch8UqV2tlQUJkWcNehQsffyCHwDSIy10GFUg9r2GB14 HpY8uIwlga9BEo62x+RG5rGQsh64/9A= Received: from mail-ej1-f70.google.com (mail-ej1-f70.google.com [209.85.218.70]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-93-EYidEQP2PiyUowx354ZfDw-1; Thu, 27 Feb 2025 09:22:38 -0500 X-MC-Unique: EYidEQP2PiyUowx354ZfDw-1 X-Mimecast-MFC-AGG-ID: EYidEQP2PiyUowx354ZfDw_1740666156 Received: by mail-ej1-f70.google.com with SMTP id a640c23a62f3a-abb7e837a7aso112977566b.3 for ; Thu, 27 Feb 2025 06:22:37 -0800 (PST) X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1740666155; x=1741270955; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=tXHZ7ahE0SuDjTAp4gMKpg+0aMsCMDD4X5FjTPi4lj4=; b=wEqyZYXL2dZ6D+WLb/yoRKnnhnuTiLolaLssP4fIFPeyqU+qfRPkEtq57dAbGhTg5a mFqKgNAWLcJKLAuzCgOdoR7RPngG18jXDdd6bkwwn27UB2HKwkJ4Wxv8H+e8JQc3C3nA sn3zjl2H6xMQDQHhlkdzqPDTAS3Hy5CVFAXNNDk8XrZjANvgy+oz1tQyNO1ZWhRNCdJA TZqK0W6PG3DXR5OURVwV5d0kygtB+w+7Vs5VvSkZd4VsU9irZlmkYY09Jz4jMlObl5+i b/Xe/OnnymJ3st7EXpiwOFeX9ccXWEBMCgcgvfMdPhv3GPIoluDoMSsX9DY+uw3xPRJ9 OnaA== X-Gm-Message-State: AOJu0YzLHwbIUph9WVD0IfI+13+yIgBdo8542VAkR4mE4KrBws2EWUTf 4uCCeGHTd0sCuQ2SRMSQyLUaCSrqj+IkbSsibBB7xm7tpoj6LPo/yr+tjoSSJeX5vuefQ/qtcY/ IfPGTcR6Ug/pTyGoWhQxDuwVix/uB6dO6JdIqCu1p/GzVFzOyIPkSXt+pj6Cxo+xr6G0HXYGJ5B ZPN7yoFnPKL9Z2RSSRTx4S62tugI8SSyu0VeSRdh0= X-Gm-Gg: ASbGncsryex07mTqkr/5tBPoeTled1qrnO7YnlXQFvr5DRvPuevgBHH1MI1Tg9fVSHn P/5F2Oz237aWH0eu/qmz1M8la603/jgNpWGbVW74K3GFm+xfS1coLPe/MkP+fWxQBZcxt5NA5U7 WZ3UPHcuPJJn70NSVbuXZ69hSL2Ql/QBTki5SJo5q9Xx36OE41fv8dI7mpXna1x3eNCyss3ziuD iR69VYAHirZkE9OPeceDsYi90z7HK6dlPFRVS4XBPcWexnB6pSImOego343Vm6vigF9ImJrexaV ZjQ7qSbtMuPzX+NQrEAB X-Received: by 2002:a17:907:96a5:b0:ab7:fbb2:b47c with SMTP id a640c23a62f3a-abc09c1a51dmr3073941166b.35.1740666154847; Thu, 27 Feb 2025 06:22:34 -0800 (PST) X-Google-Smtp-Source: AGHT+IF8W9WmasNs4OKJbm4Y1M3y+D2krJAGkB7w6y4aLrIrrp8CdNeeKERQYmZcCAQRy1rDqxjJqQ== X-Received: by 2002:a17:907:96a5:b0:ab7:fbb2:b47c with SMTP id a640c23a62f3a-abc09c1a51dmr3073937366b.35.1740666154343; Thu, 27 Feb 2025 06:22:34 -0800 (PST) Received: from [192.168.10.48] ([176.206.102.52]) by smtp.gmail.com with ESMTPSA id a640c23a62f3a-abf0c7c07d3sm128139866b.180.2025.02.27.06.22.32 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 27 Feb 2025 06:22:32 -0800 (PST) From: Paolo Bonzini To: qemu-devel@nongnu.org Cc: qemu-rust@nongnu.org, zhao1.liu@intel.com Subject: [PATCH 06/12] rust: qom: wrap Object with Opaque<> Date: Thu, 27 Feb 2025 15:22:13 +0100 Message-ID: <20250227142219.812270-7-pbonzini@redhat.com> X-Mailer: git-send-email 2.48.1 In-Reply-To: <20250227142219.812270-1-pbonzini@redhat.com> References: <20250227142219.812270-1-pbonzini@redhat.com> MIME-Version: 1.0 Received-SPF: pass client-ip=170.10.129.124; envelope-from=pbonzini@redhat.com; helo=us-smtp-delivery-124.mimecast.com X-Spam_score_int: -24 X-Spam_score: -2.5 X-Spam_bar: -- X-Spam_report: (-2.5 / 5.0 requ) BAYES_00=-1.9, DKIMWL_WL_HIGH=-0.438, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_NONE=-0.0001, RCVD_IN_MSPIKE_H5=0.001, RCVD_IN_MSPIKE_WL=0.001, RCVD_IN_VALIDITY_CERTIFIED_BLOCKED=0.001, RCVD_IN_VALIDITY_RPBL_BLOCKED=0.001, SPF_HELO_NONE=0.001, SPF_PASS=-0.001 autolearn=unavailable autolearn_force=no X-Spam_action: no action X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org Sender: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org Reviewed-by: Zhao Liu Signed-off-by: Paolo Bonzini --- rust/qemu-api/src/bindings.rs | 3 --- rust/qemu-api/src/memory.rs | 2 +- rust/qemu-api/src/qdev.rs | 6 +++--- rust/qemu-api/src/qom.rs | 35 ++++++++++++++++++++++------------- 4 files changed, 26 insertions(+), 20 deletions(-) diff --git a/rust/qemu-api/src/bindings.rs b/rust/qemu-api/src/bindings.rs index d2868639ff6..be6dd68c09c 100644 --- a/rust/qemu-api/src/bindings.rs +++ b/rust/qemu-api/src/bindings.rs @@ -46,9 +46,6 @@ unsafe impl Sync for MemoryRegion {} unsafe impl Send for ObjectClass {} unsafe impl Sync for ObjectClass {} -unsafe impl Send for Object {} -unsafe impl Sync for Object {} - unsafe impl Send for SysBusDevice {} unsafe impl Sync for SysBusDevice {} diff --git a/rust/qemu-api/src/memory.rs b/rust/qemu-api/src/memory.rs index 682951ab44e..713c494ca2e 100644 --- a/rust/qemu-api/src/memory.rs +++ b/rust/qemu-api/src/memory.rs @@ -157,7 +157,7 @@ unsafe fn do_init_io( let cstr = CString::new(name).unwrap(); memory_region_init_io( slot, - owner.cast::(), + owner.cast::(), ops, owner.cast::(), cstr.as_ptr(), diff --git a/rust/qemu-api/src/qdev.rs b/rust/qemu-api/src/qdev.rs index c136457090c..1a4d1f38762 100644 --- a/rust/qemu-api/src/qdev.rs +++ b/rust/qemu-api/src/qdev.rs @@ -52,7 +52,7 @@ pub trait ResettablePhasesImpl { /// can be downcasted to type `T`. We also expect the device is /// readable/writeable from one thread at any time. unsafe extern "C" fn rust_resettable_enter_fn( - obj: *mut Object, + obj: *mut bindings::Object, typ: ResetType, ) { let state = NonNull::new(obj).unwrap().cast::(); @@ -65,7 +65,7 @@ pub trait ResettablePhasesImpl { /// can be downcasted to type `T`. We also expect the device is /// readable/writeable from one thread at any time. unsafe extern "C" fn rust_resettable_hold_fn( - obj: *mut Object, + obj: *mut bindings::Object, typ: ResetType, ) { let state = NonNull::new(obj).unwrap().cast::(); @@ -78,7 +78,7 @@ pub trait ResettablePhasesImpl { /// can be downcasted to type `T`. We also expect the device is /// readable/writeable from one thread at any time. unsafe extern "C" fn rust_resettable_exit_fn( - obj: *mut Object, + obj: *mut bindings::Object, typ: ResetType, ) { let state = NonNull::new(obj).unwrap().cast::(); diff --git a/rust/qemu-api/src/qom.rs b/rust/qemu-api/src/qom.rs index 5488643a2fd..2defbd23516 100644 --- a/rust/qemu-api/src/qom.rs +++ b/rust/qemu-api/src/qom.rs @@ -101,16 +101,24 @@ ptr::NonNull, }; -pub use bindings::{Object, ObjectClass}; +pub use bindings::ObjectClass; use crate::{ bindings::{ self, object_class_dynamic_cast, object_dynamic_cast, object_get_class, object_get_typename, object_new, object_ref, object_unref, TypeInfo, }, - cell::bql_locked, + cell::{bql_locked, Opaque}, }; +/// A safe wrapper around [`bindings::Object`]. +#[repr(transparent)] +#[derive(Debug, qemu_api_macros::Wrapper)] +pub struct Object(Opaque); + +unsafe impl Send for Object {} +unsafe impl Sync for Object {} + /// Marker trait: `Self` can be statically upcasted to `P` (i.e. `P` is a direct /// or indirect parent of `Self`). /// @@ -199,7 +207,7 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { } } -unsafe extern "C" fn rust_instance_init(obj: *mut Object) { +unsafe extern "C" fn rust_instance_init(obj: *mut bindings::Object) { let mut state = NonNull::new(obj).unwrap().cast::(); // SAFETY: obj is an instance of T, since rust_instance_init // is called from QOM core as the instance_init function @@ -209,7 +217,7 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { } } -unsafe extern "C" fn rust_instance_post_init(obj: *mut Object) { +unsafe extern "C" fn rust_instance_post_init(obj: *mut bindings::Object) { let state = NonNull::new(obj).unwrap().cast::(); // SAFETY: obj is an instance of T, since rust_instance_post_init // is called from QOM core as the instance_post_init function @@ -230,7 +238,7 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { ::CLASS_INIT(unsafe { klass.as_mut() }) } -unsafe extern "C" fn drop_object(obj: *mut Object) { +unsafe extern "C" fn drop_object(obj: *mut bindings::Object) { // SAFETY: obj is an instance of T, since drop_object is called // from the QOM core function object_deinit() as the instance_finalize // function for class T. Note that while object_deinit() will drop the @@ -280,14 +288,14 @@ pub unsafe trait ObjectType: Sized { /// Return the receiver as an Object. This is always safe, even /// if this type represents an interface. fn as_object(&self) -> &Object { - unsafe { &*self.as_object_ptr() } + unsafe { &*self.as_ptr().cast() } } /// Return the receiver as a const raw pointer to Object. /// This is preferrable to `as_object_mut_ptr()` if a C /// function only needs a `const Object *`. - fn as_object_ptr(&self) -> *const Object { - self.as_ptr().cast() + fn as_object_ptr(&self) -> *const bindings::Object { + self.as_object().as_ptr() } /// Return the receiver as a mutable raw pointer to Object. @@ -297,8 +305,8 @@ fn as_object_ptr(&self) -> *const Object { /// This cast is always safe, but because the result is mutable /// and the incoming reference is not, this should only be used /// for calls to C functions, and only if needed. - unsafe fn as_object_mut_ptr(&self) -> *mut Object { - self.as_object_ptr() as *mut _ + unsafe fn as_object_mut_ptr(&self) -> *mut bindings::Object { + self.as_object().as_mut_ptr() } } @@ -621,7 +629,7 @@ pub trait ObjectImpl: ObjectType + IsA { /// We expect the FFI user of this function to pass a valid pointer that /// can be downcasted to type `T`. We also expect the device is /// readable/writeable from one thread at any time. -unsafe extern "C" fn rust_unparent_fn(dev: *mut Object) { +unsafe extern "C" fn rust_unparent_fn(dev: *mut bindings::Object) { let state = NonNull::new(dev).unwrap().cast::(); T::UNPARENT.unwrap()(unsafe { state.as_ref() }); } @@ -796,8 +804,9 @@ fn new() -> Owned { // SAFETY: the object created by object_new is allocated on // the heap and has a reference count of 1 unsafe { - let obj = &*object_new(Self::TYPE_NAME.as_ptr()); - Owned::from_raw(obj.unsafe_cast::()) + let raw_obj = object_new(Self::TYPE_NAME.as_ptr()); + let obj = Object::from_raw(raw_obj).unsafe_cast::(); + Owned::from_raw(obj) } } } From patchwork Thu Feb 27 14:22:14 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Paolo Bonzini X-Patchwork-Id: 13994664 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.lore.kernel.org (Postfix) with ESMTPS id F29A6C1B0FF for ; Thu, 27 Feb 2025 14:28:32 +0000 (UTC) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1tnep8-0000Wx-5r; Thu, 27 Feb 2025 09:25:14 -0500 Received: from eggs.gnu.org ([2001:470:142:3::10]) by lists.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1tnemk-0003vY-Bw for qemu-devel@nongnu.org; Thu, 27 Feb 2025 09:22:47 -0500 Received: from us-smtp-delivery-124.mimecast.com ([170.10.129.124]) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1tnemg-00047i-6U for qemu-devel@nongnu.org; Thu, 27 Feb 2025 09:22:44 -0500 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1740666159; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=SqsGJNftWM1nTyRVPF20AlSEyETSkxx30EnRjrvmmVk=; b=EUx4GtCwUrNQT4uV3UeLah1YuxLTkeUSveNmOnGafZbmpd91Qf3WRhcwnaAK8yG/Jxsaxx JWFVPqQkTs+nmHKyo66foD8QQnf3FnzRaSLVy9wtUjkFOOK0WeJnwE9oaEAudU3W/VC5nT RSUR14gwHNbgJMysLP+aUjWZUIA/zOs= Received: from mail-ed1-f72.google.com (mail-ed1-f72.google.com [209.85.208.72]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-573-vUQspwHNMFqqpJuZCCsGQw-1; Thu, 27 Feb 2025 09:22:38 -0500 X-MC-Unique: vUQspwHNMFqqpJuZCCsGQw-1 X-Mimecast-MFC-AGG-ID: vUQspwHNMFqqpJuZCCsGQw_1740666157 Received: by mail-ed1-f72.google.com with SMTP id 4fb4d7f45d1cf-5e4c2618332so1107462a12.2 for ; Thu, 27 Feb 2025 06:22:38 -0800 (PST) X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1740666156; x=1741270956; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=SqsGJNftWM1nTyRVPF20AlSEyETSkxx30EnRjrvmmVk=; b=EiSZBNhM4pqQv8enSX7xlITZg1Cy4j2PniupRU0tX1Ilcw4kbG75S+a0iR5Cfbcdmp FBNu8nE2V+aJczOr0b6XDT4oTc7I2a9sj5p2FBuQCSvqdAXNnNArs63GkZwLNkCE8gx6 gumecOO9VsS5smlCUHD/k57PVTsnZtE1ek1trww9SxLnSE92XfezQ2o9Ac8dX8COimxr JQegz8XYRHfhcEOvUXpEkhCA5aH++zlCKwEgAMMcYD30dv4ODMckI1meb+x3JsOIt/+7 nHAp4OWwvpBduAWtlQ5k6FWiZELFrIUKng76nStcfgOnhuWLxmV+3Z7M7ygryYqeu5T7 h0dw== X-Gm-Message-State: AOJu0YxzLXpU9PuIAirIo2pByRCA07+ypg1rA4GKAV7zoAsBEyrrfSrJ VnFnvOUOLdIB3UzJuabvj06fx7AEY8Qm+wWaNo0TrOj+ESCHPgwCcHgLarY8Vf8THvWnyBkojWA B4UKg4EdMf9A/jgnu6MR/Gt/ovWtT1dtxarULXtaaetND80EGZef5CbN5PITUZux5ACVUcx4KFN pMmiQ7SUsZCkG0+FVmc4+nLrU2S5Kaw8SSDQ9Y/pA= X-Gm-Gg: ASbGncvPC+EZSrucH+uUkHl5j0turwvxIxvZjih6Bq5MQ99nGvcW2Kx4g2j/Q6x13UI b10vUH4Pi/h6p4vG3nXgvKcrQ+VJOoHwDmkYtUDPA7D2xLnHxrT+J7gNTv+PIBERM0Cd+++TmJz 4KVar+cb1lnfPhpVbsE2o57jtr3xtqSCGyJ3AQC+1W1LOfZV2mS2tYZWamSCHuvulte9gFU8mnZ siTyLt5BkrxvHLgl8qNuhDoUi2hovDhtZjOf6HsyjGGxwXhHdIFxTeItoKRr7yP6m02kOdZVm+I A32AhfOPYEI3AKf1dUfN X-Received: by 2002:a05:6402:34cc:b0:5dc:cfc5:9305 with SMTP id 4fb4d7f45d1cf-5e4a0dfc8b9mr10205882a12.25.1740666156019; Thu, 27 Feb 2025 06:22:36 -0800 (PST) X-Google-Smtp-Source: AGHT+IEt5tifUuWydQe9FjasbN85GQHxx7XGc/bzgRzWf7B0XQ8CpJE7Upl33nh2rpO4mokmAd21rg== X-Received: by 2002:a05:6402:34cc:b0:5dc:cfc5:9305 with SMTP id 4fb4d7f45d1cf-5e4a0dfc8b9mr10205850a12.25.1740666155468; Thu, 27 Feb 2025 06:22:35 -0800 (PST) Received: from [192.168.10.48] ([176.206.102.52]) by smtp.gmail.com with ESMTPSA id 4fb4d7f45d1cf-5e4c3b4aa51sm1150322a12.12.2025.02.27.06.22.34 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 27 Feb 2025 06:22:35 -0800 (PST) From: Paolo Bonzini To: qemu-devel@nongnu.org Cc: qemu-rust@nongnu.org, zhao1.liu@intel.com Subject: [PATCH 07/12] rust: qdev: wrap Clock and DeviceState with Opaque<> Date: Thu, 27 Feb 2025 15:22:14 +0100 Message-ID: <20250227142219.812270-8-pbonzini@redhat.com> X-Mailer: git-send-email 2.48.1 In-Reply-To: <20250227142219.812270-1-pbonzini@redhat.com> References: <20250227142219.812270-1-pbonzini@redhat.com> MIME-Version: 1.0 Received-SPF: pass client-ip=170.10.129.124; envelope-from=pbonzini@redhat.com; helo=us-smtp-delivery-124.mimecast.com X-Spam_score_int: -24 X-Spam_score: -2.5 X-Spam_bar: -- X-Spam_report: (-2.5 / 5.0 requ) BAYES_00=-1.9, DKIMWL_WL_HIGH=-0.438, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_NONE=-0.0001, RCVD_IN_MSPIKE_H5=0.001, RCVD_IN_MSPIKE_WL=0.001, RCVD_IN_VALIDITY_CERTIFIED_BLOCKED=0.001, RCVD_IN_VALIDITY_RPBL_BLOCKED=0.001, SPF_HELO_NONE=0.001, SPF_PASS=-0.001 autolearn=unavailable autolearn_force=no X-Spam_action: no action X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org Sender: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org Reviewed-by: Zhao Liu Signed-off-by: Paolo Bonzini --- rust/qemu-api/src/bindings.rs | 6 ---- rust/qemu-api/src/qdev.rs | 68 ++++++++++++++++++++++++----------- rust/qemu-api/src/vmstate.rs | 2 +- 3 files changed, 49 insertions(+), 27 deletions(-) diff --git a/rust/qemu-api/src/bindings.rs b/rust/qemu-api/src/bindings.rs index be6dd68c09c..6e70a75a0e6 100644 --- a/rust/qemu-api/src/bindings.rs +++ b/rust/qemu-api/src/bindings.rs @@ -34,12 +34,6 @@ unsafe impl Sync for CharBackend {} unsafe impl Send for Chardev {} unsafe impl Sync for Chardev {} -unsafe impl Send for Clock {} -unsafe impl Sync for Clock {} - -unsafe impl Send for DeviceState {} -unsafe impl Sync for DeviceState {} - unsafe impl Send for MemoryRegion {} unsafe impl Sync for MemoryRegion {} diff --git a/rust/qemu-api/src/qdev.rs b/rust/qemu-api/src/qdev.rs index 1a4d1f38762..1c4a67b5728 100644 --- a/rust/qemu-api/src/qdev.rs +++ b/rust/qemu-api/src/qdev.rs @@ -10,12 +10,12 @@ ptr::NonNull, }; -pub use bindings::{Clock, ClockEvent, DeviceClass, DeviceState, Property, ResetType}; +pub use bindings::{ClockEvent, DeviceClass, Property, ResetType}; use crate::{ bindings::{self, qdev_init_gpio_in, qdev_init_gpio_out, Error, ResettableClass}, callbacks::FnCall, - cell::bql_locked, + cell::{bql_locked, Opaque}, chardev::Chardev, irq::InterruptSource, prelude::*, @@ -23,6 +23,22 @@ vmstate::VMStateDescription, }; +/// A safe wrapper around [`bindings::Clock`]. +#[repr(transparent)] +#[derive(Debug, qemu_api_macros::Wrapper)] +pub struct Clock(Opaque); + +unsafe impl Send for Clock {} +unsafe impl Sync for Clock {} + +/// A safe wrapper around [`bindings::DeviceState`]. +#[repr(transparent)] +#[derive(Debug, qemu_api_macros::Wrapper)] +pub struct DeviceState(Opaque); + +unsafe impl Send for DeviceState {} +unsafe impl Sync for DeviceState {} + /// Trait providing the contents of the `ResettablePhases` struct, /// which is part of the QOM `Resettable` interface. pub trait ResettablePhasesImpl { @@ -117,7 +133,10 @@ fn vmsd() -> Option<&'static VMStateDescription> { /// We expect the FFI user of this function to pass a valid pointer that /// can be downcasted to type `T`. We also expect the device is /// readable/writeable from one thread at any time. -unsafe extern "C" fn rust_realize_fn(dev: *mut DeviceState, _errp: *mut *mut Error) { +unsafe extern "C" fn rust_realize_fn( + dev: *mut bindings::DeviceState, + _errp: *mut *mut Error, +) { let state = NonNull::new(dev).unwrap().cast::(); T::REALIZE.unwrap()(unsafe { state.as_ref() }); } @@ -251,7 +270,7 @@ fn init_clock_in FnCall<(&'a Self::Target, ClockEvent)>>( events: ClockEvent, ) -> Owned { fn do_init_clock_in( - dev: *mut DeviceState, + dev: &DeviceState, name: &str, cb: Option, events: ClockEvent, @@ -265,14 +284,15 @@ fn do_init_clock_in( unsafe { let cstr = CString::new(name).unwrap(); let clk = bindings::qdev_init_clock_in( - dev, + dev.as_mut_ptr(), cstr.as_ptr(), cb, - dev.cast::(), + dev.as_void_ptr(), events.0, ); - Owned::from(&*clk) + let clk: &Clock = Clock::from_raw(clk); + Owned::from(clk) } } @@ -289,7 +309,7 @@ fn do_init_clock_in( None }; - do_init_clock_in(self.as_mut_ptr(), name, cb, events) + do_init_clock_in(self.upcast(), name, cb, events) } /// Add an output clock named `name`. @@ -304,9 +324,10 @@ fn do_init_clock_in( fn init_clock_out(&self, name: &str) -> Owned { unsafe { let cstr = CString::new(name).unwrap(); - let clk = bindings::qdev_init_clock_out(self.as_mut_ptr(), cstr.as_ptr()); + let clk = bindings::qdev_init_clock_out(self.upcast().as_mut_ptr(), cstr.as_ptr()); - Owned::from(&*clk) + let clk: &Clock = Clock::from_raw(clk); + Owned::from(clk) } } @@ -314,7 +335,11 @@ fn prop_set_chr(&self, propname: &str, chr: &Owned) { assert!(bql_locked()); let c_propname = CString::new(propname).unwrap(); unsafe { - bindings::qdev_prop_set_chr(self.as_mut_ptr(), c_propname.as_ptr(), chr.as_mut_ptr()); + bindings::qdev_prop_set_chr( + self.upcast().as_mut_ptr(), + c_propname.as_ptr(), + chr.as_mut_ptr(), + ); } } @@ -323,8 +348,17 @@ fn init_gpio_in FnCall<(&'a Self::Target, u32, u32)>>( num_lines: u32, _cb: F, ) { - let _: () = F::ASSERT_IS_SOME; + fn do_init_gpio_in( + dev: &DeviceState, + num_lines: u32, + gpio_in_cb: unsafe extern "C" fn(*mut c_void, c_int, c_int), + ) { + unsafe { + qdev_init_gpio_in(dev.as_mut_ptr(), Some(gpio_in_cb), num_lines as c_int); + } + } + let _: () = F::ASSERT_IS_SOME; unsafe extern "C" fn rust_irq_handler FnCall<(&'a T, u32, u32)>>( opaque: *mut c_void, line: c_int, @@ -337,19 +371,13 @@ fn init_gpio_in FnCall<(&'a Self::Target, u32, u32)>>( let gpio_in_cb: unsafe extern "C" fn(*mut c_void, c_int, c_int) = rust_irq_handler::; - unsafe { - qdev_init_gpio_in( - self.as_mut_ptr::(), - Some(gpio_in_cb), - num_lines as c_int, - ); - } + do_init_gpio_in(self.upcast(), num_lines, gpio_in_cb); } fn init_gpio_out(&self, pins: &[InterruptSource]) { unsafe { qdev_init_gpio_out( - self.as_mut_ptr::(), + self.upcast().as_mut_ptr(), InterruptSource::slice_as_ptr(pins), pins.len() as c_int, ); diff --git a/rust/qemu-api/src/vmstate.rs b/rust/qemu-api/src/vmstate.rs index 1e7ba531e2a..f0510ae769d 100644 --- a/rust/qemu-api/src/vmstate.rs +++ b/rust/qemu-api/src/vmstate.rs @@ -470,7 +470,7 @@ macro_rules! vmstate_clock { $crate::assert_field_type!( $struct_name, $field_name, - $crate::qom::Owned<$crate::bindings::Clock> + $crate::qom::Owned<$crate::qdev::Clock> ); $crate::offset_of!($struct_name, $field_name) }, From patchwork Thu Feb 27 14:22:15 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Paolo Bonzini X-Patchwork-Id: 13994655 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.lore.kernel.org (Postfix) with ESMTPS id 77C2AC19F32 for ; Thu, 27 Feb 2025 14:26:58 +0000 (UTC) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1tnenG-0005gH-1O; Thu, 27 Feb 2025 09:23:25 -0500 Received: from eggs.gnu.org ([2001:470:142:3::10]) by lists.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1tnemk-0003vR-Ap for qemu-devel@nongnu.org; Thu, 27 Feb 2025 09:22:47 -0500 Received: from us-smtp-delivery-124.mimecast.com ([170.10.129.124]) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1tnemg-000480-8D for qemu-devel@nongnu.org; Thu, 27 Feb 2025 09:22:44 -0500 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1740666161; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=G4VqwNYiNiuTUzYwk2y50HzhW9i7JscSTGolkyuQe+I=; b=aJ7huADxQq09xuF1S4BUyntKPAjdmwiqSUm2A2nZroNoVGvlS0ypp0PFuEhJXO48EIJnap hMZM39q7Mpju8hEcda8/oOmS0kIxHQGEmp9hlloQZKiyUfD7Be5bIfnvAMFh5wbZECJTXE AnoTy4TIcmIpTV6JfMjnvIqmy0zEPtY= Received: from mail-ej1-f70.google.com (mail-ej1-f70.google.com [209.85.218.70]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-649-sX2gfNIvMEi_l_GnAFCv5g-1; Thu, 27 Feb 2025 09:22:40 -0500 X-MC-Unique: sX2gfNIvMEi_l_GnAFCv5g-1 X-Mimecast-MFC-AGG-ID: sX2gfNIvMEi_l_GnAFCv5g_1740666159 Received: by mail-ej1-f70.google.com with SMTP id a640c23a62f3a-aa6b904a886so89225966b.0 for ; Thu, 27 Feb 2025 06:22:40 -0800 (PST) X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1740666158; x=1741270958; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=G4VqwNYiNiuTUzYwk2y50HzhW9i7JscSTGolkyuQe+I=; b=AAcQaA4MW2NKrBrClk/VSrQ4wuAu8x1ZnGS7j2JG/ijC9qKVRvrxqfTs62B1rfNhjw xoj+DLDCVPAV4uK83pWcK4FfAm3oDYUxViuPoMcwkIBQgFbz5Y97cH2VGdv0obOVmrIa cWBp+2QM7+WGHDSun2di5imaNd1C62nCbwl13+2az3cgMSyPzR05dSYG4TuK4fwsAV1y T26F0UuTiPrEXIGazflDTgbaoys+f3qIytS4pzDvCGG9ymolnOKYEa0gZtnQ9rmSpuiT KVVnI+PTOUFGCqP3KuQ4RETFFGq4olBuZaV6fbsdKPc6e71g2gxpGEcjCTPFiWpGcrQF +hzw== X-Gm-Message-State: AOJu0Yw/86QjnbrR4f+MEem6jxLiGyq/BwMVKx6HCYr/EyA2KcaY3eX1 FQpA6WkwhvRkizHfTjLb1b65Yslu/18DEoGL8GNnN1wK3XnHbrT3PrryNjzOe0Eja/HFcxEITqv MlMQOYD0im0dhtdfrH9irn0XyW8K/CBepvKWnDhIBn2u6PmN2y2YPk/zvVGgLps2a3rYRvvYk9M BaF3Ni4VkQ6QeoX93hueDcoFNpwkgrOpLfFSZPgJ4= X-Gm-Gg: ASbGncv0VQIRcwaXYUkEU0VBu5BHmxISNsehzRFol6jMVrtbKfdLKYUYcBth173UFKL 7tcjhgpFtu82Yh5ZKdifSXjMMIT3ZC3dEHk9ZbD/G8Ey6qDjzZLORPL0yo9zM8jvPZ6u0S20pTr vF8R1ycDcmlc1ejZsdAt5MrrB3OqbQsi7kEh6qz3tjdTOo8wSpnlqxukmx4m/W4lsMdPuYlMIac vDUkL74CF2CVCL8MRrMJ++T7iM/0kA04t6grStJy2hfCzWoDBMURkq+ACm7t++EZqIlDNK18+rF tYURajnHZB+ZABCiC3jn X-Received: by 2002:a17:906:3152:b0:ab7:d87f:665b with SMTP id a640c23a62f3a-abc0de4a2cemr2554979466b.48.1740666158163; Thu, 27 Feb 2025 06:22:38 -0800 (PST) X-Google-Smtp-Source: AGHT+IHvqN1jeEHL8v0Gq8g/eqXy/BrDmOdict2Vquc+f2bkWu2Ri45v5VoKyEwGFyHlGKflr5U15w== X-Received: by 2002:a17:906:3152:b0:ab7:d87f:665b with SMTP id a640c23a62f3a-abc0de4a2cemr2554976466b.48.1740666157672; Thu, 27 Feb 2025 06:22:37 -0800 (PST) Received: from [192.168.10.48] ([176.206.102.52]) by smtp.gmail.com with ESMTPSA id a640c23a62f3a-abf0c7bbfe2sm130718966b.171.2025.02.27.06.22.36 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 27 Feb 2025 06:22:36 -0800 (PST) From: Paolo Bonzini To: qemu-devel@nongnu.org Cc: qemu-rust@nongnu.org, zhao1.liu@intel.com Subject: [PATCH 08/12] rust: hpet: do not access fields of SysBusDevice Date: Thu, 27 Feb 2025 15:22:15 +0100 Message-ID: <20250227142219.812270-9-pbonzini@redhat.com> X-Mailer: git-send-email 2.48.1 In-Reply-To: <20250227142219.812270-1-pbonzini@redhat.com> References: <20250227142219.812270-1-pbonzini@redhat.com> MIME-Version: 1.0 Received-SPF: pass client-ip=170.10.129.124; envelope-from=pbonzini@redhat.com; helo=us-smtp-delivery-124.mimecast.com X-Spam_score_int: -24 X-Spam_score: -2.5 X-Spam_bar: -- X-Spam_report: (-2.5 / 5.0 requ) BAYES_00=-1.9, DKIMWL_WL_HIGH=-0.438, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_NONE=-0.0001, RCVD_IN_MSPIKE_H5=0.001, RCVD_IN_MSPIKE_WL=0.001, RCVD_IN_VALIDITY_CERTIFIED_BLOCKED=0.001, RCVD_IN_VALIDITY_RPBL_BLOCKED=0.001, SPF_HELO_NONE=0.001, SPF_PASS=-0.001 autolearn=unavailable autolearn_force=no X-Spam_action: no action X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org Sender: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org Fields of SysBusDevice must only be accessed with the BQL taken. Add a wrapper that verifies that. Signed-off-by: Paolo Bonzini --- rust/hw/timer/hpet/src/hpet.rs | 4 +--- rust/qemu-api/src/sysbus.rs | 12 ++++++++++++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/rust/hw/timer/hpet/src/hpet.rs b/rust/hw/timer/hpet/src/hpet.rs index ce4b289d0c8..a440c9f4cb9 100644 --- a/rust/hw/timer/hpet/src/hpet.rs +++ b/rust/hw/timer/hpet/src/hpet.rs @@ -724,8 +724,6 @@ fn realize(&self) { } fn reset_hold(&self, _type: ResetType) { - let sbd = self.upcast::(); - for timer in self.timers.iter().take(self.num_timers.get()) { timer.borrow_mut().reset(); } @@ -738,7 +736,7 @@ fn reset_hold(&self, _type: ResetType) { HPETFwConfig::update_hpet_cfg( self.hpet_id.get(), self.capability.get() as u32, - sbd.mmio[0].addr, + self.mmio_addr(0).unwrap(), ); // to document that the RTC lowers its output on reset as well diff --git a/rust/qemu-api/src/sysbus.rs b/rust/qemu-api/src/sysbus.rs index 48803a655f9..0790576d446 100644 --- a/rust/qemu-api/src/sysbus.rs +++ b/rust/qemu-api/src/sysbus.rs @@ -64,6 +64,18 @@ fn init_irq(&self, irq: &InterruptSource) { } } + // TODO: do we want a type like GuestAddress here? + fn mmio_addr(&self, id: u32) -> Option { + assert!(bql_locked()); + let sbd = self.upcast(); + let id: usize = id.try_into().unwrap(); + if sbd.mmio[id].memory.is_null() { + None + } else { + Some(sbd.mmio[id].addr) + } + } + // TODO: do we want a type like GuestAddress here? fn mmio_map(&self, id: u32, addr: u64) { assert!(bql_locked()); From patchwork Thu Feb 27 14:22:16 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Paolo Bonzini X-Patchwork-Id: 13994660 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.lore.kernel.org (Postfix) with ESMTPS id DE0B2C19F2E for ; Thu, 27 Feb 2025 14:27:36 +0000 (UTC) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1tnene-0006Bk-2t; Thu, 27 Feb 2025 09:23:47 -0500 Received: from eggs.gnu.org ([2001:470:142:3::10]) by lists.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1tneml-0003ws-10 for qemu-devel@nongnu.org; Thu, 27 Feb 2025 09:22:47 -0500 Received: from us-smtp-delivery-124.mimecast.com ([170.10.129.124]) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1tnemj-00048x-BY for qemu-devel@nongnu.org; Thu, 27 Feb 2025 09:22:46 -0500 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1740666164; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=Hp60NgzpFm3jMkNxot3ICZaotMUbZm/BSXyoCpaAV7I=; b=IRrzjMzAoa0JuMXZF/rYdg4teDGIC+ED70QEnv1ye3TGTz2M6nqVGri65oivnaminfflcE tvRVNbKpisBsl64WyO/EWuL0LzjSzudpW4a345iM3m1iuJ749VkraGWt1iHESlxhgn77jg 3crMOA+ISC5rgDqidvJOeXuMFVoD8u8= Received: from mail-ej1-f69.google.com (mail-ej1-f69.google.com [209.85.218.69]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-561-l3-G_ehtNSyYgacQzwog0w-1; Thu, 27 Feb 2025 09:22:43 -0500 X-MC-Unique: l3-G_ehtNSyYgacQzwog0w-1 X-Mimecast-MFC-AGG-ID: l3-G_ehtNSyYgacQzwog0w_1740666162 Received: by mail-ej1-f69.google.com with SMTP id a640c23a62f3a-abb61c30566so93711966b.2 for ; Thu, 27 Feb 2025 06:22:43 -0800 (PST) X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1740666161; x=1741270961; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=Hp60NgzpFm3jMkNxot3ICZaotMUbZm/BSXyoCpaAV7I=; b=oj6iMc3/7MDkZpeePrqGEQMNeikJyP6ygzm0ggG90e4cYCuSj8bE12GbnoxmD4Lg8P JBFrTOLoftRmLdSGj7ZVl5LusVgaIeELB/xUSwHWtFQvJVxKf6nJBwLcOWVOY5JZugE0 jE4KnQ+CzXQgrnGiSjVjV6r67gmMU2BdgjDgNG2LoXzts/6DPh202je4o+Oty016OInH Om1iqQr73137c7D2+//E96LOiGSwNpQJJKISK3TDa/tMCHYthPFFXH0ciUPgGTDSr+99 4C/ZcOiEm55aVMokHmHqNBlHK/IIdREg1/6351+/sZoRMJSNDSY9rThjudirr7Y8J0jF ED2g== X-Gm-Message-State: AOJu0Yxcb3YJETAbPOjcXYS3HdGiVQ1UIUokaAbf0ePO8CUj7ZuWN4+Q oI3N9hzdUo4eAW7m3TJ8dmCRCc9v4kOc4+S83PuzIFtipbiEA69NDPMKE5KJxlcB2Hs65vfV+IL 05F2F2ZQrbHb8xL1aYqMEd+uVRbRpDpU9hykOSPEywz/fqWoRlsDnUM+qaJKgTw92LS1mhrC5RP 0ckMjfIrRJ325BjIN2YVAl1azO19HCnBCuJH0rdy4= X-Gm-Gg: ASbGncuSehs8Yl+Xx51Lnmx+9iPqKqQh7to6HDi3pw/1EuplmKx5j4uOHm4zJZVnX16 MiXZCv3drVlO3ZAndTb6cJ55kj9Vjp0EF5D/gHTGtFU0SV1ulTWc3b1IxiTC1iQJSujqC4KTXTl YzAC/hK4fSWcrVf8EhLwMed8+si7h/OmUjzYLmb2Y/mrigGSLe55J0P4mJAX5P4Lom2uCySuSdP KGC7fHUpPgny3i9eV0qtgLXYP2q60MIgbVDTyI2oRCWZvApPM+XEyUL0PNkm4pfXaU5fQLCDdWS QRQ3vKTUIR0oZ9Pd2n0f X-Received: by 2002:a17:907:c407:b0:abc:4b7:e3d3 with SMTP id a640c23a62f3a-abeeedcfecbmr1035991966b.27.1740666160830; Thu, 27 Feb 2025 06:22:40 -0800 (PST) X-Google-Smtp-Source: AGHT+IGhkDzLZ7Rqvt7edxAJCDIQHcYGsOiEcgzSXzD9gNCicFHn6Ta7APVPqoxssTSBNlFJQ/LaWg== X-Received: by 2002:a17:907:c407:b0:abc:4b7:e3d3 with SMTP id a640c23a62f3a-abeeedcfecbmr1035988666b.27.1740666160328; Thu, 27 Feb 2025 06:22:40 -0800 (PST) Received: from [192.168.10.48] ([176.206.102.52]) by smtp.gmail.com with ESMTPSA id a640c23a62f3a-abf0c1165e7sm130130566b.82.2025.02.27.06.22.38 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 27 Feb 2025 06:22:38 -0800 (PST) From: Paolo Bonzini To: qemu-devel@nongnu.org Cc: qemu-rust@nongnu.org, zhao1.liu@intel.com Subject: [PATCH 09/12] rust: sysbus: wrap SysBusDevice with Opaque<> Date: Thu, 27 Feb 2025 15:22:16 +0100 Message-ID: <20250227142219.812270-10-pbonzini@redhat.com> X-Mailer: git-send-email 2.48.1 In-Reply-To: <20250227142219.812270-1-pbonzini@redhat.com> References: <20250227142219.812270-1-pbonzini@redhat.com> MIME-Version: 1.0 Received-SPF: pass client-ip=170.10.129.124; envelope-from=pbonzini@redhat.com; helo=us-smtp-delivery-124.mimecast.com X-Spam_score_int: -24 X-Spam_score: -2.5 X-Spam_bar: -- X-Spam_report: (-2.5 / 5.0 requ) BAYES_00=-1.9, DKIMWL_WL_HIGH=-0.438, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_NONE=-0.0001, RCVD_IN_MSPIKE_H5=0.001, RCVD_IN_MSPIKE_WL=0.001, RCVD_IN_VALIDITY_CERTIFIED_BLOCKED=0.001, RCVD_IN_VALIDITY_RPBL_BLOCKED=0.001, SPF_HELO_NONE=0.001, SPF_PASS=-0.001 autolearn=unavailable autolearn_force=no X-Spam_action: no action X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org Sender: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org Signed-off-by: Paolo Bonzini --- rust/qemu-api/src/bindings.rs | 3 --- rust/qemu-api/src/sysbus.rs | 29 +++++++++++++++++++++-------- 2 files changed, 21 insertions(+), 11 deletions(-) diff --git a/rust/qemu-api/src/bindings.rs b/rust/qemu-api/src/bindings.rs index 6e70a75a0e6..b791ca6d87f 100644 --- a/rust/qemu-api/src/bindings.rs +++ b/rust/qemu-api/src/bindings.rs @@ -40,9 +40,6 @@ unsafe impl Sync for MemoryRegion {} unsafe impl Send for ObjectClass {} unsafe impl Sync for ObjectClass {} -unsafe impl Send for SysBusDevice {} -unsafe impl Sync for SysBusDevice {} - // SAFETY: this is a pure data struct unsafe impl Send for CoalescedMemoryRange {} unsafe impl Sync for CoalescedMemoryRange {} diff --git a/rust/qemu-api/src/sysbus.rs b/rust/qemu-api/src/sysbus.rs index 0790576d446..e92502a8fe6 100644 --- a/rust/qemu-api/src/sysbus.rs +++ b/rust/qemu-api/src/sysbus.rs @@ -6,11 +6,11 @@ use std::{ffi::CStr, ptr::addr_of_mut}; -pub use bindings::{SysBusDevice, SysBusDeviceClass}; +pub use bindings::SysBusDeviceClass; use crate::{ bindings, - cell::bql_locked, + cell::{bql_locked, Opaque}, irq::{IRQState, InterruptSource}, memory::MemoryRegion, prelude::*, @@ -18,6 +18,14 @@ qom::Owned, }; +/// A safe wrapper around [`bindings::SysBusDevice`]. +#[repr(transparent)] +#[derive(Debug, qemu_api_macros::Wrapper)] +pub struct SysBusDevice(Opaque); + +unsafe impl Send for SysBusDevice {} +unsafe impl Sync for SysBusDevice {} + unsafe impl ObjectType for SysBusDevice { type Class = SysBusDeviceClass; const TYPE_NAME: &'static CStr = @@ -49,7 +57,7 @@ pub trait SysBusDeviceMethods: ObjectDeref fn init_mmio(&self, iomem: &MemoryRegion) { assert!(bql_locked()); unsafe { - bindings::sysbus_init_mmio(self.as_mut_ptr(), iomem.as_mut_ptr()); + bindings::sysbus_init_mmio(self.upcast().as_mut_ptr(), iomem.as_mut_ptr()); } } @@ -60,14 +68,16 @@ fn init_mmio(&self, iomem: &MemoryRegion) { fn init_irq(&self, irq: &InterruptSource) { assert!(bql_locked()); unsafe { - bindings::sysbus_init_irq(self.as_mut_ptr(), irq.as_ptr()); + bindings::sysbus_init_irq(self.upcast().as_mut_ptr(), irq.as_ptr()); } } // TODO: do we want a type like GuestAddress here? fn mmio_addr(&self, id: u32) -> Option { assert!(bql_locked()); - let sbd = self.upcast(); + // SAFETY: the BQL ensures that no one else writes to sbd.mmio[], and + // the SysBusDevice must be initialized to get an IsA. + let sbd = unsafe { *self.upcast().as_ptr() }; let id: usize = id.try_into().unwrap(); if sbd.mmio[id].memory.is_null() { None @@ -81,7 +91,7 @@ fn mmio_map(&self, id: u32, addr: u64) { assert!(bql_locked()); let id: i32 = id.try_into().unwrap(); unsafe { - bindings::sysbus_mmio_map(self.as_mut_ptr(), id, addr); + bindings::sysbus_mmio_map(self.upcast().as_mut_ptr(), id, addr); } } @@ -93,7 +103,7 @@ fn connect_irq(&self, id: u32, irq: &Owned) { let id: i32 = id.try_into().unwrap(); let irq: &IRQState = irq; unsafe { - bindings::sysbus_connect_irq(self.as_mut_ptr(), id, irq.as_mut_ptr()); + bindings::sysbus_connect_irq(self.upcast().as_mut_ptr(), id, irq.as_mut_ptr()); } } @@ -101,7 +111,10 @@ fn sysbus_realize(&self) { // TODO: return an Error assert!(bql_locked()); unsafe { - bindings::sysbus_realize(self.as_mut_ptr(), addr_of_mut!(bindings::error_fatal)); + bindings::sysbus_realize( + self.upcast().as_mut_ptr(), + addr_of_mut!(bindings::error_fatal), + ); } } } From patchwork Thu Feb 27 14:22:17 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Paolo Bonzini X-Patchwork-Id: 13994659 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.lore.kernel.org (Postfix) with ESMTPS id 36D37C19F32 for ; Thu, 27 Feb 2025 14:27:33 +0000 (UTC) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1tneoX-00077G-Fv; Thu, 27 Feb 2025 09:24:37 -0500 Received: from eggs.gnu.org ([2001:470:142:3::10]) by lists.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1tnemm-0003zf-5u for qemu-devel@nongnu.org; Thu, 27 Feb 2025 09:22:48 -0500 Received: from us-smtp-delivery-124.mimecast.com ([170.10.129.124]) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1tnemk-00049E-EL for qemu-devel@nongnu.org; Thu, 27 Feb 2025 09:22:47 -0500 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1740666165; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=S8IXFl1tjzcTpL3RiOm0U3qS7SeRxt+gon+nIrKlE5k=; b=cNzbA9qVkydW6XyIEoSXEYSPL4YCrHQkxztx0jYvUlK3nRyVkkqK9ZJ0q5s2aej+SQriey yda9PCQye1h4c3vRXSG00SCbPGnT356Km5yrKTye/4ZCMjzfUWNQQWfvTM4252766a04Me svrXmntMiwgHa108UHaGdJM3Et4GHNc= Received: from mail-ej1-f69.google.com (mail-ej1-f69.google.com [209.85.218.69]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-149-V8MUClVmMmK0-IkIZc6vRg-1; Thu, 27 Feb 2025 09:22:44 -0500 X-MC-Unique: V8MUClVmMmK0-IkIZc6vRg-1 X-Mimecast-MFC-AGG-ID: V8MUClVmMmK0-IkIZc6vRg_1740666163 Received: by mail-ej1-f69.google.com with SMTP id a640c23a62f3a-abbba16956bso132130766b.2 for ; Thu, 27 Feb 2025 06:22:44 -0800 (PST) X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1740666162; x=1741270962; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=S8IXFl1tjzcTpL3RiOm0U3qS7SeRxt+gon+nIrKlE5k=; b=RVrCjnyic6lRWZo9sN0NPf2Fe5X5EFIz8RgQyiw4fyDeThWzBTINOO4tVWXR9vPMdE PZXbq0Z1M/+z9BbqQQcjNdxc9P+04AGAWJvNTwUKelJzFioPcTpDrKcxtZ6HvsH0WuhB wTqLVHo4WG9TboSv1QEfqhuyGYJAcExgfD/o+vrR+dKQtUJ7xElwCRjM8qsHB2QzKWvE x0kpTY85Pxt0pOuNwpWY0wY96zWhStUdA6cmKVjPlgm0IXzfdWHQi9KTsls/mCYALaF+ ZgOF++r4WKA3JXAF3UfKveJjJ2ENSvx6rxRdIa5fUcSKSbsdZHj46XBeYQAKs8fWuodI iyrA== X-Gm-Message-State: AOJu0YwD+Dv3yZBBkzJ0Cz1lH6LE5FiaFC2ZOFTHuDVXGb7kCTRAuQOs P7grFSkVmPMLlMBjxRVwZQlxMW4Q91hctBHtcfxM1SXx5B2NziKFj3ziJ51dQOI0hWn6H88x2EV 6LHH862PLfg7gYjvvw29sVinRJpLbSWQP6nYmdYOkvP9SRDTISmuz/2AsIPHZn6HQ5hmUDn/c/v NQcn5tMrJWIduwsGKcBPsqKYeens+hHZSQt+A3JD0= X-Gm-Gg: ASbGncvURJuqIenhvBx+Uw4fiQpkvQHCeD2zWtlvGD+FnnTWkMUgxrzmKqJXzeNd6/a swhU+N79Bq7TDu1Bn418UEux7e3xpdRR9ysvDD2xhEmElDMRAmSXWR1iXJZRYnQNliU/mS2nRBp Lc6dScxynDgjwL2eAB2MkMKuoA2H1o/Us1c1IOEeU7zr0TuH4p0UW9vDSk928HLJTk9PLKuXjVT f/dyL7A9eSjDFQNnvfA497iR2IVdYAZFwi5NcaV2AY5DqePYwhQmeqDqljzWKHvwFBC6laZs62I OWfgyTV4UU1KHJG7szAd X-Received: by 2002:a17:907:7710:b0:abb:6e07:3714 with SMTP id a640c23a62f3a-abed0c66ec7mr1325157666b.10.1740666161950; Thu, 27 Feb 2025 06:22:41 -0800 (PST) X-Google-Smtp-Source: AGHT+IHfH4DUS1aqoEPb8TbvHR8xTpCzsmC2z5Qrepw6+FBwsfJjKOd9cg0gRimz6jmdxtGHn68PWA== X-Received: by 2002:a17:907:7710:b0:abb:6e07:3714 with SMTP id a640c23a62f3a-abed0c66ec7mr1325154266b.10.1740666161492; Thu, 27 Feb 2025 06:22:41 -0800 (PST) Received: from [192.168.10.48] ([176.206.102.52]) by smtp.gmail.com with ESMTPSA id a640c23a62f3a-abf0c75af58sm129868666b.147.2025.02.27.06.22.40 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 27 Feb 2025 06:22:41 -0800 (PST) From: Paolo Bonzini To: qemu-devel@nongnu.org Cc: qemu-rust@nongnu.org, zhao1.liu@intel.com Subject: [PATCH 10/12] rust: memory: wrap MemoryRegion with Opaque<> Date: Thu, 27 Feb 2025 15:22:17 +0100 Message-ID: <20250227142219.812270-11-pbonzini@redhat.com> X-Mailer: git-send-email 2.48.1 In-Reply-To: <20250227142219.812270-1-pbonzini@redhat.com> References: <20250227142219.812270-1-pbonzini@redhat.com> MIME-Version: 1.0 Received-SPF: pass client-ip=170.10.129.124; envelope-from=pbonzini@redhat.com; helo=us-smtp-delivery-124.mimecast.com X-Spam_score_int: -24 X-Spam_score: -2.5 X-Spam_bar: -- X-Spam_report: (-2.5 / 5.0 requ) BAYES_00=-1.9, DKIMWL_WL_HIGH=-0.438, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_NONE=-0.0001, RCVD_IN_MSPIKE_H5=0.001, RCVD_IN_MSPIKE_WL=0.001, RCVD_IN_VALIDITY_CERTIFIED_BLOCKED=0.001, RCVD_IN_VALIDITY_RPBL_BLOCKED=0.001, SPF_HELO_NONE=0.001, SPF_PASS=-0.001 autolearn=unavailable autolearn_force=no X-Spam_action: no action X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org Sender: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org Signed-off-by: Paolo Bonzini --- rust/qemu-api/src/bindings.rs | 3 --- rust/qemu-api/src/memory.rs | 35 +++++++++++++++++++++-------------- 2 files changed, 21 insertions(+), 17 deletions(-) diff --git a/rust/qemu-api/src/bindings.rs b/rust/qemu-api/src/bindings.rs index b791ca6d87f..26cc8de0cf2 100644 --- a/rust/qemu-api/src/bindings.rs +++ b/rust/qemu-api/src/bindings.rs @@ -34,9 +34,6 @@ unsafe impl Sync for CharBackend {} unsafe impl Send for Chardev {} unsafe impl Sync for Chardev {} -unsafe impl Send for MemoryRegion {} -unsafe impl Sync for MemoryRegion {} - unsafe impl Send for ObjectClass {} unsafe impl Sync for ObjectClass {} diff --git a/rust/qemu-api/src/memory.rs b/rust/qemu-api/src/memory.rs index 713c494ca2e..eff9f09fd7f 100644 --- a/rust/qemu-api/src/memory.rs +++ b/rust/qemu-api/src/memory.rs @@ -6,9 +6,8 @@ use std::{ ffi::{CStr, CString}, - marker::{PhantomData, PhantomPinned}, + marker::PhantomData, os::raw::{c_uint, c_void}, - ptr::addr_of, }; pub use bindings::{hwaddr, MemTxAttrs}; @@ -16,6 +15,7 @@ use crate::{ bindings::{self, device_endian, memory_region_init_io}, callbacks::FnCall, + cell::Opaque, prelude::*, zeroable::Zeroable, }; @@ -132,13 +132,13 @@ fn default() -> Self { } } -/// A safe wrapper around [`bindings::MemoryRegion`]. Compared to the -/// underlying C struct it is marked as pinned because the QOM tree -/// contains a pointer to it. -pub struct MemoryRegion { - inner: bindings::MemoryRegion, - _pin: PhantomPinned, -} +/// A safe wrapper around [`bindings::MemoryRegion`]. +#[repr(transparent)] +#[derive(qemu_api_macros::Wrapper)] +pub struct MemoryRegion(Opaque); + +unsafe impl Send for MemoryRegion {} +unsafe impl Sync for MemoryRegion {} impl MemoryRegion { // inline to ensure that it is not included in tests, which only @@ -174,13 +174,20 @@ pub fn init_io>( size: u64, ) { unsafe { - Self::do_init_io(&mut self.inner, owner.cast::(), &ops.0, name, size); + Self::do_init_io( + // self.0.as_mut_ptr() needed because Rust tries to call + // ObjectDeref::as_mut_ptr() on "&mut Self", instead of coercing + // to "&Self" and then calling MemoryRegion::as_mut_ptr(). + // Revisit if/when ObjectCastMut is not needed anymore; it is + // only used in a couple places for initialization. + self.0.as_mut_ptr(), + owner.cast::(), + &ops.0, + name, + size, + ); } } - - pub(crate) const fn as_mut_ptr(&self) -> *mut bindings::MemoryRegion { - addr_of!(self.inner) as *mut _ - } } unsafe impl ObjectType for MemoryRegion { From patchwork Thu Feb 27 14:22:18 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Paolo Bonzini X-Patchwork-Id: 13994685 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.lore.kernel.org (Postfix) with ESMTPS id 440C9C1B0FF for ; Thu, 27 Feb 2025 14:33:05 +0000 (UTC) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1tneox-00089M-E0; Thu, 27 Feb 2025 09:25:03 -0500 Received: from eggs.gnu.org ([2001:470:142:3::10]) by lists.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1tnemp-0004Cs-Gu for qemu-devel@nongnu.org; Thu, 27 Feb 2025 09:22:51 -0500 Received: from us-smtp-delivery-124.mimecast.com ([170.10.129.124]) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1tnemn-00049g-Gm for qemu-devel@nongnu.org; Thu, 27 Feb 2025 09:22:51 -0500 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1740666167; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=vQFYgL5OvkIroXqJVu4wnMdYvtwWSlXNwP+wGqmQy7o=; b=NJwwNULcwB0Na8mjMLTB3WkbZBh/Dlu7cN4Hh2XFVTGZEEv+WWnqERb38HMaL7UOQFuGAM 4ZnLmog9BMP4e3mqS9ZoX1a6w0Utp37VGAq41Ok5houz+nsYRqbmn0LHK6EbLYo1J0TxQt fMeQBygc4oYBWVSfj46Jf9mrZDrHbU4= Received: from mail-ej1-f71.google.com (mail-ej1-f71.google.com [209.85.218.71]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-41-orNEhhvCMN2vqZtSNWExAg-1; Thu, 27 Feb 2025 09:22:46 -0500 X-MC-Unique: orNEhhvCMN2vqZtSNWExAg-1 X-Mimecast-MFC-AGG-ID: orNEhhvCMN2vqZtSNWExAg_1740666165 Received: by mail-ej1-f71.google.com with SMTP id a640c23a62f3a-abbc0572fc9so133538566b.0 for ; Thu, 27 Feb 2025 06:22:46 -0800 (PST) X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1740666165; x=1741270965; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=vQFYgL5OvkIroXqJVu4wnMdYvtwWSlXNwP+wGqmQy7o=; b=jOU7cF8J849JsNx3QqxKlTAEEVFJmmCUTFsbL6MRLd/3NCEoZjFNP7yDCoTRjSxV7r i5GiWGeoBI/K1L7yKLkxoTlu4BTKseLq+iIgEetbHdMIUzJwg4HMQlDoGzivArwazxZz kVOGODX3NusKr3jlKrLcN79iydZ/r4p4R2aSNDtEaWl6qE4WQiBe341/IyNtq993CVVs UER5qR15cw8kIdT7LyghcWY31rRBp3eMonsVB11FzGSNdY6Ptpfei23Gy9c+YnsAt/dO BcpfsMONGY74E2bJyggcsWpkjhOftQec7NtjdB6fIE5vG9XKh/ggrPnaYzizzA20xAim dgzA== X-Gm-Message-State: AOJu0YwjSM6HzyTQJOapM4wnNxNu1NUl/oC144RBH8CBQFrHnos016Ns SgxWMpfJtP8MPtAueOAl/5zVeaZ6Ply/uuMRRHI+EzYqoW8meyEhtUJYMxOPd4NHgyQAHfVbXTC i149Q1LLBE+aZjhpppEihbH2/kf/DPobrG2ertgNDX4K9TxvP12x7tTB4fI9t2JTlmKiDAELp/r U2FQkOgKXDAZUG/f1Li7StGC2jVNe7dMFn9LkyFR8= X-Gm-Gg: ASbGncukY7bIjJE7G3jfAtg7MZ9dr0QAOZIMigS24ousINVTAmJz3ngmNR3nZ4LPnf9 NJJFhCx71t1JoLcFHGLioszSkD85laHPHuH88JVvJR1f7jGnPbC/NST5SsPQ84EPf98zg+l75py 9XyKBv8OBRyJv3pefXLL8wINPJWfMtmzD4dFKNsg7GXGESLC226a45PZ402O3RZdzehv0aUFyFg V+QuzPK7pTpB9Zw2UZapyWq0SgriktP/hoCgsOagdYFu65TzzKBjq7ccJMmSeR2uE6Xy88LHdDm 0UgpGBEfdUfzGnAPM6nu X-Received: by 2002:a17:906:b818:b0:abc:29e3:f453 with SMTP id a640c23a62f3a-abc29e3f7cdmr2333890866b.33.1740666164965; Thu, 27 Feb 2025 06:22:44 -0800 (PST) X-Google-Smtp-Source: AGHT+IFCow23dBkk3rFhCa7lI/9dK6hjQRPITll/EpbdyAGB2nPmQzKCR6XsdnnEYg4+TFph+esQ9g== X-Received: by 2002:a17:906:b818:b0:abc:29e3:f453 with SMTP id a640c23a62f3a-abc29e3f7cdmr2333887966b.33.1740666164574; Thu, 27 Feb 2025 06:22:44 -0800 (PST) Received: from [192.168.10.48] ([176.206.102.52]) by smtp.gmail.com with ESMTPSA id a640c23a62f3a-abf0c74c714sm129332066b.124.2025.02.27.06.22.42 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 27 Feb 2025 06:22:42 -0800 (PST) From: Paolo Bonzini To: qemu-devel@nongnu.org Cc: qemu-rust@nongnu.org, zhao1.liu@intel.com Subject: [PATCH 11/12] rust: chardev: wrap Chardev with Opaque<> Date: Thu, 27 Feb 2025 15:22:18 +0100 Message-ID: <20250227142219.812270-12-pbonzini@redhat.com> X-Mailer: git-send-email 2.48.1 In-Reply-To: <20250227142219.812270-1-pbonzini@redhat.com> References: <20250227142219.812270-1-pbonzini@redhat.com> MIME-Version: 1.0 Received-SPF: pass client-ip=170.10.129.124; envelope-from=pbonzini@redhat.com; helo=us-smtp-delivery-124.mimecast.com X-Spam_score_int: -24 X-Spam_score: -2.5 X-Spam_bar: -- X-Spam_report: (-2.5 / 5.0 requ) BAYES_00=-1.9, DKIMWL_WL_HIGH=-0.438, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_NONE=-0.0001, RCVD_IN_MSPIKE_H5=0.001, RCVD_IN_MSPIKE_WL=0.001, RCVD_IN_VALIDITY_CERTIFIED_BLOCKED=0.001, RCVD_IN_VALIDITY_RPBL_BLOCKED=0.001, SPF_HELO_NONE=0.001, SPF_PASS=-0.001 autolearn=unavailable autolearn_force=no X-Spam_action: no action X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org Sender: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org Reviewed-by: Zhao Liu Signed-off-by: Paolo Bonzini --- rust/qemu-api/src/bindings.rs | 3 --- rust/qemu-api/src/chardev.rs | 8 ++++++-- rust/qemu-api/src/qdev.rs | 1 + 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/rust/qemu-api/src/bindings.rs b/rust/qemu-api/src/bindings.rs index 26cc8de0cf2..c3f36108bd5 100644 --- a/rust/qemu-api/src/bindings.rs +++ b/rust/qemu-api/src/bindings.rs @@ -31,9 +31,6 @@ unsafe impl Sync for BusState {} unsafe impl Send for CharBackend {} unsafe impl Sync for CharBackend {} -unsafe impl Send for Chardev {} -unsafe impl Sync for Chardev {} - unsafe impl Send for ObjectClass {} unsafe impl Sync for ObjectClass {} diff --git a/rust/qemu-api/src/chardev.rs b/rust/qemu-api/src/chardev.rs index 74cfb634e5f..a35b9217e90 100644 --- a/rust/qemu-api/src/chardev.rs +++ b/rust/qemu-api/src/chardev.rs @@ -6,9 +6,13 @@ use std::ffi::CStr; -use crate::{bindings, prelude::*}; +use crate::{bindings, cell::Opaque, prelude::*}; + +/// A safe wrapper around [`bindings::Chardev`]. +#[repr(transparent)] +#[derive(qemu_api_macros::Wrapper)] +pub struct Chardev(Opaque); -pub type Chardev = bindings::Chardev; pub type ChardevClass = bindings::ChardevClass; unsafe impl ObjectType for Chardev { diff --git a/rust/qemu-api/src/qdev.rs b/rust/qemu-api/src/qdev.rs index 1c4a67b5728..18b4a9ba687 100644 --- a/rust/qemu-api/src/qdev.rs +++ b/rust/qemu-api/src/qdev.rs @@ -334,6 +334,7 @@ fn init_clock_out(&self, name: &str) -> Owned { fn prop_set_chr(&self, propname: &str, chr: &Owned) { assert!(bql_locked()); let c_propname = CString::new(propname).unwrap(); + let chr: &Chardev = chr; unsafe { bindings::qdev_prop_set_chr( self.upcast().as_mut_ptr(), From patchwork Thu Feb 27 14:22:19 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Paolo Bonzini X-Patchwork-Id: 13994666 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.lore.kernel.org (Postfix) with ESMTPS id 6E9D5C19F2E for ; Thu, 27 Feb 2025 14:29:18 +0000 (UTC) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1tneoP-0006oP-N5; Thu, 27 Feb 2025 09:24:32 -0500 Received: from eggs.gnu.org ([2001:470:142:3::10]) by lists.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1tnemq-0004HX-M2 for qemu-devel@nongnu.org; Thu, 27 Feb 2025 09:22:53 -0500 Received: from us-smtp-delivery-124.mimecast.com ([170.10.133.124]) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1tnemo-0004AM-JR for qemu-devel@nongnu.org; Thu, 27 Feb 2025 09:22:52 -0500 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1740666169; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=5YnANE3o7k98qiD5yXSXBYpiijAd3VVlrkAgduC094U=; b=QsntAUxcxOkEABr93R1p/exLIkMBd3YYOC1s8lWwXG5zXklFMojRREGG3Nd4xL2wqdpSMH ErSOLz7e4/nwwZPFXHKL6aarI3mV7GGzFWpZAt+am077y0Iky2GzNzdAVKDaLVGIWx8cRD MzAedDjyFdkeA7AHMK8D9A4kjsCVQw4= Received: from mail-ed1-f70.google.com (mail-ed1-f70.google.com [209.85.208.70]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-88-6_cKwmKKO-Wni1--gDOaiQ-1; Thu, 27 Feb 2025 09:22:48 -0500 X-MC-Unique: 6_cKwmKKO-Wni1--gDOaiQ-1 X-Mimecast-MFC-AGG-ID: 6_cKwmKKO-Wni1--gDOaiQ_1740666167 Received: by mail-ed1-f70.google.com with SMTP id 4fb4d7f45d1cf-5ded3946ff9so1130901a12.3 for ; Thu, 27 Feb 2025 06:22:48 -0800 (PST) X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1740666167; x=1741270967; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=5YnANE3o7k98qiD5yXSXBYpiijAd3VVlrkAgduC094U=; b=E/2E1So1tI9NPx5oOx8qTEN0JSkPX6f/eVPQDRvcQPgjEtj4adAcpgWTvNuLw3rKfT g/Wa8rOxv/+TD0ItNs/8auACsjiRPzXPgClDeKliOqVXt3fYeRdvJzQeOL5TGeTiT87/ Ohv/LV0iDJ1gUwvKWcauvwdFpcKZ6BzvUMCCvVey7tXZUZNM5Zgk/c6EzDRKea7cvYnL JdPRCluUJaYoJT8mXkmFUdswnDYsWAeXM6J4rjF6KXnYtpXkp+xJGO5dWqDvYjXm3Yuj jzg2Q44Ywh8cVREZeQpdDFBceBalwZiMCPHKZO3+So/Wl28LIIHbzSao90cQdGAK0ISm wOGA== X-Gm-Message-State: AOJu0YzVuseqjYuJT4zYnCnWVZAIXeNZyr1hTKQDtYqgMjn/7ejRzhEo Q7JzRgbEiQJHsA0PwOG85o6Ae0t7k1sqazzuzNoSuuvB0LCNLeEh/RTkzOJO4kAFBvxJkUTFATr VwvttFaSc5UtDkuIS1lhLF1kL6KknBPi/gayPSSCDTHse7UhhhVz2BnNyJTQuotHzn0EX2DZgHD 6iZzFrT6HBWYAhTE1Z0Xul7goMS+I0yTZ7NnkR93E= X-Gm-Gg: ASbGncsHM6H4aQViB/TI1g5/nE+12vOgCaC8wuiRPVZ4RPRNAV4qWtcnEAqGdZv1OB8 vFh6dUu9zQLi8ApxR6oni5RB8obruy98iYzDBwxF1OD9PsROAetR6CiwGeOb7xeVtCn5ZY7mFJf rsYC9tI1AaKG3/H6YMaQOyiOBKxi8oQ+MWLk4xGVUiNUy0V839DnKNwMKJj0cA8lF8X53+H1x5O 91BW76xHKNWi3PgKjgw55m3nEiQIcSyctnTq0994U8CsBdPOS5WhLyBNCp6SMD2NVLbmVXgUaVu rGdentZzZHL/c7fkx1DZ X-Received: by 2002:a05:6402:248c:b0:5da:d76:7b2e with SMTP id 4fb4d7f45d1cf-5e4a0bf28cemr11014797a12.0.1740666166677; Thu, 27 Feb 2025 06:22:46 -0800 (PST) X-Google-Smtp-Source: AGHT+IFI18O2SZf2XVwBJAzZdSiM75sskBvaScYSlzBp/K0tpUSEfcPx/7NIQUBZO265lJA9h0HCMw== X-Received: by 2002:a05:6402:248c:b0:5da:d76:7b2e with SMTP id 4fb4d7f45d1cf-5e4a0bf28cemr11014761a12.0.1740666166220; Thu, 27 Feb 2025 06:22:46 -0800 (PST) Received: from [192.168.10.48] ([176.206.102.52]) by smtp.gmail.com with ESMTPSA id 4fb4d7f45d1cf-5e4c3b4aa13sm1147054a12.7.2025.02.27.06.22.45 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 27 Feb 2025 06:22:45 -0800 (PST) From: Paolo Bonzini To: qemu-devel@nongnu.org Cc: qemu-rust@nongnu.org, zhao1.liu@intel.com Subject: [PATCH 12/12] rust: bindings: remove more unnecessary Send/Sync impls Date: Thu, 27 Feb 2025 15:22:19 +0100 Message-ID: <20250227142219.812270-13-pbonzini@redhat.com> X-Mailer: git-send-email 2.48.1 In-Reply-To: <20250227142219.812270-1-pbonzini@redhat.com> References: <20250227142219.812270-1-pbonzini@redhat.com> MIME-Version: 1.0 Received-SPF: pass client-ip=170.10.133.124; envelope-from=pbonzini@redhat.com; helo=us-smtp-delivery-124.mimecast.com X-Spam_score_int: -24 X-Spam_score: -2.5 X-Spam_bar: -- X-Spam_report: (-2.5 / 5.0 requ) BAYES_00=-1.9, DKIMWL_WL_HIGH=-0.438, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_NONE=-0.0001, RCVD_IN_MSPIKE_H2=0.001, RCVD_IN_VALIDITY_CERTIFIED_BLOCKED=0.001, RCVD_IN_VALIDITY_RPBL_BLOCKED=0.001, SPF_HELO_NONE=0.001, SPF_PASS=-0.001 autolearn=ham autolearn_force=no X-Spam_action: no action X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org Sender: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org Send and Sync are now implemented on the opaque wrappers. Remove them from the bindings module, unless the structs are pure data containers and/or have no C functions defined on them. Reviewed-by: Zhao Liu Signed-off-by: Paolo Bonzini --- rust/qemu-api/src/bindings.rs | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/rust/qemu-api/src/bindings.rs b/rust/qemu-api/src/bindings.rs index c3f36108bd5..3c1d297581e 100644 --- a/rust/qemu-api/src/bindings.rs +++ b/rust/qemu-api/src/bindings.rs @@ -25,15 +25,11 @@ // SAFETY: these are implemented in C; the bindings need to assert that the // BQL is taken, either directly or via `BqlCell` and `BqlRefCell`. -unsafe impl Send for BusState {} -unsafe impl Sync for BusState {} - +// 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 {} -unsafe impl Send for ObjectClass {} -unsafe impl Sync for ObjectClass {} - // SAFETY: this is a pure data struct unsafe impl Send for CoalescedMemoryRange {} unsafe impl Sync for CoalescedMemoryRange {}