diff --git a/vm-allocator/src/lib.rs b/vm-allocator/src/lib.rs index f7bf5ff22..989ec9b38 100644 --- a/vm-allocator/src/lib.rs +++ b/vm-allocator/src/lib.rs @@ -12,6 +12,8 @@ mod address; mod gsi; +/// page size related utility funtions +pub mod page_size; mod system; pub use crate::address::AddressAllocator; diff --git a/vm-allocator/src/page_size.rs b/vm-allocator/src/page_size.rs new file mode 100644 index 000000000..96ae01edf --- /dev/null +++ b/vm-allocator/src/page_size.rs @@ -0,0 +1,38 @@ +// Copyright 2023 Arm Limited (or its affiliates). All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use libc::{sysconf, _SC_PAGESIZE}; + +/// get host page size +pub fn get_page_size() -> u64 { + // SAFETY: FFI call. Trivially safe. + unsafe { sysconf(_SC_PAGESIZE) as u64 } +} + +/// round up address to let it align page size +pub fn align_page_size_up(address: u64) -> u64 { + let page_size = get_page_size(); + (address + page_size - 1) & !(page_size - 1) +} + +/// round down address to let it align page size +pub fn align_page_size_down(address: u64) -> u64 { + let page_size = get_page_size(); + address & !(page_size - 1) +} + +/// Test if address is 4k aligned +pub fn is_4k_aligned(address: u64) -> bool { + (address & 0xfff) == 0 +} + +/// Test if size is 4k aligned +pub fn is_4k_multiple(size: u64) -> bool { + (size & 0xfff) == 0 +} + +/// Test if address is page size aligned +pub fn is_page_size_aligned(address: u64) -> bool { + let page_size = get_page_size(); + address & (page_size - 1) == 0 +} diff --git a/vm-allocator/src/system.rs b/vm-allocator/src/system.rs index afc4c7e10..3f98a1063 100644 --- a/vm-allocator/src/system.rs +++ b/vm-allocator/src/system.rs @@ -14,14 +14,7 @@ use crate::gsi::GsiAllocator; #[cfg(target_arch = "x86_64")] use crate::gsi::GsiApic; -use libc::{sysconf, _SC_PAGESIZE}; - -/// Safe wrapper for `sysconf(_SC_PAGESIZE)`. -#[inline(always)] -fn pagesize() -> usize { - // SAFETY: FFI call. Trivially safe. - unsafe { sysconf(_SC_PAGESIZE) as usize } -} +use crate::page_size::get_page_size; /// Manages allocating system resources such as address space and interrupt numbers. /// @@ -126,7 +119,7 @@ impl SystemAllocator { self.platform_mmio_address_space.allocate( address, size, - Some(align_size.unwrap_or(pagesize() as u64)), + Some(align_size.unwrap_or(get_page_size())), ) } @@ -140,7 +133,7 @@ impl SystemAllocator { self.mmio_hole_address_space.allocate( address, size, - Some(align_size.unwrap_or(pagesize() as u64)), + Some(align_size.unwrap_or(get_page_size())), ) }