opentitanlib/transport/common/
fpga.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 std::time::Duration;
7
8use crate::app::TransportWrapper;
9use crate::io::gpio::GpioPin;
10use crate::io::uart::Uart;
11use crate::transport::ProgressIndicator;
12use crate::util::rom_detect::RomDetect;
13
14/// Command for Transport::dispatch().
15pub struct FpgaProgram<'a> {
16    /// The bitstream content to load into the FPGA.
17    pub bitstream: Vec<u8>,
18    /// How long of a reset pulse to send to the device.
19    pub rom_reset_pulse: Duration,
20    /// How long to wait for the ROM to print its type and version.
21    pub rom_timeout: Duration,
22    /// A progress function to provide user feedback.
23    /// Will be called with the address and length of each chunk sent to the target device.
24    pub progress: Box<dyn ProgressIndicator + 'a>,
25}
26
27impl FpgaProgram<'_> {
28    fn check_correct_version(&self, uart: &dyn Uart, reset_pin: &dyn GpioPin) -> Result<bool> {
29        let mut rd = RomDetect::new(&self.bitstream, Some(self.rom_timeout))?;
30
31        // Send a reset pulse so the ROM will print the FPGA version.
32        // Reset is active low, sleep, then drive high.
33        reset_pin.write(false)?;
34        std::thread::sleep(self.rom_reset_pulse);
35        // Also clear the UART RX buffer for improved robustness.
36        uart.clear_rx_buffer()?;
37        reset_pin.write(true)?;
38
39        // Now read the uart until the ROM prints it's version.
40        if rd.detect(uart)? {
41            log::info!("Already running the correct bitstream.  Skip loading bitstream.");
42            // If we're already running the right ROM+bitstream,
43            // then we can skip bootstrap.
44            return Ok(true);
45        }
46        Ok(false)
47    }
48
49    fn skip(&self) -> bool {
50        self.bitstream.starts_with(b"__skip__")
51    }
52
53    pub fn should_skip(&self, transport: &TransportWrapper) -> Result<bool> {
54        // Open the console UART.  We do this first so we get the receiver
55        // started and the uart buffering data for us.
56        let uart = transport.uart("CONSOLE")?;
57        let reset_pin = transport.gpio_pin("RESET")?;
58        if self.skip() {
59            log::info!("Skip loading the __skip__ bitstream.");
60            return Ok(true);
61        }
62        if self.check_correct_version(&*uart, &*reset_pin)? {
63            return Ok(true);
64        }
65        Ok(false)
66    }
67}
68
69/// Command for Transport::dispatch().
70pub struct ClearBitstream;