1use 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
17pub mod regs {
21
22 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 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 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 pub const BACKDOOR_JTAG_IDCODE: u32 = 0x0300_0cdf;
55
56 pub const RESET_PULSE_MS: u64 = 50;
58
59 pub const HOLD_TAP_STRAPS_MS: u64 = 50;
61
62 pub const CLEAR_TIMEOUT_SECS: u64 = 5;
64
65 pub const JTAG_DONE_CYCLES: u64 = 10000;
68
69 pub const DATA_REGS_PER_WORD: usize = 8; pub const MAX_MAIN_CLOCK_FREQ_HZ: u64 = 50_000_000;
74}
75
76use consts::*;
77
78pub 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 false,
90 )?
91 .set_done()
92 .context("failed to release the FPGA backdoor loader")
93}
94
95pub 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 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 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
128pub struct BackdoorTap<'a> {
133 jtag: Box<dyn JtagChain + 'a>,
134 jtag_speed_khz: u64,
135 clock_main_hz: u64,
136}
137
138impl BackdoorTap<'_> {
139 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 #[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#[derive(Debug, Clone, Copy)]
172pub struct BackdoorTargetInfo {
173 pub id: u32,
175 pub width: u32,
177 pub depth: u32,
179}
180
181impl BackdoorTargetInfo {
182 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 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 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 for (i, &b) in self.bytes.iter().rev().enumerate() {
235 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 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
261pub struct BackdoorTarget<'a> {
263 backdoor: &'a mut Backdoor,
264 index: u8,
265 pub info: BackdoorTargetInfo,
267}
268
269impl<'a> BackdoorTarget<'a> {
270 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 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 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 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 pub fn clear(&mut self, word: &Word, check_status: bool) -> Result<()> {
346 self.backdoor.clear_target(self.index, word, check_status)
347 }
348
349 pub fn read_hash(&mut self) -> Result<u32> {
353 self.backdoor.read_target_hash(self.index)
354 }
355
356 pub fn write_hash(&mut self, hash: u32) -> Result<()> {
358 self.backdoor.write_target_hash(self.index, hash)
359 }
360}
361
362pub struct Backdoor {
364 dmi: OpenOcdDmi,
365 jtag_speed_khz: u64,
366 clock_main_hz: u64,
367 targets: Vec<BackdoorTargetInfo>,
368}
369
370impl Backdoor {
371 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 fn dmi_read(&mut self, byte_addr: usize) -> Result<u32> {
395 self.dmi.dmi_read(byte_addr as u32 >> 2)
396 }
397
398 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 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 pub fn set_done(mut self) -> Result<()> {
436 log::debug!("Finished using backdoor loader until next reset");
437
438 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 drop(self);
470
471 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 pub fn targets(&self) -> &[BackdoorTargetInfo] {
482 &self.targets
483 }
484
485 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 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 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 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 let mut prev_regs = [0u32; DATA_REGS_PER_WORD];
556 let mut first = true;
557
558 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 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 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 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 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, ®)| {
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 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 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 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(®s, bytes_per_word)
766 })
767 .collect::<Vec<_>>();
768
769 if check_status {
770 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 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 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(®s, bytes_per_word))
865 }
866
867 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 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 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 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 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 let word = Word::new(vec![
1004 0x5a, 0xa5, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xbe, 0xef, 0xca, 0xfe,
1005 ]);
1006 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}