Skip to content
5 changes: 5 additions & 0 deletions zephyr-build/src/devicetree/augment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,11 @@ impl RawInfo {
quote! {
#cfg_attr
/// Get the raw `const struct device *` of the device tree generated node.
///
/// # Safety
///
/// The pointer bypasses the single-instance check of `get_instance`,
/// so the caller must not use it to alias the device returned there.
pub unsafe fn get_instance_raw() -> *const crate::raw::device {
&crate::raw::#rawdev
}
Expand Down
3 changes: 3 additions & 0 deletions zephyr/src/alloc_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,9 @@ extern "C" {
/// allocator as well.
pub struct ZephyrAllocator;

// SAFETY: `alloc` rounds the size up to a multiple of the alignment as `aligned_alloc` requires,
// and `dealloc` pairs with libc `free`. The libc heap takes a mutex, so this allocator must not
// be used from ISRs.
unsafe impl GlobalAlloc for ZephyrAllocator {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
let align = layout.align();
Expand Down
14 changes: 14 additions & 0 deletions zephyr/src/device/gpio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@ mod async_io {
callback: UnsafeCell<gpio_callback>,
}

// SAFETY: `callback` is only written under a critical section in `install`, and the remaining
// fields are atomics; `pin_mask` updates in `register` and the ISR handler rely on the benign
// race described there.
unsafe impl Sync for GpioStatic {}

impl GpioStatic {
Expand Down Expand Up @@ -103,6 +106,8 @@ mod async_io {
// If it seems that wakes are getting missed, it might be the case that this needs some
// kind of memory barrier.
let cb = self.callback.get();
// SAFETY: `cb` points to `self.callback`, valid for the borrow; see the note above on
// the tolerated race with the ISR handler.
unsafe {
(*cb).pin_mask |= 1 << pin;
}
Expand All @@ -113,6 +118,8 @@ mod async_io {
cb: *mut gpio_callback,
mut pins: gpio_port_pins_t,
) {
// SAFETY: Zephyr passes back the `gpio_callback` registered in `install`, i.e. the
// `callback` field of a `'static` `GpioStatic`, so subtracting its offset gives `Self`.
let data = unsafe {
cb.cast::<u8>()
.sub(mem::offset_of!(Self, callback))
Expand Down Expand Up @@ -209,6 +216,8 @@ mod async_io {
_ => unreachable!(),
};

// SAFETY: `self.pin.pin.port` is a valid device pointer (a `'static` devicetree device,
// or guaranteed by the `raw_new` caller), and the spec is borrowed for the call.
unsafe {
gpio_pin_interrupt_configure_dt(&self.pin.pin, mode);

Expand Down Expand Up @@ -270,6 +279,7 @@ impl Gpio {
/// Verify that the device is ready for use. At a minimum, this means the device has been
/// successfully initialized.
pub fn is_ready(&self) -> bool {
// SAFETY: `self.device` is a valid `'static` device pointer from devicetree.
unsafe { raw::device_is_ready(self.device) }
}
}
Expand Down Expand Up @@ -369,6 +379,7 @@ impl GpioPin {
/// Concurrency safety is determined by the underlying driver.
pub fn configure(&mut self, extra_flags: raw::gpio_flags_t) {
// TODO: Error?
// SAFETY: `self.pin.port` is a valid device pointer; `pin` and flags come from the spec.
unsafe {
raw::gpio_pin_configure(
self.pin.port,
Expand All @@ -385,20 +396,23 @@ impl GpioPin {
/// Concurrency safety is determined by the underlying driver.
pub fn toggle_pin(&mut self) {
// TODO: Error?
// SAFETY: `&self.pin` is a valid `gpio_dt_spec` whose port is a valid device pointer.
unsafe {
raw::gpio_pin_toggle_dt(&self.pin);
}
}

/// Set the logical level of the pin.
pub fn set(&mut self, value: bool) {
// SAFETY: `&self.pin` is a valid `gpio_dt_spec` whose port is a valid device pointer.
unsafe {
raw::gpio_pin_set_dt(&self.pin, value as c_int);
}
}

/// Read the logical level of the pin.
pub fn get(&mut self) -> bool {
// SAFETY: `&self.pin` is a valid `gpio_dt_spec` whose port is a valid device pointer.
unsafe {
match raw::gpio_pin_get_dt(&self.pin) {
0 => false,
Expand Down
8 changes: 8 additions & 0 deletions zephyr/src/device/i2c/controller.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,15 @@ impl I2c {

/// Verify that the underlying I2C device is ready for use.
pub fn is_ready(&self) -> bool {
// SAFETY: `self.device` is a valid `'static` device pointer from devicetree.
unsafe { raw::device_is_ready(self.device) }
}

/// Write bytes to an I2C device, then read bytes back in a single transaction (RESTART
/// between the write and read phases).
pub fn write_read(&mut self, addr: u16, write_buf: &[u8], read_buf: &mut [u8]) -> Result<()> {
// SAFETY: `self.device` is a valid device, and the buffer pointers and lengths come from
// slices that outlive this blocking call.
to_result_void(unsafe {
raw::i2c_write_read(
self.device,
Expand All @@ -70,11 +73,14 @@ impl I2c {

/// Write bytes to an I2C device.
pub fn write(&mut self, addr: u16, buf: &[u8]) -> Result<()> {
// SAFETY: `self.device` is a valid device, and `buf` outlives this blocking call.
to_result_void(unsafe { raw::i2c_write(self.device, buf.as_ptr(), buf.len() as u32, addr) })
}

/// Read bytes from an I2C device.
pub fn read(&mut self, addr: u16, buf: &mut [u8]) -> Result<()> {
// SAFETY: `self.device` is a valid device, and `buf` is exclusively borrowed for this
// blocking call.
to_result_void(unsafe {
raw::i2c_read(self.device, buf.as_mut_ptr(), buf.len() as u32, addr)
})
Expand Down Expand Up @@ -123,6 +129,8 @@ impl I2c {
msgs[i].flags = flags;
}

// SAFETY: `self.device` is a valid device, `msgs` holds `ops.len()` initialized messages
// whose buffers borrow from `ops`, and the transfer completes before this returns.
to_result_void(unsafe {
raw::i2c_transfer(self.device, msgs.as_mut_ptr(), ops.len() as u8, addr)
})
Expand Down
27 changes: 21 additions & 6 deletions zephyr/src/device/i2c/target.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ pub struct I2cTargetData<T: I2cTargetCallbacks> {
// the `node` field is managed by Zephyr's internal linked list under its own
// lock).
unsafe impl<T: I2cTargetCallbacks> Send for I2cTargetData<T> {}
// SAFETY: See the `Send` impl above; the same single-writer argument covers shared access.
unsafe impl<T: I2cTargetCallbacks> Sync for I2cTargetData<T> {}

impl<T: I2cTargetCallbacks> I2cTargetData<T> {
Expand Down Expand Up @@ -189,12 +190,10 @@ impl<T: I2cTargetCallbacks> I2cTargetData<T> {
config.callbacks = self.cbs.get() as *const _;
}

if let Err(e) =
to_result_void(unsafe { raw::i2c_target_register(i2c.device, self.config.get()) })
{
self.registered.store(false, Ordering::Release);
return Err(e);
}
// SAFETY: `i2c.device` is a valid device, and `self.config` is `'static` and fully
// populated above, so it stays valid while registered.
to_result_void(unsafe { raw::i2c_target_register(i2c.device, self.config.get()) })
.inspect_err(|_| self.registered.store(false, Ordering::Release))?;

Ok(I2cTarget {
device: i2c.device,
Expand All @@ -211,12 +210,16 @@ impl<T: I2cTargetCallbacks> I2cTargetData<T> {
///
/// `ptr` must originate from the `config` field of a live `I2cTargetData<T>`.
unsafe fn from_config(ptr: *mut i2c_target_config) -> &'static Self {
// SAFETY: The caller guarantees `ptr` is the first field of a live, `'static`
// `I2cTargetData<T>`, and the `#[repr(C)]` layout makes it address-equal to `Self`.
unsafe { &*(ptr as *const Self) }
}

// -- C-ABI trampoline functions -------------------------------------------

unsafe extern "C" fn write_requested_trampoline(config: *mut i2c_target_config) -> c_int {
// SAFETY: Zephyr passes the config registered by `register`, which is the first field of a
// `'static` `Self`.
let this = unsafe { Self::from_config(config) };
match this.data.write_requested() {
Ok(()) => 0,
Expand All @@ -228,6 +231,8 @@ impl<T: I2cTargetCallbacks> I2cTargetData<T> {
config: *mut i2c_target_config,
val: u8,
) -> c_int {
// SAFETY: Zephyr passes the config registered by `register`, which is the first field of a
// `'static` `Self`.
let this = unsafe { Self::from_config(config) };
match this.data.write_received(val) {
Ok(()) => 0,
Expand All @@ -239,9 +244,12 @@ impl<T: I2cTargetCallbacks> I2cTargetData<T> {
config: *mut i2c_target_config,
val: *mut u8,
) -> c_int {
// SAFETY: Zephyr passes the config registered by `register`, which is the first field of a
// `'static` `Self`.
let this = unsafe { Self::from_config(config) };
match this.data.read_requested() {
Ok(byte) => {
// SAFETY: The driver passes a valid, writable `val` for the byte to send.
unsafe { *val = byte };
0
}
Expand All @@ -253,9 +261,12 @@ impl<T: I2cTargetCallbacks> I2cTargetData<T> {
config: *mut i2c_target_config,
val: *mut u8,
) -> c_int {
// SAFETY: Zephyr passes the config registered by `register`, which is the first field of a
// `'static` `Self`.
let this = unsafe { Self::from_config(config) };
match this.data.read_processed() {
Ok(byte) => {
// SAFETY: The driver passes a valid, writable `val` for the byte to send.
unsafe { *val = byte };
0
}
Expand All @@ -264,6 +275,8 @@ impl<T: I2cTargetCallbacks> I2cTargetData<T> {
}

unsafe extern "C" fn stop_trampoline(config: *mut i2c_target_config) -> c_int {
// SAFETY: Zephyr passes the config registered by `register`, which is the first field of a
// `'static` `Self`.
let this = unsafe { Self::from_config(config) };
match this.data.stop() {
Ok(()) => 0,
Expand Down Expand Up @@ -293,6 +306,8 @@ unsafe impl Send for I2cTarget {}
impl I2cTarget {
/// Unregister this I2C target from the bus.
pub fn unregister(self) -> Result<()> {
// SAFETY: `device` and `config` are the pair that was registered and are still valid; for
// `register_target` the caller promised the config outlives registration.
to_result_void(unsafe { raw::i2c_target_unregister(self.device, self.config) })?;
if let Some(registered) = self.registered {
registered.store(false, Ordering::Release);
Expand Down
6 changes: 6 additions & 0 deletions zephyr/src/device/led.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ impl LedController {

/// Verify that the underlying LED controller is ready for use.
pub fn is_ready(&self) -> bool {
// SAFETY: `self.device` is a valid `'static` device pointer from devicetree.
unsafe { raw::device_is_ready(self.device) }
}
}
Expand Down Expand Up @@ -67,26 +68,31 @@ impl Led {

/// Verify that the underlying LED controller is ready for use.
pub fn is_ready(&self) -> bool {
// SAFETY: `self.device` is a valid `'static` device pointer from devicetree.
unsafe { raw::device_is_ready(self.device) }
}

/// Set the LED brightness as a percentage in the range `0..=100`.
pub fn set_brightness(&mut self, value: u8) -> Result<()> {
// SAFETY: `self.device` is a valid device; `led_set_brightness` takes no pointer arguments.
to_result_void(unsafe { raw::led_set_brightness(self.device, self.index, value) })
}

/// Turn the LED fully on.
pub fn on(&mut self) -> Result<()> {
// SAFETY: `self.device` is a valid device, and `led_on` has no pointer arguments.
to_result_void(unsafe { raw::led_on(self.device, self.index) })
}

/// Turn the LED fully off.
pub fn off(&mut self) -> Result<()> {
// SAFETY: `self.device` is a valid device, and `led_off` has no pointer arguments.
to_result_void(unsafe { raw::led_off(self.device, self.index) })
}

/// Blink the LED using millisecond delays.
pub fn blink(&mut self, delay_on: u32, delay_off: u32) -> Result<()> {
// SAFETY: `self.device` is a valid device, and `led_blink` has no pointer arguments.
to_result_void(unsafe { raw::led_blink(self.device, self.index, delay_on, delay_off) })
}
}
6 changes: 6 additions & 0 deletions zephyr/src/device/led_strip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ impl LedStrip {

/// Verify that the underlying LED strip device is ready for use.
pub fn is_ready(&self) -> bool {
// SAFETY: `self.device` is a valid `'static` device pointer from devicetree.
unsafe { raw::device_is_ready(self.device) }
}

Expand All @@ -52,6 +53,8 @@ impl LedStrip {
///
/// The driver may overwrite the contents of `pixels`.
pub fn update_rgb(&mut self, pixels: &mut [LedRgb]) -> Result<()> {
// SAFETY: `self.device` is a valid device, and the pointer and length come from `pixels`,
// which is exclusively borrowed for this call.
to_result_void(unsafe {
raw::led_strip_update_rgb(self.device, pixels.as_mut_ptr(), pixels.len())
})
Expand All @@ -64,13 +67,16 @@ impl LedStrip {
///
/// The driver may overwrite the contents of `channels`.
pub fn update_channels(&mut self, channels: &mut [u8]) -> Result<()> {
// SAFETY: `self.device` is a valid device, and the pointer and length come from `channels`,
// which is exclusively borrowed for this call.
to_result_void(unsafe {
raw::led_strip_update_channels(self.device, channels.as_mut_ptr(), channels.len())
})
}

/// Return the number of pixels (LEDs) in the strip.
pub fn length(&self) -> usize {
// SAFETY: `self.device` is a valid `'static` device pointer from devicetree.
unsafe { raw::led_strip_length(self.device) }
}
}
4 changes: 4 additions & 0 deletions zephyr/src/embassy/executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ impl Executor {

loop {
let _ = self.poll_needed.take(Forever);
// SAFETY: `inner` was initialized above and is only polled from this thread, so `poll`
// is never called concurrently or reentrantly.
unsafe {
// The raw executor's poll only runs things that were queued _before_ this poll
// itself is actually run. This means, specifically, that if the polled execution
Expand All @@ -51,6 +53,8 @@ impl Default for Executor {

#[export_name = "__pender"]
fn __pender(context: *mut ()) {
// SAFETY: `context` is the `&'static mut Executor` given to `raw::Executor::new`, valid forever
// as `run` never returns; `give` only touches the kernel semaphore, which is ISR-safe.
unsafe {
let this = context as *const Executor;
(*this).poll_needed.give();
Expand Down
7 changes: 7 additions & 0 deletions zephyr/src/embassy/time_driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ use crate::sys::K_FOREVER;

embassy_time_driver::time_driver_impl!(static DRIVER: ZephyrTimeDriver = ZephyrTimeDriver {
queue: Mutex::new(RefCell::new(Queue::new())),
// SAFETY: A zeroed `ZTimer` is valid (zeroed `k_timer`, `initialized: false`), and
// `set_alarm` runs `k_timer_init` before first use.
timer: Mutex::new(RefCell::new(unsafe { mem::zeroed() })),
});

Expand All @@ -39,6 +41,9 @@ impl ZTimer {

// Otherwise, initialize our timer, and handle it.
if !self.initialized {
// SAFETY: `&mut self` is exclusive and `item` lives in the static `DRIVER`, so it never
// moves; `initialized` ensures it is initialized once, and `timer_tick` matches the
// expiry signature.
unsafe {
k_timer_init(self.item.get(), Some(Self::timer_tick), None);
}
Expand All @@ -51,6 +56,8 @@ impl ZTimer {
ticks: (next - now + 1) as i64,
};
let period = K_FOREVER;
// SAFETY: `item` was initialized above and is pinned in the static `DRIVER`; `&mut self`
// and the critical section serialize use.
unsafe {
k_timer_start(self.item.get(), delta, period);
}
Expand Down
4 changes: 4 additions & 0 deletions zephyr/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@

#![no_std]
#![allow(unexpected_cfgs)]
#![allow(clippy::new_without_default)]
#![deny(missing_docs)]

// Allow this crate to refer to itself by name
Expand Down Expand Up @@ -131,6 +132,9 @@ pub mod devicetree {
// Allow nodes to have non-snake-case names. This comes from addresses in the node names, which
// usually use uppercase.
#![allow(non_snake_case)]
// `quote!` cannot emit comments. Each generated `get_instance` passes a node's own device
// pointer, `Unique` and static to the device constructor, which is that constructor's contract.
#![allow(clippy::undocumented_unsafe_blocks)]

/// An expanded property in the devicetree.
#[derive(Debug)]
Expand Down
4 changes: 4 additions & 0 deletions zephyr/src/logging/impl_zlog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ impl Log for ZlogLogger {
// Append a null so this is a valid C string. This lets us avoid an additional allocation
// and copying.
msg.push('\x00');
// SAFETY: `msg` is NUL-terminated by the push above and stays valid for the duration of the
// call.
unsafe {
rust_log_message(level, msg.as_ptr() as *const c_char);
}
Expand All @@ -56,6 +58,8 @@ static ZLOG_LOGGER: ZlogLogger = ZlogLogger;

/// Set the log handler to log messages through Zephyr's logging framework.
///
/// # Safety
///
/// This is unsafe due to racy issues in the log framework on targets that do not support atomic
/// pointers.
pub unsafe fn set_logger() -> Result<(), SetLoggerError> {
Expand Down
Loading
Loading