Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Code cleanups #43

Merged
merged 10 commits into from
Jan 17, 2025
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 12 additions & 9 deletions samples/blinky/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
// SPDX-License-Identifier: Apache-2.0

#![no_std]

// Sigh. The check config system requires that the compiler be told what possible config values
// there might be. This is completely impossible with both Kconfig and the DT configs, since the
// whole point is that we likely need to check for configs that aren't otherwise present in the
Expand All @@ -12,11 +11,13 @@
use log::warn;

use zephyr::raw::GPIO_OUTPUT_ACTIVE;
use zephyr::time::{ Duration, sleep };
use zephyr::time::{sleep, Duration};

#[no_mangle]
extern "C" fn rust_main() {
unsafe { zephyr::set_logger().unwrap(); }
unsafe {
zephyr::set_logger().unwrap();
}

warn!("Starting blinky");

Expand All @@ -32,21 +33,23 @@ fn do_blink() {

if !led0.is_ready() {
warn!("LED is not ready");
loop {
}
loop {}
}

unsafe { led0.configure(&mut gpio_token, GPIO_OUTPUT_ACTIVE); }
unsafe {
led0.configure(&mut gpio_token, GPIO_OUTPUT_ACTIVE);
}
let duration = Duration::millis_at_least(500);
loop {
unsafe { led0.toggle_pin(&mut gpio_token); }
unsafe {
led0.toggle_pin(&mut gpio_token);
}
sleep(duration);
}
}

#[cfg(not(dt = "aliases::led0"))]
fn do_blink() {
warn!("No leds configured");
loop {
}
loop {}
}
4 changes: 3 additions & 1 deletion samples/hello_world/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ use log::info;

#[no_mangle]
extern "C" fn rust_main() {
unsafe { zephyr::set_logger().unwrap(); }
unsafe {
zephyr::set_logger().unwrap();
}

info!("Hello world from Rust on {}", zephyr::kconfig::CONFIG_BOARD);
}
33 changes: 13 additions & 20 deletions samples/philosophers/src/channel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,13 @@

extern crate alloc;

use alloc::vec::Vec;
use alloc::boxed::Box;
use alloc::vec::Vec;

use zephyr::sync::channel::{self, Receiver, Sender};
use zephyr::{
kobj_define,
sync::Arc,
};
use zephyr::{kobj_define, sync::Arc};

use crate::{NUM_PHIL, ForkSync};
use crate::{ForkSync, NUM_PHIL};

/// An implementation of ForkSync that uses a server commnicated with channels to perform the
/// synchronization.
Expand Down Expand Up @@ -97,10 +94,7 @@ impl ChannelFork {
}

impl ChannelSync {
pub fn new(
command: Sender<Command>,
reply: (Sender<()>, Receiver<()>)) -> ChannelSync
{
pub fn new(command: Sender<Command>, reply: (Sender<()>, Receiver<()>)) -> ChannelSync {
ChannelSync {
command,
reply_send: reply.0,
Expand All @@ -118,23 +112,20 @@ pub fn get_channel_syncer() -> Vec<Arc<dyn ForkSync>> {
if cfg!(CONFIG_USE_BOUNDED_CHANNELS) {
// Use only one message, so that send will block, to ensure that works.
(cq_send, cq_recv) = channel::bounded(1);
reply_queues = [(); NUM_PHIL].each_ref().map(|()| {
channel::bounded(1)
});
reply_queues = [(); NUM_PHIL].each_ref().map(|()| channel::bounded(1));
} else {
(cq_send, cq_recv) = channel::unbounded();
reply_queues = [(); NUM_PHIL].each_ref().map(|()| {
channel::unbounded()
});
reply_queues = [(); NUM_PHIL].each_ref().map(|()| channel::unbounded());
}

let syncer = reply_queues.into_iter().map(|rqueue| {
let item = Box::new(ChannelSync::new(cq_send.clone(), rqueue))
as Box<dyn ForkSync>;
let item = Box::new(ChannelSync::new(cq_send.clone(), rqueue)) as Box<dyn ForkSync>;
Arc::from(item)
});

let channel_child = CHANNEL_THREAD.init_once(CHANNEL_STACK.init_once(()).unwrap()).unwrap();
let channel_child = CHANNEL_THREAD
.init_once(CHANNEL_STACK.init_once(()).unwrap())
.unwrap();
channel_child.spawn(move || {
channel_thread(cq_recv);
});
Expand Down Expand Up @@ -162,7 +153,9 @@ fn channel_thread(cq_recv: Receiver<Command>) {

impl ForkSync for ChannelSync {
fn take(&self, index: usize) {
self.command.send(Command::Acquire(index, self.reply_send.clone())).unwrap();
self.command
.send(Command::Acquire(index, self.reply_send.clone()))
.unwrap();
// When the reply comes, we know we have the resource.
self.reply_recv.recv().unwrap();
}
Expand Down
9 changes: 3 additions & 6 deletions samples/philosophers/src/condsync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,9 @@
//! This implementation of the Fork synchronizer uses a single data object, protected by a
//! `sync::Mutex`, and coordinated by a `sync::Condvar`.

use crate::{
ForkSync,
NUM_PHIL,
};
use zephyr::sync::Mutex;
use crate::{ForkSync, NUM_PHIL};
use zephyr::sync::Condvar;
use zephyr::sync::Mutex;
// use zephyr::time::Forever;

#[derive(Debug)]
Expand All @@ -24,7 +21,7 @@ pub struct CondSync {

impl CondSync {
#[allow(dead_code)]
pub fn new() -> CondSync {
pub fn new() -> CondSync {
CondSync {
lock: Mutex::new([false; NUM_PHIL]),
cond: Condvar::new(),
Expand Down
30 changes: 15 additions & 15 deletions samples/philosophers/src/dynsemsync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,10 @@

extern crate alloc;

use alloc::vec::Vec;
use alloc::boxed::Box;
use alloc::vec::Vec;

use zephyr::{
sync::Arc, sys::sync::Semaphore, time::Forever
};
use zephyr::{sync::Arc, sys::sync::Semaphore, time::Forever};

use crate::{ForkSync, NUM_PHIL};

Expand All @@ -35,17 +33,19 @@ impl ForkSync for SemSync {

#[allow(dead_code)]
pub fn dyn_semaphore_sync() -> Vec<Arc<dyn ForkSync>> {
let forks = [(); NUM_PHIL].each_ref().map(|()| {
Arc::new(Semaphore::new(1, 1).unwrap())
});

let syncers = (0..NUM_PHIL).map(|_| {
let syncer = SemSync {
forks: forks.clone(),
};
let item = Box::new(syncer) as Box<dyn ForkSync>;
Arc::from(item)
}).collect();
let forks = [(); NUM_PHIL]
.each_ref()
.map(|()| Arc::new(Semaphore::new(1, 1).unwrap()));

let syncers = (0..NUM_PHIL)
.map(|_| {
let syncer = SemSync {
forks: forks.clone(),
};
let item = Box::new(syncer) as Box<dyn ForkSync>;
Arc::from(item)
})
.collect();

syncers
}
45 changes: 25 additions & 20 deletions samples/philosophers/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
// SPDX-License-Identifier: Apache-2.0

#![no_std]

// Cargo tries to detect configs that have typos in them. Unfortunately, the Zephyr Kconfig system
// uses a large number of Kconfigs and there is no easy way to know which ones might conceivably be
// valid. This prevents a warning about each cfg that is used.
Expand All @@ -13,31 +12,30 @@ extern crate alloc;
#[allow(unused_imports)]
use alloc::boxed::Box;
use alloc::vec::Vec;
use zephyr::time::{Duration, sleep, Tick};
use zephyr::time::{sleep, Duration, Tick};
use zephyr::{
printkln,
kobj_define,
sys::uptime_get,
kobj_define, printkln,
sync::{Arc, Mutex},
sys::uptime_get,
};

// These are optional, based on Kconfig, so allow them to be unused.
#[allow(unused_imports)]
use crate::condsync::CondSync;
use crate::channel::get_channel_syncer;
#[allow(unused_imports)]
use crate::sysmutex::SysMutexSync;
use crate::condsync::CondSync;
#[allow(unused_imports)]
use crate::channel::get_channel_syncer;
use crate::dynsemsync::dyn_semaphore_sync;
#[allow(unused_imports)]
use crate::semsync::semaphore_sync;
#[allow(unused_imports)]
use crate::dynsemsync::dyn_semaphore_sync;
use crate::sysmutex::SysMutexSync;

mod channel;
mod condsync;
mod dynsemsync;
mod sysmutex;
mod semsync;
mod sysmutex;

/// How many philosophers. There will be the same number of forks.
const NUM_PHIL: usize = 6;
Expand Down Expand Up @@ -67,19 +65,23 @@ trait ForkSync: core::fmt::Debug + Sync + Send {

#[no_mangle]
extern "C" fn rust_main() {
printkln!("Hello world from Rust on {}",
zephyr::kconfig::CONFIG_BOARD);
printkln!("Hello world from Rust on {}", zephyr::kconfig::CONFIG_BOARD);
printkln!("Time tick: {}", zephyr::time::SYS_FREQUENCY);

let stats = Arc::new(Mutex::new_from(Stats::default(), STAT_MUTEX.init_once(()).unwrap()));
let stats = Arc::new(Mutex::new_from(
Stats::default(),
STAT_MUTEX.init_once(()).unwrap(),
));

let syncers = get_syncer();

printkln!("Pre fork");

for (i, syncer) in (0..NUM_PHIL).zip(syncers.into_iter()) {
let child_stat = stats.clone();
let thread = PHIL_THREADS[i].init_once(PHIL_STACKS[i].init_once(()).unwrap()).unwrap();
let thread = PHIL_THREADS[i]
.init_once(PHIL_STACKS[i].init_once(()).unwrap())
.unwrap();
thread.spawn(move || {
phil_thread(i, syncer, child_stat);
});
Expand All @@ -105,8 +107,7 @@ fn get_syncer() -> Vec<Arc<dyn ForkSync>> {

#[cfg(CONFIG_SYNC_SYS_MUTEX)]
fn get_syncer() -> Vec<Arc<dyn ForkSync>> {
let syncer = Box::new(SysMutexSync::new())
as Box<dyn ForkSync>;
let syncer = Box::new(SysMutexSync::new()) as Box<dyn ForkSync>;
let syncer: Arc<dyn ForkSync> = Arc::from(syncer);
let mut result = Vec::new();
for _ in 0..NUM_PHIL {
Expand All @@ -118,8 +119,7 @@ fn get_syncer() -> Vec<Arc<dyn ForkSync>> {
#[cfg(CONFIG_SYNC_CONDVAR)]
fn get_syncer() -> Vec<Arc<dyn ForkSync>> {
// Condvar version
let syncer = Box::new(CondSync::new())
as Box<dyn ForkSync>;
let syncer = Box::new(CondSync::new()) as Box<dyn ForkSync>;
let syncer: Arc<dyn ForkSync> = Arc::from(syncer);
let mut result = Vec::new();
for _ in 0..NUM_PHIL {
Expand All @@ -141,7 +141,7 @@ fn phil_thread(n: usize, syncer: Arc<dyn ForkSync>, stats: Arc<Mutex<Stats>>) {
// Per Dijkstra, the last phyilosopher needs to reverse forks, or we deadlock.
(0, n)
} else {
(n, n+1)
(n, n + 1)
};

loop {
Expand Down Expand Up @@ -202,7 +202,12 @@ impl Stats {
}

fn show(&self) {
printkln!("c:{:?}, e:{:?}, t:{:?}", self.count, self.eating, self.thinking);
printkln!(
"c:{:?}, e:{:?}, t:{:?}",
self.count,
self.eating,
self.thinking
);
}
}

Expand Down
22 changes: 11 additions & 11 deletions samples/philosophers/src/semsync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,10 @@

extern crate alloc;

use alloc::vec::Vec;
use alloc::boxed::Box;
use alloc::vec::Vec;

use zephyr::{
kobj_define, sync::Arc, sys::sync::Semaphore, time::Forever
};
use zephyr::{kobj_define, sync::Arc, sys::sync::Semaphore, time::Forever};

use crate::{ForkSync, NUM_PHIL};

Expand Down Expand Up @@ -40,13 +38,15 @@ pub fn semaphore_sync() -> Vec<Arc<dyn ForkSync>> {
Arc::new(m.init_once((1, 1)).unwrap())
});

let syncers = (0..NUM_PHIL).map(|_| {
let syncer = SemSync {
forks: forks.clone(),
};
let item = Box::new(syncer) as Box<dyn ForkSync>;
Arc::from(item)
}).collect();
let syncers = (0..NUM_PHIL)
.map(|_| {
let syncer = SemSync {
forks: forks.clone(),
};
let item = Box::new(syncer) as Box<dyn ForkSync>;
Arc::from(item)
})
.collect();

syncers
}
Expand Down
11 changes: 3 additions & 8 deletions samples/philosophers/src/sysmutex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,7 @@
//! This is a simple implementation of the Fork synchronizer that uses underlying Zephyr `k_mutex`
//! wrapped in `sys::Mutex`. The ForkSync semantics map simply to these.

use crate::{
ForkSync,
NUM_PHIL,
};
use crate::{ForkSync, NUM_PHIL};
use zephyr::sys::sync::Mutex;
use zephyr::time::Forever;

Expand All @@ -25,10 +22,8 @@ pub struct SysMutexSync {

impl SysMutexSync {
#[allow(dead_code)]
pub fn new() -> SysMutexSync {
let locks = [(); NUM_PHIL].each_ref().map(|()| {
Mutex::new().unwrap()
});
pub fn new() -> SysMutexSync {
let locks = [(); NUM_PHIL].each_ref().map(|()| Mutex::new().unwrap());
SysMutexSync { locks }
}
}
Expand Down
Loading