1 /*
2 * Copyright (c) 2021 Vestas Wind Systems A/S
3 * Copyright (c) 2018 Karsten Koenig
4 * Copyright (c) 2018 Alexander Wachter
5 *
6 * SPDX-License-Identifier: Apache-2.0
7 */
8
9 #ifndef ZEPHYR_INCLUDE_DRIVERS_CAN_H_
10 #define ZEPHYR_INCLUDE_DRIVERS_CAN_H_
11
12 #include <errno.h>
13
14 #include <zephyr/types.h>
15 #include <zephyr/device.h>
16 #include <zephyr/kernel.h>
17 #include <string.h>
18 #include <zephyr/sys_clock.h>
19 #include <zephyr/sys/util.h>
20
21 #ifdef __cplusplus
22 extern "C" {
23 #endif
24
25 /**
26 * @brief CAN Interface
27 * @defgroup can_interface CAN Interface
28 * @ingroup io_interfaces
29 * @{
30 */
31
32 /**
33 * @name CAN frame definitions
34 * @{
35 */
36
37 /**
38 * @brief Bit mask for a standard (11-bit) CAN identifier.
39 */
40 #define CAN_STD_ID_MASK 0x7FFU
41 /**
42 * @brief Maximum value for a standard (11-bit) CAN identifier.
43 */
44 #define CAN_MAX_STD_ID CAN_STD_ID_MASK
45 /**
46 * @brief Bit mask for an extended (29-bit) CAN identifier.
47 */
48 #define CAN_EXT_ID_MASK 0x1FFFFFFFU
49 /**
50 * @brief Maximum value for an extended (29-bit) CAN identifier.
51 */
52 #define CAN_MAX_EXT_ID CAN_EXT_ID_MASK
53 /**
54 * @brief Maximum data length code for CAN 2.0A/2.0B.
55 */
56 #define CAN_MAX_DLC 8U
57 /**
58 * @brief Maximum data length code for CAN-FD.
59 */
60 #define CANFD_MAX_DLC 15U
61
62 /**
63 * @cond INTERNAL_HIDDEN
64 * Internally calculated maximum data length
65 */
66 #ifndef CONFIG_CAN_FD_MODE
67 #define CAN_MAX_DLEN 8U
68 #else
69 #define CAN_MAX_DLEN 64U
70 #endif /* CONFIG_CAN_FD_MODE */
71
72 /** @endcond */
73
74 /** @} */
75
76 /**
77 * @name CAN controller mode flags
78 * @anchor CAN_MODE_FLAGS
79 *
80 * @{
81 */
82
83 /** Normal mode. */
84 #define CAN_MODE_NORMAL 0
85
86 /** Controller is in loopback mode (receives own frames). */
87 #define CAN_MODE_LOOPBACK BIT(0)
88
89 /** Controller is not allowed to send dominant bits. */
90 #define CAN_MODE_LISTENONLY BIT(1)
91
92 /** Controller allows transmitting/receiving CAN-FD frames. */
93 #define CAN_MODE_FD BIT(2)
94
95 /** Controller does not retransmit in case of lost arbitration or missing ACK */
96 #define CAN_MODE_ONE_SHOT BIT(3)
97
98 /** Controller uses triple sampling mode */
99 #define CAN_MODE_3_SAMPLES BIT(4)
100
101 /** @} */
102
103 /**
104 * @brief Provides a type to hold CAN controller configuration flags.
105 *
106 * The lower 24 bits are reserved for common CAN controller mode flags. The upper 8 bits are
107 * reserved for CAN controller/driver specific flags.
108 *
109 * @see @ref CAN_MODE_FLAGS.
110 */
111 typedef uint32_t can_mode_t;
112
113 /**
114 * @brief Defines the state of the CAN controller
115 */
116 enum can_state {
117 /** Error-active state (RX/TX error count < 96). */
118 CAN_STATE_ERROR_ACTIVE,
119 /** Error-warning state (RX/TX error count < 128). */
120 CAN_STATE_ERROR_WARNING,
121 /** Error-passive state (RX/TX error count < 256). */
122 CAN_STATE_ERROR_PASSIVE,
123 /** Bus-off state (RX/TX error count >= 256). */
124 CAN_STATE_BUS_OFF,
125 /** CAN controller is stopped and does not participate in CAN communication. */
126 CAN_STATE_STOPPED,
127 };
128
129 /**
130 * @name CAN frame flags
131 * @anchor CAN_FRAME_FLAGS
132 *
133 * @{
134 */
135
136 /** Frame uses extended (29-bit) CAN ID */
137 #define CAN_FRAME_IDE BIT(0)
138
139 /** Frame is a Remote Transmission Request (RTR) */
140 #define CAN_FRAME_RTR BIT(1)
141
142 /** Frame uses CAN-FD format (FDF) */
143 #define CAN_FRAME_FDF BIT(2)
144
145 /** Frame uses CAN-FD Baud Rate Switch (BRS). Only valid in combination with ``CAN_FRAME_FDF``. */
146 #define CAN_FRAME_BRS BIT(3)
147
148 /** CAN-FD Error State Indicator (ESI). Indicates that the transmitting node is in error-passive
149 * state. Only valid in combination with ``CAN_FRAME_FDF``.
150 */
151 #define CAN_FRAME_ESI BIT(4)
152
153 /** @} */
154
155 /**
156 * @brief CAN frame structure
157 */
158 struct can_frame {
159 /** Standard (11-bit) or extended (29-bit) CAN identifier. */
160 uint32_t id : 29;
161 /** @cond INTERNAL_HIDDEN */
162 uint8_t res0 : 3; /* reserved/padding. */
163 /** @endcond */
164 /** Data Length Code (DLC) indicating data length in bytes. */
165 uint8_t dlc;
166 /** Flags. @see @ref CAN_FRAME_FLAGS. */
167 uint8_t flags;
168 #if defined(CONFIG_CAN_RX_TIMESTAMP) || defined(__DOXYGEN__)
169 /** Captured value of the free-running timer in the CAN controller when
170 * this frame was received. The timer is incremented every bit time and
171 * captured at the start of frame bit (SOF).
172 *
173 * @note @kconfig{CONFIG_CAN_RX_TIMESTAMP} must be selected for this
174 * field to be available.
175 */
176 uint16_t timestamp;
177 #else
178 /** @cond INTERNAL_HIDDEN */
179 uint16_t res1; /* reserved/padding. */
180 /** @endcond */
181 #endif
182 /** The frame payload data. */
183 union {
184 uint8_t data[CAN_MAX_DLEN];
185 uint32_t data_32[DIV_ROUND_UP(CAN_MAX_DLEN, sizeof(uint32_t))];
186 };
187 };
188
189 /**
190 * @name CAN filter flags
191 * @anchor CAN_FILTER_FLAGS
192 *
193 * @{
194 */
195
196 /** Filter matches frames with extended (29-bit) CAN IDs */
197 #define CAN_FILTER_IDE BIT(0)
198
199 /** Filter matches Remote Transmission Request (RTR) frames */
200 #define CAN_FILTER_RTR BIT(1)
201
202 /** Filter matches data frames */
203 #define CAN_FILTER_DATA BIT(2)
204
205 /** Filter matches CAN-FD frames (FDF) */
206 #define CAN_FILTER_FDF BIT(3)
207
208 /** @} */
209
210 /**
211 * @brief CAN filter structure
212 */
213 struct can_filter {
214 /** CAN identifier to match. */
215 uint32_t id : 29;
216 /** @cond INTERNAL_HIDDEN */
217 uint32_t res0 : 3;
218 /** @endcond */
219 /** CAN identifier matching mask. If a bit in this mask is 0, the value
220 * of the corresponding bit in the ``id`` field is ignored by the filter.
221 */
222 uint32_t mask : 29;
223 /** Flags. @see @ref CAN_FILTER_FLAGS. */
224 uint8_t flags;
225 };
226
227 /**
228 * @brief CAN controller error counters
229 */
230 struct can_bus_err_cnt {
231 /** Value of the CAN controller transmit error counter. */
232 uint8_t tx_err_cnt;
233 /** Value of the CAN controller receive error counter. */
234 uint8_t rx_err_cnt;
235 };
236
237 /**
238 * @brief CAN bus timing structure
239 *
240 * This struct is used to pass bus timing values to the configuration and
241 * bitrate calculation functions.
242 *
243 * The propagation segment represents the time of the signal propagation. Phase
244 * segment 1 and phase segment 2 define the sampling point. The ``prop_seg`` and
245 * ``phase_seg1`` values affect the sampling point in the same way and some
246 * controllers only have a register for the sum of those two. The sync segment
247 * always has a length of 1 time quantum (see below).
248 *
249 * @code{.text}
250 *
251 * +---------+----------+------------+------------+
252 * |sync_seg | prop_seg | phase_seg1 | phase_seg2 |
253 * +---------+----------+------------+------------+
254 * ^
255 * Sampling-Point
256 *
257 * @endcode
258 *
259 * 1 time quantum (tq) has the length of 1/(core_clock / prescaler). The bitrate
260 * is defined by the core clock divided by the prescaler and the sum of the
261 * segments:
262 *
263 * br = (core_clock / prescaler) / (1 + prop_seg + phase_seg1 + phase_seg2)
264 *
265 * The Synchronization Jump Width (SJW) defines the amount of time quanta the
266 * sample point can be moved. The sample point is moved when resynchronization
267 * is needed.
268 */
269 struct can_timing {
270 /** Synchronisation jump width. */
271 uint16_t sjw;
272 /** Propagation segment. */
273 uint16_t prop_seg;
274 /** Phase segment 1. */
275 uint16_t phase_seg1;
276 /** Phase segment 2. */
277 uint16_t phase_seg2;
278 /** Prescaler value. */
279 uint16_t prescaler;
280 };
281
282 /**
283 * @brief Defines the application callback handler function signature
284 *
285 * @param dev Pointer to the device structure for the driver instance.
286 * @param error Status of the performed send operation. See the list of
287 * return values for @a can_send() for value descriptions.
288 * @param user_data User data provided when the frame was sent.
289 */
290 typedef void (*can_tx_callback_t)(const struct device *dev, int error, void *user_data);
291
292 /**
293 * @brief Defines the application callback handler function signature for receiving.
294 *
295 * @param dev Pointer to the device structure for the driver instance.
296 * @param frame Received frame.
297 * @param user_data User data provided when the filter was added.
298 */
299 typedef void (*can_rx_callback_t)(const struct device *dev, struct can_frame *frame,
300 void *user_data);
301
302 /**
303 * @brief Defines the state change callback handler function signature
304 *
305 * @param dev Pointer to the device structure for the driver instance.
306 * @param state State of the CAN controller.
307 * @param err_cnt CAN controller error counter values.
308 * @param user_data User data provided the callback was set.
309 */
310 typedef void (*can_state_change_callback_t)(const struct device *dev,
311 enum can_state state,
312 struct can_bus_err_cnt err_cnt,
313 void *user_data);
314
315 /**
316 * @cond INTERNAL_HIDDEN
317 *
318 * For internal driver use only, skip these in public documentation.
319 */
320
321 /**
322 * @brief Callback API upon setting CAN bus timing
323 * See @a can_set_timing() for argument description
324 */
325 typedef int (*can_set_timing_t)(const struct device *dev,
326 const struct can_timing *timing);
327
328 /**
329 * @brief Optional callback API upon setting CAN-FD bus timing for the data phase.
330 * See @a can_set_timing_data() for argument description
331 */
332 typedef int (*can_set_timing_data_t)(const struct device *dev,
333 const struct can_timing *timing_data);
334
335 /**
336 * @brief Callback API upon getting CAN controller capabilities
337 * See @a can_get_capabilities() for argument description
338 */
339 typedef int (*can_get_capabilities_t)(const struct device *dev, can_mode_t *cap);
340
341 /**
342 * @brief Callback API upon starting CAN controller
343 * See @a can_start() for argument description
344 */
345 typedef int (*can_start_t)(const struct device *dev);
346
347 /**
348 * @brief Callback API upon stopping CAN controller
349 * See @a can_stop() for argument description
350 */
351 typedef int (*can_stop_t)(const struct device *dev);
352
353 /**
354 * @brief Callback API upon setting CAN controller mode
355 * See @a can_set_mode() for argument description
356 */
357 typedef int (*can_set_mode_t)(const struct device *dev, can_mode_t mode);
358
359 /**
360 * @brief Callback API upon sending a CAN frame
361 * See @a can_send() for argument description
362 *
363 * @note From a driver perspective `callback` will never be `NULL` as a default callback will be
364 * provided if none is provided by the caller. This allows for simplifying the driver handling.
365 */
366 typedef int (*can_send_t)(const struct device *dev,
367 const struct can_frame *frame,
368 k_timeout_t timeout, can_tx_callback_t callback,
369 void *user_data);
370
371 /**
372 * @brief Callback API upon adding an RX filter
373 * See @a can_add_rx_callback() for argument description
374 */
375 typedef int (*can_add_rx_filter_t)(const struct device *dev,
376 can_rx_callback_t callback,
377 void *user_data,
378 const struct can_filter *filter);
379
380 /**
381 * @brief Callback API upon removing an RX filter
382 * See @a can_remove_rx_filter() for argument description
383 */
384 typedef void (*can_remove_rx_filter_t)(const struct device *dev, int filter_id);
385
386 /**
387 * @brief Callback API upon recovering the CAN bus
388 * See @a can_recover() for argument description
389 */
390 typedef int (*can_recover_t)(const struct device *dev, k_timeout_t timeout);
391
392 /**
393 * @brief Callback API upon getting the CAN controller state
394 * See @a can_get_state() for argument description
395 */
396 typedef int (*can_get_state_t)(const struct device *dev, enum can_state *state,
397 struct can_bus_err_cnt *err_cnt);
398
399 /**
400 * @brief Callback API upon setting a state change callback
401 * See @a can_set_state_change_callback() for argument description
402 */
403 typedef void(*can_set_state_change_callback_t)(const struct device *dev,
404 can_state_change_callback_t callback,
405 void *user_data);
406
407 /**
408 * @brief Callback API upon getting the CAN core clock rate
409 * See @a can_get_core_clock() for argument description
410 */
411 typedef int (*can_get_core_clock_t)(const struct device *dev, uint32_t *rate);
412
413 /**
414 * @brief Optional callback API upon getting the maximum number of concurrent CAN RX filters
415 * See @a can_get_max_filters() for argument description
416 */
417 typedef int (*can_get_max_filters_t)(const struct device *dev, bool ide);
418
419 /**
420 * @brief Optional callback API upon getting the maximum supported bitrate
421 * See @a can_get_max_bitrate() for argument description
422 */
423 typedef int (*can_get_max_bitrate_t)(const struct device *dev, uint32_t *max_bitrate);
424
425 __subsystem struct can_driver_api {
426 can_get_capabilities_t get_capabilities;
427 can_start_t start;
428 can_stop_t stop;
429 can_set_mode_t set_mode;
430 can_set_timing_t set_timing;
431 can_send_t send;
432 can_add_rx_filter_t add_rx_filter;
433 can_remove_rx_filter_t remove_rx_filter;
434 #if !defined(CONFIG_CAN_AUTO_BUS_OFF_RECOVERY) || defined(__DOXYGEN__)
435 can_recover_t recover;
436 #endif /* CONFIG_CAN_AUTO_BUS_OFF_RECOVERY */
437 can_get_state_t get_state;
438 can_set_state_change_callback_t set_state_change_callback;
439 can_get_core_clock_t get_core_clock;
440 can_get_max_filters_t get_max_filters;
441 can_get_max_bitrate_t get_max_bitrate;
442 /* Min values for the timing registers */
443 struct can_timing timing_min;
444 /* Max values for the timing registers */
445 struct can_timing timing_max;
446 #if defined(CONFIG_CAN_FD_MODE) || defined(__DOXYGEN__)
447 can_set_timing_data_t set_timing_data;
448 /* Min values for the timing registers during the data phase */
449 struct can_timing timing_data_min;
450 /* Max values for the timing registers during the data phase */
451 struct can_timing timing_data_max;
452 #endif /* CONFIG_CAN_FD_MODE */
453 };
454
455 /** @endcond */
456
457 #if defined(CONFIG_CAN_STATS) || defined(__DOXYGEN__)
458
459 #include <zephyr/stats/stats.h>
460
461 /** @cond INTERNAL_HIDDEN */
462
463 STATS_SECT_START(can)
464 STATS_SECT_ENTRY32(bit0_error)
465 STATS_SECT_ENTRY32(bit1_error)
466 STATS_SECT_ENTRY32(stuff_error)
467 STATS_SECT_ENTRY32(crc_error)
468 STATS_SECT_ENTRY32(form_error)
469 STATS_SECT_ENTRY32(ack_error)
470 STATS_SECT_ENTRY32(rx_overrun)
471 STATS_SECT_END;
472
473 STATS_NAME_START(can)
474 STATS_NAME(can, bit0_error)
475 STATS_NAME(can, bit1_error)
476 STATS_NAME(can, stuff_error)
477 STATS_NAME(can, crc_error)
478 STATS_NAME(can, form_error)
479 STATS_NAME(can, ack_error)
480 STATS_NAME(can, rx_overrun)
481 STATS_NAME_END(can);
482
483 /** @endcond */
484
485 /**
486 * @brief CAN specific device state which allows for CAN device class specific
487 * additions
488 */
489 struct can_device_state {
490 struct device_state devstate;
491 struct stats_can stats;
492 };
493
494 /** @cond INTERNAL_HIDDEN */
495
496 /**
497 * @brief Get pointer to CAN statistics structure
498 */
499 #define Z_CAN_GET_STATS(dev_) \
500 CONTAINER_OF(dev_->state, struct can_device_state, devstate)->stats
501
502 /** @endcond */
503
504 /**
505 * @brief Increment the bit0 error counter for a CAN device
506 *
507 * The bit0 error counter is incremented when the CAN controller is unable to
508 * transmit a dominant bit.
509 *
510 * @param dev_ Pointer to the device structure for the driver instance.
511 */
512 #define CAN_STATS_BIT0_ERROR_INC(dev_) \
513 STATS_INC(Z_CAN_GET_STATS(dev_), bit0_error)
514
515 /**
516 * @brief Increment the bit1 (recessive) error counter for a CAN device
517 *
518 * The bit1 error counter is incremented when the CAN controller is unable to
519 * transmit a recessive bit.
520 *
521 * @param dev_ Pointer to the device structure for the driver instance.
522 */
523 #define CAN_STATS_BIT1_ERROR_INC(dev_) \
524 STATS_INC(Z_CAN_GET_STATS(dev_), bit1_error)
525
526 /**
527 * @brief Increment the stuffing error counter for a CAN device
528 *
529 * The stuffing error counter is incremented when the CAN controller detects a
530 * bit stuffing error.
531 *
532 * @param dev_ Pointer to the device structure for the driver instance.
533 */
534 #define CAN_STATS_STUFF_ERROR_INC(dev_) \
535 STATS_INC(Z_CAN_GET_STATS(dev_), stuff_error)
536
537 /**
538 * @brief Increment the CRC error counter for a CAN device
539 *
540 * The CRC error counter is incremented when the CAN controller detects a frame
541 * with an invalid CRC.
542 *
543 * @param dev_ Pointer to the device structure for the driver instance.
544 */
545 #define CAN_STATS_CRC_ERROR_INC(dev_) \
546 STATS_INC(Z_CAN_GET_STATS(dev_), crc_error)
547
548 /**
549 * @brief Increment the form error counter for a CAN device
550 *
551 * The form error counter is incremented when the CAN controller detects a
552 * fixed-form bit field containing illegal bits.
553 *
554 * @param dev_ Pointer to the device structure for the driver instance.
555 */
556 #define CAN_STATS_FORM_ERROR_INC(dev_) \
557 STATS_INC(Z_CAN_GET_STATS(dev_), form_error)
558
559 /**
560 * @brief Increment the acknowledge error counter for a CAN device
561 *
562 * The acknowledge error counter is incremented when the CAN controller does not
563 * monitor a dominant bit in the ACK slot.
564 *
565 * @param dev_ Pointer to the device structure for the driver instance.
566 */
567 #define CAN_STATS_ACK_ERROR_INC(dev_) \
568 STATS_INC(Z_CAN_GET_STATS(dev_), ack_error)
569
570 /**
571 * @brief Increment the RX overrun counter for a CAN device
572 *
573 * The RX overrun counter is incremented when the CAN controller receives a CAN
574 * frame matching an installed filter but lacks the capacity to store it (either
575 * due to an already full RX mailbox or a full RX FIFO).
576 *
577 * @param dev_ Pointer to the device structure for the driver instance.
578 */
579 #define CAN_STATS_RX_OVERRUN_INC(dev_) \
580 STATS_INC(Z_CAN_GET_STATS(dev_), rx_overrun)
581
582 /**
583 * @brief Zero all statistics for a CAN device
584 *
585 * The driver is reponsible for resetting the statistics before starting the CAN
586 * controller.
587 *
588 * @param dev_ Pointer to the device structure for the driver instance.
589 */
590 #define CAN_STATS_RESET(dev_) \
591 stats_reset(&(Z_CAN_GET_STATS(dev_).s_hdr))
592
593 /** @cond INTERNAL_HIDDEN */
594
595 /**
596 * @brief Define a statically allocated and section assigned CAN device state
597 */
598 #define Z_CAN_DEVICE_STATE_DEFINE(dev_id) \
599 static struct can_device_state Z_DEVICE_STATE_NAME(dev_id) \
600 __attribute__((__section__(".z_devstate")))
601
602 /**
603 * @brief Define a CAN device init wrapper function
604 *
605 * This does device instance specific initialization of common data (such as stats)
606 * and calls the given init_fn
607 */
608 #define Z_CAN_INIT_FN(dev_id, init_fn) \
609 static inline int UTIL_CAT(dev_id, _init)(const struct device *dev) \
610 { \
611 struct can_device_state *state = \
612 CONTAINER_OF(dev->state, struct can_device_state, devstate); \
613 stats_init(&state->stats.s_hdr, STATS_SIZE_32, 7, \
614 STATS_NAME_INIT_PARMS(can)); \
615 stats_register(dev->name, &(state->stats.s_hdr)); \
616 if (init_fn != NULL) { \
617 return init_fn(dev); \
618 } \
619 \
620 return 0; \
621 }
622
623 /** @endcond */
624
625 /**
626 * @brief Like DEVICE_DT_DEFINE() with CAN device specifics.
627 *
628 * @details Defines a device which implements the CAN API. May generate a custom
629 * device_state container struct and init_fn wrapper when needed depending on
630 * @kconfig{CONFIG_CAN_STATS}.
631 *
632 * @param node_id The devicetree node identifier.
633 * @param init_fn Name of the init function of the driver.
634 * @param pm PM device resources reference (NULL if device does not use PM).
635 * @param data Pointer to the device's private data.
636 * @param config The address to the structure containing the configuration
637 * information for this instance of the driver.
638 * @param level The initialization level. See SYS_INIT() for
639 * details.
640 * @param prio Priority within the selected initialization level. See
641 * SYS_INIT() for details.
642 * @param api Provides an initial pointer to the API function struct
643 * used by the driver. Can be NULL.
644 */
645 #define CAN_DEVICE_DT_DEFINE(node_id, init_fn, pm, data, config, level, \
646 prio, api, ...) \
647 Z_CAN_DEVICE_STATE_DEFINE(Z_DEVICE_DT_DEV_ID(node_id)); \
648 Z_CAN_INIT_FN(Z_DEVICE_DT_DEV_ID(node_id), init_fn) \
649 Z_DEVICE_DEFINE(node_id, Z_DEVICE_DT_DEV_ID(node_id), \
650 DEVICE_DT_NAME(node_id), \
651 &UTIL_CAT(Z_DEVICE_DT_DEV_ID(node_id), _init), \
652 pm, data, config, level, prio, api, \
653 &(Z_DEVICE_STATE_NAME(Z_DEVICE_DT_DEV_ID(node_id)).devstate), \
654 __VA_ARGS__)
655
656 #else /* CONFIG_CAN_STATS */
657
658 #define CAN_STATS_BIT0_ERROR_INC(dev_)
659 #define CAN_STATS_BIT1_ERROR_INC(dev_)
660 #define CAN_STATS_STUFF_ERROR_INC(dev_)
661 #define CAN_STATS_CRC_ERROR_INC(dev_)
662 #define CAN_STATS_FORM_ERROR_INC(dev_)
663 #define CAN_STATS_ACK_ERROR_INC(dev_)
664 #define CAN_STATS_RX_OVERRUN_INC(dev_)
665 #define CAN_STATS_RESET(dev_)
666
667 #define CAN_DEVICE_DT_DEFINE(node_id, init_fn, pm, data, config, level, \
668 prio, api, ...) \
669 DEVICE_DT_DEFINE(node_id, init_fn, pm, data, config, level, \
670 prio, api, __VA_ARGS__)
671
672 #endif /* CONFIG_CAN_STATS */
673
674 /**
675 * @brief Like CAN_DEVICE_DT_DEFINE() for an instance of a DT_DRV_COMPAT compatible
676 *
677 * @param inst Instance number. This is replaced by <tt>DT_DRV_COMPAT(inst)</tt>
678 * in the call to CAN_DEVICE_DT_DEFINE().
679 * @param ... Other parameters as expected by CAN_DEVICE_DT_DEFINE().
680 */
681 #define CAN_DEVICE_DT_INST_DEFINE(inst, ...) \
682 CAN_DEVICE_DT_DEFINE(DT_DRV_INST(inst), __VA_ARGS__)
683
684 /**
685 * @name CAN controller configuration
686 *
687 * @{
688 */
689
690 /**
691 * @brief Get the CAN core clock rate
692 *
693 * Returns the CAN core clock rate. One time quantum is 1/(core clock rate).
694 *
695 * @param dev Pointer to the device structure for the driver instance.
696 * @param[out] rate CAN core clock rate in Hz.
697 *
698 * @return 0 on success, or a negative error code on error
699 */
700 __syscall int can_get_core_clock(const struct device *dev, uint32_t *rate);
701
z_impl_can_get_core_clock(const struct device * dev,uint32_t * rate)702 static inline int z_impl_can_get_core_clock(const struct device *dev, uint32_t *rate)
703 {
704 const struct can_driver_api *api = (const struct can_driver_api *)dev->api;
705
706 return api->get_core_clock(dev, rate);
707 }
708
709 /**
710 * @brief Get maximum supported bitrate
711 *
712 * Get the maximum supported bitrate for the CAN controller/transceiver combination.
713 *
714 * @param dev Pointer to the device structure for the driver instance.
715 * @param[out] max_bitrate Maximum supported bitrate in bits/s
716 *
717 * @retval 0 If successful.
718 * @retval -EIO General input/output error.
719 * @retval -ENOSYS If this function is not implemented by the driver.
720 */
721 __syscall int can_get_max_bitrate(const struct device *dev, uint32_t *max_bitrate);
722
z_impl_can_get_max_bitrate(const struct device * dev,uint32_t * max_bitrate)723 static inline int z_impl_can_get_max_bitrate(const struct device *dev, uint32_t *max_bitrate)
724 {
725 const struct can_driver_api *api = (const struct can_driver_api *)dev->api;
726
727 if (api->get_max_bitrate == NULL) {
728 return -ENOSYS;
729 }
730
731 return api->get_max_bitrate(dev, max_bitrate);
732 }
733
734 /**
735 * @brief Get the minimum supported timing parameter values.
736 *
737 * @param dev Pointer to the device structure for the driver instance.
738 *
739 * @return Pointer to the minimum supported timing parameter values.
740 */
741 __syscall const struct can_timing *can_get_timing_min(const struct device *dev);
742
z_impl_can_get_timing_min(const struct device * dev)743 static inline const struct can_timing *z_impl_can_get_timing_min(const struct device *dev)
744 {
745 const struct can_driver_api *api = (const struct can_driver_api *)dev->api;
746
747 return &api->timing_min;
748 }
749
750 /**
751 * @brief Get the maximum supported timing parameter values.
752 *
753 * @param dev Pointer to the device structure for the driver instance.
754 *
755 * @return Pointer to the maximum supported timing parameter values.
756 */
757 __syscall const struct can_timing *can_get_timing_max(const struct device *dev);
758
z_impl_can_get_timing_max(const struct device * dev)759 static inline const struct can_timing *z_impl_can_get_timing_max(const struct device *dev)
760 {
761 const struct can_driver_api *api = (const struct can_driver_api *)dev->api;
762
763 return &api->timing_max;
764 }
765
766 /**
767 * @brief Calculate timing parameters from bitrate and sample point
768 *
769 * Calculate the timing parameters from a given bitrate in bits/s and the
770 * sampling point in permill (1/1000) of the entire bit time. The bitrate must
771 * always match perfectly. If no result can be reached for the given parameters,
772 * -EINVAL is returned.
773 *
774 * @note The requested ``sample_pnt`` will not always be matched perfectly. The
775 * algorithm calculates the best possible match.
776 *
777 * @param dev Pointer to the device structure for the driver instance.
778 * @param[out] res Result is written into the @a can_timing struct provided.
779 * @param bitrate Target bitrate in bits/s.
780 * @param sample_pnt Sampling point in permill of the entire bit time.
781 *
782 * @retval 0 or positive sample point error on success.
783 * @retval -EINVAL if the requested bitrate or sample point is out of range.
784 * @retval -ENOTSUP if the requested bitrate is not supported.
785 * @retval -EIO if @a can_get_core_clock() is not available.
786 */
787 __syscall int can_calc_timing(const struct device *dev, struct can_timing *res,
788 uint32_t bitrate, uint16_t sample_pnt);
789
790 /**
791 * @brief Get the minimum supported timing parameter values for the data phase.
792 *
793 * Same as @a can_get_timing_min() but for the minimum values for the data phase.
794 *
795 * @note @kconfig{CONFIG_CAN_FD_MODE} must be selected for this function to be
796 * available.
797 *
798 * @param dev Pointer to the device structure for the driver instance.
799 *
800 * @return Pointer to the minimum supported timing parameter values, or NULL if
801 * CAN-FD support is not implemented by the driver.
802 */
803 __syscall const struct can_timing *can_get_timing_data_min(const struct device *dev);
804
805 #ifdef CONFIG_CAN_FD_MODE
z_impl_can_get_timing_data_min(const struct device * dev)806 static inline const struct can_timing *z_impl_can_get_timing_data_min(const struct device *dev)
807 {
808 const struct can_driver_api *api = (const struct can_driver_api *)dev->api;
809
810 return &api->timing_data_min;
811 }
812 #endif /* CONFIG_CAN_FD_MODE */
813
814 /**
815 * @brief Get the maximum supported timing parameter values for the data phase.
816 *
817 * Same as @a can_get_timing_max() but for the maximum values for the data phase.
818 *
819 * @note @kconfig{CONFIG_CAN_FD_MODE} must be selected for this function to be
820 * available.
821 *
822 * @param dev Pointer to the device structure for the driver instance.
823 *
824 * @return Pointer to the maximum supported timing parameter values, or NULL if
825 * CAN-FD support is not implemented by the driver.
826 */
827 __syscall const struct can_timing *can_get_timing_data_max(const struct device *dev);
828
829 #ifdef CONFIG_CAN_FD_MODE
z_impl_can_get_timing_data_max(const struct device * dev)830 static inline const struct can_timing *z_impl_can_get_timing_data_max(const struct device *dev)
831 {
832 const struct can_driver_api *api = (const struct can_driver_api *)dev->api;
833
834 return &api->timing_data_max;
835 }
836 #endif /* CONFIG_CAN_FD_MODE */
837
838 /**
839 * @brief Calculate timing parameters for the data phase
840 *
841 * Same as @a can_calc_timing() but with the maximum and minimum values from the
842 * data phase.
843 *
844 * @note @kconfig{CONFIG_CAN_FD_MODE} must be selected for this function to be
845 * available.
846 *
847 * @param dev Pointer to the device structure for the driver instance.
848 * @param[out] res Result is written into the @a can_timing struct provided.
849 * @param bitrate Target bitrate for the data phase in bits/s
850 * @param sample_pnt Sampling point for the data phase in permille of the entire bit time.
851 *
852 * @retval 0 or positive sample point error on success.
853 * @retval -EINVAL if the requested bitrate or sample point is out of range.
854 * @retval -ENOTSUP if the requested bitrate is not supported.
855 * @retval -EIO if @a can_get_core_clock() is not available.
856 */
857 __syscall int can_calc_timing_data(const struct device *dev, struct can_timing *res,
858 uint32_t bitrate, uint16_t sample_pnt);
859
860 /**
861 * @brief Configure the bus timing for the data phase of a CAN-FD controller.
862 *
863 * @note @kconfig{CONFIG_CAN_FD_MODE} must be selected for this function to be
864 * available.
865 *
866 * @see can_set_timing()
867 *
868 * @param dev Pointer to the device structure for the driver instance.
869 * @param timing_data Bus timings for data phase
870 *
871 * @retval 0 If successful.
872 * @retval -EBUSY if the CAN controller is not in stopped state.
873 * @retval -EIO General input/output error, failed to configure device.
874 * @retval -ENOTSUP if the timing parameters are not supported by the driver.
875 * @retval -ENOSYS if CAN-FD support is not implemented by the driver.
876 */
877 __syscall int can_set_timing_data(const struct device *dev,
878 const struct can_timing *timing_data);
879
880 /**
881 * @brief Set the bitrate for the data phase of the CAN-FD controller
882 *
883 * CAN in Automation (CiA) 301 v4.2.0 recommends a sample point location of
884 * 87.5% percent for all bitrates. However, some CAN controllers have
885 * difficulties meeting this for higher bitrates.
886 *
887 * This function defaults to using a sample point of 75.0% for bitrates over 800
888 * kbit/s, 80.0% for bitrates over 500 kbit/s, and 87.5% for all other
889 * bitrates. This is in line with the sample point locations used by the Linux
890 * kernel.
891 *
892 * @note @kconfig{CONFIG_CAN_FD_MODE} must be selected for this function to be
893 * available.
894 *
895 * @see can_set_bitrate()
896
897 * @param dev Pointer to the device structure for the driver instance.
898 * @param bitrate_data Desired data phase bitrate.
899 *
900 * @retval 0 If successful.
901 * @retval -EBUSY if the CAN controller is not in stopped state.
902 * @retval -EINVAL if the requested bitrate is out of range.
903 * @retval -ENOTSUP if the requested bitrate not supported by the CAN controller/transceiver
904 * combination.
905 * @retval -ERANGE if the resulting sample point is off by more than +/- 5%.
906 * @retval -EIO General input/output error, failed to set bitrate.
907 */
908 __syscall int can_set_bitrate_data(const struct device *dev, uint32_t bitrate_data);
909
910 /**
911 * @brief Fill in the prescaler value for a given bitrate and timing
912 *
913 * Fill the prescaler value in the timing struct. The sjw, prop_seg, phase_seg1
914 * and phase_seg2 must be given.
915 *
916 * The returned bitrate error is remainder of the division of the clock rate by
917 * the bitrate times the timing segments.
918 *
919 * @param dev Pointer to the device structure for the driver instance.
920 * @param timing Result is written into the can_timing struct provided.
921 * @param bitrate Target bitrate.
922 *
923 * @retval 0 or positive bitrate error.
924 * @retval Negative error code on error.
925 */
926 int can_calc_prescaler(const struct device *dev, struct can_timing *timing,
927 uint32_t bitrate);
928
929 /**
930 * @brief Configure the bus timing of a CAN controller.
931 *
932 * @see can_set_timing_data()
933 *
934 * @param dev Pointer to the device structure for the driver instance.
935 * @param timing Bus timings.
936 *
937 * @retval 0 If successful.
938 * @retval -EBUSY if the CAN controller is not in stopped state.
939 * @retval -ENOTSUP if the timing parameters are not supported by the driver.
940 * @retval -EIO General input/output error, failed to configure device.
941 */
942 __syscall int can_set_timing(const struct device *dev,
943 const struct can_timing *timing);
944
945 /**
946 * @brief Get the supported modes of the CAN controller
947 *
948 * The returned capabilities may not necessarily be supported at the same time (e.g. some CAN
949 * controllers support both ``CAN_MODE_LOOPBACK`` and ``CAN_MODE_LISTENONLY``, but not at the same
950 * time).
951 *
952 * @param dev Pointer to the device structure for the driver instance.
953 * @param[out] cap Supported capabilities.
954 *
955 * @retval 0 If successful.
956 * @retval -EIO General input/output error, failed to get capabilities.
957 */
958 __syscall int can_get_capabilities(const struct device *dev, can_mode_t *cap);
959
z_impl_can_get_capabilities(const struct device * dev,can_mode_t * cap)960 static inline int z_impl_can_get_capabilities(const struct device *dev, can_mode_t *cap)
961 {
962 const struct can_driver_api *api = (const struct can_driver_api *)dev->api;
963
964 return api->get_capabilities(dev, cap);
965 }
966
967 /**
968 * @brief Start the CAN controller
969 *
970 * Bring the CAN controller out of `CAN_STATE_STOPPED`. This will reset the RX/TX error counters,
971 * enable the CAN controller to participate in CAN communication, and enable the CAN tranceiver, if
972 * supported.
973 *
974 * @see can_stop()
975 * @see can_transceiver_enable()
976 *
977 * @param dev Pointer to the device structure for the driver instance.
978 * @retval 0 if successful.
979 * @retval -EALREADY if the device is already started.
980 * @retval -EIO General input/output error, failed to start device.
981 */
982 __syscall int can_start(const struct device *dev);
983
z_impl_can_start(const struct device * dev)984 static inline int z_impl_can_start(const struct device *dev)
985 {
986 const struct can_driver_api *api = (const struct can_driver_api *)dev->api;
987
988 return api->start(dev);
989 }
990
991 /**
992 * @brief Stop the CAN controller
993 *
994 * Bring the CAN controller into `CAN_STATE_STOPPED`. This will disallow the CAN controller from
995 * participating in CAN communication, abort any pending CAN frame transmissions, and disable the
996 * CAN transceiver, if supported.
997 *
998 * @see can_start()
999 * @see can_transceiver_disable()
1000 *
1001 * @param dev Pointer to the device structure for the driver instance.
1002 * @retval 0 if successful.
1003 * @retval -EALREADY if the device is already stopped.
1004 * @retval -EIO General input/output error, failed to stop device.
1005 */
1006 __syscall int can_stop(const struct device *dev);
1007
z_impl_can_stop(const struct device * dev)1008 static inline int z_impl_can_stop(const struct device *dev)
1009 {
1010 const struct can_driver_api *api = (const struct can_driver_api *)dev->api;
1011
1012 return api->stop(dev);
1013 }
1014
1015 /**
1016 * @brief Set the CAN controller to the given operation mode
1017 *
1018 * @param dev Pointer to the device structure for the driver instance.
1019 * @param mode Operation mode.
1020 *
1021 * @retval 0 If successful.
1022 * @retval -EBUSY if the CAN controller is not in stopped state.
1023 * @retval -EIO General input/output error, failed to configure device.
1024 */
1025 __syscall int can_set_mode(const struct device *dev, can_mode_t mode);
1026
z_impl_can_set_mode(const struct device * dev,can_mode_t mode)1027 static inline int z_impl_can_set_mode(const struct device *dev, can_mode_t mode)
1028 {
1029 const struct can_driver_api *api = (const struct can_driver_api *)dev->api;
1030
1031 return api->set_mode(dev, mode);
1032 }
1033
1034 /**
1035 * @brief Set the bitrate of the CAN controller
1036 *
1037 * CAN in Automation (CiA) 301 v4.2.0 recommends a sample point location of
1038 * 87.5% percent for all bitrates. However, some CAN controllers have
1039 * difficulties meeting this for higher bitrates.
1040 *
1041 * This function defaults to using a sample point of 75.0% for bitrates over 800
1042 * kbit/s, 80.0% for bitrates over 500 kbit/s, and 87.5% for all other
1043 * bitrates. This is in line with the sample point locations used by the Linux
1044 * kernel.
1045 *
1046 * @see can_set_bitrate_data()
1047 *
1048 * @param dev Pointer to the device structure for the driver instance.
1049 * @param bitrate Desired arbitration phase bitrate.
1050 *
1051 * @retval 0 If successful.
1052 * @retval -EBUSY if the CAN controller is not in stopped state.
1053 * @retval -EINVAL if the requested bitrate is out of range.
1054 * @retval -ENOTSUP if the requested bitrate not supported by the CAN controller/transceiver
1055 * combination.
1056 * @retval -ERANGE if the resulting sample point is off by more than +/- 5%.
1057 * @retval -EIO General input/output error, failed to set bitrate.
1058 */
1059 __syscall int can_set_bitrate(const struct device *dev, uint32_t bitrate);
1060
1061 /** @} */
1062
1063 /**
1064 * @name Transmitting CAN frames
1065 *
1066 * @{
1067 */
1068
1069 /**
1070 * @brief Queue a CAN frame for transmission on the CAN bus
1071 *
1072 * Queue a CAN frame for transmission on the CAN bus with optional timeout and
1073 * completion callback function.
1074 *
1075 * Queued CAN frames are transmitted in order according to the their priority:
1076 * - The lower the CAN-ID, the higher the priority.
1077 * - Data frames have higher priority than Remote Transmission Request (RTR)
1078 * frames with identical CAN-IDs.
1079 * - Frames with standard (11-bit) identifiers have higher priority than frames
1080 * with extended (29-bit) identifiers with identical base IDs (the higher 11
1081 * bits of the extended identifier).
1082 * - Transmission order for queued frames with the same priority is hardware
1083 * dependent.
1084 *
1085 * @note If transmitting segmented messages spanning multiple CAN frames with
1086 * identical CAN-IDs, the sender must ensure to only queue one frame at a time
1087 * if FIFO order is required.
1088 *
1089 * By default, the CAN controller will automatically retry transmission in case
1090 * of lost bus arbitration or missing acknowledge. Some CAN controllers support
1091 * disabling automatic retransmissions via ``CAN_MODE_ONE_SHOT``.
1092 *
1093 * @param dev Pointer to the device structure for the driver instance.
1094 * @param frame CAN frame to transmit.
1095 * @param timeout Timeout waiting for a empty TX mailbox or ``K_FOREVER``.
1096 * @param callback Optional callback for when the frame was sent or a
1097 * transmission error occurred. If ``NULL``, this function is
1098 * blocking until frame is sent. The callback must be ``NULL``
1099 * if called from user mode.
1100 * @param user_data User data to pass to callback function.
1101 *
1102 * @retval 0 if successful.
1103 * @retval -EINVAL if an invalid parameter was passed to the function.
1104 * @retval -ENOTSUP if an unsupported parameter was passed to the function.
1105 * @retval -ENETDOWN if the CAN controller is in stopped state.
1106 * @retval -ENETUNREACH if the CAN controller is in bus-off state.
1107 * @retval -EBUSY if CAN bus arbitration was lost (only applicable if automatic
1108 * retransmissions are disabled).
1109 * @retval -EIO if a general transmit error occurred (e.g. missing ACK if
1110 * automatic retransmissions are disabled).
1111 * @retval -EAGAIN on timeout.
1112 */
1113 __syscall int can_send(const struct device *dev, const struct can_frame *frame,
1114 k_timeout_t timeout, can_tx_callback_t callback,
1115 void *user_data);
1116
1117 /** @} */
1118
1119 /**
1120 * @name Receiving CAN frames
1121 *
1122 * @{
1123 */
1124
1125 /**
1126 * @brief Add a callback function for a given CAN filter
1127 *
1128 * Add a callback to CAN identifiers specified by a filter. When a received CAN
1129 * frame matching the filter is received by the CAN controller, the callback
1130 * function is called in interrupt context.
1131 *
1132 * If a received frame matches more than one filter (i.e., the filter IDs/masks or
1133 * flags overlap), the priority of the match is hardware dependent.
1134 *
1135 * The same callback function can be used for multiple filters.
1136 *
1137 * @param dev Pointer to the device structure for the driver instance.
1138 * @param callback This function is called by the CAN controller driver whenever
1139 * a frame matching the filter is received.
1140 * @param user_data User data to pass to callback function.
1141 * @param filter Pointer to a @a can_filter structure defining the filter.
1142 *
1143 * @retval filter_id on success.
1144 * @retval -ENOSPC if there are no free filters.
1145 * @retval -EINVAL if the requested filter type is invalid.
1146 * @retval -ENOTSUP if the requested filter type is not supported.
1147 */
can_add_rx_filter(const struct device * dev,can_rx_callback_t callback,void * user_data,const struct can_filter * filter)1148 static inline int can_add_rx_filter(const struct device *dev, can_rx_callback_t callback,
1149 void *user_data, const struct can_filter *filter)
1150 {
1151 const struct can_driver_api *api = (const struct can_driver_api *)dev->api;
1152
1153 if (filter == NULL || (filter->flags & (CAN_FILTER_DATA | CAN_FILTER_RTR)) == 0) {
1154 return -EINVAL;
1155 }
1156
1157 return api->add_rx_filter(dev, callback, user_data, filter);
1158 }
1159
1160 /**
1161 * @brief Statically define and initialize a CAN RX message queue.
1162 *
1163 * The message queue's ring buffer contains space for @a max_frames CAN frames.
1164 *
1165 * @see can_add_rx_filter_msgq()
1166 *
1167 * @param name Name of the message queue.
1168 * @param max_frames Maximum number of CAN frames that can be queued.
1169 */
1170 #define CAN_MSGQ_DEFINE(name, max_frames) \
1171 K_MSGQ_DEFINE(name, sizeof(struct can_frame), max_frames, 4)
1172
1173 /**
1174 * @brief Simple wrapper function for adding a message queue for a given filter
1175 *
1176 * Wrapper function for @a can_add_rx_filter() which puts received CAN frames
1177 * matching the filter in a message queue instead of calling a callback.
1178 *
1179 * If a received frame matches more than one filter (i.e., the filter IDs/masks or
1180 * flags overlap), the priority of the match is hardware dependent.
1181 *
1182 * The same message queue can be used for multiple filters.
1183 *
1184 * @note The message queue must be initialized before calling this function and
1185 * the caller must have appropriate permissions on it.
1186 *
1187 * @warning Message queue overruns are silently ignored and overrun frames
1188 * discarded. Custom error handling can be implemented by using
1189 * @a can_add_rx_filter() and @a k_msgq_put() directly.
1190 *
1191 * @param dev Pointer to the device structure for the driver instance.
1192 * @param msgq Pointer to the already initialized @a k_msgq struct.
1193 * @param filter Pointer to a @a can_filter structure defining the filter.
1194 *
1195 * @retval filter_id on success.
1196 * @retval -ENOSPC if there are no free filters.
1197 * @retval -ENOTSUP if the requested filter type is not supported.
1198 */
1199 __syscall int can_add_rx_filter_msgq(const struct device *dev, struct k_msgq *msgq,
1200 const struct can_filter *filter);
1201
1202 /**
1203 * @brief Remove a CAN RX filter
1204 *
1205 * This routine removes a CAN RX filter based on the filter ID returned by @a
1206 * can_add_rx_filter() or @a can_add_rx_filter_msgq().
1207 *
1208 * @param dev Pointer to the device structure for the driver instance.
1209 * @param filter_id Filter ID
1210 */
1211 __syscall void can_remove_rx_filter(const struct device *dev, int filter_id);
1212
z_impl_can_remove_rx_filter(const struct device * dev,int filter_id)1213 static inline void z_impl_can_remove_rx_filter(const struct device *dev, int filter_id)
1214 {
1215 const struct can_driver_api *api = (const struct can_driver_api *)dev->api;
1216
1217 return api->remove_rx_filter(dev, filter_id);
1218 }
1219
1220 /**
1221 * @brief Get maximum number of RX filters
1222 *
1223 * Get the maximum number of concurrent RX filters for the CAN controller.
1224 *
1225 * @param dev Pointer to the device structure for the driver instance.
1226 * @param ide Get the maximum standard (11-bit) CAN ID filters if false, or extended (29-bit) CAN ID
1227 * filters if true.
1228 *
1229 * @retval Positive number of maximum concurrent filters.
1230 * @retval -EIO General input/output error.
1231 * @retval -ENOSYS If this function is not implemented by the driver.
1232 */
1233 __syscall int can_get_max_filters(const struct device *dev, bool ide);
1234
z_impl_can_get_max_filters(const struct device * dev,bool ide)1235 static inline int z_impl_can_get_max_filters(const struct device *dev, bool ide)
1236 {
1237 const struct can_driver_api *api = (const struct can_driver_api *)dev->api;
1238
1239 if (api->get_max_filters == NULL) {
1240 return -ENOSYS;
1241 }
1242
1243 return api->get_max_filters(dev, ide);
1244 }
1245
1246 /** @} */
1247
1248 /**
1249 * @name CAN bus error reporting and handling
1250 *
1251 * @{
1252 */
1253
1254 /**
1255 * @brief Get current CAN controller state
1256 *
1257 * Returns the current state and optionally the error counter values of the CAN
1258 * controller.
1259 *
1260 * @param dev Pointer to the device structure for the driver instance.
1261 * @param[out] state Pointer to the state destination enum or NULL.
1262 * @param[out] err_cnt Pointer to the err_cnt destination structure or NULL.
1263 *
1264 * @retval 0 If successful.
1265 * @retval -EIO General input/output error, failed to get state.
1266 */
1267 __syscall int can_get_state(const struct device *dev, enum can_state *state,
1268 struct can_bus_err_cnt *err_cnt);
1269
z_impl_can_get_state(const struct device * dev,enum can_state * state,struct can_bus_err_cnt * err_cnt)1270 static inline int z_impl_can_get_state(const struct device *dev, enum can_state *state,
1271 struct can_bus_err_cnt *err_cnt)
1272 {
1273 const struct can_driver_api *api = (const struct can_driver_api *)dev->api;
1274
1275 return api->get_state(dev, state, err_cnt);
1276 }
1277
1278 /**
1279 * @brief Recover from bus-off state
1280 *
1281 * Recover the CAN controller from bus-off state to error-active state.
1282 *
1283 * @note @kconfig{CONFIG_CAN_AUTO_BUS_OFF_RECOVERY} must be deselected for this
1284 * function to be available.
1285 *
1286 * @param dev Pointer to the device structure for the driver instance.
1287 * @param timeout Timeout for waiting for the recovery or ``K_FOREVER``.
1288 *
1289 * @retval 0 on success.
1290 * @retval -ENETDOWN if the CAN controller is in stopped state.
1291 * @retval -EAGAIN on timeout.
1292 */
1293 #if !defined(CONFIG_CAN_AUTO_BUS_OFF_RECOVERY) || defined(__DOXYGEN__)
1294 __syscall int can_recover(const struct device *dev, k_timeout_t timeout);
1295
z_impl_can_recover(const struct device * dev,k_timeout_t timeout)1296 static inline int z_impl_can_recover(const struct device *dev, k_timeout_t timeout)
1297 {
1298 const struct can_driver_api *api = (const struct can_driver_api *)dev->api;
1299
1300 return api->recover(dev, timeout);
1301 }
1302 #else /* CONFIG_CAN_AUTO_BUS_OFF_RECOVERY */
1303 /* This implementation prevents inking errors for auto recovery */
z_impl_can_recover(const struct device * dev,k_timeout_t timeout)1304 static inline int z_impl_can_recover(const struct device *dev, k_timeout_t timeout)
1305 {
1306 ARG_UNUSED(dev);
1307 ARG_UNUSED(timeout);
1308 return 0;
1309 }
1310 #endif /* !CONFIG_CAN_AUTO_BUS_OFF_RECOVERY */
1311
1312 /**
1313 * @brief Set a callback for CAN controller state change events
1314 *
1315 * Set the callback for CAN controller state change events. The callback
1316 * function will be called in interrupt context.
1317 *
1318 * Only one callback can be registered per controller. Calling this function
1319 * again overrides any previously registered callback.
1320 *
1321 * @param dev Pointer to the device structure for the driver instance.
1322 * @param callback Callback function.
1323 * @param user_data User data to pass to callback function.
1324 */
can_set_state_change_callback(const struct device * dev,can_state_change_callback_t callback,void * user_data)1325 static inline void can_set_state_change_callback(const struct device *dev,
1326 can_state_change_callback_t callback,
1327 void *user_data)
1328 {
1329 const struct can_driver_api *api = (const struct can_driver_api *)dev->api;
1330
1331 api->set_state_change_callback(dev, callback, user_data);
1332 }
1333
1334 /** @} */
1335
1336 /**
1337 * @name CAN utility functions
1338 *
1339 * @{
1340 */
1341
1342 /**
1343 * @brief Convert from Data Length Code (DLC) to the number of data bytes
1344 *
1345 * @param dlc Data Length Code (DLC).
1346 *
1347 * @retval Number of bytes.
1348 */
can_dlc_to_bytes(uint8_t dlc)1349 static inline uint8_t can_dlc_to_bytes(uint8_t dlc)
1350 {
1351 static const uint8_t dlc_table[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 12,
1352 16, 20, 24, 32, 48, 64};
1353
1354 return dlc_table[MIN(dlc, ARRAY_SIZE(dlc_table) - 1)];
1355 }
1356
1357 /**
1358 * @brief Convert from number of bytes to Data Length Code (DLC)
1359 *
1360 * @param num_bytes Number of bytes.
1361 *
1362 * @retval Data Length Code (DLC).
1363 */
can_bytes_to_dlc(uint8_t num_bytes)1364 static inline uint8_t can_bytes_to_dlc(uint8_t num_bytes)
1365 {
1366 return num_bytes <= 8 ? num_bytes :
1367 num_bytes <= 12 ? 9 :
1368 num_bytes <= 16 ? 10 :
1369 num_bytes <= 20 ? 11 :
1370 num_bytes <= 24 ? 12 :
1371 num_bytes <= 32 ? 13 :
1372 num_bytes <= 48 ? 14 :
1373 15;
1374 }
1375
1376 /**
1377 * @brief Check if a CAN frame matches a CAN filter
1378 *
1379 * @param frame CAN frame.
1380 * @param filter CAN filter.
1381 * @return true if the CAN frame matches the CAN filter, false otherwise
1382 */
can_frame_matches_filter(const struct can_frame * frame,const struct can_filter * filter)1383 static inline bool can_frame_matches_filter(const struct can_frame *frame,
1384 const struct can_filter *filter)
1385 {
1386 if ((frame->flags & CAN_FRAME_IDE) != 0 && (filter->flags & CAN_FILTER_IDE) == 0) {
1387 /* Extended (29-bit) ID frame, standard (11-bit) filter */
1388 return false;
1389 }
1390
1391 if ((frame->flags & CAN_FRAME_IDE) == 0 && (filter->flags & CAN_FILTER_IDE) != 0) {
1392 /* Standard (11-bit) ID frame, extended (29-bit) filter */
1393 return false;
1394 }
1395
1396 if ((frame->flags & CAN_FRAME_RTR) == 0 && (filter->flags & CAN_FILTER_DATA) == 0) {
1397 /* non-RTR frame, remote transmission request (RTR) filter */
1398 return false;
1399 }
1400
1401 if ((frame->flags & CAN_FRAME_RTR) != 0 && (filter->flags & CAN_FILTER_RTR) == 0) {
1402 /* Remote transmission request (RTR) frame, non-RTR filter */
1403 return false;
1404 }
1405
1406 if ((frame->flags & CAN_FRAME_FDF) != 0 && (filter->flags & CAN_FILTER_FDF) == 0) {
1407 /* CAN-FD format frame, classic format filter */
1408 return false;
1409 }
1410
1411 if ((frame->flags & CAN_FRAME_FDF) == 0 && (filter->flags & CAN_FILTER_FDF) != 0) {
1412 /* Classic frame, CAN-FD format filter */
1413 return false;
1414 }
1415
1416 if ((frame->id ^ filter->id) & filter->mask) {
1417 /* Masked ID mismatch */
1418 return false;
1419 }
1420
1421 return true;
1422 }
1423
1424 /** @} */
1425
1426 /**
1427 * @}
1428 */
1429
1430 #ifdef __cplusplus
1431 }
1432 #endif
1433
1434 #include <syscalls/can.h>
1435
1436 #endif /* ZEPHYR_INCLUDE_DRIVERS_CAN_H_ */
1437