-
Notifications
You must be signed in to change notification settings - Fork 116
Expand file tree
/
Copy pathmodel_fpga_subsystem.rs
More file actions
2867 lines (2556 loc) · 99.9 KB
/
Copy pathmodel_fpga_subsystem.rs
File metadata and controls
2867 lines (2556 loc) · 99.9 KB
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
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed under the Apache-2.0 license
#![allow(clippy::mut_from_ref)]
#![allow(dead_code)]
use crate::api_types::{DeviceLifecycle, Fuses};
use crate::bmc::Bmc;
use crate::fpga_regs::{
Control, FifoData, FifoRegs, FifoStatus, FlashControl, FlashCtrlRegs, FlashOpStatus,
ItrngFifoStatus, WrapperRegs,
};
use crate::keys::{DEFAULT_LIFECYCLE_RAW_TOKENS, DEFAULT_MANUF_DEBUG_UNLOCK_RAW_TOKEN};
use crate::mcu_boot_status::McuBootMilestones;
use crate::openocd::openocd_jtag_tap::{JtagParams, JtagTap, OpenOcdJtagTap};
use crate::otp_provision::{
lc_generate_memory, otp_generate_lifecycle_tokens_mem, otp_generate_linear_majority_vote,
otp_generate_manuf_debug_unlock_token_mem, otp_generate_sw_manuf_partition_mem,
LifecycleControllerState, OtpSwManufPartition,
};
use crate::xi3c::XI3cError;
use crate::{
xi3c, BootParams, Error, HwModel, InitParams, ModelCallback, ModelError, Output, TrngMode,
};
use crate::{OcpLockState, SecurityState};
use anyhow::Result;
use caliptra_api::SocManager;
use caliptra_emu_bus::{Bus, BusError, BusMmio, Device, Event, EventData, RecoveryCommandCode};
use caliptra_emu_types::{RvAddr, RvData, RvSize};
use caliptra_hw_model_types::{HexSlice, DEFAULT_FIELD_ENTROPY, DEFAULT_UDS_SEED};
use caliptra_image_types::FwVerificationPqcKeyType;
use sensitive_mmio::{SensitiveMmio, SensitiveMmioArgs};
use std::io::Write;
use std::marker::PhantomData;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{mpsc, Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};
use tock_registers::interfaces::{ReadWriteable, Readable, Writeable};
use uio::{UioDevice, UioError};
use zerocopy::{FromBytes, IntoBytes};
// UIO mapping indices
const FPGA_WRAPPER_MAPPING: (usize, usize) = (0, 0);
const CALIPTRA_MAPPING: (usize, usize) = (0, 1);
const CALIPTRA_ROM_MAPPING: (usize, usize) = (0, 2);
const I3C_CONTROLLER_MAPPING: (usize, usize) = (0, 3);
const OTP_RAM_MAPPING: (usize, usize) = (0, 4);
const LC_MAPPING: (usize, usize) = (1, 0);
const MCU_ROM_MAPPING: (usize, usize) = (1, 1);
const I3C_TARGET_MAPPING: (usize, usize) = (1, 2);
const MCI_MAPPING: (usize, usize) = (1, 3);
const OTP_MAPPING: (usize, usize) = (1, 4);
// Default flash size: 16MB each, initialized to 0xFF
const DEFAULT_FLASH_SIZE: usize = 16 * 1024 * 1024;
// TODO(timothytrippel): autogenerate these from the OTP memory map definition
// Offsets in the OTP for all partitions.
// SW_TEST_UNLOCK_PARTITION
const OTP_SW_TEST_UNLOCK_PARTITION_OFFSET: usize = 0x0;
// SW_MANUF_PARTITION
const OTP_SW_MANUF_PARTITION_OFFSET: usize = 0x0F8;
// SECRET_LC_TRANSITION_PARTITION
const OTP_SECRET_LC_TRANSITION_PARTITION_OFFSET: usize = 0x300;
// SVN_PARTITION
const OTP_SVN_PARTITION_OFFSET: usize = 0x3B8;
const OTP_SVN_PARTITION_FMC_SVN_FIELD_OFFSET: usize = OTP_SVN_PARTITION_OFFSET + 0; // 4 bytes
const OTP_SVN_PARTITION_RUNTIME_SVN_FIELD_OFFSET: usize = OTP_SVN_PARTITION_OFFSET + 4; // 16 bytes
const OTP_SVN_PARTITION_SOC_MANIFEST_SVN_FIELD_OFFSET: usize = OTP_SVN_PARTITION_OFFSET + 20; // 16 bytes
const OTP_SVN_PARTITION_SOC_MAX_SVN_FIELD_OFFSET: usize = OTP_SVN_PARTITION_OFFSET + 36; // 1 byte used
// VENDOR_HASHES_MANUF_PARTITION
const OTP_VENDOR_HASHES_MANUF_PARTITION_OFFSET: usize = 0x420;
const FUSE_VENDOR_PKHASH_OFFSET: usize = OTP_VENDOR_HASHES_MANUF_PARTITION_OFFSET;
const FUSE_PQC_OFFSET: usize = OTP_VENDOR_HASHES_MANUF_PARTITION_OFFSET + 48;
// VENDOR_HASHES_PROD_PARTITION
const OTP_VENDOR_HASHES_PROD_PARTITION_OFFSET: usize = 0x460;
const FUSE_OWNER_PKHASH_OFFSET: usize = OTP_VENDOR_HASHES_PROD_PARTITION_OFFSET; // 48 bytes
// VENDOR_REVOCATIONS_PROD_PARTITION
const OTP_VENDOR_REVOCATIONS_PROD_PARTITION_OFFSET: usize = 0x7C0;
const FUSE_VENDOR_ECC_REVOCATION_OFFSET: usize = OTP_VENDOR_REVOCATIONS_PROD_PARTITION_OFFSET + 12; // 4 bytes
const FUSE_VENDOR_LMS_REVOCATION_OFFSET: usize = OTP_VENDOR_REVOCATIONS_PROD_PARTITION_OFFSET + 16; // 4 bytes
const FUSE_VENDOR_REVOCATION_OFFSET: usize = OTP_VENDOR_REVOCATIONS_PROD_PARTITION_OFFSET + 20; // 4 bytes
// LIFECYCLE_PARTITION
// VENDOR_NON_SECRET_PROD_PARTITION
pub const VENDOR_NON_SECRET_PROD_PARTITION_BYTE_OFFSET: usize = 0xaa8;
const UDS_SEED_OFFSET: usize = VENDOR_NON_SECRET_PROD_PARTITION_BYTE_OFFSET; // 64 bytes
const FIELD_ENTROPY_OFFSET: usize = VENDOR_NON_SECRET_PROD_PARTITION_BYTE_OFFSET + 64; // 32 bytes
// CPTRA_SS_LOCK_HEK_PROD partitions
const OTP_CPTRA_SS_LOCK_HEK_PROD_0_OFFSET: usize = 0xCB0;
const OTP_CPTRA_SS_LOCK_HEK_PROD_1_OFFSET: usize = OTP_CPTRA_SS_LOCK_HEK_PROD_0_OFFSET + 48;
const OTP_CPTRA_SS_LOCK_HEK_PROD_2_OFFSET: usize = OTP_CPTRA_SS_LOCK_HEK_PROD_1_OFFSET + 48;
const OTP_CPTRA_SS_LOCK_HEK_PROD_3_OFFSET: usize = OTP_CPTRA_SS_LOCK_HEK_PROD_2_OFFSET + 48;
const OTP_CPTRA_SS_LOCK_HEK_PROD_4_OFFSET: usize = OTP_CPTRA_SS_LOCK_HEK_PROD_3_OFFSET + 48;
const OTP_CPTRA_SS_LOCK_HEK_PROD_5_OFFSET: usize = OTP_CPTRA_SS_LOCK_HEK_PROD_4_OFFSET + 48;
const OTP_CPTRA_SS_LOCK_HEK_PROD_6_OFFSET: usize = OTP_CPTRA_SS_LOCK_HEK_PROD_5_OFFSET + 48;
const OTP_CPTRA_SS_LOCK_HEK_PROD_7_OFFSET: usize = OTP_CPTRA_SS_LOCK_HEK_PROD_6_OFFSET + 48;
// LIFECYCLE_PARTITION
const OTP_LIFECYCLE_PARTITION_OFFSET: usize = 0xE30;
// These are the default physical addresses for the peripherals. The addresses listed in
// FPGA_MEMORY_MAP are physical addresses specific to the FPGA. These addresses are used over the
// FPGA addresses so similar code can be used between the emulator and the FPGA hardware models.
// These are only used for calculating offsets from the virtual addresses retrieved from UIO.
const EMULATOR_I3C_ADDR: usize = 0x2000_4000;
const EMULATOR_I3C_ADDR_RANGE_SIZE: usize = 0x1000;
const EMULATOR_I3C_END_ADDR: usize = EMULATOR_I3C_ADDR + EMULATOR_I3C_ADDR_RANGE_SIZE - 1;
const EMULATOR_MCI_ADDR: usize = 0x2100_0000;
const EMULATOR_MCI_ADDR_RANGE_SIZE: usize = 0xe0_0000;
const EMULATOR_MCI_END_ADDR: usize = EMULATOR_MCI_ADDR + EMULATOR_MCI_ADDR_RANGE_SIZE - 1;
const EMULATOR_OTP_ADDR: usize = 0x1006_0000;
const EMULATOR_OTP_ADDR_RANGE_SIZE: usize = OTP_FULL_SIZE;
const EMULATOR_OTP_END_ADDR: usize = EMULATOR_OTP_ADDR + EMULATOR_OTP_ADDR_RANGE_SIZE - 1;
// page size of simulated flash
const FLASH_PAGE_SIZE: usize = 256;
pub(crate) fn fmt_uio_error(err: UioError) -> String {
format!("{err:?}")
}
/// Configures the memory map for the MCU.
/// These are the defaults that can be overridden and provided to the ROM and runtime builds.
#[repr(C)]
pub struct McuMemoryMap {
pub rom_offset: u32,
pub rom_size: u32,
pub rom_stack_size: u32,
pub sram_offset: u32,
pub sram_size: u32,
pub pic_offset: u32,
pub dccm_offset: u32,
pub dccm_size: u32,
pub i3c_offset: u32,
pub i3c_size: u32,
pub mci_offset: u32,
pub mci_size: u32,
pub mbox_offset: u32,
pub mbox_size: u32,
pub soc_offset: u32,
pub soc_size: u32,
pub otp_offset: u32,
pub otp_size: u32,
pub lc_offset: u32,
pub lc_size: u32,
}
const FPGA_MEMORY_MAP: McuMemoryMap = McuMemoryMap {
rom_offset: 0xb004_0000,
rom_size: 128 * 1024,
rom_stack_size: 0x3000,
dccm_offset: 0x5000_0000,
dccm_size: 16 * 1024,
sram_offset: 0xa8c0_0000,
sram_size: 384 * 1024,
pic_offset: 0x6000_0000,
i3c_offset: 0xa403_0000,
i3c_size: 0x1000,
mci_offset: 0xa800_0000,
mci_size: 0xa0_0028,
mbox_offset: 0xa412_0000,
mbox_size: 0x28,
soc_offset: 0xa413_0000,
soc_size: 0x5e0,
otp_offset: 0xa406_0000,
otp_size: OTP_FULL_SIZE as u32,
lc_offset: 0xa404_0000,
lc_size: 0x8c,
};
// Set to core_clk cycles per ITRNG sample.
const ITRNG_DIVISOR: u32 = 400;
const DEFAULT_AXI_PAUSER: u32 = 0x1;
// we split the OTP memory into two parts: the OTP half and a simulated flash half.
const OTP_FULL_SIZE: usize = 16384;
const FLASH_SIZE: usize = 8192;
const OTP_SIZE: usize = 8192;
const _: () = assert!(OTP_SIZE + FLASH_SIZE == OTP_FULL_SIZE);
const _: () = assert!(OTP_LIFECYCLE_PARTITION_OFFSET + 88 + 8 <= OTP_SIZE);
const AXI_CLK_HZ: u32 = 199_999_000;
const I3C_CLK_HZ: u32 = 12_500_000;
// ITRNG FIFO stores 1024 DW and outputs 4 bits at a time to Caliptra.
const FPGA_ITRNG_FIFO_SIZE: usize = 1024;
const I3C_WRITE_FIFO_SIZE: u16 = 128;
pub struct Wrapper {
pub ptr: *mut u32,
}
impl Wrapper {
pub fn regs(&self) -> &mut WrapperRegs {
unsafe { &mut *(self.ptr as *mut WrapperRegs) }
}
pub fn fifo_regs(&self) -> &mut FifoRegs {
unsafe { &mut *(self.ptr.offset(0x1000 / 4) as *mut FifoRegs) }
}
}
unsafe impl Send for Wrapper {}
unsafe impl Sync for Wrapper {}
#[derive(Clone)]
pub struct Mci {
pub ptr: *mut u32,
}
impl Mci {
pub fn regs<'a>(&self) -> caliptra_registers::mci::RegisterBlock<BusMmio<FpgaRealtimeBus<'a>>> {
unsafe {
caliptra_registers::mci::RegisterBlock::new_with_mmio(
EMULATOR_MCI_ADDR as *mut u32,
BusMmio::new(FpgaRealtimeBus {
mmio: self.ptr,
phantom: Default::default(),
}),
)
}
}
}
#[derive(Clone)]
pub struct XI3CWrapper {
pub controller: Arc<Mutex<xi3c::Controller>>,
// TODO: remove pub from these once we know all the ways we need to use them.
// TODO: Possibly use Mutex to protect access as well.
pub i3c_mmio: *mut u32,
pub i3c_controller_mmio: *mut u32,
}
// needed to copy pointers
// Safety: the pointers are themselves perfectly thread-safe since they are static, but
// the underlying hardware behavior may not be guaranteed if they are used by multiple threads.
unsafe impl Send for XI3CWrapper {}
unsafe impl Sync for XI3CWrapper {}
impl XI3CWrapper {
pub unsafe fn i3c_core(
&self,
) -> caliptra_registers::i3ccsr::RegisterBlock<BusMmio<FpgaRealtimeBus<'_>>> {
caliptra_registers::i3ccsr::RegisterBlock::new_with_mmio(
EMULATOR_I3C_ADDR as *mut u32,
BusMmio::new(FpgaRealtimeBus {
mmio: self.i3c_mmio,
phantom: Default::default(),
}),
)
}
pub const unsafe fn regs(&self) -> &xi3c::XI3c {
&*(self.i3c_controller_mmio as *const xi3c::XI3c)
}
pub fn configure(&self) {
println!("I3C controller initializing");
// Safety: we are only reading the register
println!("XI3C HW version = {:x}", unsafe {
self.regs().version.get()
});
const I3C_MODE: u8 = 1;
self.controller
.lock()
.unwrap()
.set_s_clk(AXI_CLK_HZ, I3C_CLK_HZ, I3C_MODE);
self.controller.lock().unwrap().cfg_initialize().unwrap();
println!("I3C controller finished initializing");
}
/// Start receiving data (non-blocking).
pub fn read_start(&self, len: u16) -> Result<(), XI3cError> {
let target_addr = self.get_primary_addr();
let cmd = xi3c::Command {
no_repeated_start: 1,
pec: 0,
target_addr,
..Default::default()
};
self.controller.lock().unwrap().master_recv(&cmd, len)
}
/// Finish receiving data (blocking).
pub fn read_finish(&self, len: u16) -> Result<Vec<u8>, XI3cError> {
let target_addr = self.get_primary_addr();
let cmd = xi3c::Command {
cmd_type: 1,
no_repeated_start: 1,
pec: 0,
target_addr,
..Default::default()
};
self.controller
.lock()
.unwrap()
.master_recv_finish(None, &cmd, len)
}
/// Receive data (blocking).
pub fn read(&self, len: u16) -> Result<Vec<u8>, XI3cError> {
let target_addr = self.get_primary_addr();
let cmd = xi3c::Command {
no_repeated_start: 1,
target_addr,
..Default::default()
};
self.controller
.lock()
.unwrap()
.master_recv_polled(None, &cmd, len)
}
pub fn get_primary_addr(&self) -> u8 {
// Safety: we are only reading the register
let reg = unsafe {
self.i3c_core()
.stdby_ctrl_mode()
.stby_cr_device_addr()
.read()
};
if reg.dynamic_addr_valid() {
reg.dynamic_addr() as u8
} else if reg.static_addr_valid() {
reg.static_addr() as u8
} else {
panic!("I3C target does not have a valid address set");
}
}
fn get_recovery_addr(&self) -> u8 {
// Safety: we are only reading the register
let reg = unsafe {
self.i3c_core()
.stdby_ctrl_mode()
.stby_cr_virt_device_addr()
.read()
};
if reg.virt_dynamic_addr_valid() {
reg.virt_dynamic_addr() as u8
} else if reg.virt_static_addr_valid() {
reg.virt_static_addr() as u8
} else {
panic!("I3C virtual target does not have a valid address set");
}
}
/// Write data and wait for ACK (blocking).
pub fn write(&self, payload: &[u8]) -> Result<(), XI3cError> {
let target_addr = self.get_primary_addr();
let cmd = xi3c::Command {
no_repeated_start: 1,
target_addr,
..Default::default()
};
self.controller
.lock()
.unwrap()
.master_send_polled(&cmd, payload, payload.len() as u16)
}
/// Send data but don't wait for ACK (non-blocking).
pub fn write_nowait(&self, payload: &[u8]) -> Result<(), XI3cError> {
let target_addr = self.get_primary_addr();
let cmd = xi3c::Command {
no_repeated_start: 1,
target_addr,
..Default::default()
};
self.controller
.lock()
.unwrap()
.master_send(&cmd, payload, payload.len() as u16)
}
pub fn ibi_ready(&self) -> bool {
self.controller.lock().unwrap().ibi_ready()
}
pub fn ibi_recv(&self, timeout: Option<Duration>) -> Result<Vec<u8>, XI3cError> {
self.controller
.lock()
.unwrap()
.ibi_recv_polled(timeout.unwrap_or(Duration::from_millis(1))) // 256 bytes only takes ~0.2ms to transmit, so this gives us plenty of time
}
/// Available space in CMD_FIFO to write
pub fn cmd_fifo_level(&self) -> u16 {
self.controller.lock().unwrap().cmd_fifo_level()
}
/// Available space in WR_FIFO to write
pub fn write_fifo_level(&self) -> u16 {
self.controller.lock().unwrap().write_fifo_level()
}
/// Number of RESP status details are available in RESP_FIFO to read
pub fn resp_fifo_level(&self) -> u16 {
self.controller.lock().unwrap().resp_fifo_level()
}
/// Number of read data words are available in RD_FIFO to read
pub fn read_fifo_level(&self) -> u16 {
self.controller.lock().unwrap().read_fifo_level()
}
pub fn write_fifo_empty(&self) -> bool {
self.write_fifo_level() == I3C_WRITE_FIFO_SIZE
}
}
pub struct ModelFpgaSubsystem {
pub devs: [UioDevice; 2],
pub wrapper: Arc<Wrapper>,
pub caliptra_rom_backdoor: *mut u8,
pub mcu_rom_backdoor: *mut u8,
pub otp_mem_backdoor: *mut u8,
// Reset sensitive MMIO UIO pointers. Accessing these while subsystem is in reset will trigger
// a kernel panic.
pub mmio: SensitiveMmio,
pub realtime_thread: Option<thread::JoinHandle<()>>,
pub realtime_thread_exit_flag: Arc<AtomicBool>,
pub realtime_thread_paused: Arc<AtomicBool>,
pub fuses: Fuses,
pub otp_init: Vec<u8>,
pub output: Output,
pub recovery_started: bool,
pub bmc: Bmc,
pub from_bmc: mpsc::Receiver<Event>,
pub to_bmc: mpsc::Sender<Event>,
pub recovery_fifo_blocks: Vec<Vec<u8>>,
pub recovery_ctrl_len: usize,
pub recovery_ctrl_written: bool,
pub bmc_step_counter: usize,
pub blocks_sent: usize,
pub enable_mcu_uart_log: bool,
pub bootfsm_break: bool,
pub rom_callback: Option<ModelCallback>,
// Flash storage buffers for the flash controllers
pub primary_flash: Vec<u8>,
pub secondary_flash: Vec<u8>,
// whether or not to attempt flash boot instead of streaming boot
pub flash_boot: bool,
// Saved init params needed for cold_reset re-initialization
saved_input_wires: [u32; 2],
saved_cptra_obf_key: [u32; 8],
saved_csr_hmac_key: [u32; 16],
saved_raw_unlock_token_hash: [u32; 4],
saved_rma_or_scrap_ppd: bool,
saved_debug_intent: bool,
saved_prod_dbg_unlock_pk_hashes_offset: u32,
saved_num_prod_dbg_unlock_pk_hashes: u32,
saved_ocp_lock_en: bool,
saved_security_state: SecurityState,
saved_lc_state: Option<LifecycleControllerState>,
saved_use_strap_secrets: bool,
}
impl ModelFpgaSubsystem {
fn mci_boot_milestones(&mut self) -> McuBootMilestones {
McuBootMilestones::from((self.mci_flow_status() >> 16) as u16)
}
fn set_bootfsm_break(&mut self, val: bool) {
if val {
self.wrapper
.regs()
.control
.modify(Control::BootfsmBrkpoint::SET);
} else {
self.wrapper
.regs()
.control
.modify(Control::BootfsmBrkpoint::CLEAR);
}
}
fn set_ss_ocp_lock(&mut self, val: bool) {
if val {
self.wrapper.regs().control.modify(Control::OcpLockEn::SET);
} else {
self.wrapper
.regs()
.control
.modify(Control::OcpLockEn::CLEAR);
}
}
fn set_ss_debug_intent(&mut self, val: bool) {
if val {
self.wrapper
.regs()
.control
.modify(Control::SsDebugIntent::SET);
} else {
self.wrapper
.regs()
.control
.modify(Control::SsDebugIntent::CLEAR);
}
}
fn set_ss_rma_or_scrap_ppd(&mut self, val: bool) {
if val {
self.wrapper
.regs()
.control
.modify(Control::LcAllowRmaOrScrapOnPpd::SET);
} else {
self.wrapper
.regs()
.control
.modify(Control::LcAllowRmaOrScrapOnPpd::CLEAR);
}
}
fn set_raw_unlock_token_hash(&mut self, token_hash: &[u32; 4]) {
for i in 0..token_hash.len() {
self.wrapper.regs().cptr_ss_raw_unlock_token_hash[i].set(token_hash[i]);
}
}
fn axi_reset(&mut self) {
self.wrapper.regs().control.modify(Control::AxiReset.val(1));
// wait a few clock cycles or we can crash the FPGA
std::thread::sleep(std::time::Duration::from_micros(1));
}
/// Re-programs all FPGA wrapper registers that are cleared by AXI reset.
/// Called from both `new_unbooted()` and `cold_reset()`.
fn setup_hardware_registers(&mut self) {
let input_wires = self.saved_input_wires;
let cptra_obf_key = self.saved_cptra_obf_key;
let csr_hmac_key = self.saved_csr_hmac_key;
let raw_unlock_token_hash = self.saved_raw_unlock_token_hash;
let rma_or_scrap_ppd = self.saved_rma_or_scrap_ppd;
let debug_intent = self.saved_debug_intent;
let bootfsm_break = self.bootfsm_break;
let prod_dbg_offset = self.saved_prod_dbg_unlock_pk_hashes_offset;
let num_prod_dbg = self.saved_num_prod_dbg_unlock_pk_hashes;
let ocp_lock_en = self.saved_ocp_lock_en;
let security_state = self.saved_security_state;
let lc_state = self.saved_lc_state;
println!(
"Setting input wires {:x} {:x}",
input_wires[0], input_wires[1]
);
self.set_generic_input_wires(&input_wires);
self.set_mci_generic_input_wires(&[0, 0]);
println!("Set itrng divider");
self.set_itrng_divider(ITRNG_DIVISOR);
println!("Set deobf key");
for i in 0..8 {
self.wrapper.regs().cptra_obf_key[i].set(cptra_obf_key[i]);
}
for i in 0..16 {
self.wrapper.regs().cptra_csr_hmac_key[i].set(csr_hmac_key[i]);
}
// Write UDS seed and field entropy to strap registers so that
// set_secrets_valid(true) gives DOE deterministic values.
for (i, &val) in DEFAULT_UDS_SEED.iter().enumerate() {
self.wrapper.regs().cptra_obf_uds_seed[i].set(val);
}
for (i, &val) in DEFAULT_FIELD_ENTROPY.iter().enumerate() {
self.wrapper.regs().cptra_obf_field_entropy[i].set(val);
}
// Use strap UDS and FE for deterministic IDevID on FPGA when requested
self.set_secrets_valid(self.saved_use_strap_secrets);
println!("Putting subsystem into reset");
self.set_subsystem_reset(true);
// Declaring this vec! gets LLVM to emit a memcpy. Otherwise, writes
// to the FPGA block RAM fail with a SIGBUS fault.
let zeroed_otp = vec![0u8; OTP_SIZE];
self.otp_slice().copy_from_slice(&zeroed_otp);
self.init_otp_with_lc_override(Some(&security_state), lc_state)
.expect("Failed to initialize OTP");
println!("Clearing fifo");
self.clear_logs();
self.set_axi_user(DEFAULT_AXI_PAUSER);
println!("AXI user written {:x}", DEFAULT_AXI_PAUSER);
self.set_raw_unlock_token_hash(&raw_unlock_token_hash);
self.set_ss_rma_or_scrap_ppd(rma_or_scrap_ppd);
self.set_ss_debug_intent(debug_intent);
self.set_bootfsm_break(bootfsm_break);
self.wrapper
.regs()
.prod_debug_unlock_auth_pk_hash_reg_bank_offset
.set(prod_dbg_offset);
self.wrapper
.regs()
.num_of_prod_debug_unlock_auth_pk_hashes
.set(num_prod_dbg);
self.set_ss_ocp_lock(ocp_lock_en);
println!("Writing MCU reset vector");
self.wrapper
.regs()
.mcu_reset_vector
.set(FPGA_MEMORY_MAP.rom_offset);
println!("Taking subsystem out of reset");
self.set_subsystem_reset(false);
}
pub fn set_subsystem_reset(&mut self, reset: bool) {
if reset {
self.mmio.disable();
}
self.wrapper.regs().control.modify(
Control::CptraSsRstB.val((!reset) as u32) + Control::CptraPwrgood.val((!reset) as u32),
);
// wait a little bit after resetting or releasing reset
std::thread::sleep(Duration::from_micros(1));
if !reset {
self.mmio.enable();
}
}
pub fn set_cptra_ss_rst_b(&mut self, value: bool) {
self.wrapper
.regs()
.control
.modify(Control::CptraSsRstB.val(value as u32));
}
fn set_secrets_valid(&mut self, value: bool) {
self.wrapper.regs().control.modify(
Control::CptraObfUdsSeedVld.val(value as u32)
+ Control::CptraObfFieldEntropyVld.val(value as u32),
)
}
/// Get a reference to the flash controller registers at the specified offset
pub fn flash_ctrl_regs(&self, is_primary: bool) -> &FlashCtrlRegs {
let offset = if is_primary { 0x2000 } else { 0x3000 };
// Safety: These are at fixed, known addresses relative to the wrapper.
unsafe {
let wrapper_base = self.wrapper.ptr as *const u8;
let flash_ctrl_ptr = wrapper_base.add(offset) as *const FlashCtrlRegs;
&*flash_ctrl_ptr
}
}
/// Implement a pair of simulated flash controllers, backed by data
/// stored in the host memory.
pub fn handle_flash(&mut self) {
self.handle_flash_ctrl(true);
self.handle_flash_ctrl(false);
}
/// Handle operations for a single flash controller
pub fn handle_flash_ctrl(&mut self, is_primary: bool) {
// check if we are in reset, in which case we don't need to worry about servicing flash
if !self.mmio.enabled() {
return;
}
let (start, page_num, op) = {
let regs = self.flash_ctrl_regs(is_primary);
(
regs.fl_control.read(FlashControl::START),
regs.page_num.get() as usize,
regs.fl_control.read(FlashControl::OP),
)
};
// Check if START bit is set
if start == 0 {
return;
}
let flash = if is_primary {
&mut self.primary_flash
} else {
&mut self.secondary_flash
};
let flash_len = flash.len();
let flash_offset = page_num * FLASH_PAGE_SIZE;
// Ensure flash buffer is large enough
let required_size = flash_offset + FLASH_PAGE_SIZE;
if flash_len < required_size {
flash.resize(required_size, 0xFF);
}
let mut error = 0u32;
if flash_offset + FLASH_PAGE_SIZE > flash.len() {
error = 1;
println!("[flash-ctrl] Flash operation FAILED: Flash offset 0x{:x} + size {} exceeds flash length {}",
flash_offset, FLASH_PAGE_SIZE, flash.len());
} else {
match op {
1 => {
// Read page: copy from flash buffer to memory at page_addr
let page_data = flash[flash_offset..flash_offset + FLASH_PAGE_SIZE].to_vec();
let word_count = FLASH_PAGE_SIZE / 4;
// re-borrow to avoid borrow checker
let flash_ctrl = self.flash_ctrl_regs(is_primary);
for i in 0..word_count {
let byte_offset = i * 4;
let value = u32::from_le_bytes(
page_data[byte_offset..byte_offset + 4].try_into().unwrap(),
);
flash_ctrl.buffer[i].set(value);
}
}
2 => {
// Write page: copy from memory at page_addr to flash buffer
let word_count = FLASH_PAGE_SIZE / 4;
let flash_ctrl = self.flash_ctrl_regs(is_primary);
let buffer: Vec<u8> = (0..word_count)
.into_iter()
.flat_map(|i| flash_ctrl.buffer[i].get().to_le_bytes())
.collect();
// re-borrow to avoid borrow checker conflicts
let flash = if is_primary {
&mut self.primary_flash
} else {
&mut self.secondary_flash
};
flash[flash_offset..flash_offset + FLASH_PAGE_SIZE].copy_from_slice(&buffer);
}
3 => {
// Erase page: fill with 0xFF
flash[flash_offset..flash_offset + FLASH_PAGE_SIZE].fill(0xFF);
}
_ => {
error = 1; // Treat invalid operation as read error
println!("[flash-ctrl] FAILED: Invalid operation code {}", op);
}
}
}
// Clear START bit and set DONE
let regs = self.flash_ctrl_regs(is_primary);
regs.fl_control.modify(FlashControl::START::CLEAR);
regs.op_status
.modify(FlashOpStatus::DONE::SET + FlashOpStatus::ERR.val(error));
regs.fl_interrupt_state.set(2); // event interrupt
}
fn clear_logs(&mut self) {
println!("Clearing Caliptra logs");
while !self
.wrapper
.fifo_regs()
.log_fifo_status
.is_set(FifoStatus::Empty)
{
self.wrapper.fifo_regs().log_fifo_data.get();
}
println!("Clearing MCU logs");
while !self
.wrapper
.fifo_regs()
.dbg_fifo_status
.is_set(FifoStatus::Empty)
{
self.wrapper.fifo_regs().dbg_fifo_data_pop.get();
}
println!("Clearing output and exit status");
let _ = self.output.sink().flush();
loop {
let s = self.output.take(1000);
if s.is_empty() {
break;
}
}
self.output.clear_exit_status();
}
fn handle_log(&mut self) {
// limit steps so that we don't starve the flash controller and BMC
const MAX_STEPS: i32 = 1000;
for _ in 0..MAX_STEPS {
// Check if the FIFO is full (which probably means there was an overrun)
if self
.wrapper
.fifo_regs()
.log_fifo_status
.is_set(FifoStatus::Full)
{
panic!("FPGA log FIFO overran");
}
if self
.wrapper
.fifo_regs()
.log_fifo_status
.is_set(FifoStatus::Empty)
{
break;
}
let data = self.wrapper.fifo_regs().log_fifo_data.extract();
// Add byte to log if it is valid
if data.is_set(FifoData::CharValid) {
self.output()
.sink()
.push_uart_char(data.read(FifoData::NextChar) as u8);
}
}
if self.enable_mcu_uart_log {
for _ in 0..MAX_STEPS {
// Check if the FIFO is full (which probably means there was an overrun)
if self
.wrapper
.fifo_regs()
.dbg_fifo_status
.is_set(FifoStatus::Full)
{
panic!("FPGA log FIFO overran");
}
if self
.wrapper
.fifo_regs()
.dbg_fifo_status
.is_set(FifoStatus::Empty)
{
break;
}
let data = self.wrapper.fifo_regs().dbg_fifo_data_pop.extract();
// Add byte to log if it is valid
if data.is_set(FifoData::CharValid) {
self.output()
.sink()
.push_uart_char(data.read(FifoData::NextChar) as u8);
}
}
}
}
// UIO crate doesn't provide a way to unmap memory.
pub fn unmap_mapping(&self, addr: *mut u32, mapping: (usize, usize)) {
let map_size = self.devs[mapping.0].map_size(mapping.1).unwrap();
unsafe {
nix::sys::mman::munmap(addr as *mut libc::c_void, map_size).unwrap();
}
}
fn realtime_thread_itrng_fn(
wrapper: Arc<Wrapper>,
running: Arc<AtomicBool>,
paused: Arc<AtomicBool>,
mut itrng_nibbles: Box<dyn Iterator<Item = u8> + Send>,
) {
// Reset ITRNG FIFO to clear out old data
wrapper
.fifo_regs()
.itrng_fifo_status
.write(ItrngFifoStatus::Reset::SET);
wrapper
.fifo_regs()
.itrng_fifo_status
.write(ItrngFifoStatus::Reset::CLEAR);
// Small delay to allow reset to complete
thread::sleep(Duration::from_millis(1));
while running.load(Ordering::Relaxed) {
// If paused, sleep and check again
if paused.load(Ordering::Relaxed) {
thread::sleep(Duration::from_millis(1));
continue;
}
// Once TRNG data is requested the FIFO will continously empty. Load at max one FIFO load at a time.
// FPGA ITRNG FIFO is 1024 DW deep.
for _ in 0..FPGA_ITRNG_FIFO_SIZE {
if !wrapper
.fifo_regs()
.itrng_fifo_status
.is_set(ItrngFifoStatus::Full)
{
let mut itrng_dw = 0;
for i in 0..8 {
match itrng_nibbles.next() {
Some(nibble) => itrng_dw += u32::from(nibble) << (4 * i),
None => return,
}
}
wrapper.fifo_regs().itrng_fifo_data.set(itrng_dw);
} else {
break;
}
}
// 1 second * (20 MHz / (2^13 throttling counter)) / 8 nibbles per DW: 305 DW of data consumed in 1 second.
let end_time = Instant::now() + Duration::from_millis(1000);
while running.load(Ordering::Relaxed) && Instant::now() < end_time {
thread::sleep(Duration::from_millis(1));
}
}
}
pub fn i3c_core(
&mut self,
) -> Option<caliptra_registers::i3ccsr::RegisterBlock<BusMmio<FpgaRealtimeBus<'_>>>> {
self.mmio.i3c_core()
}
pub fn i3c_controller(&self) -> Option<XI3CWrapper> {
self.mmio.i3c_controller().clone()
}
pub fn i3c_target_configured(&mut self) -> bool {
self.i3c_core()
.unwrap()
.i3c_base()
.hc_control()
.read()
.bus_enable()
}
pub fn start_recovery_bmc(&mut self) {
self.recovery_started = true;
}
fn bmc_step(&mut self) {
if !self.recovery_started {
return;
}
self.bmc_step_counter += 1;
// check if we need to fill the recovey FIFO
if !self.recovery_fifo_blocks.is_empty() {
if !self.recovery_ctrl_written {
let status = self
.i3c_core()
.unwrap()
.sec_fw_recovery_if()
.device_status_0()
.read()
.dev_status();
if status != 3 && self.bmc_step_counter % 65536 == 0 {
println!("Waiting for device status to be 3, currently: {}", status);
return;
}
// wait for any other packets to be sent
if !self.i3c_controller().unwrap().write_fifo_empty() {
return;
}
let len = ((self.recovery_ctrl_len / 4) as u32).to_le_bytes();
let mut ctrl = vec![0, 1]; // CMS = 0, reset FIFO
ctrl.extend_from_slice(&len);
println!("Writing Indirect fifo ctrl: {:x?}", ctrl);
self.recovery_block_write_request(RecoveryCommandCode::IndirectFifoCtrl, &ctrl);
let reported_len = self
.i3c_core()
.unwrap()
.sec_fw_recovery_if()
.indirect_fifo_ctrl_1()
.read();
println!("I3C core reported length: {}", reported_len);
if reported_len as usize != self.recovery_ctrl_len / 4 {
println!(
"I3C core reported length should have been {}",
self.recovery_ctrl_len / 4
);
self.print_i3c_registers();