Skip to main content

kh_runtime/mem/
layout.rs

1//! Page-size policy used when planning and mapping Mach-O segments.
2//!
3//! Apple Silicon macOS uses 16 KiB pages. Linux aarch64 is often 4 KiB (Colima /
4//! stock Ubuntu) or 16 KiB (Asahi and some server configs). Mapping always uses
5//! host-page multiples; guest alignment defaults to 16 KiB for Darwin arm64.
6
7use thiserror::Error;
8
9/// Default guest page size for arm64 Darwin images (bytes).
10pub const DARWIN_ARM64_PAGE_SIZE: u32 = 16_384;
11
12/// Supported host page sizes we handle explicitly.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
14pub enum HostPageSize {
15    /// Standard Linux aarch64 (and most containers).
16    FourK,
17    /// Asahi Linux and some aarch64 kernels.
18    SixteenK,
19}
20
21impl HostPageSize {
22    /// Size in bytes.
23    #[inline]
24    pub const fn bytes(self) -> u32 {
25        match self {
26            Self::FourK => 4_096,
27            Self::SixteenK => 16_384,
28        }
29    }
30
31    /// Detects the host page size via `libc::sysconf(_SC_PAGESIZE)`.
32    ///
33    /// Returns [`PageError::UnsupportedHostPageSize`] when the value is not
34    /// 4096 or 16384.
35    pub fn detect() -> Result<Self, PageError> {
36        detect_host_page_size()
37    }
38
39    /// Maps a raw byte size to a known host page size.
40    #[inline]
41    pub const fn from_bytes(bytes: u32) -> Option<Self> {
42        match bytes {
43            4_096 => Some(Self::FourK),
44            16_384 => Some(Self::SixteenK),
45            _ => None,
46        }
47    }
48}
49
50/// Guest page size policy for image planning.
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
52pub enum GuestPageSize {
53    /// 16 KiB — default for arm64 Darwin.
54    #[default]
55    Darwin16K,
56    /// Explicit size (must be a power of two, currently 4K or 16K).
57    Explicit(u32),
58}
59
60impl GuestPageSize {
61    /// Size in bytes.
62    #[inline]
63    pub const fn bytes(self) -> u32 {
64        match self {
65            Self::Darwin16K => DARWIN_ARM64_PAGE_SIZE,
66            Self::Explicit(n) => n,
67        }
68    }
69
70    /// Builds an explicit size if it is 4096 or 16384.
71    pub const fn try_explicit(bytes: u32) -> Option<Self> {
72        match bytes {
73            4_096 | 16_384 => Some(Self::Explicit(bytes)),
74            _ => None,
75        }
76    }
77}
78
79/// Combined host + guest geometry for one process session.
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81pub struct PageLayout {
82    /// Detected or configured host page size.
83    pub host: HostPageSize,
84    /// Guest alignment / protection planning size.
85    pub guest: GuestPageSize,
86}
87
88impl PageLayout {
89    /// Creates a layout from host detection and a guest policy.
90    pub fn new(host: HostPageSize, guest: GuestPageSize) -> Self {
91        Self { host, guest }
92    }
93
94    /// Detects host page size and uses the default Darwin guest size.
95    pub fn detect_host_default_guest() -> Result<Self, PageError> {
96        Ok(Self {
97            host: HostPageSize::detect()?,
98            guest: GuestPageSize::default(),
99        })
100    }
101
102    /// Host page size in bytes.
103    #[inline]
104    pub const fn host_bytes(self) -> u32 {
105        self.host.bytes()
106    }
107
108    /// Guest page size in bytes.
109    #[inline]
110    pub const fn guest_bytes(self) -> u32 {
111        self.guest.bytes()
112    }
113
114    /// Rounds `value` up to a multiple of `page`.
115    ///
116    /// Returns `None` if `page` is zero or the result would overflow.
117    #[inline]
118    #[allow(clippy::arithmetic_side_effects)]
119    pub fn align_up(value: u64, page: u32) -> Option<u64> {
120        if page == 0 {
121            return None;
122        }
123        let page_u = u64::from(page);
124        let rem = value % page_u;
125        if rem == 0 {
126            Some(value)
127        } else {
128            value.checked_add(page_u - rem)
129        }
130    }
131
132    /// Rounds `value` down to a multiple of `page`.
133    #[inline]
134    #[allow(clippy::arithmetic_side_effects)]
135    pub fn align_down(value: u64, page: u32) -> Option<u64> {
136        if page == 0 {
137            return None;
138        }
139        let page_u = u64::from(page);
140        Some(value - (value % page_u))
141    }
142
143    /// Number of whole `page`-sized units needed to cover `length` bytes.
144    #[inline]
145    #[allow(clippy::arithmetic_side_effects, clippy::integer_division)]
146    pub fn page_count(length: u64, page: u32) -> Option<u64> {
147        let aligned = Self::align_up(length, page)?;
148        Some(aligned / u64::from(page))
149    }
150
151    /// True if `addr` is aligned to the guest page size.
152    #[inline]
153    pub fn is_guest_aligned(self, addr: u64) -> bool {
154        let page = u64::from(self.guest_bytes());
155        page != 0 && addr.is_multiple_of(page)
156    }
157
158    /// True if `addr` is aligned to the host page size.
159    #[inline]
160    pub fn is_host_aligned(self, addr: u64) -> bool {
161        let page = u64::from(self.host_bytes());
162        page != 0 && addr.is_multiple_of(page)
163    }
164}
165
166/// Errors from page-size detection or validation.
167#[derive(Debug, Error, Clone, PartialEq, Eq)]
168pub enum PageError {
169    /// `sysconf(_SC_PAGESIZE)` failed.
170    #[error("failed to detect host page size")]
171    DetectFailed,
172
173    /// Host page size is not 4 KiB or 16 KiB.
174    #[error("unsupported host page size: {bytes} bytes (expected 4096 or 16384)")]
175    UnsupportedHostPageSize {
176        /// Raw size reported by the host (may not fit in `u32`).
177        bytes: i64,
178    },
179}
180
181/// Queries the OS page size via [`crate::host`].
182fn detect_host_page_size() -> Result<HostPageSize, PageError> {
183    let Some(raw) = crate::host::page_size() else {
184        return Err(PageError::DetectFailed);
185    };
186    let Ok(bytes) = u32::try_from(raw) else {
187        return Err(PageError::UnsupportedHostPageSize {
188            bytes: i64::try_from(raw).unwrap_or(i64::MAX),
189        });
190    };
191    HostPageSize::from_bytes(bytes).ok_or(PageError::UnsupportedHostPageSize {
192        bytes: i64::from(bytes),
193    })
194}
195
196#[cfg(test)]
197#[allow(clippy::expect_used)]
198mod tests {
199    use super::*;
200
201    #[test]
202    fn align_up_down_4k() {
203        assert_eq!(PageLayout::align_up(0, 4096), Some(0));
204        assert_eq!(PageLayout::align_up(1, 4096), Some(4096));
205        assert_eq!(PageLayout::align_up(4096, 4096), Some(4096));
206        assert_eq!(PageLayout::align_up(4097, 4096), Some(8192));
207        assert_eq!(PageLayout::align_down(4097, 4096), Some(4096));
208        assert_eq!(PageLayout::align_down(4096, 4096), Some(4096));
209    }
210
211    #[test]
212    fn align_up_down_16k() {
213        assert_eq!(PageLayout::align_up(1, 16_384), Some(16_384));
214        assert_eq!(PageLayout::align_up(16_384, 16_384), Some(16_384));
215        assert_eq!(PageLayout::align_down(16_385, 16_384), Some(16_384));
216    }
217
218    #[test]
219    fn page_count_covers_partial() {
220        assert_eq!(PageLayout::page_count(0, 4096), Some(0));
221        assert_eq!(PageLayout::page_count(1, 4096), Some(1));
222        assert_eq!(PageLayout::page_count(4096, 4096), Some(1));
223        assert_eq!(PageLayout::page_count(4097, 4096), Some(2));
224        assert_eq!(PageLayout::page_count(16_384, 16_384), Some(1));
225    }
226
227    #[test]
228    fn zero_page_rejected() {
229        assert_eq!(PageLayout::align_up(1, 0), None);
230        assert_eq!(PageLayout::align_down(1, 0), None);
231        assert_eq!(PageLayout::page_count(1, 0), None);
232    }
233
234    #[test]
235    fn host_from_bytes() {
236        assert_eq!(HostPageSize::from_bytes(4096), Some(HostPageSize::FourK));
237        assert_eq!(
238            HostPageSize::from_bytes(16_384),
239            Some(HostPageSize::SixteenK)
240        );
241        assert_eq!(HostPageSize::from_bytes(8192), None);
242    }
243
244    #[test]
245    fn guest_default_is_darwin_16k() {
246        assert_eq!(GuestPageSize::default().bytes(), 16_384);
247    }
248
249    #[test]
250    fn detect_host_succeeds_on_this_machine() {
251        let host = HostPageSize::detect().expect("host page size should be 4K or 16K");
252        assert!(matches!(host, HostPageSize::FourK | HostPageSize::SixteenK));
253        let layout = PageLayout::detect_host_default_guest().expect("layout");
254        assert_eq!(layout.guest_bytes(), 16_384);
255        assert_eq!(layout.host_bytes(), host.bytes());
256    }
257
258    #[test]
259    fn layout_alignment_helpers() {
260        let layout = PageLayout::new(HostPageSize::FourK, GuestPageSize::Darwin16K);
261        assert!(layout.is_guest_aligned(0));
262        assert!(layout.is_guest_aligned(16_384));
263        assert!(!layout.is_guest_aligned(4096));
264        assert!(layout.is_host_aligned(4096));
265        assert!(!layout.is_host_aligned(2048));
266    }
267}