use std::io::{Read, Write};
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, RttChannels, RttTarget};
struct KeepMailbox<'a> {
session: &'a mut Session,
saved: Option<(u32, u32)>,
}
impl RttTarget for KeepMailbox<'_> {
fn is_halted(&mut self) -> Result<bool, ch32rv_dmi::DmiError> {
self.session.is_halted()
}
fn halt(&mut self) -> Result<(), ch32rv_dmi::DmiError> {
self.session.halt()?;
if self.saved.is_none() {
self.saved = Some(self.session.dm().mailbox_words()?);
}
Ok(())
}
fn resume(&mut self) -> Result<(), ch32rv_dmi::DmiError> {
if let Some((d0, d1)) = self.saved.take() {
self.session.dm().set_mailbox_words(d0, d1)?;
}
self.session.resume()
}
fn read(&mut self, addr: u32, len: u32) -> Result<Vec<u8>, ch32rv_dmi::DmiError> {
self.session.read(addr, len)
}
fn write(&mut self, addr: u32, data: &[u8]) -> Result<(), ch32rv_dmi::DmiError> {
RttTarget::write(self.session, addr, data)
}
}
const RTT_SCANS_MS: [u64; 3] = [500, 2000, 4000];
const RTT_EVERY: Duration = Duration::from_millis(50);
const OEP_TRY: Duration = Duration::from_secs(3);
const OEP_ORDER: [MonitorSource; 3] = [
MonitorSource::Dmseq,
MonitorSource::Sdi,
MonitorSource::Dmdata,
];
const LEFTOVER_READS: u8 = 3;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Path {
Uart,
Mail,
Rtt,
}
enum Kind {
Uart,
Wch(Box<Wch>),
Oep(Box<Oep>),
}
struct Wch {
session: Session,
mail: Option<DmiSource>,
other_run: u8,
rtt: Option<RttChannels>,
rtt_polled: Instant,
rtt_from: Instant,
rtt_scans: usize,
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>,
trying: usize,
since: Instant,
locked: bool,
heard: Instant,
rtt: Option<crate::oep::ConsoleSession>,
rtt_tried: bool,
rtt_polled: Instant,
opened: Instant,
}
pub(crate) struct Auto {
kind: Kind,
uart: Option<Box<dyn SerialPort>>,
last: Option<Path>,
q_uart: Vec<u8>,
q_mail: Vec<u8>,
q_rtt: Vec<u8>,
said: String,
notes: Vec<u8>,
out_path: Option<usize>,
at_line_start: bool,
lines: [Lines; 3],
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 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()))?;
session
.dm()
.dmdata_clear()
.map_err(|e| format!("mailbox: {e}"))?;
let mut port = port;
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,
other_run: 0,
rtt: None,
rtt_polled: now,
rtt_from: now,
rtt_scans: 0,
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 mut oep = Oep {
addr: addr.clone(),
chip: chip.map(str::to_owned),
speed,
fixture,
mail: None,
trying: 0,
since: Instant::now(),
locked: false,
heard: Instant::now(),
rtt: None,
rtt_tried: false,
rtt_polled: Instant::now(),
opened: Instant::now(),
};
oep.mail = oep.open_mail(0).ok();
if oep.fixture.is_none() && oep.mail.is_none() {
oep.open_mail(0)?;
}
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(),
q_rtt: 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"),
}
if w.rtt.is_some() {
parts.push("rtt".to_owned());
} else if w.rtt_scans < RTT_SCANS_MS.len() {
looking.push("rtt");
}
}
Kind::Oep(o) => {
if o.fixture.is_some() {
parts.push("fixture-uart".to_owned());
}
if o.locked {
parts.push(OEP_ORDER[o.trying].as_str().to_owned());
} else {
looking.push("dmseq / sdi / dmdata");
}
if o.rtt.is_some() {
parts.push("rtt".to_owned());
} else if !o.rtt_tried {
looking.push("rtt");
}
}
}
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::Rtt) => &mut self.q_rtt,
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.q_rtt.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, &mut self.q_rtt)?,
Kind::Oep(o) => o.poll(&mut self.q_uart, &mut self.q_mail, &mut self.q_rtt)?,
};
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),
(Path::Rtt, got.rtt),
] {
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() {
match self.last {
Some(Path::Mail) => self.q_mail.append(&mut self.q_uart),
Some(Path::Rtt) => self.q_rtt.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,
rtt: Vec<u8>,
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 rearm(&mut self) {
let set = self
.session
.dm()
.dmstatus()
.is_ok_and(|s| s & ALLRESUMEACK != 0);
self.armed = set || arm_restart_watch(&mut self.session);
}
fn poll(&mut self, q_mail: &mut Vec<u8>, q_rtt: &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.other_run = 0;
self.rtt = None;
self.rtt_scans = 0;
self.rtt_from = Instant::now();
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 ch32rv_dmi::mailbox_shape(d0, d1) {
MailboxShape::Empty => None,
MailboxShape::Sdi => Some(MonitorSource::Sdi),
MailboxShape::Dmseq => Some(MonitorSource::Dmseq),
MailboxShape::Dmdata => Some(MonitorSource::Dmdata),
MailboxShape::Other => {
self.other_run += 1;
if self.other_run >= LEFTOVER_READS {
self.other_run = 0;
let _ = self.session.dm().sdi_prepare();
}
None
}
};
if let Some(source) = source {
self.other_run = 0;
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;
self.rtt = None;
self.rtt_scans = 0;
self.rtt_from = Instant::now();
}
}
}
match &mut self.rtt {
None => {
if self.rtt_scans < RTT_SCANS_MS.len()
&& self.rtt_from.elapsed()
>= Duration::from_millis(RTT_SCANS_MS[self.rtt_scans])
{
self.rtt_scans += 1;
let window = crate::source::rtt_window_in(
self.session.db(),
Some(self.session.attach.chip_id),
);
let mut keep = KeepMailbox {
session: &mut self.session,
saved: None,
};
if let Ok(ch) =
crate::source::rtt_find_tries(&mut keep, window, &mut Vec::new(), 1)
{
self.rtt = Some(ch);
self.rtt_polled = Instant::now();
}
let _ = keep.resume();
self.rearm();
}
}
Some(ch) => {
if self.rtt_polled.elapsed() >= RTT_EVERY {
self.rtt_polled = Instant::now();
let mut keep = KeepMailbox {
session: &mut self.session,
saved: None,
};
got.rtt = crate::source::rtt_poll(&mut keep, *ch, q_rtt)
.map_err(|e| format!("rtt failed: {e}"))?;
self.rearm();
}
}
}
Ok(got)
}
}
impl Oep {
fn open_mail(&self, i: usize) -> Result<crate::oep::ConsoleSession, String> {
use ch32rv_oep::stream::Mechanism;
let mech = match OEP_ORDER[i] {
MonitorSource::Dmseq => Mechanism::Dmseq,
MonitorSource::Sdi => Mechanism::Sdi,
_ => Mechanism::Dmdata,
};
crate::oep::ConsoleSession::open(
&self.addr,
crate::oep::StreamWanted::Console(mech),
self.chip.as_deref(),
self.speed,
)
}
fn poll(
&mut self,
q_uart: &mut Vec<u8>,
q_mail: &mut Vec<u8>,
q_rtt: &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()?;
}
let is_sdi = OEP_ORDER[self.trying] == MonitorSource::Sdi;
if let Some(m) = self.mail.as_mut() {
if self.locked && !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.locked = true;
self.heard = Instant::now();
}
}
if self.locked && self.heard.elapsed() >= OEP_QUIET {
self.locked = false;
self.since = Instant::now()
.checked_sub(OEP_TRY)
.unwrap_or_else(Instant::now);
}
if !self.locked && self.since.elapsed() >= OEP_TRY {
self.mail = None;
self.trying = (self.trying + 1) % OEP_ORDER.len();
self.since = Instant::now();
self.mail = self.open_mail(self.trying).ok();
}
if !self.rtt_tried && self.opened.elapsed() >= Duration::from_millis(RTT_SCANS_MS[0]) {
self.rtt_tried = true;
self.rtt = crate::oep::ConsoleSession::open(
&self.addr,
crate::oep::StreamWanted::Rtt,
self.chip.as_deref(),
self.speed,
)
.ok();
}
if let Some(r) = self.rtt.as_mut()
&& self.rtt_polled.elapsed() >= RTT_EVERY
{
self.rtt_polled = Instant::now();
if !q_rtt.is_empty() {
let n = r.write(q_rtt)?;
q_rtt.drain(..n.min(q_rtt.len()));
}
got.rtt = r.poll()?;
}
Ok(got)
}
}