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
// Copyright lowRISC contributors (OpenTitan project).
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0

use anyhow::Result;
use clap::Args;
use serde::{Deserialize, Serialize};
use thiserror::Error;

use std::path::PathBuf;
use std::time::Duration;

use crate::app::TransportWrapper;
use crate::debug::openocd::OpenOcd;
use crate::dif::lc_ctrl::LcCtrlReg;
use crate::impl_serializable_error;

#[derive(Debug, Args, Clone)]
pub struct JtagParams {
    /// OpenOCD binary path.
    #[arg(long, default_value = "openocd")]
    pub openocd: PathBuf,

    #[arg(long, default_value = "1000")]
    pub adapter_speed_khz: u64,

    #[arg(long, default_value = "false")]
    pub log_stdio: bool,
}

impl JtagParams {
    pub fn create<'t>(&self, transport: &'t TransportWrapper) -> Result<Box<dyn JtagChain + 't>> {
        let jtag = transport.jtag(self)?;
        Ok(jtag)
    }
}

/// Errors related to the JTAG interface.
#[derive(Error, Debug, Deserialize, Serialize)]
pub enum JtagError {
    #[error("Operation not valid on selected JTAG TAP: {0:?}")]
    Tap(JtagTap),
    #[error("JTAG timeout")]
    Timeout,
    #[error("JTAG busy")]
    Busy,
    #[error("Generic error {0}")]
    Generic(String),
}
impl_serializable_error!(JtagError);

/// A trait which represents a JTAG interface.
///
/// JTAG lines form a daisy-chained topology and can connect multiple TAPs together in a chain.
/// This trait represents an adaptor that has been configured to connect to a given JTAG chain,
/// but have not yet been configured to only access a particular TAP.
pub trait JtagChain {
    /// Connect to the given JTAG TAP on this chain.
    fn connect(self: Box<Self>, tap: JtagTap) -> Result<Box<dyn Jtag>>;

    /// Stop further setup and returns raw OpenOCD instance.
    fn into_raw(self: Box<Self>) -> Result<OpenOcd>;
}

/// A trait which represents a TAP on a JTAG chain.
pub trait Jtag {
    /// Stop further operation and returns raw OpenOCD instance.
    fn into_raw(self: Box<Self>) -> Result<OpenOcd>;

    /// Returns the underlying OpenOCD instance.
    fn as_raw(&mut self) -> Result<&mut OpenOcd>;

    /// Disconnect from the TAP.
    fn disconnect(self: Box<Self>) -> Result<()>;
    /// Get TAP we are currently connected too.
    fn tap(&self) -> JtagTap;

    /// Read a lifecycle controller register.
    fn read_lc_ctrl_reg(&mut self, reg: &LcCtrlReg) -> Result<u32>;

    /// Write a value to a lifecycle controller register.
    fn write_lc_ctrl_reg(&mut self, reg: &LcCtrlReg, value: u32) -> Result<()>;

    /// Read bytes/words from memory into the provided buffer.
    /// When reading bytes, each memory access is 8 bits.
    /// When reading words, each memory access is 32 bit. If the hardware
    /// does not support unaligned memory accesses, this function will fail.
    ///
    /// On success, returns the number of bytes/words read.
    fn read_memory(&mut self, addr: u32, buf: &mut [u8]) -> Result<usize>;
    fn read_memory32(&mut self, addr: u32, buf: &mut [u32]) -> Result<usize>;

    /// Write bytes/words to memory.
    fn write_memory(&mut self, addr: u32, buf: &[u8]) -> Result<()>;
    fn write_memory32(&mut self, addr: u32, buf: &[u32]) -> Result<()>;

    /// Halt execution.
    fn halt(&mut self) -> Result<()>;

    /// Wait until the target halt. This does NOT halt the target on timeout.
    fn wait_halt(&mut self, timeout: Duration) -> Result<()>;

    /// Resume execution at its current code position.
    fn resume(&mut self) -> Result<()>;
    /// Resume execution at the specified address.
    fn resume_at(&mut self, addr: u32) -> Result<()>;

    /// Single-step the target at its current code position.
    fn step(&mut self) -> Result<()>;
    /// Single-step the target at the specified address.
    fn step_at(&mut self, addr: u32) -> Result<()>;

    /// Reset the target as hard as possible.
    /// If run is true, the target will start running code immediately
    /// after reset, otherwise it will be halted immediately.
    fn reset(&mut self, run: bool) -> Result<()>;

    /// Read/write a RISC-V register
    fn read_riscv_reg(&mut self, reg: &RiscvReg) -> Result<u32>;
    fn write_riscv_reg(&mut self, reg: &RiscvReg, val: u32) -> Result<()>;

    /// Set a breakpoint at the given address.
    fn set_breakpoint(&mut self, addr: u32, hw: bool) -> Result<()>;
    fn remove_breakpoint(&mut self, addr: u32) -> Result<()>;
    fn remove_all_breakpoints(&mut self) -> Result<()>;
}

/// Available JTAG TAPs (software TAPS) in OpenTitan.
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq)]
pub enum JtagTap {
    /// RISC-V core's TAP.
    RiscvTap,
    /// Lifecycle Controller's TAP.
    LcTap,
}

/// List of RISC-V general purpose registers
#[derive(Clone, Copy, Debug, Deserialize, Serialize, strum::IntoStaticStr)]
#[strum(serialize_all = "lowercase")]
pub enum RiscvGpr {
    RA,
    SP,
    GP,
    TP,
    T0,
    T1,
    T2,
    FP,
    S1,
    A0,
    A1,
    A2,
    A3,
    A4,
    A5,
    A6,
    A7,
    S2,
    S3,
    S4,
    S5,
    S6,
    S7,
    S8,
    S9,
    S10,
    S11,
    T3,
    T4,
    T5,
    T6,
}

impl RiscvGpr {
    /// Get the register name as a string.
    pub fn name(self) -> &'static str {
        self.into()
    }
}

/// List of useful RISC-V control and status registers
#[derive(Clone, Copy, Debug, Deserialize, Serialize, strum::IntoStaticStr)]
#[strum(serialize_all = "lowercase")]
#[non_exhaustive]
pub enum RiscvCsr {
    MSTATUS,
    MISA,
    MIE,
    MTVEC,
    MCOUNTINHIBIT,
    MHPMEVENT3,
    MHPMEVENT4,
    MHPMEVENT5,
    MHPMEVENT6,
    MHPMEVENT7,
    MHPMEVENT8,
    MHPMEVENT9,
    MHPMEVENT10,
    MHPMEVENT11,
    MHPMEVENT12,
    MHPMEVENT13,
    MHPMEVENT14,
    MHPMEVENT15,
    MHPMEVENT16,
    MHPMEVENT17,
    MHPMEVENT18,
    MHPMEVENT19,
    MHPMEVENT20,
    MHPMEVENT21,
    MHPMEVENT22,
    MHPMEVENT23,
    MHPMEVENT24,
    MHPMEVENT25,
    MHPMEVENT26,
    MHPMEVENT27,
    MHPMEVENT28,
    MHPMEVENT29,
    MHPMEVENT30,
    MHPMEVENT31,
    MSCRATCH,
    MEPC,
    MCAUSE,
    MTVAL,
    MIP,
    PMPCFG0,
    PMPCFG1,
    PMPCFG2,
    PMPCFG3,
    PMPADDR0,
    PMPADDR1,
    PMPADDR2,
    PMPADDR3,
    PMPADDR4,
    PMPADDR5,
    PMPADDR6,
    PMPADDR7,
    PMPADDR8,
    PMPADDR9,
    PMPADDR10,
    PMPADDR11,
    PMPADDR12,
    PMPADDR13,
    PMPADDR14,
    PMPADDR15,
    SCONTEXT,
    MSECCFG,
    MSECCFGH,
    TSELECT,
    TDATA1,
    TDATA2,
    TDATA3,
    MCONTEXT,
    MSCONTEXT,
    DCSR,
    DPC,
    DSCRATCH0,
    DSCRATCH1,
    MCYCLE,
    MINSTRET,
    MHPMCOUNTER3,
    MHPMCOUNTER4,
    MHPMCOUNTER5,
    MHPMCOUNTER6,
    MHPMCOUNTER7,
    MHPMCOUNTER8,
    MHPMCOUNTER9,
    MHPMCOUNTER10,
    MHPMCOUNTER11,
    MHPMCOUNTER12,
    MHPMCOUNTER13,
    MHPMCOUNTER14,
    MHPMCOUNTER15,
    MHPMCOUNTER16,
    MHPMCOUNTER17,
    MHPMCOUNTER18,
    MHPMCOUNTER19,
    MHPMCOUNTER20,
    MHPMCOUNTER21,
    MHPMCOUNTER22,
    MHPMCOUNTER23,
    MHPMCOUNTER24,
    MHPMCOUNTER25,
    MHPMCOUNTER26,
    MHPMCOUNTER27,
    MHPMCOUNTER28,
    MHPMCOUNTER29,
    MHPMCOUNTER30,
    MHPMCOUNTER31,
    MCYCLEH,
    MINSTRETH,
    MHPMCOUNTER3H,
    MHPMCOUNTER4H,
    MHPMCOUNTER5H,
    MHPMCOUNTER6H,
    MHPMCOUNTER7H,
    MHPMCOUNTER8H,
    MHPMCOUNTER9H,
    MHPMCOUNTER10H,
    MHPMCOUNTER11H,
    MHPMCOUNTER12H,
    MHPMCOUNTER13H,
    MHPMCOUNTER14H,
    MHPMCOUNTER15H,
    MHPMCOUNTER16H,
    MHPMCOUNTER17H,
    MHPMCOUNTER18H,
    MHPMCOUNTER19H,
    MHPMCOUNTER20H,
    MHPMCOUNTER21H,
    MHPMCOUNTER22H,
    MHPMCOUNTER23H,
    MHPMCOUNTER24H,
    MHPMCOUNTER25H,
    MHPMCOUNTER26H,
    MHPMCOUNTER27H,
    MHPMCOUNTER28H,
    MHPMCOUNTER29H,
    MHPMCOUNTER30H,
    MHPMCOUNTER31H,
    MVENDORID,
    MARCHID,
    MIMPID,
    MHARTID,

    // Custom CSRs, those are exposed with "csr_" prefix.
    #[strum(serialize = "csr_cpuctrl")]
    CPUCTRL,
    #[strum(serialize = "csr_secureseed")]
    SECURESEED,
}

impl RiscvCsr {
    /// Get the register name as a string.
    pub fn name(self) -> &'static str {
        self.into()
    }
}

/// Available registers for RISC-V TAP
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub enum RiscvReg {
    /// General Purpose Register
    Gpr(RiscvGpr),
    /// Control and Status Register
    Csr(RiscvCsr),
}

impl RiscvReg {
    /// Get the register name as a string.
    pub fn name(self) -> &'static str {
        match self {
            Self::Gpr(gpr) => gpr.name(),
            Self::Csr(csr) => csr.name(),
        }
    }
}

impl From<RiscvGpr> for RiscvReg {
    fn from(gpr: RiscvGpr) -> Self {
        Self::Gpr(gpr)
    }
}

impl From<RiscvCsr> for RiscvReg {
    fn from(csr: RiscvCsr) -> Self {
        Self::Csr(csr)
    }
}