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