hyperlight_guest/arch/amd64/prim_alloc.rs
1/*
2Copyright 2025 The Hyperlight Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15 */
16
17use hyperlight_common::flatbuffer_wrappers::guest_error::ErrorCode;
18
19// There are no notable architecture-specific safety considerations
20// here, and the general conditions are documented in the
21// architecture-independent re-export in prim_alloc.rs
22#[allow(clippy::missing_safety_doc)]
23pub unsafe fn alloc_phys_pages(n: u64) -> u64 {
24 let addr = crate::layout::allocator_gva();
25 let nbytes = n * hyperlight_common::vmem::PAGE_SIZE as u64;
26 let mut x = nbytes;
27 unsafe {
28 core::arch::asm!(
29 "lock xadd qword ptr [{addr}], {x}",
30 addr = in(reg) addr,
31 x = inout(reg) x
32 );
33 }
34 // Set aside two pages at the top of the scratch region for the
35 // exception stack, shared state, etc
36 let max_avail = hyperlight_common::layout::MAX_GPA - hyperlight_common::vmem::PAGE_SIZE * 2;
37 if x.checked_add(nbytes)
38 .is_none_or(|xx| xx >= max_avail as u64)
39 {
40 unsafe {
41 crate::exit::abort_with_code_and_message(
42 &[ErrorCode::MallocFailed as u8],
43 c"Out of physical memory".as_ptr(),
44 )
45 }
46 }
47 x
48}