Skip to main content

ch32_hal/
debug.rs

1//! The debug module.
2//!
3//! See-also: https://github.com/openwch/ch32v003/blob/main/EVT/EXAM/SDI_Printf/SDI_Printf/Debug/debug.c
4
5use qingke::dm::{DATA0, DATA1};
6use qingke::riscv;
7
8const DEBUG_DATA0_ADDRESS: *mut u32 = DATA0 as *mut u32;
9const DEBUG_DATA1_ADDRESS: *mut u32 = DATA1 as *mut u32;
10
11/// Give the debug-interface pins back to GPIO (`AFIO.PCFR1.SW_CFG = 0b100`).
12///
13/// The debugger can only reattach after resetting into the system bootloader.
14#[cfg(afio)]
15pub fn release_swd_pins() {
16    crate::pac::AFIO.pcfr1().modify(|w| w.set_sw_cfg(0b100));
17}
18
19pub struct SDIPrint;
20
21impl SDIPrint {
22    pub fn enable() {
23        unsafe {
24            // Enable SDI print
25            core::ptr::write_volatile(DEBUG_DATA0_ADDRESS, 0);
26            riscv::asm::delay(100000);
27        }
28    }
29
30    #[inline]
31    pub fn is_busy() -> bool {
32        unsafe { core::ptr::read_volatile(DEBUG_DATA0_ADDRESS) != 0 }
33    }
34
35    /// Write, giving up (and dropping the rest of the message) once a chunk
36    /// waits longer than [`SPINS`] iterations.
37    ///
38    /// SDI print is only drained while the debugger has it armed
39    /// (`wlink --enable-sdi-print`). With it disarmed the blocking
40    /// [`core::fmt::Write`] impl spins forever on the second chunk — which is
41    /// fine for a core that has nothing else to do, but not for a core in a
42    /// control loop (or on hart 1, which must not stall behind a console).
43    pub fn write_str_lossy(s: &str) -> core::fmt::Result {
44        write(s, Some(SPINS))
45    }
46}
47
48/// Writer that routes formatting through [`SDIPrint::write_str_lossy`], so a
49/// `try_println!` never blocks even though `SDIPrint`'s own [`core::fmt::Write`]
50/// impl does.
51struct LossyWriter;
52
53impl core::fmt::Write for LossyWriter {
54    fn write_str(&mut self, s: &str) -> core::fmt::Result {
55        SDIPrint::write_str_lossy(s)
56    }
57}
58
59/// Format `args` into the lossy writer and terminate the line.
60pub fn write_fmt_lossy(args: core::fmt::Arguments) -> core::fmt::Result {
61    use core::fmt::Write as _;
62
63    let mut writer = LossyWriter;
64    core::fmt::write(&mut writer, args)?;
65    writer.write_str("\n")
66}
67
68/// Iterations [`SDIPrint::write_str_lossy`] tolerates per chunk. Kept small
69/// because each iteration is a *debug-module* read, which is far slower than a
70/// normal load — and deliberately *not* remembered across calls: a console that
71/// attaches later must still receive output, so each message pays its own budget.
72const SPINS: u32 = 20_000;
73
74impl core::fmt::Write for SDIPrint {
75    fn write_str(&mut self, s: &str) -> core::fmt::Result {
76        write(s, None)
77    }
78}
79
80fn write(s: &str, spins: Option<u32>) -> core::fmt::Result {
81    {
82        let mut data = [0u8; 8];
83        for chunk in s.as_bytes().chunks(7) {
84            data[1..chunk.len() + 1].copy_from_slice(chunk);
85            data[0] = chunk.len() as u8;
86
87            // data1 is the last 4 bytes of data
88            let data1 = u32::from_le_bytes(data[4..].try_into().unwrap());
89            let data0 = u32::from_le_bytes(data[..4].try_into().unwrap());
90
91            let mut waited = 0u32;
92            while SDIPrint::is_busy() {
93                if let Some(limit) = spins {
94                    waited += 1;
95                    if waited > limit {
96                        return Ok(());
97                    }
98                }
99            }
100
101            unsafe {
102                core::ptr::write_volatile(DEBUG_DATA1_ADDRESS, data1);
103                core::ptr::write_volatile(DEBUG_DATA0_ADDRESS, data0);
104            }
105        }
106
107        Ok(())
108    }
109}
110
111/// `println!` over SDI that drops the message rather than spinning when the
112/// console is not armed. Use it in control loops; use [`println!`] when the
113/// console is known to be attached.
114#[macro_export]
115macro_rules! try_println {
116    ($($arg:tt)*) => {
117        {
118            // Not `writeln!(&mut SDIPrint, ..)`: that goes through the *blocking*
119            // `Write` impl, which is exactly what this variant exists to avoid.
120            let _ = $crate::debug::write_fmt_lossy(format_args!($($arg)*));
121        }
122    };
123}
124
125#[macro_export]
126macro_rules! println {
127    ($($arg:tt)*) => {
128        {
129            use core::fmt::Write;
130            use core::writeln;
131
132            writeln!(&mut $crate::debug::SDIPrint, $($arg)*).unwrap();
133        }
134    }
135}
136
137#[macro_export]
138macro_rules! print {
139    ($($arg:tt)*) => {
140        {
141            use core::fmt::Write;
142            use core::write;
143
144            write!(&mut $crate::debug::SDIPrint, $($arg)*).unwrap();
145        }
146    }
147}