feat(phase-ab): 4kHz timestamp stamping + rfm-sync-4k experiment + dc-align + L0b fresh watchdog

- Phase A: aOut1[264..271]=plc_ts / aIn1[264..279]=t_d2k_ns+plc_ts_echo (RTT p50=2.0ms p99=2.25ms, 7.7M samples)
- rfm-sync-4k chunked mode: implemented, measured infeasible (slot exec p50=295us > 250us budget)
- --dc-align + --sync-offset-ns/--dc-wphase-ns: DC-grid phase gating for FPRD/FPWR kicks;
  sweep showed net loss vs free-running async (p50 RTT 2.0->2.5-3.0ms), kept off in production
- L0b watchdog: fresh-stall >3s -> exit(42); fixes blind spot where bridge wedge freezes
  tx_seq and old echo watchdog condition stays false (2026-11-13 incident, cured by CX TwinCAT reset)
- ethercrab pdu_rx/pdu_loop patch: late/short/unknown-idx frames downgraded to Ignored
  instead of killing the tx_rx task (production robustness fix)
- plc_data_age metric: (dc_read - plc_ts) mod 250us, proved end-to-end DC grid lock
- production binary md5=72eb50fb deployed to D2000 + SSD p4
This commit is contained in:
Tony Cao 2026-11-16 17:19:17 +08:00
parent 788499cf55
commit ad312c0b00
4 changed files with 1151 additions and 138 deletions

File diff suppressed because it is too large Load Diff

View File

@ -290,7 +290,34 @@ use std::os::unix::io::FromRawFd;
pub const MB_REQ_OFF: usize = 0x0000;
pub const MB_REP_OFF: usize = 0x1000;
pub const MB_MAGIC: u32 = 0x5246_4D32; // "RFM2"
pub const MB_MAX_PAYLOAD: usize = 1024;
pub const MB_MAX_PAYLOAD: usize = 1400;
// ---- streaming chunk protocol ----
pub const MB_CHUNK: usize = 256;
pub const MB_NCHUNK: usize = 6; // 1400 = 5*256 + 120
pub const REQ_MARK_OFF: usize = 0x0F00;
pub const REP_MARK_OFF: usize = 0x1F00;
#[inline]
pub fn mark_pack(seq: u64, cnt: u32) -> u64 {
(((seq as u32) as u64) << 32) | (cnt as u64 & 0xFFFF_FFFF)
}
#[inline]
pub fn mark_seq(m: u64) -> u32 {
(m >> 32) as u32
}
#[inline]
pub fn mark_cnt(m: u64) -> u32 {
(m & 0xFFFF_FFFF) as u32
}
#[inline]
pub unsafe fn mark_load(p: *const u8) -> u64 {
(p as *const u64).read_volatile()
}
#[inline]
pub unsafe fn mark_store(p: *mut u8, v: u64) {
(p as *mut u64).write_volatile(v)
}
#[repr(C)]
pub struct Mailbox {
@ -298,6 +325,7 @@ pub struct Mailbox {
pub len: u32,
pub seq: u64,
pub ts_ns: u64,
pub _pad: u64, // header 24->32B: payload 16B-aligned for SIMD wide stores
pub payload: [u8; MB_MAX_PAYLOAD],
}
@ -349,15 +377,45 @@ pub fn ring_cont(fd: i32) -> io::Result<bool> {
#[inline]
pub unsafe fn dev_write(dst: *mut u8, src: &[u8]) {
// Single-instruction wide stores: one CPU store = one PCIe transaction.
// Old 8B volatile stores: ~1us per transaction on the wire (measured
// 125ns/B slope). 16B SIMD stores should halve transaction count.
#[cfg(target_arch = "aarch64")]
unsafe fn wide_copy(dst: *mut u8, src: *const u8, n: usize) -> usize {
use core::arch::aarch64::*;
let mut i = 0usize;
while i + 16 <= n {
let v = vld1q_u8(src.add(i));
vst1q_u8(dst.add(i), v);
i += 16;
}
i
}
#[cfg(all(target_arch = "x86_64", target_feature = "sse2"))]
unsafe fn wide_copy(dst: *mut u8, src: *const u8, n: usize) -> usize {
use core::arch::x86_64::*;
let mut i = 0usize;
while i + 16 <= n {
let v = _mm_loadu_si128(src.add(i) as *const __m128i);
_mm_storeu_si128(dst.add(i) as *mut __m128i, v);
i += 16;
}
i
}
#[cfg(not(any(target_arch = "aarch64", all(target_arch = "x86_64", target_feature = "sse2"))))]
unsafe fn wide_copy(dst: *mut u8, src: *const u8, n: usize) -> usize {
let _ = (dst, src);
0
}
let n = src.len();
let mut i = 0usize;
let mut i = unsafe { wide_copy(dst, src.as_ptr(), n) };
while i + 8 <= n && (dst.add(i) as usize) % 8 == 0 {
let v = u64::from_le_bytes(src[i..i + 8].try_into().unwrap());
(dst.add(i) as *mut u64).write_volatile(v);
unsafe { (dst.add(i) as *mut u64).write_volatile(v); }
i += 8;
}
while i < n {
dst.add(i).write_volatile(src[i]);
unsafe { dst.add(i).write_volatile(src[i]); }
i += 1;
}
}

View File

@ -827,4 +827,81 @@ mod tests {
assert_eq!(&remaining[sent..], empty);
}
#[test]
fn concurrent_pdu_response_routing_no_cross_talk() {
crate::test_logger();
static STORAGE: PduStorage<4, { PduStorage::element_size(64) }> = PduStorage::new();
let (mut tx, mut rx, pdu_loop) = STORAGE.try_split().unwrap();
// Frame A: FPRD (cmd 0x04), frame B: FPWR (cmd 0x05)
let mut fa = pdu_loop.storage.alloc_frame().unwrap();
let ha = fa
.push_pdu(Command::fprd(0x1000, 0x8E00).into(), [0x11u8; 8], None)
.unwrap();
let fa = fa.mark_sendable(&pdu_loop, MAX_TIMEOUT, usize::MAX);
let mut fb = pdu_loop.storage.alloc_frame().unwrap();
let hb = fb
.push_pdu(Command::fpwr(0x1000, 0x1C00).into(), [0x55u8; 8], None)
.unwrap();
let fb = fb.mark_sendable(&pdu_loop, MAX_TIMEOUT, usize::MAX);
// Drive TX for both frames
while let Some(f) = tx.next_sendable_frame() {
f.send_blocking(|d| Ok(d.len())).unwrap();
}
fn resp(cmd: u8, idx: u8, adp: u16, ado: u16, data: &[u8], wkc: u16) -> Vec<u8> {
let mut f = std::vec::Vec::new();
f.extend_from_slice(&[0xff, 0xff, 0xff, 0xff, 0xff, 0xff]);
f.extend_from_slice(&[0x12, 0x10, 0x10, 0x10, 0x10, 0x10]);
f.extend_from_slice(&[0x88, 0xa4]);
let pdu_len = 10 + data.len() + 2;
f.extend_from_slice(&(pdu_len as u16 | (1 << 12)).to_le_bytes());
f.push(cmd);
f.push(idx);
f.extend_from_slice(&adp.to_le_bytes());
f.extend_from_slice(&ado.to_le_bytes());
f.extend_from_slice(&(data.len() as u16).to_le_bytes());
f.extend_from_slice(&0u16.to_le_bytes());
f.extend_from_slice(data);
f.extend_from_slice(&wkc.to_le_bytes());
f
}
// Deliver ONLY A's response
rx.receive_frame(&resp(0x04, ha.pdu_idx, 0x1000, 0x8E00, &[0x22u8; 8], 1))
.unwrap();
let mut fa = pin!(fa);
let mut fb = pin!(fb);
let ra = futures_lite::future::block_on(futures_lite::future::poll_once(fa.as_mut()))
.unwrap()
.expect("A ready");
let pa = ra.first_pdu(ha).expect("A pdu");
assert_eq!(pa.working_counter, 1, "A must get its own wkc");
// B must STILL be pending - cross-talk assertion
assert!(
matches!(
futures_lite::future::block_on(futures_lite::future::poll_once(fb.as_mut())),
None
),
"B completed early: response cross-talk"
);
// Now deliver B's response
rx.receive_frame(&resp(0x05, hb.pdu_idx, 0x1000, 0x1C00, &[0x66u8; 8], 3))
.unwrap();
let rb = futures_lite::future::block_on(futures_lite::future::poll_once(fb.as_mut()))
.unwrap()
.expect("B ready");
let pb = rb.first_pdu(hb).expect("B pdu");
assert_eq!(pb.working_counter, 3, "B must get its own wkc");
assert_eq!(&pb[..4], &[0x66u8; 4][..], "B must get its own data");
}
}

View File

@ -53,7 +53,14 @@ impl<'sto> PduRx<'sto> {
return Ok(ReceiveAction::Ignored);
}
let raw_packet = EthernetFrame::new_checked(ethernet_frame)?;
let raw_packet = match EthernetFrame::new_checked(ethernet_frame) {
Ok(p) => p,
Err(e) => {
fmt::warn!("Ignoring unparseable Ethernet frame: {}", e);
return Ok(ReceiveAction::Ignored);
}
};
// Look for EtherCAT packets whilst ignoring broadcast packets sent from self. As per
// <https://github.com/OpenEtherCATsociety/SOEM/issues/585#issuecomment-1013688786>, the
@ -69,9 +76,14 @@ impl<'sto> PduRx<'sto> {
let i = raw_packet.payload();
let frame_header = EthercatFrameHeader::unpack_from_slice(i).inspect_err(|&e| {
fmt::error!("Failed to parse frame header: {}", e);
})?;
let frame_header = match EthercatFrameHeader::unpack_from_slice(i) {
Ok(h) => h,
Err(e) => {
fmt::warn!("Ignoring frame with unparseable header: {}", e);
return Ok(ReceiveAction::Ignored);
}
};
if frame_header.payload_len == 0 {
fmt::trace!("Ignoring empty frame");
@ -80,16 +92,17 @@ impl<'sto> PduRx<'sto> {
}
// Skip EtherCAT header and get PDU(s) payload
let i = i
.get(
EthercatFrameHeader::PACKED_LEN
..(EthercatFrameHeader::PACKED_LEN + usize::from(frame_header.payload_len)),
)
.ok_or_else(|| {
fmt::error!("Received frame is too short");
//
// PATCH(rustbootd bench): a truncated/corrupt frame (payload_len beyond
// the actual frame) must not kill the TX/RX task; ignore it.
let Some(i) = i.get(
EthercatFrameHeader::PACKED_LEN
..(EthercatFrameHeader::PACKED_LEN + usize::from(frame_header.payload_len)),
) else {
fmt::warn!("Ignoring truncated frame (claimed payload_len exceeds frame)");
Error::ReceiveFrame
})?;
return Ok(ReceiveAction::Ignored);
};
// `i` now contains the EtherCAT frame payload, consisting of one or more PDUs including
// their headers and payloads.
@ -101,10 +114,15 @@ impl<'sto> PduRx<'sto> {
// use the first one.
// PDU has its own EtherCAT index. This needs mapping back to the original frame.
let frame_index = self
.storage
.frame_index_by_first_pdu_index(pdu_idx)
.ok_or(Error::Pdu(PduError::Decode))?;
//
// PATCH(rustbootd bench): a late/duplicate response whose frame slot was
// already freed (e.g. after a PDU timeout) must NOT kill the TX/RX task.
// Ignore it instead of propagating a fatal Decode error.
let Some(frame_index) = self.storage.frame_index_by_first_pdu_index(pdu_idx) else {
fmt::warn!("Ignoring response for unknown PDU index {:#04x}", pdu_idx);
return Ok(ReceiveAction::Ignored);
};
fmt::trace!(
"Receiving frame index {} (found from PDU {:#04x})",
@ -112,10 +130,19 @@ impl<'sto> PduRx<'sto> {
pdu_idx
);
let mut frame = self
.storage
.claim_receiving(frame_index)
.ok_or(PduError::InvalidIndex(frame_index))?;
// PATCH(rustbootd bench): a frame that is no longer in the receiving
// state (timed out / replaced) is ignored rather than killing TX/RX.
let mut frame = match self.storage.claim_receiving(frame_index) {
Some(frame) => frame,
None => {
fmt::warn!(
"Ignoring frame index {} not in receiving state",
frame_index
);
return Ok(ReceiveAction::Ignored);
}
};
let frame_data = frame.buf_mut();