[pvmfw] Move memory flush functions to vmbase
To facilitate reusing the memory management code in rialto later.
Bug: 284462758
Test: m pvmfw_img
Change-Id: I9a544c783ff322d4894f0b3d7e10c0643908d48f
diff --git a/vmbase/src/memory/util.rs b/vmbase/src/memory/util.rs
index 3186409..3739d28 100644
--- a/vmbase/src/memory/util.rs
+++ b/vmbase/src/memory/util.rs
@@ -14,8 +14,11 @@
//! Utility functions for memory management.
+use crate::read_sysreg;
use crate::util::unchecked_align_down;
+use core::arch::asm;
use core::ptr::NonNull;
+use zeroize::Zeroize;
/// The size of a 4KB memory in bytes.
pub const SIZE_4KB: usize = 4 << 10;
@@ -24,6 +27,51 @@
/// The size of a 4MB memory in bytes.
pub const SIZE_4MB: usize = 4 << 20;
+/// Reads the number of words in the smallest cache line of all the data caches and unified caches.
+#[inline]
+pub fn min_dcache_line_size() -> usize {
+ const DMINLINE_SHIFT: usize = 16;
+ const DMINLINE_MASK: usize = 0xf;
+ let ctr_el0 = read_sysreg!("ctr_el0");
+
+ // DminLine: log2 of the number of words in the smallest cache line of all the data caches.
+ let dminline = (ctr_el0 >> DMINLINE_SHIFT) & DMINLINE_MASK;
+
+ 1 << dminline
+}
+
+/// Flush `size` bytes of data cache by virtual address.
+#[inline]
+pub(super) fn flush_region(start: usize, size: usize) {
+ let line_size = min_dcache_line_size();
+ let end = start + size;
+ let start = unchecked_align_down(start, line_size);
+
+ for line in (start..end).step_by(line_size) {
+ // SAFETY - Clearing cache lines shouldn't have Rust-visible side effects.
+ unsafe {
+ asm!(
+ "dc cvau, {x}",
+ x = in(reg) line,
+ options(nomem, nostack, preserves_flags),
+ )
+ }
+ }
+}
+
+/// Flushes the slice to the point of unification.
+#[inline]
+pub fn flush(reg: &[u8]) {
+ flush_region(reg.as_ptr() as usize, reg.len())
+}
+
+/// Overwrites the slice with zeroes, to the point of unification.
+#[inline]
+pub fn flushed_zeroize(reg: &mut [u8]) {
+ reg.zeroize();
+ flush(reg)
+}
+
/// Computes the address of the 4KiB page containing a given address.
pub const fn page_4kb_of(addr: usize) -> usize {
unchecked_align_down(addr, SIZE_4KB)