From nobody Wed Nov 27 05:29:56 2024 Delivered-To: importer@patchew.org Authentication-Results: mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; dmarc=pass(p=none dis=none) header.from=redhat.com ARC-Seal: i=1; a=rsa-sha256; t=1732261734; cv=none; d=zohomail.com; s=zohoarc; b=UAcCc3ZyVi7yIKboD/HBmeIB1vVt3msFql4vgqRte3bkSlFa4tFJxnnKCq+SZ7m9PTswHkXdZryOfnh3Ji1Lr41zQ+Qts8FkiPK6EsejpPMAVJ5XjrpQmw0VUI4Gfr/Mv19tvIyAI1C1BdZjG8JPyKpHOpK0UFs6cohoFCFTseA= ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=zohomail.com; s=zohoarc; t=1732261734; h=Content-Transfer-Encoding:Cc:Cc:Date:Date:From:From:In-Reply-To:List-Subscribe:List-Post:List-Id:List-Archive:List-Help:List-Unsubscribe:MIME-Version:Message-ID:References:Sender:Subject:Subject:To:To:Message-Id:Reply-To; bh=OsxImFeu8DkA26mh4aT3AmBOCZzr2QCcHOFFPPBcuo4=; b=V8Qoy7bCqrzXL5ovNtV0MBqSOosEF5mx+LzPPqggXJCD+xN3wTqpMan+bDdXq8jfgX+a7qp8mcGzVmlN9pOQAQ/PqaLmZz5MlFMxgS3wprzTTVYjxzqk2qtxXHjdJi9HmAtM59lwwvfdzxDGje8nj0gS3KVtzOEy1vNEXBYxh4g= ARC-Authentication-Results: i=1; mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; dmarc=pass header.from= (p=none dis=none) Return-Path: Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) by mx.zohomail.com with SMTPS id 1732261734960152.57207714100832; Thu, 21 Nov 2024 23:48:54 -0800 (PST) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1tEOOe-00057m-Tt; Fri, 22 Nov 2024 02:48: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 1tEOOd-00057Z-7v for qemu-devel@nongnu.org; Fri, 22 Nov 2024 02:48:07 -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 1tEOOb-0003Op-93 for qemu-devel@nongnu.org; Fri, 22 Nov 2024 02:48:06 -0500 Received: from mail-wr1-f71.google.com (mail-wr1-f71.google.com [209.85.221.71]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-205-nEJHqkaWNXiv3PsARVWutw-1; Fri, 22 Nov 2024 02:48:03 -0500 Received: by mail-wr1-f71.google.com with SMTP id ffacd0b85a97d-38242a78f3eso958300f8f.0 for ; Thu, 21 Nov 2024 23:48:02 -0800 (PST) Received: from [192.168.10.3] ([151.49.204.250]) by smtp.gmail.com with ESMTPSA id ffacd0b85a97d-3825fad6470sm1665945f8f.11.2024.11.21.23.47.58 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 21 Nov 2024 23:47:58 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1732261684; 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=OsxImFeu8DkA26mh4aT3AmBOCZzr2QCcHOFFPPBcuo4=; b=Q8djQaoitPVFNVlCLLsJsynUWIcPiVHCQlVXUQYzwLBbUD/UQ1CSnu9lUw4/ZVPDMl3kwR qjiR86BkHDxu5LDQvSEDg4YmTrwKWEqTmfHmoXmqk9nJ0EvF1F8oLjmoj+PLh+ZKQCi3lw n0a+O0HScPbKb+Rb0ti30a2S+Qel284= X-MC-Unique: nEJHqkaWNXiv3PsARVWutw-1 X-Mimecast-MFC-AGG-ID: nEJHqkaWNXiv3PsARVWutw X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1732261681; x=1732866481; 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=OsxImFeu8DkA26mh4aT3AmBOCZzr2QCcHOFFPPBcuo4=; b=OTT/LTEJQ47Oxx1BrsGCLxGxQFlyXqxA5/9AAOusYZaSY6KusAfHv4aQQZxmk2pa2j iTi21L7nTxOOY+POPHXNetdK6N7HTF1cRfgEXlE2zZxm08BstxCKOjiXouYEpLYDpd1Q mnGIHfnamXPilyxypod3PkyUDRkj1+I5+EF1H0wYdmD/sJ2mRimdjDRCxmOimTVWjEr8 B2qIOvBgKnv0R0GI75d65Rg8T01VNvrZhHu+y7TmrP5ZOe9FkQEdVu0C/PHj1y5e5Ql9 1XdHKiTfvNi9cKhGHeRQZw2JtjOa6tnNAv9HvxsQXPoNJD3UpzooxUuWmY+zINR1PPQU tqMw== X-Gm-Message-State: AOJu0YwaTFO5ry8yWwC4P8PtlVspvbWEy5bBTFglZ5Awb9oAdpaOtW4a nB88SWzJpGji3J9sDWvfNPksqzMt1DX16yndfEts3gAoZeC5KM0+TMFJUZY+fruMFqi6tECWRVe M9Cn/A8ygA40IiZs0x9NnnlSe7IhyGVvJAucPhmY5aDwqKPwAObRHg3p+N8Xmo4K3ea47crjzMm RvFkJVPipR2Cgfr3/0YmfGbJ7myD95Lc8f971X X-Gm-Gg: ASbGncvKf/vLWODFvY/omad2gfeX8Ca3GoxSSXRxPzHbwxlreK8WUfm7tDhwN9MsiOB m8rFC9yHKinq6JXArox/LjPfSCgSPnwOMaibjDnC9Gzjm3UX/VkB92N6cF8ATALELWCU5b5rVXP lLrd5B71sQUYNwOxcyjj15Yx0U5zMV4haqLQG6l03fQnVJyF8pZY1jY2UEwFdKTSObnfrEQcp4b IM8jQxRgqkHesWCi9RVrGPk+XxjTwb13xBzlLc2D0lYPa3j9VIt4Q== X-Received: by 2002:a5d:5f53:0:b0:382:4bb8:e1d with SMTP id ffacd0b85a97d-38260b4d616mr1490590f8f.1.1732261680766; Thu, 21 Nov 2024 23:48:00 -0800 (PST) X-Google-Smtp-Source: AGHT+IGGlwZTZdrv818qqftL07lFhPrmRCi4bLxvk6ruBGAA9Ggn+NtPu9148gdIYzjgWGJOlpARcA== X-Received: by 2002:a5d:5f53:0:b0:382:4bb8:e1d with SMTP id ffacd0b85a97d-38260b4d616mr1490567f8f.1.1732261680242; Thu, 21 Nov 2024 23:48:00 -0800 (PST) From: Paolo Bonzini To: qemu-devel@nongnu.org Cc: junjie.mao@hotmail.com, zhao1.liu@intel.com, qemu-rust@nongnu.org Subject: [PATCH 1/2] rust: add BQL-enforcing Cell variant Date: Fri, 22 Nov 2024 08:47:55 +0100 Message-ID: <20241122074756.282142-2-pbonzini@redhat.com> X-Mailer: git-send-email 2.47.0 In-Reply-To: <20241122074756.282142-1-pbonzini@redhat.com> References: <20241122074756.282142-1-pbonzini@redhat.com> MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Received-SPF: pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) client-ip=209.51.188.17; envelope-from=qemu-devel-bounces+importer=patchew.org@nongnu.org; helo=lists.gnu.org; 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: -21 X-Spam_score: -2.2 X-Spam_bar: -- X-Spam_report: (-2.2 / 5.0 requ) BAYES_00=-1.9, DKIMWL_WL_HIGH=-0.14, 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_RPBL_BLOCKED=0.001, RCVD_IN_VALIDITY_SAFE_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+importer=patchew.org@nongnu.org Sender: qemu-devel-bounces+importer=patchew.org@nongnu.org X-ZohoMail-DKIM: pass (identity @redhat.com) X-ZM-MESSAGEID: 1732261737107116600 Content-Type: text/plain; charset="utf-8" QEMU objects usually have their pointer shared with the "outside world" very early in their lifetime, for example when they create their MemoryRegions. Because at this point it is not valid anymore to create a &mut reference to the device, individual parts of the device struct must be made mutable in a controlled manner. QEMU's Big Lock (BQL) effectively turns multi-threaded code into single-threaded code while device code runs, as long as the BQL is not released while the device is borrowed (because C code could sneak in and mutate the device). We can then introduce custom interior mutability primi= tives that are semantically similar to the standard library's (single-threaded) Cell and RefCell, but account for QEMU's threading model. Accessing the "BqlCell" or borrowing the "BqlRefCell" requires proving that the BQL is held, and attempting to access without the BQL is a runtime panic, similar to RefCell's already-borrowed panic. With respect to naming I also considered omitting the "Bql" prefix or moving it to the module, e.g. qemu_api::bql::{Cell, RefCell}. However, this could easily lead to mistakes and confusion; for example rustc could suggest the wrong import, leading to subtle bugs. As a start introduce the an equivalent of Cell. Almost all of the code was taken from Rust's standard library, while removing unstable features and probably-unnecessary functionality that amounts to 60% of the original code. A lot of what's left is documentation, as well as unit tests in the form of doctests. These are not yet integrated in "make check" but can be run with "cargo test --doc". Signed-off-by: Paolo Bonzini --- rust/qemu-api/meson.build | 1 + rust/qemu-api/src/cell.rs | 294 ++++++++++++++++++++++++++++++++++++++ rust/qemu-api/src/lib.rs | 1 + 3 files changed, 296 insertions(+) create mode 100644 rust/qemu-api/src/cell.rs diff --git a/rust/qemu-api/meson.build b/rust/qemu-api/meson.build index d719c13f46d..edc21e1a3f8 100644 --- a/rust/qemu-api/meson.build +++ b/rust/qemu-api/meson.build @@ -13,6 +13,7 @@ _qemu_api_rs =3D static_library( [ 'src/lib.rs', 'src/bindings.rs', + 'src/cell.rs', 'src/c_str.rs', 'src/definitions.rs', 'src/device_class.rs', diff --git a/rust/qemu-api/src/cell.rs b/rust/qemu-api/src/cell.rs new file mode 100644 index 00000000000..8842d43228b --- /dev/null +++ b/rust/qemu-api/src/cell.rs @@ -0,0 +1,294 @@ +// SPDX-License-Identifier: MIT +// +// This file is based on library/core/src/cell.rs from +// Rust 1.82.0. +// +// Permission is hereby granted, free of charge, to any +// person obtaining a copy of this software and associated +// documentation files (the "Software"), to deal in the +// Software without restriction, including without +// limitation the rights to use, copy, modify, merge, +// publish, distribute, sublicense, and/or sell copies of +// the Software, and to permit persons to whom the Software +// is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice +// shall be included in all copies or substantial portions +// of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +// DEALINGS IN THE SOFTWARE. + +//! BQL-protected mutable containers. +//! +//! Rust memory safety is based on this rule: Given an object `T`, it is o= nly +//! possible to have one of the following: +//! +//! - Having several immutable references (`&T`) to the object (also known= as +//! **aliasing**). +//! - Having one mutable reference (`&mut T`) to the object (also known as +//! **mutability**). +//! +//! This is enforced by the Rust compiler. However, there are situations w= here +//! this rule is not flexible enough. Sometimes it is required to have mul= tiple +//! references to an object and yet mutate it. In particular, QEMU objects +//! 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, individu= al +//! parts of a device must be made mutable in a controlled manner through= the +//! use of cell types. +//! +//! This module provides a way to do so via the Big QEMU Lock. While +//! [`BQLCell`] is essentially the same single-threaded primitive that = is +//! available in `std::cell`, the BQL allows it to be used from a multi-th= readed +//! context and to share references across threads, while maintaining Rust= 's +//! safety guarantees. For this reason, unlike its `std::cell` counterpar= t, +//! `BqlCell` implements the `Sync` trait. +//! +//! BQL checks are performed in debug builds but can be optimized away in +//! release builds, providing runtime safety during development with no ov= erhead +//! in production. +//! +//! Warning: While `BqlCell` is similar to its `std::cell` counterpart, th= e two +//! are not interchangeable. Using `std::cell` types in QEMU device +//! implementations is usually incorrect and can lead to thread-safety iss= ues. +//! +//! ## `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 obtaine= d as +//! long as the cell is shared. The value itself cannot be directly obtain= ed +//! without copying it, cloning it, or replacing it with something else. T= his +//! type provides the following methods, all of which can be called only w= hile +//! the BQL is held: +//! +//! - For types that implement [`Copy`], the [`get`](BqlCell::get) method +//! retrieves the current interior value by duplicating it. +//! - For types that implement [`Default`], the [`take`](BqlCell::take) m= ethod +//! replaces the current interior value with [`Default::default()`] and +//! returns the replaced value. +//! - All types have: +//! - [`replace`](BqlCell::replace): replaces the current interior valu= e and +//! returns the replaced value. +//! - [`set`](BqlCell::set): this method replaces the interior value, +//! dropping the replaced value. + +use std::{cell::UnsafeCell, cmp::Ordering, fmt, mem}; + +use crate::bindings; + +// TODO: When building doctests do not include the actual BQL, because car= go +// does not know how to link them to libqemuutil. This can be fixed by +// running rustdoc from "meson test" instead of relying on cargo. +fn bql_locked() -> bool { + // SAFETY: the function does nothing but return a thread-local bool + !cfg!(MESON) || unsafe { bindings::bql_locked() } +} + +/// A mutable memory location that is protected by the Big QEMU Lock. +/// +/// # Memory layout +/// +/// `BqlCell` has the same in-memory representation as its inner type `= T`. +#[repr(transparent)] +pub struct BqlCell { + value: UnsafeCell, +} + +// SAFETY: Same as for std::sync::Mutex. In the end this *is* a Mutex, +// except it is stored out-of-line +unsafe impl Send for BqlCell {} +unsafe impl Sync for BqlCell {} + +impl Clone for BqlCell { + #[inline] + fn clone(&self) -> BqlCell { + BqlCell::new(self.get()) + } +} + +impl Default for BqlCell { + /// Creates a `BqlCell`, with the `Default` value for T. + #[inline] + fn default() -> BqlCell { + BqlCell::new(Default::default()) + } +} + +impl PartialEq for BqlCell { + #[inline] + fn eq(&self, other: &BqlCell) -> bool { + self.get() =3D=3D other.get() + } +} + +impl Eq for BqlCell {} + +impl PartialOrd for BqlCell { + #[inline] + fn partial_cmp(&self, other: &BqlCell) -> Option { + self.get().partial_cmp(&other.get()) + } +} + +impl Ord for BqlCell { + #[inline] + fn cmp(&self, other: &BqlCell) -> Ordering { + self.get().cmp(&other.get()) + } +} + +impl From for BqlCell { + /// Creates a new `BqlCell` containing the given value. + fn from(t: T) -> BqlCell { + BqlCell::new(t) + } +} + +impl fmt::Debug for BqlCell { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.get().fmt(f) + } +} + +impl fmt::Display for BqlCell { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.get().fmt(f) + } +} + +impl BqlCell { + /// Creates a new `BqlCell` containing the given value. + /// + /// # Examples + /// + /// ``` + /// use qemu_api::cell::BqlCell; + /// + /// let c =3D BqlCell::new(5); + /// ``` + #[inline] + pub const fn new(value: T) -> BqlCell { + BqlCell { + value: UnsafeCell::new(value), + } + } + + /// Sets the contained value. + /// + /// # Examples + /// + /// ``` + /// use qemu_api::cell::BqlCell; + /// + /// let c =3D BqlCell::new(5); + /// + /// c.set(10); + /// ``` + #[inline] + pub fn set(&self, val: T) { + self.replace(val); + } + + /// Replaces the contained value with `val`, and returns the old conta= ined + /// value. + /// + /// # Examples + /// + /// ``` + /// use qemu_api::cell::BqlCell; + /// + /// let cell =3D BqlCell::new(5); + /// assert_eq!(cell.get(), 5); + /// assert_eq!(cell.replace(10), 5); + /// assert_eq!(cell.get(), 10); + /// ``` + #[inline] + pub fn replace(&self, val: T) -> T { + debug_assert!(bql_locked()); + // SAFETY: This can cause data races if called from a separate thr= ead, + // but `BqlCell` is `!Sync` so this won't happen. + mem::replace(unsafe { &mut *self.value.get() }, val) + } + + /// Unwraps the value, consuming the cell. + /// + /// # Examples + /// + /// ``` + /// use qemu_api::cell::BqlCell; + /// + /// let c =3D BqlCell::new(5); + /// let five =3D c.into_inner(); + /// + /// assert_eq!(five, 5); + /// ``` + pub fn into_inner(self) -> T { + debug_assert!(bql_locked()); + self.value.into_inner() + } +} + +impl BqlCell { + /// Returns a copy of the contained value. + /// + /// # Examples + /// + /// ``` + /// use qemu_api::cell::BqlCell; + /// + /// let c =3D BqlCell::new(5); + /// + /// let five =3D c.get(); + /// ``` + #[inline] + pub fn get(&self) -> T { + debug_assert!(bql_locked()); + unsafe { *self.value.get() } + } +} + +impl BqlCell { + /// Returns a raw pointer to the underlying data in this cell. + /// + /// # Examples + /// + /// ``` + /// use qemu_api::cell::BqlCell; + /// + /// let c =3D BqlCell::new(5); + /// + /// let ptr =3D c.as_ptr(); + /// ``` + #[inline] + pub const fn as_ptr(&self) -> *mut T { + self.value.get() + } +} + +impl BqlCell { + /// Takes the value of the cell, leaving `Default::default()` in its p= lace. + /// + /// # Examples + /// + /// ``` + /// use qemu_api::cell::BqlCell; + /// + /// let c =3D BqlCell::new(5); + /// let five =3D c.take(); + /// + /// assert_eq!(five, 5); + /// assert_eq!(c.into_inner(), 0); + /// ``` + pub fn take(&self) -> T { + self.replace(Default::default()) + } +} diff --git a/rust/qemu-api/src/lib.rs b/rust/qemu-api/src/lib.rs index 440aff3817d..b04d110b3f5 100644 --- a/rust/qemu-api/src/lib.rs +++ b/rust/qemu-api/src/lib.rs @@ -8,6 +8,7 @@ pub mod bindings; =20 pub mod c_str; +pub mod cell; pub mod definitions; pub mod device_class; pub mod offset_of; --=20 2.47.0 From nobody Wed Nov 27 05:29:56 2024 Delivered-To: importer@patchew.org Authentication-Results: mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; dmarc=pass(p=none dis=none) header.from=redhat.com ARC-Seal: i=1; a=rsa-sha256; t=1732261723; cv=none; d=zohomail.com; s=zohoarc; b=HcC/qml3h0QpgdavZyv4qq8ew+k0ZuJPtvGXB0SRbo/7HUjGraxeBwXUGjRCS6DI4uzxEd/omx5BKjp08hKJyuHmnNK864F/Kk/x2ekV9rgFhFIWR/eiaiDQ8Rc3kPi8M6PS/98FBFGB8Zdg2xoQLlzRFgbHuNGVlspQA0AUFgk= ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=zohomail.com; s=zohoarc; t=1732261723; h=Content-Transfer-Encoding:Cc:Cc:Date:Date:From:From:In-Reply-To:List-Subscribe:List-Post:List-Id:List-Archive:List-Help:List-Unsubscribe:MIME-Version:Message-ID:References:Sender:Subject:Subject:To:To:Message-Id:Reply-To; bh=nkXxjzz1/Ou6IvHIAiqoZmLOReU2XBVksCsyChdWv20=; b=UEgnuuNgsTOmCHjiyVFbpNh881/vrWg+C3xQHVZ67MRvQrFP1RInIcFoh64xQDnDcYqZfHYQGxGA+EuZfr8WimcAzp/vW2rj2unVaFlmkBgGCQtDgqFFZ5WXhApizzas5FpR0fhE0Y4Qr1oD0VP3YLKNflRCythmB0tYfosyae0= ARC-Authentication-Results: i=1; mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; dmarc=pass header.from= (p=none dis=none) Return-Path: Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) by mx.zohomail.com with SMTPS id 1732261723924504.04298263935993; Thu, 21 Nov 2024 23:48:43 -0800 (PST) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1tEOOh-00058Q-Tw; Fri, 22 Nov 2024 02:48:11 -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 1tEOOg-00058I-A4 for qemu-devel@nongnu.org; Fri, 22 Nov 2024 02:48:10 -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 1tEOOe-0003PH-CS for qemu-devel@nongnu.org; Fri, 22 Nov 2024 02:48:10 -0500 Received: from mail-wm1-f70.google.com (mail-wm1-f70.google.com [209.85.128.70]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-222-aegqa0Q-M7mFkioJUznwcQ-1; Fri, 22 Nov 2024 02:48:05 -0500 Received: by mail-wm1-f70.google.com with SMTP id 5b1f17b1804b1-432d04b3d40so11227415e9.1 for ; Thu, 21 Nov 2024 23:48:05 -0800 (PST) Received: from [192.168.10.3] ([151.49.204.250]) by smtp.gmail.com with ESMTPSA id ffacd0b85a97d-3825fb30bfdsm1667602f8f.56.2024.11.21.23.48.00 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 21 Nov 2024 23:48:01 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1732261687; 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=nkXxjzz1/Ou6IvHIAiqoZmLOReU2XBVksCsyChdWv20=; b=V1f0+oxrLpRl0tfChdqqmeF4ToYAcb3mtTCFh69QUhBPm6g+W4Ro7XXTE4LWxn0HOgXwkg PuBcMT7fq76Fp3hP5YFx0waGSBJw91NnN5S/skmn9/wy6+zZcwfTO4X0AyDwP40nG3W+Ho HcdQA7ehVqhHBRdlRnWJbWKno0gAYx0= X-MC-Unique: aegqa0Q-M7mFkioJUznwcQ-1 X-Mimecast-MFC-AGG-ID: aegqa0Q-M7mFkioJUznwcQ X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1732261682; x=1732866482; 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=nkXxjzz1/Ou6IvHIAiqoZmLOReU2XBVksCsyChdWv20=; b=Y+a6WvXF6P4ho8/7Y9cW9WTEwgcxOuGbe1APQ9xghX95ik8s0c9WgkCPSa8QBI5F/6 YHyAM20oEJ/hb8a+kLm7TVA5oBSKh8J1iw2C0JVUHb3/XXSp714h096b/mEZpYkiADAS vDXgPmc+gTBLHfj/7xaoWtUuUVf3bSvI40mqO6eS1da0ZOnRngkf/OvfNBs4ozMueN/m W7msYwHs3UroYB97HmpLu+2IUJGz802xfgY8tEYe4k82bi3FTvpjNmbRSeD3TZgI8LPf o09ADQt2nJLbMr/p+nOKmVNgThMsbcJIsK2+IyJl5XzIeAQ3uSZAZ0Zmb9atD09ujDFR XQfg== X-Gm-Message-State: AOJu0YxjqUA41BF/G9VK0pU60ajyn6zli59/hT7F5huA0Aen3h0hQ3Wl YuCEJLS0ELtcUp2UC902VN9C8OTg7sfHs2jPb5cBr9BMdQXhmyCqTfH1CNj1OvZP03wK0t30SF9 Raq1y2mZysSrdo6NpF1jQ0Re07f7aJ4rKn1jPXQLGFmlnIbdSiNUoPloa+PxHW76FVE1CW5giBg YtVUbdhBBEMXMjOLa7HpZMR1xZ8LPG9XUyaDKC X-Gm-Gg: ASbGncvBnMb4FaKeeXby29GFH9LgY5JNAGow5Ate/1aS6vEkReRSfbWvqCaJxTLLtEk cTX1CPH536oTWrcO4Jb9AVUKTfsdgc2TKV4p5PTTZi/QEVIyqF5+Aufhe+NcR+6XPXuivoK+8fT yVv9bKZl+hSevLOX+5Sl0puVbAP/V9kwlJRsGH02T7HUlIO2yo0jnC1ayDaikD2r97zUvuzwx0u g/25HVIpKtWCGuvwnt63PqMgE5C6Z6cdBLb2yom/yc5mbbMnClNag== X-Received: by 2002:a05:6000:188c:b0:382:2276:c93c with SMTP id ffacd0b85a97d-38260bce871mr1545615f8f.44.1732261681975; Thu, 21 Nov 2024 23:48:01 -0800 (PST) X-Google-Smtp-Source: AGHT+IEESruyTio13ifrLzMjOAOsgqywStiCT1onPyGqRutu90TcKero1dmyjrUe1Ow8CvXsOvJ9tg== X-Received: by 2002:a05:6000:188c:b0:382:2276:c93c with SMTP id ffacd0b85a97d-38260bce871mr1545594f8f.44.1732261681518; Thu, 21 Nov 2024 23:48:01 -0800 (PST) From: Paolo Bonzini To: qemu-devel@nongnu.org Cc: junjie.mao@hotmail.com, zhao1.liu@intel.com, qemu-rust@nongnu.org Subject: [PATCH 2/2] rust: add bindings for interrupt sources Date: Fri, 22 Nov 2024 08:47:56 +0100 Message-ID: <20241122074756.282142-3-pbonzini@redhat.com> X-Mailer: git-send-email 2.47.0 In-Reply-To: <20241122074756.282142-1-pbonzini@redhat.com> References: <20241122074756.282142-1-pbonzini@redhat.com> MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Received-SPF: pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) client-ip=209.51.188.17; envelope-from=qemu-devel-bounces+importer=patchew.org@nongnu.org; helo=lists.gnu.org; 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: -21 X-Spam_score: -2.2 X-Spam_bar: -- X-Spam_report: (-2.2 / 5.0 requ) BAYES_00=-1.9, DKIMWL_WL_HIGH=-0.14, 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_H3=0.001, RCVD_IN_MSPIKE_WL=0.001, RCVD_IN_VALIDITY_RPBL_BLOCKED=0.001, RCVD_IN_VALIDITY_SAFE_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+importer=patchew.org@nongnu.org Sender: qemu-devel-bounces+importer=patchew.org@nongnu.org X-ZohoMail-DKIM: pass (identity @redhat.com) X-ZM-MESSAGEID: 1732261726279116600 Content-Type: text/plain; charset="utf-8" The InterruptSource bindings let us call qemu_set_irq() and sysbus_init_irq= () as safe code. Interrupt sources, qemu_irq in C code, are pointers to IRQState objects. They are QOM link properties and can be written to outside the control of the device (i.e. from a shared reference); therefore they must be interior-mutable in Rust. Since thread-safety is provided by the BQL, what we want here is the newly-introduced BqlCell. A pointer to the contents of the BqlCell (an IRQState**, or equivalently qemu_irq*) is then passed to the C sysbus_init_irq function. Signed-off-by: Paolo Bonzini --- rust/hw/char/pl011/src/device.rs | 22 ++++++----- rust/qemu-api/meson.build | 2 + rust/qemu-api/src/irq.rs | 66 ++++++++++++++++++++++++++++++++ rust/qemu-api/src/lib.rs | 2 + rust/qemu-api/src/sysbus.rs | 26 +++++++++++++ 5 files changed, 108 insertions(+), 10 deletions(-) create mode 100644 rust/qemu-api/src/irq.rs create mode 100644 rust/qemu-api/src/sysbus.rs diff --git a/rust/hw/char/pl011/src/device.rs b/rust/hw/char/pl011/src/devi= ce.rs index e582a31e4d3..7e57634bba0 100644 --- a/rust/hw/char/pl011/src/device.rs +++ b/rust/hw/char/pl011/src/device.rs @@ -13,6 +13,7 @@ c_str, definitions::ObjectImpl, device_class::TYPE_SYS_BUS_DEVICE, + irq::InterruptSource, }; =20 use crate::{ @@ -94,7 +95,7 @@ pub struct PL011State { /// * sysbus IRQ 5: `UARTEINTR` (error interrupt line) /// ``` #[doc(alias =3D "irq")] - pub interrupts: [qemu_irq; 6usize], + pub interrupts: [InterruptSource; IRQMASK.len()], #[doc(alias =3D "clk")] pub clock: NonNull, #[doc(alias =3D "migrate_clk")] @@ -139,7 +140,8 @@ impl PL011State { unsafe fn init(&mut self) { const CLK_NAME: &CStr =3D c_str!("clk"); =20 - let dev =3D addr_of_mut!(*self).cast::(); + let sbd =3D unsafe { &mut *(addr_of_mut!(*self).cast::()) }; + // SAFETY: // // self and self.iomem are guaranteed to be valid at this point si= nce callers @@ -153,12 +155,15 @@ unsafe fn init(&mut self) { Self::TYPE_INFO.name, 0x1000, ); - let sbd =3D addr_of_mut!(*self).cast::(); sysbus_init_mmio(sbd, addr_of_mut!(self.iomem)); - for irq in self.interrupts.iter_mut() { - sysbus_init_irq(sbd, irq); - } } + + for irq in self.interrupts.iter() { + sbd.init_irq(irq); + } + + let dev =3D addr_of_mut!(*self).cast::(); + // SAFETY: // // self.clock is not initialized at this point; but since `NonNull= <_>` is Copy, @@ -498,10 +503,7 @@ pub fn put_fifo(&mut self, value: c_uint) { pub fn update(&self) { let flags =3D self.int_level & self.int_enabled; for (irq, i) in self.interrupts.iter().zip(IRQMASK) { - // SAFETY: self.interrupts have been initialized in init(). - unsafe { - qemu_set_irq(*irq, i32::from(flags & i !=3D 0)); - } + irq.set(flags & i !=3D 0); } } =20 diff --git a/rust/qemu-api/meson.build b/rust/qemu-api/meson.build index edc21e1a3f8..973cfbcfb4a 100644 --- a/rust/qemu-api/meson.build +++ b/rust/qemu-api/meson.build @@ -17,7 +17,9 @@ _qemu_api_rs =3D static_library( 'src/c_str.rs', 'src/definitions.rs', 'src/device_class.rs', + 'src/irq.rs', 'src/offset_of.rs', + 'src/sysbus.rs', 'src/vmstate.rs', 'src/zeroable.rs', ], diff --git a/rust/qemu-api/src/irq.rs b/rust/qemu-api/src/irq.rs new file mode 100644 index 00000000000..7dbff007995 --- /dev/null +++ b/rust/qemu-api/src/irq.rs @@ -0,0 +1,66 @@ +// Copyright 2024 Red Hat, Inc. +// Author(s): Paolo Bonzini +// SPDX-License-Identifier: GPL-2.0-or-later + +//! Bindings for interrupt sources + +use core::ptr; + +use crate::{ + bindings::{qemu_set_irq, IRQState}, + cell::BqlCell, +}; + +/// Interrupt sources are used by devices to pass changes to a boolean val= ue to +/// other devices (typically interrupt or GPIO controllers). QEMU interru= pt +/// sources are always active-high. +/// +/// 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 +/// [`SysBusDevice::init_irq`](crate::sysbus::SysBusDevice::init_irq), and +/// initially leaves the pointer to a NULL value, representing an unconnec= ted +/// interrupt. To connect it, whoever creates the device fills the pointer= with +/// the sink's `IRQState *`, for example using `sysbus_connect_irq`. Beca= use +/// devices are generally shared objects, interrupt sources are an example= of +/// the interior mutability pattern. +/// +/// Interrupt sources can only be triggered under the Big QEMU Lock; they = are +/// neither `Send` nor `Sync`. +#[derive(Debug)] +pub struct InterruptSource(BqlCell<*mut IRQState>); + +impl InterruptSource { + /// Send a low (`false`) value to the interrupt sink. + pub fn lower(&self) { + self.set(false); + } + + /// Send a high-low pulse to the interrupt sink. + pub fn pulse(&self) { + self.set(true); + self.set(false); + } + + /// Send a high (`true`) value to the interrupt sink. + pub fn raise(&self) { + self.set(true); + } + + /// Send `level` to the interrupt sink. + pub fn set(&self, level: bool) { + unsafe { + qemu_set_irq(self.0.get(), level.into()); + } + } + + pub(crate) const fn as_ptr(&self) -> *mut *mut IRQState { + self.0.as_ptr() + } +} + +impl Default for InterruptSource { + fn default() -> Self { + InterruptSource(BqlCell::new(ptr::null_mut())) + } +} diff --git a/rust/qemu-api/src/lib.rs b/rust/qemu-api/src/lib.rs index b04d110b3f5..aa692939688 100644 --- a/rust/qemu-api/src/lib.rs +++ b/rust/qemu-api/src/lib.rs @@ -11,7 +11,9 @@ pub mod cell; pub mod definitions; pub mod device_class; +pub mod irq; pub mod offset_of; +pub mod sysbus; pub mod vmstate; pub mod zeroable; =20 diff --git a/rust/qemu-api/src/sysbus.rs b/rust/qemu-api/src/sysbus.rs new file mode 100644 index 00000000000..1a9b8a1f971 --- /dev/null +++ b/rust/qemu-api/src/sysbus.rs @@ -0,0 +1,26 @@ +// Copyright 2024 Red Hat, Inc. +// Author(s): Paolo Bonzini +// SPDX-License-Identifier: GPL-2.0-or-later + +use std::ptr::addr_of; + +pub use bindings::{SysBusDevice, SysBusDeviceClass}; + +use crate::{bindings, irq::InterruptSource}; + +impl SysBusDevice { + /// Return `self` cast to a mutable pointer, for use in calls to C cod= e. + const fn as_mut_ptr(&self) -> *mut SysBusDevice { + addr_of!(*self) as *mut _ + } + + /// Expose an interrupt source outside the device as a qdev GPIO outpu= t. + /// Note that the ordering of calls to `init_irq` is important, since + /// whoever creates the sysbus device will refer to the interrupts with + /// a number that corresponds to the order of calls to `init_irq`. + pub fn init_irq(&self, irq: &InterruptSource) { + unsafe { + bindings::sysbus_init_irq(self.as_mut_ptr(), irq.as_ptr()); + } + } +} --=20 2.47.0