interplane.Get Omega
Read in your language

synapse

A component of the AienOS ecosystem.

Brought by drakestapleton

branch main Branches Tags History

synapse / crates / synapse-wire / src / ring.rs

842 lines · 29732 bytes Raw Blame History
1//! Shared-memory ring for local agents (ADR 0003 section 9 step G3, experiment X5).
2//!
3//! A [`RingRegion`] holds two single-producer, single-consumer byte rings, one per
4//! direction. Each side owns a [`RingSender`] on one ring and a [`RingReceiver`] on the
5//! other; [`RingStream`] joins the two into a byte stream, so the G1 frame reader
6//! ([`crate::transport::FrameConn`]) and the have-want session run over the ring unchanged.
7//!
8//! The peer is hostile. Every word of the region is writable by both sides, so:
9//!
10//! * Each side keeps its own index (the sender its `head`, the receiver its `tail`) and its
11//! own copy of the ring configuration. It publishes them to the region and never reads
12//! them back. A word the peer overwrites changes nothing for this side.
13//! * Every value read from the region (the peer's index, a record's length and sequence
14//! number) is loaded once into a local, checked, and only then used. A record's payload
15//! is copied into the receiver's own buffer before anyone validates it, so the bytes a
16//! frame decoder checks are the bytes it uses.
17//! * Every position is the index masked by the power-of-two capacity, and every access is
18//! a bounds-checked slice index, so no input can address memory outside the ring.
19//! * All shared accesses are atomics with explicit orderings: the sender writes a record
20//! with relaxed stores, then publishes `head` with a release store; the receiver loads
21//! `head` with acquire, then the record with relaxed loads, then publishes `tail` with
22//! release (so the sender cannot reuse space the receiver is still copying).
23//! * The first refusal poisons the endpoint: framing can no longer be trusted, so it refuses
24//! every later call, as the G1 stream reader closes a connection on a malformed frame.
25//!
26//! # Layout
27//!
28//! All fields are little-endian `u64` words. One ring is [`CONTROL_WORDS`] words of control
29//! block followed by `capacity / 8` data words; the region is ring 0 then ring 1. The
30//! creator sends on ring 0 and receives on ring 1.
31//!
32//! | Word | Field | Written by |
33//! | :--- | :--- | :--- |
34//! | 0 | magic `SYNRING1` | creator, at set-up |
35//! | 1 | capacity in bytes | creator, at set-up |
36//! | 2 | start index | creator, at set-up |
37//! | 8 | `head`: bytes published | sender |
38//! | 9 | closed (0 or 1) | sender |
39//! | 16 | `tail`: bytes consumed | receiver |
40//! | 17 | receiver sleeping (0 or 1) | receiver |
41//! | 24 | doorbell (wake counter; futex word on Linux) | sender |
42//!
43//! Indices are byte counters that only grow and wrap at 2^64 (wrapping arithmetic). A
44//! record is a 16-byte header (`len` word, `seq` word), then `len` payload bytes padded with
45//! zeros to a multiple of 8. Records may wrap across the end of the data area. `seq` starts
46//! at 0 and counts records; the receiver refuses any other value, so no record is accepted
47//! twice and none is skipped.
48//!
49//! # Waiting
50//!
51//! A receiver with nothing to read polls for [`RingConfig::spin`], then sleeps on the
52//! doorbell word (a futex on Linux, with a 10 ms timeout so a peer that never rings costs a
53//! delay, never a hang; a 50 microsecond sleep elsewhere). A sender rings the doorbell only
54//! when the receiver says it is sleeping. A sender whose ring is full polls and yields.
55
56use std::fmt;
57use std::sync::atomic::{fence, AtomicU64, Ordering};
58use std::sync::Arc;
59use std::time::{Duration, Instant};
60use synapse_core::{RefusalCode, SynapseError, SynapseResult};
61
62/// Ring magic, word 0 of each ring.
63pub const RING_MAGIC: u64 = u64::from_le_bytes(*b"SYNRING1");
64/// Record header: `len` word and `seq` word.
65pub const RECORD_HEADER_LEN: usize = 16;
66/// Words of control block in front of each ring's data (four 64-byte lines).
67pub const CONTROL_WORDS: usize = 32;
68
69/// Word offsets inside one ring's control block (see the module table).
70pub mod layout {
71 pub const MAGIC: usize = 0;
72 pub const CAPACITY: usize = 1;
73 pub const START: usize = 2;
74 pub const HEAD: usize = 8;
75 pub const CLOSED: usize = 9;
76 pub const TAIL: usize = 16;
77 pub const RX_SLEEPING: usize = 17;
78 pub const DOORBELL: usize = 24;
79}
80
81const MIN_CAPACITY: usize = 64;
82const MAX_CAPACITY: usize = 1 << 30;
83/// How long a sleeping receiver waits before it looks again on its own.
84const SLEEP_TIMEOUT: Duration = Duration::from_millis(10);
85
86/// Ring parameters. Both sides must use the same values; each keeps its own copy and only
87/// checks the region's set-up words against it.
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub struct RingConfig {
90 /// Data bytes per direction: a power of two from 64 to 2^30.
91 pub capacity: usize,
92 /// Largest record payload, from 1 to `capacity - 16`. Longer writes are split.
93 pub max_record: usize,
94 /// First byte index, a multiple of 8 (tests start near `u64::MAX` to cross the wrap).
95 pub start: u64,
96 /// How long a receiver polls before it sleeps.
97 pub spin: Duration,
98}
99
100impl Default for RingConfig {
101 fn default() -> Self {
102 Self {
103 capacity: 1 << 20,
104 max_record: 256 << 10,
105 start: 0,
106 spin: Duration::from_micros(50),
107 }
108 }
109}
110
111impl RingConfig {
112 /// Check the parameters.
113 pub fn validate(&self) -> Result<(), RingRefusal> {
114 if !self.capacity.is_power_of_two()
115 || self.capacity < MIN_CAPACITY
116 || self.capacity > MAX_CAPACITY
117 {
118 return Err(RingRefusal::BadConfig(
119 "capacity must be a power of two from 64 to 2^30",
120 ));
121 }
122 if self.max_record == 0 || self.max_record > self.capacity - RECORD_HEADER_LEN {
123 return Err(RingRefusal::BadConfig(
124 "max_record must be from 1 to capacity - 16",
125 ));
126 }
127 if !self.start.is_multiple_of(8) {
128 return Err(RingRefusal::BadConfig("start must be a multiple of 8"));
129 }
130 Ok(())
131 }
132
133 fn data_words(&self) -> usize {
134 self.capacity / 8
135 }
136
137 /// Words in one ring (control block and data).
138 pub fn ring_words(&self) -> usize {
139 CONTROL_WORDS + self.data_words()
140 }
141
142 /// Words in a region (two rings).
143 pub fn region_words(&self) -> usize {
144 2 * self.ring_words()
145 }
146
147 /// Bytes in a region (two rings).
148 pub fn region_bytes(&self) -> usize {
149 8 * self.region_words()
150 }
151
152 /// Word offset of ring `ring` (0 or 1) inside a region.
153 pub fn ring_base(&self, ring: usize) -> usize {
154 ring * self.ring_words()
155 }
156}
157
158/// Bytes a record of `len` payload bytes occupies (header plus padded payload). `len` is
159/// at most `max_record`, so this cannot overflow.
160pub fn record_span(len: usize) -> usize {
161 RECORD_HEADER_LEN + len.div_ceil(8) * 8
162}
163
164/// Typed refusal from the ring. Everything after set-up is the peer breaking the protocol.
165#[derive(Debug, Clone, PartialEq, Eq)]
166pub enum RingRefusal {
167 /// The local configuration is invalid.
168 BadConfig(&'static str),
169 /// The region does not have the size the configuration needs.
170 RegionSize { need: usize, found: usize },
171 /// A set-up word (magic, capacity, start) differs from the local configuration.
172 HeaderMismatch {
173 ring: usize,
174 field: &'static str,
175 found: u64,
176 },
177 /// The shared region could be shrunk by the peer (no `F_SEAL_SHRINK` seal), which would
178 /// let it fault the reader; refused before mapping.
179 RegionNotSealed,
180 /// The peer's index is not a multiple of 8.
181 IndexMisaligned { which: &'static str, found: u64 },
182 /// The peer's index is outside the range its own past and this side's index allow: the
183 /// sender's `head` more than `capacity` ahead of the receiver's `tail` or behind it, or
184 /// the receiver's `tail` ahead of `head` or behind where it was.
185 IndexOutOfRange {
186 which: &'static str,
187 found: u64,
188 low: u64,
189 high: u64,
190 },
191 /// The sender's `head` moved back behind a value this side already saw.
192 IndexRegressed { found: u64, seen: u64 },
193 /// Published bytes end inside a record: `need` bytes were required, `available` were
194 /// published.
195 TornRecord { need: u64, available: u64 },
196 /// A record declares more payload than `max_record`.
197 LengthOverCap { declared: u64, cap: u64 },
198 /// A record carries the wrong sequence number (a replay, a skip, or garbage).
199 SequenceMismatch { expected: u64, found: u64 },
200 /// A local send of more than `max_record` bytes (not a peer fault; nothing is written).
201 RecordTooLarge { len: usize, cap: usize },
202 /// A send after this side closed its sender.
203 SenderClosed,
204}
205
206impl RingRefusal {
207 /// Short stable name of the refusal kind.
208 pub fn kind(&self) -> &'static str {
209 match self {
210 Self::BadConfig(_) => "BadConfig",
211 Self::RegionSize { .. } => "RegionSize",
212 Self::HeaderMismatch { .. } => "HeaderMismatch",
213 Self::RegionNotSealed => "RegionNotSealed",
214 Self::IndexMisaligned { .. } => "IndexMisaligned",
215 Self::IndexOutOfRange { .. } => "IndexOutOfRange",
216 Self::IndexRegressed { .. } => "IndexRegressed",
217 Self::TornRecord { .. } => "TornRecord",
218 Self::LengthOverCap { .. } => "LengthOverCap",
219 Self::SequenceMismatch { .. } => "SequenceMismatch",
220 Self::RecordTooLarge { .. } => "RecordTooLarge",
221 Self::SenderClosed => "SenderClosed",
222 }
223 }
224
225 /// The refusal as a `SynapseError` with code `WireRingViolation`.
226 pub fn into_error(self) -> SynapseError {
227 SynapseError::new(
228 RefusalCode::WireRingViolation,
229 format!("wire ring: {} ({self:?})", self.kind()),
230 )
231 }
232}
233
234impl fmt::Display for RingRefusal {
235 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
236 write!(f, "wire ring: {} ({self:?})", self.kind())
237 }
238}
239
240impl std::error::Error for RingRefusal {}
241
242enum Memory {
243 Heap(Box<[AtomicU64]>),
244 #[cfg(all(target_os = "linux", target_pointer_width = "64"))]
245 Shared(crate::shm::Mapping),
246}
247
248/// Memory holding two rings: on the heap for one process, or a sealed shared mapping
249/// ([`RingRegion::create_shared`], [`RingRegion::attach_shared`]) for two.
250pub struct RingRegion {
251 cfg: RingConfig,
252 mem: Memory,
253}
254
255/// Which end of the region a side is: the creator sends on ring 0, the attacher on ring 1.
256#[derive(Debug, Clone, Copy, PartialEq, Eq)]
257pub enum Side {
258 Creator,
259 Attacher,
260}
261
262impl RingRegion {
263 /// A region on this process's heap (both sides in one process; tests and models).
264 pub fn in_process(cfg: RingConfig) -> Result<Arc<Self>, RingRefusal> {
265 cfg.validate()?;
266 let words = (0..cfg.region_words()).map(|_| AtomicU64::new(0)).collect();
267 let region = Self {
268 cfg,
269 mem: Memory::Heap(words),
270 };
271 region.init();
272 Ok(Arc::new(region))
273 }
274
275 /// A new sealed shared-memory region (Linux `memfd`, sealed against shrinking and
276 /// growing). Another process attaches with [`Self::attach_shared`] on
277 /// [`Self::attach_path`].
278 #[cfg(all(target_os = "linux", target_pointer_width = "64"))]
279 pub fn create_shared(cfg: RingConfig) -> SynapseResult<Arc<Self>> {
280 cfg.validate().map_err(RingRefusal::into_error)?;
281 let map = crate::shm::Mapping::create(cfg.region_bytes()).map_err(io_error)?;
282 let region = Self {
283 cfg,
284 mem: Memory::Shared(map),
285 };
286 region.init();
287 Ok(Arc::new(region))
288 }
289
290 /// Attach to a region another process created. Refused unless the file is sealed against
291 /// shrinking, has exactly the configured size, and carries the configured set-up words.
292 #[cfg(all(target_os = "linux", target_pointer_width = "64"))]
293 pub fn attach_shared(path: &std::path::Path, cfg: RingConfig) -> SynapseResult<Arc<Self>> {
294 cfg.validate().map_err(RingRefusal::into_error)?;
295 let map = match crate::shm::Mapping::attach(path, cfg.region_bytes()) {
296 Ok(m) => m,
297 Err(crate::shm::AttachError::Refused(r)) => return Err(r.into_error()),
298 Err(crate::shm::AttachError::Io(e)) => return Err(io_error(e)),
299 };
300 let region = Self {
301 cfg,
302 mem: Memory::Shared(map),
303 };
304 region.verify().map_err(RingRefusal::into_error)?;
305 Ok(Arc::new(region))
306 }
307
308 /// A path another process of the same user can open to attach (`/proc/<pid>/fd/<fd>`);
309 /// `None` for a heap region.
310 pub fn attach_path(&self) -> Option<std::path::PathBuf> {
311 match &self.mem {
312 Memory::Heap(_) => None,
313 #[cfg(all(target_os = "linux", target_pointer_width = "64"))]
314 Memory::Shared(m) => Some(m.attach_path()),
315 }
316 }
317
318 /// The configuration this side uses.
319 pub fn config(&self) -> &RingConfig {
320 &self.cfg
321 }
322
323 /// Every word of the region. Public so tests can play a hostile peer; production code
324 /// only goes through [`RingSender`] and [`RingReceiver`].
325 pub fn words(&self) -> &[AtomicU64] {
326 match &self.mem {
327 Memory::Heap(w) => w,
328 #[cfg(all(target_os = "linux", target_pointer_width = "64"))]
329 Memory::Shared(m) => m.words(),
330 }
331 }
332
333 fn init(&self) {
334 let w = self.words();
335 for ring in 0..2 {
336 let b = self.cfg.ring_base(ring);
337 w[b + layout::CAPACITY].store(self.cfg.capacity as u64, Ordering::Relaxed);
338 w[b + layout::START].store(self.cfg.start, Ordering::Relaxed);
339 w[b + layout::HEAD].store(self.cfg.start, Ordering::Relaxed);
340 w[b + layout::TAIL].store(self.cfg.start, Ordering::Relaxed);
341 w[b + layout::CLOSED].store(0, Ordering::Relaxed);
342 w[b + layout::RX_SLEEPING].store(0, Ordering::Relaxed);
343 w[b + layout::DOORBELL].store(0, Ordering::Relaxed);
344 w[b + layout::MAGIC].store(RING_MAGIC, Ordering::Release);
345 }
346 }
347
348 fn verify(&self) -> Result<(), RingRefusal> {
349 let w = self.words();
350 if w.len() != self.cfg.region_words() {
351 return Err(RingRefusal::RegionSize {
352 need: self.cfg.region_bytes(),
353 found: w.len() * 8,
354 });
355 }
356 for ring in 0..2 {
357 let b = self.cfg.ring_base(ring);
358 let checks = [
359 ("magic", layout::MAGIC, RING_MAGIC),
360 ("capacity", layout::CAPACITY, self.cfg.capacity as u64),
361 ("start", layout::START, self.cfg.start),
362 ];
363 for (field, off, want) in checks {
364 let found = w[b + off].load(Ordering::Acquire);
365 if found != want {
366 return Err(RingRefusal::HeaderMismatch { ring, field, found });
367 }
368 }
369 }
370 Ok(())
371 }
372
373 /// The sender and receiver for `side`.
374 pub fn endpoints(self: &Arc<Self>, side: Side) -> (RingSender, RingReceiver) {
375 let (tx, rx) = match side {
376 Side::Creator => (0, 1),
377 Side::Attacher => (1, 0),
378 };
379 (
380 RingSender::new(self.clone(), tx),
381 RingReceiver::new(self.clone(), rx),
382 )
383 }
384
385 /// A [`RingStream`] for `side`.
386 pub fn stream(self: &Arc<Self>, side: Side) -> RingStream {
387 let (tx, rx) = self.endpoints(side);
388 RingStream::new(tx, rx)
389 }
390}
391
392#[cfg(all(target_os = "linux", target_pointer_width = "64"))]
393fn io_error(e: std::io::Error) -> SynapseError {
394 SynapseError::new(RefusalCode::IoFailure, format!("wire ring: {e}"))
395}
396
397/// One ring as seen by one endpoint: bounds-checked access to its control and data words.
398struct RingView {
399 region: Arc<RingRegion>,
400 base: usize,
401 data_mask: u64,
402}
403
404impl RingView {
405 fn new(region: Arc<RingRegion>, ring: usize) -> Self {
406 let cfg = *region.config();
407 Self {
408 base: cfg.ring_base(ring),
409 data_mask: (cfg.data_words() - 1) as u64,
410 region,
411 }
412 }
413
414 fn ctl(&self, off: usize) -> &AtomicU64 {
415 &self.region.words()[self.base + off]
416 }
417
418 /// The data word holding byte index `index` (a multiple of 8). The mask keeps the
419 /// position inside the data area for every `index`; the slice index is bounds-checked.
420 fn data(&self, index: u64) -> &AtomicU64 {
421 let pos = ((index / 8) & self.data_mask) as usize;
422 &self.region.words()[self.base + CONTROL_WORDS + pos]
423 }
424
425 fn ring_doorbell(&self) {
426 let bell = self.ctl(layout::DOORBELL);
427 bell.fetch_add(1, Ordering::Release);
428 doorbell_wake(bell);
429 }
430}
431
432/// The writing end of one ring.
433pub struct RingSender {
434 view: RingView,
435 cfg: RingConfig,
436 head: u64,
437 tail_seen: u64,
438 seq: u64,
439 closed: bool,
440 poisoned: Option<RingRefusal>,
441}
442
443impl RingSender {
444 fn new(region: Arc<RingRegion>, ring: usize) -> Self {
445 let cfg = *region.config();
446 Self {
447 view: RingView::new(region, ring),
448 cfg,
449 head: cfg.start,
450 tail_seen: cfg.start,
451 seq: 0,
452 closed: false,
453 poisoned: None,
454 }
455 }
456
457 fn poison(&mut self, r: RingRefusal) -> RingRefusal {
458 self.poisoned = Some(r.clone());
459 r
460 }
461
462 /// Bytes free for new records, after checking the receiver's published `tail`.
463 fn free(&mut self) -> Result<u64, RingRefusal> {
464 let tail = self.view.ctl(layout::TAIL).load(Ordering::Acquire);
465 if !tail.is_multiple_of(8) {
466 return Err(self.poison(RingRefusal::IndexMisaligned {
467 which: "tail",
468 found: tail,
469 }));
470 }
471 // The receiver's tail may only move forward from where it was, and never past head.
472 if tail.wrapping_sub(self.tail_seen) > self.head.wrapping_sub(self.tail_seen) {
473 return Err(self.poison(RingRefusal::IndexOutOfRange {
474 which: "tail",
475 found: tail,
476 low: self.tail_seen,
477 high: self.head,
478 }));
479 }
480 self.tail_seen = tail;
481 Ok(self.cfg.capacity as u64 - self.head.wrapping_sub(tail))
482 }
483
484 /// Write one record if it fits now. `Ok(false)`: the ring is full, nothing written.
485 pub fn try_send(&mut self, payload: &[u8]) -> Result<bool, RingRefusal> {
486 if let Some(r) = &self.poisoned {
487 return Err(r.clone());
488 }
489 if self.closed {
490 return Err(RingRefusal::SenderClosed);
491 }
492 if payload.len() > self.cfg.max_record {
493 return Err(RingRefusal::RecordTooLarge {
494 len: payload.len(),
495 cap: self.cfg.max_record,
496 });
497 }
498 let span = record_span(payload.len()) as u64;
499 if self.free()? < span {
500 return Ok(false);
501 }
502 let mut at = self.head;
503 self.view
504 .data(at)
505 .store(payload.len() as u64, Ordering::Relaxed);
506 self.view
507 .data(at.wrapping_add(8))
508 .store(self.seq, Ordering::Relaxed);
509 at = at.wrapping_add(RECORD_HEADER_LEN as u64);
510 for chunk in payload.chunks(8) {
511 let mut word = [0u8; 8];
512 word[..chunk.len()].copy_from_slice(chunk);
513 self.view
514 .data(at)
515 .store(u64::from_le_bytes(word), Ordering::Relaxed);
516 at = at.wrapping_add(8);
517 }
518 self.head = self.head.wrapping_add(span);
519 self.seq += 1;
520 self.view
521 .ctl(layout::HEAD)
522 .store(self.head, Ordering::Release);
523 // Pairs with the receiver's fence between "I am sleeping" and its last look at head:
524 // either it sees the new head, or this side sees it sleeping and rings.
525 fence(Ordering::SeqCst);
526 if self.view.ctl(layout::RX_SLEEPING).load(Ordering::Relaxed) != 0 {
527 self.view.ring_doorbell();
528 }
529 Ok(true)
530 }
531
532 /// Write one record, waiting (polling, then yielding) while the ring is full.
533 pub fn send(&mut self, payload: &[u8]) -> Result<(), RingRefusal> {
534 let mut backoff = Backoff::new();
535 while !self.try_send(payload)? {
536 backoff.snooze();
537 }
538 Ok(())
539 }
540
541 /// Mark the ring closed: the receiver reads what was published, then sees the end.
542 pub fn close(&mut self) {
543 if !self.closed {
544 self.closed = true;
545 self.view.ctl(layout::CLOSED).store(1, Ordering::Release);
546 self.view.ring_doorbell();
547 }
548 }
549
550 /// Records written so far.
551 pub fn records_sent(&self) -> u64 {
552 self.seq
553 }
554}
555
556impl Drop for RingSender {
557 fn drop(&mut self) {
558 self.close();
559 }
560}
561
562/// What [`RingReceiver::try_recv`] found.
563#[derive(Debug, Clone, Copy, PartialEq, Eq)]
564pub enum RecvStatus {
565 /// One record was copied into the caller's buffer.
566 Record,
567 /// Nothing published yet.
568 Empty,
569 /// The sender closed and every published record was read.
570 Closed,
571}
572
573/// The reading end of one ring.
574pub struct RingReceiver {
575 view: RingView,
576 cfg: RingConfig,
577 tail: u64,
578 head_seen: u64,
579 seq: u64,
580 poisoned: Option<RingRefusal>,
581}
582
583impl RingReceiver {
584 fn new(region: Arc<RingRegion>, ring: usize) -> Self {
585 let cfg = *region.config();
586 Self {
587 view: RingView::new(region, ring),
588 cfg,
589 tail: cfg.start,
590 head_seen: cfg.start,
591 seq: 0,
592 poisoned: None,
593 }
594 }
595
596 fn poison(&mut self, r: RingRefusal) -> RingRefusal {
597 self.poisoned = Some(r.clone());
598 r
599 }
600
601 /// Copy the next record into `out` (replacing its contents) if one is published.
602 pub fn try_recv(&mut self, out: &mut Vec<u8>) -> Result<RecvStatus, RingRefusal> {
603 if let Some(r) = &self.poisoned {
604 return Err(r.clone());
605 }
606 // Closed first, then head: a sender stores head before closed (both release), so
607 // seeing closed means the head loaded next is final.
608 let closed = self.view.ctl(layout::CLOSED).load(Ordering::Acquire) != 0;
609 let head = self.view.ctl(layout::HEAD).load(Ordering::Acquire);
610 if !head.is_multiple_of(8) {
611 return Err(self.poison(RingRefusal::IndexMisaligned {
612 which: "head",
613 found: head,
614 }));
615 }
616 let cap = self.cfg.capacity as u64;
617 let available = head.wrapping_sub(self.tail);
618 if available > cap {
619 return Err(self.poison(RingRefusal::IndexOutOfRange {
620 which: "head",
621 found: head,
622 low: self.tail,
623 high: self.tail.wrapping_add(cap),
624 }));
625 }
626 if available < self.head_seen.wrapping_sub(self.tail) {
627 return Err(self.poison(RingRefusal::IndexRegressed {
628 found: head,
629 seen: self.head_seen,
630 }));
631 }
632 self.head_seen = head;
633 if available == 0 {
634 return Ok(if closed {
635 RecvStatus::Closed
636 } else {
637 RecvStatus::Empty
638 });
639 }
640 if available < RECORD_HEADER_LEN as u64 {
641 return Err(self.poison(RingRefusal::TornRecord {
642 need: RECORD_HEADER_LEN as u64,
643 available,
644 }));
645 }
646 // Each header word is loaded once; the checks and the copy use these locals.
647 let len = self.view.data(self.tail).load(Ordering::Relaxed);
648 let seq = self
649 .view
650 .data(self.tail.wrapping_add(8))
651 .load(Ordering::Relaxed);
652 if len > self.cfg.max_record as u64 {
653 return Err(self.poison(RingRefusal::LengthOverCap {
654 declared: len,
655 cap: self.cfg.max_record as u64,
656 }));
657 }
658 let len = len as usize;
659 let span = record_span(len) as u64;
660 if span > available {
661 return Err(self.poison(RingRefusal::TornRecord {
662 need: span,
663 available,
664 }));
665 }
666 if seq != self.seq {
667 return Err(self.poison(RingRefusal::SequenceMismatch {
668 expected: self.seq,
669 found: seq,
670 }));
671 }
672 out.clear();
673 out.reserve(len);
674 let mut at = self.tail.wrapping_add(RECORD_HEADER_LEN as u64);
675 let mut left = len;
676 while left > 0 {
677 let word = self.view.data(at).load(Ordering::Relaxed).to_le_bytes();
678 let n = left.min(8);
679 out.extend_from_slice(&word[..n]);
680 left -= n;
681 at = at.wrapping_add(8);
682 }
683 self.tail = self.tail.wrapping_add(span);
684 self.seq += 1;
685 self.view
686 .ctl(layout::TAIL)
687 .store(self.tail, Ordering::Release);
688 Ok(RecvStatus::Record)
689 }
690
691 /// Copy the next record into `out`, waiting for it. `Ok(false)`: the sender closed and
692 /// every record was read.
693 pub fn recv(&mut self, out: &mut Vec<u8>) -> Result<bool, RingRefusal> {
694 let started = Instant::now();
695 let mut polls = 0u32;
696 loop {
697 match self.try_recv(out)? {
698 RecvStatus::Record => return Ok(true),
699 RecvStatus::Closed => return Ok(false),
700 RecvStatus::Empty => {}
701 }
702 polls = polls.wrapping_add(1);
703 if polls.is_multiple_of(64) && started.elapsed() >= self.cfg.spin {
704 break;
705 }
706 std::hint::spin_loop();
707 }
708 loop {
709 self.view
710 .ctl(layout::RX_SLEEPING)
711 .store(1, Ordering::SeqCst);
712 fence(Ordering::SeqCst);
713 let bell = self.view.ctl(layout::DOORBELL).load(Ordering::SeqCst);
714 let status = self.try_recv(out);
715 match status {
716 Ok(RecvStatus::Empty) => {
717 doorbell_wait(self.view.ctl(layout::DOORBELL), bell, SLEEP_TIMEOUT)
718 }
719 other => {
720 self.view
721 .ctl(layout::RX_SLEEPING)
722 .store(0, Ordering::Relaxed);
723 return other.map(|s| s == RecvStatus::Record);
724 }
725 }
726 }
727 }
728
729 /// Records accepted so far.
730 pub fn records_received(&self) -> u64 {
731 self.seq
732 }
733}
734
735/// Polling, then yielding, then short sleeps.
736struct Backoff {
737 n: u32,
738}
739
740impl Backoff {
741 fn new() -> Self {
742 Self { n: 0 }
743 }
744
745 fn snooze(&mut self) {
746 self.n = self.n.saturating_add(1);
747 if self.n < 64 {
748 std::hint::spin_loop();
749 } else if self.n < 128 {
750 std::thread::yield_now();
751 } else {
752 std::thread::sleep(Duration::from_micros(50));
753 }
754 }
755}
756
757#[cfg(all(target_os = "linux", target_pointer_width = "64"))]
758fn doorbell_wait(word: &AtomicU64, seen: u64, timeout: Duration) {
759 crate::shm::futex_wait(word, seen as u32, timeout);
760}
761
762#[cfg(all(target_os = "linux", target_pointer_width = "64"))]
763fn doorbell_wake(word: &AtomicU64) {
764 crate::shm::futex_wake(word);
765}
766
767#[cfg(not(all(target_os = "linux", target_pointer_width = "64")))]
768fn doorbell_wait(_word: &AtomicU64, _seen: u64, _timeout: Duration) {
769 std::thread::sleep(Duration::from_micros(50));
770}
771
772#[cfg(not(all(target_os = "linux", target_pointer_width = "64")))]
773fn doorbell_wake(_word: &AtomicU64) {}
774
775/// A byte stream over a region: writes are buffered and published as records on
776/// [`std::io::Write::flush`] (split at `max_record`); reads return record bytes in order.
777/// A ring refusal surfaces as an `InvalidData` I/O error carrying the [`RingRefusal`],
778/// which the frame transport turns into `WireRingViolation`. Dropping the stream closes its
779/// sender.
780pub struct RingStream {
781 tx: RingSender,
782 rx: RingReceiver,
783 out: Vec<u8>,
784 inbuf: Vec<u8>,
785 pos: usize,
786}
787
788impl RingStream {
789 pub fn new(tx: RingSender, rx: RingReceiver) -> Self {
790 Self {
791 tx,
792 rx,
793 out: Vec::new(),
794 inbuf: Vec::new(),
795 pos: 0,
796 }
797 }
798
799 /// Records (sent, received) so far.
800 pub fn records(&self) -> (u64, u64) {
801 (self.tx.records_sent(), self.rx.records_received())
802 }
803}
804
805fn ring_io(r: RingRefusal) -> std::io::Error {
806 std::io::Error::new(std::io::ErrorKind::InvalidData, r)
807}
808
809impl std::io::Read for RingStream {
810 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
811 if buf.is_empty() {
812 return Ok(0);
813 }
814 while self.pos == self.inbuf.len() {
815 self.pos = 0;
816 if !self.rx.recv(&mut self.inbuf).map_err(ring_io)? {
817 self.inbuf.clear();
818 return Ok(0);
819 }
820 }
821 let n = buf.len().min(self.inbuf.len() - self.pos);
822 buf[..n].copy_from_slice(&self.inbuf[self.pos..self.pos + n]);
823 self.pos += n;
824 Ok(n)
825 }
826}
827
828impl std::io::Write for RingStream {
829 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
830 self.out.extend_from_slice(buf);
831 Ok(buf.len())
832 }
833
834 fn flush(&mut self) -> std::io::Result<()> {
835 let max = self.tx.cfg.max_record;
836 for chunk in self.out.chunks(max) {
837 self.tx.send(chunk).map_err(ring_io)?;
838 }
839 self.out.clear();
840 Ok(())
841 }
842}