use std::io::{Read, Write};
use std::sync::mpsc::{Receiver, TryRecvError};
use std::time::{Duration, Instant};
use ch32rv_contract::Warning;
use ch32rv_contract::policy::MonitorSource;
use ch32rv_dmi::MailboxShape;
use serialport::SerialPort;
use crate::cmd_probe::Entry;
use crate::session::Session;
use crate::source::DmiSource;
const AMBIGUOUS_STAYS: Duration = Duration::from_secs(1);
fn dmdata_shaped(d0: u32) -> bool {
d0 & 0x80 != 0 && (4..=11).contains(&(d0 & 0x3f))
}
const LEFTOVER_READS: u8 = 3;
#[derive(Debug, PartialEq, Eq)]
enum Verdict {
Wait,
Clear,
Found(MonitorSource),
}
#[derive(Default)]
struct Vote {
ambiguous: Option<(u32, u32, Instant)>,
other_run: u8,
}
impl Vote {
fn feed(&mut self, d0: u32, d1: u32) -> Verdict {
let found = match ch32rv_dmi::mailbox_shape(d0, d1) {
MailboxShape::Empty => return Verdict::Wait,
MailboxShape::Sdi => MonitorSource::Sdi,
MailboxShape::Dmseq if dmdata_shaped(d0) => match self.ambiguous {
Some((a0, a1, _)) if (a0, a1) != (d0, d1) => MonitorSource::Dmseq,
Some((_, _, since)) if since.elapsed() >= AMBIGUOUS_STAYS => MonitorSource::Dmseq,
Some(_) => return Verdict::Wait,
None => {
self.ambiguous = Some((d0, d1, Instant::now()));
return Verdict::Wait;
}
},
MailboxShape::Dmseq => MonitorSource::Dmseq,
MailboxShape::Dmdata => MonitorSource::Dmdata,
MailboxShape::Other => {
self.other_run += 1;
if self.other_run >= LEFTOVER_READS {
self.other_run = 0;
return Verdict::Clear;
}
return Verdict::Wait;
}
};
*self = Vote::default();
Verdict::Found(found)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Path {
Uart,
Mail,
}
enum Kind {
Uart,
Wch(Box<Wch>),
Oep(Box<Oep>),
}
struct Wch {
session: Session,
mail: Option<DmiSource>,
vote: Vote,
restarts: u64,
reset_checked: Instant,
armed: bool,
}
const ALLRESUMEACK: u32 = 1 << 17;
fn arm_restart_watch(session: &mut Session) -> bool {
let _ = session.dm().halt();
let _ = session.dm().resume();
session.dm().dmstatus().is_ok_and(|s| s & ALLRESUMEACK != 0)
}
const RESET_CHECK: Duration = Duration::from_millis(50);
const ANYHAVERESET: u32 = 1 << 18;
const OEP_QUIET: Duration = Duration::from_secs(5);
struct Oep {
addr: crate::oep::OepAddr,
chip: Option<String>,
speed: Option<u32>,
fixture: Option<crate::oep::ConsoleSession>,
mail: Option<(crate::oep::ConsoleSession, MonitorSource)>,
heard: Instant,
finding: Option<Finding>,
}
struct Finding {
rx: Receiver<Result<(crate::oep::ConsoleSession, MonitorSource), String>>,
stop: std::sync::Arc<std::sync::atomic::AtomicBool>,
}
impl Drop for Finding {
fn drop(&mut self) {
self.stop.store(true, std::sync::atomic::Ordering::Relaxed);
}
}
fn find_console(addr: &crate::oep::OepAddr, chip: Option<&str>, speed: Option<u32>) -> Finding {
use std::sync::atomic::{AtomicBool, Ordering};
let (tx, rx) = std::sync::mpsc::channel();
let stop = std::sync::Arc::new(AtomicBool::new(false));
let flag = stop.clone();
let addr = addr.clone();
let chip = chip.map(str::to_owned);
std::thread::spawn(move || {
let found = (|| {
let mut peek = crate::oep::MailboxPeek::open(&addr, chip.as_deref(), speed)?;
let mut vote = Vote::default();
let source = loop {
if flag.load(Ordering::Relaxed) {
return Err("stopped".to_owned());
}
let (d0, d1) = peek.words()?;
match vote.feed(d0, d1) {
Verdict::Found(src) => break src,
Verdict::Clear => peek.clear(),
Verdict::Wait => std::thread::sleep(Duration::from_millis(5)),
}
};
drop(peek);
let mech = match source {
MonitorSource::Sdi => ch32rv_oep::stream::Mechanism::Sdi,
MonitorSource::Dmdata => ch32rv_oep::stream::Mechanism::Dmdata,
_ => ch32rv_oep::stream::Mechanism::Dmseq,
};
let s = crate::oep::ConsoleSession::open(
&addr,
crate::oep::StreamWanted::Console(mech),
chip.as_deref(),
speed,
)?;
Ok((s, source))
})();
let _ = tx.send(found);
});
Finding { rx, stop }
}
pub(crate) struct Auto {
kind: Kind,
uart: Option<Box<dyn SerialPort>>,
last: Option<Path>,
q_uart: Vec<u8>,
q_mail: Vec<u8>,
said: String,
notes: Vec<u8>,
out_path: Option<usize>,
at_line_start: bool,
lines: [Lines; 2],
pub(crate) warnings: Vec<Warning>,
}
const LINE_WAIT: Duration = Duration::from_millis(150);
const LINE_HOLD_MAX: Duration = Duration::from_secs(1);
#[derive(Default)]
struct Lines {
buf: Vec<u8>,
since: Option<Instant>,
grew: Option<Instant>,
}
impl Lines {
fn push(&mut self, data: &[u8], out: &mut Vec<u8>) {
if data.is_empty() {
return;
}
self.buf.extend_from_slice(data);
if let Some(i) = self.buf.iter().rposition(|&b| b == b'\n') {
out.extend(self.buf.drain(..=i));
self.since = None;
self.grew = None;
}
if !self.buf.is_empty() {
self.since.get_or_insert_with(Instant::now);
self.grew = Some(Instant::now());
}
}
fn postpone(&mut self, d: Duration) {
self.since = self.since.map(|t| t + d);
self.grew = self.grew.map(|t| t + d);
}
fn flush_old(&mut self, out: &mut Vec<u8>) {
let quiet = self.grew.is_some_and(|t| t.elapsed() >= LINE_WAIT);
let long = self.since.is_some_and(|t| t.elapsed() >= LINE_HOLD_MAX);
if quiet || long {
out.append(&mut self.buf);
self.since = None;
self.grew = None;
}
}
}
fn note(text: &str) -> Vec<u8> {
format!("\r\n[ch32rv monitor] {text}\r\n").into_bytes()
}
impl Auto {
pub(crate) fn open_uart(port: Box<dyn SerialPort>) -> Self {
let mut a = Auto::new(Kind::Uart, Some(port));
a.say();
a
}
pub(crate) fn open_uart_only(port: Box<dyn SerialPort>, why: &str) -> Self {
let mut a = Auto::open_uart(port);
a.notes.extend(note(&format!(
"warning: reading the UART only; the debug paths did not open: {why}"
)));
a
}
pub(crate) fn open_wch(
entry: &Entry,
port: Option<Box<dyn SerialPort>>,
speed: ch32rv_wchlink::Speed,
lock_timeout: Duration,
chip: Option<&str>,
) -> Result<Self, String> {
let mut port = port;
if let Some(p) = port.as_mut()
&& let Ok(baud) = p.baud_rate()
{
let other = if baud == 9600 { 115_200 } else { 9600 };
if p.set_baud_rate(other).is_ok() {
std::thread::sleep(Duration::from_millis(50));
let _ = p.set_baud_rate(baud);
}
let _ = p.clear(serialport::ClearBuffer::Input);
}
let mut warnings = Vec::new();
let mut session = Session::attach(
entry,
speed,
Duration::from_millis(1000),
lock_timeout,
chip,
None,
&mut warnings,
)
.map_err(|e| format!("attach: {}", e.with_fix()))?;
let (d0, d1) = session
.dm()
.mailbox_words()
.map_err(|e| format!("mailbox: {e}"))?;
if matches!(
ch32rv_dmi::mailbox_shape(d0, d1),
ch32rv_dmi::MailboxShape::Other
) {
session
.dm()
.dmdata_clear()
.map_err(|e| format!("mailbox: {e}"))?;
}
let must_reset = warnings.iter().any(|w| {
matches!(
w.code.as_str(),
"attach-corrupts-register" | "attach-may-corrupt-register"
)
});
if must_reset {
if let Some(p) = port.as_mut() {
let _ = p.clear(serialport::ClearBuffer::Input);
}
crate::cmd_flash::soft_reset_and_run(&mut session)?;
}
follow_running_hart(&mut session);
let armed = arm_restart_watch(&mut session);
warnings.retain(|w| {
!matches!(
w.code.as_str(),
"attach-reclocks-target"
| "attach-corrupts-register"
| "attach-may-corrupt-register"
)
});
let now = Instant::now();
let mut a = Auto::new(
Kind::Wch(Box::new(Wch {
session,
mail: None,
vote: Vote::default(),
restarts: 0,
reset_checked: now,
armed,
})),
port,
);
a.warnings = warnings;
a.say();
Ok(a)
}
pub(crate) fn open_oep(
addr: &crate::oep::OepAddr,
chip: Option<&str>,
speed: Option<u32>,
baud: u32,
) -> Result<Self, String> {
let fixture = crate::oep::ConsoleSession::open(
addr,
crate::oep::StreamWanted::FixtureUart(baud),
chip,
speed,
)
.ok();
let oep = Oep {
addr: addr.clone(),
chip: chip.map(str::to_owned),
speed,
fixture,
mail: None,
heard: Instant::now(),
finding: Some(find_console(addr, chip, speed)),
};
let mut a = Auto::new(Kind::Oep(Box::new(oep)), None);
a.say();
Ok(a)
}
fn new(kind: Kind, uart: Option<Box<dyn SerialPort>>) -> Self {
Auto {
kind,
uart,
last: None,
q_uart: Vec::new(),
q_mail: Vec::new(),
said: String::new(),
notes: Vec::new(),
lines: Default::default(),
out_path: None,
at_line_start: true,
warnings: Vec::new(),
}
}
pub(crate) fn status(&self) -> (String, Option<String>) {
let mut parts: Vec<String> = Vec::new();
let mut looking: Vec<&str> = Vec::new();
match &self.kind {
Kind::Uart => parts.push("uart".to_owned()),
Kind::Wch(w) => {
if self.uart.is_some() {
parts.push("uart".to_owned());
}
match &w.mail {
Some(m) => parts.push(m.name().to_owned()),
None => looking.push("dmseq / sdi / dmdata"),
}
}
Kind::Oep(o) => {
if o.fixture.is_some() {
parts.push("fixture-uart".to_owned());
}
match &o.mail {
Some((_, src)) => parts.push(src.as_str().to_owned()),
None => looking.push("dmseq / sdi / dmdata"),
}
}
}
let read = if parts.is_empty() {
"auto: (nothing yet)".to_owned()
} else {
format!("auto: {}", parts.join(" + "))
};
let looking =
(!looking.is_empty()).then(|| format!("; looking for {}", looking.join(", ")));
(read, looking)
}
fn say(&mut self) {
if self.said.is_empty() {
let (read, looking) = self.status();
self.notes
.extend(note(&format!("{read}{}", looking.unwrap_or_default())));
self.said = read;
}
}
pub(crate) fn input(&mut self, data: &[u8]) {
if data.is_empty() {
return;
}
let q = match self.last {
Some(Path::Mail) => &mut self.q_mail,
Some(Path::Uart) | None => &mut self.q_uart,
};
q.extend_from_slice(data);
}
fn restarted(&mut self) {
self.q_uart.clear();
self.q_mail.clear();
self.last = None;
}
pub(crate) fn set_line(&mut self, baud: u32, dtr: bool, rts: bool) -> Result<(), String> {
if let Some(p) = self.uart.as_mut() {
let _ = p.set_baud_rate(baud);
let _ = p.write_data_terminal_ready(dtr);
let _ = p.write_request_to_send(rts);
}
if let Kind::Oep(o) = &mut self.kind
&& let Some(f) = o.fixture.as_mut()
{
f.set_baud(baud)?;
}
Ok(())
}
pub(crate) fn poll(&mut self) -> Result<Vec<u8>, String> {
let mut out = std::mem::take(&mut self.notes);
if !out.is_empty() {
self.at_line_start = true;
self.out_path = None;
}
let mut from_uart = Vec::new();
if let Some(p) = self.uart.as_mut() {
if !self.q_uart.is_empty() {
p.write_all(&self.q_uart)
.map_err(|e| format!("serial port write failed: {e}"))?;
self.q_uart.clear();
}
let mut buf = [0u8; 512];
match p.read(&mut buf) {
Ok(n) if n > 0 => {
from_uart.extend_from_slice(&buf[..n]);
self.last = Some(Path::Uart);
}
Ok(_) => {}
Err(e) if e.kind() == std::io::ErrorKind::TimedOut => {}
Err(e) => return Err(format!("serial port read failed: {e}")),
}
}
let round = Instant::now();
let got = match &mut self.kind {
Kind::Uart => Got::default(),
Kind::Wch(w) => w.poll(&mut self.q_mail)?,
Kind::Oep(o) => o.poll(&mut self.q_uart, &mut self.q_mail)?,
};
let took = round.elapsed();
if took >= Duration::from_millis(20) {
for l in &mut self.lines {
l.postpone(took);
}
}
if got.restarted {
self.restarted();
}
for (path, bytes) in [(Path::Uart, got.uart), (Path::Mail, got.mail)] {
let merged = if path == Path::Uart {
from_uart.extend_from_slice(&bytes);
&from_uart
} else {
&bytes
};
let mut whole = Vec::new();
self.lines[path as usize].push(merged, &mut whole);
self.emit(path as usize, &whole, &mut out);
if !merged.is_empty() {
self.last = Some(if path == Path::Mail && got.mail_is_sdi {
Path::Uart
} else {
path
});
}
}
if !self.has_uart() && !self.q_uart.is_empty() && self.last == Some(Path::Mail) {
self.q_mail.append(&mut self.q_uart);
}
for (code, msg) in got.notices {
self.notes.extend(note(&format!("{code}: {msg}")));
}
for i in 0..self.lines.len() {
let mut part = Vec::new();
self.lines[i].flush_old(&mut part);
self.emit(i, &part, &mut out);
}
self.say();
if !self.notes.is_empty() {
out.append(&mut self.notes);
self.at_line_start = true;
self.out_path = None;
}
Ok(out)
}
fn emit(&mut self, path: usize, data: &[u8], out: &mut Vec<u8>) {
if data.is_empty() {
return;
}
if !self.at_line_start && self.out_path != Some(path) {
out.extend_from_slice(b"\r\n");
}
out.extend_from_slice(data);
self.out_path = Some(path);
self.at_line_start = data.ends_with(b"\n");
}
fn has_uart(&self) -> bool {
self.uart.is_some() || matches!(&self.kind, Kind::Oep(o) if o.fixture.is_some())
}
pub(crate) fn idle(&self) -> Duration {
Duration::from_millis(2)
}
}
#[derive(Default)]
struct Got {
uart: Vec<u8>,
mail: Vec<u8>,
mail_is_sdi: bool,
restarted: bool,
notices: Vec<(&'static str, String)>,
}
fn follow_running_hart(session: &mut Session) {
if session.attach.family_byte != 0xc6 {
return;
}
std::thread::sleep(Duration::from_millis(50));
let family = session.attach.family_byte;
let ran = crate::session::harts_that_ran(session.link(), family);
if ran[1] {
let _ = session.select_core(1);
}
}
impl Wch {
fn poll(&mut self, q_mail: &mut Vec<u8>) -> Result<Got, String> {
let mut got = Got::default();
if self.reset_checked.elapsed() >= RESET_CHECK {
self.reset_checked = Instant::now();
let status = self
.session
.dm()
.dmstatus()
.map_err(|e| format!("dmstatus: {e}"))?;
let resumeack_fell = self.armed && status & ALLRESUMEACK == 0;
if status & ANYHAVERESET != 0 || resumeack_fell {
let _ = self.session.dm().ack_have_reset();
follow_running_hart(&mut self.session);
self.armed = arm_restart_watch(&mut self.session);
self.mail = None;
self.vote = Vote::default();
got.restarted = true;
}
}
match &mut self.mail {
None => {
let (d0, d1) = self
.session
.dm()
.mailbox_words()
.map_err(|e| format!("mailbox: {e}"))?;
let source = match self.vote.feed(d0, d1) {
Verdict::Found(src) => Some(src),
Verdict::Clear => {
let _ = self.session.dm().sdi_prepare();
None
}
Verdict::Wait => None,
};
if let Some(source) = source {
self.mail = Some(if source == MonitorSource::Dmdata {
DmiSource::Dmdata
} else {
DmiSource::open(&mut self.session, source, &mut Vec::new())
.map_err(|e| format!("open {}: {e}", source.as_str()))?
});
}
}
Some(m) => {
let is_sdi = m.name() == "sdi";
let mut none = Vec::new();
let q = if is_sdi { &mut none } else { q_mail };
got.mail = m
.poll(&mut self.session, q)
.map_err(|e| format!("{} failed: {e}", m.name()))?;
got.mail_is_sdi = is_sdi;
if m.take_notices()
.iter()
.any(|(code, _)| code.ends_with("-no-console"))
{
self.mail = None;
} else if m.restarts() > self.restarts {
self.restarts = m.restarts();
got.restarted = true;
}
}
}
Ok(got)
}
}
impl Oep {
fn poll(&mut self, q_uart: &mut Vec<u8>, q_mail: &mut Vec<u8>) -> Result<Got, String> {
let mut got = Got::default();
if let Some(f) = self.fixture.as_mut() {
if !q_uart.is_empty() {
let n = f.write(q_uart)?;
q_uart.drain(..n.min(q_uart.len()));
}
got.uart = f.poll()?;
}
if let Some(f) = &self.finding {
match f.rx.try_recv() {
Ok(Ok(found)) => {
self.mail = Some(found);
self.heard = Instant::now();
self.finding = None;
}
Ok(Err(e)) => {
got.notices.push(("console-not-found", e));
self.finding = None;
}
Err(TryRecvError::Disconnected) => self.finding = None,
Err(TryRecvError::Empty) => {}
}
}
if let Some((m, src)) = self.mail.as_mut() {
let is_sdi = *src == MonitorSource::Sdi;
if !is_sdi && !q_mail.is_empty() {
let n = m.write(q_mail)?;
q_mail.drain(..n.min(q_mail.len()));
}
got.mail = m.poll()?;
got.mail_is_sdi = is_sdi;
if !got.mail.is_empty() {
self.heard = Instant::now();
}
}
if self.mail.is_some() && self.heard.elapsed() >= OEP_QUIET {
self.mail = None;
self.finding = Some(find_console(&self.addr, self.chip.as_deref(), self.speed));
}
Ok(got)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn dmseq_word(status: u8, payload: &[u8]) -> (u32, u32) {
let mut b = [0u8; 8];
b[0] = 0x80 | status | payload.len() as u8;
b[1..1 + payload.len()].copy_from_slice(payload);
b[1 + payload.len()] = ch32rv_dmi::dmseq::crc8(&b[..1 + payload.len()]);
(
u32::from_le_bytes([b[0], b[1], b[2], b[3]]),
u32::from_le_bytes([b[4], b[5], b[6], b[7]]),
)
}
#[test]
fn each_framing_is_told_from_one_word() {
assert_eq!(
Vote::default().feed(0x0063_6202, 0),
Verdict::Found(MonitorSource::Sdi)
);
let (d0, d1) = dmseq_word(0x18, &[]);
assert_eq!(
Vote::default().feed(d0, d1),
Verdict::Found(MonitorSource::Dmseq)
);
assert_eq!(
Vote::default().feed(0x84, 0),
Verdict::Found(MonitorSource::Dmdata)
);
assert_eq!(Vote::default().feed(0, 0), Verdict::Wait);
}
#[test]
fn a_word_fitting_dmseq_and_dmdata_waits_for_the_next() {
let (d0, d1) = dmseq_word(0, b"tick");
assert!(dmdata_shaped(d0));
let mut v = Vote::default();
assert_eq!(v.feed(d0, d1), Verdict::Wait);
assert_eq!(
v.feed(d0, d1),
Verdict::Wait,
"the same word decides nothing"
);
let (e0, e1) = dmseq_word(0x20, b" 1");
assert_eq!(v.feed(e0, e1), Verdict::Found(MonitorSource::Dmseq));
}
#[test]
fn a_leftover_word_is_cleared_after_three_reads() {
let mut v = Vote::default();
assert_eq!(v.feed(0xe339_e339, 0x1fff_f7f0), Verdict::Wait);
assert_eq!(v.feed(0xe339_e339, 0x1fff_f7f0), Verdict::Wait);
assert_eq!(v.feed(0xe339_e339, 0x1fff_f7f0), Verdict::Clear);
}
}