rust/memory: Integrate the vm-memory API from rust-vmm
Subsystems (2)
v2 cover rust/memory: Integrate the vm-memory API from rust-vmm
Hi,
This RFC series explores integrating the vm-memory API into QEMU's rust/memory bindings.
Compared to v1 [*], v2 has the following main changes:
* Upgrade vm-memory to v0.18.0, and drop QEMU-specific patches in v1.
- Thanks to Paolo and Hanna, the mian gaps identified in v1 have been largely resolved:
1) Blanket Bytes<GuestAddress> trait for GuestMemory: done.
2) Extend try_access: try_access has been deprecated, so that QEMU is free to decide ...
...whether to use a private try_access method (Patch 19):
FlatView::try_access_full()
...or to switch to iterator (Patch 20):
FlatViewChunk / FlatViewChunkIterator / FlatView::get_chunks()
* Drop native endianness and require explicit endianness at AddressSpace::store and load.
- EndianValued trait bound: Patch 22.
And now we can have:
ADDRESS_SPACE_MEMORY.store(GuestAddress(addr), Le32::from(val))
* "Rich" expression in the Bytes trait:
- impl Bytes<(MemoryRegionAddress, MemTxAttrs)> for MemoryRegionSection
- impl Bytes<(GuestAddress, MemTxAttrs)> for FlatView
* New RCU binding - Patch 9.
* New HPET FSB test (to verify memory store).
- the full test is a gap since it's no way to link physmem.c without a emulator.
Overall, there have been quite a few changes since v1. For more details, please refer to the Changelog sction.
[*] RFC v1: https://lore.kernel.org/qemu-devel/[email protected]/
Thanks for your feedback!
Background
==========
About vm-memory crate, it's design documentation said:
"The vm-memory crate focuses on defining consumer side interfaces to
access the physical memory of the VM. It does not define how the underlying VM memory provider is implemented. Lightweight VMMs like CrosVM and Firecracker can make assumptions about the structure of VM's physical memory and implement a lightweight backend to access it. For VMMs like Qemu, a high performance and full functionality backend may be implemented with less assumptions."
At present, in addition to the memory model abstractions (including GuestMemoryRegion, GuestMemory, and AddressSpace) it provides, it also implements a simple memory management backend based on mmap for RAM access.
However, for QEMU, the backend implementation based on vm-memory is more complex, as QEMU not only needs to consider MMIO/IOMMU, but also complex situations such as different endian/memory attributes.
This series tries to integrate vm-memory API for QEMU.
But... wait, why vm-memory is necessary?
QEMU needs the safe Rust bindings for memory access. Whatever vm-memory is used or not, there'll be the similar wrappers over AddressSpace/ FlatView/MemorySection, and there'll be the safe bindings for translation/ memory store, load, read and write.
Even if we don't use vm-memory, we will likely end up creating something similar to vm-memory.
Furthermore, many components in vm-memory are also inspiring for enhancements on the QEMU Rust side.
So, why not have a try?
Introduction
============
The core idea of this series is simple:
* Implement vm_memory::GuestMemoryRegion trait for MemoryRegionSection to represent (non-overlapping) memory region.
vm_memory::GuestMemoryRegion trait itself doesn't provide any interface to access memory. So vm_memory::Bytes trait is also necessary for MemoryRegionSection to access memory region.
* Implement vm_memory::GuestMemory trait for FlatView to manage Guest memory regions (that's MemoryRegionSection).
Similarly, vm_memory::Bytes trait is also needed for FlatView to provide methods to write/read/store/load memory.
* Implement vm_memory::AddressSpace tarit for AddressSpace, to provide a safe address space abstraction at Rust side.
For the above three parts, the most critical stuff is related to MemoryRegionSection.
Currently QEMU's memory API is built around MemoryRegion, and MemoryRegionSection is only for internal use at the most time.
But vm_memory::GuestMemoryRegion trait requires us to wrap unsafe C bindings based on MemoryRegionSection. So it's necessary to expose some C memory APIs based MemoryRegionSection. This is the following section:
NEW QEMU memory APIs wrappers at C side
=======================================
Around MemoryRegionSection, this series provides these interfaces:
* Some straightforward wrappers over original C interfaces:
- section_access_allowed
- section_covers_region_addr,
- section_fuzz_dma_read
* Critical wrappers for intermediate memroy read/write (they're still simple wrapper over C functions):
- rust_section_read_continue_step
- rust_section_write_continue_step
With the above step helpers, Rust could build its own read/write loop (a simple loop or iteration with iterator).
* And, special C helpers for memory load/store:
- rust_section_load
MemTxResult rust_section_load(MemoryRegionSection *section,
hwaddr mr_offset, uint8_t *buf, MemTxAttrs attrs, hwaddr len);
- rust_section_store
MemTxResult rust_section_store(MemoryRegionSection *section,
hwaddr mr_offset, const uint8_t *buf, MemTxAttrs attrs, hwaddr len);
These 2 load/store helpers are so different:
1) comparing with the detail implementations of address_space_ld{size}_{endian}/address_space_st{size}_{endian}, these 2 functions aren't bound with specific type (l, q, or w), and transfer the value via byte array.
This is because of the AtomicAccess bound in vm_memory::Bytes, which makes it difficult to convert AtomicAccess type to u64! (For more details, please refer the comments of Bytes::store/Bytes::load in patch 18 "rust/memory: Implement vm_memory::GuestMemoryRegion for MemoryRegionSection").
2) these 2 helpers do not have "endian" suffix since the endianness is specified by Rust side entries (via EndianValued trait bound). And more importantly, Rust entries do not support native endianness. So as the intermediate bridge, these C helpers do not strictly enforce endianness; that task is left to Rust.
Of course, some other wrappers are also needed for FlatView and AddressSpace:
* For FlatView:
- flatview_ref
- flatview_translate_section
- flatview_unref
* For AddressSpace:
- address_space_lookup_section
- address_space_memory
- address_space_get_flatview
They're all simple wrappers.
Endianness & Memory attributes
==============================
Rust side uses two different approaches to address the issues of endianness and memory attributes support.
Endianness
----------
Rust side introduces EndianValued trait which packs endian types from vm-memory: LeNN & BeNN.
Then the top-level entries could limit endianness for its argument type. For example:
impl AddressSpace {
...
pub fn store<T: EndianValued>(&self, addr: GuestAddress, val: T) -> Result<()> {}
pub fn load<T: EndianValued>(&self, addr: GuestAddress) -> Result<T>{}...
}
The above store and load methods only accetpt explicit endian types:
Le32 (little endian 32 bits), Be64 (big endian 64 bits), etc.
And they reject plain (without explicit endianness/depend on host endianness) types: u32, u64.
The EndianValued trait bound in Rust serves the same purpose as the "endian" suffixes in C-side functions (such as *_le and *_be).
Memory Attributes
-----------------
Unlike the default Bytes implementation in vm-memory, QEMU Rust integrates MemAttrs into Bytes as well:
impl Bytes<(MemoryRegionAddress, MemTxAttrs)> for MemoryRegionSection impl Bytes<(GuestAddress, MemTxAttrs)> for FlatView
so that all methods (write/read/store/load) under Bytes trait could accept "(MemoryRegionAddress, MemTxAttrs)" as the parameter type, which includes both address and MemTxAttrs information.
QEMU's FlatViewChunk vs vm-memory's VolatileSlice
=================================================
VolatileSlice of vm-memory cannot be applied to QEMU since it only support RAM with host address pointer.
In RFC v1 (with vm-memory v0.16.0), there was no need to consider such things in the first place.
However, vm-memory (v0.18.0) deprecated GestMemoryBackend::try_access() and switched to using the iterator to implement memory access via get_slices(), which is built on VolatileSlice and GuestMemoryBackendSliceIterator.
QEMU has two options: either keep the try_access()-style loop, or switch to its own get_slices()-style implementation.
For option #1, that's the patch 19, which has the try_access_full() out of GestMemoryBackend trait and try_access_full() is a private/ inherent method of FlatView.
For option #2, patch 20 introduces FlatViewChunk (similar to VolatileSlice), FlatViewChunkIterator (similar to GuestMemoryBackendSliceIterator) and get_chunks() (simialr to get_slices()).
Of these two options, option #1 is simpler, but option #2 demonstrates QEMU's requirements for something similar to VolatileSlice, which is insightful for considering higher-level slice/iterator abstractions upstream.
NEW QEMU memory bindings/APIs based on vm-memory at Rust side
=============================================================
With all of the above are ready, now we could have the safe bindings for the memory access in Rust side.
* write:
```
use system::memory::{GuestAddress, ADDRESS_SPACE_MEMORY};
let addr = GuestAddress(0x123123000);
let buf = [0x1, 0x2, 0x3, 0x4];
assert!(ADDRESS_SPACE_MEMORY.write(&buf, addr).is_ok());
```* read:
```
use system::memory::{GuestAddress, ADDRESS_SPACE_MEMORY};
let addr = GuestAddress(0x123123000);
let mut buf = [0u8; 4];
assert!(ADDRESS_SPACE_MEMORY.read(&mut buf, addr).is_ok());
```* load:
```
use system::memory::{GuestAddress, Le32, ADDRESS_SPACE_MEMORY};
let addr = GuestAddress(0x123123000);
assert!(ADDRESS_SPACE_MEMORY.load::<Le32>(addr).is_ok());
```* store:
```
use system::memory::{GuestAddress, Le32, ADDRESS_SPACE_MEMORY};
let addr = GuestAddress(0x123123000);
assert!(ADDRESS_SPACE_MEMORY.store(addr, Le32::from(5)).is_ok());
```Remaining Gap
=============
The full test is a gap since it's no way to link physmem.c without a emulator at Rust side. Instead, provide a HPET FSB qtest case.
Change Log
==========
* Use From instead of Into for u8->usize type conversion issue.
* Upgrade vm-memory dependency to v0.18.0
* Update Cargo.lock.
* Drop windows dependencies for vm-memory.
* Drop extra QEMU specific patches for vm-memory.
* Add rust wrappers instead of dropping inline for C rcu read lock & unlock interfaces.
* Include rcu.h in util-sys binding.
* Use RAII pattern to guard RCU locking.
* New RcuCell to simplify RCU read in Rust.
* Do not expose address_space_to_flatview() to Rust anymore. Instead, implement address_space_get_flatview() at Rust side.
* Drop section_get_host_addr().
* Drop the native endian assumption and require the caller to use the target device's endianness.
* Implement GuestMemoryRegionBytes for MemoryRegionSection to satisfy supertrait requirement.
* Implement Bytes<(MemoryRegionAddress, MemTxAttrs)> to attach MemTxAttrs.
* For write/read, add an extra loop to ensure write/read are actually finished within the same region.
* Implement Bytes<(MemoryRegionAddress, MemTxAttrs)> to attach MemTxAttrs.
* Move GuestMemoryBackend::try_access() to FlatView::try_access_full().
* Use vm-memory::Permissions to replace is_write flag.
* Implement get_chunks with iterator for memory access.
* Implement EndianValued trait to bind top level store & load entries.
* Implement GuestAddressSpace for &AddressSpace since it requires Clone for now.
* Re-implement RCU protection logic by using RcuCell and lifetime to provide RCU critical section.
* Fix AddressSapce::memory() and use a loop just like C side did.
* Explicitly require AddressSpace::save and load specify endianness and no longer rely on native endianness.
* Explicitly specify endianness by Le32 and get rid of native endianness.
* Drop expect() method to avoid abort() on error - consistent with the behavior on the C side.
* New HPET test case.
Thanks and Best Regards,
Zhao
---
Zhao Liu (26):
rust/hpet: Fix the error caused by vm-memory
rust/cargo: Add the support for vm-memory
subprojects: Add thiserror-impl crate
subprojects: Add thiserror crate
subprojects: Add vm-memory crate
rust: Add vm-memory in meson
rcu: Add rust wrappers for rcu_read_lock & rcu_read_unlock rust/bindings/util-sys: Include rcu.h in bindings wrapper rust/util: Add RCU bindings
memory: Expose FlatView refcount interfaces to Rust
memory: Rename address_space_lookup_region and expose it to Rust
memory: Make flatview_do_translate() return a pointer to
MemoryRegionSection
memory: Add a translation helper to return a MemoryRegionSection
memory: Rename flatview_access_allowed() to
memory_region_access_allowed()
memory: Add MemoryRegionSection-based misc helpers
memory: Add wrappers for intermediate read/write steps
memory: Add store/load interfaces for Rust rust/system/memory: Implement vm_memory::GuestMemoryRegion for
MemoryRegionSection
rust/system/memory: Implement vm_memory::GuestMemory for FlatView rust/system/memory: Switch to iteration style for memory access rust/system/memory: Add an RAII guard to manage FlatView reference
counts
rust/system/memory: Wrap vm-memory's endian types for explicit access rust/memory: Provide AddressSpace bindings
rust/hpet: Use safe binding to access address space hw/timer/hpet: Add HPET_TN_BASE macro
tests/qtest: Add HPET test case to verify FSB store
hw/timer/hpet.c | 8 +- include/hw/timer/hpet.h | 1 + include/qemu/rcu.h | 18 + include/system/memory.h | 273 +++- rust/Cargo.lock | 33 +- rust/Cargo.toml | 1 + rust/bindings/hwcore-sys/lib.rs | 2 +- rust/bindings/system-sys/lib.rs | 2 +- rust/bindings/util-sys/wrapper.h | 1 + rust/hw/char/pl011/wrapper.h | 1 + rust/hw/timer/hpet/src/device.rs | 31 +- rust/meson.build | 2 + rust/system/Cargo.toml | 1 + rust/system/meson.build | 2 +- rust/system/src/memory.rs | 1294 ++++++++++++++++- rust/util/src/lib.rs | 1 + rust/util/src/rcu.rs | 137 ++ scripts/archive-source.sh | 3 + scripts/make-release | 3 +- subprojects/.gitignore | 3 + .../packagefiles/thiserror-1-rs/meson.build | 23 + .../thiserror-impl-1-rs/meson.build | 41 + .../vm-memory-0.18-rs/meson.build | 27 + subprojects/thiserror-1-rs.wrap | 10 + subprojects/thiserror-impl-1-rs.wrap | 10 + subprojects/vm-memory-0.18-rs.wrap | 10 + system/memory-internal.h | 1 - system/memory.c | 2 +- system/physmem.c | 203 ++- tests/qtest/hpet-test.c | 77 + tests/qtest/meson.build | 1 + util/rcu.c | 10 + 32 files changed, 2142 insertions(+), 90 deletions(-) create mode 100644 rust/util/src/rcu.rs create mode 100644 subprojects/packagefiles/thiserror-1-rs/meson.build create mode 100644 subprojects/packagefiles/thiserror-impl-1-rs/meson.build create mode 100644 subprojects/packagefiles/vm-memory-0.18-rs/meson.build create mode 100644 subprojects/thiserror-1-rs.wrap create mode 100644 subprojects/thiserror-impl-1-rs.wrap create mode 100644 subprojects/vm-memory-0.18-rs.wrap create mode 100644 tests/qtest/hpet-test.c
Signature · 1 line
2.34.1
RFC v2 1/26 rust/hpet: Fix the error caused by vm-memory
error[E0283]: type annotations needed
--> hw/timer/hpet/src/device.rs:884:55
|
884 | self.num_timers == self.num_timers_save.get().into()
| -- ^^^^
| |
| type must be known at this point
| = note: multiple impls satisfying usize: PartialEq<_> found in the following crates: core, vm_memory:
- impl PartialEq<vm_memory::endian::BeSize> for usize;
- impl PartialEq<vm_memory::endian::LeSize> for usize;
- impl<host> PartialEq for usize
where the constant host has type bool;
help: try using a fully qualified path to specify the expected types
|
884 | self.num_timers == <u8 as Into<T>>::into(self.num_timers_save.get())
| ++++++++++++++++++++++ ~For more information about this error, try rustc --explain E0283.
error: could not compile hpet (lib) due to 1 previous error
---
Changes since v1:
* Use From instead of Into.
--- rust/hw/timer/hpet/src/device.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
rust/hw/timer/hpet/src/device.rs +1 -1
@@ -959,7 +959,7 @@ fn is_offset_needed(&self) -> bool { }fn validate_num_timers (&self, _version_id:u8 ) ->bool { - self.num_timers == self.num_timers_save.get ().into () + self.num_timers == usize::from (self.num_timers_save.get ()) } }
Signature · 1 line
2.34.1
RFC v2 2/26 rust/cargo: Add the support for vm-memory
In reply to Zhao LiuUse vm-memory v0.18.0 for QEMU.
By the way, the dependency relationship for system-sys and hwcore-sys is also updated in Cargo.lock.
---
Changes since v1:
* Upgrade vm-memory dependency to v0.18.0
* Update Cargo.lock.
--- rust/Cargo.lock | 33 ++++++++++++++++++++++++++++++++- rust/Cargo.toml | 1 + rust/system/Cargo.toml | 1 + 3 files changed, 34 insertions(+), 1 deletion(-)
rust/Cargo.lock +32 -1
@@ -184,7 +184,6 @@ dependencies = [ "glib-sys", "migration-sys", "qom-sys", - "system-sys", "util-sys", ]
@@ -410,6 +409,7 @@ dependencies = [ "qom", "system-sys", "util", + "vm-memory", ] [[package]]
@@ -431,6 +431,7 @@ version = "0.1.0" dependencies = [ "common", "glib-sys", + "hwcore-sys", "migration-sys", "qom-sys", "util-sys",
@@ -456,6 +457,26 @@ dependencies = [ "util", ] +[[package]] +name = "thiserror" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "toml" version = "0.8.23"
@@ -535,6 +556,16 @@ version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" +[[package]] +name = "vm-memory" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b55e753c7725603745cb32b2287ef7ef3da05c03c7702cda3fa8abe25ae0465" +dependencies = [ + "libc", + "thiserror", +] + [[package]] name = "winnow" version = "0.7.13"
rust/Cargo.toml +1 -0
@@ -20,6 +20,7 @@ anyhow = "~1.0" foreign = "~0.3.1" libc = "0.2.162" glib-sys = { version = "0.21.2", features = ["v2_66"] } +vm-memory = "0.18.0" [workspace.lints.rust] unexpected_cfgs = { level = "deny", check-cfg = ['cfg(MESON)'] }
rust/system/Cargo.toml +1 -0
@@ -21,6 +21,7 @@ migration = { path = "../migration" } qom = { path = "../qom" } util = { path = "../util" } glib-sys.workspace = true +vm-memory.workspace = true [lints] workspace = true
Signature · 1 line
2.34.1
RFC v2 3/26 subprojects: Add thiserror-impl crate
In reply to Zhao LiuUse thiserror-impl-1 v1.0.65 for QEMU.
--- scripts/archive-source.sh | 1 + scripts/make-release | 2 +- subprojects/.gitignore | 1 + .../thiserror-impl-1-rs/meson.build | 41 +++++++++++++++++++ subprojects/thiserror-impl-1-rs.wrap | 10 +++++ 5 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 subprojects/packagefiles/thiserror-impl-1-rs/meson.build create mode 100644 subprojects/thiserror-impl-1-rs.wrap
scripts/archive-source.sh +1 -0
@@ -47,6 +47,7 @@ subprojects=( proc-macro2-1-rs quote-1-rs syn-2-rs + thiserror-impl-1-rs unicode-ident-1-rs ) sub_deinit=""
scripts/make-release +1 -1
@@ -44,7 +44,7 @@ SUBPROJECTS="libvfio-user keycodemapdb berkeley-softfloat-3 bilge-impl-0.2-rs either-1-rs foreign-0.3-rs itertools-0.11-rs libc-0.2-rs probe-0.5-rs proc-macro2-1-rs proc-macro-error-1-rs proc-macro-error-attr-1-rs quote-1-rs - syn-2-rs unicode-ident-1-rs" + syn-2-rs thiserror-impl-1-rs unicode-ident-1-rs" src="$1" version="$2"
subprojects/.gitignore +1 -0
@@ -22,6 +22,7 @@ /proc-macro* /quote-* /syn-* +/thiserror-impl-* /unicode-ident-* # Workaround for Meson v1.9.0 https://github.com/mesonbuild/meson/issues/14948
subprojects/packagefiles/thiserror-impl-1-rs/meson.build new file +41 -0
41 lines not on this page · raw message
subprojects/thiserror-impl-1-rs.wrap new file +10 -0
@@ -0,0 +1,10 @@ +[wrap-file] +directory = thiserror-impl-1.0.65 +source_url = https://crates.io/api/v1/crates/thiserror-impl/1.0.65/download +source_filename = thiserror-impl-1.0.65.tar.gz +source_hash = ae71770322cbd277e69d762a16c444af02aa0575ac0d174f0b9562d3b37f8602 +#method = cargo +patch_directory = thiserror-impl-1-rs + +# bump this version number on every change to meson.build or the patches: +# v2
Signature · 1 line
2.34.1
RFC v2 4/26 subprojects: Add thiserror crate
In reply to Zhao LiuUse thiserror v1.0.65 for QEMU.
--- scripts/archive-source.sh | 1 + scripts/make-release | 2 +- subprojects/.gitignore | 1 + .../packagefiles/thiserror-1-rs/meson.build | 23 +++++++++++++++++++ subprojects/thiserror-1-rs.wrap | 10 ++++++++ 5 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 subprojects/packagefiles/thiserror-1-rs/meson.build create mode 100644 subprojects/thiserror-1-rs.wrap
scripts/archive-source.sh +1 -0
@@ -47,6 +47,7 @@ subprojects=( proc-macro2-1-rs quote-1-rs syn-2-rs + thiserror-1-rs thiserror-impl-1-rs unicode-ident-1-rs )
scripts/make-release +1 -1
@@ -44,7 +44,7 @@ SUBPROJECTS="libvfio-user keycodemapdb berkeley-softfloat-3 bilge-impl-0.2-rs either-1-rs foreign-0.3-rs itertools-0.11-rs libc-0.2-rs probe-0.5-rs proc-macro2-1-rs proc-macro-error-1-rs proc-macro-error-attr-1-rs quote-1-rs - syn-2-rs thiserror-impl-1-rs unicode-ident-1-rs" + syn-2-rs thiserror-1-rs thiserror-impl-1-rs unicode-ident-1-rs" src="$1" version="$2"
subprojects/.gitignore +1 -0
@@ -22,6 +22,7 @@ /proc-macro* /quote-* /syn-* +/thiserror-* /thiserror-impl-* /unicode-ident-*
subprojects/packagefiles/thiserror-1-rs/meson.build new file +23 -0
@@ -0,0 +1,23 @@ +project('thiserror-1-rs', 'rust', + meson_version: '>=1.5.0', + version: '1.0.65', + license: 'MIT OR Apache-2.0', + default_options: []) + +subproject('thiserror-impl-1-rs', required: true) +thiserror_impl_rs = dependency('thiserror-impl-1-rs') + +_thiserror_rs = static_library( + 'thiserror', + files('src/lib.rs'), + gnu_symbol_visibility: 'hidden', + override_options: ['rust_std=2021', 'build.rust_std=2021'], + rust_abi: 'rust', + dependencies: [thiserror_impl_rs], +) + +thiserror_dep = declare_dependency( + link_with: _thiserror_rs, +) + +meson.override_dependency('thiserror-1-rs', thiserror_dep)
subprojects/thiserror-1-rs.wrap new file +10 -0
@@ -0,0 +1,10 @@ +[wrap-file] +directory = thiserror-1.0.65 +source_url = https://crates.io/api/v1/crates/thiserror/1.0.65/download +source_filename = thiserror-1.0.65.tar.gz +source_hash = 5d11abd9594d9b38965ef50805c5e469ca9cc6f197f883f717e0269a3057b3d5 +#method = cargo +patch_directory = thiserror-1-rs + +# bump this version number on every change to meson.build or the patches: +# v2
Signature · 1 line
2.34.1
RFC v2 5/26 subprojects: Add vm-memory crate
In reply to Zhao LiuUse vm-memory v0.18.0 for QEMU.
---
Changes since v1:
* Upgrade vm-memory to v0.18.0 then we don't need extra patch for vm-memory subproject in QEMU.
--- scripts/archive-source.sh | 1 + scripts/make-release | 3 ++- subprojects/.gitignore | 1 + .../vm-memory-0.18-rs/meson.build | 27 +++++++++++++++++++ subprojects/vm-memory-0.18-rs.wrap | 10 +++++++ 5 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 subprojects/packagefiles/vm-memory-0.18-rs/meson.build create mode 100644 subprojects/vm-memory-0.18-rs.wrap
scripts/archive-source.sh +1 -0
@@ -49,6 +49,7 @@ subprojects=( syn-2-rs thiserror-1-rs thiserror-impl-1-rs + vm-memory-0.18-rs unicode-ident-1-rs ) sub_deinit=""
scripts/make-release +2 -1
@@ -44,7 +44,8 @@ SUBPROJECTS="libvfio-user keycodemapdb berkeley-softfloat-3 bilge-impl-0.2-rs either-1-rs foreign-0.3-rs itertools-0.11-rs libc-0.2-rs probe-0.5-rs proc-macro2-1-rs proc-macro-error-1-rs proc-macro-error-attr-1-rs quote-1-rs - syn-2-rs thiserror-1-rs thiserror-impl-1-rs unicode-ident-1-rs" + syn-2-rs thiserror-1-rs thiserror-impl-1-rs unicode-ident-1-rs + vm-memory-0.18-rs" src="$1" version="$2"
subprojects/.gitignore +1 -0
@@ -25,6 +25,7 @@ /thiserror-* /thiserror-impl-* /unicode-ident-* +/vm-memory-* # Workaround for Meson v1.9.0 https://github.com/mesonbuild/meson/issues/14948 /.wraplock
subprojects/packagefiles/vm-memory-0.18-rs/meson.build new file +27 -0
@@ -0,0 +1,27 @@ +project('vm-memory-0.18-rs', 'rust', + meson_version: '>=1.5.0', + version : '0.18.0', + license : 'Apache-2.0 or BSD-3-Clause', + default_options: []) + +all_deps = [] + +subproject('thiserror-1-rs', required: true) +all_deps += dependency('thiserror-1-rs') + +_vm_memory_rs = static_library( + 'vm_memory', + files('src/lib.rs'), + gnu_symbol_visibility: 'hidden', + override_options : ['rust_std=2021', 'build.rust_std=2021'], + rust_abi : 'rust', + rust_args: ['--cap-lints', 'allow'], + dependencies: all_deps, + native: true, +) + +dep = declare_dependency( + link_with : _vm_memory_rs, +) + +meson.override_dependency('vm-memory-0.18-rs', dep, native: true)
subprojects/vm-memory-0.18-rs.wrap new file +10 -0
@@ -0,0 +1,10 @@ +[wrap-file] +directory = vm-memory-0.18.0 +source_url = https://crates.io/api/v1/crates/vm-memory/0.18.0/download +source_filename = vm-memory-0.18.0.tar.gz +source_hash = 9b55e753c7725603745cb32b2287ef7ef3da05c03c7702cda3fa8abe25ae0465 +#method = cargo +patch_directory = vm-memory-0.18-rs + +# bump this version number on every change to meson.build or the patches: +# v2
Signature · 1 line
2.34.1
RFC v2 6/26 rust: Add vm-memory in meson
In reply to Zhao LiuIntegrate vm-memory into meson.
---
Changes since v1:
* Upgrade vm-memory to v0.18.0.
--- rust/meson.build | 2 ++ rust/system/meson.build | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-)
rust/meson.build +2 -0
@@ -11,6 +11,7 @@ subproject('foreign-0.3-rs', required: true) subproject('glib-sys-0.21-rs', required: true) subproject('libc-0.2-rs', required: true) subproject('probe-0.5-rs', required: true) +subproject('vm-memory-0.18-rs', required: true) anyhow_rs = dependency('anyhow-1-rs') bilge_rs = dependency('bilge-0.2-rs')
@@ -19,6 +20,7 @@ foreign_rs = dependency('foreign-0.3-rs') glib_sys_rs = dependency('glib-sys-0.21-rs') libc_rs = dependency('libc-0.2-rs') probe_rs = dependency('probe-0.5-rs') +vm_memory_rs = dependency('vm-memory-0.18-rs') subproject('proc-macro2-1-rs', required: true) subproject('quote-1-rs', required: true)
rust/system/meson.build +1 -1
@@ -2,7 +2,7 @@ _system_rs = static_library( 'system', 'src/lib.rs', link_with: [_bql_rs, _hwcore_rs, _migration_rs, _qom_rs, _util_rs], - dependencies: [glib_sys_rs, common_rs, qemu_macros, system_sys_rs], + dependencies: [glib_sys_rs, common_rs, qemu_macros, system_sys_rs, vm_memory_rs], ) system_rs = declare_dependency(link_with: [_system_rs],
Signature · 1 line
2.34.1
RFC v2 7/26 rcu: Add rust wrappers for rcu_read_lock & rcu_read_unlock
In reply to Zhao LiuAdd rust wrappers for rcu_read_lock & rcu_read_unlock, then bindgen could generate the bindings.
---
Changes since v1:
* Add rust wrappers instead of dropping inline.
--- include/qemu/rcu.h | 18 ++++++++++++++++++ util/rcu.c | 10 ++++++++++ 2 files changed, 28 insertions(+)
include/qemu/rcu.h +18 -0
@@ -118,6 +118,24 @@ static inline void rcu_read_unlock(void) } } +/** +* rust_rcu_read_lock: +* +* A wrapper over rcu_read_lock(). +* Called from Rust to acquire an RCU read lock. +* Do not touch. +*/ +void rust_rcu_read_lock (void ); + +/** +* rust_rcu_read_unlock: +* +* A wrapper over rcu_read_unlock(). +* Called from Rust to release an RCU read lock. +* Do not touch. +*/ +void rust_rcu_read_unlock (void ); +void synchronize_rcu (void );/*
util/rcu.c +10 -0
@@ -171,6 +171,16 @@ static void wait_for_readers(void)QLIST_SWAP (®istry, &qsreaders, node); } +void rust_rcu_read_lock (void ) +{ +rcu_read_lock (); +} + +void rust_rcu_read_unlock (void ) +{ +rcu_read_unlock (); +} +void synchronize_rcu (void ) {QEMU_LOCK_GUARD (&rcu_sync_lock);
Signature · 1 line
2.34.1
RFC v2 8/26 rust/bindings/util-sys: Include rcu.h in bindings wrapper
In reply to Zhao Liurcu.h is transitively included by several crates' wrapper.h files (e.g. hwcore via hw/core/qdev.h, system via system/memory.h).
Because several structs (e.g. BusChild/FlatView/AddressSpace) embed struct rcu_head, bindgen automatically generates a rcu_head definition in each crate that references it.
Explicitly add rcu.h to util-sys/wrapper.h. With the allowlist-then- blocklist logic in generate_bindgen_args.py, this makes util-sys the only owner of rcu.h bindings. Then rcu.h is blocked in hwcore-sys and system-sys, thus it's necessary to import rcu_head from util_sys in hwcore-sys/lib.rs and system-sys/lib.rs.
---
Changes since v1:
* New commit.
--- rust/bindings/hwcore-sys/lib.rs | 2 +- rust/bindings/system-sys/lib.rs | 2 +- rust/bindings/util-sys/wrapper.h | 1 + 3 files changed, 3 insertions(+), 2 deletions(-)
rust/bindings/hwcore-sys/lib.rs +1 -1
@@ -26,7 +26,7 @@ InterfaceClass, Object, ObjectClass, ObjectProperty, ObjectPropertyAccessor, ObjectPropertyRelease, }; -use util_sys::{Error ,QDict ,QList }; +use util_sys::{rcu_head,Error ,QDict ,QList };#[cfg( MESON )] include! ("bindings.inc.rs" );
rust/bindings/system-sys/lib.rs +1 -1
@@ -21,7 +21,7 @@use common::Zeroable ;use hwcore_sys::{qemu_irq,DeviceClass ,DeviceState };use qom_sys::{Object ,ObjectClass }; -use util_sys::{Error ,EventNotifier ,QEMUBH }; +use util_sys::{rcu_head,Error ,EventNotifier ,QEMUBH };#[cfg( MESON )] include! ("bindings.inc.rs" );
rust/bindings/util-sys/wrapper.h +1 -0
@@ -27,6 +27,7 @@ typedef struct Visitor Visitor;#include "qemu/module.h" #include "qemu/option.h" #include "qemu/timer.h" +#include "qemu/rcu.h" #include "qapi/visitor.h" #include "qobject/qbool.h" #include "qobject/qdict.h"
Signature · 1 line
2.34.1
RFC v2 9/26 rust/util: Add RCU bindings
In reply to Zhao LiuAdd RCU bindings, including an RAII guard for rcu_read_lock() & rcu_read_unlock(), and an RcuCell to model qatomic_rcu_read within an RCU critical section.
---
Changes since v1:
* Use RAII pattern to guard RCU locking.
* New RcuCell to simplify RCU read in Rust.
--- rust/hw/char/pl011/wrapper.h | 1 + rust/util/src/lib.rs | 1 + rust/util/src/rcu.rs | 137 +++++++++++++++++++++++++++++++++++ 3 files changed, 139 insertions(+) create mode 100644 rust/util/src/rcu.rs
rust/hw/char/pl011/wrapper.h +1 -0
@@ -49,3 +49,4 @@ typedef enum memory_order {#include "qemu/osdep.h" #include "hw/char/pl011.h" +#include "qemu/rcu.h"
rust/util/src/lib.rs +1 -0
@@ -5,6 +5,7 @@pub mod error;pub mod log;pub mod module; +pub mod rcu;// preserve one-item-per-"use" syntax, it is clearer // for prelude-like modules
rust/util/src/rcu.rs new file +137 -0
137 lines not on this page · raw message
Signature · 1 line
2.34.1
RFC v2 10/26 memory: Expose FlatView refcount interfaces to Rust
In reply to Zhao LiuMove the declarations of the following functions to memory.h so that Rust can generate bindings for them:
* flatview_ref
* flatview_unref
In addition, add documentation for these two interfaces.
Note that these interfaces serve the address_space_to_flatview() logic. However, address_space_to_flatview() is not exposed to Rust because Rust can perform qatomic_rcu_read() itself. Furthermore, acquiring the RCU lock in Rust while C reads "current_map" via qatomic_rcu_read() would make for a very dangerous cross-FFI design.
Instead, Rust should either use address_space_get_flatview() directly, or implement the logic entirely on the Rust side. The latter is a more worthwhile approach, as the RCU reader pattern (qatomic_rcu_read() within an RCU critical section) is a general pattern in QEMU.
---
Changes since v1:
* Do not expose address_space_to_flatview() to Rust anymore.
--- include/system/memory.h | 34 ++++++++++++++++++++++++++++++++++ system/memory-internal.h | 1 - system/memory.c | 2 +- 3 files changed, 35 insertions(+), 2 deletions(-)
include/system/memory.h +34 -0
@@ -948,6 +948,40 @@ static inline FlatView *address_space_to_flatview(const AddressSpace *as)return qatomic_rcu_read (&as->current_map); } +/** +* flatview_ref: Atomically increment the reference count of a #FlatView. +* +* @view: The #FlatView whose reference count is to be incremented. +* +* This function attempts to atomically increment the reference count +* of the given @view. This operation is conditional and will only +* succeed if the current reference count is non-zero. +* +* A non-zero reference count indicates that the #FlatView is live and +* in use. If the reference count is already zero, it indicates that the +* #FlatView is being deinitialized, and no new references can be +* acquired. +* +* Returns: +* true if the reference count was successfully incremented (i.e., it +* was non-zero before the call). +* false if the reference count was already zero and could not be +* incremented. +*/ +bool flatview_ref (FlatView *view); + +/** +* flatview_unref: Atomically decrement the reference count of a +* #FlatView. +* +* @view: The #FlatView to be unreferenced. +* +* This function atomically decrements the reference count of the given +* @view. When the reference count drops to zero, the #FlatView will be +* destroyed via RCU. +*/ +void flatview_unref (FlatView *view); +/** * typedef flatview_cb: callback for flatview_for_each_range() *
system/memory-internal.h +0 -1
@@ -28,7 +28,6 @@ AddressSpaceDispatch *address_space_to_dispatch(const AddressSpace *as) }FlatView *address_space_get_flatview (const AddressSpace *as); -void flatview_unref (FlatView *view);extern const MemoryRegionOps unassigned_mem_ops;
system/memory.c +1 -1
@@ -305,7 +305,7 @@ static void flatview_destroy(FlatView *view)g_free (view); } -static bool flatview_ref (FlatView *view) +bool flatview_ref (FlatView *view) {return qatomic_fetch_inc_nonzero (&view->ref) >0 ; }
Signature · 1 line
2.34.1
RFC v2 11/26 memory: Rename address_space_lookup_region and expose it to Rust
In reply to Zhao Liuaddress_space_lookup_region() returns a pointer to a MemoryRegionSection instead of a MemoryRegion. Therefore, rename it to address_space_lookup_section().
Add its declaration to memory.h so that bindgen can generate bindings for it.
This interface will be used to implement GuestMemory::find_region() in the vm_memory crate.
In addition, add its documentation in memory.h.
--- include/system/memory.h | 21 +++++++++++++++++++++ system/physmem.c | 8 ++++---- 2 files changed, 25 insertions(+), 4 deletions(-)
include/system/memory.h +21 -0
@@ -948,6 +948,27 @@ static inline FlatView *address_space_to_flatview(const AddressSpace *as)return qatomic_rcu_read (&as->current_map); } +/** +* address_space_lookup_section: Find the MemoryRegionSection within a +* given #AddressSpaceDispatch. +* +* @d: The AddressSpaceDispatch to search within. +* @addr: The address to look up. +* @resolve_subpage: If 'true', resolve to a subpage section if the +* region is a subpage container. +* +* This function translates an address (@addr) into its corresponding +* #MemoryRegionSection within a given address space dispatch (@d). +* Must be called within an RCU critical section. +* +* Returns: +* A pointer to the #MemoryRegionSection. If the address is not +* mapped, this will be a pointer to the 'unassigned' section. +*/ +MemoryRegionSection *address_space_lookup_section (AddressSpaceDispatch *d, +hwaddr addr, +bool resolve_subpage); +/** * flatview_ref: Atomically increment the reference count of a #FlatView. *
system/physmem.c +4 -4
@@ -342,9 +342,9 @@ static MemoryRegionSection *phys_page_find(AddressSpaceDispatch *d, hwaddr addr) }/* Called from RCU critical section */ -static MemoryRegionSection *address_space_lookup_region (AddressSpaceDispatch *d, -hwaddr addr, -bool resolve_subpage) +MemoryRegionSection *address_space_lookup_section (AddressSpaceDispatch *d, +hwaddr addr, +bool resolve_subpage) {MemoryRegionSection *section =qatomic_read (&d->mru_section);subpage_t *subpage;
@@ -370,7 +370,7 @@ address_space_translate_internal(AddressSpaceDispatch *d, hwaddr addr, hwaddr *xMemoryRegion *mr;Int128 diff; - section =address_space_lookup_region (d, addr, resolve_subpage); + section =address_space_lookup_section (d, addr, resolve_subpage);/* Compute offset within MemoryRegionSection */ addr -= section->offset_within_address_space;
Signature · 1 line
2.34.1
RFC v2 12/26 memory: Make flatview_do_translate() return a pointer to MemoryRegionSection
In reply to Zhao LiuRust will use common::Opaque to hide the details of C structures, which helps avoid direct manipulation of C memory from the Rust side.
Therefore, it is necessary to create a translation binding wrapper that returns a pointer to a MemoryRegionSection, instead of returning a copy by value.
As a first step, make flatview_do_translate() return a pointer to a MemoryRegionSection so that we can build a wrapper around it.
In addition, add a global variable unassigned_section to provide a pointer to an invalid MemoryRegionSection.
--- system/physmem.c | 51 ++++++++++++++++++++++-------------------------- 1 file changed, 23 insertions(+), 28 deletions(-)
system/physmem.c +23 -28
@@ -104,6 +104,9 @@ AddressSpace address_space_io;AddressSpace address_space_memory;static MemoryRegion io_mem_unassigned; +static MemoryRegionSection unassigned_section = { + .mr = &io_mem_unassigned +};typedef struct PhysPageEntry PhysPageEntry ;
@@ -419,14 +422,11 @@ address_space_translate_internal(AddressSpaceDispatch *d, hwaddr addr, hwaddr *x* This function is called from RCU critical section. It is the common * part of flatview_do_translate and address_space_translate_cached. */ -static MemoryRegionSection address_space_translate_iommu (IOMMUMemoryRegion *iommu_mr, -hwaddr *xlat, -hwaddr *plen_out, -hwaddr *page_mask_out, -bool is_write, -bool is_mmio, -AddressSpace **target_as, -MemTxAttrs attrs) +static MemoryRegionSection * +address_space_translate_iommu (IOMMUMemoryRegion *iommu_mr,hwaddr *xlat, +hwaddr *plen_out,hwaddr *page_mask_out, +bool is_write,bool is_mmio, +AddressSpace **target_as,MemTxAttrs attrs) {MemoryRegionSection *section;hwaddr page_mask = (hwaddr)-1 ;
@@ -464,10 +464,10 @@ static MemoryRegionSection address_space_translate_iommu(IOMMUMemoryRegion *iommif (page_mask_out) { *page_mask_out = page_mask; } -return *section; +return section; unassigned: -return (MemoryRegionSection ) { .mr = &io_mem_unassigned }; +return &unassigned_section; }/**
@@ -490,15 +490,10 @@ unassigned:* * This function is called from RCU critical section */ -static MemoryRegionSection flatview_do_translate (FlatView *fv, -hwaddr addr, -hwaddr *xlat, -hwaddr *plen_out, -hwaddr *page_mask_out, -bool is_write, -bool is_mmio, -AddressSpace **target_as, -MemTxAttrs attrs) +static MemoryRegionSection * +flatview_do_translate (FlatView *fv,hwaddr addr,hwaddr *xlat,hwaddr *plen_out, +hwaddr *page_mask_out,bool is_write,bool is_mmio, +AddressSpace **target_as,MemTxAttrs attrs) {MemoryRegionSection *section;IOMMUMemoryRegion *iommu_mr;
@@ -524,14 +519,14 @@ static MemoryRegionSection flatview_do_translate(FlatView *fv, *page_mask_out = ~TARGET_PAGE_MASK ; } -return *section; +return section; }/* Called from RCU critical section */ IOMMUTLBEntry address_space_get_iotlb_entry (AddressSpace *as,hwaddr addr,bool is_write,MemTxAttrs attrs) { -MemoryRegionSection section; +MemoryRegionSection *section;hwaddr xlat, page_mask;/*
@@ -543,13 +538,13 @@ IOMMUTLBEntry address_space_get_iotlb_entry(AddressSpace *as, hwaddr addr, attrs);/* Illegal translation */ -if (section.mr == &io_mem_unassigned) { +if (section->mr == &io_mem_unassigned) { goto iotlb_fail; }/* Convert memory region offset into address space offset */ - xlat += section.offset_within_address_space - - section.offset_within_region; + xlat += section->offset_within_address_space - + section->offset_within_region;return (IOMMUTLBEntry ) { .target_as = as,
@@ -570,13 +565,13 @@ MemoryRegion *flatview_translate(FlatView *fv, hwaddr addr, hwaddr *xlat, MemTxAttrs attrs) {MemoryRegion *mr; -MemoryRegionSection section; +MemoryRegionSection *section;AddressSpace *as =NULL ;/* This can be MMIO, so setup MMIO bit. */ section =flatview_do_translate (fv, addr, xlat, plen,NULL , is_write, true, &as, attrs); - mr = section.mr; + mr = section->mr;if (xen_map_cache_enabled () &&memory_access_is_direct (mr, is_write, attrs)) {
@@ -3908,7 +3903,7 @@ static inline MemoryRegion *address_space_translate_cached( const MemoryRegionCache *cache, hwaddr addr, hwaddr *xlat, hwaddr *plen, bool is_write, MemTxAttrs attrs) { - MemoryRegionSection section; + MemoryRegionSection *section;MemoryRegion *mr;IOMMUMemoryRegion *iommu_mr;AddressSpace *target_as;
@@ -3926,7 +3921,7 @@ static inline MemoryRegion *address_space_translate_cached( section =address_space_translate_iommu (iommu_mr, xlat, plen,NULL , is_write, true, &target_as, attrs); -return section.mr; +return section->mr; }/* Called within RCU critical section. */
Signature · 1 line
2.34.1
RFC v2 13/26 memory: Add a translation helper to return a MemoryRegionSection
In reply to Zhao LiuThe Rust side will rely on MemoryRegionSection to organize non-overlapping memory "region" abstractions. Therefore, it is necessary to provide a translation helper variant that returns a MemoryRegionSection directly.
Additionally, refine and complete the documentation for the translation helpers.
--- include/system/memory.h | 76 +++++++++++++++++++++++++++++++++++------ system/physmem.c | 22 +++++++++--- 2 files changed, 84 insertions(+), 14 deletions(-)
include/system/memory.h +66 -10
@@ -2609,24 +2609,80 @@ void address_space_flush_icache_range(AddressSpace *as,IOMMUTLBEntry address_space_get_iotlb_entry (AddressSpace *as,hwaddr addr,bool is_write,MemTxAttrs attrs); -/* address_space_translate: translate an address range into an address space -* into a MemoryRegion and an address range into that section. Should be -* called from an RCU critical section, to avoid that the last reference -* to the returned region disappears after address_space_translate returns. +/** +* flatview_translate_section: Translate a guest physical address range +* to the corresponding #MemoryRegionSection in a FlatView. * -* @fv: #FlatView to be accessed -* @addr: address within that address space -* @xlat: pointer to address within the returned memory region section's +* Must be called within an RCU critical section to prevent the last +* reference to the memory region (referenced by the returned section) +* from disappearing after the function returns. +* +* @fv: The FlatView to be accessed. +* @addr: The address to be translated within the given FlatView. +* @xlat: The translated address offset within the returned section's * #MemoryRegion. -* @len: pointer to length -* @is_write: indicates the transfer direction -* @attrs: memory attributes +* @len: Pointer to the length. On return, this will be updated to the +* valid read/write length of the translated address range. +* @is_write: Indicates the transfer direction. +* @attrs: Memory attributes. +* +* Returns: +* The #MemoryRegionSection that contains the translated address. +*/ +MemoryRegionSection *flatview_translate_section (FlatView *fv,hwaddr addr, +hwaddr *xlat,hwaddr *len, +bool is_write,MemTxAttrs attrs); + +/** +* flatview_translate: Translate a guest physical address range +* to the corresponding #MemoryRegionSection in a FlatView. +* +* Must be called within an RCU critical section to prevent the last +* reference to the returned memory region from disappearing after +* the function returns. +* +* This function is a variant of flatview_translate_section(), with the +* difference that it returns the #MemoryRegion contained in the +* #MemoryRegionSection. +* +* @fv: The FlatView to be accessed. +* @addr: The address to be translated within the given FlatView. +* @xlat: The translated address offset within the returned #MemoryRegion. +* @len: Pointer to the length. On return, this will be updated to the +* valid read/write length of the translated address range. +* @is_write: Indicates whether the translation operation is for a write. +* @attrs: Memory transaction attributes. +* +* Returns: +* The #MemoryRegion that contains the translated address. */ MemoryRegion *flatview_translate (FlatView *fv,hwaddr addr,hwaddr *xlat,hwaddr *len,bool is_write,MemTxAttrs attrs); +/** +* address_space_translate: Translate a guest physical address range +* to the corresponding #MemoryRegionSection in a FlatView. +* +* Must be called within an RCU critical section to prevent the last +* reference to the returned memory region from disappearing after +* the function returns. +* +* This function is a variant of flatview_translate(), with the difference +* that it operates on an #AddressSpace rather than a #FlatView directly. +* +* @as: The #AddressSpace to be accessed. +* @addr: The address to be translated within the given address space. +* @xlat: The translated address offset within the returned #MemoryRegion. +* @len: Pointer to the length. On return, this will be updated to the +* valid read/write length of the translated address range. +* @is_write: Indicates whether the translation operation is for a write. +* @attrs: Memory transaction attributes. +* +* Returns: +* The #MemoryRegion that contains the translated address. +*/ static inline MemoryRegion *address_space_translate(AddressSpace *as, hwaddr addr, hwaddr *xlat, hwaddr *len, bool is_write,
system/physmem.c +18 -4
@@ -560,9 +560,9 @@ iotlb_fail: }/* Called from RCU critical section */ -MemoryRegion *flatview_translate (FlatView *fv,hwaddr addr,hwaddr *xlat, -hwaddr *plen,bool is_write, -MemTxAttrs attrs) +MemoryRegionSection *flatview_translate_section (FlatView *fv,hwaddr addr, +hwaddr *xlat,hwaddr *plen, +bool is_write,MemTxAttrs attrs) {MemoryRegion *mr;MemoryRegionSection *section;
@@ -580,7 +580,21 @@ MemoryRegion *flatview_translate(FlatView *fv, hwaddr addr, hwaddr *xlat, *plen =MIN (page, *plen); } -return mr; +return section; +} + +/* Called from RCU critical section */ +MemoryRegion *flatview_translate (FlatView *fv,hwaddr addr,hwaddr *xlat, +hwaddr *plen,bool is_write, +MemTxAttrs attrs) +{ +MemoryRegionSection *section; + +/* This can be MMIO, so setup MMIO bit. */ + section =flatview_translate_section (fv, addr, xlat, plen, + is_write, attrs); + +return section->mr; }#ifdef CONFIG_TCG
Signature · 1 line
2.34.1
RFC v2 14/26 memory: Rename flatview_access_allowed() to memory_region_access_allowed()
In reply to Zhao Liuflatview_access_allowed() takes a MemoryRegion * as an argument, meaning it operates on a MemoryRegion rather than a FlatView. Therefore, rename it to memory_region_access_allowed() to accurately reflect its behavior.
--- system/physmem.c | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-)
system/physmem.c +7 -7
@@ -3210,7 +3210,7 @@ bool prepare_mmio_access(MemoryRegion *mr) }/** -* flatview_access_allowed +* memory_region_access_allowed * @mr: #MemoryRegion to be accessed * @attrs: memory transaction attributes * @addr: address within that memory region
@@ -3220,8 +3220,8 @@ bool prepare_mmio_access(MemoryRegion *mr)* * Returns: true if transaction is allowed, false if denied. */ -static bool flatview_access_allowed (MemoryRegion *mr,MemTxAttrs attrs, -hwaddr addr,hwaddr len) +static bool memory_region_access_allowed (MemoryRegion *mr,MemTxAttrs attrs, +hwaddr addr,hwaddr len) {if (likely (!attrs.memory)) {return true;
@@ -3241,7 +3241,7 @@ static MemTxResult flatview_write_continue_step(MemTxAttrs attrs, hwaddr len, hwaddr mr_addr, hwaddr *l, MemoryRegion *mr) { - if (!flatview_access_allowed(mr, attrs, mr_addr, *l)) { + if (!memory_region_access_allowed(mr, attrs, mr_addr, *l)) { return MEMTX_ACCESS_ERROR; }
@@ -3325,7 +3325,7 @@ static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs, l = len; mr =flatview_translate (fv, addr, &mr_addr, &l, true, attrs); -if (!flatview_access_allowed (mr, attrs, mr_addr, l)) { +if (!memory_region_access_allowed (mr, attrs, addr, len)) {return MEMTX_ACCESS_ERROR ; } return flatview_write_continue(fv, addr, attrs, buf, len,
@@ -3337,7 +3337,7 @@ static MemTxResult flatview_read_continue_step(MemTxAttrs attrs, uint8_t *buf, hwaddr *l, MemoryRegion *mr) { -if (!flatview_access_allowed (mr, attrs, mr_addr, *l)) { +if (!memory_region_access_allowed (mr, attrs, mr_addr, *l)) {return MEMTX_ACCESS_ERROR ; }
@@ -3416,7 +3416,7 @@ static MemTxResult flatview_read(FlatView *fv, hwaddr addr, l = len; mr =flatview_translate (fv, addr, &mr_addr, &l, false, attrs); -if (!flatview_access_allowed (mr, attrs, mr_addr, l)) { +if (!memory_region_access_allowed (mr, attrs, addr, len)) {return MEMTX_ACCESS_ERROR ; } return flatview_read_continue(fv, addr, attrs, buf, len,
Signature · 1 line
2.34.1
RFC v2 15/26 memory: Add MemoryRegionSection-based misc helpers
In reply to Zhao LiuAdd the following helpers:
* section_access_allowed()
- used to check memory access permissions.
* section_covers_region_addr()
- used to implement GuestMemoryRegion::check_address().
* section_fuzz_dma_read()
- used to insert a fuzzing hook before read/load operations.
---
Changes since v1:
* Drop section_get_host_addr() for two reasons:
- GuestMemoryRegion::get_host_address() doesn't accept Permissions and MemTxAttrs arguments, which doesn't map well to QEMU's complex use cases.
- section_get_host_addr() itself doesn't differentiate between MMIO and RAM. Although this could be fixed, the first reason makes it unnecessary.
--- include/system/memory.h | 39 +++++++++++++++++++++++++++++++++++++++ system/physmem.c | 20 ++++++++++++++++++++ 2 files changed, 59 insertions(+)
include/system/memory.h +39 -0
@@ -2878,6 +2878,45 @@ MemTxResult address_space_read(const AddressSpace *as, hwaddr addr,MemTxResult address_space_set (const AddressSpace *as,hwaddr addr,uint8_t c,hwaddr len,MemTxAttrs attrs); +/** +* section_access_allowed: Check if a memory transaction is allowed. +* +* @section: The #MemoryRegionSection to be accessed. +* @attrs: Memory transaction attributes. +* @addr: The address within that memory region. +* @len: The number of bytes to access. +* +* Returns: true if the transaction is allowed, false if denied. +*/ +bool section_access_allowed (MemoryRegionSection *section, +MemTxAttrs attrs,hwaddr addr, +hwaddr len); + +/** +* section_covers_region_addr: Check if a region address is covered by +* a #MemoryRegionSection. +* +* @section: The #MemoryRegionSection to check against. +* @region_addr: The address within the memory region referenced by the +* @section. +* +* Returns: true if the address is covered by the section, false otherwise. +*/ +bool section_covers_region_addr (const MemoryRegionSection *section, +hwaddr region_addr); + +/** +* section_fuzz_dma_read: Wrapper for fuzz_dma_read_cb(). +* +* @section: The #MemoryRegionSection to be accessed. +* @addr: The memory address to be fuzzed. +* @len: The length of the memory to fuzz. +* +* This function is a wrapper for fuzz_dma_read_cb(). +*/ +void section_fuzz_dma_read (MemoryRegionSection *section, +hwaddr addr,hwaddr len); +/* Coalesced MMIO regions are areas where write operations can be reordered. * This usually implies that write operations are side-effect free. This allows * batching which can make a major impact on performance when using
system/physmem.c +20 -0
@@ -321,6 +321,19 @@ static inline bool section_covers_addr(const MemoryRegionSection *section, int128_getlo(section->size), addr); } +bool section_covers_region_addr (const MemoryRegionSection *section, +hwaddr region_addr) +{ +return section->offset_within_region <= region_addr && + section->offset_within_region +int128_get64 (section->size) >= region_addr; +} + +void section_fuzz_dma_read (MemoryRegionSection *section, +hwaddr addr,hwaddr len) +{ +fuzz_dma_read_cb (addr, len, section->mr); +} +static MemoryRegionSection *phys_page_find (AddressSpaceDispatch *d,hwaddr addr) {PhysPageEntry lp = d->phys_map, *p;
@@ -3236,6 +3249,13 @@ static bool memory_region_access_allowed(MemoryRegion *mr, MemTxAttrs attrs,return false; } +bool section_access_allowed (MemoryRegionSection *section, +MemTxAttrs attrs,hwaddr addr, +hwaddr len) +{ +return memory_region_access_allowed (section->mr, attrs, addr, len); +} + static MemTxResult flatview_write_continue_step(MemTxAttrs attrs, const uint8_t *buf, hwaddr len, hwaddr mr_addr,
Signature · 1 line
2.34.1
RFC v2 16/26 memory: Add wrappers for intermediate read/write steps
In reply to Zhao LiuAdd the following two wrappers to allow bindgen to generate bindings based on MemoryRegionSection:
* rust_section_write_continue_step()
* rust_section_read_continue_step()
This allows the Rust side to reconstruct the full write/read process, similar to what address_space_write() and address_space_read_full() do.
--- include/system/memory.h | 53 +++++++++++++++++++++++++++++++++++++++++ system/physmem.c | 16 +++++++++++++ 2 files changed, 69 insertions(+)
include/system/memory.h +53 -0
@@ -2917,6 +2917,59 @@ bool section_covers_region_addr(const MemoryRegionSection *section,void section_fuzz_dma_read (MemoryRegionSection *section,hwaddr addr,hwaddr len); +/** +* rust_section_write_continue_step: Write to a #MemoryRegionSection. +* +* Note: This function should only be used by the Rust side, and callers +* should not invoke it directly! +* +* This function provides a wrapper for flatview_write_continue_step(), +* and allows the Rust side to reconstruct the full write process, similar +* to what address_space_write() does. +* +* Must be called within an RCU critical section. +* +* @section: The #MemoryRegionSection to be accessed. +* @attrs: Memory transaction attributes. +* @buf: Buffer containing the data to be written. +* @len: The number of bytes to write. +* @mr_addr: The address within that memory region. +* @l: Pointer to the actual length. On return, this is updated to the +* number of bytes written. +* +* Returns: +* A MemTxResult indicating whether the operation succeeded or failed +* (e.g., unassigned memory, device rejected the transaction, IOMMU fault). +*/ +MemTxResult rust_section_write_continue_step (MemoryRegionSection *section, +MemTxAttrs attrs,const uint8_t *buf,hwaddr len,hwaddr mr_addr,hwaddr *l); + +/** +* rust_section_read_continue_step: Read from a #MemoryRegionSection. +* +* Note: This function should only be used by the Rust side, and callers +* should not invoke it directly! +* +* This function provides a wrapper for flatview_read_continue_step(), +* and allows the Rust side to reconstruct the full read process, similar +* to what address_space_read_full() does. +* +* Must be called within an RCU critical section. +* +* @section: The #MemoryRegionSection to be accessed. +* @attrs: Memory transaction attributes. +* @buf: Buffer to store the read data. +* @len: The expected number of bytes to read. +* @mr_addr: The address within that memory region. +* @l: Pointer to the actual length. On return, this is updated to the +* number of bytes read. +* +* Returns: +* A MemTxResult indicating whether the operation succeeded or failed. +*/ +MemTxResult rust_section_read_continue_step (MemoryRegionSection *section, +MemTxAttrs attrs,uint8_t *buf,hwaddr len,hwaddr mr_addr,hwaddr *l); +/* Coalesced MMIO regions are areas where write operations can be reordered. * This usually implies that write operations are side-effect free. This allows * batching which can make a major impact on performance when using
system/physmem.c +16 -0
@@ -3398,6 +3398,14 @@ static MemTxResult flatview_read_continue_step(MemTxAttrs attrs, uint8_t *buf, } } +MemTxResult +rust_section_read_continue_step (MemoryRegionSection *section,MemTxAttrs attrs, +uint8_t *buf,hwaddr len,hwaddr mr_addr, +hwaddr *l) +{ +return flatview_read_continue_step (attrs, buf, len, mr_addr, l, section->mr); +} +/* Called within RCU critical section. */ MemTxResult flatview_read_continue(FlatView *fv, hwaddr addr, MemTxAttrs attrs, void *ptr,
@@ -3987,6 +3995,14 @@ static MemTxResult address_space_write_continue_cached(MemTxAttrs attrs,return result; } +MemTxResult +rust_section_write_continue_step (MemoryRegionSection *section,MemTxAttrs attrs, +const uint8_t *buf,hwaddr len,hwaddr mr_addr, +hwaddr *l) +{ +return flatview_write_continue_step (attrs, buf, len, mr_addr, l, section->mr); +} +/* Called within RCU critical section. */ static MemTxResult address_space_read_continue_cached(MemTxAttrs attrs, void *ptr, hwaddr len,
Signature · 1 line
2.34.1
RFC v2 17/26 memory: Add store/load interfaces for Rust
In reply to Zhao LiuCurrently, there are many store/load variants defined in memory_ldst.c.inc.
However, the vm-memory crate's Bytes::store() and Bytes::load() methods are bound by the AtomicAccess trait, making it almost impossible to select the proper interface (e.g., for l, w, or q) based on a specific type.
Therefore, it is necessary to provide interfaces that hide these type details as much as possible. Compared to the address_space_st{size}_{endian} and address_space_ld{size}_{endian} functions, the differences include:
* No address translation; they only perform memory access.
* They treat the byte array as raw bytes. RAM accesses copy the bytes unchanged. For MMIO accesses, the Rust caller must use the correct endian ordering for the target device (via LeNN/BeNN), just as the C side must select the appropriate address_space_st{size}_le() or _be() variants.
* They use byte arrays instead of a single uint64_t for the value being written or read, eliminating the need for the Rust side to convert generic types to u64.
- However, this incurs an extra cost for MMIO accesses, as it requires conversion between byte arrays and uint64_t internally.
* They do not handle cross-region MMIO accesses. The Rust side will be responsible for handling such edge cases.
---
Changes since v1:
* Drop the native endian assumption and require the caller to use the target device's endianness.
--- include/system/memory.h | 50 ++++++++++++++++++++++++++++ system/physmem.c | 72 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 122 insertions(+)
include/system/memory.h +50 -0
@@ -2970,6 +2970,56 @@ MemTxResult rust_section_write_continue_step(MemoryRegionSection *section,MemTxResult rust_section_read_continue_step (MemoryRegionSection *section,MemTxAttrs attrs,uint8_t *buf,hwaddr len,hwaddr mr_addr,hwaddr *l); +/** +* rust_section_store: Store data to a #MemoryRegionSection. +* +* Note: This function should only be used by the Rust side, and callers +* should not invoke it directly! +* +* This function does a single-access store without translation. @buf provides +* raw bytes: RAM uses direct memory copy; MMIO expects data in device +* endianness. +* +* Must be called within an RCU critical section. +* +* @section: The #MemoryRegionSection to be accessed. +* @mr_offset: The address within that memory region. +* @buf: Buffer containing the data to be written. +* @attrs: Memory transaction attributes. +* @len: The number of bytes to write. +* +* Returns: +* A MemTxResult indicating whether the operation succeeded or failed. +*/ +MemTxResult rust_section_store (MemoryRegionSection *section, +hwaddr mr_offset,const uint8_t *buf, +MemTxAttrs attrs,hwaddr len); + +/** +* rust_section_load: Load data from a #MemoryRegionSection. +* +* Note: This function should only be used by the Rust side, and callers +* should not invoke it directly! +* +* This function does a single-access load without translation. @buf receives +* raw bytes: RAM uses direct memory copy; MMIO returns data in device +* endianness. +* +* Must be called within an RCU critical section. +* +* @section: The #MemoryRegionSection to be accessed. +* @mr_offset: The address within that memory region. +* @buf: The output buffer to store the read data. +* @attrs: Memory transaction attributes. +* @len: The expected number of bytes to read. +* +* Returns: +* A MemTxResult indicating whether the operation succeeded or failed. +*/ +MemTxResult rust_section_load (MemoryRegionSection *section, +hwaddr mr_offset,uint8_t *buf, +MemTxAttrs attrs,hwaddr len); +/* Coalesced MMIO regions are areas where write operations can be reordered. * This usually implies that write operations are side-effect free. This allows * batching which can make a major impact on performance when using
system/physmem.c +72 -0
78 lines not on this page · raw message
Signature · 1 line
2.34.1
RFC v2 18/26 rust/system/memory: Implement vm_memory::GuestMemoryRegion for MemoryRegionSection
In reply to Zhao LiuAlthough QEMU already has a native memory region abstraction (MemoryRegion), it supports overlapping regions. Since the vm-memory crate does not support overlapping memory, MemoryRegionSection is a more appropriate choice to implement the vm_memory::GuestMemoryRegion trait.
To achieve this, implement vm_memory::GuestMemoryRegion for MemoryRegionSection, along with its required supertrait, GuestMemoryRegionBytes. Additionally, implement Bytes<(MemoryRegionAddress, MemTxAttrs)> to properly attach QEMU's memory transaction attributes to memory operations.
Furthermore, provide low-level memory write/read/store/load bindings based on MemoryRegionSection, and add the necessary helpers (fuzz_dma_read() and is_access_allowed()).
---
Changes since v1:
* Implement GuestMemoryRegionBytes for MemoryRegionSection to satisfy supertrait requirement.
* Implement Bytes<(MemoryRegionAddress, MemTxAttrs)> to attach MemTxAttrs.
* For write/read, add an extra loop to ensure write/read are actually finished within the same region.
--- rust/system/src/memory.rs | 449 +++++++++++++++++++++++++++++++++++++- 1 file changed, 447 insertions(+), 2 deletions(-)
rust/system/src/memory.rs +447 -2
@@ -2,19 +2,38 @@// Author(s): Paolo Bonzini <[email protected]> // SPDX-License-Identifier: GPL-2.0-or-later -//! Bindings for `MemoryRegion`, `MemoryRegionOps` and `MemTxAttrs` +//! Bindings for `MemoryRegion`, `MemoryRegionOps`, `MemTxAttrs` and +//! `MemoryRegionSection`. use std::{ ffi::{c_uint, c_void,CStr ,CString }, + io::ErrorKind , marker::PhantomData , + mem::size_of, + ops::Deref , + sync::atomic::Ordering , };use common::{callbacks::FnCall , uninit::MaybeUninitField , zeroable::Zeroable ,Opaque };use qom::prelude::*; +pub use vm_memory::GuestAddress ; +use vm_memory::{ + bitmap::BS ,Address ,AtomicAccess ,Bytes ,GuestMemoryError ,GuestMemoryRegion , +GuestMemoryRegionBytes ,GuestMemoryResult ,GuestUsize ,MemoryRegionAddress ,ReadVolatile , +WriteVolatile , +}; -use crate ::bindings::{self, device_endian, memory_region_init_io}; +use crate ::bindings::{ + self, device_endian, memory_region_init_io, rust_section_load, rust_section_read_continue_step, + rust_section_store, rust_section_write_continue_step, section_access_allowed, + section_covers_region_addr, section_fuzz_dma_read,MemTxResult , +}; +// FIXME: Convert hwaddr to GuestAddress pub use crate ::bindings::{hwaddr,MemTxAttrs }; +/// Corresponds to C `MEMTX_OK` (#define `MEMTX_OK` 0). +const MEMTX_OK :MemTxResult =0 ; +pub struct MemoryRegionOps <T >( bindings::MemoryRegionOps , // Note: quite often you'll see PhantomData<fn(&T)> mentioned when discussing
@@ -187,3 +206,429 @@ unsafe impl ObjectType for MemoryRegion { unspecified: true, ..Zeroable ::ZERO }; + +/// A safe wrapper around [`bindings::MemoryRegionSection`]. +/// +/// This struct is fundamental for integrating QEMU's memory model with +/// the `vm-memory` ecosystem. It directly maps to the concept of +/// [`GuestMemoryRegion`] and implements that trait. +/// +/// ### `MemoryRegion` vs. `MemoryRegionSection` +/// +/// Although QEMU already has native memory region abstraction, this is +/// [`MemoryRegion`], which supports overlapping. But `vm-memory` doesn't +/// support overlapped memory, so `MemoryRegionSection` is more proper +/// to implement [`GuestMemoryRegion`] trait. +/// +/// One point should pay attention is, [`MemoryRegionAddress`] represents the +/// address or offset within the `MemoryRegionSection`. But traditional C +/// bindings treats memory region address or offset as the offset within +/// `MemoryRegion`. +/// +/// Therefore, it's necessary to do conversion when calling C bindings +/// with `MemoryRegionAddress` from the context of `MemoryRegionSection`. +/// +/// ### Usage +/// +/// Considerring memory access is almost always through `AddressSpace` +/// in QEMU, `MemoryRegionSection` is intended for **internal use only** +/// within the `vm-memory` backend implementation. +/// +/// Device and other external users should **not** use or create +/// `MemoryRegionSection`s directly. Instead, they should work with the +/// higher-level `MemoryRegion` API to create and manage their device's +/// memory. This separation of concerns mirrors the C API and avoids +/// confusion about different memory abstractions. +#[repr(transparent)] +#[derive(common:: Wrapper , Debug )] +pub struct MemoryRegionSection (Opaque <bindings::MemoryRegionSection >); + +unsafe impl Send for MemoryRegionSection {} +unsafe impl Sync for MemoryRegionSection {} + +impl Deref for MemoryRegionSection { +type Target = bindings::MemoryRegionSection ; + +fn deref (&self) -> &Self ::Target { +// SAFETY: Opaque<> wraps a pointer from C side. The validity +// of the pointer is confirmed at the creation of Opaque<>. +unsafe { &*self.0 .as_ptr () } + } +} + +impl MemoryRegionSection { +/// A fuzz testing hook for DMA read. +/// +/// When `CONFIG_FUZZ` is not set, this hook will do nothing. +#[allow(dead_code)] +fn fuzz_dma_read (&self, addr:GuestAddress , len:GuestUsize ) -> &Self { +// SAFETY: Opaque<> ensures the pointer is valid, and here it +// takes into account the offset conversion between MemoryRegionSection +// and MemoryRegion. +unsafe { +section_fuzz_dma_read ( + self.as_mut_ptr (), + addr.checked_add (self.deref ().offset_within_region) + .unwrap () + .raw_value (), + len, + ); + } + self + } + +/// A helper to check if the memory access is allowed. +/// +/// This is needed for memory write/read. +#[allow(dead_code)] +fn is_access_allowed ( + &self, + addr:MemoryRegionAddress , + len:GuestUsize , + attrs:MemTxAttrs , + ) ->bool { +// SAFETY: Opaque<> ensures the pointer is valid, and here it +// takes into account the offset conversion between MemoryRegionSection +// and MemoryRegion. +let allowed =unsafe { +section_access_allowed ( + self.as_mut_ptr (), + attrs, + addr.checked_add (self.deref ().offset_within_region) + .unwrap () + .raw_value (), + len, + ) + }; + allowed + } +} + +/// Satisfies the `Bytes<MemoryRegionAddress>` supertrait required by +/// `GuestMemoryRegion`. +/// +/// The blanket impl fails with `HostAddressNotAvailable` because +/// `MemoryRegionSection` methods all go through `as_volatile_slice()` and +/// `get_slice()`, which by default return an error. +/// +/// QEMU's real access path is always attrs-aware and reaches this section +/// through the `Bytes<(MemoryRegionAddress, +/// MemTxAttrs)>` impl below. +impl GuestMemoryRegionBytes for MemoryRegionSection {} + +/// The attrs-aware `Bytes` implementation that actually does the C-side +/// memory access for a single `MemoryRegionSection`. +/// +/// This composite impl is the *only* real access path into a +/// `MemoryRegionSection`: QEMU always reaches it through `FlatView` +/// with the real `attrs`. The blanket `GuestMemoryRegionBytes` impl above +/// just satisfies the `GuestMemoryRegion` supertrait bound and is never +/// actually called. +impl Bytes <(MemoryRegionAddress ,MemTxAttrs )>for MemoryRegionSection { +type E =GuestMemoryError ; + +/// Write a byte buffer into guest memory at `addr`. +/// +/// This shouldn't be called to access memory directly; it is the +/// per-region worker invoked by `FlatView`'s write path. The transaction +/// `attrs` are forwarded to the C side. And the cross-region is handled by +/// `FlatView`'s write. +fn write ( + &self, + buf: &[u8 ], + (addr, attrs): (MemoryRegionAddress ,MemTxAttrs ), + ) ->GuestMemoryResult <usize > { +let base = addr + .checked_add (self.deref ().offset_within_region) + .unwrap () + .raw_value (); +let total = buf.len ()as u64 ; +let mut done:u64 =0 ; + +while done < total { +// `step` is the attempt size on input and the bytes actually +// handled on output. +let mut step = total - done; + +// SAFETY: the pointers and reference are convertible and the +// offset conversion is considered. +let ret =unsafe { +rust_section_write_continue_step ( + self.as_mut_ptr (), + attrs, + buf[doneas usize ..].as_ptr (), + total - done, + base + done, + &mut step, + ) + }; + +if ret !=MEMTX_OK { +return Err (GuestMemoryError ::InvalidBackendAddress ); + } + +// A zero-length step can never make progress. +if step ==0 { +break ; + } + + done += step; + } + +Ok (doneas usize ) + } + +/// Read a byte buffer from guest memory at `addr`. +/// +/// This shouldn't be called to access memory directly; it is the +/// per-region worker invoked by `FlatView`'s read path. The transaction +/// `attrs` are forwarded to the C side. And the cross-region is handled by +/// `FlatView`'s read. +fn read ( + &self, + buf: &mut [u8 ], + (addr, attrs): (MemoryRegionAddress ,MemTxAttrs ), + ) ->GuestMemoryResult <usize > { +let base = addr + .checked_add (self.deref ().offset_within_region) + .unwrap () + .raw_value (); +let total = buf.len ()as u64 ; +let mut done:u64 =0 ; + +while done < total { +// `step` is the attempt size on input and the bytes actually +// handled on output. +let mut step = total - done; + +// SAFETY: the pointers and reference are convertible and the +// offset conversion is considered. +let ret =unsafe { +rust_section_read_continue_step ( + self.as_mut_ptr (), + attrs, + buf[doneas usize ..].as_mut_ptr (), + total - done, + base + done, + &mut step, + ) + }; + +if ret !=MEMTX_OK { +return Err (GuestMemoryError ::InvalidBackendAddress ); + } + +// A zero-length step can never make progress. +if step ==0 { +break ; + } + + done += step; + } + +Ok (doneas usize ) + } + +/// Store a value into guest memory at `addr`. +/// +/// This function - as the low-level store implementation - is +/// called by `FlatView`'s `store()`. And it shouldn't be called to +/// access memory directly. +/// +/// The transaction `attrs` are forwarded to the C side; the `Ordering` is +/// ignored because the access is not Rust-atomic. +fn store <T :AtomicAccess >( + &self, + val:T , + (addr, attrs): (MemoryRegionAddress ,MemTxAttrs ), + _order:Ordering , + ) ->GuestMemoryResult <()> { +let len =size_of ::<T >(); + +if len >size_of ::<u64 >() { +return Err (GuestMemoryError ::IOError (std::io::Error ::new ( +ErrorKind ::InvalidInput , +"failed to store the data more then 8 bytes" , + ))); + } + +// Note: rust_section_store() accepts `const uint8_t *buf`. +// +// This is a "compromise" solution: vm-memory requires AtomicAccess +// but QEMU uses uint64_t as the default type. Here we can't convert +// AtomicAccess to u64, since the compiler will complain "an `as` +// expression can only be used to convert between primitive types or +// to coerce to a specific trait object", or other endless errors +// about conversion to u64. +// +// Fortunately, we can use a byte array to bridge the Rust wrapper +// and the C binding. This approach is not without a trade-off, +// however: the rust_section_store() function requires an additional +// conversion from bytes to a uint64_t for the MMIO case. This performance +// overhead is considered acceptable. +// +// SAFETY: the pointers are convertible and the offset conversion is +// considered. +let res =unsafe { +rust_section_store ( + self.as_mut_ptr (), + addr.checked_add (self.deref ().offset_within_region) + .unwrap () + .raw_value (), + val.as_slice ().as_ptr (), + attrs, + lenas u64 , + ) + }; + +match res { +MEMTX_OK =>Ok (()), + _ =>Err (GuestMemoryError ::InvalidBackendAddress ), + } + } + +/// Load a value from guest memory at `addr`. +/// +/// This function - as the low-level load implementation - is +/// called by `FlatView`'s `load()`. And it shouldn't be called to +/// access memory directly. +/// +/// The transaction `attrs` are forwarded to the C side; the `Ordering` is +/// ignored because the access is not Rust-atomic. +fn load <T :AtomicAccess >( + &self, + (addr, attrs): (MemoryRegionAddress ,MemTxAttrs ), + _order:Ordering , + ) ->GuestMemoryResult <T > { +let len =size_of ::<T >(); + +if len >size_of ::<u64 >() { +return Err (GuestMemoryError ::IOError (std::io::Error ::new ( +ErrorKind ::InvalidInput , +"failed to load the data more then 8 bytes" , + ))); + } + +let mut val:T =T ::zeroed (); + +// Note: rust_section_load() accepts `uint8_t *buf`. +// +// This is for a similar reason as store(), with the slight difference +// that rust_section_load() requires an additional conversion from +// uint64_t to bytes. +// +// SAFETY: the pointers are convertible and the offset conversion is +// considered. +let res =unsafe { +rust_section_load ( + self.as_mut_ptr (), + addr.checked_add (self.deref ().offset_within_region) + .unwrap () + .raw_value (), + val.as_mut_slice ().as_mut_ptr (), + attrs, +size_of ::<T >()as u64 , + ) + }; + +match res { +MEMTX_OK =>Ok (val), + _ =>Err (GuestMemoryError ::InvalidBackendAddress ), + } + } + +fn write_slice ( + &self, + _buf: &[u8 ], + _addr: (MemoryRegionAddress ,MemTxAttrs ), + ) ->GuestMemoryResult <()> { +unimplemented! () + } + +fn read_slice ( + &self, + _buf: &mut [u8 ], + _addr: (MemoryRegionAddress ,MemTxAttrs ), + ) ->GuestMemoryResult <()> { +unimplemented! () + } + +fn read_volatile_from <F >( + &self, + _addr: (MemoryRegionAddress ,MemTxAttrs ), + _src: &mut F , + _count:usize , + ) ->GuestMemoryResult <usize > +where +F :ReadVolatile , + { +unimplemented! () + } + +fn read_exact_volatile_from <F >( + &self, + _addr: (MemoryRegionAddress ,MemTxAttrs ), + _src: &mut F , + _count:usize , + ) ->GuestMemoryResult <()> +where +F :ReadVolatile , + { +unimplemented! () + } + +fn write_volatile_to <F >( + &self, + _addr: (MemoryRegionAddress ,MemTxAttrs ), + _dst: &mut F , + _count:usize , + ) ->GuestMemoryResult <usize > +where +F :WriteVolatile , + { +unimplemented! () + } + +fn write_all_volatile_to <F >( + &self, + _addr: (MemoryRegionAddress ,MemTxAttrs ), + _dst: &mut F , + _count:usize , + ) ->GuestMemoryResult <()> +where +F :WriteVolatile , + { +unimplemented! () + } +} + +impl GuestMemoryRegion for MemoryRegionSection { +type B = (); + +/// Get the memory size covered by this `MemoryRegionSection`. +fn len (&self) ->GuestUsize { + self.deref ().sizeas GuestUsize + } + +/// Return the minimum (inclusive) Guest physical address managed by +/// this `MemoryRegionSection`. +fn start_addr (&self) ->GuestAddress { +GuestAddress (self.deref ().offset_within_address_space) + } + +fn bitmap (&self) ->BS <'_,Self ::B > {} + +/// Check whether the `@addr` is covered by this `MemoryRegionSection`. +fn check_address (&self, addr:MemoryRegionAddress ) ->Option <MemoryRegionAddress > { +let region_addr = addr + .checked_add (self.deref ().offset_within_region)? + .raw_value (); +// SAFETY: the pointer is convertible and the offset conversion is +// considered. +if unsafe {section_covers_region_addr (self.as_mut_ptr (), region_addr) } { +Some (addr) + }else { +None + } + } +}
Signature · 1 line
2.34.1
RFC v2 19/26 rust/system/memory: Implement vm_memory::GuestMemory for FlatView
In reply to Zhao LiuImplement vm_memory::GuestMemory for FlatView, and provide memory write/read/store/load bindings.
Note that the semantics of Bytes::read and Bytes::write in FlatView differ from those of the C functions: on the Rust side, read/write operations stop once an error occurs, while on the C side, MemTxResult errors are accumulated and continue accessing to subsequent memory regions.
This is because the current Rust loop implementation (try_access_full()) simply returns an error and aborts the operation. To achieve the consistent semantics as the C side, it would be necessary to support accumulating MemTxResult. This can be addressed as a future enhancement.
---
Changes since v1:
* Implement Bytes<(MemoryRegionAddress, MemTxAttrs)> to attach MemTxAttrs.
* Move GuestMemoryBackend::try_access() to FlatView::try_access_full().
* Use vm-memory::Permissions to replace is_write flag.
--- rust/system/src/memory.rs | 428 +++++++++++++++++++++++++++++++++++++- 1 file changed, 418 insertions(+), 10 deletions(-)
rust/system/src/memory.rs +418 -10
@@ -2,8 +2,8 @@// Author(s): Paolo Bonzini <[email protected]> // SPDX-License-Identifier: GPL-2.0-or-later -//! Bindings for `MemoryRegion`, `MemoryRegionOps`, `MemTxAttrs` and -//! `MemoryRegionSection`. +//! Bindings for `MemoryRegion`, `MemoryRegionOps`, `MemTxAttrs` +//! `MemoryRegionSection` and `FlatView`. use std::{ ffi::{c_uint, c_void,CStr ,CString },
@@ -18,15 +18,16 @@use qom::prelude::*;pub use vm_memory::GuestAddress ;use vm_memory::{ - bitmap::BS ,Address ,AtomicAccess ,Bytes ,GuestMemoryError ,GuestMemoryRegion , -GuestMemoryRegionBytes ,GuestMemoryResult ,GuestUsize ,MemoryRegionAddress ,ReadVolatile , -WriteVolatile , + bitmap::BS ,Address ,AtomicAccess ,Bytes ,GuestMemoryBackend ,GuestMemoryError , +GuestMemoryRegion ,GuestMemoryRegionBytes ,GuestMemoryResult ,GuestUsize ,MemoryRegionAddress , +Permissions ,ReadVolatile ,WriteVolatile , };use crate ::bindings::{ - self, device_endian, memory_region_init_io, rust_section_load, rust_section_read_continue_step, - rust_section_store, rust_section_write_continue_step, section_access_allowed, - section_covers_region_addr, section_fuzz_dma_read,MemTxResult , + self, address_space_lookup_section, device_endian, flatview_translate_section, + memory_region_init_io, rust_section_load, rust_section_read_continue_step, rust_section_store, + rust_section_write_continue_step, section_access_allowed, section_covers_region_addr, + section_fuzz_dma_read,MemTxResult , };// FIXME: Convert hwaddr to GuestAddress pub use crate ::bindings::{hwaddr,MemTxAttrs };
@@ -260,7 +261,6 @@ impl MemoryRegionSection {/// A fuzz testing hook for DMA read. /// /// When `CONFIG_FUZZ` is not set, this hook will do nothing. -#[allow(dead_code)] fn fuzz_dma_read (&self, addr:GuestAddress , len:GuestUsize ) -> &Self {// SAFETY: Opaque<> ensures the pointer is valid, and here it // takes into account the offset conversion between MemoryRegionSection
@@ -280,7 +280,6 @@ fn fuzz_dma_read(&self, addr: GuestAddress, len: GuestUsize) -> &Self {/// A helper to check if the memory access is allowed. /// /// This is needed for memory write/read. -#[allow(dead_code)] fn is_access_allowed ( &self, addr: MemoryRegionAddress,
@@ -632,3 +631,412 @@ fn check_address(&self, addr: MemoryRegionAddress) -> Option<MemoryRegionAddress } } } + +/// A safe wrapper around [`bindings::FlatView`]. +/// +/// [`FlatView`] represents a collection of memory regions, and maps to +/// [`GuestMemoryRegion`]. +/// +/// The memory details are hidden beneath this wrapper. Direct memory access +/// is not allowed. Instead, memory access, e.g., write/read/store/load +/// should process through [`Bytes<GuestAddress>`]. +#[repr(transparent)] +#[derive(common:: Wrapper )] +pub struct FlatView (Opaque <bindings::FlatView >); + +unsafe impl Send for FlatView {} +unsafe impl Sync for FlatView {} + +impl Deref for FlatView { +type Target = bindings::FlatView ; + +fn deref (&self) -> &Self ::Target { +// SAFETY: Opaque<> wraps a pointer from C side. The validity +// of the pointer is confirmed at the creation of Opaque<>. +unsafe { &*self.0 .as_ptr () } + } +} + +impl FlatView { +/// Translate guest address to the offset within a `MemoryRegionSection`. +/// +/// Ideally, this helper should be integrated into +/// `GuestMemoryBackend::to_region_addr()`, but we haven't reached there +/// yet. +fn translate ( + &self, + addr:GuestAddress , + len:GuestUsize , + access:Permissions , + attrs:MemTxAttrs , + ) ->Option <(&MemoryRegionSection ,MemoryRegionAddress ,GuestUsize )> { +let mut remain = lenas hwaddr ; +let mut raw_addr:hwaddr =0 ; + +// SAFETY: the pointers and reference are convertible and the +// offset conversion is considerred. +let ptr =unsafe { +flatview_translate_section ( + self.as_mut_ptr (), + addr.raw_value (), + &mut raw_addr, + &mut remain, + access.has_write (), + attrs, + ) + }; + +if ptr.is_null () { +return None ; + } + +// SAFETY: the pointer is valid and not NULL. +let s =unsafe { + <FlatView as GuestMemoryBackend >::R ::from_raw ( + ptr.cast ::<bindings::MemoryRegionSection >(), + ) + }; +Some (( + s, +MemoryRegionAddress (raw_addr) + .checked_sub (s.deref ().offset_within_region) + .unwrap (), + remainas GuestUsize , + )) + } + +/// Attempts to access a contiguous block of guest memory, executing a +/// callback for each memory region that backs the requested address +/// range. +/// +/// This method is the core of memory access operations. It iterates +/// through each `MemoryRegionSection` that corresponds to the guest +/// address range [`addr`, `addr` + `count`) and invokes the provided +/// closure `f` for each section. +/// +/// This method is a variant of `GuestMemoryBackend::try_access()`, but it +/// includes additional permissions (`Permissions`) and memory transaction +/// attributes (`MemTxAttrs`). Since `GuestMemoryBackend::try_access()` was +/// deprecated in `vm-memory` v0.18.0, `try_access_full()` is implemented +/// directly as an intrinsic method of [`FlatView`]. +/// +/// The callback follows the `try_access()` semantics of `vm-memory`: an +/// `Err` stops the loop immediately. Note that this differs from the +/// C side (`flatview_read_continue()` / `flatview_write_continue()`), +/// which accumulates `MemTxResult` errors and continues accessing +/// subsequent memory regions. +fn try_access_full <F >( + &self, + count:usize , + addr:GuestAddress , + access:Permissions , + attrs:MemTxAttrs , +mut f:F , + ) ->GuestMemoryResult <usize > +where +F :FnMut ( +usize , +usize , +MemoryRegionAddress , + &MemoryRegionSection , + ) ->GuestMemoryResult <usize >, + { +if count ==0 { +return Ok (count); + } + +let mut total =0 ; +let mut curr = addr; + +while total < count { +let len = (count - total)as GuestUsize ; +let (region, start, remain) = self.translate (curr, len, access, attrs).unwrap (); + +if !region.is_access_allowed (start, remain, attrs) { +return Err (GuestMemoryError ::InvalidGuestAddress (addr)); + } + +match f (total, remainas usize , start, region) { +// no more data +Ok (0 ) =>return Ok (total), +// made some progress +Ok (res) => { +if resas GuestUsize > remain { +return Err (GuestMemoryError ::CallbackOutOfRange ); + } + + total =match total.checked_add (res) { +Some (x)if x < count => x, +Some (x)if x == count =>return Ok (x), + _ =>return Err (GuestMemoryError ::CallbackOutOfRange ), + }; + + curr =match curr.overflowing_add (resas GuestUsize ) { + (x @GuestAddress (0 ), _) | (x,false ) => x, + (_,true ) =>return Err (GuestMemoryError ::GuestAddressOverflow ), + }; + } +// error happened + e =>return e, + } + } + +if total ==0 { +Err (GuestMemoryError ::InvalidGuestAddress (addr)) + }else { +Ok (total) + } + } +} + +/// The attrs-aware `Bytes` implementation for `(GuestAddress, MemTxAttrs)`. +impl Bytes <(GuestAddress ,MemTxAttrs )>for FlatView { +type E =GuestMemoryError ; + +/// Write a byte buffer into guest memory, similar to `flatview_write` on +/// the C side. It is only for internal use and should not be called +/// directly. +/// +/// The write stops once an error occurs. This differs from the C side +/// (`flatview_write_continue()`), which accumulates `MemTxResult` errors +/// and continues accessing subsequent memory regions. +/// +/// Note: This function should be called within RCU critical section. +fn write ( + &self, + buf: &[u8 ], + (addr, attrs): (GuestAddress ,MemTxAttrs ), + ) ->GuestMemoryResult <usize > { + self.try_access_full ( + buf.len (), + addr, +Permissions ::Write , + attrs, + |offset, count, caddr, region| ->GuestMemoryResult <usize > { +// vm-memory provides an elegent way to advance (See +// ReadVolatile::read_volatile), but at this moment, +// this simple way is enough. +let sub_buf = &buf[offset..offset + count]; +Bytes ::write (region, sub_buf, (caddr, attrs)) + }, + ) + } + +/// Read a byte buffer from guest memory, similar to `flatview_read` on +/// the C side. It is only for internal use and should not be called +/// directly. +/// +/// The read stops once an error occurs. This differs from the C side +/// (`flatview_read_continue()`), which accumulates `MemTxResult` errors +/// and continues accessing subsequent memory regions. +/// +/// Note: This function should be called within RCU critical section. +fn read ( + &self, + buf: &mut [u8 ], + (addr, attrs): (GuestAddress ,MemTxAttrs ), + ) ->GuestMemoryResult <usize > { +if buf.is_empty () { +return Ok (0 ); + } + + self.try_access_full ( + buf.len (), + addr, +Permissions ::Read , + attrs, + |offset, count, caddr, region| ->GuestMemoryResult <usize > { +// vm-memory provides an elegent way to advance (See +// ReadVolatile::write_volatile), but at this moment, +// this simple way is enough. +let sub_buf = &mut buf[offset..offset + count]; +Bytes ::read ( + region.fuzz_dma_read (addr, sub_buf.len ()as GuestUsize ), + sub_buf, + (caddr, attrs), + ) + }, + ) + } + +/// Store a value into guest memory at `addr`. It is only for internal +/// use and should not be called directly. +/// +/// Note: This function should be called within RCU critical section. +fn store <T :AtomicAccess >( + &self, + val:T , + (addr, attrs): (GuestAddress ,MemTxAttrs ), + order:Ordering , + ) ->GuestMemoryResult <()> { + self.translate ( + addr, +size_of ::<T >()as GuestUsize , +Permissions ::Write , + attrs, + ) + .ok_or (GuestMemoryError ::InvalidGuestAddress (addr)) + .and_then (|(region, region_addr, remain)| { +// Although the C side handles this cross-region case via MMIO +// by default, it is highly suspicious for store/load operations. +// Since Bytes::store() does not support additional arguments to +// identify this scenario, report an error directly! +if remain <size_of ::<T >()as GuestUsize { +return Err (GuestMemoryError ::InvalidBackendAddress ); + } + +Bytes ::store (region, val, (region_addr, attrs), order) + }) + } + +/// Load a value from guest memory at `addr`. It is only for internal +/// use and should not be called directly. +/// +/// Note: This function should be called within RCU critical section. +fn load <T :AtomicAccess >( + &self, + (addr, attrs): (GuestAddress ,MemTxAttrs ), + order:Ordering , + ) ->GuestMemoryResult <T > { + self.translate (addr,size_of ::<T >()as GuestUsize ,Permissions ::Read , attrs) + .ok_or (GuestMemoryError ::InvalidGuestAddress (addr)) + .and_then (|(region, region_addr, remain)| ->GuestMemoryResult <T > { +// Although the C side handles this cross-region case via MMIO +// by default, it is highly suspicious for store/load operations. +// Since Bytes::load() does not support additional arguments to +// identify this scenario, report an error directly! +if remain <size_of ::<T >()as GuestUsize { +return Err (GuestMemoryError ::InvalidBackendAddress ); + } + +Bytes ::load ( + region.fuzz_dma_read (addr,size_of ::<T >()as GuestUsize ), + (region_addr, attrs), + order, + ) + }) + } + +fn write_slice (&self, _buf: &[u8 ], _addr: (GuestAddress ,MemTxAttrs )) ->GuestMemoryResult <()> { +unimplemented! () + } + +fn read_slice ( + &self, + _buf: &mut [u8 ], + _addr: (GuestAddress ,MemTxAttrs ), + ) ->GuestMemoryResult <()> { +unimplemented! () + } + +fn read_volatile_from <F >( + &self, + _addr: (GuestAddress ,MemTxAttrs ), + _src: &mut F , + _count:usize , + ) ->GuestMemoryResult <usize > +where +F :ReadVolatile , + { +unimplemented! () + } + +fn read_exact_volatile_from <F >( + &self, + _addr: (GuestAddress ,MemTxAttrs ), + _src: &mut F , + _count:usize , + ) ->GuestMemoryResult <()> +where +F :ReadVolatile , + { +unimplemented! () + } + +fn write_volatile_to <F >( + &self, + _addr: (GuestAddress ,MemTxAttrs ), + _dst: &mut F , + _count:usize , + ) ->GuestMemoryResult <usize > +where +F :WriteVolatile , + { +unimplemented! () + } + +fn write_all_volatile_to <F >( + &self, + _addr: (GuestAddress ,MemTxAttrs ), + _dst: &mut F , + _count:usize , + ) ->GuestMemoryResult <()> +where +F :WriteVolatile , + { +unimplemented! () + } +} + +impl GuestMemoryBackend for FlatView { +type R =MemoryRegionSection ; + +/// Get the number of `MemoryRegionSection`s managed by this `FlatView`. +fn num_regions (&self) ->usize { + self.deref ().nr.try_into ().unwrap () + } + +/// Find the `MemoryRegionSection` which covers @addr +fn find_region (&self, addr:GuestAddress ) ->Option <&Self ::R > { +// set resolve_subpage as true by default +// +// SAFETY: bindings::FlatView has `dispatch` field and the pointer is +// valid, although accessing the field of C structure is ugly. +let raw = +unsafe {address_space_lookup_section (self.deref ().dispatch, addr.raw_value (),true ) }; + +if !raw.is_null () { +let s =unsafe {Self ::R ::from_raw (raw) }; +Some (s) + }else { +None + } + } + +/// Return an empty iterator. +/// +/// This function always triggers panic. +#[allow(unreachable_code)] +fn iter (&self) ->impl Iterator <Item = &Self ::R > { +unreachable! ();// Do not use this iter()! + +// QEMU has a linear iteration mechanism on the C side named +// `flatview_for_each_range`, but it iterates over `FlatRange`s +// instead of `MemoryRegionSection`s. +// +// It is still possible to have an `Iterator` based on +// `MemoryRegionSection` by iterating over +// `FlatView::dispatch::map::sections`. +// +// However, it is not worth it. QEMU has implemented the two-level +// "page" walk in `phys_page_find`, which is more efficient than +// linear iteration. Therefore, there is no need to reinvent the +// wheel on the Rust side, at least for now. +// +// Just return an empty iterator to satisfy the trait's contract. +// This makes the code compile, but the iterator won't yield +// any items. + std::iter::empty () + } + +fn to_region_addr (&self, _addr:GuestAddress ) ->Option <(&Self ::R ,MemoryRegionAddress )> { +// Note: This method should implement FlatView::translate(), but +// its function signature is ill-suited for QEMU's translation needs. +// QEMU needs to distinguish whether an access is a write, and it must +// account for the remaining bytes of the region. +// +// FIXME: Once GuestMemoryBackend::to_region_addr() can meet QEMU's +// requirements, move the FlatView::translate() logic here. +unimplemented! () + } +}
Signature · 1 line
2.34.1
RFC v2 20/26 rust/system/memory: Switch to iteration style for memory access
In reply to Zhao LiuThe vm-memory crate deprecated try_access() and switched to using get_slices(). Therefore, continuing to access memory in QEMU via a similar function like try_access_full() is no longer appropriate in the long run, as it blocks future alignment with vm-memory.
However, QEMU cannot directly use get_slices() because VolatileSlice does not match QEMU's richer memory backend semantics (which must support both RAM and MMIO).
To achieve an iteration-style approach similar to get_slices(), introduce FlatViewChunk to QEMU. Unlike VolatileSlice, FlatViewChunk does not contain a host address; instead, it records the corresponding backend memory region (RAM or MMIO).
Building on this, introduce FlatViewChunkIterator as the memory access iterator. This replaces the original try_access_full() with a graceful iteration mechanism, providing QEMU with a get_chunks() method equivalent to vm-memory's get_slices().
While this iteration style adds some structural complexity, it actually aligns perfectly with the C side's loop logic. Conceptually, the Rust iterator simply encapsulates the local variables of the C loop into an iterator state (FlatViewChunkIterator) and a step structure (FlatViewChunk). Furthermore, this complexity is contained entirely within the lower-level implementation and remains invisible to high-level callers.
Finally, this design reflects QEMU's actual requirements and highlights the gap with the current vm-memory crate. This could inspire vm-memory to implement a higher-level slice abstraction in the future that accommodates both VolatileSlice and FlatViewChunk semantics.
---
Changes since v1:
* New commit to align with the changes in vm-memory v0.18.0.
--- rust/system/src/memory.rs | 383 ++++++++++++++++++++++++-------------- 1 file changed, 243 insertions(+), 140 deletions(-)
rust/system/src/memory.rs +243 -140
@@ -632,6 +632,146 @@ fn check_address(&self, addr: MemoryRegionAddress) -> Option<MemoryRegionAddress } } +/// A contiguous part of a guest address range within a single +/// [`MemoryRegionSection`], inspired by `vm-memory`'s `VolatileSlice`. +/// +/// QEMU cannot use `VolatileSlice` because it requires a host pointer, which +/// is not available for MMIO regions. Instead, QEMU needs to record the +/// `MemoryRegionSection` as the backend to support both RAM and MMIO. +/// +/// The `(mr, mr_addr, l)` triple corresponds to the loop-local variables used +/// in the C side's `flatview_read_continue()` and `flatview_write_continue()`. +/// On the Rust side, these variables are encapsulated into a `FlatViewChunk` +/// to enable an iterator-based abstraction; the remaining loop variables are +/// stored in [`FlatViewChunkIterator`]. +#[derive( Debug )] +struct FlatViewChunk <'a> { +/// The section backing this chunk. + region: &'aMemoryRegionSection , +/// Offset of this chunk within `region`. + region_addr:MemoryRegionAddress , +/// Length of this chunk, in bytes. + len:usize , +} + +/// Iterator over the [`FlatViewChunk`]s covering a guest address range, +/// inspired by `vm-memory`'s `GuestMemoryBackendSliceIterator`. +/// +/// It maintains the loop state across iterations, while each +/// [`FlatViewChunk`] describes the result of a single translation step. +struct FlatViewChunkIterator <'a> { +/// The `FlatView` being iterated. + view: &'aFlatView , +/// Next guest address still to translate. + addr:GuestAddress , +/// Bytes still to cover. + remaining:usize , +/// Requested access mode: whether it is a write or not. + access:Permissions , +/// Transaction attributes. + attrs:MemTxAttrs , +} + +impl <'a>FlatViewChunkIterator <'a> { +/// Helper [`Self::next`]. Get the next chunk and update the internal +/// state. +/// +/// This method is inspired by `vm-memory`'s +/// `GuestMemorySliceIterator::do_next`. +/// +/// # Safety +/// +/// Whether `self.remaining` is 0 is the key condition that determines +/// whether the iteration should be terminated. This function is +/// responsible only for the actual execution of the iteration. The caller +/// must ensure the timing and logic for resetting `self.remaining` to 0 +/// are correct to avoid invalid memory accesses or undefined behavior. +unsafe fn do_next (&mut self) ->Option <GuestMemoryResult <FlatViewChunk <'a>>> { +if self.remaining ==0 { +return None ; + } + +let (region, region_addr, region_len) =match self.view.translate ( + self.addr, + self.remainingas GuestUsize , + self.access, + self.attrs, + ) { +Some (t) => t, +None => { +return Some (Err (GuestMemoryError ::InvalidGuestAddress (self.addr))); + } + }; + +if !region.is_access_allowed (region_addr, region_len, self.attrs) { +return Some (Err (GuestMemoryError ::InvalidGuestAddress (self.addr))); + } + +// A zero-length translation would loop forever. +if region_len ==0 { +return Some (Err (GuestMemoryError ::InvalidGuestAddress (self.addr))); + } + + self.remaining -= region_lenas usize ; +if self.remaining >0 { + self.addr =match self.addr.overflowing_add (region_len) { + (x @GuestAddress (0 ), _) | (x,false ) => x, + (_,true ) => { +return Some (Err (GuestMemoryError ::GuestAddressOverflow )); + } + }; + } + +Some (Ok (FlatViewChunk { + region, + region_addr, + len: region_lenas usize , + })) + } + +/// Adapts the iterator to return `None` when an error occurs after +/// at least one successful chunk, halting iteration and yielding a +/// partial result. If an error occurs on the very first chunk, it is +/// propagated instead. +/// +/// This method is inspired by `vm-memory`'s +/// `GuestMemorySliceIterator::stop_on_error`. +/// +/// For QEMU, this implementation is a trade-off. Currently, there is +/// no way to report the number of bytes successfully processed within +/// `GuestMemoryError`. Returning this partial progress would be much +/// more useful than simply returning a bare error type. In the future, +/// a richer error type carrying `(bytes_done, cause)` could replace +/// this method. +fn stop_on_error (self) ->GuestMemoryResult <impl Iterator <Item =FlatViewChunk <'a>>> { +let mut peek = self.peekable (); +if let Some (err) = peek.next_if (GuestMemoryResult ::is_err) { +return Err (err.unwrap_err ()); + } +Ok (peek.filter_map (GuestMemoryResult ::ok)) + } +} + +impl <'a>Iterator for FlatViewChunkIterator <'a> { +type Item =GuestMemoryResult <FlatViewChunk <'a>>; + +/// A wrapper for [`Self::do_next`] that permanently stops the iteration on +/// error. If an `Err` is returned, it sets `self.remaining` to 0 so that +/// all subsequent calls simply return `None`. +fn next (&mut self) ->Option <Self ::Item > { +// SAFETY: +// Reset `self.remaining` to 0 on error +match unsafe { self.do_next () } { +Some (Ok (chunk)) =>Some (Ok (chunk)), + other => { +// On error (or end), reset to 0 so iteration remains stopped + self.remaining =0 ; + other + } + } + } +} +/// A safe wrapper around [`bindings::FlatView`]. /// /// [`FlatView`] represents a collection of memory regions, and maps to
@@ -705,86 +845,21 @@ fn translate( )) } -/// Attempts to access a contiguous block of guest memory, executing a -/// callback for each memory region that backs the requested address -/// range. -/// -/// This method is the core of memory access operations. It iterates -/// through each `MemoryRegionSection` that corresponds to the guest -/// address range [`addr`, `addr` + `count`) and invokes the provided -/// closure `f` for each section. -/// -/// This method is a variant of `GuestMemoryBackend::try_access()`, but it -/// includes additional permissions (`Permissions`) and memory transaction -/// attributes (`MemTxAttrs`). Since `GuestMemoryBackend::try_access()` was -/// deprecated in `vm-memory` v0.18.0, `try_access_full()` is implemented -/// directly as an intrinsic method of [`FlatView`]. -/// -/// The callback follows the `try_access()` semantics of `vm-memory`: an -/// `Err` stops the loop immediately. Note that this differs from the -/// C side (`flatview_read_continue()` / `flatview_write_continue()`), -/// which accumulates `MemTxResult` errors and continues accessing -/// subsequent memory regions. -fn try_access_full <F >( +/// Returns a lazy iterator over the [`FlatViewChunk`]s, inspired by +/// vm-memory's `get_slices()`. +fn get_chunks ( &self, - count:usize , addr:GuestAddress , + count:usize , access:Permissions , attrs:MemTxAttrs , -mut f:F , - ) ->GuestMemoryResult <usize > -where -F :FnMut ( -usize , -usize , -MemoryRegionAddress , - &MemoryRegionSection , - ) ->GuestMemoryResult <usize >, - { -if count ==0 { -return Ok (count); - } - -let mut total =0 ; -let mut curr = addr; - -while total < count { -let len = (count - total)as GuestUsize ; -let (region, start, remain) = self.translate (curr, len, access, attrs).unwrap (); - -if !region.is_access_allowed (start, remain, attrs) { -return Err (GuestMemoryError ::InvalidGuestAddress (addr)); - } - -match f (total, remainas usize , start, region) { -// no more data -Ok (0 ) =>return Ok (total), -// made some progress -Ok (res) => { -if resas GuestUsize > remain { -return Err (GuestMemoryError ::CallbackOutOfRange ); - } - - total =match total.checked_add (res) { -Some (x)if x < count => x, -Some (x)if x == count =>return Ok (x), - _ =>return Err (GuestMemoryError ::CallbackOutOfRange ), - }; - - curr =match curr.overflowing_add (resas GuestUsize ) { - (x @GuestAddress (0 ), _) | (x,false ) => x, - (_,true ) =>return Err (GuestMemoryError ::GuestAddressOverflow ), - }; - } -// error happened - e =>return e, - } - } - -if total ==0 { -Err (GuestMemoryError ::InvalidGuestAddress (addr)) - }else { -Ok (total) + ) ->FlatViewChunkIterator <'_> { +FlatViewChunkIterator { + view: self, + addr, + remaining: count, + access, + attrs, } } }
@@ -807,19 +882,32 @@ fn write( buf: &[u8], (addr, attrs): (GuestAddress, MemTxAttrs), ) -> GuestMemoryResult<usize> { - self.try_access_full ( - buf.len (), - addr, -Permissions ::Write , - attrs, - |offset, count, caddr, region| ->GuestMemoryResult <usize > { -// vm-memory provides an elegent way to advance (See -// ReadVolatile::read_volatile), but at this moment, -// this simple way is enough. -let sub_buf = &buf[offset..offset + count]; -Bytes ::write (region, sub_buf, (caddr, attrs)) - }, - ) +let completed = self + .get_chunks (addr, buf.len (),Permissions ::Write , attrs) + .stop_on_error ()? + .try_fold (0 , |acc, chunk| { +let sub_buf = &buf[acc..acc + chunk.len]; +let n =Bytes ::write (chunk.region, sub_buf, (chunk.region_addr, attrs))?; +// Since the iterator has already advanced past it, the +// incomplete write results in the wrong buffer offset. +if n != chunk.len { +return Err (GuestMemoryError ::PartialBuffer { + expected: buf.len (), + completed: acc + n, + }); + } +Ok (acc + n) + })?; + +// `stop_on_error` silently truncates the iterator if `next()` returns +// an error. Convert this into a `PartialBuffer` error. +if completed != buf.len () { +return Err (GuestMemoryError ::PartialBuffer { + expected: buf.len (), + completed, + }); + } +Ok (completed) }/// Read a byte buffer from guest memory, similar to `flatview_read` on
@@ -836,27 +924,36 @@ fn read( buf: &mut [u8], (addr, attrs): (GuestAddress, MemTxAttrs), ) -> GuestMemoryResult<usize> { -if buf.is_empty () { -return Ok (0 ); +let expected = buf.len (); +let completed = self + .get_chunks (addr, expected,Permissions ::Read , attrs) + .stop_on_error ()? + .try_fold (0 , |acc, chunk| { +let sub_buf = &mut buf[acc..acc + chunk.len]; +let region = chunk + .region + .fuzz_dma_read (addr, sub_buf.len ()as GuestUsize ); +let n =Bytes ::read (region, sub_buf, (chunk.region_addr, attrs))?; +// Since the iterator has already advanced past it, the +// incomplete read results in the wrong buffer offset. +if n != chunk.len { +return Err (GuestMemoryError ::PartialBuffer { + expected, + completed: acc + n, + }); + } +Ok (acc + n) + })?; + +// `stop_on_error` silently truncates the iterator if `next()` returns +// an error. Convert this into a `PartialBuffer` error. +if completed != expected { +return Err (GuestMemoryError ::PartialBuffer { + expected, + completed, + }); } - - self.try_access_full ( - buf.len (), - addr, -Permissions ::Read , - attrs, - |offset, count, caddr, region| ->GuestMemoryResult <usize > { -// vm-memory provides an elegent way to advance (See -// ReadVolatile::write_volatile), but at this moment, -// this simple way is enough. -let sub_buf = &mut buf[offset..offset + count]; -Bytes ::read ( - region.fuzz_dma_read (addr, sub_buf.len ()as GuestUsize ), - sub_buf, - (caddr, attrs), - ) - }, - ) +Ok (completed) }/// Store a value into guest memory at `addr`. It is only for internal
@@ -869,24 +966,25 @@ fn store<T: AtomicAccess>( (addr, attrs): (GuestAddress, MemTxAttrs), order: Ordering, ) -> GuestMemoryResult<()> { - self.translate ( - addr, -size_of ::<T >()as GuestUsize , -Permissions ::Write , - attrs, - ) - .ok_or (GuestMemoryError ::InvalidGuestAddress (addr)) - .and_then (|(region, region_addr, remain)| { -// Although the C side handles this cross-region case via MMIO -// by default, it is highly suspicious for store/load operations. -// Since Bytes::store() does not support additional arguments to -// identify this scenario, report an error directly! -if remain <size_of ::<T >()as GuestUsize { -return Err (GuestMemoryError ::InvalidBackendAddress ); - } +match self + .get_chunks (addr,size_of ::<T >(),Permissions ::Write , attrs) + .next ()// Compared to C, this includes additional checks for access and overflow. + { +None =>Err (GuestMemoryError ::InvalidGuestAddress (addr)), +Some (Err (e)) =>Err (e), +Some (Ok (chunk)) => { +// Though C side handles this cross region case via MMIO +// by default, it still looks very suspicious for store/ +// load. It happens Bytes::store() doesn't support more +// argument to identify this case, so report an error +// directly! +if chunk.len <size_of ::<T >() { +return Err (GuestMemoryError ::InvalidBackendAddress ); + } -Bytes ::store (region, val, (region_addr, attrs), order) - }) +Bytes ::store (chunk.region, val, (chunk.region_addr, attrs), order) + } + } }/// Load a value from guest memory at `addr`. It is only for internal
@@ -898,23 +996,28 @@ fn load<T: AtomicAccess>( (addr, attrs): (GuestAddress, MemTxAttrs), order: Ordering, ) -> GuestMemoryResult<T> { - self.translate (addr,size_of ::<T >()as GuestUsize ,Permissions ::Read , attrs) - .ok_or (GuestMemoryError ::InvalidGuestAddress (addr)) - .and_then (|(region, region_addr, remain)| ->GuestMemoryResult <T > { -// Although the C side handles this cross-region case via MMIO -// by default, it is highly suspicious for store/load operations. -// Since Bytes::load() does not support additional arguments to -// identify this scenario, report an error directly! -if remain <size_of ::<T >()as GuestUsize { + match self + .get_chunks(addr, size_of::<T>(), Permissions::Read, attrs) + .next() // Compared to C, this includes additional checks for access and overflow. + { + None => Err(GuestMemoryError::InvalidGuestAddress(addr)), + Some(Err(e)) => Err(e), + Some(Ok(chunk)) => { + // Though C side handles this cross region case via MMIO + // by default, it still looks very suspicious for store/ + // load. It happens Bytes::load() doesn't support more + // arguments to identify this case, so report an error + // directly! + if chunk.len < size_of::<T>() { return Err(GuestMemoryError::InvalidBackendAddress); } -Bytes ::load ( - region.fuzz_dma_read (addr,size_of ::<T >()as GuestUsize ), - (region_addr, attrs), - order, - ) - }) + let region = chunk + .region + .fuzz_dma_read(addr, size_of::<T>() as GuestUsize); + Bytes::load(region, (chunk.region_addr, attrs), order) + } + } } fn write_slice(&self, _buf: &[u8], _addr: (GuestAddress, MemTxAttrs)) -> GuestMemoryResult<()> {
Signature · 1 line
2.34.1
RFC v2 21/26 rust/system/memory: Add an RAII guard to manage FlatView reference counts
In reply to Zhao LiuIntroduce FlatViewRefGuard to automatically manage the reference count for FlatView on the Rust side using RAII.
--- rust/system/src/memory.rs | 65 ++++++++++++++++++++++++++++++++++++--- 1 file changed, 61 insertions(+), 4 deletions(-)
rust/system/src/memory.rs +61 -4
@@ -11,6 +11,7 @@ marker::PhantomData, mem::size_of, ops::Deref, + ptr::NonNull, sync::atomic::Ordering, };
@@ -24,10 +25,10 @@ };use crate ::bindings::{ - self, address_space_lookup_section, device_endian, flatview_translate_section, - memory_region_init_io, rust_section_load, rust_section_read_continue_step, rust_section_store, - rust_section_write_continue_step, section_access_allowed, section_covers_region_addr, - section_fuzz_dma_read,MemTxResult , + self, address_space_lookup_section, device_endian, flatview_ref, flatview_translate_section, + flatview_unref, memory_region_init_io, rust_section_load, rust_section_read_continue_step, + rust_section_store, rust_section_write_continue_step, section_access_allowed, + section_covers_region_addr, section_fuzz_dma_read,MemTxResult , };// FIXME: Convert hwaddr to GuestAddress pub use crate ::bindings::{hwaddr,MemTxAttrs };
@@ -1143,3 +1144,59 @@ fn to_region_addr(&self, _addr: GuestAddress) -> Option<(&Self::R, MemoryRegionAunimplemented! () } } + +/// A RAII guard that provides temporary access to a `FlatView`. +/// +/// Upon creation, this guard increments the reference count of the +/// underlying `FlatView`. When the guard goes out of of scope, it +/// automatically decrements the count. +/// +/// As long as the guard lives, the access to `FlatView` is valid. +#[derive( Debug )] +pub struct FlatViewRefGuard (NonNull <FlatView >); + +impl Drop for FlatViewRefGuard { +fn drop (&mut self) { +// SAFETY: the pointer is convertible. +unsafe { +flatview_unref (self.0 .as_ref ().as_mut_ptr ()); + } + } +} + +impl FlatViewRefGuard { +/// Attempt to create a new RAII guard for the given `FlatView`. +/// +/// This may fail if the `FlatView`'s reference count is already zero. +pub fn new (flat: &FlatView ) ->Option <Self > { +// SAFETY: the pointer is convertible. +if unsafe {flatview_ref (flat.as_mut_ptr ()) } { +Some (FlatViewRefGuard (NonNull ::from (flat))) + }else { +None + } + } +} + +impl Deref for FlatViewRefGuard { +type Target =FlatView ; + +fn deref (&self) -> &Self ::Target { +// SAFETY: the pointer and reference are convertible. +unsafe { &*self.0 .as_ptr () } + } +} + +impl Clone for FlatViewRefGuard { +/// Clone the guard, which involves incrementing the reference +/// count again. +/// +/// This method will **panic** if the reference count of the underlying +/// `FlatView` cannot be incremented (e.g., if it is zero, meaning the +/// object is being destroyed). This can happen in concurrent scenarios. +fn clone (&self) ->Self { +FlatViewRefGuard ::new (self.deref ()).expect ( +"Failed to clone FlatViewRefGuard: the FlatView may have been destroyed concurrently." , + ) + } +}
Signature · 1 line
2.34.1
RFC v2 22/26 rust/system/memory: Wrap vm-memory's endian types for explicit access
In reply to Zhao LiuQEMU is getting rid of native endianness, so the load/store interfaces should explicitly specify the target device's endianness.
vm-memory provides BeNN and LeNN types, but its Bytes trait uses the AtomicAccess trait bound for its save/load methods. The explicit endian wrappers do not implement this bound.
As the top-level interface, AddressSpace does not need to implement the Bytes trait. It can simply take explicit endian types in its save/load methods, convert them to a fixed-width AtomicAccess primitive, and forward them to the underlying FlatView's Bytes::save and load.
Introduce the EndianValued trait to wrap vm-memory's endian types, allowing interfaces that require explicit endianness to use it as a trait bound.
Also, add a conversion method in EndianValued to get the fixed-width AtomicAccess carrier, allowing higher-level interfaces to maintain compatibility with Bytes::save/load internally.
Finally, implement the Sealed pattern for EndianValued to strictly limit the supported types within the crate.
---
Changes since v1:
* New commit to wrap BeNN and LeNN as an independent trait.
--- rust/system/src/memory.rs | 94 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 92 insertions(+), 2 deletions(-)
rust/system/src/memory.rs +92 -2
@@ -17,12 +17,12 @@use common::{callbacks::FnCall , uninit::MaybeUninitField , zeroable::Zeroable ,Opaque };use qom::prelude::*; -pub use vm_memory::GuestAddress ;use vm_memory::{ - bitmap::BS ,Address ,AtomicAccess ,Bytes ,GuestMemoryBackend ,GuestMemoryError , + bitmap::BS ,Address ,AtomicAccess ,ByteValued ,Bytes ,GuestMemoryBackend ,GuestMemoryError ,GuestMemoryRegion ,GuestMemoryRegionBytes ,GuestMemoryResult ,GuestUsize ,MemoryRegionAddress ,Permissions ,ReadVolatile ,WriteVolatile , }; +pub use vm_memory::{Be16 ,Be32 ,Be64 ,GuestAddress ,Le16 ,Le32 ,Le64 };use crate ::bindings::{ self, address_space_lookup_section, device_endian, flatview_ref, flatview_translate_section,
@@ -1200,3 +1200,93 @@ fn clone(&self) -> Self { ) } } + +/// Private module hosting the [`Sealed`](private::Sealed) supertrait of +/// [`EndianValued`], keeping the set of [`EndianValued`] types closed to the +/// ones listed below. +/// +/// Reference: <https://rust-lang.github.io/api-guidelines/future-proofing.html#c-sealed> +mod private { +pub trait Sealed {} +} + +/// A sealed trait for types with an explicitly fixed byte order (e.g., `Le32`, +/// `Be32`). +/// +/// This ensures guest memory accesses via [`AddressSpace::store`] and +/// [`AddressSpace::load`] are strictly independent of the host endianness. +/// Types with implicit endianness (like bare u32 or [u8; 4]) are rejected. +/// +/// Architecturally, this trait is designed for two purposes: +/// +/// 1) Bypass the orphan rule: It acts as a local trait allowed to select +/// specific `LeNN` and `BeNN` types from `vm-memory`'s [`ByteValued`], +/// allowing a trait bound for the `AddressSpace` API. +/// +/// 2) Enforce a closed set: Combined with the sealed mechanism, it prevents +/// downstream crates (device or other crates) from implementing this trait. +pub trait EndianValued :ByteValued + private::Sealed { +/// The same-width primitive integer used as the atomic carrier when an +/// explicit-endian access is passed to `Bytes::store`/`Bytes::load`. +type Carrier :AtomicAccess ; + +/// Convert `self` to [`Carrier`](Self::Carrier) integer, keeping the exact +/// bytes. +fn to_carrier (self) ->Self ::Carrier ; + +/// Convert the [`Carrier`](Self::Carrier) integer back to this +/// fixed-endian type, keeping the exact bytes. +fn from_carrier (carrier:Self ::Carrier ) ->Self ; +} + +macro_rules! impl_endian_valued { + ($($t:ty => $carrier:ty),* $(,)?) => { + $( +impl private::Sealed for $t {} + +impl EndianValued for $t { +type Carrier = $carrier; + +#[inline(always)] +#[allow(clippy::useless_transmute)] // For i8 and u8 +fn to_carrier (self) ->Self ::Carrier { +// SAFETY: The macro strictly pairs types of the exact same size. +unsafe { std::mem::transmute (self) } + } + +#[inline(always)] +#[allow(clippy::useless_transmute)] // For i8 and u8 +fn from_carrier (carrier:Self ::Carrier ) ->Self { +// SAFETY: The macro strictly pairs types of the exact same size. +unsafe { std::mem::transmute (carrier) } + } + } + )* + }; +} + +// Explicit-endian wrappers (byte order fixed by the type) plus the single-byte +// integers (which have no byte order at all). +impl_endian_valued! ( +Le16 =>u16 , +Le32 =>u32 , +Be16 =>u16 , +Be32 =>u32 , +u8 =>u8 , +i8 =>i8 , +); + +// vm-memory only implements `AtomicAccess` for the 64-bit primitives on 64-bit +// targets. Copy vm-memory's cfg here to avoid a mismatch between the two +// traits. +#[cfg(any( +target_arch = "x86_64" , +target_arch = "aarch64" , +target_arch = "powerpc64" , +target_arch = "s390x" , +target_arch = "riscv64" +))] +impl_endian_valued! ( +Le64 =>u64 , +Be64 =>u64 , +);
Signature · 1 line
2.34.1
RFC v2 23/26 rust/memory: Provide AddressSpace bindings
In reply to Zhao LiuQEMU's AddressSpace matches vm_memory::GuestAddressSpace very well, so it's straightforward to implement vm_memory::GuestAddressSpace trait for &AddressSpace (not AddressSpace because GuestAddressSpace requires Clone).
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.
Note, AddressSpace::read, write, load and store methods support MEMTXATTRS_UNSPECIFIED by default, but it can support any MemTxAttrs. When necessary, it's possible to add *_attrs variants.
---
Changes since v1:
* Implement GuestAddressSpace for &AddressSpace since it requires Clone for now.
* Re-implement RCU protection logic by using RcuCell and lifetime to provide RCU critical section.
* Fix AddressSapce::memory() and use a loop just like C side did.
* Explicitly require AddressSpace::save and load specify endianness and no longer rely on native endianness.
--- rust/system/src/memory.rs | 205 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 196 insertions(+), 9 deletions(-)
rust/system/src/memory.rs +196 -9
@@ -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,24 +11,28 @@ marker::PhantomData, mem::size_of, ops::Deref, - ptr::NonNull, + ptr::{addr_of, NonNull}, sync::atomic::Ordering, };use common::{callbacks::FnCall , uninit::MaybeUninitField , zeroable::Zeroable ,Opaque };use qom::prelude::*; +use util::{ + error::Result , + rcu::{RcuCell ,RcuGuard }, +};use vm_memory::{ - bitmap::BS ,Address ,AtomicAccess ,ByteValued ,Bytes ,GuestMemoryBackend ,GuestMemoryError , -GuestMemoryRegion ,GuestMemoryRegionBytes ,GuestMemoryResult ,GuestUsize ,MemoryRegionAddress , -Permissions ,ReadVolatile ,WriteVolatile , + bitmap::BS ,Address ,AtomicAccess ,ByteValued ,Bytes ,GuestAddressSpace ,GuestMemoryBackend , +GuestMemoryError ,GuestMemoryRegion ,GuestMemoryRegionBytes ,GuestMemoryResult ,GuestUsize , +MemoryRegionAddress ,Permissions ,ReadVolatile ,WriteVolatile , };pub use vm_memory::{Be16 ,Be32 ,Be64 ,GuestAddress ,Le16 ,Le32 ,Le64 };use crate ::bindings::{ - self, address_space_lookup_section, device_endian, flatview_ref, flatview_translate_section, - flatview_unref, memory_region_init_io, rust_section_load, rust_section_read_continue_step, - rust_section_store, rust_section_write_continue_step, section_access_allowed, - section_covers_region_addr, section_fuzz_dma_read,MemTxResult , + self, address_space_lookup_section, address_space_memory, device_endian, flatview_ref, + flatview_translate_section, flatview_unref, memory_region_init_io, rust_section_load, + rust_section_read_continue_step, rust_section_store, rust_section_write_continue_step, + section_access_allowed, section_covers_region_addr, section_fuzz_dma_read,MemTxResult , };// FIXME: Convert hwaddr to GuestAddress pub use crate ::bindings::{hwaddr,MemTxAttrs };
@@ -1290,3 +1294,186 @@ fn from_carrier(carrier: Self::Carrier) -> Self { Le64 => u64, Be64 => u64, ); + +/// 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(common:: 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`], similar to `address_space_get_flatview` on the C side. +fn memory (&self) ->Self ::T { +let rcu =RcuGuard ::new (); +// Similar loop as `address_space_get_flatview` did. +loop { +// SAFETY: FlatViewRefGuard ensures the returned reference is protected by the +// guard. +if let Some (guard) =FlatViewRefGuard ::new (unsafe { self.get_flatview (&rcu) }) { +return guard; + } + } + } +} + +impl Deref for AddressSpace { +type Target = bindings::AddressSpace ; + +fn deref (&self) -> &Self ::Target { +// SAFETY: Opaque<> wraps a pointer from C side. The validity +// of the pointer is confirmed at the creation of Opaque<>. +unsafe { &*self.0 .as_ptr () } + } +} + +impl AddressSpace { +/// Helper function to get the [`FlatView`] of the current [`AddressSpace`] +/// without reference count protection. +/// +/// # Safety +/// +/// The caller must ensure that the returned reference is protected by +/// reference count. +unsafe fn get_flatview <'g>(&self, rcu: &'gRcuGuard ) -> &'gFlatView { +// SAFETY: `current_map` is an RCU-protected pointer field and any change is +// protected by the RCU mechanism. +let cell =unsafe {RcuCell ::from_ptr (std::ptr::addr_of!(self.deref ().current_map)) }; +// SAFETY: the pointer is valid and not NULL. +unsafe {FlatView ::from_raw (std::ptr::from_ref (cell.get (rcu).unwrap ()).cast_mut ()) } + } + +/// The write interface of `AddressSpace`. +/// +/// This function is similar to `address_space_write` on the C side. +/// +/// But it assumes the memory attributes is `MEMTXATTRS_UNSPECIFIED`. +/// +/// # Examples +/// +/// ``` +/// use system::memory::{GuestAddress, ADDRESS_SPACE_MEMORY}; +/// +/// let addr = GuestAddress(0x123123000); +/// let buf = [0x1, 0x2, 0x3, 0x4]; +/// assert!(ADDRESS_SPACE_MEMORY.write(&buf, addr).is_ok()); +/// ``` +pub fn write (&self, buf: &[u8 ], addr:GuestAddress ) ->Result <usize > { +Ok (Bytes ::write ( + &*self.memory (), + buf, + (addr,MEMTXATTRS_UNSPECIFIED ), + )?) + } + +/// The read interface of `AddressSpace`. +/// +/// This function is similar to `address_space_read_full` on the C side. +/// +/// But it assumes the memory attributes is `MEMTXATTRS_UNSPECIFIED`. +/// +/// Note: this function does not support the fast path like +/// `address_space_read` on the C side. +/// +/// # Examples +/// +/// ``` +/// use system::memory::{GuestAddress, ADDRESS_SPACE_MEMORY}; +/// +/// let addr = GuestAddress(0x123123000); +/// let mut buf = [0u8; 4]; +/// assert!(ADDRESS_SPACE_MEMORY.read(&mut buf, addr).is_ok()); +/// ``` +pub fn read (&self, buf: &mut [u8 ], addr:GuestAddress ) ->Result <usize > { +Ok (Bytes ::read ( + &*self.memory (), + buf, + (addr,MEMTXATTRS_UNSPECIFIED ), + )?) + } + +/// The store interface of `AddressSpace`. +/// +/// This function is similar to `address_space_st{size}_{endian}` on the C +/// side. +/// +/// The endianness of the access is carried by the value's type, which must +/// implement [`EndianValued`]: pass an explicit-endian type such as +/// `Le32`/`Be32` (or a single-byte `u8`/`i8`). +/// +/// And it assumes the memory attributes is `MEMTXATTRS_UNSPECIFIED`. +/// +/// # Examples +/// +/// ``` +/// use system::memory::{GuestAddress, Le32, ADDRESS_SPACE_MEMORY}; +/// +/// let addr = GuestAddress(0x123123000); +/// assert!(ADDRESS_SPACE_MEMORY.store(addr, Le32::from(5)).is_ok()); +/// ``` +pub fn store <T :EndianValued >(&self, addr:GuestAddress , val:T ) ->Result <()> { +// the `Ordering::Relaxed` will be ignored: QEMU's path is not +// Rust-atomic. +Ok (Bytes ::store ( + &*self.memory (), + val.to_carrier (), + (addr,MEMTXATTRS_UNSPECIFIED ), +Ordering ::Relaxed , + )?) + } + +/// The load interface of `AddressSpace`. +/// +/// This function is similar to `address_space_ld{size}_{endian}` on the C +/// side. +/// +/// The endianness of the access is carried by the requested type, which +/// must implement [`EndianValued`]: ask for an explicit-endian type such +/// as `Le32`/`Be32` (or a single-byte `u8`/`i8`). +/// +/// And it assumes the memory attributes is `MEMTXATTRS_UNSPECIFIED`. +/// +/// # Examples +/// +/// ``` +/// use system::memory::{GuestAddress, Le32, ADDRESS_SPACE_MEMORY}; +/// +/// let addr = GuestAddress(0x123123000); +/// assert!(ADDRESS_SPACE_MEMORY.load::<Le32>(addr).is_ok()); +/// ``` +pub fn load <T :EndianValued >(&self, addr:GuestAddress ) ->Result <T > { +// the `Ordering::Relaxed` will be ignored: QEMU's path is not +// Rust-atomic. +let carrier:T ::Carrier =Bytes ::load ( + &*self.memory (), + (addr,MEMTXATTRS_UNSPECIFIED ), +Ordering ::Relaxed , + )?; +Ok (T ::from_carrier (carrier)) + } +} + +/// 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 on the C side during +// the whole QEMU life. + &*wrapper_ptr +};
Signature · 1 line
2.34.1
RFC v2 24/26 rust/hpet: Use safe binding to access address space
In reply to Zhao LiuCurrently, HPET uses unsafe address_space_stl_le() to store MSI message.
Therefore, use the safe binding - AddressSpace::store() with Le32, to access address space.
Since then, the last unsafe piece of HPET has been filled in.
---
Changes since v1:
* Explicitly specify endianness by Le32 and get rid of native endianness.
* Drop expect() method to avoid abort() on error - consistent with the behavior on the C side.
--- rust/hw/timer/hpet/src/device.rs | 29 ++++++----------------------- 1 file changed, 6 insertions(+), 23 deletions(-)
rust/hw/timer/hpet/src/device.rs +6 -23
@@ -2,24 +2,14 @@// Author(s): Zhao Liu <[email protected]> // SPDX-License-Identifier: GPL-2.0-or-later -use std::{ - ffi::CStr , - mem::MaybeUninit , - pin::Pin , - ptr::{addr_of_mut, null_mut,NonNull }, - slice::from_ref, -}; +use std::{ffi::CStr , mem::MaybeUninit , pin::Pin , ptr::NonNull , slice::from_ref};use bql::prelude::*;use common::prelude::*;use hwcore::prelude::*;use migration::{self, prelude::*,ToMigrationStateShared };use qom::prelude::*; -use system::{ - bindings::{address_space_memory, address_space_stl_le}, - prelude::*, -MEMTXATTRS_UNSPECIFIED , -}; +use system::{prelude::*,GuestAddress ,Le32 ,ADDRESS_SPACE_MEMORY };use util::prelude::*;use crate ::fw_cfg::HPETFwConfig ;
@@ -327,17 +317,10 @@ fn set_irq(&self, regs: &HPETRegisters, set: bool) {if set && tn_regs.is_int_enabled () && regs.is_hpet_enabled () {if tn_regs.is_fsb_route_enabled () { -// SAFETY: -// the parameters are valid. -unsafe { -address_space_stl_le ( -addr_of_mut! (address_space_memory), - tn_regs.fsb >>32 ,// Timer N FSB int addr - tn_regs.fsbas u32 ,// Timer N FSB int value, truncate! -MEMTXATTRS_UNSPECIFIED , -null_mut (), - ); - } +let _ =ADDRESS_SPACE_MEMORY .store ( +GuestAddress (tn_regs.fsb >>32 ),// Timer N FSB int addr +Le32 ::from (tn_regs.fsbas u32 ),// Timer N FSB int value, truncate! + ); }else if tn_regs.is_int_level_triggered () { self.get_state ().irqs[route].raise (); }else {
Signature · 1 line
2.34.1
RFC v2 25/26 hw/timer/hpet: Add HPET_TN_BASE macro
In reply to Zhao LiuUse the HPET_TN_BASE macro instead of a hardcoded value to support next HPET test case.
---
Changes since v1:
* New commit.
--- hw/timer/hpet.c | 8 ++++---- include/hw/timer/hpet.h | 1 + 2 files changed, 5 insertions(+), 4 deletions(-)
hw/timer/hpet.c +4 -4
@@ -450,7 +450,7 @@ static uint64_t hpet_ram_read(void *opaque, hwaddr addr,QEMU_LOCK_GUARD (&s->lock);/*address range of all global regs*/ -if (addr <=0xff ) { +if (addr <HPET_TN_BASE ) {switch (addr) {case HPET_ID :// including HPET_PERIOD return s->capability >> shift;
@@ -463,7 +463,7 @@ static uint64_t hpet_ram_read(void *opaque, hwaddr addr,break ; } }else { -uint8_t timer_id = (addr -0x100 ) /0x20 ; +uint8_t timer_id = (addr -HPET_TN_BASE ) /0x20 ;HPETTimer *timer;if (timer_id >= s->num_timers) {
@@ -501,7 +501,7 @@ static void hpet_ram_write(void *opaque, hwaddr addr, addr &= ~4 ;/*address range of all global regs*/ -if (addr <=0xff ) { +if (addr <HPET_TN_BASE ) {switch (addr) {case HPET_ID :return ;
@@ -564,7 +564,7 @@ static void hpet_ram_write(void *opaque, hwaddr addr,break ; } }else { -uint8_t timer_id = (addr -0x100 ) /0x20 ; +uint8_t timer_id = (addr -HPET_TN_BASE ) /0x20 ;HPETTimer *timer;trace_hpet_ram_write_timer_id (timer_id);
include/hw/timer/hpet.h +1 -0
@@ -37,6 +37,7 @@#define HPET_CFG 0x010#define HPET_STATUS 0x020#define HPET_COUNTER 0x0f0 +#define HPET_TN_BASE 0x100#define HPET_TN_CFG 0x000#define HPET_TN_CMP 0x008#define HPET_TN_ROUTE 0x010
Signature · 1 line
2.34.1
RFC v2 26/26 tests/qtest: Add HPET test case to verify FSB store
In reply to Zhao LiuAdd an HPET qtest case to exercise the FSB interrupt delivery path. This verifies the memory store logic for both the C and Rust implementations.
---
Changes since v1:
* New commit.
--- tests/qtest/hpet-test.c | 77 +++++++++++++++++++++++++++++++++++++++++ tests/qtest/meson.build | 1 + 2 files changed, 78 insertions(+) create mode 100644 tests/qtest/hpet-test.c
tests/qtest/hpet-test.c new file +77 -0
@@ -0,0 +1,77 @@ +/* +* QTest testcase for the HPET +* +* Copyright (C) 2026 Intel Corporation. +* +* Authors: +* Zhao Liu <[email protected]> +* +* SPDX-License-Identifier: GPL-2.0-or-later +*/ + +#include "qemu/osdep.h" +#include "libqtest.h" +#include "qemu/timer.h" +#include "hw/timer/hpet.h" + +#define HPET_TN_BASE_ADDR (n) (HPET_TN_BASE + (n) * 0x20) +#define HPET_TN_CFG_ADDR (n) (HPET_TN_BASE_ADDR(n) + HPET_TN_CFG) +#define HPET_TN_CMP_ADDR (n) (HPET_TN_BASE_ADDR(n) + HPET_TN_CMP) +#define HPET_TN_FSB_ADDR (n) (HPET_TN_BASE_ADDR(n) + HPET_TN_ROUTE) + +/* +* Normally, the MSI should be written to the Local APIC address space. +* However, since the goal for current MSI testing is to verify +* memory store and load, use a RAM for simplicity. +*/ +#define MSI_TARGET_ADDR 0x100000 +#define MSI_DATA 0x19680718U + +static void test_hpet_fsb_store (void ) +{ +QTestState *s; +uint32_t got; +uint64_t tn_cfg; + + s =qtest_init ("-machine pc,hpet=on -global hpet.msi=on" ); + +qtest_writel (s,MSI_TARGET_ADDR ,0 ); + g_assert_cmphex(qtest_readl(s, MSI_TARGET_ADDR), ==, 0); + +/* Ensure HPET (timer 0) supports FSB first. */ + tn_cfg =qtest_readq (s,HPET_BASE +HPET_TN_CFG_ADDR (0 )); +g_assert (tn_cfg &HPET_TN_FSB_CAP ); + +/* Configure FSB for timer 0. */ +qtest_writeq (s,HPET_BASE +HPET_TN_FSB_ADDR (0 ), + ((uint64_t )MSI_TARGET_ADDR <<32 ) |MSI_DATA ); + +/* Enable the timer 0's interrupt and FSB (non-periodic mode). */ +qtest_writeq (s,HPET_BASE +HPET_TN_CFG_ADDR (0 ), + tn_cfg |HPET_TN_ENABLE |HPET_TN_FSB_ENABLE ); + +/* +* Expire time: 0x100 = 256 ticks. +* Considering HPET_CLK_PERIOD, it's 2560 ns. +*/ +qtest_writeq (s,HPET_BASE +HPET_TN_CMP_ADDR (0 ),0x100 ); + +/* Start main counter to run - arm the timer 0. */ +qtest_writeq (s,HPET_BASE +HPET_CFG ,HPET_CFG_ENABLE ); + +/* Advance 10000 ns, which is enough for timer 0 to expire. */ +qtest_clock_step (s,10000 ); + +/* The 32-bit data must now be in guest RAM now, little-endian. */ + got =qtest_readl (s,MSI_TARGET_ADDR ); + g_assert_cmphex(got, ==, MSI_DATA); + +qtest_quit (s); +} + +int main (int argc,char **argv) +{ +g_test_init (&argc, &argv,NULL ); +qtest_add_func ("/hpet/fsb-store" , test_hpet_fsb_store); +return g_test_run (); +}
tests/qtest/meson.build +1 -0
@@ -111,6 +111,7 @@ qtests_i386 = \ config_all_devices.has_key('CONFIG_PARALLEL') ? ['bios-tables-test'] : []) + \ qtests_pci + \ qtests_cxl + \ + (config_all_devices.has_key('CONFIG_HPET') ? ['hpet-test'] : []) + \ [ 'hd-geo-test', 'boot-order-test',
Signature · 1 line
2.34.1