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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
// Licensed under the Apache License, Version 2.0 or the MIT License.
// SPDX-License-Identifier: Apache-2.0 OR MIT
// Copyright Tock Contributors 2022
// Copyright OxidOS Automotive SRL 2022
//
// Author: Teona Severin <teona.severin@oxidos.io>

//! Syscall driver capsule for CAN communication.
//!
//! This module has a CAN syscall driver capsule implementation.
//!
//! This capsule sends commands from the userspace to a driver that
//! implements the Can trait.
//!
//! The capsule shares 2 buffers with the userspace: one RO that is used
//! for transmitting messages and one RW that is used for receiving
//! messages.
//!
//! The RO buffer uses the first 4 bytes as a counter of how many messages
//! the userspace must read, at the time the upcall was sent. If the
//! userspace is slower and in the meantime there were other messages
//! that were received, the userspace reads them all and sends to the
//! capsule a new buffer that has the counter on the first 4 bytes 0.
//! Because of that, when receiving a callback from the driver regarding
//! a received message, the capsule checks the counter:
//! - if it's 0, the message will be copied to the RW buffer, the counter
//!   will be incremented and an upcall will be sent
//! - if it's greater the 0, the message will be copied to the RW buffer
//!   but no upcall will be done
//!
//! Usage
//! -----
//!
//! You need a driver that implements the Can trait.
//! ```rust,ignore
//! let grant_cap = create_capability!(capabilities::MemoryAllocationCapability);
//! let grant_can = self.board_kernel.create_grant(
//!     capsules::can::CanCapsule::DRIVER_NUM, &grant_cap);
//! let can = capsules::can::CanCapsule::new(
//!    can_peripheral,
//!    grant_can,
//!    tx_buffer,
//!    rx_buffer,
//! );
//!
//! kernel::hil::can::Controller::set_client(can_peripheral, Some(can));
//! kernel::hil::can::Transmit::set_client(can_peripheral, Some(can));
//! kernel::hil::can::Receive::set_client(can_peripheral, Some(can));
//! ```
//!

use core::mem::size_of;

use kernel::grant::{AllowRoCount, AllowRwCount, Grant, UpcallCount};
use kernel::hil::can;
use kernel::processbuffer::{ReadableProcessBuffer, WriteableProcessBuffer};
use kernel::syscall::{CommandReturn, SyscallDriver};
use kernel::utilities::cells::{OptionalCell, TakeCell};
use kernel::utilities::streaming_process_slice::StreamingProcessSlice;
use kernel::ErrorCode;
use kernel::ProcessId;

use capsules_core::driver;
pub const DRIVER_NUM: usize = driver::NUM::Can as usize;
pub const BYTE4_MASK: usize = 0xff000000;
pub const BYTE3_MASK: usize = 0xff0000;
pub const BYTE2_MASK: usize = 0xff00;
pub const BYTE1_MASK: usize = 0xff;

mod error_upcalls {
    pub const ERROR_TX: usize = 100;
    pub const ERROR_RX: usize = 101;
}

mod up_calls {
    pub const UPCALL_ENABLE: usize = 0;
    pub const UPCALL_DISABLE: usize = 1;
    pub const UPCALL_MESSAGE_SENT: usize = 2;
    pub const UPCALL_MESSAGE_RECEIVED: usize = 3;
    pub const UPCALL_RECEIVED_STOPPED: usize = 4;
    pub const UPCALL_TRANSMISSION_ERROR: usize = 5;
    pub const COUNT: u8 = 6;
}

mod ro_allow {
    pub const RO_ALLOW_BUFFER: usize = 0;
    pub const COUNT: u8 = 1;
}

mod rw_allow {
    pub const RW_ALLOW_BUFFER: usize = 0;
    pub const COUNT: u8 = 1;
}

pub struct CanCapsule<'a, Can: can::Can> {
    // CAN driver
    can: &'a Can,

    // CAN buffers
    can_tx: TakeCell<'static, [u8; can::STANDARD_CAN_PACKET_SIZE]>,
    can_rx: TakeCell<'static, [u8; can::STANDARD_CAN_PACKET_SIZE]>,

    // Process
    processes: Grant<
        App,
        UpcallCount<{ up_calls::COUNT }>,
        AllowRoCount<{ ro_allow::COUNT }>,
        AllowRwCount<{ rw_allow::COUNT }>,
    >,
    processid: OptionalCell<ProcessId>,

    // Variable used to store the current state of the CAN peripheral
    // during an `enable` or `disable` command.
    peripheral_state: OptionalCell<can::State>,
}

#[derive(Default)]
pub struct App {
    lost_messages: u32,
}

impl<'a, Can: can::Can> CanCapsule<'a, Can> {
    pub fn new(
        can: &'a Can,
        grant: Grant<
            App,
            UpcallCount<{ up_calls::COUNT }>,
            AllowRoCount<{ ro_allow::COUNT }>,
            AllowRwCount<{ rw_allow::COUNT }>,
        >,
        can_tx: &'static mut [u8; can::STANDARD_CAN_PACKET_SIZE],
        can_rx: &'static mut [u8; can::STANDARD_CAN_PACKET_SIZE],
    ) -> CanCapsule<'a, Can> {
        CanCapsule {
            can,
            can_tx: TakeCell::new(can_tx),
            can_rx: TakeCell::new(can_rx),
            processes: grant,
            peripheral_state: OptionalCell::empty(),
            processid: OptionalCell::empty(),
        }
    }

    fn schedule_callback(&self, callback_number: usize, data: (usize, usize, usize)) {
        self.processid.map(|processid| {
            let _ = self.processes.enter(processid, |_app, kernel_data| {
                kernel_data
                    .schedule_upcall(callback_number, (data.0, data.1, data.2))
                    .ok();
            });
        });
    }

    /// This function makes a copy of the buffer in the grant and sends it
    /// to the low-level hardware, in order for it to be sent on the bus.
    pub fn process_send_command(
        &self,
        processid: ProcessId,
        id: can::Id,
        length: usize,
    ) -> Result<(), ErrorCode> {
        self.processes
            .enter(processid, |_, kernel_data| {
                kernel_data
                    .get_readonly_processbuffer(ro_allow::RO_ALLOW_BUFFER)
                    .map_or_else(
                        |err| err.into(),
                        |buffer_ref| {
                            buffer_ref
                                .enter(|buffer| {
                                    self.can_tx.take().map_or(
                                        Err(ErrorCode::NOMEM),
                                        |dest_buffer| {
                                            for i in 0..length {
                                                dest_buffer[i] = buffer[i].get();
                                            }
                                            match self.can.send(id, dest_buffer, length) {
                                                Ok(()) => Ok(()),
                                                Err((err, buf)) => {
                                                    self.can_tx.replace(buf);
                                                    Err(err)
                                                }
                                            }
                                        },
                                    )
                                })
                                .unwrap_or_else(|err| err.into())
                        },
                    )
            })
            .unwrap_or_else(|err| err.into())
    }

    pub fn is_valid_process(&self, processid: ProcessId) -> bool {
        self.processid.map_or(true, |owning_process| {
            self.processes
                .enter(owning_process, |_, _| owning_process == processid)
                .unwrap_or(true)
        })
    }
}

impl<'a, Can: can::Can> SyscallDriver for CanCapsule<'a, Can> {
    fn command(
        &self,
        command_num: usize,
        arg1: usize,
        arg2: usize,
        processid: ProcessId,
    ) -> CommandReturn {
        // This driver exists.
        if command_num == 0 {
            return CommandReturn::success();
        }

        // Check to see if the process or no process at all
        // owns the capsule. Only one application can use the
        // capsule at a time.
        if !self.is_valid_process(processid) {
            return CommandReturn::failure(ErrorCode::RESERVE);
        } else {
            self.processid.set(processid);
        }

        match command_num {
            // Set the bitrate
            1 => match self.can.set_bitrate(arg1 as u32) {
                Ok(()) => CommandReturn::success(),
                Err(err) => CommandReturn::failure(err),
            },

            // Set the operation mode (Loopback, Monitoring, etc)
            2 => {
                match self.can.set_operation_mode(match arg1 {
                    0 => can::OperationMode::Loopback,
                    1 => can::OperationMode::Monitoring,
                    2 => can::OperationMode::Freeze,
                    _ => can::OperationMode::Normal,
                }) {
                    Ok(()) => CommandReturn::success(),
                    Err(err) => CommandReturn::failure(err),
                }
            }

            // Enable the peripheral
            3 => match self.can.enable() {
                Ok(()) => CommandReturn::success(),
                Err(err) => CommandReturn::failure(err),
            },

            // Disable the peripheral
            4 => match self.can.disable() {
                Ok(()) => CommandReturn::success(),
                Err(err) => CommandReturn::failure(err),
            },

            // Send a message with a 16-bit identifier
            5 => {
                let id = can::Id::Standard(arg1 as u16);
                self.processid
                    .map_or(
                        CommandReturn::failure(ErrorCode::BUSY),
                        |processid| match self.process_send_command(processid, id, arg2) {
                            Ok(()) => CommandReturn::success(),
                            Err(err) => CommandReturn::failure(err),
                        },
                    )
            }

            // Send a message with a 32-bit identifier
            6 => {
                let id = can::Id::Extended(arg1 as u32);
                self.processid
                    .map_or(
                        CommandReturn::failure(ErrorCode::BUSY),
                        |processid| match self.process_send_command(processid, id, arg2) {
                            Ok(()) => CommandReturn::success(),
                            Err(err) => CommandReturn::failure(err),
                        },
                    )
            }

            // Start receiving messages
            7 => {
                self.can_rx
                    .take()
                    .map_or(CommandReturn::failure(ErrorCode::NOMEM), |dest_buffer| {
                        self.processes
                            .enter(processid, |_, kernel| {
                                match kernel.get_readwrite_processbuffer(0).map_or_else(
                                    |err| err.into(),
                                    |buffer_ref| {
                                        buffer_ref
                                            .enter(|buffer| {
                                                // make sure that the receiving buffer can have at least
                                                // 2 messages of 8 bytes each and 4 another bytes for the counter
                                                if buffer.len()
                                                    >= 2 * can::STANDARD_CAN_PACKET_SIZE
                                                        + size_of::<u32>()
                                                {
                                                    Ok(())
                                                } else {
                                                    Err(ErrorCode::SIZE)
                                                }
                                            })
                                            .unwrap_or_else(|err| err.into())
                                    },
                                ) {
                                    Ok(()) => match self.can.start_receive_process(dest_buffer) {
                                        Ok(()) => CommandReturn::success(),
                                        Err((err, _)) => CommandReturn::failure(err),
                                    },
                                    Err(err) => CommandReturn::failure(err),
                                }
                            })
                            .unwrap_or_else(|err| err.into())
                    })
            }

            // Stop receiving messages
            8 => match self.can.stop_receive() {
                Ok(()) => CommandReturn::success(),
                Err(err) => CommandReturn::failure(err),
            },

            // Set the timing parameters
            9 => {
                match self.can.set_bit_timing(can::BitTiming {
                    segment1: ((arg1 & BYTE4_MASK) >> 24) as u8,
                    segment2: ((arg1 & BYTE3_MASK) >> 16) as u8,
                    propagation: arg2 as u8,
                    sync_jump_width: ((arg1 & BYTE2_MASK) >> 8) as u32,
                    baud_rate_prescaler: (arg1 & BYTE1_MASK) as u32,
                }) {
                    Ok(()) => CommandReturn::success(),
                    Err(err) => CommandReturn::failure(err),
                }
            }

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

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

impl<'a, Can: can::Can> can::ControllerClient for CanCapsule<'a, Can> {
    // This callback must be called after an `enable` or `disable` command was sent.
    // It stores the new state of the peripheral.
    fn state_changed(&self, state: can::State) {
        self.peripheral_state.replace(state);
    }

    // This callback must be called after an `enable` command was sent and after a
    // `state_changed` callback was called. If there is no error and the state of
    // the peripheral is Running, send to the userspace a success callback.
    // If the state is different or the status is an error, send to the userspace an
    // error callback.
    fn enabled(&self, status: Result<(), ErrorCode>) {
        match status {
            Ok(()) => match self.peripheral_state.take() {
                Some(can::State::Running) => {
                    self.schedule_callback(up_calls::UPCALL_ENABLE, (0, 0, 0));
                }
                Some(can::State::Error(err)) => {
                    self.schedule_callback(up_calls::UPCALL_ENABLE, (err as usize, 0, 0));
                }
                Some(can::State::Disabled) | None => {
                    self.schedule_callback(
                        up_calls::UPCALL_ENABLE,
                        (ErrorCode::OFF as usize, 0, 0),
                    );
                }
            },
            Err(err) => {
                self.peripheral_state.take();
                self.schedule_callback(up_calls::UPCALL_ENABLE, (err as usize, 0, 0));
            }
        }
    }

    // This callback must be called after an `disable` command was sent and after a
    // `state_changed` callback was called. If there is no error and  the state of
    // the peripheral is Disabled, send to the userspace a success callback.
    // If the state is different or the status is an error, send to the userspace an
    // error callback.
    fn disabled(&self, status: Result<(), ErrorCode>) {
        match status {
            Ok(()) => match self.peripheral_state.take() {
                Some(can::State::Disabled) => {
                    self.schedule_callback(up_calls::UPCALL_DISABLE, (0, 0, 0));
                }
                Some(can::State::Error(err)) => {
                    self.schedule_callback(up_calls::UPCALL_DISABLE, (err as usize, 0, 0));
                }
                Some(can::State::Running) | None => {
                    self.schedule_callback(
                        up_calls::UPCALL_DISABLE,
                        (ErrorCode::FAIL as usize, 0, 0),
                    );
                }
            },
            Err(err) => {
                self.peripheral_state.take();
                self.schedule_callback(up_calls::UPCALL_ENABLE, (err as usize, 0, 0));
            }
        }
        self.processid.clear();
    }
}

impl<'a, Can: can::Can> can::TransmitClient<{ can::STANDARD_CAN_PACKET_SIZE }>
    for CanCapsule<'a, Can>
{
    // This callback is called when the hardware acknowledges that a message
    // was sent. This callback also makes an upcall to the userspace.
    fn transmit_complete(
        &self,
        status: Result<(), can::Error>,
        buffer: &'static mut [u8; can::STANDARD_CAN_PACKET_SIZE],
    ) {
        self.can_tx.replace(buffer);
        match status {
            Ok(()) => self.schedule_callback(up_calls::UPCALL_MESSAGE_SENT, (0, 0, 0)),
            Err(err) => {
                self.schedule_callback(
                    up_calls::UPCALL_TRANSMISSION_ERROR,
                    (error_upcalls::ERROR_TX, err as usize, 0),
                );
            }
        }
    }
}

impl<'a, Can: can::Can> can::ReceiveClient<{ can::STANDARD_CAN_PACKET_SIZE }>
    for CanCapsule<'a, Can>
{
    // This callback is called when a new message is received on any receiving
    // fifo.
    fn message_received(
        &self,
        id: can::Id,
        buffer: &mut [u8; can::STANDARD_CAN_PACKET_SIZE],
        _len: usize,
        status: Result<(), can::Error>,
    ) {
        match status {
            Ok(()) => {
                let res: Result<(bool, u32), ErrorCode> =
                    self.processid.map_or(Err(ErrorCode::NOMEM), |processid| {
                        self.processes
                            .enter(processid, |app_data, kernel_data| {
                                kernel_data
                                    .get_readwrite_processbuffer(rw_allow::RW_ALLOW_BUFFER)
                                    .map_or_else(
                                        |err| Err(err.into()),
                                        |buffer_ref| {
                                            buffer_ref
                                                .mut_enter(|user_slice| {
                                                    StreamingProcessSlice::new(user_slice)
                                                        .append_chunk(buffer)
                                                        .inspect_err(|_err| {
                                                            app_data.lost_messages += 1;
                                                        })
                                                })
                                                .unwrap_or_else(|err| Err(err.into()))
                                        },
                                    )
                            })
                            .unwrap_or_else(|err| Err(err.into()))
                    });

                match res {
                    Err(err) => self.schedule_callback(
                        up_calls::UPCALL_TRANSMISSION_ERROR,
                        (error_upcalls::ERROR_RX, err as usize, 0),
                    ),
                    Ok((_first_chunk, new_offset)) => self.schedule_callback(
                        up_calls::UPCALL_MESSAGE_RECEIVED,
                        (
                            0,
                            new_offset as usize,
                            match id {
                                can::Id::Standard(u16) => u16 as usize,
                                can::Id::Extended(u32) => u32 as usize,
                            },
                        ),
                    ),
                }
            }
            Err(err) => {
                let kernel_err: ErrorCode = err.into();
                self.schedule_callback(
                    up_calls::UPCALL_TRANSMISSION_ERROR,
                    (error_upcalls::ERROR_RX, kernel_err.into(), 0),
                )
            }
        };
    }

    fn stopped(&self, buffer: &'static mut [u8; can::STANDARD_CAN_PACKET_SIZE]) {
        self.can_rx.replace(buffer);
        self.schedule_callback(up_calls::UPCALL_RECEIVED_STOPPED, (0, 0, 0));
    }
}