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