diff --git a/Cargo.lock b/Cargo.lock index a9f6e17c7..8abc8206b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -868,10 +868,12 @@ dependencies = [ "log-server", "num-derive", "num-traits", + "rkyv 0.4.3", "susres", "ticktimer-server", "utralib", "xous", + "xous-ipc", "xous-names", ] @@ -1449,6 +1451,7 @@ dependencies = [ "aes-xous", "blowfish", "cipher", + "com", "curve25519-dalek", "digest", "ed25519-dalek", @@ -1457,6 +1460,7 @@ dependencies = [ "graphics-server", "hex", "jtag", + "llio", "locales", "log", "log-server", @@ -1464,6 +1468,7 @@ dependencies = [ "num-traits", "rand_core 0.5.1", "rkyv 0.4.3", + "rtc", "sha2", "spinor", "susres", diff --git a/services/jtag/Cargo.toml b/services/jtag/Cargo.toml new file mode 100644 index 000000000..01bc89771 --- /dev/null +++ b/services/jtag/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "jtag" +version = "0.1.0" +authors = ["bunnie "] +edition = "2018" +description = "JTAG port server" + +[dependencies] +xous = { path = "../../xous-rs" } +log-server = { path = "../log-server" } +ticktimer-server = { path = "../ticktimer-server" } +xous-names = { path = "../xous-names" } +log = "0.4" +num-derive = {version = "0.3", default-features = false} +num-traits = {version = "0.2", default-features = false} +susres = {path = "../susres"} + +xous-ipc = {path = "../../xous-ipc"} +rkyv = {version = "0.4.3", default-features = false, features = ["const_generics"]} + +[target.'cfg(not(any(windows,unix)))'.dependencies] +utralib = { path = "../../utralib"} + +[features] +hazardous-debug = [] +default = ["hazardous-debug"] diff --git a/services/jtag/src/api.rs b/services/jtag/src/api.rs new file mode 100644 index 000000000..e5f2ae2dc --- /dev/null +++ b/services/jtag/src/api.rs @@ -0,0 +1,25 @@ +pub(crate) const SERVER_NAME_JTAG: &str = "_JTAG Server_"; + +#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] +pub struct EfuseRecord { + pub key: [u8; 32], + pub user: u32, + pub cntl: u8, +} + +#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] +pub enum EfuseResult { + Success, + Failure, +} + +#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] +pub(crate) enum Opcode { + GetId, + GetDna, + EfuseFetch, + EfuseKeyBurn, + EfuseUserBurn, + EfuseCtlBurn, + WriteIr, +} diff --git a/services/jtag/src/efuse_api.rs b/services/jtag/src/efuse_api.rs new file mode 100644 index 000000000..46567597f --- /dev/null +++ b/services/jtag/src/efuse_api.rs @@ -0,0 +1,386 @@ +/// efuse API for 7-series FPGAs +/// +/// There are three fuse types to burn: USER, KEY, and CNTL +/// +/// USER and KEY fuses share a similar ECC structure ,and in fact, the USER fuses partially +/// share a fuse bank with the KEY. +/// +/// CNTL fuses are unique in that instead of having ECC, each fuse has two copies, and are burned +/// in duplicate for reliability. +/// +/// Fuses are write-once. It's also not possible within the documented command set to read out the +/// raw fuse values once burned -- they can only be implied through a set of readback calls. +/// This means the fuse life cycle looks like this: +/// * Initial, unprogrammed factory state is all 0's +/// * USER/KEY data is coded by blowing only the 1's. An ECC code must also be blown simultaneously +/// to match the final pattern of 1's for correct readout +/// * It seems that patches to fuses can be done, so long as it only involves changing 0->1 and results +/// in a valid state after ECC is factored in. This is especially true for data values striped across +/// multiple banks. +/// +/// Patching support may be particularly valuable in the case that e.g. anti-rollback fusing is desired. +/// +/// This API implements the following features: +/// * retrieve the current fuse state +/// * validate if a proposed state change results in a valid operation (only 0->1 including ECC mods) +/// * perform the actual burn operation +/// +/// In order to represent the fusing structure more accurately, this module models the state of fuses +/// not by their logical function, but by their physical mapping into the bank. There is then a layer +/// of code that can convert the physical bank information into the logical view. Validation code thus +/// works with a set of calls that can validate bank-by-bank, which are then called by the meta-functions +/// which will implement the logical KEY/USER/CNTL requests. +/// + +use crate::efuse_ecc::efuse_ecc::*; +use crate::{JtagMach, JtagChain, JtagEndian, JtagLeg}; + +/// There are 13 banks of fuses, 12 of which (key/user) are "hamming" ECC, 1 of which (config) is "dup" ECC. +pub struct EfusePhy { + banks: [u32; 13], + key: [u8; 32], + user: u32, + cntl: u8, +} + +const FUSE_BANKS: usize = 13; +const KEY_BANKS: usize = 11; +const CMD_FUSE_USER: u32 = 0b110011; +const CMD_FUSE_KEY: u32 = 0b110001; +const CMD_FUSE_CNTL: u32 = 0b110100; + +impl EfusePhy { + pub fn new() -> Self { + EfusePhy { + /// bank mapping as follows: + /// 0 - config + /// 1-11 - key (11 shared with user LSB) + /// 12 - user + banks: [0; FUSE_BANKS], + key: [0; 32], + user: 0, + cntl: 0, + } + } + + pub fn user(&self) -> u32 { self.user } + pub fn cntl(&self) -> u8 { self.cntl } + pub fn key(&self) -> [u8; 32] { self.key } + + /// this is a TEST FUNCTION ONLY. Unfortunately, the Rust test directive does not + /// like this no_std runtime / std test environment. + pub fn bank_patch(&mut self, index: usize, data: u32) { // this is just for test routines + self.banks[index] = data; + // re-derive key bits from bank data + for i in 0..32 { + self.key[i] = ((self.banks[((i / 3) + 1) as usize] >> ((i % 3) * 8)) & 0xFF) as u8; + } + } + + /// fetch the current fuse state + pub fn fetch(&mut self, jm: &mut JtagMach) { + jm.reset(); + + // get the KEY fuse + jm.pause(2000); + let mut ir_leg: JtagLeg = JtagLeg::new(JtagChain::IR, "cmd"); + ir_leg.push_u32(CMD_FUSE_KEY, 6, JtagEndian::Little); + jm.add(ir_leg); + jm.next(); + assert!(jm.get().is_some()); + + let mut data_leg: JtagLeg = JtagLeg::new(JtagChain::DR, "fuse"); + data_leg.push_u128(0, 128, JtagEndian::Big); + data_leg.push_u128(0, 128, JtagEndian::Big); + jm.add(data_leg); + jm.next(); + if let Some(mut data) = jm.get() { + let mut bank_data: u32; + for index in 0..KEY_BANKS { + if index == 0 { + // first bank is special because it's split with the user fuse + bank_data = data.pop_u32(16, JtagEndian::Little).unwrap(); + self.banks[11-index] = bank_data; + } else { + bank_data = data.pop_u32(24, JtagEndian::Little).unwrap(); + self.banks[11-index] = add_ecc(bank_data); + } + } + } else { + assert!(false); + } + // derive bits from bank data, to debug any bit-order issues on readout, etc. + for index in 0..32 { + self.key[index] = ((self.banks[((index / 3) + 1) as usize] >> ((index % 3) * 8)) & 0xFF) as u8; + } + + jm.pause(2000); + // get the USER fuse and populate the split bank + let mut ir_leg: JtagLeg = JtagLeg::new(JtagChain::IR, "cmd"); + ir_leg.push_u32(CMD_FUSE_USER, 6, JtagEndian::Little); + jm.add(ir_leg); + jm.next(); + assert!(jm.get().is_some()); + + let mut data_leg: JtagLeg = JtagLeg::new(JtagChain::DR, "user"); + data_leg.push_u32(0, 32, JtagEndian::Little); + jm.add(data_leg); + jm.next(); + if let Some(mut data) = jm.get() { + let user_data: u32 = data.pop_u32(32, JtagEndian::Little).unwrap(); + self.user = user_data; + self.banks[11] |= (user_data & 0xFF) << 16; + self.banks[11] = add_ecc(self.banks[11]); + + self.banks[12] = add_ecc( (user_data >> 8) & 0xFF_FF_FF); + } else { + assert!(false); + } + + jm.pause(2000); + // get the CNTL fuse + let mut ir_leg: JtagLeg = JtagLeg::new(JtagChain::IR, "cmd"); + ir_leg.push_u32(CMD_FUSE_CNTL, 6, JtagEndian::Little); + jm.add(ir_leg); + jm.next(); + assert!(jm.get().is_some()); + + let mut data_leg: JtagLeg = JtagLeg::new(JtagChain::DR, "cntl"); + data_leg.push_u32(0, 14, JtagEndian::Little); // cntl only has 14 bits length, but only bottom 6 bits are documented + jm.add(data_leg); + jm.next(); + if let Some(mut data) = jm.get() { + let cntl_data: u32 = data.pop_u32(14, JtagEndian::Little).unwrap(); + self.cntl = (cntl_data & 0x3F) as u8; + self.banks[0] = cntl_data & 0x3F; + self.banks[0] |= (cntl_data & 0x3F) << 14; // ths is the redundant value, no ECC on this bank + } else { + assert!(false); + } + } +} + +pub struct EfuseApi { + key: [u8; 32], + user: u32, + cntl: u8, + phy: EfusePhy, +} + +impl EfuseApi { + pub fn new() -> Self { + EfuseApi { + key: [0; 32], + user: 0, + cntl: 0, + phy: EfusePhy::new(), + } + } + /// phy_ series of calls returns the current "phy" state, that is, the actual programmed state + pub fn phy_key(&self) -> [u8; 32] { self.phy.key() } + pub fn phy_user(&self) -> u32 { self.phy.user() } + pub fn phy_cntl(&self) -> u8 { self.phy.cntl() } + + /// api_ series of call returns the current "api" state, which is the intended state to be programmed if not yet programmed + #[allow(dead_code)] + pub fn api_key(&self) -> [u8; 32] { self.key } + #[allow(dead_code)] + pub fn api_user(&self) -> u32 { self.user } + #[allow(dead_code)] + pub fn api_cntl(&self) -> u8 { self.cntl } + + /// this is a TEST FUNCTION ONLY. Unfortunately, the Rust test directive does not + /// like this no_std runtime / std test environment. + #[allow(dead_code)] + pub fn bank_patch(&mut self, index: usize, data: u32) { self.phy.bank_patch(index, data); } + + // synchronizes the API state with the hardware. Needs to be called first. + pub fn fetch(&mut self, jm: &mut JtagMach) { + self.phy.fetch(jm); + } + + pub fn set_key(&mut self, new_key: [u8; 32]) { + for i in 0..32 { + self.key[i] = new_key[i]; + } + } + pub fn set_user(&mut self, new_user: u32) { self.user = new_user; } + pub fn set_cntl(&mut self, new_cntl: u8) { self.cntl = new_cntl; } + + pub fn is_valid(&mut self) -> bool { + let mut valid: bool = true; + + // go through each bank and check if the current configuratiion only involves 0->1 flips or no change + for index in 0..KEY_BANKS { + if index == 0 { + // handle cntl special case + if ((self.phy.banks[0] & 0x3F) as u8 ^ self.cntl) & (self.phy.banks[0] & 0x3F) as u8 != 0 { + valid = false; + } + } else if index == 12 { + // handle user special case + if ((self.phy.banks[index] ^ add_ecc(self.user >> 8)) & self.phy.banks[index]) != 0 { + valid = false; + } + } else if index == 11 { + // handle user + key special case + let raw_fuse: u32 = ((self.user & 0xFF) << 16) | (self.key[31] as u32) << 8 | self.key[30] as u32; + if ((self.phy.banks[index] ^ add_ecc(raw_fuse)) & self.phy.banks[index]) != 0 { + valid = false; + } + } else { + // handle key fuses (most of the bank) + let mut raw_fuse: u32 = 0; + for i in 0..3 { + raw_fuse <<= 8; + raw_fuse |= self.key[(index-1)*3 + 2-i] as u32; + } + if ((self.phy.banks[index] ^ add_ecc(raw_fuse)) & self.phy.banks[index]) != 0 { + valid = false; + } + } + } + valid + } + + fn jtag_seq(&mut self, jm: &mut JtagMach, cmds: &[(JtagChain, usize, u64, &str)] ) -> u128 { + let mut ret: u128 = 0; + + for tuple in cmds.iter() { + let (chain, count, value, comment) = *tuple; + let mut leg: JtagLeg = JtagLeg::new(chain, comment); + leg.push_u128(value as u128, count, JtagEndian::Little); + jm.add(leg); + } + while jm.has_pending() { + jm.pause(200); // 200us pause before starting a new series of commands + jm.next(); + if let Some(mut data) = jm.get() { + // it's safe to just pop the "max length" because pop is "best effort only" + ret = data.pop_u128(128, JtagEndian::Little).unwrap(); + } + } + // only the very last sequence value is returned + ret + } + + fn burn_bank(&mut self, bank: usize, ones: u32, jm: &mut JtagMach) { + if ones == 0 { // skip the bank if nothing to burn + return; + } + jm.pause(2500); // 2.5ms pause between banks + + let mut bank_select: u8 = 1; // bank 0 by default (special case) + let mut word_select: u8 = 3; + if bank > 0 { // rest of banks + bank_select = (bank as u8 - 1) * 8 + 0xA1; + word_select = bank_select | 0b10; + } + + let bank_fuse: [(JtagChain, usize, u64, &str); 7] = [ + (JtagChain::IR, 6, 0b001100, "JSTART"), + (JtagChain::IR, 6, 0b110000, "EFUSE"), + (JtagChain::DR, 64, 0xa08a28ac00004001, "KEY_UNLOCK1"), + (JtagChain::DR, 64, 0xa08a28ac00004001, "KEY_UNLOCK2"), + (JtagChain::IR, 6, 0b110000, "EFUSE"), + (JtagChain::DR, 64, 0xa08a28ac00000000 | bank_select as u64, "KEY_BANK"), + (JtagChain::DR, 64, 0x0, "KEY_BANK_WAIT"), + ]; + self.jtag_seq(jm, &bank_fuse); + let mut curbit = ones; + for i in 0..32 { + if (curbit & 0x1) == 1 { + let bit_burn: [(JtagChain, usize, u64, &str); 3] = [ + (JtagChain::IR, 6, 0b110000, "EFUSE"), + (JtagChain::DR, 64, (0xa08a28ac00004000 | (word_select as u64)) + ((i as u64) << 8), "KEY_BIT"), + (JtagChain::DR, 64, 0x0, "KEY_BIT_WAIT"), + ]; + self.jtag_seq(jm, &bit_burn); + } + curbit >>= 1; + } + self.jtag_seq(jm, &bank_fuse); + } + + // burns fuses to the FPGA bank + pub fn burn(&mut self, jm: &mut JtagMach) -> bool { + const COMMIT_SEQ: [(JtagChain, usize, u64, &str); 22] = + [ + (JtagChain::DR, 64, 0xff000000ff, "EFUSE_COMMIT"), + (JtagChain::IR, 6, 0b000010, "USER1"), + (JtagChain::DR, 32, 0, "USER1"), + (JtagChain::IR, 6, 0b000010, "USER1"), + (JtagChain::DR, 17, 0xF000, "USER1"), + (JtagChain::DR, 75, 0xA9, "USER1"), + (JtagChain::IR, 6, 0b100010, "USER3"), + (JtagChain::DR, 17, 0xF000, "USER3"), + (JtagChain::DR, 75, 0xA9, "USER3"), + (JtagChain::IR, 6, 0b111111, "BYPASS"), + (JtagChain::IR, 6, 0b000011, "USER2"), + (JtagChain::DR, 32, 0x0, "USER2"), + (JtagChain::IR, 6, 0b111111, "BYPASS"), + (JtagChain::IR, 6, 0b000011, "USER2"), + (JtagChain::DR, 42, 0x69, "USER2"), + (JtagChain::IR, 6, 0b111111, "BYPASS"), + (JtagChain::IR, 6, 0b000011, "USER2"), + (JtagChain::DR, 6, 0xC, "USER2"), + (JtagChain::DR, 42, 0x69, "USER2"), + (JtagChain::IR, 6, 0b111111, "BYPASS"), + (JtagChain::IR, 6, 0b000011, "USER2"), + (JtagChain::DR, 36, 0x0, "USER2"), + ]; + + let ok: bool = true; + + // first check if we're valid + if !self.is_valid() { + return false; + } + + // reset the machine before doing any burning + jm.pause(2000); + jm.reset(); + jm.pause(2000); + + // iterate through banks, careful to make bank 0 the last + for index in (0..FUSE_BANKS).rev() { + if index == 0 { + // handle cntl special case + if ((self.phy.banks[0] & 0x3F) as u8 ^ self.cntl) != 0 { + // 1111_1100_0000_0011_1111 + let new_cntl: u32 = (self.cntl as u32) | ((self.cntl as u32) << 14); + self.burn_bank(index, ((self.phy.banks[0] & 0xFC03F) ^ new_cntl) & new_cntl, jm); + } + } else if index == 12 { + // handle user special case + if (self.phy.banks[index] ^ add_ecc(self.user >> 8)) != 0 { + // compute just the 0->1's and pass that on to burn_bank + self.burn_bank(index, self.phy.banks[index] ^ add_ecc(self.user >> 8) & add_ecc(self.user >> 8), jm); + } + } else if index == 11 { + // handle user + key special case + let raw_fuse: u32 = ((self.user & 0xFF) << 16) | (self.key[31] as u32) << 8 | self.key[30] as u32; + if (self.phy.banks[index] ^ add_ecc(raw_fuse)) != 0 { + self.burn_bank(index, (self.phy.banks[index] ^ add_ecc(raw_fuse)) & add_ecc(raw_fuse), jm); + } + } else { + // handle key fuses (most of the bank) + let mut raw_fuse: u32 = 0; + for i in 0..3 { + raw_fuse <<= 8; + raw_fuse |= self.key[(index-1)*3 + 2-i] as u32; + } + if (self.phy.banks[index] ^ add_ecc(raw_fuse)) != 0 { + self.burn_bank(index, (self.phy.banks[index] ^ add_ecc(raw_fuse)) & add_ecc(raw_fuse), jm); + } + } + + } + jm.pause(2000); + self.jtag_seq(jm, &COMMIT_SEQ); + jm.pause(2000); + jm.reset(); + ok + } + +} diff --git a/services/jtag/src/efuse_ecc.rs b/services/jtag/src/efuse_ecc.rs new file mode 100644 index 000000000..0fa191b4d --- /dev/null +++ b/services/jtag/src/efuse_ecc.rs @@ -0,0 +1,63 @@ +pub mod efuse_ecc { + /// given an unprotected 24-bit data record, return + /// a number which is the data + its 6-bit ECC code + pub fn add_ecc(data: u32) -> u32 { + assert!(data & 0xFF00_0000 == 0); // if the top 8 bits are filled in, that's an error + const GENERATOR: [u32; 6] = [16_515_312, 14_911_249, 10_180_898, 5_696_068, 3_011_720, 16_777_215]; + + let mut code: u32 = 0; + + for (i, gen) in GENERATOR.iter().enumerate() { + let mut parity: u32 = 0; + for bit in 0..24 { + parity ^= ((gen & data) >> bit) & 0x1; + } + code ^= parity << i; + } + + if (code & 0x20) != 0 { + code = (!code & 0x1F) | 0x20; + } + + let secded = ((((code >> 5) ^ (code >> 4) ^ (code >> 3) ^ (code >> 2) ^ (code >> 1) ^ code) & 0x1) << 5) | code; + + data | secded << 24 + } +} + +// run with `cargo test --target x86_64-unknown-linux-gnu` +#[cfg(test)] +mod tests { + use crate::efuse_ecc::*; + + #[test] + fn it_works() { + assert_eq!(2 + 2, 4); + } + + #[test] + fn vectors() { + const V: [(u32, u32); 7] = [ + (0x00_FFFFFD, 0x25_FFFFFD), + (0x00_00A003, 0x24_00A003), + (0x00_00A00A, 0x36_00A00A), + (0x00_00F00A, 0x1E_00F00A), + (0x00_00F00F, 0x14_00F00F), + (0x00_00B00F, 0x37_00B00F), + (0x00_C5B000, 0x2A_C5B000), + ]; + + for i in &V { + assert_eq!(i.1, add_ecc(i.0)); + } + } + + #[test] + fn gen_test() { + assert_eq!(0x2708_63C1, add_ecc(0x8_63C1)); + assert_eq!(0x2C02_A541, add_ecc(0x2_A541)); + assert_eq!(0x00CC_ABCD, add_ecc(0xCC_ABCD)); + assert_eq!(0x03C6_DEF0, add_ecc(0xC6_DEF0)); + assert_eq!(0x3944_EEEE, add_ecc(0x44_EEEE)); + } +} diff --git a/services/jtag/src/lib.rs b/services/jtag/src/lib.rs new file mode 100644 index 000000000..9166d1e39 --- /dev/null +++ b/services/jtag/src/lib.rs @@ -0,0 +1,151 @@ +#![cfg_attr(target_os = "none", no_std)] + +pub mod api; +pub use api::*; +use xous::{CID, send_message, Message}; +use xous_ipc::Buffer; +use num_traits::*; + +#[derive(Debug)] +pub struct Jtag { + conn: CID, +} +impl Jtag { + pub fn new(xns: &xous_names::XousNames) -> Result { + REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) + 1, Ordering::Relaxed); + let conn = xns.request_connection_blocking(api::SERVER_NAME_JTAG).expect("Can't connect to JTAG server"); + Ok(Jtag { + conn + }) + } + + pub fn get_id(&self) -> Result { + let response = send_message(self.conn, + Message::new_blocking_scalar(Opcode::GetId.to_usize().unwrap(), 0, 0, 0, 0) + ).expect("can't issue get_id message"); + if let xous::Result::Scalar1(id)= response { + Ok(id as u32) + } else { + Err(xous::Error::InternalError) + } + } + pub fn get_dna(&self) -> Result { + let response = send_message(self.conn, + Message::new_blocking_scalar(Opcode::GetDna.to_usize().unwrap(), 0, 0, 0, 0) + ).expect("can't issue get_id message"); + if let xous::Result::Scalar2(v1, v2)= response { + Ok(((v1 as u64) << 32) | v2 as u64) + } else { + Err(xous::Error::InternalError) + } + } + pub fn efuse_fetch(&self) -> Result { + let xmit = EfuseRecord { + key: [0; 32], + user: 0, + cntl: 0, + }; + let mut buf = Buffer::into_buf(xmit).or(Err(xous::Error::InternalError))?; + buf.lend_mut(self.conn, Opcode::EfuseFetch.to_u32().unwrap()).or(Err(xous::Error::InternalError))?; + + buf.to_original::().or(Err(xous::Error::InternalError)) + } + pub fn write_ir(&self, ir: u8) -> Result<(), xous::Error> { + send_message(self.conn, + Message::new_scalar(Opcode::WriteIr.to_usize().unwrap(), ir as usize, 0, 0, 0) + ).map(|_| ()) + } + pub fn efuse_key_burn(&self, key: [u8; 32]) -> Result { + let mut buf = Buffer::into_buf(key).or(Err(xous::Error::InternalError))?; + buf.lend_mut(self.conn, Opcode::EfuseKeyBurn.to_u32().unwrap()).or(Err(xous::Error::InternalError))?; + match buf.to_original().unwrap() { + EfuseResult::Success => Ok(true), + EfuseResult::Failure => Ok(false), + } + } + pub fn efuse_user_burn(&self, user: u32) -> Result { + let response = send_message(self.conn, + Message::new_blocking_scalar(Opcode::EfuseUserBurn.to_usize().unwrap(), user as usize, 0, 0, 0) + ).expect("can't fetch user value"); + if let xous::Result::Scalar1(res) = response { + if res == 0 { + Ok(false) + } else { + Ok(true) + } + } else { + Err(xous::Error::InternalError) + } + } + pub fn is_efuse_only_boot(&self) -> Result { + let erec = self.efuse_fetch().expect("couldn't read efuse record"); + if (erec.cntl & 0x1) != 0 { Ok(true) } else { Ok(false) } + } + pub fn is_disable_jtag(&self) -> Result { + let erec = self.efuse_fetch().expect("couldn't read efuse record"); + if (erec.cntl & 0x2) != 0 { Ok(true) } else { Ok(false) } + } + pub fn is_efuse_writeable(&self) -> Result { + let erec = self.efuse_fetch().expect("couldn't read efuse record"); + if (erec.cntl & 0x4) != 0 { Ok(true) } else { Ok(false) } + } + pub fn is_key_access_protected(&self) -> Result { + let erec = self.efuse_fetch().expect("couldn't read efuse record"); + if (erec.cntl & 0x8) != 0 { Ok(true) } else { Ok(false) } + } + pub fn is_user_and_key_access_protected(&self) -> Result { + let erec = self.efuse_fetch().expect("couldn't read efuse record"); + if (erec.cntl & 0x10) != 0 { Ok(true) } else { Ok(false) } + } + pub fn is_control_write_protected(&self) -> Result { + let erec = self.efuse_fetch().expect("couldn't read efuse record"); + if (erec.cntl & 0x20) != 0 { Ok(true) } else { Ok(false) } + } + fn mod_ctl_efuse(&self, bits_to_set: u8) -> Result { + let erec = self.efuse_fetch().expect("couldn't read efuse record"); + let response = send_message(self.conn, + Message::new_blocking_scalar(Opcode::EfuseCtlBurn.to_usize().unwrap(), (erec.cntl | bits_to_set) as usize, 0, 0, 0) + ).expect("can't issue config burn message"); + if let xous::Result::Scalar1(r)= response { + if r != 0 { Ok(true) } else { Ok(false) } + } else { + Err(xous::Error::InternalError) + } + } + pub fn burn_efuse_only_boot(&self) -> Result { + self.mod_ctl_efuse(0x1) + } + pub fn burn_disable_jtag(&self) -> Result { + self.mod_ctl_efuse(0x2) + } + pub fn burn_efuse_write_protect(&self) -> Result { + self.mod_ctl_efuse(0x4) + } + pub fn burn_key_access_protect(&self) -> Result { + self.mod_ctl_efuse(0x8) + } + pub fn burn_user_and_key_access_protect(&self) -> Result { + self.mod_ctl_efuse(0x10) + } + pub fn burn_control_write_protect(&self) -> Result { + self.mod_ctl_efuse(0x20) + } + pub fn seal_device_forever(&self) -> Result { + self.mod_ctl_efuse(0x3F) + } +} + +use core::sync::atomic::{AtomicU32, Ordering}; +static REFCOUNT: AtomicU32 = AtomicU32::new(0); +impl Drop for Jtag { + fn drop(&mut self) { + // the connection to the server side must be reference counted, so that multiple instances of this object within + // a single process do not end up de-allocating the CID on other threads before they go out of scope. + // Note to future me: you want this. Don't get rid of it because you think, "nah, nobody will ever make more than one copy of this object". + if REFCOUNT.load(Ordering::Relaxed) == 0 { + unsafe{xous::disconnect(self.conn).unwrap();} + } + // if there was object-specific state (such as a one-time use server for async callbacks, specific to the object instance), + // de-allocate those items here. They don't need a reference count because they are object-specific + } +} \ No newline at end of file diff --git a/services/jtag/src/main.rs b/services/jtag/src/main.rs new file mode 100644 index 000000000..da7083909 --- /dev/null +++ b/services/jtag/src/main.rs @@ -0,0 +1,659 @@ +#![cfg_attr(target_os = "none", no_std)] +#![cfg_attr(target_os = "none", no_main)] + +mod api; +mod efuse_api; +mod efuse_ecc; + +use api::*; +use num_traits::*; +use xous::{msg_blocking_scalar_unpack, msg_scalar_unpack}; +use xous_ipc::Buffer; +use efuse_api::*; +use crate::implementation::JtagPhy; + +pub enum JtagState { + TestReset, + RunIdle, + Select, + Capture, + Shift, + Exit1, + Pause, + Exit2, + Update, +} + +#[derive(Copy, Clone)] +pub enum JtagChain { + DR, + IR, +} + +pub enum JtagEndian { + Big, // MSB-first shiftout + Little // LSB-first shiftout +} + +/// option 1: make a "leg" machine that contains the shift-in/shift-out records specific to each leg +/// option 2: make a comprehensive machine that receives meta-commands to transition between states +/// +/// I think we want a machine that has a Vector which holds a set of instructions that encapsulate either +/// data to send into the IR or DR. There should be a state bit that indicates if the data has been +/// executed; after execution, there is a result vector that is now valid. +/// +#[derive(Clone)] +pub struct JtagLeg { + /// which chain (DR or IR) + c: JtagChain, + /// output bit vector to device; chain length is defined by vector length + o: Vec, + /// input bit vector from device; length is dynamically allocated as leg traverses + i: Vec, + /// a tag for the leg, to be used by higher level logic to track pending/done entries + tag: String, +} + +impl JtagLeg { + pub fn new(chain_type: JtagChain, mytag: &str) -> Self { + JtagLeg { + c: chain_type, + o: Vec::new(), + i: Vec::new(), + tag: String::from(mytag), + } + } + + /// `push` will take data in the form of an unsigned int (either u128 or u32) + /// and append it to the JTAG input vector in preparation for sending. + /// "count" specifies the number of bits of the vector that are valid, and + /// "endian" specifies if the MSB or LSB first should be pushed into the JTAG + /// chain. + /// + /// In the case that "count" is less than the full data length and MSB first + /// order is requested, `push` first discards the left-most unused bits and + /// then starts push from the remaining MSB. e.g., to push the number + /// `101100` into the JTAG chain MSB first, store 0x2C into "data" and specify + /// a "count" of 6, and an "endian" of JtagEndian::Big. Do not shift + /// data all the way to the MSB of the containing "data" parameter in this case! + pub fn push_u128(&mut self, data: u128, count: usize, endian: JtagEndian) { + assert!(count <= 128); + for i in 0..count { + match endian { + JtagEndian::Big => { + if (data & (1 << i)) == 0 { self.i.push(false) } else { self.i.push(true) } + }, + JtagEndian::Little => { + if (data & (1 << (count-1-i))) == 0 { self.i.push(false) } else { self.i.push(true) } + }, + } + } + } + + pub fn push_u32(&mut self, data: u32, count: usize, endian: JtagEndian) { + assert!(count <= 32); + for i in 0..count { + match endian { + JtagEndian::Big => { + if (data & (1 << i)) == 0 { self.i.push(false) } else { self.i.push(true) } + }, + JtagEndian::Little => { + if (data & (1 << (count-1-i))) == 0 { self.i.push(false) } else { self.i.push(true) } + }, + } + } + } + + pub fn push_u8(&mut self, data: u8, count: usize, endian: JtagEndian) { + assert!(count <= 8); + for i in 0..count { + match endian { + JtagEndian::Big => { + if (data & (1 << i)) == 0 { self.i.push(false) } else { self.i.push(true) } + }, + JtagEndian::Little => { + if (data & (1 << (count-1-i))) == 0 { self.i.push(false) } else { self.i.push(true) } + }, + } + } + } + + pub fn pop_u32(&mut self, count: usize, endian: JtagEndian) -> Option { + if self.o.len() < count { + // error out before trying to touch the vector, so that in case + // of a parameter error we can try again without having lost our data + // in general, "count" should be very well specified in this protocol. + return None; + } + + let mut data: u32 = 0; + for _ in 0..count { + match endian { + JtagEndian::Little => { + data <<= 1; + if self.o.pop().unwrap() { data |= 0x1; } + } + JtagEndian::Big => { + data >>= 1; + if self.o.pop().unwrap() { data |= 0x8000_0000; } + } + } + } + + Some(data) + } + + /// pop_u128 does a "Best effort" to return up to count_req elements, will return what is + /// available if less is available + pub fn pop_u128(&mut self, count_req: usize, endian: JtagEndian) -> Option { + let mut count: usize = count_req; + if self.o.len() == 0 { + return None; + } else if self.o.len() < count_req { + count = self.o.len(); + } + + let mut data: u128 = 0; + for _ in 0..count { + match endian { + JtagEndian::Little => { + data <<= 1; + if self.o.pop().unwrap() { data |= 0x1; } + }, + JtagEndian::Big => { + data >>= 1; + if self.o.pop().unwrap() { data |= 0x8000_0000_0000_0000_0000_0000_0000_0000; } + } + } + } + + Some(data) + } + + pub fn pop_u8(&mut self, count: usize, endian: JtagEndian) -> Option { + if self.o.len() < count { + // error out before trying to touch the vector, so that in case + // of a parameter error we can try again without having lost our data + // in general, "count" should be very well specified in this protocol. + return None; + } + + let mut data: u8 = 0; + for _ in 0..count { + match endian { + JtagEndian::Little => { + data <<= 1; + if self.o.pop().unwrap() { data |= 0x1; } + } + JtagEndian::Big => { + data >>= 1; + if self.o.pop().unwrap() { data |= 0x80; } + } + } + } + + Some(data) + } + + pub fn tag(&self) -> String { + self.tag.clone() + } + + pub fn dbg_i_len(&self) -> usize { + self.i.len() + } + pub fn dbg_o_len(&self) -> usize { + self.o.len() + } +} + +pub struct JtagMach { + /// current state (could be in one of two generics, or in DR/IR chain; check top of Vector for current chain) + s: JtagState, + /// a vector of legs to traverse. An entry stays in pending until the traversal is complete. Aborted + /// traversals leave the leg in place + pending: Vec, + /// a vector of legs traversed. An entry is only put into the done vector once its traversal is completed. + done: Vec, + /// the current leg being processed + current: Option, + /// an integer for debug help + debug: u32, + /// the jtag phy + phy: JtagPhy, + ticktimer: ticktimer_server::Ticktimer, +} + +impl JtagMach { + pub fn new() -> Self { + JtagMach { + s: JtagState::TestReset, + pending: Vec::new(), + done: Vec::new(), + current: None, + debug: 0, + phy: implementation::JtagPhy::new(), + ticktimer: ticktimer_server::Ticktimer::new().unwrap(), + } + } + /// pause for a given number of microseconds. + pub fn pause(&mut self, us: u32) { + let mut delay: u32 = us/1000; + if delay == 0 { + delay = 1; + } + self.ticktimer.sleep_ms(delay as usize).expect("couldn't sleep"); + } + + /// add() -- add a leg to the pending queue + pub fn add(&mut self, leg: JtagLeg) { + self.pending.push(leg); + } + + /// get() -- get the oldest result in the done queue. Returns an option. + pub fn get(&mut self) -> Option { + if self.done.len() > 0 { + Some(self.done.remove(0)) + } else { + None + } + } + + /// has_pending() -- tells if the jtag machine has a pending leg to traverse. Returns the tag of the pending item, or None. + pub fn has_pending(&self) -> bool { + if self.pending.len() > 0 { + true + } else { + false + } + } + + /// has_done() -- tells if the jtag machine has any legs that are done to read out. Returns the tag of the done item, or None. + #[allow(dead_code)] + pub fn has_done(&self) -> bool { + if self.done.len() > 0 { + true + } else { + false + } + } + + /// for debug + #[allow(dead_code)] + pub fn pending_len(&self) -> usize { + self.pending.len() + } + /// for debug + #[allow(dead_code)] + pub fn done_len(&self) -> usize { + self.done.len() + } + pub fn dbg_reset(&mut self) { + self.debug = 0; + } + pub fn dbg_get(&self) -> u32 { + self.debug + } + + /// step() -- move state machine by one cycle + /// if there is nothing in the pending queue, stay in idle + /// if something in the pending queue, traverse to execute it + pub fn step(&mut self) { + self.s = match self.s { + JtagState::TestReset => { + self.phy.sync(false, false); + JtagState::RunIdle + }, + JtagState::RunIdle => { + // we have a current item, traverse to the correct tree based on the type + if let Some(ref mut cur) = self.current { + match cur.c { + JtagChain::DR => { + self.debug = 2; + self.phy.sync(false, true); + }, + JtagChain::IR => { + self.debug = 3; + // must be IR -- do two TMS high pulses to get to the IR leg + self.phy.sync(false, true); + self.phy.sync(false, true); + } + } + JtagState::Select + } else { + if self.pending.len() > 0 { + // nothing current, but has pending --> assign a current + // don't pop the entry, though, until we are finished traversing the leg, + // hence we make a clone of the entry + self.current = Some(self.pending[0].clone()); + } else { + // nothing pending, nothing current + // stay in the current state + self.phy.sync(false, false); + } + JtagState::RunIdle + } + }, + JtagState::Select => { + self.phy.sync(false, false); + JtagState::Capture + }, + JtagState::Capture => { + // always move to shift, because leg structures always have data + self.phy.sync(false, false); + JtagState::Shift + }, + JtagState::Shift => { + // shift data until the input vector is exhausted + if let Some(ref mut cur) = self.current { + if let Some(tdi) = cur.i.pop() { + if cur.i.len() > 0 { + let tdo: bool = self.phy.sync(tdi, false); + cur.o.push(tdo); + self.current = Some(cur.clone()); + JtagState::Shift + } else { + // last element should leave the state + let tdo: bool = self.phy.sync(tdi, true); + cur.o.push(tdo); + self.current = Some(cur.clone()); + JtagState::Exit1 + } + } else { + // Shouldn't happen: no "i", but move on gracefully + JtagState::Exit1 + } + } else { + // Shouldn't happen: No "Current", but move on gracefully + JtagState::Exit1 + } + }, + JtagState::Exit1 => { + self.phy.sync(false, true); + JtagState::Update + }, + JtagState::Pause => { + self.phy.sync(false, true); + JtagState::Exit2 + }, + JtagState::Exit2 => { + self.phy.sync(false, true); + JtagState::Update + }, + JtagState::Update => { + self.phy.sync(false, false); + + self.pending.remove(0); // remove the oldest entry + if let Some(next) = self.current.take() { + self.done.push(next); + } + JtagState::RunIdle + } + } + } + + /// reset() -- bring the state machine back to the TEST_RESET state + pub fn reset(&mut self) { + // regardless of what state we are in, 5 cycles of TMS=1 will bring us to RESET + for _ in 0..5 { + self.phy.sync(false, true); + } + self.s = JtagState::TestReset; + } + + /// next() -- advance until a RUN_IDLE state. If currently RUN_IDLE, traverse the next available leg, if one exists + pub fn next(&mut self) { + match self.s { + JtagState::RunIdle | JtagState::TestReset => { + if self.has_pending() { + // if pending, step until we're into a leg + loop { + match self.s { + JtagState::RunIdle | JtagState::TestReset => self.step(), + _ => break, + } + } + // then step until we're out of the leg + loop { + match self.s { + JtagState::RunIdle | JtagState::TestReset => break, + _ => self.step(), + } + } + } else { + self.step(); // this should be a single step with no state change + } + }, + _ => { + // in the case that we're not already in idle or reset, run the machine until we get to idle or reset + loop { + match self.s { + JtagState::RunIdle | JtagState::TestReset => break, + _ => self.step(), + } + } + }, + } + } +} + +#[cfg(any(target_os = "none", target_os = "xous"))] +mod implementation { + use utralib::generated::*; + + #[allow(dead_code)] + pub(crate) struct JtagPhy { + csr: utralib::CSR, + } + + impl JtagPhy { + pub fn new() -> JtagPhy { + let csr = xous::syscall::map_memory( + xous::MemoryAddress::new(utra::jtag::HW_JTAG_BASE), + None, + 4096, + xous::MemoryFlags::R | xous::MemoryFlags::W, + ) + .expect("couldn't map JTAG CSR range"); + + let jtag = JtagPhy { + csr: CSR::new(csr.as_mut_ptr() as *mut u32), + }; + + jtag + } + + /// given a tdi and tms value, pulse the clock, and then return the tdo that comes out + pub fn sync(&mut self, tdi: bool, tms: bool) -> bool { + self.csr.wo(utra::jtag::NEXT, + self.csr.ms(utra::jtag::NEXT_TDI, if tdi {1} else {0}) | + self.csr.ms(utra::jtag::NEXT_TMS, if tms {1} else {0}) + ); + + while self.csr.rf(utra::jtag::TDO_READY) == 0 { } // make sure we are in a ready/tdo valid state + if self.csr.rf(utra::jtag::TDO_TDO) == 0 { // this is the TDO value from /prior/ to the TCK rise + false + } else { + true + } + // note: the hardware already guarantees TDO sample timing relative to TCK edge: in other words, + // TDO is sampled before the TCK edge is allowed to rise + } + } +} + +// a stub to try to avoid breaking hosted mode for as long as possible. +#[cfg(not(any(target_os = "none", target_os = "xous")))] +mod implementation { + pub struct JtagMach { + } + + impl JtagMach { + pub fn new() -> JtagMach { + JtagMach { + } + } + fn sync(&mut self, tdi: bool, tms: bool) -> bool { + false + } + } +} + + +#[xous::xous_main] +fn xmain() -> ! { + log_server::init_wait().unwrap(); + log::set_max_level(log::LevelFilter::Info); + log::info!("my PID is {}", xous::process::id()); + + let xns = xous_names::XousNames::new().unwrap(); + // expect: + // - one connection from the key server + // - one connection from shellchat for testing + let jtag_sid = xns.register_name(api::SERVER_NAME_JTAG, Some(2)).expect("can't register server"); + log::trace!("registered with NS -- {:?}", jtag_sid); + + let mut jtag = JtagMach::new(); + let mut efuse = EfuseApi::new(); + + log::trace!("ready to accept requests"); + + // register a suspend/resume listener + let mut susres = susres::Susres::new_without_hook(&xns).expect("couldn't create suspend/resume object"); + + loop { + let mut msg = xous::receive_message(jtag_sid).unwrap(); + match FromPrimitive::from_usize(msg.body.id()) { + Some(Opcode::GetId) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { + jtag.reset(); + let mut id_leg: JtagLeg = JtagLeg::new(JtagChain::IR, "idcode"); + id_leg.push_u32(0b001001, 6, JtagEndian::Little); + jtag.add(id_leg); + jtag.next(); + // NOW: - check the return data on .get() before using it + if jtag.get().is_none() { // discard ID code but check that there's something + log::error!("ID instruction not in get queue!"); + xous::return_scalar(msg.sender, 0xFFFF_FFFF).unwrap(); + continue; + } + + let mut data_leg: JtagLeg = JtagLeg::new(JtagChain::DR, "iddata"); + data_leg.push_u32(0, 32, JtagEndian::Little); + jtag.add(data_leg); + jtag.dbg_reset(); + jtag.next(); + let d: u32 = jtag.dbg_get(); + if let Some(mut iddata) = jtag.get() { // this contains the actual idcode data + let id = iddata.pop_u32(32, JtagEndian::Little).unwrap(); + log::trace!("tag: {}, code: 0x{:08x}, d:{}", iddata.tag(), id, d); + xous::return_scalar(msg.sender, id as usize).unwrap(); + } else { + log::trace!("ID data not in get queue!"); + } + }), + Some(Opcode::GetDna) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { + jtag.reset(); + let mut ir_leg: JtagLeg = JtagLeg::new(JtagChain::IR, "cmd"); + ir_leg.push_u32(0b110010, 6, JtagEndian::Little); + jtag.add(ir_leg); + jtag.next(); + if jtag.get().is_none() { // discard ID code but check that there's something + log::error!("cmd instruction not in get queue!"); + xous::return_scalar2(msg.sender, 0xFFFF_FFFF, 0xFFFF).unwrap(); + } + + let mut data_leg: JtagLeg = JtagLeg::new(JtagChain::DR, "dna"); + data_leg.push_u128(0, 64, JtagEndian::Little); + jtag.add(data_leg); + jtag.next(); + if let Some(mut data) = jtag.get() { + let dna: u128 = data.pop_u128(64, JtagEndian::Little).unwrap(); + xous::return_scalar2(msg.sender, (dna >> 32) as usize, dna as usize).unwrap(); + log::info!("{}/0x{:16x}", data.tag(), dna); + } else { + log::error!("cmd instruction not in get queue!"); + xous::return_scalar2(msg.sender, 0xFFFF_FFFF, 0xFFFF).unwrap(); + } + }), + Some(Opcode::EfuseFetch) => { + efuse.fetch(&mut jtag); + let mut buffer = unsafe{Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap())}; + let mut efuse_rec = buffer.to_original::().unwrap(); + + efuse_rec.user = efuse.phy_user(); + efuse_rec.cntl = efuse.phy_cntl(); + for (&src, dst) in efuse.phy_key().iter().zip(efuse_rec.key.iter_mut()) { + *dst = src; + } + buffer.replace(efuse_rec).unwrap(); + } + Some(Opcode::WriteIr) => msg_scalar_unpack!(msg, ir, _, _, _, { + jtag.reset(); + let mut ir_leg: JtagLeg = JtagLeg::new(JtagChain::IR, "cmd"); + ir_leg.push_u32(ir as u32, 6, JtagEndian::Little); // ISC_ENABLE + jtag.add(ir_leg); + jtag.next(); + if jtag.get().is_none() { // discard ID code but check that there's something + log::error!("cmd instruction not in get queue!"); + } + }), + Some(Opcode::EfuseKeyBurn) => { + susres.set_suspendable(false).unwrap(); + let mut buffer = unsafe{Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap())}; + let key = buffer.to_original::<[u8; 32], _>().unwrap(); + // refresh the efuse cache + efuse.fetch(&mut jtag); + #[cfg(feature = "hazardous-debug")] + log::info!("attempting to burn key: {:x?}", key); + efuse.set_key(key); + if efuse.is_valid() { + log::info!("efuse key is valid to burn, proceeding. There is no return..."); + efuse.burn(&mut jtag); + buffer.replace(EfuseResult::Success).unwrap(); + } else { + log::error!("efuses already burned, new key is unpatchable. Refusing to burn!"); + buffer.replace(EfuseResult::Failure).unwrap(); + } + susres.set_suspendable(true).unwrap(); + } + Some(Opcode::EfuseCtlBurn) => msg_blocking_scalar_unpack!(msg, ctl, _, _, _, { + susres.set_suspendable(false).unwrap(); + efuse.fetch(&mut jtag); + efuse.set_cntl(ctl as u8); + if efuse.is_valid() { + log::info!("control is valid to burn, proceeding. There is no return..."); + efuse.burn(&mut jtag); + susres.set_suspendable(true).unwrap(); + xous::return_scalar(msg.sender, 1).unwrap(); + } else { + susres.set_suspendable(true).unwrap(); + xous::return_scalar(msg.sender, 0).unwrap(); + } + }), + Some(Opcode::EfuseUserBurn) => msg_blocking_scalar_unpack!(msg, user, _, _, _, { + susres.set_suspendable(false).unwrap(); + efuse.fetch(&mut jtag); + efuse.set_user(user as u32); + if efuse.is_valid() { + log::info!("user fuses are valid to burn, proceeding. There is no return..."); + efuse.burn(&mut jtag); + susres.set_suspendable(true).unwrap(); + xous::return_scalar(msg.sender, 1).unwrap(); + } else { + susres.set_suspendable(true).unwrap(); + xous::return_scalar(msg.sender, 0).unwrap(); + } + }), + None => { + log::error!("couldn't convert opcode"); + break + } + } + } + // clean up our program + log::trace!("main loop exit, destroying servers"); + xns.unregister_server(jtag_sid).unwrap(); + xous::destroy_server(jtag_sid).unwrap(); + log::trace!("quitting"); + xous::terminate_process(0) +} diff --git a/services/llio/src/main.rs b/services/llio/src/main.rs index 1d94f844c..5bbf86b68 100644 --- a/services/llio/src/main.rs +++ b/services/llio/src/main.rs @@ -657,12 +657,13 @@ fn xmain() -> ! { // - shellchat/sleep // - shellchat/environment // - spinor (for turning off wfi during writes) - let llio_sid = xns.register_name(api::SERVER_NAME_LLIO, Some(6)).expect("can't register server"); + // - rootkeys (for reboots) + let llio_sid = xns.register_name(api::SERVER_NAME_LLIO, Some(7)).expect("can't register server"); log::trace!("registered with NS -- {:?}", llio_sid); // create the I2C handler thread // each connection to llio also creates an i2c connection, so it has the same expectation list - let i2c_sid = xns.register_name(api::SERVER_NAME_I2C, Some(6)).expect("can't register I2C thread"); + let i2c_sid = xns.register_name(api::SERVER_NAME_I2C, Some(7)).expect("can't register I2C thread"); log::trace!("registered I2C thread with NS -- {:?}", i2c_sid); let (sid0, sid1, sid2, sid3) = i2c_sid.to_u32(); xous::create_thread_4(i2c_thread, sid0 as usize, sid1 as usize, sid2 as usize, sid3 as usize).expect("couldn't start I2C handler thread"); diff --git a/services/root-keys/Cargo.toml b/services/root-keys/Cargo.toml index 67c5dcf8e..056c82fa3 100644 --- a/services/root-keys/Cargo.toml +++ b/services/root-keys/Cargo.toml @@ -14,6 +14,9 @@ log = "0.4" susres = {path = "../susres"} trng = {path= "../trng"} spinor = {path="../spinor"} +llio = {path="../llio"} +rtc = {path="../rtc"} +com = {path="../com"} xous-ipc = {path = "../../xous-ipc"} num-derive = {version = "0.3", default-features = false} diff --git a/services/root-keys/locales/i18n.json b/services/root-keys/locales/i18n.json index 31f256e9b..c14d2b528 100644 --- a/services/root-keys/locales/i18n.json +++ b/services/root-keys/locales/i18n.json @@ -69,10 +69,15 @@ "zh": "保存签名\n可能还要等一下\n不要重置或睡眠!\n", "en-audio": "Committing signatures. This may take a while, don't reset or sleep the device." }, + "rootkeys.init.unplug_power": { + "en": "Please unplug the charging\ncable so I can reboot!\n\n", + "zh": "拔下充电线以允许重启!", + "en-audio": "Unplug the charging cable so I can reboot!" + }, "rootkeys.init.finished": { - "en": "Preparing to reboot...\n\n\n", + "en": "Reboot in 5 seconds...\n\n\n", "zh": "准备重启...\n\n", - "en-audio": "Preparing to reboot." + "en-audio": "Reboot in 5 seconds." }, "rootkeys.init.fail_verify": { "en": "Verification failed,\naborting!", diff --git a/services/root-keys/src/api.rs b/services/root-keys/src/api.rs index efa7a3473..4c3dc9a4d 100644 --- a/services/root-keys/src/api.rs +++ b/services/root-keys/src/api.rs @@ -23,6 +23,7 @@ pub(crate) enum Opcode { UxGutter, // NOP for UX calls that require a destination UxGetPolicy, UxPolicyReturn, + UxTryReboot, /// provision a gateware update with our secret data UxUpdateGateware, /// self-sign kernel/loader diff --git a/services/root-keys/src/main.rs b/services/root-keys/src/main.rs index 7ee1463b4..b2a11976b 100644 --- a/services/root-keys/src/main.rs +++ b/services/root-keys/src/main.rs @@ -120,6 +120,12 @@ fn xmain() -> ! { let mut keys = RootKeys::new(); + // create the servers necessary to coordinate an auto-reboot sequence... + let llio = llio::Llio::new(&xns).unwrap(); + let rtc = rtc::Rtc::new(&xns).unwrap(); + let ticktimer = ticktimer_server::Ticktimer::new().unwrap(); + let com = com::Com::new(&xns).unwrap(); + log::trace!("ready to accept requests"); // register a suspend/resume listener @@ -318,12 +324,22 @@ fn xmain() -> ! { // the stop emoji, when sent to the slider action bar in progress mode, will cause it to close and relinquish focus rootkeys_modal.key_event(['🛑', '\u{0000}', '\u{0000}', '\u{0000}']); - // at this point, we may want to pop up a modal indicating we are going to reboot? - // we also need to include a command that does the reboot. match result { Ok(_) => { keys.finish_key_init(); - // TODO: need to insert the reboot command here + + // summon a modal that brings us to a reboot + dismiss_modal_action.set_action_opcode(Opcode::UxTryReboot.to_u32().unwrap()); + rootkeys_modal.modify( + Some(ActionType::Notification(dismiss_modal_action)), + Some(t!("rootkeys.init.finished", xous::LANG)), false, + None, false, None); + rootkeys_modal.activate(); + + send_message(main_cid, + xous::Message::new_scalar(Opcode::UxTryReboot.to_usize().unwrap(), 0, 0, 0, 0)).expect("couldn't initiate dialog box"); + + continue; } Err(RootkeyResult::AlignmentError) => { dismiss_modal_action.set_action_opcode(Opcode::UxGutter.to_u32().unwrap()); @@ -371,6 +387,62 @@ fn xmain() -> ! { log::error!("invalid UX state -- someone called init password return, but no password type was set!"); } }, + Some(Opcode::UxTryReboot) => { + // ensure the boost is off so that the reboot will not fail + com.set_boost(false).unwrap(); + llio.boost_on(false).unwrap(); + ticktimer.sleep_ms(50).unwrap(); // give some time for the voltage to move + + let vbus = (llio.adc_vbus().unwrap() as f64) * 0.005033; + log::info!("Vbus is: {:.3}V", vbus); + if vbus > 1.5 { + // if power is plugged in, request that it be removed + dismiss_modal_action.set_action_opcode(Opcode::UxTryReboot.to_u32().unwrap()); + rootkeys_modal.modify( + Some(ActionType::Notification(dismiss_modal_action)), + Some(t!("rootkeys.init.unplug_power", xous::LANG)), false, + None, false, None); + rootkeys_modal.activate(); + rootkeys_modal.redraw(); + xous::yield_slice(); + ticktimer.sleep_ms(500).unwrap(); + + send_message(main_cid, + xous::Message::new_scalar(Opcode::UxTryReboot.to_usize().unwrap(), 0, 0, 0, 0) + ).expect("couldn't initiate dialog box"); + + log::info!("vbus is high, holding off on reboot"); + } else { + dismiss_modal_action.set_action_opcode(Opcode::UxGutter.to_u32().unwrap()); + rootkeys_modal.modify( + Some(ActionType::Notification(dismiss_modal_action)), + Some(t!("rootkeys.init.finished", xous::LANG)), false, + None, false, None); + rootkeys_modal.activate(); + rootkeys_modal.redraw(); + xous::yield_slice(); + + // set a wakeup alarm a couple seconds from now -- this is the coldboot + rtc.set_wakeup_alarm(4).unwrap(); + + // allow EC to snoop, so that it can wake up the system + llio.allow_ec_snoop(true).unwrap(); + // allow the EC to power me down + llio.allow_power_off(true).unwrap(); + // now send the power off command + com.power_off_soc().unwrap(); + + log::info!("reboot in 4 seconds!"); + // pause execution, nothing after this should be reachable + ticktimer.sleep_ms(5000).unwrap(); + log::info!("if you can read this, reboot failed!"); + + // try it again, anyways... + send_message(main_cid, + xous::Message::new_scalar(Opcode::UxTryReboot.to_usize().unwrap(), 0, 0, 0, 0) + ).expect("couldn't initiate dialog box"); + } + } Some(Opcode::UxUpdateGateware) => { unimplemented!(); }, diff --git a/services/rtc/src/main.rs b/services/rtc/src/main.rs index 9d0951827..5bcc3f9bc 100644 --- a/services/rtc/src/main.rs +++ b/services/rtc/src/main.rs @@ -582,7 +582,8 @@ fn xmain() -> ! { // - shellchat/rtc // - shellchat/sleep x2 // - UX thread (self, created without xns, so does not count) - let rtc_sid = xns.register_name(api::SERVER_NAME_RTC, Some(4)).expect("can't register server"); + // - rootkeys (for coordinating reboot) + let rtc_sid = xns.register_name(api::SERVER_NAME_RTC, Some(5)).expect("can't register server"); log::trace!("registered with NS -- {:?}", rtc_sid); CB_TO_MAIN_CONN.store(xous::connect(rtc_sid).unwrap(), Ordering::Relaxed);