1 // SPDX-License-Identifier: GPL-2.0
2 
3 /* Driver for ETAS GmbH ES58X USB CAN(-FD) Bus Interfaces.
4  *
5  * File es58x_core.c: Core logic to manage the network devices and the
6  * USB interface.
7  *
8  * Copyright (c) 2019 Robert Bosch Engineering and Business Solutions. All rights reserved.
9  * Copyright (c) 2020 ETAS K.K.. All rights reserved.
10  * Copyright (c) 2020, 2021 Vincent Mailhol <mailhol.vincent@wanadoo.fr>
11  */
12 
13 #include <linux/kernel.h>
14 #include <linux/module.h>
15 #include <linux/usb.h>
16 #include <linux/crc16.h>
17 #include <asm/unaligned.h>
18 
19 #include "es58x_core.h"
20 
21 #define DRV_VERSION "1.00"
22 MODULE_AUTHOR("Vincent Mailhol <mailhol.vincent@wanadoo.fr>");
23 MODULE_AUTHOR("Arunachalam Santhanam <arunachalam.santhanam@in.bosch.com>");
24 MODULE_DESCRIPTION("Socket CAN driver for ETAS ES58X USB adapters");
25 MODULE_VERSION(DRV_VERSION);
26 MODULE_LICENSE("GPL v2");
27 
28 #define ES58X_MODULE_NAME "etas_es58x"
29 #define ES58X_VENDOR_ID 0x108C
30 #define ES581_4_PRODUCT_ID 0x0159
31 #define ES582_1_PRODUCT_ID 0x0168
32 #define ES584_1_PRODUCT_ID 0x0169
33 
34 /* ES58X FD has some interface protocols unsupported by this driver. */
35 #define ES58X_FD_INTERFACE_PROTOCOL 0
36 
37 /* Table of devices which work with this driver. */
38 static const struct usb_device_id es58x_id_table[] = {
39 	{
40 		/* ETAS GmbH ES581.4 USB dual-channel CAN Bus Interface module. */
41 		USB_DEVICE(ES58X_VENDOR_ID, ES581_4_PRODUCT_ID),
42 		.driver_info = ES58X_DUAL_CHANNEL
43 	}, {
44 		/* ETAS GmbH ES582.1 USB dual-channel CAN FD Bus Interface module. */
45 		USB_DEVICE_INTERFACE_PROTOCOL(ES58X_VENDOR_ID, ES582_1_PRODUCT_ID,
46 					      ES58X_FD_INTERFACE_PROTOCOL),
47 		.driver_info = ES58X_DUAL_CHANNEL | ES58X_FD_FAMILY
48 	}, {
49 		/* ETAS GmbH ES584.1 USB single-channel CAN FD Bus Interface module. */
50 		USB_DEVICE_INTERFACE_PROTOCOL(ES58X_VENDOR_ID, ES584_1_PRODUCT_ID,
51 					      ES58X_FD_INTERFACE_PROTOCOL),
52 		.driver_info = ES58X_FD_FAMILY
53 	}, {
54 		/* Terminating entry */
55 	}
56 };
57 
58 MODULE_DEVICE_TABLE(usb, es58x_id_table);
59 
60 #define es58x_print_hex_dump(buf, len)					\
61 	print_hex_dump(KERN_DEBUG,					\
62 		       ES58X_MODULE_NAME " " __stringify(buf) ": ",	\
63 		       DUMP_PREFIX_NONE, 16, 1, buf, len, false)
64 
65 #define es58x_print_hex_dump_debug(buf, len)				 \
66 	print_hex_dump_debug(ES58X_MODULE_NAME " " __stringify(buf) ": ",\
67 			     DUMP_PREFIX_NONE, 16, 1, buf, len, false)
68 
69 /* The last two bytes of an ES58X command is a CRC16. The first two
70  * bytes (the start of frame) are skipped and the CRC calculation
71  * starts on the third byte.
72  */
73 #define ES58X_CRC_CALC_OFFSET sizeof_field(union es58x_urb_cmd, sof)
74 
75 /**
76  * es58x_calculate_crc() - Compute the crc16 of a given URB.
77  * @urb_cmd: The URB command for which we want to calculate the CRC.
78  * @urb_len: Length of @urb_cmd. Must be at least bigger than 4
79  *	(ES58X_CRC_CALC_OFFSET + sizeof(crc))
80  *
81  * Return: crc16 value.
82  */
83 static u16 es58x_calculate_crc(const union es58x_urb_cmd *urb_cmd, u16 urb_len)
84 {
85 	u16 crc;
86 	ssize_t len = urb_len - ES58X_CRC_CALC_OFFSET - sizeof(crc);
87 
88 	crc = crc16(0, &urb_cmd->raw_cmd[ES58X_CRC_CALC_OFFSET], len);
89 	return crc;
90 }
91 
92 /**
93  * es58x_get_crc() - Get the CRC value of a given URB.
94  * @urb_cmd: The URB command for which we want to get the CRC.
95  * @urb_len: Length of @urb_cmd. Must be at least bigger than 4
96  *	(ES58X_CRC_CALC_OFFSET + sizeof(crc))
97  *
98  * Return: crc16 value.
99  */
100 static u16 es58x_get_crc(const union es58x_urb_cmd *urb_cmd, u16 urb_len)
101 {
102 	u16 crc;
103 	const __le16 *crc_addr;
104 
105 	crc_addr = (__le16 *)&urb_cmd->raw_cmd[urb_len - sizeof(crc)];
106 	crc = get_unaligned_le16(crc_addr);
107 	return crc;
108 }
109 
110 /**
111  * es58x_set_crc() - Set the CRC value of a given URB.
112  * @urb_cmd: The URB command for which we want to get the CRC.
113  * @urb_len: Length of @urb_cmd. Must be at least bigger than 4
114  *	(ES58X_CRC_CALC_OFFSET + sizeof(crc))
115  */
116 static void es58x_set_crc(union es58x_urb_cmd *urb_cmd, u16 urb_len)
117 {
118 	u16 crc;
119 	__le16 *crc_addr;
120 
121 	crc = es58x_calculate_crc(urb_cmd, urb_len);
122 	crc_addr = (__le16 *)&urb_cmd->raw_cmd[urb_len - sizeof(crc)];
123 	put_unaligned_le16(crc, crc_addr);
124 }
125 
126 /**
127  * es58x_check_crc() - Validate the CRC value of a given URB.
128  * @es58x_dev: ES58X device.
129  * @urb_cmd: The URB command for which we want to check the CRC.
130  * @urb_len: Length of @urb_cmd. Must be at least bigger than 4
131  *	(ES58X_CRC_CALC_OFFSET + sizeof(crc))
132  *
133  * Return: zero on success, -EBADMSG if the CRC check fails.
134  */
135 static int es58x_check_crc(struct es58x_device *es58x_dev,
136 			   const union es58x_urb_cmd *urb_cmd, u16 urb_len)
137 {
138 	u16 calculated_crc = es58x_calculate_crc(urb_cmd, urb_len);
139 	u16 expected_crc = es58x_get_crc(urb_cmd, urb_len);
140 
141 	if (expected_crc != calculated_crc) {
142 		dev_err_ratelimited(es58x_dev->dev,
143 				    "%s: Bad CRC, urb_len: %d\n",
144 				    __func__, urb_len);
145 		return -EBADMSG;
146 	}
147 
148 	return 0;
149 }
150 
151 /**
152  * es58x_timestamp_to_ns() - Convert a timestamp value received from a
153  *	ES58X device to nanoseconds.
154  * @timestamp: Timestamp received from a ES58X device.
155  *
156  * The timestamp received from ES58X is expressed in multiples of 0.5
157  * micro seconds. This function converts it in to nanoseconds.
158  *
159  * Return: Timestamp value in nanoseconds.
160  */
161 static u64 es58x_timestamp_to_ns(u64 timestamp)
162 {
163 	const u64 es58x_timestamp_ns_mult_coef = 500ULL;
164 
165 	return es58x_timestamp_ns_mult_coef * timestamp;
166 }
167 
168 /**
169  * es58x_set_skb_timestamp() - Set the hardware timestamp of an skb.
170  * @netdev: CAN network device.
171  * @skb: socket buffer of a CAN message.
172  * @timestamp: Timestamp received from an ES58X device.
173  *
174  * Used for both received and echo messages.
175  */
176 static void es58x_set_skb_timestamp(struct net_device *netdev,
177 				    struct sk_buff *skb, u64 timestamp)
178 {
179 	struct es58x_device *es58x_dev = es58x_priv(netdev)->es58x_dev;
180 	struct skb_shared_hwtstamps *hwts;
181 
182 	hwts = skb_hwtstamps(skb);
183 	/* Ignoring overflow (overflow on 64 bits timestamp with nano
184 	 * second precision would occur after more than 500 years).
185 	 */
186 	hwts->hwtstamp = ns_to_ktime(es58x_timestamp_to_ns(timestamp) +
187 				     es58x_dev->realtime_diff_ns);
188 }
189 
190 /**
191  * es58x_rx_timestamp() - Handle a received timestamp.
192  * @es58x_dev: ES58X device.
193  * @timestamp: Timestamp received from a ES58X device.
194  *
195  * Calculate the difference between the ES58X device and the kernel
196  * internal clocks. This difference will be later used as an offset to
197  * convert the timestamps of RX and echo messages to match the kernel
198  * system time (e.g. convert to UNIX time).
199  */
200 void es58x_rx_timestamp(struct es58x_device *es58x_dev, u64 timestamp)
201 {
202 	u64 ktime_real_ns = ktime_get_real_ns();
203 	u64 device_timestamp = es58x_timestamp_to_ns(timestamp);
204 
205 	dev_dbg(es58x_dev->dev, "%s: request round-trip time: %llu ns\n",
206 		__func__, ktime_real_ns - es58x_dev->ktime_req_ns);
207 
208 	es58x_dev->realtime_diff_ns =
209 	    (es58x_dev->ktime_req_ns + ktime_real_ns) / 2 - device_timestamp;
210 	es58x_dev->ktime_req_ns = 0;
211 
212 	dev_dbg(es58x_dev->dev,
213 		"%s: Device timestamp: %llu, diff with kernel: %llu\n",
214 		__func__, device_timestamp, es58x_dev->realtime_diff_ns);
215 }
216 
217 /**
218  * es58x_set_realtime_diff_ns() - Calculate difference between the
219  *	clocks of the ES58X device and the kernel
220  * @es58x_dev: ES58X device.
221  *
222  * Request a timestamp from the ES58X device. Once the answer is
223  * received, the timestamp difference will be set by the callback
224  * function es58x_rx_timestamp().
225  *
226  * Return: zero on success, errno when any error occurs.
227  */
228 static int es58x_set_realtime_diff_ns(struct es58x_device *es58x_dev)
229 {
230 	if (es58x_dev->ktime_req_ns) {
231 		dev_warn(es58x_dev->dev,
232 			 "%s: Previous request to set timestamp has not completed yet\n",
233 			 __func__);
234 		return -EBUSY;
235 	}
236 
237 	es58x_dev->ktime_req_ns = ktime_get_real_ns();
238 	return es58x_dev->ops->get_timestamp(es58x_dev);
239 }
240 
241 /**
242  * es58x_is_can_state_active() - Is the network device in an active
243  *	CAN state?
244  * @netdev: CAN network device.
245  *
246  * The device is considered active if it is able to send or receive
247  * CAN frames, that is to say if it is in any of
248  * CAN_STATE_ERROR_ACTIVE, CAN_STATE_ERROR_WARNING or
249  * CAN_STATE_ERROR_PASSIVE states.
250  *
251  * Caution: when recovering from a bus-off,
252  * net/core/dev.c#can_restart() will call
253  * net/core/dev.c#can_flush_echo_skb() without using any kind of
254  * locks. For this reason, it is critical to guarantee that no TX or
255  * echo operations (i.e. any access to priv->echo_skb[]) can be done
256  * while this function is returning false.
257  *
258  * Return: true if the device is active, else returns false.
259  */
260 static bool es58x_is_can_state_active(struct net_device *netdev)
261 {
262 	return es58x_priv(netdev)->can.state < CAN_STATE_BUS_OFF;
263 }
264 
265 /**
266  * es58x_is_echo_skb_threshold_reached() - Determine the limit of how
267  *	many skb slots can be taken before we should stop the network
268  *	queue.
269  * @priv: ES58X private parameters related to the network device.
270  *
271  * We need to save enough free skb slots in order to be able to do
272  * bulk send. This function can be used to determine when to wake or
273  * stop the network queue in regard to the number of skb slots already
274  * taken if the echo FIFO.
275  *
276  * Return: boolean.
277  */
278 static bool es58x_is_echo_skb_threshold_reached(struct es58x_priv *priv)
279 {
280 	u32 num_echo_skb =  priv->tx_head - priv->tx_tail;
281 	u32 threshold = priv->can.echo_skb_max -
282 		priv->es58x_dev->param->tx_bulk_max + 1;
283 
284 	return num_echo_skb >= threshold;
285 }
286 
287 /**
288  * es58x_can_free_echo_skb_tail() - Remove the oldest echo skb of the
289  *	echo FIFO.
290  * @netdev: CAN network device.
291  *
292  * Naming convention: the tail is the beginning of the FIFO, i.e. the
293  * first skb to have entered the FIFO.
294  */
295 static void es58x_can_free_echo_skb_tail(struct net_device *netdev)
296 {
297 	struct es58x_priv *priv = es58x_priv(netdev);
298 	u16 fifo_mask = priv->es58x_dev->param->fifo_mask;
299 	unsigned int frame_len = 0;
300 
301 	can_free_echo_skb(netdev, priv->tx_tail & fifo_mask, &frame_len);
302 	netdev_completed_queue(netdev, 1, frame_len);
303 
304 	priv->tx_tail++;
305 
306 	netdev->stats.tx_dropped++;
307 }
308 
309 /**
310  * es58x_can_get_echo_skb_recovery() - Try to re-sync the echo FIFO.
311  * @netdev: CAN network device.
312  * @rcv_packet_idx: Index
313  *
314  * This function should not be called under normal circumstances. In
315  * the unlikely case that one or several URB packages get dropped by
316  * the device, the index will get out of sync. Try to recover by
317  * dropping the echo skb packets with older indexes.
318  *
319  * Return: zero if recovery was successful, -EINVAL otherwise.
320  */
321 static int es58x_can_get_echo_skb_recovery(struct net_device *netdev,
322 					   u32 rcv_packet_idx)
323 {
324 	struct es58x_priv *priv = es58x_priv(netdev);
325 	int ret = 0;
326 
327 	netdev->stats.tx_errors++;
328 
329 	if (net_ratelimit())
330 		netdev_warn(netdev,
331 			    "Bad echo packet index: %u. First index: %u, end index %u, num_echo_skb: %02u/%02u\n",
332 			    rcv_packet_idx, priv->tx_tail, priv->tx_head,
333 			    priv->tx_head - priv->tx_tail,
334 			    priv->can.echo_skb_max);
335 
336 	if ((s32)(rcv_packet_idx - priv->tx_tail) < 0) {
337 		if (net_ratelimit())
338 			netdev_warn(netdev,
339 				    "Received echo index is from the past. Ignoring it\n");
340 		ret = -EINVAL;
341 	} else if ((s32)(rcv_packet_idx - priv->tx_head) >= 0) {
342 		if (net_ratelimit())
343 			netdev_err(netdev,
344 				   "Received echo index is from the future. Ignoring it\n");
345 		ret = -EINVAL;
346 	} else {
347 		if (net_ratelimit())
348 			netdev_warn(netdev,
349 				    "Recovery: dropping %u echo skb from index %u to %u\n",
350 				    rcv_packet_idx - priv->tx_tail,
351 				    priv->tx_tail, rcv_packet_idx - 1);
352 		while (priv->tx_tail != rcv_packet_idx) {
353 			if (priv->tx_tail == priv->tx_head)
354 				return -EINVAL;
355 			es58x_can_free_echo_skb_tail(netdev);
356 		}
357 	}
358 	return ret;
359 }
360 
361 /**
362  * es58x_can_get_echo_skb() - Get the skb from the echo FIFO and loop
363  *	it back locally.
364  * @netdev: CAN network device.
365  * @rcv_packet_idx: Index of the first packet received from the device.
366  * @tstamps: Array of hardware timestamps received from a ES58X device.
367  * @pkts: Number of packets (and so, length of @tstamps).
368  *
369  * Callback function for when we receive a self reception
370  * acknowledgment.  Retrieves the skb from the echo FIFO, sets its
371  * hardware timestamp (the actual time it was sent) and loops it back
372  * locally.
373  *
374  * The device has to be active (i.e. network interface UP and not in
375  * bus off state or restarting).
376  *
377  * Packet indexes must be consecutive (i.e. index of first packet is
378  * @rcv_packet_idx, index of second packet is @rcv_packet_idx + 1 and
379  * index of last packet is @rcv_packet_idx + @pkts - 1).
380  *
381  * Return: zero on success.
382  */
383 int es58x_can_get_echo_skb(struct net_device *netdev, u32 rcv_packet_idx,
384 			   u64 *tstamps, unsigned int pkts)
385 {
386 	struct es58x_priv *priv = es58x_priv(netdev);
387 	unsigned int rx_total_frame_len = 0;
388 	unsigned int num_echo_skb = priv->tx_head - priv->tx_tail;
389 	int i;
390 	u16 fifo_mask = priv->es58x_dev->param->fifo_mask;
391 
392 	if (!netif_running(netdev)) {
393 		if (net_ratelimit())
394 			netdev_info(netdev,
395 				    "%s: %s is down, dropping %d echo packets\n",
396 				    __func__, netdev->name, pkts);
397 		netdev->stats.tx_dropped += pkts;
398 		return 0;
399 	} else if (!es58x_is_can_state_active(netdev)) {
400 		if (net_ratelimit())
401 			netdev_dbg(netdev,
402 				   "Bus is off or device is restarting. Ignoring %u echo packets from index %u\n",
403 				   pkts, rcv_packet_idx);
404 		/* stats.tx_dropped will be (or was already)
405 		 * incremented by
406 		 * drivers/net/can/net/dev.c:can_flush_echo_skb().
407 		 */
408 		return 0;
409 	} else if (num_echo_skb == 0) {
410 		if (net_ratelimit())
411 			netdev_warn(netdev,
412 				    "Received %u echo packets from index: %u but echo skb queue is empty.\n",
413 				    pkts, rcv_packet_idx);
414 		netdev->stats.tx_dropped += pkts;
415 		return 0;
416 	}
417 
418 	if (priv->tx_tail != rcv_packet_idx) {
419 		if (es58x_can_get_echo_skb_recovery(netdev, rcv_packet_idx) < 0) {
420 			if (net_ratelimit())
421 				netdev_warn(netdev,
422 					    "Could not find echo skb for echo packet index: %u\n",
423 					    rcv_packet_idx);
424 			return 0;
425 		}
426 	}
427 	if (num_echo_skb < pkts) {
428 		int pkts_drop = pkts - num_echo_skb;
429 
430 		if (net_ratelimit())
431 			netdev_err(netdev,
432 				   "Received %u echo packets but have only %d echo skb. Dropping %d echo skb\n",
433 				   pkts, num_echo_skb, pkts_drop);
434 		netdev->stats.tx_dropped += pkts_drop;
435 		pkts -= pkts_drop;
436 	}
437 
438 	for (i = 0; i < pkts; i++) {
439 		unsigned int skb_idx = priv->tx_tail & fifo_mask;
440 		struct sk_buff *skb = priv->can.echo_skb[skb_idx];
441 		unsigned int frame_len = 0;
442 
443 		if (skb)
444 			es58x_set_skb_timestamp(netdev, skb, tstamps[i]);
445 
446 		netdev->stats.tx_bytes += can_get_echo_skb(netdev, skb_idx,
447 							   &frame_len);
448 		rx_total_frame_len += frame_len;
449 
450 		priv->tx_tail++;
451 	}
452 
453 	netdev_completed_queue(netdev, pkts, rx_total_frame_len);
454 	netdev->stats.tx_packets += pkts;
455 
456 	priv->err_passive_before_rtx_success = 0;
457 	if (!es58x_is_echo_skb_threshold_reached(priv))
458 		netif_wake_queue(netdev);
459 
460 	return 0;
461 }
462 
463 /**
464  * es58x_can_reset_echo_fifo() - Reset the echo FIFO.
465  * @netdev: CAN network device.
466  *
467  * The echo_skb array of struct can_priv will be flushed by
468  * drivers/net/can/dev.c:can_flush_echo_skb(). This function resets
469  * the parameters of the struct es58x_priv of our device and reset the
470  * queue (c.f. BQL).
471  */
472 static void es58x_can_reset_echo_fifo(struct net_device *netdev)
473 {
474 	struct es58x_priv *priv = es58x_priv(netdev);
475 
476 	priv->tx_tail = 0;
477 	priv->tx_head = 0;
478 	priv->tx_urb = NULL;
479 	priv->err_passive_before_rtx_success = 0;
480 	netdev_reset_queue(netdev);
481 }
482 
483 /**
484  * es58x_flush_pending_tx_msg() - Reset the buffer for transmission messages.
485  * @netdev: CAN network device.
486  *
487  * es58x_start_xmit() will queue up to tx_bulk_max messages in
488  * &tx_urb buffer and do a bulk send of all messages in one single URB
489  * (c.f. xmit_more flag). When the device recovers from a bus off
490  * state or when the device stops, the tx_urb buffer might still have
491  * pending messages in it and thus need to be flushed.
492  */
493 static void es58x_flush_pending_tx_msg(struct net_device *netdev)
494 {
495 	struct es58x_priv *priv = es58x_priv(netdev);
496 	struct es58x_device *es58x_dev = priv->es58x_dev;
497 
498 	if (priv->tx_urb) {
499 		netdev_warn(netdev, "%s: dropping %d TX messages\n",
500 			    __func__, priv->tx_can_msg_cnt);
501 		netdev->stats.tx_dropped += priv->tx_can_msg_cnt;
502 		while (priv->tx_can_msg_cnt > 0) {
503 			unsigned int frame_len = 0;
504 			u16 fifo_mask = priv->es58x_dev->param->fifo_mask;
505 
506 			priv->tx_head--;
507 			priv->tx_can_msg_cnt--;
508 			can_free_echo_skb(netdev, priv->tx_head & fifo_mask,
509 					  &frame_len);
510 			netdev_completed_queue(netdev, 1, frame_len);
511 		}
512 		usb_anchor_urb(priv->tx_urb, &priv->es58x_dev->tx_urbs_idle);
513 		atomic_inc(&es58x_dev->tx_urbs_idle_cnt);
514 		usb_free_urb(priv->tx_urb);
515 	}
516 	priv->tx_urb = NULL;
517 }
518 
519 /**
520  * es58x_tx_ack_msg() - Handle acknowledgment messages.
521  * @netdev: CAN network device.
522  * @tx_free_entries: Number of free entries in the device transmit FIFO.
523  * @rx_cmd_ret_u32: error code as returned by the ES58X device.
524  *
525  * ES58X sends an acknowledgment message after a transmission request
526  * is done. This is mandatory for the ES581.4 but is optional (and
527  * deactivated in this driver) for the ES58X_FD family.
528  *
529  * Under normal circumstances, this function should never throw an
530  * error message.
531  *
532  * Return: zero on success, errno when any error occurs.
533  */
534 int es58x_tx_ack_msg(struct net_device *netdev, u16 tx_free_entries,
535 		     enum es58x_ret_u32 rx_cmd_ret_u32)
536 {
537 	struct es58x_priv *priv = es58x_priv(netdev);
538 
539 	if (tx_free_entries <= priv->es58x_dev->param->tx_bulk_max) {
540 		if (net_ratelimit())
541 			netdev_err(netdev,
542 				   "Only %d entries left in device queue, num_echo_skb: %d/%d\n",
543 				   tx_free_entries,
544 				   priv->tx_head - priv->tx_tail,
545 				   priv->can.echo_skb_max);
546 		netif_stop_queue(netdev);
547 	}
548 
549 	return es58x_rx_cmd_ret_u32(netdev, ES58X_RET_TYPE_TX_MSG,
550 				    rx_cmd_ret_u32);
551 }
552 
553 /**
554  * es58x_rx_can_msg() - Handle a received a CAN message.
555  * @netdev: CAN network device.
556  * @timestamp: Hardware time stamp (only relevant in rx branches).
557  * @data: CAN payload.
558  * @can_id: CAN ID.
559  * @es58x_flags: Please refer to enum es58x_flag.
560  * @dlc: Data Length Code (raw value).
561  *
562  * Fill up a CAN skb and post it.
563  *
564  * This function handles the case where the DLC of a classical CAN
565  * frame is greater than CAN_MAX_DLEN (c.f. the len8_dlc field of
566  * struct can_frame).
567  *
568  * Return: zero on success.
569  */
570 int es58x_rx_can_msg(struct net_device *netdev, u64 timestamp, const u8 *data,
571 		     canid_t can_id, enum es58x_flag es58x_flags, u8 dlc)
572 {
573 	struct canfd_frame *cfd;
574 	struct can_frame *ccf;
575 	struct sk_buff *skb;
576 	u8 len;
577 	bool is_can_fd = !!(es58x_flags & ES58X_FLAG_FD_DATA);
578 
579 	if (dlc > CAN_MAX_RAW_DLC) {
580 		netdev_err(netdev,
581 			   "%s: DLC is %d but maximum should be %d\n",
582 			   __func__, dlc, CAN_MAX_RAW_DLC);
583 		return -EMSGSIZE;
584 	}
585 
586 	if (is_can_fd) {
587 		len = can_fd_dlc2len(dlc);
588 		skb = alloc_canfd_skb(netdev, &cfd);
589 	} else {
590 		len = can_cc_dlc2len(dlc);
591 		skb = alloc_can_skb(netdev, &ccf);
592 		cfd = (struct canfd_frame *)ccf;
593 	}
594 	if (!skb) {
595 		netdev->stats.rx_dropped++;
596 		return 0;
597 	}
598 
599 	cfd->can_id = can_id;
600 	if (es58x_flags & ES58X_FLAG_EFF)
601 		cfd->can_id |= CAN_EFF_FLAG;
602 	if (is_can_fd) {
603 		cfd->len = len;
604 		if (es58x_flags & ES58X_FLAG_FD_BRS)
605 			cfd->flags |= CANFD_BRS;
606 		if (es58x_flags & ES58X_FLAG_FD_ESI)
607 			cfd->flags |= CANFD_ESI;
608 	} else {
609 		can_frame_set_cc_len(ccf, dlc, es58x_priv(netdev)->can.ctrlmode);
610 		if (es58x_flags & ES58X_FLAG_RTR) {
611 			ccf->can_id |= CAN_RTR_FLAG;
612 			len = 0;
613 		}
614 	}
615 	memcpy(cfd->data, data, len);
616 	netdev->stats.rx_packets++;
617 	netdev->stats.rx_bytes += len;
618 
619 	es58x_set_skb_timestamp(netdev, skb, timestamp);
620 	netif_rx(skb);
621 
622 	es58x_priv(netdev)->err_passive_before_rtx_success = 0;
623 
624 	return 0;
625 }
626 
627 /**
628  * es58x_rx_err_msg() - Handle a received CAN event or error message.
629  * @netdev: CAN network device.
630  * @error: Error code.
631  * @event: Event code.
632  * @timestamp: Timestamp received from a ES58X device.
633  *
634  * Handle the errors and events received by the ES58X device, create
635  * a CAN error skb and post it.
636  *
637  * In some rare cases the devices might get stuck alternating between
638  * CAN_STATE_ERROR_PASSIVE and CAN_STATE_ERROR_WARNING. To prevent
639  * this behavior, we force a bus off state if the device goes in
640  * CAN_STATE_ERROR_WARNING for ES58X_MAX_CONSECUTIVE_WARN consecutive
641  * times with no successful transmission or reception in between.
642  *
643  * Once the device is in bus off state, the only way to restart it is
644  * through the drivers/net/can/dev.c:can_restart() function. The
645  * device is technically capable to recover by itself under certain
646  * circumstances, however, allowing self recovery would create
647  * complex race conditions with drivers/net/can/dev.c:can_restart()
648  * and thus was not implemented. To activate automatic restart, please
649  * set the restart-ms parameter (e.g. ip link set can0 type can
650  * restart-ms 100).
651  *
652  * If the bus is really instable, this function would try to send a
653  * lot of log messages. Those are rate limited (i.e. you will see
654  * messages such as "net_ratelimit: XXX callbacks suppressed" in
655  * dmesg).
656  *
657  * Return: zero on success, errno when any error occurs.
658  */
659 int es58x_rx_err_msg(struct net_device *netdev, enum es58x_err error,
660 		     enum es58x_event event, u64 timestamp)
661 {
662 	struct es58x_priv *priv = es58x_priv(netdev);
663 	struct can_priv *can = netdev_priv(netdev);
664 	struct can_device_stats *can_stats = &can->can_stats;
665 	struct can_frame *cf = NULL;
666 	struct sk_buff *skb;
667 	int ret = 0;
668 
669 	if (!netif_running(netdev)) {
670 		if (net_ratelimit())
671 			netdev_info(netdev, "%s: %s is down, dropping packet\n",
672 				    __func__, netdev->name);
673 		netdev->stats.rx_dropped++;
674 		return 0;
675 	}
676 
677 	if (error == ES58X_ERR_OK && event == ES58X_EVENT_OK) {
678 		netdev_err(netdev, "%s: Both error and event are zero\n",
679 			   __func__);
680 		return -EINVAL;
681 	}
682 
683 	skb = alloc_can_err_skb(netdev, &cf);
684 
685 	switch (error) {
686 	case ES58X_ERR_OK:	/* 0: No error */
687 		break;
688 
689 	case ES58X_ERR_PROT_STUFF:
690 		if (net_ratelimit())
691 			netdev_dbg(netdev, "Error BITSTUFF\n");
692 		if (cf)
693 			cf->data[2] |= CAN_ERR_PROT_STUFF;
694 		break;
695 
696 	case ES58X_ERR_PROT_FORM:
697 		if (net_ratelimit())
698 			netdev_dbg(netdev, "Error FORMAT\n");
699 		if (cf)
700 			cf->data[2] |= CAN_ERR_PROT_FORM;
701 		break;
702 
703 	case ES58X_ERR_ACK:
704 		if (net_ratelimit())
705 			netdev_dbg(netdev, "Error ACK\n");
706 		if (cf)
707 			cf->can_id |= CAN_ERR_ACK;
708 		break;
709 
710 	case ES58X_ERR_PROT_BIT:
711 		if (net_ratelimit())
712 			netdev_dbg(netdev, "Error BIT\n");
713 		if (cf)
714 			cf->data[2] |= CAN_ERR_PROT_BIT;
715 		break;
716 
717 	case ES58X_ERR_PROT_CRC:
718 		if (net_ratelimit())
719 			netdev_dbg(netdev, "Error CRC\n");
720 		if (cf)
721 			cf->data[3] |= CAN_ERR_PROT_LOC_CRC_SEQ;
722 		break;
723 
724 	case ES58X_ERR_PROT_BIT1:
725 		if (net_ratelimit())
726 			netdev_dbg(netdev,
727 				   "Error: expected a recessive bit but monitored a dominant one\n");
728 		if (cf)
729 			cf->data[2] |= CAN_ERR_PROT_BIT1;
730 		break;
731 
732 	case ES58X_ERR_PROT_BIT0:
733 		if (net_ratelimit())
734 			netdev_dbg(netdev,
735 				   "Error expected a dominant bit but monitored a recessive one\n");
736 		if (cf)
737 			cf->data[2] |= CAN_ERR_PROT_BIT0;
738 		break;
739 
740 	case ES58X_ERR_PROT_OVERLOAD:
741 		if (net_ratelimit())
742 			netdev_dbg(netdev, "Error OVERLOAD\n");
743 		if (cf)
744 			cf->data[2] |= CAN_ERR_PROT_OVERLOAD;
745 		break;
746 
747 	case ES58X_ERR_PROT_UNSPEC:
748 		if (net_ratelimit())
749 			netdev_dbg(netdev, "Unspecified error\n");
750 		if (cf)
751 			cf->can_id |= CAN_ERR_PROT;
752 		break;
753 
754 	default:
755 		if (net_ratelimit())
756 			netdev_err(netdev,
757 				   "%s: Unspecified error code 0x%04X\n",
758 				   __func__, (int)error);
759 		if (cf)
760 			cf->can_id |= CAN_ERR_PROT;
761 		break;
762 	}
763 
764 	switch (event) {
765 	case ES58X_EVENT_OK:	/* 0: No event */
766 		break;
767 
768 	case ES58X_EVENT_CRTL_ACTIVE:
769 		if (can->state == CAN_STATE_BUS_OFF) {
770 			netdev_err(netdev,
771 				   "%s: state transition: BUS OFF -> ACTIVE\n",
772 				   __func__);
773 		}
774 		if (net_ratelimit())
775 			netdev_dbg(netdev, "Event CAN BUS ACTIVE\n");
776 		if (cf)
777 			cf->data[1] |= CAN_ERR_CRTL_ACTIVE;
778 		can->state = CAN_STATE_ERROR_ACTIVE;
779 		break;
780 
781 	case ES58X_EVENT_CRTL_PASSIVE:
782 		if (net_ratelimit())
783 			netdev_dbg(netdev, "Event CAN BUS PASSIVE\n");
784 		/* Either TX or RX error count reached passive state
785 		 * but we do not know which. Setting both flags by
786 		 * default.
787 		 */
788 		if (cf) {
789 			cf->data[1] |= CAN_ERR_CRTL_RX_PASSIVE;
790 			cf->data[1] |= CAN_ERR_CRTL_TX_PASSIVE;
791 		}
792 		if (can->state < CAN_STATE_BUS_OFF)
793 			can->state = CAN_STATE_ERROR_PASSIVE;
794 		can_stats->error_passive++;
795 		if (priv->err_passive_before_rtx_success < U8_MAX)
796 			priv->err_passive_before_rtx_success++;
797 		break;
798 
799 	case ES58X_EVENT_CRTL_WARNING:
800 		if (net_ratelimit())
801 			netdev_dbg(netdev, "Event CAN BUS WARNING\n");
802 		/* Either TX or RX error count reached warning state
803 		 * but we do not know which. Setting both flags by
804 		 * default.
805 		 */
806 		if (cf) {
807 			cf->data[1] |= CAN_ERR_CRTL_RX_WARNING;
808 			cf->data[1] |= CAN_ERR_CRTL_TX_WARNING;
809 		}
810 		if (can->state < CAN_STATE_BUS_OFF)
811 			can->state = CAN_STATE_ERROR_WARNING;
812 		can_stats->error_warning++;
813 		break;
814 
815 	case ES58X_EVENT_BUSOFF:
816 		if (net_ratelimit())
817 			netdev_dbg(netdev, "Event CAN BUS OFF\n");
818 		if (cf)
819 			cf->can_id |= CAN_ERR_BUSOFF;
820 		can_stats->bus_off++;
821 		netif_stop_queue(netdev);
822 		if (can->state != CAN_STATE_BUS_OFF) {
823 			can->state = CAN_STATE_BUS_OFF;
824 			can_bus_off(netdev);
825 			ret = can->do_set_mode(netdev, CAN_MODE_STOP);
826 		}
827 		break;
828 
829 	case ES58X_EVENT_SINGLE_WIRE:
830 		if (net_ratelimit())
831 			netdev_warn(netdev,
832 				    "Lost connection on either CAN high or CAN low\n");
833 		/* Lost connection on either CAN high or CAN
834 		 * low. Setting both flags by default.
835 		 */
836 		if (cf) {
837 			cf->data[4] |= CAN_ERR_TRX_CANH_NO_WIRE;
838 			cf->data[4] |= CAN_ERR_TRX_CANL_NO_WIRE;
839 		}
840 		break;
841 
842 	default:
843 		if (net_ratelimit())
844 			netdev_err(netdev,
845 				   "%s: Unspecified event code 0x%04X\n",
846 				   __func__, (int)event);
847 		if (cf)
848 			cf->can_id |= CAN_ERR_CRTL;
849 		break;
850 	}
851 
852 	if (cf) {
853 		if (cf->data[1])
854 			cf->can_id |= CAN_ERR_CRTL;
855 		if (cf->data[2] || cf->data[3]) {
856 			cf->can_id |= CAN_ERR_PROT;
857 			can_stats->bus_error++;
858 		}
859 		if (cf->data[4])
860 			cf->can_id |= CAN_ERR_TRX;
861 
862 		es58x_set_skb_timestamp(netdev, skb, timestamp);
863 		netif_rx(skb);
864 	}
865 
866 	if ((event & ES58X_EVENT_CRTL_PASSIVE) &&
867 	    priv->err_passive_before_rtx_success == ES58X_CONSECUTIVE_ERR_PASSIVE_MAX) {
868 		netdev_info(netdev,
869 			    "Got %d consecutive warning events with no successful RX or TX. Forcing bus-off\n",
870 			    priv->err_passive_before_rtx_success);
871 		return es58x_rx_err_msg(netdev, ES58X_ERR_OK,
872 					ES58X_EVENT_BUSOFF, timestamp);
873 	}
874 
875 	return ret;
876 }
877 
878 /**
879  * es58x_cmd_ret_desc() - Convert a command type to a string.
880  * @cmd_ret_type: Type of the command which triggered the return code.
881  *
882  * The final line (return "<unknown>") should not be reached. If this
883  * is the case, there is an implementation bug.
884  *
885  * Return: a readable description of the @cmd_ret_type.
886  */
887 static const char *es58x_cmd_ret_desc(enum es58x_ret_type cmd_ret_type)
888 {
889 	switch (cmd_ret_type) {
890 	case ES58X_RET_TYPE_SET_BITTIMING:
891 		return "Set bittiming";
892 	case ES58X_RET_TYPE_ENABLE_CHANNEL:
893 		return "Enable channel";
894 	case ES58X_RET_TYPE_DISABLE_CHANNEL:
895 		return "Disable channel";
896 	case ES58X_RET_TYPE_TX_MSG:
897 		return "Transmit message";
898 	case ES58X_RET_TYPE_RESET_RX:
899 		return "Reset RX";
900 	case ES58X_RET_TYPE_RESET_TX:
901 		return "Reset TX";
902 	case ES58X_RET_TYPE_DEVICE_ERR:
903 		return "Device error";
904 	}
905 
906 	return "<unknown>";
907 };
908 
909 /**
910  * es58x_rx_cmd_ret_u8() - Handle the command's return code received
911  *	from the ES58X device.
912  * @dev: Device, only used for the dev_XXX() print functions.
913  * @cmd_ret_type: Type of the command which triggered the return code.
914  * @rx_cmd_ret_u8: Command error code as returned by the ES58X device.
915  *
916  * Handles the 8 bits command return code. Those are specific to the
917  * ES581.4 device. The return value will eventually be used by
918  * es58x_handle_urb_cmd() function which will take proper actions in
919  * case of critical issues such and memory errors or bad CRC values.
920  *
921  * In contrast with es58x_rx_cmd_ret_u32(), the network device is
922  * unknown.
923  *
924  * Return: zero on success, return errno when any error occurs.
925  */
926 int es58x_rx_cmd_ret_u8(struct device *dev,
927 			enum es58x_ret_type cmd_ret_type,
928 			enum es58x_ret_u8 rx_cmd_ret_u8)
929 {
930 	const char *ret_desc = es58x_cmd_ret_desc(cmd_ret_type);
931 
932 	switch (rx_cmd_ret_u8) {
933 	case ES58X_RET_U8_OK:
934 		dev_dbg_ratelimited(dev, "%s: OK\n", ret_desc);
935 		return 0;
936 
937 	case ES58X_RET_U8_ERR_UNSPECIFIED_FAILURE:
938 		dev_err(dev, "%s: unspecified failure\n", ret_desc);
939 		return -EBADMSG;
940 
941 	case ES58X_RET_U8_ERR_NO_MEM:
942 		dev_err(dev, "%s: device ran out of memory\n", ret_desc);
943 		return -ENOMEM;
944 
945 	case ES58X_RET_U8_ERR_BAD_CRC:
946 		dev_err(dev, "%s: CRC of previous command is incorrect\n",
947 			ret_desc);
948 		return -EIO;
949 
950 	default:
951 		dev_err(dev, "%s: returned unknown value: 0x%02X\n",
952 			ret_desc, rx_cmd_ret_u8);
953 		return -EBADMSG;
954 	}
955 }
956 
957 /**
958  * es58x_rx_cmd_ret_u32() - Handle the command return code received
959  *	from the ES58X device.
960  * @netdev: CAN network device.
961  * @cmd_ret_type: Type of the command which triggered the return code.
962  * @rx_cmd_ret_u32: error code as returned by the ES58X device.
963  *
964  * Handles the 32 bits command return code. The return value will
965  * eventually be used by es58x_handle_urb_cmd() function which will
966  * take proper actions in case of critical issues such and memory
967  * errors or bad CRC values.
968  *
969  * Return: zero on success, errno when any error occurs.
970  */
971 int es58x_rx_cmd_ret_u32(struct net_device *netdev,
972 			 enum es58x_ret_type cmd_ret_type,
973 			 enum es58x_ret_u32 rx_cmd_ret_u32)
974 {
975 	struct es58x_priv *priv = es58x_priv(netdev);
976 	const struct es58x_operators *ops = priv->es58x_dev->ops;
977 	const char *ret_desc = es58x_cmd_ret_desc(cmd_ret_type);
978 
979 	switch (rx_cmd_ret_u32) {
980 	case ES58X_RET_U32_OK:
981 		switch (cmd_ret_type) {
982 		case ES58X_RET_TYPE_ENABLE_CHANNEL:
983 			es58x_can_reset_echo_fifo(netdev);
984 			priv->can.state = CAN_STATE_ERROR_ACTIVE;
985 			netif_wake_queue(netdev);
986 			netdev_info(netdev,
987 				    "%s: %s (Serial Number %s): CAN%d channel becomes ready\n",
988 				    ret_desc, priv->es58x_dev->udev->product,
989 				    priv->es58x_dev->udev->serial,
990 				    priv->channel_idx + 1);
991 			break;
992 
993 		case ES58X_RET_TYPE_TX_MSG:
994 			if (IS_ENABLED(CONFIG_VERBOSE_DEBUG) && net_ratelimit())
995 				netdev_vdbg(netdev, "%s: OK\n", ret_desc);
996 			break;
997 
998 		default:
999 			netdev_dbg(netdev, "%s: OK\n", ret_desc);
1000 			break;
1001 		}
1002 		return 0;
1003 
1004 	case ES58X_RET_U32_ERR_UNSPECIFIED_FAILURE:
1005 		if (cmd_ret_type == ES58X_RET_TYPE_ENABLE_CHANNEL) {
1006 			int ret;
1007 
1008 			netdev_warn(netdev,
1009 				    "%s: channel is already opened, closing and re-opening it to reflect new configuration\n",
1010 				    ret_desc);
1011 			ret = ops->disable_channel(es58x_priv(netdev));
1012 			if (ret)
1013 				return ret;
1014 			return ops->enable_channel(es58x_priv(netdev));
1015 		}
1016 		if (cmd_ret_type == ES58X_RET_TYPE_DISABLE_CHANNEL) {
1017 			netdev_info(netdev,
1018 				    "%s: channel is already closed\n", ret_desc);
1019 			return 0;
1020 		}
1021 		netdev_err(netdev,
1022 			   "%s: unspecified failure\n", ret_desc);
1023 		return -EBADMSG;
1024 
1025 	case ES58X_RET_U32_ERR_NO_MEM:
1026 		netdev_err(netdev, "%s: device ran out of memory\n", ret_desc);
1027 		return -ENOMEM;
1028 
1029 	case ES58X_RET_U32_WARN_PARAM_ADJUSTED:
1030 		netdev_warn(netdev,
1031 			    "%s: some incompatible parameters have been adjusted\n",
1032 			    ret_desc);
1033 		return 0;
1034 
1035 	case ES58X_RET_U32_WARN_TX_MAYBE_REORDER:
1036 		netdev_warn(netdev,
1037 			    "%s: TX messages might have been reordered\n",
1038 			    ret_desc);
1039 		return 0;
1040 
1041 	case ES58X_RET_U32_ERR_TIMEDOUT:
1042 		netdev_err(netdev, "%s: command timed out\n", ret_desc);
1043 		return -ETIMEDOUT;
1044 
1045 	case ES58X_RET_U32_ERR_FIFO_FULL:
1046 		netdev_warn(netdev, "%s: fifo is full\n", ret_desc);
1047 		return 0;
1048 
1049 	case ES58X_RET_U32_ERR_BAD_CONFIG:
1050 		netdev_err(netdev, "%s: bad configuration\n", ret_desc);
1051 		return -EINVAL;
1052 
1053 	case ES58X_RET_U32_ERR_NO_RESOURCE:
1054 		netdev_err(netdev, "%s: no resource available\n", ret_desc);
1055 		return -EBUSY;
1056 
1057 	default:
1058 		netdev_err(netdev, "%s returned unknown value: 0x%08X\n",
1059 			   ret_desc, rx_cmd_ret_u32);
1060 		return -EBADMSG;
1061 	}
1062 }
1063 
1064 /**
1065  * es58x_increment_rx_errors() - Increment the network devices' error
1066  *	count.
1067  * @es58x_dev: ES58X device.
1068  *
1069  * If an error occurs on the early stages on receiving an URB command,
1070  * we might not be able to figure out on which network device the
1071  * error occurred. In such case, we arbitrarily increment the error
1072  * count of all the network devices attached to our ES58X device.
1073  */
1074 static void es58x_increment_rx_errors(struct es58x_device *es58x_dev)
1075 {
1076 	int i;
1077 
1078 	for (i = 0; i < es58x_dev->num_can_ch; i++)
1079 		if (es58x_dev->netdev[i])
1080 			es58x_dev->netdev[i]->stats.rx_errors++;
1081 }
1082 
1083 /**
1084  * es58x_handle_urb_cmd() - Handle the URB command
1085  * @es58x_dev: ES58X device.
1086  * @urb_cmd: The URB command received from the ES58X device, might not
1087  *	be aligned.
1088  *
1089  * Sends the URB command to the device specific function. Manages the
1090  * errors thrown back by those functions.
1091  */
1092 static void es58x_handle_urb_cmd(struct es58x_device *es58x_dev,
1093 				 const union es58x_urb_cmd *urb_cmd)
1094 {
1095 	const struct es58x_operators *ops = es58x_dev->ops;
1096 	size_t cmd_len;
1097 	int i, ret;
1098 
1099 	ret = ops->handle_urb_cmd(es58x_dev, urb_cmd);
1100 	switch (ret) {
1101 	case 0:		/* OK */
1102 		return;
1103 
1104 	case -ENODEV:
1105 		dev_err_ratelimited(es58x_dev->dev, "Device is not ready\n");
1106 		break;
1107 
1108 	case -EINVAL:
1109 	case -EMSGSIZE:
1110 	case -EBADRQC:
1111 	case -EBADMSG:
1112 	case -ECHRNG:
1113 	case -ETIMEDOUT:
1114 		cmd_len = es58x_get_urb_cmd_len(es58x_dev,
1115 						ops->get_msg_len(urb_cmd));
1116 		dev_err(es58x_dev->dev,
1117 			"ops->handle_urb_cmd() returned error %pe",
1118 			ERR_PTR(ret));
1119 		es58x_print_hex_dump(urb_cmd, cmd_len);
1120 		break;
1121 
1122 	case -EFAULT:
1123 	case -ENOMEM:
1124 	case -EIO:
1125 	default:
1126 		dev_crit(es58x_dev->dev,
1127 			 "ops->handle_urb_cmd() returned error %pe, detaching all network devices\n",
1128 			 ERR_PTR(ret));
1129 		for (i = 0; i < es58x_dev->num_can_ch; i++)
1130 			if (es58x_dev->netdev[i])
1131 				netif_device_detach(es58x_dev->netdev[i]);
1132 		if (es58x_dev->ops->reset_device)
1133 			es58x_dev->ops->reset_device(es58x_dev);
1134 		break;
1135 	}
1136 
1137 	/* Because the urb command could not fully be parsed,
1138 	 * channel_id is not confirmed. Incrementing rx_errors count
1139 	 * of all channels.
1140 	 */
1141 	es58x_increment_rx_errors(es58x_dev);
1142 }
1143 
1144 /**
1145  * es58x_check_rx_urb() - Check the length and format of the URB command.
1146  * @es58x_dev: ES58X device.
1147  * @urb_cmd: The URB command received from the ES58X device, might not
1148  *	be aligned.
1149  * @urb_actual_len: The actual length of the URB command.
1150  *
1151  * Check if the first message of the received urb is valid, that is to
1152  * say that both the header and the length are coherent.
1153  *
1154  * Return:
1155  * the length of the first message of the URB on success.
1156  *
1157  * -ENODATA if the URB command is incomplete (in which case, the URB
1158  * command should be buffered and combined with the next URB to try to
1159  * reconstitute the URB command).
1160  *
1161  * -EOVERFLOW if the length is bigger than the maximum expected one.
1162  *
1163  * -EBADRQC if the start of frame does not match the expected value.
1164  */
1165 static signed int es58x_check_rx_urb(struct es58x_device *es58x_dev,
1166 				     const union es58x_urb_cmd *urb_cmd,
1167 				     u32 urb_actual_len)
1168 {
1169 	const struct device *dev = es58x_dev->dev;
1170 	const struct es58x_parameters *param = es58x_dev->param;
1171 	u16 sof, msg_len;
1172 	signed int urb_cmd_len, ret;
1173 
1174 	if (urb_actual_len < param->urb_cmd_header_len) {
1175 		dev_vdbg(dev,
1176 			 "%s: Received %d bytes [%*ph]: header incomplete\n",
1177 			 __func__, urb_actual_len, urb_actual_len,
1178 			 urb_cmd->raw_cmd);
1179 		return -ENODATA;
1180 	}
1181 
1182 	sof = get_unaligned_le16(&urb_cmd->sof);
1183 	if (sof != param->rx_start_of_frame) {
1184 		dev_err_ratelimited(es58x_dev->dev,
1185 				    "%s: Expected sequence 0x%04X for start of frame but got 0x%04X.\n",
1186 				    __func__, param->rx_start_of_frame, sof);
1187 		return -EBADRQC;
1188 	}
1189 
1190 	msg_len = es58x_dev->ops->get_msg_len(urb_cmd);
1191 	urb_cmd_len = es58x_get_urb_cmd_len(es58x_dev, msg_len);
1192 	if (urb_cmd_len > param->rx_urb_cmd_max_len) {
1193 		dev_err_ratelimited(es58x_dev->dev,
1194 				    "%s: Biggest expected size for rx urb_cmd is %u but receive a command of size %d\n",
1195 				    __func__,
1196 				    param->rx_urb_cmd_max_len, urb_cmd_len);
1197 		return -EOVERFLOW;
1198 	} else if (urb_actual_len < urb_cmd_len) {
1199 		dev_vdbg(dev, "%s: Received %02d/%02d bytes\n",
1200 			 __func__, urb_actual_len, urb_cmd_len);
1201 		return -ENODATA;
1202 	}
1203 
1204 	ret = es58x_check_crc(es58x_dev, urb_cmd, urb_cmd_len);
1205 	if (ret)
1206 		return ret;
1207 
1208 	return urb_cmd_len;
1209 }
1210 
1211 /**
1212  * es58x_copy_to_cmd_buf() - Copy an array to the URB command buffer.
1213  * @es58x_dev: ES58X device.
1214  * @raw_cmd: the buffer we want to copy.
1215  * @raw_cmd_len: length of @raw_cmd.
1216  *
1217  * Concatenates @raw_cmd_len bytes of @raw_cmd to the end of the URB
1218  * command buffer.
1219  *
1220  * Return: zero on success, -EMSGSIZE if not enough space is available
1221  * to do the copy.
1222  */
1223 static int es58x_copy_to_cmd_buf(struct es58x_device *es58x_dev,
1224 				 u8 *raw_cmd, int raw_cmd_len)
1225 {
1226 	if (es58x_dev->rx_cmd_buf_len + raw_cmd_len >
1227 	    es58x_dev->param->rx_urb_cmd_max_len)
1228 		return -EMSGSIZE;
1229 
1230 	memcpy(&es58x_dev->rx_cmd_buf.raw_cmd[es58x_dev->rx_cmd_buf_len],
1231 	       raw_cmd, raw_cmd_len);
1232 	es58x_dev->rx_cmd_buf_len += raw_cmd_len;
1233 
1234 	return 0;
1235 }
1236 
1237 /**
1238  * es58x_split_urb_try_recovery() - Try to recover bad URB sequences.
1239  * @es58x_dev: ES58X device.
1240  * @raw_cmd: pointer to the buffer we want to copy.
1241  * @raw_cmd_len: length of @raw_cmd.
1242  *
1243  * Under some rare conditions, we might get incorrect URBs from the
1244  * device. From our observations, one of the valid URB gets replaced
1245  * by one from the past. The full root cause is not identified.
1246  *
1247  * This function looks for the next start of frame in the urb buffer
1248  * in order to try to recover.
1249  *
1250  * Such behavior was not observed on the devices of the ES58X FD
1251  * family and only seems to impact the ES581.4.
1252  *
1253  * Return: the number of bytes dropped on success, -EBADMSG if recovery failed.
1254  */
1255 static int es58x_split_urb_try_recovery(struct es58x_device *es58x_dev,
1256 					u8 *raw_cmd, size_t raw_cmd_len)
1257 {
1258 	union es58x_urb_cmd *urb_cmd;
1259 	signed int urb_cmd_len;
1260 	u16 sof;
1261 	int dropped_bytes = 0;
1262 
1263 	es58x_increment_rx_errors(es58x_dev);
1264 
1265 	while (raw_cmd_len > sizeof(sof)) {
1266 		urb_cmd = (union es58x_urb_cmd *)raw_cmd;
1267 		sof = get_unaligned_le16(&urb_cmd->sof);
1268 
1269 		if (sof == es58x_dev->param->rx_start_of_frame) {
1270 			urb_cmd_len = es58x_check_rx_urb(es58x_dev,
1271 							 urb_cmd, raw_cmd_len);
1272 			if ((urb_cmd_len == -ENODATA) || urb_cmd_len > 0) {
1273 				dev_info_ratelimited(es58x_dev->dev,
1274 						     "Recovery successful! Dropped %d bytes (urb_cmd_len: %d)\n",
1275 						     dropped_bytes,
1276 						     urb_cmd_len);
1277 				return dropped_bytes;
1278 			}
1279 		}
1280 		raw_cmd++;
1281 		raw_cmd_len--;
1282 		dropped_bytes++;
1283 	}
1284 
1285 	dev_warn_ratelimited(es58x_dev->dev, "%s: Recovery failed\n", __func__);
1286 	return -EBADMSG;
1287 }
1288 
1289 /**
1290  * es58x_handle_incomplete_cmd() - Reconstitute an URB command from
1291  *	different URB pieces.
1292  * @es58x_dev: ES58X device.
1293  * @urb: last urb buffer received.
1294  *
1295  * The device might split the URB commands in an arbitrary amount of
1296  * pieces. This function concatenates those in an URB buffer until a
1297  * full URB command is reconstituted and consume it.
1298  *
1299  * Return:
1300  * number of bytes consumed from @urb if successful.
1301  *
1302  * -ENODATA if the URB command is still incomplete.
1303  *
1304  * -EBADMSG if the URB command is incorrect.
1305  */
1306 static signed int es58x_handle_incomplete_cmd(struct es58x_device *es58x_dev,
1307 					      struct urb *urb)
1308 {
1309 	size_t cpy_len;
1310 	signed int urb_cmd_len, tmp_cmd_buf_len, ret;
1311 
1312 	tmp_cmd_buf_len = es58x_dev->rx_cmd_buf_len;
1313 	cpy_len = min_t(int, es58x_dev->param->rx_urb_cmd_max_len -
1314 			es58x_dev->rx_cmd_buf_len, urb->actual_length);
1315 	ret = es58x_copy_to_cmd_buf(es58x_dev, urb->transfer_buffer, cpy_len);
1316 	if (ret < 0)
1317 		return ret;
1318 
1319 	urb_cmd_len = es58x_check_rx_urb(es58x_dev, &es58x_dev->rx_cmd_buf,
1320 					 es58x_dev->rx_cmd_buf_len);
1321 	if (urb_cmd_len == -ENODATA) {
1322 		return -ENODATA;
1323 	} else if (urb_cmd_len < 0) {
1324 		dev_err_ratelimited(es58x_dev->dev,
1325 				    "Could not reconstitute incomplete command from previous URB, dropping %d bytes\n",
1326 				    tmp_cmd_buf_len + urb->actual_length);
1327 		dev_err_ratelimited(es58x_dev->dev,
1328 				    "Error code: %pe, es58x_dev->rx_cmd_buf_len: %d, urb->actual_length: %u\n",
1329 				    ERR_PTR(urb_cmd_len),
1330 				    tmp_cmd_buf_len, urb->actual_length);
1331 		es58x_print_hex_dump(&es58x_dev->rx_cmd_buf, tmp_cmd_buf_len);
1332 		es58x_print_hex_dump(urb->transfer_buffer, urb->actual_length);
1333 		return urb->actual_length;
1334 	}
1335 
1336 	es58x_handle_urb_cmd(es58x_dev, &es58x_dev->rx_cmd_buf);
1337 	return urb_cmd_len - tmp_cmd_buf_len;	/* consumed length */
1338 }
1339 
1340 /**
1341  * es58x_split_urb() - Cut the received URB in individual URB commands.
1342  * @es58x_dev: ES58X device.
1343  * @urb: last urb buffer received.
1344  *
1345  * The device might send urb in bulk format (i.e. several URB commands
1346  * concatenated together). This function will split all the commands
1347  * contained in the urb.
1348  *
1349  * Return:
1350  * number of bytes consumed from @urb if successful.
1351  *
1352  * -ENODATA if the URB command is incomplete.
1353  *
1354  * -EBADMSG if the URB command is incorrect.
1355  */
1356 static signed int es58x_split_urb(struct es58x_device *es58x_dev,
1357 				  struct urb *urb)
1358 {
1359 	union es58x_urb_cmd *urb_cmd;
1360 	u8 *raw_cmd = urb->transfer_buffer;
1361 	s32 raw_cmd_len = urb->actual_length;
1362 	int ret;
1363 
1364 	if (es58x_dev->rx_cmd_buf_len != 0) {
1365 		ret = es58x_handle_incomplete_cmd(es58x_dev, urb);
1366 		if (ret != -ENODATA)
1367 			es58x_dev->rx_cmd_buf_len = 0;
1368 		if (ret < 0)
1369 			return ret;
1370 
1371 		raw_cmd += ret;
1372 		raw_cmd_len -= ret;
1373 	}
1374 
1375 	while (raw_cmd_len > 0) {
1376 		if (raw_cmd[0] == ES58X_HEARTBEAT) {
1377 			raw_cmd++;
1378 			raw_cmd_len--;
1379 			continue;
1380 		}
1381 		urb_cmd = (union es58x_urb_cmd *)raw_cmd;
1382 		ret = es58x_check_rx_urb(es58x_dev, urb_cmd, raw_cmd_len);
1383 		if (ret > 0) {
1384 			es58x_handle_urb_cmd(es58x_dev, urb_cmd);
1385 		} else if (ret == -ENODATA) {
1386 			es58x_copy_to_cmd_buf(es58x_dev, raw_cmd, raw_cmd_len);
1387 			return -ENODATA;
1388 		} else if (ret < 0) {
1389 			ret = es58x_split_urb_try_recovery(es58x_dev, raw_cmd,
1390 							   raw_cmd_len);
1391 			if (ret < 0)
1392 				return ret;
1393 		}
1394 		raw_cmd += ret;
1395 		raw_cmd_len -= ret;
1396 	}
1397 
1398 	return 0;
1399 }
1400 
1401 /**
1402  * es58x_read_bulk_callback() - Callback for reading data from device.
1403  * @urb: last urb buffer received.
1404  *
1405  * This function gets eventually called each time an URB is received
1406  * from the ES58X device.
1407  *
1408  * Checks urb status, calls read function and resubmits urb read
1409  * operation.
1410  */
1411 static void es58x_read_bulk_callback(struct urb *urb)
1412 {
1413 	struct es58x_device *es58x_dev = urb->context;
1414 	const struct device *dev = es58x_dev->dev;
1415 	int i, ret;
1416 
1417 	switch (urb->status) {
1418 	case 0:		/* success */
1419 		break;
1420 
1421 	case -EOVERFLOW:
1422 		dev_err_ratelimited(dev, "%s: error %pe\n",
1423 				    __func__, ERR_PTR(urb->status));
1424 		es58x_print_hex_dump_debug(urb->transfer_buffer,
1425 					   urb->transfer_buffer_length);
1426 		goto resubmit_urb;
1427 
1428 	case -EPROTO:
1429 		dev_warn_ratelimited(dev, "%s: error %pe. Device unplugged?\n",
1430 				     __func__, ERR_PTR(urb->status));
1431 		goto free_urb;
1432 
1433 	case -ENOENT:
1434 	case -EPIPE:
1435 		dev_err_ratelimited(dev, "%s: error %pe\n",
1436 				    __func__, ERR_PTR(urb->status));
1437 		goto free_urb;
1438 
1439 	case -ESHUTDOWN:
1440 		dev_dbg_ratelimited(dev, "%s: error %pe\n",
1441 				    __func__, ERR_PTR(urb->status));
1442 		goto free_urb;
1443 
1444 	default:
1445 		dev_err_ratelimited(dev, "%s: error %pe\n",
1446 				    __func__, ERR_PTR(urb->status));
1447 		goto resubmit_urb;
1448 	}
1449 
1450 	ret = es58x_split_urb(es58x_dev, urb);
1451 	if ((ret != -ENODATA) && ret < 0) {
1452 		dev_err(es58x_dev->dev, "es58x_split_urb() returned error %pe",
1453 			ERR_PTR(ret));
1454 		es58x_print_hex_dump_debug(urb->transfer_buffer,
1455 					   urb->actual_length);
1456 
1457 		/* Because the urb command could not be parsed,
1458 		 * channel_id is not confirmed. Incrementing rx_errors
1459 		 * count of all channels.
1460 		 */
1461 		es58x_increment_rx_errors(es58x_dev);
1462 	}
1463 
1464  resubmit_urb:
1465 	usb_fill_bulk_urb(urb, es58x_dev->udev, es58x_dev->rx_pipe,
1466 			  urb->transfer_buffer, urb->transfer_buffer_length,
1467 			  es58x_read_bulk_callback, es58x_dev);
1468 
1469 	ret = usb_submit_urb(urb, GFP_ATOMIC);
1470 	if (ret == -ENODEV) {
1471 		for (i = 0; i < es58x_dev->num_can_ch; i++)
1472 			if (es58x_dev->netdev[i])
1473 				netif_device_detach(es58x_dev->netdev[i]);
1474 	} else if (ret)
1475 		dev_err_ratelimited(dev,
1476 				    "Failed resubmitting read bulk urb: %pe\n",
1477 				    ERR_PTR(ret));
1478 	return;
1479 
1480  free_urb:
1481 	usb_free_coherent(urb->dev, urb->transfer_buffer_length,
1482 			  urb->transfer_buffer, urb->transfer_dma);
1483 }
1484 
1485 /**
1486  * es58x_write_bulk_callback() - Callback after writing data to the device.
1487  * @urb: urb buffer which was previously submitted.
1488  *
1489  * This function gets eventually called each time an URB was sent to
1490  * the ES58X device.
1491  *
1492  * Puts the @urb back to the urbs idle anchor and tries to restart the
1493  * network queue.
1494  */
1495 static void es58x_write_bulk_callback(struct urb *urb)
1496 {
1497 	struct net_device *netdev = urb->context;
1498 	struct es58x_device *es58x_dev = es58x_priv(netdev)->es58x_dev;
1499 
1500 	switch (urb->status) {
1501 	case 0:		/* success */
1502 		break;
1503 
1504 	case -EOVERFLOW:
1505 		if (net_ratelimit())
1506 			netdev_err(netdev, "%s: error %pe\n",
1507 				   __func__, ERR_PTR(urb->status));
1508 		es58x_print_hex_dump(urb->transfer_buffer,
1509 				     urb->transfer_buffer_length);
1510 		break;
1511 
1512 	case -ENOENT:
1513 		if (net_ratelimit())
1514 			netdev_dbg(netdev, "%s: error %pe\n",
1515 				   __func__, ERR_PTR(urb->status));
1516 		usb_free_coherent(urb->dev,
1517 				  es58x_dev->param->tx_urb_cmd_max_len,
1518 				  urb->transfer_buffer, urb->transfer_dma);
1519 		return;
1520 
1521 	default:
1522 		if (net_ratelimit())
1523 			netdev_info(netdev, "%s: error %pe\n",
1524 				    __func__, ERR_PTR(urb->status));
1525 		break;
1526 	}
1527 
1528 	usb_anchor_urb(urb, &es58x_dev->tx_urbs_idle);
1529 	atomic_inc(&es58x_dev->tx_urbs_idle_cnt);
1530 }
1531 
1532 /**
1533  * es58x_alloc_urb() - Allocate memory for an URB and its transfer
1534  *	buffer.
1535  * @es58x_dev: ES58X device.
1536  * @urb: URB to be allocated.
1537  * @buf: used to return DMA address of buffer.
1538  * @buf_len: requested buffer size.
1539  * @mem_flags: affect whether allocation may block.
1540  *
1541  * Allocates an URB and its @transfer_buffer and set its @transfer_dma
1542  * address.
1543  *
1544  * This function is used at start-up to allocate all RX URBs at once
1545  * and during run time for TX URBs.
1546  *
1547  * Return: zero on success, -ENOMEM if no memory is available.
1548  */
1549 static int es58x_alloc_urb(struct es58x_device *es58x_dev, struct urb **urb,
1550 			   u8 **buf, size_t buf_len, gfp_t mem_flags)
1551 {
1552 	*urb = usb_alloc_urb(0, mem_flags);
1553 	if (!*urb) {
1554 		dev_err(es58x_dev->dev, "No memory left for URBs\n");
1555 		return -ENOMEM;
1556 	}
1557 
1558 	*buf = usb_alloc_coherent(es58x_dev->udev, buf_len,
1559 				  mem_flags, &(*urb)->transfer_dma);
1560 	if (!*buf) {
1561 		dev_err(es58x_dev->dev, "No memory left for USB buffer\n");
1562 		usb_free_urb(*urb);
1563 		return -ENOMEM;
1564 	}
1565 
1566 	(*urb)->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
1567 
1568 	return 0;
1569 }
1570 
1571 /**
1572  * es58x_get_tx_urb() - Get an URB for transmission.
1573  * @es58x_dev: ES58X device.
1574  *
1575  * Gets an URB from the idle urbs anchor or allocate a new one if the
1576  * anchor is empty.
1577  *
1578  * If there are more than ES58X_TX_URBS_MAX in the idle anchor, do
1579  * some garbage collection. The garbage collection is done here
1580  * instead of within es58x_write_bulk_callback() because
1581  * usb_free_coherent() should not be used in IRQ context:
1582  * c.f. WARN_ON(irqs_disabled()) in dma_free_attrs().
1583  *
1584  * Return: a pointer to an URB on success, NULL if no memory is
1585  * available.
1586  */
1587 static struct urb *es58x_get_tx_urb(struct es58x_device *es58x_dev)
1588 {
1589 	atomic_t *idle_cnt = &es58x_dev->tx_urbs_idle_cnt;
1590 	struct urb *urb = usb_get_from_anchor(&es58x_dev->tx_urbs_idle);
1591 
1592 	if (!urb) {
1593 		size_t tx_buf_len;
1594 		u8 *buf;
1595 
1596 		tx_buf_len = es58x_dev->param->tx_urb_cmd_max_len;
1597 		if (es58x_alloc_urb(es58x_dev, &urb, &buf, tx_buf_len,
1598 				    GFP_ATOMIC))
1599 			return NULL;
1600 
1601 		usb_fill_bulk_urb(urb, es58x_dev->udev, es58x_dev->tx_pipe,
1602 				  buf, tx_buf_len, NULL, NULL);
1603 		return urb;
1604 	}
1605 
1606 	while (atomic_dec_return(idle_cnt) > ES58X_TX_URBS_MAX) {
1607 		/* Garbage collector */
1608 		struct urb *tmp = usb_get_from_anchor(&es58x_dev->tx_urbs_idle);
1609 
1610 		if (!tmp)
1611 			break;
1612 		usb_free_coherent(tmp->dev,
1613 				  es58x_dev->param->tx_urb_cmd_max_len,
1614 				  tmp->transfer_buffer, tmp->transfer_dma);
1615 		usb_free_urb(tmp);
1616 	}
1617 
1618 	return urb;
1619 }
1620 
1621 /**
1622  * es58x_submit_urb() - Send data to the device.
1623  * @es58x_dev: ES58X device.
1624  * @urb: URB to be sent.
1625  * @netdev: CAN network device.
1626  *
1627  * Return: zero on success, errno when any error occurs.
1628  */
1629 static int es58x_submit_urb(struct es58x_device *es58x_dev, struct urb *urb,
1630 			    struct net_device *netdev)
1631 {
1632 	int ret;
1633 
1634 	es58x_set_crc(urb->transfer_buffer, urb->transfer_buffer_length);
1635 	usb_fill_bulk_urb(urb, es58x_dev->udev, es58x_dev->tx_pipe,
1636 			  urb->transfer_buffer, urb->transfer_buffer_length,
1637 			  es58x_write_bulk_callback, netdev);
1638 	usb_anchor_urb(urb, &es58x_dev->tx_urbs_busy);
1639 	ret = usb_submit_urb(urb, GFP_ATOMIC);
1640 	if (ret) {
1641 		netdev_err(netdev, "%s: USB send urb failure: %pe\n",
1642 			   __func__, ERR_PTR(ret));
1643 		usb_unanchor_urb(urb);
1644 		usb_free_coherent(urb->dev,
1645 				  es58x_dev->param->tx_urb_cmd_max_len,
1646 				  urb->transfer_buffer, urb->transfer_dma);
1647 	}
1648 	usb_free_urb(urb);
1649 
1650 	return ret;
1651 }
1652 
1653 /**
1654  * es58x_send_msg() - Prepare an URB and submit it.
1655  * @es58x_dev: ES58X device.
1656  * @cmd_type: Command type.
1657  * @cmd_id: Command ID.
1658  * @msg: ES58X message to be sent.
1659  * @msg_len: Length of @msg.
1660  * @channel_idx: Index of the network device.
1661  *
1662  * Creates an URB command from a given message, sets the header and the
1663  * CRC and then submits it.
1664  *
1665  * Return: zero on success, errno when any error occurs.
1666  */
1667 int es58x_send_msg(struct es58x_device *es58x_dev, u8 cmd_type, u8 cmd_id,
1668 		   const void *msg, u16 msg_len, int channel_idx)
1669 {
1670 	struct net_device *netdev;
1671 	union es58x_urb_cmd *urb_cmd;
1672 	struct urb *urb;
1673 	int urb_cmd_len;
1674 
1675 	if (channel_idx == ES58X_CHANNEL_IDX_NA)
1676 		netdev = es58x_dev->netdev[0];	/* Default to first channel */
1677 	else
1678 		netdev = es58x_dev->netdev[channel_idx];
1679 
1680 	urb_cmd_len = es58x_get_urb_cmd_len(es58x_dev, msg_len);
1681 	if (urb_cmd_len > es58x_dev->param->tx_urb_cmd_max_len)
1682 		return -EOVERFLOW;
1683 
1684 	urb = es58x_get_tx_urb(es58x_dev);
1685 	if (!urb)
1686 		return -ENOMEM;
1687 
1688 	urb_cmd = urb->transfer_buffer;
1689 	es58x_dev->ops->fill_urb_header(urb_cmd, cmd_type, cmd_id,
1690 					channel_idx, msg_len);
1691 	memcpy(&urb_cmd->raw_cmd[es58x_dev->param->urb_cmd_header_len],
1692 	       msg, msg_len);
1693 	urb->transfer_buffer_length = urb_cmd_len;
1694 
1695 	return es58x_submit_urb(es58x_dev, urb, netdev);
1696 }
1697 
1698 /**
1699  * es58x_alloc_rx_urbs() - Allocate RX URBs.
1700  * @es58x_dev: ES58X device.
1701  *
1702  * Allocate URBs for reception and anchor them.
1703  *
1704  * Return: zero on success, errno when any error occurs.
1705  */
1706 static int es58x_alloc_rx_urbs(struct es58x_device *es58x_dev)
1707 {
1708 	const struct device *dev = es58x_dev->dev;
1709 	const struct es58x_parameters *param = es58x_dev->param;
1710 	size_t rx_buf_len = es58x_dev->rx_max_packet_size;
1711 	struct urb *urb;
1712 	u8 *buf;
1713 	int i;
1714 	int ret = -EINVAL;
1715 
1716 	for (i = 0; i < param->rx_urb_max; i++) {
1717 		ret = es58x_alloc_urb(es58x_dev, &urb, &buf, rx_buf_len,
1718 				      GFP_KERNEL);
1719 		if (ret)
1720 			break;
1721 
1722 		usb_fill_bulk_urb(urb, es58x_dev->udev, es58x_dev->rx_pipe,
1723 				  buf, rx_buf_len, es58x_read_bulk_callback,
1724 				  es58x_dev);
1725 		usb_anchor_urb(urb, &es58x_dev->rx_urbs);
1726 
1727 		ret = usb_submit_urb(urb, GFP_KERNEL);
1728 		if (ret) {
1729 			usb_unanchor_urb(urb);
1730 			usb_free_coherent(es58x_dev->udev, rx_buf_len,
1731 					  buf, urb->transfer_dma);
1732 			usb_free_urb(urb);
1733 			break;
1734 		}
1735 		usb_free_urb(urb);
1736 	}
1737 
1738 	if (i == 0) {
1739 		dev_err(dev, "%s: Could not setup any rx URBs\n", __func__);
1740 		return ret;
1741 	}
1742 	dev_dbg(dev, "%s: Allocated %d rx URBs each of size %zu\n",
1743 		__func__, i, rx_buf_len);
1744 
1745 	return ret;
1746 }
1747 
1748 /**
1749  * es58x_free_urbs() - Free all the TX and RX URBs.
1750  * @es58x_dev: ES58X device.
1751  */
1752 static void es58x_free_urbs(struct es58x_device *es58x_dev)
1753 {
1754 	struct urb *urb;
1755 
1756 	if (!usb_wait_anchor_empty_timeout(&es58x_dev->tx_urbs_busy, 1000)) {
1757 		dev_err(es58x_dev->dev, "%s: Timeout, some TX urbs still remain\n",
1758 			__func__);
1759 		usb_kill_anchored_urbs(&es58x_dev->tx_urbs_busy);
1760 	}
1761 
1762 	while ((urb = usb_get_from_anchor(&es58x_dev->tx_urbs_idle)) != NULL) {
1763 		usb_free_coherent(urb->dev, es58x_dev->param->tx_urb_cmd_max_len,
1764 				  urb->transfer_buffer, urb->transfer_dma);
1765 		usb_free_urb(urb);
1766 		atomic_dec(&es58x_dev->tx_urbs_idle_cnt);
1767 	}
1768 	if (atomic_read(&es58x_dev->tx_urbs_idle_cnt))
1769 		dev_err(es58x_dev->dev,
1770 			"All idle urbs were freed but tx_urb_idle_cnt is %d\n",
1771 			atomic_read(&es58x_dev->tx_urbs_idle_cnt));
1772 
1773 	usb_kill_anchored_urbs(&es58x_dev->rx_urbs);
1774 }
1775 
1776 /**
1777  * es58x_open() - Enable the network device.
1778  * @netdev: CAN network device.
1779  *
1780  * Called when the network transitions to the up state. Allocate the
1781  * URB resources if needed and open the channel.
1782  *
1783  * Return: zero on success, errno when any error occurs.
1784  */
1785 static int es58x_open(struct net_device *netdev)
1786 {
1787 	struct es58x_device *es58x_dev = es58x_priv(netdev)->es58x_dev;
1788 	int ret;
1789 
1790 	if (!es58x_dev->opened_channel_cnt) {
1791 		ret = es58x_alloc_rx_urbs(es58x_dev);
1792 		if (ret)
1793 			return ret;
1794 
1795 		ret = es58x_set_realtime_diff_ns(es58x_dev);
1796 		if (ret)
1797 			goto free_urbs;
1798 	}
1799 
1800 	ret = open_candev(netdev);
1801 	if (ret)
1802 		goto free_urbs;
1803 
1804 	ret = es58x_dev->ops->enable_channel(es58x_priv(netdev));
1805 	if (ret)
1806 		goto free_urbs;
1807 
1808 	es58x_dev->opened_channel_cnt++;
1809 	netif_start_queue(netdev);
1810 
1811 	return ret;
1812 
1813  free_urbs:
1814 	if (!es58x_dev->opened_channel_cnt)
1815 		es58x_free_urbs(es58x_dev);
1816 	netdev_err(netdev, "%s: Could not open the network device: %pe\n",
1817 		   __func__, ERR_PTR(ret));
1818 
1819 	return ret;
1820 }
1821 
1822 /**
1823  * es58x_stop() - Disable the network device.
1824  * @netdev: CAN network device.
1825  *
1826  * Called when the network transitions to the down state. If all the
1827  * channels of the device are closed, free the URB resources which are
1828  * not needed anymore.
1829  *
1830  * Return: zero on success, errno when any error occurs.
1831  */
1832 static int es58x_stop(struct net_device *netdev)
1833 {
1834 	struct es58x_priv *priv = es58x_priv(netdev);
1835 	struct es58x_device *es58x_dev = priv->es58x_dev;
1836 	int ret;
1837 
1838 	netif_stop_queue(netdev);
1839 	ret = es58x_dev->ops->disable_channel(priv);
1840 	if (ret)
1841 		return ret;
1842 
1843 	priv->can.state = CAN_STATE_STOPPED;
1844 	es58x_can_reset_echo_fifo(netdev);
1845 	close_candev(netdev);
1846 
1847 	es58x_flush_pending_tx_msg(netdev);
1848 
1849 	es58x_dev->opened_channel_cnt--;
1850 	if (!es58x_dev->opened_channel_cnt)
1851 		es58x_free_urbs(es58x_dev);
1852 
1853 	return 0;
1854 }
1855 
1856 /**
1857  * es58x_xmit_commit() - Send the bulk urb.
1858  * @netdev: CAN network device.
1859  *
1860  * Do the bulk send. This function should be called only once by bulk
1861  * transmission.
1862  *
1863  * Return: zero on success, errno when any error occurs.
1864  */
1865 static int es58x_xmit_commit(struct net_device *netdev)
1866 {
1867 	struct es58x_priv *priv = es58x_priv(netdev);
1868 	int ret;
1869 
1870 	if (!es58x_is_can_state_active(netdev))
1871 		return -ENETDOWN;
1872 
1873 	if (es58x_is_echo_skb_threshold_reached(priv))
1874 		netif_stop_queue(netdev);
1875 
1876 	ret = es58x_submit_urb(priv->es58x_dev, priv->tx_urb, netdev);
1877 	if (ret == 0)
1878 		priv->tx_urb = NULL;
1879 
1880 	return ret;
1881 }
1882 
1883 /**
1884  * es58x_xmit_more() - Can we put more packets?
1885  * @priv: ES58X private parameters related to the network device.
1886  *
1887  * Return: true if we can put more, false if it is time to send.
1888  */
1889 static bool es58x_xmit_more(struct es58x_priv *priv)
1890 {
1891 	unsigned int free_slots =
1892 	    priv->can.echo_skb_max - (priv->tx_head - priv->tx_tail);
1893 
1894 	return netdev_xmit_more() && free_slots > 0 &&
1895 		priv->tx_can_msg_cnt < priv->es58x_dev->param->tx_bulk_max;
1896 }
1897 
1898 /**
1899  * es58x_start_xmit() - Transmit an skb.
1900  * @skb: socket buffer of a CAN message.
1901  * @netdev: CAN network device.
1902  *
1903  * Called when a packet needs to be transmitted.
1904  *
1905  * This function relies on Byte Queue Limits (BQL). The main benefit
1906  * is to increase the throughput by allowing bulk transfers
1907  * (c.f. xmit_more flag).
1908  *
1909  * Queues up to tx_bulk_max messages in &tx_urb buffer and does
1910  * a bulk send of all messages in one single URB.
1911  *
1912  * Return: NETDEV_TX_OK regardless of if we could transmit the @skb or
1913  *	had to drop it.
1914  */
1915 static netdev_tx_t es58x_start_xmit(struct sk_buff *skb,
1916 				    struct net_device *netdev)
1917 {
1918 	struct es58x_priv *priv = es58x_priv(netdev);
1919 	struct es58x_device *es58x_dev = priv->es58x_dev;
1920 	unsigned int frame_len;
1921 	int ret;
1922 
1923 	if (can_dropped_invalid_skb(netdev, skb)) {
1924 		if (priv->tx_urb)
1925 			goto xmit_commit;
1926 		return NETDEV_TX_OK;
1927 	}
1928 
1929 	if (priv->tx_urb && priv->tx_can_msg_is_fd != can_is_canfd_skb(skb)) {
1930 		/* Can not do bulk send with mixed CAN and CAN FD frames. */
1931 		ret = es58x_xmit_commit(netdev);
1932 		if (ret)
1933 			goto drop_skb;
1934 	}
1935 
1936 	if (!priv->tx_urb) {
1937 		priv->tx_urb = es58x_get_tx_urb(es58x_dev);
1938 		if (!priv->tx_urb) {
1939 			ret = -ENOMEM;
1940 			goto drop_skb;
1941 		}
1942 		priv->tx_can_msg_cnt = 0;
1943 		priv->tx_can_msg_is_fd = can_is_canfd_skb(skb);
1944 	}
1945 
1946 	ret = es58x_dev->ops->tx_can_msg(priv, skb);
1947 	if (ret)
1948 		goto drop_skb;
1949 
1950 	frame_len = can_skb_get_frame_len(skb);
1951 	ret = can_put_echo_skb(skb, netdev,
1952 			       priv->tx_head & es58x_dev->param->fifo_mask,
1953 			       frame_len);
1954 	if (ret)
1955 		goto xmit_failure;
1956 	netdev_sent_queue(netdev, frame_len);
1957 
1958 	priv->tx_head++;
1959 	priv->tx_can_msg_cnt++;
1960 
1961  xmit_commit:
1962 	if (!es58x_xmit_more(priv)) {
1963 		ret = es58x_xmit_commit(netdev);
1964 		if (ret)
1965 			goto xmit_failure;
1966 	}
1967 
1968 	return NETDEV_TX_OK;
1969 
1970  drop_skb:
1971 	dev_kfree_skb(skb);
1972 	netdev->stats.tx_dropped++;
1973  xmit_failure:
1974 	netdev_warn(netdev, "%s: send message failure: %pe\n",
1975 		    __func__, ERR_PTR(ret));
1976 	netdev->stats.tx_errors++;
1977 	es58x_flush_pending_tx_msg(netdev);
1978 	return NETDEV_TX_OK;
1979 }
1980 
1981 static const struct net_device_ops es58x_netdev_ops = {
1982 	.ndo_open = es58x_open,
1983 	.ndo_stop = es58x_stop,
1984 	.ndo_start_xmit = es58x_start_xmit
1985 };
1986 
1987 /**
1988  * es58x_set_mode() - Change network device mode.
1989  * @netdev: CAN network device.
1990  * @mode: either %CAN_MODE_START, %CAN_MODE_STOP or %CAN_MODE_SLEEP
1991  *
1992  * Currently, this function is only used to stop and restart the
1993  * channel during a bus off event (c.f. es58x_rx_err_msg() and
1994  * drivers/net/can/dev.c:can_restart() which are the two only
1995  * callers).
1996  *
1997  * Return: zero on success, errno when any error occurs.
1998  */
1999 static int es58x_set_mode(struct net_device *netdev, enum can_mode mode)
2000 {
2001 	struct es58x_priv *priv = es58x_priv(netdev);
2002 
2003 	switch (mode) {
2004 	case CAN_MODE_START:
2005 		switch (priv->can.state) {
2006 		case CAN_STATE_BUS_OFF:
2007 			return priv->es58x_dev->ops->enable_channel(priv);
2008 
2009 		case CAN_STATE_STOPPED:
2010 			return es58x_open(netdev);
2011 
2012 		case CAN_STATE_ERROR_ACTIVE:
2013 		case CAN_STATE_ERROR_WARNING:
2014 		case CAN_STATE_ERROR_PASSIVE:
2015 		default:
2016 			return 0;
2017 		}
2018 
2019 	case CAN_MODE_STOP:
2020 		switch (priv->can.state) {
2021 		case CAN_STATE_STOPPED:
2022 			return 0;
2023 
2024 		case CAN_STATE_ERROR_ACTIVE:
2025 		case CAN_STATE_ERROR_WARNING:
2026 		case CAN_STATE_ERROR_PASSIVE:
2027 		case CAN_STATE_BUS_OFF:
2028 		default:
2029 			return priv->es58x_dev->ops->disable_channel(priv);
2030 		}
2031 
2032 	case CAN_MODE_SLEEP:
2033 	default:
2034 		return -EOPNOTSUPP;
2035 	}
2036 }
2037 
2038 /**
2039  * es58x_init_priv() - Initialize private parameters.
2040  * @es58x_dev: ES58X device.
2041  * @priv: ES58X private parameters related to the network device.
2042  * @channel_idx: Index of the network device.
2043  */
2044 static void es58x_init_priv(struct es58x_device *es58x_dev,
2045 			    struct es58x_priv *priv, int channel_idx)
2046 {
2047 	const struct es58x_parameters *param = es58x_dev->param;
2048 	struct can_priv *can = &priv->can;
2049 
2050 	priv->es58x_dev = es58x_dev;
2051 	priv->channel_idx = channel_idx;
2052 	priv->tx_urb = NULL;
2053 	priv->tx_can_msg_cnt = 0;
2054 
2055 	can->bittiming_const = param->bittiming_const;
2056 	if (param->ctrlmode_supported & CAN_CTRLMODE_FD) {
2057 		can->data_bittiming_const = param->data_bittiming_const;
2058 		can->tdc_const = param->tdc_const;
2059 	}
2060 	can->bitrate_max = param->bitrate_max;
2061 	can->clock = param->clock;
2062 	can->state = CAN_STATE_STOPPED;
2063 	can->ctrlmode_supported = param->ctrlmode_supported;
2064 	can->do_set_mode = es58x_set_mode;
2065 }
2066 
2067 /**
2068  * es58x_init_netdev() - Initialize the network device.
2069  * @es58x_dev: ES58X device.
2070  * @channel_idx: Index of the network device.
2071  *
2072  * Return: zero on success, errno when any error occurs.
2073  */
2074 static int es58x_init_netdev(struct es58x_device *es58x_dev, int channel_idx)
2075 {
2076 	struct net_device *netdev;
2077 	struct device *dev = es58x_dev->dev;
2078 	int ret;
2079 
2080 	netdev = alloc_candev(sizeof(struct es58x_priv),
2081 			      es58x_dev->param->fifo_mask + 1);
2082 	if (!netdev) {
2083 		dev_err(dev, "Could not allocate candev\n");
2084 		return -ENOMEM;
2085 	}
2086 	SET_NETDEV_DEV(netdev, dev);
2087 	es58x_dev->netdev[channel_idx] = netdev;
2088 	es58x_init_priv(es58x_dev, es58x_priv(netdev), channel_idx);
2089 
2090 	netdev->netdev_ops = &es58x_netdev_ops;
2091 	netdev->flags |= IFF_ECHO;	/* We support local echo */
2092 	netdev->dev_port = channel_idx;
2093 
2094 	ret = register_candev(netdev);
2095 	if (ret)
2096 		return ret;
2097 
2098 	netdev_queue_set_dql_min_limit(netdev_get_tx_queue(netdev, 0),
2099 				       es58x_dev->param->dql_min_limit);
2100 
2101 	return ret;
2102 }
2103 
2104 /**
2105  * es58x_free_netdevs() - Release all network resources of the device.
2106  * @es58x_dev: ES58X device.
2107  */
2108 static void es58x_free_netdevs(struct es58x_device *es58x_dev)
2109 {
2110 	int i;
2111 
2112 	for (i = 0; i < es58x_dev->num_can_ch; i++) {
2113 		struct net_device *netdev = es58x_dev->netdev[i];
2114 
2115 		if (!netdev)
2116 			continue;
2117 		unregister_candev(netdev);
2118 		es58x_dev->netdev[i] = NULL;
2119 		free_candev(netdev);
2120 	}
2121 }
2122 
2123 /**
2124  * es58x_get_product_info() - Get the product information and print them.
2125  * @es58x_dev: ES58X device.
2126  *
2127  * Do a synchronous call to get the product information.
2128  *
2129  * Return: zero on success, errno when any error occurs.
2130  */
2131 static int es58x_get_product_info(struct es58x_device *es58x_dev)
2132 {
2133 	struct usb_device *udev = es58x_dev->udev;
2134 	const int es58x_prod_info_idx = 6;
2135 	/* Empirical tests show a prod_info length of maximum 83,
2136 	 * below should be more than enough.
2137 	 */
2138 	const size_t prod_info_len = 127;
2139 	char *prod_info;
2140 	int ret;
2141 
2142 	prod_info = kmalloc(prod_info_len, GFP_KERNEL);
2143 	if (!prod_info)
2144 		return -ENOMEM;
2145 
2146 	ret = usb_string(udev, es58x_prod_info_idx, prod_info, prod_info_len);
2147 	if (ret < 0) {
2148 		dev_err(es58x_dev->dev,
2149 			"%s: Could not read the product info: %pe\n",
2150 			__func__, ERR_PTR(ret));
2151 		goto out_free;
2152 	}
2153 	if (ret >= prod_info_len - 1) {
2154 		dev_warn(es58x_dev->dev,
2155 			 "%s: Buffer is too small, result might be truncated\n",
2156 			 __func__);
2157 	}
2158 	dev_info(es58x_dev->dev, "Product info: %s\n", prod_info);
2159 
2160  out_free:
2161 	kfree(prod_info);
2162 	return ret < 0 ? ret : 0;
2163 }
2164 
2165 /**
2166  * es58x_init_es58x_dev() - Initialize the ES58X device.
2167  * @intf: USB interface.
2168  * @driver_info: Quirks of the device.
2169  *
2170  * Return: pointer to an ES58X device on success, error pointer when
2171  *	any error occurs.
2172  */
2173 static struct es58x_device *es58x_init_es58x_dev(struct usb_interface *intf,
2174 						 kernel_ulong_t driver_info)
2175 {
2176 	struct device *dev = &intf->dev;
2177 	struct es58x_device *es58x_dev;
2178 	const struct es58x_parameters *param;
2179 	const struct es58x_operators *ops;
2180 	struct usb_device *udev = interface_to_usbdev(intf);
2181 	struct usb_endpoint_descriptor *ep_in, *ep_out;
2182 	int ret;
2183 
2184 	dev_info(dev,
2185 		 "Starting %s %s (Serial Number %s) driver version %s\n",
2186 		 udev->manufacturer, udev->product, udev->serial, DRV_VERSION);
2187 
2188 	ret = usb_find_common_endpoints(intf->cur_altsetting, &ep_in, &ep_out,
2189 					NULL, NULL);
2190 	if (ret)
2191 		return ERR_PTR(ret);
2192 
2193 	if (driver_info & ES58X_FD_FAMILY) {
2194 		param = &es58x_fd_param;
2195 		ops = &es58x_fd_ops;
2196 	} else {
2197 		param = &es581_4_param;
2198 		ops = &es581_4_ops;
2199 	}
2200 
2201 	es58x_dev = devm_kzalloc(dev, es58x_sizeof_es58x_device(param),
2202 				 GFP_KERNEL);
2203 	if (!es58x_dev)
2204 		return ERR_PTR(-ENOMEM);
2205 
2206 	es58x_dev->param = param;
2207 	es58x_dev->ops = ops;
2208 	es58x_dev->dev = dev;
2209 	es58x_dev->udev = udev;
2210 
2211 	if (driver_info & ES58X_DUAL_CHANNEL)
2212 		es58x_dev->num_can_ch = 2;
2213 	else
2214 		es58x_dev->num_can_ch = 1;
2215 
2216 	init_usb_anchor(&es58x_dev->rx_urbs);
2217 	init_usb_anchor(&es58x_dev->tx_urbs_idle);
2218 	init_usb_anchor(&es58x_dev->tx_urbs_busy);
2219 	atomic_set(&es58x_dev->tx_urbs_idle_cnt, 0);
2220 	usb_set_intfdata(intf, es58x_dev);
2221 
2222 	es58x_dev->rx_pipe = usb_rcvbulkpipe(es58x_dev->udev,
2223 					     ep_in->bEndpointAddress);
2224 	es58x_dev->tx_pipe = usb_sndbulkpipe(es58x_dev->udev,
2225 					     ep_out->bEndpointAddress);
2226 	es58x_dev->rx_max_packet_size = le16_to_cpu(ep_in->wMaxPacketSize);
2227 
2228 	return es58x_dev;
2229 }
2230 
2231 /**
2232  * es58x_probe() - Initialize the USB device.
2233  * @intf: USB interface.
2234  * @id: USB device ID.
2235  *
2236  * Return: zero on success, -ENODEV if the interface is not supported
2237  * or errno when any other error occurs.
2238  */
2239 static int es58x_probe(struct usb_interface *intf,
2240 		       const struct usb_device_id *id)
2241 {
2242 	struct es58x_device *es58x_dev;
2243 	int ch_idx, ret;
2244 
2245 	es58x_dev = es58x_init_es58x_dev(intf, id->driver_info);
2246 	if (IS_ERR(es58x_dev))
2247 		return PTR_ERR(es58x_dev);
2248 
2249 	ret = es58x_get_product_info(es58x_dev);
2250 	if (ret)
2251 		return ret;
2252 
2253 	for (ch_idx = 0; ch_idx < es58x_dev->num_can_ch; ch_idx++) {
2254 		ret = es58x_init_netdev(es58x_dev, ch_idx);
2255 		if (ret) {
2256 			es58x_free_netdevs(es58x_dev);
2257 			return ret;
2258 		}
2259 	}
2260 
2261 	return ret;
2262 }
2263 
2264 /**
2265  * es58x_disconnect() - Disconnect the USB device.
2266  * @intf: USB interface
2267  *
2268  * Called by the usb core when driver is unloaded or device is
2269  * removed.
2270  */
2271 static void es58x_disconnect(struct usb_interface *intf)
2272 {
2273 	struct es58x_device *es58x_dev = usb_get_intfdata(intf);
2274 
2275 	dev_info(&intf->dev, "Disconnecting %s %s\n",
2276 		 es58x_dev->udev->manufacturer, es58x_dev->udev->product);
2277 
2278 	es58x_free_netdevs(es58x_dev);
2279 	es58x_free_urbs(es58x_dev);
2280 	usb_set_intfdata(intf, NULL);
2281 }
2282 
2283 static struct usb_driver es58x_driver = {
2284 	.name = ES58X_MODULE_NAME,
2285 	.probe = es58x_probe,
2286 	.disconnect = es58x_disconnect,
2287 	.id_table = es58x_id_table
2288 };
2289 
2290 module_usb_driver(es58x_driver);
2291