From 1b25f4c11d68e45ab5c83443cf7402af57848f62 Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 6 Apr 2022 13:38:44 +0800 Subject: [PATCH 1/8] fix hosted mode --- services/llio/src/i2c/hosted.rs | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/services/llio/src/i2c/hosted.rs b/services/llio/src/i2c/hosted.rs index 3e5e28fbc..8ac8da341 100644 --- a/services/llio/src/i2c/hosted.rs +++ b/services/llio/src/i2c/hosted.rs @@ -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::().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) { } From b75df1efb33aa96ceffca924ee8a9f5f485e9cab Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 6 Apr 2022 23:46:39 +0800 Subject: [PATCH 2/8] annotate rationale on multiple variants of pddb mount calls --- services/pddb/src/lib.rs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/services/pddb/src/lib.rs b/services/pddb/src/lib.rs index b8ff671a0..68727a258 100644 --- a/services/pddb/src/lib.rs +++ b/services/pddb/src/lib.rs @@ -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) @@ -125,7 +130,9 @@ impl Pddb { tt: ticktimer_server::Ticktimer::new().unwrap(), } } - pub fn is_mounted(&self) -> bool { + /// This call "sometimes blocks". It will block when the PDDB is busy performing other tasks, such as + /// mounting the PDDB, or requesting the user's password. + pub fn is_mounted_maybe_blocking(&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 { @@ -144,7 +151,7 @@ impl Pddb { } else { (self.trng.get_u32().unwrap() % 1000) + 1000 }; - while !self.is_mounted() { + while !self.is_mounted_maybe_blocking() { self.tt.sleep_ms(interval as usize).unwrap(); } } From 92c6a93147578eede4033df5a52f2a10525927a7 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 7 Apr 2022 00:04:25 +0800 Subject: [PATCH 3/8] eliminate yield loop on blocking mount poller --- services/net/src/connection_manager.rs | 2 +- services/pddb/src/lib.rs | 32 ++++++++------------------ services/pddb/src/main.rs | 13 ++++++++++- 3 files changed, 23 insertions(+), 24 deletions(-) diff --git a/services/net/src/connection_manager.rs b/services/net/src/connection_manager.rs index 9282264ee..a72932f78 100644 --- a/services/net/src/connection_manager.rs +++ b/services/net/src/connection_manager.rs @@ -107,7 +107,7 @@ pub(crate) fn connection_manager(sid: xous::SID, activity_interval: Arc >>>, trng: trng::Trng, - tt: ticktimer_server::Ticktimer, } impl Pddb { pub fn new() -> Self { @@ -127,32 +126,21 @@ impl Pddb { cb_handle: Some(handle), keys, trng: trng::Trng::new(&xns).unwrap(), - tt: ticktimer_server::Ticktimer::new().unwrap(), - } - } - /// This call "sometimes blocks". It will block when the PDDB is busy performing other tasks, such as - /// mounting the PDDB, or requesting the user's password. - pub fn is_mounted_maybe_blocking(&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) { - let interval = if let Some(i) = poll_interval_ms { - i - } else { - (self.trng.get_u32().unwrap() % 1000) + 1000 - }; - while !self.is_mounted_maybe_blocking() { - 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 { diff --git a/services/pddb/src/main.rs b/services/pddb/src/main.rs index d024ad322..bc9eeea69 100644 --- a/services/pddb/src/main.rs +++ b/services/pddb/src/main.rs @@ -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::::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"); From c36d0d4111ad7f5d393b19c6ce17a53f11c8ee72 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 7 Apr 2022 00:20:07 +0800 Subject: [PATCH 4/8] remove an unnecessary xns registration --- services/status/src/main.rs | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/services/status/src/main.rs b/services/status/src/main.rs index da10b378e..d6da4f6ce 100644 --- a/services/status/src/main.rs +++ b/services/status/src/main.rs @@ -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) }; From 1261d73451901d673a9e9b67221b59c6ab2304f1 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 7 Apr 2022 01:13:49 +0800 Subject: [PATCH 5/8] remove execution gate server and use deferred callback idiom instead reduces one connection on all PIDs that require suspend/resume callbacks; lightens kernel by about 16k runtime load --- services/susres/src/api.rs | 9 ++--- services/susres/src/lib.rs | 12 +++---- services/susres/src/main.rs | 66 +++++++++++++++++-------------------- 3 files changed, 38 insertions(+), 49 deletions(-) diff --git a/services/susres/src/api.rs b/services/susres/src/api.rs index e4dbb825f..b44439120 100644 --- a/services/susres/src/api.rs +++ b/services/susres/src/api.rs @@ -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 diff --git a/services/susres/src/lib.rs b/services/susres/src/lib.rs index 87a6c7b63..2c9423bee 100644 --- a/services/susres/src/lib.rs +++ b/services/susres/src/lib.rs @@ -14,14 +14,12 @@ use num_traits::{ToPrimitive, FromPrimitive}; pub struct Susres { conn: CID, suspend_cb_sid: Option, - execution_gate_conn: CID, } impl Susres { #[cfg(any(target_os = "none", target_os = "xous"))] pub fn new(order: Option, xns: &xous_names::XousNames, cb_discriminant: u32, cid: CID) -> Result { 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, diff --git a/services/susres/src/main.rs b/services/susres/src/main.rs index 978e29f2a..7ca5b6af5 100644 --- a/services/susres/src/main.rs +++ b/services/susres/src/main.rs @@ -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::::new(); let mut current_op_order = crate::api::SuspendOrder::Early; + + let mut gated_pids = Vec::::new(); loop { let msg = xous::receive_message(susres_sid).unwrap(); if reboot_requested { @@ -634,6 +604,16 @@ fn xmain() -> ! { let hookdata = buffer.to_original::().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 From 360e50a8bbcd95bbb47e1a8151c115b289c065b1 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 7 Apr 2022 02:19:37 +0800 Subject: [PATCH 6/8] refactor locking to use deferred responses --- services/modals/src/lib.rs | 18 +++--------------- services/modals/src/main.rs | 26 +++++++++++++++++++------- 2 files changed, 22 insertions(+), 22 deletions(-) diff --git a/services/modals/src/lib.rs b/services/modals/src/lib.rs index 325fc7e92..8d76229a5 100644 --- a/services/modals/src/lib.rs +++ b/services/modals/src/lib.rs @@ -12,7 +12,6 @@ use std::thread; pub struct Modals { conn: CID, token: [u32; 4], - tt: ticktimer_server::Ticktimer, } impl Modals { pub fn new(xns: &xous_names::XousNames) -> Result { @@ -24,7 +23,6 @@ impl Modals { Ok(Modals { conn, token, - tt: ticktimer_server::Ticktimer::new().unwrap(), }) } @@ -211,14 +209,8 @@ impl Modals { 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(), @@ -228,18 +220,14 @@ impl Modals { self.token[3] as usize, )).expect("couldn't send mutex acquisition message") { xous::Result::Scalar1(code) => { - if code == 1 { - true - } else { - false + if code != 1 { + log::warn!("Unexpected return from lock acquisition."); } }, _ => { log::error!("Internal error trying to acquire mutex"); - false } } - } } diff --git a/services/modals/src/main.rs b/services/modals/src/main.rs index fc0e3796b..01860692a 100644 --- a/services/modals/src/main.rs +++ b/services/modals/src/main.rs @@ -435,6 +435,8 @@ fn xmain() -> ! { let default_nonce = [ trng.get_u32().unwrap(), trng.get_u32().unwrap(), trng.get_u32().unwrap(), trng.get_u32().unwrap(), ]; + let mut work_queue = Vec::<(xous::MessageSender, [u32; 4])>::new(); + loop { let mut msg = xous::receive_message(modals_sid).unwrap(); log::debug!("message: {:?}", msg); @@ -445,7 +447,7 @@ fn xmain() -> ! { if token == incoming_token { xous::return_scalar(msg.sender, 1).unwrap(); } else { - xous::return_scalar(msg.sender, 0).unwrap(); + work_queue.push((msg.sender, incoming_token)); } } else { token_lock = Some(incoming_token); @@ -470,7 +472,7 @@ fn xmain() -> ! { RendererState::RunRadio(_) => (), RendererState::ResponseRadio(item) => { buffer.replace(item).unwrap(); - token_lock = None; + token_lock = next_lock(&mut work_queue); break; }, _ => { @@ -499,7 +501,7 @@ fn xmain() -> ! { RendererState::RunCheckBox(_) => (), RendererState::ResponseCheckBox(items) => { buffer.replace(items).unwrap(); - token_lock = None; + token_lock = next_lock(&mut work_queue); break; }, _ => { @@ -528,7 +530,7 @@ fn xmain() -> ! { RendererState::RunText(_) => (), RendererState::ResponseText(text) => { buffer.replace(text).unwrap(); - token_lock = None; + token_lock = next_lock(&mut work_queue); break; }, _ => { @@ -554,7 +556,7 @@ fn xmain() -> ! { loop { match *op.lock().unwrap() { RendererState::RunNotification(_) => (), - RendererState::None => {token_lock = None; break}, + RendererState::None => {token_lock = next_lock(&mut work_queue); break}, _ => { log::error!("Illegal state transition in renderer"); panic!("Illegal state transition in renderer"); @@ -592,7 +594,7 @@ fn xmain() -> ! { renderer_cid, Message::new_scalar(RendererOp::FinishProgress.to_usize().unwrap(), 0, 0, 0, 0) ).expect("couldn't update progress bar"); - token_lock = None; + token_lock = next_lock(&mut work_queue); }), Some(Opcode::AddModalItem) => { let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; @@ -640,7 +642,7 @@ fn xmain() -> ! { renderer_cid, Message::new_scalar(RendererOp::CloseDynamicNotification.to_usize().unwrap(), 0, 0, 0, 0) ).expect("couldn't close dynamic notification"); - token_lock = None; + token_lock = next_lock(&mut work_queue); }), Some(Opcode::Quit) => { log::warn!("Shared modal UX handler exiting."); @@ -676,4 +678,14 @@ fn compute_checked_percentage(current: u32, start: u32, end: u32) -> u32 { (((current as u64 - start as u64) * 100) / (end as u64 - start as u64)) as u32 } } +} + +fn next_lock(work_queue: &mut Vec::<(xous::MessageSender, [u32; 4])>) -> Option<[u32; 4]> { + if work_queue.len() > 0 { + let (unblock_pid, token) = work_queue.remove(0); + xous::return_scalar(unblock_pid, 1).unwrap(); + Some(token) + } else { + None + } } \ No newline at end of file From f720f3175c14fae23e273f016d49b91784dce656 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 7 Apr 2022 04:04:37 +0800 Subject: [PATCH 7/8] refactor main loop to use deferred responses I think things could be compactified even further, but this is a first-step "merge the threads and break as few things as possible" pass. Would like to get @gsora's multi-line boxes merged into this new system before doing even more optimization. --- services/modals/src/api.rs | 24 + services/modals/src/lib.rs | 44 +- services/modals/src/main.rs | 918 ++++++++++++++++------------------- services/modals/src/tests.rs | 2 +- 4 files changed, 485 insertions(+), 503 deletions(-) diff --git a/services/modals/src/api.rs b/services/modals/src/api.rs index 3838b9d51..3e9f53759 100644 --- a/services/modals/src/api.rs +++ b/services/modals/src/api.rs @@ -89,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, } diff --git a/services/modals/src/lib.rs b/services/modals/src/lib.rs index 8d76229a5..648e62f4e 100644 --- a/services/modals/src/lib.rs +++ b/services/modals/src/lib.rs @@ -8,10 +8,12 @@ use xous::{CID, SID, send_message, Message}; use num_traits::{ToPrimitive, FromPrimitive}; use xous_ipc::Buffer; use std::thread; +use core::cell::Cell; pub struct Modals { conn: CID, token: [u32; 4], + have_lock: Cell::, } impl Modals { pub fn new(xns: &xous_names::XousNames) -> Result { @@ -23,6 +25,7 @@ impl Modals { Ok(Modals { conn, token, + have_lock: Cell::new(false), }) } @@ -78,6 +81,7 @@ impl Modals { 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"); } + self.unlock(); match buf.to_original::() { Ok(response) => Ok(response), _ => Err(xous::Error::InternalError) @@ -93,6 +97,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(()) } @@ -131,6 +136,7 @@ impl Modals { self.token[3] as usize, ) ).expect("couldn't stop progress"); + self.unlock(); Ok(()) } @@ -154,6 +160,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::().unwrap(); + self.unlock(); Ok(String::from(itemname.as_str())) } @@ -172,6 +179,7 @@ impl Modals { ret.push(String::from(item.as_str())); } } + self.unlock(); Ok(ret) } @@ -197,7 +205,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, @@ -206,28 +213,35 @@ impl Modals { self.token[3] as usize, ) ).expect("couldn't stop progress"); + self.unlock(); Ok(()) } /// Blocks until we have a lock on the modals server fn lock(&self) { - 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."); + 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"); } } + self.have_lock.set(true); + } + fn unlock(&self) { + self.have_lock.set(false); } } diff --git a/services/modals/src/main.rs b/services/modals/src/main.rs index 01860692a..ec791836a 100644 --- a/services/modals/src/main.rs +++ b/services/modals/src/main.rs @@ -10,9 +10,6 @@ use xous::SID; use xous::{msg_scalar_unpack, msg_blocking_scalar_unpack, send_message, Message}; use xous_ipc::Buffer; -use std::sync::{Arc, Mutex}; -use std::thread; - use gam::modal::*; #[cfg(feature="tts")] use tts_frontend::TtsFrontend; @@ -33,36 +30,9 @@ enum RendererState { RunText(ManagedPromptWithTextResponse), RunProgress(ManagedProgress), RunNotification(ManagedNotification), - /// response ready state - ResponseText(TextEntryPayload), - ResponseRadio(ItemName), - ResponseCheckBox(CheckBoxPayload), RunDynamicNotification(DynamicNotification), } -#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] -pub(crate) enum RendererOp { - InitiateOp, - UpdateProgress, - FinishProgress, - - TextEntryReturn, - RadioReturn, - CheckBoxReturn, - NotificationReturn, - - AddModalItem, - - UpdateDynamicNotification, - CloseDynamicNotification, - - ModalRedraw, - ModalKeypress, - ModalDrop, - Quit, - Gutter, -} - #[xous::xous_main] fn xmain() -> ! { log_server::init_wait().unwrap(); @@ -75,354 +45,58 @@ fn xmain() -> ! { let tt = ticktimer_server::Ticktimer::new().unwrap(); - let renderer_sid = xous::create_server().expect("couldn't create a server for the modal UX renderer"); - let renderer_cid = xous::connect(renderer_sid).expect("couldn't connect to the modal UX renderer"); + // we are our own renderer now that we implement deferred responses + let renderer_cid = xous::connect(modals_sid).expect("couldn't connect to the modal UX renderer"); #[cfg(feature="tts")] let tts = TtsFrontend::new(&xns).unwrap(); #[cfg(feature="tts")] let mut last_tick = tt.elapsed_ms(); - let op = Arc::new(Mutex::new(RendererState::None)); - // create a thread that just handles the redrawing requests - let _redraw_handle = thread::spawn({ - let op = Arc::clone(&op); - move || { - #[cfg(feature="tts")] - let tt = ticktimer_server::Ticktimer::new().unwrap(); - // build the core data structure here - let text_action = TextEntry { - is_password: false, - visibility: TextEntryVisibility::Visible, - action_conn: renderer_cid, - action_opcode: RendererOp::TextEntryReturn.to_u32().unwrap(), - action_payload: TextEntryPayload::new(), - validator: None, - }; - let mut fixed_items = Vec::::new(); - let notification = gam::modal::Notification::new( - renderer_cid, - RendererOp::NotificationReturn.to_u32().unwrap() - ); - let mut gutter = gam::modal::Notification::new( - renderer_cid, - RendererOp::Gutter.to_u32().unwrap() - ); - gutter.set_manual_dismiss(false); - let mut progress_action = Slider::new(renderer_cid, RendererOp::Gutter.to_u32().unwrap(), - 0, 100, 1, Some("%"), 0, true, true - ); - let mut last_percentage = 0; - let mut start_work: u32 = 0; - let mut end_work: u32 = 100; - let mut renderer_modal = - Modal::new( - gam::SHARED_MODAL_NAME, - ActionType::TextEntry(text_action), - Some("Placeholder"), - None, - GlyphStyle::Regular, - 8 - ); - renderer_modal.spawn_helper(renderer_sid, renderer_modal.sid, - RendererOp::ModalRedraw.to_u32().unwrap(), - RendererOp::ModalKeypress.to_u32().unwrap(), - RendererOp::ModalDrop.to_u32().unwrap(), - ); + // current opcode being processed by the modals server + let mut op = RendererState::None; + // the message for the deferred response + let mut dr: Option = None; - loop { - let msg = xous::receive_message(renderer_sid).unwrap(); - log::debug!("renderer message: {:?}", msg); - match FromPrimitive::from_usize(msg.body.id()) { - Some(RendererOp::InitiateOp) => { - log::debug!("InitiateOp called"); - let mutex_op = op.lock().unwrap(); - match *mutex_op { - RendererState::RunText(config) => { - log::debug!("initiating text entry modal"); - #[cfg(feature="tts")] - tts.tts_simple(config.prompt.as_str().unwrap()).unwrap(); - renderer_modal.modify( - Some(ActionType::TextEntry(text_action)), - Some(config.prompt.as_str().unwrap()), false, - None, true, None - ); - renderer_modal.activate(); - log::debug!("should be active!"); - }, - RendererState::RunNotification(config) => { - #[cfg(feature="tts")] - tts.tts_simple(config.message.as_str().unwrap()).unwrap(); - renderer_modal.modify( - Some(ActionType::Notification(notification)), - Some(config.message.as_str().unwrap()), false, - None, true, None - ); - renderer_modal.activate(); - }, - RendererState::RunProgress(config) => { - start_work = config.start_work; - end_work = config.end_work; - last_percentage = compute_checked_percentage( - config.current_work, start_work, end_work); - log::debug!("init percentage: {}, current: {}, start: {}, end: {}", last_percentage, config.current_work, start_work, end_work); - progress_action.set_state(last_percentage); - #[cfg(feature="tts")] - tts.tts_simple(config.title.as_str().unwrap()).unwrap(); - renderer_modal.modify( - Some(ActionType::Slider(progress_action)), - Some(config.title.as_str().unwrap()), false, - None, true, None - ); - renderer_modal.activate(); - }, - RendererState::RunRadio(config) => { - let mut radiobuttons = gam::modal::RadioButtons::new( - renderer_cid, - RendererOp::RadioReturn.to_u32().unwrap() - ); - for item in fixed_items.iter() { - radiobuttons.add_item(*item); - } - fixed_items.clear(); - #[cfg(feature="tts")] - { - tts.tts_blocking(t!("modals.radiobutton", xous::LANG)).unwrap(); - tts.tts_blocking(config.prompt.as_str().unwrap()).unwrap(); - } - renderer_modal.modify( - Some(ActionType::RadioButtons(radiobuttons)), - Some(config.prompt.as_str().unwrap()), false, - None, true, None - ); - renderer_modal.activate(); - }, - RendererState::RunCheckBox(config) => { - let mut checkbox = gam::modal::CheckBoxes::new( - renderer_cid, - RendererOp::CheckBoxReturn.to_u32().unwrap() - ); - for item in fixed_items.iter() { - checkbox.add_item(*item); - } - fixed_items.clear(); - #[cfg(feature="tts")] - { - tts.tts_blocking(t!("modals.checkbox", xous::LANG)).unwrap(); - tts.tts_blocking(config.prompt.as_str().unwrap()).unwrap(); - } - renderer_modal.modify( - Some(ActionType::CheckBoxes(checkbox)), - Some(config.prompt.as_str().unwrap()), false, - None, true, None - ); - renderer_modal.activate(); - }, - RendererState::RunDynamicNotification(config) => { - let mut top_text = String::new(); - if let Some(title) = config.title { - #[cfg(feature="tts")] - tts.tts_simple(title.as_str().unwrap()).unwrap(); - top_text.push_str(title.as_str().unwrap()); - } - let mut bot_text = String::new(); - if let Some(text) = config.text { - #[cfg(feature="tts")] - tts.tts_simple(text.as_str().unwrap()).unwrap(); - bot_text.push_str(text.as_str().unwrap()); - } - renderer_modal.modify( - Some(ActionType::Notification(gutter)), - Some(&top_text), config.title.is_none(), - Some(&bot_text), config.text.is_none(), - None - ); - renderer_modal.activate(); - }, - RendererState::None => { - log::error!("Operation initiated with no argument specified. Ignoring request."); - continue; - } - _ => { - log::warn!("unimplemented arm in renderer match"); - unimplemented!(); - } - } - }, - Some(RendererOp::UpdateProgress) => msg_scalar_unpack!(msg, current, _, _, _, { - let new_percentage = compute_checked_percentage( - current as u32, start_work, end_work); - log::trace!("percentage: {}, current: {}, start: {}, end: {}", new_percentage, current, start_work, end_work); - if new_percentage != last_percentage { - last_percentage = new_percentage; - progress_action.set_state(last_percentage); - #[cfg(feature="tts")] - { - if tt.elapsed_ms() - last_tick > TICK_INTERVAL { - tts.tts_blocking(t!("progress.increment", xous::LANG)).unwrap(); - last_tick = tt.elapsed_ms(); - } - } - renderer_modal.modify( - Some(ActionType::Slider(progress_action)), - None, false, - None, false, None - ); - renderer_modal.redraw(); - xous::yield_slice(); // give time for the GAM to redraw - } - }), - Some(RendererOp::FinishProgress) => { - renderer_modal.gam.relinquish_focus().unwrap(); - }, - Some(RendererOp::UpdateDynamicNotification) => { - let mutex_op = op.lock().unwrap(); - match *mutex_op { - RendererState::RunDynamicNotification(config) => { - let mut top_text = String::new(); - if let Some(title) = config.title { - top_text.push_str(title.as_str().unwrap()); - } - let mut bot_text = String::new(); - if let Some(text) = config.text { - bot_text.push_str(text.as_str().unwrap()); - } - renderer_modal.modify( - None, - Some(&top_text), config.title.is_none(), - Some(&bot_text), config.text.is_none(), - None - ); - renderer_modal.redraw(); - } - _ => { - log::error!("UX return opcode does not match our current operation in flight. This is a serious internal error."); - panic!("UX return opcode does not match our current operation in flight. This is a serious internal error."); - } - } - }, - Some(RendererOp::CloseDynamicNotification) => { - renderer_modal.gam.relinquish_focus().unwrap(); - }, - Some(RendererOp::TextEntryReturn) => { - let mut mutex_op = op.lock().unwrap(); - match *mutex_op { - RendererState::RunText(config) => { - log::trace!("validating text entry modal"); - let buf = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; - let text = buf.to_original::().unwrap(); - if let Some(validator_sid) = config.validator { - let cid = xous::connect(SID::from_array(validator_sid)).unwrap(); - let validation = Validation { - text, - opcode: config.validator_op, - }; - let mut buf = Buffer::into_buf(validation).expect("couldn't convert validator structure"); - buf.lend_mut(cid, ValidationOp::Validate.to_u32().unwrap()).expect("validation call failed"); - let response = buf.to_original::>, _>().expect("couldn't unpack validation response"); - unsafe{xous::disconnect(cid).unwrap();} - if let Some(err) = response { - // try again - renderer_modal.modify( - Some(ActionType::TextEntry(text_action)), - Some(config.prompt.as_str().unwrap()), false, - Some(err.as_str().unwrap()), false, None - ); - renderer_modal.activate(); - } else { - // the change in mutex_op enum type will signal the state change to the caller - *mutex_op = RendererState::ResponseText(text); - } - } else { - *mutex_op = RendererState::ResponseText(text); - } - } - RendererState::None => log::warn!("Text entry detected a fat finger event, ignoring."), - _ => { - log::error!("UX return opcode does not match our current operation in flight. This is a serious internal error."); - panic!("UX return opcode does not match our current operation in flight. This is a serious internal error."); - } - } - } - Some(RendererOp::NotificationReturn) => { - let mut mutex_op = op.lock().unwrap(); - match *mutex_op { - RendererState::RunNotification(_) => *mutex_op = RendererState::None, - RendererState::None => log::warn!("Notification detected a fat finger event, ignoring."), - _ => { - log::error!("UX return opcode does not match our current operation in flight: {:?}", mutex_op); - panic!("UX return opcode does not match our current operation in flight. This is a serious internal error."); - } - } - }, - Some(RendererOp::Gutter) => { - log::info!("gutter op, doing nothing"); - }, - Some(RendererOp::AddModalItem) => { - let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; - let item = buffer.to_original::().unwrap(); - fixed_items.push(item); - } - Some(RendererOp::RadioReturn) => { - let mut mutex_op = op.lock().unwrap(); - match *mutex_op { - RendererState::RunRadio(_config) => { - let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; - let item = buffer.to_original::().unwrap(); - *mutex_op = RendererState::ResponseRadio(item.0); - } - RendererState::ResponseRadio(_) => log::warn!("Radio buttons detected a fat finger event, ignoring."), - RendererState::None => log::warn!("Radio buttons detected a fat finger event, ignoring."), - _ => { - log::error!("UX return opcode does not match our current operation in flight. This is a serious internal error."); - panic!("UX return opcode does not match our current operation in flight. This is a serious internal error."); - } - } - } - Some(RendererOp::CheckBoxReturn) => { - let mut mutex_op = op.lock().unwrap(); - match *mutex_op { - RendererState::RunCheckBox(_config) => { - let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; - let item = buffer.to_original::().unwrap(); - *mutex_op = RendererState::ResponseCheckBox(item); - } - RendererState::ResponseCheckBox(_) => log::warn!("Check boxes detected a fat finger event, ignoring."), - RendererState::None => log::warn!("Check boxes detected a fat finger event, ignoring."), - _ => { - log::error!("UX return opcode does not match our current operation in flight. This is a serious internal error."); - panic!("UX return opcode does not match our current operation in flight. This is a serious internal error."); - } - } - } - Some(RendererOp::ModalRedraw) => { - renderer_modal.redraw(); - }, - Some(RendererOp::ModalKeypress) => msg_scalar_unpack!(msg, k1, k2, k3, k4, { - let keys = [ - if let Some(a) = core::char::from_u32(k1 as u32) {a} else {'\u{0000}'}, - if let Some(a) = core::char::from_u32(k2 as u32) {a} else {'\u{0000}'}, - if let Some(a) = core::char::from_u32(k3 as u32) {a} else {'\u{0000}'}, - if let Some(a) = core::char::from_u32(k4 as u32) {a} else {'\u{0000}'}, - ]; - renderer_modal.key_event(keys); - }), - Some(RendererOp::ModalDrop) => { // this guy should never quit, it's a core OS service - panic!("Password modal for PDDB quit unexpectedly"); - }, - Some(RendererOp::Quit) => { - log::warn!("received quit on PDDB password UX renderer loop"); - xous::return_scalar(msg.sender, 0).unwrap(); - break; - }, - None => { - log::error!("Couldn't convert opcode: {:?}", msg); - } - } - } - xous::destroy_server(renderer_sid).unwrap(); - } - }); + // build the core data structure here + let text_action = TextEntry { + is_password: false, + visibility: TextEntryVisibility::Visible, + action_conn: renderer_cid, + action_opcode: Opcode::TextEntryReturn.to_u32().unwrap(), + action_payload: TextEntryPayload::new(), + validator: None, + }; + let mut fixed_items = Vec::::new(); + let notification = gam::modal::Notification::new( + renderer_cid, + Opcode::NotificationReturn.to_u32().unwrap() + ); + let mut gutter = gam::modal::Notification::new( + renderer_cid, + Opcode::Gutter.to_u32().unwrap() + ); + gutter.set_manual_dismiss(false); + let mut progress_action = Slider::new(renderer_cid, Opcode::Gutter.to_u32().unwrap(), + 0, 100, 1, Some("%"), 0, true, true + ); + let mut last_percentage = 0; + let mut start_work: u32 = 0; + let mut end_work: u32 = 100; + let mut renderer_modal = + Modal::new( + gam::SHARED_MODAL_NAME, + ActionType::TextEntry(text_action), + Some("Placeholder"), + None, + GlyphStyle::Regular, + 8 + ); + renderer_modal.spawn_helper(modals_sid, renderer_modal.sid, + Opcode::ModalRedraw.to_u32().unwrap(), + Opcode::ModalKeypress.to_u32().unwrap(), + Opcode::ModalDrop.to_u32().unwrap(), + ); if cfg!(feature = "ux_tests") { tt.sleep_ms(1000).unwrap(); @@ -441,147 +115,105 @@ fn xmain() -> ! { let mut msg = xous::receive_message(modals_sid).unwrap(); log::debug!("message: {:?}", msg); match FromPrimitive::from_usize(msg.body.id()) { + // ------------------ EXTERNAL APIS -------------------- Some(Opcode::GetMutex) => msg_blocking_scalar_unpack!(msg, t0, t1, t2, t3, { let incoming_token = [t0 as u32, t1 as u32, t2 as u32, t3 as u32]; - if let Some(token) = token_lock { - if token == incoming_token { - xous::return_scalar(msg.sender, 1).unwrap(); - } else { - work_queue.push((msg.sender, incoming_token)); - } - } else { + if token_lock.is_none() { token_lock = Some(incoming_token); xous::return_scalar(msg.sender, 1).unwrap(); + } else { + work_queue.push((msg.sender, incoming_token)); } }), Some(Opcode::PromptWithFixedResponse) => { - let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; - let spec = buffer.to_original::().unwrap(); - if spec.token != token_lock.unwrap_or(default_nonce) { - log::warn!("Attempt to access modals without a mutex lock. Ignoring."); - buffer.replace(ItemName::new("internal error")).unwrap(); - continue; - } - *op.lock().unwrap() = RendererState::RunRadio(spec); + let spec = { + let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; + let spec = buffer.to_original::().unwrap(); + if spec.token != token_lock.unwrap_or(default_nonce) { + log::warn!("Attempt to access modals without a mutex lock. Ignoring."); + buffer.replace(ItemName::new("internal error")).unwrap(); + continue; + } + spec + }; + op = RendererState::RunRadio(spec); + dr = Some(msg); send_message( renderer_cid, - Message::new_scalar(RendererOp::InitiateOp.to_usize().unwrap(), 0, 0, 0, 0) + Message::new_scalar(Opcode::InitiateOp.to_usize().unwrap(), 0, 0, 0, 0) ).expect("couldn't initiate UX op"); - loop { - match *op.lock().unwrap() { - RendererState::RunRadio(_) => (), - RendererState::ResponseRadio(item) => { - buffer.replace(item).unwrap(); - token_lock = next_lock(&mut work_queue); - break; - }, - _ => { - log::error!("Illegal state transition in renderer"); - panic!("Illegal state transition in renderer"); - } - } - tt.sleep_ms(100).unwrap(); // don't put the idle in the match/lock(), it'll prevent the other thread from running! - } }, Some(Opcode::PromptWithMultiResponse) => { - let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; - let spec = buffer.to_original::().unwrap(); - if spec.token != token_lock.unwrap_or(default_nonce) { - log::warn!("Attempt to access modals without a mutex lock. Ignoring."); - buffer.replace(CheckBoxPayload::new()).unwrap(); - continue; - } - *op.lock().unwrap() = RendererState::RunCheckBox(spec); + let spec = { + let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; + let spec = buffer.to_original::().unwrap(); + if spec.token != token_lock.unwrap_or(default_nonce) { + log::warn!("Attempt to access modals without a mutex lock. Ignoring."); + buffer.replace(CheckBoxPayload::new()).unwrap(); + continue; + } + spec + }; + op = RendererState::RunCheckBox(spec); + dr = Some(msg); send_message( renderer_cid, - Message::new_scalar(RendererOp::InitiateOp.to_usize().unwrap(), 0, 0, 0, 0) + Message::new_scalar(Opcode::InitiateOp.to_usize().unwrap(), 0, 0, 0, 0) ).expect("couldn't initiate UX op"); - loop { - match *op.lock().unwrap() { - RendererState::RunCheckBox(_) => (), - RendererState::ResponseCheckBox(items) => { - buffer.replace(items).unwrap(); - token_lock = next_lock(&mut work_queue); - break; - }, - _ => { - log::error!("Illegal state transition in renderer"); - panic!("Illegal state transition in renderer"); - } - } - tt.sleep_ms(100).unwrap(); // don't put the idle in the match/lock(), it'll prevent the other thread from running! - } }, Some(Opcode::PromptWithTextResponse) => { - let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; - let spec = buffer.to_original::().unwrap(); - if spec.token != token_lock.unwrap_or(default_nonce) { - log::warn!("Attempt to access modals without a mutex lock. Ignoring."); - buffer.replace(TextEntryPayload::new()).unwrap(); - continue; - } - *op.lock().unwrap() = RendererState::RunText(spec); + let spec = { + let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; + let spec = buffer.to_original::().unwrap(); + if spec.token != token_lock.unwrap_or(default_nonce) { + log::warn!("Attempt to access modals without a mutex lock. Ignoring."); + buffer.replace(TextEntryPayload::new()).unwrap(); + continue; + } + spec + }; + op = RendererState::RunText(spec); + dr = Some(msg); send_message( renderer_cid, - Message::new_scalar(RendererOp::InitiateOp.to_usize().unwrap(), 0, 0, 0, 0) + Message::new_scalar(Opcode::InitiateOp.to_usize().unwrap(), 0, 0, 0, 0) ).expect("couldn't initiate UX op"); - loop { - match *op.lock().unwrap() { - RendererState::RunText(_) => (), - RendererState::ResponseText(text) => { - buffer.replace(text).unwrap(); - token_lock = next_lock(&mut work_queue); - break; - }, - _ => { - log::error!("Illegal state transition in renderer"); - panic!("Illegal state transition in renderer"); - } - } - tt.sleep_ms(100).unwrap(); // don't put the idle in the match/lock(), it'll prevent the other thread from running! - } }, Some(Opcode::Notification) => { - let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; - let spec = buffer.to_original::().unwrap(); + let spec = { + let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; + buffer.to_original::().unwrap() + }; if spec.token != token_lock.unwrap_or(default_nonce) { log::warn!("Attempt to access modals without a mutex lock. Ignoring."); continue; } - *op.lock().unwrap() = RendererState::RunNotification(spec); + op = RendererState::RunNotification(spec); + dr = Some(msg); send_message( renderer_cid, - Message::new_scalar(RendererOp::InitiateOp.to_usize().unwrap(), 0, 0, 0, 0) + Message::new_scalar(Opcode::InitiateOp.to_usize().unwrap(), 0, 0, 0, 0) ).expect("couldn't initiate UX op"); - loop { - match *op.lock().unwrap() { - RendererState::RunNotification(_) => (), - RendererState::None => {token_lock = next_lock(&mut work_queue); break}, - _ => { - log::error!("Illegal state transition in renderer"); - panic!("Illegal state transition in renderer"); - } - } - tt.sleep_ms(100).unwrap(); // don't put the idle in the match/lock(), it'll prevent the other thread from running! - } }, Some(Opcode::StartProgress) => { - let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; - let spec = buffer.to_original::().unwrap(); + let spec = { + let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; + buffer.to_original::().unwrap() + }; if spec.token != token_lock.unwrap_or(default_nonce) { log::warn!("Attempt to access modals without a mutex lock. Ignoring."); continue; } - *op.lock().unwrap() = RendererState::RunProgress(spec); + op = RendererState::RunProgress(spec); send_message( renderer_cid, - Message::new_scalar(RendererOp::InitiateOp.to_usize().unwrap(), 0, 0, 0, 0) + Message::new_scalar(Opcode::InitiateOp.to_usize().unwrap(), 0, 0, 0, 0) ).expect("couldn't initiate UX op"); }, Some(Opcode::UpdateProgress) => msg_scalar_unpack!(msg, current, _, _, _, { send_message( renderer_cid, - Message::new_scalar(RendererOp::UpdateProgress.to_usize().unwrap(), current, 0, 0, 0) + Message::new_scalar(Opcode::DoUpdateProgress.to_usize().unwrap(), current, 0, 0, 0) ).expect("couldn't update progress bar"); }), Some(Opcode::StopProgress) => msg_scalar_unpack!(msg, t0, t1, t2, t3, { @@ -592,31 +224,31 @@ fn xmain() -> ! { } send_message( renderer_cid, - Message::new_scalar(RendererOp::FinishProgress.to_usize().unwrap(), 0, 0, 0, 0) + Message::new_scalar(Opcode::FinishProgress.to_usize().unwrap(), 0, 0, 0, 0) ).expect("couldn't update progress bar"); - token_lock = next_lock(&mut work_queue); }), Some(Opcode::AddModalItem) => { let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; let manageditem = buffer.to_original::().unwrap(); if manageditem.token != token_lock.unwrap_or(default_nonce) { - log::warn!("Attempt to access modals without a mutex lock. Ignoring."); + log::warn!("Attempt to access modals without a mutex lock. Ignoring. got: {:x?} have: {:x?}", manageditem.token, token_lock); continue; } - let fwd_buf = Buffer::into_buf(manageditem.item).unwrap(); - fwd_buf.lend(renderer_cid, RendererOp::AddModalItem.to_u32().unwrap()).expect("couldn't add item"); + fixed_items.push(manageditem.item); } Some(Opcode::DynamicNotification) => { - let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; - let spec = buffer.to_original::().unwrap(); + let spec = { + let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; + buffer.to_original::().unwrap() + }; if spec.token != token_lock.unwrap_or(default_nonce) { log::warn!("Attempt to access modals without a mutex lock. Ignoring."); continue; } - *op.lock().unwrap() = RendererState::RunDynamicNotification(spec); + op = RendererState::RunDynamicNotification(spec); send_message( renderer_cid, - Message::new_scalar(RendererOp::InitiateOp.to_usize().unwrap(), 0, 0, 0, 0) + Message::new_scalar(Opcode::InitiateOp.to_usize().unwrap(), 0, 0, 0, 0) ).expect("couldn't initiate UX op"); }, Some(Opcode::UpdateDynamicNotification) => { @@ -626,10 +258,10 @@ fn xmain() -> ! { log::warn!("Attempt to access modals without a mutex lock. Ignoring."); continue; } - *op.lock().unwrap() = RendererState::RunDynamicNotification(spec); + op = RendererState::RunDynamicNotification(spec); send_message( renderer_cid, - Message::new_scalar(RendererOp::UpdateDynamicNotification.to_usize().unwrap(), 0, 0, 0, 0) + Message::new_scalar(Opcode::DoUpdateDynamicNotification.to_usize().unwrap(), 0, 0, 0, 0) ).expect("couldn't initiate UX op"); }, Some(Opcode::CloseDynamicNotification) => msg_scalar_unpack!(msg, t0, t1, t2, t3, { @@ -640,10 +272,319 @@ fn xmain() -> ! { } send_message( renderer_cid, - Message::new_scalar(RendererOp::CloseDynamicNotification.to_usize().unwrap(), 0, 0, 0, 0) + Message::new_scalar(Opcode::DoCloseDynamicNotification.to_usize().unwrap(), 0, 0, 0, 0) ).expect("couldn't close dynamic notification"); - token_lock = next_lock(&mut work_queue); }), + + // ------------------ INTERNAL APIS -------------------- + Some(Opcode::InitiateOp) => { + log::debug!("InitiateOp called"); + match op { + RendererState::RunText(config) => { + log::debug!("initiating text entry modal"); + #[cfg(feature="tts")] + tts.tts_simple(config.prompt.as_str().unwrap()).unwrap(); + renderer_modal.modify( + Some(ActionType::TextEntry(text_action)), + Some(config.prompt.as_str().unwrap()), false, + None, true, None + ); + renderer_modal.activate(); + log::debug!("should be active!"); + }, + RendererState::RunNotification(config) => { + #[cfg(feature="tts")] + tts.tts_simple(config.message.as_str().unwrap()).unwrap(); + renderer_modal.modify( + Some(ActionType::Notification(notification)), + Some(config.message.as_str().unwrap()), false, + None, true, None + ); + renderer_modal.activate(); + }, + RendererState::RunProgress(config) => { + start_work = config.start_work; + end_work = config.end_work; + last_percentage = compute_checked_percentage( + config.current_work, start_work, end_work); + log::debug!("init percentage: {}, current: {}, start: {}, end: {}", last_percentage, config.current_work, start_work, end_work); + progress_action.set_state(last_percentage); + #[cfg(feature="tts")] + tts.tts_simple(config.title.as_str().unwrap()).unwrap(); + renderer_modal.modify( + Some(ActionType::Slider(progress_action)), + Some(config.title.as_str().unwrap()), false, + None, true, None + ); + renderer_modal.activate(); + }, + RendererState::RunRadio(config) => { + let mut radiobuttons = gam::modal::RadioButtons::new( + renderer_cid, + Opcode::RadioReturn.to_u32().unwrap() + ); + for item in fixed_items.iter() { + radiobuttons.add_item(*item); + } + fixed_items.clear(); + #[cfg(feature="tts")] + { + tts.tts_blocking(t!("modals.radiobutton", xous::LANG)).unwrap(); + tts.tts_blocking(config.prompt.as_str().unwrap()).unwrap(); + } + renderer_modal.modify( + Some(ActionType::RadioButtons(radiobuttons)), + Some(config.prompt.as_str().unwrap()), false, + None, true, None + ); + renderer_modal.activate(); + }, + RendererState::RunCheckBox(config) => { + let mut checkbox = gam::modal::CheckBoxes::new( + renderer_cid, + Opcode::CheckBoxReturn.to_u32().unwrap() + ); + for item in fixed_items.iter() { + checkbox.add_item(*item); + } + fixed_items.clear(); + #[cfg(feature="tts")] + { + tts.tts_blocking(t!("modals.checkbox", xous::LANG)).unwrap(); + tts.tts_blocking(config.prompt.as_str().unwrap()).unwrap(); + } + renderer_modal.modify( + Some(ActionType::CheckBoxes(checkbox)), + Some(config.prompt.as_str().unwrap()), false, + None, true, None + ); + renderer_modal.activate(); + }, + RendererState::RunDynamicNotification(config) => { + let mut top_text = String::new(); + if let Some(title) = config.title { + #[cfg(feature="tts")] + tts.tts_simple(title.as_str().unwrap()).unwrap(); + top_text.push_str(title.as_str().unwrap()); + } + let mut bot_text = String::new(); + if let Some(text) = config.text { + #[cfg(feature="tts")] + tts.tts_simple(text.as_str().unwrap()).unwrap(); + bot_text.push_str(text.as_str().unwrap()); + } + renderer_modal.modify( + Some(ActionType::Notification(gutter)), + Some(&top_text), config.title.is_none(), + Some(&bot_text), config.text.is_none(), + None + ); + renderer_modal.activate(); + }, + RendererState::None => { + log::error!("Operation initiated with no argument specified. Ignoring request."); + continue; + } + } + }, + Some(Opcode::DoUpdateProgress) => msg_scalar_unpack!(msg, current, _, _, _, { + let new_percentage = compute_checked_percentage( + current as u32, start_work, end_work); + log::trace!("percentage: {}, current: {}, start: {}, end: {}", new_percentage, current, start_work, end_work); + if new_percentage != last_percentage { + last_percentage = new_percentage; + progress_action.set_state(last_percentage); + #[cfg(feature="tts")] + { + if tt.elapsed_ms() - last_tick > TICK_INTERVAL { + tts.tts_blocking(t!("progress.increment", xous::LANG)).unwrap(); + last_tick = tt.elapsed_ms(); + } + } + renderer_modal.modify( + Some(ActionType::Slider(progress_action)), + None, false, + None, false, None + ); + renderer_modal.redraw(); + xous::yield_slice(); // give time for the GAM to redraw + } + }), + Some(Opcode::FinishProgress) => { + renderer_modal.gam.relinquish_focus().unwrap(); + op = RendererState::None; + token_lock = next_lock(&mut work_queue); + /* + if work_queue.len() > 0 { + let (unblock_pid, token) = work_queue.remove(0); + token_lock = Some(token); + xous::return_scalar(unblock_pid, 1).unwrap(); + } else { + token_lock = None; + }*/ + }, + Some(Opcode::DoUpdateDynamicNotification) => { + match op { + RendererState::RunDynamicNotification(config) => { + let mut top_text = String::new(); + if let Some(title) = config.title { + top_text.push_str(title.as_str().unwrap()); + } + let mut bot_text = String::new(); + if let Some(text) = config.text { + bot_text.push_str(text.as_str().unwrap()); + } + renderer_modal.modify( + None, + Some(&top_text), config.title.is_none(), + Some(&bot_text), config.text.is_none(), + None + ); + renderer_modal.redraw(); + } + _ => { + log::error!("UX return opcode does not match our current operation in flight. This is a serious internal error."); + panic!("UX return opcode does not match our current operation in flight. This is a serious internal error."); + } + } + }, + Some(Opcode::DoCloseDynamicNotification) => { + renderer_modal.gam.relinquish_focus().unwrap(); + op = RendererState::None; + token_lock = next_lock(&mut work_queue); + }, + Some(Opcode::TextEntryReturn) => { + match op { + RendererState::RunText(config) => { + log::trace!("validating text entry modal"); + let buf = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; + let text = buf.to_original::().unwrap(); + if let Some(validator_sid) = config.validator { + let cid = xous::connect(SID::from_array(validator_sid)).unwrap(); + let validation = Validation { + text, + opcode: config.validator_op, + }; + let mut buf = Buffer::into_buf(validation).expect("couldn't convert validator structure"); + buf.lend_mut(cid, ValidationOp::Validate.to_u32().unwrap()).expect("validation call failed"); + let response = buf.to_original::>, _>().expect("couldn't unpack validation response"); + unsafe{xous::disconnect(cid).unwrap();} + if let Some(err) = response { + // try again + renderer_modal.modify( + Some(ActionType::TextEntry(text_action)), + Some(config.prompt.as_str().unwrap()), false, + Some(err.as_str().unwrap()), false, None + ); + renderer_modal.activate(); + } else { + if let Some(mut origin) = dr.take() { + let mut response = unsafe { Buffer::from_memory_message_mut(origin.body.memory_message_mut().unwrap()) }; + response.replace(text).unwrap(); + op = RendererState::None; + } else { + log::error!("Ux routine returned but no origin was recorded"); + panic!("Ux routine returned but no origin was recorded"); + } + token_lock = next_lock(&mut work_queue); + } + } else { + if let Some(mut origin) = dr.take() { + let mut response = unsafe { Buffer::from_memory_message_mut(origin.body.memory_message_mut().unwrap()) }; + response.replace(text).unwrap(); + op = RendererState::None; + } else { + log::error!("Ux routine returned but no origin was recorded"); + panic!("Ux routine returned but no origin was recorded"); + } + token_lock = next_lock(&mut work_queue); + } + } + RendererState::None => log::warn!("Text entry detected a fat finger event, ignoring."), + _ => { + log::error!("UX return opcode does not match our current operation in flight. This is a serious internal error."); + panic!("UX return opcode does not match our current operation in flight. This is a serious internal error."); + } + } + } + Some(Opcode::NotificationReturn) => { + match op { + RendererState::RunNotification(_) => { + op = RendererState::None; + dr.take(); // unblocks the caller, but without any response data + token_lock = next_lock(&mut work_queue); + }, + RendererState::None => log::warn!("Notification detected a fat finger event, ignoring."), + _ => { + log::error!("UX return opcode does not match our current operation in flight: {:?}", op); + panic!("UX return opcode does not match our current operation in flight. This is a serious internal error."); + } + } + }, + Some(Opcode::Gutter) => { + log::info!("gutter op, doing nothing"); + }, + Some(Opcode::RadioReturn) => { + match op { + RendererState::RunRadio(_config) => { + let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; + let item = buffer.to_original::().unwrap(); + if let Some(mut origin) = dr.take() { + let mut response = unsafe { Buffer::from_memory_message_mut(origin.body.memory_message_mut().unwrap()) }; + response.replace(item).unwrap(); + op = RendererState::None; + } else { + log::error!("Ux routine returned but no origin was recorded"); + panic!("Ux routine returned but no origin was recorded"); + } + token_lock = next_lock(&mut work_queue); + } + RendererState::None => log::warn!("Radio buttons detected a fat finger event, ignoring."), + _ => { + log::error!("UX return opcode does not match our current operation in flight. This is a serious internal error."); + panic!("UX return opcode does not match our current operation in flight. This is a serious internal error."); + } + } + } + Some(Opcode::CheckBoxReturn) => { + match op { + RendererState::RunCheckBox(_config) => { + let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; + let item = buffer.to_original::().unwrap(); + if let Some(mut origin) = dr.take() { + let mut response = unsafe { Buffer::from_memory_message_mut(origin.body.memory_message_mut().unwrap()) }; + response.replace(item).unwrap(); + op = RendererState::None; + } else { + log::error!("Ux routine returned but no origin was recorded"); + panic!("Ux routine returned but no origin was recorded"); + } + token_lock = next_lock(&mut work_queue); + } + RendererState::None => log::warn!("Check boxes detected a fat finger event, ignoring."), + _ => { + log::error!("UX return opcode does not match our current operation in flight. This is a serious internal error."); + panic!("UX return opcode does not match our current operation in flight. This is a serious internal error."); + } + } + } + Some(Opcode::ModalRedraw) => { + renderer_modal.redraw(); + }, + Some(Opcode::ModalKeypress) => msg_scalar_unpack!(msg, k1, k2, k3, k4, { + let keys = [ + if let Some(a) = core::char::from_u32(k1 as u32) {a} else {'\u{0000}'}, + if let Some(a) = core::char::from_u32(k2 as u32) {a} else {'\u{0000}'}, + if let Some(a) = core::char::from_u32(k3 as u32) {a} else {'\u{0000}'}, + if let Some(a) = core::char::from_u32(k4 as u32) {a} else {'\u{0000}'}, + ]; + renderer_modal.key_event(keys); + }), + Some(Opcode::ModalDrop) => { // this guy should never quit, it's a core OS service + panic!("Password modal for PDDB quit unexpectedly"); + }, + + Some(Opcode::Quit) => { log::warn!("Shared modal UX handler exiting."); break @@ -651,14 +592,10 @@ fn xmain() -> ! { None => { log::error!("couldn't convert opcode"); } - } } // clean up our program log::trace!("main loop exit, destroying servers"); - send_message(renderer_cid, Message::new_blocking_scalar(RendererOp::Quit.to_usize().unwrap(), 0, 0, 0, 0)).unwrap(); - unsafe{xous::disconnect(renderer_cid).unwrap()}; - xous::destroy_server(renderer_sid).unwrap(); xns.unregister_server(modals_sid).unwrap(); xous::destroy_server(modals_sid).unwrap(); log::trace!("quitting"); @@ -682,7 +619,14 @@ fn compute_checked_percentage(current: u32, start: u32, end: u32) -> u32 { fn next_lock(work_queue: &mut Vec::<(xous::MessageSender, [u32; 4])>) -> Option<[u32; 4]> { if work_queue.len() > 0 { + /* + log::debug!("pending:"); + for (pid, tok) in work_queue.iter() { + log::debug!("pid: {:x?}, tok: {:x?}", pid, tok); + } + */ let (unblock_pid, token) = work_queue.remove(0); + log::debug!("next token: {:x?}", token); xous::return_scalar(unblock_pid, 1).unwrap(); Some(token) } else { diff --git a/services/modals/src/tests.rs b/services/modals/src/tests.rs index edbffa562..594772760 100644 --- a/services/modals/src/tests.rs +++ b/services/modals/src/tests.rs @@ -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(); } From c97a00ed1f67a519f0478e73b17a0777a7d2e563 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 7 Apr 2022 04:38:38 +0800 Subject: [PATCH 8/8] refactor validator to not create a new single-use server --- services/modals/src/api.rs | 11 ++--- services/modals/src/lib.rs | 91 +++++++++++++++++-------------------- services/modals/src/main.rs | 57 +++++++---------------- 3 files changed, 62 insertions(+), 97 deletions(-) diff --git a/services/modals/src/api.rs b/services/modals/src/api.rs index 3e9f53759..9ff28188b 100644 --- a/services/modals/src/api.rs +++ b/services/modals/src/api.rs @@ -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 { @@ -67,13 +63,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) diff --git a/services/modals/src/lib.rs b/services/modals/src/lib.rs index 648e62f4e..cc20929f0 100644 --- a/services/modals/src/lib.rs +++ b/services/modals/src/lib.rs @@ -4,10 +4,9 @@ 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 { @@ -35,56 +34,48 @@ impl Modals { maybe_validator_op: Option, ) -> Result { 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::().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"); - } - self.unlock(); - match buf.to_original::() { - 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::() { + 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); + } + } } } diff --git a/services/modals/src/main.rs b/services/modals/src/main.rs index ec791836a..8d4cca1b3 100644 --- a/services/modals/src/main.rs +++ b/services/modals/src/main.rs @@ -5,8 +5,6 @@ mod api; use api::*; mod tests; -use xous::SID; - use xous::{msg_scalar_unpack, msg_blocking_scalar_unpack, send_message, Message}; use xous_ipc::Buffer; @@ -455,49 +453,17 @@ fn xmain() -> ! { }, Some(Opcode::TextEntryReturn) => { match op { - RendererState::RunText(config) => { + RendererState::RunText(_config) => { log::trace!("validating text entry modal"); let buf = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; let text = buf.to_original::().unwrap(); - if let Some(validator_sid) = config.validator { - let cid = xous::connect(SID::from_array(validator_sid)).unwrap(); - let validation = Validation { - text, - opcode: config.validator_op, - }; - let mut buf = Buffer::into_buf(validation).expect("couldn't convert validator structure"); - buf.lend_mut(cid, ValidationOp::Validate.to_u32().unwrap()).expect("validation call failed"); - let response = buf.to_original::>, _>().expect("couldn't unpack validation response"); - unsafe{xous::disconnect(cid).unwrap();} - if let Some(err) = response { - // try again - renderer_modal.modify( - Some(ActionType::TextEntry(text_action)), - Some(config.prompt.as_str().unwrap()), false, - Some(err.as_str().unwrap()), false, None - ); - renderer_modal.activate(); - } else { - if let Some(mut origin) = dr.take() { - let mut response = unsafe { Buffer::from_memory_message_mut(origin.body.memory_message_mut().unwrap()) }; - response.replace(text).unwrap(); - op = RendererState::None; - } else { - log::error!("Ux routine returned but no origin was recorded"); - panic!("Ux routine returned but no origin was recorded"); - } - token_lock = next_lock(&mut work_queue); - } + if let Some(mut origin) = dr.take() { + let mut response = unsafe { Buffer::from_memory_message_mut(origin.body.memory_message_mut().unwrap()) }; + response.replace(text).unwrap(); + op = RendererState::None; } else { - if let Some(mut origin) = dr.take() { - let mut response = unsafe { Buffer::from_memory_message_mut(origin.body.memory_message_mut().unwrap()) }; - response.replace(text).unwrap(); - op = RendererState::None; - } else { - log::error!("Ux routine returned but no origin was recorded"); - panic!("Ux routine returned but no origin was recorded"); - } - token_lock = next_lock(&mut work_queue); + log::error!("Ux routine returned but no origin was recorded"); + panic!("Ux routine returned but no origin was recorded"); } } RendererState::None => log::warn!("Text entry detected a fat finger event, ignoring."), @@ -507,6 +473,15 @@ fn xmain() -> ! { } } } + Some(Opcode::TextResponseValid) => msg_blocking_scalar_unpack!(msg, t0, t1, t2, t3, { + let incoming_token = [t0 as u32, t1 as u32, t2 as u32, t3 as u32]; + if incoming_token != token_lock.unwrap_or(default_nonce) { + log::warn!("Attempt to access modals without a mutex lock. Ignoring."); + } else { + token_lock = next_lock(&mut work_queue); + } + xous::return_scalar(msg.sender, 1).unwrap(); + }), Some(Opcode::NotificationReturn) => { match op { RendererState::RunNotification(_) => {