From 47a4a26a50c2dd153bbdf747574547553147ab7e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rom=C3=A1n=20C=C3=A1rdenas=20Rodr=C3=ADguez?= Date: Fri, 11 Oct 2024 14:37:37 +0200 Subject: [PATCH] replace static muts with mutexes --- hifive1/CHANGELOG.md | 1 + hifive1/Cargo.toml | 1 + hifive1/src/stdout.rs | 25 ++++++++++++------------- 3 files changed, 14 insertions(+), 13 deletions(-) diff --git a/hifive1/CHANGELOG.md b/hifive1/CHANGELOG.md index 4924efa..40286ad 100644 --- a/hifive1/CHANGELOG.md +++ b/hifive1/CHANGELOG.md @@ -6,6 +6,7 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). ## [Unreleased] +- Replace static muts with Mutexes - Apply clippy changes - Bump MSRV to 1.72 - Adapt to new Cargo workspace diff --git a/hifive1/Cargo.toml b/hifive1/Cargo.toml index efa0546..ac01280 100644 --- a/hifive1/Cargo.toml +++ b/hifive1/Cargo.toml @@ -11,6 +11,7 @@ edition = "2021" rust-version = "1.72" [dependencies] +critical-section = { version = "1.1.3" } e310x-hal = { path = "../e310x-hal", version = "0.11.0" } embedded-hal = "0.2.7" riscv = "0.10.1" diff --git a/hifive1/src/stdout.rs b/hifive1/src/stdout.rs index 59be531..bf21848 100644 --- a/hifive1/src/stdout.rs +++ b/hifive1/src/stdout.rs @@ -1,6 +1,7 @@ //! Stdout based on the UART hooked up to FTDI or J-Link -use core::fmt; +use core::{cell::RefCell, fmt}; +use critical_section::Mutex; use e310x_hal::{ clock::Clocks, e310x::Uart0, @@ -10,12 +11,11 @@ use e310x_hal::{ time::Bps, }; use nb::block; -use riscv::interrupt; - -static mut STDOUT: Option = None; struct SerialWrapper(Tx); +static STDOUT: Mutex>> = Mutex::new(RefCell::new(None)); + impl core::fmt::Write for SerialWrapper { fn write_str(&mut self, s: &str) -> fmt::Result { for byte in s.as_bytes() { @@ -50,28 +50,27 @@ pub fn configure( let serial = Serial::new(uart, (tx, rx), baud_rate, clocks); let (tx, rx) = serial.split(); - interrupt::free(|| unsafe { - STDOUT.replace(SerialWrapper(tx)); - }); + critical_section::with(|cs| STDOUT.borrow(cs).replace(Some(SerialWrapper(tx)))); + rx } /// Writes string to stdout pub fn write_str(s: &str) { - interrupt::free(|| unsafe { - if let Some(stdout) = STDOUT.as_mut() { + critical_section::with(|cs| { + if let Some(stdout) = STDOUT.borrow(cs).borrow_mut().as_mut() { let _ = stdout.write_str(s); } - }) + }); } /// Writes formatted string to stdout pub fn write_fmt(args: fmt::Arguments) { - interrupt::free(|| unsafe { - if let Some(stdout) = STDOUT.as_mut() { + critical_section::with(|cs| { + if let Some(stdout) = STDOUT.borrow(cs).borrow_mut().as_mut() { let _ = stdout.write_fmt(args); } - }) + }); } /// Macro for printing to the serial standard output