1 // Copyright 2023, 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 //! Utility functions for memory management.
16
17 use crate::arch::flush_region;
18 use crate::util::unchecked_align_down;
19 use core::ptr::NonNull;
20 use zeroize::Zeroize;
21
22 /// The size of a 4KB memory in bytes.
23 pub const SIZE_4KB: usize = 4 << 10;
24 /// The size of a 16KB memory in bytes.
25 pub const SIZE_16KB: usize = 16 << 10;
26 /// The size of a 64KB memory in bytes.
27 pub const SIZE_64KB: usize = 64 << 10;
28 /// The size of a 128KB memory in bytes.
29 pub const SIZE_128KB: usize = 128 << 10;
30 /// The size of a 2MB memory in bytes.
31 pub const SIZE_2MB: usize = 2 << 20;
32 /// The size of a 4MB memory in bytes.
33 pub const SIZE_4MB: usize = 4 << 20;
34
35 /// The page size in bytes assumed by vmbase - 4 KiB.
36 pub const PAGE_SIZE: usize = SIZE_4KB;
37
38 /// Flushes the slice to the point of unification.
39 #[inline]
flush(reg: &[u8])40 pub fn flush(reg: &[u8]) {
41 flush_region(reg.as_ptr() as usize, reg.len())
42 }
43
44 /// Overwrites the slice with zeroes, to the point of unification.
45 #[inline]
flushed_zeroize(reg: &mut [u8])46 pub fn flushed_zeroize(reg: &mut [u8]) {
47 reg.zeroize();
48 flush(reg)
49 }
50
51 /// Computes the address of the 4KiB page containing a given address.
page_4kb_of(addr: usize) -> usize52 pub const fn page_4kb_of(addr: usize) -> usize {
53 unchecked_align_down(addr, SIZE_4KB)
54 }
55
56 /// Returns the intermediate physical address corresponding to the given virtual address.
57 ///
58 /// As we use identity mapping for everything, this is just a cast, but it's useful to use it to be
59 /// explicit about where we are converting from virtual to physical address.
virt_to_phys(vaddr: NonNull<u8>) -> usize60 pub(crate) fn virt_to_phys(vaddr: NonNull<u8>) -> usize {
61 vaddr.as_ptr() as _
62 }
63
64 /// Returns a pointer for the virtual address corresponding to the given non-zero intermediate
65 /// physical address.
66 ///
67 /// Panics if `paddr` is 0.
phys_to_virt(paddr: usize) -> NonNull<u8>68 pub(crate) fn phys_to_virt(paddr: usize) -> NonNull<u8> {
69 NonNull::new(paddr as _).unwrap()
70 }
71