1#![cfg_attr(
16 not(any(
17 feature = "esp32",
18 feature = "esp32c3",
19 feature = "esp32c6",
20 feature = "esp32s3",
21 feature = "esp32p4",
22 feature = "esp32s31"
23 )),
24 no_std
25)]
26#![forbid(unsafe_code)]
27
28extern crate alloc;
29
30use litz_mcu::MemoryRegion;
31
32#[cfg(any(
35 feature = "esp32",
36 feature = "esp32c3",
37 feature = "esp32c6",
38 feature = "esp32s3",
39 feature = "esp32p4",
40 feature = "esp32s31"
41))]
42pub mod router;
43
44pub mod debug;
48pub mod gdb;
49pub mod screenshot;
50
51#[cfg(any(
52 feature = "esp32",
53 feature = "esp32c3",
54 feature = "esp32c6",
55 feature = "esp32s3",
56 feature = "esp32p4",
57 feature = "esp32s31"
58))]
59pub use litz_net::{NetworkConfig, Service};
60#[cfg(any(
61 feature = "esp32",
62 feature = "esp32c3",
63 feature = "esp32c6",
64 feature = "esp32s3",
65 feature = "esp32p4",
66 feature = "esp32s31"
67))]
68pub use router::EspRouter;
69
70#[derive(Clone, Copy, Debug, PartialEq, Eq)]
72pub enum Chip {
73 Esp32C3,
75 Esp32C6,
77 Esp32H2,
79}
80
81#[derive(Clone, Copy, Debug)]
83pub struct FlashLayout {
84 pub size: u32,
85 pub bootloader_offset: u32,
87 pub partition_table_offset: u32,
89 pub app_offset: u32,
91}
92
93impl Chip {
94 pub const fn memory_map(self) -> &'static [MemoryRegion] {
95 match self {
97 Chip::Esp32C3 | Chip::Esp32C6 | Chip::Esp32H2 => &PLIC_AND_RV_MAP,
98 }
99 }
100
101 pub const fn flash_layout(self) -> FlashLayout {
102 FlashLayout {
103 size: 4 * 1024 * 1024,
104 bootloader_offset: 0x0,
105 partition_table_offset: 0x8000,
106 app_offset: 0x1_0000,
107 }
108 }
109}
110
111#[cfg(any(
119 feature = "esp32",
120 feature = "esp32c3",
121 feature = "esp32c6",
122 feature = "esp32s3",
123 feature = "esp32p4",
124 feature = "esp32s31"
125))]
126pub mod backend {
127 use alloc::vec::Vec;
128 use core::cell::RefCell;
129 use std::cell::Cell;
130 use std::collections::BTreeMap;
131 use std::rc::Rc;
132
133 use esp_periph::i2c::I2cDevice as EspI2cDevice;
134 use esp_soc::ble::peer::Nearby;
135 use esp_soc::board::{BoardEdge, BoardModel, SpiPins};
136 use esp_soc::uart::{UartInput, UartRoute};
137 use esp_soc::{Machine, Soc, SocBus};
138 use litz_board::{Board as LitzBoard, Conflict};
139 use litz_core::{Drive, Level, PartState};
140
141 pub type BusFactory<S> = fn(
149 [u8; 6],
150 usize,
151 Option<Rc<RefCell<LitzBoard>>>,
152 u16,
153 Rc<Cell<[u32; 2]>>,
154 ) -> <S as Soc>::Bus;
155
156 pub struct EspChip<S: Soc> {
158 machine: Machine<S>,
159 board: Option<Rc<RefCell<LitzBoard>>>,
160 mac: [u8; 6],
163 flash: usize,
164 bus_for: BusFactory<S>,
165 bootloader_loaded: bool,
168 analog: Vec<(u8, f32)>,
171 elf: Option<Vec<u8>>,
176 gdb: Option<GdbServeFn<S>>,
181 guest_call: Option<GuestCall<S>>,
185 board_index: u16,
188 net_clock: Rc<Cell<u64>>,
191 ble_attached: bool,
194 ble_seen: u64,
196 ble_peers: Vec<litz_ble::Beacon>,
199 powered: bool,
202 off_ns: u64,
206 spi_clock: Option<SpiClockSpec>,
211 spi_rates: Rc<Cell<[u32; 2]>>,
214 }
215
216 pub type GdbServeFn<S> = fn(&mut EspChip<S>, u16) -> Result<(), String>;
218
219 pub type GuestCall<S> = fn(&mut EspChip<S>, u32) -> Result<u32, String>;
223
224 #[cfg(any(
227 feature = "esp32c3",
228 feature = "esp32c6",
229 feature = "esp32p4",
230 feature = "esp32s31"
231 ))]
232 fn serve_gdb<S: crate::debug::Rv32Chip>(
233 chip: &mut EspChip<S>,
234 port: u16,
235 ) -> Result<(), String> {
236 crate::gdb::serve(chip, port)
237 }
238
239 impl<S: Soc> EspChip<S> {
240 fn bare(mac: [u8; 6], flash: usize, bus_for: BusFactory<S>) -> Self {
243 let spi_rates = Rc::new(Cell::new([0; 2]));
244 let machine = Self::build(mac, flash, bus_for, None, 0, Rc::clone(&spi_rates));
245 Self {
246 machine,
247 board: None,
248 mac,
249 flash,
250 bus_for,
251 bootloader_loaded: false,
252 analog: Vec::new(),
253 elf: None,
254 gdb: None,
255 guest_call: None,
256 board_index: 0,
257 powered: true,
258 off_ns: 0,
259 net_clock: Rc::new(Cell::new(0)),
260 ble_attached: false,
261 ble_seen: 0,
262 ble_peers: Vec::new(),
263 spi_clock: None,
264 spi_rates,
265 }
266 }
267
268 fn build(
269 mac: [u8; 6],
270 flash: usize,
271 bus_for: BusFactory<S>,
272 board: Option<Rc<RefCell<LitzBoard>>>,
273 index: u16,
274 spi_rates: Rc<Cell<[u32; 2]>>,
275 ) -> Machine<S> {
276 let mut machine = Machine::new(mac, bus_for(mac, flash, board, index, spi_rates));
277 machine.vq_max = 1;
284 machine.bb_max = 1;
285 machine.console.capture = true;
288 machine
289 }
290
291 pub fn with_board(self, board: LitzBoard) -> Self {
294 let shared = Rc::new(RefCell::new(board));
295 self.with_shared_board(shared, 0)
296 }
297
298 pub fn with_shared_board(mut self, board: Rc<RefCell<LitzBoard>>, index: u16) -> Self {
306 self.machine = Self::build(
307 self.mac,
308 self.flash,
309 self.bus_for,
310 Some(Rc::clone(&board)),
311 index,
312 Rc::clone(&self.spi_rates),
313 );
314 self.board = Some(board);
315 self.board_index = index;
316 if let Some(bytes) = &self.elf {
320 let _ = self.machine.add_symbols(bytes);
321 }
322 self.install_spi_observer();
323 self
324 }
325
326 fn install_spi_observer(&mut self) {
336 if self.board.is_none() {
337 return;
338 }
339 let Some(spec) = self.spi_clock else {
340 return;
341 };
342 if self.machine.has_observer("litz-spi-clock") {
343 return;
344 }
345 self.machine.add_observer(Box::new(SpiClockObserver {
346 rates: Rc::clone(&self.spi_rates),
347 spec,
348 }));
349 }
350
351 pub(crate) fn machine_ref(&self) -> &Machine<S> {
354 &self.machine
355 }
356
357 pub(crate) fn machine_mut(&mut self) -> &mut Machine<S> {
358 &mut self.machine
359 }
360
361 pub fn gdb_serve(&mut self, port: u16) -> Result<(), String> {
364 match self.gdb {
365 Some(serve) => serve(self, port),
366 None => Err(format!(
367 "{} has no GDB target: only the RISC-V chips describe a register file",
368 S::NAME
369 )),
370 }
371 }
372
373 pub fn with_elf(mut self, bytes: &[u8]) -> Result<Self, String> {
382 self.machine.add_symbols(bytes)?;
383 self.elf = Some(bytes.to_vec());
384 Ok(self)
385 }
386
387 pub fn has_bootloader(&self) -> bool {
390 self.bootloader_loaded
391 }
392
393 pub fn board(&self) -> Option<&Rc<RefCell<LitzBoard>>> {
394 self.board.as_ref()
395 }
396
397 pub fn board_model(&mut self) -> &mut dyn BoardModel {
401 self.machine.bus.board()
402 }
403
404 pub fn state(&self, part: &str) -> Option<PartState> {
405 self.board.as_ref()?.borrow().state(part)
406 }
407
408 pub fn press(&mut self, part: &str, pressed: bool) -> bool {
412 let Some(board) = self.board.as_ref() else {
413 return false;
414 };
415 let now = (self.machine.seconds() * 1e9) as u64;
416 board.borrow_mut().press(part, pressed, now)
417 }
418
419 pub fn set_psram_size(&mut self, bytes: usize) -> Result<(), String> {
424 self.machine.bus.set_psram_size(bytes)
425 }
426
427 pub fn set_control(&mut self, part: &str, permille: u16) -> bool {
428 let Some(board) = self.board.as_ref() else {
429 return false;
430 };
431 let now = (self.machine.seconds() * 1e9) as u64;
432 board.borrow_mut().set_control(part, permille, now)
433 }
434
435 pub fn set_named_control(&mut self, part: &str, name: &str, value: &str) -> bool {
437 let Some(board) = self.board.as_ref() else {
438 return false;
439 };
440 let now = (self.machine.seconds() * 1e9) as u64;
441 board.borrow_mut().set_named_control(part, name, value, now)
442 }
443
444 pub fn write_serial(&mut self, bytes: &[u8]) {
447 self.machine.bus.uart_input(0, bytes);
448 *self.machine.bus.irq_dirty() = true;
449 }
450
451 pub fn analog_inputs(&self) -> Vec<(u8, f32)> {
453 self.board
454 .as_ref()
455 .map(|b| b.borrow().analog_inputs_on(self.board_index))
456 .unwrap_or_default()
457 }
458
459 fn publish_analog(&mut self) {
468 let Some(board) = self.board.as_ref() else {
469 return;
470 };
471 let now = board.borrow().analog_inputs();
472 for &(gpio, volts) in &now {
473 let unchanged = self
474 .analog
475 .iter()
476 .any(|&(pin, v)| pin == gpio && v == volts);
477 if !unchanged {
478 self.machine
479 .bus
480 .analog_set(gpio, esp_periph::AnalogSource::Const(volts));
481 }
482 }
483 self.analog = now;
484 }
485
486 pub fn part_pin_level(&self, part: &str, pin: Option<&str>) -> Option<Level> {
489 let board = self.board.as_ref()?.borrow();
490 match pin {
491 Some(pin) => board.part_pin_level(part, pin),
492 None => board.chip_pin_level_on(self.board_index, part),
493 }
494 }
495
496 pub fn gpio_level(&self, gpio: u8) -> Option<Level> {
498 let board = self.board.as_ref()?.borrow();
499 board.chip_level_on(self.board_index, gpio)
500 }
501
502 pub fn conflicts(&self) -> Vec<Conflict> {
503 self.board
504 .as_ref()
505 .map(|b| b.borrow().conflicts().to_vec())
506 .unwrap_or_default()
507 }
508
509 pub fn load_rom(&mut self, rom_elf: &[u8]) -> Result<(), String> {
511 self.machine.load_rom(rom_elf)
512 }
513
514 pub fn write_flash(&mut self, offset: usize, data: &[u8]) -> Result<(), String> {
517 self.machine.write_flash(offset, data)
518 }
519
520 pub fn flash_image(&self) -> Option<&[u8]> {
523 self.machine.bus.flash_image()
524 }
525
526 pub fn boot_app(&mut self, app_off: usize) -> Result<u32, String> {
529 self.machine.boot_app(app_off)
530 }
531
532 pub fn load_script(&mut self, text: &str) -> Result<(), String> {
535 self.machine.load_script(text)
536 }
537
538 pub fn add_symbols(&mut self, elf: &[u8]) -> Result<(), String> {
541 self.machine.add_symbols(elf)
542 }
543
544 pub fn break_at(&mut self, pc: u32) {
546 self.machine
547 .add_observer(Box::new(esp_soc::observers::Breakpoints { pcs: vec![pc] }));
548 }
549
550 pub fn registers(&self) -> String {
552 self.machine.dump_regs()
553 }
554
555 pub fn enable_coverage(&mut self) {
558 if !self.machine.has_observer("coverage") {
559 self.machine
560 .add_observer(Box::new(esp_soc::observers::Coverage::new(None)));
561 }
562 }
563
564 pub fn reports(&mut self) -> Vec<String> {
566 self.machine.reports().lines().map(str::to_string).collect()
567 }
568
569 pub fn symbol_addr(&self, name: &str) -> Option<u32> {
573 self.machine.sym_addr(name)
574 }
575
576 pub fn call_guest(&mut self, address: u32) -> Result<u32, String> {
586 match self.guest_call {
587 Some(call) => call(self, address),
588 None => Err(format!(
589 "{} does not install a guest-call trampoline",
590 S::NAME
591 )),
592 }
593 }
594
595 pub fn sample_heap(&mut self) -> Result<u32, String> {
601 let names = [
602 "esp_get_free_heap_size",
603 "heap_caps_get_free_size",
604 "xPortGetFreeHeapSize",
605 ];
606 let (name, address) = names
607 .iter()
608 .find_map(|name| self.symbol_addr(name).map(|address| (*name, address)))
609 .ok_or_else(|| {
610 "no heap getter symbol in the ELF (esp_get_free_heap_size, \
611 heap_caps_get_free_size or xPortGetFreeHeapSize); supply `elf` in the project"
612 .to_string()
613 })?;
614 self.call_guest(address)
615 .map_err(|error| format!("{name}: {error}"))
616 }
617
618 pub fn disassemble(&mut self, addr: u32, count: usize) -> String {
619 self.machine.disasm(addr, count)
620 }
621
622 pub fn attach_wifi(&mut self, spec: &str) -> Result<(), String> {
629 let ap = esp_soc::wifi::ApConfig::parse(spec)?;
630 self.machine.bus.attach_wifi(ap, None)
631 }
632
633 pub fn attach_network(&mut self, config: &crate::NetworkConfig) -> Result<(), String> {
642 let specs: Vec<String> = config.access_points.iter().map(ap_spec).collect();
643 let aps = esp_soc::wifi::ApConfig::parse_all(&specs)?;
644 let nat = esp_soc::nat::Nat::with_transport(
645 false,
646 Box::new(crate::EspRouter::with_clock(
647 config,
648 Rc::clone(&self.net_clock),
649 )),
650 );
651 self.machine.bus.attach_wifi(aps[0].clone(), Some(nat))?;
652 for ap in &aps[1..] {
653 self.machine.bus.add_wifi_ap(ap.clone())?;
654 }
655 if !config.nearby.is_empty() {
656 let specs: Vec<String> = config.nearby.iter().map(nearby_spec).collect();
657 let beacons = esp_soc::wifi::BeaconAp::parse_all(&specs)?;
658 let left_out = self.machine.bus.wifi_nearby(beacons)?;
659 if let Some((beacon, why)) = left_out.first() {
660 return Err(format!(
661 "the network '{}' cannot be beside the access point: it shares {why}",
662 beacon.ssid
663 ));
664 }
665 }
666 Ok(())
667 }
668
669 #[cfg(not(target_arch = "wasm32"))]
676 pub fn attach_host_nat(&mut self, local_ntp: bool) -> Result<(), String> {
677 self.machine
678 .bus
679 .attach_nat(Some(esp_soc::nat::Nat::new(false)), local_ntp)
680 }
681
682 #[cfg(not(target_arch = "wasm32"))]
687 pub fn attach_host_forwards(
688 &mut self,
689 forwards: &[String],
690 local_ntp: bool,
691 ) -> Result<Vec<String>, String> {
692 let mut transport = esp_soc::nat::StdTransport::new();
693 let mut lines = Vec::new();
694 for spec in forwards {
695 let forward = esp_soc::nat::HostFwdSpec::parse(spec)?;
696 let at = transport
697 .listen(&forward)
698 .map_err(|e| format!("host forward {spec:?}: {e}"))?;
699 lines.push(format!("{spec} -> {at}"));
700 }
701 let mut nat = esp_soc::nat::Nat::with_transport(false, Box::new(transport));
702 nat.hostfwd = forwards.len() as u64;
703 self.machine.bus.attach_nat(Some(nat), local_ntp)?;
704 Ok(lines)
705 }
706
707 pub fn set_net_tap(&mut self, tap: esp_soc::netcap::NetTap) -> Result<(), String> {
710 self.machine.bus.set_net_tap(tap)
711 }
712
713 pub fn start_air_capture(&mut self, path: &std::path::Path) -> Result<(), String> {
716 let file =
717 std::fs::File::create(path).map_err(|e| format!("{}: {e}", path.display()))?;
718 let capture =
719 std::sync::Arc::new(std::sync::Mutex::new(esp_soc::netcap::AirCapture::default()));
720 capture
721 .lock()
722 .map_err(|_| "the air capture lock is poisoned".to_string())?
723 .set_pcap(Box::new(file))
724 .map_err(|e| format!("{}: {e}", path.display()))?;
725 self.machine
726 .bus
727 .set_air_tap(Some(capture))
728 .map_err(|e| format!("802.11 capture: {e}"))
729 }
730
731 pub fn start_ethernet_capture(&mut self, path: &std::path::Path) -> Result<(), String> {
734 let file =
735 std::fs::File::create(path).map_err(|e| format!("{}: {e}", path.display()))?;
736 let capture =
737 std::sync::Arc::new(std::sync::Mutex::new(esp_soc::netcap::NetCapture::default()));
738 capture
739 .lock()
740 .map_err(|_| "the Ethernet capture lock is poisoned".to_string())?
741 .set_pcap(Box::new(file))
742 .map_err(|e| format!("{}: {e}", path.display()))?;
743 self.machine
744 .bus
745 .set_net_tap(capture)
746 .map_err(|e| format!("Ethernet capture: {e}"))
747 }
748
749 pub fn set_ethernet_relay(&mut self, enabled: bool) -> Result<(), String> {
754 self.machine.bus.set_ethernet_relay(enabled)
755 }
756
757 pub fn take_ethernet_frames(&mut self) -> Vec<Vec<u8>> {
760 self.machine.bus.take_ethernet_frames()
761 }
762
763 pub fn receive_ethernet_frame(&mut self, frame: &[u8]) -> Result<(), String> {
765 self.machine.bus.receive_ethernet_frame(frame)
766 }
767
768 pub fn attach_ble(&mut self, config: &litz_ble::BleConfig) -> Result<(), String> {
782 if config.is_empty() {
783 return Ok(());
784 }
785 self.ble_seen = self
789 .board
790 .as_ref()
791 .map(|board| board.borrow().ble_generation())
792 .unwrap_or(0);
793 self.ble_attached = false;
794 let Some(bytes) = self.elf.clone() else {
802 return Err(format!(
803 "{} needs the firmware ELF to scan for a beacon: set [sim] elf, \
804 because the Bluetooth controller is started through the guest's \
805 symbol table",
806 S::NAME
807 ));
808 };
809 let elf = esp_soc::elf::parse(&bytes)?;
810 self.machine
811 .bus
812 .enable_ble(&elf)
813 .map_err(|why| format!("{} cannot carry BLE beacons: {why}", S::NAME))?;
814 let beacons = nearby_list(&config.beacons);
815 self.machine.bus.ble_nearby(beacons)?;
816 self.ble_peers = config.beacons.clone();
817 self.ble_attached = true;
818 Ok(())
819 }
820
821 pub fn set_ble_nearby(&mut self, config: &litz_ble::BleConfig) -> Result<(), String> {
830 if !self.ble_attached {
831 return Err("BLE is not enabled on this chip".into());
832 }
833 self.machine.bus.ble_nearby(nearby_list(&config.beacons))?;
834 self.ble_peers = config.beacons.clone();
835 self.ble_seen = self
836 .board
837 .as_ref()
838 .map(|board| board.borrow().ble_generation())
839 .unwrap_or(0);
840 Ok(())
841 }
842
843 pub fn add_ble_peer(&mut self, beacon: &litz_ble::Beacon) -> Result<(), String> {
851 if !self.ble_attached {
852 return Err("BLE is not enabled on this chip".into());
853 }
854 self.ble_peers.push(beacon.clone());
855 let peers = nearby_list(&self.ble_peers);
856 if let Err(error) = self.machine.bus.ble_nearby(peers) {
857 self.ble_peers.pop();
858 return Err(error);
859 }
860 self.ble_seen = self
861 .board
862 .as_ref()
863 .map(|board| board.borrow().ble_generation())
864 .unwrap_or(0);
865 Ok(())
866 }
867
868 pub fn ble_command(&mut self, command: &str) -> Result<(), String> {
879 self.machine.bus.ble_command(command)
880 }
881
882 pub fn ble_pending_commands(&self) -> usize {
884 self.machine.bus.ble_pending_commands()
885 }
886
887 pub fn ble_log(&mut self) -> Option<String> {
889 self.machine.bus.ble_log_take()
890 }
891
892 pub fn enable_full_ble(&mut self, observe: bool) -> Result<(), String> {
896 self.machine.bus.enable_ble_full(observe)
897 }
898
899 pub fn seconds(&self) -> f64 {
901 self.machine.seconds() + self.off_ns as f64 / 1e9
902 }
903
904 pub fn board_power(&self) -> bool {
906 match &self.board {
907 Some(board) => board.borrow().board_powered(self.board_index),
908 None => true,
909 }
910 }
911
912 fn boot_after_power(&mut self) -> Result<u32, String> {
915 if self.bootloader_loaded {
916 self.machine.reboot();
917 Ok(0)
918 } else {
919 let app = litz_board::Chip::info(self).flash.app as usize;
920 self.boot_app(app)
921 }
922 }
923
924 fn power_off(&mut self) {
926 self.powered = false;
927 if let Some(board) = &self.board {
928 let now = (self.seconds() * 1e9) as u64;
929 board
930 .borrow_mut()
931 .release_chip_outputs(self.board_index, now);
932 }
933 }
934
935 pub fn run(&mut self, steps: u64) -> esp_soc::Stop {
937 self.publish_analog();
940 if let Some(board) = &self.board {
942 let now = board.borrow().now();
943 self.net_clock.set(now);
944 if self.ble_attached {
948 let (generation, air) = {
949 let board = board.borrow();
950 (board.ble_generation(), board.ble_air(self.board_index))
951 };
952 if generation != self.ble_seen {
953 self.ble_seen = generation;
954 let _ = self.machine.bus.ble_nearby(nearby_list(&air));
955 self.ble_peers = air;
956 }
957 }
958 }
959 self.machine.run(steps)
960 }
961
962 pub fn uart0(&self) -> &[u8] {
963 &self.machine.console.uart0
964 }
965
966 pub fn take_uart0(&mut self) -> Vec<u8> {
967 core::mem::take(&mut self.machine.console.uart0)
968 }
969 }
970
971 fn ap_spec(ap: &litz_net::AccessPoint) -> String {
975 let mut spec = format!("ssid={},channel={}", ap.ssid, ap.channel);
976 if let Some(psk) = &ap.psk {
977 spec.push_str(&format!(",psk={psk}"));
978 }
979 if let Some(bssid) = ap.bssid {
980 spec.push_str(&format!(
981 ",bssid={}",
982 bssid
983 .iter()
984 .map(|b| format!("{b:02x}"))
985 .collect::<Vec<_>>()
986 .join(":")
987 ));
988 }
989 if let Some(epoch) = ap.epoch_s {
990 spec.push_str(&format!(",epoch={epoch}"));
991 }
992 spec
993 }
994
995 fn nearby_list(beacons: &[litz_ble::Beacon]) -> Vec<Nearby> {
998 beacons
999 .iter()
1000 .map(|beacon| Nearby {
1001 addr: beacon.address,
1002 addr_type: beacon.address_type(),
1003 rssi: beacon.rssi,
1004 adv: beacon.adv.clone(),
1005 scan_response: beacon.scan_response.clone(),
1006 gatt: beacon
1007 .gatt
1008 .iter()
1009 .map(|service| esp_soc::ble::peer::GattService {
1010 uuid: service.uuid,
1011 characteristics: service
1012 .characteristics
1013 .iter()
1014 .map(|characteristic| esp_soc::ble::peer::GattCharacteristic {
1015 uuid: characteristic.uuid,
1016 flags: characteristic.flags,
1017 value: characteristic.value.clone(),
1018 })
1019 .collect(),
1020 })
1021 .collect(),
1022 })
1023 .collect()
1024 }
1025
1026 fn nearby_spec(network: &litz_net::NearbyNetwork) -> String {
1027 format!(
1028 "ssid={},channel={},rssi={},secure={}",
1029 network.ssid,
1030 network.channel,
1031 network.rssi,
1032 u8::from(network.secure)
1033 )
1034 }
1035
1036 #[cfg(feature = "esp32c3")]
1038 pub type C3 = EspChip<esp32c3::C3>;
1039
1040 #[cfg(feature = "esp32c3")]
1041 impl EspChip<esp32c3::C3> {
1042 pub fn new(mac: [u8; 6], flash_size: usize) -> Self {
1043 let mut chip = Self::bare(mac, flash_size, c3_bus);
1044 chip.gdb = Some(serve_gdb::<esp32c3::C3>);
1045 chip.guest_call = Some(crate::debug::rv32_call_guest::<esp32c3::C3>);
1046 chip
1047 }
1048 }
1049
1050 #[cfg(feature = "esp32c3")]
1051 fn c3_bus(
1052 mac: [u8; 6],
1053 flash: usize,
1054 board: Option<Rc<RefCell<LitzBoard>>>,
1055 index: u16,
1056 spi_rates: Rc<Cell<[u32; 2]>>,
1057 ) -> esp32c3::bus::SocBus {
1058 const CPU_HZ: u64 = esp32c3::periph::CPU_HZ;
1059 let mut bus = esp32c3::bus::SocBus::new(flash, mac);
1060 if let Some(board) = board {
1061 bus.board = Box::new(LitzModel::new(board, CPU_HZ, index, spi_rates));
1062 bus.attach_board_devices();
1065 }
1066 bus
1067 }
1068
1069 #[cfg(feature = "esp32c6")]
1071 pub type C6 = EspChip<esp32c6::C6>;
1072
1073 #[cfg(feature = "esp32c6")]
1074 impl EspChip<esp32c6::C6> {
1075 pub fn new(mac: [u8; 6], flash_size: usize) -> Self {
1076 let mut chip = Self::bare(mac, flash_size, c6_bus);
1077 chip.gdb = Some(serve_gdb::<esp32c6::C6>);
1078 chip.guest_call = Some(crate::debug::rv32_call_guest::<esp32c6::C6>);
1079 chip
1080 }
1081 }
1082
1083 #[cfg(feature = "esp32c6")]
1084 fn c6_bus(
1085 mac: [u8; 6],
1086 flash: usize,
1087 board: Option<Rc<RefCell<LitzBoard>>>,
1088 index: u16,
1089 spi_rates: Rc<Cell<[u32; 2]>>,
1090 ) -> esp32c6::bus::SocBus {
1091 const CPU_HZ: u64 = esp32c6::periph::CPU_HZ;
1092 let mut bus = esp32c6::bus::SocBus::new(flash, mac);
1093 if let Some(board) = board {
1094 bus.board = Box::new(LitzModel::new(board, CPU_HZ, index, spi_rates));
1095 bus.attach_board_devices();
1096 }
1097 bus
1098 }
1099
1100 #[cfg(feature = "esp32")]
1102 pub type Esp32 = EspChip<esp32::Esp32>;
1103
1104 #[cfg(feature = "esp32")]
1105 impl EspChip<esp32::Esp32> {
1106 pub fn new(mac: [u8; 6], flash_size: usize) -> Self {
1107 let mut chip = Self::bare(mac, flash_size, esp32_bus);
1108 chip.guest_call = Some(crate::debug::XtensaChip::call_guest);
1109 chip.spi_clock = Some(ESP32_SPI_CLOCKS);
1110 chip
1111 }
1112 }
1113
1114 #[cfg(feature = "esp32")]
1115 fn esp32_bus(
1116 mac: [u8; 6],
1117 flash: usize,
1118 board: Option<Rc<RefCell<LitzBoard>>>,
1119 index: u16,
1120 spi_rates: Rc<Cell<[u32; 2]>>,
1121 ) -> esp32::bus::SocBus {
1122 const CPU_HZ: u64 = esp32::periph::CPU_HZ;
1123 let mut bus = esp32::bus::SocBus::new(flash, mac);
1124 if let Some(board) = board {
1125 bus.board = Box::new(LitzModel::new(board, CPU_HZ, index, spi_rates));
1126 bus.attach_board_devices();
1127 }
1128 bus
1129 }
1130
1131 #[cfg(feature = "esp32s3")]
1134 const S3_PSRAM: usize = 2 << 20;
1135
1136 #[cfg(feature = "esp32s3")]
1138 pub type S3 = EspChip<esp32s3::S3>;
1139
1140 #[cfg(feature = "esp32s3")]
1141 impl EspChip<esp32s3::S3> {
1142 pub fn new(mac: [u8; 6], flash_size: usize) -> Self {
1143 let mut chip = Self::bare(mac, flash_size, s3_bus);
1144 chip.guest_call = Some(crate::debug::XtensaChip::call_guest);
1145 chip.spi_clock = Some(S3_SPI_CLOCKS);
1146 chip
1147 }
1148 }
1149
1150 #[cfg(feature = "esp32s3")]
1151 fn s3_bus(
1152 mac: [u8; 6],
1153 flash: usize,
1154 board: Option<Rc<RefCell<LitzBoard>>>,
1155 index: u16,
1156 spi_rates: Rc<Cell<[u32; 2]>>,
1157 ) -> esp32s3::bus::SocBus {
1158 const CPU_HZ: u64 = esp32s3::periph::CPU_HZ;
1159 let mut bus = esp32s3::bus::SocBus::new(flash, S3_PSRAM, mac);
1160 if let Some(board) = board {
1161 bus.board = Box::new(LitzModel::new(board, CPU_HZ, index, spi_rates));
1162 bus.attach_board_devices();
1163 }
1164 bus
1165 }
1166
1167 #[cfg(feature = "esp32p4")]
1170 pub type P4 = EspChip<esp32p4::P4>;
1171
1172 #[cfg(feature = "esp32p4")]
1173 impl EspChip<esp32p4::P4> {
1174 pub fn new(mac: [u8; 6], flash_size: usize) -> Self {
1175 let mut chip = Self::bare(mac, flash_size, p4_bus);
1176 chip.gdb = Some(serve_gdb::<esp32p4::P4>);
1177 chip.guest_call = Some(crate::debug::rv32_call_guest::<esp32p4::P4>);
1178 chip
1179 }
1180 }
1181
1182 #[cfg(feature = "esp32p4")]
1183 fn p4_bus(
1184 mac: [u8; 6],
1185 flash: usize,
1186 board: Option<Rc<RefCell<LitzBoard>>>,
1187 index: u16,
1188 spi_rates: Rc<Cell<[u32; 2]>>,
1189 ) -> esp32p4::bus::SocBus {
1190 const CPU_HZ: u64 = esp32p4::periph::CPU_HZ;
1191 let wafer = <esp32p4::RevLt3 as esp32p4::Revision>::WAFER;
1192 let mut bus = esp32p4::bus::SocBus::new(flash, mac, wafer);
1193 if let Some(board) = board {
1194 bus.board = Box::new(LitzModel::new(board, CPU_HZ, index, spi_rates));
1195 bus.attach_board_devices();
1196 }
1197 bus
1198 }
1199
1200 #[cfg(feature = "esp32s31")]
1202 pub type S31 = EspChip<esp32s31::S31>;
1203
1204 #[cfg(feature = "esp32s31")]
1205 impl EspChip<esp32s31::S31> {
1206 pub fn new(mac: [u8; 6], flash_size: usize) -> Self {
1207 let mut chip = Self::bare(mac, flash_size, s31_bus);
1208 chip.gdb = Some(serve_gdb::<esp32s31::S31>);
1209 chip.guest_call = Some(crate::debug::rv32_call_guest::<esp32s31::S31>);
1210 chip
1211 }
1212 }
1213
1214 #[cfg(feature = "esp32s31")]
1215 fn s31_bus(
1216 mac: [u8; 6],
1217 flash: usize,
1218 board: Option<Rc<RefCell<LitzBoard>>>,
1219 index: u16,
1220 spi_rates: Rc<Cell<[u32; 2]>>,
1221 ) -> esp32s31::SocBus {
1222 const CPU_HZ: u64 = esp32s31::periph::CPU_HZ;
1223 let mut bus = esp32s31::SocBus::new(flash, mac);
1224 if let Some(board) = board {
1225 bus.board = Box::new(LitzModel::new(board, CPU_HZ, index, spi_rates));
1226 bus.attach_board_devices();
1227 }
1228 bus
1229 }
1230
1231 struct BoardI2cDevice {
1238 board: Rc<RefCell<LitzBoard>>,
1239 board_index: u16,
1242 controller: u8,
1243 address: u8,
1244 written: Vec<u8>,
1248 received: Vec<u8>,
1249 reading: bool,
1250 open: bool,
1251 last_at: u64,
1255 started_at: u64,
1259 }
1260
1261 impl EspI2cDevice for BoardI2cDevice {
1262 fn address(&self, _configured: u8) -> u8 {
1263 self.address
1264 }
1265
1266 fn start(&mut self, read: bool) -> bool {
1267 if !self.open {
1268 self.written.clear();
1269 self.received.clear();
1270 self.open = true;
1271 self.started_at = self.board.borrow().now();
1272 }
1273 self.reading = read;
1274 let mut board = self.board.borrow_mut();
1275 let Some(bus) = board
1276 .buses_mut()
1277 .i2c
1278 .get_mut(&(self.board_index, self.controller))
1279 else {
1280 return false;
1281 };
1282 let Some(device) = bus.device_mut(self.address) else {
1283 return false;
1284 };
1285 device.connect(read);
1286 true
1287 }
1288
1289 fn write(&mut self, byte: u8) -> bool {
1290 if !self.reading {
1291 self.written.push(byte);
1292 }
1293 let mut board = self.board.borrow_mut();
1294 let Some(bus) = board
1295 .buses_mut()
1296 .i2c
1297 .get_mut(&(self.board_index, self.controller))
1298 else {
1299 return false;
1300 };
1301 let Some(device) = bus.device_mut(self.address) else {
1302 return false;
1303 };
1304 device.write(byte)
1305 }
1306
1307 fn read(&mut self) -> u8 {
1308 let byte = {
1309 let mut board = self.board.borrow_mut();
1310 let Some(bus) = board
1311 .buses_mut()
1312 .i2c
1313 .get_mut(&(self.board_index, self.controller))
1314 else {
1315 return 0xff;
1316 };
1317 let Some(device) = bus.device_mut(self.address) else {
1318 return 0xff;
1319 };
1320 device.read()
1321 };
1322 self.received.push(byte);
1323 byte
1324 }
1325
1326 fn stop(&mut self) {
1327 {
1328 let mut board = self.board.borrow_mut();
1329 let Some(bus) = board
1330 .buses_mut()
1331 .i2c
1332 .get_mut(&(self.board_index, self.controller))
1333 else {
1334 return;
1335 };
1336 if let Some(device) = bus.device_mut(self.address) {
1337 device.stop();
1338 }
1339 }
1340 if self.open {
1341 let mut board = self.board.borrow_mut();
1342 let end = board.now();
1343 let at = self.started_at.max(self.last_at);
1344 let phases = 1
1345 + self.written.len()
1346 + if self.received.is_empty() {
1347 0
1348 } else {
1349 1 + self.received.len()
1350 };
1351 let elapsed = end.saturating_sub(self.started_at);
1356 let hz = if elapsed > 0 {
1357 (phases as u128 * 9 * 1_000_000_000 / u128::from(elapsed))
1358 .clamp(1_000, 5_000_000) as u32
1359 } else {
1360 board.i2c_hz(self.board_index, self.controller)
1361 };
1362 board.set_i2c_hz(self.board_index, self.controller, hz);
1363 board.observe_i2c(
1364 self.board_index,
1365 self.controller,
1366 self.address,
1367 &self.written,
1368 &self.received,
1369 at,
1370 );
1371 let period = 1_000_000_000 / u64::from(hz);
1372 self.last_at = (at + phases as u64 * 9 * period).max(end);
1373 }
1374 self.open = false;
1375 self.reading = false;
1376 }
1377 }
1378
1379 #[derive(Clone, Copy)]
1386 struct SpiClockSpec {
1387 ports: [(u32, u32, u32); 2],
1389 }
1390
1391 #[cfg(feature = "esp32")]
1392 const ESP32_SPI_CLOCKS: SpiClockSpec = SpiClockSpec {
1393 ports: [(0x3ff6_4018, 18, 0x1fff), (0x3ff6_5018, 18, 0x1fff)],
1394 };
1395
1396 #[cfg(feature = "esp32s3")]
1397 const S3_SPI_CLOCKS: SpiClockSpec = SpiClockSpec {
1398 ports: [(0x6002_400c, 18, 0xf), (0x6002_500c, 18, 0xf)],
1399 };
1400
1401 struct SpiClockObserver {
1408 rates: Rc<Cell<[u32; 2]>>,
1409 spec: SpiClockSpec,
1410 }
1411
1412 impl<S: Soc> esp_soc::Observer<S> for SpiClockObserver {
1413 fn name(&self) -> &'static str {
1414 "litz-spi-clock"
1415 }
1416
1417 fn wants(&self) -> esp_soc::Wants {
1418 esp_soc::Wants::MMIO
1419 }
1420
1421 fn on_mmio(&mut self, _cx: &esp_soc::Ctx, _pc: u32, addr: u32, value: u32, write: bool) {
1422 if !write {
1423 return;
1424 }
1425 let Some(slot) = self.spec.ports.iter().position(|&(reg, ..)| reg == addr) else {
1426 return;
1427 };
1428 let (_, shift, mask) = self.spec.ports[slot];
1429 let divider = if value & (1 << 31) != 0 {
1432 1
1433 } else {
1434 (((value >> shift) & mask) + 1) * (((value >> 12) & 0x3f) + 1)
1435 };
1436 let mut rates = self.rates.get();
1437 rates[slot] = (esp_periph::APB_HZ / u64::from(divider)) as u32;
1438 self.rates.set(rates);
1439 }
1440 }
1441
1442 struct LitzModel {
1448 board: Rc<RefCell<LitzBoard>>,
1449 index: u16,
1451 enabled: u64,
1452 output: u64,
1453 cycle: u64,
1454 releases: Vec<u8>,
1455 cpu_hz: u64,
1458 uart_routes: BTreeMap<u8, (u8, u32)>,
1462 spi_rates: Rc<Cell<[u32; 2]>>,
1465 }
1466
1467 impl LitzModel {
1468 fn new(
1469 board: Rc<RefCell<LitzBoard>>,
1470 cpu_hz: u64,
1471 index: u16,
1472 spi_rates: Rc<Cell<[u32; 2]>>,
1473 ) -> Self {
1474 Self {
1475 board,
1476 index,
1477 enabled: 0,
1478 output: 0,
1479 cycle: 0,
1480 releases: Vec::new(),
1481 cpu_hz,
1482 uart_routes: BTreeMap::new(),
1483 spi_rates,
1484 }
1485 }
1486
1487 fn spi_rate(&self, host: u8) -> Option<u32> {
1489 let slot = usize::from(host.checked_sub(2)?);
1490 let hz = *self.spi_rates.get().get(slot)?;
1491 (hz > 0).then_some(hz)
1492 }
1493
1494 fn ns(&self, cycle: u64) -> u64 {
1495 (u128::from(cycle) * 1_000_000_000 / u128::from(self.cpu_hz)) as u64
1496 }
1497
1498 fn cycles_for(&self, ns: u64) -> u64 {
1501 let cycles = u128::from(ns) * u128::from(self.cpu_hz);
1502 (cycles.div_ceil(1_000_000_000)) as u64
1503 }
1504 }
1505
1506 fn expand_monochrome(bytes: &[u8], width: u32, height: u32) -> Vec<u16> {
1509 let mut pixels = vec![0u16; (width * height) as usize];
1510 for page in 0..height.div_ceil(8) {
1511 for column in 0..width {
1512 let Some(byte) = bytes.get((page * width + column) as usize) else {
1513 continue;
1514 };
1515 for bit in 0..8u32 {
1516 let y = page * 8 + bit;
1517 if y >= height {
1518 break;
1519 }
1520 if byte & (1 << bit) != 0 {
1521 pixels[(y * width + column) as usize] = 0xffff;
1522 }
1523 }
1524 }
1525 }
1526 pixels
1527 }
1528
1529 fn board_can_frame(frame: &esp_soc::board::CanFrame) -> litz_board::bus::CanFrame {
1532 let mut data = [0u8; litz_board::bus::CAN_MAX_DATA];
1534 let len = usize::from(frame.len).min(frame.data.len());
1535 data[..len].copy_from_slice(&frame.data[..len]);
1536 litz_board::bus::CanFrame {
1537 id: frame.id,
1538 extended: frame.extended,
1539 rtr: frame.rtr,
1540 len: frame.len,
1541 data,
1542 kind: if frame.rtr {
1543 litz_board::bus::CanFrameKind::Remote
1544 } else {
1545 litz_board::bus::CanFrameKind::Classic
1546 },
1547 }
1548 }
1549
1550 impl BoardModel for LitzModel {
1551 fn name(&self) -> &'static str {
1552 "litz"
1553 }
1554
1555 fn gpio_output_at(
1556 &mut self,
1557 cycle: u64,
1558 changes: &[(u8, bool)],
1559 enabled: u64,
1560 output: u64,
1561 ) {
1562 self.cycle = self.cycle.max(cycle);
1566 let now = self.ns(self.cycle);
1567 if std::env::var("LITZ_TRACE_DEBUG").is_ok() {
1568 eprintln!("DBG cycle={} now={}", self.cycle, now);
1569 }
1570 let mut mask = (enabled ^ self.enabled) | (output ^ self.output);
1573 for &(pin, _) in changes {
1574 mask |= 1u64 << pin;
1575 }
1576 let mut board = self.board.borrow_mut();
1577 while mask != 0 {
1578 let pin = mask.trailing_zeros() as u8;
1579 mask &= mask - 1;
1580 let bit = 1u64 << pin;
1581 let drive = if enabled & bit != 0 {
1582 if output & bit != 0 {
1583 Drive::strong(Level::High)
1584 } else {
1585 Drive::strong(Level::Low)
1586 }
1587 } else {
1588 Drive::HIGH_Z
1589 };
1590 board.set_chip_output_on(self.index, pin, drive, now);
1591 }
1592 self.enabled = enabled;
1593 self.output = output;
1594 }
1595
1596 fn display(&self) -> Option<(u32, u32, Vec<u16>, u64)> {
1601 let board = self.board.borrow();
1602 let buses = board.buses();
1603 for (&(owner, _), i2c) in &buses.i2c {
1604 if owner != self.index {
1605 continue;
1606 }
1607 for address in i2c.addresses() {
1608 if let Some(oled) = i2c.device_as::<litz_board::Ssd1306>(address) {
1609 let (bytes, width, height) = oled.framebuffer();
1610 return Some((
1611 width,
1612 height,
1613 expand_monochrome(bytes, width, height),
1614 oled.frame_version(),
1615 ));
1616 }
1617 }
1618 }
1619 for (&(owner, _), spi) in &buses.spi {
1620 if owner != self.index {
1621 continue;
1622 }
1623 for select in spi.chip_selects() {
1624 if let Some(tft) = spi.device_as::<litz_board::Ili9341>(select) {
1625 let (pixels, width, height) = tft.framebuffer();
1626 return Some((width, height, pixels.to_vec(), tft.frame_version()));
1627 }
1628 }
1629 }
1630 None
1631 }
1632
1633 fn touch(&mut self, x: u16, y: u16, down: bool) {
1637 let _ = self.board.borrow_mut().touch_panel(x, y, down);
1638 }
1639
1640 fn display_version(&self) -> u64 {
1641 let board = self.board.borrow();
1642 let buses = board.buses();
1643 for (&(owner, _), i2c) in &buses.i2c {
1644 if owner != self.index {
1645 continue;
1646 }
1647 for address in i2c.addresses() {
1648 if let Some(oled) = i2c.device_as::<litz_board::Ssd1306>(address) {
1649 return oled.frame_version();
1650 }
1651 }
1652 }
1653 for (&(owner, _), spi) in &buses.spi {
1654 if owner != self.index {
1655 continue;
1656 }
1657 for select in spi.chip_selects() {
1658 if let Some(tft) = spi.device_as::<litz_board::Ili9341>(select) {
1659 return tft.frame_version();
1660 }
1661 }
1662 }
1663 0
1664 }
1665
1666 fn advance_to(&mut self, cycle: u64) {
1667 self.cycle = cycle;
1668 let now = self.ns(cycle);
1673 self.board.borrow_mut().advance_to(now);
1674 }
1675
1676 fn next_deadline(&self) -> Option<u64> {
1677 let board = self.board.borrow();
1680 let now = board.has_pending_inputs_on(self.index).then_some(0);
1681 let event = board.next_event().map(|at| self.cycles_for(at));
1682 match (now, event) {
1683 (Some(a), Some(b)) => Some(a.min(b)),
1684 (a, b) => a.or(b),
1685 }
1686 }
1687
1688 fn take_edges(&mut self) -> Vec<BoardEdge> {
1689 let cycle = self.cycle;
1690 let drained = self.board.borrow_mut().take_chip_inputs_on(self.index);
1691 let mut levels: BTreeMap<u8, Level> = BTreeMap::new();
1697 for (pin, level) in drained {
1698 levels.insert(pin, level);
1699 }
1700 let mut edges = Vec::new();
1701 for (pin, level) in levels {
1702 match level {
1703 Level::High => edges.push(BoardEdge {
1704 cycle,
1705 pin,
1706 level: true,
1707 }),
1708 Level::Low => edges.push(BoardEdge {
1709 cycle,
1710 pin,
1711 level: false,
1712 }),
1713 Level::HighZ => self.releases.push(pin),
1714 }
1715 }
1716 edges
1717 }
1718
1719 fn released_inputs(&mut self) -> Vec<u8> {
1720 core::mem::take(&mut self.releases)
1721 }
1722
1723 fn input_levels(&self) -> Vec<(u8, bool)> {
1724 self.board
1725 .borrow()
1726 .input_levels_on(self.index)
1727 .into_iter()
1728 .filter_map(|(pin, level)| match level {
1729 Level::High => Some((pin, true)),
1730 Level::Low => Some((pin, false)),
1731 Level::HighZ => None,
1732 })
1733 .collect()
1734 }
1735
1736 fn named_pin(&self, name: &str) -> Option<u8> {
1737 let board = self.board.borrow();
1738 let (index, pin) = board.named_pin_on(name)?;
1739 (index == self.index).then_some(pin)
1740 }
1741
1742 fn i2c_devices(&mut self) -> Vec<(u8, u8, Box<dyn EspI2cDevice>)> {
1747 let board = self.board.borrow();
1748 let mut devices: Vec<(u8, u8)> = Vec::new();
1749 for (&(owner, controller), bus) in &board.buses().i2c {
1750 if owner != self.index {
1751 continue;
1752 }
1753 for address in bus.addresses() {
1754 devices.push((controller, address));
1755 }
1756 }
1757 drop(board);
1758 devices
1759 .into_iter()
1760 .map(|(controller, address)| {
1761 let device: Box<dyn EspI2cDevice> = Box::new(BoardI2cDevice {
1762 board: Rc::clone(&self.board),
1763 board_index: self.index,
1764 controller,
1765 address,
1766 written: Vec::new(),
1767 received: Vec::new(),
1768 reading: false,
1769 open: false,
1770 last_at: 0,
1771 started_at: 0,
1772 });
1773 (controller, address, device)
1774 })
1775 .collect()
1776 }
1777
1778 fn uses_spi_pins(&self) -> bool {
1779 self.board
1780 .borrow()
1781 .buses()
1782 .spi
1783 .keys()
1784 .any(|&(owner, _)| owner == self.index)
1785 }
1786
1787 fn spi_transfer(&mut self, host: u8, tx: &[u8], rx_len: usize) -> Vec<u8> {
1792 let rate = self.spi_rate(host);
1793 let mut board = self.board.borrow_mut();
1794 let selected = board
1795 .buses()
1796 .spi_sole(self.index, host)
1797 .or_else(|| board.buses().spi_only_device(self.index));
1798 match selected {
1799 Some((controller, chip_select)) => {
1800 if let Some(hz) = rate {
1803 board.set_spi_hz(self.index, controller, hz);
1804 }
1805 board.spi_transfer(self.index, controller, chip_select, tx, rx_len)
1806 }
1807 None => vec![0xff; rx_len],
1808 }
1809 }
1810
1811 fn spi_transfer_pins(
1814 &mut self,
1815 host: u8,
1816 pins: SpiPins,
1817 tx: &[u8],
1818 rx_len: usize,
1819 ) -> Vec<u8> {
1820 let rate = self.spi_rate(host);
1821 let mut board = self.board.borrow_mut();
1822 match board.buses().spi_selected(self.index, pins.cs) {
1823 Some((controller, chip_select)) => {
1824 if let Some(hz) = rate {
1825 board.set_spi_hz(self.index, controller, hz);
1826 }
1827 board.spi_transfer(self.index, controller, chip_select, tx, rx_len)
1828 }
1829 None => vec![0xff; rx_len],
1830 }
1831 }
1832
1833 fn uses_uart_pins(&self) -> bool {
1834 let board = self.board.borrow();
1835 if board
1836 .buses()
1837 .uart
1838 .keys()
1839 .any(|&(owner, _)| owner == self.index)
1840 {
1841 return true;
1842 }
1843 board.flat().has_chip_to_chip_wire(self.index)
1846 }
1847
1848 fn uart_tx(&mut self, cycle: u64, route: UartRoute, byte: u8) {
1851 let now = self.ns(cycle);
1852 let port = route.port as u8;
1853 let baud = route
1854 .baud
1855 .unwrap_or(litz_board::runtime::OBSERVED_UART_BAUD);
1856 let mut board = self.board.borrow_mut();
1857 board.set_uart_baud(self.index, port, baud);
1858 board.set_uart_pins(self.index, port, route.tx_pins, route.rx_pin);
1860 board.uart_receive(self.index, port, now, &[byte]);
1861 drop(board);
1862 if let Some(pin) = route.rx_pin {
1863 self.uart_routes
1864 .insert(port, (pin, route.baud.unwrap_or(115_200)));
1865 }
1866 }
1867
1868 fn uart_rx(&mut self, cycle: u64) -> Vec<UartInput> {
1873 let now = self.ns(cycle);
1874 let mut board = self.board.borrow_mut();
1875 for (&port, &(_, baud)) in &self.uart_routes {
1876 board.set_uart_baud(self.index, port, baud);
1877 }
1878 let mut ports: BTreeMap<u8, Option<(u8, u32)>> = self
1881 .uart_routes
1882 .iter()
1883 .map(|(&port, &route)| (port, Some(route)))
1884 .collect();
1885 for &(owner, port) in board.buses().uart.keys() {
1886 if owner != self.index {
1887 continue;
1888 }
1889 ports.entry(port).or_insert_with(|| {
1890 board
1891 .flat()
1892 .buses
1893 .uart
1894 .get(&(self.index, port))
1895 .map(|bus| (bus.chip_rx, 115_200))
1896 });
1897 }
1898 let mut inputs = Vec::new();
1899 for (port, route) in ports {
1900 let Some((pin, baud)) = route else { continue };
1901 let data = board.uart_poll(self.index, port, now);
1902 if !data.is_empty() {
1903 inputs.push(UartInput::new(pin, baud, data));
1904 }
1905 }
1906 inputs
1907 }
1908
1909 fn can_tx(&mut self, _host: u8, frame: &[u8]) {
1912 let Some(frame) = esp_soc::board::CanFrame::decode(frame) else {
1913 return;
1914 };
1915 let mut board = self.board.borrow_mut();
1916 let can = board.buses_mut().can_mut();
1917 can.attach(self.index);
1918 let _ = can.transmit(self.index, board_can_frame(&frame));
1919 }
1920
1921 fn can_take(&mut self, _host: u8) -> Option<Vec<u8>> {
1925 let mut board = self.board.borrow_mut();
1926 let can = board.buses_mut().can_mut();
1927 can.attach(self.index);
1928 let frame = can.take(self.index)?;
1929 let mut data = [0u8; esp_soc::board::CAN_MAX_DATA];
1931 let len = usize::from(frame.len).min(data.len());
1932 data[..len].copy_from_slice(&frame.data[..len]);
1933 Some(
1934 esp_soc::board::CanFrame {
1935 id: frame.id,
1936 extended: frame.extended,
1937 rtr: frame.rtr || frame.kind == litz_board::bus::CanFrameKind::Remote,
1938 len: frame.len,
1939 data,
1940 }
1941 .encode()
1942 .to_vec(),
1943 )
1944 }
1945 }
1946
1947 impl<S: Soc> litz_board::Chip for EspChip<S> {
1950 fn info(&self) -> litz_board::ChipInfo {
1951 litz_board::ChipInfo {
1952 name: S::NAME.into(),
1953 cpu_hz: S::CPU_HZ,
1954 flash: litz_board::FlashLayout {
1955 size: self.flash as u64,
1956 bootloader: S::BOOTLOADER_OFFSET as u64,
1957 partition_table: 0x8000,
1958 app: 0x1_0000,
1959 },
1960 }
1961 }
1962
1963 fn load_image(
1964 &mut self,
1965 kind: litz_board::ImageKind,
1966 offset: u64,
1967 bytes: &[u8],
1968 ) -> Result<(), String> {
1969 match kind {
1970 litz_board::ImageKind::Rom => self.load_rom(bytes),
1971 litz_board::ImageKind::Bootloader => {
1972 self.bootloader_loaded = true;
1973 self.write_flash(offset as usize, bytes)
1974 }
1975 _ => self.write_flash(offset as usize, bytes),
1976 }
1977 }
1978
1979 fn set_psram_size(&mut self, bytes: usize) -> Result<(), String> {
1980 EspChip::set_psram_size(self, bytes)
1981 }
1982
1983 fn flash_image(&self) -> Option<Vec<u8>> {
1984 EspChip::flash_image(self).map(<[u8]>::to_vec)
1985 }
1986
1987 fn boot(&mut self) -> Result<u32, String> {
1988 self.powered = self.board_power();
1989 if !self.powered {
1990 return Ok(0);
1993 }
1994 if self.bootloader_loaded {
1995 return Ok(0);
1998 }
1999 let app = self.info().flash.app as usize;
2000 self.boot_app(app)
2001 }
2002
2003 fn schedule(&mut self, inputs: Vec<litz_board::Input>) -> Result<(), String> {
2004 let mut text = String::new();
2005 for input in inputs {
2006 match input {
2007 litz_board::Input::Gpio { at_ns, pin, level } => {
2008 let seconds = at_ns as f64 / 1e9;
2009 let bit = u8::from(level == Level::High);
2010 text.push_str(&format!("{seconds:.6} gpio {pin} {bit}\n"));
2011 }
2012 litz_board::Input::Uart { at_ns, bytes } => {
2013 let seconds = at_ns as f64 / 1e9;
2014 let text_in = String::from_utf8_lossy(&bytes);
2015 text.push_str(&format!(
2017 "{seconds:.6} uart0 {}\n",
2018 text_in.trim_end_matches('\n')
2019 ));
2020 }
2021 }
2022 }
2023 if text.is_empty() {
2024 Ok(())
2025 } else {
2026 self.load_script(&text)
2027 }
2028 }
2029
2030 fn run(&mut self, budget_cycles: u64) -> litz_board::RunResult {
2031 if !EspChip::board_power(self) {
2032 if self.powered {
2033 self.power_off();
2034 }
2035 let cycles = u128::from(budget_cycles) * 1_000_000_000;
2038 let cpu_hz = u128::from(litz_board::Chip::info(self).cpu_hz.max(1));
2039 self.off_ns = self.off_ns.saturating_add((cycles / cpu_hz) as u64);
2040 return litz_board::RunResult {
2041 cycles: budget_cycles,
2042 stop: litz_board::Stop::Idle,
2043 };
2044 }
2045 if !self.powered {
2046 if self.boot_after_power().is_err() {
2048 return litz_board::RunResult {
2049 cycles: 0,
2050 stop: litz_board::Stop::Trap,
2051 };
2052 }
2053 self.powered = true;
2054 }
2055 let stop = match EspChip::run(self, budget_cycles) {
2056 esp_soc::Stop::MaxInsns => litz_board::Stop::Budget,
2057 esp_soc::Stop::Halted => litz_board::Stop::Halted,
2058 esp_soc::Stop::SwReset => litz_board::Stop::Reset,
2059 esp_soc::Stop::Breakpoint(pc) => litz_board::Stop::Breakpoint(pc),
2060 _ => litz_board::Stop::Idle,
2061 };
2062 litz_board::RunResult {
2063 cycles: budget_cycles,
2064 stop,
2065 }
2066 }
2067
2068 fn seconds(&self) -> f64 {
2069 EspChip::seconds(self)
2070 }
2071
2072 fn write_console(&mut self, bytes: &[u8]) {
2073 self.write_serial(bytes);
2077 }
2078
2079 fn take_console(&mut self) -> Vec<u8> {
2080 let mut bytes = self.take_uart0();
2081 let usb = core::mem::take(&mut self.machine.console.usb);
2087 if usb != bytes {
2088 bytes.extend(usb);
2089 }
2090 bytes
2091 }
2092
2093 fn state(&self, part: &str) -> Option<PartState> {
2094 EspChip::state(self, part)
2095 }
2096
2097 fn press(&mut self, part: &str, pressed: bool) -> bool {
2098 EspChip::press(self, part, pressed)
2099 }
2100
2101 fn set_control(&mut self, part: &str, value: u16) -> bool {
2102 EspChip::set_control(self, part, value)
2103 }
2104
2105 fn set_named_control(&mut self, part: &str, name: &str, value: &str) -> bool {
2106 EspChip::set_named_control(self, part, name, value)
2107 }
2108
2109 fn part_pin_level(&self, part: &str, pin: Option<&str>) -> Option<Level> {
2110 EspChip::part_pin_level(self, part, pin)
2111 }
2112
2113 fn gpio_level(&self, gpio: u8) -> Option<Level> {
2114 EspChip::gpio_level(self, gpio)
2115 }
2116
2117 fn conflicts(&self) -> Vec<Conflict> {
2118 EspChip::conflicts(self)
2119 }
2120
2121 fn start_trace(&mut self) {
2122 if let Some(board) = self.board.as_ref() {
2123 board.borrow_mut().start_trace();
2124 }
2125 }
2126
2127 fn vcd(&self) -> String {
2128 self.board
2129 .as_ref()
2130 .map(|board| board.borrow().vcd())
2131 .unwrap_or_default()
2132 }
2133
2134 fn break_at(&mut self, pc: u32) {
2135 EspChip::break_at(self, pc);
2136 }
2137
2138 fn registers(&self) -> String {
2139 self.machine.dump_regs()
2140 }
2141
2142 fn report(&mut self) -> Vec<String> {
2143 EspChip::reports(self)
2144 }
2145
2146 fn enable_coverage(&mut self) {
2147 EspChip::enable_coverage(self);
2148 }
2149
2150 fn display(&mut self) -> Option<(u32, u32, Vec<u16>, u64)> {
2151 self.machine.bus.board().display()
2152 }
2153
2154 fn display_version(&mut self) -> u64 {
2155 self.machine.bus.board().display_version()
2156 }
2157
2158 fn save_display(&mut self, path: &std::path::Path) -> Result<(), String> {
2159 crate::screenshot::capture(self, path)
2160 }
2161
2162 fn save_part_display(&mut self, part: &str, path: &std::path::Path) -> Result<(), String> {
2163 let Some(board) = &self.board else {
2164 return Err("this chip is not attached to a board".into());
2165 };
2166 let image = board
2167 .borrow()
2168 .part_framebuffer(part)
2169 .ok_or_else(|| format!("part {part:?} is not a display with a framebuffer"))?;
2170 std::fs::write(path, image.to_png()).map_err(|e| format!("{}: {e}", path.display()))
2171 }
2172
2173 fn sample_heap(&mut self) -> Result<u32, String> {
2174 EspChip::sample_heap(self)
2175 }
2176
2177 fn touch(&mut self, x: u16, y: u16, down: bool) -> Result<(), String> {
2178 let Some(board) = &self.board else {
2179 return Err("this chip is not attached to a board".into());
2180 };
2181 board.borrow_mut().touch_panel(x, y, down)
2182 }
2183
2184 fn start_air_capture(&mut self, path: &std::path::Path) -> Result<(), String> {
2185 EspChip::start_air_capture(self, path)
2186 }
2187
2188 fn start_ethernet_capture(&mut self, path: &std::path::Path) -> Result<(), String> {
2189 EspChip::start_ethernet_capture(self, path)
2190 }
2191
2192 fn attach_host_gateway(&mut self, forwards: &[String]) -> Result<Vec<String>, String> {
2193 #[cfg(not(target_arch = "wasm32"))]
2194 {
2195 if forwards.is_empty() {
2196 EspChip::attach_host_nat(self, false).map(|()| Vec::new())
2197 } else {
2198 EspChip::attach_host_forwards(self, forwards, false)
2199 }
2200 }
2201 #[cfg(target_arch = "wasm32")]
2202 {
2203 let _ = forwards;
2204 Err("the browser build has no host sockets".into())
2205 }
2206 }
2207
2208 fn debug_available(&self) -> bool {
2209 use emu_core::Core;
2210 self.machine_ref()
2211 .cores
2212 .first()
2213 .map(|core| {
2214 let mut names = Vec::new();
2215 core.regs(&mut names);
2216 names.iter().any(|(name, _)| *name == "ra")
2217 && names.iter().any(|(name, _)| *name == "sp")
2218 })
2219 .unwrap_or(false)
2220 }
2221
2222 fn debug_pc(&self) -> Option<u32> {
2223 use emu_core::Core;
2224 self.machine_ref().cores.first().map(|core| core.pc())
2225 }
2226
2227 fn debug_register_file(&self) -> Option<[u32; 33]> {
2228 use emu_core::Core;
2229 let core = self.machine_ref().cores.first()?;
2230 let mut names = Vec::new();
2231 core.regs(&mut names);
2232 if !names.iter().any(|(name, _)| *name == "ra") {
2233 return None;
2234 }
2235 const RV: [&str; 32] = [
2236 "zero", "ra", "sp", "gp", "tp", "t0", "t1", "t2", "s0", "s1", "a0", "a1", "a2",
2237 "a3", "a4", "a5", "a6", "a7", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9",
2238 "s10", "s11", "t3", "t4", "t5", "t6",
2239 ];
2240 let mut file = [0u32; 33];
2241 for (index, want) in RV.iter().enumerate() {
2242 if let Some((_, value)) = names.iter().find(|(name, _)| name == want) {
2243 file[index] = *value;
2244 }
2245 }
2246 file[32] = core.pc();
2247 Some(file)
2248 }
2249
2250 fn debug_read_memory(&mut self, addr: u32, len: usize) -> Vec<u8> {
2251 if len == 0 {
2252 return Vec::new();
2253 }
2254 let start = addr & !3;
2255 let skip = (addr - start) as usize;
2256 let words = (skip + len).div_ceil(4);
2257 let text = self.machine_mut().peek(start, words);
2258 let mut bytes = Vec::with_capacity(words * 4);
2259 for line in text.lines() {
2260 let Some((_, word)) = line.split_once(": ") else {
2261 break;
2262 };
2263 let Ok(word) = u32::from_str_radix(word.trim(), 16) else {
2264 break;
2265 };
2266 bytes.extend_from_slice(&word.to_le_bytes());
2267 }
2268 if bytes.len() < skip {
2269 return Vec::new();
2270 }
2271 let end = (skip + len).min(bytes.len());
2272 bytes[skip..end].to_vec()
2273 }
2274
2275 fn debug_disassemble(&mut self, addr: u32, count: usize) -> String {
2276 self.disassemble(addr, count)
2277 }
2278
2279 fn debug_set_breakpoints(&mut self, pcs: &[u32]) {
2280 self.machine_mut().set_breakpoints(pcs.to_vec());
2281 }
2282
2283 fn debug_step(&mut self) -> Option<litz_board::Stop> {
2284 Some(match self.machine_mut().step_one() {
2285 esp_soc::Stop::MaxInsns => litz_board::Stop::Budget,
2286 esp_soc::Stop::Halted => litz_board::Stop::Halted,
2287 esp_soc::Stop::SwReset => litz_board::Stop::Reset,
2288 esp_soc::Stop::Breakpoint(pc) => litz_board::Stop::Breakpoint(pc),
2289 _ => litz_board::Stop::Idle,
2290 })
2291 }
2292
2293 fn debug(&mut self) -> Option<&mut dyn litz_board::ChipDebug> {
2294 Some(self)
2295 }
2296 }
2297
2298 impl<S: Soc> litz_board::ChipDebug for EspChip<S> {
2299 fn serve(&mut self, port: u16) -> Result<(), String> {
2300 self.gdb_serve(port)
2301 }
2302
2303 fn report(&mut self) -> String {
2304 self.machine.dump_regs()
2305 }
2306 }
2307
2308 #[cfg(all(test, feature = "esp32c3"))]
2309 mod ble_peers {
2310 use super::*;
2311
2312 fn beacon() -> litz_ble::Beacon {
2313 litz_ble::Beacon {
2314 name: Some("late".into()),
2315 services: Vec::new(),
2316 address: [0x04, 0x03, 0x02, 0x01, 0xaa, 0xc4],
2317 rssi: -42,
2318 adv: vec![2, 1, 6, 6, 9, b'l', b'a', b't', b'e'],
2319 scan_response: Vec::new(),
2320 gatt: Vec::new(),
2321 }
2322 }
2323
2324 #[test]
2328 fn a_peer_added_at_runtime_reaches_a_live_scan() {
2329 let mut chip = C3::new([0x24, 0x0a, 0xc4, 0x00, 0x01, 0x10], 4 << 20);
2330 assert_eq!(
2331 chip.add_ble_peer(&beacon()).unwrap_err(),
2332 "BLE is not enabled on this chip"
2333 );
2334 chip.machine_mut().bus.ble.hooks.push(0);
2335 chip.machine_mut().bus.ble.lines.keep();
2336 chip.ble_attached = true;
2337
2338 chip.machine_mut()
2340 .bus
2341 .ble
2342 .session
2343 .send(&[1, 0x0c, 0x20, 2, 1, 0]);
2344 chip.machine_mut().bus.ble.session.drain_log();
2345
2346 chip.add_ble_peer(&beacon())
2347 .expect("the scan accepts the list");
2348 assert_eq!(chip.ble_peers.len(), 1);
2349 let line = chip.ble_log().expect("the controller logged a report");
2350 assert!(line.contains("scan report"), "{line}");
2351 assert!(line.contains("c4:aa:01:02:03:04"), "{line}");
2352 }
2353 }
2354}
2355
2356const PLIC_AND_RV_MAP: [MemoryRegion; 6] = [
2357 MemoryRegion::new("irom", 0x4200_0000, 0x0040_0000),
2358 MemoryRegion::new("drom", 0x3C00_0000, 0x0040_0000),
2359 MemoryRegion::new("dram", 0x3FC8_0000, 0x0004_0000),
2360 MemoryRegion::new("irom-dram", 0x4037_C000, 0x0000_8000),
2361 MemoryRegion::new("peripherals", 0x6000_0000, 0x0010_0000),
2362 MemoryRegion::new("rtc", 0x5000_0000, 0x0001_0000),
2363];