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