mirror of
https://github.com/saymrwulf/xous-core.git
synced 2026-11-16 08:38:26 +00:00
Merge branch 'main' into qrcode
This commit is contained in:
commit
8c5c2228d2
12 changed files with 609 additions and 655 deletions
|
|
@ -10,8 +10,23 @@ impl I2cStateMachine {
|
|||
}
|
||||
pub fn suspend(&mut self) {}
|
||||
pub fn resume(&mut self) {}
|
||||
pub fn initiate(&mut self, _transaction: I2cTransaction) -> I2cStatus {
|
||||
I2cStatus::ResponseInProgress
|
||||
pub fn initiate(&mut self, mut msg: xous::MessageEnvelope) {
|
||||
let mut buffer = unsafe { xous_ipc::Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) };
|
||||
let transaction = buffer.to_original::<I2cTransaction, _>().unwrap();
|
||||
let response = if transaction.rxbuf.is_some() {
|
||||
I2cResult {
|
||||
rxbuf: [0u8; I2C_MAX_LEN],
|
||||
rxlen: transaction.rxbuf.unwrap().len() as u32,
|
||||
status: I2cStatus::ResponseReadOk,
|
||||
}
|
||||
} else {
|
||||
I2cResult {
|
||||
rxbuf: [0u8; I2C_MAX_LEN],
|
||||
rxlen: 0,
|
||||
status: I2cStatus::ResponseWriteOk,
|
||||
}
|
||||
};
|
||||
buffer.replace(response).unwrap();
|
||||
}
|
||||
pub fn report_write_done(&mut self) {
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,10 +27,6 @@ pub struct ManagedListItem {
|
|||
pub struct ManagedPromptWithTextResponse {
|
||||
pub token: [u32; 4],
|
||||
pub prompt: xous_ipc::String::<1024>,
|
||||
/// SID of a validator
|
||||
pub validator: Option<[u32; 4]>,
|
||||
/// the opcode to pass the validator
|
||||
pub validator_op: u32,
|
||||
}
|
||||
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)]
|
||||
pub struct ManagedNotification {
|
||||
|
|
@ -68,13 +64,16 @@ pub(crate) enum Opcode {
|
|||
PromptWithFixedResponse,
|
||||
/// ask a question, get multiple responses from a list of defined items (check box)
|
||||
PromptWithMultiResponse,
|
||||
/// ask a question, get a free-form answer back
|
||||
PromptWithTextResponse,
|
||||
/// simple notification
|
||||
Notification,
|
||||
/// dynamic notification - a simple non-interactive notification that allows its text to be dynamically updated
|
||||
DynamicNotification,
|
||||
|
||||
/// ask a question, get a free-form answer back
|
||||
PromptWithTextResponse,
|
||||
/// must be used by the PromptWithTextResponse caller to acknowledge correct input
|
||||
TextResponseValid,
|
||||
|
||||
// these are non-blocking calls
|
||||
/// add an item to the radio box or check box. Note that all added items
|
||||
/// are cleared after the relevant "action" call happens (PromptWith[Fixed,Multi]Response)
|
||||
|
|
@ -90,7 +89,31 @@ pub(crate) enum Opcode {
|
|||
/// close dynamic notification
|
||||
CloseDynamicNotification,
|
||||
|
||||
/// used by libraries to get the mutex on the server
|
||||
GetMutex,
|
||||
|
||||
// these are used internally by the modals to handle intermediate state. Do not call from the outside.
|
||||
// these were originally handled in a separate thread for deferred responses using busy-waits. They are
|
||||
// now handled with deferred responses with makes code less complicated and less load on the CPU but
|
||||
// it does expose some of the internal API mechanics to outside processes. This is fine for the modals
|
||||
// box because it's a convenience routine used by "everyone"; password boxes are always handled within
|
||||
// a given secured server so that the attack surface for these do not extend into the modals boundary.
|
||||
InitiateOp,
|
||||
DoUpdateProgress,
|
||||
FinishProgress,
|
||||
|
||||
TextEntryReturn,
|
||||
RadioReturn,
|
||||
CheckBoxReturn,
|
||||
NotificationReturn,
|
||||
|
||||
DoUpdateDynamicNotification,
|
||||
DoCloseDynamicNotification,
|
||||
|
||||
ModalRedraw,
|
||||
ModalKeypress,
|
||||
ModalDrop,
|
||||
Gutter,
|
||||
|
||||
Quit,
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,15 +4,15 @@ pub mod api;
|
|||
use api::*;
|
||||
|
||||
use gam::*;
|
||||
use xous::{CID, SID, send_message, Message};
|
||||
use num_traits::{ToPrimitive, FromPrimitive};
|
||||
use xous::{CID, send_message, Message};
|
||||
use num_traits::*;
|
||||
use xous_ipc::Buffer;
|
||||
use std::thread;
|
||||
use core::cell::Cell;
|
||||
|
||||
pub struct Modals {
|
||||
conn: CID,
|
||||
token: [u32; 4],
|
||||
tt: ticktimer_server::Ticktimer,
|
||||
have_lock: Cell::<bool>,
|
||||
}
|
||||
impl Modals {
|
||||
pub fn new(xns: &xous_names::XousNames) -> Result<Self, xous::Error> {
|
||||
|
|
@ -24,7 +24,7 @@ impl Modals {
|
|||
Ok(Modals {
|
||||
conn,
|
||||
token,
|
||||
tt: ticktimer_server::Ticktimer::new().unwrap(),
|
||||
have_lock: Cell::new(false),
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -34,55 +34,48 @@ impl Modals {
|
|||
maybe_validator_op: Option<u32>,
|
||||
) -> Result<TextEntryPayload, xous::Error> {
|
||||
self.lock();
|
||||
let validator = if let Some(validator) = maybe_validator {
|
||||
// create a one-time use server
|
||||
let validator_server = xous::create_server().unwrap();
|
||||
thread::spawn({
|
||||
let vsid = validator_server.to_array();
|
||||
move || {
|
||||
loop {
|
||||
let mut msg = xous::receive_message(SID::from_array(vsid)).unwrap();
|
||||
log::debug!("validator message: {:?}", msg);
|
||||
match FromPrimitive::from_usize(msg.body.id()) {
|
||||
Some(ValidationOp::Validate) => {
|
||||
let mut buffer = unsafe{Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap())};
|
||||
let validation = buffer.to_original::<Validation, _>().unwrap();
|
||||
let result = validator(validation.text, validation.opcode);
|
||||
buffer.replace(result).expect("couldn't place validation result");
|
||||
}
|
||||
Some(ValidationOp::Quit) => {
|
||||
// this is a blocking scalar, have to return a dummy value to unblock the caller
|
||||
xous::return_scalar(msg.sender, 0).unwrap();
|
||||
break;
|
||||
}
|
||||
_ => {
|
||||
log::error!("received unknown message: {:?}", msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
Some(validator_server.to_array())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let spec = ManagedPromptWithTextResponse {
|
||||
|
||||
let mut spec = ManagedPromptWithTextResponse {
|
||||
token: self.token,
|
||||
prompt: xous_ipc::String::from_str(prompt),
|
||||
validator,
|
||||
validator_op: maybe_validator_op.unwrap_or(0)
|
||||
};
|
||||
let mut buf = Buffer::into_buf(spec).or(Err(xous::Error::InternalError))?;
|
||||
buf.lend_mut(self.conn, Opcode::PromptWithTextResponse.to_u32().unwrap()).or(Err(xous::Error::InternalError))?;
|
||||
if let Some(server) = validator {
|
||||
let cid = xous::connect(SID::from_array(server)).unwrap();
|
||||
send_message(cid, Message::new_blocking_scalar(ValidationOp::Quit.to_usize().unwrap(), 0, 0, 0, 0)).unwrap();
|
||||
unsafe{xous::disconnect(cid).unwrap()}; // must disconnect before destroy to avoid the CID from hanging out in our outbound table which is limited to 32 entries
|
||||
xous::destroy_server(SID::from_array(server)).expect("couldn't destroy temporary server");
|
||||
}
|
||||
match buf.to_original::<TextEntryPayload, _>() {
|
||||
Ok(response) => Ok(response),
|
||||
_ => Err(xous::Error::InternalError)
|
||||
// question: do we want to add a retry limit?
|
||||
loop {
|
||||
let mut buf = Buffer::into_buf(spec).or(Err(xous::Error::InternalError))?;
|
||||
buf.lend_mut(self.conn, Opcode::PromptWithTextResponse.to_u32().unwrap()).or(Err(xous::Error::InternalError))?;
|
||||
match buf.to_original::<TextEntryPayload, _>() {
|
||||
Ok(response) => {
|
||||
if let Some(validator) = maybe_validator {
|
||||
if let Some(err_msg) = validator(response, maybe_validator_op.unwrap_or(0)) {
|
||||
spec.prompt.clear();
|
||||
spec.prompt.append(err_msg.as_str().unwrap_or("UTF-8 error")).ok();
|
||||
} else {
|
||||
send_message(self.conn,
|
||||
Message::new_blocking_scalar(Opcode::TextResponseValid.to_usize().unwrap(),
|
||||
self.token[0] as _, self.token[1] as _, self.token[2] as _, self.token[3] as _,
|
||||
)).expect("couldn't acknowledge text entry");
|
||||
self.unlock();
|
||||
return Ok(response)
|
||||
}
|
||||
} else {
|
||||
send_message(self.conn,
|
||||
Message::new_blocking_scalar(Opcode::TextResponseValid.to_usize().unwrap(),
|
||||
self.token[0] as _, self.token[1] as _, self.token[2] as _, self.token[3] as _,
|
||||
)).expect("couldn't acknowledge text entry");
|
||||
self.unlock();
|
||||
return Ok(response)
|
||||
}
|
||||
},
|
||||
_ => {
|
||||
// we send the valid response token even in this case because we want the modals server to move on and not get stuck on this error.
|
||||
send_message(self.conn,
|
||||
Message::new_blocking_scalar(Opcode::TextResponseValid.to_usize().unwrap(),
|
||||
self.token[0] as _, self.token[1] as _, self.token[2] as _, self.token[3] as _,
|
||||
)).expect("couldn't acknowledge text entry");
|
||||
self.unlock();
|
||||
return Err(xous::Error::InternalError);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -109,6 +102,7 @@ impl Modals {
|
|||
};
|
||||
let buf = Buffer::into_buf(spec).or(Err(xous::Error::InternalError))?;
|
||||
buf.lend(self.conn, Opcode::Notification.to_u32().unwrap()).or(Err(xous::Error::InternalError))?;
|
||||
self.unlock();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
@ -147,6 +141,7 @@ impl Modals {
|
|||
self.token[3] as usize,
|
||||
)
|
||||
).expect("couldn't stop progress");
|
||||
self.unlock();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
@ -170,6 +165,7 @@ impl Modals {
|
|||
let mut buf = Buffer::into_buf(spec).or(Err(xous::Error::InternalError))?;
|
||||
buf.lend_mut(self.conn, Opcode::PromptWithFixedResponse.to_u32().unwrap()).or(Err(xous::Error::InternalError))?;
|
||||
let itemname = buf.to_original::<ItemName, _>().unwrap();
|
||||
self.unlock();
|
||||
Ok(String::from(itemname.as_str()))
|
||||
}
|
||||
|
||||
|
|
@ -188,6 +184,7 @@ impl Modals {
|
|||
ret.push(String::from(item.as_str()));
|
||||
}
|
||||
}
|
||||
self.unlock();
|
||||
Ok(ret)
|
||||
}
|
||||
|
||||
|
|
@ -213,7 +210,6 @@ impl Modals {
|
|||
Ok(())
|
||||
}
|
||||
pub fn dynamic_notification_close(&self) -> Result<(), xous::Error> {
|
||||
self.lock();
|
||||
send_message(self.conn,
|
||||
Message::new_scalar(Opcode::CloseDynamicNotification.to_usize().unwrap(),
|
||||
self.token[0] as usize,
|
||||
|
|
@ -222,38 +218,35 @@ impl Modals {
|
|||
self.token[3] as usize,
|
||||
)
|
||||
).expect("couldn't stop progress");
|
||||
self.unlock();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// busy-wait until we have acquired a mutex on the Modals server
|
||||
/// Blocks until we have a lock on the modals server
|
||||
fn lock(&self) {
|
||||
while !self.try_get_mutex() {
|
||||
self.tt.sleep_ms(1000).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
fn try_get_mutex(&self) -> bool {
|
||||
match send_message(
|
||||
self.conn,
|
||||
Message::new_blocking_scalar(Opcode::GetMutex.to_usize().unwrap(),
|
||||
self.token[0] as usize,
|
||||
self.token[1] as usize,
|
||||
self.token[2] as usize,
|
||||
self.token[3] as usize,
|
||||
)).expect("couldn't send mutex acquisition message") {
|
||||
xous::Result::Scalar1(code) => {
|
||||
if code == 1 {
|
||||
true
|
||||
} else {
|
||||
false
|
||||
if !self.have_lock.get() {
|
||||
match send_message(
|
||||
self.conn,
|
||||
Message::new_blocking_scalar(Opcode::GetMutex.to_usize().unwrap(),
|
||||
self.token[0] as usize,
|
||||
self.token[1] as usize,
|
||||
self.token[2] as usize,
|
||||
self.token[3] as usize,
|
||||
)).expect("couldn't send mutex acquisition message") {
|
||||
xous::Result::Scalar1(code) => {
|
||||
if code != 1 {
|
||||
log::warn!("Unexpected return from lock acquisition.");
|
||||
}
|
||||
},
|
||||
_ => {
|
||||
log::error!("Internal error trying to acquire mutex");
|
||||
}
|
||||
},
|
||||
_ => {
|
||||
log::error!("Internal error trying to acquire mutex");
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
self.have_lock.set(true);
|
||||
}
|
||||
fn unlock(&self) {
|
||||
self.have_lock.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -38,7 +38,7 @@ pub(crate) fn spawn_test() {
|
|||
// The start and end items are deliberately structured to be not zero-indexed; the use of PDDB_LOC is just a
|
||||
// convenient global constant.
|
||||
modals.start_progress("Progress Quest", xous::PDDB_LOC, xous::PDDB_LOC + 64*1024*128, xous::PDDB_LOC).expect("couldn't raise progress bar");
|
||||
for i in (xous::PDDB_LOC..xous::PDDB_LOC + 64*1024*128).step_by(64*1024) {
|
||||
for i in (xous::PDDB_LOC..xous::PDDB_LOC + 64*1024*128).step_by(64*1024*16) {
|
||||
modals.update_progress(i).expect("couldn't update progress bar");
|
||||
tt.sleep_ms(100).unwrap();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -107,7 +107,7 @@ pub(crate) fn connection_manager(sid: xous::SID, activity_interval: Arc<AtomicU3
|
|||
move || {
|
||||
let tt = ticktimer_server::Ticktimer::new().unwrap();
|
||||
let pddb = pddb::Pddb::new();
|
||||
pddb.is_mounted_blocking(None);
|
||||
pddb.is_mounted_blocking();
|
||||
loop {
|
||||
let msg = xous::receive_message(sid).unwrap();
|
||||
match FromPrimitive::from_usize(msg.body.id()) {
|
||||
|
|
|
|||
|
|
@ -35,6 +35,11 @@ impl PddbMountPoller {
|
|||
let conn = xns.request_connection_blocking(api::SERVER_NAME_PDDB_POLLER).expect("can't connect to Pddb mount poller server");
|
||||
PddbMountPoller { conn }
|
||||
}
|
||||
/// This call is guaranteed to *never* block and return the instantaneous state of the PDDB, even if the server itself
|
||||
/// is currently busy processing other requests. This has to be done with a separate server from the main one, because
|
||||
/// the main server will block during the mount operations, as it owns the PDDB data objects and cannot concurrently process
|
||||
/// the mount check task while manipulating them. Instead, this routine queries a separate thread that shares an AtomicBool
|
||||
/// with the main thread that reports the mount state.
|
||||
pub fn is_mounted_nonblocking(&self) -> bool {
|
||||
match send_message(self.conn,
|
||||
Message::new_blocking_scalar(PollOp::Poll.to_usize().unwrap(), 0, 0, 0, 0)
|
||||
|
|
@ -82,7 +87,6 @@ pub struct Pddb {
|
|||
/// like this are probably OK.
|
||||
keys: Arc<Mutex<HashMap<ApiToken, Box<dyn Fn() + 'static + Send> >>>,
|
||||
trng: trng::Trng,
|
||||
tt: ticktimer_server::Ticktimer,
|
||||
}
|
||||
impl Pddb {
|
||||
pub fn new() -> Self {
|
||||
|
|
@ -122,30 +126,21 @@ impl Pddb {
|
|||
cb_handle: Some(handle),
|
||||
keys,
|
||||
trng: trng::Trng::new(&xns).unwrap(),
|
||||
tt: ticktimer_server::Ticktimer::new().unwrap(),
|
||||
}
|
||||
}
|
||||
pub fn is_mounted(&self) -> bool {
|
||||
let ret = send_message(self.conn, Message::new_blocking_scalar(
|
||||
Opcode::IsMounted.to_usize().unwrap(), 0, 0, 0, 0)).expect("couldn't execute IsMounted query");
|
||||
match ret {
|
||||
xous::Result::Scalar1(code) => {
|
||||
if code == 0 {false} else {true}
|
||||
},
|
||||
_ => panic!("Internal error"),
|
||||
}
|
||||
}
|
||||
/// This blocks until the PDDB is mounted by the end user. If `None` is specified for the poll_interval_ms,
|
||||
/// A random interval between 1 and 2 seconds is chosen for the poll wait time. Randomizing the waiting time
|
||||
/// helps to level out the task scheduler in the case that many threads are waiting on the PDDB simultaneously.
|
||||
pub fn is_mounted_blocking(&self, poll_interval_ms: Option<u32>) {
|
||||
let interval = if let Some(i) = poll_interval_ms {
|
||||
i
|
||||
} else {
|
||||
(self.trng.get_u32().unwrap() % 1000) + 1000
|
||||
};
|
||||
while !self.is_mounted() {
|
||||
self.tt.sleep_ms(interval as usize).unwrap();
|
||||
///
|
||||
/// This is typically the API call one would use to hold execution of a service until the PDDB is mounted.
|
||||
pub fn is_mounted_blocking(&self) {
|
||||
let ret = send_message(self.conn, Message::new_blocking_scalar(
|
||||
Opcode::IsMounted.to_usize().unwrap(), 0, 0, 0, 0)).expect("couldn't execute IsMounted query");
|
||||
match ret {
|
||||
xous::Result::Scalar1(_code) => {
|
||||
()
|
||||
},
|
||||
_ => panic!("Internal error"),
|
||||
}
|
||||
}
|
||||
pub fn try_mount(&self) -> bool {
|
||||
|
|
|
|||
|
|
@ -518,6 +518,9 @@ fn xmain() -> ! {
|
|||
// it is the only server capable of doing this.
|
||||
let time_resetter = xns.request_connection_blocking(crate::TIME_SERVER_PDDB).unwrap();
|
||||
|
||||
// track processes that want a notification of a mount event
|
||||
let mut mount_notifications = Vec::<xous::MessageSender>::new();
|
||||
|
||||
// register a suspend/resume listener
|
||||
let mut susres = susres::Susres::new(Some(susres::SuspendOrder::Early), &xns,
|
||||
Opcode::SuspendResume as u32, my_cid).expect("couldn't create suspend/resume object");
|
||||
|
|
@ -532,7 +535,7 @@ fn xmain() -> ! {
|
|||
if basis_cache.basis_count() > 0 { // if there's anything in the cache, we're mounted.
|
||||
xous::return_scalar(msg.sender, 1).expect("couldn't return scalar");
|
||||
} else {
|
||||
xous::return_scalar(msg.sender, 0).expect("couldn't return scalar");
|
||||
mount_notifications.push(msg.sender); // defer response until later
|
||||
}
|
||||
}),
|
||||
Some(Opcode::TryMount) => xous::msg_blocking_scalar_unpack!(msg, _, _, _, _, {
|
||||
|
|
@ -547,6 +550,10 @@ fn xmain() -> ! {
|
|||
PasswordState::Correct => {
|
||||
if try_mount_or_format(&modals, &mut pddb_os, &mut basis_cache, PasswordState::Correct, time_resetter) {
|
||||
is_mounted.store(true, Ordering::SeqCst);
|
||||
for requester in mount_notifications.drain(..) {
|
||||
xous::return_scalar(requester, 1).expect("couldn't return scalar");
|
||||
}
|
||||
assert!(mount_notifications.len() == 0, "apparently I don't understand what drain() does");
|
||||
xous::return_scalar(msg.sender, 1).expect("couldn't return scalar");
|
||||
} else {
|
||||
xous::return_scalar(msg.sender, 0).expect("couldn't return scalar");
|
||||
|
|
@ -555,6 +562,10 @@ fn xmain() -> ! {
|
|||
PasswordState::Uninit => {
|
||||
if try_mount_or_format(&modals, &mut pddb_os, &mut basis_cache, PasswordState::Uninit, time_resetter) {
|
||||
is_mounted.store(true, Ordering::SeqCst);
|
||||
for requester in mount_notifications.drain(..) {
|
||||
xous::return_scalar(requester, 1).expect("couldn't return scalar");
|
||||
}
|
||||
assert!(mount_notifications.len() == 0, "apparently I don't understand what drain() does");
|
||||
xous::return_scalar(msg.sender, 1).expect("couldn't return scalar");
|
||||
} else {
|
||||
xous::return_scalar(msg.sender, 0).expect("couldn't return scalar");
|
||||
|
|
|
|||
|
|
@ -30,7 +30,6 @@ use std::sync::atomic::{AtomicBool, Ordering};
|
|||
)]
|
||||
use std::thread;
|
||||
|
||||
const SERVER_NAME_STATUS: &str = "_Status bar manager_";
|
||||
const SERVER_NAME_STATUS_GID: &str = "_Status bar GID receiver_";
|
||||
|
||||
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]
|
||||
|
|
@ -138,10 +137,8 @@ fn xmain() -> ! {
|
|||
log::trace!("|status: my canvas {:?}", status_gid);
|
||||
|
||||
log::debug!("|status: registering GAM|status thread");
|
||||
// we have one connection, from the status main loop; but we make it with a local call, not using xns. so there's 0 in xns.
|
||||
let status_sid = xns
|
||||
.register_name(SERVER_NAME_STATUS, Some(0))
|
||||
.expect("|status: can't register server");
|
||||
|
||||
let status_sid = xous::create_server().unwrap(); // completely private to this crate
|
||||
// create a connection for callback hooks
|
||||
let cb_cid = xous::connect(status_sid).unwrap();
|
||||
unsafe { CB_TO_MAIN_CONN = Some(cb_cid) };
|
||||
|
|
|
|||
|
|
@ -4,7 +4,6 @@
|
|||
use utralib::generated::*;
|
||||
|
||||
pub(crate) const SERVER_NAME_SUSRES: &str = "_Suspend/resume manager_";
|
||||
pub(crate) const SERVER_NAME_EXEC_GATE: &str = "_Suspend/resume execution gate_";
|
||||
|
||||
/// Note: there must be at least one subscriber to the `Last` suspend order event, otherwise
|
||||
/// the logic will never terminate. There may be multiple `Last` subscribers, but the order at
|
||||
|
|
@ -61,6 +60,9 @@ pub(crate) enum Opcode {
|
|||
/// not tested - reboot address
|
||||
RebootVector, //(u32),
|
||||
|
||||
/// used by processes to indicate they are suspending now; this blocks until resume using the "execution gate"
|
||||
SuspendingNow,
|
||||
|
||||
/// exit the server
|
||||
Quit,
|
||||
}
|
||||
|
|
@ -79,11 +81,6 @@ pub(crate) enum SuspendEventCallback {
|
|||
Drop,
|
||||
}
|
||||
|
||||
#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)]
|
||||
pub(crate) enum ExecGateOpcode {
|
||||
SuspendingNow,
|
||||
Drop,
|
||||
}
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////
|
||||
/////////////////////////// suspend-resume hardware management primitives
|
||||
|
|
|
|||
|
|
@ -14,14 +14,12 @@ use num_traits::{ToPrimitive, FromPrimitive};
|
|||
pub struct Susres {
|
||||
conn: CID,
|
||||
suspend_cb_sid: Option<xous::SID>,
|
||||
execution_gate_conn: CID,
|
||||
}
|
||||
impl Susres {
|
||||
#[cfg(any(target_os = "none", target_os = "xous"))]
|
||||
pub fn new(order: Option<SuspendOrder>, xns: &xous_names::XousNames, cb_discriminant: u32, cid: CID) -> Result<Self, xous::Error> {
|
||||
REFCOUNT.fetch_add(1, Ordering::Relaxed);
|
||||
let conn = xns.request_connection_blocking(api::SERVER_NAME_SUSRES).expect("Can't connect to SUSRES");
|
||||
let execution_gate_conn = xns.request_connection_blocking(api::SERVER_NAME_EXEC_GATE).expect("Can't connect to the execution gate");
|
||||
|
||||
let sid = xous::create_server().unwrap();
|
||||
let sid_tuple = sid.to_u32();
|
||||
|
|
@ -39,7 +37,6 @@ impl Susres {
|
|||
Ok(Susres {
|
||||
conn,
|
||||
suspend_cb_sid: Some(sid),
|
||||
execution_gate_conn,
|
||||
})
|
||||
}
|
||||
// suspend/resume is not implemented in hosted mode, and will break if you try to do it.
|
||||
|
|
@ -53,7 +50,6 @@ impl Susres {
|
|||
Ok(Susres {
|
||||
conn: 0,
|
||||
suspend_cb_sid: None,
|
||||
execution_gate_conn: 0,
|
||||
})
|
||||
}
|
||||
pub fn conn(&self) -> CID { self.conn }
|
||||
|
|
@ -64,7 +60,6 @@ impl Susres {
|
|||
Ok(Susres {
|
||||
conn,
|
||||
suspend_cb_sid: None,
|
||||
execution_gate_conn: 0,
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -86,9 +81,12 @@ impl Susres {
|
|||
Message::new_scalar(Opcode::SuspendReady.to_usize().unwrap(), token, 0, 0, 0)
|
||||
).map(|_|())?;
|
||||
log::trace!("blocking until suspend");
|
||||
|
||||
// sometime between here and when this next message unblocks, the power went out...
|
||||
|
||||
// now block until we've resumed
|
||||
send_message(self.execution_gate_conn,
|
||||
Message::new_blocking_scalar(ExecGateOpcode::SuspendingNow.to_usize().unwrap(), 0, 0, 0, 0)
|
||||
send_message(self.conn,
|
||||
Message::new_blocking_scalar(Opcode::SuspendingNow.to_usize().unwrap(), 0, 0, 0, 0)
|
||||
).map(|_|())?;
|
||||
|
||||
let response = send_message(self.conn,
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@
|
|||
mod murmur3;
|
||||
|
||||
mod api;
|
||||
use api::{Opcode, ScalarHook, SuspendEventCallback, ExecGateOpcode};
|
||||
use api::{Opcode, ScalarHook, SuspendEventCallback};
|
||||
|
||||
use num_traits::{ToPrimitive, FromPrimitive};
|
||||
use xous_ipc::Buffer;
|
||||
|
|
@ -530,35 +530,6 @@ pub fn timeout_thread(sid0: usize, sid1: usize, sid2: usize, sid3: usize) {
|
|||
}
|
||||
|
||||
static SHOULD_RESUME: AtomicBool = AtomicBool::new(false);
|
||||
static RESUME_EXEC: AtomicBool = AtomicBool::new(false);
|
||||
pub fn execution_gate() {
|
||||
let xns = xous_names::XousNames::new().unwrap();
|
||||
let execgate_sid = xns.register_name(api::SERVER_NAME_EXEC_GATE, None).expect("can't register execution gate");
|
||||
log::trace!("execution_gate registered with NS -- {:?}", execgate_sid);
|
||||
|
||||
loop {
|
||||
let msg = xous::receive_message(execgate_sid).unwrap();
|
||||
match FromPrimitive::from_usize(msg.body.id()) {
|
||||
// the entire purpose of SupendingNow is to block the thread that sent the message, until we're ready to resume.
|
||||
Some(ExecGateOpcode::SuspendingNow) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
|
||||
println!("checking exec gate:");
|
||||
while !RESUME_EXEC.load(Ordering::Relaxed) {
|
||||
println!("execution gate active");
|
||||
xous::yield_slice();
|
||||
}
|
||||
println!("execution is ungated!");
|
||||
xous::return_scalar(msg.sender, 0).expect("couldn't return dummy message to unblock execution");
|
||||
}),
|
||||
Some(ExecGateOpcode::Drop) => {
|
||||
break;
|
||||
}
|
||||
None => {
|
||||
log::error!("received unknown opcode in execution_gate");
|
||||
}
|
||||
}
|
||||
}
|
||||
xous::destroy_server(execgate_sid).unwrap();
|
||||
}
|
||||
|
||||
#[xous::xous_main]
|
||||
fn xmain() -> ! {
|
||||
|
|
@ -578,9 +549,6 @@ fn xmain() -> ! {
|
|||
// so this is the only way to debug what's going on.
|
||||
println!("App UART debug printing is on!");
|
||||
|
||||
// start up the execution gate
|
||||
xous::create_thread_0(execution_gate).unwrap();
|
||||
|
||||
let xns = xous_names::XousNames::new().unwrap();
|
||||
// unlimited connections allowed
|
||||
let susres_sid = xns.register_name(api::SERVER_NAME_SUSRES, None).expect("can't register server");
|
||||
|
|
@ -603,6 +571,8 @@ fn xmain() -> ! {
|
|||
|
||||
let mut suspend_subscribers = Vec::<ScalarCallback>::new();
|
||||
let mut current_op_order = crate::api::SuspendOrder::Early;
|
||||
|
||||
let mut gated_pids = Vec::<xous::MessageSender>::new();
|
||||
loop {
|
||||
let msg = xous::receive_message(susres_sid).unwrap();
|
||||
if reboot_requested {
|
||||
|
|
@ -634,6 +604,16 @@ fn xmain() -> ! {
|
|||
let hookdata = buffer.to_original::<ScalarHook, _>().unwrap();
|
||||
do_hook(hookdata, &mut suspend_subscribers);
|
||||
},
|
||||
Some(Opcode::SuspendingNow) => {
|
||||
if !suspend_requested {
|
||||
// this is harmless, it means a process' execution gate came a bit later than expected, so just ignore and tell it to resume
|
||||
// the execution gate is only requested until *after* a process has checked in and said it is ready to suspend, anyways.
|
||||
log::warn!("exec gate message received late, ignoring");
|
||||
xous::return_scalar(msg.sender, 0).expect("couldn't return dummy message to unblock execution");
|
||||
} else {
|
||||
gated_pids.push(msg.sender);
|
||||
}
|
||||
},
|
||||
Some(Opcode::SuspendReady) => msg_scalar_unpack!(msg, token, _, _, _, {
|
||||
//log::trace!("suspendready with token {}", token);
|
||||
if !suspend_requested {
|
||||
|
|
@ -674,6 +654,11 @@ fn xmain() -> ! {
|
|||
timeout_pending = false;
|
||||
// susres_hw.debug_delay(500); // let the messages print
|
||||
susres_hw.do_suspend(false);
|
||||
|
||||
// ---- power turns off ----
|
||||
// ---- time passes while we are asleep ----
|
||||
// ---- omg power came back! ---
|
||||
|
||||
// when do_suspend() returns, it means we've resumed
|
||||
suspend_requested = false;
|
||||
log_server::resume(); // log server is a special case, in order to avoid circular dependencies
|
||||
|
|
@ -682,7 +667,9 @@ fn xmain() -> ! {
|
|||
}
|
||||
// this now allows all other threads to commence
|
||||
log::trace!("low-level resume done, restoring execution");
|
||||
RESUME_EXEC.store(true, Ordering::Relaxed);
|
||||
for pid in gated_pids.drain(..) {
|
||||
xous::return_scalar(pid, 0).expect("couldn't return dummy message to unblock execution");
|
||||
}
|
||||
susres_hw.restore_wfi();
|
||||
} else if all_ready {
|
||||
log::debug!("finished with {:?} going to next round", current_op_order);
|
||||
|
|
@ -716,7 +703,6 @@ fn xmain() -> ! {
|
|||
suspend_requested = true;
|
||||
// clear the resume gate
|
||||
SHOULD_RESUME.store(false, Ordering::Relaxed);
|
||||
RESUME_EXEC.store(false, Ordering::Relaxed);
|
||||
// clear the ready to suspend flag and failed to suspend flag
|
||||
for sub in suspend_subscribers.iter_mut() {
|
||||
sub.ready_to_suspend = false;
|
||||
|
|
@ -755,6 +741,11 @@ fn xmain() -> ! {
|
|||
// susres_hw.debug_delay(500); // let the messages print
|
||||
// force a suspend
|
||||
susres_hw.do_suspend(true);
|
||||
|
||||
// ---- power turns off ----
|
||||
// ---- time passes while we are asleep ----
|
||||
// ---- omg power came back! ---
|
||||
|
||||
// when do_suspend() returns, it means we've resumed
|
||||
suspend_requested = false;
|
||||
log_server::resume(); // log server is a special case, in order to avoid circular dependencies
|
||||
|
|
@ -763,7 +754,10 @@ fn xmain() -> ! {
|
|||
} else {
|
||||
log::error!("We forced a suspend, but the bootloader is claiming we did a clean suspend. Internal state may be inconsistent.");
|
||||
}
|
||||
RESUME_EXEC.store(true, Ordering::Relaxed);
|
||||
for pid in gated_pids.drain(..) {
|
||||
xous::return_scalar(pid, 0).expect("couldn't return dummy message to unblock execution");
|
||||
}
|
||||
susres_hw.restore_wfi();
|
||||
} else {
|
||||
log::trace!("clean suspend timeout received, ignoring");
|
||||
// this means we did a clean suspend, we've resumed, and the timeout came back after the resume
|
||||
|
|
|
|||
Loading…
Reference in a new issue