1 /**
2  * @file
3  *
4  * @brief Public APIs for the CAN drivers.
5  */
6 
7 /*
8  * Copyright (c) 2018 Alexander Wachter
9  *
10  * SPDX-License-Identifier: Apache-2.0
11  */
12 
13 #ifndef ZEPHYR_INCLUDE_DRIVERS_CAN_H_
14 #define ZEPHYR_INCLUDE_DRIVERS_CAN_H_
15 
16 /**
17  * @brief CAN Interface
18  * @defgroup can_interface CAN Interface
19  * @ingroup io_interfaces
20  * @{
21  */
22 
23 #include <zephyr/types.h>
24 #include <device.h>
25 #include <string.h>
26 #include <sys/util.h>
27 
28 #ifdef __cplusplus
29 extern "C" {
30 #endif
31 
32 #define CAN_EX_ID      (1 << 31)
33 #define CAN_MAX_STD_ID (0x7FF)
34 #define CAN_STD_ID_MASK CAN_MAX_STD_ID
35 #define CAN_EXT_ID_MASK (0x1FFFFFFF)
36 #define CAN_MAX_DLC    (8)
37 #define CANFD_MAX_DLC  CONFIG_CANFD_MAX_DLC
38 #ifndef CONFIG_CANFD_MAX_DLC
39 #define CAN_MAX_DLEN    8
40 #else
41 #if CONFIG_CANFD_MAX_DLC <= 8
42 #define CAN_MAX_DLEN    CONFIG_CANFD_MAX_DLC
43 #elif CONFIG_CANFD_MAX_DLC <= 12
44 #define CAN_MAX_DLEN    CONFIG_CANFD_MAX_DLC + (CONFIG_CANFD_MAX_DLC - 8) * 4
45 #elif CONFIG_CANFD_MAX_DLC == 13
46 #define CAN_MAX_DLEN 32
47 #elif CONFIG_CANFD_MAX_DLC == 14
48 #define CAN_MAX_DLEN 48
49 #elif CONFIG_CANFD_MAX_DLC == 15
50 #define CAN_MAX_DLEN 64
51 #endif
52 #endif /* CONFIG_CANFD_MAX_DLC */
53 
54 /* CAN_TX_* are the error flags from tx_callback and send.*/
55 /** send successfully */
56 #define CAN_TX_OK       (0)
57 /** general send error */
58 #define CAN_TX_ERR      (-2)
59 /** bus arbitration lost during sending */
60 #define CAN_TX_ARB_LOST (-3)
61 /** controller is in bus off state */
62 #define CAN_TX_BUS_OFF  (-4)
63 /** unexpected error */
64 #define CAN_TX_UNKNOWN  (-5)
65 
66 /** invalid parameter */
67 #define CAN_TX_EINVAL   (-22)
68 
69 /** attach_* failed because there is no unused filter left*/
70 #define CAN_NO_FREE_FILTER (-1)
71 
72 /** operation timed out*/
73 #define CAN_TIMEOUT (-1)
74 
75 /**
76  * @brief Statically define and initialize a can message queue.
77  *
78  * The message queue's ring buffer contains space for @a size messages.
79  *
80  * @param name Name of the message queue.
81  * @param size Number of can messages.
82  */
83 #define CAN_DEFINE_MSGQ(name, size) \
84 	K_MSGQ_DEFINE(name, sizeof(struct zcan_frame), size, 4)
85 
86 /**
87  * @brief can_ide enum
88  * Define if the message has a standard (11bit) or extended (29bit)
89  * identifier
90  */
91 enum can_ide {
92 	CAN_STANDARD_IDENTIFIER,
93 	CAN_EXTENDED_IDENTIFIER
94 };
95 
96 /**
97  * @brief can_rtr enum
98  * Define if the message is a data or remote frame
99  */
100 enum can_rtr {
101 	CAN_DATAFRAME,
102 	CAN_REMOTEREQUEST
103 };
104 
105 /**
106  * @brief can_mode enum
107  * Defines the mode of the can controller
108  */
109 enum can_mode {
110 	/*Normal mode*/
111 	CAN_NORMAL_MODE,
112 	/*Controller is not allowed to send dominant bits*/
113 	CAN_SILENT_MODE,
114 	/*Controller is in loopback mode (receive own messages)*/
115 	CAN_LOOPBACK_MODE,
116 	/*Combination of loopback and silent*/
117 	CAN_SILENT_LOOPBACK_MODE
118 };
119 
120 /**
121  * @brief can_state enum
122  * Defines the possible states of the CAN bus
123  */
124 enum can_state {
125 	CAN_ERROR_ACTIVE,
126 	CAN_ERROR_PASSIVE,
127 	CAN_BUS_OFF,
128 	CAN_BUS_UNKNOWN
129 };
130 
131 /*
132  * Controller Area Network Identifier structure for Linux compatibility.
133  *
134  * The fields in this type are:
135  *
136  * bit 0-28	: CAN identifier (11/29 bit)
137  * bit 29	: error message frame flag (0 = data frame, 1 = error message)
138  * bit 30	: remote transmission request flag (1 = rtr frame)
139  * bit 31	: frame format flag (0 = standard 11 bit, 1 = extended 29 bit)
140  */
141 typedef uint32_t canid_t;
142 
143 /**
144  * @brief CAN frame structure that is compatible with Linux. This is mainly
145  * used by Socket CAN code.
146  *
147  * @details Used to pass CAN messages from userspace to the socket CAN and vice
148  * versa.
149  */
150 struct can_frame {
151 	/** 32 bit CAN_ID + EFF/RTR/ERR flags */
152 	canid_t can_id;
153 
154 	/** The length of the message */
155 	uint8_t can_dlc;
156 
157 	/** @cond INTERNAL_HIDDEN */
158 	uint8_t pad;   /* padding */
159 	uint8_t res0;  /* reserved / padding */
160 	uint8_t res1;  /* reserved / padding */
161 	/** @endcond */
162 
163 	/** The message data */
164 	uint8_t data[CAN_MAX_DLEN];
165 };
166 
167 /**
168  * @brief CAN filter that is compatible with Linux. This is mainly used by
169  * Socket CAN code.
170  *
171  * @details A filter matches, when "received_can_id & mask == can_id & mask"
172  */
173 struct can_filter {
174 	canid_t can_id;
175 	canid_t can_mask;
176 };
177 
178 /**
179  * @brief CAN message structure
180  *
181  * Used to pass can messages from userspace to the driver and
182  * from driver to userspace
183  *
184  */
185 struct zcan_frame {
186 	/** Message identifier*/
187 	uint32_t id      : 29;
188 	/** Frame is in the CAN-FD frame format */
189 	uint32_t fd      : 1;
190 	/** Set the message to a transmission request instead of data frame
191 	 * use can_rtr enum for assignment
192 	 */
193 	uint32_t rtr     : 1;
194 	/** Indicates the identifier type (standard or extended)
195 	 * use can_ide enum for assignment
196 	 */
197 	uint32_t id_type : 1;
198 	/** The length of the message (max. 8) in byte */
199 	uint8_t dlc;
200 	/** Baud Rate Switch. Frame transfer with different timing during
201 	 * the data phase. Only valid for CAN-FD
202 	 */
203 	uint8_t brs : 1;
204 	/** Reserved for future flags */
205 	uint8_t res : 7;
206 #if defined(CONFIG_CAN_RX_TIMESTAMP)
207 	/** Timer value of the CAN free-running timer.
208 	 * The timer is incremented every bit time and captured at the start
209 	 * of frame bit (SOF).
210 	 */
211 	uint16_t timestamp;
212 #else
213 	/** @cond INTERNAL_HIDDEN */
214 	uint8_t res0;  /* reserved / padding */
215 	uint8_t res1;  /* reserved / padding */
216 	/** @endcond */
217 #endif
218 	/** The frame payload data. */
219 	union {
220 		uint8_t data[CAN_MAX_DLEN];
221 		uint32_t data_32[ceiling_fraction(CAN_MAX_DLEN, sizeof(uint32_t))];
222 	};
223 };
224 
225 /**
226  * @brief CAN filter structure
227  *
228  * Used to pass can identifier filter information to the driver.
229  * rtr_mask and *_id_mask are used to mask bits of the rtr and id fields.
230  * If the mask bit is 0, the value of the corresponding bit in the id or rtr
231  * field don't care for the filter matching.
232  *
233  */
234 struct zcan_filter {
235 	/** target state of the identifier */
236 	uint32_t id           : 29;
237 	uint32_t res0         : 1;
238 	/** target state of the rtr bit */
239 	uint32_t rtr          : 1;
240 	/** Indicates the identifier type (standard or extended)
241 	 * use can_ide enum for assignment
242 	 */
243 	uint32_t id_type      : 1;
244 	/** identifier mask*/
245 	uint32_t id_mask  : 29;
246 	uint32_t res1         : 1;
247 	/** rtr bit mask */
248 	uint32_t rtr_mask     : 1;
249 	uint32_t res2         : 1;
250 };
251 
252 /**
253  * @brief can bus error count structure
254  *
255  * Used to pass the bus error counters to userspace
256  */
257 struct can_bus_err_cnt {
258 	uint8_t tx_err_cnt;
259 	uint8_t rx_err_cnt;
260 };
261 
262 /** SWJ value to indicate that the SJW should not be changed */
263 #define CAN_SJW_NO_CHANGE 0
264 
265 /**
266  * @brief canbus timings
267  *
268  * Used to pass bus timing values to the config and bitrate calculator function.
269  *
270  * The propagation segment represents the time of the signal propagation.
271  * Phase segment 1 and phase segment 2 define the sampling point.
272  * prop_seg and phase_seg1 affect the sampling-point in the same way and some
273  * controllers only have a register for the sum of those two. The sync segment
274  * always has a length of 1 tq
275  * +---------+----------+------------+------------+
276  * |sync_seg | prop_seg | phase_seg1 | phase_seg2 |
277  * +---------+----------+------------+------------+
278  *                                   ^
279  *                             Sampling-Point
280  * 1 tq (time quantum) has the length of 1/(core_clock / prescaler)
281  * The bitrate is defined by the core clock divided by the prescaler and the
282  * sum of the segments.
283  * br = (core_clock / prescaler) / (1 + prop_seg + phase_seg1 + phase_seg2)
284  * The resynchronization jump width (SJW) defines the amount of time quantum
285  * the sample point can be moved.
286  * The sample point is moved when resynchronization is needed.
287  */
288 struct can_timing {
289 	/** Synchronisation jump width*/
290 	uint16_t sjw;
291 	/** Propagation Segment */
292 	uint16_t prop_seg;
293 	/** Phase Segment 1 */
294 	uint16_t phase_seg1;
295 	/** Phase Segment 2 */
296 	uint16_t phase_seg2;
297 	/** Prescaler value */
298 	uint16_t prescaler;
299 };
300 
301 /**
302  * @typedef can_tx_callback_t
303  * @brief Define the application callback handler function signature
304  *
305  * @param error status of the performed send operation
306  * @param arg argument that was passed when the message was sent
307  */
308 typedef void (*can_tx_callback_t)(int error, void *arg);
309 
310 /**
311  * @typedef can_rx_callback_t
312  * @brief Define the application callback handler function signature
313  *        for receiving.
314  *
315  * @param msg received message
316  * @param arg argument that was passed when the filter was attached
317  */
318 typedef void (*can_rx_callback_t)(struct zcan_frame *msg, void *arg);
319 
320 /**
321  * @typedef can_state_change_isr_t
322  * @brief Defines the state change isr handler function signature
323  *
324  * @param state state of the node
325  * @param err_cnt struct with the error counter values
326  */
327 typedef void(*can_state_change_isr_t)(enum can_state state,
328 					  struct can_bus_err_cnt err_cnt);
329 
330 typedef int (*can_set_timing_t)(const struct device *dev,
331 				const struct can_timing *timing,
332 				const struct can_timing *timing_data);
333 
334 typedef int (*can_set_mode_t)(const struct device *dev, enum can_mode mode);
335 
336 typedef int (*can_send_t)(const struct device *dev,
337 			  const struct zcan_frame *msg,
338 			  k_timeout_t timeout, can_tx_callback_t callback_isr,
339 			  void *callback_arg);
340 
341 
342 typedef int (*can_attach_msgq_t)(const struct device *dev,
343 				 struct k_msgq *msg_q,
344 				 const struct zcan_filter *filter);
345 
346 typedef int (*can_attach_isr_t)(const struct device *dev,
347 				can_rx_callback_t isr,
348 				void *callback_arg,
349 				const struct zcan_filter *filter);
350 
351 typedef void (*can_detach_t)(const struct device *dev, int filter_id);
352 
353 typedef int (*can_recover_t)(const struct device *dev, k_timeout_t timeout);
354 
355 typedef enum can_state (*can_get_state_t)(const struct device *dev,
356 					  struct can_bus_err_cnt *err_cnt);
357 
358 typedef void(*can_register_state_change_isr_t)(const struct device *dev,
359 					       can_state_change_isr_t isr);
360 
361 typedef int (*can_get_core_clock_t)(const struct device *dev, uint32_t *rate);
362 
363 #ifndef CONFIG_CAN_WORKQ_FRAMES_BUF_CNT
364 #define CONFIG_CAN_WORKQ_FRAMES_BUF_CNT 4
365 #endif
366 struct can_frame_buffer {
367 	struct zcan_frame buf[CONFIG_CAN_WORKQ_FRAMES_BUF_CNT];
368 	uint16_t head;
369 	uint16_t tail;
370 };
371 
372 /**
373  * @brief CAN work structure
374  *
375  * Used to attach a work queue to a filter.
376  */
377 struct zcan_work {
378 	struct k_work work_item;
379 	struct k_work_q *work_queue;
380 	struct can_frame_buffer buf;
381 	can_rx_callback_t cb;
382 	void *cb_arg;
383 };
384 
385 __subsystem struct can_driver_api {
386 	can_set_mode_t set_mode;
387 	can_set_timing_t set_timing;
388 	can_send_t send;
389 	can_attach_isr_t attach_isr;
390 	can_detach_t detach;
391 #ifndef CONFIG_CAN_AUTO_BUS_OFF_RECOVERY
392 	can_recover_t recover;
393 #endif
394 	can_get_state_t get_state;
395 	can_register_state_change_isr_t register_state_change_isr;
396 	can_get_core_clock_t get_core_clock;
397 	/* Min values for the timing registers */
398 	struct can_timing timing_min;
399 	/* Max values for the timing registers */
400 	struct can_timing timing_max;
401 #ifdef CONFIG_CAN_FD_MODE
402 	/* Min values for the timing registers during the data phase */
403 	struct can_timing timing_min_data;
404 	/* Max values for the timing registers during the data phase */
405 	struct can_timing timing_max_data;
406 #endif
407 };
408 
409 /**
410  * @brief Convert the DLC to the number of bytes
411  *
412  * This function converts a the Data Length Code to the number of bytes.
413  *
414  * @param dlc The Data Length Code
415  *
416  * @retval Number of bytes
417  */
can_dlc_to_bytes(uint8_t dlc)418 static inline uint8_t can_dlc_to_bytes(uint8_t dlc)
419 {
420 	static const uint8_t dlc_table[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 12,
421 					 16, 20, 24, 32, 48, 64};
422 
423 	return dlc_table[MIN(dlc, ARRAY_SIZE(dlc_table) - 1)];
424 }
425 
426 /**
427  * @brief Convert a number of bytes to the DLC
428  *
429  * This function converts a number of bytes to the Data Length Code
430  *
431  * @param num_bytes The number of bytes
432  *
433  * @retval The DLC
434  */
435 
can_bytes_to_dlc(uint8_t num_bytes)436 static inline uint8_t can_bytes_to_dlc(uint8_t num_bytes)
437 {
438 	return num_bytes <= 8  ? num_bytes :
439 	       num_bytes <= 12 ? 9 :
440 	       num_bytes <= 16 ? 10 :
441 	       num_bytes <= 20 ? 11 :
442 	       num_bytes <= 24 ? 12 :
443 	       num_bytes <= 32 ? 13 :
444 	       num_bytes <= 48 ? 14 :
445 	       15;
446 }
447 
448 /**
449  * @brief Perform data transfer to CAN bus.
450  *
451  * This routine provides a generic interface to perform data transfer
452  * to the can bus. Use can_write() for simple write.
453  * *
454  * @param dev          Pointer to the device structure for the driver instance.
455  * @param msg          Message to transfer.
456  * @param timeout      Waiting for empty tx mailbox timeout or K_FOREVER.
457  * @param callback_isr Is called when message was sent or a transmission error
458  *                     occurred. If NULL, this function is blocking until
459  *                     message is sent. This must be NULL if called from user
460  *                     mode.
461  * @param callback_arg This will be passed whenever the isr is called.
462  *
463  * @retval 0 If successful.
464  * @retval CAN_TX_* on failure.
465  */
466 __syscall int can_send(const struct device *dev, const struct zcan_frame *msg,
467 		       k_timeout_t timeout, can_tx_callback_t callback_isr,
468 		       void *callback_arg);
469 
z_impl_can_send(const struct device * dev,const struct zcan_frame * msg,k_timeout_t timeout,can_tx_callback_t callback_isr,void * callback_arg)470 static inline int z_impl_can_send(const struct device *dev,
471 				  const struct zcan_frame *msg,
472 				  k_timeout_t timeout,
473 				  can_tx_callback_t callback_isr,
474 				  void *callback_arg)
475 {
476 	const struct can_driver_api *api =
477 		(const struct can_driver_api *)dev->api;
478 
479 	return api->send(dev, msg, timeout, callback_isr, callback_arg);
480 }
481 
482 /*
483  * Derived can APIs -- all implemented in terms of can_send()
484  */
485 
486 /**
487  * @brief Write a set amount of data to the can bus.
488  *
489  * This routine writes a set amount of data synchronously.
490  *
491  * @param dev  Pointer to the device structure for the driver instance.
492  * @param data Data to send.
493  * @param length Number of bytes to write (max. 8).
494  * @param id  Identifier of the can message.
495  * @param rtr Send remote transmission request or data frame
496  * @param timeout Waiting for empty tx mailbox timeout or K_FOREVER
497  *
498  * @retval 0 If successful.
499  * @retval -EIO General input / output error.
500  * @retval -EINVAL if length > 8.
501  */
can_write(const struct device * dev,const uint8_t * data,uint8_t length,uint32_t id,enum can_rtr rtr,k_timeout_t timeout)502 static inline int can_write(const struct device *dev, const uint8_t *data,
503 			    uint8_t length,
504 			    uint32_t id, enum can_rtr rtr, k_timeout_t timeout)
505 {
506 	struct zcan_frame msg;
507 
508 	if (length > 8) {
509 		return -EINVAL;
510 	}
511 
512 	msg.id = id;
513 
514 	if (id > CAN_MAX_STD_ID) {
515 		msg.id_type = CAN_EXTENDED_IDENTIFIER;
516 	} else {
517 		msg.id_type = CAN_STANDARD_IDENTIFIER;
518 	}
519 
520 	msg.dlc = length;
521 	msg.rtr = rtr;
522 	memcpy(msg.data, data, length);
523 
524 	return can_send(dev, &msg, timeout, NULL, NULL);
525 }
526 
527 /**
528  * @brief Attach a CAN work queue to a single or group of identifiers.
529  *
530  * This routine attaches a work queue to identifiers specified by a filter.
531  * Whenever the filter matches, the message is pushed to the buffer
532  * of the zcan_work structure and the work element is put to the workqueue.
533  * If a message passes more than one filter the priority of the match
534  * is hardware dependent.
535  * A CAN work queue can be attached to more than one filter.
536  * The work queue must be initialized before and the caller must have
537  * appropriate permissions on it.
538  *
539  * @param dev          Pointer to the device structure for the driver instance.
540  * @param work_q       Pointer to the already initialized work queue.
541  * @param work         Pointer to a zcan_work. The work will be initialized.
542  * @param callback     This function is called by workq whenever a message arrives.
543  * @param callback_arg Is passed to the callback when called.
544  * @param filter       Pointer to a zcan_filter structure defining the id
545  *                     filtering.
546  *
547  * @retval filter_id on success.
548  * @retval CAN_NO_FREE_FILTER if there is no filter left.
549  */
550 int can_attach_workq(const struct device *dev, struct k_work_q  *work_q,
551 		     struct zcan_work *work,
552 		     can_rx_callback_t callback, void *callback_arg,
553 		     const struct zcan_filter *filter);
554 
555 /**
556  * @brief Attach a message queue to a single or group of identifiers.
557  *
558  * This routine attaches a message queue to identifiers specified by
559  * a filter. Whenever the filter matches, the message is pushed to the queue
560  * If a message passes more than one filter the priority of the match
561  * is hardware dependent.
562  * A message queue can be attached to more than one filter.
563  * The message queue must me initialized before, and the caller must have
564  * appropriate permissions on it.
565  *
566  * @param dev    Pointer to the device structure for the driver instance.
567  * @param msg_q  Pointer to the already initialized message queue.
568  * @param filter Pointer to a zcan_filter structure defining the id
569  *               filtering.
570  *
571  * @retval filter_id on success.
572  * @retval CAN_NO_FREE_FILTER if there is no filter left.
573  */
574 __syscall int can_attach_msgq(const struct device *dev, struct k_msgq *msg_q,
575 			      const struct zcan_filter *filter);
576 
577 /**
578  * @brief Attach an isr callback function to a single or group of identifiers.
579  *
580  * This routine attaches an isr callback to identifiers specified by
581  * a filter. Whenever the filter matches, the callback function is called
582  * with isr context.
583  * If a message passes more than one filter the priority of the match
584  * is hardware dependent.
585  * A callback function can be attached to more than one filter.
586  * *
587  * @param dev          Pointer to the device structure for the driver instance.
588  * @param isr          Callback function pointer.
589  * @param callback_arg This will be passed whenever the isr is called.
590  * @param filter       Pointer to a zcan_filter structure defining the id
591  *                     filtering.
592  *
593  * @retval filter_id on success.
594  * @retval CAN_NO_FREE_FILTER if there is no filter left.
595  */
can_attach_isr(const struct device * dev,can_rx_callback_t isr,void * callback_arg,const struct zcan_filter * filter)596 static inline int can_attach_isr(const struct device *dev,
597 				       can_rx_callback_t isr,
598 				       void *callback_arg,
599 				       const struct zcan_filter *filter)
600 {
601 	const struct can_driver_api *api =
602 		(const struct can_driver_api *)dev->api;
603 
604 	return api->attach_isr(dev, isr, callback_arg, filter);
605 }
606 
607 /**
608  * @brief Detach an isr or message queue from the identifier filtering.
609  *
610  * This routine detaches an isr callback  or message queue from the identifier
611  * filtering.
612  * *
613  * @param dev       Pointer to the device structure for the driver instance.
614  * @param filter_id filter id returned by can_attach_isr or can_attach_msgq.
615  *
616  * @retval none
617  */
618 __syscall void can_detach(const struct device *dev, int filter_id);
619 
z_impl_can_detach(const struct device * dev,int filter_id)620 static inline void z_impl_can_detach(const struct device *dev, int filter_id)
621 {
622 	const struct can_driver_api *api =
623 		(const struct can_driver_api *)dev->api;
624 
625 	return api->detach(dev, filter_id);
626 }
627 
628 /**
629  * @brief Read the core clock value
630  *
631  * Returns the core clock value. One time quantum is 1/core clock.
632  *
633  * @param dev Pointer to the device structure for the driver instance.
634  * @param[out] rate controller clock rate
635  *
636  * @retval 0 on success
637  * @retval negative on error
638  */
639 __syscall int can_get_core_clock(const struct device *dev, uint32_t *rate);
640 
z_impl_can_get_core_clock(const struct device * dev,uint32_t * rate)641 static inline int z_impl_can_get_core_clock(const struct device *dev,
642 					    uint32_t *rate)
643 {
644 	const struct can_driver_api *api =
645 		(const struct can_driver_api *)dev->api;
646 
647 	return api->get_core_clock(dev, rate);
648 }
649 
650 /**
651  * @brief Calculate timing parameters from bitrate and sample point
652  *
653  * Calculate the timing parameters from a given bitrate in bits/s and the
654  * sampling point in permill (1/1000) of the entire bit time.
655  * The bitrate must alway match perfectly. If no result can be given for the,
656  * give parameters, -EINVAL is returned.
657  * The sample_pnt does not always match perfectly. The algorithm tries to find
658  * the best match possible.
659  *
660  * @param dev        Pointer to the device structure for the driver instance.
661  * @param res        Result is written into the can_timing struct provided.
662  * @param bitrate    Target bitrate in bits/s
663  * @param sample_pnt Sampling point in permill of the entire bit time.
664  *
665  * @retval Positive sample point error on success
666  * @retval -EINVAL if there is no solution for the desired values
667  * @retval -EIO if core_clock is not available
668  */
669 int can_calc_timing(const struct device *dev, struct can_timing *res,
670 		    uint32_t bitrate, uint16_t sample_pnt);
671 
672 #ifdef CONFIG_CAN_FD_MODE
673 /**
674  * @brief Calculate timing parameters for the data phase
675  *
676  * Same as can_calc_timing but with the max and min values from the data phase.
677  *
678  * @param dev        Pointer to the device structure for the driver instance.
679  * @param res        Result is written into the can_timing struct provided.
680  * @param bitrate    Target bitrate for the data phase in bits/s
681  * @param sample_pnt Sampling point data phase in permille of the entire bit time.
682  *
683  * @retval Positive sample point error on success
684  * @retval -EINVAL if there is no solution for the desired values
685  * @retval -EIO if core_clock is not available
686  */
687 int can_calc_timing_data(const struct device *dev, struct can_timing *res,
688 			 uint32_t bitrate, uint16_t sample_pnt);
689 #endif
690 
691 /**
692  * @brief Fill in the prescaler value for a given bitrate and timing
693  *
694  * Fill the prescaler value in the timing struct.
695  * sjw, prop_seg, phase_seg1 and phase_seg2 must be given.
696  * The returned bitrate error is reminder of the devision of the clockrate by
697  * the bitrate times the timing segments.
698  *
699  * @param dev     Pointer to the device structure for the driver instance.
700  * @param timing  Result is written into the can_timing struct provided.
701  * @param bitrate Target bitrate.
702  *
703  * @retval bitrate error
704  * @retval negative on error
705  */
706 int can_calc_prescaler(const struct device *dev, struct can_timing *timing,
707 		       uint32_t bitrate);
708 
709 /**
710  * @brief Set the controller to the given mode
711  *
712  * @param dev Pointer to the device structure for the driver instance.
713  * @param mode   Operation mode
714  *
715  * @retval 0 If successful.
716  * @retval -EIO General input / output error, failed to configure device.
717  */
718 __syscall int can_set_mode(const struct device *dev, enum can_mode mode);
719 
z_impl_can_set_mode(const struct device * dev,enum can_mode mode)720 static inline int z_impl_can_set_mode(const struct device *dev,
721 				      enum can_mode mode)
722 {
723 	const struct can_driver_api *api =
724 		(const struct can_driver_api *)dev->api;
725 
726 	return api->set_mode(dev, mode);
727 }
728 
729 /**
730  * @brief Configure timing of a host controller.
731  *
732  * If the sjw equals CAN_SJW_NO_CHANGE, the sjw parameter is not changed.
733  *
734  * The second parameter timing_data is only relevant for CAN-FD.
735  * If the controller does not support CAN-FD or the FD mode is not enabled,
736  * this parameter is ignored.
737  *
738  * @param dev         Pointer to the device structure for the driver instance.
739  * @param timing      Bus timings
740  * @param timing_data Bus timings for data phase (CAN-FD only)
741  *
742  * @retval 0 If successful.
743  * @retval -EIO General input / output error, failed to configure device.
744  */
745 __syscall int can_set_timing(const struct device *dev,
746 			     const struct can_timing *timing,
747 			     const struct can_timing *timing_data);
748 
z_impl_can_set_timing(const struct device * dev,const struct can_timing * timing,const struct can_timing * timing_data)749 static inline int z_impl_can_set_timing(const struct device *dev,
750 					const struct can_timing *timing,
751 					const struct can_timing *timing_data)
752 {
753 	const struct can_driver_api *api =
754 		(const struct can_driver_api *)dev->api;
755 
756 	return api->set_timing(dev, timing, timing_data);
757 }
758 
759 /**
760  * @brief Set the bitrate of the CAN controller
761  *
762  * The second parameter bitrate_data is only relevant for CAN-FD.
763  * If the controller does not support CAN-FD or the FD mode is not enabled,
764  * this parameter is ignored.
765  * The sample point is set to the CiA DS 301 reccommended value of 87.5%
766  *
767  * @param dev          Pointer to the device structure for the driver instance.
768  * @param bitrate      Desired arbitration phase bitrate
769  * @param bitrate_data Desired data phase bitrate
770  *
771  * @retval 0 If successful.
772  * @retval -EINVAL bitrate cannot be reached.
773  * @retval -EIO General input / output error, failed to set bitrate.
774  */
can_set_bitrate(const struct device * dev,uint32_t bitrate,uint32_t bitrate_data)775 static inline int can_set_bitrate(const struct device *dev,
776 				  uint32_t bitrate,
777 				  uint32_t bitrate_data)
778 {
779 	struct can_timing timing;
780 #ifdef CONFIG_CAN_FD_MODE
781 	struct can_timing timing_data;
782 #endif
783 	int ret;
784 
785 	ret = can_calc_timing(dev, &timing, bitrate, 875);
786 	if (ret < 0) {
787 		return -EINVAL;
788 	}
789 
790 	timing.sjw = CAN_SJW_NO_CHANGE;
791 
792 #ifdef CONFIG_CAN_FD_MODE
793 	ret = can_calc_timing_data(dev, &timing_data, bitrate_data, 875);
794 	if (ret < 0) {
795 		return -EINVAL;
796 	}
797 
798 	timing_data.sjw = CAN_SJW_NO_CHANGE;
799 
800 	return can_set_timing(dev, &timing, &timing_data);
801 #else
802 	return can_set_timing(dev, &timing, NULL);
803 #endif /* CONFIG_CAN_FD_MODE */
804 }
805 
806 /**
807  * @brief Configure operation of a host controller.
808  *
809  * @param dev Pointer to the device structure for the driver instance.
810  * @param mode Operation mode
811  * @param bitrate bus-speed in Baud/s
812  *
813  * @retval 0 If successful.
814  * @retval -EIO General input / output error, failed to configure device.
815  */
can_configure(const struct device * dev,enum can_mode mode,uint32_t bitrate)816 static inline int can_configure(const struct device *dev, enum can_mode mode,
817 				uint32_t bitrate)
818 {
819 	if (bitrate > 0) {
820 		int err = can_set_bitrate(dev, bitrate, bitrate);
821 		if (err != 0) {
822 			return err;
823 		}
824 	}
825 
826 	return can_set_mode(dev, mode);
827 }
828 
829 /**
830  * @brief Get current state
831  *
832  * Returns the actual state of the CAN controller.
833  *
834  * @param dev     Pointer to the device structure for the driver instance.
835  * @param err_cnt Pointer to the err_cnt destination structure or NULL.
836  *
837  * @retval  state
838  */
839 __syscall enum can_state can_get_state(const struct device *dev,
840 				       struct can_bus_err_cnt *err_cnt);
841 
842 static inline
z_impl_can_get_state(const struct device * dev,struct can_bus_err_cnt * err_cnt)843 enum can_state z_impl_can_get_state(const struct device *dev,
844 				    struct can_bus_err_cnt *err_cnt)
845 {
846 	const struct can_driver_api *api =
847 		(const struct can_driver_api *)dev->api;
848 
849 	return api->get_state(dev, err_cnt);
850 }
851 
852 /**
853  * @brief Recover from bus-off state
854  *
855  * Recover the CAN controller from bus-off state to error-active state.
856  *
857  * @param dev     Pointer to the device structure for the driver instance.
858  * @param timeout Timeout for waiting for the recovery or K_FOREVER.
859  *
860  * @retval 0 on success.
861  * @retval CAN_TIMEOUT on timeout.
862  */
863 #ifndef CONFIG_CAN_AUTO_BUS_OFF_RECOVERY
864 __syscall int can_recover(const struct device *dev, k_timeout_t timeout);
865 
z_impl_can_recover(const struct device * dev,k_timeout_t timeout)866 static inline int z_impl_can_recover(const struct device *dev,
867 				     k_timeout_t timeout)
868 {
869 	const struct can_driver_api *api =
870 		(const struct can_driver_api *)dev->api;
871 
872 	return api->recover(dev, timeout);
873 }
874 #else
875 /* This implementation prevents inking errors for auto recovery */
z_impl_can_recover(const struct device * dev,k_timeout_t timeout)876 static inline int z_impl_can_recover(const struct device *dev,
877 				     k_timeout_t timeout)
878 {
879 	return 0;
880 }
881 #endif /* CONFIG_CAN_AUTO_BUS_OFF_RECOVERY */
882 
883 /**
884  * @brief Register an ISR callback for state change interrupt
885  *
886  * Only one callback can be registered per controller.
887  * Calling this function again, overrides the previous call.
888  *
889  * @param dev Pointer to the device structure for the driver instance.
890  * @param isr Pointer to ISR
891  */
892 static inline
can_register_state_change_isr(const struct device * dev,can_state_change_isr_t isr)893 void can_register_state_change_isr(const struct device *dev,
894 				   can_state_change_isr_t isr)
895 {
896 	const struct can_driver_api *api =
897 		(const struct can_driver_api *)dev->api;
898 
899 	return api->register_state_change_isr(dev, isr);
900 }
901 
902 /**
903  * @brief Converter that translates between can_frame and zcan_frame structs.
904  *
905  * @param frame Pointer to can_frame struct.
906  * @param zframe Pointer to zcan_frame struct.
907  */
can_copy_frame_to_zframe(const struct can_frame * frame,struct zcan_frame * zframe)908 static inline void can_copy_frame_to_zframe(const struct can_frame *frame,
909 					    struct zcan_frame *zframe)
910 {
911 	zframe->id_type = (frame->can_id & BIT(31)) >> 31;
912 	zframe->rtr = (frame->can_id & BIT(30)) >> 30;
913 	zframe->id = frame->can_id & BIT_MASK(29);
914 	zframe->dlc = frame->can_dlc;
915 	memcpy(zframe->data, frame->data, sizeof(zframe->data));
916 }
917 
918 /**
919  * @brief Converter that translates between zcan_frame and can_frame structs.
920  *
921  * @param zframe Pointer to zcan_frame struct.
922  * @param frame Pointer to can_frame struct.
923  */
can_copy_zframe_to_frame(const struct zcan_frame * zframe,struct can_frame * frame)924 static inline void can_copy_zframe_to_frame(const struct zcan_frame *zframe,
925 					    struct can_frame *frame)
926 {
927 	frame->can_id = (zframe->id_type << 31) | (zframe->rtr << 30) |
928 		zframe->id;
929 	frame->can_dlc = zframe->dlc;
930 	memcpy(frame->data, zframe->data, sizeof(frame->data));
931 }
932 
933 /**
934  * @brief Converter that translates between can_filter and zcan_frame_filter
935  * structs.
936  *
937  * @param filter Pointer to can_filter struct.
938  * @param zfilter Pointer to zcan_frame_filter struct.
939  */
940 static inline
can_copy_filter_to_zfilter(const struct can_filter * filter,struct zcan_filter * zfilter)941 void can_copy_filter_to_zfilter(const struct can_filter *filter,
942 				struct zcan_filter *zfilter)
943 {
944 	zfilter->id_type = (filter->can_id & BIT(31)) >> 31;
945 	zfilter->rtr = (filter->can_id & BIT(30)) >> 30;
946 	zfilter->id = filter->can_id & BIT_MASK(29);
947 	zfilter->rtr_mask = (filter->can_mask & BIT(30)) >> 30;
948 	zfilter->id_mask = filter->can_mask & BIT_MASK(29);
949 }
950 
951 /**
952  * @brief Converter that translates between zcan_filter and can_filter
953  * structs.
954  *
955  * @param zfilter Pointer to zcan_filter struct.
956  * @param filter Pointer to can_filter struct.
957  */
958 static inline
can_copy_zfilter_to_filter(const struct zcan_filter * zfilter,struct can_filter * filter)959 void can_copy_zfilter_to_filter(const struct zcan_filter *zfilter,
960 				struct can_filter *filter)
961 {
962 	filter->can_id = (zfilter->id_type << 31) |
963 		(zfilter->rtr << 30) | zfilter->id;
964 	filter->can_mask = (zfilter->rtr_mask << 30) |
965 		(zfilter->id_type << 31) | zfilter->id_mask;
966 }
967 
968 #ifdef __cplusplus
969 }
970 #endif
971 /**
972  * @}
973  */
974 #include <syscalls/can.h>
975 
976 #endif /* ZEPHYR_INCLUDE_DRIVERS_CAN_H_ */
977