From ca07645dce3c9e9e763e928be93032a0e6441ce8 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 18 Mar 2021 16:21:10 +0800 Subject: [PATCH 01/27] remove loop polling on GAM, seems unecessary --- services/gam/src/main.rs | 391 +++++++++++++++++++-------------------- 1 file changed, 190 insertions(+), 201 deletions(-) diff --git a/services/gam/src/main.rs b/services/gam/src/main.rs index 445494785..5e39bc8ee 100644 --- a/services/gam/src/main.rs +++ b/services/gam/src/main.rs @@ -181,7 +181,7 @@ impl ModalCanvases { #[xous::xous_main] fn xmain() -> ! { let debug1 = false; // debug level 1 - most general level - let debugc = false; + let debugc = true; log_server::init_wait().unwrap(); info!("GAM: my PID is {}", xous::process::id()); @@ -230,222 +230,211 @@ fn xmain() -> ! { let mut last_time: u64 = ticktimer_server::elapsed_ms(ticktimer_conn).unwrap(); info!("GAM: entering main loop"); loop { - let maybe_env = xous::try_receive_message(gam_sid).unwrap(); - if debug1 { if maybe_env.is_some() {info!("GAM: Message: {:?}", maybe_env);} } - match maybe_env { - Some(envelope) => { - if debug1 {info!("GAM: Message: {:?}", envelope); } - if let Ok(opcode) = Opcode::try_from(&envelope.body) { - if debug1 {info!("GAM: Opcode: {:?}", opcode);} - match opcode { - Opcode::ClearCanvas(gid) => { - match canvases.get(&gid) { - Some(c) => { - let mut rect = c.clip_rect(); - rect.style = DrawStyle {fill_color: Some(PixelColor::Light), stroke_color: None, stroke_width: 0,}; - graphics_server::draw_rectangle(gfx_conn, rect).expect("GAM: can't clear canvas"); - }, - None => info!("GAM: attempt to clear bogus canvas, ignored."), - } + let envelope = xous::receive_message(gam_sid).unwrap(); + if debug1 { info!("GAM: Message: {:?}", envelope);} + if let Ok(opcode) = Opcode::try_from(&envelope.body) { + if debug1 {info!("GAM: Opcode: {:?}", opcode);} + match opcode { + Opcode::ClearCanvas(gid) => { + match canvases.get(&gid) { + Some(c) => { + let mut rect = c.clip_rect(); + rect.style = DrawStyle {fill_color: Some(PixelColor::Light), stroke_color: None, stroke_width: 0,}; + graphics_server::draw_rectangle(gfx_conn, rect).expect("GAM: can't clear canvas"); }, - Opcode::GetCanvasBounds(gid) => { - match canvases.get(&gid) { - Some(c) => { - let mut rect = c.clip_rect(); - rect.normalize(); // normalize to 0,0 coordinates - xous::return_scalar2(envelope.sender, - rect.tl.into(), - rect.br.into(), - ).expect("GAM: couldn't return canvas bounds"); - }, - None => info!("GAM: attempt to get bounds on bogus canvas gid {:?}, {:?} ignored.", gid, envelope), - } - }, - Opcode::PowerDownRequest => { - powerdown_requested = true; - graphics_server::draw_sleepscreen(gfx_conn).expect("GAM: couldn't draw sleep screen"); - // a screen flush is part of the draw_sleepscreen abstraction - xous::return_scalar(envelope.sender, 1).expect("GAM: couldn't confirm power down UI request"); - }, - Opcode::Redraw => { - if powerdown_requested { - continue; // don't allow any redraws if a powerdown is requested - } - if let Ok(elapsed_time) = ticktimer_server::elapsed_ms(ticktimer_conn) { - if elapsed_time - last_time > 33 { // rate limit updates, no point in going faster than the eye can see - last_time = elapsed_time; - - deface(gfx_conn, &mut canvases); - graphics_server::flush(gfx_conn).expect("GAM: couldn't flush buffer to screen"); - /* // this throws errors right now because deface() doesn't work. - for (_, c) in canvases.iter_mut() { - c.do_flushed(); - }*/ - } - } - }, - _ => todo!("GAM: opcode not yet implemented"), + None => info!("GAM: attempt to clear bogus canvas, ignored."), } - } else if let xous::Message::MutableBorrow(m) = &envelope.body { - let mut buf = unsafe { xous::XousBuffer::from_memory_message(m) }; - let value = unsafe { - archived_value_mut::(Pin::new(buf.as_mut()), m.id as usize) - }; - match &*value { - rkyv::Archived::::RenderTextView(rtv) => { - let mut tv = rtv.deserialize(&mut xous::XousDeserializer).unwrap(); - if debug1{info!("GAM: rendertextview {:?}", tv);} - match tv.get_op() { - TextOp::Nop => (), - TextOp::Render | TextOp::ComputeBounds => { - if debug1{info!("GAM: render request for {:?}", tv);} - if tv.get_op() == TextOp::ComputeBounds { - tv.dry_run = true; - } else { - tv.dry_run = false; - } - - if let Some(canvas) = canvases.get_mut(&tv.get_canvas_gid()) { - // first, figure out if we should even be drawing to this canvas. - if canvas.is_drawable() { - // set the clip rectangle according to the canvas' location - tv.clip_rect = Some(canvas.clip_rect().into()); - - // you have to clone the tv object, because if you don't the same block of - // memory gets passed on to the graphics_server(). Which is efficient, but, - // the call will automatically Drop() the memory, which causes a panic when - // this routine returns. - let mut tv_clone = tv.clone(); - // issue the draw command - graphics_server::draw_textview(gfx_conn, &mut tv_clone).expect("GAM: text view draw could not complete."); - // copy back the fields that we want to be mutable - if debug1{info!("GAM: got computed cursor of {:?}", tv_clone.cursor);} - tv.cursor = tv_clone.cursor; - tv.bounds_computed = tv_clone.bounds_computed; - - // pack our data back into the buffer to return - let mut writer = rkyv::ser::serializers::BufferSerializer::new(buf); - writer.serialize_value(&api::Opcode::RenderTextView(tv)).expect("GAM: couldn't re-archive return value"); - canvas.do_drawn().expect("GAM: couldn't set canvas to drawn"); - } else { - info!("GAM: attempt to draw TextView on non-drawable canvas. Not fatal, but request ignored."); - } - } else { - info!("GAM: bogus GID {:?} in TextView {}, not doing anything in response to draw request.", tv.get_canvas_gid(), tv.text); - // silently fail if a bogus Gid is given??? - } - }, - }; + }, + Opcode::GetCanvasBounds(gid) => { + match canvases.get(&gid) { + Some(c) => { + let mut rect = c.clip_rect(); + rect.normalize(); // normalize to 0,0 coordinates + xous::return_scalar2(envelope.sender, + rect.tl.into(), + rect.br.into(), + ).expect("GAM: couldn't return canvas bounds"); }, - rkyv::Archived::::SetCanvasBounds(rcb) => { - let mut cb: SetCanvasBoundsRequest = rcb.deserialize(&mut xous::XousDeserializer).unwrap(); - if debug1{info!("GAM: SetCanvasBoundsRequest {:?}", cb);} - // ASSUME: - // very few canvases allow dynamic resizing, so we special case these - if cb.canvas == chatlayout.input { - let newheight = chatlayout.resize_input(cb.requested.y, &mut canvases).expect("GAM: SetCanvasBoundsRequest couldn't recompute input canvas height"); - cb.granted = Some(newheight); - canvases = recompute_canvases(canvases, Rectangle::new(Point::new(0, 0), screensize)); + None => info!("GAM: attempt to get bounds on bogus canvas gid {:?}, {:?} ignored.", gid, envelope), + } + }, + Opcode::PowerDownRequest => { + powerdown_requested = true; + graphics_server::draw_sleepscreen(gfx_conn).expect("GAM: couldn't draw sleep screen"); + // a screen flush is part of the draw_sleepscreen abstraction + xous::return_scalar(envelope.sender, 1).expect("GAM: couldn't confirm power down UI request"); + }, + Opcode::Redraw => { + if powerdown_requested { + continue; // don't allow any redraws if a powerdown is requested + } + if let Ok(elapsed_time) = ticktimer_server::elapsed_ms(ticktimer_conn) { + if elapsed_time - last_time > 33 { // rate limit updates, no point in going faster than the eye can see + last_time = elapsed_time; - if ccc.connection.is_some() { - ccc.redraw_canvas().expect("GAM: couldn't issue redraw to content canvas"); - } + deface(gfx_conn, &mut canvases); + graphics_server::flush(gfx_conn).expect("GAM: couldn't flush buffer to screen"); + /* // this throws errors right now because deface() doesn't work. + for (_, c) in canvases.iter_mut() { + c.do_flushed(); + }*/ + } + } + }, + _ => todo!("GAM: opcode not yet implemented"), + } + } else if let xous::Message::MutableBorrow(m) = &envelope.body { + let mut buf = unsafe { xous::XousBuffer::from_memory_message(m) }; + let value = unsafe { + archived_value_mut::(Pin::new(buf.as_mut()), m.id as usize) + }; + match &*value { + rkyv::Archived::::RenderTextView(rtv) => { + let mut tv = rtv.deserialize(&mut xous::XousDeserializer).unwrap(); + if debug1{info!("GAM: rendertextview {:?}", tv);} + match tv.get_op() { + TextOp::Nop => (), + TextOp::Render | TextOp::ComputeBounds => { + if debug1{info!("GAM: render request for {:?}", tv);} + if tv.get_op() == TextOp::ComputeBounds { + tv.dry_run = true; } else { - cb.granted = None; + tv.dry_run = false; } - // pack our data back into the buffer to return - let mut writer = rkyv::ser::serializers::BufferSerializer::new(buf); - writer.serialize_value(&api::Opcode::SetCanvasBounds(cb)).expect("GAM: SetCanvasBoundsRequest couldn't re-archive return value"); - }, - rkyv::Archived::::RequestContentCanvas(rcc) => { - let mut req: ContentCanvasRequest = rcc.deserialize(&mut xous::XousDeserializer).unwrap(); - if debug1{info!("GAM: RequestContentCanvas {:?}", req);} - // for now, we do nothing with the incoming gid value; but, in the future, we can use it - // as an authentication token perhaps to control access - //// here make a connection back to the requesting server, so that we can tell it to redraw if the layout has changed, etc. - if let Ok(cc) = xous_names::request_connection_blocking(req.servername.as_str().expect("GAM: malformed server name in content canvas request")) { - ccc.connection = Some(cc); - } else { - log::error!("GAM: content requestor gave us a bogus canvas result, aborting"); - continue; - }; - - req.canvas = chatlayout.content; - // pack our data back into the buffer to return - let mut writer = rkyv::ser::serializers::BufferSerializer::new(buf); - writer.serialize_value(&api::Opcode::RequestContentCanvas(req)).expect("GAM: RequestContentCanvas couldn't re-archive return value"); - }, - _ => panic!("GAM: invalid mutable borrow message"), - }; - } else if let xous::Message::Borrow(m) = &envelope.body { - let buf = unsafe { xous::XousBuffer::from_memory_message(m) }; - let bytes = Pin::new(buf.as_ref()); - let value = unsafe { - archived_value::(&bytes, m.id as usize) - }; - match &*value { - rkyv::Archived::::RenderObject(rtv) => { - let obj: GamObject = rtv.deserialize(&mut xous::XousDeserializer).unwrap(); - if debug1{info!("GAM: renderobject {:?}", obj);} - if let Some(canvas) = canvases.get_mut(&obj.canvas) { + if let Some(canvas) = canvases.get_mut(&tv.get_canvas_gid()) { // first, figure out if we should even be drawing to this canvas. if canvas.is_drawable() { - match obj.obj { - GamObjectType::Line(mut line) => { - line.translate(canvas.clip_rect().tl); - line.translate(canvas.pan_offset()); - graphics_server::draw_line_clipped(gfx_conn, - line, - canvas.clip_rect(), - ).expect("GAM: couldn't draw line"); - }, - GamObjectType::Circ(mut circ) => { - circ.translate(canvas.clip_rect().tl); - circ.translate(canvas.pan_offset()); - graphics_server::draw_circle_clipped(gfx_conn, - circ, - canvas.clip_rect(), - ).expect("GAM: couldn't draw circle"); - }, - GamObjectType::Rect(mut rect) => { - rect.translate(canvas.clip_rect().tl); - rect.translate(canvas.pan_offset()); - graphics_server::draw_rectangle_clipped(gfx_conn, - rect, - canvas.clip_rect(), - ).expect("GAM: couldn't draw rectangle"); - }, - GamObjectType::RoundRect(mut rr) => { - rr.translate(canvas.clip_rect().tl); - rr.translate(canvas.pan_offset()); - graphics_server::draw_rounded_rectangle_clipped(gfx_conn, - rr, - canvas.clip_rect(), - ).expect("GAM: couldn't draw rounded rectangle"); - } - } + // set the clip rectangle according to the canvas' location + tv.clip_rect = Some(canvas.clip_rect().into()); + + // you have to clone the tv object, because if you don't the same block of + // memory gets passed on to the graphics_server(). Which is efficient, but, + // the call will automatically Drop() the memory, which causes a panic when + // this routine returns. + let mut tv_clone = tv.clone(); + // issue the draw command + graphics_server::draw_textview(gfx_conn, &mut tv_clone).expect("GAM: text view draw could not complete."); + // copy back the fields that we want to be mutable + if debug1{info!("GAM: got computed cursor of {:?}", tv_clone.cursor);} + tv.cursor = tv_clone.cursor; + tv.bounds_computed = tv_clone.bounds_computed; + + // pack our data back into the buffer to return + let mut writer = rkyv::ser::serializers::BufferSerializer::new(buf); + writer.serialize_value(&api::Opcode::RenderTextView(tv)).expect("GAM: couldn't re-archive return value"); canvas.do_drawn().expect("GAM: couldn't set canvas to drawn"); } else { - info!("GAM: attempt to draw Object on non-drawable canvas. Not fatal, but request ignored."); + info!("GAM: attempt to draw TextView on non-drawable canvas. Not fatal, but request ignored."); } } else { - info!("GAM: bogus GID in Object, not doing anything in response to draw request."); + info!("GAM: bogus GID {:?} in TextView {}, not doing anything in response to draw request.", tv.get_canvas_gid(), tv.text); + // silently fail if a bogus Gid is given??? } - if debug1{info!("GAM: leaving RenderObject");} }, - _ => panic!("GAM: invalid borrow message"), }; - } else { - panic!("GAM: unhandled message {:?}", envelope); - } - // /* - }, - _ => xous::yield_slice(), - // envelope implements Drop(), which includes a call to syscall::return_memory(self.sender, message.buf) - } + }, + rkyv::Archived::::SetCanvasBounds(rcb) => { + let mut cb: SetCanvasBoundsRequest = rcb.deserialize(&mut xous::XousDeserializer).unwrap(); + if debug1{info!("GAM: SetCanvasBoundsRequest {:?}", cb);} + // ASSUME: + // very few canvases allow dynamic resizing, so we special case these + if cb.canvas == chatlayout.input { + let newheight = chatlayout.resize_input(cb.requested.y, &mut canvases).expect("GAM: SetCanvasBoundsRequest couldn't recompute input canvas height"); + cb.granted = Some(newheight); + canvases = recompute_canvases(canvases, Rectangle::new(Point::new(0, 0), screensize)); - // auto-redraw code used to be here, but I think it's a bad idea....causes more - // graphics traffic than necessary? Trying out redraw-on-demand by clients. + if ccc.connection.is_some() { + ccc.redraw_canvas().expect("GAM: couldn't issue redraw to content canvas"); + } + } else { + cb.granted = None; + } + // pack our data back into the buffer to return + let mut writer = rkyv::ser::serializers::BufferSerializer::new(buf); + writer.serialize_value(&api::Opcode::SetCanvasBounds(cb)).expect("GAM: SetCanvasBoundsRequest couldn't re-archive return value"); + }, + rkyv::Archived::::RequestContentCanvas(rcc) => { + let mut req: ContentCanvasRequest = rcc.deserialize(&mut xous::XousDeserializer).unwrap(); + if debug1{info!("GAM: RequestContentCanvas {:?}", req);} + // for now, we do nothing with the incoming gid value; but, in the future, we can use it + // as an authentication token perhaps to control access + + //// here make a connection back to the requesting server, so that we can tell it to redraw if the layout has changed, etc. + if let Ok(cc) = xous_names::request_connection_blocking(req.servername.as_str().expect("GAM: malformed server name in content canvas request")) { + ccc.connection = Some(cc); + } else { + log::error!("GAM: content requestor gave us a bogus canvas result, aborting"); + continue; + }; + + req.canvas = chatlayout.content; + // pack our data back into the buffer to return + let mut writer = rkyv::ser::serializers::BufferSerializer::new(buf); + writer.serialize_value(&api::Opcode::RequestContentCanvas(req)).expect("GAM: RequestContentCanvas couldn't re-archive return value"); + }, + _ => panic!("GAM: invalid mutable borrow message"), + }; + } else if let xous::Message::Borrow(m) = &envelope.body { + let buf = unsafe { xous::XousBuffer::from_memory_message(m) }; + let bytes = Pin::new(buf.as_ref()); + let value = unsafe { + archived_value::(&bytes, m.id as usize) + }; + match &*value { + rkyv::Archived::::RenderObject(rtv) => { + let obj: GamObject = rtv.deserialize(&mut xous::XousDeserializer).unwrap(); + if debug1{info!("GAM: renderobject {:?}", obj);} + if let Some(canvas) = canvases.get_mut(&obj.canvas) { + // first, figure out if we should even be drawing to this canvas. + if canvas.is_drawable() { + match obj.obj { + GamObjectType::Line(mut line) => { + line.translate(canvas.clip_rect().tl); + line.translate(canvas.pan_offset()); + graphics_server::draw_line_clipped(gfx_conn, + line, + canvas.clip_rect(), + ).expect("GAM: couldn't draw line"); + }, + GamObjectType::Circ(mut circ) => { + circ.translate(canvas.clip_rect().tl); + circ.translate(canvas.pan_offset()); + graphics_server::draw_circle_clipped(gfx_conn, + circ, + canvas.clip_rect(), + ).expect("GAM: couldn't draw circle"); + }, + GamObjectType::Rect(mut rect) => { + rect.translate(canvas.clip_rect().tl); + rect.translate(canvas.pan_offset()); + graphics_server::draw_rectangle_clipped(gfx_conn, + rect, + canvas.clip_rect(), + ).expect("GAM: couldn't draw rectangle"); + }, + GamObjectType::RoundRect(mut rr) => { + rr.translate(canvas.clip_rect().tl); + rr.translate(canvas.pan_offset()); + graphics_server::draw_rounded_rectangle_clipped(gfx_conn, + rr, + canvas.clip_rect(), + ).expect("GAM: couldn't draw rounded rectangle"); + } + } + canvas.do_drawn().expect("GAM: couldn't set canvas to drawn"); + } else { + info!("GAM: attempt to draw Object on non-drawable canvas. Not fatal, but request ignored."); + } + } else { + info!("GAM: bogus GID in Object, not doing anything in response to draw request."); + } + if debug1{info!("GAM: leaving RenderObject");} + }, + _ => panic!("GAM: invalid borrow message"), + }; + } else { + panic!("GAM: unhandled message {:?}", envelope); + } } } From db5e56fd1a0ad3585d40dd2fcca0ed4a75db4bdb Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 18 Mar 2021 16:21:43 +0800 Subject: [PATCH 02/27] futzing with structures to try and figure out a threading issue --- services/graphics-server/src/api/text.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/services/graphics-server/src/api/text.rs b/services/graphics-server/src/api/text.rs index 5db098dec..dfd60ca33 100644 --- a/services/graphics-server/src/api/text.rs +++ b/services/graphics-server/src/api/text.rs @@ -49,6 +49,8 @@ pub struct TextView { // this is the operation as specified for the GAM. Note this is different from the "op" when sent to graphics-server // only the GAM should be sending TextViews to the graphics-server, and a different coding scheme is used for that link. operation: TextOp, + canvas: Gid, // GID of the canvas to draw on + pub clip_rect: Option, // this is set by the GAM to the canvas' clip_rect; needed by gfx for drawing. Note this is in screen coordinates. pub untrusted: bool, // render content with random stipples to indicate the strings within are untrusted pub token: Option<[u32; 4]>, // optional 128-bit token which is presented to prove a field's trustability @@ -75,9 +77,6 @@ pub struct TextView { // this field specifies the beginning and end of a "selected" region of text pub selected: Option<[u32; 2]>, - canvas: Gid, // GID of the canvas to draw on - pub clip_rect: Option, // this is set by the GAM to the canvas' clip_rect; needed by gfx for drawing. Note this is in screen coordinates. - pub text: xous::String::<3072>, } impl TextView { From 6677d798344e780bb2ac8f1ced0444d1af6eb275 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 18 Mar 2021 16:22:08 +0800 Subject: [PATCH 03/27] initial RTC framework --- Cargo.lock | 14 ++ Cargo.toml | 2 + services/rtc/Cargo.toml | 22 +++ services/rtc/src/api.rs | 73 +++++++ services/rtc/src/lib.rs | 22 +++ services/rtc/src/main.rs | 404 +++++++++++++++++++++++++++++++++++++++ xous-rs/src/names.rs | 1 + 7 files changed, 538 insertions(+) create mode 100644 services/rtc/Cargo.toml create mode 100644 services/rtc/src/api.rs create mode 100644 services/rtc/src/lib.rs create mode 100644 services/rtc/src/main.rs diff --git a/Cargo.lock b/Cargo.lock index eb688aa3d..89dbe8fc5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1072,6 +1072,20 @@ dependencies = [ "syn 1.0.60", ] +[[package]] +name = "rtc" +version = "0.1.0" +dependencies = [ + "bitflags", + "heapless", + "log", + "log-server", + "ticktimer-server", + "utralib", + "xous", + "xous-names", +] + [[package]] name = "rustc-hash" version = "1.1.0" diff --git a/Cargo.toml b/Cargo.toml index 73b1e61b1..54c636f49 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,6 +27,7 @@ members = [ "services/ime-plugin-api", "services/content-plugin-api", "services/llio", + "services/rtc", "services/trng-tester", ] default-members = [ @@ -50,6 +51,7 @@ default-members = [ "services/content-plugin-api", "services/shellchat", "services/llio", + "services/rtc", "services/trng-tester", ] diff --git a/services/rtc/Cargo.toml b/services/rtc/Cargo.toml new file mode 100644 index 000000000..3d0a6efd6 --- /dev/null +++ b/services/rtc/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "rtc" +version = "0.1.0" +authors = ["bunnie "] +edition = "2018" +description = "RTC server" + +[dependencies] +xous = { path = "../../xous-rs" } +heapless = "0.5.6" +log-server = { path = "../log-server" } +ticktimer-server = { path = "../ticktimer-server" } +xous-names = { path = "../xous-names" } +log = "0.4" +bitflags = "1.2.1" + +[target.'cfg(not(any(windows,unix)))'.dependencies] +utralib = { path = "../../utralib"} + +[features] +debugprint = [] +default = [] # "debugprint" diff --git a/services/rtc/src/api.rs b/services/rtc/src/api.rs new file mode 100644 index 000000000..e7102cef8 --- /dev/null +++ b/services/rtc/src/api.rs @@ -0,0 +1,73 @@ +use xous::{Message, ScalarMessage}; + +pub enum Weekday { + Sunday, + Monday, + Tuesday, + Wednesday, + Thursday, + Friday, + Saturday, +} + +pub enum TimeUnits { + Seconds, + Minutes, + Hours, +} + +pub struct DateTime { + pub seconds: u8, + pub minutes: u8, + pub hours: u8, + pub days: u8, + pub months: u8, + pub years: u8, + pub weekday: Weekday, +} + +#[allow(dead_code)] +#[derive(Debug)] +pub enum Opcode { + /// Get datetime. This will be accurate to +/-2s, as the RTC is updated from hardware + /// once a second. + GetDateTime, + + /// sets the datetime + SetDateTime(DateTime), + + /// sets a wake-up alarm. This forces the SoC into power-on state, if it happens to be off. + /// primarily used to trigger cold reboots, but could have other reasons + SetWakeupAlarm(u8, TimeUnits), + + /// clear any wakeup alarms that have been set + ClearWakeupAlarm, +} + +impl core::convert::TryFrom<& Message> for Opcode { + type Error = &'static str; + fn try_from(message: & Message) -> Result { + match message { + Message::BlockingScalar(m) => match m.id { + 0 => Ok(Opcode::GetTrng(m.arg1)), + _ => Err("TRNG api: unknown BlockingScalar ID"), + }, + _ => Err("TRNG api: unhandled message type"), + } + } +} + +impl Into for Opcode { + fn into(self) -> Message { + match self { + Opcode::GetTrng(count) => Message::BlockingScalar(ScalarMessage { + id: 0, + arg1: count.into(), + arg2: 0, + arg3: 0, + arg4: 0, + }), + // _ => panic!("TRNG api: Opcode type not handled by Into(), refer to helper method"), + } + } +} diff --git a/services/rtc/src/lib.rs b/services/rtc/src/lib.rs new file mode 100644 index 000000000..45f98edcb --- /dev/null +++ b/services/rtc/src/lib.rs @@ -0,0 +1,22 @@ +#![cfg_attr(target_os = "none", no_std)] + +pub mod api; +use xous::{CID, send_message}; + +pub fn get_u32(cid: CID) -> Result { + let response = send_message(cid, api::Opcode::GetTrng(1).into())?; + if let xous::Result::Scalar2(trng, _) = response { + Ok(trng as u32) + } else { + panic!("unexpected return value: {:#?}", response); + } +} + +pub fn get_u64(cid: CID) -> Result { + let response = send_message(cid, api::Opcode::GetTrng(2).into())?; + if let xous::Result::Scalar2(lo, hi) = response { + Ok( lo as u64 | ((hi as u64) << 32) ) + } else { + panic!("unexpected return value: {:#?}", response); + } +} diff --git a/services/rtc/src/main.rs b/services/rtc/src/main.rs new file mode 100644 index 000000000..bc5c4b123 --- /dev/null +++ b/services/rtc/src/main.rs @@ -0,0 +1,404 @@ +#![cfg_attr(target_os = "none", no_std)] +#![cfg_attr(target_os = "none", no_main)] + +mod api; +use api::*; + +use core::convert::TryFrom; + +use log::{error, info}; + + +#[cfg(target_os = "none")] +mod implementation { + use log::info; + #[macro_use] + use bitflags::*; + + const ABRTCMC_I2C_ADR: u8 = 0x68; + const ABRTCMC_CONTROL1: u8 = 0x00; + bitflags! { + pub struct Control1: u8 { + const CORRECTION_INT = 0b0000_0001; + const ALARM_INT = 0b0000_0010; + const SECONDS_INT = 0b0000_0100; + const HR_MODE_12 = 0b0000_1000; + const SOFT_RESET = 0b0001_0000; + const STOP = 0b0010_0000; + } + } + + const ABRTCMC_CONTROL2: u8 = 0x01; + bitflags! { + pub struct Control2: u8 { + const COUNTDOWN_B_INT = 0b0000_0001; + const COUNTDOWN_A_INT = 0b0000_0010; + const WATCHDOG_A_INT = 0b0000_0100; + const ALARM_HAPPENED = 0b0000_1000; + const SECONDS_HAPPENED= 0b0001_0000; + const COUNTB_HAPPENED = 0b0010_0000; + const COUNTA_HAPPENED = 0b0100_0000; + const WATCHA_HAPPENED = 0b1000_0000; + } + } + + const ABRTCMC_CONTROL3: u8 = 0x02; + bitflags! { + pub struct Control3: u8 { + const BATTLOW_INT = 0b0000_0001; + const BATTSWITCH_INT = 0b0000_0010; + const BATTLOW_STAT = 0b0000_0100; + const BATTSW_HAPPENED = 0b0000_1000; + + const BATT_STD_BL_EN = 0b0000_0000; + const BATT_DIR_BL_EN = 0b0010_0000; + const BATT_DIS_BL_EN = 0b0100_0000; + const BATT_STD_BL_DIS = 0b1000_0000; + const BATT_DI_BL_DIS = 0b1110_0000; + } + } + + const ABRTCMC_SECONDS: u8 = 0x3; + bitflags! { + pub struct Seconds: u8 { + const SECONDS_BCD = 0b0111_1111; + const CORRUPTED = 0b1000_0000; + } + } + + const ABRTCMC_MINUTES: u8 = 0x4; + // no bitflags, minutes are BCD whole register + + const ABRTCMC_HOURS: u8 = 0x5; + bitflags! { + pub struct Hours: u8 { + const HR12_HOURS_BCD = 0b0001_1111; + const HR12_PM_FLAG = 0b0010_0000; + const HR24_HOURS_BCD = 0b0011_1111; + } + } + + const ABRTCMC_DAYS: u8 = 0x6; + // no bitflags, days are BCD whole register + + const ABRTCMC_WEEKDAYS: u8 = 0x7; + bitflags! { + pub struct Weekdays: u8 { + const SUNDAY = 0b000; + const MONDAY = 0b001; + const TUESDAY = 0b010; + const WEDNESDAY= 0b011; + const THURSDAY = 0b100; + const FRIDAY = 0b101; + const SATURDAY = 0b110; + } + } + + const ABRTCMC_MONTHS: u8 = 0x8; + bitflags! { + pub struct Months: u8 { // BCD "months" + const JANUARY = 0b0_0001; + const FEBRUARY = 0b0_0010; + const MARCH = 0b0_0011; + const APRIL = 0b0_0100; + const MAY = 0b0_0101; + const JUNE = 0b0_0110; + const JULY = 0b0_0111; + const AUGUST = 0b0_1000; + const SEPTEMBER = 0b0_1001; + const OCTOBER = 0b1_0000; + const NOVEMBER = 0b1_0001; + const DECEMBER = 0b1_0010; + } + } + + const ABRTCMC_YEARS: u8 = 0x9; + // no bitflags, years are 00-99 in BCD format + + const ABRTCMC_MINUTE_ALARM: u8 = 0xA; + const ABRTCMC_HOUR_ALARM: u8 = 0xB; + const ABRTCMC_DAY_ALARM: u8 = 0xC; + const ABRTCMC_WEEKDAY_ALARM: u8 = 0xD; + bitflags! { + pub struct Alarm: u8 { + const ENABLE = 0b1000_0000; + // all others code minute/hour/day/weekday in BCD LSBs + const HR12_PM_FLAG = 0b0010_0000; // only used in hours alarm, 12-hour mode + } + } + + const ABRTCMC_CONFIG: u8 = 0xF; + bitflags! { + pub struct Config: u8 { + const TIMER_B_ENABLE = 0b0000_0001; + const TIMER_A_WATCHDOG = 0b0000_0100; + const TIMER_A_COUNTDWN = 0b0000_0010; + const TIMER_A_DISABLE = 0b0000_0000; + const TIMER_A_DISABLE2 = 0b0000_0110; + + const CLKOUT_32768_HZ = 0b0000_0000; + const CLKOUT_16384_HZ = 0b0000_1000; + const CLKOUT_8192_HZ = 0b0001_0000; + const CLKOUT_4096_HZ = 0b0001_1000; + const CLKOUT_1024_HZ = 0b0010_0000; + const CLKOUT_32_HZ = 0b0010_1000; + const CLKOUT_1_HZ = 0b0011_0000; + const CLKOUT_DISABLE = 0b0011_1000; + + const TIMERB_INT_PULSED = 0b0100_0000; + const TIMERA_SECONDS_INT_PULSED = 0b1000_0000; + } + } + + const ABRTCMC_TIMERA_CLK: u8 = 0x10; + const ABRTCMC_TIMERB_CLK: u8 = 0x12; + bitflags! { + pub struct TimerClk: u8 { + const CLK_3600_S = 0b0000_0100; + const CLK_60_S = 0b0000_0011; + const CLK_1_S = 0b0000_0010; + const CLK_64_HZ = 0b0000_0001; // 15.625ms + const CLK_4096_HZ = 0b0000_0000; // 0.2441ms + + const PULSE_46_MS = 0b0000_0000; + const PULSE_62_MS = 0b0001_0000; + const PULSE_78_MS = 0b0010_0000; + const PULSE_93_MS = 0b0011_0000; + const PULSE_125_MS = 0b0100_0000; + const PULSE_156_MS = 0b0101_0000; + const PULSE_187_MS = 0b0110_0000; + const PULSE_218_MS = 0b0111_0000; + } + } + + const ABRTCMC_TIMERA: u8 = 0x11; + // no bitflags, register is timer period in seconds, and the period is N / (source clock frequency) + const ABRTCMC_TIMERB: u8 = 0x13; + // no bitflags, register is timer period in seconds, and the period is N / (source clock frequency) + + /// convert binary to BCD + fn to_bcd(binary: u8) -> u8 { + let mut lsd: u8 = binary % 10; + if lsd > 9 { + lsd = 9; + } + let mut msd: u8 = binary / 10; + if msd > 9 { + msd = 9; + } + + (msd << 4) | lsd + } + + fn to_binary(bcd: u8) -> u8 { + (bcd & 0xf) + ((bcd >> 4) * 10) + } + + fn to_weekday(bcd: u8) -> Weekdays { + match bcd { + 0 => Weekdays::SUNDAY, + 1 => Weekdays::MONDAY, + 2 => Weekdays::TUESDAY, + 3 => Weekdays::WEDNESDAY, + 4 => Weekdays::THURSDAY, + 5 => Weekdays::FRIDAY, + 6 => Weekdays::SATURDAY, + _ => Weekdays::SUNDAY, + } + } + + pub struct Rtc { + pub seconds: u8, + pub minutes: u8, + pub hours: u8, + pub days: u8, + pub months: u8, + pub years: u8, + pub weekday: Weekdays, + updated_ticks: u64, + } + + impl Rtc { + pub fn new() -> Rtc { + info!("RTC: hardware initialized"); + + Rtc { + seconds: 0, + minutes: 0, + hours: 0, + days: 0, + months: 0, + years: 0, + weekday: Weekdays::SUNDAY, + updated_ticks: 0, + } + } + + + /// we only support 24 hour mode + /// TODO: sanity check arguments + /// TODO: write accesses should happen in a single block, to guarante atomicity of the operation + pub fn rtc_set(&mut self, secs: u8, mins: u8, hours: u8, days: u8, months: u8, years: u8, d: Weekdays) -> bool { + let mut txbuf: [u8; 2]; + + // make sure battery switchover is enabled, otherwise we won't keep time when power goes off + txbuf = [ABRTCMC_CONTROL3, (Control3::BATT_STD_BL_EN).bits()]; + i2c_controller(&self.p, ABRTCMC_I2C_ADR, Some(&txbuf), None, I2C_TIMEOUT); + + txbuf = [ABRTCMC_SECONDS, to_bcd(secs)]; + i2c_controller(&self.p, ABRTCMC_I2C_ADR, Some(&txbuf), None, I2C_TIMEOUT); + self.updated_ticks = get_ticks(&self.p); + self.seconds = secs; + + txbuf = [ABRTCMC_MINUTES, to_bcd(mins)]; + i2c_controller(&self.p, ABRTCMC_I2C_ADR, Some(&txbuf), None, I2C_TIMEOUT); + self.minutes = mins; + + txbuf = [ABRTCMC_HOURS, to_bcd(hours)]; + i2c_controller(&self.p, ABRTCMC_I2C_ADR, Some(&txbuf), None, I2C_TIMEOUT); + self.hours = hours; + + txbuf = [ABRTCMC_DAYS, to_bcd(days)]; + i2c_controller(&self.p, ABRTCMC_I2C_ADR, Some(&txbuf), None, I2C_TIMEOUT); + self.days = days; + + txbuf = [ABRTCMC_MONTHS, to_bcd(months)]; + i2c_controller(&self.p, ABRTCMC_I2C_ADR, Some(&txbuf), None, I2C_TIMEOUT); + self.months = months; + + txbuf = [ABRTCMC_YEARS, to_bcd(years)]; + i2c_controller(&self.p, ABRTCMC_I2C_ADR, Some(&txbuf), None, I2C_TIMEOUT); + self.years = years; + + txbuf = [ABRTCMC_WEEKDAYS, d.bits()]; + i2c_controller(&self.p, ABRTCMC_I2C_ADR, Some(&txbuf), None, I2C_TIMEOUT); + self.weekday = d; + + true // sanity check args would return false on fail + } + + pub fn rtc_update(&mut self) { + let txbuf: [u8; 1]; + let mut rxbuf: [u8; 7] = [0; 7]; + + // only update from RTC if more than 1 second has passed since the last update + if get_ticks(&self.p) - self.updated_ticks > 1000 { + // read as a single block to make the time readout atomic + txbuf = [ABRTCMC_SECONDS]; + i2c_controller(&self.p, ABRTCMC_I2C_ADR, Some(&txbuf), Some(&mut rxbuf), I2C_TIMEOUT); + + self.seconds = to_binary(rxbuf[0] & 0x7f); + self.minutes = to_binary(rxbuf[1] & 0x7f); + self.hours = to_binary(rxbuf[2] & 0x3f); + self.days = to_binary(rxbuf[3] & 0x3f); + self.weekday = to_weekday(rxbuf[4] & 0x7f); + self.months = to_binary(rxbuf[5] & 0x1f); + self.years = to_binary(rxbuf[6]); + + self.updated_ticks = get_ticks(&self.p); + } + } + + /// testing-only routine -- wakeup self after designated number of seconds + pub fn wakeup_alarm(&mut self, seconds: u8) { + let mut txbuf: [u8; 2]; + + // make sure battery switchover is enabled + txbuf = [ABRTCMC_CONTROL3, (Control3::BATT_STD_BL_EN).bits()]; + i2c_controller(&self.p, ABRTCMC_I2C_ADR, Some(&txbuf), None, I2C_TIMEOUT); + + // set clock units to 1 second, output pulse length to ~218ms + txbuf = [ABRTCMC_TIMERB_CLK, (TimerClk::CLK_1_S | TimerClk::PULSE_218_MS).bits()]; + i2c_controller(&self.p, ABRTCMC_I2C_ADR, Some(&txbuf), None, I2C_TIMEOUT); + + // program elapsed time + txbuf = [ABRTCMC_TIMERB, seconds]; + i2c_controller(&self.p, ABRTCMC_I2C_ADR, Some(&txbuf), None, I2C_TIMEOUT); + + // enable timerb countdown interrupt, also clears any prior interrupt flag + txbuf = [ABRTCMC_CONTROL2, (Control2::COUNTDOWN_B_INT).bits()]; + i2c_controller(&self.p, ABRTCMC_I2C_ADR, Some(&txbuf), None, I2C_TIMEOUT); + + // turn on the timer proper -- the system will restart in 5...4..3.... + txbuf = [ABRTCMC_CONFIG, (Config::TIMER_B_ENABLE | Config::CLKOUT_DISABLE).bits()]; + i2c_controller(&self.p, ABRTCMC_I2C_ADR, Some(&txbuf), None, I2C_TIMEOUT); + } + + pub fn clear_alarm(&mut self) { + // turn off RTC wakeup timer, in case previously set + let mut txbuf : [u8; 2] = [ABRTCMC_CONFIG, (Config::CLKOUT_DISABLE).bits()]; + i2c_controller(&self.p, ABRTCMC_I2C_ADR, Some(&txbuf), None, I2C_TIMEOUT); + + // clear all interrupts and flags + txbuf = [ABRTCMC_CONTROL2, 0]; + i2c_controller(&self.p, ABRTCMC_I2C_ADR, Some(&txbuf), None, I2C_TIMEOUT); + } + } +} + +// a stub to try to avoid breaking hosted mode for as long as possible. +#[cfg(not(target_os = "none"))] +mod implementation { + use log::info; + + pub struct Rtc { + pub seconds: u8, + pub minutes: u8, + pub hours: u8, + pub days: u8, + pub months: u8, + pub years: u8, + pub weekday: Weekdays, + updated_ticks: u64, + } + + impl Rtc { + pub fn new() -> Rtc { + Rtc { + seconds: 0, + minutes: 0, + hours: 0, + days: 0, + months: 0, + years: 0, + weekday: Weekdays::SUNDAY, + updated_ticks: 0, + } + } + + } +} + +#[xous::xous_main] +fn xmain() -> ! { + use crate::implementation::Rtc; + + log_server::init_wait().unwrap(); + info!("RTC: my PID is {}", xous::process::id()); + + let rtc_sid = xous_names::register_name(xous::names::SERVER_NAME_RTC).expect("RTC: can't register server"); + info!("RTC: registered with NS -- {:?}", rtc_sid); + + #[cfg(target_os = "none")] + let rtc = Rtc::new(); + + #[cfg(not(target_os = "none"))] + let mut rtc = Rtc::new(); + + info!("RTC: ready to accept requests"); + + loop { + let envelope = xous::receive_message(rtc_sid).unwrap(); + if let Ok(opcode) = Opcode::try_from(&envelope.body) { + match opcode { + Opcode::GetRtc(count) => { + let val: [u32; 2] = rtc.get_rtc(count); + xous::return_scalar2(envelope.sender, val[0] as _, val[1] as _) + .expect("RTC: couldn't return GetRtc request"); + }, + } + } else { + error!("KBD: couldn't convert opcode"); + } + } +} diff --git a/xous-rs/src/names.rs b/xous-rs/src/names.rs index 394d73af2..071ea843b 100644 --- a/xous-rs/src/names.rs +++ b/xous-rs/src/names.rs @@ -16,6 +16,7 @@ pub const SERVER_NAME_STATUS: &str = "_Status bar manager_"; pub const SERVER_NAME_IME_FRONT: &str = "_IME front end_"; pub const SERVER_NAME_IME_PLUGIN_SHELL: &str = "_IME shell plugin_"; pub const SERVER_NAME_SHELLCHAT: &str = "_Shell chat application_"; +pub const SERVER_NAME_RTC: &str = "_Real time clock application server_"; pub const SERVER_NAME_FCCAGENT: &str = "_Agent for EMC Testing_"; pub const SERVER_NAME_BENCHMARK: &str= "_Benchmark target_"; From 184a284da55dde306abc9c9fa783f534e98188b3 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 18 Mar 2021 17:34:48 +0800 Subject: [PATCH 04/27] sleep_ms() bug exhibitition --- services/shellchat/src/cmds/callback.rs | 4 ++-- services/ticktimer-server/src/api.rs | 23 +++++++++++++++++++++++ services/ticktimer-server/src/main.rs | 18 ++++++++++-------- 3 files changed, 35 insertions(+), 10 deletions(-) diff --git a/services/shellchat/src/cmds/callback.rs b/services/shellchat/src/cmds/callback.rs index 855e55203..c250cc6a7 100644 --- a/services/shellchat/src/cmds/callback.rs +++ b/services/shellchat/src/cmds/callback.rs @@ -12,7 +12,7 @@ pub fn callback_thread(_: u32) { if CB_RUN.load(Ordering::Relaxed) { CB_RUN.store(false, Ordering::Relaxed); - ticktimer_server::sleep_ms(ticktimer_conn, 2000).unwrap(); + ticktimer_server::sleep_ms(ticktimer_conn, 10000).unwrap(); // just send a bogus message xous::send_message(callback_conn, Message::Scalar(ScalarMessage{ id: 0xdeadbeef, arg1: 0, arg2: 0, arg3: 0, arg4: 0, @@ -38,7 +38,7 @@ impl CallBack { } impl<'a> ShellCmdApi<'a> for CallBack { - cmd_api!(callback); + cmd_api!(cb); fn process(&mut self, _args: String::<1024>, _env: &mut CommonEnv) -> Result>, xous::Error> { use core::fmt::Write; diff --git a/services/ticktimer-server/src/api.rs b/services/ticktimer-server/src/api.rs index 0cc34e78b..f0e7bc634 100644 --- a/services/ticktimer-server/src/api.rs +++ b/services/ticktimer-server/src/api.rs @@ -1,5 +1,10 @@ use xous::{Message, ScalarMessage}; +#[derive(Debug)] +pub struct TimerToken { + token: u64, // this field is 48 bits wide, random number +} + #[derive(Debug)] pub enum Opcode { /// Reset the timer @@ -13,6 +18,24 @@ pub enum Opcode { /// Recalculate the sleep time RecalculateSleep, +/* + ////////// new APIs + /// Subscribe to wakeup alarms. Takes in the server name that's subcribed, returns a Token to refer to the subscription. + SubscribeWakeup(xous::String::<64>), + + /// set an alarm in milliseconds, which is returned via the SubscribeWakeup registration token + WakeupAlarm(u16, TimerToken), + + /// The generic message that gets sent to other servers, at the alarm time + WakeupMessage, + + /// Request a blocking, in-line delay server -- returns a CID that can be used to send the BlockingDelayMs message + /// each request consumes a thread in the ticktimer that tracks & responds to a blockingdelay + RequestBlockingDelay, + + /// Do a blocking delay. Responds with the current ElapsedMs by default. + BlockingDelayMs(u32), + */ } impl<'a> core::convert::TryFrom<&'a Message> for Opcode { diff --git a/services/ticktimer-server/src/main.rs b/services/ticktimer-server/src/main.rs index 17baf5995..1bc2a4959 100644 --- a/services/ticktimer-server/src/main.rs +++ b/services/ticktimer-server/src/main.rs @@ -349,14 +349,16 @@ fn xmain() -> ! { .expect("TickTimer: couldn't return time request"); //info!("TickTimer: done returning value"); } - Opcode::SleepMs(ms) => recalculate_sleep( - &mut ticktimer, - &mut sleep_heap, - Some(SleepResponse { - msec: ms, - sender: envelope.sender, - }), - ), + Opcode::SleepMs(ms) => { + recalculate_sleep( + &mut ticktimer, + &mut sleep_heap, + Some(SleepResponse { + msec: ms, + sender: envelope.sender, + }), + ); + } Opcode::RecalculateSleep => { recalculate_sleep(&mut ticktimer, &mut sleep_heap, None); //info!("TickTimer: Done recalculating"); From 071f2047f83ea47407699a7f86ae7e82d901539b Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Thu, 18 Mar 2021 20:10:01 +0800 Subject: [PATCH 05/27] xous: return TID and PID from current_tid() and current_pid() These should return the raw values, rather than the Result values. Signed-off-by: Sean Cross --- xous-rs/src/process.rs | 2 +- xous-rs/src/syscall.rs | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/xous-rs/src/process.rs b/xous-rs/src/process.rs index c0357d85f..a7bde40d1 100644 --- a/xous-rs/src/process.rs +++ b/xous-rs/src/process.rs @@ -1,5 +1,5 @@ pub fn id() -> u32 { - if let Ok(crate::Result::ProcessID(pid)) = crate::syscall::current_pid() { + if let Ok(pid) = crate::syscall::current_pid() { pid.get() as u32 } else { 0 diff --git a/xous-rs/src/syscall.rs b/xous-rs/src/syscall.rs index 1c242b5b8..5143dc561 100644 --- a/xous-rs/src/syscall.rs +++ b/xous-rs/src/syscall.rs @@ -1,7 +1,7 @@ use crate::{ pid_from_usize, CpuID, Error, MemoryAddress, MemoryFlags, MemoryMessage, MemoryRange, MemorySize, MemoryType, Message, MessageEnvelope, MessageSender, ProcessArgs, ProcessInit, - Result, ScalarMessage, SysCallResult, ThreadInit, CID, PID, SID, + Result, ScalarMessage, SysCallResult, ThreadInit, CID, PID, SID, TID, }; use core::convert::TryInto; @@ -1406,10 +1406,10 @@ pub fn wait_process(joiner: crate::arch::ProcessHandle) -> SysCallResult { } /// Get the current process ID -pub fn current_pid() -> SysCallResult { +pub fn current_pid() -> core::result::Result { rsyscall(SysCall::GetProcessId).and_then(|result| { if let Result::ProcessID(pid) = result { - Ok(Result::ProcessID(pid)) + Ok(pid) } else { Err(Error::InternalError) } @@ -1417,10 +1417,10 @@ pub fn current_pid() -> SysCallResult { } /// Get the current thread ID -pub fn current_tid() -> SysCallResult { - rsyscall(SysCall::GetProcessId).and_then(|result| { +pub fn current_tid() -> core::result::Result { + rsyscall(SysCall::GetThreadId).and_then(|result| { if let Result::ThreadID(tid) = result { - Ok(Result::ThreadID(tid)) + Ok(tid) } else { Err(Error::InternalError) } From 27c35223cdbec2f5e9280f22acd955f9315cd371 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Thu, 18 Mar 2021 20:10:26 +0800 Subject: [PATCH 06/27] xous: run cargo-fmt Signed-off-by: Sean Cross --- xous-rs/src/syscall.rs | 47 +++++++++++++++++------------------------- 1 file changed, 19 insertions(+), 28 deletions(-) diff --git a/xous-rs/src/syscall.rs b/xous-rs/src/syscall.rs index 5143dc561..fd55cccfc 100644 --- a/xous-rs/src/syscall.rs +++ b/xous-rs/src/syscall.rs @@ -461,8 +461,9 @@ impl SysCall { 0, ] } - SysCall::CreateServerId => - [SysCallNumber::CreateServerId as usize, 0, 0, 0, 0, 0, 0, 0], + SysCall::CreateServerId => { + [SysCallNumber::CreateServerId as usize, 0, 0, 0, 0, 0, 0, 0] + } SysCall::ReturnToParent(a1, a2) => [ SysCallNumber::ReturnToParent as usize, a1.get() as usize, @@ -678,24 +679,8 @@ impl SysCall { 0, 0, ], - SysCall::GetThreadId => [SysCallNumber::GetThreadId as usize, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - ], - SysCall::GetProcessId => [SysCallNumber::GetProcessId as usize, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - ], + SysCall::GetThreadId => [SysCallNumber::GetThreadId as usize, 0, 0, 0, 0, 0, 0, 0], + SysCall::GetProcessId => [SysCallNumber::GetProcessId as usize, 0, 0, 0, 0, 0, 0, 0], SysCall::Invalid(a1, a2, a3, a4, a5, a6, a7) => [ SysCallNumber::Invalid as usize, *a1, @@ -905,7 +890,10 @@ impl SysCall { pub fn has_memory(&self) -> bool { match self { SysCall::TrySendMessage(_, msg) | SysCall::SendMessage(_, msg) => { - matches!(msg, Message::Move(_) | Message::Borrow(_) | Message::MutableBorrow(_)) + matches!( + msg, + Message::Move(_) | Message::Borrow(_) | Message::MutableBorrow(_) + ) } SysCall::ReturnMemory(_, _) => true, _ => false, @@ -963,13 +951,16 @@ impl SysCall { /// Returns `true` if the given syscall may be called from an IRQ context pub fn can_call_from_interrupt(&self) -> bool { - matches!(self, SysCall::TrySendMessage(_, _) - | SysCall::TryConnect(_) - | SysCall::TryReceiveMessage(_) - | SysCall::ReturnToParent(_, _) - | SysCall::ReturnScalar2(_, _, _) - | SysCall::ReturnScalar1(_, _) - | SysCall::ReturnMemory(_, _)) + matches!( + self, + SysCall::TrySendMessage(_, _) + | SysCall::TryConnect(_) + | SysCall::TryReceiveMessage(_) + | SysCall::ReturnToParent(_, _) + | SysCall::ReturnScalar2(_, _, _) + | SysCall::ReturnScalar1(_, _) + | SysCall::ReturnMemory(_, _) + ) } } From 751dc8ee3a3ba07cb733ddca8a4c1a38435a6638 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Thu, 18 Mar 2021 20:10:58 +0800 Subject: [PATCH 07/27] kernel-test: add test for ticktimer-server This test is an attempt to fix `sleep_ms()`. Signed-off-by: Sean Cross --- services/kernel-test/Cargo.toml | 6 +- services/kernel-test/src/main.rs | 372 +++++-------------------------- xtask/src/main.rs | 2 +- 3 files changed, 57 insertions(+), 323 deletions(-) diff --git a/services/kernel-test/Cargo.toml b/services/kernel-test/Cargo.toml index 743b522e3..92a814098 100644 --- a/services/kernel-test/Cargo.toml +++ b/services/kernel-test/Cargo.toml @@ -7,10 +7,12 @@ description = "Program to test various aspects of the kernel" [dependencies] xous = { path = "../../xous-rs" } +log-server = { path = "../log-server" } +ticktimer-server = { path = "../ticktimer-server" } +log = "0.4" [target.'cfg(not(any(windows,unix)))'.dependencies] utralib = { path = "../../utralib"} [features] -logging = [] # adding this allocates the UART for logging of Xous -default = ["logging"] +default = [] diff --git a/services/kernel-test/src/main.rs b/services/kernel-test/src/main.rs index b8242d049..cf580fffe 100644 --- a/services/kernel-test/src/main.rs +++ b/services/kernel-test/src/main.rs @@ -1,336 +1,68 @@ #![cfg_attr(target_os = "none", no_std)] #![cfg_attr(target_os = "none", no_main)] -#[cfg(baremetal)] -#[macro_use] -mod debug; - -use core::fmt::Write; -use xous::String; - -#[cfg(not(target_os = "none"))] -mod implementation { - use core::fmt::{Error, Write}; - use std::sync::mpsc::{channel, Receiver, Sender}; - - enum ControlMessage { - Text(String), - Byte(u8), - Exit, - } - - pub struct Output { - tx: Sender, - rx: Receiver, - stdout: std::io::Stdout, - } - - pub fn init() -> Output { - let (tx, rx) = channel(); - - Output { - tx, - rx, - stdout: std::io::stdout(), - } - } - - impl Output { - pub fn run(&mut self) { - use std::io::Write; - loop { - match self.rx.recv_timeout(std::time::Duration::from_millis(50)) { - Ok(msg) => match msg { - ControlMessage::Exit => break, - ControlMessage::Text(s) => print!("{}", s), - ControlMessage::Byte(s) => { - let mut handle = self.stdout.lock(); - handle.write_all(&[s]).unwrap(); - } - }, - Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {} - Err(e) => panic!("Error: {}", e), - } - } - } - - pub fn get_writer(&self) -> OutputWriter { - OutputWriter { - tx: self.tx.clone(), - } - } - } - - impl Drop for Output { - fn drop(&mut self) { - self.tx.send(ControlMessage::Exit).unwrap(); - } - } - - impl Write for Output { - fn write_str(&mut self, s: &str) -> Result<(), Error> { - // It would be nice if this worked with &str - self.tx.send(ControlMessage::Text(s.to_owned())).unwrap(); - Ok(()) - } - } - - pub struct OutputWriter { - tx: Sender, - } - - impl OutputWriter { - pub fn putc(&self, c: u8) { - self.tx.send(ControlMessage::Byte(c)).unwrap(); - } - } - - impl Write for OutputWriter { - fn write_str(&mut self, s: &str) -> Result<(), Error> { - // It would be nice if this worked with &str - self.tx.send(ControlMessage::Text(s.to_owned())).unwrap(); - Ok(()) - } - } +struct LoopArg { + msec: usize, } +// fn sleep_10_loop(_ign: usize) { +// let ticktimer_server_id = xous::SID::from_bytes(b"ticktimer-server").unwrap(); +// let ticktimer_conn = xous::connect(ticktimer_server_id).unwrap(); -#[cfg(target_os = "none")] -mod implementation { - use core::fmt::{Error, Write}; - use utralib::generated::*; +// let mut ms_count = 1; +// loop { +// log::info!("10ms Loop count {}", ms_count); +// sleep_ms(ticktimer_conn, 10).unwrap(); +// ms_count += 1; +// } +// } - pub struct Output {} +// fn sleep_5_loop(_ign: usize) { +// let ticktimer_server_id = xous::SID::from_bytes(b"ticktimer-server").unwrap(); +// let ticktimer_conn = xous::connect(ticktimer_server_id).unwrap(); - pub fn init() -> Output { - if cfg!(feature = "logging") { - let uart = xous::syscall::map_memory( - xous::MemoryAddress::new(utra::console::HW_CONSOLE_BASE), - None, - 4096, - xous::MemoryFlags::R | xous::MemoryFlags::W, - ) - .expect("couldn't map serial port"); - unsafe { crate::debug::DEFAULT_UART_ADDR = uart.as_mut_ptr() as _ }; - println!("Mapped UART @ {:08x}", uart.addr.get()); +// let mut ms_count = 1; +// loop { +// log::info!("5ms Loop count {}", ms_count); +// sleep_ms(ticktimer_conn, 5).unwrap(); +// ms_count += 1; +// } +// } - println!("Process: map success!"); - crate::debug::DEFAULT.enable_rx(); +fn sleep_loop(_arg: usize) { + let ticktimer_server_id = xous::SID::from_bytes(b"ticktimer-server").unwrap(); + let ticktimer_conn = xous::connect(ticktimer_server_id).unwrap(); + let tid = xous::current_tid().unwrap(); + let sleep_ms = match tid { + 2 => 2, + 3 => 5, + 4 => 10, + _ => panic!("Unknown TID"), + }; + log::info!("My thread number is {}, sleeping {} ms", tid, sleep_ms); - println!("Allocating IRQ..."); - xous::syscall::claim_interrupt( - utra::console::CONSOLE_IRQ, - handle_irq, - core::ptr::null_mut::(), - ) - .expect("couldn't claim interrupt"); - println!("Claimed IRQ {}", utra::console::CONSOLE_IRQ); - } - Output {} - } - - impl Output { - pub fn get_writer(&self) -> OutputWriter { - OutputWriter {} - } - - pub fn run(&mut self) { - loop { - xous::wait_event(); - } - } - } - - fn handle_irq(irq_no: usize, arg: *mut usize) { - if cfg!(feature = "logging") { - print!("Handling IRQ {} (arg: {:08x}): ", irq_no, arg as usize); - - while let Some(c) = crate::debug::DEFAULT.getc() { - print!("0x{:02x}", c); - } - println!(); - } - } - - pub struct OutputWriter {} - - impl OutputWriter { - pub fn putc(&self, c: u8) { - if cfg!(feature = "logging") { - let mut uart_csr = CSR::new(unsafe { crate::debug::DEFAULT_UART_ADDR as *mut u32 }); - - // Wait until TXFULL is `0` - while uart_csr.r(utra::uart::TXFULL) != 0 {} - uart_csr.wo(utra::uart::RXTX, c as u32); - } - } - } - - impl Write for OutputWriter { - fn write_str(&mut self, s: &str) -> Result<(), Error> { - for c in s.bytes() { - self.putc(c); - if c == '\n' as u8 { - self.putc('\r' as u8); - } - } - Ok(()) - } - } -} - -fn handle_scalar( - output: &mut implementation::OutputWriter, - sender: xous::MessageSender, - msg: &xous::ScalarMessage, - sender_pid: xous::PID, -) { - match msg.id { - 1000 => writeln!(output, "PANIC from PID {} | {}", sender_pid, sender).unwrap(), - 1100 => (), - 1101..=1132 => { - let mut output_bfr = [0u8; core::mem::size_of::() * 4]; - let output_iter = output_bfr.iter_mut(); - - // Combine the four arguments to form a single - // contiguous buffer. Note: The buffer size will change - // depending on the platfor's `usize` length. - let arg1_bytes = msg.arg1.to_le_bytes(); - let arg2_bytes = msg.arg2.to_le_bytes(); - let arg3_bytes = msg.arg3.to_le_bytes(); - let arg4_bytes = msg.arg4.to_le_bytes(); - let input_iter = arg1_bytes - .iter() - .chain(arg2_bytes.iter()) - .chain(arg3_bytes.iter()) - .chain(arg4_bytes.iter()); - for (dest, src) in output_iter.zip(input_iter) { - *dest = *src; - } - let total_chars = msg.id - 1100; - for (idx, c) in output_bfr.iter().enumerate() { - if idx >= total_chars { - break; - } - output.putc(*c); - } - } - 1200 => writeln!(output, "Terminating process").unwrap(), - _ => writeln!( - output, - "Unrecognized scalar message from {}: {:#?}", - sender, msg - ) - .unwrap(), - } -} - -fn reader_thread(mut output: implementation::OutputWriter) { - writeln!(output, "LOG: Xous Logging Server starting up...").unwrap(); - - writeln!(output, "LOG: ****************************************************************").unwrap(); - // time stamp isn't actually the time stamp of the build, unfortunately. It's the time stamp of the - // last time you managed to force a rebuild that also causes log-server to be rebuilt, not necessarily - // capturing the build time of the very most recent change! - // writeln!(output, "LOG: *** Built: {:49} ***", env!("VERGEN_BUILD_TIMESTAMP")).unwrap(); - writeln!(output, "LOG: ****************************************************************").unwrap(); - let server_addr = xous::create_server_with_address(b"xous-log-server ").unwrap(); - writeln!(output, "LOG: Server listening on address {:?}", server_addr).unwrap(); - - let mut counter: usize = 0; + let mut ms_count = 1; loop { - if counter.trailing_zeros() >= 12 { - writeln!(output, "LOG: Counter tick: {}", counter).unwrap(); - } - counter += 1; - // writeln!(output, "LOG: Waiting for an event...").unwrap(); - let mut envelope = - xous::syscall::receive_message(server_addr).expect("couldn't get address"); - let sender = envelope.sender; - // writeln!(output, "LOG: Got message envelope: {:?}", envelope).unwrap(); - match &mut envelope.body { - xous::Message::Scalar(msg) => handle_scalar(&mut output, sender, msg, envelope.sender.pid().unwrap()), - xous::Message::BlockingScalar(msg) => { - writeln!( - output, - "LOG: BlockingScalar message from {}: {:?}", - envelope.sender, msg - ) - .unwrap(); - } - xous::Message::Move(msg) => { - String::<4000>::from_message(msg) - .map(|log_entry: String<4000>| { - writeln!( - output, - "LOG: Moved log message from {}: {}", - sender, log_entry - ) - .unwrap() - }) - .or_else(|e| { - writeln!(output, "LOG: unable to convert Move message to str: {}", e) - }) - .ok(); - } - xous::Message::Borrow(msg) => { - String::<4000>::from_message(msg) - .map(|log_entry: String<4000>| writeln!(output, "{}", log_entry).unwrap()) - .or_else(|e| { - writeln!( - output, - "LOG: unable to convert Borrow message to str: {}", - e - ) - }) - .ok(); - } - xous::Message::MutableBorrow(msg) => { - String::<4000>::from_message(msg) - .map(|mut log_entry: String<4000>| { - writeln!( - output, - "LOG: Mutable borrowed log message from {} len {}:\n\r {}\n\r", - sender, - log_entry.len(), - log_entry, - ) - .unwrap(); - writeln!(log_entry, " << HELLO FROM THE SERVER").unwrap(); - }) - .or_else(|e| { - writeln!( - output, - "LOG: unable to convert MutableBorrow message to str: {}", - e - ) - }) - .ok(); - } - } - } -} - -fn writer_thread(_ignored: usize) { - let mut counter = 0; - loop { - let conn = xous::connect(xous::SID::from_bytes(b"xous-log-server ").unwrap()).unwrap(); - let mut buffer = xous::String::<4000>::new(); - write!(buffer, "Hello, myself! Loop: {}", counter).unwrap(); - buffer.lend(conn).unwrap(); - - counter += 1; + log::info!("{}ms Loop count {}", sleep_ms, ms_count); + ticktimer_server::sleep_ms(ticktimer_conn, sleep_ms).unwrap(); + ms_count += 1; } } #[xous::xous_main] fn test_main() -> ! { - let mut output = implementation::init(); - let writer = output.get_writer(); - println!("LOG: my PID is {}", xous::process::id()); - println!("LOG: Creating the reader thread"); - xous::create_thread_simple(reader_thread, writer).unwrap(); - xous::create_thread_simple(writer_thread, 0usize).unwrap(); - println!("LOG: Running the output"); - output.run(); - loop {} + log_server::init_wait().unwrap(); + // let ticktimer_server_id = xous::SID::from_bytes(b"ticktimer-server").unwrap(); + // let ticktimer_conn = xous::connect(ticktimer_server_id).unwrap(); + + xous::create_thread_simple(sleep_loop, 10).unwrap(); + xous::create_thread_simple(sleep_loop, 5).unwrap(); + xous::create_thread_simple(sleep_loop, 2).unwrap(); + + // let mut ms_count = 1; + loop { + xous::wait_event(); + // log::info!("Loop {}", ms_count); + // sleep_ms(ticktimer_conn, 1).unwrap(); + // ms_count += 1; + } } diff --git a/xtask/src/main.rs b/xtask/src/main.rs index f17566e6f..77507aead 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -74,7 +74,7 @@ fn try_main() -> Result<(), DynError> { let task = env::args().nth(1); match task.as_deref() { Some("renode-image") => renode_image(false, &hw_pkgs)?, - Some("renode-test") => renode_image(false, &["kernel-test"])?, + Some("renode-test") => renode_image(false, &["ticktimer-server", "log-server", "xous-names", "kernel-test"])?, Some("renode-image-debug") => renode_image(true, &hw_pkgs)?, Some("run") => run(false)?, Some("hw-image") => build_hw_image(false, env::args().nth(2), &hw_pkgs)?, From cb5efccdf87bbb0069e387f16f172558571df543 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Mon, 22 Mar 2021 22:23:03 +0800 Subject: [PATCH 08/27] emulation: ticktimer: fix spurious interrupt on init Due to a race condition, an IRQ was always fired when the timer was turned on. Force a recalculation of the IRQ state when the IRQ is turned on to avoid firing an interrupt when none should fire. Signed-off-by: Sean Cross --- emulation/peripherals/ticktimer.cs | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/emulation/peripherals/ticktimer.cs b/emulation/peripherals/ticktimer.cs index 3350b362c..4cb034876 100644 --- a/emulation/peripherals/ticktimer.cs +++ b/emulation/peripherals/ticktimer.cs @@ -47,12 +47,16 @@ namespace Antmicro.Renode.Peripherals.Timers private void UpdateInterrupts() { - if (this.irqStatus && this.irqEnabled.Value) + if ((Interlocked.Read(ref this.tickValue) >= (long)this.msleepTarget) && this.irqEnabled.Value) { this.irqPending.Value = true; } - this.Log(LogLevel.Noisy, "Setting IRQ: {0}", irqPending.Value); - IRQ.Set(irqPending.Value && irqEnabled.Value); + this.Log(LogLevel.Noisy, "Setting IRQ: {0} because tickValue {1} >= msleepTarget {2} ({3}) and irqEnabled = {4}", + irqPending.Value && this.irqEnabled.Value, + this.tickValue, + this.msleepTarget, + this.tickValue >= (long)this.msleepTarget, this.irqEnabled.Value); + IRQ.Set(this.irqPending.Value && this.irqEnabled.Value); } public long Size { get { return 0x20; } } @@ -88,7 +92,7 @@ namespace Antmicro.Renode.Peripherals.Timers .WithValueField(0, 32, name: "MsleepTarget1", writeCallback: (_, value) => { this.msleepTarget = (this.msleepTarget & 0x00000000ffffffff) | (value << 32); - this.Log(LogLevel.Noisy, "Setting sleep target 1: {0}, sleep target now: {1}", value, this.msleepTarget); + this.Log(LogLevel.Noisy, "Setting MsleepTarget1: {0}, sleep target now: {1}", value, this.msleepTarget); }, valueProviderCallback: _ => { @@ -101,7 +105,7 @@ namespace Antmicro.Renode.Peripherals.Timers writeCallback: (_, value) => { this.msleepTarget = (this.msleepTarget & 0xffffffff00000000) | (value & 0xffffffff); - this.Log(LogLevel.Noisy, "Setting sleep target 0: {0}, sleep target now: {1}", value, this.msleepTarget); + this.Log(LogLevel.Noisy, "Setting MsleepTarget0: {0}, sleep target now: {1}", value, this.msleepTarget); }, valueProviderCallback: _ => { From f3ed417c7ae03c5a349a66d54877999c338e6fab Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Mon, 22 Mar 2021 22:23:53 +0800 Subject: [PATCH 09/27] emulation: xous-release: add more debug examples Signed-off-by: Sean Cross --- emulation/xous-release.resc | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/emulation/xous-release.resc b/emulation/xous-release.resc index 4c2f41623..5699b2c58 100644 --- a/emulation/xous-release.resc +++ b/emulation/xous-release.resc @@ -22,10 +22,11 @@ machine LoadPlatformDescription @betrusted.repl machine StartGdbServer 3333 true showAnalyzer uart showAnalyzer uartconsole -showAnalyzer uartserver0 -showAnalyzer memlcd +# showAnalyzer uartserver0 +# showAnalyzer memlcd logLevel -1 kbd +# logLevel -1 ticktimer # The macro `reset` gets called implicitly when running `machine Reset` macro reset From 06a5997a459f44ef64b029be9f739df38411adbc Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Mon, 22 Mar 2021 22:27:53 +0800 Subject: [PATCH 10/27] kernel: debug: add wrap-print feature This feature works around a bug in Renode where unwrapped lines cause it to crash. This forces columns to be wrapped at 80 characters. Signed-off-by: Sean Cross --- kernel/src/debug.rs | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/kernel/src/debug.rs b/kernel/src/debug.rs index 8b2c1f463..afba24bec 100644 --- a/kernel/src/debug.rs +++ b/kernel/src/debug.rs @@ -6,9 +6,6 @@ use core::fmt::{Error, Write}; #[cfg(baremetal)] use utralib::generated::*; -#[allow(dead_code)] // this is unused in hosted mode, kill the warning -static mut INITIALIZED: bool = false; - #[macro_use] #[cfg(all( not(test), @@ -66,6 +63,11 @@ macro_rules! println pub struct Uart { // pub base: *mut usize, } +#[cfg(baremetal)] +static mut INITIALIZED: bool = false; + +#[cfg(all(baremetal, feature = "wrap-print"))] +static mut CHAR_COUNT: usize = 0; #[cfg(baremetal)] impl Uart { @@ -86,6 +88,23 @@ impl Uart { while uart_csr.r(utra::uart::TXFULL) != 0 { () } + #[cfg(feature = "wrap-print")] + unsafe { + if c == b'\n' { + CHAR_COUNT = 0; + } else if CHAR_COUNT > 80 { + CHAR_COUNT = 0; + self.putc(b'\n'); + self.putc(b'\r'); + self.putc(b' '); + self.putc(b' '); + self.putc(b' '); + self.putc(b' '); + } + else { + CHAR_COUNT += 1; + } + } uart_csr.wfo(utra::uart::RXTX_RXTX, c as u32); } From eb4ab4ca3512c25537c620bc463ab68949df6e54 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Tue, 23 Mar 2021 19:34:53 +0800 Subject: [PATCH 11/27] kernel: main: ignore interrupts in main loop When the kernel is running its main loop, interrupts are disabled as it is running in supervisor mode. As a result, we can ignore any interrupt enabling/disabling that may need to occur. Signed-off-by: Sean Cross --- kernel/src/main.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/kernel/src/main.rs b/kernel/src/main.rs index 2a9b61dd7..1c3d82cf3 100644 --- a/kernel/src/main.rs +++ b/kernel/src/main.rs @@ -153,9 +153,7 @@ pub extern "C" fn kmain() { } loop { - arch::irq::disable_all_irqs(); pid = next_pid_to_run(pid); - arch::irq::enable_all_irqs(); match pid { Some(pid) => { From 6e290500db6855e821936716061187b04f9339f8 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Tue, 23 Mar 2021 19:38:48 +0800 Subject: [PATCH 12/27] kernel: riscv: fix wfi handling for interrupts Keep interrupts nominally disabled in supervisor mode, and only enable them for a brief period after WFI hits. If an interrupt occurs, then WFI becomes a NOP. The `idle()` function is only called when no more processes are running, which happens when all processes are waiting for an interrupt. Therefore, enable interrupts for a brief period when WFI returns in order to drain all pending interrupts and return to the caller to handle any change in the process table. Signed-off-by: Sean Cross --- kernel/src/arch/riscv.rs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/kernel/src/arch/riscv.rs b/kernel/src/arch/riscv.rs index a1a15138d..df6885888 100644 --- a/kernel/src/arch/riscv.rs +++ b/kernel/src/arch/riscv.rs @@ -19,7 +19,6 @@ pub fn current_pid() -> PID { pub fn init() { unsafe { - sstatus::set_sie(); sie::set_ssoft(); sie::set_sext(); } @@ -29,6 +28,21 @@ pub fn init() { /// Put the core to sleep until an interrupt hits. Returns `true` /// to indicate the kernel should not exit. pub fn idle() -> bool { + + // Issue `wfi`. This will return as soon as an external interrupt + // is available. unsafe { riscv::asm::wfi() }; + + // Enable interrupts temporarily in Supervisor mode, allowing them + // to drain. Aside from this brief instance, interrupts are + // disabled when running in Supervisor mode. + // + // These interrupts are handled by userspace, so code execution will + // immediately jump to the interrupt handler and return here after + // all interrupts have been handled. + unsafe { + sstatus::set_sie(); + sstatus::clear_sie(); + }; true } From 6987df997dadc78fb5ff105f0231a88a769a0f5f Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Tue, 23 Mar 2021 19:40:56 +0800 Subject: [PATCH 13/27] kernel: irq: don't disable interrupts when claiming irq When claiming an IRQ, we used to disable interrupts. This is unnecessary, as interrupts are already disabled when running in kernel mode. Signed-off-by: Sean Cross --- kernel/src/irq.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/kernel/src/irq.rs b/kernel/src/irq.rs index 3d99179b1..056e6456f 100644 --- a/kernel/src/irq.rs +++ b/kernel/src/irq.rs @@ -53,7 +53,6 @@ pub fn interrupt_claim( // Unsafe is required since we're accessing a static mut array. // However, we disable interrupts to prevent contention on this array. unsafe { - arch::irq::disable_all_irqs(); let result = if irq > IRQ_HANDLERS.len() { Err(xous_kernel::Error::InterruptNotFound) } else if IRQ_HANDLERS[irq].is_some() { @@ -63,7 +62,6 @@ pub fn interrupt_claim( arch::irq::enable_irq(irq); Ok(()) }; - arch::irq::enable_all_irqs(); result } } From ccc7264b797a2762dbef76207be00b81ac4ab159 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Tue, 23 Mar 2021 19:42:33 +0800 Subject: [PATCH 14/27] kernel: main: use iterator when printing processes This avoids a C-style for() loop. Signed-off-by: Sean Cross --- kernel/src/main.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/kernel/src/main.rs b/kernel/src/main.rs index 1c3d82cf3..5e12efa48 100644 --- a/kernel/src/main.rs +++ b/kernel/src/main.rs @@ -168,8 +168,10 @@ pub extern "C" fn kmain() { #[cfg(feature = "debug-print")] SystemServices::with(|system_services| { - for test_idx in 0..system_services.processes.len() { - println!("{:?}", system_services.processes[test_idx]); + for (test_idx, process) in system_services.processes.iter().enumerate() { + if ! process.free() { + println!("PID {}: {:?}", test_idx + 1, process); + } } }); From 9ab5b4880f5f65fd19beb3e226a890fe287fbb2e Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Tue, 23 Mar 2021 19:45:32 +0800 Subject: [PATCH 15/27] kernel: server: allow taking multiple messages from queue Previously, we would only look at the top item on the server queue. If it was not a known message, we would return an error. This patch changes this behavior to look through the entire queue for something we can take, and then clean it up as we go along. This allow for having outstanding requests in the queue an forms the backbone of the sleep server. Signed-off-by: Sean Cross --- kernel/src/server.rs | 477 ++++++++++++++++++++++++------------------- 1 file changed, 268 insertions(+), 209 deletions(-) diff --git a/kernel/src/server.rs b/kernel/src/server.rs index 0e47b8960..75d45771d 100644 --- a/kernel/src/server.rs +++ b/kernel/src/server.rs @@ -387,17 +387,26 @@ impl Server { } } *current_val = QueuedMessage::Empty; - self.queue_tail += 1; - if self.queue_tail >= self.queue.len() { - self.queue_tail = 0; + if idx == self.queue_tail { + self.queue_tail += 1; + if self.queue_tail >= self.queue.len() { + self.queue_tail = 0; + } + // Advance the pointer in case we have a long string of Empty messages. + while self.queue_tail != self.queue_head && self.queue[self.queue_tail] == QueuedMessage::Empty { + self.queue_tail += 1; + if self.queue_tail >= self.queue.len() { + self.queue_tail = 0; + } + } } // Destructure the PID and context ID from the `pid_tid` field - klog!( - "taking waiting message and returning to pid: {} tid: {}", - pid, - tid - ); + // klog!( + // "taking waiting message and returning to pid: {} tid: {}", + // pid, + // tid + // ); if !is_memory { return Ok(WaitingMessage::ScalarMessage( @@ -442,219 +451,259 @@ impl Server { /// * **None**: There are no waiting messages /// ***Some(MessageEnvelope): This message is queued. pub fn take_next_message(&mut self, sidx: usize) -> Option { - // println!( + // klog!( // "queue_head: ((({}))) queue_tail: ((({}))): {:?} CID: ((({})))", - // self.queue_head, self.queue_tail, self.queue[self.queue_tail], sidx + // self.queue_head, + // self.queue_tail, + // self.queue[self.queue_tail], + // sidx // ); use core::convert::TryInto; - let mut sender = SenderID::new(sidx, self.queue_tail, None); - let (result, response) = match self.queue[self.queue_tail] { - QueuedMessage::Empty => return None, - QueuedMessage::WaitingReturnMemory(_, _, _, _, _) => return None, - QueuedMessage::WaitingForget(_, _, _, _, _) => return None, - QueuedMessage::WaitingReturnScalar(_, _, _) => return None, - QueuedMessage::MemoryMessageROLend( - pid, - tid, - client_addr, - id, - buf, - buf_size, - offset, - valid, - ) => { - sender.pid = PID::new(pid.try_into().unwrap()); - ( - xous_kernel::MessageEnvelope { - sender: sender.into(), - body: xous_kernel::Message::Borrow(xous_kernel::MemoryMessage { - id, - buf: MemoryRange::new(buf, buf_size).ok()?, - offset: MemorySize::new(offset), - valid: MemorySize::new(valid), - }), - }, - QueuedMessage::WaitingReturnMemory(pid, tid, buf, client_addr, buf_size), - ) - } - QueuedMessage::MemoryMessageRWLend( - pid, - tid, - client_addr, - id, - buf, - buf_size, - offset, - valid, - ) => { - sender.pid = PID::new(pid.try_into().unwrap()); - ( - xous_kernel::MessageEnvelope { - sender: sender.into(), - body: xous_kernel::Message::MutableBorrow(xous_kernel::MemoryMessage { - id, - buf: MemoryRange::new(buf, buf_size).ok()?, - offset: MemorySize::new(offset), - valid: MemorySize::new(valid), - }), - }, - QueuedMessage::WaitingReturnMemory(pid, tid, buf, client_addr, buf_size), - ) - } - QueuedMessage::MemoryMessageROLendTerminated( - pid, - tid, - client_addr, - id, - buf, - buf_size, - offset, - valid, - ) => { - sender.pid = PID::new(pid.try_into().unwrap()); - ( - xous_kernel::MessageEnvelope { - sender: sender.into(), - body: xous_kernel::Message::Borrow(xous_kernel::MemoryMessage { - id, - buf: MemoryRange::new(buf, buf_size).ok()?, - offset: MemorySize::new(offset), - valid: MemorySize::new(valid), - }), - }, - QueuedMessage::WaitingReturnMemory(pid, tid, buf, client_addr, buf_size), - ) - } - QueuedMessage::MemoryMessageRWLendTerminated( - pid, - tid, - client_addr, - id, - buf, - buf_size, - offset, - valid, - ) => { - sender.pid = PID::new(pid.try_into().unwrap()); - ( - xous_kernel::MessageEnvelope { - sender: sender.into(), - body: xous_kernel::Message::MutableBorrow(xous_kernel::MemoryMessage { - id, - buf: MemoryRange::new(buf, buf_size).ok()?, - offset: MemorySize::new(offset), - valid: MemorySize::new(valid), - }), - }, - QueuedMessage::WaitingReturnMemory(pid, tid, buf, client_addr, buf_size), - ) - } + let mut queue_idx = self.queue_tail; + while queue_idx != self.queue_head { + let mut sender = SenderID::new(sidx, queue_idx, None); + // klog!("Message @ server.queue[{}]: {:?}", queue_idx, self.queue[queue_idx]); + let (result, response) = match self.queue[queue_idx] { + QueuedMessage::Empty => { + queue_idx += 1; + if queue_idx >= self.queue.len() { + queue_idx = 0; + } + continue; + } + QueuedMessage::WaitingReturnMemory(_, _, _, _, _) => { + queue_idx += 1; + if queue_idx >= self.queue.len() { + queue_idx = 0; + } + continue; + } + QueuedMessage::WaitingForget(_, _, _, _, _) => { + queue_idx += 1; + if queue_idx >= self.queue.len() { + queue_idx = 0; + } + continue; + } + QueuedMessage::WaitingReturnScalar(_, _, _) => { + queue_idx += 1; + if queue_idx >= self.queue.len() { + queue_idx = 0; + } + continue; + } + QueuedMessage::MemoryMessageROLend( + pid, + tid, + client_addr, + id, + buf, + buf_size, + offset, + valid, + ) => { + sender.pid = PID::new(pid.try_into().unwrap()); + ( + xous_kernel::MessageEnvelope { + sender: sender.into(), + body: xous_kernel::Message::Borrow(xous_kernel::MemoryMessage { + id, + buf: MemoryRange::new(buf, buf_size).ok()?, + offset: MemorySize::new(offset), + valid: MemorySize::new(valid), + }), + }, + QueuedMessage::WaitingReturnMemory(pid, tid, buf, client_addr, buf_size), + ) + } + QueuedMessage::MemoryMessageRWLend( + pid, + tid, + client_addr, + id, + buf, + buf_size, + offset, + valid, + ) => { + sender.pid = PID::new(pid.try_into().unwrap()); + ( + xous_kernel::MessageEnvelope { + sender: sender.into(), + body: xous_kernel::Message::MutableBorrow(xous_kernel::MemoryMessage { + id, + buf: MemoryRange::new(buf, buf_size).ok()?, + offset: MemorySize::new(offset), + valid: MemorySize::new(valid), + }), + }, + QueuedMessage::WaitingReturnMemory(pid, tid, buf, client_addr, buf_size), + ) + } + QueuedMessage::MemoryMessageROLendTerminated( + pid, + tid, + client_addr, + id, + buf, + buf_size, + offset, + valid, + ) => { + sender.pid = PID::new(pid.try_into().unwrap()); + ( + xous_kernel::MessageEnvelope { + sender: sender.into(), + body: xous_kernel::Message::Borrow(xous_kernel::MemoryMessage { + id, + buf: MemoryRange::new(buf, buf_size).ok()?, + offset: MemorySize::new(offset), + valid: MemorySize::new(valid), + }), + }, + QueuedMessage::WaitingReturnMemory(pid, tid, buf, client_addr, buf_size), + ) + } + QueuedMessage::MemoryMessageRWLendTerminated( + pid, + tid, + client_addr, + id, + buf, + buf_size, + offset, + valid, + ) => { + sender.pid = PID::new(pid.try_into().unwrap()); + ( + xous_kernel::MessageEnvelope { + sender: sender.into(), + body: xous_kernel::Message::MutableBorrow(xous_kernel::MemoryMessage { + id, + buf: MemoryRange::new(buf, buf_size).ok()?, + offset: MemorySize::new(offset), + valid: MemorySize::new(valid), + }), + }, + QueuedMessage::WaitingReturnMemory(pid, tid, buf, client_addr, buf_size), + ) + } - QueuedMessage::BlockingScalarMessage( - pid, - tid, - client_addr, - id, - arg1, - arg2, - arg3, - arg4, - ) => { - sender.pid = PID::new(pid.try_into().unwrap()); - ( - xous_kernel::MessageEnvelope { + QueuedMessage::BlockingScalarMessage( + pid, + tid, + client_addr, + id, + arg1, + arg2, + arg3, + arg4, + ) => { + sender.pid = PID::new(pid.try_into().unwrap()); + ( + xous_kernel::MessageEnvelope { + sender: sender.into(), + body: xous_kernel::Message::BlockingScalar( + xous_kernel::ScalarMessage { + id, + arg1, + arg2, + arg3, + arg4, + }, + ), + }, + QueuedMessage::WaitingReturnScalar(pid, tid, client_addr), + ) + } + QueuedMessage::MemoryMessageSend( + pid, + _tid, + _reserved, + id, + buf, + buf_size, + offset, + valid, + ) => { + sender.pid = PID::new(pid.try_into().unwrap()); + let msg = xous_kernel::MessageEnvelope { sender: sender.into(), - body: xous_kernel::Message::BlockingScalar(xous_kernel::ScalarMessage { + body: xous_kernel::Message::Move(xous_kernel::MemoryMessage { + id, + buf: MemoryRange::new(buf, buf_size).ok()?, + offset: MemorySize::new(offset), + valid: MemorySize::new(valid), + }), + }; + self.queue[queue_idx] = QueuedMessage::Empty; + if queue_idx == self.queue_tail { + self.queue_tail += 1; + if self.queue_tail >= self.queue.len() { + self.queue_tail = 0; + } + } + return Some(msg); + } + + // Scalar messages have nothing to return, so they can go straight to the `Free` state + QueuedMessage::ScalarMessage(pid, _tid, _reserved, id, arg1, arg2, arg3, arg4) => { + sender.pid = PID::new(pid.try_into().unwrap()); + let msg = xous_kernel::MessageEnvelope { + sender: sender.into(), + body: xous_kernel::Message::Scalar(xous_kernel::ScalarMessage { id, arg1, arg2, arg3, arg4, }), - }, - QueuedMessage::WaitingReturnScalar(pid, tid, client_addr), - ) - } - QueuedMessage::MemoryMessageSend( - pid, - _tid, - _reserved, - id, - buf, - buf_size, - offset, - valid, - ) => { - sender.pid = PID::new(pid.try_into().unwrap()); - let msg = xous_kernel::MessageEnvelope { - sender: sender.into(), - body: xous_kernel::Message::Move(xous_kernel::MemoryMessage { - id, - buf: MemoryRange::new(buf, buf_size).ok()?, - offset: MemorySize::new(offset), - valid: MemorySize::new(valid), - }), - }; - self.queue[self.queue_tail] = QueuedMessage::Empty; - self.queue_tail += 1; - if self.queue_tail >= self.queue.len() { - self.queue_tail = 0; + }; + self.queue[queue_idx] = QueuedMessage::Empty; + if queue_idx == self.queue_tail { + self.queue_tail += 1; + if self.queue_tail >= self.queue.len() { + self.queue_tail = 0; + } + } + return Some(msg); } - return Some(msg); - } + QueuedMessage::BlockingScalarTerminated( + pid, + _tid, + _reserved, + id, + arg1, + arg2, + arg3, + arg4, + ) => { + sender.pid = PID::new(pid.try_into().unwrap()); + let msg = xous_kernel::MessageEnvelope { + sender: sender.into(), + body: xous_kernel::Message::Scalar(xous_kernel::ScalarMessage { + id, + arg1, + arg2, + arg3, + arg4, + }), + }; + self.queue[queue_idx] = QueuedMessage::Empty; + if queue_idx == self.queue_tail { + self.queue_tail += 1; + if self.queue_tail >= self.queue.len() { + self.queue_tail = 0; + } + } + return Some(msg); + } + }; - // Scalar messages have nothing to return, so they can go straight to the `Free` state - QueuedMessage::ScalarMessage(pid, _tid, _reserved, id, arg1, arg2, arg3, arg4) => { - sender.pid = PID::new(pid.try_into().unwrap()); - let msg = xous_kernel::MessageEnvelope { - sender: sender.into(), - body: xous_kernel::Message::Scalar(xous_kernel::ScalarMessage { - id, - arg1, - arg2, - arg3, - arg4, - }), - }; - self.queue[self.queue_tail] = QueuedMessage::Empty; - self.queue_tail += 1; - if self.queue_tail >= self.queue.len() { - self.queue_tail = 0; - } - return Some(msg); - } - QueuedMessage::BlockingScalarTerminated( - pid, - _tid, - _reserved, - id, - arg1, - arg2, - arg3, - arg4, - ) => { - sender.pid = PID::new(pid.try_into().unwrap()); - let msg = xous_kernel::MessageEnvelope { - sender: sender.into(), - body: xous_kernel::Message::Scalar(xous_kernel::ScalarMessage { - id, - arg1, - arg2, - arg3, - arg4, - }), - }; - self.queue[self.queue_tail] = QueuedMessage::Empty; - self.queue_tail += 1; - if self.queue_tail >= self.queue.len() { - self.queue_tail = 0; - } - return Some(msg); - } - }; - - self.queue[self.queue_tail] = response; - Some(result) + self.queue[queue_idx] = response; + return Some(result); + } + None } /// Add the given message to this server's queue. @@ -669,7 +718,12 @@ impl Server { message: xous_kernel::Message, original_address: Option, ) -> core::result::Result { - // println!("Queueing message: {:?} for pid: {} tid: {}", message, pid.get(), context); + // klog!( + // "Queueing message: {:?} for pid: {} tid: {}", + // message, + // pid.get(), + // context + // ); if self.queue[self.queue_head] != QueuedMessage::Empty { return Err(xous_kernel::Error::ServerQueueFull); } @@ -732,6 +786,11 @@ impl Server { if self.queue_head >= self.queue.len() { self.queue_head = 0; } + // klog!( + // "queue head: {} queue_tail: {}", + // self.queue_head, + // self.queue_tail + // ); Ok(idx) } From 00e7f071877238503424e7385ea57001cc324924 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Tue, 23 Mar 2021 19:50:12 +0800 Subject: [PATCH 16/27] kernel: services: remember new thread if specified If we switch to a thread and specify a thread ID, remember that as the current thread ID. This prevents thread starvation by repeatedly going back to the same thread ID. Signed-off-by: Sean Cross --- kernel/src/services.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/kernel/src/services.rs b/kernel/src/services.rs index d56cabcd3..1d02649c5 100644 --- a/kernel/src/services.rs +++ b/kernel/src/services.rs @@ -854,13 +854,15 @@ impl SystemServices { } } new.current_thread = new_tid as _; - // println!(" -- picked thread {}", new_tid); + klog!("picked thread ID {}", new_tid); } else if x & (1 << new_tid) == 0 { // println!( // "thread is {:?}, which is not valid for new thread {}", // new.state, new_tid // ); return Err(xous_kernel::Error::ProcessNotFound); + } else { + new.current_thread = new_tid as _; } } ProcessState::Sleeping => { From 0d77f704a98822255342f9c4a0a40aa9e9e81299 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Tue, 23 Mar 2021 19:51:33 +0800 Subject: [PATCH 17/27] kernel: services: run cargo fmt on this file Minor text reformatting. Signed-off-by: Sean Cross --- kernel/src/services.rs | 78 +++++++++++++++++++++++++----------------- 1 file changed, 46 insertions(+), 32 deletions(-) diff --git a/kernel/src/services.rs b/kernel/src/services.rs index 1d02649c5..cdd614914 100644 --- a/kernel/src/services.rs +++ b/kernel/src/services.rs @@ -717,7 +717,7 @@ impl SystemServices { /// If the current process is not running. pub fn switch_from_thread(&mut self, pid: PID, tid: TID) -> Result<(), xous_kernel::Error> { let process = self.get_process_mut(pid)?; - // println!( + // klog!( // "switch_from_thread({}:{}): Old state was {:?}", // pid, tid, process.state // ); @@ -750,7 +750,7 @@ impl SystemServices { ); }, }; - // println!( + // klog!( // "switch_from_thread({}:{}): New state is {:?}", // pid, tid, process.state // ); @@ -810,14 +810,12 @@ impl SystemServices { ) -> Result { let previous_pid = self.current_pid(); - let debug = false; - if debug { - println!( - "\n\r KERNEL({},{}): Activating process {} thread {}", - previous_pid, previous_tid, new_pid, new_tid - ); - //ArchProcess::with_current(|current| current.print_thread()); + if new_tid != 0 { + klog!("Activating process {} thread {}", new_pid, new_tid); + } else { + klog!("Activating process {} thread ANY", new_pid); } + //ArchProcess::with_current(|current| current.print_thread()); // Save state if the PID has changed. This will activate the new memory // space. @@ -876,8 +874,8 @@ impl SystemServices { // if we encounter an error. new.mapping.activate()?; - // Set up the new process, if necessary. Remove the new context from - // the list of ready contexts. + // Set up the new process, if necessary. Remove the new thread from + // the list of ready threads. new.state = match new.state { ProcessState::Setup(thread_init) => { // println!("Setting up new process..."); @@ -904,14 +902,16 @@ impl SystemServices { let previous = self .get_process_mut(previous_pid) .expect("couldn't get previous pid"); - let _oldstate = previous.state; // for tracking state in the debug print after the following closure + let _oldstate = previous.state; // for tracking state in the debug print after the following closure previous.state = match previous.state { // If the previous process had exactly one thread that can be // run, then the Running thread list will be 0. In that case, // we will either need to Sleep this process, or mark it as // being Ready to run. ProcessState::Running(x) if x == 0 => { - if can_resume /*|| advance_thread*/ { + if can_resume + /*|| advance_thread*/ + { ProcessState::Ready(1 << previous_tid) } else { ProcessState::Sleeping @@ -932,17 +932,18 @@ impl SystemServices { previous_pid, other ), }; - if debug {println!(" KERNEL|STATE: state change from {:?} -> {:?}", _oldstate, previous.state);} - // if advance_thread { - // previous.current_thread += 1; - // if previous.current_thread as TID > arch::process::MAX_CONTEXT { - // previous.current_thread = 0; - // } - // } - // println!( - // "Set previous process PID {} state to {:?} (with can_resume = {})", - // previous_pid, previous.state, can_resume - // ); + klog!( + "PID {:?} state change from {:?} -> {:?}", + previous_pid, + _oldstate, + previous.state + ); + // klog!( + // "Set previous process PID {} state to {:?} (with can_resume = {})", + // previous_pid, + // previous.state, + // can_resume + // ); } else { let new = self.get_process_mut(new_pid)?; @@ -978,7 +979,9 @@ impl SystemServices { } // Mark the previous TID as being runnable, and remove the new TID // from the list of threads that can be run. - ProcessState::Running(x & !(1 << new_tid) | if can_resume { 1 << previous_tid } else { 0 }) + ProcessState::Running( + x & !(1 << new_tid) | if can_resume { 1 << previous_tid } else { 0 }, + ) } else { panic!( "PID {} invalid process state (not Running): {:?}", @@ -1392,23 +1395,34 @@ impl SystemServices { /// queue. /// * **ServerNotFound**: The server queue was full and a free slot could not /// be found. - pub fn create_server( - &mut self, - pid: PID, - ) -> Result<(SID, CID), xous_kernel::Error> { - let sid = SID::from_u32(arch::rand::get_u32(), arch::rand::get_u32(), arch::rand::get_u32(), arch::rand::get_u32()); + pub fn create_server(&mut self, pid: PID) -> Result<(SID, CID), xous_kernel::Error> { + let sid = SID::from_u32( + arch::rand::get_u32(), + arch::rand::get_u32(), + arch::rand::get_u32(), + arch::rand::get_u32(), + ); self.create_server_with_address(pid, sid) } /// Generate a random server ID and return it to the caller. Doesn't create /// any processes. pub fn create_server_id(&mut self) -> Result { - let sid = SID::from_u32(arch::rand::get_u32(), arch::rand::get_u32(), arch::rand::get_u32(), arch::rand::get_u32()); + let sid = SID::from_u32( + arch::rand::get_u32(), + arch::rand::get_u32(), + arch::rand::get_u32(), + arch::rand::get_u32(), + ); Ok(sid) } /// Connect to a server on behalf of another process. - pub fn connect_process_to_server(&mut self, target_pid: PID, sid: SID) -> Result{ + pub fn connect_process_to_server( + &mut self, + target_pid: PID, + sid: SID, + ) -> Result { let original_pid = crate::arch::process::current_pid(); let process = self.get_process_mut(target_pid)?; From 93fc8a0b993d49d6259a7817c361647993d2585e Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Tue, 23 Mar 2021 19:52:53 +0800 Subject: [PATCH 18/27] kernel: cargo: add wrap-print feature This is used to force kernel messages to be wrapped to 80 columns. Signed-off-by: Sean Cross --- kernel/Cargo.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/kernel/Cargo.toml b/kernel/Cargo.toml index 4ffce8b58..d41f23af3 100644 --- a/kernel/Cargo.toml +++ b/kernel/Cargo.toml @@ -21,6 +21,7 @@ riscv = "0.5.6" debug-print = [] print-panics = [] report-memory = ["stats_alloc"] +wrap-print = [] #default = ["print-panics", "debug-print"] default = ["print-panics"] From ff05fff4d6c673fb430228c4daa4e0de3cec6e39 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Tue, 23 Mar 2021 19:53:22 +0800 Subject: [PATCH 19/27] kernel: syscall: run cargo fmt on syscall.rs Signed-off-by: Sean Cross --- kernel/src/syscall.rs | 35 +++++++++++++++++------------------ 1 file changed, 17 insertions(+), 18 deletions(-) diff --git a/kernel/src/syscall.rs b/kernel/src/syscall.rs index f12e473e9..d673eea18 100644 --- a/kernel/src/syscall.rs +++ b/kernel/src/syscall.rs @@ -64,7 +64,6 @@ fn send_message(pid: PID, thread: TID, cid: CID, message: Message) -> SysCallRes let sidx = ss .sidx_from_cid(cid) .ok_or(xous_kernel::Error::ServerNotFound)?; - // ::debug_here::debug_here!(); let server_pid = ss .server_from_sidx(sidx) @@ -140,20 +139,21 @@ fn send_message(pid: PID, thread: TID, cid: CID, message: Message) -> SysCallRes } }; - // If the server has an available context to receive the message, + // If the server has an available thread to receive the message, // transfer it right away. if let Some(server_tid) = ss .server_from_sidx_mut(sidx) .expect("server couldn't be located") .take_available_thread() { - klog!( - "there are contexts available to handle this message -- marking PID {} as Ready", - server_pid - ); + // klog!( + // "there are threads available in PID {} to handle this message -- marking as Ready", + // server_pid + // ); let sender_idx = if message.is_blocking() { ss.remember_server_message(sidx, pid, thread, &message, client_address) .map_err(|e| { + klog!("error remembering server message: {:?}", e); ss.server_from_sidx_mut(sidx) .expect("server couldn't be located") .return_available_thread(thread); @@ -184,12 +184,12 @@ fn send_message(pid: PID, thread: TID, cid: CID, message: Message) -> SysCallRes })?; if blocking && cfg!(baremetal) { - // println!("Activating Server context and switching away from Client"); + klog!("Activating Server context and switching away from Client"); ss.activate_process_thread(thread, server_pid, server_tid, !blocking) .map(|_| Ok(xous_kernel::Result::Message(envelope))) .unwrap_or(Err(xous_kernel::Error::ProcessNotFound)) } else if blocking && !cfg!(baremetal) { - // println!("Blocking client, since it sent a blocking message"); + klog!("Blocking client, since it sent a blocking message"); ss.switch_from_thread(pid, thread)?; ss.switch_to_thread(server_pid, Some(server_tid))?; ss.set_thread_result( @@ -199,7 +199,8 @@ fn send_message(pid: PID, thread: TID, cid: CID, message: Message) -> SysCallRes ) .map(|_| xous_kernel::Result::BlockedProcess) } else if cfg!(baremetal) { - // println!("Setting the return value of the Server and returning to Client"); + klog!("Setting the return value of the Server ({}:{}) to {:?} and returning to Client", + server_pid, server_tid, envelope); ss.set_thread_result( server_pid, server_tid, @@ -223,7 +224,7 @@ fn send_message(pid: PID, thread: TID, cid: CID, message: Message) -> SysCallRes } } else { klog!( - "no threads available in PID {} to handle this message, so blocking", + "no threads available in PID {} to handle this message, so queueing", server_pid ); // Add this message to the queue. If the queue is full, this @@ -734,7 +735,9 @@ pub fn handle_inner(pid: PID, tid: TID, in_irq: bool, call: SysCall) -> SysCallR Ok(xous_kernel::Result::ResumeProcess) } SysCall::ReceiveMessage(sid) => receive_message(pid, tid, sid, ExecutionType::Blocking), - SysCall::TryReceiveMessage(sid) => receive_message(pid, tid, sid, ExecutionType::NonBlocking), + SysCall::TryReceiveMessage(sid) => { + receive_message(pid, tid, sid, ExecutionType::NonBlocking) + } SysCall::WaitEvent => SystemServices::with_mut(|ss| { let process = ss.get_process(pid).expect("Can't get current process"); let ppid = process.ppid; @@ -767,7 +770,7 @@ pub fn handle_inner(pid: PID, tid: TID, in_irq: bool, call: SysCall) -> SysCallR }), SysCall::CreateServerId => SystemServices::with_mut(|ss| { ss.create_server_id() - .map(|sid| xous_kernel::Result::ServerID(sid)) + .map(|sid| xous_kernel::Result::ServerID(sid)) }), SysCall::TryConnect(sid) => SystemServices::with_mut(|ss| { ss.connect_to_server(sid) @@ -792,12 +795,8 @@ pub fn handle_inner(pid: PID, tid: TID, in_irq: bool, call: SysCall) -> SysCallR SysCall::Shutdown => { SystemServices::with_mut(|ss| ss.shutdown().map(|_| xous_kernel::Result::Ok)) } - SysCall::GetProcessId => { - Ok(xous_kernel::Result::ProcessID(pid)) - } - SysCall::GetThreadId => { - Ok(xous_kernel::Result::ThreadID(tid)) - } + SysCall::GetProcessId => Ok(xous_kernel::Result::ProcessID(pid)), + SysCall::GetThreadId => Ok(xous_kernel::Result::ThreadID(tid)), SysCall::Connect(sid) => { let result = SystemServices::with_mut(|ss| { From 91647592ca548b7cc5a9dbd1ffb00ac595620611 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Tue, 23 Mar 2021 19:53:54 +0800 Subject: [PATCH 20/27] kernel-test: implement sleep test This patch implements a simple sleep test. Signed-off-by: Sean Cross --- services/kernel-test/src/main.rs | 61 ++++++++++++-------------------- 1 file changed, 23 insertions(+), 38 deletions(-) diff --git a/services/kernel-test/src/main.rs b/services/kernel-test/src/main.rs index cf580fffe..3ddaa06e9 100644 --- a/services/kernel-test/src/main.rs +++ b/services/kernel-test/src/main.rs @@ -1,59 +1,44 @@ #![cfg_attr(target_os = "none", no_std)] #![cfg_attr(target_os = "none", no_main)] -struct LoopArg { - msec: usize, -} -// fn sleep_10_loop(_ign: usize) { -// let ticktimer_server_id = xous::SID::from_bytes(b"ticktimer-server").unwrap(); -// let ticktimer_conn = xous::connect(ticktimer_server_id).unwrap(); - -// let mut ms_count = 1; -// loop { -// log::info!("10ms Loop count {}", ms_count); -// sleep_ms(ticktimer_conn, 10).unwrap(); -// ms_count += 1; -// } -// } - -// fn sleep_5_loop(_ign: usize) { -// let ticktimer_server_id = xous::SID::from_bytes(b"ticktimer-server").unwrap(); -// let ticktimer_conn = xous::connect(ticktimer_server_id).unwrap(); - -// let mut ms_count = 1; -// loop { -// log::info!("5ms Loop count {}", ms_count); -// sleep_ms(ticktimer_conn, 5).unwrap(); -// ms_count += 1; -// } -// } - -fn sleep_loop(_arg: usize) { +fn sleep_loop(sleep_ms: usize) { let ticktimer_server_id = xous::SID::from_bytes(b"ticktimer-server").unwrap(); let ticktimer_conn = xous::connect(ticktimer_server_id).unwrap(); let tid = xous::current_tid().unwrap(); let sleep_ms = match tid { - 2 => 2, - 3 => 5, - 4 => 10, + 4 => 50, + 2 => 10, + 3 => 20, _ => panic!("Unknown TID"), }; - log::info!("My thread number is {}, sleeping {} ms", tid, sleep_ms); + // log::info!("My thread number is {}, sleeping 0x{:08x} ({}) ms", tid, sleep_ms, sleep_ms); - let mut ms_count = 1; + let mut loop_count = 0; loop { - log::info!("{}ms Loop count {}", sleep_ms, ms_count); + // log::info!( + // "TEST THREAD {}: {}ms Number of times slept: {}", + // tid, + // sleep_ms, + // loop_count + // ); + let start_time = ticktimer_server::elapsed_ms(ticktimer_conn).unwrap(); ticktimer_server::sleep_ms(ticktimer_conn, sleep_ms).unwrap(); - ms_count += 1; + let end_time = ticktimer_server::elapsed_ms(ticktimer_conn).unwrap(); + log::info!( + "TEST THREAD {}: target {}ms, {} loops: Sleep finished (uptime: {}, took {} ms)", + tid, + sleep_ms, + loop_count, + end_time, + end_time - start_time, + ); + loop_count += 1; } } #[xous::xous_main] fn test_main() -> ! { log_server::init_wait().unwrap(); - // let ticktimer_server_id = xous::SID::from_bytes(b"ticktimer-server").unwrap(); - // let ticktimer_conn = xous::connect(ticktimer_server_id).unwrap(); - xous::create_thread_simple(sleep_loop, 10).unwrap(); xous::create_thread_simple(sleep_loop, 5).unwrap(); xous::create_thread_simple(sleep_loop, 2).unwrap(); From 2a6de6ed67036eb294482f995f7a3873fa757a2a Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Tue, 23 Mar 2021 21:34:37 +0800 Subject: [PATCH 21/27] kernel: hosted: remove unused interrupt calls These were removed from riscv, and have no place in hosted mode. Signed-off-by: Sean Cross --- kernel/src/arch/hosted/irq.rs | 8 -------- 1 file changed, 8 deletions(-) diff --git a/kernel/src/arch/hosted/irq.rs b/kernel/src/arch/hosted/irq.rs index 4f4ffe300..5151506a4 100644 --- a/kernel/src/arch/hosted/irq.rs +++ b/kernel/src/arch/hosted/irq.rs @@ -3,14 +3,6 @@ use xous_kernel::{TID, PID}; -pub fn disable_all_irqs() { - // There are no IRQs in a hosted environment, so there's nothing to do. -} - -pub fn enable_all_irqs() { - // There are no IRQs in a hosted environment, so there's nothing to do. -} - pub fn enable_irq(_irq_no: usize) { unimplemented!(); } From bf3a3879d2a5ad9ee79f4b9a916e945478380607 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Tue, 23 Mar 2021 21:35:20 +0800 Subject: [PATCH 22/27] kernel: hosted: create thread id 1 This ensures that PID1 has a thread ID created as well. Signed-off-by: Sean Cross --- kernel/src/arch/hosted.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/kernel/src/arch/hosted.rs b/kernel/src/arch/hosted.rs index e6af71273..fc61f7972 100644 --- a/kernel/src/arch/hosted.rs +++ b/kernel/src/arch/hosted.rs @@ -443,6 +443,7 @@ pub fn idle() -> bool { }; let pid1 = SystemServices::with_mut(|ss| ss.create_process(pid1_init)).unwrap(); assert_eq!(pid1.get(), 1); + let _tid1 = SystemServices::with_mut(|ss| ss.create_thread(pid1, ThreadInit {})).unwrap(); let listen_addr = env::var("XOUS_LISTEN_ADDR") .map(|s| { From 861565054e75cf357a88e9af53e080af5b0ded48 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Tue, 23 Mar 2021 21:35:52 +0800 Subject: [PATCH 23/27] kernel: don't activate target thread on hosted mode This operation is unneeded on hosted, and causes an error. Signed-off-by: Sean Cross --- kernel/src/syscall.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/kernel/src/syscall.rs b/kernel/src/syscall.rs index d673eea18..abc9171cf 100644 --- a/kernel/src/syscall.rs +++ b/kernel/src/syscall.rs @@ -743,9 +743,13 @@ pub fn handle_inner(pid: PID, tid: TID, in_irq: bool, call: SysCall) -> SysCallR let ppid = process.ppid; unsafe { SWITCHTO_CALLER = None }; // TODO: Advance thread - ss.activate_process_thread(tid, ppid, 0, false) - .map(|_| Ok(xous_kernel::Result::ResumeProcess)) - .unwrap_or(Err(xous_kernel::Error::ProcessNotFound)) + if cfg!(baremetal) { + ss.activate_process_thread(tid, ppid, 0, false) + .map(|_| Ok(xous_kernel::Result::ResumeProcess)) + .unwrap_or(Err(xous_kernel::Error::ProcessNotFound)) + } else { + Ok(xous_kernel::Result::Ok) + } }), SysCall::CreateThread(thread_init) => SystemServices::with_mut(|ss| { ss.create_thread(pid, thread_init).map(|new_tid| { From 89cf0c1ab1450a63e64d1c15ea75ad886748468b Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Tue, 23 Mar 2021 21:37:52 +0800 Subject: [PATCH 24/27] ticktimer-server: run rustfmt on Cargo.toml Signed-off-by: Sean Cross --- services/ticktimer-server/Cargo.toml | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/services/ticktimer-server/Cargo.toml b/services/ticktimer-server/Cargo.toml index 7e2b2c868..1529f05f0 100644 --- a/services/ticktimer-server/Cargo.toml +++ b/services/ticktimer-server/Cargo.toml @@ -1,23 +1,24 @@ [package] +authors = ["bunnie "] +description = "Provide high-resolution, non-rollover system time" +edition = "2018" name = "ticktimer-server" version = "0.1.0" -authors = ["bunnie "] -edition = "2018" -description = "Provide high-resolution, non-rollover system time" [dependencies] -xous = { path = "../../xous-rs" } heapless = "0.5" -log-server = { path = "../log-server" } log = "0.4" +log-server = {path = "../log-server"} +xous = {path = "../../xous-rs"} [target.'cfg(not(any(windows,unix)))'.dependencies] -utralib = { path = "../../utralib"} +utralib = {path = "../../utralib"} [target.'cfg(any(windows,unix))'.dependencies] [features] -debugprint = [] -disablewatchdog = [] +debug-print = [] +watchdog = [] # generally you want to disable watchdog if you're doing development. -default = ["disablewatchdog"] # "debugprint" +default = ["watchdog"] +# default = ["debug-print"] From e624c184cdad50e2388a41ddc198fb63a7008b95 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Tue, 23 Mar 2021 21:41:30 +0800 Subject: [PATCH 25/27] ticktimer-server: rewrite sleep server as deadline Use deadlines for sleep, rather than calculating the amount of remaining time. This keeps time consistent, because it means we don't have to recalculate all sleeps whenever one expires. It also allows us to take advantage of the hardware which will fire an interrupt if we schedule a wakeup in the past. Signed-off-by: Sean Cross --- services/ticktimer-server/src/main.rs | 252 +++++++++++++++++--------- 1 file changed, 170 insertions(+), 82 deletions(-) diff --git a/services/ticktimer-server/src/main.rs b/services/ticktimer-server/src/main.rs index 1bc2a4959..98e396a06 100644 --- a/services/ticktimer-server/src/main.rs +++ b/services/ticktimer-server/src/main.rs @@ -6,32 +6,50 @@ use api::Opcode; mod os_timer; -use core::convert::TryFrom; - use heapless::binary_heap::{BinaryHeap, Min}; use heapless::consts::*; +use core::convert::TryFrom; + use log::{error, info}; -#[derive(Eq, Debug)] -pub struct SleepResponse { - msec: usize, +#[derive(Eq)] +pub struct SleepRequest { + msec: i64, sender: xous::MessageSender, } -impl core::cmp::Ord for SleepResponse { - fn cmp(&self, other: &Self) -> core::cmp::Ordering { - self.msec.cmp(&other.msec) +impl core::fmt::Display for SleepRequest { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "SleepRequest {{ msec: {}, {} }}", self.msec, self.sender) } } -impl core::cmp::PartialOrd for SleepResponse { +impl core::fmt::Debug for SleepRequest { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "SleepRequest {{ msec: {}, {} }}", self.msec, self.sender) + } +} + +impl core::cmp::Ord for SleepRequest { + fn cmp(&self, other: &Self) -> core::cmp::Ordering { + if self.msec < other.msec { + core::cmp::Ordering::Less + } else if self.msec > other.msec { + core::cmp::Ordering::Greater + } else { + self.sender.cmp(&other.sender) + } + } +} + +impl core::cmp::PartialOrd for SleepRequest { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } -impl core::cmp::PartialEq for SleepResponse { +impl core::cmp::PartialEq for SleepRequest { fn eq(&self, other: &Self) -> bool { self.msec == other.msec && self.sender == other.sender } @@ -40,14 +58,14 @@ impl core::cmp::PartialEq for SleepResponse { #[cfg(target_os = "none")] mod implementation { const TICKS_PER_MS: u64 = 1; - use super::SleepResponse; + use super::SleepRequest; use utralib::generated::*; pub struct XousTickTimer { csr: utralib::CSR, + #[cfg(feature = "watchdog")] wdt: utralib::CSR, - current_response: Option, - response_start: u64, + current_response: Option, connection: xous::CID, } @@ -58,14 +76,16 @@ mod implementation { // Safe because we're in an interrupt, and this interrupt is only // enabled when this value is not None. let response = xtt.current_response.take().unwrap(); + xous::return_scalar(response.sender, 0).expect("couldn't send response"); - xtt.csr.wo(utra::ticktimer::EV_ENABLE, 0); // Disable the interrupt + // Disable the timer + xtt.csr.wfo(utra::ticktimer::EV_ENABLE_ALARM, 0); + xtt.csr.wfo(utra::ticktimer::EV_PENDING_ALARM, 1); - // This is dangerous and may panic if the queue is full. - xous::try_send_message(xtt.connection, crate::api::Opcode::RecalculateSleep.into()) - .map(|_| ()) - .unwrap(); + // This is dangerous and may return an error if the queue is full. + // Which is fine, because the queue is always recalculated any time a message arrives. + xous::try_send_message(xtt.connection, crate::api::Opcode::RecalculateSleep.into()).ok(); } impl XousTickTimer { @@ -88,17 +108,14 @@ mod implementation { let mut xtt = XousTickTimer { csr: CSR::new(csr.as_mut_ptr() as *mut u32), + #[cfg(feature = "watchdog")] wdt: CSR::new(wdt.as_mut_ptr() as *mut u32), current_response: None, - response_start: 0, connection, }; - if cfg!(feature = "disablewatchdog") { - // do nothing - } else { - xtt.wdt.wfo(utra::wdt::WATCHDOG_ENABLE, 1); - } + #[cfg(feature = "watchdog")] + xtt.wdt.wfo(utra::wdt::WATCHDOG_ENABLE, 1); xous::claim_interrupt( utra::ticktimer::TICKTIMER_IRQ, @@ -126,39 +143,58 @@ mod implementation { self.raw_ticktime() / TICKS_PER_MS } - pub fn stop_interrupt(&mut self) -> Option { - self.csr.wfo(utra::ticktimer::EV_ENABLE_ALARM, 0); // Disable the timer - let current_value = self.elapsed_ms(); + pub fn stop_interrupt(&mut self) -> Option { + // Disable the timer + self.csr.wfo(utra::ticktimer::EV_ENABLE_ALARM, 0); + + // Now that the interrupt is disabled, we can see if the interrupt handler has a current response. + // If it exists, then that means that an interrupt did NOT fire, and an existing interrupt + // is in place. if let Some(sr) = self.current_response.take() { - Some(SleepResponse { - msec: (current_value - self.response_start) as _, - sender: sr.sender, - }) + #[cfg(feature = "debug-print")] + { + log::info!( + "TickTimer: Stopping currently-running timer sr.msec: {} elapsed_ms: {}", + sr.msec, + self.elapsed_ms() + ); + } + Some(sr) } else { None } } - pub fn schedule_response(&mut self, milliseconds: usize, sender: xous::MessageSender) { - self.current_response = Some(SleepResponse { - sender, - msec: milliseconds, - }); - self.response_start = self.elapsed_ms(); - let irq_target = self.response_start + (milliseconds as u64); + pub fn schedule_response(&mut self, request: SleepRequest) { + let irq_target = request.msec; + #[cfg(feature = "debug-print")] log::info!( - "setting a response at {} ms (current time: {} ms)", + "TickTimer: setting a response at {} ms (current time: {} ms)", irq_target, - self.response_start + self.elapsed_ms() ); - self.csr.wfo(utra::ticktimer::EV_PENDING_ALARM, 1); // Clear previous interrupt (if any) + + // Disable the timer interrupt + assert!(self.csr.rf(utra::ticktimer::EV_ENABLE_ALARM) == 0); + self.csr.wfo(utra::ticktimer::EV_ENABLE_ALARM, 0); + + // Save a copy of the current sleep request + self.current_response = Some(request); + + // Set the new target time self.csr .wo(utra::ticktimer::MSLEEP_TARGET1, (irq_target >> 32) as _); self.csr .wo(utra::ticktimer::MSLEEP_TARGET0, irq_target as _); - self.csr.wfo(utra::ticktimer::EV_ENABLE_ALARM, 1); // Enable the interrupt + + // Clear previous interrupt (if any) + self.csr.wfo(utra::ticktimer::EV_PENDING_ALARM, 1); + + // Enable the interrupt + self.csr.wfo(utra::ticktimer::EV_ENABLE_ALARM, 1); } + #[cfg(feature = "watchdog")] pub fn reset_wdt(&mut self) { // disarm the WDT @@ -185,18 +221,22 @@ mod implementation { #[cfg(not(target_os = "none"))] mod implementation { - use super::SleepResponse; + use super::SleepRequest; use std::convert::TryInto; #[derive(Debug)] enum SleepComms { InterruptSleep, - StartSleep(xous::MessageSender, u64 /* ms */), + StartSleep( + xous::MessageSender, + i64, /* ms */ + u64, /* elapsed */ + ), } pub struct XousTickTimer { start: std::time::Instant, sleep_comms: std::sync::mpsc::Sender, - time_remaining_receiver: std::sync::mpsc::Receiver>, + time_remaining_receiver: std::sync::mpsc::Receiver>, } impl XousTickTimer { @@ -205,9 +245,8 @@ mod implementation { let (time_remaining_sender, time_remaining_receiver) = std::sync::mpsc::channel(); xous::create_thread(move || { let mut timeout = None; - let mut sender = Default::default(); + let mut current_response: Option = None; loop { - let start_time = std::time::Instant::now(); let result = match timeout { None => sleep_receiver .recv() @@ -216,6 +255,9 @@ mod implementation { }; match result { Err(std::sync::mpsc::RecvTimeoutError::Timeout) => { + let sender = current_response.take().unwrap().sender; + #[cfg(feature = "debug-print")] + log::info!("Returning scalar to {}", sender); xous::return_scalar(sender, 0).expect("couldn't send response"); // This is dangerous and may panic if the queue is full. @@ -229,19 +271,35 @@ mod implementation { Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => { return; } - Ok(SleepComms::InterruptSleep) => time_remaining_sender - .send(if timeout.is_some() { - Some(SleepResponse { - sender, - msec: start_time.elapsed().as_millis() as _, - }) + Ok(SleepComms::InterruptSleep) => { + timeout = None; + time_remaining_sender.send(current_response.take()).unwrap() + } + Ok(SleepComms::StartSleep(new_sender, expiry, elapsed)) => { + let mut duration = expiry - (elapsed as i64); + if duration > 0 { + #[cfg(feature = "debug-print")] + log::info!( + "Starting sleep for {} ms, returning to {}", + duration, + new_sender + ); } else { - None - }) - .unwrap(), - Ok(SleepComms::StartSleep(new_sender, duration)) => { - timeout = Some(std::time::Duration::from_millis(duration)); - sender = new_sender; + #[cfg(feature = "debug-print")] + log::info!( + "Clamping duration to 0 (was: {})m returning to {}", + duration, + new_sender + ); + duration = 0; + } + timeout = Some(std::time::Duration::from_millis( + duration.try_into().unwrap(), + )); + current_response = Some(SleepRequest { + sender: new_sender, + msec: expiry, + }); } } } @@ -263,17 +321,29 @@ mod implementation { self.start.elapsed().as_millis().try_into().unwrap() } - pub fn stop_interrupt(&mut self) -> Option { + pub fn stop_interrupt(&mut self) -> Option { self.sleep_comms.send(SleepComms::InterruptSleep).unwrap(); self.time_remaining_receiver.recv().unwrap() } - pub fn schedule_response(&mut self, milliseconds: usize, sender: xous::MessageSender) { + pub fn schedule_response(&mut self, request: SleepRequest) { + #[cfg(feature = "debug-print")] + log::info!( + "request.msec: {} self.elapsed_ms: {} returning to: {}", + request.msec, + self.elapsed_ms(), + request.sender + ); self.sleep_comms - .send(SleepComms::StartSleep(sender, milliseconds as _)) + .send(SleepComms::StartSleep( + request.sender, + request.msec as i64, + self.elapsed_ms(), + )) .unwrap(); } + #[cfg(feature = "watchdog")] pub fn reset_wdt(&self) { // dummy function, does nothing } @@ -284,21 +354,44 @@ use implementation::*; fn recalculate_sleep( ticktimer: &mut XousTickTimer, - sleep_heap: &mut BinaryHeap, - new: Option, + sleep_heap: &mut BinaryHeap, + new: Option, ) { + // If there's a sleep request ongoing now, grab it. if let Some(current) = ticktimer.stop_interrupt() { + #[cfg(feature = "debug-print")] + info!("TickTimer: Existing request was {:?}", current); sleep_heap.push(current).expect("couldn't push to heap") + } else { + #[cfg(feature = "debug-print")] + info!("TickTimer: There was no existing request"); } - if let Some(response) = new { + // If we have a new sleep request, add it to the heap. + if let Some(mut request) = new { + #[cfg(feature = "debug-print")] + info!("TickTimer: New sleep request was: {:?}", request); + + request.msec += ticktimer.elapsed_ms() as i64; + + #[cfg(feature = "debug-print")] + info!("TickTimer: Modified, the request was: {:?}", request); sleep_heap - .push(response) + .push(request) .expect("couldn't push new sleep to heap"); + } else { + #[cfg(feature = "debug-print")] + info!("TickTimer: No new sleep request"); } + + // If there are items in the sleep heap, take the next item that will expire. if let Some(next_response) = sleep_heap.pop() { - info!("scheduling a response at {}", next_response.msec); - ticktimer.schedule_response(next_response.msec, next_response.sender); + #[cfg(feature = "debug-print")] + info!( + "TickTimer: scheduling a response at {} to {} (heap: {:?})", + next_response.msec, next_response.sender, sleep_heap + ); + ticktimer.schedule_response(next_response); } } @@ -307,12 +400,11 @@ fn xmain() -> ! { // Start the OS timer which is responsible for setting up preemption. os_timer::init(); + let mut sleep_heap: BinaryHeap = BinaryHeap::new(); + log_server::init_wait().unwrap(); info!("TICKTIMER: my PID is {}", xous::process::id()); - // "Sleep" commands get put in here and are ordered as necessary - let mut sleep_heap: BinaryHeap = BinaryHeap::new(); - let ticktimer_server = xous::create_server_with_address(b"ticktimer-server") .expect("Couldn't create Ticktimer server"); info!("TICKTIMER: Server started with SID {:?}", ticktimer_server); @@ -326,42 +418,38 @@ fn xmain() -> ! { ticktimer.reset(); // make sure the time starts from zero loop { + #[cfg(feature = "watchdog")] ticktimer.reset_wdt(); - //info!("TickTimer: waiting for message"); let envelope = xous::receive_message(ticktimer_server).unwrap(); - //info!("TickTimer: Message: {:?}", envelope); if let Ok(opcode) = Opcode::try_from(&envelope.body) { - //info!("TickTimer: Opcode: {:?}", opcode); + // info!("TickTimer: Opcode: {:?}", opcode); match opcode { /*Opcode::Reset => { info!("TickTimer: reset called"); ticktimer.reset(); }*/ Opcode::ElapsedMs => { - let time = ticktimer.elapsed_ms(); - //info!("TickTimer: returning time of {:?}", time); + let time = ticktimer.elapsed_ms() as i64; xous::return_scalar2( envelope.sender, - (time & 0xFFFF_FFFFu64) as usize, - ((time >> 32) & 0xFFF_FFFFu64) as usize, + (time & 0xFFFF_FFFFi64) as usize, + ((time >> 32) & 0xFFF_FFFFi64) as usize, ) .expect("TickTimer: couldn't return time request"); - //info!("TickTimer: done returning value"); } Opcode::SleepMs(ms) => { recalculate_sleep( &mut ticktimer, &mut sleep_heap, - Some(SleepResponse { - msec: ms, + Some(SleepRequest { + msec: ms as i64, sender: envelope.sender, }), ); } Opcode::RecalculateSleep => { recalculate_sleep(&mut ticktimer, &mut sleep_heap, None); - //info!("TickTimer: Done recalculating"); } } } else { From d16d0c9bd8284f030a9900c50924cf75b83ae128 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Tue, 23 Mar 2021 21:43:35 +0800 Subject: [PATCH 26/27] ticktimer-server: set quantum to 10ms This is an experiment to see if this shorter time improves things. Signed-off-by: Sean Cross --- services/ticktimer-server/src/os_timer.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/ticktimer-server/src/os_timer.rs b/services/ticktimer-server/src/os_timer.rs index dbe36fe63..1adfdfbbb 100644 --- a/services/ticktimer-server/src/os_timer.rs +++ b/services/ticktimer-server/src/os_timer.rs @@ -38,7 +38,7 @@ pub fn init() { )) .expect("timer: couldn't claim interrupt"); - let ms = 100; // tick every 100 ms + let ms = 10; // tick every 10 ms en(false); load((SYSTEM_CLOCK_FREQUENCY / 1_000) * ms); reload((SYSTEM_CLOCK_FREQUENCY / 1_000) * ms); From 9a702437b04b0077c9dd4aa8a391c9d8cbbd575e Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Tue, 23 Mar 2021 21:43:55 +0800 Subject: [PATCH 27/27] cargo: add lockfile for kernel-test Signed-off-by: Sean Cross --- Cargo.lock | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index 89dbe8fc5..63968a818 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -602,6 +602,9 @@ checksum = "dd25036021b0de88a0aff6b850051563c6516d0bf53f8638938edbb9de732736" name = "kernel-test" version = "0.1.0" dependencies = [ + "log", + "log-server", + "ticktimer-server", "utralib", "xous", ]