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