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
|
// CAN backend device
//
// Copyright 2023-2024 VIRTUAL OPEN SYSTEMS SAS. All Rights Reserved.
// Timos Ampelikiotis <t.ampelikiotis@virtualopensystems.com>
//
// SPDX-License-Identifier: Apache-2.0 or BSD-3-Clause
use log::{error, info, trace, warn};
use std::sync::{Arc, RwLock};
use std::thread::{spawn, JoinHandle};
use thiserror::Error as ThisError;
use vmm_sys_util::eventfd::{EventFd, EFD_NONBLOCK};
extern crate queues;
use queues::*;
extern crate socketcan;
use crate::virtio_can::{
VirtioCanConfig, VirtioCanFrame, CAN_CS_STARTED, CAN_CS_STOPPED, CAN_EFF_FLAG,
CAN_FRMF_TYPE_FD, VIRTIO_CAN_RX,
};
use socketcan::{
CanAnyFrame, CanDataFrame, CanFdFrame, CanFdSocket, EmbeddedFrame, ExtendedId, Frame, Id,
Socket, StandardId,
};
type Result<T> = std::result::Result<T, Error>;
#[derive(Copy, Clone, Debug, PartialEq, ThisError)]
/// Errors related to low level can helpers
pub(crate) enum Error {
#[error("Can open socket operation failed")]
SocketOpen,
#[error("Can write socket operation failed")]
SocketWrite,
#[error("Can read socket operation failed")]
SocketRead,
#[error("Pop can element operation failed")]
PopFailed,
#[error("Queue is empty")]
QueueEmpty,
#[error("Creating Eventfd for CAN events failed")]
EventFdFailed,
#[error("Push can element operation failed")]
PushFailed,
#[error("No output interface available")]
NoOutputInterface,
}
#[derive(Debug)]
pub(crate) struct CanController {
pub config: VirtioCanConfig,
pub can_name: String,
pub can_socket: Option<CanFdSocket>,
pub rx_event_fd: EventFd,
rx_fifo: Queue<VirtioCanFrame>,
pub status: bool,
pub ctrl_state: u8,
}
impl CanController {
// Creates a new controller corresponding to `device`.
pub(crate) fn new(can_name: String) -> Result<CanController> {
let can_name = can_name.to_owned();
info!("can_name: {:?}", can_name);
let rx_fifo = Queue::new();
let rx_efd = EventFd::new(EFD_NONBLOCK).map_err(|_| Error::EventFdFailed)?;
Ok(CanController {
config: VirtioCanConfig { status: 0x0.into() },
can_name,
can_socket: None,
rx_event_fd: rx_efd,
rx_fifo,
status: true,
ctrl_state: CAN_CS_STOPPED,
})
}
pub fn print_can_frame(canframe: VirtioCanFrame) {
trace!("canframe.msg_type 0x{:x}", canframe.msg_type.to_native());
trace!("canframe.can_id 0x{:x}", canframe.can_id.to_native());
trace!("canframe.length {}", canframe.length.to_native());
trace!("canframe.flags 0x{:x}", canframe.flags.to_native());
if canframe.length.to_native() == 0 {
trace!("[]");
return;
}
trace!("[");
let last_elem = canframe.length.to_native() as usize - 1;
for (index, sdu) in canframe.sdu.iter().enumerate() {
if index == last_elem {
trace!("0x{:x}", sdu);
break;
}
trace!("0x{:x}, ", sdu);
}
trace!("]");
}
pub fn start_read_thread(controller: Arc<RwLock<CanController>>) -> JoinHandle<Result<()>> {
spawn(move || CanController::read_can_socket(controller))
}
pub fn push(&mut self, rx_elem: VirtioCanFrame) -> Result<()> {
match self.rx_fifo.add(rx_elem) {
Ok(_) => Ok(()),
_ => Err(Error::PushFailed),
}
}
pub fn rx_is_empty(&mut self) -> bool {
self.rx_fifo.size() == 0
}
pub fn pop(&mut self) -> Result<VirtioCanFrame> {
if self.rx_fifo.size() < 1 {
return Err(Error::QueueEmpty);
}
match self.rx_fifo.remove() {
Ok(item) => Ok(item),
_ => Err(Error::PopFailed),
}
}
pub fn open_can_socket(&mut self) -> Result<()> {
self.can_socket = match CanFdSocket::open(&self.can_name) {
Ok(socket) => Some(socket),
Err(_) => {
warn!("Error opening CAN socket");
return Err(Error::SocketOpen);
}
};
Ok(())
}
// Helper function to process frame
fn process_frame<F: Frame>(frame: F, is_fd: bool) -> VirtioCanFrame {
VirtioCanFrame {
msg_type: VIRTIO_CAN_RX.into(),
can_id: frame.id_word().into(),
length: (frame.data().len() as u16).into(),
reserved: 0.into(),
flags: if is_fd {
CAN_FRMF_TYPE_FD.into()
} else {
0.into()
},
sdu: {
let mut sdu_data: [u8; 64] = [0; 64];
sdu_data[..frame.data().len()].copy_from_slice(frame.data());
sdu_data
},
}
}
pub fn read_can_socket(controller: Arc<RwLock<CanController>>) -> Result<()> {
let can_name = &controller.read().unwrap().can_name.clone();
dbg!("Start reading from {} socket!", &can_name);
let socket = match CanFdSocket::open(can_name) {
Ok(socket) => socket,
Err(_) => {
warn!("Error opening CAN socket");
return Err(Error::SocketOpen);
}
};
// Set non-blocking otherwise the device will not restart immediatelly
// when the VM closes, and a new canfd message needs to be received for
// restart to happen.
// This caused by the fact that the thread is stacked in read function
// and does not go to the next loop to check the status condition.
socket
.set_nonblocking(true)
.expect("Cannot set nonblocking");
// Receive CAN messages
loop {
// If the status variable is false then break and exit.
if !controller.read().unwrap().status {
dbg!("exit read can thread");
return Ok(());
}
if let Ok(frame) = socket.read_frame() {
// If ctrl_state is stopped, consume the received CAN/FD frame
// and loop till the ctrl_state changes to started or the thread
// to exit.
if controller.read().unwrap().ctrl_state != CAN_CS_STARTED {
trace!("CAN/FD frame is received but not saved!");
continue;
}
// Match and process frame variants
let read_can_frame = match frame {
CanAnyFrame::Normal(frame) => {
trace!("Received CAN frame: {:?}", frame);
Self::process_frame(frame, false)
}
CanAnyFrame::Fd(frame) => {
trace!("Received CAN FD frame: {:?}", frame);
Self::process_frame(frame, true)
}
CanAnyFrame::Remote(frame) => {
trace!("Received Remote CAN frame: {:?}", frame);
Self::process_frame(frame, false)
}
CanAnyFrame::Error(frame) => {
trace!("Received Error frame: {:?}", frame);
Self::process_frame(frame, false)
}
};
match controller.write().unwrap().push(read_can_frame) {
Ok(_) => warn!("New Can frame was received"),
Err(_) => {
warn!("Error read/push CAN frame");
return Err(Error::SocketRead);
}
};
controller
.write()
.unwrap()
.rx_event_fd
.write(1)
.expect("Fail to write on rx_event_fd");
}
}
}
pub(crate) fn exit_read_thread(&mut self) {
trace!("Exit can read thread\n");
self.status = false;
}
pub(crate) fn config(&mut self) -> &VirtioCanConfig {
&self.config
}
pub(crate) fn can_out(&self, tx_request: VirtioCanFrame) -> Result<()> {
// Create a CAN frame with a specific CAN-ID and the data buffer
let can_id: Id = if (tx_request.can_id.to_native() & CAN_EFF_FLAG) != 0 {
// SAFETY: Use new_unchecked cause checks have been taken place
// to prior stage. Also flags have beem already added on can_id
// so tnew will fail (can_id + can_flags) > 29 bits
unsafe { Id::Extended(ExtendedId::new_unchecked(tx_request.can_id.into())) }
} else {
// SAFETY: Use new_unchecked cause checks have been taken place
// to prior stage. Also flags have beem already added on can_id
// so tnew will fail (can_id + can_flags) > 11 bits
unsafe {
Id::Standard(StandardId::new_unchecked(
tx_request.can_id.to_native() as u16
))
}
};
// Grab the data to be tranfered
let data_len = tx_request.length.to_native() as usize;
let data: Vec<u8> = tx_request.sdu.iter().cloned().take(data_len).collect();
// Format CAN/FD frame
let frame: CanAnyFrame = if (tx_request.flags.to_native() & CAN_FRMF_TYPE_FD) != 0 {
CanAnyFrame::Fd(CanFdFrame::new(can_id, &data).expect("Fail to create CanFdFrame"))
} else {
CanAnyFrame::Normal(CanDataFrame::new(can_id, &data).expect("Fail to create CanFrame"))
};
// Send the CAN/FD frame
let socket = self.can_socket.as_ref().ok_or("No available device");
match socket {
Ok(socket) => match socket.write_frame(&frame) {
Ok(_) => Ok(()),
Err(_) => {
warn!("Error write CAN socket");
Err(Error::SocketWrite)
}
},
Err(_) => Err(Error::NoOutputInterface),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::vhu_can::VhostUserCanBackend;
use std::sync::{Arc, RwLock};
#[test]
fn test_can_controller_creation() {
let can_name = "can".to_string();
let controller = CanController::new(can_name.clone()).unwrap();
assert_eq!(controller.can_name, can_name);
}
#[test]
fn test_can_controller_push_and_pop() {
let can_name = "can".to_string();
let mut controller = CanController::new(can_name.clone()).unwrap();
let frame = VirtioCanFrame {
msg_type: VIRTIO_CAN_RX.into(),
can_id: 123.into(),
length: 64.into(),
reserved: 0.into(),
flags: 0.into(),
sdu: [0; 64],
};
// Test push
controller.push(frame).unwrap();
// Test pop
let pop_result = controller.pop().unwrap();
assert_eq!(pop_result, frame);
}
#[test]
fn test_can_controller_config() {
let can_name = "can".to_string();
let mut controller = CanController::new(can_name.clone()).unwrap();
// Test config
let config = controller.config();
assert_eq!(config.status.to_native(), 0);
}
#[test]
fn test_can_controller_operation() {
let can_name = "can".to_string();
let mut controller = CanController::new(can_name.clone()).unwrap();
let frame = VirtioCanFrame {
msg_type: VIRTIO_CAN_RX.into(),
can_id: 123.into(),
length: 64.into(),
reserved: 0.into(),
flags: 0.into(),
sdu: [0; 64],
};
match controller.open_can_socket() {
Ok(_) => {
// Test operation
let operation_result = controller.can_out(frame);
assert!(operation_result.is_ok());
}
Err(_) => warn!("There is no CAN interface with {} name", can_name),
}
}
#[test]
fn test_can_controller_start_read_thread() {
let can_name = "can".to_string();
let controller = CanController::new(can_name.clone()).unwrap();
let arc_controller = Arc::new(RwLock::new(controller));
// Test start_read_thread
let thread_handle = CanController::start_read_thread(arc_controller.clone());
assert!(thread_handle.join().is_ok());
}
#[test]
fn test_can_open_socket_fail() {
let controller =
CanController::new("can0".to_string()).expect("Could not build controller");
let controller = Arc::new(RwLock::new(controller));
VhostUserCanBackend::new(controller.clone()).expect("Could not build vhucan device");
assert_eq!(
controller.write().unwrap().open_can_socket(),
Err(Error::SocketOpen)
);
}
#[test]
fn test_can_read_socket_fail() {
let controller =
CanController::new("can0".to_string()).expect("Could not build controller");
let controller = Arc::new(RwLock::new(controller));
VhostUserCanBackend::new(controller.clone()).expect("Could not build vhucan device");
assert_eq!(
CanController::read_can_socket(controller),
Err(Error::SocketOpen)
);
}
}
|