diff --git a/Cargo.lock b/Cargo.lock index b53a9f55a..1db0a23a6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -459,7 +459,7 @@ dependencies = [ [[package]] name = "com_rs" version = "0.1.0" -source = "git+https://github.com/betrusted-io/com_rs.git?rev=b3bf4aebe1d3c91e77dae5d3832d17e717c5669b#b3bf4aebe1d3c91e77dae5d3832d17e717c5669b" +source = "git+https://github.com/betrusted-io/com_rs.git?rev=1effb7eaebbec59f7fda4a678e2d36efafc2e673#1effb7eaebbec59f7fda4a678e2d36efafc2e673" [[package]] name = "com_rs-ref" @@ -1279,6 +1279,7 @@ version = "0.1.0" dependencies = [ "byteorder", "com", + "com_rs-ref", "llio", "log", "log-server", @@ -1961,6 +1962,7 @@ dependencies = [ "cipher", "codec", "com", + "com_rs-ref", "content-plugin-api", "curve25519-dalek", "debug-here", diff --git a/imports/com_rs-ref/Cargo.toml b/imports/com_rs-ref/Cargo.toml index da0df052c..9ec1a9303 100644 --- a/imports/com_rs-ref/Cargo.toml +++ b/imports/com_rs-ref/Cargo.toml @@ -7,7 +7,7 @@ description = "com_rs import package" # Dependency policy: fully specify dependencies to the minor version number [dependencies] -com_rs = { git = "https://github.com/betrusted-io/com_rs.git", rev = "b3bf4aebe1d3c91e77dae5d3832d17e717c5669b" } +com_rs = { git = "https://github.com/betrusted-io/com_rs.git", rev = "1effb7eaebbec59f7fda4a678e2d36efafc2e673" } #com_rs = { path = "../../../betrusted-ec/sw/com_rs" } diff --git a/services/com/src/api.rs b/services/com/src/api.rs index 036f3b348..5e8bfdc50 100644 --- a/services/com/src/api.rs +++ b/services/com/src/api.rs @@ -44,7 +44,7 @@ impl Into<[usize; 2]> for BattStats { } #[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] -pub enum FlashOp { +pub(crate) enum FlashOp { /// erase a region defined by (address, len) Erase(u32, u32), /// Send up to 1kiB of data at a time. This reduces messaging overhead and makes @@ -54,17 +54,82 @@ pub enum FlashOp { Program(u32, [Option<[u8; 256]>; 4]) } #[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] -pub enum FlashResult { +pub(crate) enum FlashResult { Pass, Fail, } #[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] -pub struct FlashRecord { +pub(crate) struct FlashRecord { /// identifier to validate that we're authorized to do this pub id: [u32; 4], /// operation pub op: FlashOp, } +#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] +pub struct SsidRecord { + pub name: xous_ipc::String::<32>, + pub rssi: u8, +} +impl Default for SsidRecord { + fn default() -> Self { + SsidRecord { name: xous_ipc::String::<32>::new(), rssi: 0 } + } +} +#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] +pub(crate) struct SsidReturn { + pub list: [SsidRecord; 8], +} +impl Default for SsidReturn { + fn default() -> Self { + SsidReturn { + list: [SsidRecord::default(); 8], + } + } +} +#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] +pub(crate) struct WlanStatusIpc { + pub ssid: Option, + pub link_state: u16, // this is slung around as a u16 to avoid pulling rkyv into the EC dependency tree + pub ipv4: [u16; com_rs_ref::ComState::WLAN_GET_IPV4_CONF.r_words as usize], +} +impl Default for WlanStatusIpc { + fn default() -> Self { + WlanStatusIpc { + ssid: None, + link_state: com_rs_ref::LinkState::Unknown as u16, + ipv4: [0u16; com_rs_ref::ComState::WLAN_GET_IPV4_CONF.r_words as usize], + } + } +} +#[derive(Debug, Copy, Clone)] +pub struct WlanStatus { + pub ssid: Option, + pub link_state: com_rs_ref::LinkState, // converted back into LinkState once it's across the IPC boundary + pub ipv4: Ipv4Conf, +} +impl WlanStatus { + #[allow(dead_code)] + pub(crate) fn from_ipc(status: WlanStatusIpc) -> Self { + WlanStatus { + ssid: status.ssid, + link_state: com_rs_ref::LinkState::decode_u16(status.link_state), + ipv4: com_rs_ref::serdes::Ipv4Conf::decode_u16(&status.ipv4), + } + } +} + +#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Default)] +pub struct WlanDebug { + pub tx_errs: u32, + pub drops: u32, + // config(2) - control - alloc_fail(2) - alloc_oversize(2) - alloc_count + pub config: u32, + pub control: u16, + pub alloc_fail: u32, + pub alloc_oversize: u32, + pub alloc_free_count: u16, +} + #[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)] pub(crate) enum Opcode { @@ -131,9 +196,12 @@ pub(crate) enum Opcode { /// Return the latest SSID list SsidFetchAsString, + SsidFetchAsStringV2, /// Fetch the git ID of the EC EcGitRev, + /// Fetch the SW tag of the EC as a {00|maj|min|rev} u32 + EcSwTag, /// Fetch the firmware rev of the WF200 Wf200Rev, @@ -189,6 +257,9 @@ pub(crate) enum Opcode { /// wlan: send net packet WlanSendPacket, + /// wlan: debug infos + WlanDebug, + /// sets the EC-side com interrupt mask IntSetMask, diff --git a/services/com/src/lib.rs b/services/com/src/lib.rs index 1d91e597c..2c0d7a22c 100644 --- a/services/com/src/lib.rs +++ b/services/com/src/lib.rs @@ -4,7 +4,7 @@ /// are calling these functions inside a different process. pub mod api; -pub use api::BattStats; +pub use api::*; use api::{Callback, ComIntSources, NET_MTU, Opcode}; use xous::{send_message, Error, CID, Message, msg_scalar_unpack}; use xous_ipc::{String, Buffer}; @@ -111,6 +111,7 @@ impl Com { } } + /// this is the Git rev of the *soc*, not the firmware. pub fn get_ec_git_rev(&self) -> Result<(u32, bool), Error> { let response = send_message(self.conn, Message::new_blocking_scalar(Opcode::EcGitRev.to_usize().unwrap(), 0, 0, 0, 0))?; @@ -127,6 +128,22 @@ impl Com { } } + /// this is the rev of the firmware, as (maj, min, rev, +commit) + pub fn get_ec_sw_tag(&self) -> Result<(u8, u8, u8, u8), Error> { + let response = send_message(self.conn, + Message::new_blocking_scalar(Opcode::EcSwTag.to_usize().unwrap(), 0, 0, 0, 0))?; + if let xous::Result::Scalar1(rev) = response { + Ok(( + ((rev >> 24) & 0xff) as u8, + ((rev >> 16) & 0xff) as u8, + ((rev >> 8) & 0xff) as u8, + ((rev >> 0) & 0xff) as u8, + )) + } else { + panic!("unexpected return value: {:#?}", response); + } + } + pub fn send_pds_line(&self, s: &String<512>) -> Result<(), Error> { use core::fmt::Write; let mut clone_s: String<512> = String::new(); @@ -232,6 +249,8 @@ impl Com { Err(xous::Error::InternalError) } } + // superceded by ssid_fetch_as_list in versions later 0.9.5 (non-inclusive) + #[deprecated] pub fn ssid_fetch_as_string(&self) -> Result, xous::Error> { let ssid_list = xous_ipc::String::<256>::new(); let mut buf = Buffer::into_buf(ssid_list).or(Err(xous::Error::InternalError))?; @@ -239,6 +258,18 @@ impl Com { let response = buf.to_original::, _>().unwrap(); Ok(response) } + /// returns a vector of `(u8, String)` tuples that represent rssi + AP name + pub fn ssid_fetch_as_list(&self) -> Result, xous::Error> { + let ssid_alloc = SsidReturn::default(); + let mut buf = Buffer::into_buf(ssid_alloc).or(Err(xous::Error::InternalError))?; + buf.lend_mut(self.conn, Opcode::SsidFetchAsStringV2.to_u32().unwrap()).or(Err(xous::Error::InternalError))?; + let response = buf.to_original::().unwrap(); + let mut ret = Vec::<(u8, std::string::String)>::new(); + for ssid in response.list { + ret.push((ssid.rssi, std::string::String::from(ssid.name.as_str().unwrap_or("UTF-8 Parse Error")))); + } + Ok(ret) + } pub fn get_standby_current(&self) -> Result, xous::Error> { if let xous::Result::Scalar2(valid, current) = @@ -419,14 +450,12 @@ impl Com { ) } - pub fn wlan_status(&mut self) -> Result { - // TODO: how to make this return IP, netmask, gateway, DNS server, and STA MAC? - const STATUS_MAX_LEN: usize = 160; - let status = xous_ipc::String::::new(); + pub fn wlan_status(&mut self) -> Result { + let status = WlanStatusIpc::default(); let mut buf = Buffer::into_buf(status).or(Err(xous::Error::InternalError))?; buf.lend_mut(self.conn, Opcode::WlanStatus.to_u32().unwrap()).or(Err(xous::Error::InternalError))?; - let response = buf.to_original::, _>().unwrap(); - Ok(std::string::String::from(response.as_str().expect("status contained non-utf8 characters"))) + let response = buf.to_original::().unwrap(); + Ok(WlanStatus::from_ipc(response)) } pub fn wlan_get_config(&self) -> Result { @@ -438,6 +467,14 @@ impl Com { Ok(config) } + pub fn wlan_debug(&self) -> Result { + let prealloc = WlanDebug::default(); + let mut buf = Buffer::into_buf(prealloc).or(Err(xous::Error::InternalError))?; + buf.lend_mut(self.conn, Opcode::WlanDebug.to_u32().expect("WlanDebug failed")).or(Err(xous::Error::InternalError))?; + let response = buf.to_original().expect("Couldn't convert WlanDebug buffer"); + Ok(response) + } + pub fn wlan_fetch_packet(&self, pkt: &mut [u8]) -> Result<(), xous::Error> { if pkt.len() > NET_MTU { return Err(xous::Error::OutOfMemory) diff --git a/services/com/src/main.rs b/services/com/src/main.rs index bb944720b..288a003d6 100644 --- a/services/com/src/main.rs +++ b/services/com/src/main.rs @@ -10,12 +10,17 @@ use log::{error, info, trace}; use com_rs_ref as com_rs; use com_rs::*; -use com_rs::serdes::{STR_32_WORDS, STR_64_WORDS, STR_64_U8_SIZE, StringSer, StringDes, Ipv4Conf}; +use com_rs::serdes::{STR_32_WORDS, STR_64_WORDS, StringSer, Ipv4Conf}; use xous::{CID, msg_scalar_unpack, msg_blocking_scalar_unpack}; use xous_ipc::{Buffer, String}; +use core::convert::TryInto; + +const LEGACY_REV: u32 = 0x8b5b_8e50; // this is the git rev shipped before we went to version tagging +const LEGACY_TAG: u32 = 0x00_09_05_00; // this is corresponding tag const STD_TIMEOUT: u32 = 100; + #[derive(Debug, Copy, Clone)] pub struct WorkRequest { work: ComSpec, @@ -367,6 +372,22 @@ fn xmain() -> ! { } } + // determine the version of the COM that we're talking to + let mut ec_git_rev = { + com.txrx(ComState::EC_GIT_REV.verb); + let rev_msb = com.wait_txrx(ComState::LINK_READ.verb, Some(STD_TIMEOUT)) as u16; + let rev_lsb = com.wait_txrx(ComState::LINK_READ.verb, Some(STD_TIMEOUT)) as u16; + let _dirty = com.wait_txrx(ComState::LINK_READ.verb, Some(STD_TIMEOUT)) as u8; + ((rev_msb as u32) << 16) | (rev_lsb as u32) + }; + let mut ec_tag = { + if ec_git_rev == LEGACY_REV { + LEGACY_TAG + } else { + parse_version(&mut com) + } + }; + trace!("starting main loop"); loop { let mut msg = xous::receive_message(com_sid).unwrap(); @@ -610,13 +631,28 @@ fn xmain() -> ! { let rev_msb = com.wait_txrx(ComState::LINK_READ.verb, Some(STD_TIMEOUT)) as u16; let rev_lsb = com.wait_txrx(ComState::LINK_READ.verb, Some(STD_TIMEOUT)) as u16; let dirty = com.wait_txrx(ComState::LINK_READ.verb, Some(STD_TIMEOUT)) as u8; + ec_git_rev = ((rev_msb as u32) << 16) | (rev_lsb as u32); xous::return_scalar2( msg.sender, - ((rev_msb as usize) << 16) | (rev_lsb as usize), + ec_git_rev as usize, dirty as usize ) .expect("couldn't return WF200 firmware rev"); } + Some(Opcode::EcSwTag) => { + if ec_git_rev == LEGACY_REV { // this corresponds to a 0.9.5 tag -- the last tag shipped that lacked detailed versioning + xous::return_scalar( + msg.sender, + 0x00_09_05_00 + ).expect("couldn't return WF200 revision tag"); + } else { + ec_tag = parse_version(&mut com); + xous::return_scalar( + msg.sender, + ec_tag as usize, + ).expect("couldn't return WF200 revision tag"); + } + } Some(Opcode::Wf200Reset) => { com.txrx(ComState::WF200_RESET.verb); com.txrx(0); @@ -639,46 +675,81 @@ fn xmain() -> ! { ).expect("couldn't return SsidCheckUpdate"); }, Some(Opcode::SsidFetchAsString) => { - use core::fmt::Write; - let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; + if ec_tag == LEGACY_TAG { + // this is kept around because the original firmware shipped with units don't support software tagging + // and the SSID API was modified. This allows the SOC to interop with older versions of the EC for SSID scanning. + // If it's 2023 and you're looking at this comment and thinking about removing this code, it might actually be + // ok to do that. Just check that the factory test infrastructure is fully updated to match a modern EC rev. + use core::fmt::Write; + let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; - com.txrx(ComState::SSID_FETCH.verb); - let mut ssid_list: [[u8; 32]; 6] = [[0; 32]; 6]; // index as ssid_list[6][32] - for i in 0..16 * 6 { - let data = com.wait_txrx(ComState::LINK_READ.verb, Some(STD_TIMEOUT)) as u16; - let lsb : u8 = (data & 0xff) as u8; - let msb : u8 = ((data >> 8) & 0xff) as u8; - //if lsb == 0 { lsb = 0x20; } - //if msb == 0 { msb = 0x20; } - ssid_list[i / 16][(i % 16) * 2] = lsb; - ssid_list[i / 16][(i % 16) * 2 + 1] = msb; - } - // this is a questionably useful return format -- maybe it's actually more useful to return the raw characters?? - // for now, this is good enough for human eyes, but a scrollable list of SSIDs might be more useful with the raw u8 representation - let mut ssid_str = xous_ipc::String::<256>::from_str("Top 6 SSIDs:\n"); - let mut itemized = xous_ipc::String::<256>::new(); - for i in 0..6 { - let mut stop = 0; - // truncate the nulls - for l in 0..ssid_list[i].len() { - stop = l; - if ssid_list[i][l] == 0 { - break; + com.txrx(ComState::SSID_FETCH.verb); + let mut ssid_list: [[u8; 32]; 6] = [[0; 32]; 6]; // index as ssid_list[6][32] + for i in 0..16 * 6 { + let data = com.wait_txrx(ComState::LINK_READ.verb, Some(STD_TIMEOUT)) as u16; + let lsb : u8 = (data & 0xff) as u8; + let msb : u8 = ((data >> 8) & 0xff) as u8; + //if lsb == 0 { lsb = 0x20; } + //if msb == 0 { msb = 0x20; } + ssid_list[i / 16][(i % 16) * 2] = lsb; + ssid_list[i / 16][(i % 16) * 2 + 1] = msb; + } + // this is a questionably useful return format -- maybe it's actually more useful to return the raw characters?? + // for now, this is good enough for human eyes, but a scrollable list of SSIDs might be more useful with the raw u8 representation + let mut ssid_str = xous_ipc::String::<256>::from_str("Top 6 SSIDs:\n"); + let mut itemized = xous_ipc::String::<256>::new(); + for i in 0..6 { + let mut stop = 0; + // truncate the nulls + for l in 0..ssid_list[i].len() { + stop = l; + if ssid_list[i][l] == 0 { + break; + } + } + let ssid = core::str::from_utf8(&ssid_list[i][0..stop]); + match ssid { + Ok(textid) => { + itemized.clear(); + write!(itemized, "{}. {}\n", i+1, textid).unwrap(); + ssid_str.append(itemized.as_str().unwrap()).unwrap(); + }, + _ => { + ssid_str.append("-Parse Error-\n").unwrap(); + }, } } - let ssid = core::str::from_utf8(&ssid_list[i][0..stop]); - match ssid { - Ok(textid) => { - itemized.clear(); - write!(itemized, "{}. {}\n", i+1, textid).unwrap(); - ssid_str.append(itemized.as_str().unwrap()).unwrap(); - }, - _ => { - ssid_str.append("-Parse Error-\n").unwrap(); - }, + buffer.replace(ssid_str).unwrap(); + } else { + log::error!("This API is not implemented for this EC firmware revision"); + } + } + Some(Opcode::SsidFetchAsStringV2) => { + if ec_tag == LEGACY_TAG { + log::error!("This API is not implemented for legacy EC revs"); + continue; + } + com.txrx(ComState::SSID_FETCH_STR.verb); + // these sizes are hard-coded constants from the EC firmware. We don't have a good cross-code base method for + // sharing these yet, so they are just magic numbers. + let mut ssid_list: [[u8; 34]; 8] = [[0; 34]; 8]; + for record in ssid_list.iter_mut() { + for word in record.chunks_mut(2) { + let data = com.wait_txrx(ComState::LINK_READ.verb, Some(STD_TIMEOUT)) as u16; + word[0] = (data & 0xff) as u8; + word[1] = ((data >> 8) & 0xff) as u8; } } - buffer.replace(ssid_str).unwrap(); + let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; + let mut ssid_ret = buffer.to_original::().expect("couldn't convert incoming storage"); + for (raw, ssid_rec) in ssid_list.iter().zip(ssid_ret.list.iter_mut()) { + ssid_rec.rssi = raw[0]; + let len = if raw[1] < 32 {raw[1] as usize} else {32}; + let ssid_str = core::str::from_utf8(&raw[2..2 + len as usize]).unwrap_or("UTF-8 parse error"); + ssid_rec.name.clear(); // should be pre-cleared, but let's just be safe about it + ssid_rec.name.append(ssid_str).ok(); // don't panic if we truncate + } + buffer.replace(ssid_ret).unwrap(); } Some(Opcode::WlanOn) => { info!("TODO: implement WlanOn"); @@ -729,31 +800,47 @@ fn xmain() -> ! { com.txrx(ComState::WLAN_LEAVE.verb); } Some(Opcode::WlanStatus) => { - let mut buffer = unsafe { - Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) - }; - com.txrx(ComState::WLAN_STATUS.verb); - let mut rx_buf: [u16; STR_64_WORDS] = [0; STR_64_WORDS]; - for dest in rx_buf.iter_mut() { - *dest = com.wait_txrx(ComState::LINK_READ.verb, Some(STD_TIMEOUT)); - } - let mut des = StringDes::::new(); - match des.decode_u16(&rx_buf) { - Ok(status) => { - log::debug!("status: {}", status); - let status_str = String::::from_str(&status); - let _ = buffer.replace(status_str); + if ec_tag == LEGACY_TAG { + log::warn!("Legacy EC detected. Ignoring status request update"); + } else { + let mut buffer = unsafe { + Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) + }; + com.txrx(ComState::WLAN_BIN_STATUS.verb); + let maybe_rssi = com.wait_txrx(ComState::LINK_READ.verb, Some(STD_TIMEOUT)); + let rssi = if (maybe_rssi >> 8) & 0xff != 0 { + None + } else { + Some(maybe_rssi & 0xff) + }; + let link_state = com.wait_txrx(ComState::LINK_READ.verb, Some(STD_TIMEOUT)); + let mut ipv4_raw = Ipv4Conf::default().encode_u16(); + for dest in ipv4_raw.iter_mut() { + *dest = com.wait_txrx(ComState::LINK_READ.verb, Some(STD_TIMEOUT)); } - _ => { - #[cfg(not(any(target_os = "none", target_os = "xous")))] - { - let status_str = String::::from_str("down"); - let _ = buffer.replace(status_str); - log::info!("replacing status with bogus data"); - } - info!("status decode failed"); - }, - }; + let mut ssid_buf = [0u8; 34]; + for w in ssid_buf.chunks_mut(2) { + let word = com.wait_txrx(ComState::LINK_READ.verb, Some(STD_TIMEOUT)).to_le_bytes(); + w[0] = word[0]; + w[1] = word[1]; + } + let ssid_len = u16::from_le_bytes(ssid_buf[0..2].try_into().unwrap()) as usize; + let ssid_checked_len = if ssid_len < 32 {ssid_len} else {32}; + let ssid_str = core::str::from_utf8(&ssid_buf[2..2+ssid_checked_len]).unwrap_or("Invalid SSID"); + let status = WlanStatusIpc { + ssid: if let Some(rssi) = rssi { + Some(SsidRecord { + rssi: rssi as u8, + name: xous_ipc::String::<32>::from_str(ssid_str) + }) + } else { + None + }, + link_state, + ipv4: ipv4_raw, + }; + buffer.replace(status).unwrap(); + } } Some(Opcode::WlanGetConfig) => { let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; @@ -842,6 +929,38 @@ fn xmain() -> ! { .expect("couldn't return IntFetchVector"); } }), + Some(Opcode::WlanDebug) => { + com.txrx(ComState::WLAN_GET_ERRCOUNTS.verb); + let mut tx_errs_16 = [0u16; 2]; + let mut drops_16 = [0u16; 2]; + tx_errs_16[0] = com.wait_txrx(ComState::LINK_READ.verb, Some(STD_TIMEOUT)); + tx_errs_16[1] = com.wait_txrx(ComState::LINK_READ.verb, Some(STD_TIMEOUT)); + drops_16[0] = com.wait_txrx(ComState::LINK_READ.verb, Some(STD_TIMEOUT)); + drops_16[1] = com.wait_txrx(ComState::LINK_READ.verb, Some(STD_TIMEOUT)); + com.txrx(ComState::WF200_DEBUG.verb); + let mut config_16 = [0u16; 2]; + config_16[0] = com.wait_txrx(ComState::LINK_READ.verb, Some(STD_TIMEOUT)); + config_16[1] = com.wait_txrx(ComState::LINK_READ.verb, Some(STD_TIMEOUT)); + let control = com.wait_txrx(ComState::LINK_READ.verb, Some(STD_TIMEOUT)); + let mut alloc_fail_16 = [0u16; 2]; + alloc_fail_16[0] = com.wait_txrx(ComState::LINK_READ.verb, Some(STD_TIMEOUT)); + alloc_fail_16[1] = com.wait_txrx(ComState::LINK_READ.verb, Some(STD_TIMEOUT)); + let mut alloc_oversize_16 = [0u16; 2]; + alloc_oversize_16[0] = com.wait_txrx(ComState::LINK_READ.verb, Some(STD_TIMEOUT)); + alloc_oversize_16[1] = com.wait_txrx(ComState::LINK_READ.verb, Some(STD_TIMEOUT)); + let alloc_free_count = com.wait_txrx(ComState::LINK_READ.verb, Some(STD_TIMEOUT)); + let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; + let debug = WlanDebug { + tx_errs: from_le_words(tx_errs_16), + drops: from_le_words(drops_16), + config: from_le_words(config_16), + control, + alloc_fail: from_le_words(alloc_fail_16), + alloc_oversize: from_le_words(alloc_oversize_16), + alloc_free_count, + }; + buffer.replace(debug).unwrap(); + }, None => {error!("unknown opcode"); break}, } @@ -862,3 +981,42 @@ fn xmain() -> ! { log::trace!("quitting"); xous::terminate_process(0) } + +fn parse_version(com: &mut crate::implementation::XousCom) -> u32 { + com.txrx(ComState::EC_SW_TAG.verb); + let mut rev_ret = [0u16; ComState::EC_SW_TAG.r_words as usize]; + for w in rev_ret.iter_mut() { + *w = com.wait_txrx(ComState::LINK_READ.verb, Some(STD_TIMEOUT)) as u16; + } + // unpack u16 words into u8 array + let mut rev_bytes = [0u8; (ComState::EC_SW_TAG.r_words as usize - 1) * 2]; + for (src, dst) in rev_ret[1..].iter().zip(rev_bytes.chunks_mut(2)) { + dst[0] = src.to_le_bytes()[0]; + dst[1] = src.to_le_bytes()[1]; + } + // translate u8 array into &str + let len_checked = if rev_ret[0] as usize <= rev_bytes.len() { rev_ret[0] as usize} else {rev_bytes.len()}; + let revstr = core::str::from_utf8(&rev_bytes[..len_checked]).unwrap_or("v0.0.0-0-xxxxxxx"); // fake version number for hosted mode + // parse &str -- we do it here not in the EC, because the EC is memory-constrained + // v0.9.5-2-gb3e2868 exemplar template + let hyphenstr: Vec<&str> = revstr[1..].split('-').collect(); // drop the leading 'v' by doing [1..] + let revcodes: Vec<&str> = hyphenstr[0].split('.').collect(); + let major = revcodes[0].parse::().unwrap_or(0); + let minor = revcodes[1].parse::().unwrap_or(0); + let rev = revcodes[2].parse::().unwrap_or(0); + let commit = if hyphenstr.len() > 2 { // extra commits beyond the tag + // version-extra-commit + hyphenstr[1].parse::().unwrap_or(0) + } else { + // I think the "extra" might disappear in the case that there is no extra beyond the tag. In this case, we would have just + // v0.9.6-gxxxxxx only, not v0.9.6-0-gxxxxxx. I'm actually not 100% sure, but also, I can't seem to find a definitive + // answer right now and I don't want to fuck up the tag state of my repo just to find out. Either way, this + // logic will cause the right thing to happen (a 0 for the extra commits) + 0 + }; + (commit & 0xff) as u32 | ((rev & 0xff) as u32) << 8 | (((minor & 0xff) as u32) << 16) | (((major & 0xff) as u32) << 24) +} + +fn from_le_words(words: [u16; 2]) -> u32 { + words[0] as u32 | (words[1] as u32) << 16 +} \ No newline at end of file diff --git a/services/gam/src/canvas.rs b/services/gam/src/canvas.rs index f5ccf10a8..d1d3f0e09 100644 --- a/services/gam/src/canvas.rs +++ b/services/gam/src/canvas.rs @@ -207,10 +207,8 @@ pub fn deface(gfx: &graphics_server::Gfx, trng: &trng::Trng, canvases: &mut Hash } // rand >>= 1; - x = x % width; - y = y % height; - delta_x = delta_x % width; - delta_y = delta_y % width; + x = remap_rand(width as _, x as _, 0xfff); + y = remap_rand(height as _, y as _, 0xfff); gfx.draw_line_clipped_xor( Line::new_with_style( @@ -229,6 +227,19 @@ pub fn deface(gfx: &graphics_server::Gfx, trng: &trng::Trng, canvases: &mut Hash } defaced } +fn remap_rand(end_range: i32, rand: i16, source_range: i32) -> i16 { + // x is a number from 0 through 2^12 -1 = 4095 + // we want to take 0<->4095 and renormalize to a range of -width/2 <-> width/2 and + // then add it to width/2 to get a somewhat regular distribution (a modulus would + // tend to bias lines "away" from the lower and right edges since both points of + // the line would have to, by chance, be just up to the width but not larger than that) + ( + (((end_range as i32 * rand as i32 * 100i32) / source_range) // remap to 0:end_range*100 + - (end_range as i32 * 100i32) / 2i32) // remap to -end_range*100/2:end_range*100/2 + / 100i32 // remap to -end_range/2:end_range/2 + + (end_range as i32 / 2) // remap to 0:end_range + ) as i16 +} // we use the "screen" parameter to determine when we can turn off drawing to canvases that are off-screen pub fn recompute_canvases(canvases: &HashMap, screen: Rectangle) -> HashMap { diff --git a/services/net/Cargo.toml b/services/net/Cargo.toml index 646239f6d..8c7766921 100644 --- a/services/net/Cargo.toml +++ b/services/net/Cargo.toml @@ -22,6 +22,7 @@ llio = {path = "../llio"} com = {path = "../com"} byteorder = { version = "1.0", default-features = false } trng = {path = "../trng"} +com_rs-ref = {path = "../../imports/com_rs-ref"} # for automatic SSID management and AP list storage pddb = {path = "../pddb"} diff --git a/services/net/src/api.rs b/services/net/src/api.rs index b1b1764d6..88ca1f434 100644 --- a/services/net/src/api.rs +++ b/services/net/src/api.rs @@ -19,6 +19,10 @@ pub(crate) const SERVER_NAME_NET: &str = "_Middleware Network Server_"; #[allow(dead_code)] pub const AP_DICT_NAME: &'static str = "wlan_ap_list"; +#[allow(dead_code)] +/// minimum revision required for compatibility with Net crate +pub const MIN_EC_REV: u32 = 0x00_09_05_07; + /// Dispatch opcodes to the Net crate main loop. #[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] pub(crate) enum Opcode { @@ -45,6 +49,10 @@ pub(crate) enum Opcode { PingSetTimeout, PingGetTimeout, + /// Link Management, + GetIpv4Config, + Reset, + /// [Internal] com llio interrupt callback ComInterrupt, /// [Internal] run the network stack code diff --git a/services/net/src/connection_manager.rs b/services/net/src/connection_manager.rs index 65ce87e72..c879d0c5d 100644 --- a/services/net/src/connection_manager.rs +++ b/services/net/src/connection_manager.rs @@ -1,6 +1,7 @@ use crate::api::*; use std::sync::Arc; use core::sync::atomic::{AtomicU32, Ordering}; +use net::MIN_EC_REV; use xous::{msg_blocking_scalar_unpack, msg_scalar_unpack, send_message, Message}; use num_traits::*; use std::io::Read; @@ -19,12 +20,22 @@ pub(crate) fn connection_manager(sid: xous::SID, activity_interval: Arc= MIN_EC_REV; + if !rev_ok { + log::warn!("EC firmware is too old to interoperate with the connection manager."); + } + + let mut run = rev_ok; send_message(self_cid, Message::new_scalar(ConnectionManagerOpcode::Poll.to_usize().unwrap(), POLL_INTERVAL_MS, 0, 0, 0)).expect("couldn't kick off next poll"); loop { let msg = xous::receive_message(sid).unwrap(); @@ -40,13 +51,30 @@ pub(crate) fn connection_manager(sid: xous::SID, activity_interval: Arc POLL_INTERVAL_MS as u32 { log::info!("wlan activity interval timeout"); // if the pddb isn't mounted, don't even bother checking -- we can't connect until we have a place to get keys - if pddb.is_mounted() { + if pddb.is_mounted() && rev_ok { // the status check code is going to get refactored, so this is a "bare minimum" check let status = com.wlan_status().unwrap(); - if status.contains("down") { + let config = netmgr.get_ipv4_config(); + let needs_reconnect = + if status.link_state == com_rs_ref::LinkState::Connected { + if let Some(config) = config { // check that the EC's view of the world is synchronized with our view + // is it enough to just check that the address is the same? + if config.addr != status.ipv4.addr { + true + } else { + false + } + } else { + true + } + } else { + true + }; + if needs_reconnect { log::info!("wlan is not connected, attempting auto-reconnect to known AP list"); if let Ok(ap_list) = pddb.list_keys(AP_DICT_NAME, None) { com.wlan_leave().expect("couldn't issue leave command"); // leave the previous config to reset state + netmgr.reset(); // TODO: add an SSID scan phase, so we only try to connect to SSIDs that are currently visible. // for now, just try every single one as a brute force approach. for ap in ap_list { @@ -60,7 +88,7 @@ pub(crate) fn connection_manager(sid: xous::SID, activity_interval: Arc NetManager { + NetManager { + netconn: NetConn::new(&xous_names::XousNames::new().unwrap()).expect("can't connect to Net Server"), + } + } + pub fn get_ipv4_config(&self) -> Option { + let storage = Some(Ipv4Conf::default().encode_u16()); + let mut buf = Buffer::into_buf(storage).expect("Couldn't convert to memory structure"); + buf.lend_mut(self.netconn.conn(), Opcode::GetIpv4Config.to_u32().unwrap()).expect("Couldn't execute GetIpv4Config opcode"); + let maybe_config = buf.to_original().expect("couldn't restore config structure"); + if let Some(config) = maybe_config { + let ipv4 = Ipv4Conf::decode_u16(&config); + Some(ipv4) + } else { + None + } + } + pub fn reset(&self) { + send_message( + self.netconn.conn(), + Message::new_blocking_scalar(Opcode::Reset.to_usize().unwrap(), 0, 0, 0, 0), + ).expect("couldn't send reset"); + } +} \ No newline at end of file diff --git a/services/net/src/main.rs b/services/net/src/main.rs index fc74a81f6..20a8e4c26 100644 --- a/services/net/src/main.rs +++ b/services/net/src/main.rs @@ -950,6 +950,38 @@ fn xmain() -> ! { } } } + Some(Opcode::GetIpv4Config) => { + let mut buffer = unsafe { + Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) + }; + let ser = if let Some(config) = net_config { + Some(config.encode_u16()) + } else { + None + }; + buffer.replace(ser).expect("couldn't return config"); + }, + Some(Opcode::Reset) => { + net_config = None; + let neighbor_cache = NeighborCache::new(BTreeMap::new()); + let ip_addrs = [IpCidr::new(Ipv4Address::UNSPECIFIED.into(), 0)]; + let routes = Routes::new(BTreeMap::new()); + let device = device::NetPhy::new(&xns); + let medium = device.capabilities().medium; + let mut builder = InterfaceBuilder::new(device) + .ip_addrs(ip_addrs) + .routes(routes); + if medium == Medium::Ethernet { + builder = builder + .ethernet_addr(EthernetAddress::from_bytes(&[0; 6])) + .neighbor_cache(neighbor_cache); + } + iface = builder.finalize(); + iface.routes_mut().remove_default_ipv4_route(); + dns_allclear_hook.notify(); + // question: do we need to clear the UDP and ICMP states? + xous::return_scalar(msg.sender, 1).unwrap(); + } Some(Opcode::SuspendResume) => xous::msg_scalar_unpack!(msg, token, _, _, _, { // handle an suspend/resume state stuff here. right now, it's a NOP susres.suspend_until_resume(token).expect("couldn't execute suspend/resume"); diff --git a/services/shellchat/Cargo.toml b/services/shellchat/Cargo.toml index 0b2a58a0c..fbc59d1a1 100644 --- a/services/shellchat/Cargo.toml +++ b/services/shellchat/Cargo.toml @@ -45,6 +45,8 @@ rkyv = {version = "0.4.3", default-features = false, features = ["const_generics # for audio self-test analysis spectrum-analyzer = "0.5.2" +# used to parse net connectivity results +com_rs-ref = {path = "../../imports/com_rs-ref"} # for the curve25519 tests # hardware acceleration adaptations are inserted into a fork of the main branch. diff --git a/services/shellchat/src/cmds.rs b/services/shellchat/src/cmds.rs index 775d45607..c34d883e0 100644 --- a/services/shellchat/src/cmds.rs +++ b/services/shellchat/src/cmds.rs @@ -176,10 +176,13 @@ impl CmdEnv { log::info!("SoC DNA: 0x{:x}", common.llio.soc_dna().unwrap()); let (rev, dirty) = common.com.get_ec_git_rev().unwrap(); let dirtystr = if dirty { "dirty" } else { "clean" }; - log::info!("EC git commit: {:x}, {}", rev, dirtystr); + log::info!("EC gateware git commit: {:x}, {}", rev, dirtystr); + let (maj, min, rev, commit) = common.com.get_ec_sw_tag().unwrap(); + log::info!("EC sw tag: {}.{}.{}+{}", maj, min, rev, commit); let (maj, min, rev) = common.com.get_wf200_fw_rev().unwrap(); log::info!("WF200 fw rev {}.{}.{}", maj, min, rev); + CmdEnv { common_env: common, lastverb: String::<256>::new(), diff --git a/services/shellchat/src/cmds/ssid.rs b/services/shellchat/src/cmds/ssid.rs index 069f302b1..924bb75d4 100644 --- a/services/shellchat/src/cmds/ssid.rs +++ b/services/shellchat/src/cmds/ssid.rs @@ -4,49 +4,23 @@ use com::Com; use ticktimer_server::Ticktimer; use core::fmt::Write; - use xous::{Message, ScalarMessage, MessageEnvelope}; -use core::sync::atomic::{AtomicBool, Ordering}; -static CB_RUN: AtomicBool = AtomicBool::new(false); -pub fn callback_thread() { - let ticktimer = Ticktimer::new().expect("Couldn't connect to Ticktimer"); - let xns = xous_names::XousNames::new().unwrap(); - let callback_conn = xns.request_connection_blocking(crate::SERVER_NAME_SHELLCHAT).unwrap(); - let com = Com::new(&xns).unwrap(); +use num_traits::*; - let mut iters = 0; // count how long we've been waiting - loop { - if CB_RUN.load(Ordering::Relaxed) { - log::trace!("checking ssid status"); - if com.ssid_scan_updated().unwrap() { - log::trace!("initiating callback check"); - // just send a bogus message - xous::send_message(callback_conn, Message::Scalar(ScalarMessage{ - id: 0xdeadbeef, arg1: 0, arg2: 0, arg3: 0, arg4: 0, - })).unwrap(); - CB_RUN.store(false, Ordering::Relaxed); - } else { - iters += 1; - if iters > 11 { // should have gotten a result within 20 seconds... - // there may have been stale data in the scan cache, clear it - let _ = com.ssid_fetch_as_string().unwrap(); - } - } - ticktimer.sleep_ms(2_000).unwrap(); - } else { - ticktimer.sleep_ms(1_000).unwrap(); - iters = 0; - } - } +#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)] +enum ScanResult { + Ok, + Timeout, } #[derive(Debug)] pub struct Ssid { + cb_id: Option, } impl Ssid { pub fn new() -> Ssid { - xous::create_thread_0(callback_thread).expect("couldn't create callback generator thread"); Ssid { + cb_id: None, } } } @@ -58,12 +32,42 @@ impl<'a> ShellCmdApi<'a> for Ssid { let helpstring = "ssid [scan]"; let mut tokens = args.as_str().unwrap().split(' '); + if self.cb_id.is_none() { + self.cb_id = Some( + env.register_handler(String::<256>::from_str(self.verb())) + ); + } if let Some(sub_cmd) = tokens.next() { match sub_cmd { "scan" => { env.com.set_ssid_scanning(true).expect("couldn't turn on SSID scanning"); - CB_RUN.store(true, Ordering::Relaxed); + let _ = std::thread::spawn({ + let cb_id = self.cb_id.expect("should have been initialized by this point"); + move || { + let ticktimer = Ticktimer::new().expect("Couldn't connect to Ticktimer"); + let xns = xous_names::XousNames::new().unwrap(); + let callback_conn = xns.request_connection_blocking(crate::SERVER_NAME_SHELLCHAT).unwrap(); + let com = Com::new(&xns).unwrap(); + let mut responded = false; + for _ in 0..15 { + if com.ssid_scan_updated().unwrap() { + // just send a bogus message + xous::send_message(callback_conn, Message::Scalar(ScalarMessage{ + id: cb_id as usize, arg1: ScanResult::Ok.to_usize().unwrap(), arg2: 0, arg3: 0, arg4: 0, + })).unwrap(); + responded = true; + break; + } + ticktimer.sleep_ms(2_000).unwrap(); + } + if !responded { + xous::send_message(callback_conn, Message::Scalar(ScalarMessage{ + id: cb_id as usize, arg1: ScanResult::Timeout.to_usize().unwrap(), arg2: 0, arg3: 0, arg4: 0, + })).unwrap(); + } + } + }); write!(ret, "SSID scan initiated, please wait...").unwrap(); } _ => { @@ -76,10 +80,27 @@ impl<'a> ShellCmdApi<'a> for Ssid { Ok(Some(ret)) } - fn callback(&mut self, _msg: &MessageEnvelope, env: &mut CommonEnv) -> Result>, xous::Error> { + fn callback(&mut self, msg: &MessageEnvelope, env: &mut CommonEnv) -> Result>, xous::Error> { let mut ret = String::<1024>::new(); log::trace!("fetching SSID"); - write!(ret, "{}", env.com.ssid_fetch_as_string().unwrap()).unwrap(); + xous::msg_scalar_unpack!(msg, arg1, _arg2, _arg3, _arg4, { + match FromPrimitive::from_usize(arg1) { + Some(ScanResult::Ok) => { + let ssid_list = env.com.ssid_fetch_as_list().unwrap(); + write!(ret, "RSSI in dBm:\n").unwrap(); + for (rssi, name) in ssid_list { + if name.len() > 0 { + write!(ret, "-{} {}\n", rssi, &name).unwrap(); + } + } + } + Some(ScanResult::Timeout) => { + write!(ret, "SSID scan timed out").unwrap(); + } + _ => log::error!("Unknown callback received by ssid scan") + } + + }); Ok(Some(ret)) } } diff --git a/services/shellchat/src/cmds/test.rs b/services/shellchat/src/cmds/test.rs index 6264aa736..9de4977ed 100644 --- a/services/shellchat/src/cmds/test.rs +++ b/services/shellchat/src/cmds/test.rs @@ -467,17 +467,26 @@ impl<'a> ShellCmdApi<'a> for Test { loop { match oqc_status(oqc_cid) { Some(true) => { - let ssid_str = env.com.ssid_fetch_as_string().unwrap(); - use std::str::FromStr; - let ssid = std::string::String::from_str(ssid_str.as_str().unwrap()).unwrap(); - let ssid_short = ssid.replace(".", ""); - let mut lines = ssid_short.lines(); - let _ = lines.next(); // skip the banner - write!(ret, "SSID {}\nCHECK: was backlight on?\ndid keyboard vibrate?\nwas there sound?\n", - lines.next().unwrap() // just the first SSID result + log::info!("wrapping up: fetching SSID list"); + let ssid_str = env.com.ssid_fetch_as_list().unwrap(); + let mut min = 255u8; + let mut min_index = 0; + for (index, (rssi, name)) in ssid_str.iter().enumerate() { + if name.len() > 0 { + if *rssi < min { + min = *rssi; + min_index = index; + } + } + } + let (rssi, name) = &ssid_str[min_index]; + log::info!("strongest AP: -{}dBm, {}", *rssi, name); + write!(ret, "SSID (-{}):{}\nCHECK: was backlight on?\ndid keyboard vibrate?\nwas there sound?\n", + *rssi, name // just the first SSID result ).unwrap(); let (maj, min, rev, extra, gitrev) = env.llio.soc_gitrev().unwrap(); write!(ret, "Version {}.{}.{}+{}, commit {:x}\n", maj, min, rev, extra, gitrev).unwrap(); + log::info!("finished status update"); break; } Some(false) => { @@ -493,42 +502,31 @@ impl<'a> ShellCmdApi<'a> for Test { let mut net_up = false; let mut dhcp_ok = false; let mut ssid_ok = false; - let mut rssi_pass = false; let mut wifi_tries = 0; loop { // parse and see if we connected from the first attempt (called before this loop) - if let Ok(msg) = env.com.wlan_status() { - let mut elements = msg.as_str().split(' '); - rssi_pass = if let Some(_rssi_str) = elements.next() { - //rssi_str.parse::().unwrap() < -10 - // for now always pass, don't use RSSI as it's not reliable - true - } else { - false - }; - net_up = if let Some(up_str) = elements.next() { - up_str == "up" - } else { - false - }; - dhcp_ok = if let Some(dhcp_str) = elements.next() { - dhcp_str == "dhcpBound" - } else { - false - }; - ssid_ok = if let Some(ssid_str) = elements.next() { - ssid_str == "\nprecursortest" + log::info!("polling WLAN status"); + if let Ok(status) = env.com.wlan_status() { + log::info!("got status: {:?}", status); + net_up = status.link_state == com_rs_ref::LinkState::Connected; + dhcp_ok = status.ipv4.dhcp == com_rs_ref::DhcpState::Bound; + ssid_ok = if let Some(ssid) = status.ssid { + log::info!("got ssid: {}", ssid.name.as_str().unwrap_or("invalid")); + ssid.name.as_str().unwrap_or("invalid") == "precursortest" } else { false }; // if connected, break - if rssi_pass && net_up && dhcp_ok && ssid_ok { - write!(ret, "WLAN OK: {}\n", msg.as_str()).unwrap(); + if net_up && dhcp_ok && ssid_ok { + log::info!("WLAN is OK"); + write!(ret, "WLAN OK\n").unwrap(); break; } else { - write!(ret, "WLAN TRY: {}", msg.as_str()).unwrap(); + log::info!("WLAN is TRY"); + write!(ret, "WLAN TRY\n").unwrap(); } } else { + log::info!("WLAN couldn't get status"); write!(ret, "WLAN TRY: Couldn't get status!\n").unwrap(); } if wifi_tries < 3 { @@ -542,16 +540,16 @@ impl<'a> ShellCmdApi<'a> for Test { env.com.wlan_join().unwrap(); env.ticktimer.sleep_ms(8000).unwrap(); } else { - if !rssi_pass { - write!(ret, "WLAN FAIL: rssi weak\n").unwrap(); - } if !net_up { + log::info!("connection failed"); write!(ret, "WLAN FAIL: connection failed\n").unwrap(); } if !dhcp_ok { + log::info!("dhcp failed"); write!(ret, "WLAN FAIL: dhcp fail\n").unwrap(); } if !ssid_ok { + log::info!("ssid mismatch"); write!(ret, "WLAN FAIL: ssid mismatch\n").unwrap(); } return Ok(Some(ret)); diff --git a/services/shellchat/src/cmds/ver.rs b/services/shellchat/src/cmds/ver.rs index 3336ea71d..723b135ad 100644 --- a/services/shellchat/src/cmds/ver.rs +++ b/services/shellchat/src/cmds/ver.rs @@ -20,7 +20,10 @@ impl<'a> ShellCmdApi<'a> for Ver { "ec" => { let (rev, dirty) = env.com.get_ec_git_rev().unwrap(); let dirtystr = if dirty { "dirty" } else { "clean" }; - write!(ret, "EC git commit: {:x}, {}", rev, dirtystr).unwrap(); + write!(ret, "EC gateware commit: {:x}, {}\n", rev, dirtystr).unwrap(); + let (maj, min, rev, commit) = env.com.get_ec_sw_tag().unwrap(); + log::info!("EC sw tag: {}.{}.{}+{}", maj, min, rev, commit); + write!(ret, "EC sw tag: {}.{}.{}+{}", maj, min, rev, commit).unwrap(); } "wf200" => { let (maj, min, rev) = env.com.get_wf200_fw_rev().unwrap(); diff --git a/services/shellchat/src/cmds/wlan.rs b/services/shellchat/src/cmds/wlan.rs index 9bea64405..d2e9abd9f 100644 --- a/services/shellchat/src/cmds/wlan.rs +++ b/services/shellchat/src/cmds/wlan.rs @@ -128,10 +128,14 @@ impl<'a> ShellCmdApi<'a> for Wlan { } "status" => { let _ = match env.com.wlan_status() { - Ok(msg) => write!(ret, "{}", msg), + Ok(msg) => write!(ret, "{:?}", msg), Err(e) => write!(ret, "Error: {:?}", e), }; } + "debug" => { + let debug = env.com.wlan_debug().expect("couldn't issue debug command"); + write!(ret, "{:x?}", debug).unwrap(); + } _ => { show_help = true; } diff --git a/services/status/locales/i18n.json b/services/status/locales/i18n.json index 0304a1fd4..3c5ba7f81 100644 --- a/services/status/locales/i18n.json +++ b/services/status/locales/i18n.json @@ -64,6 +64,11 @@ "zh": "设置时间", "en-audio": "Set time" }, + "mainmenu.reboot": { + "en": "Reboot", + "zh": "重启", + "en-audio": "Reboot" + }, "mainmenu.closemenu": { "en": "Close menu", "zh": "关闭功能表", diff --git a/services/status/src/main.rs b/services/status/src/main.rs index f5fecf935..98729081b 100644 --- a/services/status/src/main.rs +++ b/services/status/src/main.rs @@ -41,6 +41,8 @@ enum StatusOpcode { Pump, /// Pulls up the time setting UI UxSetTime, + /// Initiates a reboot + Reboot, Quit, } @@ -141,6 +143,7 @@ fn xmain() -> ! { let gam = gam::Gam::new(&xns).expect("|status: can't connect to GAM"); let ticktimer = ticktimer_server::Ticktimer::new().expect("Couldn't connect to Ticktimer"); let mut com = com::Com::new(&xns).expect("|status: can't connect to COM"); + let susres = susres::Susres::new_without_hook(&xns).unwrap(); log::trace!("|status: getting screen size"); let screensize = gam @@ -597,6 +600,25 @@ fn xmain() -> ! { rtc.set_rtc(dt).expect("couldn't set the current time"); pump_run.store(true, Ordering::Relaxed); // stop status updates while we do this }), + Some(StatusOpcode::Reboot) => { + if ((llio.adc_vbus().unwrap() as f64) * 0.005033) > 1.5 { + // power plugged in, do a reboot using a warm boot method + susres.reboot(true).expect("couldn't issue reboot command"); + } else { + // ensure the self-boosting facility is turned off, this interferes with a cold boot + com.set_boost(false).ok(); + llio.boost_on(false).ok(); + // do a full cold-boot if the power is cut. This will force a re-load of the SoC contents. + gam.shipmode_blank_request().ok(); + ticktimer.sleep_ms(500).ok(); // screen redraw time after the blank request + rtc.set_wakeup_alarm(4).expect("couldn't set wakeup alarm"); + llio.allow_ec_snoop(true).ok(); + llio.allow_power_off(true).ok(); + com.power_off_soc().ok(); + ticktimer.sleep_ms(4000).ok(); + panic!("system did not reboot"); + } + } Some(StatusOpcode::Quit) => { break; } diff --git a/services/status/src/mainmenu.rs b/services/status/src/mainmenu.rs index 8855af941..7931fb504 100644 --- a/services/status/src/mainmenu.rs +++ b/services/status/src/mainmenu.rs @@ -84,6 +84,15 @@ pub fn main_menu_thread(keys: Arc>, status_sid: xous::SID) { }; menu.add_item(setrtc_item); + let reboot_item = MenuItem { + name: String::<64>::from_str(t!("mainmenu.reboot", xous::LANG)), + action_conn: status_conn, + action_opcode: StatusOpcode::Reboot.to_u32().unwrap(), + action_payload: MenuPayload::Scalar([0, 0, 0, 0]), + close_on_select: true, + }; + menu.add_item(reboot_item); + let close_item = MenuItem { name: String::<64>::from_str(t!("mainmenu.closemenu", xous::LANG)), action_conn: menu.gam.conn(), diff --git a/services/susres/src/lib.rs b/services/susres/src/lib.rs index b0e613739..a1c6169e0 100644 --- a/services/susres/src/lib.rs +++ b/services/susres/src/lib.rs @@ -115,6 +115,23 @@ impl Susres { } } + /// Passing `true` causes the whole SOC including peripherals to receive a reset signal + /// `false` causes only the CPU to reboot, while the peripherals retain state. Generally you want `true`. + pub fn reboot(&self, whole_soc: bool) -> Result<(), xous::Error> { + send_message(self.conn, + Message::new_scalar(Opcode::RebootRequest.to_usize().unwrap(), 0, 0, 0, 0) + ).map(|_|())?; + + if whole_soc { + send_message(self.conn, + Message::new_scalar(Opcode::RebootSocConfirm.to_usize().unwrap(), 0, 0, 0, 0) + ).map(|_|()) + } else { + send_message(self.conn, + Message::new_scalar(Opcode::RebootCpuConfirm.to_usize().unwrap(), 0, 0, 0, 0) + ).map(|_|()) + } + } } fn drop_conn(sid: xous::SID) { let cid = xous::connect(sid).unwrap();