1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
// Licensed under the Apache License, Version 2.0 or the MIT License.
// SPDX-License-Identifier: Apache-2.0 OR MIT
// Copyright Tock Contributors 2022.

//! Provides userspace applications with access to GPIO pins.
//!
//! GPIOs are presented through a driver interface with synchronous commands
//! and a callback for interrupts.
//!
//! This capsule takes an array of pins to expose as generic GPIOs.
//! Note that this capsule is used for general purpose GPIOs. Pins that are
//! attached to LEDs or buttons are generally wired directly to those capsules,
//! not through this capsule as an intermediary.
//!
//! Usage
//! -----
//!
//! ```rust,ignore
//! # use kernel::static_init;
//!
//! let gpio_pins = static_init!(
//!     [Option<&'static sam4l::gpio::GPIOPin>; 4],
//!     [Option<&sam4l::gpio::PB[14]>,
//!      Option<&sam4l::gpio::PB[15]>,
//!      Option<&sam4l::gpio::PB[11]>,
//!      Option<&sam4l::gpio::PB[12]>]);
//! let gpio = static_init!(
//!     capsules_core::gpio::GPIO<'static, sam4l::gpio::GPIOPin>,
//!     capsules_core::gpio::GPIO::new(gpio_pins));
//! for maybe_pin in gpio_pins.iter() {
//!     if let Some(pin) = maybe_pin {
//!         pin.set_client(gpio);
//!     }
//! }
//! ```
//!
//! Syscall Interface
//! -----------------
//!
//! - Stability: 2 - Stable
//!
//! ### Commands
//!
//! All GPIO operations are synchronous.
//!
//! Commands control and query GPIO information, namely how many GPIOs are
//! present, the GPIO direction and state, and whether they should interrupt.
//!
//! ### Subscribes
//!
//! The GPIO interface provides only one callback, which is used for pins that
//! have had interrupts enabled.

/// Syscall driver number.
use crate::driver;
pub const DRIVER_NUM: usize = driver::NUM::Gpio as usize;

use kernel::grant::{AllowRoCount, AllowRwCount, Grant, UpcallCount};
use kernel::hil::gpio;
use kernel::hil::gpio::{Configure, Input, InterruptWithValue, Output};
use kernel::syscall::{CommandReturn, SyscallDriver};
use kernel::{ErrorCode, ProcessId};

/// ### `subscribe_num`
///
/// - `0`: Subscribe to interrupts from all pins with interrupts enabled.
///        The callback signature is `fn(pin_num: usize, pin_state: bool)`
const UPCALL_NUM: usize = 0;

pub struct GPIO<'a, IP: gpio::InterruptPin<'a>> {
    pins: &'a [Option<&'a gpio::InterruptValueWrapper<'a, IP>>],
    apps: Grant<(), UpcallCount<1>, AllowRoCount<0>, AllowRwCount<0>>,
}

impl<'a, IP: gpio::InterruptPin<'a>> GPIO<'a, IP> {
    pub fn new(
        pins: &'a [Option<&'a gpio::InterruptValueWrapper<'a, IP>>],
        grant: Grant<(), UpcallCount<1>, AllowRoCount<0>, AllowRwCount<0>>,
    ) -> Self {
        for (i, maybe_pin) in pins.iter().enumerate() {
            if let Some(pin) = maybe_pin {
                pin.set_value(i as u32);
            }
        }
        Self { pins, apps: grant }
    }

    fn configure_input_pin(&self, pin_num: u32, config: usize) -> CommandReturn {
        let maybe_pin = self.pins[pin_num as usize];
        if let Some(pin) = maybe_pin {
            pin.make_input();
            match config {
                0 => {
                    pin.set_floating_state(gpio::FloatingState::PullNone);
                    CommandReturn::success()
                }
                1 => {
                    pin.set_floating_state(gpio::FloatingState::PullUp);
                    CommandReturn::success()
                }
                2 => {
                    pin.set_floating_state(gpio::FloatingState::PullDown);
                    CommandReturn::success()
                }
                _ => CommandReturn::failure(ErrorCode::NOSUPPORT),
            }
        } else {
            CommandReturn::failure(ErrorCode::NODEVICE)
        }
    }

    fn configure_interrupt(&self, pin_num: u32, config: usize) -> CommandReturn {
        let pins = self.pins;
        let index = pin_num as usize;
        if let Some(pin) = pins[index] {
            match config {
                0 => {
                    let _ = pin.enable_interrupts(gpio::InterruptEdge::EitherEdge);
                    CommandReturn::success()
                }

                1 => {
                    let _ = pin.enable_interrupts(gpio::InterruptEdge::RisingEdge);
                    CommandReturn::success()
                }

                2 => {
                    let _ = pin.enable_interrupts(gpio::InterruptEdge::FallingEdge);
                    CommandReturn::success()
                }

                _ => CommandReturn::failure(ErrorCode::NOSUPPORT),
            }
        } else {
            CommandReturn::failure(ErrorCode::NODEVICE)
        }
    }
}

impl<'a, IP: gpio::InterruptPin<'a>> gpio::ClientWithValue for GPIO<'a, IP> {
    fn fired(&self, pin_num: u32) {
        // read the value of the pin
        let pins = self.pins;
        if let Some(pin) = pins[pin_num as usize] {
            let pin_state = pin.read();

            // schedule callback with the pin number and value
            self.apps.each(|_, _, upcalls| {
                upcalls
                    .schedule_upcall(UPCALL_NUM, (pin_num as usize, pin_state as usize, 0))
                    .ok();
            });
        }
    }
}

impl<'a, IP: gpio::InterruptPin<'a>> SyscallDriver for GPIO<'a, IP> {
    /// Query and control pin values and states.
    ///
    /// Each byte of the `data` argument is treated as its own field.
    /// For all commands, the lowest order halfword is the pin number (`pin`).
    /// A few commands use higher order bytes for purposes documented below.
    /// If the higher order bytes are not used, they must be set to `0`.
    ///
    /// Other data bytes:
    ///
    ///   - `pin_config`: An internal resistor setting.
    ///                   Set to `0` for a pull-up resistor.
    ///                   Set to `1` for a pull-down resistor.
    ///                   Set to `2` for none.
    ///   - `irq_config`: Interrupt configuration setting.
    ///                   Set to `0` to interrupt on either edge.
    ///                   Set to `1` for rising edge.
    ///                   Set to `2` for falling edge.
    ///
    /// ### `command_num`
    ///
    /// - `0`: Driver existence check.
    /// - `1`: Enable output on `pin`.
    /// - `2`: Set `pin`.
    /// - `3`: Clear `pin`.
    /// - `4`: Toggle `pin`.
    /// - `5`: Enable input on `pin` with `pin_config` in 0x00XX00000
    /// - `6`: Read `pin` value.
    /// - `7`: Configure interrupt on `pin` with `irq_config` in 0x00XX00000
    /// - `8`: Disable interrupt on `pin`.
    /// - `9`: Disable `pin`.
    /// - `10`: Get number of GPIO ports supported.
    fn command(
        &self,
        command_num: usize,
        data1: usize,
        data2: usize,
        _: ProcessId,
    ) -> CommandReturn {
        let pins = self.pins;
        let pin_index = data1;
        match command_num {
            // Check existence.
            0 => CommandReturn::success(),

            // enable output
            1 => {
                if pin_index >= pins.len() {
                    /* impossible pin */
                    CommandReturn::failure(ErrorCode::INVAL)
                } else {
                    if let Some(pin) = pins[pin_index] {
                        pin.make_output();
                        CommandReturn::success()
                    } else {
                        CommandReturn::failure(ErrorCode::NODEVICE)
                    }
                }
            }

            // set pin
            2 => {
                if pin_index >= pins.len() {
                    /* impossible pin */
                    CommandReturn::failure(ErrorCode::INVAL)
                } else {
                    if let Some(pin) = pins[pin_index] {
                        pin.set();
                        CommandReturn::success()
                    } else {
                        CommandReturn::failure(ErrorCode::NODEVICE)
                    }
                }
            }

            // clear pin
            3 => {
                if pin_index >= pins.len() {
                    /* impossible pin */
                    CommandReturn::failure(ErrorCode::INVAL)
                } else {
                    if let Some(pin) = pins[pin_index] {
                        pin.clear();
                        CommandReturn::success()
                    } else {
                        CommandReturn::failure(ErrorCode::NODEVICE)
                    }
                }
            }

            // toggle pin
            4 => {
                if pin_index >= pins.len() {
                    /* impossible pin */
                    CommandReturn::failure(ErrorCode::INVAL)
                } else {
                    if let Some(pin) = pins[pin_index] {
                        pin.toggle();
                        CommandReturn::success()
                    } else {
                        CommandReturn::failure(ErrorCode::NODEVICE)
                    }
                }
            }

            // enable and configure input
            5 => {
                let pin_config = data2;
                if pin_index >= pins.len() {
                    /* impossible pin */
                    CommandReturn::failure(ErrorCode::INVAL)
                } else {
                    self.configure_input_pin(pin_index as u32, pin_config)
                }
            }

            // read input
            6 => {
                if pin_index >= pins.len() {
                    /* impossible pin */
                    CommandReturn::failure(ErrorCode::INVAL)
                } else {
                    if let Some(pin) = pins[pin_index] {
                        let pin_state = pin.read();
                        CommandReturn::success_u32(pin_state as u32)
                    } else {
                        CommandReturn::failure(ErrorCode::NODEVICE)
                    }
                }
            }

            // configure interrupts on pin
            // (no affect or reliance on registered callback)
            7 => {
                let irq_config = data2;
                if pin_index >= pins.len() {
                    /* impossible pin */
                    CommandReturn::failure(ErrorCode::INVAL)
                } else {
                    self.configure_interrupt(pin_index as u32, irq_config)
                }
            }

            // disable interrupts on pin, also disables pin
            // (no affect or reliance on registered callback)
            8 => {
                if pin_index >= pins.len() {
                    /* impossible pin */
                    CommandReturn::failure(ErrorCode::INVAL)
                } else {
                    if let Some(pin) = pins[pin_index] {
                        pin.disable_interrupts();
                        pin.deactivate_to_low_power();
                        CommandReturn::success()
                    } else {
                        CommandReturn::failure(ErrorCode::NODEVICE)
                    }
                }
            }

            // disable pin
            9 => {
                if pin_index >= pins.len() {
                    /* impossible pin */
                    CommandReturn::failure(ErrorCode::INVAL)
                } else {
                    if let Some(pin) = pins[pin_index] {
                        pin.deactivate_to_low_power();
                        CommandReturn::success()
                    } else {
                        CommandReturn::failure(ErrorCode::NODEVICE)
                    }
                }
            }

            // number of pins
            10 => CommandReturn::success_u32(pins.len() as u32),

            // default
            _ => CommandReturn::failure(ErrorCode::NOSUPPORT),
        }
    }

    fn allocate_grant(&self, processid: ProcessId) -> Result<(), kernel::process::Error> {
        self.apps.enter(processid, |_, _| {})
    }
}