blob: dcfd99cd5cc1a433eee47c25aaddf7a42c423b8a [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;
Alice Wang81399f52023-05-26 14:23:43 +000019use vmbase::read_sysreg;
Pierre-Clément Tosi8383c542022-11-01 14:07:29 +000020use zeroize::Zeroize;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000021
Pierre-Clément Tosif0f9b8b2022-10-19 10:12:49 +010022pub const SIZE_4KB: usize = 4 << 10;
Pierre-Clément Tosia1d3ea32022-11-01 15:05:11 +000023pub const SIZE_2MB: usize = 2 << 20;
Pierre-Clément Tosi164a6f52023-04-18 19:29:11 +010024pub const SIZE_4MB: usize = 4 << 20;
Pierre-Clément Tosif0f9b8b2022-10-19 10:12:49 +010025
Pierre-Clément Tosi4f4f5eb2022-12-08 14:31:42 +000026pub const GUEST_PAGE_SIZE: usize = SIZE_4KB;
Pierre-Clément Tosi23aba522023-04-21 17:03:50 +010027pub const PVMFW_PAGE_SIZE: usize = SIZE_4KB;
Pierre-Clément Tosi4f4f5eb2022-12-08 14:31:42 +000028
Pierre-Clément Tosie8726e42022-10-17 13:35:27 +010029/// Computes the largest multiple of the provided alignment smaller or equal to the address.
30///
31/// Note: the result is undefined if alignment isn't a power of two.
32pub const fn unchecked_align_down(addr: usize, alignment: usize) -> usize {
33 addr & !(alignment - 1)
34}
35
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010036/// Computes the smallest multiple of the provided alignment larger or equal to the address.
37///
38/// Note: the result is undefined if alignment isn't a power of two and may wrap to 0.
39pub const fn unchecked_align_up(addr: usize, alignment: usize) -> usize {
40 unchecked_align_down(addr + alignment - 1, alignment)
41}
42
Pierre-Clément Tosie8726e42022-10-17 13:35:27 +010043/// Safe wrapper around unchecked_align_up() that validates its assumptions and doesn't wrap.
44pub const fn align_up(addr: usize, alignment: usize) -> Option<usize> {
45 if !alignment.is_power_of_two() {
46 None
47 } else if let Some(s) = addr.checked_add(alignment - 1) {
48 Some(unchecked_align_down(s, alignment))
49 } else {
50 None
51 }
Pierre-Clément Tosida4440a2022-08-22 18:06:32 +010052}
53
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +000054/// Performs an integer division rounding up.
55///
56/// Note: Returns None if den isn't a power of two.
57pub const fn ceiling_div(num: usize, den: usize) -> Option<usize> {
58 let Some(r) = align_up(num, den) else {
59 return None;
60 };
61
62 r.checked_div(den)
63}
64
Andrew Walbran41ebe932022-12-14 15:22:30 +000065/// Aligns the given address to the given alignment, if it is a power of two.
66///
67/// Returns `None` if the alignment isn't a power of two.
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +000068#[allow(dead_code)] // Currently unused but might be needed again.
Andrew Walbran41ebe932022-12-14 15:22:30 +000069pub const fn align_down(addr: usize, alignment: usize) -> Option<usize> {
70 if !alignment.is_power_of_two() {
71 None
72 } else {
73 Some(unchecked_align_down(addr, alignment))
74 }
75}
76
Pierre-Clément Tosida4440a2022-08-22 18:06:32 +010077/// Computes the address of the 4KiB page containing a given address.
Pierre-Clément Tosi446136e2022-10-19 10:10:42 +010078pub const fn page_4kb_of(addr: usize) -> usize {
Pierre-Clément Tosie8726e42022-10-17 13:35:27 +010079 unchecked_align_down(addr, SIZE_4KB)
Pierre-Clément Tosida4440a2022-08-22 18:06:32 +010080}
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000081
82#[inline]
Pierre-Clément Tosi97f52492023-04-04 15:52:17 +010083/// Read the number of words in the smallest cache line of all the data caches and unified caches.
84pub fn min_dcache_line_size() -> usize {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000085 const DMINLINE_SHIFT: usize = 16;
86 const DMINLINE_MASK: usize = 0xf;
Jakob Vukalovicc9afb512023-03-30 16:04:32 +000087 let ctr_el0 = read_sysreg!("ctr_el0");
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000088
89 // DminLine: log2 of the number of words in the smallest cache line of all the data caches.
90 let dminline = (ctr_el0 >> DMINLINE_SHIFT) & DMINLINE_MASK;
91
92 1 << dminline
93}
94
Pierre-Clément Tosi2ca2e312022-11-29 11:24:52 +000095/// Flush `size` bytes of data cache by virtual address.
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000096#[inline]
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000097pub fn flush_region(start: usize, size: usize) {
98 let line_size = min_dcache_line_size();
99 let end = start + size;
100 let start = unchecked_align_down(start, line_size);
101
102 for line in (start..end).step_by(line_size) {
103 // SAFETY - Clearing cache lines shouldn't have Rust-visible side effects.
Pierre-Clément Tosi7d6944f2023-03-30 19:14:11 +0100104 unsafe {
105 asm!(
106 "dc cvau, {x}",
107 x = in(reg) line,
108 options(nomem, nostack, preserves_flags),
109 )
110 }
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000111 }
112}
Pierre-Clément Tosi8383c542022-11-01 14:07:29 +0000113
114#[inline]
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000115/// Flushes the slice to the point of unification.
116pub fn flush(reg: &[u8]) {
117 flush_region(reg.as_ptr() as usize, reg.len())
118}
119
120#[inline]
Pierre-Clément Tosi8383c542022-11-01 14:07:29 +0000121/// Overwrites the slice with zeroes, to the point of unification.
122pub fn flushed_zeroize(reg: &mut [u8]) {
123 reg.zeroize();
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000124 flush(reg)
Pierre-Clément Tosi8383c542022-11-01 14:07:29 +0000125}
Jiyong Parkb87f3302023-03-21 10:03:11 +0900126
Jiyong Park9c63cd12023-03-21 17:53:07 +0900127/// Flatten [[T; N]] into &[T]
128/// TODO: use slice::flatten when it graduates from experimental
129pub fn flatten<T, const N: usize>(original: &[[T; N]]) -> &[T] {
130 // SAFETY: no overflow because original (whose size is len()*N) is already in memory
131 let len = original.len() * N;
132 // SAFETY: [T] has the same layout as [T;N]
133 unsafe { core::slice::from_raw_parts(original.as_ptr().cast(), len) }
134}
135
Srivatsa Vaddagiric25d68e2023-04-19 22:56:33 -0700136/// Trait to check containment of one range within another.
137pub(crate) trait RangeExt {
138 /// Returns true if `self` is contained within the `other` range.
139 fn is_within(&self, other: &Self) -> bool;
140}
141
142impl<T: PartialOrd> RangeExt for Range<T> {
143 fn is_within(&self, other: &Self) -> bool {
144 self.start >= other.start && self.end <= other.end
145 }
146}
147
Jiyong Parkb87f3302023-03-21 10:03:11 +0900148/// Create &CStr out of &str literal
149#[macro_export]
150macro_rules! cstr {
151 ($str:literal) => {{
Pierre-Clément Tosi7c5df042023-05-12 12:06:44 +0000152 core::ffi::CStr::from_bytes_with_nul(concat!($str, "\0").as_bytes()).unwrap()
Jiyong Parkb87f3302023-03-21 10:03:11 +0900153 }};
154}