format services/jtag

This commit is contained in:
bunnie 2024-01-14 22:16:12 +08:00
parent 411e0ca9d8
commit 2f9f91648c
5 changed files with 330 additions and 260 deletions

View file

@ -1,4 +1,4 @@
pub(crate) const SERVER_NAME_JTAG: &str = "_JTAG Server_";
pub(crate) const SERVER_NAME_JTAG: &str = "_JTAG Server_";
#[allow(dead_code)]
pub const XCS750_IDCODE: u32 = 0x362F093;

View file

@ -12,8 +12,8 @@
/// 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
/// * 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.
@ -30,10 +30,8 @@
/// 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};
use crate::{JtagChain, JtagEndian, JtagLeg, JtagMach};
/// There are 13 banks of fuses, 12 of which (key/user) are "hamming" ECC, 1 of which (config) is "dup" ECC.
pub struct EfusePhy {
@ -64,12 +62,15 @@ impl EfusePhy {
}
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
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 {
@ -100,10 +101,10 @@ impl EfusePhy {
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;
self.banks[11 - index] = bank_data;
} else {
bank_data = data.pop_u32(24, JtagEndian::Little).unwrap();
self.banks[11-index] = add_ecc(bank_data);
self.banks[11 - index] = add_ecc(bank_data);
}
}
} else {
@ -112,7 +113,8 @@ impl EfusePhy {
// derive bits from bank data, to debug any bit-order issues on readout, etc.
for index in 0..32 {
// key reversal from hw storage state is handled here
self.key[31 - index] = ((self.banks[((index / 3) + 1) as usize] >> ((index % 3) * 8)) & 0xFF) as u8;
self.key[31 - index] =
((self.banks[((index / 3) + 1) as usize] >> ((index % 3) * 8)) & 0xFF) as u8;
}
jm.pause(2000);
@ -133,7 +135,7 @@ impl EfusePhy {
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);
self.banks[12] = add_ecc((user_data >> 8) & 0xFF_FF_FF);
} else {
assert!(false);
}
@ -169,24 +171,23 @@ pub struct EfuseApi {
}
impl EfuseApi {
pub fn new() -> Self {
EfuseApi {
key: [0; 32],
user: 0,
cntl: 0,
phy: EfusePhy::new(),
}
}
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
/// 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 }
@ -208,7 +209,9 @@ impl EfuseApi {
self.key[i] = new_key[31 - i]; // key is reversed in byte order
}
}
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 {
@ -220,19 +223,32 @@ impl EfuseApi {
// handle cntl special case
if ((self.phy.banks[0] & 0x3F) as u8 ^ self.cntl) & (self.phy.banks[0] & 0x3F) as u8 != 0 {
valid = false;
log::warn!("proposed efuse cntl setting is not valid {:x?} -> {:x?}", self.phy.banks[0] & 0x3F, self.cntl);
log::warn!(
"proposed efuse cntl setting is not valid {:x?} -> {:x?}",
self.phy.banks[0] & 0x3F,
self.cntl
);
}
} else if index == 12 {
// handle user special case
if ((self.phy.banks[index] ^ add_ecc(self.user >> 8)) & self.phy.banks[index]) != 0 {
log::warn!("proposed efuse user setting is not valid {:x?} -> {:x?}", self.phy.banks[index], add_ecc(self.user >> 8));
log::warn!(
"proposed efuse user setting is not valid {:x?} -> {:x?}",
self.phy.banks[index],
add_ecc(self.user >> 8)
);
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;
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 {
log::warn!("proposed user/key overlap area setting is not valid {:x?} -> {:x?}", self.phy.banks[index], add_ecc(raw_fuse));
log::warn!(
"proposed user/key overlap area setting is not valid {:x?} -> {:x?}",
self.phy.banks[index],
add_ecc(raw_fuse)
);
valid = false;
}
} else {
@ -240,10 +256,14 @@ impl EfuseApi {
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;
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 {
log::warn!("proposed key setting is not valid {:x?} -> {:x?}", self.phy.banks[index], add_ecc(raw_fuse));
log::warn!(
"proposed key setting is not valid {:x?} -> {:x?}",
self.phy.banks[index],
add_ecc(raw_fuse)
);
valid = false;
}
}
@ -251,7 +271,7 @@ impl EfuseApi {
valid
}
fn jtag_seq(&mut self, jm: &mut JtagMach, cmds: &[(JtagChain, usize, u64, &str)] ) -> u128 {
fn jtag_seq(&mut self, jm: &mut JtagMach, cmds: &[(JtagChain, usize, u64, &str)]) -> u128 {
let mut ret: u128 = 0;
for tuple in cmds.iter() {
@ -273,14 +293,16 @@ impl EfuseApi {
}
fn burn_bank(&mut self, bank: usize, ones: u32, jm: &mut JtagMach) {
if ones == 0 { // skip the bank if nothing to burn
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
if bank > 0 {
// rest of banks
bank_select = (bank as u8 - 1) * 8 + 0xA1;
word_select = bank_select | 0b10;
}
@ -300,7 +322,12 @@ impl EfuseApi {
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,
(0xa08a28ac00004000 | (word_select as u64)) + ((i as u64) << 8),
"KEY_BIT",
),
(JtagChain::DR, 64, 0x0, "KEY_BIT_WAIT"),
];
self.jtag_seq(jm, &bit_burn);
@ -312,31 +339,30 @@ impl EfuseApi {
// 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"),
];
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;
@ -363,26 +389,38 @@ impl EfuseApi {
// 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);
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;
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);
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;
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);
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);
@ -390,5 +428,4 @@ impl EfuseApi {
jm.reset();
ok
}
}

View file

@ -19,7 +19,9 @@ pub mod efuse_ecc {
code = (!code & 0x1F) | 0x20;
}
let secded = ((((code >> 5) ^ (code >> 4) ^ (code >> 3) ^ (code >> 2) ^ (code >> 1) ^ code) & 0x1) << 5) | code;
let secded = ((((code >> 5) ^ (code >> 4) ^ (code >> 3) ^ (code >> 2) ^ (code >> 1) ^ code) & 0x1)
<< 5)
| code;
data | secded << 24
}

View file

@ -2,9 +2,9 @@
pub mod api;
pub use api::*;
use xous::{CID, send_message, Message};
use xous_ipc::Buffer;
use num_traits::*;
use xous::{send_message, Message, CID};
use xous_ipc::Buffer;
#[derive(Debug)]
pub struct Jtag {
@ -13,152 +13,167 @@ pub struct Jtag {
impl Jtag {
pub fn new(xns: &xous_names::XousNames) -> Result<Self, xous::Error> {
REFCOUNT.fetch_add(1, Ordering::Relaxed);
let conn = xns.request_connection_blocking(api::SERVER_NAME_JTAG).expect("Can't connect to JTAG server");
Ok(Jtag {
conn
})
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<u32, xous::Error> {
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)
}
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<u64, xous::Error> {
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 {
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<EfuseRecord, xous::Error> {
let xmit = EfuseRecord {
key: [0; 32],
user: 0,
cntl: 0,
};
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::<EfuseRecord, _>().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(|_| ())
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<bool, xous::Error> {
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))?;
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<bool, xous::Error> {
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");
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)
}
if res == 0 { Ok(false) } else { Ok(true) }
} else {
Err(xous::Error::InternalError)
}
}
pub fn is_efuse_only_boot(&self) -> Result<bool, xous::Error> {
let erec = self.efuse_fetch().expect("couldn't read efuse record");
if (erec.cntl & 0x1) != 0 { Ok(true) } else { Ok(false) }
if (erec.cntl & 0x1) != 0 { Ok(true) } else { Ok(false) }
}
pub fn is_disable_jtag(&self) -> Result<bool, xous::Error> {
let erec = self.efuse_fetch().expect("couldn't read efuse record");
if (erec.cntl & 0x2) != 0 { Ok(true) } else { Ok(false) }
if (erec.cntl & 0x2) != 0 { Ok(true) } else { Ok(false) }
}
pub fn is_efuse_writeable(&self) -> Result<bool, xous::Error> {
let erec = self.efuse_fetch().expect("couldn't read efuse record");
if (erec.cntl & 0x4) != 0 { Ok(true) } else { Ok(false) }
if (erec.cntl & 0x4) != 0 { Ok(true) } else { Ok(false) }
}
pub fn is_key_access_protected(&self) -> Result<bool, xous::Error> {
let erec = self.efuse_fetch().expect("couldn't read efuse record");
if (erec.cntl & 0x8) != 0 { Ok(true) } else { Ok(false) }
if (erec.cntl & 0x8) != 0 { Ok(true) } else { Ok(false) }
}
pub fn is_user_and_key_access_protected(&self) -> Result<bool, xous::Error> {
let erec = self.efuse_fetch().expect("couldn't read efuse record");
if (erec.cntl & 0x10) != 0 { Ok(true) } else { Ok(false) }
if (erec.cntl & 0x10) != 0 { Ok(true) } else { Ok(false) }
}
pub fn is_control_write_protected(&self) -> Result<bool, xous::Error> {
let erec = self.efuse_fetch().expect("couldn't read efuse record");
if (erec.cntl & 0x20) != 0 { Ok(true) } else { Ok(false) }
if (erec.cntl & 0x20) != 0 { Ok(true) } else { Ok(false) }
}
pub fn get_raw_control_bits(&self) -> Result<u8, xous::Error> {
let erec = self.efuse_fetch().expect("couldn't read efuse record");
Ok(erec.cntl)
}
fn mod_ctl_efuse(&self, bits_to_set: u8) -> Result<bool, xous::Error> {
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 {
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<bool, xous::Error> {
self.mod_ctl_efuse(0x1)
}
pub fn burn_disable_jtag(&self) -> Result<bool, xous::Error> {
self.mod_ctl_efuse(0x2)
}
pub fn burn_efuse_write_protect(&self) -> Result<bool, xous::Error> {
self.mod_ctl_efuse(0x4)
}
pub fn burn_key_access_protect(&self) -> Result<bool, xous::Error> {
self.mod_ctl_efuse(0x8)
}
pub fn burn_user_and_key_access_protect(&self) -> Result<bool, xous::Error> {
self.mod_ctl_efuse(0x10)
}
pub fn burn_control_write_protect(&self) -> Result<bool, xous::Error> {
self.mod_ctl_efuse(0x20)
}
pub fn burn_efuse_only_boot(&self) -> Result<bool, xous::Error> { self.mod_ctl_efuse(0x1) }
pub fn burn_disable_jtag(&self) -> Result<bool, xous::Error> { self.mod_ctl_efuse(0x2) }
pub fn burn_efuse_write_protect(&self) -> Result<bool, xous::Error> { self.mod_ctl_efuse(0x4) }
pub fn burn_key_access_protect(&self) -> Result<bool, xous::Error> { self.mod_ctl_efuse(0x8) }
pub fn burn_user_and_key_access_protect(&self) -> Result<bool, xous::Error> { self.mod_ctl_efuse(0x10) }
pub fn burn_control_write_protect(&self) -> Result<bool, xous::Error> { self.mod_ctl_efuse(0x20) }
/// Sets all the fuses, except `disable_jtag` and `control_write_protect`.
/// This forces the device to:
/// - only boot from an encrypted image (so unbricking via JTAG requires you to provide an encryption key)
/// - only boot from an encrypted image (so unbricking via JTAG requires you to provide an encryption
/// key)
/// - key update disallowed
/// - key readback disallowed
/// - user bits can be read out (but they can't be updated)
/// - control bits can still be blown (so you can still set `disable_jtag` later on;
/// however, it is physically impossible to unset bits, so it is not possible to
/// enable key readback despite being able to write bits)
pub fn seal_device(&self) -> Result<bool, xous::Error> {
self.mod_ctl_efuse(0b00_1101)
}
/// - control bits can still be blown (so you can still set `disable_jtag` later on; however, it is
/// physically impossible to unset bits, so it is not possible to enable key readback despite being
/// able to write bits)
pub fn seal_device(&self) -> Result<bool, xous::Error> { self.mod_ctl_efuse(0b00_1101) }
}
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".
// 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.fetch_sub(1, Ordering::Relaxed) == 1 {
unsafe{xous::disconnect(self.conn).unwrap();}
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
// 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
}
}
}

View file

@ -6,10 +6,11 @@ mod efuse_api;
mod efuse_ecc;
use api::*;
use efuse_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 {
@ -32,7 +33,7 @@ pub enum JtagChain {
pub enum JtagEndian {
Big, // MSB-first shiftout
Little // LSB-first shiftout
Little, // LSB-first shiftout
}
/// option 1: make a "leg" machine that contains the shift-in/shift-out records specific to each leg
@ -41,7 +42,6 @@ pub enum JtagEndian {
/// 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)
@ -56,12 +56,7 @@ pub struct JtagLeg {
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),
}
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)
@ -81,11 +76,19 @@ impl JtagLeg {
for i in 0..count {
match endian {
JtagEndian::Big => {
if (data & (1 << i)) == 0 { self.i.push(false) } else { self.i.push(true) }
},
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) }
},
if (data & (1 << (count - 1 - i))) == 0 {
self.i.push(false)
} else {
self.i.push(true)
}
}
}
}
}
@ -95,11 +98,19 @@ impl JtagLeg {
for i in 0..count {
match endian {
JtagEndian::Big => {
if (data & (1 << i)) == 0 { self.i.push(false) } else { self.i.push(true) }
},
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) }
},
if (data & (1 << (count - 1 - i))) == 0 {
self.i.push(false)
} else {
self.i.push(true)
}
}
}
}
}
@ -109,11 +120,19 @@ impl JtagLeg {
for i in 0..count {
match endian {
JtagEndian::Big => {
if (data & (1 << i)) == 0 { self.i.push(false) } else { self.i.push(true) }
},
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) }
},
if (data & (1 << (count - 1 - i))) == 0 {
self.i.push(false)
} else {
self.i.push(true)
}
}
}
}
}
@ -131,11 +150,15 @@ impl JtagLeg {
match endian {
JtagEndian::Little => {
data <<= 1;
if self.o.pop().unwrap() { data |= 0x1; }
if self.o.pop().unwrap() {
data |= 0x1;
}
}
JtagEndian::Big => {
data >>= 1;
if self.o.pop().unwrap() { data |= 0x8000_0000; }
if self.o.pop().unwrap() {
data |= 0x8000_0000;
}
}
}
}
@ -158,11 +181,15 @@ impl JtagLeg {
match endian {
JtagEndian::Little => {
data <<= 1;
if self.o.pop().unwrap() { data |= 0x1; }
},
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; }
if self.o.pop().unwrap() {
data |= 0x8000_0000_0000_0000_0000_0000_0000_0000;
}
}
}
}
@ -183,11 +210,15 @@ impl JtagLeg {
match endian {
JtagEndian::Little => {
data <<= 1;
if self.o.pop().unwrap() { data |= 0x1; }
if self.o.pop().unwrap() {
data |= 0x1;
}
}
JtagEndian::Big => {
data >>= 1;
if self.o.pop().unwrap() { data |= 0x80; }
if self.o.pop().unwrap() {
data |= 0x80;
}
}
}
}
@ -195,25 +226,22 @@ impl JtagLeg {
Some(data)
}
pub fn tag(&self) -> String {
self.tag.clone()
}
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 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)
/// 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<JtagLeg>,
/// a vector of legs traversed. An entry is only put into the done vector once its traversal is completed.
/// a vector of legs traversed. An entry is only put into the done vector once its traversal is
/// completed.
done: Vec<JtagLeg>,
/// the current leg being processed
current: Option<JtagLeg>,
@ -236,9 +264,10 @@ impl JtagMach {
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;
let mut delay: u32 = us / 1000;
if delay == 0 {
delay = 1;
}
@ -246,54 +275,33 @@ impl JtagMach {
}
/// add() -- add a leg to the pending queue
pub fn add(&mut self, leg: JtagLeg) {
self.pending.push(leg);
}
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<JtagLeg> {
if self.done.len() > 0 {
Some(self.done.remove(0))
} else {
None
}
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_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.
/// 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
}
}
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()
}
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
}
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
@ -303,7 +311,7 @@ impl JtagMach {
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 {
@ -311,7 +319,7 @@ impl JtagMach {
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
@ -333,16 +341,16 @@ impl JtagMach {
}
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 {
@ -367,19 +375,19 @@ impl JtagMach {
// 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);
@ -401,7 +409,8 @@ impl JtagMach {
self.s = JtagState::TestReset;
}
/// next() -- advance until a RUN_IDLE state. If currently RUN_IDLE, traverse the next available leg, if one exists
/// 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 => {
@ -423,21 +432,22 @@ impl JtagMach {
} 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
// 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(feature="precursor", feature="renode"))]
#[cfg(any(feature = "precursor", feature = "renode"))]
mod implementation {
use utralib::generated::*;
@ -456,22 +466,22 @@ mod implementation {
)
.expect("couldn't map JTAG CSR range");
let jtag = JtagPhy {
csr: CSR::new(csr.as_mut_ptr() as *mut u32),
};
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})
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
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
@ -485,21 +495,15 @@ mod implementation {
// a stub to try to avoid breaking hosted mode for as long as possible.
#[cfg(not(target_os = "xous"))]
mod implementation {
pub struct JtagPhy {
}
pub struct JtagPhy {}
impl JtagPhy {
pub fn new() -> JtagPhy {
JtagPhy {
}
}
pub fn sync(&mut self, _tdi: bool, _tms: bool) -> bool {
false
}
pub fn new() -> JtagPhy { JtagPhy {} }
pub fn sync(&mut self, _tdi: bool, _tms: bool) -> bool { false }
}
}
fn main() -> ! {
log_server::init_wait().unwrap();
log::set_max_level(log::LevelFilter::Info);
@ -510,9 +514,9 @@ fn main() -> ! {
// - one connection from the key server
// - one connection from shellchat for command line
// - another connection from shellchat for oqc testing
#[cfg(all(any(feature="precursor", feature="renode"), not(feature="dvt")))]
#[cfg(all(any(feature = "precursor", feature = "renode"), not(feature = "dvt")))]
let jtag_sid = xns.register_name(api::SERVER_NAME_JTAG, Some(3)).expect("can't register server");
#[cfg(all(any(feature="precursor", feature="renode"), feature="dvt"))] // dvt build has less in it
#[cfg(all(any(feature = "precursor", feature = "renode"), feature = "dvt"))] // dvt build has less in it
let jtag_sid = xns.register_name(api::SERVER_NAME_JTAG, Some(2)).expect("can't register server");
#[cfg(not(target_os = "xous"))]
let jtag_sid = xns.register_name(api::SERVER_NAME_JTAG, Some(2)).expect("can't register server");
@ -536,7 +540,8 @@ fn main() -> ! {
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
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;
@ -548,7 +553,8 @@ fn main() -> ! {
jtag.dbg_reset();
jtag.next();
let d: u32 = jtag.dbg_get();
if let Some(mut iddata) = jtag.get() { // this contains the actual idcode data
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();
@ -562,7 +568,8 @@ fn main() -> ! {
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
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();
}
@ -582,7 +589,8 @@ fn main() -> ! {
}),
Some(Opcode::EfuseFetch) => {
efuse.fetch(&mut jtag);
let mut buffer = unsafe{Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap())};
let mut buffer =
unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) };
let mut efuse_rec = buffer.to_original::<EfuseRecord, _>().unwrap();
efuse_rec.user = efuse.phy_user();
@ -596,13 +604,15 @@ fn main() -> ! {
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
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 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);
@ -614,7 +624,9 @@ fn main() -> ! {
if efuse.is_valid() {
log::info!("efuse key is valid to burn, proceeding. There is no return...");
if cfg!(feature = "dry-run") {
log::info!("Dry run selected, key NOT BURNED. Device will be in an inconsistent state.");
log::info!(
"Dry run selected, key NOT BURNED. Device will be in an inconsistent state."
);
} else {
efuse.burn(&mut jtag);
}
@ -632,7 +644,9 @@ fn main() -> ! {
if efuse.is_valid() {
log::info!("control is valid to burn, proceeding. There is no return...");
if cfg!(feature = "dry-run") {
log::info!("Dry run selected, control fuses NOT BURNED. Device will be in an inconsistent state.");
log::info!(
"Dry run selected, control fuses NOT BURNED. Device will be in an inconsistent state."
);
} else {
efuse.burn(&mut jtag);
}
@ -650,7 +664,9 @@ fn main() -> ! {
if efuse.is_valid() {
log::info!("user fuses are valid to burn, proceeding. There is no return...");
if cfg!(feature = "dry-run") {
log::info!("Dry run selected, user fuse NOT BURNED. Device will be in an inconsistent state.");
log::info!(
"Dry run selected, user fuse NOT BURNED. Device will be in an inconsistent state."
);
} else {
efuse.burn(&mut jtag);
}
@ -663,7 +679,7 @@ fn main() -> ! {
}),
None => {
log::error!("couldn't convert opcode");
break
break;
}
}
}