Skip to main content

hyperlight_guest/arch/amd64/
prim_alloc.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2025 The Hyperlight Authors.
3
4use hyperlight_common::flatbuffer_wrappers::guest_error::ErrorCode;
5
6// There are no notable architecture-specific safety considerations
7// here, and the general conditions are documented in the
8// architecture-independent re-export in prim_alloc.rs
9#[allow(clippy::missing_safety_doc)]
10pub unsafe fn alloc_phys_pages(n: u64) -> u64 {
11    let addr = crate::layout::allocator_gva();
12    let nbytes = n * hyperlight_common::vmem::PAGE_SIZE as u64;
13    let mut x = nbytes;
14    unsafe {
15        core::arch::asm!(
16            "lock xadd qword ptr [{addr}], {x}",
17            addr = in(reg) addr,
18            x = inout(reg) x
19        );
20    }
21    // Set aside two pages at the top of the scratch region for the
22    // exception stack, shared state, etc
23    let max_avail =
24        hyperlight_common::layout::SCRATCH_TOP_GPA - hyperlight_common::vmem::PAGE_SIZE * 2;
25    if x.checked_add(nbytes)
26        .is_none_or(|xx| xx >= max_avail as u64)
27    {
28        unsafe {
29            crate::exit::abort_with_code_and_message(
30                &[ErrorCode::MallocFailed as u8],
31                c"Out of physical memory".as_ptr(),
32            )
33        }
34    }
35    x
36}