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
//! # Wishbone Bridges
//!
//! Wishbone is an internal bus that runs on-chip. It provides memory-based
//! interconnect between various hardware modules. Wishbone buses frequently
//! contain memories such as RAM and ROM, as well as memory-mapped peripherals.
//!
//! By accessing these memories remotely, a target device may be examined or
//! tested by a host.
//!
//! Wishbone may be bridged from a target to a host using a variety of protocols.
//! This library supports different protocols depending on what features are
//! enabled. By default, all supported protocols are enabled.
//!
//! Creating a Wishbone `Bridge` object involves first creating a configuration
//! struct that describes the connection mechanism, and then calling `.create()`
//! on that struct to create the `Bridge`. For example, to create a USB Bridge
//! using the USB PID `0x1234`, peek memory at address 0, and poke the value
//! `0x12345678` into address `0x20000000`, you would use a `UsbBridge` like this:
//!
//! ```no_run
//! use wishbone_bridge::UsbBridge;
//! let bridge = UsbBridge::new().pid(0x1234).create().unwrap();
//! println!("Memory at address 0: {:08x}", bridge.peek(0).unwrap());
//! bridge.poke(0x2000_0000, 0x1234_5678).unwrap();
//! ```
//!
//! Creating other bridges is done in a similar manner -- see their individual
//! pages for more information.

#[cfg(not(any(
    feature = "pcie",
    feature = "uart",
    feature = "spi",
    feature = "ethernet",
    feature = "usb"
)))]
compile_error!("Must enable at least one bridge type: pcie, uart, spi, ethernet, or usb");

pub(crate) mod bridges;

#[doc(hidden)]
#[cfg(feature = "ethernet")]
pub use bridges::ethernet::EthernetBridgeInner;
#[doc(hidden)]
#[cfg(feature = "pcie")]
pub use bridges::pcie::PCIeBridgeInner;
#[doc(hidden)]
#[cfg(feature = "spi")]
pub use bridges::spi::SpiBridgeInner;
#[doc(hidden)]
#[cfg(feature = "uart")]
pub use bridges::uart::UartBridgeInner;
#[doc(hidden)]
#[cfg(feature = "usb")]
pub use bridges::usb::UsbBridgeInner;

#[cfg(feature = "ethernet")]
pub use bridges::ethernet::{EthernetBridge, EthernetBridgeProtocol};
#[cfg(feature = "pcie")]
pub use bridges::pcie::PCIeBridge;
#[cfg(feature = "spi")]
pub use bridges::spi::SpiBridge;
#[cfg(feature = "uart")]
pub use bridges::uart::UartBridge;
#[cfg(feature = "usb")]
pub use bridges::usb::UsbBridge;

use log::debug;

use std::io;
use std::sync::{Arc, Mutex};

#[doc(hidden)]
#[derive(Clone)]
/// A `BridgeConfig` describes the configuration of a bridge that has
/// not yet been opened.
pub enum BridgeConfig {
    /// An unconfigured `BridgeConfig`. Attempts to use this will return
    /// an `Err(NoBridgeSpecified)`, so this value exists so that `Default`
    /// may be implemented.
    None,

    /// Describes a bridge that connects via Ethernet, either via UDP
    /// (for direct hardware connections) or TCP (for connecting to
    /// other Wishbone servers such as `litex_server` or `wishbone-tool`)
    #[cfg(feature = "ethernet")]
    EthernetBridge(EthernetBridge),

    /// Describes a connection to a device via a PCIe bridge. Unlike most
    /// other bridges, a PCIe bridge does not provide a complete view of
    /// the memory space.
    #[cfg(feature = "pcie")]
    PCIeBridge(PCIeBridge),

    /// Describes a connection to a device via SPI wires.
    #[cfg(feature = "spi")]
    SpiBridge(SpiBridge),

    /// Describes a connection to a device via a serial or other UART port.
    #[cfg(feature = "uart")]
    UartBridge(UartBridge),

    /// Describes a connection to a device via USB.
    #[cfg(feature = "usb")]
    UsbBridge(UsbBridge),
}

#[doc(hidden)]
#[derive(Clone)]
pub enum BridgeCore {
    #[cfg(feature = "ethernet")]
    EthernetBridge(EthernetBridgeInner),
    #[cfg(feature = "pcie")]
    PCIeBridge(PCIeBridgeInner),
    #[cfg(feature = "spi")]
    SpiBridge(SpiBridgeInner),
    #[cfg(feature = "uart")]
    UartBridge(UartBridgeInner),
    #[cfg(feature = "usb")]
    UsbBridge(UsbBridgeInner),
}

/// Bridges represent the actual connection to the device. You must create
/// a Bridge by constructing a configuration from the relevant
/// configuration type, and then calling `create()`.
///
/// For example, to create a USB bridge, use the `UsbBridge` object:
///
/// ```
/// use wishbone_bridge::UsbBridge;
/// let mut bridge_config = UsbBridge::new();
/// let bridge = bridge_config.pid(0x1234).create().unwrap();
/// ```
#[derive(Clone)]
pub struct Bridge {
    core: BridgeCore,
    mutex: Arc<Mutex<()>>,
}

/// Errors that are generated while creating or using the Wishbone Bridge.
#[derive(Debug)]
pub enum BridgeError {
    /// No bridge was specified (i.e. it was None)
    NoBridgeSpecified,

    /// Expected one size, but got another
    LengthError(usize, usize),

    /// USB subsystem returned an error
    #[cfg(feature = "usb")]
    USBError(libusb_wishbone_tool::Error),

    /// std::io error
    IoError(io::Error),

    /// Attempted to communicate with the bridge, but it wasn't connected
    NotConnected,

    /// The address or path was incorrect
    InvalidAddress,

    /// We got something weird back from the bridge
    WrongResponse,

    /// Requested protocol is not supported on this platform
    #[allow(dead_code)]
    ProtocolNotSupported,

    /// We got nothing back from the bridge
    #[allow(dead_code)]
    Timeout,
}

impl ::std::fmt::Display for BridgeError {
    fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
        use BridgeError::*;
        match self {
            LengthError(expected, actual) => {
                write!(f, "expected {} bytes, but got {} instead", expected, actual)
            }
            #[cfg(feature = "usb")]
            USBError(e) => write!(f, "libusb error {}", e.strerror()),
            IoError(e) => write!(f, "io error {}", e),
            NoBridgeSpecified => write!(f, "no bridge was specified"),
            NotConnected => write!(f, "bridge not connected"),
            WrongResponse => write!(f, "wrong response received"),
            InvalidAddress => write!(f, "bad address or path"),
            ProtocolNotSupported => write!(f, "protocol not supported on this platform"),
            Timeout => write!(f, "connection timed out"),
        }
    }
}

#[cfg(feature = "usb")]
impl std::convert::From<libusb_wishbone_tool::Error> for BridgeError {
    fn from(e: libusb_wishbone_tool::Error) -> BridgeError {
        BridgeError::USBError(e)
    }
}

impl std::convert::From<io::Error> for BridgeError {
    fn from(e: io::Error) -> BridgeError {
        BridgeError::IoError(e)
    }
}

impl Bridge {
    /// Create a new Bridge with the specified configuration. The new bridge
    /// starts out in a Disconnected state, but may be connecting in the background.
    /// To ensure the bridge is connected, so you must call `connect()`.
    pub(crate) fn new(bridge_cfg: BridgeConfig) -> Result<Bridge, BridgeError> {
        let mutex = Arc::new(Mutex::new(()));
        match &bridge_cfg {
            BridgeConfig::None => Err(BridgeError::NoBridgeSpecified),
            #[cfg(feature = "ethernet")]
            BridgeConfig::EthernetBridge(bridge_cfg) => Ok(Bridge {
                mutex,
                core: BridgeCore::EthernetBridge(EthernetBridgeInner::new(bridge_cfg)?),
            }),
            #[cfg(feature = "pcie")]
            BridgeConfig::PCIeBridge(bridge_cfg) => Ok(Bridge {
                mutex,
                core: BridgeCore::PCIeBridge(PCIeBridgeInner::new(bridge_cfg)?),
            }),
            #[cfg(feature = "spi")]
            BridgeConfig::SpiBridge(bridge_cfg) => Ok(Bridge {
                mutex,
                core: BridgeCore::SpiBridge(SpiBridgeInner::new(bridge_cfg)?),
            }),
            #[cfg(feature = "uart")]
            BridgeConfig::UartBridge(bridge_cfg) => Ok(Bridge {
                mutex,
                core: BridgeCore::UartBridge(UartBridgeInner::new(bridge_cfg)?),
            }),
            #[cfg(feature = "usb")]
            BridgeConfig::UsbBridge(bridge_cfg) => Ok(Bridge {
                mutex,
                core: BridgeCore::UsbBridge(UsbBridgeInner::new(bridge_cfg)?),
            }),
        }
    }

    /// Ensure the bridge is connected. Many bridges support performing connection
    /// in the background, so calling `connect()` ensures that the bridge has been
    /// established.
    pub fn connect(&self) -> Result<(), BridgeError> {
        let _mtx = self.mutex.lock().unwrap();
        match &self.core {
            #[cfg(feature = "ethernet")]
            BridgeCore::EthernetBridge(b) => b.connect(),
            #[cfg(feature = "pcie")]
            BridgeCore::PCIeBridge(b) => b.connect(),
            #[cfg(feature = "spi")]
            BridgeCore::SpiBridge(b) => b.connect(),
            #[cfg(feature = "uart")]
            BridgeCore::UartBridge(b) => b.connect(),
            #[cfg(feature = "usb")]
            BridgeCore::UsbBridge(b) => b.connect(),
        }
    }

    /// Read a single 32-bit value from the target device.
    /// ```no_run
    /// use wishbone_bridge::UsbBridge;
    /// let mut bridge_config = UsbBridge::new();
    /// let bridge = bridge_config.pid(0x5bf0).create().unwrap();
    /// println!("The value at address 0 is: {:08x}", bridge.peek(0).unwrap());
    /// ```
    pub fn peek(&self, addr: u32) -> Result<u32, BridgeError> {
        let _mtx = self.mutex.lock().unwrap();
        loop {
            let result = match &self.core {
                #[cfg(feature = "ethernet")]
                BridgeCore::EthernetBridge(b) => b.peek(addr),
                #[cfg(feature = "pcie")]
                BridgeCore::PCIeBridge(b) => b.peek(addr),
                #[cfg(feature = "spi")]
                BridgeCore::SpiBridge(b) => b.peek(addr),
                #[cfg(feature = "uart")]
                BridgeCore::UartBridge(b) => b.peek(addr),
                #[cfg(feature = "usb")]
                BridgeCore::UsbBridge(b) => b.peek(addr),
            };
            #[allow(unreachable_code)] // Only possible when no features are enabled (compile error)
            if let Err(e) = result {
                #[cfg(feature = "usb")]
                if let BridgeError::USBError(libusb_wishbone_tool::Error::Pipe) = e {
                    debug!("USB device disconnected, forcing early return");
                    return Err(e);
                }
                debug!("Peek failed, trying again: {:?}", e);
            } else {
                return result;
            }
        }
    }

    /// Write a single 32-bit value into the specified address.
    /// ```no_run
    /// use wishbone_bridge::UsbBridge;
    /// let mut bridge_config = UsbBridge::new();
    /// let bridge = bridge_config.pid(0x5bf0).create().unwrap();
    /// // Poke 0x12345678 into the target device at address 0
    /// bridge.poke(0, 0x12345678).unwrap();
    /// ```
    pub fn poke(&self, addr: u32, value: u32) -> Result<(), BridgeError> {
        let _mtx = self.mutex.lock().unwrap();
        loop {
            let result = match &self.core {
                #[cfg(feature = "ethernet")]
                BridgeCore::EthernetBridge(b) => b.poke(addr, value),
                #[cfg(feature = "pcie")]
                BridgeCore::PCIeBridge(b) => b.poke(addr, value),
                #[cfg(feature = "spi")]
                BridgeCore::SpiBridge(b) => b.poke(addr, value),
                #[cfg(feature = "uart")]
                BridgeCore::UartBridge(b) => b.poke(addr, value),
                #[cfg(feature = "usb")]
                BridgeCore::UsbBridge(b) => b.poke(addr, value),
            };
            #[allow(unreachable_code)] // Only possible when no features are enabled (compile error)
            if let Err(e) = result {
                match e {
                    #[cfg(feature = "usb")]
                    BridgeError::USBError(libusb_wishbone_tool::Error::Pipe) => {
                        debug!("USB device disconnected (Windows), forcing early return");
                        return Err(e);
                    }
                    #[cfg(feature = "usb")]
                    BridgeError::USBError(libusb_wishbone_tool::Error::Io) => {
                        debug!("USB device disconnected (Posix), forcing early return");
                        return Err(e);
                    }
                    _ => {}
                }
                debug!("Poke failed, trying again: {:?}", e);
            } else {
                return result;
            }
        }
    }
}