1 /* SPDX-License-Identifier: GPL-2.0 */
2 
3 /* Driver for ETAS GmbH ES58X USB CAN(-FD) Bus Interfaces.
4  *
5  * File es58x_core.h: All common definitions and declarations.
6  *
7  * Copyright (c) 2019 Robert Bosch Engineering and Business Solutions. All rights reserved.
8  * Copyright (c) 2020 ETAS K.K.. All rights reserved.
9  * Copyright (c) 2020, 2021 Vincent Mailhol <mailhol.vincent@wanadoo.fr>
10  */
11 
12 #ifndef __ES58X_COMMON_H__
13 #define __ES58X_COMMON_H__
14 
15 #include <linux/types.h>
16 #include <linux/usb.h>
17 #include <linux/netdevice.h>
18 #include <linux/can.h>
19 #include <linux/can/dev.h>
20 
21 #include "es581_4.h"
22 #include "es58x_fd.h"
23 
24 /* Driver constants */
25 #define ES58X_RX_URBS_MAX 5	/* Empirical value */
26 #define ES58X_TX_URBS_MAX 6	/* Empirical value */
27 
28 #define ES58X_MAX(param)				\
29 	(ES581_4_##param > ES58X_FD_##param ?		\
30 		ES581_4_##param : ES58X_FD_##param)
31 #define ES58X_TX_BULK_MAX ES58X_MAX(TX_BULK_MAX)
32 #define ES58X_RX_BULK_MAX ES58X_MAX(RX_BULK_MAX)
33 #define ES58X_ECHO_BULK_MAX ES58X_MAX(ECHO_BULK_MAX)
34 #define ES58X_NUM_CAN_CH_MAX ES58X_MAX(NUM_CAN_CH)
35 
36 /* Use this when channel index is irrelevant (e.g. device
37  * timestamp).
38  */
39 #define ES58X_CHANNEL_IDX_NA 0xFF
40 #define ES58X_EMPTY_MSG NULL
41 
42 /* Threshold on consecutive CAN_STATE_ERROR_PASSIVE. If we receive
43  * ES58X_CONSECUTIVE_ERR_PASSIVE_MAX times the event
44  * ES58X_ERR_CRTL_PASSIVE in a row without any successful RX or TX,
45  * we force the device to switch to CAN_STATE_BUS_OFF state.
46  */
47 #define ES58X_CONSECUTIVE_ERR_PASSIVE_MAX 254
48 
49 /* A magic number sent by the ES581.4 to inform it is alive. */
50 #define ES58X_HEARTBEAT 0x11
51 
52 /**
53  * enum es58x_driver_info - Quirks of the device.
54  * @ES58X_DUAL_CHANNEL: Device has two CAN channels. If this flag is
55  *	not set, it is implied that the device has only one CAN
56  *	channel.
57  * @ES58X_FD_FAMILY: Device is CAN-FD capable. If this flag is not
58  *	set, the device only supports classical CAN.
59  */
60 enum es58x_driver_info {
61 	ES58X_DUAL_CHANNEL = BIT(0),
62 	ES58X_FD_FAMILY = BIT(1)
63 };
64 
65 enum es58x_echo {
66 	ES58X_ECHO_OFF = 0,
67 	ES58X_ECHO_ON = 1
68 };
69 
70 /**
71  * enum es58x_physical_layer - Type of the physical layer.
72  * @ES58X_PHYSICAL_LAYER_HIGH_SPEED: High-speed CAN (c.f. ISO
73  *	11898-2).
74  *
75  * Some products of the ETAS portfolio also support low-speed CAN
76  * (c.f. ISO 11898-3). However, all the devices in scope of this
77  * driver do not support the option, thus, the enum has only one
78  * member.
79  */
80 enum es58x_physical_layer {
81 	ES58X_PHYSICAL_LAYER_HIGH_SPEED = 1
82 };
83 
84 enum es58x_samples_per_bit {
85 	ES58X_SAMPLES_PER_BIT_ONE = 1,
86 	ES58X_SAMPLES_PER_BIT_THREE = 2
87 };
88 
89 /**
90  * enum es58x_sync_edge - Synchronization method.
91  * @ES58X_SYNC_EDGE_SINGLE: ISO CAN specification defines the use of a
92  *	single edge synchronization.  The synchronization should be
93  *	done on recessive to dominant level change.
94  *
95  * For information, ES582.1 and ES584.1 also support a double
96  * synchronization, requiring both recessive to dominant then dominant
97  * to recessive level change. However, this is not supported in
98  * SocketCAN framework, thus, the enum has only one member.
99  */
100 enum es58x_sync_edge {
101 	ES58X_SYNC_EDGE_SINGLE = 1
102 };
103 
104 /**
105  * enum es58x_flag - CAN flags for RX/TX messages.
106  * @ES58X_FLAG_EFF: Extended Frame Format (EFF).
107  * @ES58X_FLAG_RTR: Remote Transmission Request (RTR).
108  * @ES58X_FLAG_FD_BRS: Bit rate switch (BRS): second bitrate for
109  *	payload data.
110  * @ES58X_FLAG_FD_ESI: Error State Indicator (ESI): tell if the
111  *	transmitting node is in error passive mode.
112  * @ES58X_FLAG_FD_DATA: CAN FD frame.
113  */
114 enum es58x_flag {
115 	ES58X_FLAG_EFF = BIT(0),
116 	ES58X_FLAG_RTR = BIT(1),
117 	ES58X_FLAG_FD_BRS = BIT(3),
118 	ES58X_FLAG_FD_ESI = BIT(5),
119 	ES58X_FLAG_FD_DATA = BIT(6)
120 };
121 
122 /**
123  * enum es58x_err - CAN error detection.
124  * @ES58X_ERR_OK: No errors.
125  * @ES58X_ERR_PROT_STUFF: Bit stuffing error: more than 5 consecutive
126  *	equal bits.
127  * @ES58X_ERR_PROT_FORM: Frame format error.
128  * @ES58X_ERR_ACK: Received no ACK on transmission.
129  * @ES58X_ERR_PROT_BIT: Single bit error.
130  * @ES58X_ERR_PROT_CRC: Incorrect 15, 17 or 21 bits CRC.
131  * @ES58X_ERR_PROT_BIT1: Unable to send recessive bit: tried to send
132  *	recessive bit 1 but monitored dominant bit 0.
133  * @ES58X_ERR_PROT_BIT0: Unable to send dominant bit: tried to send
134  *	dominant bit 0 but monitored recessive bit 1.
135  * @ES58X_ERR_PROT_OVERLOAD: Bus overload.
136  * @ES58X_ERR_PROT_UNSPEC: Unspecified.
137  *
138  * Please refer to ISO 11898-1:2015, section 10.11 "Error detection"
139  * and section 10.13 "Overload signaling" for additional details.
140  */
141 enum es58x_err {
142 	ES58X_ERR_OK = 0,
143 	ES58X_ERR_PROT_STUFF = BIT(0),
144 	ES58X_ERR_PROT_FORM = BIT(1),
145 	ES58X_ERR_ACK = BIT(2),
146 	ES58X_ERR_PROT_BIT = BIT(3),
147 	ES58X_ERR_PROT_CRC = BIT(4),
148 	ES58X_ERR_PROT_BIT1 = BIT(5),
149 	ES58X_ERR_PROT_BIT0 = BIT(6),
150 	ES58X_ERR_PROT_OVERLOAD = BIT(7),
151 	ES58X_ERR_PROT_UNSPEC = BIT(31)
152 };
153 
154 /**
155  * enum es58x_event - CAN error codes returned by the device.
156  * @ES58X_EVENT_OK: No errors.
157  * @ES58X_EVENT_CRTL_ACTIVE: Active state: both TR and RX error count
158  *	is less than 128.
159  * @ES58X_EVENT_CRTL_PASSIVE: Passive state: either TX or RX error
160  *	count is greater than 127.
161  * @ES58X_EVENT_CRTL_WARNING: Warning state: either TX or RX error
162  *	count is greater than 96.
163  * @ES58X_EVENT_BUSOFF: Bus off.
164  * @ES58X_EVENT_SINGLE_WIRE: Lost connection on either CAN high or CAN
165  *	low.
166  *
167  * Please refer to ISO 11898-1:2015, section 12.1.4 "Rules of fault
168  * confinement" for additional details.
169  */
170 enum es58x_event {
171 	ES58X_EVENT_OK = 0,
172 	ES58X_EVENT_CRTL_ACTIVE = BIT(0),
173 	ES58X_EVENT_CRTL_PASSIVE = BIT(1),
174 	ES58X_EVENT_CRTL_WARNING = BIT(2),
175 	ES58X_EVENT_BUSOFF = BIT(3),
176 	ES58X_EVENT_SINGLE_WIRE = BIT(4)
177 };
178 
179 /* enum es58x_ret_u8 - Device return error codes, 8 bit format.
180  *
181  * Specific to ES581.4.
182  */
183 enum es58x_ret_u8 {
184 	ES58X_RET_U8_OK = 0x00,
185 	ES58X_RET_U8_ERR_UNSPECIFIED_FAILURE = 0x80,
186 	ES58X_RET_U8_ERR_NO_MEM = 0x81,
187 	ES58X_RET_U8_ERR_BAD_CRC = 0x99
188 };
189 
190 /* enum es58x_ret_u32 - Device return error codes, 32 bit format.
191  */
192 enum es58x_ret_u32 {
193 	ES58X_RET_U32_OK = 0x00000000UL,
194 	ES58X_RET_U32_ERR_UNSPECIFIED_FAILURE = 0x80000000UL,
195 	ES58X_RET_U32_ERR_NO_MEM = 0x80004001UL,
196 	ES58X_RET_U32_WARN_PARAM_ADJUSTED = 0x40004000UL,
197 	ES58X_RET_U32_WARN_TX_MAYBE_REORDER = 0x40004001UL,
198 	ES58X_RET_U32_ERR_TIMEDOUT = 0x80000008UL,
199 	ES58X_RET_U32_ERR_FIFO_FULL = 0x80003002UL,
200 	ES58X_RET_U32_ERR_BAD_CONFIG = 0x80004000UL,
201 	ES58X_RET_U32_ERR_NO_RESOURCE = 0x80004002UL
202 };
203 
204 /* enum es58x_ret_type - Type of the command returned by the ES58X
205  *	device.
206  */
207 enum es58x_ret_type {
208 	ES58X_RET_TYPE_SET_BITTIMING,
209 	ES58X_RET_TYPE_ENABLE_CHANNEL,
210 	ES58X_RET_TYPE_DISABLE_CHANNEL,
211 	ES58X_RET_TYPE_TX_MSG,
212 	ES58X_RET_TYPE_RESET_RX,
213 	ES58X_RET_TYPE_RESET_TX,
214 	ES58X_RET_TYPE_DEVICE_ERR
215 };
216 
217 union es58x_urb_cmd {
218 	struct es581_4_urb_cmd es581_4_urb_cmd;
219 	struct es58x_fd_urb_cmd es58x_fd_urb_cmd;
220 	struct {		/* Common header parts of all variants */
221 		__le16 sof;
222 		u8 cmd_type;
223 		u8 cmd_id;
224 	} __packed;
225 	u8 raw_cmd[0];
226 };
227 
228 /**
229  * struct es58x_priv - All information specific to a CAN channel.
230  * @can: struct can_priv must be the first member (Socket CAN relies
231  *	on the fact that function netdev_priv() returns a pointer to
232  *	a struct can_priv).
233  * @es58x_dev: pointer to the corresponding ES58X device.
234  * @tx_urb: Used as a buffer to concatenate the TX messages and to do
235  *	a bulk send. Please refer to es58x_start_xmit() for more
236  *	details.
237  * @tx_tail: Index of the oldest packet still pending for
238  *	completion. @tx_tail & echo_skb_mask represents the beginning
239  *	of the echo skb FIFO, i.e. index of the first element.
240  * @tx_head: Index of the next packet to be sent to the
241  *	device. @tx_head & echo_skb_mask represents the end of the
242  *	echo skb FIFO plus one, i.e. the first free index.
243  * @tx_can_msg_cnt: Number of messages in @tx_urb.
244  * @tx_can_msg_is_fd: false: all messages in @tx_urb are Classical
245  *	CAN, true: all messages in @tx_urb are CAN FD. Rationale:
246  *	ES58X FD devices do not allow to mix Classical CAN and FD CAN
247  *	frames in one single bulk transmission.
248  * @err_passive_before_rtx_success: The ES58X device might enter in a
249  *	state in which it keeps alternating between error passive
250  *	and active states. This counter keeps track of the number of
251  *	error passive and if it gets bigger than
252  *	ES58X_CONSECUTIVE_ERR_PASSIVE_MAX, es58x_rx_err_msg() will
253  *	force the status to bus-off.
254  * @channel_idx: Channel index, starts at zero.
255  */
256 struct es58x_priv {
257 	struct can_priv can;
258 	struct es58x_device *es58x_dev;
259 	struct urb *tx_urb;
260 
261 	u32 tx_tail;
262 	u32 tx_head;
263 
264 	u8 tx_can_msg_cnt;
265 	bool tx_can_msg_is_fd;
266 
267 	u8 err_passive_before_rtx_success;
268 
269 	u8 channel_idx;
270 };
271 
272 /**
273  * struct es58x_parameters - Constant parameters of a given hardware
274  *	variant.
275  * @bittiming_const: Nominal bittimming constant parameters.
276  * @data_bittiming_const: Data bittiming constant parameters.
277  * @tdc_const: Transmission Delay Compensation constant parameters.
278  * @bitrate_max: Maximum bitrate supported by the device.
279  * @clock: CAN clock parameters.
280  * @ctrlmode_supported: List of supported modes. Please refer to
281  *	can/netlink.h file for additional details.
282  * @tx_start_of_frame: Magic number at the beginning of each TX URB
283  *	command.
284  * @rx_start_of_frame: Magic number at the beginning of each RX URB
285  *	command.
286  * @tx_urb_cmd_max_len: Maximum length of a TX URB command.
287  * @rx_urb_cmd_max_len: Maximum length of a RX URB command.
288  * @fifo_mask: Bit mask to quickly convert the tx_tail and tx_head
289  *	field of the struct es58x_priv into echo_skb
290  *	indexes. Properties: @fifo_mask = echo_skb_max - 1 where
291  *	echo_skb_max must be a power of two. Also, echo_skb_max must
292  *	not exceed the maximum size of the device internal TX FIFO
293  *	length. This parameter is used to control the network queue
294  *	wake/stop logic.
295  * @dql_min_limit: Dynamic Queue Limits (DQL) absolute minimum limit
296  *	of bytes allowed to be queued on this network device transmit
297  *	queue. Used by the Byte Queue Limits (BQL) to determine how
298  *	frequently the xmit_more flag will be set to true in
299  *	es58x_start_xmit(). Set this value higher to optimize for
300  *	throughput but be aware that it might have a negative impact
301  *	on the latency! This value can also be set dynamically. Please
302  *	refer to Documentation/ABI/testing/sysfs-class-net-queues for
303  *	more details.
304  * @tx_bulk_max: Maximum number of TX messages that can be sent in one
305  *	single URB packet.
306  * @urb_cmd_header_len: Length of the URB command header.
307  * @rx_urb_max: Number of RX URB to be allocated during device probe.
308  * @tx_urb_max: Number of TX URB to be allocated during device probe.
309  */
310 struct es58x_parameters {
311 	const struct can_bittiming_const *bittiming_const;
312 	const struct can_bittiming_const *data_bittiming_const;
313 	const struct can_tdc_const *tdc_const;
314 	u32 bitrate_max;
315 	struct can_clock clock;
316 	u32 ctrlmode_supported;
317 	u16 tx_start_of_frame;
318 	u16 rx_start_of_frame;
319 	u16 tx_urb_cmd_max_len;
320 	u16 rx_urb_cmd_max_len;
321 	u16 fifo_mask;
322 	u16 dql_min_limit;
323 	u8 tx_bulk_max;
324 	u8 urb_cmd_header_len;
325 	u8 rx_urb_max;
326 	u8 tx_urb_max;
327 };
328 
329 /**
330  * struct es58x_operators - Function pointers used to encode/decode
331  *	the TX/RX messages.
332  * @get_msg_len: Get field msg_len of the urb_cmd. The offset of
333  *	msg_len inside urb_cmd depends of the device model.
334  * @handle_urb_cmd: Decode the URB command received from the device
335  *	and dispatch it to the relevant sub function.
336  * @fill_urb_header: Fill the header of urb_cmd.
337  * @tx_can_msg: Encode a TX CAN message and add it to the bulk buffer
338  *	cmd_buf of es58x_dev.
339  * @enable_channel: Start the CAN channel.
340  * @disable_channel: Stop the CAN channel.
341  * @reset_device: Full reset of the device. N.B: this feature is only
342  *	present on the ES581.4. For ES58X FD devices, this field is
343  *	set to NULL.
344  * @get_timestamp: Request a timestamp from the ES58X device.
345  */
346 struct es58x_operators {
347 	u16 (*get_msg_len)(const union es58x_urb_cmd *urb_cmd);
348 	int (*handle_urb_cmd)(struct es58x_device *es58x_dev,
349 			      const union es58x_urb_cmd *urb_cmd);
350 	void (*fill_urb_header)(union es58x_urb_cmd *urb_cmd, u8 cmd_type,
351 				u8 cmd_id, u8 channel_idx, u16 cmd_len);
352 	int (*tx_can_msg)(struct es58x_priv *priv, const struct sk_buff *skb);
353 	int (*enable_channel)(struct es58x_priv *priv);
354 	int (*disable_channel)(struct es58x_priv *priv);
355 	int (*reset_device)(struct es58x_device *es58x_dev);
356 	int (*get_timestamp)(struct es58x_device *es58x_dev);
357 };
358 
359 /**
360  * struct es58x_device - All information specific to an ES58X device.
361  * @dev: Device information.
362  * @udev: USB device information.
363  * @netdev: Array of our CAN channels.
364  * @param: The constant parameters.
365  * @ops: Operators.
366  * @rx_pipe: USB reception pipe.
367  * @tx_pipe: USB transmission pipe.
368  * @rx_urbs: Anchor for received URBs.
369  * @tx_urbs_busy: Anchor for TX URBs which were send to the device.
370  * @tx_urbs_idle: Anchor for TX USB which are idle. This driver
371  *	allocates the memory for the URBs during the probe. When a TX
372  *	URB is needed, it can be taken from this anchor. The network
373  *	queue wake/stop logic should prevent this URB from getting
374  *	empty. Please refer to es58x_get_tx_urb() for more details.
375  * @tx_urbs_idle_cnt: number of urbs in @tx_urbs_idle.
376  * @ktime_req_ns: kernel timestamp when es58x_set_realtime_diff_ns()
377  *	was called.
378  * @realtime_diff_ns: difference in nanoseconds between the clocks of
379  *	the ES58X device and the kernel.
380  * @timestamps: a temporary buffer to store the time stamps before
381  *	feeding them to es58x_can_get_echo_skb(). Can only be used
382  *	in RX branches.
383  * @rx_max_packet_size: Maximum length of bulk-in URB.
384  * @num_can_ch: Number of CAN channel (i.e. number of elements of @netdev).
385  * @opened_channel_cnt: number of channels opened. Free of race
386  *	conditions because its two users (net_device_ops:ndo_open()
387  *	and net_device_ops:ndo_close()) guarantee that the network
388  *	stack big kernel lock (a.k.a. rtnl_mutex) is being hold.
389  * @rx_cmd_buf_len: Length of @rx_cmd_buf.
390  * @rx_cmd_buf: The device might split the URB commands in an
391  *	arbitrary amount of pieces. This buffer is used to concatenate
392  *	all those pieces. Can only be used in RX branches. This field
393  *	has to be the last one of the structure because it is has a
394  *	flexible size (c.f. es58x_sizeof_es58x_device() function).
395  */
396 struct es58x_device {
397 	struct device *dev;
398 	struct usb_device *udev;
399 	struct net_device *netdev[ES58X_NUM_CAN_CH_MAX];
400 
401 	const struct es58x_parameters *param;
402 	const struct es58x_operators *ops;
403 
404 	int rx_pipe;
405 	int tx_pipe;
406 
407 	struct usb_anchor rx_urbs;
408 	struct usb_anchor tx_urbs_busy;
409 	struct usb_anchor tx_urbs_idle;
410 	atomic_t tx_urbs_idle_cnt;
411 
412 	u64 ktime_req_ns;
413 	s64 realtime_diff_ns;
414 
415 	u64 timestamps[ES58X_ECHO_BULK_MAX];
416 
417 	u16 rx_max_packet_size;
418 	u8 num_can_ch;
419 	u8 opened_channel_cnt;
420 
421 	u16 rx_cmd_buf_len;
422 	union es58x_urb_cmd rx_cmd_buf;
423 };
424 
425 /**
426  * es58x_sizeof_es58x_device() - Calculate the maximum length of
427  *	struct es58x_device.
428  * @es58x_dev_param: The constant parameters of the device.
429  *
430  * The length of struct es58x_device depends on the length of its last
431  * field: rx_cmd_buf. This macro allows to optimize the memory
432  * allocation.
433  *
434  * Return: length of struct es58x_device.
435  */
es58x_sizeof_es58x_device(const struct es58x_parameters * es58x_dev_param)436 static inline size_t es58x_sizeof_es58x_device(const struct es58x_parameters
437 					       *es58x_dev_param)
438 {
439 	return offsetof(struct es58x_device, rx_cmd_buf) +
440 		es58x_dev_param->rx_urb_cmd_max_len;
441 }
442 
__es58x_check_msg_len(const struct device * dev,const char * stringified_msg,size_t actual_len,size_t expected_len)443 static inline int __es58x_check_msg_len(const struct device *dev,
444 					const char *stringified_msg,
445 					size_t actual_len, size_t expected_len)
446 {
447 	if (expected_len != actual_len) {
448 		dev_err(dev,
449 			"Length of %s is %zu but received command is %zu.\n",
450 			stringified_msg, expected_len, actual_len);
451 		return -EMSGSIZE;
452 	}
453 	return 0;
454 }
455 
456 /**
457  * es58x_check_msg_len() - Check the size of a received message.
458  * @dev: Device, used to print error messages.
459  * @msg: Received message, must not be a pointer.
460  * @actual_len: Length of the message as advertised in the command header.
461  *
462  * Must be a macro in order to accept the different types of messages
463  * as an input. Can be use with any of the messages which have a fixed
464  * length. Check for an exact match of the size.
465  *
466  * Return: zero on success, -EMSGSIZE if @actual_len differs from the
467  * expected length.
468  */
469 #define es58x_check_msg_len(dev, msg, actual_len)			\
470 	__es58x_check_msg_len(dev, __stringify(msg),			\
471 			      actual_len, sizeof(msg))
472 
__es58x_check_msg_max_len(const struct device * dev,const char * stringified_msg,size_t actual_len,size_t expected_len)473 static inline int __es58x_check_msg_max_len(const struct device *dev,
474 					    const char *stringified_msg,
475 					    size_t actual_len,
476 					    size_t expected_len)
477 {
478 	if (actual_len > expected_len) {
479 		dev_err(dev,
480 			"Maximum length for %s is %zu but received command is %zu.\n",
481 			stringified_msg, expected_len, actual_len);
482 		return -EOVERFLOW;
483 	}
484 	return 0;
485 }
486 
487 /**
488  * es58x_check_msg_max_len() - Check the maximum size of a received message.
489  * @dev: Device, used to print error messages.
490  * @msg: Received message, must not be a pointer.
491  * @actual_len: Length of the message as advertised in the command header.
492  *
493  * Must be a macro in order to accept the different types of messages
494  * as an input. To be used with the messages of variable sizes. Only
495  * check that the message is not bigger than the maximum expected
496  * size.
497  *
498  * Return: zero on success, -EOVERFLOW if @actual_len is greater than
499  * the expected length.
500  */
501 #define es58x_check_msg_max_len(dev, msg, actual_len)			\
502 	__es58x_check_msg_max_len(dev, __stringify(msg),		\
503 				  actual_len, sizeof(msg))
504 
__es58x_msg_num_element(const struct device * dev,const char * stringified_msg,size_t actual_len,size_t msg_len,size_t elem_len)505 static inline int __es58x_msg_num_element(const struct device *dev,
506 					  const char *stringified_msg,
507 					  size_t actual_len, size_t msg_len,
508 					  size_t elem_len)
509 {
510 	size_t actual_num_elem = actual_len / elem_len;
511 	size_t expected_num_elem = msg_len / elem_len;
512 
513 	if (actual_num_elem == 0) {
514 		dev_err(dev,
515 			"Minimum length for %s is %zu but received command is %zu.\n",
516 			stringified_msg, elem_len, actual_len);
517 		return -EMSGSIZE;
518 	} else if ((actual_len % elem_len) != 0) {
519 		dev_err(dev,
520 			"Received command length: %zu is not a multiple of %s[0]: %zu\n",
521 			actual_len, stringified_msg, elem_len);
522 		return -EMSGSIZE;
523 	} else if (actual_num_elem > expected_num_elem) {
524 		dev_err(dev,
525 			"Array %s is supposed to have %zu elements each of size %zu...\n",
526 			stringified_msg, expected_num_elem, elem_len);
527 		dev_err(dev,
528 			"... But received command has %zu elements (total length %zu).\n",
529 			actual_num_elem, actual_len);
530 		return -EOVERFLOW;
531 	}
532 	return actual_num_elem;
533 }
534 
535 /**
536  * es58x_msg_num_element() - Check size and give the number of
537  *	elements in a message of array type.
538  * @dev: Device, used to print error messages.
539  * @msg: Received message, must be an array.
540  * @actual_len: Length of the message as advertised in the command
541  *	header.
542  *
543  * Must be a macro in order to accept the different types of messages
544  * as an input. To be used on message of array type. Array's element
545  * has to be of fixed size (else use es58x_check_msg_max_len()). Check
546  * that the total length is an exact multiple of the length of a
547  * single element.
548  *
549  * Return: number of elements in the array on success, -EOVERFLOW if
550  * @actual_len is greater than the expected length, -EMSGSIZE if
551  * @actual_len is not a multiple of a single element.
552  */
553 #define es58x_msg_num_element(dev, msg, actual_len)			\
554 ({									\
555 	size_t __elem_len = sizeof((msg)[0]) + __must_be_array(msg);	\
556 	__es58x_msg_num_element(dev, __stringify(msg), actual_len,	\
557 				sizeof(msg), __elem_len);		\
558 })
559 
560 /**
561  * es58x_priv() - Get the priv member and cast it to struct es58x_priv.
562  * @netdev: CAN network device.
563  *
564  * Return: ES58X device.
565  */
es58x_priv(struct net_device * netdev)566 static inline struct es58x_priv *es58x_priv(struct net_device *netdev)
567 {
568 	return (struct es58x_priv *)netdev_priv(netdev);
569 }
570 
571 /**
572  * ES58X_SIZEOF_URB_CMD() - Calculate the maximum length of an urb
573  *	command for a given message field name.
574  * @es58x_urb_cmd_type: type (either "struct es581_4_urb_cmd" or
575  *	"struct es58x_fd_urb_cmd").
576  * @msg_field: name of the message field.
577  *
578  * Must be a macro in order to accept the different command types as
579  * an input.
580  *
581  * Return: length of the urb command.
582  */
583 #define ES58X_SIZEOF_URB_CMD(es58x_urb_cmd_type, msg_field)		\
584 	(offsetof(es58x_urb_cmd_type, raw_msg)				\
585 		+ sizeof_field(es58x_urb_cmd_type, msg_field)		\
586 		+ sizeof_field(es58x_urb_cmd_type,			\
587 			       reserved_for_crc16_do_not_use))
588 
589 /**
590  * es58x_get_urb_cmd_len() - Calculate the actual length of an urb
591  *	command for a given message length.
592  * @es58x_dev: ES58X device.
593  * @msg_len: Length of the message.
594  *
595  * Add the header and CRC lengths to the message length.
596  *
597  * Return: length of the urb command.
598  */
es58x_get_urb_cmd_len(struct es58x_device * es58x_dev,u16 msg_len)599 static inline size_t es58x_get_urb_cmd_len(struct es58x_device *es58x_dev,
600 					   u16 msg_len)
601 {
602 	return es58x_dev->param->urb_cmd_header_len + msg_len + sizeof(u16);
603 }
604 
605 /**
606  * es58x_get_netdev() - Get the network device.
607  * @es58x_dev: ES58X device.
608  * @channel_no: The channel number as advertised in the urb command.
609  * @channel_idx_offset: Some of the ES58x starts channel numbering
610  *	from 0 (ES58X FD), others from 1 (ES581.4).
611  * @netdev: CAN network device.
612  *
613  * Do a sanity check on the index provided by the device.
614  *
615  * Return: zero on success, -ECHRNG if the received channel number is
616  *	out of range and -ENODEV if the network device is not yet
617  *	configured.
618  */
es58x_get_netdev(struct es58x_device * es58x_dev,int channel_no,int channel_idx_offset,struct net_device ** netdev)619 static inline int es58x_get_netdev(struct es58x_device *es58x_dev,
620 				   int channel_no, int channel_idx_offset,
621 				   struct net_device **netdev)
622 {
623 	int channel_idx = channel_no - channel_idx_offset;
624 
625 	*netdev = NULL;
626 	if (channel_idx < 0 || channel_idx >= es58x_dev->num_can_ch)
627 		return -ECHRNG;
628 
629 	*netdev = es58x_dev->netdev[channel_idx];
630 	if (!*netdev || !netif_device_present(*netdev))
631 		return -ENODEV;
632 
633 	return 0;
634 }
635 
636 /**
637  * es58x_get_raw_can_id() - Get the CAN ID.
638  * @cf: CAN frame.
639  *
640  * Mask the CAN ID in order to only keep the significant bits.
641  *
642  * Return: the raw value of the CAN ID.
643  */
es58x_get_raw_can_id(const struct can_frame * cf)644 static inline int es58x_get_raw_can_id(const struct can_frame *cf)
645 {
646 	if (cf->can_id & CAN_EFF_FLAG)
647 		return cf->can_id & CAN_EFF_MASK;
648 	else
649 		return cf->can_id & CAN_SFF_MASK;
650 }
651 
652 /**
653  * es58x_get_flags() - Get the CAN flags.
654  * @skb: socket buffer of a CAN message.
655  *
656  * Return: the CAN flag as an enum es58x_flag.
657  */
es58x_get_flags(const struct sk_buff * skb)658 static inline enum es58x_flag es58x_get_flags(const struct sk_buff *skb)
659 {
660 	struct canfd_frame *cf = (struct canfd_frame *)skb->data;
661 	enum es58x_flag es58x_flags = 0;
662 
663 	if (cf->can_id & CAN_EFF_FLAG)
664 		es58x_flags |= ES58X_FLAG_EFF;
665 
666 	if (can_is_canfd_skb(skb)) {
667 		es58x_flags |= ES58X_FLAG_FD_DATA;
668 		if (cf->flags & CANFD_BRS)
669 			es58x_flags |= ES58X_FLAG_FD_BRS;
670 		if (cf->flags & CANFD_ESI)
671 			es58x_flags |= ES58X_FLAG_FD_ESI;
672 	} else if (cf->can_id & CAN_RTR_FLAG)
673 		/* Remote frames are only defined in Classical CAN frames */
674 		es58x_flags |= ES58X_FLAG_RTR;
675 
676 	return es58x_flags;
677 }
678 
679 int es58x_can_get_echo_skb(struct net_device *netdev, u32 packet_idx,
680 			   u64 *tstamps, unsigned int pkts);
681 int es58x_tx_ack_msg(struct net_device *netdev, u16 tx_free_entries,
682 		     enum es58x_ret_u32 rx_cmd_ret_u32);
683 int es58x_rx_can_msg(struct net_device *netdev, u64 timestamp, const u8 *data,
684 		     canid_t can_id, enum es58x_flag es58x_flags, u8 dlc);
685 int es58x_rx_err_msg(struct net_device *netdev, enum es58x_err error,
686 		     enum es58x_event event, u64 timestamp);
687 void es58x_rx_timestamp(struct es58x_device *es58x_dev, u64 timestamp);
688 int es58x_rx_cmd_ret_u8(struct device *dev, enum es58x_ret_type cmd_ret_type,
689 			enum es58x_ret_u8 rx_cmd_ret_u8);
690 int es58x_rx_cmd_ret_u32(struct net_device *netdev,
691 			 enum es58x_ret_type cmd_ret_type,
692 			 enum es58x_ret_u32 rx_cmd_ret_u32);
693 int es58x_send_msg(struct es58x_device *es58x_dev, u8 cmd_type, u8 cmd_id,
694 		   const void *msg, u16 cmd_len, int channel_idx);
695 
696 extern const struct es58x_parameters es581_4_param;
697 extern const struct es58x_operators es581_4_ops;
698 
699 extern const struct es58x_parameters es58x_fd_param;
700 extern const struct es58x_operators es58x_fd_ops;
701 
702 #endif /* __ES58X_COMMON_H__ */
703