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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 The Hyperlight Authors.

//! Fixed-slot pool with optional lower and required upper tiers.
//!
//! [`SlotPool`] manages one or two non-overlapping [`SlotLayout`]s. Each tier
//! contains independent, equal-sized slots tracked by a free list and an
//! allocation bitmap. Eligible requests try the lower tier first and fall back
//! to the upper tier only when the lower tier has no free slot.
//!
//! Each allocation occupies one slot. [`SlotPool::live_addrs`] reports ownership
//! in deterministic index order.

use alloc::rc::Rc;
use alloc::vec::Vec;
use core::cell::RefCell;

use fixedbitset::FixedBitSet;
use smallvec::SmallVec;

use super::{AllocError, Allocation};

/// Validated memory layout for one [`SlotPool`] tier.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SlotLayout {
    /// Start of the first slot.
    base_addr: u64,
    /// Capacity of each slot. Must fit in [`Allocation::len`].
    slot_size: u32,
    /// Number of slots.
    slot_count: usize,
}

impl SlotLayout {
    /// Validate exact fixed-slot placement.
    ///
    /// Rejects empty layouts, slots larger than [`u32::MAX`], and unrepresentable
    /// backing or free-list byte ranges.
    pub fn new(base_addr: u64, slot_size: usize, slot_count: usize) -> Result<Self, AllocError> {
        let slot_size = u32::try_from(slot_size).map_err(|_| AllocError::InvalidArg)?;

        if slot_size == 0 {
            return Err(AllocError::InvalidArg);
        }

        if slot_count == 0 {
            return Err(AllocError::EmptyRegion);
        }

        let byte_len = (slot_size as usize)
            .checked_mul(slot_count)
            .ok_or(AllocError::Overflow)?;

        base_addr
            .checked_add(u64::try_from(byte_len).map_err(|_| AllocError::Overflow)?)
            .ok_or(AllocError::Overflow)?;

        core::alloc::Layout::array::<u64>(slot_count).map_err(|_| AllocError::Overflow)?;

        Ok(Self {
            base_addr,
            slot_size,
            slot_count,
        })
    }

    /// Start address of the first slot.
    pub const fn base_addr(self) -> u64 {
        self.base_addr
    }

    /// Capacity of each slot in bytes.
    pub const fn slot_size(self) -> usize {
        self.slot_size as usize
    }

    /// Number of equal-sized slots.
    pub const fn slot_count(self) -> usize {
        self.slot_count
    }

    /// Total bytes occupied by the slots.
    pub const fn byte_len(self) -> usize {
        self.slot_size as usize * self.slot_count
    }

    /// Exclusive end address.
    pub const fn end_addr(self) -> u64 {
        self.base_addr + self.byte_len() as u64
    }
}

/// Single-tier fixed-slot free list.
///
/// Tracks a fixed set of equal-sized buffer slots. Allocation pops a free slot
/// and deallocation returns it, both O(1). A [`FixedBitSet`] records which slots
/// are currently allocated, so double frees and frees of unknown addresses are
/// rejected without scanning the free list.
struct Tier {
    /// Start of this tier's backing memory.
    base_addr: u64,
    /// Capacity of this slot.
    slot_size: u32,
    /// Number of slots in this tier.
    count: usize,
    /// Free slot addresses, popped/pushed LIFO.
    free: SmallVec<[u64; 64]>,
    /// One bit per slot index; set means the slot is currently handed out.
    allocated: FixedBitSet,
}

impl Tier {
    fn from_layout(layout: SlotLayout) -> Result<Self, AllocError> {
        let mut free = SmallVec::new();
        free.try_reserve_exact(layout.slot_count)
            .map_err(|_| AllocError::Bookkeeping)?;

        for i in 0..layout.slot_count {
            free.push(layout.base_addr + (i * layout.slot_size as usize) as u64);
        }

        Ok(Self {
            base_addr: layout.base_addr,
            slot_size: layout.slot_size,
            count: layout.slot_count,
            free,
            allocated: FixedBitSet::with_capacity(layout.slot_count),
        })
    }

    fn end(&self) -> u64 {
        self.base_addr + self.count as u64 * u64::from(self.slot_size)
    }

    fn contains(&self, addr: u64) -> bool {
        (self.base_addr..self.end()).contains(&addr)
    }

    /// Validate that `addr` names a slot start within the region.
    fn slot_of(&self, addr: u64) -> Result<usize, AllocError> {
        if !self.contains(addr) {
            return Err(AllocError::InvalidFree(addr, 0));
        }

        let off = addr - self.base_addr;
        if !off.is_multiple_of(u64::from(self.slot_size)) {
            return Err(AllocError::InvalidFree(addr, 0));
        }

        Ok((off / u64::from(self.slot_size)) as usize)
    }

    /// Validate that `addr` is a live (currently allocated) slot start.
    fn live_slot_of(&self, addr: u64) -> Result<usize, AllocError> {
        let slot = self.slot_of(addr)?;
        if !self.allocated.contains(slot) {
            return Err(AllocError::InvalidFree(addr, 0));
        }
        Ok(slot)
    }

    fn alloc(&mut self, len: usize) -> Result<Allocation, AllocError> {
        if len == 0 {
            return Err(AllocError::InvalidArg);
        }
        if len > self.slot_size as usize {
            return Err(AllocError::OutOfMemory);
        }

        let addr = self.free.pop().ok_or(AllocError::NoSpace)?;
        // Safety of the index: `addr` came from `free`, which only ever holds
        // valid slot starts.
        self.allocated
            .insert(((addr - self.base_addr) / u64::from(self.slot_size)) as usize);

        Ok(Allocation {
            addr,
            len: self.slot_size,
        })
    }

    fn dealloc_addr(&mut self, addr: u64) -> Result<(), AllocError> {
        let slot = self.live_slot_of(addr)?;
        self.allocated.set(slot, false);
        self.free.push(addr);
        Ok(())
    }

    /// Keep one queue-owned slot unavailable during generation recovery.
    fn reserve_addr(&mut self, addr: u64) -> Result<(), AllocError> {
        let slot = self.slot_of(addr)?;

        if self.allocated.contains(slot) {
            return Err(AllocError::InvalidArg);
        }

        self.allocated.insert(slot);
        Ok(())
    }

    /// Rebuild the free list from the recovered ownership bitmap.
    fn rebuild_free(&mut self) {
        self.free.clear();

        for slot in self.allocated.zeroes() {
            self.free
                .push(self.base_addr + slot as u64 * u64::from(self.slot_size));
        }
    }

    fn allocation_len(&self, addr: u64) -> Result<usize, AllocError> {
        self.live_slot_of(addr)?;
        Ok(self.slot_size as usize)
    }

    fn slot_addr(&self, index: usize) -> Option<u64> {
        (index < self.count).then(|| self.base_addr + (index * self.slot_size as usize) as u64)
    }

    fn num_free(&self) -> usize {
        self.free.len()
    }

    fn append_live_addrs(&self, addrs: &mut Vec<u64>) {
        addrs.extend(
            self.allocated
                .ones()
                .map(|slot| self.base_addr + (slot * self.slot_size as usize) as u64),
        );
    }

    fn layout(&self) -> SlotLayout {
        SlotLayout {
            base_addr: self.base_addr,
            slot_size: self.slot_size,
            slot_count: self.count,
        }
    }
}

struct Inner {
    lower: Option<Tier>,
    upper: Tier,
    generation: u64,
}

impl Inner {
    fn new(lower: Option<SlotLayout>, upper: SlotLayout) -> Result<Self, AllocError> {
        let Some(lower) = lower else {
            return Ok(Self {
                lower: None,
                upper: Tier::from_layout(upper)?,
                generation: 0,
            });
        };

        if lower.slot_size > upper.slot_size || lower.end_addr() > upper.base_addr {
            return Err(AllocError::InvalidArg);
        }

        if lower.slot_size == upper.slot_size {
            if lower.end_addr() != upper.base_addr {
                return Err(AllocError::InvalidArg);
            }

            let count = lower
                .slot_count
                .checked_add(upper.slot_count)
                .ok_or(AllocError::Overflow)?;

            let layout = SlotLayout::new(lower.base_addr, lower.slot_size(), count)?;

            return Ok(Self {
                lower: None,
                upper: Tier::from_layout(layout)?,
                generation: 0,
            });
        }

        Ok(Self {
            lower: Some(Tier::from_layout(lower)?),
            upper: Tier::from_layout(upper)?,
            generation: 0,
        })
    }

    fn max_alloc_len(&self) -> usize {
        self.upper.slot_size as usize
    }

    fn alloc(&mut self, len: usize) -> Result<Allocation, AllocError> {
        if let Some(lower) = &mut self.lower
            && len <= lower.slot_size as usize
        {
            match lower.alloc(len) {
                Ok(alloc) => return Ok(alloc),
                Err(AllocError::NoSpace) => {}
                Err(err) => return Err(err),
            }
        }

        self.upper.alloc(len)
    }

    fn dealloc_addr(&mut self, addr: u64) -> Result<(), AllocError> {
        if let Some(lower) = &mut self.lower
            && lower.contains(addr)
        {
            return lower.dealloc_addr(addr);
        }
        self.upper.dealloc_addr(addr)
    }

    /// Start a new generation and rebuild allocation state from `reserved`.
    fn retire_generation(
        &mut self,
        reserved: impl Iterator<Item = u64> + Clone,
    ) -> Result<(), AllocError> {
        let generation = self.generation.checked_add(1).ok_or(AllocError::Overflow)?;

        #[cfg(debug_assertions)]
        for addr in reserved.clone() {
            debug_assert!(
                self.allocation_len(addr).is_ok(),
                "address {addr:#x} is not a live pool slot"
            );
        }

        self.generation = generation;
        self.upper.allocated.clear();

        if let Some(lower) = &mut self.lower {
            lower.allocated.clear();
        }

        for addr in reserved {
            if let Some(lower) = &mut self.lower
                && lower.contains(addr)
            {
                lower.reserve_addr(addr)?;
            } else {
                self.upper.reserve_addr(addr)?;
            }
        }

        self.upper.rebuild_free();

        if let Some(lower) = &mut self.lower {
            lower.rebuild_free();
        }

        Ok(())
    }

    fn allocation_len(&self, addr: u64) -> Result<usize, AllocError> {
        if let Some(lower) = &self.lower
            && lower.contains(addr)
        {
            return lower.allocation_len(addr);
        }
        self.upper.allocation_len(addr)
    }

    fn slot_addr(&self, index: usize) -> Option<u64> {
        if let Some(lower) = &self.lower {
            if index < lower.count {
                return lower.slot_addr(index);
            }
            return self.upper.slot_addr(index - lower.count);
        }
        self.upper.slot_addr(index)
    }

    fn live_addrs(&self) -> Vec<u64> {
        let mut addrs = Vec::with_capacity(self.num_live());
        if let Some(lower) = &self.lower {
            lower.append_live_addrs(&mut addrs);
        }
        self.upper.append_live_addrs(&mut addrs);
        addrs
    }

    fn base_addr(&self) -> u64 {
        self.lower
            .as_ref()
            .map_or(self.upper.base_addr, |lower| lower.base_addr)
    }

    fn count(&self) -> usize {
        self.lower.as_ref().map_or(0, |lower| lower.count) + self.upper.count
    }

    fn num_free(&self) -> usize {
        self.lower.as_ref().map_or(0, Tier::num_free) + self.upper.num_free()
    }

    fn num_live(&self) -> usize {
        self.count() - self.num_free()
    }

    fn layouts(&self) -> (Option<SlotLayout>, SlotLayout) {
        (self.lower.as_ref().map(Tier::layout), self.upper.layout())
    }

    /// Byte span of both tiers, including any gap.
    fn byte_len(&self) -> usize {
        (self.upper.layout().end_addr() - self.base_addr()) as usize
    }
}

/// A buffer pool with one or two fixed-slot tiers.
///
/// Allocation and deallocation are O(1) per slot. Eligible allocations first
/// try the optional lower tier and fall back to the required upper tier when
/// the lower tier is full.
#[derive(Clone)]
pub struct SlotPool {
    inner: Rc<RefCell<Inner>>,
}

impl SlotPool {
    /// Generation owning the current scratch allocations.
    pub(crate) fn generation(&self) -> u64 {
        self.inner.borrow().generation
    }

    /// Retire existing leases and rebuild the pool around the supplied reservations.
    ///
    /// # Safety
    ///
    /// Retired views must already use backing independent of these scratch slots.
    /// `reserved` must name every other live allocation exactly once.
    /// No allocation or peer access may race this call.
    pub(crate) unsafe fn retire_generation(
        &self,
        reserved: impl Iterator<Item = u64> + Clone,
    ) -> Result<(), AllocError> {
        self.inner.borrow_mut().retire_generation(reserved)
    }

    /// Create a single-tier recycling pool from exact slot placement.
    pub fn new(layout: SlotLayout) -> Result<Self, AllocError> {
        Self::from_layouts(None, layout)
    }

    /// Create a two-tier recycling pool from exact lower and upper layouts.
    ///
    /// The lower layout must precede the upper layout without overlap, and its
    /// slot size must not exceed the upper slot size. Adjacent equal-sized
    /// layouts form one tier.
    pub fn new_tiered(lower: SlotLayout, upper: SlotLayout) -> Result<Self, AllocError> {
        Self::from_layouts(Some(lower), upper)
    }

    fn from_layouts(lower: Option<SlotLayout>, upper: SlotLayout) -> Result<Self, AllocError> {
        let inner = Inner::new(lower, upper)?;
        Ok(Self {
            inner: Rc::new(RefCell::new(inner)),
        })
    }

    /// Return every live slot address in deterministic tier and index order.
    pub fn live_addrs(&self) -> Vec<u64> {
        self.inner.borrow().live_addrs()
    }

    /// Return the lower and upper tier layouts.
    pub fn layouts(&self) -> (Option<SlotLayout>, SlotLayout) {
        self.inner.borrow().layouts()
    }

    /// Compute the address of slot `index`, with lower-tier slots first.
    ///
    /// Returns `None` if `index >= count`.
    pub fn slot_addr(&self, index: usize) -> Option<u64> {
        self.inner.borrow().slot_addr(index)
    }

    /// Total number of free slots across all tiers.
    pub fn num_free(&self) -> usize {
        self.inner.borrow().num_free()
    }

    /// Total number of currently allocated slots across all tiers.
    pub fn num_live(&self) -> usize {
        self.inner.borrow().num_live()
    }

    /// Total number of free slots in the lower tier.
    pub fn num_free_lower(&self) -> usize {
        self.inner.borrow().lower.as_ref().map_or(0, Tier::num_free)
    }

    /// Total number of free slots in the upper tier.
    pub fn num_free_upper(&self) -> usize {
        self.inner.borrow().upper.num_free()
    }

    /// Free a previously allocated slot by address.
    pub fn dealloc(&self, addr: u64) -> Result<(), AllocError> {
        self.inner.borrow_mut().dealloc_addr(addr)
    }

    /// Capacity of a live allocation by its start address.
    pub fn allocation_len(&self, addr: u64) -> Result<usize, AllocError> {
        self.inner.borrow().allocation_len(addr)
    }

    /// Base address of the first managed tier.
    pub fn base_addr(&self) -> u64 {
        self.inner.borrow().base_addr()
    }

    /// Maximum slot size in bytes.
    pub fn slot_size(&self) -> usize {
        self.inner.borrow().max_alloc_len()
    }

    /// Slot size in bytes for the lower tier, if present.
    pub fn lower_slot_size(&self) -> Option<usize> {
        self.inner
            .borrow()
            .lower
            .as_ref()
            .map(|lower| lower.slot_size as usize)
    }

    /// Maximum slot size in bytes for the upper tier.
    pub fn upper_slot_size(&self) -> usize {
        self.inner.borrow().upper.slot_size as usize
    }

    /// Total number of slots across all tiers.
    pub fn count(&self) -> usize {
        self.inner.borrow().count()
    }

    /// Allocate one slot holding at least `len` bytes.
    pub fn alloc(&self, len: usize) -> Result<Allocation, AllocError> {
        self.inner.borrow_mut().alloc(len)
    }

    /// Byte span from the first slot to the last, including any gap between tiers.
    pub fn byte_len(&self) -> usize {
        self.inner.borrow().byte_len()
    }

    #[cfg(test)]
    pub(crate) fn strong_count(&self) -> usize {
        Rc::strong_count(&self.inner)
    }
}