blob: 3186409e092eb595cd9e9439e4b0261cb456a4aa [file] [log] [blame]
Alice Wangf47b2342023-06-02 11:51:57 +00001// 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
Alice Wangeacb7382023-06-05 12:53:54 +000017use crate::util::unchecked_align_down;
Alice Wangf47b2342023-06-02 11:51:57 +000018use core::ptr::NonNull;
19
Alice Wangeacb7382023-06-05 12:53:54 +000020/// The size of a 4KB memory in bytes.
21pub const SIZE_4KB: usize = 4 << 10;
22/// The size of a 2MB memory in bytes.
23pub const SIZE_2MB: usize = 2 << 20;
24/// The size of a 4MB memory in bytes.
25pub const SIZE_4MB: usize = 4 << 20;
26
27/// Computes the address of the 4KiB page containing a given address.
28pub const fn page_4kb_of(addr: usize) -> usize {
29 unchecked_align_down(addr, SIZE_4KB)
30}
31
Alice Wangf47b2342023-06-02 11:51:57 +000032/// Returns the intermediate physical address corresponding to the given virtual address.
33///
34/// As we use identity mapping for everything, this is just a cast, but it's useful to use it to be
35/// explicit about where we are converting from virtual to physical address.
36pub fn virt_to_phys(vaddr: NonNull<u8>) -> usize {
37 vaddr.as_ptr() as _
38}
39
40/// Returns a pointer for the virtual address corresponding to the given non-zero intermediate
41/// physical address.
42///
43/// Panics if `paddr` is 0.
44pub fn phys_to_virt(paddr: usize) -> NonNull<u8> {
45 NonNull::new(paddr as _).unwrap()
46}