blob: 9c4cb1b28cf37303a27dda5d597131cc767f0346 [file] [log] [blame]
Pierre-Clément Tosida4440a2022-08-22 18:06:32 +01001// Copyright 2022, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Miscellaneous helper functions.
16
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000017use core::arch::asm;
Srivatsa Vaddagiric25d68e2023-04-19 22:56:33 -070018use core::ops::Range;
Pierre-Clément Tosi8383c542022-11-01 14:07:29 +000019use zeroize::Zeroize;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000020
Pierre-Clément Tosif0f9b8b2022-10-19 10:12:49 +010021pub const SIZE_4KB: usize = 4 << 10;
Pierre-Clément Tosia1d3ea32022-11-01 15:05:11 +000022pub const SIZE_2MB: usize = 2 << 20;
Pierre-Clément Tosi164a6f52023-04-18 19:29:11 +010023pub const SIZE_4MB: usize = 4 << 20;
Pierre-Clément Tosif0f9b8b2022-10-19 10:12:49 +010024
Pierre-Clément Tosi4f4f5eb2022-12-08 14:31:42 +000025pub const GUEST_PAGE_SIZE: usize = SIZE_4KB;
Pierre-Clément Tosi23aba522023-04-21 17:03:50 +010026pub const PVMFW_PAGE_SIZE: usize = SIZE_4KB;
Pierre-Clément Tosi4f4f5eb2022-12-08 14:31:42 +000027
Jakob Vukalovicc9afb512023-03-30 16:04:32 +000028/// Read a value from a system register.
29#[macro_export]
30macro_rules! read_sysreg {
31 ($sysreg:literal) => {{
32 let mut r: usize;
33 // Safe because it reads a system register and does not affect Rust.
Pierre-Clément Tosib7557742023-05-15 17:35:59 +000034 #[allow(unused_unsafe)] // In case the macro is used within an unsafe block.
Jakob Vukalovicc9afb512023-03-30 16:04:32 +000035 unsafe {
36 core::arch::asm!(
37 concat!("mrs {}, ", $sysreg),
38 out(reg) r,
39 options(nomem, nostack, preserves_flags),
40 )
41 }
42 r
43 }};
44}
45
46/// Write a value to a system register.
Pierre-Clément Tosi2aedaae2023-04-14 15:01:47 +010047///
48/// # Safety
49///
50/// Callers must ensure that side effects of updating the system register are properly handled.
Jakob Vukalovicc9afb512023-03-30 16:04:32 +000051#[macro_export]
52macro_rules! write_sysreg {
53 ($sysreg:literal, $val:expr) => {{
54 let value: usize = $val;
Pierre-Clément Tosi2aedaae2023-04-14 15:01:47 +010055 core::arch::asm!(
56 concat!("msr ", $sysreg, ", {}"),
57 in(reg) value,
58 options(nomem, nostack, preserves_flags),
59 )
Jakob Vukalovicc9afb512023-03-30 16:04:32 +000060 }};
61}
62
Pierre-Clément Tosie8726e42022-10-17 13:35:27 +010063/// Computes the largest multiple of the provided alignment smaller or equal to the address.
64///
65/// Note: the result is undefined if alignment isn't a power of two.
66pub const fn unchecked_align_down(addr: usize, alignment: usize) -> usize {
67 addr & !(alignment - 1)
68}
69
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010070/// Computes the smallest multiple of the provided alignment larger or equal to the address.
71///
72/// Note: the result is undefined if alignment isn't a power of two and may wrap to 0.
73pub const fn unchecked_align_up(addr: usize, alignment: usize) -> usize {
74 unchecked_align_down(addr + alignment - 1, alignment)
75}
76
Pierre-Clément Tosie8726e42022-10-17 13:35:27 +010077/// Safe wrapper around unchecked_align_up() that validates its assumptions and doesn't wrap.
78pub const fn align_up(addr: usize, alignment: usize) -> Option<usize> {
79 if !alignment.is_power_of_two() {
80 None
81 } else if let Some(s) = addr.checked_add(alignment - 1) {
82 Some(unchecked_align_down(s, alignment))
83 } else {
84 None
85 }
Pierre-Clément Tosida4440a2022-08-22 18:06:32 +010086}
87
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +000088/// Performs an integer division rounding up.
89///
90/// Note: Returns None if den isn't a power of two.
91pub const fn ceiling_div(num: usize, den: usize) -> Option<usize> {
92 let Some(r) = align_up(num, den) else {
93 return None;
94 };
95
96 r.checked_div(den)
97}
98
Andrew Walbran41ebe932022-12-14 15:22:30 +000099/// Aligns the given address to the given alignment, if it is a power of two.
100///
101/// Returns `None` if the alignment isn't a power of two.
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000102#[allow(dead_code)] // Currently unused but might be needed again.
Andrew Walbran41ebe932022-12-14 15:22:30 +0000103pub const fn align_down(addr: usize, alignment: usize) -> Option<usize> {
104 if !alignment.is_power_of_two() {
105 None
106 } else {
107 Some(unchecked_align_down(addr, alignment))
108 }
109}
110
Pierre-Clément Tosida4440a2022-08-22 18:06:32 +0100111/// Computes the address of the 4KiB page containing a given address.
Pierre-Clément Tosi446136e2022-10-19 10:10:42 +0100112pub const fn page_4kb_of(addr: usize) -> usize {
Pierre-Clément Tosie8726e42022-10-17 13:35:27 +0100113 unchecked_align_down(addr, SIZE_4KB)
Pierre-Clément Tosida4440a2022-08-22 18:06:32 +0100114}
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000115
116#[inline]
Pierre-Clément Tosi97f52492023-04-04 15:52:17 +0100117/// Read the number of words in the smallest cache line of all the data caches and unified caches.
118pub fn min_dcache_line_size() -> usize {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000119 const DMINLINE_SHIFT: usize = 16;
120 const DMINLINE_MASK: usize = 0xf;
Jakob Vukalovicc9afb512023-03-30 16:04:32 +0000121 let ctr_el0 = read_sysreg!("ctr_el0");
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000122
123 // DminLine: log2 of the number of words in the smallest cache line of all the data caches.
124 let dminline = (ctr_el0 >> DMINLINE_SHIFT) & DMINLINE_MASK;
125
126 1 << dminline
127}
128
Pierre-Clément Tosi2ca2e312022-11-29 11:24:52 +0000129/// Flush `size` bytes of data cache by virtual address.
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000130#[inline]
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000131pub fn flush_region(start: usize, size: usize) {
132 let line_size = min_dcache_line_size();
133 let end = start + size;
134 let start = unchecked_align_down(start, line_size);
135
136 for line in (start..end).step_by(line_size) {
137 // SAFETY - Clearing cache lines shouldn't have Rust-visible side effects.
Pierre-Clément Tosi7d6944f2023-03-30 19:14:11 +0100138 unsafe {
139 asm!(
140 "dc cvau, {x}",
141 x = in(reg) line,
142 options(nomem, nostack, preserves_flags),
143 )
144 }
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000145 }
146}
Pierre-Clément Tosi8383c542022-11-01 14:07:29 +0000147
148#[inline]
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000149/// Flushes the slice to the point of unification.
150pub fn flush(reg: &[u8]) {
151 flush_region(reg.as_ptr() as usize, reg.len())
152}
153
154#[inline]
Pierre-Clément Tosi8383c542022-11-01 14:07:29 +0000155/// Overwrites the slice with zeroes, to the point of unification.
156pub fn flushed_zeroize(reg: &mut [u8]) {
157 reg.zeroize();
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000158 flush(reg)
Pierre-Clément Tosi8383c542022-11-01 14:07:29 +0000159}
Jiyong Parkb87f3302023-03-21 10:03:11 +0900160
Jiyong Park9c63cd12023-03-21 17:53:07 +0900161/// Flatten [[T; N]] into &[T]
162/// TODO: use slice::flatten when it graduates from experimental
163pub fn flatten<T, const N: usize>(original: &[[T; N]]) -> &[T] {
164 // SAFETY: no overflow because original (whose size is len()*N) is already in memory
165 let len = original.len() * N;
166 // SAFETY: [T] has the same layout as [T;N]
167 unsafe { core::slice::from_raw_parts(original.as_ptr().cast(), len) }
168}
169
Srivatsa Vaddagiric25d68e2023-04-19 22:56:33 -0700170/// Trait to check containment of one range within another.
171pub(crate) trait RangeExt {
172 /// Returns true if `self` is contained within the `other` range.
173 fn is_within(&self, other: &Self) -> bool;
174}
175
176impl<T: PartialOrd> RangeExt for Range<T> {
177 fn is_within(&self, other: &Self) -> bool {
178 self.start >= other.start && self.end <= other.end
179 }
180}
181
Jiyong Parkb87f3302023-03-21 10:03:11 +0900182/// Create &CStr out of &str literal
183#[macro_export]
184macro_rules! cstr {
185 ($str:literal) => {{
Pierre-Clément Tosi7c5df042023-05-12 12:06:44 +0000186 core::ffi::CStr::from_bytes_with_nul(concat!($str, "\0").as_bytes()).unwrap()
Jiyong Parkb87f3302023-03-21 10:03:11 +0900187 }};
188}
Jakob Vukalovic44b1ce32023-04-17 19:10:10 +0100189
Jakob Vukalovic4c1edbe2023-04-17 19:10:57 +0100190/// Returns `true` if hardware dirty state management is available.
191pub fn dbm_available() -> bool {
192 if !cfg!(feature = "cpu_feat_hafdbs") {
193 return false;
194 }
195 // Hardware dirty bit management available flag (ID_AA64MMFR1_EL1.HAFDBS[1])
196 const DBM_AVAILABLE: usize = 1 << 1;
197 read_sysreg!("id_aa64mmfr1_el1") & DBM_AVAILABLE != 0
198}
199
Jakob Vukalovic44b1ce32023-04-17 19:10:10 +0100200/// Executes a data synchronization barrier.
201#[macro_export]
202macro_rules! dsb {
203 ($option:literal) => {{
204 // Safe because this is just a memory barrier and does not affect Rust.
205 #[allow(unused_unsafe)] // In case the macro is used within an unsafe block.
206 unsafe {
207 core::arch::asm!(concat!("dsb ", $option), options(nomem, nostack, preserves_flags));
208 }
209 }};
210}
211
212/// Executes an instruction synchronization barrier.
213#[macro_export]
214macro_rules! isb {
215 () => {{
216 // Safe because this is just a memory barrier and does not affect Rust.
217 #[allow(unused_unsafe)] // In case the macro is used within an unsafe block.
218 unsafe {
219 core::arch::asm!("isb", options(nomem, nostack, preserves_flags));
220 }
221 }};
222}
223
224/// Invalidates cached leaf PTE entries by virtual address.
225#[macro_export]
226macro_rules! tlbi {
227 ($option:literal, $asid:expr, $addr:expr) => {{
228 let asid: usize = $asid;
229 let addr: usize = $addr;
230 // Safe because it invalidates TLB and doesn't affect Rust. When the address matches a
231 // block entry larger than the page size, all translations for the block are invalidated.
232 #[allow(unused_unsafe)] // In case the macro is used within an unsafe block.
233 unsafe {
234 core::arch::asm!(
235 concat!("tlbi ", $option, ", {x}"),
236 x = in(reg) (asid << 48) | (addr >> 12),
237 options(nomem, nostack, preserves_flags)
238 );
239 }
240 }};
241}