Merge branch 'nto-bringup' into sam.artybio-LED

This commit is contained in:
bunnie 2025-08-07 00:34:11 +08:00 committed by GitHub
commit a70fd8d26b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
25 changed files with 1378 additions and 73 deletions

View file

@ -518,6 +518,10 @@ perform the Xous firmware upgrade. This requires running manual update commands,
- This change now hides the GAM abstraction in most cases. The GAM is used to implement windowing; for lightweight platforms that don't have the screen real estate for windows, the `canvas`/`Gid` abstractions still exist but are ignored, and applications can draw directly to the screen.
- `baosec` target in particular supports no windowing as the screen is 128x128: the UI is purely modal, where every user interaction occupies the entire screen.
- Modify the core message loop to use reply_and_receive_next() API
- Improve message passing time by ~15% in tight scalar message benchmark
- `activate_process_thread` now takes a `lazy_arg` which is evaluated after the thread is activated. When `lazy_arg` is set, it can save a context switch, as it allows pre-switch context setup to be deferred until the final context switch to activate the target process.
- Vexii SoC target support. This is primarily for testing the Vexii core for future implementations.
- Baremetal targets. As the name implies, these are baremetal targets, free of Xous OS. The primary purpose of baremetal targets are to streamline low-level driver development. However, they can also be useful as templates for very small embedded projects that don't require all the features of Xous.
## Roadmap
- Lots of testing and bug fixes

45
apps/vault/README.md Normal file
View file

@ -0,0 +1,45 @@
# Vault App
The Vault app can manage U2F/FIDO2, TOTP, and conventional passwords, all from a single UX, and in a plausibly deniable manner.
When the Vault app is launched, you can plug your Precursor into a host PC, and use it as a U2F or FIDO2 authentication token. Unlike a typical security key, you can see a description of what you’re authenticating:
![FIDO credential example](../../docs/images/vault/fido-credential.jpg)
You can also see the list of U2F credentials that are stored inside your device:
![FIDO list](../../docs/images/vault/fido-list.jpg)
You can use the `F1`-`F3` hot keys below the screen to switch between Vault modes. `F2` brings you to the TOTP mode:
![TOTP list](../../docs/images/vault/totp-list.jpg)
And `F3` brings you to the classic password manager:
![Password list](../../docs/images/vault/password-list.jpg)
In each of these modes, you can select and edit the credentials on the device, like so:
![Password edit example](../../docs/images/vault/password-example2.jpg)
Here, you can see how each password record has a descriptive name (“demo password”), the username (“bunnie”), the password itself, and a note field where I can keep track of any special characteristics for the password (“this line is for notes”).
The password manager can also help you create a strong password with the help of Precursor’s built-in TRNG. It has basic configuration options for things like the length of the password, and if the password should include symbols, numbers, and/or upper case characters.
![Vault menu](../../docs/images/vault/menu-example.jpg)
The Vault also features “Autotype”: if your device is connected to your host via USB, it will appear as a keyboard when the Vault app is active. Precursor can then send virtual key-strokes to automatically fill in a password or OTP with the push of a button. This way, you never actually have to see or type any passwords yourself; so long as you have your Precursor plugged into the host machine, your passwords are just a couple button presses away.
You can also see from this menu that “secret bases” (bases being the plural of basis) are explicitly supported by the Vault app, thanks to the [Plausibly Deniable DataBase](https://www.bunniestudios.com/blog/?p=6307) (PDDB) built into Xous. The structure of the PDDB is a subject for a whole other post, but in a nutshell secret bases are database overlays that can hide credentials in a plausibly deniable fashion. By keeping sensitive credentials in a secret basis, you can safely share only the credentials that are currently visible with friends, colleagues, or even law enforcement. The locked credentials are untraceable: even if a full forensic dump is made of the device’s contents without your permission, it is hard to prove the existence or non-existence of secrets beyond the ones you have chosen to reveal to the party in possession of your device. To this end, the "Unlock secret Basis" menu item is _always_ present, even if there are no secret bases on the device.
## Backups
Of course, a cautious user would hesitate to put all their passwords into a single device without backups. For those users: Good news! In this release, we also have a solution for backups. There is now a new main menu item titled “Prepare for Backup…” which extracts your root keys, encrypts them, and stages them with the PDDB for readout by a host via USB. You can read about how to do [backups and restores at our wiki](https://github.com/betrusted-io/betrusted-wiki/wiki/Backups).
The backup key is the 256-bit AES key encrypts your FPGA, and transitively your root key store. When you perform a backup, the backup key is displayed on your screen as a BIP-39 wordlist:
![BIP39-backup](../../docs/images/vault/bip39-example.jpg)
We also have created a BIP-39 wordlist input helper, so you don’t actually have to type every word in full – the helper will offer autocomplete suggestions.
As most developers have not set their backup key, the key by default would show as “abandon abandon abandon … art” (That is, 256 zeroes in BIP-39 format), but users who wish to set a strong backup key can currently follow [this guide](https://github.com/betrusted-io/betrusted-wiki/wiki/FAQ:-FPGA-AES-Encryption-Key-(eFuse-BBRAM)#how-do-i-externally-provision-my-device) to “burn” their BBRAM FPGA key with the help of a Raspberry Pi. We plan to unlock fully self-contained burning of the eFuse key in the next release or two. However, we’d like to put this flow through more testing first, because once the eFuse key is burned, you can’t undo it, and the device is permanently bricked if something goes wrong!

View file

@ -24,7 +24,14 @@ artybio = [
"xous-bio-bdma/baremetal",
]
artyvexii = ["utralib/artyvexii", "linked_list_allocator"]
cramium-soc = ["utralib/cramium-soc"]
v0p9 = []
cramium-soc = [
"utralib/cramium-soc",
"linked_list_allocator",
"cramium-hal/loader-baosec",
"cramium-api",
"v0p9",
]
verilator-only = []
default = ["artyvexii"]

View file

@ -6,6 +6,7 @@ use crate::platform;
// Note: inline constants are not yet stable in Rust: https://github.com/rust-lang/rust/pull/104087
#[link_section = ".text.init"]
#[export_name = "_start"]
#[cfg(not(feature = "cramium-soc"))]
pub extern "C" fn _start() {
unsafe {
#[rustfmt::skip]
@ -28,6 +29,82 @@ pub extern "C" fn _start() {
}
}
#[link_section = ".text.init"]
#[export_name = "_start"]
#[cfg(feature = "cramium-soc")]
pub extern "C" fn _start() {
unsafe {
#[rustfmt::skip]
asm! (
// Place the stack pointer at the end of RAM
"mv sp, {ram_top}",
// subtract four from sp to make room for a DMA "gutter"
"addi sp, sp, -4",
// twiddle duart
"li t0, 0x40042000",
// setup etuc
"sw x0, 0x4(t0)", // CR is 0
"li t1, 34", // tuned based on ringosc & oscope. not guaranteed to be precise
"sw t1, 0xc(t0)",
"li t1, 0x1",
"sw t1, 0x4(t0)", // CR is 1
// print 32 instances of 'Z' (0x5A) (provided to measure baud)
"li t2, 32",
"li t1, 0x5A",
"10:",
"sw t1, 0x0(t0)",
"11:",
"lw t3, 0x8(t0)", // check SR
"bne x0, t3, 11b", // wait for 0
"addi t2, t2, -1",
"bne x0, t2, 10b",
/*
// test if ifram is cleared
"li t0, 0x50000000",
"li t1, 0x50040000",
"60:",
"lw t2, 0(t0)",
// if not 0, jump to clearing routine
"bne x0, t2, 30f",
"addi t0, t0, 4",
// loop if we haven't checked all of ifram
"bltu t0, t1, 60b",
// if we got here, all of ifram was 0, continue with boot
"j 50f",
// clear ifram
"30:",
"sw x0, 0(t0)",
"addi t0, t0, 4",
"bltu t0, t1, 30b",
*/
/*
// clear main ram
"li t0, 0x61000000",
"li t1, 0x61200000",
"20:",
"sw x0, 0(t0)",
"addi t0, t0, 4",
"bltu t0, t1, 20b",
".word 0x500f",
*/
"50:",
// Install a machine mode trap handler
"la t0, abort",
"csrw mtvec, t0",
// Start Rust
"j rust_entry",
ram_top = in(reg) (platform::RAM_BASE + platform::RAM_SIZE),
options(noreturn)
);
}
}
#[link_section = ".text.init"]
#[export_name = "abort"]
/// This is only used in debug mode
@ -35,12 +112,23 @@ pub extern "C" fn abort() -> ! {
unsafe {
#[rustfmt::skip]
asm!(
"li t0, 0xf0000000",
"li t1, 0x00f",
"li t2, 0xf00",
"300:", // abort
"sw t1, 0(t0)",
"sw t2, 0(t0)",
"li t0, 0x40042000",
"li t1, 0x75",
"li t2, 1024",
"10:", // abort by printing u (0x75) to duart
"sw t1, 0x0(t0)",
"11:",
"lw t3, 0x8(t0)", // check SR
"bne x0, t3, 11b", // wait for 0
"li t3, 4000",
// add a short delay between characters to help differentiate them on oscope
"12:",
"addi t3, t3, -1",
"bne x0, t3, 12b",
// check how many prints
"addi t2, t2, -1",
"bne x0, t2, 10b",
"300:",
"j 300b",
options(noreturn)
);

View file

@ -13,6 +13,7 @@ use core::cell::RefCell;
use critical_section::Mutex;
use platform::*;
#[allow(unused_imports)]
use utralib::*;
#[cfg(feature = "artybio")]
use xous_bio_bdma::*;
@ -44,9 +45,12 @@ pub fn uart_irq_handler() {
/// This function is safe to call exactly once.
#[export_name = "rust_entry"]
pub unsafe extern "C" fn rust_entry() -> ! {
// turn on a green LED to indicate boot
let mut rgb = CSR::new(utra::rgb::HW_RGB_BASE as *mut u32);
rgb.wfo(arty_rgb::LD3, 0b010);
#[cfg(any(feature = "artyvexii", feature = "artybio"))]
{
// turn on a green LED to indicate boot
let mut rgb = CSR::new(utra::rgb::HW_RGB_BASE as *mut u32);
rgb.wfo(utra::rgb::OUT_OUT, 0x002);
}
crate::platform::early_init();
crate::println!("\n~~Baremetal up!~~\n");
@ -61,7 +65,9 @@ pub unsafe extern "C" fn rust_entry() -> ! {
// The green LEDs flash whenever the FPGA is configured with the Arty BIO design.
// The RGB LEDs flash when the CPU is running this code.
#[allow(unused_variables)]
let mut count = 0;
#[cfg(any(feature = "artyvexii", feature = "artybio"))]
let mut rgb = CSR::new(utra::rgb::HW_RGB_BASE as *mut u32);
// provide some feedback on the run state of the BIO by peeking at the program counter
@ -82,8 +88,8 @@ pub unsafe extern "C" fn rust_entry() -> ! {
// Animate the LED flashing to indicate repl loop is running
delay(1);
count += 1;
rgb.rmwf(arty_rgb::LD3, (count / 500) as u32);
#[cfg(any(feature = "artyvexii", feature = "artybio"))]
rgb.wfo(utra::rgb::OUT_OUT, ((count / 500) as u32) << 6);
}
}

View file

@ -1,2 +1,4 @@
pub mod cramium;
pub use cramium::*;
pub mod debug;
pub mod irq;

View file

@ -1,9 +1,533 @@
use utralib::CSR;
use utralib::utra;
use utralib::utra::sysctrl;
use crate::platform::{
debug::setup_rx,
irq::{enable_irq, irq_setup},
};
#[global_allocator]
static ALLOCATOR: linked_list_allocator::LockedHeap = linked_list_allocator::LockedHeap::empty();
pub const RAM_SIZE: usize = utralib::generated::HW_SRAM_MEM_LEN;
pub const RAM_BASE: usize = utralib::generated::HW_SRAM_MEM;
pub const RAM_SIZE: usize = utralib::generated::HW_SRAM_MEM_LEN - 0x8_0000;
pub const RAM_BASE: usize = utralib::generated::HW_SRAM_MEM + 0x8_0000;
#[allow(dead_code)]
pub const FLASH_BASE: usize = utralib::generated::HW_RERAM_MEM;
#[cfg(all(feature = "cramium-soc", not(feature = "verilator-only")))]
pub fn early_init() {}
pub const HEAP_START: usize = RAM_BASE + 0x5000;
pub const HEAP_LEN: usize = 1024 * 256;
// scratch page for exceptions located at top of RAM
// NOTE: there is an additional page above this for exception stack
pub const SCRATCH_PAGE: usize = HEAP_START - 8192;
pub const UART_IFRAM_ADDR: usize = cramium_hal::board::UART_DMA_TX_BUF_PHYS;
// the 800_000_000 setting is tested to work at least on one sample
pub const SYSTEM_CLOCK_FREQUENCY: u32 = 400_000_000;
pub const SYSTEM_TICK_INTERVAL_MS: u32 = 1;
pub fn early_init() {
let uart = crate::debug::Uart {};
for _ in 0..100 {
uart.putc('a' as u32 as u8);
}
unsafe {
// this block is mandatory in all cases to get clocks set into some consistent, expected mode
{
let daric_cgu = sysctrl::HW_SYSCTRL_BASE as *mut u32;
// conservative dividers
daric_cgu.add(utra::sysctrl::SFR_CGUFD_CFGFDCR_0_4_0.offset()).write_volatile(0x7f7f);
daric_cgu.add(utra::sysctrl::SFR_CGUFD_CFGFDCR_0_4_1.offset()).write_volatile(0x7f7f);
daric_cgu.add(utra::sysctrl::SFR_CGUFD_CFGFDCR_0_4_2.offset()).write_volatile(0x3f7f);
daric_cgu.add(utra::sysctrl::SFR_CGUFD_CFGFDCR_0_4_3.offset()).write_volatile(0x1f3f);
daric_cgu.add(utra::sysctrl::SFR_CGUFD_CFGFDCR_0_4_4.offset()).write_volatile(0x0f1f);
// ungate all clocks
daric_cgu.add(utra::sysctrl::SFR_ACLKGR.offset()).write_volatile(0xFF);
daric_cgu.add(utra::sysctrl::SFR_HCLKGR.offset()).write_volatile(0xFF);
daric_cgu.add(utra::sysctrl::SFR_ICLKGR.offset()).write_volatile(0xFF);
daric_cgu.add(utra::sysctrl::SFR_PCLKGR.offset()).write_volatile(0xFF);
// commit clocks
daric_cgu.add(utra::sysctrl::SFR_CGUSET.offset()).write_volatile(0x32);
}
// enable DUART
let duart = utra::duart::HW_DUART_BASE as *mut u32;
duart.add(utra::duart::SFR_CR.offset()).write_volatile(0);
// based on ringosc trimming as measured by oscope. this will get precise after we set the PLL.
duart.add(utra::duart::SFR_ETUC.offset()).write_volatile(34);
duart.add(utra::duart::SFR_CR.offset()).write_volatile(1);
}
// sram0 requires 1 wait state for writes
let mut sramtrm = CSR::new(utra::coresub_sramtrm::HW_CORESUB_SRAMTRM_BASE as *mut u32);
sramtrm.wo(utra::coresub_sramtrm::SFR_SRAM0, 0x8);
sramtrm.wo(utra::coresub_sramtrm::SFR_SRAM1, 0x8);
#[cfg(feature = "v0p9")]
{
/*
logic [15:0] trm_ram32kx72 ; assign trm_ram32kx72 = trmdat[0 ]; localparam t_trm IV_trm_ram32kx72 = IV_sram_sp_uhde_inst_sram0;
logic [15:0] trm_ram8kx72 ; assign trm_ram8kx72 = trmdat[1 ]; localparam t_trm IV_trm_ram8kx72 = IV_sram_sp_hde_inst_sram1;
logic [15:0] trm_rf1kx72 ; assign trm_rf1kx72 = trmdat[2 ]; localparam t_trm IV_trm_rf1kx72 = IV_rf_sp_hde_inst_cache;
logic [15:0] trm_rf256x27 ; assign trm_rf256x27 = trmdat[3 ]; localparam t_trm IV_trm_rf256x27 = IV_rf_sp_hde_inst_cache;
logic [15:0] trm_rf512x39 ; assign trm_rf512x39 = trmdat[4 ]; localparam t_trm IV_trm_rf512x39 = IV_rf_sp_hde_inst_cache;
logic [15:0] trm_rf128x31 ; assign trm_rf128x31 = trmdat[5 ]; localparam t_trm IV_trm_rf128x31 = IV_rf_sp_hde_inst_cache;
logic [15:0] trm_dtcm8kx36 ; assign trm_dtcm8kx36 = trmdat[6 ]; localparam t_trm IV_trm_dtcm8kx36 = IV_sram_sp_hde_inst_tcm;
logic [15:0] trm_itcm32kx18 ; assign trm_itcm32kx18 = trmdat[7 ]; localparam t_trm IV_trm_itcm32kx18 = IV_sram_sp_hde_inst_tcm;
logic [15:0] trm_ifram32kx36 ; assign trm_ifram32kx36 = trmdat[8 ]; localparam t_trm IV_trm_ifram32kx36 = IV_sram_sp_uhde_inst;
logic [15:0] trm_sce_sceram_10k ; assign trm_sce_sceram_10k = trmdat[9 ]; localparam t_trm IV_trm_sce_sceram_10k = IV_sram_sp_hde_inst;
logic [15:0] trm_sce_hashram_3k ; assign trm_sce_hashram_3k = trmdat[10]; localparam t_trm IV_trm_sce_hashram_3k = IV_rf_sp_hde_inst;
logic [15:0] trm_sce_aesram_1k ; assign trm_sce_aesram_1k = trmdat[11]; localparam t_trm IV_trm_sce_aesram_1k = IV_rf_sp_hde_inst;
logic [15:0] trm_sce_pkeram_4k ; assign trm_sce_pkeram_4k = trmdat[12]; localparam t_trm IV_trm_sce_pkeram_4k = IV_rf_sp_hde_inst;
logic [15:0] trm_sce_aluram_3k ; assign trm_sce_aluram_3k = trmdat[13]; localparam t_trm IV_trm_sce_aluram_3k = IV_rf_sp_hde_inst;
logic [15:0] trm_sce_mimmdpram ; assign trm_sce_mimmdpram = trmdat[14]; localparam t_trm IV_trm_sce_mimmdpram = IV_rf_2p_hdc_inst;
logic [15:0] trm_rdram1kx32 ; assign trm_rdram1kx32 = trmdat[15]; localparam t_trm IV_trm_rdram1kx32 = IV_rf_2p_hdc_inst_vex;
logic [15:0] trm_rdram512x64 ; assign trm_rdram512x64 = trmdat[16]; localparam t_trm IV_trm_rdram512x64 = IV_rf_2p_hdc_inst_vex;
logic [15:0] trm_rdram128x22 ; assign trm_rdram128x22 = trmdat[17]; localparam t_trm IV_trm_rdram128x22 = IV_rf_2p_hdc_inst_vex;
logic [15:0] trm_rdram32x16 ; assign trm_rdram32x16 = trmdat[18]; localparam t_trm IV_trm_rdram32x16 = IV_rf_2p_hdc_inst_vex;
logic [15:0] trm_bioram1kx32 ; assign trm_bioram1kx32 = trmdat[19]; localparam t_trm IV_trm_bioram1kx32 = IV_rf_sp_hde_inst_cache;
logic [15:0] trm_tx_fifo128x32 ; assign trm_tx_fifo128x32 = trmdat[20]; localparam t_trm IV_trm_tx_fifo128x32 = IV_rf_2p_hdc_inst;
logic [15:0] trm_rx_fifo128x32 ; assign trm_rx_fifo128x32 = trmdat[21]; localparam t_trm IV_trm_rx_fifo128x32 = IV_rf_2p_hdc_inst;
logic [15:0] trm_fifo32x19 ; assign trm_fifo32x19 = trmdat[22]; localparam t_trm IV_trm_fifo32x19 = IV_rf_2p_hdc_inst;
logic [15:0] trm_udcmem_share ; assign trm_udcmem_share = trmdat[23]; localparam t_trm IV_trm_udcmem_share = IV_rf_2p_hdc_inst;
logic [15:0] trm_udcmem_odb ; assign trm_udcmem_odb = trmdat[24]; localparam t_trm IV_trm_udcmem_odb = IV_rf_2p_hdc_inst;
logic [15:0] trm_udcmem_256x64 ; assign trm_udcmem_256x64 = trmdat[25]; localparam t_trm IV_trm_udcmem_256x64 = IV_rf_2p_hdc_inst;
logic [15:0] trm_acram2kx64 ; assign trm_acram2kx64 = trmdat[26]; localparam t_trm IV_trm_acram2kx64 = IV_sram_sp_uhde_inst_sram0;
logic [15:0] trm_aoram1kx36 ; assign trm_aoram1kx36 = trmdat[27]; localparam t_trm IV_trm_aoram1kx36 = IV_sram_sp_hde_inst;
*/
crate::println!("setting 0.9v sramtrm");
let mut sramtrm = CSR::new(utra::coresub_sramtrm::HW_CORESUB_SRAMTRM_BASE as *mut u32);
sramtrm.wo(utra::coresub_sramtrm::SFR_CACHE, 0x3);
sramtrm.wo(utra::coresub_sramtrm::SFR_ITCM, 0x3);
sramtrm.wo(utra::coresub_sramtrm::SFR_DTCM, 0x3);
sramtrm.wo(utra::coresub_sramtrm::SFR_VEXRAM, 0x1);
let mut rbist = CSR::new(utra::rbist_wrp::HW_RBIST_WRP_BASE as *mut u32);
// bio 0.9v settings
rbist.wo(utra::rbist_wrp::SFRCR_TRM, (19 << 16) | 0b011_000_01_0_0_000_0_00);
rbist.wo(utra::rbist_wrp::SFRAR_TRM, 0x5a);
// vex 0.9v settings
for i in 0..4 {
rbist.wo(utra::rbist_wrp::SFRCR_TRM, ((15 + i) << 16) | 0b001_010_00_0_0_000_0_00);
rbist.wo(utra::rbist_wrp::SFRAR_TRM, 0x5a);
}
// sram 0.9v settings
rbist.wo(utra::rbist_wrp::SFRCR_TRM, (0 << 16) | 0b011_000_01_0_1_000_0_00);
rbist.wo(utra::rbist_wrp::SFRAR_TRM, 0x5a);
rbist.wo(utra::rbist_wrp::SFRCR_TRM, (1 << 16) | 0b011_000_00_0_0_000_0_00);
rbist.wo(utra::rbist_wrp::SFRAR_TRM, 0x5a);
crate::println!("setting other 0.9v trims");
// tcm 0.9v
rbist.wo(utra::rbist_wrp::SFRCR_TRM, (6 << 16) | 0b011_000_00_0_0_000_0_00);
rbist.wo(utra::rbist_wrp::SFRAR_TRM, 0x5a);
rbist.wo(utra::rbist_wrp::SFRCR_TRM, (7 << 16) | 0b011_000_00_0_0_000_0_00);
rbist.wo(utra::rbist_wrp::SFRAR_TRM, 0x5a);
// ifram 0.9v
rbist.wo(utra::rbist_wrp::SFRCR_TRM, (8 << 16) | 0b010_000_00_0_1_000_1_01);
rbist.wo(utra::rbist_wrp::SFRAR_TRM, 0x5a);
// sce 0.9V
rbist.wo(utra::rbist_wrp::SFRCR_TRM, (9 << 16) | 0b011_000_00_0_0_000_0_00);
rbist.wo(utra::rbist_wrp::SFRAR_TRM, 0x5a);
for i in 0..4 {
rbist.wo(utra::rbist_wrp::SFRCR_TRM, ((10 + i) << 16) | 0b011_000_01_0_1_000_0_00);
rbist.wo(utra::rbist_wrp::SFRAR_TRM, 0x5a);
}
rbist.wo(utra::rbist_wrp::SFRCR_TRM, (14 << 16) | 0b001_010_00_0_0_000_0_00);
rbist.wo(utra::rbist_wrp::SFRAR_TRM, 0x5a);
}
let perclk = unsafe { init_clock_asic(SYSTEM_CLOCK_FREQUENCY) };
// test memory
crate::println!("\ntest memory...");
let base = 0x6108_5000;
let mem_range = unsafe {
core::slice::from_raw_parts_mut(base as *mut u32, (0x6120_0000 - base) / core::mem::size_of::<u32>())
};
let mut state = 1;
for m in mem_range.iter_mut() {
state = lfsr_next_u32(state);
*m = state;
}
state = 1;
let mut failures = 0;
for m in mem_range.iter() {
state = lfsr_next_u32(state);
if state != *m {
failures += 1;
}
}
if failures != 0 {
crate::println!("fast mem test failed");
} else {
crate::println!("fast mem test passed");
}
crate::println!("scratch page: {:x}, heap start: {:x}", SCRATCH_PAGE, HEAP_START);
// setup the static data (hard-coded, because no loader) - necessary for heap
// see build message about non-zero data. Also need to zero out the BSS region.
let static_data = unsafe { core::slice::from_raw_parts_mut(0x6108_0000 as *mut u8, 0x14 + 0x24) };
static_data.fill(0);
static_data[8] = 1;
crate::print!("static data {:x}: ", static_data.as_ptr() as usize);
for sd in static_data.iter() {
crate::print!("{:x} ", *sd);
}
crate::println!("");
// setup heap alloc
setup_alloc();
setup_timer();
// Rx setup
let mut udma_uart = setup_rx(perclk);
irq_setup();
enable_irq(utra::irqarray5::IRQARRAY5_IRQ);
udma_uart.write("console up\r\n".as_bytes());
}
pub fn setup_timer() {
// Initialize the timer, which is needed by the delay() function.
let mut timer = CSR::new(utra::timer0::HW_TIMER0_BASE as *mut u32);
// not using interrupts, this will be polled by delay()
timer.wfo(utra::timer0::EV_ENABLE_ZERO, 0);
timer.wfo(utra::timer0::EV_PENDING_ZERO, 1);
let ms = SYSTEM_TICK_INTERVAL_MS;
timer.wfo(utra::timer0::EN_EN, 0b0); // disable the timer
// load its values
timer.wfo(utra::timer0::LOAD_LOAD, 0);
timer.wfo(utra::timer0::RELOAD_RELOAD, (SYSTEM_CLOCK_FREQUENCY / 1_000) * ms);
// enable the timer
timer.wfo(utra::timer0::EN_EN, 0b1);
}
pub fn setup_alloc() {
// Initialize the allocator with heap memory range
crate::println!("Setting up heap @ {:x}-{:x}", HEAP_START, HEAP_START + HEAP_LEN);
crate::println!("Stack @ {:x}-{:x}", HEAP_START + HEAP_LEN, RAM_BASE + RAM_SIZE);
unsafe {
ALLOCATOR.lock().init(HEAP_START as *mut u8, HEAP_LEN);
}
}
/// Delay function that delays a given number of milliseconds.
pub fn delay(ms: usize) {
let mut timer = utralib::CSR::new(utra::timer0::HW_TIMER0_BASE as *mut u32);
timer.wfo(utra::timer0::EV_PENDING_ZERO, 1);
for _ in 0..ms {
// comment this out for testing on MPW
while timer.rf(utra::timer0::EV_PENDING_ZERO) == 0 {}
timer.wfo(utra::timer0::EV_PENDING_ZERO, 1);
}
}
mod panic_handler {
use core::panic::PanicInfo;
#[panic_handler]
fn handle_panic(_arg: &PanicInfo) -> ! {
crate::println!("{}", _arg);
loop {}
}
}
// This function supercedes init_clock_asic() and needs to be back-ported
// into xous-core
pub unsafe fn init_clock_asic(freq_hz: u32) -> u32 {
use utra::sysctrl;
let daric_cgu = sysctrl::HW_SYSCTRL_BASE as *mut u32;
let mut cgu = CSR::new(daric_cgu);
const UNIT_MHZ: u32 = 1000 * 1000;
const PFD_F_MHZ: u32 = 16;
const FREQ_0: u32 = 16 * UNIT_MHZ;
const FREQ_OSC_MHZ: u32 = 48; // Actually 48MHz
const M: u32 = FREQ_OSC_MHZ / PFD_F_MHZ; // - 1; // OSC input was 24, replace with 48
const TBL_Q: [u16; 7] = [
// keep later DIV even number as possible
0x7777, // 16-32 MHz
0x7737, // 32-64
0x3733, // 64-128
0x3313, // 128-256
0x3311, // 256-512 // keep ~ 100MHz
0x3301, // 512-1024
0x3301, // 1024-1600
];
const TBL_MUL: [u32; 7] = [
64, // 16-32 MHz
32, // 32-64
16, // 64-128
8, // 128-256
4, // 256-512
2, // 512-1024
2, // 1024-1600
];
// this block might belong at the top, in particular, configuring the dividers prevents stuff
// from being overclocked when the PLL comes live; but for now we are debugging other stuff
{
// Hits a 16:8:4:2:1 ratio on fclk:aclk:hclk:iclk:pclk
// Resulting in 800:400:200:100:50 MHz assuming 800MHz fclk
daric_cgu.add(utra::sysctrl::SFR_CGUFD_CFGFDCR_0_4_0.offset()).write_volatile(0x3f7f); // fclk
// Hits a 8:8:4:2:1 ratio on fclk:aclk:hclk:iclk:pclk
daric_cgu.add(utra::sysctrl::SFR_CGUFD_CFGFDCR_0_4_1.offset()).write_volatile(0x3f7f); // aclk
daric_cgu.add(utra::sysctrl::SFR_CGUFD_CFGFDCR_0_4_2.offset()).write_volatile(0x1f3f); // hclk
daric_cgu.add(utra::sysctrl::SFR_CGUFD_CFGFDCR_0_4_3.offset()).write_volatile(0x0f1f); // iclk
daric_cgu.add(utra::sysctrl::SFR_CGUFD_CFGFDCR_0_4_4.offset()).write_volatile(0x070f); // pclk
// perclk divider - set to divide by 16 off of an 800Mhz base. Only found on NTO.
// daric_cgu.add(utra::sysctrl::SFR_CGUFDPER.offset()).write_volatile(0x03_ff_ff);
// perclk divider - set to divide by 8 off of an 800Mhz base. Only found on NTO.
// TODO: this only works for two clock settings. Broken @ 600. Need to fix this to instead derive
// what pclk is instead of always reporting 100mhz
if freq_hz == 800_000_000 {
daric_cgu.add(utra::sysctrl::SFR_CGUFDPER.offset()).write_volatile(0x07_ff_ff);
} else {
daric_cgu.add(utra::sysctrl::SFR_CGUFDPER.offset()).write_volatile(0x03_ff_ff);
}
/*
perclk fields: min-cycle-lp | min-cycle | fd-lp | fd
clkper fd
0xff : Fperclk = Fclktop/2
0x7f: Fperclk = Fclktop/4
0x3f : Fperclk = Fclktop/8
0x1f : Fperclk = Fclktop/16
0x0f : Fperclk = Fclktop/32
0x07 : Fperclk = Fclktop/64
0x03: Fperclk = Fclktop/128
0x01: Fperclk = Fclktop/256
min cycle of clktop, F means frequency
Fperclk Max = Fperclk/(min cycle+1)*2
*/
// turn off gates
daric_cgu.add(utra::sysctrl::SFR_ACLKGR.offset()).write_volatile(0x2f);
daric_cgu.add(utra::sysctrl::SFR_HCLKGR.offset()).write_volatile(0xff);
daric_cgu.add(utra::sysctrl::SFR_ICLKGR.offset()).write_volatile(0x8f);
daric_cgu.add(utra::sysctrl::SFR_PCLKGR.offset()).write_volatile(0xff);
crate::println!("bef gates set");
for _ in 0..100 {
crate::print!("*");
}
crate::println!(".");
// commit dividers
daric_cgu.add(utra::sysctrl::SFR_CGUSET.offset()).write_volatile(0x32);
crate::println!("gates set");
for _ in 0..100 {
crate::print!("-");
}
crate::println!(".");
}
/*
if (0 == (cgu.r(sysctrl::SFR_IPCPLLMN) & 0x0001F000))
|| (0 == (cgu.r(sysctrl::SFR_IPCPLLMN) & 0x00000fff))
{
// for SIM, avoid div by 0 if unconfigurated
// , default VCO 48MHz / 48 * 1200 = 1.2GHz
// TODO magic numbers
cgu.wo(sysctrl::SFR_IPCPLLMN, ((M << 12) & 0x0001F000) | ((1200) & 0x00000fff));
cgu.wo(sysctrl::SFR_IPCPLLF, 0);
cgu.wo(sysctrl::SFR_IPCARIPFLOW, 0x32);
}
*/
for _ in 0..100 {
crate::print!("1");
}
crate::println!(".");
// TODO select int/ext osc/xtal
// DARIC_CGU->cgusel1 = 1; // 0: RC, 1: XTAL
cgu.wo(sysctrl::SFR_CGUSEL1, 1);
// DARIC_CGU->cgufscr = FREQ_OSC_MHZ; // external crystal is 48MHz
cgu.wo(sysctrl::SFR_CGUFSCR, FREQ_OSC_MHZ);
// __DSB();
// DARIC_CGU->cguset = 0x32UL;
cgu.wo(sysctrl::SFR_CGUSET, 0x32);
// __DSB();
let duart = utra::duart::HW_DUART_BASE as *mut u32;
duart.add(utra::duart::SFR_CR.offset()).write_volatile(0);
// set the ETUC now that we're on the xosc.
duart.add(utra::duart::SFR_ETUC.offset()).write_volatile(FREQ_OSC_MHZ);
duart.add(utra::duart::SFR_CR.offset()).write_volatile(1);
for _ in 0..100 {
crate::print!("2");
}
crate::println!(".");
if freq_hz < 1000000 {
// DARIC_IPC->osc = freqHz;
cgu.wo(sysctrl::SFR_IPCOSC, freq_hz);
// __DSB();
// DARIC_IPC->ar = 0x0032; // commit, must write 32
cgu.wo(sysctrl::SFR_IPCARIPFLOW, 0x32);
// __DSB();
}
// switch to OSC
//DARIC_CGU->cgusel0 = 0; // clktop sel, 0:clksys, 1:clkpll0
cgu.wo(sysctrl::SFR_CGUSEL0, 0);
// __DSB();
// DARIC_CGU->cguset = 0x32; // commit
cgu.wo(sysctrl::SFR_CGUSET, 0x32);
//__DSB();
for _ in 0..100 {
crate::print!("3");
}
crate::println!(".");
if freq_hz < 1000000 {
} else {
let n_fxp24: u64; // fixed point
let f16mhz_log2: u32 = (freq_hz / FREQ_0).ilog2();
for _ in 0..100 {
crate::print!("4");
}
crate::println!(".");
// PD PLL
// DARIC_IPC->lpen |= 0x02 ;
cgu.wo(sysctrl::SFR_IPCLPEN, cgu.r(sysctrl::SFR_IPCLPEN) | 0x2);
// __DSB();
// DARIC_IPC->ar = 0x0032; // commit, must write 32
cgu.wo(sysctrl::SFR_IPCARIPFLOW, 0x32);
// __DSB();
// delay
// for (uint32_t i = 0; i < 1024; i++){
// __NOP();
//}
for _ in 0..1024 {
unsafe { core::arch::asm!("nop") };
}
crate::println!("PLL delay 1");
n_fxp24 = (((freq_hz as u64) << 24) * TBL_MUL[f16mhz_log2 as usize] as u64
+ PFD_F_MHZ as u64 * UNIT_MHZ as u64 / 2)
/ (PFD_F_MHZ as u64 * UNIT_MHZ as u64); // rounded
let n_frac: u32 = (n_fxp24 & 0x00ffffff) as u32;
// TODO very verbose
//printf ("%s(%4" PRIu32 "MHz) M = %4" PRIu32 ", N = %4" PRIu32 ".%08" PRIu32 ", Q = %2lu, QDiv =
// 0x%04" PRIx16 "\n", __FUNCTION__, freqHz / 1000000, M, (uint32_t)(n_fxp24 >> 24),
// (uint32_t)((uint64_t)(n_fxp24 & 0x00ffffff) * 100000000/(1UL <<24)), TBL_MUL[f16MHzLog2],
// TBL_Q[f16MHzLog2]); DARIC_IPC->pll_mn = ((M << 12) & 0x0001F000) | ((n_fxp24 >> 24) &
// 0x00000fff); // 0x1F598; // ??
cgu.wo(sysctrl::SFR_IPCPLLMN, ((M << 12) & 0x0001F000) | (((n_fxp24 >> 24) as u32) & 0x00000fff));
// DARIC_IPC->pll_f = n_frac | ((0 == n_frac) ? 0 : (1UL << 24)); // ??
cgu.wo(sysctrl::SFR_IPCPLLF, n_frac | if 0 == n_frac { 0 } else { 1u32 << 24 });
// DARIC_IPC->pll_q = TBL_Q[f16MHzLog2]; // ?? TODO select DIV for VCO freq
cgu.wo(sysctrl::SFR_IPCPLLQ, TBL_Q[f16mhz_log2 as usize] as u32);
// VCO bias CPP bias CPI bias
// 1 2 3
//DARIC_IPC->ipc = (3 << 6) | (5 << 3) | (5);
// DARIC_IPC->ipc = (1 << 6) | (2 << 3) | (3);
cgu.wo(sysctrl::SFR_IPCCR, (1 << 6) | (2 << 3) | (3));
// __DSB();
// DARIC_IPC->ar = 0x0032; // commit
cgu.wo(sysctrl::SFR_IPCARIPFLOW, 0x32);
// __DSB();
// DARIC_IPC->lpen &= ~0x02;
cgu.wo(sysctrl::SFR_IPCLPEN, cgu.r(sysctrl::SFR_IPCLPEN) & !0x2);
//__DSB();
// DARIC_IPC->ar = 0x0032; // commit
cgu.wo(sysctrl::SFR_IPCARIPFLOW, 0x32);
// __DSB();
// delay
// for (uint32_t i = 0; i < 1024; i++){
// __NOP();
// }
for _ in 0..1024 {
unsafe { core::arch::asm!("nop") };
}
crate::println!("PLL delay 2");
//printf("read reg a0 : %08" PRIx32"\n", *((volatile uint32_t* )0x400400a0));
//printf("read reg a4 : %04" PRIx16"\n", *((volatile uint16_t* )0x400400a4));
//printf("read reg a8 : %04" PRIx16"\n", *((volatile uint16_t* )0x400400a8));
// TODO wait/poll lock status?
// DARIC_CGU->cgusel0 = 1; // clktop sel, 0:clksys, 1:clkpll0
cgu.wo(sysctrl::SFR_CGUSEL0, 1);
// __DSB();
// DARIC_CGU->cguset = 0x32; // commit
cgu.wo(sysctrl::SFR_CGUSET, 0x32);
crate::println!("clocks set");
// __DSB();
// printf (" MN: 0x%05x, F: 0x%06x, Q: 0x%04x\n",
// DARIC_IPC->pll_mn, DARIC_IPC->pll_f, DARIC_IPC->pll_q);
// printf (" LPEN: 0x%01x, OSC: 0x%04x, BIAS: 0x%04x,\n",
// DARIC_IPC->lpen, DARIC_IPC->osc, DARIC_IPC->ipc);
}
crate::println!(
"mn {:x}, q{:x}",
(0x400400a0 as *const u32).read_volatile(),
(0x400400a8 as *const u32).read_volatile()
);
crate::println!("fsvalid: {}", daric_cgu.add(sysctrl::SFR_CGUFSVLD.offset()).read_volatile());
let cgufsfreq0 = daric_cgu.add(sysctrl::SFR_CGUFSSR_FSFREQ0.offset()).read_volatile();
let cgufsfreq1 = daric_cgu.add(sysctrl::SFR_CGUFSSR_FSFREQ1.offset()).read_volatile();
let cgufsfreq2 = daric_cgu.add(sysctrl::SFR_CGUFSSR_FSFREQ2.offset()).read_volatile();
let cgufsfreq3 = daric_cgu.add(sysctrl::SFR_CGUFSSR_FSFREQ3.offset()).read_volatile();
crate::println!(
"Internal osc: {} -> {} MHz ({} MHz)",
cgufsfreq0,
fsfreq_to_hz(cgufsfreq0),
fsfreq_to_hz_32(cgufsfreq0)
);
crate::println!(
"XTAL: {} -> {} MHz ({} MHz)",
cgufsfreq1,
fsfreq_to_hz(cgufsfreq1),
fsfreq_to_hz_32(cgufsfreq1)
);
crate::println!(
"pll output 0: {} -> {} MHz ({} MHz)",
cgufsfreq2,
fsfreq_to_hz(cgufsfreq2),
fsfreq_to_hz_32(cgufsfreq2)
);
crate::println!(
"pll output 1: {} -> {} MHz ({} MHz)",
cgufsfreq3,
fsfreq_to_hz(cgufsfreq3),
fsfreq_to_hz_32(cgufsfreq3)
);
crate::println!("PLL configured to {} MHz", freq_hz / 1_000_000);
100_000_000
}
#[allow(dead_code)]
fn fsfreq_to_hz(fs_freq: u32) -> u32 { (fs_freq * (48_000_000 / 32)) / 1_000_000 }
#[allow(dead_code)]
fn fsfreq_to_hz_32(fs_freq: u32) -> u32 { (fs_freq * (32_000_000 / 32)) / 1_000_000 }
/// used to generate some test vectors
#[allow(dead_code)]
pub fn lfsr_next_u32(state: u32) -> u32 {
let bit = ((state >> 31) ^ (state >> 21) ^ (state >> 1) ^ (state >> 0)) & 1;
(state << 1) + bit
}

View file

@ -0,0 +1,154 @@
use cramium_api::*;
use cramium_hal::iox::Iox;
use cramium_hal::udma::UartIrq;
use cramium_hal::{udma, udma::GlobalConfig};
use utralib::generated::*;
/// A trait for serial like drivers which allows reading from a source.
#[allow(dead_code)]
pub trait SerialRead {
/// Read a single byte.
fn getc(&mut self) -> Option<u8>;
}
pub struct Uart {}
#[allow(dead_code)]
impl Uart {
pub fn putc(&self, c: u8) {
let base = utra::duart::HW_DUART_BASE as *mut u32;
let mut uart = CSR::new(base);
if uart.rf(utra::duart::SFR_CR_SFR_CR) == 0 {
uart.wfo(utra::duart::SFR_CR_SFR_CR, 1);
}
while uart.r(utra::duart::SFR_SR) != 0 {}
uart.wo(utra::duart::SFR_TXD, c as u32);
}
fn put_digit(&mut self, d: u8) {
let nyb = d & 0xF;
let c = if nyb < 10 { nyb + 0x30 } else { nyb + 0x61 - 10 };
assert!(c >= 0x30, "conversion failed!");
self.putc(c);
}
pub fn put_hex(&mut self, c: u8) {
self.put_digit(c >> 4);
self.put_digit(c & 0xF);
}
pub fn newline(&mut self) {
self.putc(0xa);
self.putc(0xd);
}
pub fn print_hex_word(&mut self, word: u32) {
for &byte in word.to_be_bytes().iter() {
self.put_hex(byte);
}
}
pub fn tiny_write_str(&mut self, s: &str) {
for c in s.bytes() {
self.putc(c);
}
}
}
use core::fmt::{Error, Write};
impl Write for Uart {
fn write_str(&mut self, s: &str) -> Result<(), Error> {
for c in s.bytes() {
self.putc(c);
}
Ok(())
}
}
impl SerialRead for Uart {
fn getc(&mut self) -> Option<u8> {
let uart_buf_addr = crate::platform::UART_IFRAM_ADDR;
let mut udma_uart = unsafe {
// safety: this is safe to call, because we set up clock and events prior to calling new.
udma::Uart::get_handle(utra::udma_uart_1::HW_UDMA_UART_1_BASE, uart_buf_addr, uart_buf_addr)
};
let mut c = 0u8;
udma_uart.read_async(&mut c);
let mut irqarray5 = CSR::new(utra::irqarray5::HW_IRQARRAY5_BASE as *mut u32);
// read & clear the pending bits
let pending = irqarray5.r(utra::irqarray5::EV_PENDING);
// crate::println!("pending {:x} {}", pending, unsafe { char::from_u32_unchecked(c as u32) });
irqarray5.wo(utra::irqarray5::EV_PENDING, pending);
if pending != 0 { Some(c) } else { None }
}
}
#[macro_use]
pub mod debug_print_hardware {
#[macro_export]
macro_rules! print
{
($($args:tt)+) => ({
use core::fmt::Write;
let _ = write!(crate::debug::Uart {}, $($args)+);
});
}
}
#[macro_export]
macro_rules! println
{
() => ({
$crate::print!("\r\n")
});
($fmt:expr) => ({
$crate::print!(concat!($fmt, "\r\n"))
});
($fmt:expr, $($args:tt)+) => ({
$crate::print!(concat!($fmt, "\r\n"), $($args)+)
});
}
pub fn setup_rx(perclk: u32) -> cramium_hal::udma::Uart {
let iox = Iox::new(utra::iox::HW_IOX_BASE as *mut u32);
iox.set_alternate_function(IoxPort::PD, 13, IoxFunction::AF1);
iox.set_alternate_function(IoxPort::PD, 14, IoxFunction::AF1);
// rx as input, with pull-up
iox.set_gpio_dir(IoxPort::PD, 13, IoxDir::Input);
iox.set_gpio_pullup(IoxPort::PD, 13, IoxEnable::Enable);
// tx as output
iox.set_gpio_dir(IoxPort::PD, 14, IoxDir::Output);
let udma_global = GlobalConfig::new();
udma_global.clock_on(PeriphId::Uart1);
udma_global.map_event(
PeriphId::Uart1,
PeriphEventType::Uart(EventUartOffset::Rx),
EventChannel::Channel0,
);
udma_global.map_event(
PeriphId::Uart1,
PeriphEventType::Uart(EventUartOffset::Tx),
EventChannel::Channel1,
);
let baudrate: u32 = 115200;
let freq: u32 = perclk / 2;
// the address of the UART buffer is "hard-allocated" at an offset one page from the top of
// IFRAM0. This is a convention that must be respected by the UDMA UART library implementation
// for things to work.
let uart_buf_addr = crate::platform::UART_IFRAM_ADDR;
let mut udma_uart = unsafe {
// safety: this is safe to call, because we set up clock and events prior to calling new.
udma::Uart::get_handle(utra::udma_uart_1::HW_UDMA_UART_1_BASE, uart_buf_addr, uart_buf_addr)
};
udma_uart.set_baud(baudrate, freq);
udma_uart.setup_async_read();
// setup interrupt here
let mut uart_irq = UartIrq::new();
uart_irq.rx_irq_ena(udma::UartChannel::Uart1, true);
udma_uart
}

View file

@ -0,0 +1,206 @@
use riscv::register::{mcause, mie, mstatus};
use vexriscv::register::vexriscv::{mim, mip};
use crate::*;
pub fn irq_setup() {
unsafe {
#[rustfmt::skip]
core::arch::asm!(
// Set trap handler, which will be called
// on interrupts and cpu faults
"la t0, _start_trap", // this first one forces the nop sled symbol to be generated
"la t0, _start_trap_aligned", // this is the actual target
"csrw mtvec, t0",
);
}
mim::write(0x0); // first make sure everything is disabled, so we aren't OR'ing in garbage
unsafe {
mstatus::set_mie();
}
// must enable external interrupts on the CPU for any of the above to matter
unsafe { mie::set_mext() };
}
pub fn enable_irq(irq_no: usize) {
// Note that the vexriscv "IRQ Mask" register is inverse-logic --
// that is, setting a bit in the "mask" register unmasks (i.e. enables) it.
mim::write(mim::read() | (1 << irq_no));
// must enable external interrupts on the CPU for any of the above to matter
unsafe { mie::set_mext() };
}
#[export_name = "_start_trap"]
// #[repr(align(4))] // can't do this yet.
#[inline(never)]
pub unsafe extern "C" fn _start_trap() -> ! {
loop {
// install a NOP sled before _start_trap() until https://github.com/rust-lang/rust/issues/82232 is stable
core::arch::asm!("nop", "nop", "nop", "nop");
#[export_name = "_start_trap_aligned"]
pub unsafe extern "C" fn _start_trap_aligned() {
#[rustfmt::skip]
core::arch::asm!(
"csrw mscratch, sp",
"li sp, 0x61083000", // crate::platform::SCRATCH_PAGE - has to be hard-coded
"sw x1, 0*4(sp)",
// Skip SP for now
"sw x3, 2*4(sp)",
"sw x4, 3*4(sp)",
"sw x5, 4*4(sp)",
"sw x6, 5*4(sp)",
"sw x7, 6*4(sp)",
"sw x8, 7*4(sp)",
"sw x9, 8*4(sp)",
"sw x10, 9*4(sp)",
"sw x11, 10*4(sp)",
"sw x12, 11*4(sp)",
"sw x13, 12*4(sp)",
"sw x14, 13*4(sp)",
"sw x15, 14*4(sp)",
"sw x16, 15*4(sp)",
"sw x17, 16*4(sp)",
"sw x18, 17*4(sp)",
"sw x19, 18*4(sp)",
"sw x20, 19*4(sp)",
"sw x21, 20*4(sp)",
"sw x22, 21*4(sp)",
"sw x23, 22*4(sp)",
"sw x24, 23*4(sp)",
"sw x25, 24*4(sp)",
"sw x26, 25*4(sp)",
"sw x27, 26*4(sp)",
"sw x28, 27*4(sp)",
"sw x29, 28*4(sp)",
"sw x30, 29*4(sp)",
"sw x31, 30*4(sp)",
// Save MEPC
"csrr t0, mepc",
"sw t0, 31*4(sp)",
// Save x1, which was used to calculate the offset. Prior to
// calculating, it was stashed at 0x61006000.
//"li t0, 0x61006000",
//"lw t1, 0*4(t0)",
//"sw t1, 0*4(sp)",
// Finally, save SP
"csrr t0, mscratch",
"sw t0, 1*4(sp)",
// Restore a default stack pointer
"li sp, 0x61085000", // heap base, grows down
// Note that registers $a0-$a7 still contain the arguments
"j _start_trap_rust",
// Note to self: trying to assign the scratch and default pages using in(reg) syntax
// clobbers the `a0` register and places the initialization outside of the handler loop
// and there seems to be no way to refer directly to a symbol? the `sym` directive wants
// to refer to an address, not a constant.
);
}
_start_trap_aligned();
core::arch::asm!("nop", "nop", "nop", "nop");
}
}
#[export_name = "_resume_context"]
#[inline(never)]
pub unsafe extern "C" fn _resume_context(registers: u32) -> ! {
#[rustfmt::skip]
core::arch::asm!(
"move sp, {registers}",
"lw x1, 0*4(sp)",
// Skip SP for now
"lw x3, 2*4(sp)",
"lw x4, 3*4(sp)",
"lw x5, 4*4(sp)",
"lw x6, 5*4(sp)",
"lw x7, 6*4(sp)",
"lw x8, 7*4(sp)",
"lw x9, 8*4(sp)",
"lw x10, 9*4(sp)",
"lw x11, 10*4(sp)",
"lw x12, 11*4(sp)",
"lw x13, 12*4(sp)",
"lw x14, 13*4(sp)",
"lw x15, 14*4(sp)",
"lw x16, 15*4(sp)",
"lw x17, 16*4(sp)",
"lw x18, 17*4(sp)",
"lw x19, 18*4(sp)",
"lw x20, 19*4(sp)",
"lw x21, 20*4(sp)",
"lw x22, 21*4(sp)",
"lw x23, 22*4(sp)",
"lw x24, 23*4(sp)",
"lw x25, 24*4(sp)",
"lw x26, 25*4(sp)",
"lw x27, 26*4(sp)",
"lw x28, 27*4(sp)",
"lw x29, 28*4(sp)",
"lw x30, 29*4(sp)",
"lw x31, 30*4(sp)",
// Restore SP
"lw x2, 1*4(sp)",
"mret",
registers = in(reg) registers,
);
loop {}
}
/// Just handles specific traps for testing CPU interactions. Doesn't do anything useful with the traps.
#[export_name = "_start_trap_rust"]
pub extern "C" fn trap_handler(
_a0: usize,
_a1: usize,
_a2: usize,
_a3: usize,
_a4: usize,
_a5: usize,
_a6: usize,
_a7: usize,
) -> ! {
let cause: mcause::Mcause = mcause::read();
// crate::println!("cause {:x}", cause.bits());
// 2 is illegal instruction
if cause.bits() == 2 {
// skip past the illegal instruction, in case that's what we want to do...
unsafe {
#[rustfmt::skip]
core::arch::asm!(
"csrr t0, mepc",
"addi t0, t0, 4",
"csrw mepc, t0",
);
}
// ...but also panic.
panic!("Illegal Instruction");
} else if cause.bits() == 4 {
let epc = riscv::register::mepc::read();
panic!("Load address misaligned @ {:x}", epc);
} else if cause.bits() == 6 {
let epc = riscv::register::mepc::read();
panic!("Store address misaligned @ {:x}", epc);
} else if cause.bits() == 0x8000_000b {
// external machine interrupt
// external interrupt. find out which ones triggered it, and clear the source.
let irqs_pending = mip::read();
if (irqs_pending & (1 << utra::timer0::TIMER0_IRQ)) != 0 {
let ms = SYSTEM_TICK_INTERVAL_MS;
let mut timer0 = CSR::new(utra::timer0::HW_TIMER0_BASE as *mut u32);
timer0.wfo(utra::timer0::EV_PENDING_ZERO, 1);
timer0.wfo(utra::timer0::RELOAD_RELOAD, (SYSTEM_CLOCK_FREQUENCY / 1_000) * ms);
} else if (irqs_pending & (1 << utra::irqarray5::IRQARRAY5_IRQ)) != 0 {
crate::uart_irq_handler();
}
}
// re-enable interrupts
unsafe { mie::set_mext() };
// crate::println!("restoring from {:x}", crate::platform::SCRATCH_PAGE);
unsafe { _resume_context(crate::platform::SCRATCH_PAGE as u32) };
}

View file

@ -1,7 +1,7 @@
MEMORY
{
FLASH : ORIGIN = 0x60000000, LENGTH = 2M
RAM : ORIGIN = 0x61000000, LENGTH = 2M
FLASH : ORIGIN = 0x61000000, LENGTH = 256k
RAM : ORIGIN = 0x61080000, LENGTH = 1536k
}
REGION_ALIAS("REGION_TEXT", FLASH);

View file

@ -2,6 +2,7 @@ use alloc::string::{String, ToString};
use alloc::vec::Vec;
use core::sync::atomic::{AtomicBool, Ordering};
#[allow(unused_imports)]
use utralib::*;
#[cfg(feature = "artybio")]
use xous_bio_bdma::*;
@ -37,6 +38,7 @@ pub struct Repl {
do_cmd: bool,
}
const COLUMNS: usize = 4;
impl Repl {
pub fn new() -> Self { Self { cmdline: String::new(), do_cmd: false } }
@ -75,6 +77,7 @@ impl Repl {
let cmd = parts.next().unwrap_or("").to_string();
let args: Vec<String> = parts.map(|s| s.to_string()).collect();
match cmd.as_str() {
#[cfg(not(feature = "cramium-soc"))]
"mon" => {
#[cfg(feature = "artybio")]
let bio_ss = BioSharedState::new();
@ -109,6 +112,143 @@ impl Repl {
});
}
}
"peek" => {
if args.len() == 1 || args.len() == 2 {
if let Ok(addr) = usize::from_str_radix(&args[0], 16) {
let count = if args.len() == 2 {
if let Ok(count) = u32::from_str_radix(&args[1], 10) { count } else { 1 }
} else {
1
};
// safety: it's not safe to do this, the user peeks at their own risk
let peek = unsafe { core::slice::from_raw_parts(addr as *const u32, count as usize) };
for (i, &d) in peek.iter().enumerate() {
if (i % COLUMNS) == 0 {
crate::print!("\n\r{:08x}: ", addr + i * size_of::<u32>());
}
crate::print!("{:08x} ", d);
}
crate::println!("");
} else {
crate::println!("Peek address is in hex");
}
} else {
crate::println!("Help: peek <addr> [count], addr is in hex, count in decimal");
}
}
"poke" => {
if args.len() == 2 || args.len() == 3 {
if let Ok(addr) = u32::from_str_radix(&args[0], 16) {
if let Ok(value) = u32::from_str_radix(&args[1], 16) {
let count = if args.len() == 3 {
if let Ok(count) = u32::from_str_radix(&args[2], 10) { count } else { 1 }
} else {
1
};
// safety: it's not safe to do this, the user pokes at their own risk
let poke =
unsafe { core::slice::from_raw_parts_mut(addr as *mut u32, count as usize) };
for d in poke.iter_mut() {
*d = value;
}
crate::println!("Poked {:x} into {:x}, {} times", value, addr, count);
} else {
crate::println!("Poke value is in hex");
}
} else {
crate::println!("Poke address is in hex");
}
} else {
crate::println!(
"Help: poke <addr> <value> [count], addr/value is in hex, count in decimal"
);
}
}
#[cfg(feature = "cramium-soc")]
"rram" => {
if args.len() == 2 || args.len() == 3 {
if let Ok(addr) = usize::from_str_radix(&args[0], 16) {
if addr < utralib::HW_RERAM_MEM_LEN {
if let Ok(value) = u32::from_str_radix(&args[1], 16) {
let count = if args.len() == 3 {
if let Ok(count) = u32::from_str_radix(&args[2], 10) { count } else { 1 }
} else {
1
}
.min(utralib::HW_RRC_MEM_LEN as u32); // limit count to length of RRAM
let mut poke = Vec::new();
for _ in 0..count {
poke.push(value);
}
// safety: this is safe because all elements are valid between the two
// representations, there are no alignment
// issues downcasting to a u8, and the underlying representation
// is in fact the data we're hoping to access.
let poke_inner = unsafe {
core::slice::from_raw_parts(
poke.as_ptr() as *const u8,
poke.len() * core::mem::size_of::<u32>(),
)
};
let mut rram = cramium_hal::rram::Reram::new();
rram.write_slice(addr, poke_inner);
crate::println!("RRAM written {:x} into {:x}, {} times", value, addr, count);
} else {
crate::println!("RRAM value is in hex");
}
} else {
crate::println!(
"RRAM addresses are relative to base of RRAM, max 4M, and in hex"
);
}
} else {
crate::println!("RRAM address is in hex");
}
} else {
crate::println!(
"Help: rram <addr> <value> [count], addr/value is in hex, count in decimal"
);
}
}
#[cfg(feature = "cramium-soc")]
"bogomips" => {
crate::println!("start test");
// start the RTC
unsafe { (0x4006100c as *mut u32).write_volatile(1) };
let mut count: usize;
unsafe {
#[rustfmt::skip]
core::arch::asm!(
// grab the RTC value
"li t0, 0x40061000",
"lw t1, 0x0(t0)",
"li t3, 0",
// wait until the next second
"10:",
"lw t2, 0x0(t0)",
"beq t1, t2, 10b",
// start of test
"20:",
// count outer loops
"addi t3, t3, 1",
// inner loop 10,000 times
"li t4, 10000",
"30:",
"addi t4, t4, -1",
"bne x0, t4, 30b",
// after inner loop, check current time; do another outer loop if time is same
"lw t1, 0x0(t0)",
"beq t1, t2, 20b",
out("t0") _,
out("t1") _,
out("t2") _,
out("t3") count,
out("t4") _,
);
}
crate::println!("{}.{} bogomips", (count * 2 * 10_000) / 1_000_000, (count * 2) % 10_000);
crate::platform::setup_timer();
}
"echo" => {
for word in args {
crate::print!("{} ", word);
@ -248,8 +388,13 @@ impl Repl {
"" => {}
_ => {
crate::println!("Command not recognized: '{}'", cmd);
crate::println!("Type 'help' for a list of commands.");
crate::println!("Command not recognized: {}", cmd);
crate::print!("Commands include: echo, poke, peek, bogomips");
#[cfg(feature = "cramium-soc")]
crate::print!(", rram");
#[cfg(not(feature = "cramium-soc"))]
crate::print!(", mon");
crate::println!("");
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 101 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 162 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

View file

@ -30,3 +30,21 @@ pub mod usb;
pub use shared_csr::*;
#[cfg(not(feature = "hosted-baosec"))]
pub mod mbox;
#[cfg(not(feature = "hosted-baosec"))]
pub mod rram;
#[inline(always)]
pub fn cache_flush() {
unsafe {
// cache flush
#[rustfmt::skip]
core::arch::asm!(
"fence.i",
".word 0x500F",
"nop",
"nop",
"nop",
"nop",
);
}
}

View file

@ -0,0 +1,139 @@
use utralib::{CSR, utra};
pub struct Reram {
csr: CSR<u32>,
array: &'static mut [u32],
}
/// Matches the alignment requirement of the RRC write buffer
const ALIGNMENT: usize = 32;
#[repr(align(4))]
struct AlignedBuffer([u8; ALIGNMENT]);
impl AlignedBuffer {
pub fn as_slice_u32(&self) -> &[u32] {
// safety: this is safe because the #repr(align) ensures that our alignment is correct,
// and the length of the internal data structure is set correctly by design. Furthermore,
// all values in both the source and destination transmutation are representable and valid.
unsafe { core::slice::from_raw_parts(self.0.as_ptr() as *const u32, self.0.len() / 4) }
}
}
/// This is the code that enables the security modes. Must be written into
/// RRCR on every update - kind of dangerous design, because it is too easy
/// to overlook setting this in a compound register.
const SECURITY_MODE: u32 = 0b1111_1100_0000_0000;
const RRC_LOAD_BUFFER: u32 = 0x5200;
const RRC_WRITE_BUFFER: u32 = 0x9528;
const RRC_CR_NORMAL: u32 = 0;
#[allow(dead_code)]
const RRC_CR_POWERDOWN: u32 = 1;
#[allow(dead_code)]
const RRC_CR_WRITE_DATA: u32 = 0;
const RRC_CR_WRITE_CMD: u32 = 2;
impl Reram {
pub fn new() -> Self {
Reram {
csr: CSR::new(utra::rrc::HW_RRC_BASE as *mut u32),
array: unsafe {
core::slice::from_raw_parts_mut(
utralib::HW_RERAM_MEM as *mut u32,
utralib::HW_RERAM_MEM_LEN / core::mem::size_of::<u32>(),
)
},
}
}
pub fn read_slice(&self) -> &[u32] { self.array }
/// This is a crappy "unsafe" initial version that requires the write
/// destination address to be aligned to a 256-bit boundary, and the data
/// to be exactly 256 bits long.
pub unsafe fn write_u32_aligned(&mut self, addr: usize, data: &[u32]) {
assert!(addr % 0x20 == 0, "unaligned destination address!");
assert!(data.len() % 8 == 0, "unaligned source data!");
// crate::print!("@ {:x} > ", addr);
for (outer, d) in data.chunks_exact(8).enumerate() {
// write the data to the buffer
for (inner, &datum) in d.iter().enumerate() {
// crate::print!(" {:x}", datum);
self.array
.as_mut_ptr()
.add(addr / core::mem::size_of::<u32>() + outer * 8 + inner)
.write_volatile(datum);
core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
}
// crate::println!("");
self.csr.rmwf(utra::rrc::SFR_RRCCR_SFR_RRCCR, RRC_CR_WRITE_CMD | SECURITY_MODE);
self.array
.as_mut_ptr()
.add(addr / core::mem::size_of::<u32>() + outer * 8)
.write_volatile(RRC_LOAD_BUFFER);
core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
self.array
.as_mut_ptr()
.add(addr / core::mem::size_of::<u32>() + outer * 8)
.write_volatile(RRC_WRITE_BUFFER);
core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
self.csr.rmwf(utra::rrc::SFR_RRCCR_SFR_RRCCR, RRC_CR_NORMAL | SECURITY_MODE);
}
crate::cache_flush();
}
/// This is a general unaligned write primitive for the RRAM that can handle any length
/// slice and alignment of data.
pub fn write_slice(&mut self, offset: usize, data: &[u8]) {
let mut buffer = AlignedBuffer([0u8; ALIGNMENT]);
// ragged start
let start_len = ALIGNMENT - (offset % ALIGNMENT);
if start_len != 0 {
let start_offset = offset & !(ALIGNMENT - 1);
let dest_slice = unsafe {
core::slice::from_raw_parts(
(start_offset + utralib::HW_RERAM_MEM) as *const u8,
buffer.0.len(),
)
};
// populate from old data first
buffer.0.copy_from_slice(&dest_slice);
buffer.0[offset % ALIGNMENT..].copy_from_slice(&data[..start_len]);
// safe because alignment and buffer sizes are guaranteed
unsafe {
self.write_u32_aligned(start_offset, buffer.as_slice_u32());
}
}
// aligned middle & end
let mut cur_offset = offset + start_len;
if data.len() - start_len > 0 {
for chunk in data[start_len..].chunks(buffer.0.len()) {
// full chunk
if chunk.len() == buffer.0.len() {
buffer.0.copy_from_slice(&chunk);
// safe because alignment and buffer sizes are guaranteed
unsafe {
self.write_u32_aligned(cur_offset, &buffer.as_slice_u32());
}
} else {
let dest_slice = unsafe {
core::slice::from_raw_parts(
(cur_offset + utralib::HW_RERAM_MEM) as *const u8,
buffer.0.len(),
)
};
// read in the destination full contents
buffer.0.copy_from_slice(&dest_slice);
// now overwrite the "ragged end"
buffer.0[..chunk.len()].copy_from_slice(&chunk);
// safe because alignment and buffer sizes are guaranteed
unsafe {
self.write_u32_aligned(cur_offset, &buffer.as_slice_u32());
}
}
cur_offset += chunk.len();
}
}
}
}

View file

@ -1353,24 +1353,3 @@ impl Spim {
true
}
}
// Stub retained because it is helpful for debugging some bus contention issues.
#[allow(dead_code)]
fn cache_flush() {
unsafe {
// let the write go through before continuing
#[rustfmt::skip]
core::arch::asm!(
".word 0x500F",
"nop",
"nop",
"nop",
"nop",
"fence",
"nop",
"nop",
"nop",
"nop",
);
}
}

View file

@ -361,7 +361,7 @@ pub fn process_update(perclk: u32) {
};
}
progress_bar(&mut sh1107, 100);
cache_flush();
cramium_hal::cache_flush();
crate::println!(
"data after: {:x?} .. {:x?}",
&check_slice[..32],
@ -621,18 +621,3 @@ pub fn write_rram(mbox: &mut Mbox, data: &[u32]) -> Result<usize, MboxError> {
}
}
}
#[inline(always)]
fn cache_flush() {
unsafe {
#[rustfmt::skip]
core::arch::asm!(
".word 0x500F",
"nop",
"nop",
"nop",
"nop",
"nop",
);
}
}

View file

@ -340,7 +340,7 @@ impl<'a> ShellCmdApi<'a> for Mbox {
.ok();
} else {
log::info!("Wrote {} bytes", rx_pkt.data[0]);
cache_flush();
cramium_hal::cache_flush();
let flash_slice: &[u8] = unsafe { self.flash_window.as_slice() };
log::info!("Data values before writing: {:x?}", &orig_data[..16]);
log::info!("Data values after writing: {:x?}", &flash_slice[..16]);
@ -516,18 +516,3 @@ impl<'a> ShellCmdApi<'a> for Mbox {
Ok(Some(ret))
}
}
#[inline(always)]
fn cache_flush() {
unsafe {
#[rustfmt::skip]
core::arch::asm!(
".word 0x500F",
"nop",
"nop",
"nop",
"nop",
"nop",
);
}
}

View file

@ -413,6 +413,19 @@ impl Builder {
self
}
/// Configure for baremetal bringup
pub fn target_baremetal_cramsoc(&mut self) -> &mut Builder {
self.target = Some(crate::TARGET_TRIPLE_RISCV32.to_string());
self.target_kernel = Some(crate::TARGET_TRIPLE_RISCV32_KERNEL.to_string());
self.stream = BuildStream::Release;
self.utra_target = "cramium-soc".to_string();
self.run_svd2repl = false;
self.loader = CrateSpec::Local("baremetal".to_string(), LoaderRegion::Ram);
// this is actually a dummy, there is no kernel in baremetal
self.kernel = CrateSpec::Local("xous-kernel".to_string(), LoaderRegion::Ram);
self
}
/// Override the default kernel. For example, to use the kernel from crates.io, specify as
/// "xous-kernel@0.9.9"
#[allow(dead_code)]

View file

@ -647,6 +647,11 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
builder.target_artyvexii();
}
Some("baremetal-cramsoc") => {
builder.set_baremetal(true);
builder.target_baremetal_cramsoc();
}
Some("baosec") => {
let board = "board-baosec";
// select the board