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

Start of Kobj support: Semaphores and Threads #12

Merged
merged 39 commits into from
Oct 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
39 commits
Select commit Hold shift + click to select a range
fa00bea
zephyr::kconfig: Document module
d3zd3z Oct 11, 2024
823b48a
zephyr: Add some missing doc comments
d3zd3z Oct 11, 2024
45192f3
zephyr: Enforce documentation
d3zd3z Oct 11, 2024
ed875c2
zephyr: Add Error and Result types
d3zd3z Sep 23, 2024
e1196a0
zephyr: Make symbols from portable-atomic available
d3zd3z Sep 17, 2024
594bbc4
zephyr: Introduce static kobject support
d3zd3z Sep 18, 2024
3e362a7
zephyr: include portable atomic
d3zd3z Oct 11, 2024
67e456b
zephyr: Add sys::Sempahore
d3zd3z Oct 11, 2024
d8fbb57
zephyr: `take` in static kernel object takes args
d3zd3z Oct 11, 2024
aed43fd
zephyr: Provide critical-section for Zephyr
d3zd3z Sep 17, 2024
6598cd1
zephyr: Add alignment helper
d3zd3z Sep 23, 2024
a9ea9a1
zephyr: Add allocator support
d3zd3z Jul 18, 2024
59907d7
zephyr-sys: Export stack alignment constants
d3zd3z Sep 23, 2024
6b3e831
zephyr: Add sys::thread support
d3zd3z Oct 11, 2024
e71bd6a
samples: philosophers: Dining philosophers example
d3zd3z Oct 11, 2024
096d34b
Upgrade crate versions to match Zephyr
d3zd3z Oct 8, 2024
32b8fbf
zephyr: Add `k_uptime_get`
d3zd3z Sep 23, 2024
907c044
zephyr: Implement Debug for Semaphore
d3zd3z Oct 11, 2024
3d2477d
zephyr: StaticSemaphire needs to implement Sync
d3zd3z Oct 11, 2024
3fd043a
zephyr: Semaphore methods should not be `mut`
d3zd3z Oct 11, 2024
c88307f
zephyr: hide docs of RealStaticThreadStack
d3zd3z Oct 11, 2024
1b92ea5
zephyr: Expose some fields publicly
d3zd3z Oct 11, 2024
1971feb
zephyr: StaticThread must be Sync
d3zd3z Oct 11, 2024
97b217f
samples: hello_world: Fix dependency version
d3zd3z Oct 11, 2024
2ccb628
zephyr: Fix some warnings by being conditional
d3zd3z Oct 11, 2024
e8eebb2
samples: philosophers: Fix yaml
d3zd3z Oct 11, 2024
a34507f
tests: time: Fix dependency
d3zd3z Oct 11, 2024
91d6f33
zephyr-sys: Allow broken doc links in bindgen
d3zd3z Oct 12, 2024
177a932
zephyr: object: Improve docs about safety
d3zd3z Oct 12, 2024
1cd9299
zephyr: printk: Fix doc error
d3zd3z Oct 12, 2024
266a7a7
zephyr: sys: sync: Fix some doc links
d3zd3z Oct 12, 2024
fdd97ae
zephyr: printk: Remove dependency on alloc
d3zd3z Oct 14, 2024
d01153a
zephyr: Create export type alias
d3zd3z Oct 15, 2024
7375e44
zephyr: Use constructor for static thread stack
d3zd3z Oct 15, 2024
8bbade3
zephyr: object: Add kboj_define support for arrays of stacks
d3zd3z Oct 15, 2024
98a15fe
samples: philosophers: Convert to array of stacks
d3zd3z Oct 15, 2024
861cb83
zephyr: docgen
d3zd3z Oct 15, 2024
057e169
zephyr: Fix some broken doc comments
d3zd3z Oct 15, 2024
d11c5d2
module: Make sure all tests are run
d3zd3z Oct 15, 2024
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
12 changes: 12 additions & 0 deletions Kconfig
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,16 @@ config RUST
help
This option enables the use of applications written in Rust.

if RUST

config RUST_ALLOC
bool "Support an allocator in Rust code"
help
If enabled, the Rust zephyr support library will include support for
an allocator. This allocator will use the currently configured
Zephyr allocator (malloc/free). This this enabled, Rust
applications can use the `alloc` crate.

endif # RUST

endmenu
4 changes: 2 additions & 2 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ your application directory, with options set so that it can find the Zephyr supp
that the output will be contained within the Zephyr build directory.

The :file:`Cargo.toml` will need to have a ``[lib]`` section that sets ``crate-type =
["staticlib"]``, and will need to include ``zephyr = "0.1.0"`` as a dependency. You can use
["staticlib"]``, and will need to include ``zephyr = "3.7.0"`` as a dependency. You can use
crates.io and the Crate ecosystem to include any other dependencies you need. Just make sure that
you use crates that support building with no-std.

Expand Down Expand Up @@ -115,7 +115,7 @@ To your ``Cargo.toml`` file, add the following:
.. code-block:: toml

[build-dependencies]
zephyr-build = "0.1.0"
zephyr-build = "3.7.0"

Then, you will need a ``build.rs`` file to call the support function. The following will work:

Expand Down
1 change: 1 addition & 0 deletions docgen/.cargo/config.toml
7 changes: 7 additions & 0 deletions docgen/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# In this case, we do want the symlink checked in. We'll assume we have the module in the standard
# module place.
#
# On Windows, this symlink will just get checked out as a regular file and will have to be replaced
# with a copy (or real symlinks enabled). But, this shouldn't affect CI runs of the documentation,
# which are done on Linux.
!.cargo/
8 changes: 8 additions & 0 deletions docgen/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# SPDX-License-Identifier: Apache-2.0

cmake_minimum_required(VERSION 3.20.0)

find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE})

project(hello_rust_world)
rust_cargo_application()
16 changes: 16 additions & 0 deletions docgen/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Copyright (c) 2024 Linaro LTD
# SPDX-License-Identifier: Apache-2.0

[package]
# This must be rustapp for now.
name = "rustapp"
version = "3.7.0"
edition = "2021"
description = "A small application to generate documentation"
license = "Apache-2.0 or MIT"

[lib]
crate-type = ["staticlib"]

[dependencies]
zephyr = "3.7.0"
5 changes: 5 additions & 0 deletions docgen/prj.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Copyright (c) 2024 Linaro LTD
# SPDX-License-Identifier: Apache-2.0

CONFIG_RUST=y
CONFIG_RUST_ALLOC=y
16 changes: 16 additions & 0 deletions docgen/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Copyright (c) 2024 Linaro LTD
// SPDX-License-Identifier: Apache-2.0

#![no_std]

use zephyr::printkln;

// Reference the Zephyr crate so that the panic handler gets used. This is only needed if no
// symbols from the crate are directly used.
extern crate zephyr;

#[no_mangle]
extern "C" fn rust_main() {
printkln!("Hello world from Rust on {}",
zephyr::kconfig::CONFIG_BOARD);
}
4 changes: 2 additions & 2 deletions samples/hello_world/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
[package]
# This must be rustapp for now.
name = "rustapp"
version = "0.1.0"
version = "3.7.0"
edition = "2021"
description = "A sample hello world application in Rust"
license = "Apache-2.0 or MIT"
Expand All @@ -13,4 +13,4 @@ license = "Apache-2.0 or MIT"
crate-type = ["staticlib"]

[dependencies]
zephyr = "0.1.0"
zephyr = "3.7.0"
8 changes: 8 additions & 0 deletions samples/philosophers/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# SPDX-License-Identifier: Apache-2.0

cmake_minimum_required(VERSION 3.20.0)

find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE})
project(philosophers)

rust_cargo_application()
25 changes: 25 additions & 0 deletions samples/philosophers/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Copyright (c) 2024 Linaro LTD
# SPDX-License-Identifier: Apache-2.0

[package]
# This must be rustapp for now.
name = "rustapp"
version = "3.7.0"
edition = "2021"
description = "A sample hello world application in Rust"
license = "Apache-2.0 or MIT"

[lib]
crate-type = ["staticlib"]

[dependencies]
zephyr = "3.7.0"

# Dependencies that are used by build.rs.
[build-dependencies]
zephyr-build = "3.7.0"

[profile.release]
debug-assertions = true
overflow-checks = true
debug = true
18 changes: 18 additions & 0 deletions samples/philosophers/Kconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Copyright (c) 2024 Linaro LTD
# SPDX-License-Identifier: Apache-2.0

mainmenu "Rust Dining Philosphers"

source "Kconfig.zephyr"

choice
prompt "Select Synchronization implementation"
default SYNC_SYS_SEMAPHORE

config SYNC_SYS_SEMAPHORE
bool "Use sys::Semaphore to synchronize forks"
help
Use to have the dining philosophers sample use sys::Semaphore, with one per form,
to synchronize.

endchoice
7 changes: 7 additions & 0 deletions samples/philosophers/boards/rpi_pico.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Copyright (c) 2024 Linaro LTD
# SPDX-License-Identifier: Apache-2.0

# This board doesn't have a serial console, so use RTT.
CONFIG_UART_CONSOLE=n
CONFIG_RTT_CONSOLE=y
CONFIG_USE_SEGGER_RTT=y
9 changes: 9 additions & 0 deletions samples/philosophers/build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// Copyright (c) 2023 Linaro LTD
// SPDX-License-Identifier: Apache-2.0

// This crate needs access to kconfig variables. This is an example of how to do that. The
// zephyr-build must be a build dependency.

fn main() {
zephyr_build::export_bool_kconfig();
}
15 changes: 15 additions & 0 deletions samples/philosophers/prj.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Copyright (c) 2024 Linaro LTD
# SPDX-License-Identifier: Apache-2.0

CONFIG_RUST=y
CONFIG_RUST_ALLOC=y
CONFIG_MAIN_STACK_SIZE=8192

# CONFIG_USERSPACE=y

# Some debugging
CONFIG_THREAD_MONITOR=y
CONFIG_THREAD_ANALYZER=y
CONFIG_THREAD_ANALYZER_USE_PRINTK=y
CONFIG_THREAD_ANALYZER_AUTO=n
# CONFIG_THREAD_ANALYZER_AUTO_INTERVAL=15
22 changes: 22 additions & 0 deletions samples/philosophers/sample.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
sample:
description: Philosphers, in Rust
name: philosophers rust
common:
harness: console
harness_config:
type: one_line
regex:
# Match the statistics, and make sure that each philosopher has at least 10 (two digits)
# meals.
# - "^\\[\\d{2,}, \\d{2,}, \\d{2,}, \\d{2,}, \\d{2,}, \\d{2,}\\]"
#
# Until the stastics have been implemented, just match on one of the children thinking
- "^Child 5 thinking \\(\\d+ ticks.*"
tags: rust
filter: CONFIG_RUST_SUPPORTED
tests:
sample.rust.philosopher.semaphore:
tags: introduction
min_ram: 32
extra_configs:
- CONFIG_SYNC_SYS_SEMAPHORE=y
134 changes: 134 additions & 0 deletions samples/philosophers/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
// Copyright (c) 2023 Linaro LTD
// 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.
#![allow(unexpected_cfgs)]

extern crate alloc;

#[allow(unused_imports)]
use alloc::boxed::Box;
use alloc::vec::Vec;
use zephyr::time::{Duration, sleep, Tick};
use zephyr::{
printkln,
kobj_define,
sys::uptime_get,
sync::Arc,
};

// These are optional, based on Kconfig, so allow them to be unused.
#[allow(unused_imports)]
use crate::semsync::semaphore_sync;

mod semsync;

/// How many philosophers. There will be the same number of forks.
const NUM_PHIL: usize = 6;

/// How much stack should each philosopher thread get. Worst case I've seen is riscv64, with 3336
/// bytes, when printing messages. Make a bit larger to work.
const PHIL_STACK_SIZE: usize = 4096;

// The dining philosophers problem is a simple example of cooperation between multiple threads.
// This implementation use one of several different underlying mechanism to support this cooperation.

// This example uses dynamic dispatch to allow multiple implementations. The intent is to be able
// to periodically shut down all of the philosphers and start them up with a differernt sync
// mechanism. This isn't implemented yet.

/// The philosophers use a fork synchronization mechanism. Essentially, this is 6 locks, and will be
/// implemented in a few different ways to demonstrate/test different mechanmism in Rust. All of
/// them implement The ForkSync trait which provides this mechanism.
trait ForkSync: core::fmt::Debug + Sync + Send {
/// Take the given fork. The are indexed the same as the philosopher index number. This will
/// block until the fork is released.
fn take(&self, index: usize);

/// Release the given fork. Index is the same as take.
fn release(&self, index: usize);
}

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

let syncers = get_syncer();

printkln!("Pre fork");

for (i, syncer) in (0..NUM_PHIL).zip(syncers.into_iter()) {
let thread = PHIL_THREADS[i].init_once(PHIL_STACKS[i].init_once(()).unwrap()).unwrap();
thread.spawn(move || {
phil_thread(i, syncer);
});
}

let delay = Duration::secs_at_least(10);
loop {
// Periodically, printout the stats.
zephyr::time::sleep(delay);
}
}

#[cfg(CONFIG_SYNC_SYS_SEMAPHORE)]
fn get_syncer() -> Vec<Arc<dyn ForkSync>> {
semaphore_sync()
}

fn phil_thread(n: usize, syncer: Arc<dyn ForkSync>) {
printkln!("Child {} started: {:?}", n, syncer);

// Determine our two forks.
let forks = if n == NUM_PHIL - 1 {
// Per Dijkstra, the last phyilosopher needs to reverse forks, or we deadlock.
(0, n)
} else {
(n, n+1)
};

loop {
{
printkln!("Child {} hungry", n);
printkln!("Child {} take left fork", n);
syncer.take(forks.0);
printkln!("Child {} take right fork", n);
syncer.take(forks.1);

let delay = get_random_delay(n, 25);
printkln!("Child {} eating ({} ms)", n, delay);
sleep(delay);
// stats.lock().unwrap().record_eat(n, delay);

// Release the forks.
printkln!("Child {} giving up forks", n);
syncer.release(forks.1);
syncer.release(forks.0);

let delay = get_random_delay(n, 25);
printkln!("Child {} thinking ({} ms)", n, delay);
sleep(delay);
// stats.lock().unwrap().record_think(n, delay);
}
}
}

/// Get a random delay, based on the ID of this user, and the current uptime.
fn get_random_delay(id: usize, period: usize) -> Duration {
let tick = (uptime_get() & (usize::MAX as i64)) as usize;
let delay = (tick / 100 * (id + 1)) & 0x1f;

// Use one greater to be sure to never get a delay of zero.
Duration::millis_at_least(((delay + 1) * period) as Tick)
}

kobj_define! {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks good - certainly an improvement

static PHIL_THREADS: [StaticThread; NUM_PHIL];
static PHIL_STACKS: [ThreadStack<PHIL_STACK_SIZE>; NUM_PHIL];
}
Loading