opentitanlib/io/
fpga_backdoor.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::{Context, Result, bail, ensure};
6use clap::Args;
7use serde::ser::{Serialize, SerializeStruct, Serializer};
8use std::time::{Duration, Instant};
9
10use crate::app::TransportWrapper;
11use crate::debug::dmi::{Dmi, OpenOcdDmi};
12use crate::debug::openocd::OpenOcdJtagChain;
13use crate::io::jtag::{JtagChain, JtagParams, JtagTap};
14use crate::transport::Capability;
15use crate::util::vmem::Word;
16
17/// FPGA Backdoor loader register offsets (byte-addressed) and field definitions.
18/// See hw/ip/bkdr_loader/doc/registers.md
19/// TODO: it would be nice to use Bazel to auto-generate a rust "header" for this IP instead.
20pub mod regs {
21
22    // STATUS register
23    pub const STATUS_REG_OFFSET: usize = 0x0;
24    pub const STATUS_ERROR_BIT: u32 = 0;
25    pub const STATUS_CLEAR_IDLE_BIT: u32 = 1;
26
27    // CONTROL register
28    pub const CONTROL_REG_OFFSET: usize = 0x4;
29    pub const CONTROL_DONE_BIT: u32 = 0;
30    pub const CONTROL_WRITE_ENA_BIT: u32 = 1;
31    pub const CONTROL_CLEAR_START_BIT: u32 = 2;
32    pub const CONTROL_CLEAR_SEGMENT_START_BIT: u32 = 3;
33    pub const CONTROL_AUTO_INCR_BIT: u32 = 4;
34    pub const CONTROL_TARGET_IDX_MASK: u32 = 0xff;
35    pub const CONTROL_TARGET_IDX_OFFSET: usize = 8;
36
37    // Other registers (all have one 32-bit `VAL` field)
38    pub const NUM_BKDR_TARGETS_REG_OFFSET: usize = 0x8;
39    pub const MISSION_MODE_SWITCH_DELAY_REG_OFFSET: usize = 0xc;
40    pub const CLEAR_INDEX_START_REG_OFFSET: usize = 0x10;
41    pub const CLEAR_INDEX_END_REG_OFFSET: usize = 0x14;
42    pub const USR_ACCESS_TIMESTAMP_REG_OFFSET: usize = 0x18;
43    pub const TARGET_INFO_0_REG_OFFSET: usize = 0x100;
44    pub const WIDTH_INFO_0_REG_OFFSET: usize = 0x200;
45    pub const DEPTH_INFO_0_REG_OFFSET: usize = 0x300;
46    pub const READ_DATA_0_REG_OFFSET: usize = 0x400;
47    pub const WRITE_DATA_0_REG_OFFSET: usize = 0x500;
48    pub const INDEX_REG_OFFSET: usize = 0x600;
49    pub const HASH_LAST_LOADED_0_REG_OFFSET: usize = 0x700;
50}
51
52pub mod consts {
53    // Defined in `hw/ip/bkdr_loader/rtl/bkdr_loader_pkg.sv`.
54    pub const BACKDOOR_JTAG_IDCODE: u32 = 0x0300_0cdf;
55
56    // How long the reset strapping is applied for when entering the backdoor loader.
57    pub const RESET_PULSE_MS: u64 = 50;
58
59    // How long the backdoor loader TAP strapping is held after leaving reset.
60    pub const HOLD_TAP_STRAPS_MS: u64 = 50;
61
62    // Time to wait for a clear operation to finish.
63    pub const CLEAR_TIMEOUT_SECS: u64 = 5;
64
65    // How many JTAG cycles to wait for before considering the `CONTROL.DONE` transaction
66    // as being completed. We default to 10000, which is a conservative threshold.
67    pub const JTAG_DONE_CYCLES: u64 = 10000;
68
69    // Parameters - see hw/ip/bkdr_loader/doc/interfaces.md
70    pub const DATA_REGS_PER_WORD: usize = 8; // MaxWordWidthDiv32
71
72    // The maximum main clock frequency, used *only* for recovery flows.
73    pub const MAX_MAIN_CLOCK_FREQ_HZ: u64 = 50_000_000;
74}
75
76use consts::*;
77
78/// Can be used to help recover a backdoor loader that is stuck in its preload state.
79/// TODO: ideally this is temporary, only used to work around a suspected hardware issue
80/// on reset.
81pub fn release_stuck_backdoor(adapter_command: &str, opts: &JtagParams) -> Result<()> {
82    let openocd = Box::new(OpenOcdJtagChain::new(adapter_command, opts)?)
83        .connect(JtagTap::BackdoorTap)?
84        .into_raw()?;
85    Backdoor::new(
86        OpenOcdDmi::new(openocd, "fpga_backdoor.tap")?,
87        opts.adapter_speed_khz,
88        MAX_MAIN_CLOCK_FREQ_HZ,
89        /*enumerate=*/ false,
90    )?
91    .set_done()
92    .context("failed to release the FPGA backdoor loader")
93}
94
95/// Apply the bkdr_loader TAP strapping and reset to enter the backdoor loader.
96pub fn enter_backdoor_loader(transport: &TransportWrapper) -> Result<()> {
97    transport.capabilities()?.request(Capability::GPIO).ok()?;
98    let pinmux_tap_backdoor = transport.pin_strapping("PINMUX_TAP_FPGA_BACKDOOR")?;
99    let reset = transport.pin_strapping("RESET")?;
100    // Hold the JTAG TAP in reset for as long as the main reset is asserted. This works around
101    // suspected corruption of the `dmi_jtag` clock domain crossing in `bkdr_loader`.
102    // See lowrisc/opentitan#30834.
103    let trst = transport.optional_pin_strapping("TRST")?;
104
105    log::info!(
106        "Resetting with PINMUX_TAP_FPGA_BACKDOOR (== DFT) strapping applied to enter the backdoor loader"
107    );
108    pinmux_tap_backdoor.apply()?;
109    if let Some(trst) = &trst {
110        log::info!("Asserting TRST strapping");
111        trst.apply()?;
112    }
113    reset.apply()?;
114    std::thread::sleep(Duration::from_millis(RESET_PULSE_MS));
115    // Release in reverse order of assertion, so that the TCK side of the CDC never leaves reset
116    // while the `clk_i` side is still held.
117    reset.remove()?;
118    if let Some(trst) = &trst {
119        log::info!("Deasserting TRST strapping");
120        trst.remove()?;
121    }
122    std::thread::sleep(Duration::from_millis(HOLD_TAP_STRAPS_MS));
123    pinmux_tap_backdoor.remove()?;
124    log::info!("Reset complete, backdoor TAP strapping released");
125    Ok(())
126}
127
128/// A struct which represents a backdoor loader interface.
129///
130/// This struct represents an adaptor that has been configured to connect to a given JTAG chain,
131/// but has not yet been configured to access the backdoor TAP.
132pub struct BackdoorTap<'a> {
133    jtag: Box<dyn JtagChain + 'a>,
134    jtag_speed_khz: u64,
135    clock_main_hz: u64,
136}
137
138impl BackdoorTap<'_> {
139    /// Connect to the backdoor TAP, optionally enumerate information about all targets.
140    pub fn connect(self, enumerate: bool) -> Result<Backdoor> {
141        let openocd = self.jtag.connect(JtagTap::BackdoorTap)?.into_raw()?;
142        Backdoor::new(
143            OpenOcdDmi::new(openocd, "fpga_backdoor.tap")?,
144            self.jtag_speed_khz,
145            self.clock_main_hz,
146            enumerate,
147        )
148    }
149}
150
151#[derive(Debug, Args, Clone)]
152pub struct BackdoorParams {
153    /// JTAG options to apply to the backdoor TAP.
154    #[command(flatten)]
155    pub jtag: JtagParams,
156}
157
158impl BackdoorParams {
159    pub fn create<'a>(&self, transport: &'a TransportWrapper) -> Result<BackdoorTap<'a>> {
160        Ok(BackdoorTap {
161            jtag: self.jtag.create(transport)?,
162            jtag_speed_khz: self.jtag.adapter_speed_khz,
163            clock_main_hz: transport
164                .clock_frequency("main")
165                .context("main clock frequency must be set to use the FPGA backdoor")?,
166        })
167    }
168}
169
170/// Information about a specific backdoor target, e.g. OTP, ROM, FB0, SRAM.
171#[derive(Debug, Clone, Copy)]
172pub struct BackdoorTargetInfo {
173    /// The unique identifier of the backdoor target
174    pub id: u32,
175    /// The word width of the memory of the backdoor target.
176    pub width: u32,
177    /// The depth (number of words) of the memory of the backdoor target.
178    pub depth: u32,
179}
180
181impl BackdoorTargetInfo {
182    /// The target's unique identifier as a <= 4 character UTF-8 string.
183    pub fn id_str(&self) -> String {
184        let bytes = self.id.to_be_bytes();
185
186        String::from_utf8_lossy(&bytes).trim_end().to_owned()
187    }
188
189    // Convert a UTF-8 ID string into the unique u32 identifier format used by targets.
190    pub fn id_from_str(id: &str) -> Result<u32> {
191        let mut bytes = [32u8; 4];
192        let src = id.as_bytes();
193        let len = id.len().min(4);
194        bytes[..len].copy_from_slice(&src[..len]);
195
196        Ok(u32::from_be_bytes(bytes))
197    }
198}
199
200impl Serialize for BackdoorTargetInfo {
201    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
202    where
203        S: Serializer,
204    {
205        let mut s = serializer.serialize_struct("BackdoorTargetInfo", 4)?;
206        s.serialize_field("id", &self.id)?;
207        s.serialize_field("id_str", &self.id_str())?;
208        s.serialize_field("width", &self.width)?;
209        s.serialize_field("depth", &self.depth)?;
210        s.end()
211    }
212}
213
214impl std::fmt::Display for BackdoorTargetInfo {
215    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
216        write!(f, "{} {} x {}", self.id_str(), self.width, self.depth)
217    }
218}
219
220impl Word {
221    /// Convert the word to a series of 32-bit chunks to be written to the data registers.
222    fn to_u32_chunks(&self) -> Result<[u32; DATA_REGS_PER_WORD]> {
223        ensure!(
224            self.bytes.len() <= DATA_REGS_PER_WORD * 4,
225            "Word '{}' with {} bytes will not fit into {} 32-bit registers.",
226            hex::encode(self.bytes.clone()),
227            self.bytes.len(),
228            DATA_REGS_PER_WORD
229        );
230        let mut chunks = [0u32; DATA_REGS_PER_WORD];
231
232        // Bytes are stored in Big Endian; when written to registers, the u32
233        // chunks are provided in LSB-first order (Little Endian).
234        for (i, &b) in self.bytes.iter().rev().enumerate() {
235            // Within u32 chunks, bytes are still given in MSB-first order (Big Endian).
236            let chunk_idx = i / 4;
237            let byte_pos = i % 4;
238            chunks[chunk_idx] |= (b as u32) << (byte_pos * 8);
239        }
240
241        Ok(chunks)
242    }
243
244    /// Convert the 32-bit chunks read from data registers into a word (MSB-first byte stream).
245    fn from_u32_chunks(chunks: &[u32; DATA_REGS_PER_WORD], bytes_per_word: usize) -> Self {
246        let num_chunks = bytes_per_word.div_ceil(size_of::<u32>());
247        let padding_bytes = (num_chunks * size_of::<u32>()) - bytes_per_word;
248
249        Self {
250            bytes: chunks
251                .iter()
252                .take(num_chunks)
253                .rev()
254                .flat_map(|chunk| chunk.to_be_bytes())
255                .skip(padding_bytes)
256                .collect(),
257        }
258    }
259}
260
261/// Handle for interacting with a given target via the backdoor loader.
262pub struct BackdoorTarget<'a> {
263    backdoor: &'a mut Backdoor,
264    index: u8,
265    /// Information about the target.
266    pub info: BackdoorTargetInfo,
267}
268
269impl<'a> BackdoorTarget<'a> {
270    /// Write a sequence of words at a given offset (word index) in the target's memory.
271    ///
272    /// The `write_all` parameter is used to control whether writes can be optimized by
273    /// maintaining shadow CSRs to determine when register contents have genuinely changed.
274    /// The `check_status` parameter is used to control whether the status bit is polled
275    /// after all words are written, to check for any errors.
276    pub fn write(
277        &mut self,
278        start: u32,
279        words: &[Word],
280        write_all: bool,
281        check_status: bool,
282    ) -> Result<()> {
283        ensure!(
284            start + words.len() as u32 <= self.info.depth,
285            "fpga bkdr_loader write of len {:#x} to word {:#x} of {} is out of bounds (depth: {:#x})",
286            words.len(),
287            start,
288            self.info.id_str(),
289            self.info.depth,
290        );
291        self.backdoor
292            .write_target(self.index, start, words, write_all, check_status)
293    }
294
295    /// Read a sequence of words at a given offset (word index) from the target's memory.
296    ///
297    /// The `check_status` parameter is used to control whether the status bit is polled
298    /// after all words are read, to check for any errors.
299    pub fn read(&mut self, start: u32, count: u32, check_status: bool) -> Result<Vec<Word>> {
300        ensure!(
301            start + count <= self.info.depth,
302            "fpga bkdr_loader read of len {:#x} to word {:#x} of {} is out of bounds (depth: {:#x})",
303            count,
304            start,
305            self.info.id_str(),
306            self.info.depth,
307        );
308        self.backdoor
309            .read_target(self.index, start, count, check_status)
310    }
311
312    /// Write a single word at a given word index in the target's memory, without disturbing any
313    /// auto-increment cursor. See [`Backdoor::write_target_word`].
314    pub fn write_word(&mut self, index: u32, word: &Word, check_status: bool) -> Result<()> {
315        ensure!(
316            index < self.info.depth,
317            "fpga bkdr_loader write to word {:#x} of {} is out of bounds (depth: {:#x})",
318            index,
319            self.info.id_str(),
320            self.info.depth,
321        );
322        self.backdoor
323            .write_target_word(self.index, index, word, check_status)
324    }
325
326    /// Read a single word at a given word index from the target's memory, without disturbing any
327    /// auto-increment cursor. See [`Backdoor::read_target_word`].
328    pub fn read_word(&mut self, index: u32, check_status: bool) -> Result<Word> {
329        ensure!(
330            index < self.info.depth,
331            "fpga bkdr_loader read from word {:#x} of {} is out of bounds (depth: {:#x})",
332            index,
333            self.info.id_str(),
334            self.info.depth,
335        );
336        self.backdoor
337            .read_target_word(self.index, index, check_status)
338    }
339
340    /// Clear the entire memory of the target with a given word.
341    ///
342    /// An optimized fast-path for clearing memories, primarily used to replicate existing
343    /// bitstream synthesis defaults. The `check_status` parameter is used to control
344    /// whether the status bit is polled after clearing, to check for any errors.
345    pub fn clear(&mut self, word: &Word, check_status: bool) -> Result<()> {
346        self.backdoor.clear_target(self.index, word, check_status)
347    }
348
349    /// Read this target's `HASH_LAST_LOADED` register: a non-resettable, software-managed
350    /// hash of the content that was last preloaded into this target, see
351    /// [`Backdoor::read_target_hash`].
352    pub fn read_hash(&mut self) -> Result<u32> {
353        self.backdoor.read_target_hash(self.index)
354    }
355
356    /// Write this target's `HASH_LAST_LOADED` register, see [`Backdoor::write_target_hash`].
357    pub fn write_hash(&mut self, hash: u32) -> Result<()> {
358        self.backdoor.write_target_hash(self.index, hash)
359    }
360}
361
362/// A struct which represents an active backdoor loader connection.
363pub struct Backdoor {
364    dmi: OpenOcdDmi,
365    jtag_speed_khz: u64,
366    clock_main_hz: u64,
367    targets: Vec<BackdoorTargetInfo>,
368}
369
370impl Backdoor {
371    /// Construct a [`Backdoor`] from a DMI connection to the backdoor TAP. Optionally
372    /// enumerate and discover information about all available targets.
373    pub fn new(
374        dmi: OpenOcdDmi,
375        jtag_speed_khz: u64,
376        clock_main_hz: u64,
377        enumerate: bool,
378    ) -> Result<Self> {
379        let mut fpga_backdoor = Self {
380            dmi,
381            jtag_speed_khz,
382            clock_main_hz,
383            targets: Vec::new(),
384        };
385        if enumerate {
386            fpga_backdoor.enumerate()?;
387        }
388
389        Ok(fpga_backdoor)
390    }
391
392    /// Read from a DMI register with the given byte address offset.
393    /// DMI is a register interface; we must map the byte offsets to register (word) index.
394    fn dmi_read(&mut self, byte_addr: usize) -> Result<u32> {
395        self.dmi.dmi_read(byte_addr as u32 >> 2)
396    }
397
398    /// Write a value to a DMI register with the given byte address offset.
399    /// DMI is a register interface; we must map the byte offsets to register (word) index.
400    fn dmi_write(&mut self, byte_addr: usize, data: u32) -> Result<()> {
401        self.dmi.dmi_write(byte_addr as u32 >> 2, data)
402    }
403
404    // Enumerate the backdoor loader and retrieve information about available targets.
405    pub fn enumerate(&mut self) -> Result<()> {
406        self.targets.clear();
407
408        let num_targets = self
409            .dmi_read(regs::NUM_BKDR_TARGETS_REG_OFFSET)
410            .context("cannot read number of targets")? as usize;
411        log::info!("Number of FPGA bkdr_loader targets: {num_targets:?}");
412        for idx in 0..num_targets {
413            let addr_offset = idx * 4;
414            let target_info = BackdoorTargetInfo {
415                id: self
416                    .dmi_read(regs::TARGET_INFO_0_REG_OFFSET + addr_offset)
417                    .context("cannot read target info")?,
418                width: self
419                    .dmi_read(regs::WIDTH_INFO_0_REG_OFFSET + addr_offset)
420                    .context("cannot read width info")?,
421                depth: self
422                    .dmi_read(regs::DEPTH_INFO_0_REG_OFFSET + addr_offset)
423                    .context("cannot read depth info")?,
424            };
425            self.targets.push(target_info);
426        }
427
428        Ok(())
429    }
430
431    /// Communicate with the backdoor loader that we are finished using it.
432    ///
433    /// This transitions the bkdr_loader from it from its "Preload" state to "Mission mode",
434    /// causing it to re-route incoming JTAG back to the regular downstream interface.
435    pub fn set_done(mut self) -> Result<()> {
436        log::debug!("Finished using backdoor loader until next reset");
437
438        // We don't want the bkdr_loader to re-route JTAG mid-transaction, since that will
439        // cause us to see an unexpected response, as we will then be talking to an entirely
440        // different DMI / DTM (which can also put the RV_DM into a bad state). It will also
441        // potentially put the RV_dM debug infrastructure into a bad state. Configure the
442        // bkdr_loader to wait long enough so that we can finish our JTAG transaction.
443        let jtag_freq_hz: u64 = self.jtag_speed_khz * 1000;
444        let soc_clk_wait_cycles = self.clock_main_hz.div_ceil(jtag_freq_hz) * JTAG_DONE_CYCLES;
445        let soc_clk_wait_cycles: u32 = soc_clk_wait_cycles.try_into().unwrap_or_else(|_| {
446            log::warn!(
447                "Configured JTAG speed ({} kHz) may overflow bkdr_loader wait time.",
448                self.jtag_speed_khz
449            );
450            log::warn!("Configuring maximum wait time.");
451            u32::MAX
452        });
453        self.dmi_write(
454            regs::MISSION_MODE_SWITCH_DELAY_REG_OFFSET,
455            soc_clk_wait_cycles,
456        )
457        .context("cannot write FPGA bkdr_loader mission_mode_switch_delay register")?;
458
459        if let Err(e) = self
460            .dmi_write(regs::CONTROL_REG_OFFSET, 0b1 << regs::CONTROL_DONE_BIT)
461            .context("cannot write done to FPGA bkdr_loader control reg")
462        {
463            log::error!("Error received when writing to `CONTROL.DONE`: {:?}", e);
464            log::error!("Trying to continue anyway...");
465        }
466
467        // Explicitly shut down all JTAG state before the transition happens, to avoid
468        // putting the next TAP(s) into some bad state across the transition.
469        drop(self);
470
471        // Wait until the transition to mission mode is complete and the system exits reset
472        // before continuing. For most sensible JTAG speeds this should be basically instant;
473        // for very slow speeds (e.g. <= 50 kHz) we need to add some special casing.
474        let done_wait_millis = (JTAG_DONE_CYCLES * 1000).div_ceil(jtag_freq_hz);
475        std::thread::sleep(Duration::from_millis(done_wait_millis));
476
477        Ok(())
478    }
479
480    /// Retrieve information about all of the targets available via the backdoor interface.
481    pub fn targets(&self) -> &[BackdoorTargetInfo] {
482        &self.targets
483    }
484
485    /// Borrow a target by its integer identifier. Only one BackdoorTarget can exist at a time.
486    pub fn target_by_id(&mut self, id: u32) -> Option<BackdoorTarget<'_>> {
487        let (index, info) = self.targets.iter().enumerate().find(|&(_, t)| t.id == id)?;
488        let (index, info) = (index as u8, *info);
489
490        Some(BackdoorTarget {
491            backdoor: self,
492            index,
493            info,
494        })
495    }
496
497    /// Borrow a target by its string identifier. Only one BackdoorTarget can exist at a time.
498    pub fn target_by_id_str(&mut self, id: &str) -> Result<Option<BackdoorTarget<'_>>> {
499        let encoded_id = BackdoorTargetInfo::id_from_str(id)?;
500
501        Ok(self.target_by_id(encoded_id))
502    }
503
504    /// Write a sequence of words at a given offset (word index) to a specified target's memory,
505    /// using the bkdr_loader's `AUTO_INCR` write mode.
506    ///
507    /// With `AUTO_INCR` set, writing the highest-indexed `WRITE_DATA` register needed for the
508    /// target's line width both commits a bkdr write at the current `INDEX` and advances `INDEX`
509    /// by one, so a full sequential range can be streamed without an `INDEX` write per word.
510    /// That top-word write must always happen (it's what fires the commit), but writes to any
511    /// lower-indexed `WRITE_DATA` registers can still be elided by the `write_all` parameter,
512    /// using shadow CSRs to determine when register contents have genuinely changed since the
513    /// previous word.
514    /// The `check_status` parameter is used to control whether the status bit is polled
515    /// after all words are written, to check for any errors; it also reads back `INDEX` to
516    /// verify the cursor advanced exactly once per word (i.e. no commit was lost).
517    pub fn write_target(
518        &mut self,
519        target_index: u8,
520        start: u32,
521        words: &[Word],
522        write_all: bool,
523        check_status: bool,
524    ) -> Result<()> {
525        ensure!(
526            usize::from(target_index) < self.targets.len(),
527            "Target index {} is out of range for {} targets",
528            target_index,
529            self.targets.len()
530        );
531        let info = self.targets[target_index as usize];
532        let width = info.width as usize;
533        let regs_used = width.div_ceil(u32::BITS as usize);
534        ensure!(
535            regs_used <= DATA_REGS_PER_WORD,
536            "Advertised target width {:#x} is too wide for the data registers (needs: {:#x}, has: {:#x})",
537            width,
538            regs_used,
539            DATA_REGS_PER_WORD
540        );
541
542        if words.is_empty() {
543            return Ok(());
544        }
545
546        // The top `WRITE_DATA` register (i.e. `bkdr_loader`'s `max_word_idx_tgt`) is the one
547        // whose write commits the line and advances `INDEX`; it must be written every time.
548        let top_reg_idx = regs_used - 1;
549
550        let mut control = (target_index as u32) << regs::CONTROL_TARGET_IDX_OFFSET;
551        control |= 0b1 << regs::CONTROL_WRITE_ENA_BIT;
552        control |= 0b1 << regs::CONTROL_AUTO_INCR_BIT;
553
554        // Cache previous written values in Shadow CSRs
555        let mut prev_regs = [0u32; DATA_REGS_PER_WORD];
556        let mut first = true;
557
558        // We batch together all the necessary writes - including the CONTROL setup and the
559        // single INDEX seed - so that we can perform a single batched write operation at the
560        // end, which is optimized for throughput. Batched writes execute strictly in order,
561        // so CONTROL (selecting the target and enabling AUTO_INCR) and the INDEX seed land
562        // before any data; with AUTO_INCR already set, the INDEX write cannot trigger a
563        // manual write. From the seed on, INDEX auto-increments in hardware.
564        let mut writes = vec![
565            ((regs::CONTROL_REG_OFFSET >> 2) as u32, control),
566            ((regs::INDEX_REG_OFFSET >> 2) as u32, start),
567        ];
568
569        for word in words {
570            let regs = word.to_u32_chunks()?;
571            for idx in 0..regs_used {
572                // Optimization - maintain shadow CSRs in software, and only write the
573                // data if there is a diff in that CSR from the previous contents. Vastly
574                // minimizes required operations for repetitive payloads. The top register
575                // is exempted since its write is what commits the line and advances INDEX.
576                if idx == top_reg_idx || write_all || first || regs[idx] != prev_regs[idx] {
577                    let addr_offset = idx * 4;
578                    writes.push((
579                        ((regs::WRITE_DATA_0_REG_OFFSET + addr_offset) >> 2) as u32,
580                        regs[idx],
581                    ));
582                    prev_regs[idx] = regs[idx];
583                }
584            }
585            first = false;
586        }
587
588        self.dmi
589            .batched_dmi_writes(&writes)
590            .context("failed to perform DMI writes")?;
591
592        if check_status {
593            // The auto-increment cursor must have advanced exactly once per word; a mismatch
594            // means a commit (top-word write) was lost somewhere in the stream, which would
595            // shift every subsequent word by one address.
596            let end_index = self
597                .dmi_read(regs::INDEX_REG_OFFSET)
598                .context("cannot read back index")?;
599            ensure!(
600                end_index == start + words.len() as u32,
601                "fpga bkdr_loader index is {:#x} after writing {:#x} words at {:#x} of target {} (expected {:#x})",
602                end_index,
603                words.len(),
604                start,
605                info.id_str(),
606                start + words.len() as u32
607            );
608
609            let status = self
610                .dmi_read(regs::STATUS_REG_OFFSET)
611                .context("cannot read status")?;
612            ensure!(
613                status & (0b1 << regs::STATUS_ERROR_BIT) == 0,
614                "fpga bkdr_loader reported an error writing to target {}",
615                info.id_str()
616            );
617        }
618
619        Ok(())
620    }
621
622    /// Write a single word at a given word index to a specified target's memory, using the
623    /// bkdr_loader's manual (non-`AUTO_INCR`) write mode: `WRITE_DATA` is loaded, then writing
624    /// `INDEX` itself commands the write to that exact address.
625    ///
626    /// Unlike [`Backdoor::write_target`], this does not move any auto-increment cursor and can
627    /// address any word directly, which is handy for one-off single-word pokes that don't want
628    /// to reason about a running `INDEX`. The `check_status` parameter is used to control whether
629    /// the status bit is polled afterwards, to check for any errors.
630    pub fn write_target_word(
631        &mut self,
632        target_index: u8,
633        index: u32,
634        word: &Word,
635        check_status: bool,
636    ) -> Result<()> {
637        ensure!(
638            usize::from(target_index) < self.targets.len(),
639            "Target index {} is out of range for {} targets",
640            target_index,
641            self.targets.len()
642        );
643        let info = self.targets[target_index as usize];
644        let width = info.width as usize;
645        let regs_used = width.div_ceil(u32::BITS as usize);
646        ensure!(
647            regs_used <= DATA_REGS_PER_WORD,
648            "Advertised target width {:#x} is too wide for the data registers (needs: {:#x}, has: {:#x})",
649            width,
650            regs_used,
651            DATA_REGS_PER_WORD
652        );
653
654        let mut control = (target_index as u32) << regs::CONTROL_TARGET_IDX_OFFSET;
655        control |= 0b1 << regs::CONTROL_WRITE_ENA_BIT;
656
657        // Batch everything into one round trip: CONTROL setup, the data registers, and the
658        // final INDEX write whose qe strobe (with AUTO_INCR clear) triggers the actual write.
659        let regs = word.to_u32_chunks()?;
660        let writes: Vec<(u32, u32)> =
661            std::iter::once(((regs::CONTROL_REG_OFFSET >> 2) as u32, control))
662                .chain(regs[..regs_used].iter().enumerate().map(|(idx, &reg)| {
663                    let addr_offset = idx * 4;
664                    (
665                        ((regs::WRITE_DATA_0_REG_OFFSET + addr_offset) >> 2) as u32,
666                        reg,
667                    )
668                }))
669                .chain(std::iter::once((
670                    (regs::INDEX_REG_OFFSET >> 2) as u32,
671                    index,
672                )))
673                .collect();
674
675        self.dmi
676            .batched_dmi_writes(&writes)
677            .context("failed to perform DMI writes")?;
678
679        if check_status {
680            let status = self
681                .dmi_read(regs::STATUS_REG_OFFSET)
682                .context("cannot read status")?;
683            ensure!(
684                status & (0b1 << regs::STATUS_ERROR_BIT) == 0,
685                "fpga bkdr_loader reported an error writing to target {}",
686                info.id_str()
687            );
688        }
689
690        Ok(())
691    }
692
693    /// Read a sequence of words at a given offset (word index) from a specified target's memory,
694    /// using the bkdr_loader's `AUTO_INCR` read mode.
695    ///
696    /// With `AUTO_INCR` set and `WRITE_ENA` clear, reading the highest-indexed `READ_DATA`
697    /// register needed for the target's line width advances `INDEX` by one (no bkdr write is
698    /// ever triggered on the read side), so a full sequential range can be streamed with a single
699    /// `INDEX` write up front rather than one per word. Because that top-word read is what
700    /// advances `INDEX`, each line's registers must be read in ascending order (topmost last),
701    /// reading it out of order would advance past data that hasn't been collected yet.
702    /// The `check_status` parameter is used to control whether the status bit is polled
703    /// after all words are read, to check for any errors; it also reads back `INDEX` to
704    /// verify the cursor advanced exactly once per word.
705    pub fn read_target(
706        &mut self,
707        target_index: u8,
708        start: u32,
709        count: u32,
710        check_status: bool,
711    ) -> Result<Vec<Word>> {
712        ensure!(
713            usize::from(target_index) < self.targets.len(),
714            "Target index {} is out of range for {} targets",
715            target_index,
716            self.targets.len()
717        );
718        let info = self.targets[target_index as usize];
719        let width = info.width as usize;
720        let bytes_per_word = width.div_ceil(u8::BITS as usize);
721        let regs_used = width.div_ceil(u32::BITS as usize);
722        ensure!(
723            regs_used <= DATA_REGS_PER_WORD,
724            "Advertised target width {:#x} is too wide for the data registers (needs: {:#x}, has: {:#x})",
725            width,
726            regs_used,
727            DATA_REGS_PER_WORD
728        );
729
730        if count == 0 {
731            return Ok(Vec::new());
732        }
733
734        let mut control = (target_index as u32) << regs::CONTROL_TARGET_IDX_OFFSET;
735        control |= 0b1 << regs::CONTROL_AUTO_INCR_BIT;
736        // WRITE_ENA is left clear: with AUTO_INCR set, this selects the read-side trigger.
737        // Batch the CONTROL setup and the single INDEX seed into one round trip; the writes
738        // execute strictly in order, and with WRITE_ENA clear the INDEX write cannot trigger
739        // a write. From the seed on, INDEX auto-increments in hardware.
740        self.dmi
741            .batched_dmi_writes(&[
742                ((regs::CONTROL_REG_OFFSET >> 2) as u32, control),
743                ((regs::INDEX_REG_OFFSET >> 2) as u32, start),
744            ])
745            .context("cannot set up control and index registers")?;
746
747        // Reading the top register advances INDEX, so within each word the registers must be
748        // read in ascending order (topmost last). The flattened address sequence preserves
749        // that order, and batched reads keep operation order, across chunks too.
750        let addrs: Vec<u32> = (0..count)
751            .flat_map(|_| {
752                (0..regs_used).map(|idx| ((regs::READ_DATA_0_REG_OFFSET + idx * 4) >> 2) as u32)
753            })
754            .collect();
755        let values = self
756            .dmi
757            .batched_dmi_reads(&addrs)
758            .context("cannot read from read_data registers")?;
759
760        let words = values
761            .chunks_exact(regs_used)
762            .map(|chunk| {
763                let mut regs = [0u32; DATA_REGS_PER_WORD];
764                regs[..regs_used].copy_from_slice(chunk);
765                Word::from_u32_chunks(&regs, bytes_per_word)
766            })
767            .collect::<Vec<_>>();
768
769        if check_status {
770            // The auto-increment cursor must have advanced exactly once per word read; a
771            // mismatch means a top-word read strobe was lost or fired more than expected.
772            let end_index = self
773                .dmi_read(regs::INDEX_REG_OFFSET)
774                .context("cannot read back index")?;
775            ensure!(
776                end_index == start + count,
777                "fpga bkdr_loader index is {:#x} after reading {:#x} words at {:#x} of target {} (expected {:#x})",
778                end_index,
779                count,
780                start,
781                info.id_str(),
782                start + count
783            );
784
785            let status = self
786                .dmi_read(regs::STATUS_REG_OFFSET)
787                .context("cannot read status")?;
788            ensure!(
789                status & (0b1 << regs::STATUS_ERROR_BIT) == 0,
790                "fpga bkdr_loader reported an error reading from target {} starting at word {}",
791                info.id_str(),
792                start
793            );
794        }
795
796        Ok(words)
797    }
798
799    /// Read a single word at a given word index from a specified target's memory, using the
800    /// bkdr_loader's manual (non-`AUTO_INCR`) read mode: writing `INDEX` addresses the word, then
801    /// `READ_DATA` is read back.
802    ///
803    /// Unlike [`Backdoor::read_target`], this does not move any auto-increment cursor and can
804    /// address any word directly, which is handy for one-off single-word peeks. The
805    /// `check_status` parameter is used to control whether the status bit is polled afterwards,
806    /// to check for any errors.
807    pub fn read_target_word(
808        &mut self,
809        target_index: u8,
810        index: u32,
811        check_status: bool,
812    ) -> Result<Word> {
813        ensure!(
814            usize::from(target_index) < self.targets.len(),
815            "Target index {} is out of range for {} targets",
816            target_index,
817            self.targets.len()
818        );
819        let info = self.targets[target_index as usize];
820        let width = info.width as usize;
821        let bytes_per_word = width.div_ceil(u8::BITS as usize);
822        let regs_used = width.div_ceil(u32::BITS as usize);
823        ensure!(
824            regs_used <= DATA_REGS_PER_WORD,
825            "Advertised target width {:#x} is too wide for the data registers (needs: {:#x}, has: {:#x})",
826            width,
827            regs_used,
828            DATA_REGS_PER_WORD
829        );
830
831        // Batch the CONTROL setup (WRITE_ENA and AUTO_INCR both clear: manual read mode, no
832        // side effects on READ_DATA reads) and the INDEX write into one round trip.
833        let control = (target_index as u32) << regs::CONTROL_TARGET_IDX_OFFSET;
834        self.dmi
835            .batched_dmi_writes(&[
836                ((regs::CONTROL_REG_OFFSET >> 2) as u32, control),
837                ((regs::INDEX_REG_OFFSET >> 2) as u32, index),
838            ])
839            .context("cannot set up control and index registers")?;
840
841        if check_status {
842            let status = self
843                .dmi_read(regs::STATUS_REG_OFFSET)
844                .context("cannot read status")?;
845            ensure!(
846                status & (0b1 << regs::STATUS_ERROR_BIT) == 0,
847                "fpga bkdr_loader reported an error reading from word idx {} of target {}",
848                index,
849                info.id_str()
850            );
851        }
852
853        let addrs: Vec<u32> = (0..regs_used)
854            .map(|idx| ((regs::READ_DATA_0_REG_OFFSET + idx * 4) >> 2) as u32)
855            .collect();
856        let values = self
857            .dmi
858            .batched_dmi_reads(&addrs)
859            .context("cannot read from read_data registers")?;
860
861        let mut regs = [0u32; DATA_REGS_PER_WORD];
862        regs[..regs_used].copy_from_slice(&values);
863
864        Ok(Word::from_u32_chunks(&regs, bytes_per_word))
865    }
866
867    /// Clear the entire memory of a specified target with a given word.
868    ///
869    /// An optimized fast-path for clearing memories, primarily used to replicate existing
870    /// bitstream synthesis defaults. The `check_status` parameter is used to control
871    /// whether the status bit is polled after clearing, to check for any errors.
872    pub fn clear_target(
873        &mut self,
874        target_index: u8,
875        word: &Word,
876        check_status: bool,
877    ) -> Result<()> {
878        ensure!(
879            usize::from(target_index) < self.targets.len(),
880            "Target index {} is out of range for {} targets",
881            target_index,
882            self.targets.len()
883        );
884        let info = self.targets[target_index as usize];
885
886        self.dmi
887            .batched_dmi_writes(
888                &word
889                    .to_u32_chunks()?
890                    .into_iter()
891                    .enumerate()
892                    .map(|(idx, reg)| {
893                        let addr_offset = idx * 4;
894                        (
895                            ((regs::WRITE_DATA_0_REG_OFFSET + addr_offset) >> 2) as u32,
896                            reg,
897                        )
898                    })
899                    .collect::<Vec<_>>(),
900            )
901            .context("failed to perform DMI writes")?;
902
903        let mut control = (target_index as u32) << regs::CONTROL_TARGET_IDX_OFFSET;
904        control |= 0b1 << regs::CONTROL_WRITE_ENA_BIT;
905        control |= 0b1 << regs::CONTROL_CLEAR_START_BIT;
906        self.dmi_write(regs::CONTROL_REG_OFFSET, control)
907            .context("cannot write to control register")?;
908
909        // Wait for the `CLEAR_IDLE` bit to appear set in the status register.
910        let timeout = Instant::now() + Duration::from_secs(CLEAR_TIMEOUT_SECS);
911        let mut status: u32;
912        loop {
913            status = self
914                .dmi_read(regs::STATUS_REG_OFFSET)
915                .context("cannot read status")?;
916            if status & (0b1 << regs::STATUS_CLEAR_IDLE_BIT) != 0 {
917                break;
918            }
919
920            if Instant::now() > timeout {
921                bail!(
922                    "Timed out after {} seconds waiting for {} clear to complete",
923                    CLEAR_TIMEOUT_SECS,
924                    info.id_str()
925                );
926            }
927        }
928
929        if check_status {
930            ensure!(
931                status & (0b1 << regs::STATUS_ERROR_BIT) == 0,
932                "fpga bkdr_loader reported an error writing to target {}",
933                info.id_str()
934            );
935        }
936
937        Ok(())
938    }
939
940    /// Read a specified target's `HASH_LAST_LOADED` register.
941    ///
942    /// This is a plain `rw` register with no side effects of its own: hardware only stores
943    /// whatever value software last wrote to it, and never clears it on the button/`rst_ni`
944    /// reset used to re-enter the backdoor loader. It exists so a caller can stash a hash
945    /// of a target's memory content across preloads, and skip re-writing that content if
946    /// the hash of what it's about to write hasn't changed.
947    pub fn read_target_hash(&mut self, target_index: u8) -> Result<u32> {
948        ensure!(
949            usize::from(target_index) < self.targets.len(),
950            "Target index {} is out of range for {} targets",
951            target_index,
952            self.targets.len()
953        );
954        self.dmi_read(regs::HASH_LAST_LOADED_0_REG_OFFSET + (target_index as usize) * 4)
955            .context("cannot read target hash register")
956    }
957
958    /// Write a specified target's `HASH_LAST_LOADED` register. See [`Backdoor::read_target_hash`].
959    pub fn write_target_hash(&mut self, target_index: u8, hash: u32) -> Result<()> {
960        ensure!(
961            usize::from(target_index) < self.targets.len(),
962            "Target index {} is out of range for {} targets",
963            target_index,
964            self.targets.len()
965        );
966        self.dmi_write(
967            regs::HASH_LAST_LOADED_0_REG_OFFSET + (target_index as usize) * 4,
968            hash,
969        )
970        .context("cannot write target hash register")
971    }
972
973    /// Read the FPGA's `USR_ACCESS_TIMESTAMP` register: the same value embedded in the
974    /// bitstream's `USR_ACCESS` primitive at build time (see `util::usr_access::usr_access_get`).
975    /// Unlike that value, this one is read directly from the FPGA fabric's configuration over
976    /// the backdoor TAP, so it identifies the bitstream currently loaded.
977    pub fn read_usr_access_timestamp(&mut self) -> Result<u32> {
978        self.dmi_read(regs::USR_ACCESS_TIMESTAMP_REG_OFFSET)
979            .context("cannot read USR_ACCESS_TIMESTAMP register")
980    }
981}
982
983#[cfg(test)]
984mod tests {
985    use super::*;
986
987    #[test]
988    fn identifer_str_encoding() {
989        let (width, depth) = (1, 1);
990        for (id, id_str) in [
991            (0x4f545020, "OTP"),
992            (0x5352414d, "SRAM"),
993            (0x46493031, "FI01"),
994        ] {
995            assert_eq!(BackdoorTargetInfo { id, width, depth }.id_str(), id_str);
996            assert_eq!(BackdoorTargetInfo::id_from_str(id_str).unwrap(), id);
997        }
998    }
999
1000    #[test]
1001    fn byte_u32_conversion() {
1002        // Bytes stored in words are Big Endian (MSB first).
1003        let word = Word::new(vec![
1004            0x5a, 0xa5, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xbe, 0xef, 0xca, 0xfe,
1005        ]);
1006        // Register chunks are Little Endian, but bytes in each u32 are Big Endian.
1007        // The 4th register should be half-used, the 4 remaining regs should be unused.
1008        let mut expected = [0x0; DATA_REGS_PER_WORD];
1009        expected[0] = 0xbeefcafe;
1010        expected[1] = 0x89abcdef;
1011        expected[2] = 0x01234567;
1012        expected[3] = 0x00005aa5;
1013
1014        let chunks = word.to_u32_chunks().unwrap();
1015        assert_eq!(chunks, expected);
1016        assert_eq!(Word::from_u32_chunks(&chunks, word.bytes.len()), word);
1017    }
1018}