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
// Licensed under the Apache License, Version 2.0 or the MIT License.
// SPDX-License-Identifier: Apache-2.0 OR MIT
// Copyright Tock Contributors 2022.

//! System call interface for userspace processes implemented by capsules.
//!
//! Drivers implement these interfaces to expose operations to processes.
//!
//! # System-call Overview
//!
//! Tock supports six system calls. The `allow_readonly`, `allow_readwrite`,
//! `subscribe`, `yield`, and `memop` system calls are handled by the core
//! kernel, while `command` is implemented by drivers. The main system calls:
//!
//!   * `subscribe` passes a upcall to the driver which it can
//!   invoke on the process later, when an event has occurred or data
//!   of interest is available.
//!
//!   * `command` tells the driver to do something immediately.
//!
//!   * `allow_readwrite` provides the driver read-write access to an
//!   application buffer.
//!
//!   * `allow_userspace_readable` provides the driver read-write access to an
//!   application buffer that is still shared with the app.
//!
//!   * `allow_readonly` provides the driver read-only access to an
//!   application buffer.
//!
//! ## Mapping system-calls to drivers
//!
//! Each of these three system calls takes at least two
//! parameters. The first is a _driver identifier_ and tells the
//! scheduler which driver to forward the system call to. The second
//! parameters is a __syscall number_ and is used by the driver to
//! differentiate instances of the call with different driver-specific
//! meanings (e.g. `subscribe` for "data received" vs `subscribe` for
//! "send completed"). The mapping between _driver identifiers_ and
//! drivers is determined by a particular platform, while the _syscall
//! number_ is driver-specific.
//!
//! One convention in Tock is that _driver minor number_ 0 for the `command`
//! syscall can always be used to determine if the driver is supported by
//! the running kernel by checking the return code. If the return value is
//! greater than or equal to zero then the driver is present. Typically this is
//! implemented by a null command that only returns 0, but in some cases the
//! command can also return more information, like the number of supported
//! devices (useful for things like the number of LEDs).
//!
//! # The `yield` system call class
//!
//! While drivers do not handle `yield` system calls, it is important
//! to understand them and how they interact with `subscribe`, which
//! registers upcall functions with the kernel. When a process calls
//! a `yield` system call, the kernel checks if there are any pending
//! upcalls for the process. If there are pending upcalls, it
//! pushes one upcall onto the process stack. If there are no
//! pending upcalls, `yield-wait` will cause the process to sleep
//! until a upcall is triggered, while `yield-no-wait` returns
//! immediately.
//!
//! # Method result types
//!
//! Each driver method has a limited set of valid return types. Every
//! method has a single return type corresponding to success and a
//! single return type corresponding to failure. For the `subscribe`
//! and `allow` system calls, these return types are the same for
//! every instance of those calls. Each instance of the `command`
//! system call, however, has its own specified return types. A
//! command that requests a timestamp, for example, might return a
//! 32-bit number on success and an error code on failure, while a
//! command that requests time of day in microsecond granularity might
//! return a 64-bit number and a 32-bit timezone encoding on success,
//! and an error code on failure.
//!
//! These result types are represented as safe Rust types. The core
//! kernel (the scheduler and syscall dispatcher) is responsible for
//! encoding these types into the Tock system call ABI specification.

use crate::errorcode::ErrorCode;
use crate::process;
use crate::process::ProcessId;
use crate::processbuffer::UserspaceReadableProcessBuffer;
use crate::syscall::SyscallReturn;

/// Possible return values of a `command` driver method, as specified
/// in TRD104.
///
/// This is just a wrapper around
/// [`SyscallReturn`](SyscallReturn) since a
/// `command` driver method may only return primitive integer types as
/// payload.
///
/// It is important for this wrapper to only be constructable over
/// variants of
/// [`SyscallReturn`](SyscallReturn) that are
/// deemed safe for a capsule to construct and return to an
/// application (e.g. not
/// [`SubscribeSuccess`](crate::syscall::SyscallReturn::SubscribeSuccess)).
/// This means that the inner value **must** remain private.
pub struct CommandReturn(SyscallReturn);
impl CommandReturn {
    pub(crate) fn into_inner(self) -> SyscallReturn {
        self.0
    }

    /// Command error
    pub fn failure(rc: ErrorCode) -> Self {
        CommandReturn(SyscallReturn::Failure(rc))
    }

    /// Command error with an additional 32-bit data field
    pub fn failure_u32(rc: ErrorCode, data0: u32) -> Self {
        CommandReturn(SyscallReturn::FailureU32(rc, data0))
    }

    /// Command error with two additional 32-bit data fields
    pub fn failure_u32_u32(rc: ErrorCode, data0: u32, data1: u32) -> Self {
        CommandReturn(SyscallReturn::FailureU32U32(rc, data0, data1))
    }

    /// Command error with an additional 64-bit data field
    pub fn failure_u64(rc: ErrorCode, data0: u64) -> Self {
        CommandReturn(SyscallReturn::FailureU64(rc, data0))
    }

    /// Successful command
    pub fn success() -> Self {
        CommandReturn(SyscallReturn::Success)
    }

    /// Successful command with an additional 32-bit data field
    pub fn success_u32(data0: u32) -> Self {
        CommandReturn(SyscallReturn::SuccessU32(data0))
    }

    /// Successful command with two additional 32-bit data fields
    pub fn success_u32_u32(data0: u32, data1: u32) -> Self {
        CommandReturn(SyscallReturn::SuccessU32U32(data0, data1))
    }

    /// Successful command with three additional 32-bit data fields
    pub fn success_u32_u32_u32(data0: u32, data1: u32, data2: u32) -> Self {
        CommandReturn(SyscallReturn::SuccessU32U32U32(data0, data1, data2))
    }

    /// Successful command with an additional 64-bit data field
    pub fn success_u64(data0: u64) -> Self {
        CommandReturn(SyscallReturn::SuccessU64(data0))
    }

    /// Successful command with an additional 64-bit and 32-bit data field
    pub fn success_u32_u64(data0: u32, data1: u64) -> Self {
        CommandReturn(SyscallReturn::SuccessU32U64(data0, data1))
    }
}

impl From<Result<(), ErrorCode>> for CommandReturn {
    fn from(rc: Result<(), ErrorCode>) -> Self {
        match rc {
            Ok(()) => CommandReturn::success(),
            _ => CommandReturn::failure(ErrorCode::try_from(rc).unwrap()),
        }
    }
}

impl From<process::Error> for CommandReturn {
    fn from(perr: process::Error) -> Self {
        CommandReturn::failure(perr.into())
    }
}

/// Trait for capsules implementing peripheral driver system calls
/// specified in TRD104. The kernel translates the values passed from
/// userspace into Rust types and includes which process is making the
/// call. All of these system calls perform very little synchronous work;
/// long running computations or I/O should be split-phase, with an upcall
/// indicating their completion.
///
/// The exact instances of each of these methods (which identifiers are valid
/// and what they represents) are specific to the peripheral system call
/// driver.
///
/// Note about **subscribe**, **read-only allow**, and *read-write allow**
/// syscalls:
/// those are handled entirely by the core kernel, and there is no
/// corresponding function for capsules to implement.
#[allow(unused_variables)]
pub trait SyscallDriver {
    /// System call for a process to perform a short synchronous operation
    /// or start a long-running split-phase operation (whose completion
    /// is signaled with an upcall). Command 0 is a reserved command to
    /// detect if a peripheral system call driver is installed and must
    /// always return a CommandReturn::Success.
    fn command(
        &self,
        command_num: usize,
        r2: usize,
        r3: usize,
        process_id: ProcessId,
    ) -> CommandReturn {
        CommandReturn::failure(ErrorCode::NOSUPPORT)
    }

    /// System call for a process to pass a buffer (a
    /// `UserspaceReadableProcessBuffer`) to the kernel that the kernel can
    /// either read or write. The kernel calls this method only after it checks
    /// that the entire buffer is within memory the process can both read and
    /// write.
    ///
    /// This is different to `allow_readwrite()` in that the app is allowed
    /// to read the buffer once it has been passed to the kernel.
    /// For more details on how this can be done safely see the userspace
    /// readable allow syscalls TRDXXX.
    fn allow_userspace_readable(
        &self,
        app: ProcessId,
        which: usize,
        slice: UserspaceReadableProcessBuffer,
    ) -> Result<UserspaceReadableProcessBuffer, (UserspaceReadableProcessBuffer, ErrorCode)> {
        Err((slice, ErrorCode::NOSUPPORT))
    }

    /// Request to allocate a capsule's grant for a specific process.
    ///
    /// The core kernel uses this function to instruct a capsule to ensure its
    /// grant (if it has one) is allocated for a specific process. The core
    /// kernel needs the capsule to initiate the allocation because only the
    /// capsule knows the type T (and therefore the size of T) that will be
    /// stored in the grant.
    ///
    /// The typical implementation will look like:
    /// ```rust, ignore
    /// fn allocate_grant(&self, processid: ProcessId) -> Result<(), kernel::process::Error> {
    ///    self.apps.enter(processid, |_, _| {})
    /// }
    /// ```
    ///
    /// No default implementation is provided to help prevent accidentally
    /// forgetting to implement this function.
    ///
    /// If a capsule fails to successfully implement this function, subscribe
    /// calls from userspace for the Driver may fail.
    //
    // The inclusion of this function originates from the method for ensuring
    // correct upcall swapping semantics in the kernel starting with Tock 2.0.
    // To ensure upcalls are always swapped correctly all upcall handling is
    // done in the core kernel. Capsules only have access to a handle which
    // permits them to schedule upcalls, but capsules no longer manage upcalls.
    //
    // The core kernel stores upcalls in the process's grant region along with
    // the capsule's grant object. A simultaneous Tock 2.0 change requires that
    // capsules wishing to use upcalls must also use grants. Storing upcalls in
    // the grant requires that the grant be allocated for that capsule in that
    // process. This presents a challenge as grants are dynamically allocated
    // only when actually used by a process. If a subscribe syscall happens
    // first, before the capsule has allocated the grant, the kernel has no way
    // to store the upcall. The kernel cannot allocate the grant itself because
    // it does not know the type T the capsule will use for the grant (or more
    // specifically the kernel does not know the size of T to use for the memory
    // allocation).
    //
    // There are a few ideas on how to handle this case where the kernel must
    // store an upcall before the capsule has allocated the grant.
    //
    // 1. The kernel could allocate space for the grant type T, but not actually
    //    initialize it, based only on the size of T. However, this would
    //    require the kernel to keep track of the size of T for each grant, and
    //    there is no convenient place to store that information.
    //
    // 2. The kernel could store upcalls and grant types separately in the grant
    //    region.
    //
    //    a. One approach is to store upcalls completely dynamically. That is,
    //       whenever a new subscribe_num is used for a particular driver the
    //       core kernel allocates new memory from the grant region to store it.
    //       This would work, but would have high memory and runtime overhead to
    //       manage all of the dynamic upcall stores.
    //    b. To reduce the tracking overhead, all upcalls for a particular
    //       driver could be stored together as one allocation. This would only
    //       cost one additional pointer per grant to point to the upcall array.
    //       However, the kernel does not know how many upcalls a particular
    //       driver needs, and there is no convenient place for it to store that
    //       information.
    //
    // 3. The kernel could allocate a fixed region for all upcalls across all
    //    drivers in the grant region. When each grant is created it could tell
    //    the kernel how many upcalls it will use and the kernel could easily
    //    keep track of the total. Then, when a process's memory is allocated
    //    the kernel would reserve room for that many upcalls. There are two
    //    issues, however. The kernel would not know how many upcalls each
    //    driver individually requires, so it would not be able to index into
    //    this array properly to store each upcall. Second, the upcall array
    //    memory would be statically allocated, and would be wasted for drivers
    //    the process never uses.
    //
    //    A version of this approach would assume a maximum limit of a certain
    //    number of upcalls per driver. This would address the indexing
    //    challenge, but would still have the memory overhead problem. It would
    //    also limit capsule flexibility by capping the number of upcalls any
    //    capsule could ever use.
    //
    // 4. The kernel could have some mechanism to ask a capsule to allocate its
    //    grant, and since the capsule knows the size of T and the number of
    //    upcalls it uses the grant type and upcall storage could be allocated
    //    together.
    //
    // Based on the available options, the Tock developers decided go with
    // option 4 and add the `allocate_grant` method to the `Driver` trait. This
    // mechanism may find more uses in the future if the kernel needs to store
    // additional state on a per-driver basis and therefore needs a mechanism to
    // force a grant allocation.
    //
    // This same mechanism was later extended to handle allow calls as well.
    // Capsules that do not need upcalls but do use process buffers must also
    // implement this function.
    fn allocate_grant(&self, process_id: ProcessId) -> Result<(), crate::process::Error>;
}