From: Zhao Liu <zhao1.liu@intel.com>
To: "Paolo Bonzini" <pbonzini@redhat.com>,
"Peter Xu" <peterx@redhat.com>,
"David Hildenbrand" <david@redhat.com>,
"Philippe Mathieu-Daudé" <philmd@linaro.org>,
"Manos Pitsidianakis" <manos.pitsidianakis@linaro.org>,
"Alex Bennée" <alex.bennee@linaro.org>,
"Thomas Huth" <thuth@redhat.com>,
"Junjie Mao" <junjie.mao@hotmail.com>
Cc: qemu-devel@nongnu.org, qemu-rust@nongnu.org,
Dapeng Mi <dapeng1.mi@linux.intel.com>,
Chuanxiao Dong <chuanxiao.dong@intel.com>,
Zhao Liu <zhao1.liu@intel.com>
Subject: [RFC 24/26] rust/memory: Provide AddressSpace bindings
Date: Thu, 7 Aug 2025 20:30:25 +0800 [thread overview]
Message-ID: <20250807123027.2910950-25-zhao1.liu@intel.com> (raw)
In-Reply-To: <20250807123027.2910950-1-zhao1.liu@intel.com>
QEMU's AddressSpace matches vm_memory::GuestAddressSpace very well,
so it's straightforward to implement vm_memory::GuestAddressSpace trait
for AddressSpace structure.
And since QEMU's memory is almost entirely processed through
AddressSpace, provide the high-level memory write/read/store/load
interfaces for Rust side use.
Additionally, provide the safe binding for address_space_memory.
Signed-off-by: Zhao Liu <zhao1.liu@intel.com>
---
rust/qemu-api/src/memory.rs | 149 +++++++++++++++++++++++++++++++++---
1 file changed, 140 insertions(+), 9 deletions(-)
diff --git a/rust/qemu-api/src/memory.rs b/rust/qemu-api/src/memory.rs
index 23347f35e5da..42bba23cf3f8 100644
--- a/rust/qemu-api/src/memory.rs
+++ b/rust/qemu-api/src/memory.rs
@@ -3,7 +3,7 @@
// SPDX-License-Identifier: GPL-2.0-or-later
//! Bindings for `MemoryRegion`, `MemoryRegionOps`, `MemTxAttrs`
-//! `MemoryRegionSection` and `FlatView`.
+//! `MemoryRegionSection`, `FlatView` and `AddressSpace`.
use std::{
ffi::{c_uint, c_void, CStr, CString},
@@ -11,7 +11,7 @@
marker::PhantomData,
mem::size_of,
ops::Deref,
- ptr::NonNull,
+ ptr::{addr_of, NonNull},
sync::atomic::Ordering,
};
@@ -19,21 +19,25 @@
pub use bindings::{hwaddr, MemTxAttrs};
pub use vm_memory::GuestAddress;
use vm_memory::{
- bitmap::BS, Address, AtomicAccess, Bytes, GuestMemory, GuestMemoryError, GuestMemoryRegion,
- GuestMemoryResult, GuestUsize, MemoryRegionAddress, ReadVolatile, VolatileSlice, WriteVolatile,
+ bitmap::BS, Address, AtomicAccess, Bytes, GuestAddressSpace, GuestMemory, GuestMemoryError,
+ GuestMemoryRegion, GuestMemoryResult, GuestUsize, MemoryRegionAddress, ReadVolatile,
+ VolatileSlice, WriteVolatile,
};
use crate::{
bindings::{
- self, address_space_lookup_section, device_endian, flatview_ref,
- flatview_translate_section, flatview_unref, memory_region_init_io, section_access_allowed,
- section_covers_region_addr, section_fuzz_dma_read, section_get_host_addr,
- section_rust_load, section_rust_read_continue_step, section_rust_store,
- section_rust_write_continue_step, MEMTX_OK,
+ self, address_space_lookup_section, address_space_memory, address_space_to_flatview,
+ device_endian, flatview_ref, flatview_translate_section, flatview_unref,
+ memory_region_init_io, section_access_allowed, section_covers_region_addr,
+ section_fuzz_dma_read, section_get_host_addr, section_rust_load,
+ section_rust_read_continue_step, section_rust_store, section_rust_write_continue_step,
+ MEMTX_OK,
},
callbacks::FnCall,
cell::Opaque,
+ error::{Error, Result},
prelude::*,
+ rcu::{rcu_read_lock, rcu_read_unlock},
uninit::MaybeUninitField,
zeroable::Zeroable,
};
@@ -1016,3 +1020,130 @@ fn clone(&self) -> Self {
)
}
}
+
+/// A safe wrapper around [`bindings::AddressSpace`].
+///
+/// [`AddressSpace`] is the address space abstraction in QEMU, which
+/// provides memory access for the Guest memory it managed.
+#[repr(transparent)]
+#[derive(qemu_api_macros::Wrapper)]
+pub struct AddressSpace(Opaque<bindings::AddressSpace>);
+
+unsafe impl Send for AddressSpace {}
+unsafe impl Sync for AddressSpace {}
+
+impl GuestAddressSpace for AddressSpace {
+ type M = FlatView;
+ type T = FlatViewRefGuard;
+
+ /// Get the memory of the [`AddressSpace`].
+ ///
+ /// This function retrieves the [`FlatView`] for the current
+ /// [`AddressSpace`]. And it should be called from an RCU
+ /// critical section. The returned [`FlatView`] is used for
+ /// short-term memory access.
+ ///
+ /// Note, this function method may **panic** if [`FlatView`] is
+ /// being distroying. Fo this case, we should consider to providing
+ /// the more stable binding with [`bindings::address_space_get_flatview`].
+ fn memory(&self) -> Self::T {
+ let flatp = unsafe { address_space_to_flatview(self.0.as_mut_ptr()) };
+ FlatViewRefGuard::new(unsafe { Self::M::from_raw(flatp) }).expect(
+ "Failed to clone FlatViewRefGuard: the FlatView may have been destroyed concurrently.",
+ )
+ }
+}
+
+/// The helper to convert [`vm_memory::GuestMemoryError`] to
+/// [`crate::error::Error`].
+#[track_caller]
+fn guest_mem_err_to_qemu_err(err: GuestMemoryError) -> Error {
+ match err {
+ GuestMemoryError::InvalidGuestAddress(addr) => {
+ Error::from(format!("Invalid guest address: {:#x}", addr.raw_value()))
+ }
+ GuestMemoryError::InvalidBackendAddress => Error::from("Invalid backend memory address"),
+ GuestMemoryError::GuestAddressOverflow => {
+ Error::from("Guest address addition resulted in an overflow")
+ }
+ GuestMemoryError::CallbackOutOfRange => {
+ Error::from("Callback accessed memory out of range")
+ }
+ GuestMemoryError::IOError(io_err) => Error::with_error("Guest memory I/O error", io_err),
+ other_err => Error::with_error("An unexpected guest memory error occurred", other_err),
+ }
+}
+
+impl AddressSpace {
+ /// The write interface of `AddressSpace`.
+ ///
+ /// This function is similar to `address_space_write` in C side.
+ ///
+ /// But it assumes the memory attributes is MEMTXATTRS_UNSPECIFIED.
+ pub fn write(&self, buf: &[u8], addr: GuestAddress) -> Result<usize> {
+ rcu_read_lock();
+ let r = self.memory().deref().write(buf, addr);
+ rcu_read_unlock();
+ r.map_err(guest_mem_err_to_qemu_err)
+ }
+
+ /// The read interface of `AddressSpace`.
+ ///
+ /// This function is similar to `address_space_read_full` in C side.
+ ///
+ /// But it assumes the memory attributes is MEMTXATTRS_UNSPECIFIED.
+ ///
+ /// It should also be noted that this function does not support the fast
+ /// path like `address_space_read` in C side.
+ pub fn read(&self, buf: &mut [u8], addr: GuestAddress) -> Result<usize> {
+ rcu_read_lock();
+ let r = self.memory().deref().read(buf, addr);
+ rcu_read_unlock();
+ r.map_err(guest_mem_err_to_qemu_err)
+ }
+
+ /// The store interface of `AddressSpace`.
+ ///
+ /// This function is similar to `address_space_st{size}` in C side.
+ ///
+ /// But it only assumes @val follows target-endian by default. So ensure
+ /// the endian of `val` aligned with target, before using this method.
+ ///
+ /// And it assumes the memory attributes is MEMTXATTRS_UNSPECIFIED.
+ pub fn store<T: AtomicAccess>(&self, addr: GuestAddress, val: T) -> Result<()> {
+ rcu_read_lock();
+ let r = self.memory().deref().store(val, addr, Ordering::Relaxed);
+ rcu_read_unlock();
+ r.map_err(guest_mem_err_to_qemu_err)
+ }
+
+ /// The load interface of `AddressSpace`.
+ ///
+ /// This function is similar to `address_space_ld{size}` in C side.
+ ///
+ /// But it only support target-endian by default. The returned value is
+ /// with target-endian.
+ ///
+ /// And it assumes the memory attributes is MEMTXATTRS_UNSPECIFIED.
+ pub fn load<T: AtomicAccess>(&self, addr: GuestAddress) -> Result<T> {
+ rcu_read_lock();
+ let r = self.memory().deref().load(addr, Ordering::Relaxed);
+ rcu_read_unlock();
+ r.map_err(guest_mem_err_to_qemu_err)
+ }
+}
+
+/// The safe binding around [`bindings::address_space_memory`].
+///
+/// `ADDRESS_SPACE_MEMORY` provides the complete address space
+/// abstraction for the whole Guest memory.
+pub static ADDRESS_SPACE_MEMORY: &AddressSpace = unsafe {
+ let ptr: *const bindings::AddressSpace = addr_of!(address_space_memory);
+
+ // SAFETY: AddressSpace is #[repr(transparent)].
+ let wrapper_ptr: *const AddressSpace = ptr.cast();
+
+ // SAFETY: `address_space_memory` structure is valid in C side during
+ // the whole QEMU life.
+ &*wrapper_ptr
+};
--
2.34.1
next prev parent reply other threads:[~2025-08-07 12:18 UTC|newest]
Thread overview: 58+ messages / expand[flat|nested] mbox.gz Atom feed top
2025-08-07 12:30 [RFC 00/26] rust/memory: Integrate the vm-memory API from rust-vmm Zhao Liu
2025-08-07 12:30 ` [RFC 01/26] rust/hpet: Fix the error caused by vm-memory Zhao Liu
2025-08-07 13:52 ` Paolo Bonzini
2025-08-08 7:27 ` Zhao Liu
2025-08-07 12:30 ` [RFC 02/26] rust/cargo: Add the support for vm-memory Zhao Liu
2025-08-07 12:30 ` [RFC 03/26] subprojects: Add thiserror-impl crate Zhao Liu
2025-08-07 12:30 ` [RFC 04/26] subprojects: Add thiserror crate Zhao Liu
2025-08-07 12:30 ` [RFC 05/26] subprojects: Add winapi-i686-pc-windows-gnu crate Zhao Liu
2025-08-07 12:30 ` [RFC 06/26] subprojects: Add winapi-x86_64-pc-windows-gnu crate Zhao Liu
2025-08-07 12:30 ` [RFC 07/26] subprojects: Add winapi crate Zhao Liu
2025-08-07 13:17 ` Paolo Bonzini
2025-08-08 7:33 ` Zhao Liu
2025-08-07 12:30 ` [RFC 08/26] subprojects: Add vm-memory crate Zhao Liu
2025-08-07 12:30 ` [RFC 09/26] rust: Add vm-memory in meson Zhao Liu
2025-08-07 12:30 ` [RFC 10/26] subprojects/vm-memory: Patch vm-memory for QEMU memory backend Zhao Liu
2025-08-07 13:59 ` Paolo Bonzini
2025-08-08 8:17 ` Zhao Liu
2025-08-08 8:17 ` Paolo Bonzini
2025-08-08 8:51 ` Zhao Liu
2025-08-07 12:30 ` [RFC 11/26] rust/cargo: Specify the patched vm-memory crate Zhao Liu
2025-08-07 12:30 ` [RFC 12/26] rcu: Make rcu_read_lock & rcu_read_unlock not inline Zhao Liu
2025-08-07 13:54 ` Paolo Bonzini
2025-08-08 8:19 ` Zhao Liu
2025-08-07 12:30 ` [RFC 13/26] rust: Add RCU bindings Zhao Liu
2025-08-07 12:29 ` Manos Pitsidianakis
2025-08-07 13:38 ` Paolo Bonzini
2025-08-09 7:21 ` Zhao Liu
2025-08-09 9:13 ` Paolo Bonzini
2025-08-09 9:26 ` Manos Pitsidianakis
2025-08-12 10:43 ` Zhao Liu
2025-08-12 10:31 ` Zhao Liu
2025-08-07 12:30 ` [RFC 14/26] memory: Expose interfaces about Flatview reference count to Rust side Zhao Liu
2025-08-07 12:30 ` [RFC 15/26] memory: Rename address_space_lookup_region and expose it " Zhao Liu
2025-08-07 12:30 ` [RFC 16/26] memory: Make flatview_do_translate() return a pointer to MemoryRegionSection Zhao Liu
2025-08-07 13:57 ` Paolo Bonzini
2025-08-12 15:39 ` Zhao Liu
2025-08-12 15:42 ` Manos Pitsidianakis
2025-08-13 15:12 ` Zhao Liu
2025-08-12 19:23 ` Paolo Bonzini
2025-08-13 15:10 ` Zhao Liu
2025-08-07 12:30 ` [RFC 17/26] memory: Add a translation helper to return MemoryRegionSection Zhao Liu
2025-08-07 12:30 ` [RFC 18/26] memory: Rename flatview_access_allowed() to memory_region_access_allowed() Zhao Liu
2025-08-07 12:41 ` Manos Pitsidianakis
2025-08-07 12:30 ` [RFC 19/26] memory: Add MemoryRegionSection based misc helpers Zhao Liu
2025-08-07 12:30 ` [RFC 20/26] memory: Add wrappers of intermediate steps for read/write Zhao Liu
2025-08-07 12:30 ` [RFC 21/26] memory: Add store/load interfaces for Rust side Zhao Liu
2025-08-07 12:30 ` [RFC 22/26] rust/memory: Implement vm_memory::GuestMemoryRegion for MemoryRegionSection Zhao Liu
2025-08-07 12:30 ` [RFC 23/26] rust/memory: Implement vm_memory::GuestMemory for FlatView Zhao Liu
2025-08-07 12:30 ` Zhao Liu [this message]
2025-08-07 13:50 ` [RFC 24/26] rust/memory: Provide AddressSpace bindings Paolo Bonzini
2025-08-13 14:47 ` Zhao Liu
2025-08-07 12:30 ` [RFC 25/26] rust/memory: Add binding to check target endian Zhao Liu
2025-08-07 12:44 ` Manos Pitsidianakis
2025-08-13 14:48 ` Zhao Liu
2025-08-07 12:30 ` [RFC 26/26] rust/hpet: Use safe binding to access address space Zhao Liu
2025-08-07 12:42 ` [RFC 00/26] rust/memory: Integrate the vm-memory API from rust-vmm Zhao Liu
2025-08-07 14:13 ` Paolo Bonzini
2025-08-13 14:56 ` Zhao Liu
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=20250807123027.2910950-25-zhao1.liu@intel.com \
--to=zhao1.liu@intel.com \
--cc=alex.bennee@linaro.org \
--cc=chuanxiao.dong@intel.com \
--cc=dapeng1.mi@linux.intel.com \
--cc=david@redhat.com \
--cc=junjie.mao@hotmail.com \
--cc=manos.pitsidianakis@linaro.org \
--cc=pbonzini@redhat.com \
--cc=peterx@redhat.com \
--cc=philmd@linaro.org \
--cc=qemu-devel@nongnu.org \
--cc=qemu-rust@nongnu.org \
--cc=thuth@redhat.com \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).