Skip to main content
← PSoXide SDK guides and examples · SDK 80d1c329e977 · All Cargo features enabled; check feature gates before use.

psx_residency/
pool.rs

1//! Contiguous-run page allocation with generation handles.
2//!
3//! Lifted from the retired grid streamer's `StreamedRoomPages` (PSoXide-editor
4//! `psx-game-runtime`), split in two: [`PagePool`] here is only the allocation
5//! map (which pages belong to which allocation), so it works for RAM pages,
6//! VRAM texture slots and SPU RAM blocks alike; the bytes of RAM pages live in
7//! [`crate::PageBuffer`]. What carried over: each allocation is one contiguous
8//! run (a CD transfer lands in its final place), a [`Handle`] carries the slot
9//! and a generation so a stale handle stops resolving the moment its run is
10//! freed or reused, and compaction slides runs toward page 0. What is new:
11//! first-fit or best-fit placement, locked runs that compaction and callers
12//! must not move, one compaction step at a time (so it fits a CPU budget), and
13//! fragmentation statistics.
14
15/// Bytes in one page: one CD-ROM Mode 1 sector.
16pub const PAGE_BYTES: usize = 2048;
17
18/// A run of pages: `page_count` pages starting at `first_page`.
19#[derive(Copy, Clone, Debug, PartialEq, Eq)]
20pub struct PageRun {
21    /// Index of the first page.
22    pub first_page: u32,
23    /// Number of pages.
24    pub page_count: u32,
25}
26
27impl PageRun {
28    /// Index one past the last page.
29    pub const fn end_page(self) -> u32 {
30        self.first_page + self.page_count
31    }
32
33    /// Capacity of the run in bytes, for pages of [`PAGE_BYTES`].
34    pub const fn capacity_bytes(self) -> usize {
35        self.page_count as usize * PAGE_BYTES
36    }
37}
38
39/// Generation-checked identity of one allocation. It stops resolving as soon
40/// as its allocation is freed, even if the slot is reused for another run.
41#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
42pub struct Handle {
43    pool: u8,
44    slot: u16,
45    generation: u32,
46}
47
48impl Handle {
49    /// A handle that is never current, for filling buffers.
50    pub const NONE: Handle = Handle {
51        pool: u8::MAX,
52        slot: u16::MAX,
53        generation: 0,
54    };
55
56    /// Pool number the handle was allocated from.
57    pub const fn pool(self) -> u8 {
58        self.pool
59    }
60
61    /// Allocation slot inside that pool.
62    pub const fn slot(self) -> u16 {
63        self.slot
64    }
65
66    /// Generation of the slot when the handle was issued.
67    pub const fn generation(self) -> u32 {
68        self.generation
69    }
70}
71
72/// Which free gap a new run goes into.
73#[derive(Copy, Clone, Debug, PartialEq, Eq)]
74pub enum Placement {
75    /// The lowest-addressed gap that is large enough.
76    FirstFit,
77    /// The smallest gap that is large enough (ties go to the lowest address).
78    BestFit,
79}
80
81/// Free-space shape of a pool, for fragmentation reports.
82#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
83pub struct Fragmentation {
84    /// Free pages in total.
85    pub free_pages: u32,
86    /// Pages in the largest free run.
87    pub largest_free_run: u32,
88    /// Number of separate free runs.
89    pub free_run_count: u32,
90}
91
92impl Fragmentation {
93    /// Share of free space that is not in the largest run, in permille
94    /// (0 when all free space is one run, or there is none).
95    pub const fn permille(self) -> u32 {
96        if self.free_pages == 0 {
97            return 0;
98        }
99        // 32-bit only: scale huge pools down so the product cannot overflow.
100        let mut free = self.free_pages;
101        let mut largest = self.largest_free_run;
102        while free > u32::MAX / 1000 {
103            free >>= 1;
104            largest >>= 1;
105        }
106        1000 - largest * 1000 / free
107    }
108}
109
110/// One run moved by [`PagePool::compact_step`].
111#[derive(Copy, Clone, Debug, PartialEq, Eq)]
112pub struct Moved {
113    /// The moved allocation (its handle stays valid).
114    pub handle: Handle,
115    /// Where it was.
116    pub from: PageRun,
117    /// First page it occupies now.
118    pub to_page: u32,
119}
120
121#[derive(Copy, Clone)]
122struct Run {
123    first: u32,
124    /// Zero means the slot is free.
125    count: u32,
126    generation: u32,
127    locked: bool,
128}
129
130const FREE_RUN: Run = Run {
131    first: 0,
132    count: 0,
133    generation: 0,
134    locked: false,
135};
136
137/// Allocation map of `capacity_pages` pages shared by up to `SLOTS` runs.
138///
139/// Pure bookkeeping: the pool never touches page contents. All state is plain
140/// integers, so a static pool can live in `.bss`.
141pub struct PagePool<const SLOTS: usize> {
142    pool: u8,
143    capacity_pages: u32,
144    placement: Placement,
145    runs: [Run; SLOTS],
146    /// Live slots sorted by first page; only `order[..live]` is meaningful.
147    order: [u16; SLOTS],
148    live: usize,
149    used_pages: u32,
150    layout_generation: u32,
151}
152
153impl<const SLOTS: usize> PagePool<SLOTS> {
154    /// An empty pool numbered `pool` (stamped into its handles) of
155    /// `capacity_pages` pages.
156    pub const fn new(pool: u8, capacity_pages: u32, placement: Placement) -> Self {
157        Self {
158            pool,
159            capacity_pages,
160            placement,
161            runs: [FREE_RUN; SLOTS],
162            order: [0; SLOTS],
163            live: 0,
164            used_pages: 0,
165            layout_generation: 0,
166        }
167    }
168
169    /// Total pages in the pool.
170    pub const fn capacity_pages(&self) -> u32 {
171        self.capacity_pages
172    }
173
174    /// Pages held by live allocations.
175    pub const fn used_pages(&self) -> u32 {
176        self.used_pages
177    }
178
179    /// Pages not held by any allocation (possibly scattered).
180    pub const fn free_pages(&self) -> u32 {
181        self.capacity_pages - self.used_pages
182    }
183
184    /// Number of live allocations.
185    pub const fn live_count(&self) -> usize {
186        self.live
187    }
188
189    /// Placement policy for new runs.
190    pub const fn placement(&self) -> Placement {
191        self.placement
192    }
193
194    /// Change the placement policy; existing runs stay where they are.
195    pub fn set_placement(&mut self, placement: Placement) {
196        self.placement = placement;
197    }
198
199    /// Bumped every time compaction moves a run. A byte view taken before a
200    /// bump may point at the wrong pages: re-resolve it.
201    pub const fn layout_generation(&self) -> u32 {
202        self.layout_generation
203    }
204
205    /// Allocate a contiguous run of `page_count` pages, or `None` when no gap
206    /// is large enough or every slot is taken. Never moves another run.
207    pub fn allocate(&mut self, page_count: u32) -> Option<(Handle, PageRun)> {
208        if page_count == 0 {
209            return None;
210        }
211        let first = self.find_fit(page_count)?;
212        self.allocate_at(first, page_count)
213    }
214
215    /// Allocate an exact contiguous range without moving existing allocations.
216    /// This supports consumers whose code windows constrain placement.
217    pub fn allocate_at(&mut self, first: u32, page_count: u32) -> Option<(Handle, PageRun)> {
218        let end = first.checked_add(page_count)?;
219        if page_count == 0 || end > self.capacity_pages {
220            return None;
221        }
222        if self
223            .runs
224            .iter()
225            .any(|run| run.count != 0 && first < run.first + run.count && run.first < end)
226        {
227            return None;
228        }
229        let slot = self.runs.iter().position(|run| run.count == 0)?;
230        let generation = self.runs[slot].generation.wrapping_add(1);
231        self.runs[slot] = Run {
232            first,
233            count: page_count,
234            generation,
235            locked: false,
236        };
237        let mut position = self.live;
238        while position > 0 && self.runs[self.order[position - 1] as usize].first > first {
239            self.order[position] = self.order[position - 1];
240            position -= 1;
241        }
242        self.order[position] = slot as u16;
243        self.live += 1;
244        self.used_pages += page_count;
245        Some((
246            Handle {
247                pool: self.pool,
248                slot: slot as u16,
249                generation,
250            },
251            PageRun {
252                first_page: first,
253                page_count,
254            },
255        ))
256    }
257
258    /// First page of the gap a run of `page_count` pages would get.
259    pub fn find_fit(&self, page_count: u32) -> Option<u32> {
260        if page_count == 0 || page_count > self.free_pages() {
261            return None;
262        }
263        let mut best: Option<(u32, u32)> = None;
264        for (start, length) in self.gaps() {
265            if length < page_count {
266                continue;
267            }
268            match self.placement {
269                Placement::FirstFit => return Some(start),
270                Placement::BestFit => {
271                    if best.is_none_or(|(_, best_length)| length < best_length) {
272                        best = Some((start, length));
273                    }
274                }
275            }
276        }
277        best.map(|(start, _)| start)
278    }
279
280    /// Free `handle`. `false` (and no change) when the handle is stale.
281    pub fn free(&mut self, handle: Handle) -> bool {
282        if !self.is_current(handle) {
283            return false;
284        }
285        let slot = handle.slot as usize;
286        let position = self.order[..self.live]
287            .iter()
288            .position(|&s| s as usize == slot)
289            .expect("a live run is always in the order table");
290        self.order.copy_within(position + 1..self.live, position);
291        self.live -= 1;
292        self.used_pages -= self.runs[slot].count;
293        self.runs[slot] = Run {
294            generation: self.runs[slot].generation.wrapping_add(1),
295            ..FREE_RUN
296        };
297        true
298    }
299
300    /// Whether `handle` still names the allocation it was issued for.
301    pub fn is_current(&self, handle: Handle) -> bool {
302        handle.pool == self.pool
303            && self
304                .runs
305                .get(handle.slot as usize)
306                .is_some_and(|run| run.count > 0 && run.generation == handle.generation)
307    }
308
309    /// The pages `handle` names, or `None` when it is stale.
310    pub fn try_run(&self, handle: Handle) -> Option<PageRun> {
311        if !self.is_current(handle) {
312            return None;
313        }
314        let run = self.runs[handle.slot as usize];
315        Some(PageRun {
316            first_page: run.first,
317            page_count: run.count,
318        })
319    }
320
321    /// Current handle of an occupied allocation slot, for owner bookkeeping.
322    /// This does not revive any previously issued handle.
323    pub fn handle_for_slot(&self, slot: u16) -> Option<Handle> {
324        let run = self.runs.get(slot as usize)?;
325        (run.count != 0).then_some(Handle {
326            pool: self.pool,
327            slot,
328            generation: run.generation,
329        })
330    }
331
332    /// Lock or unlock the run. A locked run is never moved by
333    /// [`PagePool::compact_step`] (a transfer is landing in it, or a consumer
334    /// holds a raw view of it). `false` when the handle is stale.
335    pub fn set_locked(&mut self, handle: Handle, locked: bool) -> bool {
336        if !self.is_current(handle) {
337            return false;
338        }
339        self.runs[handle.slot as usize].locked = locked;
340        true
341    }
342
343    /// Whether the run is locked (`false` for a stale handle).
344    pub fn is_locked(&self, handle: Handle) -> bool {
345        self.is_current(handle) && self.runs[handle.slot as usize].locked
346    }
347
348    /// Live allocations in address order as `(slot, run, locked)`.
349    pub fn iter_runs(&self) -> impl Iterator<Item = (u16, PageRun, bool)> + '_ {
350        self.order[..self.live].iter().map(move |&slot| {
351            let run = self.runs[slot as usize];
352            (
353                slot,
354                PageRun {
355                    first_page: run.first,
356                    page_count: run.count,
357                },
358                run.locked,
359            )
360        })
361    }
362
363    /// Handle of the live allocation in `slot`.
364    pub fn handle_of_slot(&self, slot: u16) -> Option<Handle> {
365        let run = self.runs.get(slot as usize)?;
366        (run.count > 0).then_some(Handle {
367            pool: self.pool,
368            slot,
369            generation: run.generation,
370        })
371    }
372
373    /// Free gaps in address order as `(first_page, page_count)`.
374    pub fn gaps(&self) -> impl Iterator<Item = (u32, u32)> + '_ {
375        let mut cursor = 0u32;
376        let mut position = 0usize;
377        let mut done = false;
378        core::iter::from_fn(move || {
379            while !done {
380                let (end, next_cursor) = if position < self.live {
381                    let run = self.runs[self.order[position] as usize];
382                    position += 1;
383                    (run.first, run.first + run.count)
384                } else {
385                    done = true;
386                    (self.capacity_pages, self.capacity_pages)
387                };
388                let start = cursor;
389                cursor = next_cursor;
390                if end > start {
391                    return Some((start, end - start));
392                }
393            }
394            None
395        })
396    }
397
398    /// Shape of the free space.
399    pub fn fragmentation(&self) -> Fragmentation {
400        let mut result = Fragmentation::default();
401        for (_, length) in self.gaps() {
402            result.free_pages += length;
403            result.free_run_count += 1;
404            result.largest_free_run = result.largest_free_run.max(length);
405        }
406        result
407    }
408
409    /// Slide the lowest unlocked run that has free space below it down to the
410    /// lowest page it can reach, calling `copy(from, to_page)` so the owner of
411    /// the bytes moves them (the destination may overlap the source; copy as
412    /// `memmove`). Locked runs stay put and act as barriers. One run per call,
413    /// so a caller can spend a CPU budget on it. `None` when nothing can move.
414    pub fn compact_step(&mut self, mut copy: impl FnMut(PageRun, u32)) -> Option<Moved> {
415        let mut cursor = 0u32;
416        for position in 0..self.live {
417            let slot = self.order[position] as usize;
418            let run = self.runs[slot];
419            if !run.locked && run.first > cursor {
420                let from = PageRun {
421                    first_page: run.first,
422                    page_count: run.count,
423                };
424                copy(from, cursor);
425                self.runs[slot].first = cursor;
426                self.layout_generation = self.layout_generation.wrapping_add(1);
427                return Some(Moved {
428                    handle: Handle {
429                        pool: self.pool,
430                        slot: slot as u16,
431                        generation: run.generation,
432                    },
433                    from,
434                    to_page: cursor,
435                });
436            }
437            cursor = run.first + run.count;
438        }
439        None
440    }
441
442    /// Check the structural invariants (host tests and debug assertions).
443    #[cfg(any(test, debug_assertions))]
444    pub fn check_invariants(&self) {
445        let mut used = 0u32;
446        let mut previous_end = 0u32;
447        for position in 0..self.live {
448            let run = self.runs[self.order[position] as usize];
449            assert!(run.count > 0, "order lists a free slot");
450            assert!(run.first >= previous_end, "runs overlap or are unsorted");
451            previous_end = run.first + run.count;
452            assert!(previous_end <= self.capacity_pages, "run past capacity");
453            used += run.count;
454        }
455        assert_eq!(used, self.used_pages, "used_pages out of step");
456        let live = self.runs.iter().filter(|run| run.count > 0).count();
457        assert_eq!(live, self.live, "live count out of step");
458    }
459}
460
461#[cfg(test)]
462mod tests {
463    use super::*;
464
465    #[test]
466    fn charges_exact_page_count() {
467        let mut pool = PagePool::<3>::new(0, 8, Placement::FirstFit);
468        let (_, a) = pool.allocate(1).unwrap();
469        let (_, b) = pool.allocate(2).unwrap();
470        assert_eq!(a.page_count, 1);
471        assert_eq!(b.page_count, 2);
472        assert_eq!(pool.free_pages(), 5);
473        pool.check_invariants();
474    }
475
476    #[test]
477    fn released_or_reused_slot_invalidates_old_handle() {
478        let mut pool = PagePool::<1>::new(0, 4, Placement::FirstFit);
479        let (first, _) = pool.allocate(1).unwrap();
480        assert!(pool.try_run(first).is_some());
481        assert!(pool.free(first));
482        assert!(pool.try_run(first).is_none());
483        assert!(!pool.free(first), "double free is refused");
484        let (second, _) = pool.allocate(1).unwrap();
485        assert_eq!(first.slot(), second.slot());
486        assert_ne!(first.generation(), second.generation());
487        assert!(pool.try_run(first).is_none(), "reuse must not revive it");
488    }
489
490    #[test]
491    fn handle_from_another_pool_is_stale() {
492        let mut a = PagePool::<2>::new(0, 4, Placement::FirstFit);
493        let b = PagePool::<2>::new(1, 4, Placement::FirstFit);
494        let (handle, _) = a.allocate(1).unwrap();
495        assert!(!b.is_current(handle));
496    }
497
498    #[test]
499    fn placement_policies_choose_different_gaps() {
500        // Layout: [A 2][gap 4][B 1][gap 2][C 1]; capacity 10.
501        let build = |placement| {
502            let mut pool = PagePool::<8>::new(0, 10, placement);
503            let (a, _) = pool.allocate(2).unwrap();
504            let (gap1, _) = pool.allocate(4).unwrap();
505            let (b, _) = pool.allocate(1).unwrap();
506            let (gap2, _) = pool.allocate(2).unwrap();
507            let (c, _) = pool.allocate(1).unwrap();
508            pool.free(gap1);
509            pool.free(gap2);
510            (pool, [a, b, c])
511        };
512        let (first_fit, _) = build(Placement::FirstFit);
513        let (best_fit, _) = build(Placement::BestFit);
514        assert_eq!(first_fit.find_fit(2), Some(2));
515        assert_eq!(best_fit.find_fit(2), Some(7));
516        assert_eq!(best_fit.find_fit(4), Some(2));
517        assert_eq!(best_fit.find_fit(5), None);
518    }
519
520    #[test]
521    fn fragmented_pool_compacts_and_keeps_handles() {
522        let mut pool = PagePool::<4>::new(0, 8, Placement::FirstFit);
523        let (a, _) = pool.allocate(2).unwrap();
524        let (b, _) = pool.allocate(2).unwrap();
525        let (c, _) = pool.allocate(2).unwrap();
526        pool.free(b);
527        assert_eq!(pool.find_fit(4), None);
528        assert_eq!(pool.fragmentation().free_run_count, 2);
529        let before = pool.layout_generation();
530        let mut copies = [None; 2];
531        let mut count = 0;
532        while let Some(moved) = pool.compact_step(|from, to| {
533            copies[count] = Some((from.first_page, to));
534        }) {
535            assert_eq!(moved.handle, c);
536            count += 1;
537        }
538        assert_eq!(copies[0], Some((4, 2)));
539        assert_ne!(pool.layout_generation(), before);
540        assert_eq!(pool.try_run(a).unwrap().first_page, 0);
541        assert_eq!(pool.try_run(c).unwrap().first_page, 2);
542        assert_eq!(pool.find_fit(4), Some(4));
543        pool.check_invariants();
544    }
545
546    #[test]
547    fn locked_run_is_a_compaction_barrier() {
548        let mut pool = PagePool::<5>::new(0, 12, Placement::FirstFit);
549        let (a, _) = pool.allocate(2).unwrap();
550        let (b, _) = pool.allocate(2).unwrap();
551        let (c, _) = pool.allocate(2).unwrap();
552        let (d, _) = pool.allocate(2).unwrap();
553        pool.free(a);
554        pool.free(c);
555        assert!(pool.set_locked(b, true));
556        assert!(pool.is_locked(b));
557        // Layout: [gap 0..2][b locked 2..4][gap 4..6][d 6..8]. d slides to 4,
558        // b stays, and nothing jumps over b into the first gap.
559        let moved = pool.compact_step(|_, _| {}).unwrap();
560        assert_eq!(moved.handle, d);
561        assert_eq!(moved.to_page, 4);
562        assert!(pool.compact_step(|_, _| {}).is_none());
563        assert_eq!(pool.try_run(b).unwrap().first_page, 2);
564        assert_eq!(pool.try_run(d).unwrap().first_page, 4);
565        pool.check_invariants();
566    }
567
568    #[test]
569    fn free_space_shape_is_reported() {
570        let mut pool = PagePool::<4>::new(0, 10, Placement::FirstFit);
571        let (a, _) = pool.allocate(3).unwrap();
572        let (_b, _) = pool.allocate(3).unwrap();
573        pool.free(a);
574        let shape = pool.fragmentation();
575        assert_eq!(shape.free_pages, 7);
576        assert_eq!(shape.largest_free_run, 4);
577        assert_eq!(shape.free_run_count, 2);
578        assert_eq!(shape.permille(), 1000 - 4 * 1000 / 7);
579    }
580
581    #[test]
582    fn full_slot_table_refuses_even_when_pages_are_free() {
583        let mut pool = PagePool::<2>::new(0, 100, Placement::FirstFit);
584        pool.allocate(1).unwrap();
585        pool.allocate(1).unwrap();
586        assert!(pool.allocate(1).is_none());
587        assert!(pool.allocate(0).is_none());
588    }
589}