Skip to main content

subetha_cxc/
frame_region.rs

1//! `FrameRegion` - concurrent fixed-block payload region for the
2//! self-describing offset path shared by every `AdaptiveRing` shape.
3//!
4//! Records too large to inline in a ring slot spill here: the producer
5//! allocates a block, copies the payload in, and writes the block index
6//! into the ring descriptor; the consumer reads the block and frees it.
7//! Because the offset payloads of every shape (SPSC / MPSC / MPMC /
8//! Vyukov) land in one region, the allocator must be safe for many
9//! producers allocating and many consumers freeing at once, in any
10//! order. That is a Treiber-stack free list with an ABA counter plus a
11//! bump high-water mark - the same allocator
12//! [`SharedRegion`](crate::shared_region::SharedRegion) ships, here with
13//! a runtime block size instead of a const-generic `T` so the
14//! `AdaptiveRing` can size its blocks to the workload.
15//!
16//! Reclaim order does not matter: a freed block returns to the stack
17//! and is handed to the next allocation regardless of which consumer
18//! freed it, so no FIFO bookkeeping is needed across consumers.
19
20use std::fs::{File, OpenOptions};
21use std::path::Path;
22use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
23
24use memmap2::{MmapMut, MmapOptions};
25
26use crate::shared_ring::RingError;
27
28/// Magic identifying a `FrameRegion` layout. ASCII "FRGN" + version.
29pub const FRAME_REGION_MAGIC: u64 = 0x4652_474e_0000_0001;
30
31/// Free-list sentinel: "no next block".
32const NIL: u32 = u32::MAX;
33
34/// Smallest block: must hold the 4-byte free-list link.
35pub const MIN_BLOCK_SIZE: usize = 8;
36
37#[inline]
38fn pack(counter: u32, index: u32) -> u64 {
39    ((counter as u64) << 32) | (index as u64)
40}
41#[inline]
42fn unpack(v: u64) -> (u32, u32) {
43    ((v >> 32) as u32, v as u32)
44}
45
46/// Header: metadata line, then the bump cursor and the free-list head
47/// each on their own cache line so allocators and freers do not
48/// false-share.
49#[repr(C, align(64))]
50struct FrameRegionHeader {
51    magic: AtomicU64,
52    block_size: u64,
53    block_count: u64,
54    _pad_meta: [u8; 64 - 24],
55    /// Bump high-water mark (next never-yet-allocated block).
56    bump_next: AtomicU32,
57    _pad_bump: [u8; 64 - 4],
58    /// Treiber-stack free-list head, ABA-tagged (`counter << 32 | idx`).
59    free_head: AtomicU64,
60    _pad_free: [u8; 64 - 8],
61}
62
63/// Total mapped bytes for `block_count` blocks of `block_size`.
64pub const fn frame_region_file_size(block_size: usize, block_count: usize) -> usize {
65    std::mem::size_of::<FrameRegionHeader>() + block_size * block_count
66}
67
68#[allow(dead_code)]
69enum RegionBacking {
70    Anon(MmapMut),
71    File(File, MmapMut),
72    Shm(crate::shm_file::ShmFile),
73}
74
75/// Concurrent fixed-block region. Multi-producer `alloc`,
76/// multi-consumer `free`, any-order reclaim.
77pub struct FrameRegion {
78    _backing: RegionBacking,
79    raw_ptr: *mut u8,
80    block_size: usize,
81    block_count: usize,
82    blocks_base: usize,
83}
84
85unsafe impl Send for FrameRegion {}
86unsafe impl Sync for FrameRegion {}
87
88fn validate(block_size: usize, block_count: usize) -> Result<(), RingError> {
89    if block_size < MIN_BLOCK_SIZE || !block_size.is_multiple_of(8) {
90        return Err(RingError::LayoutMismatch);
91    }
92    if block_count < 1 || block_count >= NIL as usize {
93        return Err(RingError::LayoutMismatch);
94    }
95    Ok(())
96}
97
98/// Lay out a fresh region. The magic is published last with `Release`, because
99/// attachers on every backing spin on it and must observe the cursors first.
100unsafe fn init_region(ptr: *mut u8, block_size: usize, block_count: usize) {
101    unsafe {
102        std::ptr::write(ptr as *mut FrameRegionHeader, FrameRegionHeader {
103            magic: AtomicU64::new(0),
104            block_size: block_size as u64,
105            block_count: block_count as u64,
106            _pad_meta: [0; 64 - 24],
107            bump_next: AtomicU32::new(0),
108            _pad_bump: [0; 64 - 4],
109            free_head: AtomicU64::new(pack(0, NIL)),
110            _pad_free: [0; 64 - 8],
111        });
112        (*(ptr as *const FrameRegionHeader))
113            .magic
114            .store(FRAME_REGION_MAGIC, std::sync::atomic::Ordering::Release);
115    }
116}
117
118impl FrameRegion {
119    /// Anonymous in-process region.
120    pub fn create_anon(block_size: usize, block_count: usize) -> Result<Self, RingError> {
121        validate(block_size, block_count)?;
122        let total = frame_region_file_size(block_size, block_count);
123        let mut mmap = MmapOptions::new().len(total).map_anon()?;
124        unsafe { init_region(mmap.as_mut_ptr(), block_size, block_count) };
125        let raw_ptr = mmap.as_mut_ptr();
126        Ok(Self::from_parts(RegionBacking::Anon(mmap), raw_ptr, block_size, block_count))
127    }
128
129    /// File-backed region; cross-process via the page cache.
130    pub fn create(
131        path: impl AsRef<Path>, block_size: usize, block_count: usize,
132    ) -> Result<Self, RingError> {
133        validate(block_size, block_count)?;
134        let total = frame_region_file_size(block_size, block_count);
135        let file = OpenOptions::new()
136            .read(true).write(true).create(true).truncate(true)
137            .open(path.as_ref())?;
138        file.set_len(total as u64)?;
139        let mut mmap = unsafe { MmapOptions::new().len(total).map_mut(&file)? };
140        unsafe { init_region(mmap.as_mut_ptr(), block_size, block_count) };
141        let raw_ptr = mmap.as_mut_ptr();
142        Ok(Self::from_parts(RegionBacking::File(file, mmap), raw_ptr, block_size, block_count))
143    }
144
145    /// Open an existing file-backed region. Validates the header.
146    pub fn open(
147        path: impl AsRef<Path>, block_size: usize, block_count: usize,
148    ) -> Result<Self, RingError> {
149        validate(block_size, block_count)?;
150        let total = frame_region_file_size(block_size, block_count);
151        let file = OpenOptions::new().read(true).write(true).open(path.as_ref())?;
152        if (file.metadata()?.len() as usize) < total {
153            return Err(RingError::LayoutMismatch);
154        }
155        let mut mmap = unsafe { MmapOptions::new().len(total).map_mut(&file)? };
156        Self::check_header(mmap.as_ptr(), block_size, block_count)?;
157        let raw_ptr = mmap.as_mut_ptr();
158        Ok(Self::from_parts(RegionBacking::File(file, mmap), raw_ptr, block_size, block_count))
159    }
160
161    /// Build a region on a named RAM-resident shared-memory backing.
162    pub fn create_from_shm(
163        mut shm: crate::shm_file::ShmFile, block_size: usize, block_count: usize,
164    ) -> Result<Self, RingError> {
165        validate(block_size, block_count)?;
166        if shm.len() < frame_region_file_size(block_size, block_count) {
167            return Err(RingError::LayoutMismatch);
168        }
169        let raw_ptr = shm.as_mut_slice().as_mut_ptr();
170        unsafe { init_region(raw_ptr, block_size, block_count) };
171        Ok(Self::from_parts(RegionBacking::Shm(shm), raw_ptr, block_size, block_count))
172    }
173
174    /// Open an existing named ShmFs-backed region (no re-init).
175    pub fn open_from_shm(
176        mut shm: crate::shm_file::ShmFile, block_size: usize, block_count: usize,
177    ) -> Result<Self, RingError> {
178        validate(block_size, block_count)?;
179        if shm.len() < frame_region_file_size(block_size, block_count) {
180            return Err(RingError::LayoutMismatch);
181        }
182        let raw_ptr = shm.as_mut_slice().as_mut_ptr();
183        Self::check_header(raw_ptr, block_size, block_count)?;
184        Ok(Self::from_parts(RegionBacking::Shm(shm), raw_ptr, block_size, block_count))
185    }
186
187    /// Create-or-open a named ShmFs frame region. The first attacher
188    /// CAS-initialises the layout and publishes the magic; racing
189    /// attachers spin until it lands, so a late-joining consumer never
190    /// wipes a region a producer already filled. This is the shared
191    /// payload region the cross-process offset-frame path needs: the
192    /// producer create-or-opens it on the first offset `send_frame`,
193    /// and every consumer create-or-opens the SAME region on the first
194    /// offset `recv_frame` (the descriptor it popped implies the
195    /// producer already created it).
196    pub fn create_or_open_shm(
197        name: &str, block_size: usize, block_count: usize,
198    ) -> Result<Self, RingError> {
199        validate(block_size, block_count)?;
200        let total = frame_region_file_size(block_size, block_count);
201        let mut shm = crate::shm_file::ShmFile::create_or_open_named(name, total)
202            .map_err(|_| RingError::LayoutMismatch)?;
203        if shm.len() < total {
204            return Err(RingError::LayoutMismatch);
205        }
206        let raw_ptr = shm.as_mut_slice().as_mut_ptr();
207        Self::guarded_init_or_attach(raw_ptr, block_size, block_count)?;
208        Ok(Self::from_parts(RegionBacking::Shm(shm), raw_ptr, block_size, block_count))
209    }
210
211    /// Create-or-open a file-backed frame region: the file-locale peer
212    /// of [`create_or_open_shm`](Self::create_or_open_shm), for rings
213    /// backed by [`AdaptiveRing::create`] / `open`.
214    pub fn create_or_open_file(
215        path: impl AsRef<Path>, block_size: usize, block_count: usize,
216    ) -> Result<Self, RingError> {
217        validate(block_size, block_count)?;
218        let total = frame_region_file_size(block_size, block_count);
219        let file = OpenOptions::new()
220            .read(true).write(true).create(true).truncate(false)
221            .open(path.as_ref())?;
222        if (file.metadata()?.len() as usize) < total {
223            file.set_len(total as u64)?;
224        }
225        let mut mmap = unsafe { MmapOptions::new().len(total).map_mut(&file)? };
226        let raw_ptr = mmap.as_mut_ptr();
227        Self::guarded_init_or_attach(raw_ptr, block_size, block_count)?;
228        Ok(Self::from_parts(RegionBacking::File(file, mmap), raw_ptr, block_size, block_count))
229    }
230
231    /// CAS-guarded init used by both create-or-open paths: the winner of
232    /// the `magic: 0 -> in-progress` CAS writes the geometry + cursors
233    /// and publishes `FRAME_REGION_MAGIC` (Release); racing attachers
234    /// spin until they observe it (Acquire), then both validate the
235    /// geometry matches what the caller asked for.
236    fn guarded_init_or_attach(
237        raw_ptr: *mut u8, block_size: usize, block_count: usize,
238    ) -> Result<(), RingError> {
239        const INIT_INPROGRESS: u64 = 1;
240        let h = unsafe { &*(raw_ptr as *const FrameRegionHeader) };
241        if h
242            .magic
243            .compare_exchange(0, INIT_INPROGRESS, Ordering::AcqRel, Ordering::Acquire)
244            .is_ok()
245        {
246            unsafe {
247                let hdr = raw_ptr as *mut FrameRegionHeader;
248                (*hdr).block_size = block_size as u64;
249                (*hdr).block_count = block_count as u64;
250                (*hdr).bump_next.store(0, Ordering::Relaxed);
251                (*hdr).free_head.store(pack(0, NIL), Ordering::Relaxed);
252            }
253            h.magic.store(FRAME_REGION_MAGIC, Ordering::Release);
254        } else {
255            let mut spins = 0u32;
256            while h.magic.load(Ordering::Acquire) != FRAME_REGION_MAGIC {
257                std::hint::spin_loop();
258                spins += 1;
259                if spins > 100_000_000 {
260                    return Err(RingError::LayoutMismatch);
261                }
262            }
263        }
264        if h.block_size != block_size as u64 || h.block_count != block_count as u64 {
265            return Err(RingError::LayoutMismatch);
266        }
267        Ok(())
268    }
269
270    fn from_parts(
271        backing: RegionBacking, raw_ptr: *mut u8, block_size: usize, block_count: usize,
272    ) -> Self {
273        Self {
274            _backing: backing, raw_ptr, block_size, block_count,
275            blocks_base: std::mem::size_of::<FrameRegionHeader>(),
276        }
277    }
278
279    fn check_header(ptr: *const u8, block_size: usize, block_count: usize) -> Result<(), RingError> {
280        let h = unsafe { &*(ptr as *const FrameRegionHeader) };
281        if h.magic.load(Ordering::Acquire) != FRAME_REGION_MAGIC
282            || h.block_size != block_size as u64
283            || h.block_count != block_count as u64
284        {
285            return Err(RingError::LayoutMismatch);
286        }
287        Ok(())
288    }
289
290    /// Largest payload a block holds.
291    pub fn block_size(&self) -> usize { self.block_size }
292    /// Number of blocks.
293    pub fn block_count(&self) -> usize { self.block_count }
294
295    fn header(&self) -> &FrameRegionHeader {
296        unsafe { &*(self.raw_ptr as *const FrameRegionHeader) }
297    }
298
299    fn block_ptr(&self, idx: u32) -> *mut u8 {
300        unsafe { self.raw_ptr.add(self.blocks_base + idx as usize * self.block_size) }
301    }
302
303    /// The block's first 4 bytes reinterpreted as the free-list link
304    /// (only meaningful while the block is free).
305    fn next_link(&self, idx: u32) -> &AtomicU32 {
306        unsafe { &*(self.block_ptr(idx) as *const AtomicU32) }
307    }
308
309    /// Allocate a block. Free list first, then bump. `None` when full.
310    pub fn alloc(&self) -> Option<u32> {
311        loop {
312            let head = self.header().free_head.load(Ordering::Acquire);
313            let (counter, idx) = unpack(head);
314            if idx == NIL {
315                break;
316            }
317            let next = self.next_link(idx).load(Ordering::Acquire);
318            let new_head = pack(counter.wrapping_add(1), next);
319            if self.header().free_head.compare_exchange(
320                head, new_head, Ordering::AcqRel, Ordering::Acquire,
321            ).is_ok() {
322                return Some(idx);
323            }
324        }
325        let idx = self.header().bump_next.fetch_add(1, Ordering::AcqRel);
326        if idx >= self.block_count as u32 {
327            self.header().bump_next.fetch_sub(1, Ordering::AcqRel);
328            return None;
329        }
330        Some(idx)
331    }
332
333    /// Return a block to the free list. Any consumer may free any block.
334    pub fn free(&self, idx: u32) {
335        if idx as usize >= self.block_count {
336            return;
337        }
338        loop {
339            let head = self.header().free_head.load(Ordering::Acquire);
340            let (counter, old_top) = unpack(head);
341            self.next_link(idx).store(old_top, Ordering::Release);
342            let new_head = pack(counter.wrapping_add(1), idx);
343            if self.header().free_head.compare_exchange(
344                head, new_head, Ordering::AcqRel, Ordering::Acquire,
345            ).is_ok() {
346                return;
347            }
348        }
349    }
350
351    /// Copy `payload` into block `idx`. Caller guarantees
352    /// `payload.len() <= block_size`.
353    pub fn write_block(&self, idx: u32, payload: &[u8]) {
354        debug_assert!(payload.len() <= self.block_size);
355        unsafe {
356            std::ptr::copy_nonoverlapping(
357                payload.as_ptr(), self.block_ptr(idx), payload.len(),
358            );
359        }
360    }
361
362    /// Copy `len` bytes out of block `idx` into `out` (appended).
363    pub fn read_block_into(&self, idx: u32, len: usize, out: &mut Vec<u8>) {
364        debug_assert!(len <= self.block_size);
365        out.reserve(len);
366        unsafe {
367            std::ptr::copy_nonoverlapping(
368                self.block_ptr(idx),
369                out.spare_capacity_mut().as_mut_ptr() as *mut u8,
370                len,
371            );
372            let new_len = out.len() + len;
373            out.set_len(new_len);
374        }
375    }
376}
377
378#[cfg(test)]
379mod tests {
380    use super::*;
381    use std::sync::Arc;
382    use std::sync::atomic::AtomicUsize;
383    use std::thread;
384
385    #[test]
386    fn alloc_write_read_free_cycle() {
387        let r = FrameRegion::create_anon(256, 8).unwrap();
388        let idx = r.alloc().unwrap();
389        let payload = vec![0xABu8; 200];
390        r.write_block(idx, &payload);
391        let mut out = Vec::new();
392        r.read_block_into(idx, 200, &mut out);
393        assert_eq!(out, payload);
394        r.free(idx);
395        // Freed block is reused by the next alloc.
396        let idx2 = r.alloc().unwrap();
397        assert_eq!(idx2, idx, "freed block returns to the stack");
398    }
399
400    #[test]
401    fn exhausts_then_full() {
402        let r = FrameRegion::create_anon(64, 4).unwrap();
403        let a: Vec<u32> = (0..4).map(|_| r.alloc().unwrap()).collect();
404        assert_eq!(a.len(), 4);
405        assert!(r.alloc().is_none(), "region full");
406        r.free(a[1]);
407        assert!(r.alloc().is_some(), "freeing reopens a block");
408    }
409
410    #[test]
411    fn concurrent_alloc_free_no_double_issue() {
412        // Many threads alloc + free in a loop; assert no index is ever
413        // held by two threads at once (a double-issue would corrupt).
414        let r = Arc::new(FrameRegion::create_anon(64, 64).unwrap());
415        let held: Arc<Vec<AtomicUsize>> =
416            Arc::new((0..64).map(|_| AtomicUsize::new(0)).collect());
417        let mut handles = Vec::new();
418        for _ in 0..8 {
419            let r = r.clone();
420            let held = held.clone();
421            handles.push(thread::spawn(move || {
422                for _ in 0..20_000 {
423                    if let Some(idx) = r.alloc() {
424                        let prev = held[idx as usize].fetch_add(1, Ordering::AcqRel);
425                        assert_eq!(prev, 0, "block {idx} double-issued");
426                        held[idx as usize].fetch_sub(1, Ordering::AcqRel);
427                        r.free(idx);
428                    }
429                }
430            }));
431        }
432        for h in handles {
433            h.join().unwrap();
434        }
435    }
436
437    #[test]
438    fn shm_cross_handle() {
439        use crate::shm_file::ShmFile;
440        let nonce = std::time::SystemTime::now()
441            .duration_since(std::time::UNIX_EPOCH)
442            .map(|d| d.as_nanos())
443            .unwrap_or(0);
444        let name = format!("frame_region_{}_{}", std::process::id(), nonce);
445        let (bs, bc) = (256usize, 8usize);
446        let size = frame_region_file_size(bs, bc);
447        let a = FrameRegion::create_from_shm(
448            ShmFile::create_or_open_named(&name, size).unwrap(), bs, bc).unwrap();
449        let b = FrameRegion::open_from_shm(
450            ShmFile::create_or_open_named(&name, size).unwrap(), bs, bc).unwrap();
451        let idx = a.alloc().unwrap();
452        a.write_block(idx, b"shared across handles");
453        let mut out = Vec::new();
454        b.read_block_into(idx, 21, &mut out);
455        assert_eq!(out, b"shared across handles");
456    }
457
458    #[test]
459    fn rejects_bad_params() {
460        assert!(matches!(FrameRegion::create_anon(7, 8), Err(RingError::LayoutMismatch)));
461        assert!(matches!(FrameRegion::create_anon(64, 0), Err(RingError::LayoutMismatch)));
462    }
463}