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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
// Copyright lowRISC contributors (OpenTitan project).
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0

use anyhow::{ensure, Context, Result};
use once_cell::sync::Lazy;
use std::cmp;
use std::collections::HashMap;
use std::convert::TryFrom;
use std::convert::TryInto;
use std::marker::PhantomData;
use std::time::Duration;

use super::board::Board;
use crate::collection;
use crate::io::gpio::GpioError;
use crate::io::spi::SpiError;
use crate::transport::{ProgressIndicator, TransportError, TransportInterfaceType};
use crate::util::parse_int::ParseInt;
use crate::util::usb::UsbBackend;

/// The `Backend` struct provides high-level access to the Chip Whisperer board.
pub struct Backend<B: Board> {
    usb: UsbBackend,
    _marker: PhantomData<B>,
}

/// Multiply and divide settings for the PLLs in the CDCE906 chip.
#[derive(Default, Debug, Clone)]
struct PllMulDiv {
    numerator: u16,
    denominator: u16,
    outdiv: u8,
    fvco: u32,
}

#[derive(Ord, PartialOrd, Eq, PartialEq, Debug, Clone, serde::Serialize)]
pub struct FirmwareVersion(u8, u8, u8);

impl<B: Board> Backend<B> {
    /// Commands for the Chip Whisperer board board.
    pub const CMD_FW_VERSION: u8 = 0x17;
    pub const CMD_CDC_SETTINGS_EN: u8 = 0x31;
    pub const CMD_READMEM_BULK: u8 = 0x10;
    pub const CMD_WRITEMEM_BULK: u8 = 0x11;
    pub const CMD_READMEM_CTRL: u8 = 0x12;
    pub const CMD_WRITEMEM_CTRL: u8 = 0x13;
    pub const CMD_MEMSTREAM: u8 = 0x14;
    pub const CMD_WRITEMEM_CTRL_SAM3U: u8 = 0x15;
    pub const CMD_SMC_READ_SPEED: u8 = 0x27;
    pub const CMD_FW_BUILD_DATE: u8 = 0x40;

    // Commands for controlling the SAM3X chip.
    pub const CMD_SAM3X_CFG: u8 = 0x22;
    pub const SAM3X_RESET: u16 = 0x10;

    pub const CMD_PLL: u8 = 0x30;
    pub const REQ_PLL_WRITE: u8 = 0x01;
    pub const REQ_PLL_READ: u8 = 0x00;
    pub const RESP_PLL_OK: u8 = 0x02;
    pub const ADDR_PLL_ENABLE: u8 = 0x0c;

    /// `CMD_FPGAIO_UTIL` is used to configure gpio pins on the SAM3U chip
    /// which are connected to the FPGA.
    pub const CMD_FPGAIO_UTIL: u8 = 0x34;
    /// Requests to the `FPGAIO_UTIL` command.
    pub const REQ_IO_CONFIG: u16 = 0xA0;
    pub const REQ_IO_RELEASE: u16 = 0xA1;
    pub const REQ_IO_OUTPUT: u16 = 0xA2;
    /// Configuration requests are used in the data packet sent with `REQ_IO_CONFIG`.
    pub const CONFIG_PIN_INPUT: u8 = 0x01;
    pub const CONFIG_PIN_OUTPUT: u8 = 0x02;
    pub const CONFIG_PIN_SPI1_SDO: u8 = 0x10;
    pub const CONFIG_PIN_SPI1_SDI: u8 = 0x11;
    pub const CONFIG_PIN_SPI1_SCK: u8 = 0x12;
    pub const CONFIG_PIN_SPI1_CS: u8 = 0x13;

    /// `CMD_FPGASPI1_XFER` is used to configure and drive SPI transactions
    /// between the SAM3U chip and the FPGA.
    pub const CMD_FPGASPI1_XFER: u8 = 0x35;
    pub const REQ_ENABLE_SPI: u16 = 0xA0;
    pub const REQ_DISABLE_SPI: u16 = 0xA1;
    pub const REQ_CS_LOW: u16 = 0xA2;
    pub const REQ_CS_HIGH: u16 = 0xA3;
    pub const REQ_SEND_DATA: u16 = 0xA4;

    /// FPGA programming speed in Hz.
    pub const FPGA_PROG_SPEED: u32 = 20_000_000;

    /// Commands for programming the bitstream into the FPGA.
    pub const CMD_FPGA_STATUS: u8 = 0x15;
    pub const CMD_FPGA_PROGRAM: u8 = 0x16;
    // The names init, prepare and exit are not official; they are inferred
    // from how the constants are used in the python implementation.
    pub const PROGRAM_INIT: u16 = 0xA0;
    pub const PROGRAM_PREPARE: u16 = 0xA1;
    pub const PROGRAM_EXIT: u16 = 0xA2;

    /// Bulk endpoint numbers for the Chip Whisperer board.
    pub const BULK_IN_EP: u8 = 0x81;
    pub const BULK_OUT_EP: u8 = 0x02;

    const LAST_PIN_NUMBER: u8 = 106;

    /// Create a new connection to a Chip Whisperer board.
    pub fn new(
        usb_vid: Option<u16>,
        usb_pid: Option<u16>,
        usb_serial: Option<&str>,
    ) -> Result<Self> {
        Ok(Backend {
            usb: UsbBackend::new(
                usb_vid.unwrap_or(B::VENDOR_ID),
                usb_pid.unwrap_or(B::PRODUCT_ID),
                usb_serial,
            )?,
            _marker: PhantomData,
        })
    }

    /// Send a control write transaction to the Chip Whisperer board.
    pub fn send_ctrl(&self, cmd: u8, value: u16, data: &[u8]) -> Result<usize> {
        log::debug!("WRITE_CTRL: bmRequestType: {:02x}, bRequest: {:02x}, wValue: {:04x}, wIndex: {:04x}, data: {:?}",
                0x41, cmd, value, 0, data);
        self.usb.write_control(0x41, cmd, value, 0, data)
    }

    /// Send a control read transaction to the Chip Whisperer board.
    pub fn read_ctrl(&self, cmd: u8, value: u16, data: &mut [u8]) -> Result<usize> {
        log::debug!("READ_CTRL: bmRequestType: {:02x}, bRequest: {:02x}, wValue: {:04x}, wIndex: {:04x}, data: {:?}",
                0xC1, cmd, value, 0, data);
        self.usb.read_control(0xC1, cmd, value, 0, data)
    }

    /// Gets the usb serial number of the device.
    pub fn get_serial_number(&self) -> &str {
        self.usb.get_serial_number()
    }

    /// Get the firmware build date as a string.
    pub fn get_firmware_build_date(&self) -> Result<String> {
        let mut buf = [0u8; 100];
        let len = self.read_ctrl(Backend::<B>::CMD_FW_BUILD_DATE, 0, &mut buf)?;
        Ok(String::from_utf8_lossy(&buf[0..len]).to_string())
    }

    /// Get the firmware version.
    pub fn get_firmware_version(&self) -> Result<FirmwareVersion> {
        let mut buf = [0u8; 3];
        self.read_ctrl(Backend::<B>::CMD_FW_VERSION, 0, &mut buf)?;
        Ok(FirmwareVersion(buf[0], buf[1], buf[2]))
    }

    /// Set GPIO `pinname` to either output or input mode.
    pub fn pin_set_output(&self, pinname: &str, output: bool) -> Result<()> {
        let pinnum = Backend::<B>::pin_name_to_number(pinname)?;
        self.send_ctrl(
            Backend::<B>::CMD_FPGAIO_UTIL,
            Backend::<B>::REQ_IO_CONFIG,
            &[
                pinnum,
                if output {
                    Backend::<B>::CONFIG_PIN_OUTPUT
                } else {
                    Backend::<B>::CONFIG_PIN_INPUT
                },
            ],
        )?;
        Ok(())
    }

    /// Get the state of GPIO `pinname`.
    pub fn pin_get_state(&self, pinname: &str) -> Result<u8> {
        let pinnum = Backend::<B>::pin_name_to_number(pinname)
            .ok()
            .ok_or_else(|| {
                TransportError::InvalidInstance(TransportInterfaceType::Gpio, pinname.to_string())
            })? as u16;
        let mut buf = [0u8; 1];
        self.read_ctrl(Backend::<B>::CMD_FPGAIO_UTIL, pinnum, &mut buf)
            .context("USB error")?;
        Ok(buf[0])
    }

    /// Set the state of GPIO `pinname`.
    pub fn pin_set_state(&self, pinname: &str, value: bool) -> Result<()> {
        let pinnum = Backend::<B>::pin_name_to_number(pinname)?;
        self.send_ctrl(
            Backend::<B>::CMD_FPGAIO_UTIL,
            Backend::<B>::REQ_IO_OUTPUT,
            &[pinnum, value as u8],
        )?;
        Ok(())
    }

    /// Sends a reset signal to the SAM3U chip. Does not wait for the SAM3U to
    /// finish resetting.
    pub fn reset_sam3x(&self) -> Result<()> {
        self.send_ctrl(Backend::<B>::CMD_SAM3X_CFG, Backend::<B>::SAM3X_RESET, &[])?;
        Ok(())
    }

    /// Configure the SAM3U to perform SPI using the named pins.
    pub fn spi1_setpins(&self, sdo: &str, sdi: &str, sck: &str, cs: &str) -> Result<()> {
        let sdo = Backend::<B>::pin_name_to_number(sdo)?;
        let sdi = Backend::<B>::pin_name_to_number(sdi)?;
        let sck = Backend::<B>::pin_name_to_number(sck)?;
        let cs = Backend::<B>::pin_name_to_number(cs)?;

        self.send_ctrl(
            Backend::<B>::CMD_FPGAIO_UTIL,
            Backend::<B>::REQ_IO_CONFIG,
            &[sdo, Backend::<B>::CONFIG_PIN_SPI1_SDO],
        )?;
        self.send_ctrl(
            Backend::<B>::CMD_FPGAIO_UTIL,
            Backend::<B>::REQ_IO_CONFIG,
            &[sdi, Backend::<B>::CONFIG_PIN_SPI1_SDI],
        )?;
        self.send_ctrl(
            Backend::<B>::CMD_FPGAIO_UTIL,
            Backend::<B>::REQ_IO_CONFIG,
            &[sck, Backend::<B>::CONFIG_PIN_SPI1_SCK],
        )?;
        self.send_ctrl(
            Backend::<B>::CMD_FPGAIO_UTIL,
            Backend::<B>::REQ_IO_CONFIG,
            &[cs, Backend::<B>::CONFIG_PIN_SPI1_CS],
        )?;
        Ok(())
    }

    /// Enable the spi interface on the SAM3U chip.
    pub fn spi1_enable(&self, enable: bool) -> Result<()> {
        self.send_ctrl(
            Backend::<B>::CMD_FPGASPI1_XFER,
            if enable {
                Backend::<B>::REQ_ENABLE_SPI
            } else {
                Backend::<B>::REQ_DISABLE_SPI
            },
            &[],
        )?;
        Ok(())
    }

    /// Set the value of the SPI chip-select pin.
    pub fn spi1_set_cs_pin(&self, status: bool) -> Result<()> {
        self.send_ctrl(
            Backend::<B>::CMD_FPGASPI1_XFER,
            if status {
                Backend::<B>::REQ_CS_HIGH
            } else {
                Backend::<B>::REQ_CS_LOW
            },
            &[],
        )?;
        Ok(())
    }

    /// Perform an up to 64-byte transfer on the SPI interface.
    /// This is a low-level function and does not affect the CS pin.
    pub fn spi1_tx_rx(&self, txdata: &[u8], rxdata: &mut [u8]) -> Result<()> {
        ensure!(
            txdata.len() <= 64,
            SpiError::InvalidDataLength(txdata.len())
        );
        ensure!(
            rxdata.len() <= 64,
            SpiError::InvalidDataLength(rxdata.len())
        );
        ensure!(
            txdata.len() == rxdata.len(),
            SpiError::MismatchedDataLength(txdata.len(), rxdata.len())
        );
        self.send_ctrl(
            Backend::<B>::CMD_FPGASPI1_XFER,
            Backend::<B>::REQ_SEND_DATA,
            txdata,
        )?;
        self.read_ctrl(Backend::<B>::CMD_FPGASPI1_XFER, 0, rxdata)?;
        Ok(())
    }

    /// Read a `buffer` slice from the SPI interface.
    /// This is a low-level function and does not affect the CS pin.
    pub fn spi1_read(&self, buffer: &mut [u8]) -> Result<()> {
        let wbuf = [0u8; 64];
        for chunk in buffer.chunks_mut(64) {
            self.spi1_tx_rx(&wbuf[..chunk.len()], chunk)?;
        }
        Ok(())
    }

    /// Write a `buffer` slice to the SPI interface.
    /// This is a low-level function and does not affect the CS pin.
    pub fn spi1_write(&self, buffer: &[u8]) -> Result<()> {
        let mut rbuf = [0u8; 64];
        for chunk in buffer.chunks(64) {
            self.spi1_tx_rx(chunk, &mut rbuf[..chunk.len()])?;
        }
        Ok(())
    }

    /// Perform a write & read transaction to the SPI interface.
    /// This is a low-level function and does not affect the CS pin.
    pub fn spi1_both(&self, txbuf: &[u8], rxbuf: &mut [u8]) -> Result<()> {
        ensure!(
            txbuf.len() == rxbuf.len(),
            SpiError::MismatchedDataLength(txbuf.len(), rxbuf.len())
        );
        for (wchunk, rchunk) in txbuf.chunks(64).zip(rxbuf.chunks_mut(64)) {
            self.spi1_tx_rx(wchunk, rchunk)?;
        }
        Ok(())
    }

    /// Query whether the FPGA is programmed.
    pub fn fpga_is_programmed(&self) -> Result<bool> {
        let mut status = [0u8; 4];
        self.read_ctrl(Backend::<B>::CMD_FPGA_STATUS, 0, &mut status)?;
        Ok(status[0] & 0x01 != 0)
    }

    // Set the FPGA download speed and prepare for programming.
    fn fpga_prepare(&self, speed_hz: u32) -> Result<()> {
        let supports_variable_speed = self.get_firmware_version()? >= FirmwareVersion(1, 0, 0);
        let speed_hz = speed_hz.to_le_bytes();
        self.send_ctrl(
            Backend::<B>::CMD_FPGA_PROGRAM,
            Backend::<B>::PROGRAM_INIT,
            if supports_variable_speed {
                &speed_hz
            } else {
                &[]
            },
        )?;
        std::thread::sleep(Duration::from_millis(1));
        self.send_ctrl(
            Backend::<B>::CMD_FPGA_PROGRAM,
            Backend::<B>::PROGRAM_PREPARE,
            &[],
        )?;
        std::thread::sleep(Duration::from_millis(1));
        Ok(())
    }

    fn fpga_download(&self, bitstream: &[u8], progress: &dyn ProgressIndicator) -> Result<()> {
        // This isn't really documented well in the python implementation:
        // There appears to be a header on the bitstream which we do not
        // want to send to the board.
        let mut stream = bitstream[0x7C..].to_vec();

        // Then, we need to extend the buffer a little to make sure we send
        // enough clocks at the end to finish programming.  Apparently, we
        // cannot end with a multiple of 64 bytes.
        let newlen = stream.len() + if stream.len() % 32 != 0 { 32 } else { 33 };
        stream.resize(newlen, 0xFF);

        progress.new_stage("", stream.len());

        // Finally, chunk the payload into 2k chunks and send it to the
        // bulk endpoint.
        const CHUNK_LEN: usize = 2048;
        for (chunk_no, chunk) in stream.chunks(CHUNK_LEN).enumerate() {
            progress.progress(CHUNK_LEN * chunk_no);
            self.usb.write_bulk(Backend::<B>::BULK_OUT_EP, chunk)?;
        }
        progress.progress(stream.len());
        Ok(())
    }

    /// Program a bitstream into the FPGA.
    pub fn fpga_program(&self, bitstream: &[u8], progress: &dyn ProgressIndicator) -> Result<()> {
        self.fpga_prepare(Backend::<B>::FPGA_PROG_SPEED)?;
        let result = self.fpga_download(bitstream, progress);

        let mut status = false;
        if result.is_ok() {
            for _ in 0..5 {
                status = self.fpga_is_programmed()?;
                if status {
                    break;
                }
                std::thread::sleep(Duration::from_millis(1));
            }
        }
        self.send_ctrl(
            Backend::<B>::CMD_FPGA_PROGRAM,
            Backend::<B>::PROGRAM_EXIT,
            &[],
        )?;

        if let Err(e) = result {
            Err(TransportError::FpgaProgramFailed(e.to_string()).into())
        } else if !status {
            Err(TransportError::FpgaProgramFailed("unknown error".to_string()).into())
        } else {
            Ok(())
        }
    }

    pub fn clear_bitstream(&self) -> Result<()> {
        self.fpga_prepare(Backend::<B>::FPGA_PROG_SPEED)?;
        self.send_ctrl(
            Backend::<B>::CMD_FPGA_PROGRAM,
            Backend::<B>::PROGRAM_EXIT,
            &[],
        )?;
        if self.fpga_is_programmed()? {
            Err(TransportError::ClearBitstreamFailed().into())
        } else {
            Ok(())
        }
    }

    /// Given a Chip Whisperer board pin name, return its pin number.
    pub fn pin_name_to_number(pinname: &str) -> Result<u8> {
        // If the pinname is an integer, use it; otherwise try to see if it
        // is a symbolic name of a pin.
        if let Ok(pinnum) = u8::from_str(pinname) {
            ensure!(
                pinnum <= Backend::<B>::LAST_PIN_NUMBER,
                GpioError::InvalidPinNumber(pinnum)
            );
            return Ok(pinnum);
        }
        let pinname = pinname.to_uppercase();
        let pn = pinname.as_str();

        if SCHEMATIC_PIN_NAMES.contains_key(pn) {
            Ok(SAM3X_PIN_NAMES[SCHEMATIC_PIN_NAMES[pn]])
        } else if SAM3X_PIN_NAMES.contains_key(pn) {
            Ok(SAM3X_PIN_NAMES[pn])
        } else {
            Err(GpioError::InvalidPinName(pinname).into())
        }
    }

    /// Write a byte to the CDCE906 PLL chip.
    fn pll_write(&self, addr: u8, data: u8) -> Result<()> {
        // We don't want the EEPROM to wear out prematurely. Write only if `data` is different than
        // what is already stored.
        if self.pll_read(addr)? == data {
            log::debug!(
                "Skipping PLL write since address {} is already {}",
                addr,
                data
            );
            return Ok(());
        }
        self.send_ctrl(
            Backend::<B>::CMD_PLL,
            0,
            &[Backend::<B>::REQ_PLL_WRITE, addr, data],
        )?;
        let mut resp = [0u8; 2];
        self.read_ctrl(Backend::<B>::CMD_PLL, 0, &mut resp)?;
        if resp[0] != Backend::<B>::RESP_PLL_OK {
            Err(
                TransportError::PllProgramFailed(format!("CDCE906 write error: {}", resp[0]))
                    .into(),
            )
        } else {
            Ok(())
        }
    }

    /// Read a byte from the CDCE906 PLL chip.
    fn pll_read(&self, addr: u8) -> Result<u8> {
        self.send_ctrl(
            Backend::<B>::CMD_PLL,
            0,
            &[Backend::<B>::REQ_PLL_READ, addr, 0],
        )?;
        let mut resp = [0u8; 2];
        self.read_ctrl(Backend::<B>::CMD_PLL, 0, &mut resp)?;
        if resp[0] != Backend::<B>::RESP_PLL_OK {
            Err(TransportError::PllProgramFailed(format!("CDCE906 read error: {}", resp[0])).into())
        } else {
            Ok(resp[1])
        }
    }

    /// Enable or disable the CDCE906 PLL chip.
    pub fn pll_enable(&self, enable: bool) -> Result<()> {
        // TODO(#12872): Define constants.
        let mut reg = self.pll_read(12)?;
        if enable {
            reg &= !(1 << 6);
        } else {
            reg |= 1 << 6;
        }
        self.pll_write(12, reg)
    }

    /// Calculate the multiply and divide values for the given frequency.
    fn pll_calc_mul_div(&self, target_freq: u32) -> Result<PllMulDiv> {
        const TARGET_FREQ_MIN: u32 = 630_000;
        const TARGET_FREQ_MAX: u32 = 167_000_000;
        if !(TARGET_FREQ_MIN..=TARGET_FREQ_MAX).contains(&target_freq) {
            return Err(TransportError::PllProgramFailed(format!(
                "Target frequency out of range: {}",
                target_freq
            ))
            .into());
        }

        const REF_FREQ: u32 = 12_000_000;
        const FVCO_MIN: u32 = 80_000_000;
        const FVCO_MAX: u32 = 300_000_000;
        let mut res = PllMulDiv::default();
        // `outdiv` range to put `fvco` in [80 MHz, 300 MHz].
        let outdiv_min: u8 = cmp::max(FVCO_MIN / target_freq, 1u32).try_into()?;
        let outdiv_max: u8 = cmp::min(FVCO_MAX / target_freq, 127u32).try_into()?;
        let mut best_err: u64 = u64::MAX;

        'outer: for outdiv in outdiv_min..=outdiv_max {
            let fvco_exp = target_freq as u64 * outdiv as u64;
            for numerator in 1u16..4096 {
                for denominator in 1u16..512 {
                    let fvco_act = (REF_FREQ as u64 * numerator as u64) / denominator as u64;
                    let err = fvco_exp.abs_diff(fvco_act);
                    if err < best_err {
                        best_err = err;
                        res = PllMulDiv {
                            numerator,
                            denominator,
                            outdiv,
                            fvco: fvco_act.try_into()?,
                        };
                    }
                    if best_err == 0 {
                        break 'outer;
                    }
                }
            }
        }

        if !(FVCO_MIN..=FVCO_MAX).contains(&res.fvco) {
            Err(
                TransportError::PllProgramFailed(format!("fvco value out of range: {}", res.fvco))
                    .into(),
            )
        } else {
            Ok(res)
        }
    }

    /// Set the frequency of the given PLL in the CDCE906 PLL chip.
    pub fn pll_out_freq_set(&self, pll_num: u8, target_freq: u32) -> Result<()> {
        if pll_num > 2 {
            return Err(
                TransportError::PllProgramFailed(format!("Unknown PLL: {}", pll_num)).into(),
            );
        }

        // Configure multiply and divide values.
        let vals = self.pll_calc_mul_div(target_freq)?;
        log::debug!(
            "target_freq: {}, vals: {:?}, error: {}",
            target_freq,
            vals,
            vals.fvco / u32::from(vals.outdiv) - target_freq
        );
        // TODO(#12872): Define constants.
        let offset = 3 * pll_num;
        self.pll_write(1 + offset, (vals.denominator & 0xff).try_into()?)?;
        self.pll_write(2 + offset, (vals.numerator & 0xff).try_into()?)?;
        let mut base = self.pll_read(3 + offset)?;
        base &= 0xe0;
        base |= u8::try_from((vals.denominator & 0x100) >> 8)?;
        base |= u8::try_from((vals.numerator & 0xf00) >> 7)?;
        self.pll_write(3 + offset, base)?;
        self.pll_write(13 + pll_num, vals.outdiv & 0x7f)?;

        // Enable high-speed mode if fvco is above 180 MHz.
        const FVCO_HIGH_SPEED: u32 = 180_000_000;
        let mut data = self.pll_read(6)?;
        let pll_bit = match pll_num {
            0 => 7,
            1 => 6,
            2 => 5,
            _ => {
                return Err(
                    TransportError::PllProgramFailed(format!("Unknown PLL: {}", pll_num)).into(),
                )
            }
        };
        data &= !(1 << pll_bit);
        if vals.fvco > FVCO_HIGH_SPEED {
            data |= 1 << pll_bit;
        }
        self.pll_write(6, data)
    }

    /// Enable or disable the given PLL in CDCE906 PLL chip.
    pub fn pll_out_enable(&self, pll_num: u8, enable: bool) -> Result<()> {
        // Note: The value that we use here corresponds to '+0nS'.
        const SLEW_RATE: u8 = 3;
        let (offset, div_src) = match pll_num {
            0 => (0, 0),
            1 => (1, 1),
            2 => (4, 2),
            _ => {
                return Err(
                    TransportError::PllProgramFailed(format!("Unknown PLL: {}", pll_num)).into(),
                )
            }
        };

        // TODO(#12872): Define constants.
        let mut data = 0;
        if enable {
            data |= 1 << 3;
        }
        data |= div_src;
        data |= SLEW_RATE << 4;
        self.pll_write(19 + offset, data)?;

        Ok(())
    }

    /// Save PLL settings to EEPROM, making them power-on defaults.
    pub fn pll_write_defaults(&self) -> Result<()> {
        // TODO(#12872): Define constants.
        let data = self.pll_read(26)?;
        self.pll_write(26, data | (1 << 7))?;

        while self.pll_read(24)? & (1 << 7) != 0 {
            std::thread::sleep(Duration::from_millis(50));
        }

        self.pll_write(26, data & !(1 << 7))
    }
}

// Mapping of SAM3 pin names to pin numbers.
static SAM3X_PIN_NAMES: Lazy<HashMap<&'static str, u8>> = Lazy::new(|| {
    collection! {
        "PA0" =>  0,
        "PA1" =>  1,
        "PA2" =>  2,
        "PA3" =>  3,
        "PA4" =>  4,
        "PA5" =>  5,
        "PA6" =>  6,
        "PA7" =>  7,
        "PA8" =>  8,
        "PA9" =>  9,
        "PA10" => 10,
        "PA11" => 11,
        "PA12" => 12,
        "PA13" => 13,
        "PA14" => 14,
        "PA15" => 15,
        "PA16" => 16,
        "PA17" => 17,
        "PA18" => 18,
        "PA19" => 19,
        "PA20" => 20,
        "PA21" => 21,
        "PA22" => 22,
        "PA23" => 23,
        "PA24" => 24,
        "PA25" => 25,
        "PA26" => 26,
        "PA27" => 27,
        "PA28" => 28,
        "PA29" => 29,
        "PB0" =>  32,
        "PB1" =>  33,
        "PB2" =>  34,
        "PB3" =>  35,
        "PB4" =>  36,
        "PB5" =>  37,
        "PB6" =>  38,
        "PB7" =>  39,
        "PB8" =>  40,
        "PB9" =>  41,
        "PB10" => 42,
        "PB11" => 43,
        "PB12" => 44,
        "PB13" => 45,
        "PB14" => 46,
        "PB15" => 47,
        "PB16" => 48,
        "PB17" => 49,
        "PB18" => 50,
        "PB19" => 51,
        "PB20" => 52,
        "PB21" => 53,
        "PB22" => 54,
        "PB23" => 55,
        "PB24" => 56,
        "PB25" => 57,
        "PB26" => 58,
        "PB27" => 59,
        "PB28" => 60,
        "PB29" => 61,
        "PB30" => 62,
        "PB31" => 63,
        "PC0" =>  64,
        "PC1" =>  65,
        "PC2" =>  66,
        "PC3" =>  67,
        "PC4" =>  68,
        "PC5" =>  69,
        "PC6" =>  70,
        "PC7" =>  71,
        "PC8" =>  72,
        "PC9" =>  73,
        "PC10" => 74,
        "PC11" => 75,
        "PC12" => 76,
        "PC13" => 77,
        "PC14" => 78,
        "PC15" => 79,
        "PC16" => 80,
        "PC17" => 81,
        "PC18" => 82,
        "PC19" => 83,
        "PC20" => 84,
        "PC21" => 85,
        "PC22" => 86,
        "PC23" => 87,
        "PC24" => 88,
        "PC25" => 89,
        "PC26" => 90,
        "PC27" => 91,
        "PC28" => 92,
        "PC29" => 93,
        "PC30" => 94,
        "PD0" =>  96,
        "PD1" =>  97,
        "PD2" =>  98,
        "PD3" =>  99,
        "PD4" =>  100,
        "PD5" =>  101,
        "PD6" =>  102,
        "PD7" =>  103,
        "PD8" =>  104,
        "PD9" =>  105,
        "PD10" => 106
    }
});
// Mapping of schematic pin names to SAM3 pin names.
static SCHEMATIC_PIN_NAMES: Lazy<HashMap<&'static str, &'static str>> = Lazy::new(|| {
    collection! {
        "USBSPARE0" => "PC10",
        "USBSPARE1" => "PC11",
        "USBSPARE2" => "PC12",
        "USBSPARE3" => "PC13",
        "USBRD" => "PA29",
        "USBWR" => "PC18",
        "USBCE" => "PA6",
        "USBALE" => "PC17",
        "USBCK0" => "PB22",
        "USBCK1" => "PA24",
        "USB_A0" => "PC21",
        "USB_A1" => "PC22",
        "USB_A2" => "PC23",
        "USB_A3" => "PC24",
        "USB_A4" => "PC25",
        "USB_A5" => "PC26",
        "USB_A6" => "PC27",
        "USB_A7" => "PC28",
        "USB_A8" => "PC29",
        "USB_A9" => "PC30",
        "USB_A10" => "PD0",
        "USB_A11" => "PD1",
        "USB_A12" => "PD2",
        "USB_A13" => "PD3",
        "USB_A14" => "PD4",
        "USB_A15" => "PD5",
        "USB_A16" => "PD6",
        "USB_A17" => "PD7",
        "USB_A18" => "PD8",
        "USB_A19" => "PD9",
        "USB_D0" => "PC2",
        "USB_D1" => "PC3",
        "USB_D2" => "PC4",
        "USB_D3" => "PC5",
        "USB_D4" => "PC6",
        "USB_D5" => "PC7",
        "USB_D6" => "PC8",
        "USB_D7" => "PC9",
        "SWSTATE" => "PB26",
        "PWRON" => "PB27",
        "LEDSURGE" => "PB14",
        "SAM_FPGA_CFG_CS" => "PB16",
        "CFG_INITB" => "PB18",
        "CFG_DONE" => "PB17",
        "CFB_PROGRAMB" => "PB19",
        "SAM_FPGA_COPI" => "PB20",
        "SAM_FPGA_CIPO" => "PB21",
        "SAM_FPGA_CCLK" => "PB24",
        "USB_CLK1" => "PA24",
        "USB_SPI_CIPO" => "PA25",
        "USB_SPI_COPI" => "PA26",
        "USB_SPI_SCK" => "PA27",
        "USB_SPI_CS" => "PA28"
    }
});