Merge branch 'main' into gsora/wlan-manager
3
.gitignore
vendored
|
|
@ -36,6 +36,9 @@ tools/__pycache__
|
|||
# PDDB backup files
|
||||
*.pddb
|
||||
|
||||
# performance monitoring page table
|
||||
tools/ct_data/v2p.txt
|
||||
|
||||
# renode will tickle this every time you run it, but you shouldn't commit that back to the tree
|
||||
/emulation/linux-server-rootfs.jffs2
|
||||
|
||||
|
|
|
|||
10
Cargo.lock
generated
|
|
@ -2607,6 +2607,15 @@ version = "2.1.0"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d4fd5641d01c8f18a23da7b6fe29298ff4b55afcccdf78973b24cf3175fee32e"
|
||||
|
||||
[[package]]
|
||||
name = "perflib"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"log",
|
||||
"utralib",
|
||||
"xous",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pin-project-lite"
|
||||
version = "0.2.9"
|
||||
|
|
@ -3508,6 +3517,7 @@ dependencies = [
|
|||
"num-derive",
|
||||
"num-traits",
|
||||
"pddb",
|
||||
"perflib",
|
||||
"png",
|
||||
"rand 0.8.5",
|
||||
"rand_chacha 0.3.1",
|
||||
|
|
|
|||
|
|
@ -81,6 +81,7 @@ members = [
|
|||
"services/test-spawn/spawn",
|
||||
"services/usb-test",
|
||||
"services/usb-device-xous",
|
||||
"tools/perflib",
|
||||
"kernel",
|
||||
"loader",
|
||||
]
|
||||
|
|
|
|||
|
|
@ -250,6 +250,8 @@ perform the Xous firmware upgrade. This requires running manual update commands,
|
|||
- BitWarden export format is also supported by `vaultbackup-rs`.
|
||||
- backup and restore can only be run with user approval, accessed via the `vault` context menu and then selecting `Enable host readout`. Note that in this mode, any host can read vault secrets; therefore, the mode locks out the UI and when it is active.
|
||||
- highly experimental TLS support when the "tls" feature is enabled. Relies on a pure-Rust implementation of `ring` located in the `ring-xous` fork.
|
||||
- performance monitoring framework added. see `tools/perflib` and `services/shellchat/net_cmd.rs` for examples of how to use it.
|
||||
- HOTP support added to `vault`. HOTPs display in the TOTP window with the notation "HOTP" next to them, and they auto-increment on autotype. When creating new items in TOTP you are given the option to make an HOTP record, and you can convert between the two by editing the record and changing the bottom line from totp to hotp and vice-versa. The `timestep` field is re-used from the TOTP record to store the `count` for HOTP.
|
||||
|
||||
## Roadmap to 1.0
|
||||
|
||||
|
|
|
|||
|
|
@ -138,10 +138,28 @@
|
|||
"en-tts": "No"
|
||||
},
|
||||
"vault.newitem.totp_ss": {
|
||||
"en": "Enter the TOTP shared secret in Base32:",
|
||||
"ja": "Base32にTOTP共有シークレットを入力します。",
|
||||
"zh": "在 Base32 中输入 TOTP 共享密钥:",
|
||||
"en-tts": "Enter the TOTP shared secret in Base32:"
|
||||
"en": "Enter the OTP shared secret in Base32:",
|
||||
"ja": "Base32にOTP共有シークレットを入力します。",
|
||||
"zh": "在 Base32 中输入 OTP 共享密钥:",
|
||||
"en-tts": "Enter the OTP shared secret in Base32:"
|
||||
},
|
||||
"vault.newitem.is_t_or_h_otp": {
|
||||
"en": "Which type of OTP record is this (if you don't know, it's probably TOTP)?",
|
||||
"ja": "これはどのタイプの OTP レコードですか (わからない場合は、おそらく TOTP です)。",
|
||||
"zh": "这是哪种类型的 OTP 记录(如果您不知道,可能是 TOTP)?",
|
||||
"en-tts": "Which type of OTP record is this (if you don't know, it's probably TOTP)?"
|
||||
},
|
||||
"vault.newitem.totp": {
|
||||
"en": "TOTP",
|
||||
"ja": "TOTP",
|
||||
"zh": "TOTP",
|
||||
"en-tts": "TOTP"
|
||||
},
|
||||
"vault.newitem.hotp": {
|
||||
"en": "HOTP",
|
||||
"ja": "HOTP",
|
||||
"zh": "HOTP",
|
||||
"en-tts": "HOTP"
|
||||
},
|
||||
"vault.newitem.name": {
|
||||
"en": "Please name the credential:",
|
||||
|
|
|
|||
|
|
@ -343,6 +343,25 @@ impl ActionManager {
|
|||
},
|
||||
_ => {log::error!("Name entry failed"); self.action_active.store(false, Ordering::SeqCst); return}
|
||||
};
|
||||
|
||||
self.tt.sleep_ms(SWAP_DELAY_MS).unwrap();
|
||||
self.modals
|
||||
.add_list(vec![
|
||||
t!("vault.newitem.totp", xous::LANG),
|
||||
t!("vault.newitem.hotp", xous::LANG),
|
||||
]).expect("couldn't create configuration modal");
|
||||
let is_totp: bool;
|
||||
match self.modals.get_radiobutton(t!("vault.newitem.is_t_or_h_otp", xous::LANG)) {
|
||||
Ok(response) => {
|
||||
if &response == t!("vault.newitem.totp", xous::LANG) {
|
||||
is_totp = true;
|
||||
} else {
|
||||
is_totp = false;
|
||||
}
|
||||
}
|
||||
_ => {log::error!("Modal selection error"); self.action_active.store(false, Ordering::SeqCst); return}
|
||||
}
|
||||
|
||||
self.tt.sleep_ms(SWAP_DELAY_MS).unwrap();
|
||||
let secret = match self.modals
|
||||
.alert_builder(t!("vault.newitem.totp_ss", xous::LANG))
|
||||
|
|
@ -371,6 +390,7 @@ impl ActionManager {
|
|||
}
|
||||
};
|
||||
let validated_secret = base32::encode(base32::Alphabet::RFC4648 { padding: false }, &ss_vec);
|
||||
|
||||
// time, hash, etc. are all the "expected defaults" -- if you want to change them, edit the record after entering it.
|
||||
let mut totp = storage::TotpRecord {
|
||||
version: VAULT_TOTP_REC_VERSION,
|
||||
|
|
@ -378,8 +398,9 @@ impl ActionManager {
|
|||
secret: validated_secret,
|
||||
algorithm: TotpAlgorithm::HmacSha1,
|
||||
digits: 6,
|
||||
timestep: 30,
|
||||
ctime: 0,
|
||||
timestep: if is_totp {30} else {0},
|
||||
ctime: 0,
|
||||
is_hotp: !is_totp,
|
||||
notes: t!("vault.notes", xous::LANG).to_string(),
|
||||
};
|
||||
|
||||
|
|
@ -443,7 +464,7 @@ impl ActionManager {
|
|||
};
|
||||
|
||||
if choice.is_none() {
|
||||
let dict = VAULT_TOTP_DICT;
|
||||
let dict = U2F_APP_DICT;
|
||||
// at the moment only U2F records are supported for editing. The FIDO2 stuff is done with a different record
|
||||
// storage format that's a bit funkier to edit.
|
||||
let maybe_update = match self.pddb.borrow().get(
|
||||
|
|
@ -524,10 +545,12 @@ impl ActionManager {
|
|||
.field(Some(pw.timestep.to_string()), Some(password_validator))
|
||||
.field(Some(alg), Some(password_validator))
|
||||
.field(Some(pw.digits.to_string()), Some(password_validator))
|
||||
.field(Some(if pw.is_hotp {"HOTP".to_string()} else {"TOTP".to_string()}), Some(password_validator))
|
||||
.build().expect("modals error in edit");
|
||||
pw.name = edit_data.content()[0].content.as_str().unwrap().to_string();
|
||||
pw.secret = edit_data.content()[1].content.as_str().unwrap().to_string();
|
||||
pw.notes = edit_data.content()[2].content.as_str().unwrap().to_string();
|
||||
pw.is_hotp = if edit_data.content()[6].content.as_str().unwrap().to_string().to_uppercase() == "HOTP" {true} else {false};
|
||||
if let Ok(t) = u64::from_str_radix(edit_data.content()[3].content.as_str().unwrap(), 10) {
|
||||
pw.timestep = t;
|
||||
}
|
||||
|
|
@ -808,7 +831,13 @@ impl ActionManager {
|
|||
Ok(_len) => {
|
||||
if let Some(totp) = storage::TotpRecord::try_from(data).ok() {
|
||||
let alg: String = totp.algorithm.into();
|
||||
let extra = format!("{}:{}:{}:{}", totp.secret, totp.digits, totp.timestep, alg);
|
||||
let extra = format!("{}:{}:{}:{}:{}",
|
||||
totp.secret,
|
||||
totp.digits,
|
||||
totp.timestep,
|
||||
alg,
|
||||
if totp.is_hotp {"HOTP"} else {"TOTP"}
|
||||
);
|
||||
let desc = format!("{}", totp.name);
|
||||
let li = ListItem {
|
||||
name: desc,
|
||||
|
|
@ -947,7 +976,7 @@ impl ActionManager {
|
|||
strict: true,
|
||||
};
|
||||
let password = pg.generate_one().unwrap();
|
||||
let record = storage::PasswordRecord {
|
||||
let mut record = storage::PasswordRecord {
|
||||
version: VAULT_PASSWORD_REC_VERSION,
|
||||
description,
|
||||
username,
|
||||
|
|
@ -958,7 +987,7 @@ impl ActionManager {
|
|||
count: 0,
|
||||
};
|
||||
|
||||
match self.storage.borrow_mut().new_record(record, None) {
|
||||
match self.storage.borrow_mut().new_record(&mut record, None, true) {
|
||||
Ok(_) => {},
|
||||
Err(e) => log::error!("PW Error: {:?}", e),
|
||||
};
|
||||
|
|
@ -1058,7 +1087,7 @@ impl ActionManager {
|
|||
let notes = random_pick::pick_from_slice(&words, &weights).unwrap().to_string();
|
||||
let mut secret_bytes = [0u8; 10];
|
||||
self.trng.borrow_mut().fill_bytes(&mut secret_bytes);
|
||||
let record = storage::TotpRecord {
|
||||
let mut record = storage::TotpRecord {
|
||||
version: VAULT_TOTP_REC_VERSION,
|
||||
secret: base32::encode(base32::Alphabet::RFC4648 { padding: false }, &secret_bytes),
|
||||
name,
|
||||
|
|
@ -1067,15 +1096,16 @@ impl ActionManager {
|
|||
digits: 6,
|
||||
timestep: 30,
|
||||
ctime: 0,
|
||||
is_hotp: false,
|
||||
};
|
||||
|
||||
match self.storage.borrow_mut().new_record(record, None) {
|
||||
match self.storage.borrow_mut().new_record(&mut record, None, true) {
|
||||
Ok(_) => {},
|
||||
Err(e) => log::error!("PW Error: {:?}", e),
|
||||
};
|
||||
}
|
||||
// specific TOTP entry with a known shared secret for testing
|
||||
let record = storage::TotpRecord {
|
||||
let mut record = storage::TotpRecord {
|
||||
version: VAULT_TOTP_REC_VERSION,
|
||||
secret: "I65VU7K5ZQL7WB4E".to_string(),
|
||||
name: "totp@authenticationtest.com".to_string(),
|
||||
|
|
@ -1084,9 +1114,10 @@ impl ActionManager {
|
|||
digits: 6,
|
||||
timestep: 30,
|
||||
ctime: 0,
|
||||
is_hotp: false,
|
||||
};
|
||||
|
||||
match self.storage.borrow_mut().new_record(record, None) {
|
||||
match self.storage.borrow_mut().new_record(&mut record, None, true) {
|
||||
Ok(_) => {},
|
||||
Err(e) => log::error!("PW Error: {:?}", e),
|
||||
};
|
||||
|
|
|
|||
|
|
@ -12,7 +12,14 @@ const VAULT_PASSWORD_DICT: &'static str = "vault.passwords";
|
|||
const VAULT_TOTP_DICT: &'static str = "vault.totp";
|
||||
const VAULT_TOTP_ALLOC_HINT: usize = 128;
|
||||
const VAULT_PASSWORD_REC_VERSION: u32 = 1;
|
||||
const VAULT_TOTP_REC_VERSION: u32 = 1;
|
||||
|
||||
// Version history TOTP record:
|
||||
// - v1 created, basic record for TOTP
|
||||
// - v2 add HOTP support:
|
||||
// - `hotp` field added. If 1, then HOTP record. If not existent or not 1, then TOTP
|
||||
// - If HOTP, then the `timestep` field is re-purposed as the `count` field.
|
||||
// - v1 records read directly onto v2 records, and `hotp` is always `false` for v1 records
|
||||
const VAULT_TOTP_REC_VERSION: u32 = 2;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Error {
|
||||
|
|
@ -315,6 +322,7 @@ pub struct TotpRecord {
|
|||
pub digits: u32,
|
||||
pub timestep: u64,
|
||||
pub ctime: u64,
|
||||
pub is_hotp: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
|
|
@ -324,6 +332,7 @@ pub enum TOTPSerializationError {
|
|||
BadDigitsAmount,
|
||||
BadCtime,
|
||||
BadTimestep,
|
||||
BadHotp,
|
||||
MalformedInput,
|
||||
}
|
||||
|
||||
|
|
@ -389,6 +398,18 @@ impl StorageContent for TotpRecord {
|
|||
return Err(TOTPSerializationError::BadTimestep)?;
|
||||
}
|
||||
}
|
||||
"hotp" => {
|
||||
if let Ok(setting) = u8::from_str_radix(data, 10) {
|
||||
if setting != 0 {
|
||||
pr.is_hotp = true;
|
||||
} else {
|
||||
pr.is_hotp = false;
|
||||
}
|
||||
} else {
|
||||
log::warn!("hotp variant error");
|
||||
return Err(TOTPSerializationError::BadHotp)?;
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
log::warn!(
|
||||
"unexpected tag {} encountered parsing TOTP info, ignoring",
|
||||
|
|
@ -408,7 +429,7 @@ impl StorageContent for TotpRecord {
|
|||
fn to_vec(&self) -> Vec<u8> {
|
||||
let ta: String = self.algorithm.into();
|
||||
format!(
|
||||
"{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n",
|
||||
"{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n",
|
||||
"version",
|
||||
self.version,
|
||||
"secret",
|
||||
|
|
@ -423,6 +444,8 @@ impl StorageContent for TotpRecord {
|
|||
self.digits,
|
||||
"timestep",
|
||||
self.timestep,
|
||||
"hotp",
|
||||
if self.is_hotp {1} else {0},
|
||||
"ctime",
|
||||
self.ctime,
|
||||
)
|
||||
|
|
@ -451,6 +474,7 @@ impl TryFrom<Vec<u8>> for TotpRecord {
|
|||
digits: 0,
|
||||
ctime: 0,
|
||||
timestep: 0,
|
||||
is_hotp: false,
|
||||
};
|
||||
let lines = desc_str.split('\n');
|
||||
for line in lines {
|
||||
|
|
@ -497,6 +521,18 @@ impl TryFrom<Vec<u8>> for TotpRecord {
|
|||
return Err(TOTPSerializationError::BadTimestep);
|
||||
}
|
||||
}
|
||||
"hotp" => {
|
||||
if let Ok(setting) = u8::from_str_radix(data, 10) {
|
||||
if setting != 0 {
|
||||
pr.is_hotp = true;
|
||||
} else {
|
||||
pr.is_hotp = false;
|
||||
}
|
||||
} else {
|
||||
log::warn!("hotp error");
|
||||
return Err(TOTPSerializationError::BadHotp);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
log::warn!(
|
||||
"unexpected tag {} encountered parsing TOTP info, ignoring",
|
||||
|
|
@ -517,7 +553,7 @@ impl From<TotpRecord> for Vec<u8> {
|
|||
fn from(tr: TotpRecord) -> Self {
|
||||
let ta: String = tr.algorithm.into();
|
||||
format!(
|
||||
"{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n",
|
||||
"{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n",
|
||||
"version",
|
||||
tr.version,
|
||||
"secret",
|
||||
|
|
@ -532,6 +568,8 @@ impl From<TotpRecord> for Vec<u8> {
|
|||
tr.digits,
|
||||
"timestep",
|
||||
tr.timestep,
|
||||
"hotp",
|
||||
if tr.is_hotp {1} else {0},
|
||||
"ctime",
|
||||
tr.ctime,
|
||||
)
|
||||
|
|
|
|||
|
|
@ -573,6 +573,7 @@ pub(crate) fn deserialize_app_info(descriptor: Vec::<u8>) -> Option::<AppInfo> {
|
|||
log::trace!("invalid line skipped: {:?}", line);
|
||||
}
|
||||
}
|
||||
#[cfg(any(target_os = "none", target_os = "xous"))]
|
||||
if appinfo.name.len() > 0
|
||||
&& appinfo.id != [0u8; 32]
|
||||
&& appinfo.ctime != 0 { // atime can be 0 - indicates never used
|
||||
|
|
@ -580,6 +581,13 @@ pub(crate) fn deserialize_app_info(descriptor: Vec::<u8>) -> Option::<AppInfo> {
|
|||
} else {
|
||||
None
|
||||
}
|
||||
#[cfg(not(any(target_os = "none", target_os = "xous")))]
|
||||
if appinfo.name.len() > 0
|
||||
&& appinfo.id != [0u8; 32] { // atime can be 0 - indicates never used. In hosted mode, ctime is 0.
|
||||
Some(appinfo)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
|
|
|
|||
|
|
@ -291,7 +291,9 @@ impl VaultUx {
|
|||
}
|
||||
fn mark_as_dirty(&mut self, index: usize) {
|
||||
let list_len = self.filtered_list.len();
|
||||
self.filtered_list[index.min(list_len - 1)].dirty = true;
|
||||
if list_len > 0 {
|
||||
self.filtered_list[index.min(list_len - 1)].dirty = true;
|
||||
}
|
||||
}
|
||||
fn mark_screen_as_dirty(&mut self, index: usize) {
|
||||
let page = index as i16 / self.items_per_screen;
|
||||
|
|
@ -303,6 +305,17 @@ impl VaultUx {
|
|||
item.dirty = true;
|
||||
}
|
||||
}
|
||||
fn backpropagate_item(&mut self, updated_item: ListItem) -> bool {
|
||||
for item in self.item_list.lock().unwrap().iter_mut() {
|
||||
if item.guid == updated_item.guid {
|
||||
item.name = updated_item.name.to_string();
|
||||
item.extra = updated_item.extra.to_string();
|
||||
item.dirty = true;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
pub(crate) fn nav(&mut self, dir: NavDir) {
|
||||
match dir {
|
||||
NavDir::Up => {
|
||||
|
|
@ -576,26 +589,37 @@ impl VaultUx {
|
|||
VaultMode::Fido | VaultMode::Password => {write!(box_text, "{}\n{}", item.name, item.extra).ok();},
|
||||
VaultMode::Totp => {
|
||||
let fields = item.extra.split(':').collect::<Vec<&str>>();
|
||||
if fields.len() == 4 {
|
||||
if fields.len() == 5 {
|
||||
let shared_secret = base32::decode(
|
||||
base32::Alphabet::RFC4648 { padding: false }, fields[0])
|
||||
.unwrap_or(vec![]);
|
||||
let digit_count = u8::from_str_radix(fields[1], 10).unwrap_or(6);
|
||||
let step_seconds = u16::from_str_radix(fields[2], 10).unwrap_or(30);
|
||||
let algorithm = TotpAlgorithm::try_from(fields[2]).unwrap_or(TotpAlgorithm::HmacSha1);
|
||||
let step_seconds = u64::from_str_radix(fields[2], 10).unwrap_or(30);
|
||||
let algorithm = TotpAlgorithm::try_from(fields[3]).unwrap_or(TotpAlgorithm::HmacSha1);
|
||||
let is_hotp = fields[4].to_uppercase() == "HOTP";
|
||||
let totp = totp::TotpEntry {
|
||||
step_seconds,
|
||||
step_seconds: if !is_hotp {step_seconds as u16} else {1}, // step_seconds is re-used by hotp as the code.
|
||||
shared_secret,
|
||||
digit_count,
|
||||
algorithm
|
||||
};
|
||||
let code = generate_totp_code(
|
||||
totp::get_current_unix_time().unwrap_or(0),
|
||||
&totp
|
||||
).unwrap_or(t!("vault.error.record_error", xous::LANG).to_string());
|
||||
// why code on top? because the item.name can be very long, and it can wrap which would cause
|
||||
// the code to become hidden.
|
||||
write!(box_text, "{}\n{}", code, item.name).ok();
|
||||
if !is_hotp {
|
||||
let code = generate_totp_code(
|
||||
totp::get_current_unix_time().unwrap_or(0),
|
||||
&totp
|
||||
).unwrap_or(t!("vault.error.record_error", xous::LANG).to_string());
|
||||
// why code on top? because the item.name can be very long, and it can wrap which would cause
|
||||
// the code to become hidden.
|
||||
write!(box_text, "{}\n{}", code, item.name).ok();
|
||||
} else {
|
||||
let code = generate_totp_code(
|
||||
step_seconds,
|
||||
&totp
|
||||
).unwrap_or(t!("vault.error.record_error", xous::LANG).to_string());
|
||||
// why code on top? because the item.name can be very long, and it can wrap which would cause
|
||||
// the code to become hidden.
|
||||
write!(box_text, "HOTP {}\n{}", code, item.name).ok();
|
||||
}
|
||||
} else {
|
||||
write!(box_text, "{}", t!("vault.error.record_error", xous::LANG)).ok();
|
||||
}
|
||||
|
|
@ -734,27 +758,120 @@ impl VaultUx {
|
|||
}
|
||||
}
|
||||
self.pddb.borrow().sync().ok();
|
||||
// force a redraw of the record as the access count updated
|
||||
self.filtered_list[self.selection_index].dirty = true;
|
||||
self.backpropagate_item(self.filtered_list[self.selection_index].clone());
|
||||
}
|
||||
VaultMode::Totp => {
|
||||
let fields = self.filtered_list[self.selection_index].extra.split(':').collect::<Vec<&str>>();
|
||||
if fields.len() == 4 {
|
||||
if fields.len() == 5 {
|
||||
let shared_secret = base32::decode(
|
||||
base32::Alphabet::RFC4648 { padding: false }, fields[0])
|
||||
.unwrap_or(vec![]);
|
||||
let digit_count = u8::from_str_radix(fields[1], 10).unwrap_or(6);
|
||||
let step_seconds = u16::from_str_radix(fields[2], 10).unwrap_or(30);
|
||||
let algorithm = TotpAlgorithm::try_from(fields[2]).unwrap_or(TotpAlgorithm::HmacSha1);
|
||||
let step_seconds = u64::from_str_radix(fields[2], 10).unwrap_or(30);
|
||||
let algorithm = TotpAlgorithm::try_from(fields[3]).unwrap_or(TotpAlgorithm::HmacSha1);
|
||||
let is_hotp = fields[4] == "HOTP";
|
||||
let totp = totp::TotpEntry {
|
||||
step_seconds,
|
||||
step_seconds: if !is_hotp {step_seconds as u16} else {1}, // step_seconds is re-used by hotp as the code.
|
||||
shared_secret,
|
||||
digit_count,
|
||||
algorithm
|
||||
};
|
||||
let code = generate_totp_code(
|
||||
totp::get_current_unix_time().unwrap_or(0),
|
||||
&totp
|
||||
).unwrap_or(t!("vault.error.record_error", xous::LANG).to_string());
|
||||
self.usb_dev.send_str(&code).ok();
|
||||
let code = if !is_hotp {
|
||||
generate_totp_code(
|
||||
totp::get_current_unix_time().unwrap_or(0),
|
||||
&totp
|
||||
).unwrap_or(t!("vault.error.record_error", xous::LANG).to_string())
|
||||
} else {
|
||||
generate_totp_code(
|
||||
step_seconds,
|
||||
&totp
|
||||
).unwrap_or(t!("vault.error.record_error", xous::LANG).to_string())
|
||||
};
|
||||
match self.usb_dev.send_str(&code) {
|
||||
Ok(_) => {
|
||||
if is_hotp {
|
||||
// update the count once the HOTP has been typed successfully
|
||||
let entry = self.filtered_list[self.selection_index].guid.to_string();
|
||||
|
||||
// this get determines which basis the key is in
|
||||
let (basis, hotp_rec) = match self.pddb.borrow().get(
|
||||
crate::actions::VAULT_TOTP_DICT,
|
||||
&entry,
|
||||
None, true, true,
|
||||
Some(256), Some(crate::basis_change)
|
||||
) {
|
||||
Ok(mut app_data) => {
|
||||
let attr = app_data.attributes().expect("couldn't get attributes");
|
||||
let len = app_data.attributes().unwrap().len;
|
||||
let mut data = Vec::<u8>::with_capacity(len);
|
||||
data.resize(len, 0);
|
||||
match app_data.read_exact(&mut data) {
|
||||
Ok(_len) => {
|
||||
if let Some(mut totp_rec) = storage::TotpRecord::try_from(data).ok() {
|
||||
totp_rec.timestep += 1;
|
||||
(attr.basis, totp_rec)
|
||||
} else {
|
||||
log::error!("Couldn't deserialize HOTP: {:?}", entry);
|
||||
return Err(xous::Error::InternalError);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("Couldn't access HOTP key: {:?}", e);
|
||||
return Err(xous::Error::InternalError);
|
||||
},
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("error updating HOTP count: {:?}", e);
|
||||
return Err(xous::Error::InternalError);
|
||||
}
|
||||
};
|
||||
// remove the old entry, specifically only in the most recently open basis.
|
||||
match self.pddb.borrow().delete_key(crate::actions::VAULT_TOTP_DICT, &entry, Some(&basis)) {
|
||||
Ok(_) => {}
|
||||
Err(_e) => {
|
||||
return Err(xous::Error::InternalError);
|
||||
}
|
||||
}
|
||||
// update the "extra" field, because the timestep field has been altered
|
||||
let alg: String = hotp_rec.algorithm.into();
|
||||
self.filtered_list[self.selection_index].extra = format!("{}:{}:{}:{}:{}",
|
||||
hotp_rec.secret,
|
||||
hotp_rec.digits,
|
||||
hotp_rec.timestep,
|
||||
alg,
|
||||
if hotp_rec.is_hotp {"HOTP"} else {"TOTP"}
|
||||
);
|
||||
self.filtered_list[self.selection_index].dirty = true;
|
||||
self.backpropagate_item(self.filtered_list[self.selection_index].clone());
|
||||
// now write to disk
|
||||
match self.pddb.borrow().get(
|
||||
crate::actions::VAULT_TOTP_DICT, &entry, Some(&basis),
|
||||
false, true, Some(crate::actions::VAULT_ALLOC_HINT),
|
||||
Some(crate::basis_change)
|
||||
) {
|
||||
Ok(mut record) => {
|
||||
let ser: Vec<u8> = storage::TotpRecord::into(hotp_rec);
|
||||
match record.write(&ser) {
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
log::error!("couldn't update key {}: {:?}", entry, e);
|
||||
return Err(xous::Error::OutOfMemory);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("couldn't update key {}: {:?}", entry, e);
|
||||
return Err(xous::Error::OutOfMemory);
|
||||
}
|
||||
}
|
||||
self.pddb.borrow().sync().ok();
|
||||
}
|
||||
},
|
||||
_ => ()
|
||||
};
|
||||
}
|
||||
}
|
||||
_ => log::error!("Illegal state! we shouldn't be having an autotype on {:?}", mode_cache),
|
||||
|
|
|
|||
|
|
@ -274,6 +274,7 @@ fn handle_restore(data: Vec<u8>, xns: &xous_names::XousNames) -> Result<Vec<u8>,
|
|||
timestep: elem.step_seconds,
|
||||
ctime: 0, // Will be filled in later by storage::new_totp_record();
|
||||
notes: t!("vault.notes", xous::LANG).to_string(),
|
||||
is_hotp: false,
|
||||
};
|
||||
entries.push(Box::new(totp));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -35,6 +35,7 @@ gdbserver = ["gdbstub", "gdbstub_arch"]
|
|||
print-panics = []
|
||||
report-memory = ["stats_alloc"]
|
||||
wrap-print = []
|
||||
v2p = ["xous-kernel/v2p"]
|
||||
# default = ["print-panics", "debug-print", "wrap-print"]
|
||||
default = ["print-panics", "gdbserver"]
|
||||
|
||||
|
|
|
|||
|
|
@ -936,6 +936,14 @@ pub fn handle_inner(pid: PID, tid: TID, in_irq: bool, call: SysCall) -> SysCallR
|
|||
}),
|
||||
_ => Err(xous_kernel::Error::InvalidLimit),
|
||||
},
|
||||
#[cfg(feature="v2p")]
|
||||
SysCall::VirtToPhys(vaddr) => {
|
||||
let phys_addr = crate::arch::mem::virt_to_phys(vaddr as usize);
|
||||
match phys_addr {
|
||||
Ok(pa) => Ok(xous_kernel::Result::Scalar1(pa)),
|
||||
Err(_) => Err(xous_kernel::Error::BadAddress),
|
||||
}
|
||||
}
|
||||
/* https://github.com/betrusted-io/xous-core/issues/90
|
||||
SysCall::SetExceptionHandler(pc, sp) => SystemServices::with_mut(|ss| {
|
||||
ss.set_exception_handler(pid, pc, sp)
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
<device schemaVersion="1.1" xmlns:xs="http://www.w3.org/2001/XMLSchema-instance" xs:noNamespaceSchemaLocation="CMSIS-SVD.xsd" >
|
||||
<vendor>litex</vendor>
|
||||
<name>SOC</name>
|
||||
<description><![CDATA[Litex SoC 2022-09-10 18:39:50]]></description>
|
||||
<description><![CDATA[Litex SoC 2022-09-14 22:53:09]]></description>
|
||||
|
||||
<addressUnitBits>8</addressUnitBits>
|
||||
<width>32</width>
|
||||
|
|
@ -1222,10 +1222,10 @@ register to disable individual events.]]></description>
|
|||
<register>
|
||||
<name>GIT_GITREV</name>
|
||||
<description><![CDATA[First 32-bits of the git revision. This documentation was built from git rev
|
||||
``fa7c9335``, so this value is 4202468149, which should be enough to check out
|
||||
``c8094038``, so this value is 3356049464, which should be enough to check out
|
||||
the exact git version used to build this firmware.]]></description>
|
||||
<addressOffset>0x0014</addressOffset>
|
||||
<resetValue>0xfa7c9335</resetValue>
|
||||
<resetValue>0xc8094038</resetValue>
|
||||
<size>32</size>
|
||||
<fields>
|
||||
<field>
|
||||
|
|
@ -1242,7 +1242,7 @@ the exact git version used to build this firmware.]]></description>
|
|||
is ``1``, then the repository this was built from has one additional commit
|
||||
beyond the tag indicated in `MAJOR`, `MINOR`, and `REVISION`.]]></description>
|
||||
<addressOffset>0x0018</addressOffset>
|
||||
<resetValue>0x05</resetValue>
|
||||
<resetValue>0x07</resetValue>
|
||||
<size>32</size>
|
||||
<fields>
|
||||
<field>
|
||||
|
|
@ -3577,7 +3577,7 @@ inject too fast.]]></description>
|
|||
<name>SEED1</name>
|
||||
<description><![CDATA[Bits 32-63 of `SEED_SEED`. Seed used for the build]]></description>
|
||||
<addressOffset>0x0000</addressOffset>
|
||||
<resetValue>0x7012e077</resetValue>
|
||||
<resetValue>0x65c0105c</resetValue>
|
||||
<size>32</size>
|
||||
<fields>
|
||||
<field>
|
||||
|
|
@ -3592,7 +3592,7 @@ inject too fast.]]></description>
|
|||
<name>SEED0</name>
|
||||
<description><![CDATA[Bits 0-31 of `SEED_SEED`.]]></description>
|
||||
<addressOffset>0x0004</addressOffset>
|
||||
<resetValue>0x7406e67e</resetValue>
|
||||
<resetValue>0x66bd490a</resetValue>
|
||||
<size>32</size>
|
||||
<fields>
|
||||
<field>
|
||||
|
|
@ -7303,6 +7303,13 @@ the counters clear to 0 but then do not run.]]></description>
|
|||
<lsb>2</lsb>
|
||||
<description><![CDATA[If `1` indicates that there are events to read]]></description>
|
||||
</field>
|
||||
<field>
|
||||
<name>full</name>
|
||||
<msb>3</msb>
|
||||
<bitRange>[3:3]</bitRange>
|
||||
<lsb>3</lsb>
|
||||
<description><![CDATA[If `1` indicates that the buffer is full]]></description>
|
||||
</field>
|
||||
</fields>
|
||||
</register>
|
||||
<register>
|
||||
|
|
|
|||
|
|
@ -79,6 +79,7 @@ webpki-roots = {version = "0.22.4", optional = true}
|
|||
ring = {version = "0.16.20", optional = true} # for testing ring math functions
|
||||
tungstenite = {version = "0.17.3", optional = true, features = ["rustls-tls-webpki-roots"]}
|
||||
url = {version = "2.2.2", optional = true}
|
||||
perflib = {path="../../tools/perflib", optional = true}
|
||||
|
||||
# for the curve25519 tests
|
||||
# hardware acceleration adaptations are inserted into a fork of the main branch.
|
||||
|
|
@ -118,5 +119,5 @@ dbg-ecupdate = [] # for issuing manual commands to initiate an EC update (vs UX)
|
|||
test-rekey = []
|
||||
nettest = [] # batch network tests
|
||||
tls = ["rustls", "webpki-roots", "ring", "tungstenite", "url"]
|
||||
perfcounter = ["ring"]
|
||||
perfcounter = ["ring", "perflib", "xous/v2p"]
|
||||
default = [] # "debugprint"
|
||||
|
|
|
|||
|
|
@ -52,9 +52,9 @@ pub struct CommonEnv {
|
|||
boot_instant: std::time::Instant,
|
||||
/// make this communal so any number of commands can trigger or reset the performance counter, and/or perform logging
|
||||
#[cfg(feature="perfcounter")]
|
||||
perf_csr: CSR<u32>,
|
||||
perf_csr: AtomicCsr<u32>,
|
||||
#[cfg(feature="perfcounter")]
|
||||
event_csr: CSR::<u32>,
|
||||
event_csr: AtomicCsr::<u32>,
|
||||
}
|
||||
impl CommonEnv {
|
||||
pub fn register_handler(&mut self, verb: String::<256>) -> u32 {
|
||||
|
|
@ -196,9 +196,9 @@ impl CmdEnv {
|
|||
netmgr: net::NetManager::new(),
|
||||
boot_instant: std::time::Instant::now(),
|
||||
#[cfg(feature="perfcounter")]
|
||||
perf_csr: CSR::new(perf_csr.as_mut_ptr() as *mut u32),
|
||||
perf_csr: AtomicCsr::new(perf_csr.as_mut_ptr() as *mut u32),
|
||||
#[cfg(feature="perfcounter")]
|
||||
event_csr: CSR::new(event1_csr.as_mut_ptr() as *mut u32),
|
||||
event_csr: AtomicCsr::new(event1_csr.as_mut_ptr() as *mut u32),
|
||||
};
|
||||
//let fcc = Fcc::new(&mut common);
|
||||
#[cfg(feature="benchmarks")]
|
||||
|
|
|
|||
|
|
@ -23,8 +23,7 @@ use std::convert::TryInto;
|
|||
#[cfg(feature="tls")]
|
||||
use tungstenite::{WebSocket, stream::MaybeTlsStream};
|
||||
#[cfg(feature="perfcounter")]
|
||||
use utralib::generated::*;
|
||||
|
||||
use perflib::*;
|
||||
pub struct NetCmd {
|
||||
callback_id: Option<u32>,
|
||||
callback_conn: u32,
|
||||
|
|
@ -33,9 +32,19 @@ pub struct NetCmd {
|
|||
ping: Option<net::Ping>,
|
||||
#[cfg(feature="tls")]
|
||||
ws: Option<WebSocket<MaybeTlsStream<TcpStream>>>,
|
||||
#[cfg(feature="perfcounter")]
|
||||
perfbuf: xous::MemoryRange,
|
||||
}
|
||||
impl NetCmd {
|
||||
pub fn new(xns: &xous_names::XousNames) -> Self {
|
||||
#[cfg(feature="perfcounter")]
|
||||
let perfbuf = xous::syscall::map_memory(
|
||||
None,
|
||||
None,
|
||||
BUFLEN,
|
||||
xous::MemoryFlags::R | xous::MemoryFlags::W | xous::MemoryFlags::RESERVE,
|
||||
).expect("couldn't map in the performance buffer");
|
||||
|
||||
NetCmd {
|
||||
callback_id: None,
|
||||
callback_conn: xns.request_connection_blocking(crate::SERVER_NAME_SHELLCHAT).unwrap(),
|
||||
|
|
@ -44,6 +53,8 @@ impl NetCmd {
|
|||
ping: None,
|
||||
#[cfg(feature="tls")]
|
||||
ws: None,
|
||||
#[cfg(feature="perfcounter")]
|
||||
perfbuf,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -500,34 +511,50 @@ impl<'a> ShellCmdApi<'a> for NetCmd {
|
|||
log::info!("{}", std::str::from_utf8(&plaintext).unwrap_or("utf-error"));
|
||||
log::set_max_level(log::LevelFilter::Info);
|
||||
}
|
||||
// note: to use the `perfcounter` option, you need to load a version of the SOC that has the performance counters built in.
|
||||
// this can be generated using the command `python3 .\betrusted_soc.py -e .\dummy.nky --perfcounter` in the betrusted-soc repo.
|
||||
//
|
||||
// to read out performance monitoring data, use the `usb_update.py` script as follows:
|
||||
// ` python3 .\..\usb_update.py --dump v2p.txt --dump-file .\ring_aes_8.bin`
|
||||
// where the `v2p.txt` file contains a virtual to physical mapping that is generated by the `perflib` framework and
|
||||
// formatted in a fashion that can be automatically extracted by the usb_update script.
|
||||
// the command below can generate this page table; it must be manually copy/pasted from the console
|
||||
// into the `v2p.txt` file. Note that it will change on every boot, but it is stable throughout each boot,
|
||||
// even across multiple runs of the command.
|
||||
#[cfg(feature="perfcounter")]
|
||||
"v2p" => {
|
||||
// don't generate a new object since it clears the data, just do a raw dump
|
||||
log::info!("Buf vmem loc: {:x}", self.perfbuf.as_ptr() as u32);
|
||||
log::info!("Buf pmem loc: {:x}", xous::syscall::virt_to_phys(self.perfbuf.as_ptr() as usize).unwrap_or(0));
|
||||
log::info!("PerfLogEntry size: {}", core::mem::size_of::<PerfLogEntry>());
|
||||
log::info!("Now printing the page table mapping for the performance buffer:");
|
||||
for page in (0..BUFLEN).step_by(4096) {
|
||||
log::info!("V|P {:x} {:x}",
|
||||
self.perfbuf.as_ptr() as usize + page,
|
||||
xous::syscall::virt_to_phys(self.perfbuf.as_ptr() as usize + page).unwrap_or(0),
|
||||
);
|
||||
}
|
||||
}
|
||||
#[cfg(feature="perfcounter")]
|
||||
"cta1" => {
|
||||
log::info!("constant time RISC-V HW AES test");
|
||||
env.perf_csr.wfo(utra::perfcounter::RUN_STOP, 1);
|
||||
|
||||
// stop the counter if it would rollover
|
||||
env.perf_csr.wo(utra::perfcounter::SATURATE_LIMIT0, 0xFFFF_FFFF);
|
||||
env.perf_csr.wo(utra::perfcounter::SATURATE_LIMIT1, 0);
|
||||
|
||||
// configure the system
|
||||
env.perf_csr.wo(utra::perfcounter::CONFIG,
|
||||
env.perf_csr.ms(utra::perfcounter::CONFIG_PRESCALER, 0)
|
||||
| env.perf_csr.ms(utra::perfcounter::CONFIG_SATURATE, 1)
|
||||
| env.perf_csr.ms(utra::perfcounter::CONFIG_EVENT_WIDTH_MINUS_ONE, 31)
|
||||
let pm = PerfMgr::new(
|
||||
self.perfbuf.as_mut_ptr(),
|
||||
env.perf_csr.clone(),
|
||||
env.event_csr.clone()
|
||||
);
|
||||
pm.stop_and_reset();
|
||||
|
||||
// this starts the performance counter
|
||||
log::info!("== restart ==");
|
||||
env.perf_csr.wfo(utra::perfcounter::RUN_RESET_RUN, 1);
|
||||
pm.start();
|
||||
|
||||
use aes::Aes256;
|
||||
use aes::cipher::{BlockDecrypt, BlockEncrypt, KeyInit};
|
||||
use aes::cipher::{BlockEncrypt, KeyInit};
|
||||
use aes::cipher::generic_array::GenericArray;
|
||||
|
||||
let mut key_array: [u8; 32];
|
||||
let mut data_array: [u8; 16];
|
||||
const MAX_ENTRIES: u32 = 4096;
|
||||
let mut entries: u32 = 0; // track the number of entries we've used up
|
||||
for databit in 0..128 {
|
||||
data_array = [0; 16];
|
||||
data_array[databit / 8] = 1 << databit % 8;
|
||||
|
|
@ -536,68 +563,43 @@ impl<'a> ShellCmdApi<'a> for NetCmd {
|
|||
key_array[keybit / 8] = 1 << keybit % 8;
|
||||
let cipher_hw = Aes256::new(&key_array.into());
|
||||
let mut block = GenericArray::clone_from_slice(&mut data_array);
|
||||
|
||||
// demarcate the encryption operation performance counter events
|
||||
entries += 1;
|
||||
env.event_csr.wfo(utra::event_source1::PERFEVENT_CODE,
|
||||
((databit as u32) << 8) | keybit as u32);
|
||||
pm.log_event_unchecked(((databit as u32) << 8) | keybit as u32);
|
||||
cipher_hw.encrypt_block(&mut block);
|
||||
env.event_csr.wfo(utra::event_source1::PERFEVENT_CODE,
|
||||
0x100_0000 | ((databit as u32) << 8) | keybit as u32);
|
||||
entries += 1;
|
||||
if entries >= MAX_ENTRIES {
|
||||
// stop the counter
|
||||
env.perf_csr.wfo(utra::perfcounter::RUN_STOP, 1);
|
||||
// read out the events and print them
|
||||
while env.perf_csr.rf(utra::perfcounter::STATUS_READABLE) == 1 {
|
||||
let code = env.perf_csr.r(utra::perfcounter::EVENT_RAW0);
|
||||
let time = env.perf_csr.r(utra::perfcounter::EVENT_RAW1);
|
||||
let index = env.perf_csr.r(utra::perfcounter::EVENT_INDEX);
|
||||
log::info!("{}:{}:{}", index, time, code)
|
||||
}
|
||||
// restart the counter
|
||||
log::info!("== restart ==");
|
||||
entries = 0;
|
||||
env.perf_csr.wfo(utra::perfcounter::RUN_RESET_RUN, 1);
|
||||
}
|
||||
pm.log_event_unchecked(0x100_0000 | ((databit as u32) << 8) | keybit as u32);
|
||||
}
|
||||
if databit % 4 == 3 {
|
||||
pm.flush().ok();
|
||||
}
|
||||
}
|
||||
// stop the counter
|
||||
env.perf_csr.wfo(utra::perfcounter::RUN_STOP, 1);
|
||||
// read out the events and print them
|
||||
while env.perf_csr.rf(utra::perfcounter::STATUS_READABLE) == 1 {
|
||||
let code = env.perf_csr.r(utra::perfcounter::EVENT_RAW0);
|
||||
let time = env.perf_csr.r(utra::perfcounter::EVENT_RAW1);
|
||||
let index = env.perf_csr.r(utra::perfcounter::EVENT_INDEX);
|
||||
log::info!("{}:{}:{}", index, time, code)
|
||||
match pm.stop_and_flush() {
|
||||
Ok(entries) => {
|
||||
log::info!("entries: {}", entries);
|
||||
}
|
||||
_ => {
|
||||
log::info!("Perfcounter OOM'd during run");
|
||||
}
|
||||
}
|
||||
// pm.print_page_table();
|
||||
}
|
||||
#[cfg(feature="perfcounter")]
|
||||
"cta2" => {
|
||||
use ring::xous_test::aes_nohw::aes_key_st;
|
||||
|
||||
log::info!("constant time ring-xous test");
|
||||
env.perf_csr.wfo(utra::perfcounter::RUN_STOP, 1);
|
||||
|
||||
// stop the counter if it would rollover
|
||||
env.perf_csr.wo(utra::perfcounter::SATURATE_LIMIT0, 0xFFFF_FFFF);
|
||||
env.perf_csr.wo(utra::perfcounter::SATURATE_LIMIT1, 0);
|
||||
|
||||
// configure the system
|
||||
env.perf_csr.wo(utra::perfcounter::CONFIG,
|
||||
env.perf_csr.ms(utra::perfcounter::CONFIG_PRESCALER, 0)
|
||||
| env.perf_csr.ms(utra::perfcounter::CONFIG_SATURATE, 1)
|
||||
| env.perf_csr.ms(utra::perfcounter::CONFIG_EVENT_WIDTH_MINUS_ONE, 31)
|
||||
let pm = PerfMgr::new(
|
||||
self.perfbuf.as_mut_ptr(),
|
||||
env.perf_csr.clone(),
|
||||
env.event_csr.clone()
|
||||
);
|
||||
pm.stop_and_reset();
|
||||
|
||||
// this starts the performance counter
|
||||
log::info!("== restart ==");
|
||||
env.perf_csr.wfo(utra::perfcounter::RUN_RESET_RUN, 1);
|
||||
pm.start();
|
||||
|
||||
use ring::xous_test::aes_nohw::aes_key_st;
|
||||
|
||||
let mut key_array: [u8; 32];
|
||||
let mut data_array: [u8; 16];
|
||||
let mut out_array: [u8; 16] = [0u8; 16];
|
||||
const MAX_ENTRIES: u32 = 4096;
|
||||
let mut entries: u32 = 0; // track the number of entries we've used up
|
||||
for databit in 0..128 {
|
||||
data_array = [0; 16];
|
||||
data_array[databit / 8] = 1 << databit % 8;
|
||||
|
|
@ -610,38 +612,21 @@ impl<'a> ShellCmdApi<'a> for NetCmd {
|
|||
};
|
||||
ring::xous_test::expand_aes_key(&key_array, &mut schedule);
|
||||
// demarcate the encryption operation performance counter events
|
||||
entries += 1;
|
||||
env.event_csr.wfo(utra::event_source1::PERFEVENT_CODE,
|
||||
((databit as u32) << 8) | keybit as u32);
|
||||
pm.log_event_unchecked(((databit as u32) << 8) | keybit as u32);
|
||||
ring::xous_test::aes_encrypt(&data_array, &mut out_array, &schedule);
|
||||
env.event_csr.wfo(utra::event_source1::PERFEVENT_CODE,
|
||||
0x100_0000 | ((databit as u32) << 8) | keybit as u32);
|
||||
entries += 1;
|
||||
if entries >= MAX_ENTRIES {
|
||||
// stop the counter
|
||||
env.perf_csr.wfo(utra::perfcounter::RUN_STOP, 1);
|
||||
// read out the events and print them
|
||||
while env.perf_csr.rf(utra::perfcounter::STATUS_READABLE) == 1 {
|
||||
let code = env.perf_csr.r(utra::perfcounter::EVENT_RAW0);
|
||||
let time = env.perf_csr.r(utra::perfcounter::EVENT_RAW1);
|
||||
let index = env.perf_csr.r(utra::perfcounter::EVENT_INDEX);
|
||||
log::info!("{}:{}:{}", index, time, code)
|
||||
}
|
||||
// restart the counter
|
||||
log::info!("== restart ==");
|
||||
entries = 0;
|
||||
env.perf_csr.wfo(utra::perfcounter::RUN_RESET_RUN, 1);
|
||||
}
|
||||
pm.log_event_unchecked(0x100_0000 | ((databit as u32) << 8) | keybit as u32);
|
||||
}
|
||||
if databit % 4 == 3 {
|
||||
pm.flush().ok();
|
||||
}
|
||||
}
|
||||
// stop the counter
|
||||
env.perf_csr.wfo(utra::perfcounter::RUN_STOP, 1);
|
||||
// read out the events and print them
|
||||
while env.perf_csr.rf(utra::perfcounter::STATUS_READABLE) == 1 {
|
||||
let code = env.perf_csr.r(utra::perfcounter::EVENT_RAW0);
|
||||
let time = env.perf_csr.r(utra::perfcounter::EVENT_RAW1);
|
||||
let index = env.perf_csr.r(utra::perfcounter::EVENT_INDEX);
|
||||
log::info!("{}:{}:{}", index, time, code)
|
||||
match pm.stop_and_flush() {
|
||||
Ok(entries) => {
|
||||
log::info!("entries: {}", entries);
|
||||
}
|
||||
_ => {
|
||||
log::info!("Perfcounter OOM'd during run");
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(any(target_os = "none", target_os = "xous"))]
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
{
|
||||
"socup.candidate": {
|
||||
"ja": "ゲートウェアの更新候補が見つかりました。\n\n適用する必要がありますか?",
|
||||
"en": "An update candidate for the SoC was found.\n\nShould we apply it?",
|
||||
"en": "An update candidate for the SoC was found.\n\nShould we apply it?\n\nNOTE: if you just installed an update, try rebooting using a paperclip in the hole in the lower right hand corner. This forces the latest image to load.",
|
||||
"zh": "找到了网关软件的更新候选者。\n\n我们应该应用它吗?",
|
||||
"en-tts": "An update candidate for the SoC was found.\n\nShould we apply it?"
|
||||
"en-tts": "An update candidate for the SoC was found.\n\nShould we apply it?\n\nNOTE: if you just installed an update, try rebooting using a paperclip in the hole in the lower right hand corner. This forces the latest image to load."
|
||||
},
|
||||
"rekey.fail": {
|
||||
"ja": "キーの再生成に失敗しました。再起動して再試行してください。\n理由:",
|
||||
|
|
|
|||
|
|
@ -655,6 +655,17 @@ where
|
|||
base: AtomicPtr::new(base)
|
||||
}
|
||||
}
|
||||
/// In reality, we should wrap this in an `Arc` so we can be truly safe across a multi-core
|
||||
/// implementation, but for our single-core system this is fine. The reason we don't do it
|
||||
/// immediately is that UTRA also needs to work in a `no_std` environment, where `Arc`
|
||||
/// does not exist, and so additional config flags would need to be introduced to not break
|
||||
/// that compability issue. If migrating to multicore, this technical debt would have to be
|
||||
/// addressed.
|
||||
pub fn clone(&self) -> Self {
|
||||
AtomicCsr {
|
||||
base: AtomicPtr::new(self.base.load(core::sync::atomic::Ordering::SeqCst))
|
||||
}
|
||||
}
|
||||
/// Read the contents of this register
|
||||
pub fn r(&self, reg: Register) -> T {
|
||||
// prevent re-ordering
|
||||
|
|
|
|||
|
|
@ -1,6 +1,5 @@
|
|||
#! /usr/bin/env python3
|
||||
import argparse
|
||||
import re
|
||||
import numpy as np
|
||||
from PIL import Image as im
|
||||
import random
|
||||
|
|
@ -37,6 +36,9 @@ def main():
|
|||
parser.add_argument(
|
||||
"--file", default=False, help="file to analyze", type=str
|
||||
)
|
||||
parser.add_argument(
|
||||
"--average", default=False, help="average over a series. `file` is a root name; data series is hard-coded for now", action="store_true"
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.file is None:
|
||||
|
|
@ -47,35 +49,48 @@ def main():
|
|||
|
||||
rekey_start = 0
|
||||
enc_start = 0
|
||||
enc_times = np.arange(256*128).reshape((256, 128))
|
||||
rekey_times = np.arange(256*128).reshape((256, 128))
|
||||
with open(args.file, "r", encoding='utf-8', errors='replace') as f:
|
||||
lines = f.readlines()
|
||||
for line in lines:
|
||||
if '== restart ==' in line:
|
||||
rekey_start = 0
|
||||
rgx = re.search('.*net_cmd: ([0-9]*):([0-9]*):([0-9]*).*', line)
|
||||
if rgx is not None:
|
||||
perfdata = rgx.groups()
|
||||
timestamp = int(perfdata[1])
|
||||
code = int(perfdata[2])
|
||||
enc_times = np.zeros((256, 128))
|
||||
rekey_times = np.zeros((256, 128))
|
||||
|
||||
if args.average:
|
||||
flist = []
|
||||
for i in range(1,9):
|
||||
flist += [args.file + str(i) + ".bin"]
|
||||
else:
|
||||
flist = [args.file]
|
||||
|
||||
for fname in flist:
|
||||
with open(fname, "rb") as f:
|
||||
data = f.read()
|
||||
entries = [data[i:i+8] for i in range(0, len(data), 8)]
|
||||
for entry in entries:
|
||||
code = int.from_bytes(entry[:4], 'little')
|
||||
timestamp = int.from_bytes(entry[4:], 'little')
|
||||
keybit = code & 0xFF
|
||||
databit = (code >> 8) & 0xFF
|
||||
start = (code & 0x100_0000) == 0
|
||||
if start:
|
||||
rekey_times[keybit][databit] = timestamp - rekey_start
|
||||
rekey_times[keybit][databit] += timestamp - rekey_start
|
||||
enc_start = timestamp
|
||||
else:
|
||||
enc_times[keybit][databit] = timestamp - enc_start
|
||||
enc_times[keybit][databit] += timestamp - enc_start
|
||||
rekey_start = timestamp
|
||||
|
||||
#print('enc time sample')
|
||||
#for i in range(32):
|
||||
# print('{}'.format(enc_times[i]))
|
||||
#print('rekey time sample')
|
||||
#print('{}'.format(rekey_times[0]))
|
||||
rekey_times = rekey_times / len(flist)
|
||||
enc_times = enc_times / len(flist)
|
||||
|
||||
print('enc time sample')
|
||||
for i in range(32):
|
||||
print('{}'.format(enc_times[i]))
|
||||
print('rekey time sample')
|
||||
print('{}'.format(rekey_times[0]))
|
||||
print("enc: mean {} / max {}".format(enc_times.mean(), enc_times.max()))
|
||||
enc_hist = np.histogram(enc_times, bins=32)
|
||||
hw_range = (3800,4400)
|
||||
ring_range = (12000,13000)
|
||||
hist, bins = enc_hist = np.histogram(enc_times, bins=64, range=hw_range)
|
||||
from matplotlib import pyplot as plt
|
||||
plt.hist(enc_times, bins=bins)
|
||||
plt.savefig('hist.png')
|
||||
print(enc_hist)
|
||||
print("enc typical cycles: {}".format(enc_hist[1][0]))
|
||||
print("rekey: mean {} / max {}".format(rekey_times.mean(), rekey_times.max()))
|
||||
|
|
|
|||
BIN
tools/ct_data/hist_hw1.png
Normal file
|
After Width: | Height: | Size: 11 KiB |
BIN
tools/ct_data/hist_hwavg.png
Normal file
|
After Width: | Height: | Size: 11 KiB |
BIN
tools/ct_data/hist_ring1.png
Normal file
|
After Width: | Height: | Size: 10 KiB |
BIN
tools/ct_data/hist_ringavg.png
Normal file
|
After Width: | Height: | Size: 10 KiB |
|
Before Width: | Height: | Size: 9.9 KiB After Width: | Height: | Size: 9.9 KiB |
|
Before Width: | Height: | Size: 12 KiB After Width: | Height: | Size: 12 KiB |
BIN
tools/ct_data/hw_aes_1.bin
Normal file
BIN
tools/ct_data/hw_aes_1_enc.png
Normal file
|
After Width: | Height: | Size: 8.1 KiB |
BIN
tools/ct_data/hw_aes_1_enc_r.png
Normal file
|
After Width: | Height: | Size: 10 KiB |
BIN
tools/ct_data/hw_aes_1_rekey.png
Normal file
|
After Width: | Height: | Size: 11 KiB |
BIN
tools/ct_data/hw_aes_1_rekey_r.png
Normal file
|
After Width: | Height: | Size: 18 KiB |
BIN
tools/ct_data/hw_aes_2.bin
Normal file
BIN
tools/ct_data/hw_aes_2_enc.png
Normal file
|
After Width: | Height: | Size: 9.7 KiB |
BIN
tools/ct_data/hw_aes_2_enc_r.png
Normal file
|
After Width: | Height: | Size: 9.3 KiB |
BIN
tools/ct_data/hw_aes_2_rekey.png
Normal file
|
After Width: | Height: | Size: 177 B |
BIN
tools/ct_data/hw_aes_2_rekey_r.png
Normal file
|
After Width: | Height: | Size: 434 B |
BIN
tools/ct_data/hw_aes_3.bin
Normal file
BIN
tools/ct_data/hw_aes_4.bin
Normal file
BIN
tools/ct_data/hw_aes_5.bin
Normal file
BIN
tools/ct_data/hw_aes_6.bin
Normal file
BIN
tools/ct_data/hw_aes_7.bin
Normal file
BIN
tools/ct_data/hw_aes_8.bin
Normal file
BIN
tools/ct_data/hw_aes__enc.png
Normal file
|
After Width: | Height: | Size: 16 KiB |
BIN
tools/ct_data/hw_aes__enc_r.png
Normal file
|
After Width: | Height: | Size: 14 KiB |
BIN
tools/ct_data/hw_aes__rekey.png
Normal file
|
After Width: | Height: | Size: 177 B |
BIN
tools/ct_data/hw_aes__rekey_r.png
Normal file
|
After Width: | Height: | Size: 438 B |
|
Before Width: | Height: | Size: 30 KiB After Width: | Height: | Size: 28 KiB |
|
Before Width: | Height: | Size: 28 KiB After Width: | Height: | Size: 35 KiB |
BIN
tools/ct_data/ring_aes_1.bin
Normal file
BIN
tools/ct_data/ring_aes_1_enc.png
Normal file
|
After Width: | Height: | Size: 12 KiB |
BIN
tools/ct_data/ring_aes_1_enc_r.png
Normal file
|
After Width: | Height: | Size: 9.5 KiB |
BIN
tools/ct_data/ring_aes_1_rekey.png
Normal file
|
After Width: | Height: | Size: 14 KiB |
BIN
tools/ct_data/ring_aes_1_rekey_r.png
Normal file
|
After Width: | Height: | Size: 19 KiB |
BIN
tools/ct_data/ring_aes_2.bin
Normal file
BIN
tools/ct_data/ring_aes_3.bin
Normal file
BIN
tools/ct_data/ring_aes_4.bin
Normal file
BIN
tools/ct_data/ring_aes_5.bin
Normal file
BIN
tools/ct_data/ring_aes_6.bin
Normal file
BIN
tools/ct_data/ring_aes_7.bin
Normal file
BIN
tools/ct_data/ring_aes_8.bin
Normal file
BIN
tools/ct_data/ring_aes__enc.png
Normal file
|
After Width: | Height: | Size: 27 KiB |
BIN
tools/ct_data/ring_aes__enc_r.png
Normal file
|
After Width: | Height: | Size: 25 KiB |
BIN
tools/ct_data/ring_aes__rekey.png
Normal file
|
After Width: | Height: | Size: 177 B |
BIN
tools/ct_data/ring_aes__rekey_r.png
Normal file
|
After Width: | Height: | Size: 440 B |
|
|
@ -1,739 +0,0 @@
|
|||
#! /usr/bin/env python3
|
||||
|
||||
import argparse
|
||||
|
||||
import usb.core
|
||||
import usb.util
|
||||
import array
|
||||
import sys
|
||||
import hashlib
|
||||
import csv
|
||||
import urllib.request
|
||||
|
||||
from progressbar.bar import ProgressBar
|
||||
|
||||
class PrecursorUsb:
|
||||
def __init__(self, dev):
|
||||
self.dev = dev
|
||||
self.RDSR = 0x05
|
||||
self.RDSCUR = 0x2B
|
||||
self.RDID = 0x9F
|
||||
self.WREN = 0x06
|
||||
self.WRDI = 0x04
|
||||
self.SE4B = 0x21
|
||||
self.BE4B = 0xDC
|
||||
self.PP4B = 0x12
|
||||
self.registers = {}
|
||||
self.regions = {}
|
||||
self.gitrev = ''
|
||||
|
||||
def register(self, name):
|
||||
return int(self.registers[name], 0)
|
||||
|
||||
def peek(self, addr, display=False):
|
||||
_dummy_s = '\x00'.encode('utf-8')
|
||||
data = array.array('B', _dummy_s * 4)
|
||||
|
||||
numread = self.dev.ctrl_transfer(bmRequestType=(0x80 | 0x43), bRequest=0,
|
||||
wValue=(addr & 0xffff), wIndex=((addr >> 16) & 0xffff),
|
||||
data_or_wLength=data, timeout=500)
|
||||
|
||||
read_data = int.from_bytes(data.tobytes(), byteorder='little', signed=False)
|
||||
if display == True:
|
||||
print("0x{:08x}".format(read_data))
|
||||
return read_data
|
||||
|
||||
def poke(self, addr, wdata, check=False, display=False):
|
||||
if check == True:
|
||||
_dummy_s = '\x00'.encode('utf-8')
|
||||
data = array.array('B', _dummy_s * 4)
|
||||
|
||||
numread = self.dev.ctrl_transfer(bmRequestType=(0x80 | 0x43), bRequest=0,
|
||||
wValue=(addr & 0xffff), wIndex=((addr >> 16) & 0xffff),
|
||||
data_or_wLength=data, timeout=500)
|
||||
|
||||
read_data = int.from_bytes(data.tobytes(), byteorder='little', signed=False)
|
||||
print("before poke: 0x{:08x}".format(read_data))
|
||||
|
||||
data = array.array('B', wdata.to_bytes(4, 'little'))
|
||||
numwritten = self.dev.ctrl_transfer(bmRequestType=(0x00 | 0x43), bRequest=0,
|
||||
wValue=(addr & 0xffff), wIndex=((addr >> 16) & 0xffff),
|
||||
data_or_wLength=data, timeout=500)
|
||||
|
||||
if check == True:
|
||||
_dummy_s = '\x00'.encode('utf-8')
|
||||
data = array.array('B', _dummy_s * 4)
|
||||
|
||||
numread = self.dev.ctrl_transfer(bmRequestType=(0x80 | 0x43), bRequest=0,
|
||||
wValue=(addr & 0xffff), wIndex=((addr >> 16) & 0xffff),
|
||||
data_or_wLength=data, timeout=500)
|
||||
|
||||
read_data = int.from_bytes(data.tobytes(), byteorder='little', signed=False)
|
||||
print("after poke: 0x{:08x}".format(read_data))
|
||||
if display == True:
|
||||
print("wrote 0x{:08x} to 0x{:08x}".format(wdata, addr))
|
||||
|
||||
def burst_read(self, addr, len):
|
||||
_dummy_s = '\x00'.encode('utf-8')
|
||||
maxlen = 4096
|
||||
|
||||
ret = bytearray()
|
||||
packet_count = len // maxlen
|
||||
if (len % maxlen) != 0:
|
||||
packet_count += 1
|
||||
|
||||
for pkt_num in range(packet_count):
|
||||
cur_addr = addr + pkt_num * maxlen
|
||||
if pkt_num == packet_count - 1:
|
||||
if len % maxlen != 0:
|
||||
bufsize = len % maxlen
|
||||
else:
|
||||
bufsize = maxlen
|
||||
else:
|
||||
bufsize = maxlen
|
||||
|
||||
data = array.array('B', _dummy_s * bufsize)
|
||||
numread = self.dev.ctrl_transfer(bmRequestType=(0x80 | 0x43), bRequest=0,
|
||||
wValue=(cur_addr & 0xffff), wIndex=((cur_addr >> 16) & 0xffff),
|
||||
data_or_wLength=data, timeout=500)
|
||||
|
||||
if numread != bufsize:
|
||||
print("Burst read error: {} bytes requested, {} bytes read at 0x{:08x}".format(bufsize, numread, cur_addr))
|
||||
exit(1)
|
||||
|
||||
ret = ret + data
|
||||
|
||||
return ret
|
||||
|
||||
def burst_write(self, addr, data):
|
||||
if len(data) == 0:
|
||||
return
|
||||
|
||||
# the actual "addr" doesn't matter for a burst_write, because it's specified
|
||||
# as an argument to the flash_pp4b command. We lock out access to the base of
|
||||
# SPINOR because it's part of the gateware, so, we pick a "safe" address to
|
||||
# write to instead. The page write responder will aggregate any write data
|
||||
# to anywhere in the SPINOR address range.
|
||||
writebuf_addr = 0x2098_0000 # the current start address of the kernel, for example
|
||||
|
||||
maxlen = 4096
|
||||
packet_count = len(data) // maxlen
|
||||
if (len(data) % maxlen) != 0:
|
||||
packet_count += 1
|
||||
|
||||
for pkt_num in range(packet_count):
|
||||
cur_addr = addr + pkt_num * maxlen
|
||||
if pkt_num == packet_count - 1:
|
||||
if len(data) % maxlen != 0:
|
||||
bufsize = len(data) % maxlen
|
||||
else:
|
||||
bufsize = maxlen
|
||||
else:
|
||||
bufsize = maxlen
|
||||
|
||||
wdata = array.array('B', data[(pkt_num * maxlen):(pkt_num * maxlen) + bufsize])
|
||||
numwritten = self.dev.ctrl_transfer(bmRequestType=(0x00 | 0x43), bRequest=0,
|
||||
# note use of writebuf_addr instead of cur_addr -> see comment above about the quirk of write addressing
|
||||
wValue=(writebuf_addr & 0xffff), wIndex=((writebuf_addr >> 16) & 0xffff),
|
||||
data_or_wLength=wdata, timeout=500)
|
||||
|
||||
if numwritten != bufsize:
|
||||
print("Burst write error: {} bytes requested, {} bytes written at 0x{:08x}".format(bufsize, numwritten, cur_addr))
|
||||
exit(1)
|
||||
|
||||
def ping_wdt(self):
|
||||
self.poke(self.register('wdt_watchdog'), 1, display=False)
|
||||
self.poke(self.register('wdt_watchdog'), 1, display=False)
|
||||
|
||||
def spinor_command_value(self, exec=0, lock_reads=0, cmd_code=0, dummy_cycles=0, data_words=0, has_arg=0):
|
||||
return ((exec & 1) << 1 |
|
||||
(lock_reads & 1) << 24 |
|
||||
(cmd_code & 0xff) << 2 |
|
||||
(dummy_cycles & 0x1f) << 11 |
|
||||
(data_words & 0xff) << 16 |
|
||||
(has_arg & 1) << 10
|
||||
)
|
||||
|
||||
def flash_rdsr(self, lock_reads):
|
||||
self.poke(self.register('spinor_cmd_arg'), 0)
|
||||
self.poke(self.register('spinor_command'),
|
||||
self.spinor_command_value(exec=1, lock_reads=lock_reads, cmd_code=self.RDSR, dummy_cycles=4, data_words=1, has_arg=1)
|
||||
)
|
||||
return self.peek(self.register('spinor_cmd_rbk_data'), display=False)
|
||||
|
||||
def flash_rdscur(self):
|
||||
self.poke(self.register('spinor_cmd_arg'), 0)
|
||||
self.poke(self.register('spinor_command'),
|
||||
self.spinor_command_value(exec=1, lock_reads=1, cmd_code=self.RDSCUR, dummy_cycles=4, data_words=1, has_arg=1)
|
||||
)
|
||||
return self.peek(self.register('spinor_cmd_rbk_data'), display=False)
|
||||
|
||||
def flash_rdid(self, offset):
|
||||
self.poke(self.register('spinor_cmd_arg'), 0)
|
||||
self.poke(self.register('spinor_command'),
|
||||
self.spinor_command_value(exec=1, cmd_code=self.RDID, dummy_cycles=4, data_words=offset, has_arg=1)
|
||||
)
|
||||
return self.peek(self.register('spinor_cmd_rbk_data'), display=False)
|
||||
|
||||
def flash_wren(self):
|
||||
self.poke(self.register('spinor_cmd_arg'), 0)
|
||||
self.poke(self.register('spinor_command'),
|
||||
self.spinor_command_value(exec=1, lock_reads=1, cmd_code=self.WREN)
|
||||
)
|
||||
|
||||
def flash_wrdi(self):
|
||||
self.poke(self.register('spinor_cmd_arg'), 0)
|
||||
self.poke(self.register('spinor_command'),
|
||||
self.spinor_command_value(exec=1, lock_reads=1, cmd_code=self.WRDI)
|
||||
)
|
||||
|
||||
def flash_se4b(self, sector_address):
|
||||
self.poke(self.register('spinor_cmd_arg'), sector_address)
|
||||
self.poke(self.register('spinor_command'),
|
||||
self.spinor_command_value(exec=1, lock_reads=1, cmd_code=self.SE4B, has_arg=1)
|
||||
)
|
||||
|
||||
def flash_be4b(self, block_address):
|
||||
self.poke(self.register('spinor_cmd_arg'), block_address)
|
||||
self.poke(self.register('spinor_command'),
|
||||
self.spinor_command_value(exec=1, lock_reads=1, cmd_code=self.BE4B, has_arg=1)
|
||||
)
|
||||
|
||||
def flash_pp4b(self, address, data_bytes):
|
||||
self.poke(self.register('spinor_cmd_arg'), address)
|
||||
self.poke(self.register('spinor_command'),
|
||||
self.spinor_command_value(exec=1, lock_reads=1, cmd_code=self.PP4B, has_arg=1, data_words=(data_bytes//2))
|
||||
)
|
||||
|
||||
def load_csrs(self, fname=None):
|
||||
LOC_CSRCSV = 0x20277000 # this address shouldn't change because it's how we figure out our version number
|
||||
# CSR extraction:
|
||||
# dd if=soc_csr.bin of=csr_data_0.9.6.bin skip=2524 count=32 bs=1024
|
||||
if fname == None:
|
||||
csr_data = self.burst_read(LOC_CSRCSV, 0x8000)
|
||||
else:
|
||||
with open(fname, "rb") as f:
|
||||
csr_data = f.read(0x8000)
|
||||
|
||||
hasher = hashlib.sha512()
|
||||
hasher.update(csr_data[:0x7FC0])
|
||||
digest = hasher.digest()
|
||||
if digest != csr_data[0x7fc0:]:
|
||||
print("Could not find a valid csr.csv descriptor on the device, aborting!")
|
||||
exit(1)
|
||||
|
||||
csr_len = int.from_bytes(csr_data[:4], 'little')
|
||||
csr_extracted = csr_data[4:4+csr_len]
|
||||
decoded = csr_extracted.decode('utf-8')
|
||||
# strip comments
|
||||
stripped = []
|
||||
for line in decoded.split('\n'):
|
||||
if line.startswith('#') == False:
|
||||
stripped.append(line)
|
||||
# create database
|
||||
csr_db = csv.reader(stripped)
|
||||
for row in csr_db:
|
||||
if len(row) > 1:
|
||||
if 'csr_register' in row[0]:
|
||||
self.registers[row[1]] = row[2]
|
||||
if 'memory_region' in row[0]:
|
||||
self.regions[row[1]] = [row[2], row[3]]
|
||||
if 'git_rev' in row[0]:
|
||||
self.gitrev = row[1]
|
||||
print("Using SoC {} registers".format(self.gitrev))
|
||||
|
||||
def erase_region(self, addr, length):
|
||||
# ID code check
|
||||
code = self.flash_rdid(1)
|
||||
print("ID code bytes 1-2: 0x{:08x}".format(code))
|
||||
if code != 0x8080c2c2:
|
||||
print("ID code mismatch")
|
||||
exit(1)
|
||||
code = self.flash_rdid(2)
|
||||
print("ID code bytes 2-3: 0x{:08x}".format(code))
|
||||
if code != 0x3b3b8080:
|
||||
print("ID code mismatch")
|
||||
exit(1)
|
||||
|
||||
# block erase
|
||||
progress = ProgressBar(min_value=0, max_value=length, prefix='Erasing ').start()
|
||||
erased = 0
|
||||
while erased < length:
|
||||
self.ping_wdt()
|
||||
if (length - erased >= 65536) and ((addr & 0xFFFF) == 0):
|
||||
blocksize = 65536
|
||||
else:
|
||||
blocksize = 4096
|
||||
|
||||
while True:
|
||||
self.flash_wren()
|
||||
status = self.flash_rdsr(1)
|
||||
if status & 0x02 != 0:
|
||||
break
|
||||
|
||||
if blocksize == 4096:
|
||||
self.flash_se4b(addr + erased)
|
||||
else:
|
||||
self.flash_be4b(addr + erased)
|
||||
erased += blocksize
|
||||
|
||||
while (self.flash_rdsr(1) & 0x01) != 0:
|
||||
pass
|
||||
|
||||
result = self.flash_rdscur()
|
||||
if result & 0x60 != 0:
|
||||
print("E_FAIL/P_FAIL set on erase, programming may fail, but trying anyways...")
|
||||
|
||||
if self.flash_rdsr(1) & 0x02 != 0:
|
||||
self.flash_wrdi()
|
||||
while (self.flash_rdsr(1) & 0x02) != 0:
|
||||
pass
|
||||
if erased < length:
|
||||
progress.update(erased)
|
||||
progress.finish()
|
||||
print("Erase finished")
|
||||
|
||||
# addr is relative to the base of FLASH (not absolute)
|
||||
def flash_program(self, addr, data, verify=True):
|
||||
flash_region = int(self.regions['spiflash'][0], 0)
|
||||
flash_len = int(self.regions['spiflash'][1], 0)
|
||||
|
||||
if (addr + len(data) > flash_len):
|
||||
print("Write data out of bounds! Aborting.")
|
||||
exit(1)
|
||||
|
||||
# ID code check
|
||||
code = self.flash_rdid(1)
|
||||
print("ID code bytes 1-2: 0x{:08x}".format(code))
|
||||
if code != 0x8080c2c2:
|
||||
print("ID code mismatch")
|
||||
exit(1)
|
||||
code = self.flash_rdid(2)
|
||||
print("ID code bytes 2-3: 0x{:08x}".format(code))
|
||||
if code != 0x3b3b8080:
|
||||
print("ID code mismatch")
|
||||
exit(1)
|
||||
|
||||
# block erase
|
||||
progress = ProgressBar(min_value=0, max_value=len(data), prefix='Erasing ').start()
|
||||
erased = 0
|
||||
while erased < len(data):
|
||||
self.ping_wdt()
|
||||
if (len(data) - erased >= 65536) and ((addr & 0xFFFF) == 0):
|
||||
blocksize = 65536
|
||||
else:
|
||||
blocksize = 4096
|
||||
|
||||
while True:
|
||||
self.flash_wren()
|
||||
status = self.flash_rdsr(1)
|
||||
if status & 0x02 != 0:
|
||||
break
|
||||
|
||||
if blocksize == 4096:
|
||||
self.flash_se4b(addr + erased)
|
||||
else:
|
||||
self.flash_be4b(addr + erased)
|
||||
erased += blocksize
|
||||
|
||||
while (self.flash_rdsr(1) & 0x01) != 0:
|
||||
pass
|
||||
|
||||
result = self.flash_rdscur()
|
||||
if result & 0x60 != 0:
|
||||
print("E_FAIL/P_FAIL set on erase, programming may fail, but trying anyways...")
|
||||
|
||||
if self.flash_rdsr(1) & 0x02 != 0:
|
||||
self.flash_wrdi()
|
||||
while (self.flash_rdsr(1) & 0x02) != 0:
|
||||
pass
|
||||
if erased < len(data):
|
||||
progress.update(erased)
|
||||
progress.finish()
|
||||
print("Erase finished")
|
||||
|
||||
# program
|
||||
# pad out to the nearest word length
|
||||
if len(data) % 4 != 0:
|
||||
data += bytearray([0xff] * (4 - (len(data) % 4)))
|
||||
written = 0
|
||||
progress = ProgressBar(min_value=0, max_value=len(data), prefix='Writing ').start()
|
||||
while written < len(data):
|
||||
self.ping_wdt()
|
||||
if len(data) - written > 256:
|
||||
chunklen = 256
|
||||
else:
|
||||
chunklen = len(data) - written
|
||||
|
||||
while True:
|
||||
self.flash_wren()
|
||||
status = self.flash_rdsr(1)
|
||||
if status & 0x02 != 0:
|
||||
break
|
||||
|
||||
self.burst_write(self.register('spinor_wdata'), data[written:(written+chunklen)])
|
||||
self.flash_pp4b(addr + written, chunklen)
|
||||
|
||||
written += chunklen
|
||||
if written < len(data):
|
||||
progress.update(written)
|
||||
progress.finish()
|
||||
print("Write finished")
|
||||
|
||||
if self.flash_rdsr(1) & 0x02 != 0:
|
||||
self.flash_wrdi()
|
||||
while (self.flash_rdsr(1) & 0x02) != 0:
|
||||
pass
|
||||
|
||||
# dummy reads to clear the "read lock" bit
|
||||
self.flash_rdsr(0)
|
||||
|
||||
# verify
|
||||
self.ping_wdt()
|
||||
if verify:
|
||||
print("Performing readback for verification...")
|
||||
self.ping_wdt()
|
||||
rbk_data = self.burst_read(addr + flash_region, len(data))
|
||||
if rbk_data != data:
|
||||
errs = 0
|
||||
err_thresh = 64
|
||||
for i in range(0, len(rbk_data)):
|
||||
if rbk_data[i] != data[i]:
|
||||
if errs < err_thresh:
|
||||
print("Error at 0x{:x}: {:x}->{:x}".format(i, data[i], rbk_data[i]))
|
||||
errs += 1
|
||||
if errs == err_thresh:
|
||||
print("Too many errors, stopping print...")
|
||||
print("Errors were found in verification, programming failed")
|
||||
print("Total byte errors: {}".format(errs))
|
||||
exit(1)
|
||||
else:
|
||||
print("Verification passed.")
|
||||
else:
|
||||
print("Skipped verification at user request")
|
||||
|
||||
self.ping_wdt()
|
||||
|
||||
def auto_int(x):
|
||||
return int(x, 0)
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Update/upload to a Precursor device running Xous 0.8/0.9")
|
||||
parser.add_argument(
|
||||
"--soc", required=False, help="'Factory Reset' the SoC gateware. Note: this will overwrite any secret keys stored in your device!", type=str, nargs='?', metavar=('SoC gateware file'), const='../precursors/soc_csr.bin'
|
||||
)
|
||||
parser.add_argument(
|
||||
"-s", "--staging", required=False, help="Stage an update to apply", type=str, nargs='?', metavar=('SoC gateware file'), const='../precursors/soc_csr.bin'
|
||||
)
|
||||
parser.add_argument(
|
||||
"-l", "--loader", required=False, help="Loader", type=str, nargs='?', metavar=('loader file'), const='../target/riscv32imac-unknown-xous-elf/release/loader.bin'
|
||||
)
|
||||
parser.add_argument(
|
||||
"--disable-boot", required=False, action='store_true', help="Disable system boot (for use in multi-stage updates)"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--enable-boot-wipe", required=False, action='store_true', help="Re-enable system boot for factory reset. Requires both a loader (-l) and a soc (--soc) spec. Overwrites root keys."
|
||||
)
|
||||
parser.add_argument(
|
||||
"--enable-boot-update", required=False, action='store_true', help="Re-enable system boot for updates. Requires both a loader (-l) and a staging (-s) spec. Stages SOC without overwriting root keys."
|
||||
)
|
||||
parser.add_argument(
|
||||
"-k", "--kernel", required=False, help="Kernel", type=str, nargs='?', metavar=('kernel file'), const='../target/riscv32imac-unknown-xous-elf/release/xous.img'
|
||||
)
|
||||
parser.add_argument(
|
||||
"-e", "--ec", required=False, help="EC gateware", type=str, nargs='?', metavar=('EC gateware package'), const='ec_fw.bin'
|
||||
)
|
||||
parser.add_argument(
|
||||
"-w", "--wf200", required=False, help="WF200 firmware", type=str, nargs='?', metavar=('WF200 firmware package'), const='wf200_fw.bin'
|
||||
)
|
||||
parser.add_argument(
|
||||
"--erase-pddb", help="Erase the PDDB area", action="store_true"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--audiotest", required=False, help="Test audio clip (must be 8kHz WAV)", type=str, nargs='?', metavar=('Test audio clip'), const="testaudio.wav"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--peek", required=False, help="Inspect an address", type=auto_int, metavar=('ADDR')
|
||||
)
|
||||
parser.add_argument(
|
||||
"--poke", required=False, help="Write to an address", type=auto_int, nargs=2, metavar=('ADDR', 'DATA')
|
||||
)
|
||||
parser.add_argument(
|
||||
"--check-poke", required=False, action='store_true', help="Read data before and after the poke"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--config", required=False, help="Print the descriptor", action='store_true'
|
||||
)
|
||||
parser.add_argument(
|
||||
"-i", "--image", required=False, help="Manually specify an image and address. Offset is relative to bottom of flash.", type=str, nargs=2, metavar=('IMAGEFILE', 'ADDR')
|
||||
)
|
||||
parser.add_argument(
|
||||
"--verify", help="Readback verification. May fail for large files due to WDT timeout.", default=False, action='store_true'
|
||||
)
|
||||
parser.add_argument(
|
||||
"--force", help="Ignore gitrev version on SoC and try to burn an image anyways", action="store_true"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--bounce", help="cycle the device through a reset", action="store_true"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--factory-new", help="reset the entire image to mimic exactly what comes out of the factory, including temp files for testing. Warning: this will take a long time.", action="store_true"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--override-csr", required=False, help="CSR file to use instead of CSR values stored with the image. Used to recover in case of partial update of soc_csr.bin", type=str,
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
if not len(sys.argv) > 1:
|
||||
print("No arguments specified, doing nothing. Use --help for more information.")
|
||||
exit(1)
|
||||
|
||||
dev = usb.core.find(idProduct=0x5bf0, idVendor=0x1209)
|
||||
|
||||
if dev is None:
|
||||
raise ValueError('Precursor device not found')
|
||||
|
||||
dev.set_configuration()
|
||||
if args.config:
|
||||
cfg = dev.get_active_configuration()
|
||||
print(cfg)
|
||||
|
||||
pc_usb = PrecursorUsb(dev)
|
||||
|
||||
if args.verify:
|
||||
verify = True
|
||||
else:
|
||||
verify = False
|
||||
|
||||
if args.peek:
|
||||
pc_usb.peek(args.peek, display=True)
|
||||
# print(burst_read(dev, args.peek, 256).hex())
|
||||
exit(0)
|
||||
|
||||
if args.poke:
|
||||
addr, data = args.poke
|
||||
pc_usb.poke(addr, data, check=args.check_poke, display=True)
|
||||
# import os
|
||||
# d = bytearray(os.urandom(8000))
|
||||
# burst_write(dev, addr, d)
|
||||
# r = burst_read(dev, addr, 8000)
|
||||
# print(r.hex())
|
||||
# if d != r:
|
||||
# print("mismatch")
|
||||
# else:
|
||||
# print("match")
|
||||
exit(0)
|
||||
|
||||
pc_usb.load_csrs(args.override_csr) # prime the CSR values
|
||||
if "v0.8" in pc_usb.gitrev:
|
||||
locs = {
|
||||
"LOC_SOC" : [0x0000_0000, "soc_csr.bin"],
|
||||
"LOC_STAGING": [0x0028_0000, "pass"],
|
||||
"LOC_LOADER" : [0x0050_0000, "loader.bin"],
|
||||
"LOC_KERNEL" : [0x0098_0000, "xous.img"],
|
||||
"LOC_WF200" : [0x07F8_0000, "pass"],
|
||||
"LOC_EC" : [0x07FC_E000, "pass"],
|
||||
"LOC_AUDIO" : [0x0634_0000, "short_8khz.wav"],
|
||||
"LEN_AUDIO" : [0x01C4_0000, "pass"],
|
||||
"LOC_PDDB" : [0x0100_0000, "pass"],
|
||||
}
|
||||
elif "v0.9" in pc_usb.gitrev:
|
||||
locs = {
|
||||
"LOC_SOC" : [0x0000_0000, "soc_csr.bin"],
|
||||
"LOC_STAGING": [0x0028_0000, "pass"],
|
||||
"LOC_LOADER" : [0x0050_0000, "loader.bin"],
|
||||
"LOC_KERNEL" : [0x0098_0000, "xous.img"],
|
||||
"LOC_WF200" : [0x07F8_0000, "pass"],
|
||||
"LOC_EC" : [0x07FC_E000, "pass"],
|
||||
"LOC_AUDIO" : [0x0634_0000, "short_8khz.wav"],
|
||||
"LEN_AUDIO" : [0x01C4_0000, "pass"],
|
||||
"LOC_PDDB" : [0x01D8_0000, "pass"],
|
||||
}
|
||||
elif args.force == True:
|
||||
# try the v0.9 offsets
|
||||
locs = {
|
||||
"LOC_SOC" : [0x00000000, "soc_csr.bin"],
|
||||
"LOC_STAGING": [0x00280000, "pass"],
|
||||
"LOC_LOADER" : [0x00500000, "loader.bin"],
|
||||
"LOC_KERNEL" : [0x00980000, "xous.img"],
|
||||
"LOC_WF200" : [0x07F80000, "pass"],
|
||||
"LOC_EC" : [0x07FCE000, "pass"],
|
||||
"LOC_AUDIO" : [0x06340000, "short_8khz.wav"],
|
||||
"LEN_AUDIO" : [0x01C40000, "pass"],
|
||||
"LOC_PDDB" : [0x01D80000, "pass"],
|
||||
}
|
||||
else:
|
||||
print("SoC is from an unknow rev '{}', use --force to continue anyways with v0.9 firmware offsets".format(pc_usb.load_csrs()))
|
||||
exit(1)
|
||||
|
||||
vexdbg_addr = int(pc_usb.regions['vexriscv_debug'][0], 0)
|
||||
pc_usb.ping_wdt()
|
||||
print("Halting CPU.")
|
||||
pc_usb.poke(vexdbg_addr, 0x00020000)
|
||||
|
||||
if args.erase_pddb:
|
||||
print("Erasing PDDB region")
|
||||
pc_usb.erase_region(locs['LOC_PDDB'][0], locs['LOC_EC'][0] - locs['LOC_PDDB'][0])
|
||||
|
||||
if args.disable_boot:
|
||||
print("Disabling boot")
|
||||
pc_usb.erase_region(locs['LOC_LOADER'][0], 1024 * 256)
|
||||
|
||||
if args.enable_boot_wipe:
|
||||
if args.loader == None:
|
||||
print("Must provide both a loader and soc image")
|
||||
if args.soc == None:
|
||||
print("Must provide both a soc and loader image")
|
||||
print("Enabling boot with {} and {}".format(args.loader, args.soc))
|
||||
print("Programming loader image {}".format(args.loader))
|
||||
with open(args.loader, "rb") as f:
|
||||
image = f.read()
|
||||
pc_usb.flash_program(locs['LOC_LOADER'][0], image, verify=verify)
|
||||
print("Programming SoC gateware".format(args.soc))
|
||||
with open(args.soc, "rb") as f:
|
||||
image = f.read()
|
||||
if verify == True:
|
||||
print("Note: SoC verification is not possible as readback is locked for security purposes")
|
||||
pc_usb.flash_program(locs['LOC_SOC'][0], image, verify=False)
|
||||
|
||||
print("Erasing PDDB root structures")
|
||||
pc_usb.erase_region(locs['LOC_PDDB'][0], 1024 * 1024)
|
||||
|
||||
print("Resuming CPU.")
|
||||
pc_usb.poke(vexdbg_addr, 0x02000000)
|
||||
|
||||
print("Resetting SOC...")
|
||||
try:
|
||||
pc_usb.poke(pc_usb.register('reboot_soc_reset'), 0xac, display=False)
|
||||
except usb.core.USBError:
|
||||
pass # we expect an error because we reset the SOC and that includes the USB core
|
||||
exit(0)
|
||||
|
||||
if args.enable_boot_update:
|
||||
if args.loader == None:
|
||||
print("Must provide both a loader and soc image")
|
||||
if args.staging == None:
|
||||
print("Must provide both a soc and loader image")
|
||||
print("Enabling boot with {} and {}".format(args.loader, args.staging))
|
||||
print("Programming loader image {}".format(args.loader))
|
||||
with open(args.loader, "rb") as f:
|
||||
image = f.read()
|
||||
pc_usb.flash_program(locs['LOC_LOADER'][0], image, verify=verify)
|
||||
print("Staging SoC gateware".format(args.staging))
|
||||
with open(args.staging, "rb") as f:
|
||||
image = f.read()
|
||||
if verify == True:
|
||||
print("Note: staging area verification is not possible as readback is locked for security purposes")
|
||||
pc_usb.flash_program(locs['LOC_STAGING'][0], image, verify=verify)
|
||||
|
||||
print("Resuming CPU.")
|
||||
pc_usb.poke(vexdbg_addr, 0x02000000)
|
||||
|
||||
print("Resetting SOC...")
|
||||
try:
|
||||
pc_usb.poke(pc_usb.register('reboot_soc_reset'), 0xac, display=False)
|
||||
except usb.core.USBError:
|
||||
pass # we expect an error because we reset the SOC and that includes the USB core
|
||||
exit(0)
|
||||
|
||||
if args.image:
|
||||
image_file, addr_str = args.image
|
||||
addr = int(addr_str, 0)
|
||||
print("Burning manually specified image '{}' to address 0x{:08x} relative to bottom of FLASH".format(image_file, addr))
|
||||
with open(image_file, "rb") as f:
|
||||
image_data = f.read()
|
||||
pc_usb.flash_program(addr, image_data, verify=verify)
|
||||
|
||||
if args.ec != None:
|
||||
print("Staging EC firmware package '{}' in SOC memory space...".format(args.ec))
|
||||
with open(args.ec, "rb") as f:
|
||||
image = f.read()
|
||||
pc_usb.flash_program(locs['LOC_EC'][0], image, verify=verify)
|
||||
|
||||
if args.wf200 != None:
|
||||
print("Staging WF200 firmware package '{}' in SOC memory space...".format(args.wf200))
|
||||
with open(args.wf200, "rb") as f:
|
||||
image = f.read()
|
||||
pc_usb.flash_program(locs['LOC_WF200'][0], image, verify=verify)
|
||||
|
||||
if args.staging != None:
|
||||
print("Staging SoC gateware {}".format(args.soc))
|
||||
with open(args.staging, "rb") as f:
|
||||
image = f.read()
|
||||
if verify == True:
|
||||
print("Note: staging area verification is not possible as readback is locked for security purposes")
|
||||
pc_usb.flash_program(locs['LOC_STAGING'][0], image, verify=verify)
|
||||
|
||||
if args.kernel != None:
|
||||
print("Programming kernel image {}".format(args.kernel))
|
||||
with open(args.kernel, "rb") as f:
|
||||
image = f.read()
|
||||
pc_usb.flash_program(locs['LOC_KERNEL'][0], image, verify=verify)
|
||||
|
||||
if args.loader != None:
|
||||
print("Programming loader image {}".format(args.loader))
|
||||
with open(args.loader, "rb") as f:
|
||||
image = f.read()
|
||||
pc_usb.flash_program(locs['LOC_LOADER'][0], image, verify=verify)
|
||||
|
||||
if args.soc != None:
|
||||
if args.force == True:
|
||||
print("Programming SoC gateware {}".format(args.soc))
|
||||
with open(args.soc, "rb") as f:
|
||||
image = f.read()
|
||||
if verify == True:
|
||||
print("Note: SoC verification is not possible as readback is locked for security purposes")
|
||||
pc_usb.flash_program(locs['LOC_SOC'][0], image, verify=False)
|
||||
print("Erasing PDDB root structures")
|
||||
pc_usb.erase_region(locs['LOC_PDDB'][0], 1024 * 1024)
|
||||
else:
|
||||
print("This will overwrite any secret keys in your device and erase PDDB keys. Continue? (y/n)")
|
||||
confirm = input()
|
||||
if len(confirm) > 0 and confirm.lower()[:1] == 'y':
|
||||
print("Programming SoC gateware {}".format(args.soc))
|
||||
with open(args.soc, "rb") as f:
|
||||
image = f.read()
|
||||
if verify == True:
|
||||
print("Note: SoC verification is not possible as readback is locked for security purposes")
|
||||
pc_usb.flash_program(locs['LOC_SOC'][0], image, verify=False)
|
||||
print("Erasing PDDB root structures")
|
||||
pc_usb.erase_region(locs['LOC_PDDB'][0], 1024 * 1024)
|
||||
|
||||
|
||||
if args.audiotest != None:
|
||||
print("Loading audio test clip {}".format(args.audiotest))
|
||||
with open(args.audiotest, "rb") as f:
|
||||
image = f.read()
|
||||
if len(image) >= locs['LEN_AUDIO'][0]:
|
||||
print("audio file is too long, aborting audio burn!")
|
||||
else:
|
||||
pc_usb.flash_program(locs['LOC_AUDIO'][0], image, verify=verify)
|
||||
|
||||
if args.factory_new:
|
||||
base_url = "https://ci.betrusted.io/releases/v0.9.5/"
|
||||
# erase the entire flash
|
||||
pc_usb.erase_region(0, 0x800_0000)
|
||||
# burn the gateware
|
||||
for sections in locs.values():
|
||||
if sections[1] != 'pass':
|
||||
print('retrieving {}'.format(base_url + sections[1]))
|
||||
with urllib.request.urlopen(base_url + sections[1]) as f:
|
||||
print('burning at {:x}'.format(sections[0]))
|
||||
image = f.read()
|
||||
pc_usb.flash_program(sections[0], image, verify=False)
|
||||
|
||||
|
||||
print("Resuming CPU.")
|
||||
pc_usb.poke(vexdbg_addr, 0x02000000)
|
||||
|
||||
print("Resetting SOC...")
|
||||
try:
|
||||
pc_usb.poke(pc_usb.register('reboot_soc_reset'), 0xac, display=False)
|
||||
except usb.core.USBError:
|
||||
pass # we expect an error because we reset the SOC and that includes the USB core
|
||||
|
||||
# print("If you need to run more commands, please unplug and re-plug your device in, as the Precursor USB core was just reset")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
exit(0)
|
||||
1
tools/legacy/usb_update.py
Symbolic link
|
|
@ -0,0 +1 @@
|
|||
../usb_update.py
|
||||
15
tools/perflib/Cargo.toml
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
[package]
|
||||
name = "perflib"
|
||||
version = "0.1.0"
|
||||
authors = ["bunnie <bunnie@kosagi.com>"]
|
||||
edition = "2018"
|
||||
description = "Performance counter tooling"
|
||||
|
||||
# Dependency versions enforced by Cargo.lock.
|
||||
[dependencies]
|
||||
xous = { path = "../../xous-rs" }
|
||||
log = "0.4.14"
|
||||
utralib = { path = "../../utralib"}
|
||||
|
||||
[features]
|
||||
default = []
|
||||
266
tools/perflib/src/lib.rs
Normal file
|
|
@ -0,0 +1,266 @@
|
|||
use utralib::generated::*;
|
||||
use core::num::{NonZeroU8, NonZeroU16};
|
||||
use std::cell::RefCell;
|
||||
|
||||
pub const BUFLEN: usize = 1024 * 512;
|
||||
|
||||
#[repr(C)]
|
||||
pub struct PerfLogEntry {
|
||||
code: u32,
|
||||
ts: u32,
|
||||
}
|
||||
|
||||
/// Pure client for performance monitoring. It is not capable of emptying the FIFO or
|
||||
/// detecting an overflow, but it can register an event through a somewhat-abstracted interface.
|
||||
pub struct PerfClient {
|
||||
event_csr: AtomicCsr<u32>,
|
||||
}
|
||||
impl PerfClient {
|
||||
pub fn new(
|
||||
event_csr: AtomicCsr<u32>,
|
||||
) -> Self {
|
||||
Self {
|
||||
event_csr,
|
||||
}
|
||||
}
|
||||
#[inline(always)]
|
||||
pub fn log_event_unchecked(&self, code: u32) {
|
||||
// event_sourceN is identical across each block, so we can take advantage of the flexibility of
|
||||
// UTRA to do a non-specific cross-crate register access pattern.
|
||||
self.event_csr.wfo(utra::event_source1::PERFEVENT_CODE,
|
||||
code);
|
||||
}
|
||||
}
|
||||
|
||||
/// Manager interface for performance monitoring. This also includes a performance event port.
|
||||
pub struct PerfMgr<'a> {
|
||||
data: RefCell::<&'a mut [PerfLogEntry]>,
|
||||
perf_csr: AtomicCsr<u32>,
|
||||
event_csr: AtomicCsr<u32>,
|
||||
log_index: RefCell<usize>,
|
||||
ts_cont: RefCell<u64>,
|
||||
// these are expressed as raw values to be written to hardware
|
||||
saturation_limit: u64,
|
||||
prescaler: u16,
|
||||
saturate: bool,
|
||||
event_bit_width: u8,
|
||||
// debug fields
|
||||
dbg_buf_count: RefCell<u32>,
|
||||
}
|
||||
|
||||
impl <'a> PerfMgr<'a> {
|
||||
pub fn new(
|
||||
log_ptr: *mut u8,
|
||||
perf_csr: AtomicCsr<u32>,
|
||||
event_csr: AtomicCsr<u32>,
|
||||
) -> Self {
|
||||
let data =
|
||||
unsafe{
|
||||
core::slice::from_raw_parts_mut(
|
||||
log_ptr as *mut PerfLogEntry,
|
||||
BUFLEN / core::mem::size_of::<PerfLogEntry>()
|
||||
)
|
||||
};
|
||||
// initialize the buffer region when the manager is created
|
||||
for d in data.iter_mut() {
|
||||
d.code = 0;
|
||||
d.ts = 0;
|
||||
}
|
||||
Self {
|
||||
data: RefCell::new(data),
|
||||
perf_csr,
|
||||
event_csr,
|
||||
log_index: RefCell::new(0),
|
||||
ts_cont: RefCell::new(0),
|
||||
saturation_limit: 0xffff_ffff,
|
||||
prescaler: 0, // 1 clock per sample
|
||||
event_bit_width: 31, // 32 bits width
|
||||
saturate: true,
|
||||
dbg_buf_count: RefCell::new(0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the saturation limit for the performance counter. Units in clock cycles.
|
||||
/// If `None`, the counter will freely rollover without stopping the performance counting process.
|
||||
#[allow(dead_code)]
|
||||
pub fn sat_limit(&mut self, limit: Option<u64>) {
|
||||
if let Some(l) = limit {
|
||||
self.saturation_limit = l;
|
||||
self.saturate = true;
|
||||
} else {
|
||||
self.saturate = false;
|
||||
self.saturation_limit = u64::MAX;
|
||||
}
|
||||
}
|
||||
|
||||
/// Zero is an invalid value for clocks per sample. Hence NonZeroU16 type.
|
||||
#[allow(dead_code)]
|
||||
pub fn clocks_per_sample(&mut self, cps: NonZeroU16) {
|
||||
self.prescaler = cps.get() - 1;
|
||||
}
|
||||
|
||||
/// Sets the width of the event code. This is enforced by hardware, software is free to pass in a code that is too large.
|
||||
/// Excess bits will be ignored, starting from the MSB side. A bitwdith of 0 is illegal. A bitwidth larger than 32 is set to 32.
|
||||
#[allow(dead_code)]
|
||||
pub fn code_bitwidth(&mut self, bitwidth: NonZeroU8) {
|
||||
let bw = bitwidth.get();
|
||||
if bw > 32 {
|
||||
self.event_bit_width = 31;
|
||||
} else {
|
||||
self.event_bit_width = bw - 1;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn stop_and_reset(&self) {
|
||||
for d in self.data.borrow_mut().iter_mut() {
|
||||
d.code = 0;
|
||||
d.ts = 0;
|
||||
}
|
||||
self.perf_csr.wfo(utra::perfcounter::RUN_STOP, 1);
|
||||
while self.perf_csr.rf(utra::perfcounter::STATUS_READABLE) == 1 {
|
||||
let i = self.perf_csr.r(utra::perfcounter::EVENT_INDEX); // this advances the FIFO until it is empty
|
||||
log::warn!("FIFO was not drained before reset: {}", i);
|
||||
}
|
||||
// stop the counter if it would rollover
|
||||
self.perf_csr.wo(utra::perfcounter::SATURATE_LIMIT0, self.saturation_limit as u32);
|
||||
self.perf_csr.wo(utra::perfcounter::SATURATE_LIMIT1, (self.saturation_limit >> 32) as u32);
|
||||
|
||||
// configure the system
|
||||
self.perf_csr.wo(utra::perfcounter::CONFIG,
|
||||
self.perf_csr.ms(utra::perfcounter::CONFIG_PRESCALER, self.prescaler as u32)
|
||||
| self.perf_csr.ms(utra::perfcounter::CONFIG_SATURATE, if self.saturate {1} else {0})
|
||||
| self.perf_csr.ms(utra::perfcounter::CONFIG_EVENT_WIDTH_MINUS_ONE, self.event_bit_width as u32)
|
||||
);
|
||||
self.log_index.replace(0);
|
||||
self.ts_cont.replace(0);
|
||||
}
|
||||
|
||||
pub fn start(&self) {
|
||||
self.perf_csr.wfo(utra::perfcounter::RUN_RESET_RUN, 1);
|
||||
}
|
||||
|
||||
/// This function is convenient, but the overhead of the checking adds a lot of cache line noise to the data
|
||||
/// If you are looking to get very cycle-accurate counts, use `log_event_unchecked` with manual flush calls
|
||||
///
|
||||
/// returns Ok(()) if the event could be logged
|
||||
/// returns an Err if the performance buffer would overflow
|
||||
#[inline(always)]
|
||||
pub fn log_event(&self, code: u32) -> Result::<(), xous::Error> {
|
||||
self.flush_if_full()?;
|
||||
self.event_csr.wfo(utra::event_source1::PERFEVENT_CODE,
|
||||
code);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[inline(always)]
|
||||
pub fn log_event_unchecked(&self, code: u32) {
|
||||
self.event_csr.wfo(utra::event_source1::PERFEVENT_CODE,
|
||||
code);
|
||||
}
|
||||
#[allow(dead_code)]
|
||||
pub fn flush(&self) -> Result::<(), xous::Error> {
|
||||
let mut oom = false;
|
||||
// stop the counter
|
||||
self.perf_csr.wfo(utra::perfcounter::RUN_STOP, 1);
|
||||
// copy over the events to the long term buffer
|
||||
let mut ts_offset = 0;
|
||||
let mut expected_i = 0;
|
||||
while self.perf_csr.rf(utra::perfcounter::STATUS_READABLE) == 1 {
|
||||
if *self.log_index.borrow() < self.data.borrow().len() {
|
||||
self.dbg_buf_count.replace(self.dbg_buf_count.take() + 1); // this tracks total entries copied into the perfbuf
|
||||
(*self.data.borrow_mut())[*self.log_index.borrow()].code = self.perf_csr.r(utra::perfcounter::EVENT_RAW0);
|
||||
ts_offset = self.perf_csr.r(utra::perfcounter::EVENT_RAW1) as u32;
|
||||
(*self.data.borrow_mut())[*self.log_index.borrow()].ts = *self.ts_cont.borrow() as u32 + ts_offset;
|
||||
|
||||
let i = self.perf_csr.r(utra::perfcounter::EVENT_INDEX); // this advances the FIFO
|
||||
if i != expected_i & 0xfff {
|
||||
log::info!("i {} != expected_i {}", i, expected_i);
|
||||
}
|
||||
expected_i += 1;
|
||||
self.log_index.replace(self.log_index.take() + 1);
|
||||
} else {
|
||||
oom = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
// update the timestamp continuation field with the last timestamp seen; the next line
|
||||
// resets the timestamp counter to 0 again.
|
||||
self.ts_cont.replace(self.ts_cont.take() + ts_offset as u64);
|
||||
// restart the counter
|
||||
if !oom {
|
||||
// duplicate this code down here because we want the reset and log to be as close as possible to the return statement
|
||||
self.perf_csr.wfo(utra::perfcounter::RUN_RESET_RUN, 1);
|
||||
Ok(())
|
||||
} else {
|
||||
self.perf_csr.wfo(utra::perfcounter::RUN_RESET_RUN, 1);
|
||||
Err(xous::Error::OutOfMemory)
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn flush_if_full(&self) -> Result::<(), xous::Error> {
|
||||
// check to see if the FIFO is full first. If so, drain it.
|
||||
if self.perf_csr.rf(utra::perfcounter::STATUS_FULL) != 0 {
|
||||
self.flush()
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Flushes any data in the FIFO to the performance buffer. Also stops the performance counter from running.
|
||||
/// Returns the total number of entries in the buffer, or an OOM if the buffer is full
|
||||
/// This will update the time stamp rollover counter, so, you could in theory restart after this without losing state.
|
||||
pub fn stop_and_flush(&self) -> Result::<u32, xous::Error> {
|
||||
let mut oom = false;
|
||||
// stop the counter
|
||||
self.perf_csr.wfo(utra::perfcounter::RUN_STOP, 1);
|
||||
// copy over the events to the long term buffer
|
||||
let mut ts_offset = 0;
|
||||
let mut expected_i = 0;
|
||||
while self.perf_csr.rf(utra::perfcounter::STATUS_READABLE) == 1 {
|
||||
if *self.log_index.borrow() < self.data.borrow().len() {
|
||||
self.dbg_buf_count.replace(self.dbg_buf_count.take() + 1); // this tracks total entries copied into the perfbuf
|
||||
self.data.borrow_mut()[*self.log_index.borrow()].code = self.perf_csr.r(utra::perfcounter::EVENT_RAW0);
|
||||
ts_offset = self.perf_csr.r(utra::perfcounter::EVENT_RAW1) as u32;
|
||||
self.data.borrow_mut()[*self.log_index.borrow()].ts = *self.ts_cont.borrow() as u32 + ts_offset;
|
||||
|
||||
let i = self.perf_csr.r(utra::perfcounter::EVENT_INDEX); // this advances the FIFO
|
||||
if i != expected_i {
|
||||
log::info!("i {} != expected_i {}", i, expected_i);
|
||||
}
|
||||
expected_i += 1;
|
||||
self.log_index.replace(self.log_index.take() + 1);
|
||||
} else {
|
||||
oom = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
self.ts_cont.replace(self.ts_cont.take() + ts_offset as u64);
|
||||
log::info!("FIFO final flush had {} entries", expected_i - 1);
|
||||
log::info!("Had {} buffer entries", *self.dbg_buf_count.borrow()); // should be the same as above, but trying to chase down some minor issues...
|
||||
if !oom {
|
||||
Ok(*self.dbg_buf_count.borrow())
|
||||
} else {
|
||||
Err(xous::Error::OutOfMemory)
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn print_page_table(&self) {
|
||||
log::info!("Buf vmem loc: {:x}", self.data.borrow().as_ptr() as u32);
|
||||
match xous::syscall::virt_to_phys(self.data.borrow().as_ptr() as usize) {
|
||||
Ok(addr) => log::info!("got {}", addr),
|
||||
Err(e) => log::info!("error: {:?}", e),
|
||||
};
|
||||
log::info!("Buf pmem loc: {:x}", xous::syscall::virt_to_phys(self.data.borrow().as_ptr() as usize).unwrap_or(0));
|
||||
log::info!("PerfLogEntry size: {}", core::mem::size_of::<PerfLogEntry>());
|
||||
log::info!("Now printing the page table mapping for the performance buffer:");
|
||||
for page in (0..BUFLEN).step_by(4096) {
|
||||
log::info!("V|P {:x} {:x}",
|
||||
self.data.borrow().as_ptr() as usize + page,
|
||||
xous::syscall::virt_to_phys(self.data.borrow().as_ptr() as usize + page).unwrap_or(0),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -9,6 +9,7 @@ import sys
|
|||
import hashlib
|
||||
import csv
|
||||
import urllib.request
|
||||
import re
|
||||
|
||||
from progressbar.bar import ProgressBar
|
||||
|
||||
|
|
@ -482,6 +483,12 @@ def main():
|
|||
parser.add_argument(
|
||||
"--override-csr", required=False, help="CSR file to use instead of CSR values stored with the image. Used to recover in case of partial update of soc_csr.bin", type=str,
|
||||
)
|
||||
parser.add_argument(
|
||||
"--dump", required=False, help="Dump a region of memory. Takes a virtual memory map file as an argument. Looks for lines of format `V|P vaddr paddr`", type=str,
|
||||
)
|
||||
parser.add_argument(
|
||||
"--dump-file", required=False, help="Name out output file for dump. Required if --dump is specified.", type=str,
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
if not len(sys.argv) > 1:
|
||||
|
|
@ -570,6 +577,27 @@ def main():
|
|||
|
||||
vexdbg_addr = int(pc_usb.regions['vexriscv_debug'][0], 0)
|
||||
pc_usb.ping_wdt()
|
||||
|
||||
if args.dump:
|
||||
table = []
|
||||
with open(args.dump, 'r') as map:
|
||||
for line in map.readlines():
|
||||
rgx = re.search('.*V\|P\s([0-9a-fA-F]*)\s([0-9a-fA-F]*).*', line)
|
||||
if rgx is not None:
|
||||
map = rgx.groups()
|
||||
table += [int(map[1], 16)]
|
||||
|
||||
if args.dump_file is None:
|
||||
print("Must specify --dump-file when using --dump")
|
||||
exit(0)
|
||||
with open(args.dump_file, 'wb') as f:
|
||||
for page in table:
|
||||
pc_usb.poke(vexdbg_addr, 0x00020000)
|
||||
data = pc_usb.burst_read(page, 4096)
|
||||
pc_usb.poke(vexdbg_addr, 0x02000000)
|
||||
f.write(data)
|
||||
exit(0)
|
||||
|
||||
print("Halting CPU.")
|
||||
pc_usb.poke(vexdbg_addr, 0x00020000)
|
||||
|
||||
|
|
|
|||
|
|
@ -13,6 +13,8 @@ core = { version = '1.0.0', optional = true, package = 'rustc-std-workspace-core
|
|||
compiler_builtins = { version = '0.1.0', optional = true }
|
||||
|
||||
[features]
|
||||
v2p = []
|
||||
default = []
|
||||
|
||||
# If this is set, then the "Drop" feature of MemoryMessage structs
|
||||
# will not be implemented. This should only be set by the kernel.
|
||||
|
|
|
|||
|
|
@ -457,6 +457,21 @@ pub enum SysCall {
|
|||
usize, /* proposed new limit */
|
||||
),
|
||||
|
||||
/// Returns the physical address corresponding to a virtual address, if such a mapping exists.
|
||||
///
|
||||
/// ## Arguments
|
||||
/// * **vaddr**: The virtual address to inspect
|
||||
///
|
||||
/// ## Returns
|
||||
/// Returns a Scalar1 containing the physical address
|
||||
///
|
||||
/// ## Errors
|
||||
/// * **BadAddress**: The mapping does not exist
|
||||
#[cfg(feature="v2p")]
|
||||
VirtToPhys(
|
||||
usize, /* virtual address */
|
||||
),
|
||||
|
||||
/// This syscall does not exist. It captures all possible
|
||||
/// arguments so detailed analysis can be performed.
|
||||
Invalid(usize, usize, usize, usize, usize, usize, usize),
|
||||
|
|
@ -501,6 +516,8 @@ pub enum SysCallNumber {
|
|||
JoinThread = 36,
|
||||
SetExceptionHandler = 37,
|
||||
AdjustProcessLimit = 38,
|
||||
#[cfg(feature="v2p")]
|
||||
VirtToPhys = 39,
|
||||
Invalid,
|
||||
}
|
||||
|
||||
|
|
@ -545,6 +562,8 @@ impl SysCallNumber {
|
|||
36 => JoinThread,
|
||||
37 => SetExceptionHandler,
|
||||
38 => AdjustProcessLimit,
|
||||
#[cfg(feature="v2p")]
|
||||
39 => VirtToPhys,
|
||||
_ => Invalid,
|
||||
}
|
||||
}
|
||||
|
|
@ -909,6 +928,17 @@ impl SysCall {
|
|||
0,
|
||||
0,
|
||||
],
|
||||
#[cfg(feature="v2p")]
|
||||
SysCall::VirtToPhys(vaddr) => [
|
||||
SysCallNumber::VirtToPhys as usize,
|
||||
*vaddr,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
],
|
||||
SysCall::Invalid(a1, a2, a3, a4, a5, a6, a7) => [
|
||||
SysCallNumber::Invalid as usize,
|
||||
*a1,
|
||||
|
|
@ -1073,6 +1103,8 @@ impl SysCall {
|
|||
SysCallNumber::JoinThread => SysCall::JoinThread(a1 as _),
|
||||
SysCallNumber::SetExceptionHandler => SysCall::SetExceptionHandler(a1 as _, a2 as _),
|
||||
SysCallNumber::AdjustProcessLimit => SysCall::AdjustProcessLimit(a1, a2, a3),
|
||||
#[cfg(feature="v2p")]
|
||||
SysCallNumber::VirtToPhys => SysCall::VirtToPhys(a1 as _),
|
||||
SysCallNumber::Invalid => SysCall::Invalid(a1, a2, a3, a4, a5, a6, a7),
|
||||
})
|
||||
}
|
||||
|
|
@ -1839,6 +1871,18 @@ pub fn set_exception_handler(
|
|||
}
|
||||
*/
|
||||
|
||||
/// Translate a virtual address to a physical address
|
||||
#[cfg(feature="v2p")]
|
||||
pub fn virt_to_phys(va: usize) -> core::result::Result<usize, Error> {
|
||||
rsyscall(SysCall::VirtToPhys(va)).and_then(|result| {
|
||||
if let Result::Scalar1(pa) = result {
|
||||
Ok(pa)
|
||||
} else {
|
||||
Err(Error::BadAddress)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Perform a raw syscall and return the result. This will transform
|
||||
/// `xous::Result::Error(e)` into an `Err(e)`.
|
||||
pub fn rsyscall(call: SysCall) -> SysCallResult {
|
||||
|
|
|
|||
|
|
@ -311,7 +311,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||
None,
|
||||
Some(&["--features", "tts", "--features", "braille"]),
|
||||
&[&tts_exec_string],
|
||||
None,
|
||||
None, None,
|
||||
)?;
|
||||
let mut locale_revert = OpenOptions::new()
|
||||
.read(true)
|
||||
|
|
@ -345,7 +345,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||
None,
|
||||
None,
|
||||
None,
|
||||
extra_packages.as_slice(), None)?;
|
||||
extra_packages.as_slice(), None, None)?;
|
||||
}
|
||||
}
|
||||
Some("libstd-test") => {
|
||||
|
|
@ -385,6 +385,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||
None,
|
||||
&[],
|
||||
Some(&["--features", "renode-bypass"]),
|
||||
None,
|
||||
)?
|
||||
//renode_image(false, &pkgs, extra_packages.as_slice(),
|
||||
//None, Some(&["--features", "renode-bypass"]))?;
|
||||
|
|
@ -535,10 +536,17 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||
kkey,
|
||||
None,
|
||||
&[],
|
||||
None,
|
||||
None, None,
|
||||
)?
|
||||
}
|
||||
Some("perf-image") => {
|
||||
// note: to use this image, you need to load a version of the SOC that has the performance counters built in.
|
||||
// this can be generated using the command `python3 .\betrusted_soc.py -e .\dummy.nky --perfcounter` in the betrusted-soc repo.
|
||||
//
|
||||
// to read out performance monitoring data, use the `usb_update.py` script as follows:
|
||||
// ` python3 .\..\usb_update.py --dump v2p.txt --dump-file .\ring_aes_8.bin`
|
||||
// where the `v2p.txt` file contains a virtual to physical mapping that is generated by the `perflib` framework and
|
||||
// formatted in a fashion that can be automatically extracted by the usb_update script.
|
||||
let mut args = env::args();
|
||||
args.nth(1);
|
||||
let mut pkgs = hw_pkgs.to_vec();
|
||||
|
|
@ -554,10 +562,13 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||
lkey,
|
||||
kkey,
|
||||
Some(&[
|
||||
"--features", "perfcounter"
|
||||
"--features", "perfcounter",
|
||||
]),
|
||||
&[],
|
||||
None,
|
||||
Some(&[
|
||||
"--features", "v2p",
|
||||
]),
|
||||
)?
|
||||
}
|
||||
Some("utra") => {
|
||||
|
|
@ -584,6 +595,9 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||
std::env::set_var("XOUS_SVD_FILE", path.canonicalize().unwrap());
|
||||
println!("XOUS_SVD_FILE: {}", path.canonicalize().unwrap().display());
|
||||
}
|
||||
let generated_path = std::path::Path::new("utralib/src/generated.rs");
|
||||
// blank the contents so that the build command runs
|
||||
std::fs::write(generated_path, "")?;
|
||||
let status = Command::new(cargo())
|
||||
.current_dir(project_root())
|
||||
.args(&[
|
||||
|
|
@ -615,7 +629,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||
"--features", "ditherpunk",
|
||||
]),
|
||||
&[],
|
||||
None,
|
||||
None, None,
|
||||
)?
|
||||
}
|
||||
Some("hw-image") => {
|
||||
|
|
@ -639,7 +653,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||
kkey,
|
||||
None,
|
||||
&[],
|
||||
None,
|
||||
None, None,
|
||||
)?
|
||||
}
|
||||
Some("gfx-dev") => run(
|
||||
|
|
@ -656,7 +670,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||
kkey,
|
||||
None,
|
||||
&[],
|
||||
None,
|
||||
None, None,
|
||||
)?,
|
||||
Some("pddb-hosted") => run(false, &pddb_dev_pkgs, None, false)?,
|
||||
Some("benchmark") => build_hw_image(
|
||||
|
|
@ -667,7 +681,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||
kkey,
|
||||
None,
|
||||
&[],
|
||||
None,
|
||||
None, None,
|
||||
)?,
|
||||
Some("minimal") => build_hw_image(
|
||||
false,
|
||||
|
|
@ -677,7 +691,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||
kkey,
|
||||
None,
|
||||
&[],
|
||||
None,
|
||||
None, None,
|
||||
)?,
|
||||
Some("cbtest") => build_hw_image(
|
||||
false,
|
||||
|
|
@ -687,7 +701,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||
kkey,
|
||||
None,
|
||||
&[],
|
||||
None,
|
||||
None, None,
|
||||
)?,
|
||||
Some("trng-test") => {
|
||||
generate_app_menus(&Vec::<String>::new());
|
||||
|
|
@ -699,7 +713,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||
kkey,
|
||||
Some(&["--features", "urandomtest"]),
|
||||
&[],
|
||||
None,
|
||||
None, None,
|
||||
)?
|
||||
}
|
||||
Some("ro-test") => {
|
||||
|
|
@ -712,7 +726,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||
kkey,
|
||||
Some(&["--features", "ringosctest"]),
|
||||
&[],
|
||||
None,
|
||||
None, None,
|
||||
)?
|
||||
}
|
||||
Some("av-test") => {
|
||||
|
|
@ -725,7 +739,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||
kkey,
|
||||
Some(&["--features", "avalanchetest"]),
|
||||
&[],
|
||||
None,
|
||||
None, None,
|
||||
)?
|
||||
}
|
||||
Some("sr-test") => build_hw_image(
|
||||
|
|
@ -736,7 +750,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||
kkey,
|
||||
None,
|
||||
&[],
|
||||
None,
|
||||
None, None,
|
||||
)?,
|
||||
Some("burn-kernel") => update_usb(true, false, false, false)?,
|
||||
Some("burn-loader") => update_usb(false, true, false, false)?,
|
||||
|
|
@ -952,6 +966,7 @@ fn build_hw_image(
|
|||
extra_args: Option<&[&str]>,
|
||||
extra_packages: &[&str],
|
||||
loader_features: Option<&[&str]>,
|
||||
kernel_features: Option<&[&str]>,
|
||||
) -> Result<(), DynError> {
|
||||
let svd_file = match svd {
|
||||
Some(s) => s,
|
||||
|
|
@ -972,7 +987,7 @@ fn build_hw_image(
|
|||
let loaderkey_file = lkey.unwrap_or_else(|| "devkey/dev.key".into());
|
||||
let kernelkey_file = kkey.unwrap_or_else(|| "devkey/dev.key".into());
|
||||
|
||||
let kernel = build_kernel(debug)?;
|
||||
let kernel = build_kernel(debug, kernel_features)?;
|
||||
let mut init = vec![];
|
||||
let base_path = build(
|
||||
packages,
|
||||
|
|
@ -1170,6 +1185,7 @@ fn renode_image(
|
|||
xous_features,
|
||||
extra_packages,
|
||||
loader_features,
|
||||
None,
|
||||
)
|
||||
}
|
||||
|
||||
|
|
@ -1234,8 +1250,8 @@ fn run(
|
|||
Ok(())
|
||||
}
|
||||
|
||||
fn build_kernel(debug: bool) -> Result<PathBuf, DynError> {
|
||||
let mut path = build(&["kernel"], debug, Some(KERNEL_TARGET), None, None, None)?;
|
||||
fn build_kernel(debug: bool, features: Option<&[&str]>) -> Result<PathBuf, DynError> {
|
||||
let mut path = build(&["kernel"], debug, Some(KERNEL_TARGET), None, None, features)?;
|
||||
path.push("kernel");
|
||||
Ok(path)
|
||||
}
|
||||
|
|
|
|||