zephyr/device/
gpio.rs

1//! Most devices in Zephyr operate on a `struct device`.  This provides untyped access to
2//! devices.  We want to have stronger typing in the Zephyr interfaces, so most of these types
3//! will be wrapped in another structure.  This wraps a Gpio device, and provides methods to
4//! most of the operations on gpios.
5//!
6//! Safey: In general, even just using gpio pins is unsafe in Zephyr.  The gpio drivers are used
7//! pervasively throughout Zephyr device drivers.  As such, most of the calls in this module are
8//! unsafe.
9
10use core::ffi::c_int;
11
12use super::{NoStatic, Unique};
13use crate::raw;
14
15#[cfg(feature = "async-drivers")]
16mod async_io {
17    //! Async operations for gpio drivers.
18    //!
19    //! For now, we make an assumption that a gpio controller can contain up to 32 gpios, which is
20    //! the largest number currently used, although this might change with 64-bit targest in the
21    //! future.
22
23    use core::{
24        cell::UnsafeCell,
25        future::Future,
26        mem,
27        sync::atomic::Ordering,
28        task::{Poll, Waker},
29    };
30
31    use embassy_sync::waitqueue::AtomicWaker;
32    use zephyr_sys::{
33        device, gpio_add_callback, gpio_callback, gpio_init_callback, gpio_pin_interrupt_configure,
34        gpio_pin_interrupt_configure_dt, gpio_port_pins_t, ZR_GPIO_INT_LEVEL_HIGH,
35        ZR_GPIO_INT_LEVEL_LOW, ZR_GPIO_INT_MODE_DISABLE_ONLY,
36    };
37
38    use crate::sync::atomic::{AtomicBool, AtomicU32};
39
40    use super::GpioPin;
41
42    pub(crate) struct GpioStatic {
43        /// The wakers for each of the gpios.
44        wakers: [AtomicWaker; 32],
45        /// Indicates when an interrupt has fired.  Used to definitively indicate the event has
46        /// happened, so we can wake.
47        fired: AtomicU32,
48        /// Have we been initialized?
49        installed: AtomicBool,
50        /// The data for the callback itself.
51        callback: UnsafeCell<gpio_callback>,
52    }
53
54    unsafe impl Sync for GpioStatic {}
55
56    impl GpioStatic {
57        pub(crate) const fn new() -> Self {
58            Self {
59                wakers: [const { AtomicWaker::new() }; 32],
60                fired: AtomicU32::new(0),
61                installed: AtomicBool::new(false),
62                // SAFETY: `installed` will tell us this need to be installed.
63                callback: unsafe { mem::zeroed() },
64            }
65        }
66
67        /// Ensure that the callback has been installed.
68        pub(super) fn fast_install(&self, port: *const device) {
69            if !self.installed.load(Ordering::Acquire) {
70                self.install(port);
71            }
72        }
73
74        fn install(&self, port: *const device) {
75            critical_section::with(|_| {
76                if !self.installed.load(Ordering::Acquire) {
77                    let cb = self.callback.get();
78                    // SAFETY: We're in a critical section, so there should be no concurrent use,
79                    // and there should not be any calls from the driver.
80                    unsafe {
81                        gpio_init_callback(cb, Some(Self::callback_handler), 0);
82                        gpio_add_callback(port, cb);
83                    }
84
85                    self.installed.store(true, Ordering::Release);
86                }
87            })
88        }
89
90        /// Register (replacing) a given callback.
91        pub(super) fn register(&self, pin: u8, waker: &Waker) {
92            self.wakers[pin as usize].register(waker);
93
94            // SAFETY: Inherently unsafe, due to how the Zephyr API is defined.
95            // The API appears to assume coherent memory, which although untrue, probably is "close
96            // enough" on the supported targets.
97            // The main issue is to ensure that any race is resolved in the direction of getting the
98            // callback more than needed, rather than missing.  In the context here, ensure the
99            // waker is registered (which does use an atomic), before enabling the pin in the
100            // callback structure.
101            //
102            // If it seems that wakes are getting missed, it might be the case that this needs some
103            // kind of memory barrier.
104            let cb = self.callback.get();
105            unsafe {
106                (*cb).pin_mask |= 1 << pin;
107            }
108        }
109
110        extern "C" fn callback_handler(
111            port: *const device,
112            cb: *mut gpio_callback,
113            mut pins: gpio_port_pins_t,
114        ) {
115            let data = unsafe {
116                cb.cast::<u8>()
117                    .sub(mem::offset_of!(Self, callback))
118                    .cast::<Self>()
119            };
120
121            // For each pin we are informed of.
122            while pins > 0 {
123                let pin = pins.trailing_zeros();
124
125                pins &= !(1 << pin);
126
127                // SAFETY: Handling this correctly is a bit tricky, especially with the
128                // un-coordinated 'pin-mask' value.
129                //
130                // For level-triggered interrupts, not disabling this will result in an interrupt
131                // storm.
132                unsafe {
133                    // Disable the actual interrupt from the controller.
134                    gpio_pin_interrupt_configure(port, pin as u8, ZR_GPIO_INT_MODE_DISABLE_ONLY);
135
136                    // Remove the callback bit.  Unclear if this is actually useful.
137                    (*cb).pin_mask &= !(1 << pin);
138
139                    // Indicate that we have fired.
140                    // AcqRel is sufficient for ordering across a single atomic.
141                    (*data).fired.fetch_or(1 << pin, Ordering::AcqRel);
142
143                    // After the interrupt is off, wake the handler.
144                    (*data).wakers[pin as usize].wake();
145                }
146            }
147        }
148
149        /// Check if we have fired for a given pin.  Clears the status.
150        pub(crate) fn has_fired(&self, pin: u8) -> bool {
151            let value = self.fired.fetch_and(!(1 << pin), Ordering::AcqRel);
152            value & (1 << pin) != 0
153        }
154    }
155
156    impl GpioPin {
157        /// Asynchronously wait for a gpio pin to become high.
158        ///
159        /// # Safety
160        ///
161        /// Safety of multiple GPIOs depends on the underlying controller.
162        pub unsafe fn wait_for_high(&mut self) -> impl Future<Output = ()> + use<'_> {
163            GpioWait::new(self, 1)
164        }
165
166        /// Asynchronously wait for a gpio pin to become low.
167        ///
168        /// # Safety
169        ///
170        /// Safety of multiple GPIOs depends on the underlying controller.
171        pub unsafe fn wait_for_low(&mut self) -> impl Future<Output = ()> + use<'_> {
172            GpioWait::new(self, 0)
173        }
174    }
175
176    /// A future that waits for a gpio to become high.
177    pub struct GpioWait<'a> {
178        pin: &'a mut GpioPin,
179        level: u8,
180    }
181
182    impl<'a> GpioWait<'a> {
183        fn new(pin: &'a mut GpioPin, level: u8) -> Self {
184            Self { pin, level }
185        }
186    }
187
188    impl<'a> Future for GpioWait<'a> {
189        type Output = ();
190
191        fn poll(
192            self: core::pin::Pin<&mut Self>,
193            cx: &mut core::task::Context<'_>,
194        ) -> core::task::Poll<Self::Output> {
195            self.pin.data.fast_install(self.pin.pin.port);
196
197            // Early detection of the event.  Also clears.
198            // This should be non-racy as long as only one task at a time waits on the gpio.
199            if self.pin.data.has_fired(self.pin.pin.pin) {
200                return Poll::Ready(());
201            }
202
203            self.pin.data.register(self.pin.pin.pin, cx.waker());
204
205            let mode = match self.level {
206                0 => ZR_GPIO_INT_LEVEL_LOW,
207                1 => ZR_GPIO_INT_LEVEL_HIGH,
208                _ => unreachable!(),
209            };
210
211            unsafe {
212                gpio_pin_interrupt_configure_dt(&self.pin.pin, mode);
213
214                // Before sleeping, check if it fired, to avoid having to pend if it already
215                // happened.
216                if self.pin.data.has_fired(self.pin.pin.pin) {
217                    return Poll::Ready(());
218                }
219            }
220
221            Poll::Pending
222        }
223    }
224}
225
226#[cfg(not(feature = "async-drivers"))]
227mod async_io {
228    pub(crate) struct GpioStatic;
229
230    impl GpioStatic {
231        pub(crate) const fn new() -> Self {
232            Self
233        }
234    }
235}
236
237pub(crate) use async_io::*;
238
239/// A single instance of a zephyr device to manage a gpio controller.  A gpio controller
240/// represents a set of gpio pins, that are generally operated on by the same hardware block.
241pub struct Gpio {
242    /// The underlying device itself.
243    #[allow(dead_code)]
244    pub(crate) device: *const raw::device,
245    /// Our associated data, used for callbacks.
246    pub(crate) data: &'static GpioStatic,
247}
248
249// SAFETY: Gpio's can be shared with other threads.  Safety is maintained by the Token.
250unsafe impl Send for Gpio {}
251
252impl Gpio {
253    /// Constructor, used by the devicetree generated code.
254    ///
255    /// TODO: Guarantee single instancing.
256    #[allow(dead_code)]
257    pub(crate) unsafe fn new(
258        unique: &Unique,
259        data: &'static GpioStatic,
260        device: *const raw::device,
261    ) -> Option<Gpio> {
262        if !unique.once() {
263            return None;
264        }
265        Some(Gpio { device, data })
266    }
267
268    /// Verify that the device is ready for use.  At a minimum, this means the device has been
269    /// successfully initialized.
270    pub fn is_ready(&self) -> bool {
271        unsafe { raw::device_is_ready(self.device) }
272    }
273}
274
275/// A GpioPin represents a single pin on a gpio device.
276///
277/// This is a lightweight wrapper around the Zephyr `gpio_dt_spec` structure.
278#[allow(dead_code)]
279pub struct GpioPin {
280    pub(crate) pin: raw::gpio_dt_spec,
281    pub(crate) data: &'static GpioStatic,
282}
283
284// SAFETY: GpioPin's can be shared with other threads.  Safety is maintained by the Token.
285unsafe impl Send for GpioPin {}
286
287impl GpioPin {
288    /// Constructor, used by the devicetree generated code.
289    #[allow(dead_code)]
290    pub(crate) unsafe fn new(
291        unique: &Unique,
292        _static: &NoStatic,
293        device: *const raw::device,
294        device_static: &'static GpioStatic,
295        pin: u32,
296        dt_flags: u32,
297    ) -> Option<GpioPin> {
298        if !unique.once() {
299            return None;
300        }
301        Some(GpioPin {
302            pin: raw::gpio_dt_spec {
303                port: device,
304                pin: pin as raw::gpio_pin_t,
305                dt_flags: dt_flags as raw::gpio_dt_flags_t,
306            },
307            data: device_static,
308        })
309    }
310
311    /// Verify that the device is ready for use.  At a minimum, this means the device has been
312    /// successfully initialized.
313    pub fn is_ready(&self) -> bool {
314        self.get_gpio().is_ready()
315    }
316
317    /// Get the underlying Gpio device.
318    pub fn get_gpio(&self) -> Gpio {
319        Gpio {
320            device: self.pin.port,
321            data: self.data,
322        }
323    }
324
325    /// Configure a single pin.
326    ///
327    /// # Safety
328    ///
329    /// Concurrency safety is determined by the underlying driver.
330    pub fn configure(&mut self, extra_flags: raw::gpio_flags_t) {
331        // TODO: Error?
332        unsafe {
333            raw::gpio_pin_configure(
334                self.pin.port,
335                self.pin.pin,
336                self.pin.dt_flags as raw::gpio_flags_t | extra_flags,
337            );
338        }
339    }
340
341    /// Toggle pin level.
342    ///
343    /// # Safety
344    ///
345    /// Concurrency safety is determined by the underlying driver.
346    pub fn toggle_pin(&mut self) {
347        // TODO: Error?
348        unsafe {
349            raw::gpio_pin_toggle_dt(&self.pin);
350        }
351    }
352
353    /// Set the logical level of the pin.
354    pub fn set(&mut self, value: bool) {
355        unsafe {
356            raw::gpio_pin_set_dt(&self.pin, value as c_int);
357        }
358    }
359
360    /// Read the logical level of the pin.
361    pub fn get(&mut self) -> bool {
362        unsafe {
363            match raw::gpio_pin_get_dt(&self.pin) {
364                0 => false,
365                1 => true,
366                _ => panic!("TODO: Handle gpio get error"),
367            }
368        }
369    }
370}