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