Skip to main content

capsules_core/
gpio.rs

1// Licensed under the Apache License, Version 2.0 or the MIT License.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3// Copyright Tock Contributors 2022.
4
5//! Provides userspace applications with access to GPIO pins.
6//!
7//! GPIOs are presented through a driver interface with synchronous commands
8//! and a callback for interrupts.
9//!
10//! This capsule takes an array of pins to expose as generic GPIOs.
11//! Note that this capsule is used for general purpose GPIOs. Pins that are
12//! attached to LEDs or buttons are generally wired directly to those capsules,
13//! not through this capsule as an intermediary.
14//!
15//! Usage
16//! -----
17//!
18//! ```rust,ignore
19//! # use kernel::static_init;
20//!
21//! let gpio_pins = static_init!(
22//!     [Option<&'static sam4l::gpio::GPIOPin>; 4],
23//!     [Option<&sam4l::gpio::PB[14]>,
24//!      Option<&sam4l::gpio::PB[15]>,
25//!      Option<&sam4l::gpio::PB[11]>,
26//!      Option<&sam4l::gpio::PB[12]>]);
27//! let gpio = static_init!(
28//!     capsules_core::gpio::GPIO<'static, sam4l::gpio::GPIOPin>,
29//!     capsules_core::gpio::GPIO::new(gpio_pins));
30//! for maybe_pin in gpio_pins.iter() {
31//!     if let Some(pin) = maybe_pin {
32//!         pin.set_client(gpio);
33//!     }
34//! }
35//! ```
36//!
37//! Syscall Interface
38//! -----------------
39//!
40//! - Stability: 2 - Stable
41//!
42//! ### Commands
43//!
44//! All GPIO operations are synchronous.
45//!
46//! Commands control and query GPIO information, namely how many GPIOs are
47//! present, the GPIO direction and state, and whether they should interrupt.
48//!
49//! ### Subscribes
50//!
51//! The GPIO interface provides only one callback, which is used for pins that
52//! have had interrupts enabled.
53
54/// Syscall driver number.
55use crate::driver;
56pub const DRIVER_NUM: usize = driver::NUM::Gpio as usize;
57
58use kernel::grant::{AllowRoCount, AllowRwCount, Grant, UpcallCount};
59use kernel::hil::gpio;
60use kernel::hil::gpio::{Configure, Input, InterruptWithValue, Output};
61use kernel::syscall::{CommandReturn, SyscallDriver};
62use kernel::{ErrorCode, ProcessId};
63
64/// ### `subscribe_num`
65///
66/// - `0`: Subscribe to interrupts from all pins with interrupts enabled. The
67///   callback signature is `fn(pin_num: usize, pin_state: bool)`
68const UPCALL_NUM: usize = 0;
69
70pub struct GPIO<'a, IP: gpio::InterruptPin<'a>> {
71    pins: &'a [Option<&'a gpio::InterruptValueWrapper<'a, IP>>],
72    apps: Grant<(), UpcallCount<1>, AllowRoCount<0>, AllowRwCount<0>>,
73}
74
75impl<'a, IP: gpio::InterruptPin<'a>> GPIO<'a, IP> {
76    pub fn new(
77        pins: &'a [Option<&'a gpio::InterruptValueWrapper<'a, IP>>],
78        grant: Grant<(), UpcallCount<1>, AllowRoCount<0>, AllowRwCount<0>>,
79    ) -> Self {
80        for (i, maybe_pin) in pins.iter().enumerate() {
81            if let Some(pin) = maybe_pin {
82                pin.set_value(i as u32);
83            }
84        }
85        Self { pins, apps: grant }
86    }
87
88    fn configure_input_pin(&self, pin_num: u32, config: usize) -> CommandReturn {
89        let maybe_pin = self.pins[pin_num as usize];
90        if let Some(pin) = maybe_pin {
91            pin.make_input();
92            match config {
93                0 => {
94                    pin.set_floating_state(gpio::FloatingState::PullNone);
95                    CommandReturn::success()
96                }
97                1 => {
98                    pin.set_floating_state(gpio::FloatingState::PullUp);
99                    CommandReturn::success()
100                }
101                2 => {
102                    pin.set_floating_state(gpio::FloatingState::PullDown);
103                    CommandReturn::success()
104                }
105                _ => CommandReturn::failure(ErrorCode::NOSUPPORT),
106            }
107        } else {
108            CommandReturn::failure(ErrorCode::NODEVICE)
109        }
110    }
111
112    fn configure_interrupt(&self, pin_num: u32, config: usize) -> CommandReturn {
113        let pins = self.pins;
114        let index = pin_num as usize;
115        if let Some(pin) = pins[index] {
116            match config {
117                0 => {
118                    let _ = pin.enable_interrupts(gpio::InterruptEdge::EitherEdge);
119                    CommandReturn::success()
120                }
121
122                1 => {
123                    let _ = pin.enable_interrupts(gpio::InterruptEdge::RisingEdge);
124                    CommandReturn::success()
125                }
126
127                2 => {
128                    let _ = pin.enable_interrupts(gpio::InterruptEdge::FallingEdge);
129                    CommandReturn::success()
130                }
131
132                _ => CommandReturn::failure(ErrorCode::NOSUPPORT),
133            }
134        } else {
135            CommandReturn::failure(ErrorCode::NODEVICE)
136        }
137    }
138}
139
140impl<'a, IP: gpio::InterruptPin<'a>> gpio::ClientWithValue for GPIO<'a, IP> {
141    fn fired(&self, pin_num: u32) {
142        // read the value of the pin
143        let pins = self.pins;
144        if let Some(pin) = pins[pin_num as usize] {
145            let pin_state = pin.read();
146
147            // schedule callback with the pin number and value
148            self.apps.each(|_, _, upcalls| {
149                let _ =
150                    upcalls.schedule_upcall(UPCALL_NUM, (pin_num as usize, pin_state as usize, 0));
151            });
152        }
153    }
154}
155
156impl<'a, IP: gpio::InterruptPin<'a>> SyscallDriver for GPIO<'a, IP> {
157    /// Query and control pin values and states.
158    ///
159    /// Each byte of the `data` argument is treated as its own field.
160    /// For all commands, the lowest order halfword is the pin number (`pin`).
161    /// A few commands use higher order bytes for purposes documented below.
162    /// If the higher order bytes are not used, they must be set to `0`.
163    ///
164    /// Other data bytes:
165    ///
166    /// - `pin_config`: An internal resistor setting.
167    ///   - Set to `0` for a pull-up resistor.
168    ///   - Set to `1` for a pull-down resistor.
169    ///   - Set to `2` for none.
170    /// - `irq_config`: Interrupt configuration setting.
171    ///   - Set to `0` to interrupt on either edge.
172    ///   - Set to `1` for rising edge.
173    ///   - Set to `2` for falling edge.
174    ///
175    /// ### `command_num`
176    ///
177    /// - `0`: Driver existence check.
178    /// - `1`: Enable output on `pin`.
179    /// - `2`: Set `pin`.
180    /// - `3`: Clear `pin`.
181    /// - `4`: Toggle `pin`.
182    /// - `5`: Enable input on `pin` with `pin_config` in 0x00XX00000
183    /// - `6`: Read `pin` value.
184    /// - `7`: Configure interrupt on `pin` with `irq_config` in 0x00XX00000
185    /// - `8`: Disable interrupt on `pin`.
186    /// - `9`: Disable `pin`.
187    /// - `10`: Get number of GPIO ports supported.
188    fn command(
189        &self,
190        command_num: usize,
191        data1: usize,
192        data2: usize,
193        processid: ProcessId,
194    ) -> CommandReturn {
195        let pins = self.pins;
196        let pin_index = data1;
197
198        // This app did anything with the GPIO driver. We mark it as enabled
199        // by allocating the grant region. This allows for upcalls.
200        let grant_ret = self.apps.enter(processid, |_, _| {});
201
202        match command_num {
203            // Check existence.
204            0 => CommandReturn::success(),
205
206            // enable output
207            1 => {
208                if pin_index >= pins.len() {
209                    /* impossible pin */
210                    CommandReturn::failure(ErrorCode::INVAL)
211                } else {
212                    if let Some(pin) = pins[pin_index] {
213                        pin.make_output();
214                        CommandReturn::success()
215                    } else {
216                        CommandReturn::failure(ErrorCode::NODEVICE)
217                    }
218                }
219            }
220
221            // set pin
222            2 => {
223                if pin_index >= pins.len() {
224                    /* impossible pin */
225                    CommandReturn::failure(ErrorCode::INVAL)
226                } else {
227                    if let Some(pin) = pins[pin_index] {
228                        pin.set();
229                        CommandReturn::success()
230                    } else {
231                        CommandReturn::failure(ErrorCode::NODEVICE)
232                    }
233                }
234            }
235
236            // clear pin
237            3 => {
238                if pin_index >= pins.len() {
239                    /* impossible pin */
240                    CommandReturn::failure(ErrorCode::INVAL)
241                } else {
242                    if let Some(pin) = pins[pin_index] {
243                        pin.clear();
244                        CommandReturn::success()
245                    } else {
246                        CommandReturn::failure(ErrorCode::NODEVICE)
247                    }
248                }
249            }
250
251            // toggle pin
252            4 => {
253                if pin_index >= pins.len() {
254                    /* impossible pin */
255                    CommandReturn::failure(ErrorCode::INVAL)
256                } else {
257                    if let Some(pin) = pins[pin_index] {
258                        pin.toggle();
259                        CommandReturn::success()
260                    } else {
261                        CommandReturn::failure(ErrorCode::NODEVICE)
262                    }
263                }
264            }
265
266            // enable and configure input
267            5 => {
268                let pin_config = data2;
269                if pin_index >= pins.len() {
270                    /* impossible pin */
271                    CommandReturn::failure(ErrorCode::INVAL)
272                } else {
273                    self.configure_input_pin(pin_index as u32, pin_config)
274                }
275            }
276
277            // read input
278            6 => {
279                if pin_index >= pins.len() {
280                    /* impossible pin */
281                    CommandReturn::failure(ErrorCode::INVAL)
282                } else {
283                    if let Some(pin) = pins[pin_index] {
284                        let pin_state = pin.read();
285                        CommandReturn::success_u32(pin_state as u32)
286                    } else {
287                        CommandReturn::failure(ErrorCode::NODEVICE)
288                    }
289                }
290            }
291
292            // configure interrupts on pin
293            // (no affect or reliance on registered callback)
294            7 => {
295                // If the grant entry failed, meaning we could not allocate the
296                // grant, we want to ensure the app does not try to wait on an
297                // interrupt upcall using Yield-WaitFor which will never return. So,
298                // we return an error for this operation.
299                if grant_ret.is_err() {
300                    return CommandReturn::failure(ErrorCode::NOMEM);
301                }
302
303                let irq_config = data2;
304                if pin_index >= pins.len() {
305                    /* impossible pin */
306                    CommandReturn::failure(ErrorCode::INVAL)
307                } else {
308                    self.configure_interrupt(pin_index as u32, irq_config)
309                }
310            }
311
312            // disable interrupts on pin, also disables pin
313            // (no affect or reliance on registered callback)
314            8 => {
315                // If the grant entry failed, meaning we could not allocate the
316                // grant, we want to ensure the app does not try to wait on an
317                // interrupt upcall using Yield-WaitFor which will never return. So,
318                // we return an error for this operation.
319                if grant_ret.is_err() {
320                    return CommandReturn::failure(ErrorCode::NOMEM);
321                }
322
323                if pin_index >= pins.len() {
324                    /* impossible pin */
325                    CommandReturn::failure(ErrorCode::INVAL)
326                } else {
327                    if let Some(pin) = pins[pin_index] {
328                        pin.disable_interrupts();
329                        pin.deactivate_to_low_power();
330                        CommandReturn::success()
331                    } else {
332                        CommandReturn::failure(ErrorCode::NODEVICE)
333                    }
334                }
335            }
336
337            // disable pin
338            9 => {
339                if pin_index >= pins.len() {
340                    /* impossible pin */
341                    CommandReturn::failure(ErrorCode::INVAL)
342                } else {
343                    if let Some(pin) = pins[pin_index] {
344                        pin.deactivate_to_low_power();
345                        CommandReturn::success()
346                    } else {
347                        CommandReturn::failure(ErrorCode::NODEVICE)
348                    }
349                }
350            }
351
352            // number of pins
353            10 => CommandReturn::success_u32(pins.len() as u32),
354
355            // default
356            _ => CommandReturn::failure(ErrorCode::NOSUPPORT),
357        }
358    }
359
360    fn allocate_grant(&self, processid: ProcessId) -> Result<(), kernel::process::Error> {
361        self.apps.enter(processid, |_, _| {})
362    }
363}