ch32rv 0.25.0

Flashing and debugging tool for WCH CH32 RISC-V microcontrollers
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
//! en: Shared attach session for probe-routed commands that talk to the target
//! (`target info`, `dbg *`, `read`). Opens the probe, attaches, hands the caller a
//! [`ch32rv_dmi::DebugModule`], and always detaches on drop. Read-only by itself: it issues
//! SetSpeed + AttachChip, never a write to flash.
//! ja: target と会話する probe 経路コマンド共通の attach セッション。probe を開いて attach し、
//! DebugModule を渡し、drop 時に必ず detach する。それ自体は読み取り専用。

use std::time::Duration;

use ch32rv_contract::Warning;
use ch32rv_dmi::{DebugModule, DtmAccess};
use ch32rv_usb::{DeviceLock, LockError};
use ch32rv_wchlink::{
    AttachInfo, ChipInfo, ChipInfoStatus, ProbeInfo, Speed, WchLink, WchLinkError, family_name,
};

use crate::cmd_probe::Entry;

/// A held attach session. Detaches the target core when dropped (unless suppressed).
pub struct Session {
    link: WchLink,
    pub attach: AttachInfo,
    pub probe_info: ProbeInfo,
    /// ChipInfo readback (flash size / UUID), when the target answered it.
    pub chip: Option<ChipInfo>,
    /// en: The target DB this invocation resolved against - the built-in tables, or those plus a
    /// `--db` overlay. Held here so every consumer (SKU lookup, family string, RTT scan length)
    /// agrees; building it per call site is how `--db` silently applied to some of them and not
    /// others. ja: この実行が使う target DB(内蔵、または `--db` overlay 込み)。各所で作り直すと
    /// `--db` が一部にしか効かないので session が 1 つ持つ。
    db: ch32rv_target::Db,
    /// Per-probe advisory lock, held for the session's lifetime (released on drop).
    _lock: DeviceLock,
    /// A reset that runs the target was done (`--release-dm` resets once more on drop).
    reset_run: bool,
    /// H417: which harts were running before this session stopped them (see [`hart_ran`]).
    ran_before: [bool; 2],
}

/// What went wrong, so the CLI can pick the right exit code.
pub enum SessionError {
    Open(WchLinkError),
    ProbeInfo(WchLinkError),
    /// No target answered on the debug pins (attach got 0x55 / no response) - exit 20.
    NoTarget,
    /// Attach failed for another reason (SetSpeed, unexpected error) - exit 22.
    Attach(String),
    /// `--chip` conflicts with the detected target (exit 23).
    ChipMismatch(String),
    /// `--chip` names something the DB has never heard of, so it cannot be checked (exit 20).
    ChipNotInDb(String),
    /// The `--db` overlay could not be read or parsed (exit 2).
    DbOverlay(String),
    /// The per-probe advisory lock could not be taken in time (exit 13).
    Busy(LockError),
}

/// One line for places that can only show text (the Arduino monitor's data stream).
impl std::fmt::Display for SessionError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SessionError::Open(e) | SessionError::ProbeInfo(e) => write!(f, "{e}"),
            SessionError::NoTarget => f.write_str("no target detected on the debug pins"),
            SessionError::Attach(m)
            | SessionError::ChipMismatch(m)
            | SessionError::ChipNotInDb(m)
            | SessionError::DbOverlay(m) => f.write_str(m),
            SessionError::Busy(e) => write!(f, "{e} (another ch32rv is using this probe)"),
        }
    }
}

impl Session {
    pub fn select_core(&mut self, core: u32) -> Result<(), String> {
        if core == 0 {
            return Ok(());
        }
        if core != 1 || self.attach.family_byte != 0xc6 {
            return Err("--core 1 requires an attached CH32H417 target".into());
        }
        self.link.select_hart(core).map_err(|e| e.to_string())
    }

    /// en: Open + clear state + attach. `warnings` accumulates non-fatal notes (corrupted
    /// readback recovery, etc.). Retries the open per docs/cli.ja.md §3.7. When `chip` (`--chip`)
    /// is given, it is validated against the detected chip and a conflict fails closed (exit 23).
    /// ja: open + 状態クリア + attach。`--chip` 指定時は検出と突き合わせ、矛盾なら fail-closed(exit 23)。
    pub fn attach(
        entry: &Entry,
        speed: Speed,
        timeout: Duration,
        lock_timeout: Duration,
        chip: Option<&str>,
        db_overlay: Option<&std::path::Path>,
        warnings: &mut Vec<Warning>,
    ) -> Result<Self, SessionError> {
        // en: Take the per-probe advisory lock before opening so concurrent ch32rv processes on
        // the same probe serialize instead of colliding (docs/cli.ja.md §3.7). Key by serial, or
        // by bus topology when the probe reports no serial. Held for the whole session.
        // ja: open 前に probe 単位の advisory lock を取り、同一 probe への並行アクセスを直列化する。
        let lock_key = entry
            .dev
            .serial()
            .map(str::to_owned)
            .unwrap_or_else(|| entry.dev.topology());
        let lock = DeviceLock::acquire(&lock_key, lock_timeout).map_err(SessionError::Busy)?;

        let db = match db_overlay {
            Some(path) => ch32rv_target::Db::with_overlay(path).map_err(SessionError::DbOverlay)?,
            None => ch32rv_target::Db::builtin(),
        };

        let mut link = open_with_retry(entry).map_err(SessionError::Open)?;
        link.set_timeout(timeout);
        // Clear any leftover state a previous session left holding the target.
        let _ = link.detach_chip();

        let probe_info = link.probe_info().map_err(SessionError::ProbeInfo)?;
        let attach = attach_once(&mut link, speed)?;

        // Validate an explicit --chip against the detected target (fail-closed on a family conflict).
        if let Some(requested) = chip
            && let Err(e) = check_chip(&db, requested, &attach)
        {
            let _ = link.detach_chip();
            return Err(e);
        }

        // en: Read ChipInfo, recovering once from the known LinkE corrupted-readback state.
        // ja: ChipInfo を読み、LinkE の壊れ読み値からは 1 度だけ復旧する。
        let chip = match link.chip_info() {
            Ok(ChipInfoStatus::Ok(ci)) => Some(ci),
            Ok(ChipInfoStatus::NoAnswer) => {
                warnings.push(Warning {
                    code: "uuid-unavailable".to_owned(),
                    msg: "the target did not answer the UUID query (protected, or unsupported by this family)".to_owned(),
                });
                None
            }
            Ok(ChipInfoStatus::CorruptedReadback) => {
                warnings.push(Warning {
                    code: "probe-readback-corrupted".to_owned(),
                    msg: "the probe held a corrupted target readback (known LinkE state); recovered via re-detect".to_owned(),
                });
                let _ = link.redetect_chip();
                let _ = link.detach_chip();
                let _ = attach_once(&mut link, speed)?;
                match link.chip_info() {
                    Ok(ChipInfoStatus::Ok(ci)) => Some(ci),
                    _ => {
                        warnings.push(Warning {
                            code: "probe-readback-corrupted".to_owned(),
                            msg: "recovery did not produce a clean readback; replug the probe if values look wrong".to_owned(),
                        });
                        None
                    }
                }
            }
            Err(_) => None,
        };
        if let Some(ci) = &chip
            && reported_flash_bytes(ci).is_none()
        {
            let (_, source) = flash_capacity(chip.as_ref(), &db, attach.chip_id);
            warnings.push(Warning {
                code: "flash-capacity-unavailable".to_owned(),
                msg: format!(
                    "ChipInfo flash capacity 0x{:04x} is zero or an erased pattern; capacity source: {source}",
                    ci.flash_bytes / 1024
                ),
            });
        }
        let mut ran_before = [false; 2];
        if attach.family_byte == 0xc6
            && RESUME_OTHER_HARTS.load(std::sync::atomic::Ordering::Relaxed)
        {
            for (hart, ran) in ran_before.iter_mut().enumerate() {
                *ran = hart_ran(&mut link, hart as u32).unwrap_or(false);
            }
            let _ = link.select_hart(0);
        }
        Ok(Self {
            link,
            attach,
            probe_info,
            chip,
            db,
            _lock: lock,
            reset_run: false,
            ran_before,
        })
    }

    /// Family name from the attach signature (None -> "unknown(0xNN)").
    pub fn family(&self) -> String {
        family_name(self.attach.family_byte)
            .map(str::to_owned)
            .unwrap_or_else(|| format!("unknown(0x{:02x})", self.attach.family_byte))
    }

    /// Borrow a Debug Module driver over the probe's DMI transport.
    /// The target DB for this invocation (built-in, plus `--db` when given).
    pub fn db(&self) -> &ch32rv_target::Db {
        &self.db
    }

    /// Capacity from the probe when populated, otherwise from an unambiguous DB SKU.
    pub fn flash_capacity(&self) -> (Option<u32>, &'static str) {
        flash_capacity(self.chip.as_ref(), &self.db, self.attach.chip_id)
    }

    /// Note that a reset which runs the target was done (for `--release-dm` on drop).
    pub fn mark_reset_run(&mut self) {
        self.reset_run = true;
    }

    pub fn dm(&mut self) -> DebugModule<'_, WchLink> {
        DebugModule::new(&mut self.link)
    }

    /// en: Borrow the raw probe (for flash/erase/reset that live on `WchLink`).
    /// ja: raw probe を借りる(flash/erase/reset は `WchLink` 側)。
    pub fn link(&mut self) -> &mut WchLink {
        &mut self.link
    }
}

fn reported_flash_bytes(chip: &ChipInfo) -> Option<u32> {
    // X315's unpopulated signature reads 0xe339e339, also returned by ChipInfo.
    match chip.flash_bytes / 1024 {
        0 | 0xffff | 0xe339 => None,
        _ => Some(chip.flash_bytes),
    }
}

fn flash_capacity(
    chip: Option<&ChipInfo>,
    db: &ch32rv_target::Db,
    chip_id: u32,
) -> (Option<u32>, &'static str) {
    if let Some(bytes) = chip.and_then(reported_flash_bytes) {
        return (Some(bytes), "probe");
    }
    match db.resolve_by_chip_id(chip_id) {
        ch32rv_target::Resolution::Sku(s) if s.flash_bytes > 0 => (Some(s.flash_bytes), "db"),
        _ => (None, "unavailable"),
    }
}

impl Drop for Session {
    fn drop(&mut self) {
        if self.attach.family_byte == 0xc6
            && RESUME_OTHER_HARTS.load(std::sync::atomic::Ordering::Relaxed)
        {
            // Hart 0 under its own selection is the LinkE's to let go (DetachChip does).
            let keep = self.link.selected_hart();
            for hart in (0..2).filter(|&h| !(h == 0 && keep == 0)) {
                if self.ran_before[hart as usize]
                    && matches!(hart_ran(&mut self.link, hart), Ok(true))
                {
                    let _ = resume_hart(&mut self.link, hart);
                }
            }
        }
        if RELEASE_DM.load(std::sync::atomic::Ordering::Relaxed) {
            let _ = self.link.dmi_write(DMCONTROL, 0);
            if self.reset_run {
                // en: Reset once more with the DM off, through NRST (the LinkE's RstOut; nothing
                // happens where RST is not wired, and the CH549 Link refuses it), and send nothing
                // after it: after the LinkE's soft reset the DM was active again and core 0 was
                // found halted, while DMCONTROL = 0 left both H417 cores running and core 1 back
                // in its deep sleep (ArduinoCore-CH32RV, 2026-10-22, when the RstOut frame was
                // still malformed, so the NRST pulse itself is not measured on the H417).
                // ja: DM を止めたまま NRST でもう一度 reset し、その後は何も送らない(LinkE の
                // soft reset の後は DM が戻り core 0 が止まっていた)。H417 で NRST の効果は未測定。
                if self.link.rst_out(true).is_ok() {
                    std::thread::sleep(Duration::from_millis(20));
                    let _ = self.link.rst_out(false);
                }
                return;
            }
        }
        // Always release the core, on every path.
        let _ = self.link.detach_chip();
    }
}

/// en: Whether `hart` was running before a debugger stopped it: running now, or halted at a pc
/// other than 0. The LinkE's AttachChip stops the H417 hart a command did not select, and
/// DetachChip does not let it go, so without this `--core 0 read` left core 1 (V5F) halted and
/// `--core 1 dbg resume` left core 0 (V3F) halted. A hart halted out of a reset must not be
/// resumed: core 1 sits at pc 0, which is V3F's image, and resuming it ran both cores on core 0's
/// sketch. DMSTATUS `allhavereset` does not tell that case apart: core 1 woken by core 0's WAKEIP
/// after a reset keeps it set with nobody to acknowledge it (ArduinoCore-CH32RV, 2026-10-22).
/// The resume acknowledges it.
/// ja: hart が debugger に止められる前に走っていたか。走っている、または pc が 0 でない所で
/// 止まっている。reset から止まっている hart(core 1 は pc 0 = V3F の image)は resume しない。
/// `allhavereset` では見分けられない(reset の後に WAKEIP で起きた core 1 は立てたまま走る)。
fn hart_ran(link: &mut WchLink, hart: u32) -> Result<bool, ch32rv_dmi::DmiError> {
    link.select_hart(hart)?;
    let mut dm = DebugModule::new(link);
    if !dm.is_halted()? {
        return Ok(true);
    }
    Ok(dm.read_reg(ch32rv_dmi::RegName::Pc)? != 0)
}

/// Resume `hart` (selected first).
fn resume_hart(link: &mut WchLink, hart: u32) -> Result<(), ch32rv_dmi::DmiError> {
    link.select_hart(hart)?;
    DebugModule::new(link).resume()
}

/// en: Check an explicit `--chip` against what AttachChip found: fail-closed on a name the DB
/// does not know and on a family conflict. The caller detaches on `Err`.
/// ja: 明示の `--chip` を AttachChip の結果と突き合わせる。DB に無い名前と family の矛盾は
/// fail-closed。`Err` のとき detach は呼び出し側。
pub(crate) fn check_chip(
    db: &ch32rv_target::Db,
    requested: &str,
    attach: &AttachInfo,
) -> Result<(), SessionError> {
    let req_fams = db.families_for_chip_name(requested);
    let detected_fam = match db.resolve_by_chip_id(attach.chip_id) {
        ch32rv_target::Resolution::Sku(s) => s.family.clone(),
        ch32rv_target::Resolution::Family(f, _) => f,
        ch32rv_target::Resolution::Unknown => {
            family_name(attach.family_byte).unwrap_or("").to_owned()
        }
    };
    // en: A name the DB does not know cannot be checked against anything, so accepting it
    // would silently program whatever happens to be on the pins - exactly what `--chip`
    // exists to prevent, and what its "fail-closed on ambiguity" contract promises. The
    // gap series (V205/V407/V467/X305/X315/M030/M103) land here, which is the point: a
    // downstream IDE that offers them must hear "not in the DB", not flash a different
    // part. Auto-detection still works with `--chip` omitted.
    // ja: DB が知らない名前は何とも突き合わせられないので、受け入れると「刺さっている別の
    // チップに黙って書く」ことになる。`--chip` の存在意義と help の fail-closed 宣言に反する。
    // 未発売の gap series がここに落ちるのが狙いどおりで、`--chip` を省けば自動検出で動く。
    if req_fams.is_empty() {
        return Err(SessionError::ChipNotInDb(format!(
            "--chip {requested} is not in the target DB (detected {} from chip_id 0x{:08x})",
            if detected_fam.is_empty() {
                "an unknown part"
            } else {
                &detected_fam
            },
            attach.chip_id
        )));
    }
    // Reject a clear conflict: none of the requested name's families match the detected one.
    if !req_fams.is_empty()
        && !detected_fam.is_empty()
        && !req_fams
            .iter()
            .any(|f| f.eq_ignore_ascii_case(&detected_fam))
    {
        return Err(SessionError::ChipMismatch(format!(
            "--chip {requested} (family {}) conflicts with the detected {detected_fam} (chip_id 0x{:08x})",
            req_fams.join("/"),
            attach.chip_id
        )));
    }
    // A SKU is checked as that SKU (its device id), not only its family.
    if let Some(other) = db.sku_conflict(requested, attach.chip_id) {
        return Err(SessionError::ChipMismatch(format!(
            "--chip {requested} conflicts with the detected {other} (chip_id 0x{:08x})",
            attach.chip_id
        )));
    }
    Ok(())
}

/// en: `--connect-under-reset` for this process (set once by `main`; every WCH-Link session
/// attaches through [`attach_once`]).
/// ja: この process の `--connect-under-reset`(main が 1 回立てる)。
pub(crate) static CONNECT_UNDER_RESET: std::sync::atomic::AtomicBool =
    std::sync::atomic::AtomicBool::new(false);

/// en: `--attach-wait` for this process, in seconds (0: attach once).
/// ja: この process の `--attach-wait`(秒。0 なら 1 回だけ attach)。
pub(crate) static ATTACH_WAIT_S: std::sync::atomic::AtomicU64 =
    std::sync::atomic::AtomicU64::new(0);

/// en: The `--attach-wait` deadline, said once on stderr: what the user should do meanwhile.
/// ja: `--attach-wait` の期限。待つ間にすることを stderr に 1 度だけ言う。
pub(crate) fn attach_wait_deadline() -> Option<std::time::Instant> {
    let s = ATTACH_WAIT_S.load(std::sync::atomic::Ordering::Relaxed);
    if s == 0 {
        return None;
    }
    static SAID: std::sync::Once = std::sync::Once::new();
    SAID.call_once(|| {
        eprintln!(
            "waiting up to {s} s for the target to answer: power-cycle it or press its RESET now"
        )
    });
    Some(std::time::Instant::now() + Duration::from_secs(s))
}

/// en: Resume, at the end of a session, the H417 hart the command did not select (set by `main`:
/// every command but `dbg`, which leaves the other core as it is unless `dbg resume --all`).
/// ja: session の終わりに、選ばなかった H417 の hart を resume する(`dbg` 以外。`dbg` は
/// `dbg resume --all` のときだけ)。
pub(crate) static RESUME_OTHER_HARTS: std::sync::atomic::AtomicBool =
    std::sync::atomic::AtomicBool::new(false);

/// en: `--release-dm`: leave the debug module inactive (DMCONTROL = 0) at the end of a session,
/// and before a reset that lets the target run.
/// ja: `--release-dm`。session の終わりと、走らせる reset の前に DMCONTROL を 0 にする。
pub(crate) static RELEASE_DM: std::sync::atomic::AtomicBool =
    std::sync::atomic::AtomicBool::new(false);

const DMCONTROL: u8 = 0x10;
const DMSTATUS: u8 = 0x11;
const DMCONTROL_HALT: u32 = 0x8000_0001; // haltreq | dmactive

/// en: Attach with NRST held (the probe's RST wired to it): hold it through the LinkE's RstOut,
/// attach and request a halt while it is held, release it, and attach again at once - the
/// wire needs AttachChip after the reset - with haltreq set, so the hart stops before firmware
/// that turns the debug pins into something else can run. Measured on a CH32H417 whose firmware
/// hands PB8 / PB9 to USB a few ms after boot (2026-10-20): the second AttachChip came back in
/// about 95 ms with the hart halted, and the flash could be erased from there. That run sent a
/// malformed RstOut (read as GetProbeInfo), so the halt came from haltreq and the re-attach;
/// the NRST hold is not measured yet.
/// ja: NRST を押さえて接続する。押さえたまま attach して haltreq を立て、離してすぐ attach し直す
/// (reset の後は AttachChip が要る)。起動直後にデバッグのピンを取る firmware が走る前に止める。
fn attach_under_reset(link: &mut WchLink) -> Result<AttachInfo, SessionError> {
    link.rst_out(true)
        .map_err(|e| SessionError::Attach(format!("RstOut failed: {e}")))?;
    std::thread::sleep(Duration::from_millis(20));
    let _ = link.attach_chip();
    let _ = link.dmi_op(DMCONTROL, DMCONTROL_HALT, 2);
    link.rst_out(false)
        .map_err(|e| SessionError::Attach(format!("RstOut failed: {e}")))?;
    let mut last = None;
    for k in 0..12 {
        if k > 0 {
            std::thread::sleep(Duration::from_millis(200));
        }
        match link.attach_chip() {
            Ok(a) => {
                let _ = link.dmi_op(DMCONTROL, DMCONTROL_HALT, 2);
                let _ = link.dmi_op(DMSTATUS, 0, 1);
                return Ok(a);
            }
            Err(e) => last = Some(e),
        }
    }
    Err(match last {
        Some(WchLinkError::Protocol { reason: 0x55, .. }) | None => SessionError::NoTarget,
        Some(e) => SessionError::Attach(format!("attach under reset failed: {e}")),
    })
}

/// en: `--attach-wait`: repeat AttachChip until the target answers or the deadline passes, and
/// request a halt at once, before firmware that sleeps or takes the debug pins after its boot wait
/// gets that far. Measured on a WCH-Link (CH549) built into a CH32V103 board, whose NRST it does
/// not drive, running a sketch that went into standby 1.5 s after each boot (2026-10-30): with
/// RESET pressed by hand, attempt 123 (about 5 s in, about 40 ms each) answered and halted.
/// ja: `--attach-wait`。答えるか期限まで AttachChip を繰り返し、答えたらすぐ haltreq を立てる。
/// 起動待ちの後に眠る・デバッグのピンを取る firmware がそこへ行く前に止める。
fn attach_waiting(
    link: &mut WchLink,
    deadline: std::time::Instant,
) -> Result<AttachInfo, SessionError> {
    loop {
        match link.attach_chip() {
            Ok(a) => {
                for _ in 0..3 {
                    let _ = link.dmi_op(DMCONTROL, DMCONTROL_HALT, 2);
                }
                let _ = link.dmi_op(DMSTATUS, 0, 1);
                return Ok(a);
            }
            Err(
                WchLinkError::Protocol { reason: 0x55, .. } | WchLinkError::UnexpectedResponse(_),
            ) if std::time::Instant::now() < deadline => {}
            Err(
                WchLinkError::Protocol { reason: 0x55, .. } | WchLinkError::UnexpectedResponse(_),
            ) => {
                return Err(SessionError::NoTarget);
            }
            Err(e) => return Err(SessionError::Attach(format!("attach failed: {e}"))),
        }
    }
}

fn attach_once(link: &mut WchLink, speed: Speed) -> Result<AttachInfo, SessionError> {
    link.set_speed_default(speed)
        .map_err(|e| SessionError::Attach(format!("SetSpeed failed: {e}")))?;
    if CONNECT_UNDER_RESET.load(std::sync::atomic::Ordering::Relaxed) {
        return attach_under_reset(link);
    }
    if let Some(deadline) = attach_wait_deadline() {
        return attach_waiting(link, deadline);
    }
    link.attach_chip().map_err(|e| match e {
        // No response on the debug pins - a distinct, common case worth its own exit code (20).
        WchLinkError::Protocol { reason: 0x55, .. } | WchLinkError::UnexpectedResponse(_) => {
            SessionError::NoTarget
        }
        other => SessionError::Attach(format!("attach failed: {other}")),
    })
}

pub(crate) fn open_with_retry(entry: &Entry) -> Result<WchLink, WchLinkError> {
    let mut last = WchLink::open(&entry.dev);
    for _ in 0..2 {
        match &last {
            Err(WchLinkError::Usb(ch32rv_usb::UsbError::AccessDenied(_))) | Ok(_) => break,
            Err(_) => {
                std::thread::sleep(Duration::from_secs(1));
                last = WchLink::open(&entry.dev);
            }
        }
    }
    last
}

#[cfg(test)]
mod capacity_tests {
    use super::*;

    #[test]
    fn erased_capacity_falls_back_only_for_a_resolved_sku() {
        let db = ch32rv_target::Db::builtin();
        let mut chip = ChipInfo {
            flash_bytes: 0,
            uuid: [1; 8],
            protection_raw: [0; 4],
            chip_id_echo: 0x31500000,
        };
        for kib in [0, 0xffff, 0xe339] {
            chip.flash_bytes = kib * 1024;
            assert_eq!(
                flash_capacity(Some(&chip), &db, 0x31500000),
                (Some(196608), "db")
            );
            assert_eq!(
                flash_capacity(Some(&chip), &db, 0xdeadbeef),
                (None, "unavailable")
            );
        }
        // Valid probe capacities retain precedence, including measured values above the DB's.
        chip.flash_bytes = 288 * 1024;
        assert_eq!(
            flash_capacity(Some(&chip), &db, 0x30700528),
            (Some(288 * 1024), "probe")
        );
        assert_eq!(flash_capacity(None, &db, 0xdeadbeef), (None, "unavailable"));
    }
}