Skip to main content

rustorb_rtps/
shm.rs

1//! A shared memory transport for participants of rustorb-dds on the same
2//! host (feature `shm`).
3//!
4//! Each participant has a receive segment: a file in a shared memory
5//! directory (`/dev/shm` on Linux, else the temporary directory), mapped
6//! by every process that sends to it, holding a ring buffer of RTPS
7//! messages; and a UDP socket on the loopback interface, whose port the
8//! segment gives, that senders ring after writing. Senders take turns through a
9//! lock in the segment. A message that does not fit, after a short wait
10//! for the receiver to make room, is dropped, like a datagram lost on the
11//! way: the reliable protocol repairs it.
12//!
13//! The participant announces its segment with locators of the vendor
14//! kind [`Locator::KIND_SHM`] (the address holds the host and the segment,
15//! the port tells metatraffic from user traffic), besides its UDP ones.
16//! Other implementations ignore them. A sender uses a peer's shared memory
17//! locator when the host is its own and it can open the segment; else the
18//! peer's UDP locators ([`ShmTransport::select`]).
19
20use std::collections::HashMap;
21use std::fs::{File, OpenOptions};
22use std::io;
23use std::net::{Ipv4Addr, SocketAddr, UdpSocket};
24use std::path::{Path, PathBuf};
25use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
26use std::sync::{Arc, Mutex};
27use std::thread::JoinHandle;
28use std::time::{Duration, Instant};
29
30use memmap2::MmapMut;
31
32use crate::udp::{Channel, Datagram, Sink};
33use crate::{GuidPrefix, Locator};
34
35/// The port of a shared memory locator for metatraffic.
36pub const PORT_METATRAFFIC: u32 = 1;
37/// The port of a shared memory locator for user traffic.
38pub const PORT_USER: u32 = 2;
39
40/// "RSHM" and the layout version.
41const MAGIC: u64 = 0x5253_484d_0000_0001;
42/// The header: magic, capacity, lock, head, tail and the port of the
43/// receiver's bell, each on its own word.
44const HEADER: usize = 64;
45const OFF_MAGIC: usize = 0;
46const OFF_CAPACITY: usize = 8;
47const OFF_LOCK: usize = 16;
48const OFF_HEAD: usize = 24;
49const OFF_TAIL: usize = 32;
50const OFF_BELL: usize = 40;
51/// A record: its length and port, then the message, padded to 8.
52const RECORD_HEADER: usize = 8;
53/// The length that marks the rest of the buffer as unused.
54const WRAP: u32 = u32::MAX;
55/// How often the receive thread looks at the stop flag.
56const POLL: Duration = Duration::from_millis(100);
57/// How long a sender waits for the lock before it takes it from a holder
58/// that is gone.
59const LOCK_PATIENCE: Duration = Duration::from_millis(500);
60
61/// How long a send waits for room in a full ring before the message is
62/// dropped.
63const SEND_PATIENCE: Duration = Duration::from_millis(5);
64
65/// How the transport is set up.
66#[derive(Clone, Debug)]
67pub struct ShmConfig {
68    /// The directory of the segments: `/dev/shm` where it exists, else
69    /// the temporary directory.
70    pub directory: PathBuf,
71    /// The size of the receive buffer, in octets (default 4 MiB). A
72    /// message larger than a quarter of it cannot be sent this way.
73    pub capacity: usize,
74}
75
76impl Default for ShmConfig {
77    fn default() -> Self {
78        let shm = Path::new("/dev/shm");
79        ShmConfig {
80            directory: if shm.is_dir() {
81                shm.to_path_buf()
82            } else {
83                std::env::temp_dir()
84            },
85            capacity: 4 << 20,
86        }
87    }
88}
89
90/// An identifier of this host: from the machine id where there is one,
91/// else from the host name. Shared memory is tried only with peers of
92/// the same one.
93fn host_id() -> [u8; 8] {
94    let text = ["/etc/machine-id", "/var/lib/dbus/machine-id"]
95        .iter()
96        .find_map(|p| std::fs::read_to_string(p).ok())
97        .or_else(|| std::fs::read_to_string("/proc/sys/kernel/hostname").ok())
98        .or_else(|| std::env::var("HOSTNAME").ok())
99        .or_else(|| std::env::var("COMPUTERNAME").ok())
100        .unwrap_or_default();
101    fnv(text.trim().as_bytes()).to_be_bytes()
102}
103
104/// FNV-1a, 64 bits.
105fn fnv(b: &[u8]) -> u64 {
106    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
107    for x in b {
108        h ^= u64::from(*x);
109        h = h.wrapping_mul(0x0000_0100_0000_01b3);
110    }
111    h
112}
113
114fn segment_path(dir: &Path, segment: u64) -> PathBuf {
115    dir.join(format!("rustorb-dds-{segment:016x}"))
116}
117
118/// A mapped segment.
119struct Segment {
120    map: MmapMut,
121    capacity: usize,
122}
123
124// SAFETY: the shared words are accessed through atomics, the data under
125// the lock (writers) or below `head` (the reader).
126unsafe impl Send for Segment {}
127unsafe impl Sync for Segment {}
128
129impl Segment {
130    fn create(path: &Path, capacity: usize, bell: u16) -> io::Result<Segment> {
131        let file = OpenOptions::new()
132            .read(true)
133            .write(true)
134            .create_new(true)
135            .open(path)?;
136        file.set_len((HEADER + capacity) as u64)?;
137        let s = Segment::map(&file, capacity)?;
138        s.word(OFF_CAPACITY)
139            .store(capacity as u64, Ordering::Relaxed);
140        s.word(OFF_BELL).store(u64::from(bell), Ordering::Relaxed);
141        s.word(OFF_MAGIC).store(MAGIC, Ordering::Release);
142        Ok(s)
143    }
144
145    fn open(path: &Path) -> io::Result<Segment> {
146        let file = OpenOptions::new().read(true).write(true).open(path)?;
147        let len = file.metadata()?.len() as usize;
148        if len < HEADER {
149            return Err(io::Error::new(io::ErrorKind::InvalidData, "not a segment"));
150        }
151        let s = Segment::map(&file, len - HEADER)?;
152        if s.word(OFF_MAGIC).load(Ordering::Acquire) != MAGIC
153            || s.word(OFF_CAPACITY).load(Ordering::Relaxed) != (len - HEADER) as u64
154        {
155            return Err(io::Error::new(io::ErrorKind::InvalidData, "not a segment"));
156        }
157        Ok(s)
158    }
159
160    fn map(file: &File, capacity: usize) -> io::Result<Segment> {
161        // SAFETY: the file is a segment of this transport; other
162        // processes change it only through the protocol below.
163        let map = unsafe { MmapMut::map_mut(file) }?;
164        Ok(Segment { map, capacity })
165    }
166
167    fn word(&self, off: usize) -> &AtomicU64 {
168        // SAFETY: the mapping is page aligned and HEADER long at least;
169        // off is a multiple of 8 below HEADER.
170        unsafe { &*(self.map.as_ptr().add(off) as *const AtomicU64) }
171    }
172
173    /// The receiver's bell.
174    fn bell(&self) -> SocketAddr {
175        let port = self.word(OFF_BELL).load(Ordering::Relaxed) as u16;
176        SocketAddr::from((Ipv4Addr::LOCALHOST, port))
177    }
178
179    fn lock_word(&self) -> &AtomicU32 {
180        // SAFETY: as in `word`.
181        unsafe { &*(self.map.as_ptr().add(OFF_LOCK) as *const AtomicU32) }
182    }
183
184    fn data(&self) -> *mut u8 {
185        // SAFETY: HEADER is within the mapping.
186        unsafe { self.map.as_ptr().add(HEADER) as *mut u8 }
187    }
188
189    /// Takes the writers' lock; false if it cannot.
190    fn lock(&self) -> bool {
191        let me = std::process::id().max(1);
192        let lock = self.lock_word();
193        let start = Instant::now();
194        let mut spins = 0u32;
195        loop {
196            let held = lock.load(Ordering::Relaxed);
197            if held == 0 {
198                if lock
199                    .compare_exchange(0, me, Ordering::Acquire, Ordering::Relaxed)
200                    .is_ok()
201                {
202                    return true;
203                }
204            } else if start.elapsed() > LOCK_PATIENCE {
205                // A holder that is gone left it: on Linux, one with no
206                // /proc/<pid>; elsewhere, one that kept it far longer
207                // than a copy takes.
208                let gone = if Path::new("/proc/self").exists() {
209                    !Path::new(&format!("/proc/{held}")).exists()
210                } else {
211                    start.elapsed() > 4 * LOCK_PATIENCE
212                };
213                if gone
214                    && lock
215                        .compare_exchange(held, me, Ordering::Acquire, Ordering::Relaxed)
216                        .is_ok()
217                {
218                    return true;
219                }
220                if start.elapsed() > 8 * LOCK_PATIENCE {
221                    return false;
222                }
223            }
224            spins += 1;
225            if spins < 64 {
226                std::hint::spin_loop();
227            } else {
228                std::thread::yield_now();
229            }
230        }
231    }
232
233    fn unlock(&self) {
234        self.lock_word().store(0, Ordering::Release);
235    }
236
237    /// Puts a message in the ring; false if there is no room.
238    fn push(&self, port: u32, data: &[u8]) -> bool {
239        let need = RECORD_HEADER + data.len().next_multiple_of(8);
240        if need > self.capacity / 4 || !self.lock() {
241            return false;
242        }
243        let head = self.word(OFF_HEAD).load(Ordering::Relaxed);
244        let tail = self.word(OFF_TAIL).load(Ordering::Acquire);
245        let cap = self.capacity as u64;
246        let at = (head % cap) as usize;
247        let to_end = self.capacity - at;
248        let skip = if to_end < need { to_end } else { 0 };
249        if (head - tail) as usize + skip + need > self.capacity {
250            self.unlock();
251            return false;
252        }
253        let p = self.data();
254        // SAFETY: [at, at + to_end) and [0, need) are within the buffer,
255        // free (below tail + capacity), and only this writer, holding the
256        // lock, writes there.
257        unsafe {
258            let mut at = at;
259            if skip > 0 {
260                std::ptr::copy_nonoverlapping(WRAP.to_ne_bytes().as_ptr(), p.add(at), 4);
261                at = 0;
262            }
263            let len = data.len() as u32;
264            std::ptr::copy_nonoverlapping(len.to_ne_bytes().as_ptr(), p.add(at), 4);
265            std::ptr::copy_nonoverlapping(port.to_ne_bytes().as_ptr(), p.add(at + 4), 4);
266            std::ptr::copy_nonoverlapping(data.as_ptr(), p.add(at + RECORD_HEADER), data.len());
267        }
268        self.word(OFF_HEAD)
269            .store(head + (skip + need) as u64, Ordering::Release);
270        self.unlock();
271        true
272    }
273
274    /// Takes the messages in the ring, with their ports.
275    fn drain(&self, mut f: impl FnMut(u32, Vec<u8>)) {
276        let head = self.word(OFF_HEAD).load(Ordering::Acquire);
277        let mut tail = self.word(OFF_TAIL).load(Ordering::Relaxed);
278        let cap = self.capacity as u64;
279        let p = self.data();
280        while tail < head {
281            let at = (tail % cap) as usize;
282            let mut w = [0u8; 4];
283            // SAFETY: records below head are complete (Release/Acquire on
284            // head) and nobody writes them until tail passes them.
285            unsafe { std::ptr::copy_nonoverlapping(p.add(at), w.as_mut_ptr(), 4) };
286            let len = u32::from_ne_bytes(w);
287            if len == WRAP {
288                tail += (self.capacity - at) as u64;
289                continue;
290            }
291            let mut port = [0u8; 4];
292            let mut data = vec![0u8; len as usize];
293            // SAFETY: as above.
294            unsafe {
295                std::ptr::copy_nonoverlapping(p.add(at + 4), port.as_mut_ptr(), 4);
296                std::ptr::copy_nonoverlapping(
297                    p.add(at + RECORD_HEADER),
298                    data.as_mut_ptr(),
299                    data.len(),
300                );
301            }
302            tail += (RECORD_HEADER + (len as usize).next_multiple_of(8)) as u64;
303            // Freed at once, for a writer waiting for room.
304            self.word(OFF_TAIL).store(tail, Ordering::Release);
305            f(u32::from_ne_bytes(port), data);
306        }
307        self.word(OFF_TAIL).store(tail, Ordering::Release);
308    }
309}
310
311/// A peer's segment, opened on first use.
312struct Peer {
313    segment: Segment,
314}
315
316/// The shared memory transport of one participant.
317pub struct ShmTransport {
318    host: [u8; 8],
319    segment_id: u64,
320    directory: PathBuf,
321    path: PathBuf,
322    /// Peers by segment; `None` for one that could not be opened.
323    peers: Mutex<HashMap<u64, Option<Arc<Peer>>>>,
324    /// The pools of the samples sent by reference to this participant.
325    pools: Arc<Pools>,
326    /// Rings the peers' bells.
327    bell: UdpSocket,
328    stop: Arc<AtomicBool>,
329    thread: Option<JoinHandle<()>>,
330}
331
332impl std::fmt::Debug for ShmTransport {
333    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
334        f.debug_struct("ShmTransport")
335            .field("segment", &self.path)
336            .finish()
337    }
338}
339
340impl ShmTransport {
341    /// Creates the receive segment and socket of the participant `prefix`
342    /// and starts receiving: the messages go to `sink` (a [`Sink`], or the
343    /// sender of a queue), as datagrams of the unicast channels.
344    pub fn open(
345        config: &ShmConfig,
346        prefix: GuidPrefix,
347        sink: impl Into<Sink>,
348    ) -> io::Result<ShmTransport> {
349        let sink = sink.into();
350        let segment_id = fnv(&prefix.0) ^ u64::from(std::process::id());
351        let path = segment_path(&config.directory, segment_id);
352        let _ = std::fs::remove_file(&path);
353        let socket = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?;
354        socket.set_read_timeout(Some(POLL))?;
355        let port = socket.local_addr()?.port();
356        let segment = Arc::new(Segment::create(&path, config.capacity, port)?);
357        let bell = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?;
358        bell.set_nonblocking(true)?;
359        let stop = Arc::new(AtomicBool::new(false));
360        let thread = {
361            let stop = stop.clone();
362            std::thread::Builder::new()
363                .name("rtps-shm".into())
364                .spawn(move || receive_loop(&segment, &socket, &stop, &sink))?
365        };
366        Ok(ShmTransport {
367            host: host_id(),
368            segment_id,
369            directory: config.directory.clone(),
370            path,
371            peers: Mutex::new(HashMap::new()),
372            pools: Arc::new(Pools::new(&config.directory)),
373            bell,
374            stop,
375            thread: Some(thread),
376        })
377    }
378
379    fn locator(&self, port: u32) -> Locator {
380        let mut address = [0u8; 16];
381        address[..8].copy_from_slice(&self.host);
382        address[8..].copy_from_slice(&self.segment_id.to_be_bytes());
383        Locator {
384            kind: Locator::KIND_SHM,
385            port,
386            address,
387        }
388    }
389
390    /// The locator of the metatraffic.
391    pub fn metatraffic_locator(&self) -> Locator {
392        self.locator(PORT_METATRAFFIC)
393    }
394
395    /// The locator of the user traffic.
396    pub fn user_locator(&self) -> Locator {
397        self.locator(PORT_USER)
398    }
399
400    /// The peer behind a shared memory locator of this host, opened.
401    fn peer(&self, l: &Locator) -> Option<Arc<Peer>> {
402        if l.kind != Locator::KIND_SHM || l.address[..8] != self.host {
403            return None;
404        }
405        let id = u64::from_be_bytes(l.address[8..].try_into().ok()?);
406        let mut peers = self.peers.lock().ok()?;
407        peers
408            .entry(id)
409            .or_insert_with(|| {
410                Segment::open(&segment_path(&self.directory, id))
411                    .ok()
412                    .map(|segment| Arc::new(Peer { segment }))
413            })
414            .clone()
415    }
416
417    /// Of a peer's locators, those to send to: its shared memory ones if
418    /// one of them can be used, else the others.
419    pub fn select<'a>(&self, locators: &'a [Locator]) -> Vec<&'a Locator> {
420        let shm: Vec<&Locator> = locators.iter().filter(|l| self.peer(l).is_some()).collect();
421        if shm.is_empty() {
422            locators
423                .iter()
424                .filter(|l| l.kind != Locator::KIND_SHM)
425                .collect()
426        } else {
427            shm
428        }
429    }
430
431    /// Whether one of a peer's locators can be sent to by shared memory.
432    pub fn reaches(&self, locators: &[Locator]) -> bool {
433        locators.iter().any(|l| self.peer(l).is_some())
434    }
435
436    /// A pool of `slots` samples of up to `slot_size` octets, for a
437    /// writer to lend samples from.
438    pub fn create_pool(&self, slots: u32, slot_size: usize) -> io::Result<Arc<Pool>> {
439        Pool::create(&self.directory, slots, slot_size)
440    }
441
442    /// The pools of the samples that writers of this host send to this
443    /// participant by reference (see [`PoolLoan::reference`]).
444    pub fn pools(&self) -> Arc<Pools> {
445        self.pools.clone()
446    }
447
448    /// Sends one message to a shared memory locator. Fails with
449    /// [`io::ErrorKind::WouldBlock`] when the peer's buffer is full and
450    /// [`io::ErrorKind::Unsupported`] for a locator it cannot use.
451    pub fn send(&self, data: &[u8], to: &Locator) -> io::Result<()> {
452        let peer = self.peer(to).ok_or_else(|| {
453            io::Error::new(io::ErrorKind::Unsupported, "no such shared memory peer")
454        })?;
455        if !peer.segment.push(to.port, data) {
456            // Full: the peer drains it as it receives, so wait a little
457            // for room rather than lose the message and wait for a repair
458            // (#112).
459            let _ = self.bell.send_to(&[0], peer.segment.bell());
460            let start = Instant::now();
461            loop {
462                std::thread::yield_now();
463                if peer.segment.push(to.port, data) {
464                    break;
465                }
466                if start.elapsed() > SEND_PATIENCE {
467                    return Err(io::Error::new(
468                        io::ErrorKind::WouldBlock,
469                        "the shared memory buffer is full",
470                    ));
471                }
472            }
473        }
474        match self.bell.send_to(&[0], peer.segment.bell()) {
475            Ok(_) => Ok(()),
476            // The peer is busy or its socket is full: it drains the ring
477            // at its next wake-up anyway.
478            Err(e) if e.kind() == io::ErrorKind::WouldBlock => Ok(()),
479            Err(e) => {
480                // The peer is gone: forget it, so that the next send
481                // opens it again or falls back.
482                if let Ok(mut peers) = self.peers.lock() {
483                    peers.retain(|_, p| !p.as_ref().is_some_and(|p| Arc::ptr_eq(p, &peer)));
484                }
485                Err(e)
486            }
487        }
488    }
489}
490
491impl Drop for ShmTransport {
492    fn drop(&mut self) {
493        self.stop.store(true, Ordering::Relaxed);
494        if let Some(t) = self.thread.take() {
495            let _ = t.join();
496        }
497        // On Windows this fails while a peer still maps the file; the
498        // next participant with the same id removes it.
499        let _ = std::fs::remove_file(&self.path);
500    }
501}
502
503fn receive_loop(segment: &Segment, socket: &UdpSocket, stop: &AtomicBool, sink: &Sink) {
504    let mut buf = [0u8; 64];
505    let mut got = Vec::new();
506    let source = SocketAddr::from((Ipv4Addr::LOCALHOST, 0));
507    while !stop.load(Ordering::Relaxed) {
508        // A ring, or the poll interval, wakes it; then it drains the
509        // buffer, which may hold more than one message per ring.
510        let _ = socket.recv(&mut buf);
511        segment.drain(|port, data| {
512            let channel = if port == PORT_METATRAFFIC {
513                Channel::DiscoveryUnicast
514            } else {
515                Channel::UserUnicast
516            };
517            got.push(Datagram {
518                channel,
519                source,
520                data,
521            });
522        });
523        // Delivered once out of the ring: a handler may send.
524        let alone = got.len() == 1;
525        for d in got.drain(..) {
526            if !sink.deliver(d, alone) {
527                return;
528            }
529        }
530    }
531}
532
533/// "RPOL" and the layout version of a [`Pool`].
534const POOL_MAGIC: u64 = 0x5250_4f4c_0000_0001;
535/// The header of a pool: magic, slots, slot size, then the control words
536/// of each slot.
537const POOL_HEADER: usize = 64;
538/// The control of a slot: its state (generation in the high 32 bits,
539/// references in the low 32) and the length of its payload.
540const SLOT_CONTROL: usize = 16;
541/// Where a payload starts in its slot (whose alignment is 64): 4 octets
542/// in, so that what follows its 4-octet encapsulation header is aligned
543/// to 8.
544const PAYLOAD_OFFSET: usize = 4;
545
546fn pool_path(dir: &Path, id: u64) -> PathBuf {
547    dir.join(format!("rustorb-dds-pool-{id:016x}"))
548}
549
550/// A pool of samples in shared memory, made by a writer for the samples
551/// it loans (zero-copy): fixed-size slots that the writer fills and the
552/// readers of this host map and read in place. A slot is reused once no
553/// one holds a reference to it: the writer, while the sample is in its
554/// history, and each reader, while it has the sample.
555///
556/// Each slot has a generation, changed each time the writer takes it, so
557/// that a reference to an older sample of the slot is not taken for the
558/// new one.
559pub struct Pool {
560    map: MmapMut,
561    id: u64,
562    slots: u32,
563    slot_size: usize,
564    data: usize,
565    /// The file, removed when the writer's pool goes; `None` in readers.
566    path: Option<PathBuf>,
567}
568
569// SAFETY: the control words are atomics; a slot's data is written only by
570// the writer while it holds the slot alone, and read after it is
571// published.
572unsafe impl Send for Pool {}
573unsafe impl Sync for Pool {}
574
575impl std::fmt::Debug for Pool {
576    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
577        f.debug_struct("Pool")
578            .field("id", &format_args!("{:016x}", self.id))
579            .field("slots", &self.slots)
580            .field("slot_size", &self.slot_size)
581            .finish()
582    }
583}
584
585impl Pool {
586    /// Makes a pool of `slots` slots for payloads of up to `slot_size`
587    /// octets (rounded up, see [`Self::slot_size`]) in `dir`.
588    pub fn create(dir: &Path, slots: u32, slot_size: usize) -> io::Result<Arc<Pool>> {
589        static NEXT: AtomicU64 = AtomicU64::new(0);
590        let nanos = std::time::SystemTime::now()
591            .duration_since(std::time::UNIX_EPOCH)
592            .map_or(0, |d| d.as_nanos() as u64);
593        let id = fnv(&[
594            u64::from(std::process::id()).to_le_bytes(),
595            nanos.to_le_bytes(),
596            NEXT.fetch_add(1, Ordering::Relaxed).to_le_bytes(),
597        ]
598        .concat());
599        let slot_size = (slot_size.max(8) + PAYLOAD_OFFSET).next_multiple_of(64);
600        let data = (POOL_HEADER + slots as usize * SLOT_CONTROL).next_multiple_of(64);
601        let path = pool_path(dir, id);
602        let file = OpenOptions::new()
603            .read(true)
604            .write(true)
605            .create_new(true)
606            .open(&path)?;
607        file.set_len((data + slots as usize * slot_size) as u64)?;
608        // SAFETY: a new file of this process; others change it only
609        // through the protocol of this type.
610        let map = unsafe { MmapMut::map_mut(&file) }?;
611        let pool = Pool {
612            map,
613            id,
614            slots,
615            slot_size,
616            data,
617            path: Some(path),
618        };
619        pool.word(8).store(u64::from(slots), Ordering::Relaxed);
620        pool.word(16).store(slot_size as u64, Ordering::Relaxed);
621        pool.word(0).store(POOL_MAGIC, Ordering::Release);
622        Ok(Arc::new(pool))
623    }
624
625    /// Maps the pool `id` of `dir`, made by a writer of this host.
626    pub fn open(dir: &Path, id: u64) -> io::Result<Arc<Pool>> {
627        let file = OpenOptions::new()
628            .read(true)
629            .write(true)
630            .open(pool_path(dir, id))?;
631        let len = file.metadata()?.len() as usize;
632        let bad = || io::Error::new(io::ErrorKind::InvalidData, "not a pool");
633        if len < POOL_HEADER {
634            return Err(bad());
635        }
636        // SAFETY: as in `create`.
637        let map = unsafe { MmapMut::map_mut(&file) }?;
638        let word = |off: usize| {
639            // SAFETY: page aligned, and off < POOL_HEADER <= len.
640            unsafe { &*(map.as_ptr().add(off) as *const AtomicU64) }
641        };
642        if word(0).load(Ordering::Acquire) != POOL_MAGIC {
643            return Err(bad());
644        }
645        let slots = word(8).load(Ordering::Relaxed) as u32;
646        let slot_size = word(16).load(Ordering::Relaxed) as usize;
647        let data = (POOL_HEADER + slots as usize * SLOT_CONTROL).next_multiple_of(64);
648        if slot_size < 64
649            || !slot_size.is_multiple_of(64)
650            || (slots as usize)
651                .checked_mul(slot_size)
652                .and_then(|n| n.checked_add(data))
653                != Some(len)
654        {
655            return Err(bad());
656        }
657        Ok(Arc::new(Pool {
658            map,
659            id,
660            slots,
661            slot_size,
662            data,
663            path: None,
664        }))
665    }
666
667    /// Its id, which references name it by.
668    pub fn id(&self) -> u64 {
669        self.id
670    }
671
672    /// The largest payload a slot holds.
673    pub fn slot_size(&self) -> usize {
674        self.slot_size - PAYLOAD_OFFSET
675    }
676
677    /// The number of slots.
678    pub fn slots(&self) -> u32 {
679        self.slots
680    }
681
682    fn word(&self, off: usize) -> &AtomicU64 {
683        // SAFETY: the mapping is page aligned; off is a multiple of 8
684        // within the header and the slot controls.
685        unsafe { &*(self.map.as_ptr().add(off) as *const AtomicU64) }
686    }
687
688    fn state(&self, i: u32) -> &AtomicU64 {
689        self.word(POOL_HEADER + i as usize * SLOT_CONTROL)
690    }
691
692    fn len_word(&self, i: u32) -> &AtomicU64 {
693        self.word(POOL_HEADER + i as usize * SLOT_CONTROL + 8)
694    }
695
696    /// The payload of slot `i`.
697    fn slot_ptr(&self, i: u32) -> *mut u8 {
698        // SAFETY: slot i is within the mapping.
699        unsafe {
700            self.map
701                .as_ptr()
702                .add(self.data + i as usize * self.slot_size + PAYLOAD_OFFSET)
703                as *mut u8
704        }
705    }
706
707    /// Takes a free slot for the writer; `None` if every slot is held. It
708    /// holds zeros the first time, then the sample it held last.
709    pub fn acquire(self: &Arc<Self>) -> Option<PoolSlot> {
710        for i in 0..self.slots {
711            let s = self.state(i);
712            let v = s.load(Ordering::Acquire);
713            if v & 0xffff_ffff != 0 {
714                continue;
715            }
716            let generation = ((v >> 32) as u32).wrapping_add(1);
717            if s.compare_exchange(
718                v,
719                (u64::from(generation) << 32) | 1,
720                Ordering::AcqRel,
721                Ordering::Relaxed,
722            )
723            .is_ok()
724            {
725                return Some(PoolSlot(PoolLoan {
726                    pool: self.clone(),
727                    index: i,
728                    generation,
729                }));
730            }
731        }
732        None
733    }
734
735    /// How many slots are held.
736    pub fn held(&self) -> usize {
737        (0..self.slots)
738            .filter(|i| self.state(*i).load(Ordering::Relaxed) & 0xffff_ffff != 0)
739            .count()
740    }
741
742    /// Takes a reference to slot `index` if it still holds the sample of
743    /// `generation`.
744    fn retain(self: &Arc<Self>, index: u32, generation: u32) -> Option<PoolLoan> {
745        if index >= self.slots {
746            return None;
747        }
748        let s = self.state(index);
749        let mut v = s.load(Ordering::Acquire);
750        loop {
751            if (v >> 32) as u32 != generation || v & 0xffff_ffff == 0 {
752                return None;
753            }
754            match s.compare_exchange_weak(v, v + 1, Ordering::AcqRel, Ordering::Acquire) {
755                Ok(_) => {
756                    return Some(PoolLoan {
757                        pool: self.clone(),
758                        index,
759                        generation,
760                    });
761                }
762                Err(now) => v = now,
763            }
764        }
765    }
766}
767
768impl Drop for Pool {
769    fn drop(&mut self) {
770        // Readers that still map it keep their mapping.
771        if let Some(p) = &self.path {
772            let _ = std::fs::remove_file(p);
773        }
774    }
775}
776
777/// A slot the writer holds alone, to fill before it publishes it.
778#[derive(Debug)]
779pub struct PoolSlot(PoolLoan);
780
781impl PoolSlot {
782    /// The slot, to write the payload in: its address is 4 past a
783    /// multiple of 64, so that octet 4 on is aligned to 8.
784    pub fn bytes_mut(&mut self) -> &mut [u8] {
785        let p = &self.0.pool;
786        // SAFETY: the slot is held by this writer alone until published.
787        unsafe { std::slice::from_raw_parts_mut(p.slot_ptr(self.0.index), p.slot_size()) }
788    }
789
790    /// The slot, as [`Self::bytes_mut`].
791    pub fn bytes(&self) -> &[u8] {
792        let p = &self.0.pool;
793        // SAFETY: as in `bytes_mut`.
794        unsafe { std::slice::from_raw_parts(p.slot_ptr(self.0.index), p.slot_size()) }
795    }
796
797    /// Publishes the first `len` octets of the slot: from then on it is
798    /// only read.
799    pub fn publish(self, len: usize) -> PoolLoan {
800        let len = len.min(self.0.pool.slot_size());
801        self.0
802            .pool
803            .len_word(self.0.index)
804            .store(len as u64, Ordering::Release);
805        self.0
806    }
807}
808
809/// A reference to a published sample of a [`Pool`]: the slot is not
810/// reused while one is alive. Cloning takes another reference.
811#[derive(Debug)]
812pub struct PoolLoan {
813    pool: Arc<Pool>,
814    index: u32,
815    generation: u32,
816}
817
818/// The encapsulation identifier of a payload that is a reference to a
819/// sample in a pool, not the sample: a vendor value, sent only to
820/// participants of rustorb-dds on this host.
821pub const REFERENCE_ENCAPSULATION: [u8; 2] = [0x52, 0x44];
822
823impl PoolLoan {
824    /// The payload.
825    pub fn bytes(&self) -> &[u8] {
826        let len = (self.pool.len_word(self.index).load(Ordering::Acquire) as usize)
827            .min(self.pool.slot_size());
828        // SAFETY: published, so no longer written while referenced.
829        unsafe { std::slice::from_raw_parts(self.pool.slot_ptr(self.index), len) }
830    }
831
832    /// The payload that refers to this sample: [`REFERENCE_ENCAPSULATION`]
833    /// and two octets of options, then the pool id, the slot and its
834    /// generation (little endian).
835    pub fn reference(&self) -> Vec<u8> {
836        let mut b = Vec::with_capacity(20);
837        b.extend_from_slice(&REFERENCE_ENCAPSULATION);
838        b.extend_from_slice(&[0, 0]);
839        b.extend_from_slice(&self.pool.id.to_le_bytes());
840        b.extend_from_slice(&self.index.to_le_bytes());
841        b.extend_from_slice(&self.generation.to_le_bytes());
842        b
843    }
844}
845
846impl Clone for PoolLoan {
847    fn clone(&self) -> Self {
848        self.pool.state(self.index).fetch_add(1, Ordering::AcqRel);
849        PoolLoan {
850            pool: self.pool.clone(),
851            index: self.index,
852            generation: self.generation,
853        }
854    }
855}
856
857impl Drop for PoolLoan {
858    fn drop(&mut self) {
859        self.pool.state(self.index).fetch_sub(1, Ordering::AcqRel);
860    }
861}
862
863/// Whether a payload is a reference to a pooled sample.
864pub fn is_reference(payload: &[u8]) -> bool {
865    payload.len() == 20 && payload[..2] == REFERENCE_ENCAPSULATION
866}
867
868/// The pools of other writers that a reader opened, by id: each is kept
869/// mapped while its file exists.
870#[derive(Debug)]
871pub struct Pools {
872    directory: PathBuf,
873    open: Mutex<HashMap<u64, Arc<Pool>>>,
874}
875
876impl Pools {
877    /// The pools of directory `directory`.
878    pub fn new(directory: &Path) -> Pools {
879        Pools {
880            directory: directory.to_path_buf(),
881            open: Mutex::new(HashMap::new()),
882        }
883    }
884
885    /// The sample a reference payload names: `None` if its pool cannot
886    /// be opened or its slot holds another sample by now.
887    pub fn resolve(&self, reference: &[u8]) -> Option<PoolLoan> {
888        if !is_reference(reference) {
889            return None;
890        }
891        let id = u64::from_le_bytes(reference[4..12].try_into().ok()?);
892        let index = u32::from_le_bytes(reference[12..16].try_into().ok()?);
893        let generation = u32::from_le_bytes(reference[16..20].try_into().ok()?);
894        let pool = {
895            let mut pools = self.open.lock().ok()?;
896            match pools.get(&id) {
897                Some(p) => p.clone(),
898                None => {
899                    // The pools of writers that are gone.
900                    let dir = &self.directory;
901                    pools.retain(|id, _| pool_path(dir, *id).exists());
902                    let p = Pool::open(dir, id).ok()?;
903                    pools.insert(id, p.clone());
904                    p
905                }
906            }
907        };
908        pool.retain(index, generation)
909    }
910}
911
912#[cfg(test)]
913mod tests {
914    use super::*;
915    use std::sync::mpsc;
916
917    fn config() -> ShmConfig {
918        ShmConfig {
919            capacity: 4096,
920            ..ShmConfig::default()
921        }
922    }
923
924    fn prefix(n: u8) -> GuidPrefix {
925        GuidPrefix([n; 12])
926    }
927
928    #[test]
929    fn messages_go_through_in_order() {
930        let (tx_a, _rx_a) = mpsc::sync_channel(64);
931        let (tx_b, rx_b) = mpsc::sync_channel(64);
932        let a = ShmTransport::open(&config(), prefix(1), tx_a).unwrap();
933        let b = ShmTransport::open(&config(), prefix(2), tx_b).unwrap();
934        let to = b.user_locator();
935        assert_eq!(a.select(std::slice::from_ref(&to)), vec![&to]);
936        // Enough messages to wrap around the ring several times, each
937        // waiting for room.
938        let mut got = Vec::new();
939        for i in 0..200u32 {
940            let msg = vec![i as u8; 1 + (i as usize * 7) % 900];
941            let deadline = Instant::now() + Duration::from_secs(5);
942            while a.send(&msg, &to).is_err() {
943                assert!(Instant::now() < deadline);
944                while let Ok(d) = rx_b.try_recv() {
945                    got.push(d);
946                }
947                std::thread::sleep(Duration::from_millis(1));
948            }
949        }
950        let deadline = Instant::now() + Duration::from_secs(5);
951        while got.len() < 200 && Instant::now() < deadline {
952            if let Ok(d) = rx_b.recv_timeout(Duration::from_millis(50)) {
953                got.push(d);
954            }
955        }
956        assert_eq!(got.len(), 200);
957        for (i, d) in got.iter().enumerate() {
958            assert_eq!(d.channel, Channel::UserUnicast);
959            assert_eq!(d.data, vec![i as u8; 1 + (i * 7) % 900]);
960        }
961        let meta = b.metatraffic_locator();
962        a.send(b"hello", &meta).unwrap();
963        let d = rx_b.recv_timeout(Duration::from_secs(5)).unwrap();
964        assert_eq!(
965            (d.channel, &d.data[..]),
966            (Channel::DiscoveryUnicast, &b"hello"[..])
967        );
968    }
969
970    #[test]
971    fn other_hosts_and_gone_peers_use_udp() {
972        let (tx, _rx) = mpsc::sync_channel(64);
973        let a = ShmTransport::open(&config(), prefix(3), tx).unwrap();
974        let udp = Locator::udpv4("127.0.0.1:7411".parse().unwrap());
975        let mut elsewhere = a.user_locator();
976        elsewhere.address[0] ^= 0xff;
977        let mut gone = a.user_locator();
978        gone.address[15] ^= 0xff;
979        assert_eq!(a.select(&[elsewhere, udp]), vec![&udp]);
980        assert_eq!(a.select(&[gone, udp]), vec![&udp]);
981        assert!(a.send(b"x", &gone).is_err());
982        // Too large for the ring: not sent this way.
983        let (tx_b, _rx_b) = mpsc::sync_channel(64);
984        let b = ShmTransport::open(&config(), prefix(4), tx_b).unwrap();
985        assert!(a.send(&[0u8; 2048], &b.user_locator()).is_err());
986    }
987
988    #[test]
989    fn pooled_samples_are_shared_until_released() {
990        let dir = ShmConfig::default().directory;
991        let pool = Pool::create(&dir, 2, 100).unwrap();
992        assert_eq!(pool.slot_size(), 124);
993        let mut a = pool.acquire().unwrap();
994        a.bytes_mut()[..5].copy_from_slice(b"hello");
995        let a = a.publish(5);
996        assert_eq!(a.bytes(), b"hello");
997        let r = a.reference();
998        assert!(is_reference(&r));
999        // A reader maps it and holds the sample after the writer lets go.
1000        let pools = Pools::new(&dir);
1001        let got = pools.resolve(&r).unwrap();
1002        assert_eq!(got.bytes(), b"hello");
1003        let b = pool.acquire().unwrap();
1004        assert!(pool.acquire().is_none(), "two slots held");
1005        drop(a);
1006        assert!(pool.acquire().is_none(), "the reader holds the first");
1007        drop(got);
1008        // The slot is reused, with another generation: the old reference
1009        // no longer resolves.
1010        let c = pool.acquire().unwrap().publish(1);
1011        assert!(pools.resolve(&r).is_none());
1012        assert!(pools.resolve(&c.reference()).is_some());
1013        drop((b, c));
1014        assert_eq!(pool.held(), 0);
1015        let path = pool_path(&dir, pool.id());
1016        assert!(path.exists());
1017        drop(pool);
1018        assert!(!path.exists());
1019        assert!(pools.resolve(&r).is_none());
1020    }
1021
1022    #[test]
1023    fn dropping_removes_the_files() {
1024        let (tx, _rx) = mpsc::sync_channel(64);
1025        let a = ShmTransport::open(&config(), prefix(5), tx).unwrap();
1026        let seg = a.path.clone();
1027        assert!(seg.exists());
1028        drop(a);
1029        assert!(!seg.exists());
1030    }
1031}