Skip to content

Start of Kobj support: Semaphores and Threads #12

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

Merged
merged 39 commits into from
Oct 17, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
1 change: 1 addition & 0 deletions zephyr-sys/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ fn main() -> Result<()> {
.allowlist_function("gpio_.*")
.allowlist_function("sys_.*")
.allowlist_item("E.*")
.allowlist_item("K_.*")
// Deprecated
.blocklist_function("sys_clock_timeout_end_calc")
.parse_callbacks(Box::new(bindgen::CargoCallbacks::new()))
Expand Down
16 changes: 13 additions & 3 deletions zephyr/src/object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ use crate::sync::atomic::{AtomicUsize, Ordering};
pub struct StaticKernelObject<T> {
#[allow(dead_code)]
/// The underlying zephyr kernel object.
value: UnsafeCell<T>,
pub(crate) value: UnsafeCell<T>,
/// Initialization status of this object. Most objects will start uninitialized and be
/// initialized manually.
init: AtomicUsize,
Expand Down Expand Up @@ -142,7 +142,17 @@ macro_rules! kobj_define {
#[doc(hidden)]
#[macro_export]
macro_rules! _kobj_rule {
() => {
compile_errro!("TODO: Add kobj rules");
// static NAME: StaticSemaphore;
($v:vis, $name:ident, StaticSemaphore) => {
#[link_section = concat!("._k_sem.static.", stringify!($name), ".", file!(), line!())]
$v static $name: $crate::sys::sync::StaticSemaphore =
unsafe { ::core::mem::zeroed() };
};

// static NAMES: [StaticSemaphore; COUNT];
($v:vis, $name:ident, [StaticSemaphore; $size:expr]) => {
#[link_section = concat!("._k_sem.static.", stringify!($name), ".", file!(), line!())]
$v static $name: [$crate::sys::sync::StaticSemaphore; $size] =
unsafe { ::core::mem::zeroed() };
};
}
2 changes: 2 additions & 0 deletions zephyr/src/sys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

use zephyr_sys::k_timeout_t;

pub mod sync;

// These two constants are not able to be captured by bindgen. It is unlikely that these values
// would change in the Zephyr headers, but there will be an explicit test to make sure they are
// correct.
Expand Down
124 changes: 124 additions & 0 deletions zephyr/src/sys/sync.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
// Copyright (c) 2024 Linaro LTD
// SPDX-License-Identifier: Apache-2.0

//! # Zephyr low-level synchronization primities.
//!
//! The `zephyr-sys` crate contains direct calls into the Zephyr C API. This interface, however,
//! cannot be used from safe Rust. This crate attempts to be as direct an interface to some of
//! these synchronization mechanisms, but without the need for unsafe. The other module
//! `crate::sync` provides higher level interfaces that help manage synchronization in coordination
//! with Rust's borrowing and sharing rules, and will generally provide much more usable
//! interfaces.
//!
//! # Kernel objects
//!
//! Zephyr's primitives work with the concept of a kernel object. These are the data structures
//! that are used by the Zephyr kernel to coordinate the operation of the primitives. In addition,
//! they are where the protection barrier provided by `CONFIG_USERSPACE` is implemented. In order
//! to use these primitives from a userspace thread two things must happen:
//!
//! - The kernel objects must be specially declared. All kernel objects in Zephyr will be built,
//! at compile time, into a perfect hash table that is used to validate them. The special
//! declaration will take care of this.
//! - The objects must be granted permission to be used by the userspace thread. This can be
//! managed either by specifically granting permission, or by using inheritance when creating the
//! thread.
//!
//! At this time, only the first mechanism is implemented, and all kernel objects should be
//! declared using the `crate::kobj_define!` macro. These then must be initialized, and then the
//! special method `.get()` called, to retrieve the Rust-style value that is used to manage them.
//! Later, there will be a pool mechanism to allow these kernel objects to be allocated and freed
//! from a pool, although the objects will still be statically allocated.

use crate::{
error::{Result, to_result_void},
object::{StaticKernelObject, Wrapped},
raw::{
k_sem,
k_sem_init,
k_sem_take,
k_sem_give,
k_sem_reset,
k_sem_count_get,
K_SEM_MAX_LIMIT,
},
time::Timeout,
};

/// A zephyr `k_sem` usable from safe Rust code.
#[derive(Clone)]
pub struct Semaphore {
/// The raw Zephyr `k_sem`.
item: *mut k_sem,
}
Comment on lines +52 to +57
Copy link
Collaborator

Choose a reason for hiding this comment

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

This seems to work fine as other code carefully avoids constructing this for non-static semahpores. Does zephyr also have dynamic ones? I found these internal pointers made it harder to reason about safety eventually.

I wonder: Have you considered something like:

[repr(transparent)]
pub struct Semaphore { 
    value: UnsafeCell<MaybeUninit<k_sem>>,
    _pin: PhantomPinned,
}

?
(see https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/rust/kernel/types.rs#n261 / rust-lang/rust#43467 for context)

Then of course most code would work with a &Semaphore, but that seems like a more direct mapping of C -> Rust to me?

If all you ever deal with are static objects, then I guess this is fine too. But I think the direct wrapping is going to be a pattern elsewhere eventually anyway? It seems to me like that may also allow to unify this together with the "static object" that currently needs to be defined separately?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

So Semaphore is not a static semaphore, it is a singleton reference to some kind of semaphore. The StaticSemaphore is one way of declaring the semaphores (and currently the only way).

I intend to add dynamic variants of many of these, but as the Zephyr dynamic object support is rather poor at the moment, these will likely just have a pool of the objects that they take from. The Semaphore type will be the same, but there will lookly be a Semaphore::new that returns one from the pool. When it is dropped, it will be returned to the pool.


/// By nature, Semaphores are both Sync and Send. Safety is handled by the underlying Zephyr
/// implementation (which is why Clone is also implemented).
unsafe impl Sync for Semaphore {}
unsafe impl Send for Semaphore {}

impl Semaphore {
/// Take a semaphore.
///
/// Can be called from ISR if called with [`NoWait`].
pub fn take<T>(&mut self, timeout: T) -> Result<()>
where T: Into<Timeout>,
{
let timeout: Timeout = timeout.into();
let ret = unsafe {
k_sem_take(self.item, timeout.0)
};
to_result_void(ret)
}

/// Give a semaphore.
///
/// This routine gives to the semaphore, unless the semaphore is already at its maximum
/// permitted count.
pub fn give(&mut self) {
unsafe {
k_sem_give(self.item)
Copy link
Member

Choose a reason for hiding this comment

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

I needed to remind myself that omitting the semicolon with the last expression of a function returns that value 🦀

Does the documentation engine publish return type information for these functions?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

It would have to be declared in the code, it is never inferred. In this case, give returns nothing, and the zephyr function is void.

}
}

/// Resets a semaphor's count to zero.
///
/// This resets the count to zero. Any outstanding [`take`] calls will be aborted with
/// `Error(EAGAIN)`.
pub fn reset(&mut self) {
unsafe {
k_sem_reset(self.item)
}
}

/// Get a semaphore's count.
///
/// Returns the current count.
pub fn count_get(&mut self) -> usize {
unsafe {
k_sem_count_get(self.item) as usize
}
}
}

/// A static Zephyr `k_sem`.
///
/// This is intended to be used from within the `kobj_define!` macro. It declares a static ksem
/// that will be properly registered with the Zephyr kernel object system. Call [`take`] to get the
/// [`Semaphore`] that is represents.
pub type StaticSemaphore = StaticKernelObject<k_sem>;

impl Wrapped for StaticKernelObject<k_sem> {
type T = Semaphore;

// TODO: Thoughts about how to give parameters to the initialzation.
fn get_wrapped(&self) -> Semaphore {
let ptr = self.value.get();
unsafe {
k_sem_init(ptr, 0, K_SEM_MAX_LIMIT);
}
Semaphore {
item: ptr,
}
}
}