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
// 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 with virtualized access to 9DOF sensors.
//!
//! Usage
//! -----
//!
//! You need a device that provides the `hil::sensors::NineDof` trait.
//!
//! ```rust,ignore
//! # use kernel::{hil, static_init};
//!
//! let grant_cap = create_capability!(capabilities::MemoryAllocationCapability);
//! let grant_ninedof = board_kernel.create_grant(&grant_cap);
//!
//! let ninedof = static_init!(
//!     capsules::ninedof::NineDof<'static>,
//!     capsules::ninedof::NineDof::new(grant_ninedof));
//! ninedof.add_driver(fxos8700);
//! hil::sensors::NineDof::set_client(fxos8700, ninedof);
//! ```

use kernel::grant::{AllowRoCount, AllowRwCount, Grant, UpcallCount};
use kernel::hil;
use kernel::syscall::{CommandReturn, SyscallDriver};
use kernel::utilities::cells::OptionalCell;
use kernel::{ErrorCode, ProcessId};

/// Syscall driver number.
use capsules_core::driver;
pub const DRIVER_NUM: usize = driver::NUM::NINEDOF as usize;

#[derive(Clone, Copy, PartialEq)]
pub enum NineDofCommand {
    Exists,
    ReadAccelerometer,
    ReadMagnetometer,
    ReadGyroscope,
}

pub struct App {
    pending_command: bool,
    command: NineDofCommand,
    arg1: usize,
}

impl Default for App {
    fn default() -> App {
        App {
            pending_command: false,
            command: NineDofCommand::Exists,
            arg1: 0,
        }
    }
}

pub struct NineDof<'a> {
    drivers: &'a [&'a dyn hil::sensors::NineDof<'a>],
    apps: Grant<App, UpcallCount<1>, AllowRoCount<0>, AllowRwCount<0>>,
    current_app: OptionalCell<ProcessId>,
}

impl<'a> NineDof<'a> {
    pub fn new(
        drivers: &'a [&'a dyn hil::sensors::NineDof<'a>],
        grant: Grant<App, UpcallCount<1>, AllowRoCount<0>, AllowRwCount<0>>,
    ) -> NineDof<'a> {
        NineDof {
            drivers,
            apps: grant,
            current_app: OptionalCell::empty(),
        }
    }

    // Check so see if we are doing something. If not,
    // go ahead and do this command. If so, this is queued
    // and will be run when the pending command completes.
    fn enqueue_command(
        &self,
        command: NineDofCommand,
        arg1: usize,
        processid: ProcessId,
    ) -> CommandReturn {
        self.apps
            .enter(processid, |app, _| {
                if self.current_app.is_none() {
                    self.current_app.set(processid);
                    let value = self.call_driver(command, arg1);
                    if value != Ok(()) {
                        self.current_app.clear();
                    }
                    CommandReturn::from(value)
                } else {
                    if app.pending_command {
                        CommandReturn::failure(ErrorCode::BUSY)
                    } else {
                        app.pending_command = true;
                        app.command = command;
                        app.arg1 = arg1;
                        CommandReturn::success()
                    }
                }
            })
            .unwrap_or_else(|err| {
                let rcode: Result<(), ErrorCode> = err.into();
                CommandReturn::from(rcode)
            })
    }

    fn call_driver(&self, command: NineDofCommand, _: usize) -> Result<(), ErrorCode> {
        match command {
            NineDofCommand::ReadAccelerometer => {
                let mut data = Err(ErrorCode::NODEVICE);
                for driver in self.drivers.iter() {
                    data = driver.read_accelerometer();
                    if data == Ok(()) {
                        break;
                    }
                }
                data
            }
            NineDofCommand::ReadMagnetometer => {
                let mut data = Err(ErrorCode::NODEVICE);
                for driver in self.drivers.iter() {
                    data = driver.read_magnetometer();
                    if data == Ok(()) {
                        break;
                    }
                }
                data
            }
            NineDofCommand::ReadGyroscope => {
                let mut data = Err(ErrorCode::NODEVICE);
                for driver in self.drivers.iter() {
                    data = driver.read_gyroscope();
                    if data == Ok(()) {
                        break;
                    }
                }
                data
            }
            _ => Err(ErrorCode::NOSUPPORT),
        }
    }
}

impl hil::sensors::NineDofClient for NineDof<'_> {
    fn callback(&self, arg1: usize, arg2: usize, arg3: usize) {
        // Notify the current application that the command finished.
        // Also keep track of what just finished to see if we can re-use
        // the result.
        let mut finished_command = NineDofCommand::Exists;
        let mut finished_command_arg = 0;
        self.current_app.take().map(|processid| {
            let _ = self.apps.enter(processid, |app, upcalls| {
                app.pending_command = false;
                finished_command = app.command;
                finished_command_arg = app.arg1;
                upcalls.schedule_upcall(0, (arg1, arg2, arg3)).ok();
            });
        });

        // Check if there are any pending events.
        for cntr in self.apps.iter() {
            let processid = cntr.processid();
            let started_command = cntr.enter(|app, upcalls| {
                if app.pending_command
                    && app.command == finished_command
                    && app.arg1 == finished_command_arg
                {
                    // Don't bother re-issuing this command, just use
                    // the existing result.
                    app.pending_command = false;
                    upcalls.schedule_upcall(0, (arg1, arg2, arg3)).ok();
                    false
                } else if app.pending_command {
                    app.pending_command = false;
                    self.current_app.set(processid);
                    self.call_driver(app.command, app.arg1) == Ok(())
                } else {
                    false
                }
            });
            if started_command {
                break;
            }
        }
    }
}

impl SyscallDriver for NineDof<'_> {
    fn command(
        &self,
        command_num: usize,
        arg1: usize,
        _: usize,
        processid: ProcessId,
    ) -> CommandReturn {
        match command_num {
            0 => CommandReturn::success(),
            // Single acceleration reading.
            1 => self.enqueue_command(NineDofCommand::ReadAccelerometer, arg1, processid),

            // Single magnetometer reading.
            100 => self.enqueue_command(NineDofCommand::ReadMagnetometer, arg1, processid),

            // Single gyroscope reading.
            200 => self.enqueue_command(NineDofCommand::ReadGyroscope, arg1, processid),

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

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