hyperlight-common 0.18.0

Hyperlight's components common to host and guest.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
// SPDX-License-Identifier: Apache-2.0
// Copyright 2025 The Hyperlight Authors.

use core::mem::{align_of, offset_of, size_of};
use core::num::{NonZeroU16, NonZeroUsize};

#[cfg_attr(target_arch = "x86_64", path = "arch/amd64/layout.rs")]
#[cfg_attr(target_arch = "aarch64", path = "arch/aarch64/layout.rs")]
mod arch;

pub use arch::{
    SCRATCH_TOP_GPA, SCRATCH_TOP_GVA, SNAPSHOT_PT_GVA_MAX, SNAPSHOT_PT_GVA_MIN,
    VIRTQ_BUFFER_GVA_END, VIRTQ_BUFFER_GVA_START, io_page,
};
#[cfg(target_arch = "aarch64")]
pub use arch::{WHP_GICD_BASE_GPA, WHP_GICR_BASE_GPA, WHP_GITS_TRANSLATOR_BASE_GPA};

use crate::virtq;

const EXN_STACK_ALIGNMENT: usize = 16;
/// Pages reserved for the exception stack and scratch-top metadata.
pub const SCRATCH_TOP_RESERVED_PAGES: usize = 12;

// Fields are listed in ascending-address order. Public offsets are measured
// down from the top of scratch memory.
#[repr(C)]
struct ScratchTopMetadata {
    /// Padding that keeps the exception stack 16-byte aligned.
    _alignment_padding: [u8; 8],
    /// Host-published capacity of each H2G buffer.
    h2g_buffer_size: u64,
    /// Number of pages reserved for the H2G pool.
    h2g_pool_pages: u64,
    /// Host-published H2G descriptor count.
    h2g_queue_size: u64,
    /// Host-published capacity of each G2H upper-tier buffer.
    g2h_buffer_size: u64,
    /// Number of pages reserved for the G2H pool.
    g2h_pool_pages: u64,
    /// Host-published G2H descriptor count.
    g2h_queue_size: u64,
    /// Host-published GPA of the fixed transport arena.
    transport_arena_gpa: u64,
    /// Pending guest log filter update.
    guest_log_level: u64,
    /// Seed request for libc's pseudorandom number generator.
    libc_rng_seed: u64,
    /// Generation of the snapshot backing the sandbox.
    snapshot_generation: u64,
    /// GPA of the snapshot page-table copy in scratch memory.
    snapshot_pt_gpa_base: u64,
    /// Next GPA available to the dynamic scratch allocator.
    allocator: u64,
    /// Size of the scratch region in bytes.
    scratch_size: u64,
}

const fn scratch_top_offset(field_offset: usize) -> u64 {
    (size_of::<ScratchTopMetadata>() - field_offset) as u64
}

pub const SCRATCH_TOP_G2H_QUEUE_SIZE_OFFSET: u64 =
    scratch_top_offset(offset_of!(ScratchTopMetadata, g2h_queue_size));
pub const SCRATCH_TOP_G2H_POOL_PAGES_OFFSET: u64 =
    scratch_top_offset(offset_of!(ScratchTopMetadata, g2h_pool_pages));
pub const SCRATCH_TOP_G2H_BUFFER_SIZE_OFFSET: u64 =
    scratch_top_offset(offset_of!(ScratchTopMetadata, g2h_buffer_size));
pub const SCRATCH_TOP_H2G_QUEUE_SIZE_OFFSET: u64 =
    scratch_top_offset(offset_of!(ScratchTopMetadata, h2g_queue_size));
pub const SCRATCH_TOP_H2G_POOL_PAGES_OFFSET: u64 =
    scratch_top_offset(offset_of!(ScratchTopMetadata, h2g_pool_pages));
pub const SCRATCH_TOP_H2G_BUFFER_SIZE_OFFSET: u64 =
    scratch_top_offset(offset_of!(ScratchTopMetadata, h2g_buffer_size));
pub const SCRATCH_TOP_TRANSPORT_ARENA_GPA_OFFSET: u64 =
    scratch_top_offset(offset_of!(ScratchTopMetadata, transport_arena_gpa));
pub const SCRATCH_TOP_SIZE_OFFSET: u64 =
    scratch_top_offset(offset_of!(ScratchTopMetadata, scratch_size));
pub const SCRATCH_TOP_ALLOCATOR_OFFSET: u64 =
    scratch_top_offset(offset_of!(ScratchTopMetadata, allocator));
pub const SCRATCH_TOP_SNAPSHOT_PT_GPA_BASE_OFFSET: u64 =
    scratch_top_offset(offset_of!(ScratchTopMetadata, snapshot_pt_gpa_base));
pub const SCRATCH_TOP_SNAPSHOT_GENERATION_OFFSET: u64 =
    scratch_top_offset(offset_of!(ScratchTopMetadata, snapshot_generation));
pub const SCRATCH_TOP_LIBC_RNG_SEED_OFFSET: u64 =
    scratch_top_offset(offset_of!(ScratchTopMetadata, libc_rng_seed));
pub const SCRATCH_TOP_GUEST_LOG_LEVEL_OFFSET: u64 =
    scratch_top_offset(offset_of!(ScratchTopMetadata, guest_log_level));
pub const SCRATCH_TOP_EXN_STACK_OFFSET: u64 = size_of::<ScratchTopMetadata>() as u64;

const _: () = {
    assert!(size_of::<ScratchTopMetadata>().is_multiple_of(EXN_STACK_ALIGNMENT));
    assert!(SCRATCH_TOP_SIZE_OFFSET == 0x08);
    assert!(SCRATCH_TOP_ALLOCATOR_OFFSET == 0x10);
    assert!(SCRATCH_TOP_SNAPSHOT_PT_GPA_BASE_OFFSET == 0x18);
    assert!(SCRATCH_TOP_SNAPSHOT_GENERATION_OFFSET == 0x20);
    assert!(SCRATCH_TOP_LIBC_RNG_SEED_OFFSET == 0x28);
    assert!(SCRATCH_TOP_GUEST_LOG_LEVEL_OFFSET == 0x30);
    assert!(SCRATCH_TOP_TRANSPORT_ARENA_GPA_OFFSET == 0x38);
    assert!(SCRATCH_TOP_G2H_QUEUE_SIZE_OFFSET == 0x40);
    assert!(SCRATCH_TOP_G2H_POOL_PAGES_OFFSET == 0x48);
    assert!(SCRATCH_TOP_G2H_BUFFER_SIZE_OFFSET == 0x50);
    assert!(SCRATCH_TOP_H2G_QUEUE_SIZE_OFFSET == 0x58);
    assert!(SCRATCH_TOP_H2G_POOL_PAGES_OFFSET == 0x60);
    assert!(SCRATCH_TOP_H2G_BUFFER_SIZE_OFFSET == 0x68);
    assert!(SCRATCH_TOP_EXN_STACK_OFFSET == 0x70);

    assert!(VIRTQ_BUFFER_GVA_START < VIRTQ_BUFFER_GVA_END);
    assert!((VIRTQ_BUFFER_GVA_START as usize).is_multiple_of(crate::vmem::PAGE_SIZE));
    assert!((VIRTQ_BUFFER_GVA_END as usize).is_multiple_of(crate::vmem::PAGE_SIZE));
    assert!(VIRTQ_BUFFER_GVA_START > SNAPSHOT_PT_GVA_MAX as u64);

    assert!(VIRTQ_BUFFER_GVA_END < scratch_base_gva(16 * 1024 * 1024 * 1024));
    assert!((SCRATCH_TOP_GPA as u64) < VIRTQ_BUFFER_GVA_END - VIRTQ_BUFFER_GVA_START);
};

/// Exclusive upper GPA boundary for dynamic scratch allocations.
pub const fn scratch_allocator_limit_gpa() -> u64 {
    (SCRATCH_TOP_GPA + 1 - SCRATCH_TOP_RESERVED_PAGES * crate::vmem::PAGE_SIZE) as u64
}

pub fn scratch_base_gpa(size: usize) -> u64 {
    (SCRATCH_TOP_GPA - size + 1) as u64
}
pub const fn scratch_base_gva(size: usize) -> u64 {
    (SCRATCH_TOP_GVA - size + 1) as u64
}

/// Compute fixed scratch overhead for a sandbox, saturating at [`usize::MAX`].
///
/// `transport_len` covers rings and buffer pools. Snapshot page tables and
/// runtime allocations need additional scratch.
pub fn min_scratch_size(transport_len: usize) -> usize {
    arch::min_scratch_size()
        .and_then(|fixed| fixed.checked_add(transport_len))
        .unwrap_or(usize::MAX)
}

/// Validated address independent dimensions for one transport queue.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct QueueDims {
    size: NonZeroU16,
    pool_pages: NonZeroUsize,
}

impl QueueDims {
    /// Validate queue dimensions and their byte lengths.
    pub fn new(size: usize, pool_pages: usize) -> Option<Self> {
        let size = u16::try_from(size).ok()?;
        let size = NonZeroU16::new(size)?;

        if !size.get().is_power_of_two() {
            return None;
        }

        let pool_pages = NonZeroUsize::new(pool_pages)?;
        pool_pages.get().checked_mul(crate::vmem::PAGE_SIZE)?;
        Some(Self { size, pool_pages })
    }

    /// Number of descriptors in the queue.
    pub const fn size(&self) -> NonZeroU16 {
        self.size
    }

    /// Number of pages in the queue's buffer pool.
    pub const fn pool_pages(&self) -> NonZeroUsize {
        self.pool_pages
    }

    /// Ring length in bytes, including event suppressions.
    pub fn ring_len(&self) -> usize {
        virtq::Layout::query_size(usize::from(self.size.get()))
    }

    /// Pool length in bytes.
    pub fn pool_len(&self) -> usize {
        self.pool_pages.get() * crate::vmem::PAGE_SIZE
    }
}

/// Addresses of both rings, the checkpoint mailbox, and pools in one fixed arena.
///
/// The G2H ring begins at the arena base. The H2G ring is descriptor aligned.
/// The mailbox is `u64` aligned. Both pools are page aligned.
///
/// ```text
/// +----------+-----+----------+-----+-----+-----+----------+----------+
/// | G2H ring | pad | H2G ring | pad | mbx | pad | G2H pool | H2G pool |
/// +----------+-----+----------+-----+-----+-----+----------+----------+
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TransportArena {
    /// Address of the G2H ring and base of the arena.
    g2h_ring_addr: u64,
    /// Address of the H2G ring.
    h2g_ring_addr: u64,
    /// Address of the snapshot checkpoint mailbox.
    mbx_addr: u64,
    /// Address of the G2H pool.
    g2h_pool_addr: u64,
    /// Address of the H2G pool.
    h2g_pool_addr: u64,
    /// Page-aligned length occupied by both rings and the mailbox.
    ring_span_len: usize,
    /// Total page-aligned arena length.
    len: usize,
}

impl TransportArena {
    /// Derive one transport arena from its base address and queue dimensions.
    pub fn new(base_addr: u64, g2h: QueueDims, h2g: QueueDims) -> Option<Self> {
        if !base_addr.is_multiple_of(crate::vmem::PAGE_SIZE as u64) {
            return None;
        }

        let h2g_ring_offset = g2h
            .ring_len()
            .checked_next_multiple_of(virtq::Descriptor::ALIGN)?;

        let mbx_offset = h2g_ring_offset
            .checked_add(h2g.ring_len())?
            .checked_next_multiple_of(align_of::<u64>())?;

        let g2h_pool_offset = mbx_offset
            .checked_add(size_of::<u64>())?
            .checked_next_multiple_of(crate::vmem::PAGE_SIZE)?;

        let g2h_pool_len = g2h.pool_len();
        let h2g_pool_offset = g2h_pool_offset.checked_add(g2h_pool_len)?;

        let h2g_pool_len = h2g.pool_len();
        let len = h2g_pool_offset.checked_add(h2g_pool_len)?;

        let addr = |offset: usize| base_addr.checked_add(u64::try_from(offset).ok()?);
        let _end_addr = addr(len)?;

        Some(Self {
            g2h_ring_addr: base_addr,
            h2g_ring_addr: addr(h2g_ring_offset)?,
            mbx_addr: addr(mbx_offset)?,
            g2h_pool_addr: addr(g2h_pool_offset)?,
            h2g_pool_addr: addr(h2g_pool_offset)?,
            ring_span_len: g2h_pool_offset,
            len,
        })
    }

    /// Base address of the arena.
    pub const fn base_addr(&self) -> u64 {
        self.g2h_ring_addr
    }

    /// Address of the G2H ring.
    pub const fn g2h_ring_addr(&self) -> u64 {
        self.g2h_ring_addr
    }

    /// Address of the H2G ring.
    pub const fn h2g_ring_addr(&self) -> u64 {
        self.h2g_ring_addr
    }

    /// Address of the snapshot checkpoint mailbox.
    pub const fn mbx_addr(&self) -> u64 {
        self.mbx_addr
    }

    /// Byte offset of the snapshot checkpoint mailbox from the arena base.
    pub const fn mbx_offset(&self) -> usize {
        // `new` proves this difference is nonnegative and fits in `usize`.
        (self.mbx_addr - self.g2h_ring_addr) as usize
    }

    /// Address of the G2H pool.
    pub const fn g2h_pool_addr(&self) -> u64 {
        self.g2h_pool_addr
    }

    /// Address of the H2G pool.
    pub const fn h2g_pool_addr(&self) -> u64 {
        self.h2g_pool_addr
    }

    /// Page-aligned length occupied by both rings and the mailbox.
    pub const fn ring_span_len(&self) -> usize {
        self.ring_span_len
    }

    /// Total page-aligned arena length.
    pub const fn size(&self) -> usize {
        self.len
    }

    /// Exclusive end address of the arena.
    pub const fn end_addr(&self) -> u64 {
        self.g2h_ring_addr + self.len as u64
    }

    /// Convert the arena's absolute addresses into offsets from the arena base.
    pub fn to_offsets(&self) -> (usize, usize, usize, usize, usize) {
        #[allow(clippy::unwrap_used)] // `new` proves every stored offset fits in `usize`.
        let to_offset = |addr| usize::try_from(addr - self.g2h_ring_addr).unwrap();

        (
            to_offset(self.h2g_ring_addr),
            to_offset(self.mbx_addr),
            to_offset(self.g2h_pool_addr),
            to_offset(self.h2g_pool_addr),
            self.len,
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn queue_dims_validate_byte_lengths() {
        let max_pages = usize::MAX / crate::vmem::PAGE_SIZE;
        let dims = QueueDims::new(32768, max_pages).unwrap();

        assert_eq!(dims.ring_len(), 0x80008);
        assert_eq!(dims.pool_len(), max_pages * crate::vmem::PAGE_SIZE);

        for (size, pages) in [
            (0, 1),
            (3, 1),
            (usize::MAX, 1),
            (64, 0),
            (64, max_pages + 1),
        ] {
            assert_eq!(QueueDims::new(size, pages), None);
        }
    }

    #[test]
    fn transport_arena_derives_aligned_regions() {
        let base = 0x1_0000;
        let g2h = QueueDims::new(64, 8).unwrap();
        let h2g = QueueDims::new(32, 4).unwrap();
        let arena = TransportArena::new(base, g2h, h2g).unwrap();

        assert_eq!(arena.g2h_ring_addr(), base);
        assert!(
            arena
                .h2g_ring_addr()
                .is_multiple_of(virtq::Descriptor::ALIGN as u64)
        );
        assert!(arena.mbx_addr().is_multiple_of(align_of::<u64>() as u64));
        assert!(
            arena
                .g2h_pool_addr()
                .is_multiple_of(crate::vmem::PAGE_SIZE as u64)
        );
        assert_eq!(
            arena.h2g_pool_addr(),
            base + 9 * crate::vmem::PAGE_SIZE as u64
        );
        assert_eq!(arena.end_addr(), base + 13 * crate::vmem::PAGE_SIZE as u64);
        assert_eq!(
            arena.to_offsets(),
            (
                0x410,
                0x618,
                crate::vmem::PAGE_SIZE,
                9 * crate::vmem::PAGE_SIZE,
                13 * crate::vmem::PAGE_SIZE,
            )
        );
        assert_eq!(arena.ring_span_len(), crate::vmem::PAGE_SIZE);
        assert_eq!(arena.size(), 13 * crate::vmem::PAGE_SIZE);
        assert_eq!(TransportArena::new(base + 1, g2h, h2g), None);

        let oversized = QueueDims::new(64, usize::MAX / crate::vmem::PAGE_SIZE).unwrap();
        assert_eq!(TransportArena::new(base, oversized, h2g), None);
        assert_eq!(
            TransportArena::new(u64::MAX - crate::vmem::PAGE_SIZE as u64 + 1, g2h, h2g,),
            None
        );
    }

    #[test]
    fn transport_arena_mailbox_offset_at_high_base() {
        // A high address must not affect the small arena-relative offset.
        let base = u64::MAX - 16 * crate::vmem::PAGE_SIZE as u64 + 1;
        let g2h = QueueDims::new(64, 8).unwrap();
        let h2g = QueueDims::new(32, 4).unwrap();
        let arena = TransportArena::new(base, g2h, h2g).unwrap();

        assert_eq!(arena.mbx_offset(), 0x618);
        assert_eq!(base + arena.mbx_offset() as u64, arena.mbx_addr());
        assert!(arena.mbx_offset() + size_of::<u64>() <= arena.ring_span_len());
    }

    #[test]
    fn transport_arena_mailbox_offset_with_largest_queues() {
        // The mailbox follows both rings and fits within the control region.
        let dims = QueueDims::new(32768, 1).unwrap();
        let arena = TransportArena::new(0, dims, dims).unwrap();

        assert_eq!(arena.mbx_offset(), 0x100018);
        assert_eq!(arena.mbx_offset() as u64, arena.mbx_addr());
        assert!(arena.mbx_offset() + size_of::<u64>() <= arena.ring_span_len());
    }

    #[test]
    fn minimum_scratch_includes_transport() {
        let fixed = arch::min_scratch_size().unwrap();

        for transport_len in [0, (1 + 8 + 4) * crate::vmem::PAGE_SIZE, 5 << 20] {
            assert_eq!(fixed + transport_len, min_scratch_size(transport_len));
        }
    }

    #[test]
    fn minimum_scratch_saturates_on_overflow() {
        assert_eq!(usize::MAX, min_scratch_size(usize::MAX));
    }
}