opentitanlib/transport/
mod.rs

1// Copyright lowRISC contributors (OpenTitan project).
2// Licensed under the Apache License, Version 2.0, see LICENSE for details.
3// SPDX-License-Identifier: Apache-2.0
4
5use anyhow::Result;
6use bitflags::bitflags;
7use serde::{Deserialize, Serialize};
8use std::any::Any;
9use std::collections::HashMap;
10use std::path::PathBuf;
11use std::rc::Rc;
12
13use crate::bootstrap::BootstrapOptions;
14use crate::io::emu::Emulator;
15use crate::io::gpio::{GpioBitbanging, GpioMonitoring, GpioPin};
16use crate::io::i2c::Bus;
17use crate::io::jtag::{JtagChain, JtagParams};
18use crate::io::spi::Target;
19use crate::io::uart::Uart;
20
21pub mod common;
22pub mod ioexpander;
23
24// Export custom error types
25mod errors;
26pub use errors::{TransportError, TransportInterfaceType};
27
28bitflags! {
29    /// A bitmap of capabilities which may be provided by a transport.
30    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
31    #[serde(transparent)]
32    pub struct Capability: u32 {
33        const NONE = 0x00;
34        const UART = 0x01 << 0;
35        const SPI = 0x01 << 1;
36        const GPIO = 0x01 << 2;
37        const I2C = 0x01 << 3;
38        const PROXY = 0x01 << 4;
39        const EMULATOR = 0x01 << 5;
40        const GPIO_MONITORING = 0x01 << 6; // Logic analyzer functionality
41        const JTAG = 0x01 << 7;
42        const UART_NONBLOCKING = 0x01 << 8;
43        const SPI_DUAL = 0x01 << 9;
44        const SPI_QUAD = 0x01 << 10;
45        const GPIO_BITBANGING = 0x01 << 11;
46    }
47}
48
49/// A struct which represents what features a particular Transport instance supports.
50#[derive(Serialize, Deserialize)]
51pub struct Capabilities {
52    capabilities: Capability,
53}
54
55impl Capabilities {
56    /// Create a new Capabilities object representing a provider of
57    /// capabilities specified by `cap`.
58    pub fn new(cap: Capability) -> Self {
59        Self { capabilities: cap }
60    }
61
62    pub fn add(&self, extra: Capability) -> Self {
63        Self {
64            capabilities: self.capabilities | extra,
65        }
66    }
67
68    /// Request the capabilities specified by `cap`.
69    pub fn request(&self, needed: Capability) -> NeededCapabilities {
70        NeededCapabilities {
71            capabilities: self.capabilities,
72            needed,
73        }
74    }
75}
76
77/// A struct which can check that needed capability requirements are met.
78pub struct NeededCapabilities {
79    capabilities: Capability,
80    needed: Capability,
81}
82
83impl NeededCapabilities {
84    /// Checks that the requested capabilities are provided.
85    pub fn ok(&self) -> Result<()> {
86        if self.capabilities & self.needed != self.needed {
87            Err(TransportError::MissingCapabilities(self.needed, self.capabilities).into())
88        } else {
89            Ok(())
90        }
91    }
92}
93
94/// A transport object is a factory for the low-level interfaces provided
95/// by a given communications backend.
96pub trait Transport {
97    /// Returns a `Capabilities` object to check the capabilities of this
98    /// transport object.
99    fn capabilities(&self) -> Result<Capabilities>;
100
101    /// Resets the transport to power-on condition.  That is, pin/uart/spi configuration reverts
102    /// to default, ongoing operations are cancelled, etc.
103    fn apply_default_configuration(&self) -> Result<()> {
104        Ok(())
105    }
106
107    /// Returns a [`JtagChain`] implementation.
108    fn jtag(&self, _opts: &JtagParams) -> Result<Box<dyn JtagChain + '_>> {
109        Err(TransportError::InvalidInterface(TransportInterfaceType::Jtag).into())
110    }
111    /// Returns a SPI [`Target`] implementation.
112    fn spi(&self, _instance: &str) -> Result<Rc<dyn Target>> {
113        Err(TransportError::InvalidInterface(TransportInterfaceType::Spi).into())
114    }
115    /// Returns a I2C [`Bus`] implementation.
116    fn i2c(&self, _instance: &str) -> Result<Rc<dyn Bus>> {
117        Err(TransportError::InvalidInterface(TransportInterfaceType::I2c).into())
118    }
119    /// Returns a [`Uart`] implementation.
120    fn uart(&self, _instance: &str) -> Result<Rc<dyn Uart>> {
121        Err(TransportError::InvalidInterface(TransportInterfaceType::Uart).into())
122    }
123    /// Returns a [`GpioPin`] implementation.
124    fn gpio_pin(&self, _instance: &str) -> Result<Rc<dyn GpioPin>> {
125        Err(TransportError::InvalidInterface(TransportInterfaceType::Gpio).into())
126    }
127    /// Returns a [`GpioMonitoring`] implementation, for logic analyzer functionality.
128    fn gpio_monitoring(&self) -> Result<Rc<dyn GpioMonitoring>> {
129        Err(TransportError::InvalidInterface(TransportInterfaceType::GpioMonitoring).into())
130    }
131    /// Returns a [`GpioBitbanging`] implementation, for timed and synchronized manipulation of
132    /// multiple GPIO pins.
133    fn gpio_bitbanging(&self) -> Result<Rc<dyn GpioBitbanging>> {
134        Err(TransportError::InvalidInterface(TransportInterfaceType::GpioBitbanging).into())
135    }
136    /// Returns a [`Emulator`] implementation.
137    fn emulator(&self) -> Result<Rc<dyn Emulator>> {
138        Err(TransportError::InvalidInterface(TransportInterfaceType::Emulator).into())
139    }
140
141    /// Methods available only on Proxy implementation.
142    fn proxy_ops(&self) -> Result<Rc<dyn ProxyOps>> {
143        Err(TransportError::InvalidInterface(TransportInterfaceType::ProxyOps).into())
144    }
145
146    /// Invoke non-standard functionality of some Transport implementations.
147    fn dispatch(&self, _action: &dyn Any) -> Result<Option<Box<dyn erased_serde::Serialize>>> {
148        Err(TransportError::UnsupportedOperation.into())
149    }
150
151    /// As long as the returned `MaintainConnection` object is kept by the caller, this driver may
152    /// assume that no other `opentitantool` processes attempt to access the same debugger device.
153    /// This allows for optimizations such as keeping USB handles open across function invocations.
154    fn maintain_connection(&self) -> Result<Rc<dyn MaintainConnection>> {
155        // For implementations that have not implemented any optimizations, return a no-op object.
156        Ok(Rc::new(()))
157    }
158}
159
160/// As long as this object is kept alive, the `Transport` driver may assume that no other
161/// `opentitantool` processes attempt to access the same debugger device.  This allows for
162/// optimizations such as keeping USB handles open across function invocations.
163pub trait MaintainConnection {}
164
165/// No-op implmentation of the trait, for use by `Transport` implementations that do not do
166/// any optimizations to maintain connection between method calls.
167impl MaintainConnection for () {}
168
169/// Methods available only on the Proxy implementation of the Transport trait.
170pub trait ProxyOps {
171    /// Returns a string->string map containing user-defined aspects "provided" by the testbed
172    /// setup.  For instance, whether a SPI flash chip is fitted in the socket, or whether pullup
173    /// resistors are suitable for high-speed I2C.  Most of the time, this information will not
174    /// come from the actual transport layer, but from the TransportWrapper above it.
175    fn provides_map(&self) -> Result<HashMap<String, String>>;
176
177    fn bootstrap(&self, options: &BootstrapOptions, payload: &[u8]) -> Result<()>;
178    fn apply_pin_strapping(&self, strapping_name: &str) -> Result<()>;
179    fn remove_pin_strapping(&self, strapping_name: &str) -> Result<()>;
180
181    /// Applies the default transport init configuration expect with the specify strap applied.
182    fn apply_default_configuration_with_strap(&self, strapping_name: &str) -> Result<()>;
183}
184
185/// Used by Transport implementations dealing with emulated OpenTitan
186/// chips, allowing e.g. more efficient direct means of programming
187/// emulated flash storage.  (As opposed to running an actual
188/// bootloater on the emulated target, which would receive data via
189/// SPI to be flashed.)
190pub struct Bootstrap {
191    pub image_path: PathBuf,
192}
193
194/// Some transports allow dynamically changing which pins are used for JTAG.
195pub struct SetJtagPins {
196    pub tclk: Option<Rc<dyn GpioPin>>,
197    pub tms: Option<Rc<dyn GpioPin>>,
198    pub tdi: Option<Rc<dyn GpioPin>>,
199    pub tdo: Option<Rc<dyn GpioPin>>,
200    pub trst: Option<Rc<dyn GpioPin>>,
201}
202
203pub trait ProgressIndicator {
204    // Begins a new stage, indicating "size" of this stage in bytes.  `name` can be the empty
205    // string, for instance if the operation has only a single stage.
206    fn new_stage(&self, name: &str, total: usize);
207    // Indicates how far towards the previously declared `total`.  Operation will be shown as
208    // complete, once the parameter value to this method equals `total`.
209    fn progress(&self, absolute: usize);
210}
211
212/// Command for Transport::dispatch().
213pub struct UpdateFirmware<'a> {
214    /// The firmware to load into the HyperDebug device, None means load an "official" newest
215    /// release of the firmware for the particular debugger device, assuming that the `Transport`
216    /// trait implementation knows how to download such.
217    pub firmware: Option<Vec<u8>>,
218    /// A progress function to provide user feedback, see details of the `Progress` struct.
219    pub progress: Box<dyn ProgressIndicator + 'a>,
220    /// Should updating be attempted, even if the current firmware version matches that of the
221    /// image to be updated to.
222    pub force: bool,
223}
224
225/// An `EmptyTransport` provides no communications backend.
226pub struct EmptyTransport;
227
228impl Transport for EmptyTransport {
229    fn capabilities(&self) -> Result<Capabilities> {
230        Ok(Capabilities::new(Capability::NONE))
231    }
232}
233
234#[cfg(test)]
235pub mod tests {
236    use super::*;
237
238    #[test]
239    fn test_capabilities_met() -> anyhow::Result<()> {
240        let cap = Capabilities::new(Capability::UART | Capability::SPI);
241        assert!(cap.request(Capability::UART).ok().is_ok());
242        Ok(())
243    }
244
245    #[test]
246    fn test_capabilities_not_met() -> anyhow::Result<()> {
247        let cap = Capabilities::new(Capability::UART | Capability::SPI);
248        assert!(cap.request(Capability::GPIO).ok().is_err());
249        Ok(())
250    }
251}