diff --git a/zephyr-build/src/devicetree/augment.rs b/zephyr-build/src/devicetree/augment.rs index c0608ed8..064ab77d 100644 --- a/zephyr-build/src/devicetree/augment.rs +++ b/zephyr-build/src/devicetree/augment.rs @@ -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 } diff --git a/zephyr/src/alloc_impl.rs b/zephyr/src/alloc_impl.rs index 3c2046d3..c1881f1f 100644 --- a/zephyr/src/alloc_impl.rs +++ b/zephyr/src/alloc_impl.rs @@ -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(); diff --git a/zephyr/src/device/gpio.rs b/zephyr/src/device/gpio.rs index f3935318..67c21df6 100644 --- a/zephyr/src/device/gpio.rs +++ b/zephyr/src/device/gpio.rs @@ -52,6 +52,9 @@ mod async_io { callback: UnsafeCell, } + // 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 { @@ -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; } @@ -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::() .sub(mem::offset_of!(Self, callback)) @@ -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); @@ -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) } } } @@ -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, @@ -385,6 +396,7 @@ 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); } @@ -392,6 +404,7 @@ impl GpioPin { /// 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); } @@ -399,6 +412,7 @@ impl GpioPin { /// 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, diff --git a/zephyr/src/device/i2c/controller.rs b/zephyr/src/device/i2c/controller.rs index f23c0765..027ead68 100644 --- a/zephyr/src/device/i2c/controller.rs +++ b/zephyr/src/device/i2c/controller.rs @@ -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, @@ -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) }) @@ -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) }) diff --git a/zephyr/src/device/i2c/target.rs b/zephyr/src/device/i2c/target.rs index 865f321e..f68a4a15 100644 --- a/zephyr/src/device/i2c/target.rs +++ b/zephyr/src/device/i2c/target.rs @@ -119,6 +119,7 @@ pub struct I2cTargetData { // the `node` field is managed by Zephyr's internal linked list under its own // lock). unsafe impl Send for I2cTargetData {} +// SAFETY: See the `Send` impl above; the same single-writer argument covers shared access. unsafe impl Sync for I2cTargetData {} impl I2cTargetData { @@ -189,12 +190,10 @@ impl I2cTargetData { 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, @@ -211,12 +210,16 @@ impl I2cTargetData { /// /// `ptr` must originate from the `config` field of a live `I2cTargetData`. 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`, 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, @@ -228,6 +231,8 @@ impl I2cTargetData { 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, @@ -239,9 +244,12 @@ impl I2cTargetData { 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 } @@ -253,9 +261,12 @@ impl I2cTargetData { 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 } @@ -264,6 +275,8 @@ impl I2cTargetData { } 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, @@ -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); diff --git a/zephyr/src/device/led.rs b/zephyr/src/device/led.rs index bcf65f96..72b7f7a3 100644 --- a/zephyr/src/device/led.rs +++ b/zephyr/src/device/led.rs @@ -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) } } } @@ -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) }) } } diff --git a/zephyr/src/device/led_strip.rs b/zephyr/src/device/led_strip.rs index 8ef58e29..9608db10 100644 --- a/zephyr/src/device/led_strip.rs +++ b/zephyr/src/device/led_strip.rs @@ -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) } } @@ -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()) }) @@ -64,6 +67,8 @@ 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()) }) @@ -71,6 +76,7 @@ impl LedStrip { /// 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) } } } diff --git a/zephyr/src/embassy/executor.rs b/zephyr/src/embassy/executor.rs index 8d8c1490..b17272e4 100644 --- a/zephyr/src/embassy/executor.rs +++ b/zephyr/src/embassy/executor.rs @@ -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 @@ -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(); diff --git a/zephyr/src/embassy/time_driver.rs b/zephyr/src/embassy/time_driver.rs index c9e73247..b5d90a33 100644 --- a/zephyr/src/embassy/time_driver.rs +++ b/zephyr/src/embassy/time_driver.rs @@ -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() })), }); @@ -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); } @@ -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); } diff --git a/zephyr/src/lib.rs b/zephyr/src/lib.rs index 8e4bf8e8..5298b8ee 100644 --- a/zephyr/src/lib.rs +++ b/zephyr/src/lib.rs @@ -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 @@ -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)] diff --git a/zephyr/src/logging/impl_zlog.rs b/zephyr/src/logging/impl_zlog.rs index ec488d40..f013461d 100644 --- a/zephyr/src/logging/impl_zlog.rs +++ b/zephyr/src/logging/impl_zlog.rs @@ -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); } @@ -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> { diff --git a/zephyr/src/object.rs b/zephyr/src/object.rs index fb548f1f..8eaedfa6 100644 --- a/zephyr/src/object.rs +++ b/zephyr/src/object.rs @@ -216,7 +216,9 @@ where } // Perform the initialization. - >::init(addr); + // SAFETY: `addr` is this object's own storage, and the zero state observed inside the + // critical section means nothing else has initialized or used it. + unsafe { >::init(addr) }; self.state.store(addr as usize, Ordering::Release); @@ -234,7 +236,12 @@ pub trait ObjectInit { /// the initial address given to the `setup` call in the [`ZephyrObject::new_raw`] constructor. /// After this is called, all subsequent calls to [`ZephyrObject::get`] will return the same /// address, or panic. - fn init(item: *mut T); + /// + /// # Safety + /// + /// `item` must point to the storage of a [`ZephyrObject`] that has not been initialized, and + /// that storage must not move afterwards. + unsafe fn init(item: *mut T); } // The kernel object itself must be wrapped in `UnsafeCell` in Rust. This does several thing, but @@ -325,6 +332,8 @@ where /// uninitialized. pub const unsafe fn new() -> StaticKernelObject { StaticKernelObject { + // SAFETY: `T` is a Zephyr kernel object type, for which all-zero bytes is a valid, not + // yet initialized value; initialization is tracked separately in `init`. value: unsafe { mem::zeroed() }, init: AtomicUsize::new(KOBJ_UNINITIALIZED), } diff --git a/zephyr/src/printk.rs b/zephyr/src/printk.rs index 9a24a0f7..f8a1fda0 100644 --- a/zephyr/src/printk.rs +++ b/zephyr/src/printk.rs @@ -94,6 +94,8 @@ impl Context { fn flush(&mut self) { if self.count > 0 { + // SAFETY: `buf` is a live array and `count <= buf.len()` is maintained by `add_byte`, + // so the range passed is initialized and in bounds. unsafe { zephyr_sys::k_str_out(self.buf.as_mut_ptr() as *mut c_char, self.count); } diff --git a/zephyr/src/simpletls.rs b/zephyr/src/simpletls.rs index 9d920e51..9c936da5 100644 --- a/zephyr/src/simpletls.rs +++ b/zephyr/src/simpletls.rs @@ -42,6 +42,7 @@ impl SimpleTls { /// Lookup the data associated with a given thread. pub fn get(&self) -> Option { + // SAFETY: `k_current_get` has no preconditions and returns the current thread's id. let thread = unsafe { k_current_get() } as usize; self.map diff --git a/zephyr/src/sync/channel.rs b/zephyr/src/sync/channel.rs index 872495fe..ead738a9 100644 --- a/zephyr/src/sync/channel.rs +++ b/zephyr/src/sync/channel.rs @@ -142,6 +142,8 @@ pub struct Sender { // SAFETY: We implement Send and Sync for the Sender itself, as long as the underlying data can be // sent. The underlying zephyr primitives used for the channel provide the Sync safety. unsafe impl Send for Sender {} +// SAFETY: Same reasoning as `Send` above: a `&Sender` only reaches `Sync` kernel queues and atomic +// counts, and every message moved through is `T: Send`. unsafe impl Sync for Sender {} impl Sender { @@ -176,6 +178,9 @@ impl Sender { return Err(SendError(msg)); } let buf = buf as *mut Message; + // SAFETY: `buf` came from the free queue, so this sender owns the slot until it is + // sent; it is a slot of `Bounded` valid for a `Message` write, and is handed + // to the kernel only after. unsafe { buf.write(Message::new(msg)); chan.chan.send(buf as *mut c_void); @@ -266,6 +271,8 @@ pub struct Receiver { // SAFETY: We implement Send and Sync for the Receiver itself, as long as the underlying data can be // sent. The underlying zephyr primitives used for the channel provide the Sync safety. unsafe impl Send for Receiver {} +// SAFETY: Same reasoning as `Send` above: a `&Receiver` only reaches `Sync` kernel queues and +// atomic counts, and every message moved out is `T: Send`. unsafe impl Sync for Receiver {} impl Receiver { @@ -306,7 +313,13 @@ impl Receiver { buf }; let buf = rawbuf as *mut Message; + // SAFETY: `buf` was just dequeued from `chan`, so it is an initialized `Message` + // written by a sender and owned exclusively by this receiver; it is not returned to + // the free queue until read. let msg: Message = unsafe { buf.read() }; + // SAFETY: The slot was fully read out above, so recycling it on the free queue + // hands over no live value; `buf` is a slot of this `Bounded` and is not accessed + // again here. unsafe { chan.free.send(buf as *mut c_void); } diff --git a/zephyr/src/sync/channel/counter.rs b/zephyr/src/sync/channel/counter.rs index f72b5b1f..696d356d 100644 --- a/zephyr/src/sync/channel/counter.rs +++ b/zephyr/src/sync/channel/counter.rs @@ -46,6 +46,8 @@ pub(crate) struct Sender { impl Sender { /// Returns the internal `Counter`. fn counter(&self) -> &Counter { + // SAFETY: `counter` came from `Box::leak` in `new` and is freed only when both sides have + // been released, which cannot happen while `self` still holds a reference. unsafe { self.counter.as_ref() } } @@ -74,6 +76,9 @@ impl Sender { disconnect(&self.counter().chan); if self.counter().destroy.swap(true, Ordering::AcqRel) { + // SAFETY: `destroy` is flipped by whichever side releases last, so exactly one + // caller reaches here, after both counts hit zero; the pointer came from + // `Box::leak` and is never used again. drop(unsafe { Box::from_raw(self.counter.as_ptr()) }); } } @@ -102,6 +107,8 @@ pub(crate) struct Receiver { impl Receiver { /// Returns the internal `Counter`. fn counter(&self) -> &Counter { + // SAFETY: `counter` came from `Box::leak` in `new` and is freed only when both sides have + // been released, which cannot happen while `self` still holds a reference. unsafe { self.counter.as_ref() } } @@ -129,6 +136,9 @@ impl Receiver { disconnect(&self.counter().chan); if self.counter().destroy.swap(true, Ordering::AcqRel) { + // SAFETY: `destroy` is flipped by whichever side releases last, so exactly one + // caller reaches here, after both counts hit zero; the pointer came from + // `Box::leak` and is never used again. drop(unsafe { Box::from_raw(self.counter.as_ptr()) }); } } diff --git a/zephyr/src/sync/mutex.rs b/zephyr/src/sync/mutex.rs index a6c7ccc6..085b99de 100644 --- a/zephyr/src/sync/mutex.rs +++ b/zephyr/src/sync/mutex.rs @@ -51,9 +51,11 @@ pub struct Mutex { data: UnsafeCell, } -// At least if correctly done, the Mutex provides for Send and Sync as long as the inner data -// supports Send. +// SAFETY: At least if correctly done, the Mutex provides for Send and Sync as long as the inner +// data supports Send. unsafe impl Send for Mutex {} +// SAFETY: `data` is only reached through a `MutexGuard`, which holds the `k_mutex` and the `locked` +// flag, so access is exclusive; moving `T` between threads needs `T: Send`. unsafe impl Sync for Mutex {} impl fmt::Debug for Mutex { @@ -85,6 +87,8 @@ pub struct MutexGuard<'a, T: ?Sized + 'a> { // Make sure the guard doesn't get sent. // Negative trait bounds are unstable, see marker above. // impl !Send for MutexGuard<'_, T> {} +// SAFETY: A `&MutexGuard` only gives `&T` (mutation needs `&mut self`), so sharing it across +// threads is sound exactly when `T: Sync`; the `*const ()` marker keeps the guard `!Send`. unsafe impl Sync for MutexGuard<'_, T> {} impl Mutex { @@ -125,6 +129,8 @@ impl Mutex { self.inner.unlock().unwrap(); panic!("cannot recursively lock Mutex"); } + // SAFETY: `inner` is locked and `locked` was just swapped false to true, so no other guard + // to `data` exists until this one drops. unsafe { Ok(MutexGuard::new(self)) } } @@ -142,6 +148,8 @@ impl Mutex { self.inner.unlock().unwrap(); Err(TryLockError::WouldBlock) } else { + // SAFETY: `inner` is locked and `locked` was just swapped false to true, so no + // other guard to `data` exists until this one drops. unsafe { Ok(MutexGuard::new(self)) } } } @@ -166,12 +174,16 @@ impl Deref for MutexGuard<'_, T> { type Target = T; fn deref(&self) -> &T { + // SAFETY: A guard exists only while the mutex is held with `locked` set, so no `&mut T` + // aliases this shared borrow. unsafe { &*self.lock.data.get() } } } impl DerefMut for MutexGuard<'_, T> { fn deref_mut(&mut self) -> &mut T { + // SAFETY: A guard exists only while the mutex is held with `locked` set, and `&mut self` + // makes this the only access through it, so the `&mut T` is unique. unsafe { &mut *self.lock.data.get() } } } diff --git a/zephyr/src/sync/spinmutex.rs b/zephyr/src/sync/spinmutex.rs index a741022b..ee7fdbeb 100644 --- a/zephyr/src/sync/spinmutex.rs +++ b/zephyr/src/sync/spinmutex.rs @@ -58,7 +58,11 @@ pub struct SpinMutex { /// satisfies Rust's requirements for Send and Sync. The dependency of both on "Send" of the data /// type is intentional, as it is the Mutex that is providing the Sync semantics. However, it only /// makes sense for types that are usable from multiple thread contexts. +// SAFETY: `data` is only reached through a guard that holds the spinlock, so access is exclusive; +// moving `T` between threads needs `T: Send`. unsafe impl Send for SpinMutex {} +// SAFETY: `data` is only reached through a guard that holds the spinlock, so access is exclusive; +// moving `T` between threads needs `T: Send`. unsafe impl Sync for SpinMutex {} impl fmt::Debug for SpinMutex { @@ -83,17 +87,21 @@ pub struct SpinMutexGuard<'a, T: ?Sized + 'a> { lock: &'a SpinMutex, key: raw::k_spinlock_key_t, // Mark as not Send. - _nosend: PhantomData>, + _nosend: PhantomData<*const ()>, } // Negative trait bounds are unstable, see the _nosend field above. /// Mark as Sync if the contained data is sync. +// SAFETY: A `&SpinMutexGuard` only gives `&T` (mutation needs `&mut self`), so sharing it is sound +// when `T: Sync`. unsafe impl Sync for SpinMutexGuard<'_, T> {} impl SpinMutex { /// Construct a new wrapped Mutex. pub const fn new(t: T) -> SpinMutex { SpinMutex { + // SAFETY: An all-zero `k_spinlock` is its valid unlocked state, matching + // `K_SPINLOCK_INIT`. inner: UnsafeCell::new(unsafe { core::mem::zeroed() }), data: UnsafeCell::new(t), } @@ -107,7 +115,10 @@ impl SpinMutex { /// Returns an RAII guard to allow scoped unlock of the lock. When the guard goes out of scope, /// the SpinMutex will be unlocked. pub fn lock(&self) -> SpinLockResult> { + // SAFETY: `self.inner` is a valid `k_spinlock` for the `&self` borrow; `k_spin_lock` may be + // called from any context and the returned key is held in the guard to unlock. let key = unsafe { raw::k_spin_lock(self.inner.get()) }; + // SAFETY: The spinlock was just acquired, giving the guard exclusive access to `data`. unsafe { Ok(SpinMutexGuard::new(self, key)) } } @@ -119,7 +130,11 @@ impl SpinMutex { /// This function does not block. pub fn try_lock(&self) -> SpinTryLockResult> { let mut key = raw::k_spinlock_key_t { key: 0 }; + // SAFETY: `self.inner` is a valid `k_spinlock` for the `&self` borrow and `key` is a valid + // out-parameter that is read only if the lock was acquired. match unsafe { raw::k_spin_trylock(self.inner.get(), &mut key) } { + // SAFETY: `k_spin_trylock` returned 0, so the spinlock is held and the guard owns + // `key`. 0 => unsafe { Ok(SpinMutexGuard::new(self, key)) }, _ => Err(SpinTryLockError::WouldBlock), } @@ -143,12 +158,16 @@ impl Deref for SpinMutexGuard<'_, T> { type Target = T; fn deref(&self) -> &T { + // SAFETY: A guard exists only while the spinlock is held, so no `&mut T` aliases this + // borrow. unsafe { &*self.lock.data.get() } } } impl DerefMut for SpinMutexGuard<'_, T> { fn deref_mut(&mut self) -> &mut T { + // SAFETY: A guard exists only while the spinlock is held, and `&mut self` makes this the + // only access through it, so the `&mut T` is unique. unsafe { &mut *self.lock.data.get() } } } @@ -156,6 +175,8 @@ impl DerefMut for SpinMutexGuard<'_, T> { impl Drop for SpinMutexGuard<'_, T> { #[inline] fn drop(&mut self) { + // SAFETY: The guard holds the lock on `self.lock.inner` with `self.key` from the matching + // `k_spin_lock`/`k_spin_trylock`, and is unlocked exactly once here. unsafe { raw::k_spin_unlock(self.lock.inner.get(), self.key); } diff --git a/zephyr/src/sys.rs b/zephyr/src/sys.rs index e16c2552..c6d2db97 100644 --- a/zephyr/src/sys.rs +++ b/zephyr/src/sys.rs @@ -36,6 +36,7 @@ pub const K_NO_WAIT: k_timeout_t = k_timeout_t { ticks: 0 }; /// Direct Zephyr call. Precision is limited by the system tick timer. #[inline] pub fn uptime_get() -> i64 { + // SAFETY: `k_uptime_get` has no preconditions and may be called from any context. unsafe { crate::raw::k_uptime_get() } } @@ -65,6 +66,8 @@ pub mod critical { struct ZephyrCriticalSection; critical_section::set_impl!(ZephyrCriticalSection); + // SAFETY: `acquire` returns the `irq_lock` key and `release` restores it with `irq_unlock`, so + // nesting is sound and the lock is released in the matching order. unsafe impl critical_section::Impl for ZephyrCriticalSection { unsafe fn acquire() -> RawRestoreState { let res = zr_irq_lock(); diff --git a/zephyr/src/sys/queue.rs b/zephyr/src/sys/queue.rs index 5a2cf682..36f94b29 100644 --- a/zephyr/src/sys/queue.rs +++ b/zephyr/src/sys/queue.rs @@ -15,7 +15,10 @@ use crate::time::Timeout; /// A wrapper around a Zephyr `k_queue` object. pub struct Queue(pub(crate) ZephyrObject); +// SAFETY: The wrapped `k_queue` is only used through kernel calls, which synchronize internally, +// and `ZephyrObject` initializes it once under a critical section. unsafe impl Sync for Queue {} +// SAFETY: As for `Sync`: the `k_queue` is not tied to a thread and the kernel synchronizes access. unsafe impl Send for Queue {} impl Queue { @@ -89,7 +92,7 @@ impl Queue { } impl ObjectInit for ZephyrObject { - fn init(item: *mut k_queue) { + unsafe fn init(item: *mut k_queue) { // SAFETY: ZephyrObject handles initialization and move prevention. unsafe { k_queue_init(item); diff --git a/zephyr/src/sys/sync/mutex.rs b/zephyr/src/sys/sync/mutex.rs index bd14a06b..c80998f7 100644 --- a/zephyr/src/sys/sync/mutex.rs +++ b/zephyr/src/sys/sync/mutex.rs @@ -67,6 +67,8 @@ impl Mutex { T: Into, { let timeout: Timeout = timeout.into(); + // SAFETY: `self.item.get()` is valid for the `&self` borrow. `k_mutex_lock` must not be + // called from an ISR, which is not enforced here. to_result_void(unsafe { k_mutex_lock(self.item.get(), timeout.0) }) } @@ -75,12 +77,14 @@ impl Mutex { /// The mutex must already be locked by the calling thread. Mutexes may not be unlocked in /// ISRs. pub fn unlock(&self) -> Result<()> { + // SAFETY: `self.item.get()` is valid for the `&self` borrow; the kernel rejects an unlock + // by a thread that is not the owner with an error return. to_result_void(unsafe { k_mutex_unlock(self.item.get()) }) } } impl ObjectInit for ZephyrObject { - fn init(item: *mut k_mutex) { + unsafe fn init(item: *mut k_mutex) { // SAFETY: ZephyrObject handles initialization and move prevention. unsafe { k_mutex_init(item); @@ -97,12 +101,15 @@ impl ObjectInit for ZephyrObject { /// [`init_once`]: StaticMutex::init_once pub type StaticMutex = StaticKernelObject; +// SAFETY: The `k_mutex` is only used through kernel calls, which are valid from any thread. unsafe impl Sync for Mutex {} +// SAFETY: The `k_mutex` is not tied to a thread; see the `Sync` impl. unsafe impl Send for Mutex {} -// Sync and Send are meaningful, as the underlying Zephyr API can use these values from any thread. -// Care must be taken to use these in a safe manner. +// SAFETY: Sync and Send are meaningful, as the underlying Zephyr API can use these values from any +// thread. Care must be taken to use these in a safe manner. unsafe impl Sync for StaticMutex {} +// SAFETY: See the `Sync` impl above. unsafe impl Send for StaticMutex {} impl fmt::Debug for Mutex { @@ -122,9 +129,12 @@ pub struct Condvar { #[doc(hidden)] pub type StaticCondvar = StaticKernelObject; +// SAFETY: The `k_condvar` is only used through kernel calls, which are valid from any thread. unsafe impl Sync for StaticKernelObject {} +// SAFETY: The `k_condvar` is only used through kernel calls, which are valid from any thread. unsafe impl Sync for Condvar {} +// SAFETY: The `k_condvar` is not tied to a thread; see the `Sync` impl. unsafe impl Send for Condvar {} impl Condvar { @@ -146,6 +156,9 @@ impl Condvar { /// [`sync::Condvar`]: http://www.example.com/TODO // /// [`sync::Condvar`]: crate::sync::Condvar pub fn wait(&self, lock: &Mutex) { + // SAFETY: Both `item` pointers are valid for their `&self`/`&Mutex` borrows. + // `k_condvar_wait` with `K_FOREVER` may block, so it must not be called from an ISR, which + // is not enforced here. unsafe { k_condvar_wait(self.item.get(), lock.item.get(), K_FOREVER); } @@ -155,6 +168,7 @@ impl Condvar { /// Wake a single thread waiting on this condition variable. pub fn notify_one(&self) { + // SAFETY: `self.item.get()` is valid for the `&self` borrow. unsafe { k_condvar_signal(self.item.get()); } @@ -162,6 +176,7 @@ impl Condvar { /// Wake all threads waiting on this condition variable. pub fn notify_all(&self) { + // SAFETY: `self.item.get()` is valid for the `&self` borrow. unsafe { k_condvar_broadcast(self.item.get()); } @@ -169,7 +184,7 @@ impl Condvar { } impl ObjectInit for ZephyrObject { - fn init(item: *mut k_condvar) { + unsafe fn init(item: *mut k_condvar) { // SAFETY: ZephyrObject handles initialization and move prevention. unsafe { k_condvar_init(item); diff --git a/zephyr/src/sys/sync/semaphore.rs b/zephyr/src/sys/sync/semaphore.rs index a5e69717..0f874c0a 100644 --- a/zephyr/src/sys/sync/semaphore.rs +++ b/zephyr/src/sys/sync/semaphore.rs @@ -28,7 +28,9 @@ pub struct Semaphore(pub(crate) ZephyrObject); /// By nature, Semaphores are both Sync and Send. Safety is handled by the underlying Zephyr /// implementation (which is why Clone is also implemented). +// SAFETY: The `k_sem` is only used through kernel calls, which synchronize internally. unsafe impl Sync for Semaphore {} +// SAFETY: The `k_sem` is not tied to a thread; see the `Sync` impl. unsafe impl Send for Semaphore {} impl Semaphore { @@ -49,6 +51,8 @@ impl Semaphore { let this = >::new_raw(); + // SAFETY: `this` is not yet shared or initialized by the kernel, so `get_uninit` points to + // a live, exclusively owned `k_sem` and writing its plain integer fields is sound. unsafe { let addr = this.get_uninit(); (*addr).count = initial_count; @@ -69,6 +73,8 @@ impl Semaphore { T: Into, { let timeout: Timeout = timeout.into(); + // SAFETY: `self.0.get()` is valid for the `&self` borrow. A non-zero timeout may block, so + // it must not be used from an ISR, which is not enforced here. let ret = unsafe { k_sem_take(self.0.get(), timeout.0) }; to_result_void(ret) } @@ -78,6 +84,8 @@ impl Semaphore { /// This routine gives to the semaphore, unless the semaphore is already at its maximum /// permitted count. pub fn give(&self) { + // SAFETY: `self.0.get()` is valid for the `&self` borrow; `k_sem_give` may be called from + // any context. unsafe { k_sem_give(self.0.get()) } } @@ -88,6 +96,7 @@ impl Semaphore { /// /// [`take`]: Self::take pub fn reset(&self) { + // SAFETY: `self.0.get()` is valid for the `&self` borrow. unsafe { k_sem_reset(self.0.get()) } } @@ -95,13 +104,14 @@ impl Semaphore { /// /// Returns the current count. pub fn count_get(&self) -> usize { + // SAFETY: `self.0.get()` is valid for the `&self` borrow. unsafe { k_sem_count_get(self.0.get()) as usize } } } impl ObjectInit for ZephyrObject { - fn init(item: *mut k_sem) { - // SAFEFY: Get the initial values used in new. The address may have changed, but only due + unsafe fn init(item: *mut k_sem) { + // SAFETY: Get the initial values used in new. The address may have changed, but only due // to a move. unsafe { let count = (*item).count; diff --git a/zephyr/src/sys/thread.rs b/zephyr/src/sys/thread.rs index 771da5fc..10484507 100644 --- a/zephyr/src/sys/thread.rs +++ b/zephyr/src/sys/thread.rs @@ -79,6 +79,8 @@ pub struct RealStaticThreadStack { extra: [z_thread_stack_element; ZR_STACK_RESERVED], } +// SAFETY: The stack bytes are never read or written from Rust; the struct is only used to place +// memory that is handed to the kernel for a single thread. unsafe impl Sync for RealStaticThreadStack {} /// The dynamic stack value, which wraps the underlying stack. @@ -89,6 +91,11 @@ pub struct ThreadStack { impl ThreadStack { /// Construct a new `ThreadStack` from a raw base pointer and size. + /// + /// # Safety + /// + /// `base` must point to a Zephyr thread stack of `size` bytes that outlives every thread + /// started on it. pub unsafe fn new(base: *mut z_thread_stack_element, size: usize) -> Self { Self { base, size } } @@ -110,6 +117,8 @@ pub struct StaticThreadStack { pub size: usize, } +// SAFETY: `value` is written only by the const constructors and never afterwards, so sharing +// `&self` only produces concurrent reads of an immutable base pointer and size. unsafe impl Sync for StaticKernelObject {} /* @@ -134,7 +143,11 @@ impl Wrapped for StaticKernelObject { fn get_wrapped(&self, _args: Self::I) -> Self::T { // This is a bit messy. Whee. let stack = self.value.get(); + // SAFETY: `value` is initialized by `new_from` and never mutated, so shared reads are + // sound. let stack = unsafe { &*stack }; + // SAFETY: `base` and `size` were taken from a `RealStaticThreadStack` static, which lives + // for the whole program. unsafe { ThreadStack::new(stack.base, stack.size) } } } @@ -171,6 +184,8 @@ impl StaticKernelObject { // let mut res: [MaybeUninit; N] = MaybeUninit::uninit_array(); // Note that `mem::uninitialized` in addition to being deprecated, isn't const. But, since // this is a const computation, zero-filling shouldn't hurt anything. + // SAFETY: An all-zero `StaticKernelObject` is valid (null pointer, zero + // size and counter, no `Drop`); every element is overwritten below. let mut res: [Self; N] = unsafe { mem::zeroed() }; let mut i = 0; while i < N { @@ -200,6 +215,9 @@ pub struct Thread { /// A statically defined thread. pub type StaticThread = StaticKernelObject; +// SAFETY: `value` is only handed to the kernel as a raw pointer, and `init_once` gates creation of +// the wrapper on an atomic, so Rust never forms conflicting references. Assumes callers do not +// invoke `Wrapped::get_wrapped` directly more than once. unsafe impl Sync for StaticThread {} impl Wrapped for StaticKernelObject { @@ -277,6 +295,8 @@ impl Thread { let child: closure::Closure = Box::new(child); let child = Box::into_raw(Box::new(closure::ThreadData { closure: child })); + // SAFETY: `self.raw` and the stack are valid for the thread's life per `ThreadStack::new`; + // `child` is a leaked box whose ownership passes to `closure::child`; `F` is `Send`. unsafe { let tid = k_thread_create( self.raw, @@ -297,6 +317,8 @@ impl Thread { fn set_thread_name(&mut self, tid: k_tid_t) { if let Some(name) = self.name { + // SAFETY: `tid` was just returned by `k_thread_create`, and `name` is `'static` and + // NUL-terminated. unsafe { k_thread_name_set(tid, name.as_ptr()); } @@ -518,6 +540,8 @@ mod closure { } pub unsafe extern "C" fn child(child: *mut c_void, _p2: *mut c_void, _p3: *mut c_void) { + // SAFETY: `child` is the pointer from `Box::into_raw` in `spawn`, passed once as the + // thread's first argument, so this is the unique owner and runs once. let thread_data: Box = unsafe { Box::from_raw(child as *mut ThreadData) }; let closure = thread_data.closure; closure(); diff --git a/zephyr/src/thread.rs b/zephyr/src/thread.rs index 42405fb7..6be68544 100644 --- a/zephyr/src/thread.rs +++ b/zephyr/src/thread.rs @@ -65,6 +65,8 @@ impl InitData { } } +// SAFETY: The cell is written only in a critical section before the thread is created, and read +// only by the created thread afterwards, so accesses never overlap; `T: Send` covers the handoff. unsafe impl Sync for InitData {} /// The static data associated with each thread. The stack is kept separate, as it is intended to @@ -81,6 +83,8 @@ impl ThreadData { Self { init: InitData::new(), state: AtomicU8::new(ThreadState::Init as u8), + // SAFETY: `Thread::new` is zeroed memory for a `k_thread`, which is initialized later + // by `k_thread_create`. thread: unsafe { Thread::new() }, } } @@ -104,6 +108,8 @@ impl ThreadData { .store(ThreadState::Allocated as u8, Ordering::Relaxed); let init = self.init.0.get(); + // SAFETY: This slot was just moved to `Allocated` under the critical section and no + // thread has been created on it, so nothing else reads the cell. unsafe { *init = Some(args); } @@ -112,6 +118,8 @@ impl ThreadData { // For now, just directly start the thread. We'll want to delay this so that parameters // (priority and/or flags) can be passed, as well as to have a handle to be able to join and // restart threads. + // SAFETY: The thread, stack and init cell are `'static`, and the entry receives the init + // cell pointer whose contents were set above; the thread owns that data once it runs. let _tid = unsafe { k_thread_create( self.thread.0.get(), @@ -140,11 +148,15 @@ impl ThreadData { let id = Self::find_thread(pool); let init = pool[id].init.0.get(); + // SAFETY: `find_thread` just claimed this slot under a critical section, so no other thread + // or running entry accesses its init cell. unsafe { *init = Some(args); } // Create the thread in Zephyr, in a non-running state. + // SAFETY: The thread, stack and init cell are `'static`, and the entry receives the init + // cell pointer whose contents were set above; the thread owns that data once it runs. let tid = unsafe { k_thread_create( pool[id].thread.0.get(), @@ -161,6 +173,8 @@ impl ThreadData { }; // Set the name. + // SAFETY: `tid` was just returned by `k_thread_create`, and `name` is `'static`, NUL + // terminated. unsafe { k_thread_name_set(tid, name.as_ptr()); } @@ -193,6 +207,8 @@ impl ThreadData { // A running thread might be available if it has terminated. We could // improve performance here by not checking these until after the pool has // been checked for Init threads. + // SAFETY: `thread.thread` is a valid `k_thread` for `'static`, and + // `K_NO_WAIT` never blocks. if unsafe { k_thread_join(thread.thread.0.get(), K_NO_WAIT) } == 0 { thread .state @@ -259,6 +275,7 @@ impl RunningThread { T: Into, { let timeout: Timeout = timeout.into(); + // SAFETY: `self.id` is a valid `k_thread` that was created by `k_thread_create`. let ret = unsafe { k_thread_join(self.id, timeout.0) }; to_result_void(ret) } @@ -295,6 +312,8 @@ pub struct ThreadStack { extra: [z_thread_stack_element; ZR_STACK_RESERVED], } +// SAFETY: The stack memory is never accessed from Rust; it is only passed to the kernel for the one +// thread that uses it. unsafe impl Sync for ThreadStack {} impl ThreadStack { @@ -323,6 +342,8 @@ pub struct Thread(pub UnsafeCell); // Threads are "sort of" thread safe. But, this declaration is needed to be able to declare these // statically, and all generated versions will protect the thread with a critical section. +// SAFETY: Rust only ever takes the address of the `k_thread` and never reads or writes through it; +// the kernel owns it, and creation is guarded by the pool's critical section. unsafe impl Sync for Thread {} impl Thread { diff --git a/zephyr/src/time.rs b/zephyr/src/time.rs index a67f3b09..8524f3cf 100644 --- a/zephyr/src/time.rs +++ b/zephyr/src/time.rs @@ -57,6 +57,7 @@ pub type Instant = fugit::Instant; /// Retrieve the current scheduler time as an Instant. This can be used to schedule timeouts at /// absolute points in time. pub fn now() -> Instant { + // SAFETY: `k_uptime_ticks` has no preconditions and may be called from any context. Instant::from_ticks(unsafe { k_uptime_ticks() as u64 }) } @@ -137,6 +138,7 @@ where T: Into, { let timeout: Timeout = timeout.into(); + // SAFETY: `k_sleep` has no pointer arguments; it must be called from a thread, not an ISR. let rest = unsafe { crate::raw::k_sleep(timeout.0) }; Duration::millis(rest as Tick) } diff --git a/zephyr/src/timer.rs b/zephyr/src/timer.rs index bfa224ca..a41125e7 100644 --- a/zephyr/src/timer.rs +++ b/zephyr/src/timer.rs @@ -62,6 +62,8 @@ impl StoppedTimer { /// Allocates a dynamically allocate timer. The time will not be running. #[cfg(CONFIG_RUST_ALLOC)] pub fn new() -> Self { + // SAFETY: A zeroed `k_timer` is a valid not yet initialized value; it is initialized below, + // after `Fixed` pins it. let item: Fixed = Fixed::new(unsafe { mem::zeroed() }); unsafe { // SAFETY: The `Fixed` type takes care of ensuring the timer is allocate at a fixed or diff --git a/zephyr/src/work.rs b/zephyr/src/work.rs index 7a02c6e5..13e18653 100644 --- a/zephyr/src/work.rs +++ b/zephyr/src/work.rs @@ -184,6 +184,8 @@ impl WorkQueueBuilder { /// /// TODO: Implement a 'start' that works from a static work queue. pub fn start(&self, stack: ThreadStack) -> WorkQueue { + // SAFETY: An all-zero `k_work_q` is valid input for `k_work_queue_init`, which initializes + // it. let item: Fixed = Fixed::new(unsafe { mem::zeroed() }); unsafe { // SAFETY: Initialize zeroed memory. @@ -236,7 +238,11 @@ pub struct WorkQueue { } /// Work queues can be referenced from multiple threads, and thus are Send and Sync. +// SAFETY: A `k_work_q` lives in a pinned allocation that is never freed (`Drop` panics), and the +// work queue API may be called from any thread. unsafe impl Send for WorkQueue {} +// SAFETY: A `k_work_q` lives in a pinned allocation that is never freed (`Drop` panics), and the +// work queue API may be called from any thread. unsafe impl Sync for WorkQueue {} impl Drop for WorkQueue { @@ -269,6 +275,8 @@ struct WorkQueueRef(*mut k_work_q); // SAFETY: The work queue reference is also safe for both Send and Sync per Zephyr semantics. unsafe impl Send for WorkQueueRef {} +// SAFETY: The wrapper is only a pointer to a `k_work_q` that is never freed and is shared behind a +// `Mutex`. unsafe impl Sync for WorkQueueRef {} /// Retrieve the current work queue, if we are running within one. @@ -306,6 +314,8 @@ pub struct Signal { // SAFETY: Zephyr's API maintains thread safety. unsafe impl Send for Signal {} +// SAFETY: `k_poll_signal` operations take an internal spinlock, and `Fixed` keeps it pinned and +// never freed while shared. unsafe impl Sync for Signal {} impl Signal { @@ -315,6 +325,7 @@ impl Signal { pub fn new() -> Signal { // SAFETY: The memory is zero initialized, and Fixed ensure that it never changes address. let item: Fixed = Fixed::new(unsafe { mem::zeroed() }); + // SAFETY: `item` is pinned, zeroed memory that `k_poll_signal_init` is meant to initialize. unsafe { k_poll_signal_init(item.get()); } @@ -364,6 +375,8 @@ impl Signal { /// process of expiring. The implication is that the signal will not be raised in this case. /// ... pub fn raise(&self, result: c_int) -> crate::Result<()> { + // SAFETY: `self.item` is initialized and pinned; `k_poll_signal_raise` may be called from + // any context, including ISRs. to_result_void(unsafe { k_poll_signal_raise(self.item.get(), result) }) } }