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
98unsafe fn init_region(ptr: *mut u8, block_size: usize, block_count: usize) {
99    unsafe {
100        std::ptr::write(ptr as *mut FrameRegionHeader, FrameRegionHeader {
101            magic: AtomicU64::new(FRAME_REGION_MAGIC),
102            block_size: block_size as u64,
103            block_count: block_count as u64,
104            _pad_meta: [0; 64 - 24],
105            bump_next: AtomicU32::new(0),
106            _pad_bump: [0; 64 - 4],
107            free_head: AtomicU64::new(pack(0, NIL)),
108            _pad_free: [0; 64 - 8],
109        });
110    }
111}
112
113impl FrameRegion {
114    /// Anonymous in-process region.
115    pub fn create_anon(block_size: usize, block_count: usize) -> Result<Self, RingError> {
116        validate(block_size, block_count)?;
117        let total = frame_region_file_size(block_size, block_count);
118        let mut mmap = MmapOptions::new().len(total).map_anon()?;
119        unsafe { init_region(mmap.as_mut_ptr(), block_size, block_count) };
120        let raw_ptr = mmap.as_mut_ptr();
121        Ok(Self::from_parts(RegionBacking::Anon(mmap), raw_ptr, block_size, block_count))
122    }
123
124    /// File-backed region; cross-process via the page cache.
125    pub fn create(
126        path: impl AsRef<Path>, block_size: usize, block_count: usize,
127    ) -> Result<Self, RingError> {
128        validate(block_size, block_count)?;
129        let total = frame_region_file_size(block_size, block_count);
130        let file = OpenOptions::new()
131            .read(true).write(true).create(true).truncate(true)
132            .open(path.as_ref())?;
133        file.set_len(total as u64)?;
134        let mut mmap = unsafe { MmapOptions::new().len(total).map_mut(&file)? };
135        unsafe { init_region(mmap.as_mut_ptr(), block_size, block_count) };
136        let raw_ptr = mmap.as_mut_ptr();
137        Ok(Self::from_parts(RegionBacking::File(file, mmap), raw_ptr, block_size, block_count))
138    }
139
140    /// Open an existing file-backed region. Validates the header.
141    pub fn open(
142        path: impl AsRef<Path>, block_size: usize, block_count: usize,
143    ) -> Result<Self, RingError> {
144        validate(block_size, block_count)?;
145        let total = frame_region_file_size(block_size, block_count);
146        let file = OpenOptions::new().read(true).write(true).open(path.as_ref())?;
147        if (file.metadata()?.len() as usize) < total {
148            return Err(RingError::LayoutMismatch);
149        }
150        let mut mmap = unsafe { MmapOptions::new().len(total).map_mut(&file)? };
151        Self::check_header(mmap.as_ptr(), block_size, block_count)?;
152        let raw_ptr = mmap.as_mut_ptr();
153        Ok(Self::from_parts(RegionBacking::File(file, mmap), raw_ptr, block_size, block_count))
154    }
155
156    /// Build a region on a named RAM-resident shared-memory backing.
157    pub fn create_from_shm(
158        mut shm: crate::shm_file::ShmFile, block_size: usize, block_count: usize,
159    ) -> Result<Self, RingError> {
160        validate(block_size, block_count)?;
161        if shm.len() < frame_region_file_size(block_size, block_count) {
162            return Err(RingError::LayoutMismatch);
163        }
164        let raw_ptr = shm.as_mut_slice().as_mut_ptr();
165        unsafe { init_region(raw_ptr, block_size, block_count) };
166        Ok(Self::from_parts(RegionBacking::Shm(shm), raw_ptr, block_size, block_count))
167    }
168
169    /// Open an existing named ShmFs-backed region (no re-init).
170    pub fn open_from_shm(
171        mut shm: crate::shm_file::ShmFile, block_size: usize, block_count: usize,
172    ) -> Result<Self, RingError> {
173        validate(block_size, block_count)?;
174        if shm.len() < frame_region_file_size(block_size, block_count) {
175            return Err(RingError::LayoutMismatch);
176        }
177        let raw_ptr = shm.as_mut_slice().as_mut_ptr();
178        Self::check_header(raw_ptr, block_size, block_count)?;
179        Ok(Self::from_parts(RegionBacking::Shm(shm), raw_ptr, block_size, block_count))
180    }
181
182    /// Create-or-open a named ShmFs frame region. The first attacher
183    /// CAS-initialises the layout and publishes the magic; racing
184    /// attachers spin until it lands, so a late-joining consumer never
185    /// wipes a region a producer already filled. This is the shared
186    /// payload region the cross-process offset-frame path needs: the
187    /// producer create-or-opens it on the first offset `send_frame`,
188    /// and every consumer create-or-opens the SAME region on the first
189    /// offset `recv_frame` (the descriptor it popped implies the
190    /// producer already created it).
191    pub fn create_or_open_shm(
192        name: &str, block_size: usize, block_count: usize,
193    ) -> Result<Self, RingError> {
194        validate(block_size, block_count)?;
195        let total = frame_region_file_size(block_size, block_count);
196        let mut shm = crate::shm_file::ShmFile::create_or_open_named(name, total)
197            .map_err(|_| RingError::LayoutMismatch)?;
198        if shm.len() < total {
199            return Err(RingError::LayoutMismatch);
200        }
201        let raw_ptr = shm.as_mut_slice().as_mut_ptr();
202        Self::guarded_init_or_attach(raw_ptr, block_size, block_count)?;
203        Ok(Self::from_parts(RegionBacking::Shm(shm), raw_ptr, block_size, block_count))
204    }
205
206    /// Create-or-open a file-backed frame region: the file-locale peer
207    /// of [`create_or_open_shm`](Self::create_or_open_shm), for rings
208    /// backed by [`AdaptiveRing::create`] / `open`.
209    pub fn create_or_open_file(
210        path: impl AsRef<Path>, block_size: usize, block_count: usize,
211    ) -> Result<Self, RingError> {
212        validate(block_size, block_count)?;
213        let total = frame_region_file_size(block_size, block_count);
214        let file = OpenOptions::new()
215            .read(true).write(true).create(true).truncate(false)
216            .open(path.as_ref())?;
217        if (file.metadata()?.len() as usize) < total {
218            file.set_len(total as u64)?;
219        }
220        let mut mmap = unsafe { MmapOptions::new().len(total).map_mut(&file)? };
221        let raw_ptr = mmap.as_mut_ptr();
222        Self::guarded_init_or_attach(raw_ptr, block_size, block_count)?;
223        Ok(Self::from_parts(RegionBacking::File(file, mmap), raw_ptr, block_size, block_count))
224    }
225
226    /// CAS-guarded init used by both create-or-open paths: the winner of
227    /// the `magic: 0 -> in-progress` CAS writes the geometry + cursors
228    /// and publishes `FRAME_REGION_MAGIC` (Release); racing attachers
229    /// spin until they observe it (Acquire), then both validate the
230    /// geometry matches what the caller asked for.
231    fn guarded_init_or_attach(
232        raw_ptr: *mut u8, block_size: usize, block_count: usize,
233    ) -> Result<(), RingError> {
234        const INIT_INPROGRESS: u64 = 1;
235        let h = unsafe { &*(raw_ptr as *const FrameRegionHeader) };
236        if h
237            .magic
238            .compare_exchange(0, INIT_INPROGRESS, Ordering::AcqRel, Ordering::Acquire)
239            .is_ok()
240        {
241            unsafe {
242                let hdr = raw_ptr as *mut FrameRegionHeader;
243                (*hdr).block_size = block_size as u64;
244                (*hdr).block_count = block_count as u64;
245                (*hdr).bump_next.store(0, Ordering::Relaxed);
246                (*hdr).free_head.store(pack(0, NIL), Ordering::Relaxed);
247            }
248            h.magic.store(FRAME_REGION_MAGIC, Ordering::Release);
249        } else {
250            let mut spins = 0u32;
251            while h.magic.load(Ordering::Acquire) != FRAME_REGION_MAGIC {
252                std::hint::spin_loop();
253                spins += 1;
254                if spins > 100_000_000 {
255                    return Err(RingError::LayoutMismatch);
256                }
257            }
258        }
259        if h.block_size != block_size as u64 || h.block_count != block_count as u64 {
260            return Err(RingError::LayoutMismatch);
261        }
262        Ok(())
263    }
264
265    fn from_parts(
266        backing: RegionBacking, raw_ptr: *mut u8, block_size: usize, block_count: usize,
267    ) -> Self {
268        Self {
269            _backing: backing, raw_ptr, block_size, block_count,
270            blocks_base: std::mem::size_of::<FrameRegionHeader>(),
271        }
272    }
273
274    fn check_header(ptr: *const u8, block_size: usize, block_count: usize) -> Result<(), RingError> {
275        let h = unsafe { &*(ptr as *const FrameRegionHeader) };
276        if h.magic.load(Ordering::Acquire) != FRAME_REGION_MAGIC
277            || h.block_size != block_size as u64
278            || h.block_count != block_count as u64
279        {
280            return Err(RingError::LayoutMismatch);
281        }
282        Ok(())
283    }
284
285    /// Largest payload a block holds.
286    pub fn block_size(&self) -> usize { self.block_size }
287    /// Number of blocks.
288    pub fn block_count(&self) -> usize { self.block_count }
289
290    fn header(&self) -> &FrameRegionHeader {
291        unsafe { &*(self.raw_ptr as *const FrameRegionHeader) }
292    }
293
294    fn block_ptr(&self, idx: u32) -> *mut u8 {
295        unsafe { self.raw_ptr.add(self.blocks_base + idx as usize * self.block_size) }
296    }
297
298    /// The block's first 4 bytes reinterpreted as the free-list link
299    /// (only meaningful while the block is free).
300    fn next_link(&self, idx: u32) -> &AtomicU32 {
301        unsafe { &*(self.block_ptr(idx) as *const AtomicU32) }
302    }
303
304    /// Allocate a block. Free list first, then bump. `None` when full.
305    pub fn alloc(&self) -> Option<u32> {
306        loop {
307            let head = self.header().free_head.load(Ordering::Acquire);
308            let (counter, idx) = unpack(head);
309            if idx == NIL {
310                break;
311            }
312            let next = self.next_link(idx).load(Ordering::Acquire);
313            let new_head = pack(counter.wrapping_add(1), next);
314            if self.header().free_head.compare_exchange(
315                head, new_head, Ordering::AcqRel, Ordering::Acquire,
316            ).is_ok() {
317                return Some(idx);
318            }
319        }
320        let idx = self.header().bump_next.fetch_add(1, Ordering::AcqRel);
321        if idx >= self.block_count as u32 {
322            self.header().bump_next.fetch_sub(1, Ordering::AcqRel);
323            return None;
324        }
325        Some(idx)
326    }
327
328    /// Return a block to the free list. Any consumer may free any block.
329    pub fn free(&self, idx: u32) {
330        if idx as usize >= self.block_count {
331            return;
332        }
333        loop {
334            let head = self.header().free_head.load(Ordering::Acquire);
335            let (counter, old_top) = unpack(head);
336            self.next_link(idx).store(old_top, Ordering::Release);
337            let new_head = pack(counter.wrapping_add(1), idx);
338            if self.header().free_head.compare_exchange(
339                head, new_head, Ordering::AcqRel, Ordering::Acquire,
340            ).is_ok() {
341                return;
342            }
343        }
344    }
345
346    /// Copy `payload` into block `idx`. Caller guarantees
347    /// `payload.len() <= block_size`.
348    pub fn write_block(&self, idx: u32, payload: &[u8]) {
349        debug_assert!(payload.len() <= self.block_size);
350        unsafe {
351            std::ptr::copy_nonoverlapping(
352                payload.as_ptr(), self.block_ptr(idx), payload.len(),
353            );
354        }
355    }
356
357    /// Copy `len` bytes out of block `idx` into `out` (appended).
358    pub fn read_block_into(&self, idx: u32, len: usize, out: &mut Vec<u8>) {
359        debug_assert!(len <= self.block_size);
360        out.reserve(len);
361        unsafe {
362            std::ptr::copy_nonoverlapping(
363                self.block_ptr(idx),
364                out.spare_capacity_mut().as_mut_ptr() as *mut u8,
365                len,
366            );
367            let new_len = out.len() + len;
368            out.set_len(new_len);
369        }
370    }
371}
372
373#[cfg(test)]
374mod tests {
375    use super::*;
376    use std::sync::Arc;
377    use std::sync::atomic::AtomicUsize;
378    use std::thread;
379
380    #[test]
381    fn alloc_write_read_free_cycle() {
382        let r = FrameRegion::create_anon(256, 8).unwrap();
383        let idx = r.alloc().unwrap();
384        let payload = vec![0xABu8; 200];
385        r.write_block(idx, &payload);
386        let mut out = Vec::new();
387        r.read_block_into(idx, 200, &mut out);
388        assert_eq!(out, payload);
389        r.free(idx);
390        // Freed block is reused by the next alloc.
391        let idx2 = r.alloc().unwrap();
392        assert_eq!(idx2, idx, "freed block returns to the stack");
393    }
394
395    #[test]
396    fn exhausts_then_full() {
397        let r = FrameRegion::create_anon(64, 4).unwrap();
398        let a: Vec<u32> = (0..4).map(|_| r.alloc().unwrap()).collect();
399        assert_eq!(a.len(), 4);
400        assert!(r.alloc().is_none(), "region full");
401        r.free(a[1]);
402        assert!(r.alloc().is_some(), "freeing reopens a block");
403    }
404
405    #[test]
406    fn concurrent_alloc_free_no_double_issue() {
407        // Many threads alloc + free in a loop; assert no index is ever
408        // held by two threads at once (a double-issue would corrupt).
409        let r = Arc::new(FrameRegion::create_anon(64, 64).unwrap());
410        let held: Arc<Vec<AtomicUsize>> =
411            Arc::new((0..64).map(|_| AtomicUsize::new(0)).collect());
412        let mut handles = Vec::new();
413        for _ in 0..8 {
414            let r = r.clone();
415            let held = held.clone();
416            handles.push(thread::spawn(move || {
417                for _ in 0..20_000 {
418                    if let Some(idx) = r.alloc() {
419                        let prev = held[idx as usize].fetch_add(1, Ordering::AcqRel);
420                        assert_eq!(prev, 0, "block {idx} double-issued");
421                        held[idx as usize].fetch_sub(1, Ordering::AcqRel);
422                        r.free(idx);
423                    }
424                }
425            }));
426        }
427        for h in handles {
428            h.join().unwrap();
429        }
430    }
431
432    #[test]
433    fn shm_cross_handle() {
434        use crate::shm_file::ShmFile;
435        let nonce = std::time::SystemTime::now()
436            .duration_since(std::time::UNIX_EPOCH)
437            .map(|d| d.as_nanos())
438            .unwrap_or(0);
439        let name = format!("frame_region_{}_{}", std::process::id(), nonce);
440        let (bs, bc) = (256usize, 8usize);
441        let size = frame_region_file_size(bs, bc);
442        let a = FrameRegion::create_from_shm(
443            ShmFile::create_or_open_named(&name, size).unwrap(), bs, bc).unwrap();
444        let b = FrameRegion::open_from_shm(
445            ShmFile::create_or_open_named(&name, size).unwrap(), bs, bc).unwrap();
446        let idx = a.alloc().unwrap();
447        a.write_block(idx, b"shared across handles");
448        let mut out = Vec::new();
449        b.read_block_into(idx, 21, &mut out);
450        assert_eq!(out, b"shared across handles");
451    }
452
453    #[test]
454    fn rejects_bad_params() {
455        assert!(matches!(FrameRegion::create_anon(7, 8), Err(RingError::LayoutMismatch)));
456        assert!(matches!(FrameRegion::create_anon(64, 0), Err(RingError::LayoutMismatch)));
457    }
458}