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