1 // SPDX-License-Identifier: GPL-2.0
3 /* Driver for ETAS GmbH ES58X USB CAN(-FD) Bus Interfaces.
5 * File es58x_core.c: Core logic to manage the network devices and the
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>
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>
19 #include "es58x_core.h"
21 #define DRV_VERSION "1.00"
22 MODULE_AUTHOR("Mailhol Vincent <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");
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
34 /* ES58X FD has some interface protocols unsupported by this driver. */
35 #define ES58X_FD_INTERFACE_PROTOCOL 0
37 /* Table of devices which work with this driver. */
38 static const struct usb_device_id es58x_id_table[] = {
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
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
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
54 /* Terminating entry */
58 MODULE_DEVICE_TABLE(usb, es58x_id_table);
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)
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)
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.
73 #define ES58X_CRC_CALC_OFFSET 2
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))
81 * Return: crc16 value.
83 static u16 es58x_calculate_crc(const union es58x_urb_cmd *urb_cmd, u16 urb_len)
86 ssize_t len = urb_len - ES58X_CRC_CALC_OFFSET - sizeof(crc);
88 crc = crc16(0, &urb_cmd->raw_cmd[ES58X_CRC_CALC_OFFSET], len);
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))
98 * Return: crc16 value.
100 static u16 es58x_get_crc(const union es58x_urb_cmd *urb_cmd, u16 urb_len)
103 const __le16 *crc_addr;
105 crc_addr = (__le16 *)&urb_cmd->raw_cmd[urb_len - sizeof(crc)];
106 crc = get_unaligned_le16(crc_addr);
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))
116 static void es58x_set_crc(union es58x_urb_cmd *urb_cmd, u16 urb_len)
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);
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))
133 * Return: zero on success, -EBADMSG if the CRC check fails.
135 static int es58x_check_crc(struct es58x_device *es58x_dev,
136 const union es58x_urb_cmd *urb_cmd, u16 urb_len)
138 u16 calculated_crc = es58x_calculate_crc(urb_cmd, urb_len);
139 u16 expected_crc = es58x_get_crc(urb_cmd, urb_len);
141 if (expected_crc != calculated_crc) {
142 dev_err_ratelimited(es58x_dev->dev,
143 "%s: Bad CRC, urb_len: %d\n",
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.
156 * The timestamp received from ES58X is expressed in multiples of 0.5
157 * micro seconds. This function converts it in to nanoseconds.
159 * Return: Timestamp value in nanoseconds.
161 static u64 es58x_timestamp_to_ns(u64 timestamp)
163 const u64 es58x_timestamp_ns_mult_coef = 500ULL;
165 return es58x_timestamp_ns_mult_coef * timestamp;
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.
174 * Used for both received and echo messages.
176 static void es58x_set_skb_timestamp(struct net_device *netdev,
177 struct sk_buff *skb, u64 timestamp)
179 struct es58x_device *es58x_dev = es58x_priv(netdev)->es58x_dev;
180 struct skb_shared_hwtstamps *hwts;
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).
186 hwts->hwtstamp = ns_to_ktime(es58x_timestamp_to_ns(timestamp) +
187 es58x_dev->realtime_diff_ns);
191 * es58x_rx_timestamp() - Handle a received timestamp.
192 * @es58x_dev: ES58X device.
193 * @timestamp: Timestamp received from a ES58X device.
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).
200 void es58x_rx_timestamp(struct es58x_device *es58x_dev, u64 timestamp)
202 u64 ktime_real_ns = ktime_get_real_ns();
203 u64 device_timestamp = es58x_timestamp_to_ns(timestamp);
205 dev_dbg(es58x_dev->dev, "%s: request round-trip time: %llu ns\n",
206 __func__, ktime_real_ns - es58x_dev->ktime_req_ns);
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;
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);
218 * es58x_set_realtime_diff_ns() - Calculate difference between the
219 * clocks of the ES58X device and the kernel
220 * @es58x_dev: ES58X device.
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().
226 * Return: zero on success, errno when any error occurs.
228 static int es58x_set_realtime_diff_ns(struct es58x_device *es58x_dev)
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",
237 es58x_dev->ktime_req_ns = ktime_get_real_ns();
238 return es58x_dev->ops->get_timestamp(es58x_dev);
242 * es58x_is_can_state_active() - Is the network device in an active
244 * @netdev: CAN network device.
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.
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.
258 * Return: true if the device is active, else returns false.
260 static bool es58x_is_can_state_active(struct net_device *netdev)
262 return es58x_priv(netdev)->can.state < CAN_STATE_BUS_OFF;
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
269 * @priv: ES58X private parameters related to the network device.
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.
278 static bool es58x_is_echo_skb_threshold_reached(struct es58x_priv *priv)
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;
284 return num_echo_skb >= threshold;
288 * es58x_can_free_echo_skb_tail() - Remove the oldest echo skb of the
290 * @netdev: CAN network device.
292 * Naming convention: the tail is the beginning of the FIFO, i.e. the
293 * first skb to have entered the FIFO.
295 static void es58x_can_free_echo_skb_tail(struct net_device *netdev)
297 struct es58x_priv *priv = es58x_priv(netdev);
298 u16 fifo_mask = priv->es58x_dev->param->fifo_mask;
299 unsigned int frame_len = 0;
301 can_free_echo_skb(netdev, priv->tx_tail & fifo_mask, &frame_len);
302 netdev_completed_queue(netdev, 1, frame_len);
306 netdev->stats.tx_dropped++;
310 * es58x_can_get_echo_skb_recovery() - Try to re-sync the echo FIFO.
311 * @netdev: CAN network device.
312 * @rcv_packet_idx: Index
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.
319 * Return: zero if recovery was successful, -EINVAL otherwise.
321 static int es58x_can_get_echo_skb_recovery(struct net_device *netdev,
324 struct es58x_priv *priv = es58x_priv(netdev);
327 netdev->stats.tx_errors++;
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);
336 if ((s32)(rcv_packet_idx - priv->tx_tail) < 0) {
339 "Received echo index is from the past. Ignoring it\n");
341 } else if ((s32)(rcv_packet_idx - priv->tx_head) >= 0) {
344 "Received echo index is from the future. Ignoring it\n");
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)
355 es58x_can_free_echo_skb_tail(netdev);
362 * es58x_can_get_echo_skb() - Get the skb from the echo FIFO and loop
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).
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
374 * The device has to be active (i.e. network interface UP and not in
375 * bus off state or restarting).
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).
381 * Return: zero on success.
383 int es58x_can_get_echo_skb(struct net_device *netdev, u32 rcv_packet_idx,
384 u64 *tstamps, unsigned int pkts)
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;
390 u16 fifo_mask = priv->es58x_dev->param->fifo_mask;
392 if (!netif_running(netdev)) {
395 "%s: %s is down, dropping %d echo packets\n",
396 __func__, netdev->name, pkts);
397 netdev->stats.tx_dropped += pkts;
399 } else if (!es58x_is_can_state_active(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)
406 * drivers/net/can/net/dev.c:can_flush_echo_skb().
409 } else if (num_echo_skb == 0) {
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;
418 if (priv->tx_tail != rcv_packet_idx) {
419 if (es58x_can_get_echo_skb_recovery(netdev, rcv_packet_idx) < 0) {
422 "Could not find echo skb for echo packet index: %u\n",
427 if (num_echo_skb < pkts) {
428 int pkts_drop = pkts - num_echo_skb;
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;
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;
444 es58x_set_skb_timestamp(netdev, skb, tstamps[i]);
446 netdev->stats.tx_bytes += can_get_echo_skb(netdev, skb_idx,
448 rx_total_frame_len += frame_len;
453 netdev_completed_queue(netdev, pkts, rx_total_frame_len);
454 netdev->stats.tx_packets += pkts;
456 priv->err_passive_before_rtx_success = 0;
457 if (!es58x_is_echo_skb_threshold_reached(priv))
458 netif_wake_queue(netdev);
464 * es58x_can_reset_echo_fifo() - Reset the echo FIFO.
465 * @netdev: CAN network device.
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
472 static void es58x_can_reset_echo_fifo(struct net_device *netdev)
474 struct es58x_priv *priv = es58x_priv(netdev);
479 priv->err_passive_before_rtx_success = 0;
480 netdev_reset_queue(netdev);
484 * es58x_flush_pending_tx_msg() - Reset the buffer for transmission messages.
485 * @netdev: CAN network device.
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.
493 static void es58x_flush_pending_tx_msg(struct net_device *netdev)
495 struct es58x_priv *priv = es58x_priv(netdev);
496 struct es58x_device *es58x_dev = priv->es58x_dev;
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;
507 priv->tx_can_msg_cnt--;
508 can_free_echo_skb(netdev, priv->tx_head & fifo_mask,
510 netdev_completed_queue(netdev, 1, frame_len);
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);
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.
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.
529 * Under normal circumstances, this function should never throw an
532 * Return: zero on success, errno when any error occurs.
534 int es58x_tx_ack_msg(struct net_device *netdev, u16 tx_free_entries,
535 enum es58x_ret_u32 rx_cmd_ret_u32)
537 struct es58x_priv *priv = es58x_priv(netdev);
539 if (tx_free_entries <= priv->es58x_dev->param->tx_bulk_max) {
542 "Only %d entries left in device queue, num_echo_skb: %d/%d\n",
544 priv->tx_head - priv->tx_tail,
545 priv->can.echo_skb_max);
546 netif_stop_queue(netdev);
549 return es58x_rx_cmd_ret_u32(netdev, ES58X_RET_TYPE_TX_MSG,
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.
559 * @es58x_flags: Please refer to enum es58x_flag.
560 * @dlc: Data Length Code (raw value).
562 * Fill up a CAN skb and post it.
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
568 * Return: zero on success.
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)
573 struct canfd_frame *cfd;
574 struct can_frame *ccf;
577 bool is_can_fd = !!(es58x_flags & ES58X_FLAG_FD_DATA);
579 if (dlc > CAN_MAX_RAW_DLC) {
581 "%s: DLC is %d but maximum should be %d\n",
582 __func__, dlc, CAN_MAX_RAW_DLC);
587 len = can_fd_dlc2len(dlc);
588 skb = alloc_canfd_skb(netdev, &cfd);
590 len = can_cc_dlc2len(dlc);
591 skb = alloc_can_skb(netdev, &ccf);
592 cfd = (struct canfd_frame *)ccf;
595 netdev->stats.rx_dropped++;
599 cfd->can_id = can_id;
600 if (es58x_flags & ES58X_FLAG_EFF)
601 cfd->can_id |= CAN_EFF_FLAG;
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;
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;
615 memcpy(cfd->data, data, len);
616 netdev->stats.rx_packets++;
617 netdev->stats.rx_bytes += len;
619 es58x_set_skb_timestamp(netdev, skb, timestamp);
622 es58x_priv(netdev)->err_passive_before_rtx_success = 0;
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.
634 * Handle the errors and events received by the ES58X device, create
635 * a CAN error skb and post it.
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.
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
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
657 * Return: zero on success, errno when any error occurs.
659 int es58x_rx_err_msg(struct net_device *netdev, enum es58x_err error,
660 enum es58x_event event, u64 timestamp)
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;
669 if (!netif_running(netdev)) {
671 netdev_info(netdev, "%s: %s is down, dropping packet\n",
672 __func__, netdev->name);
673 netdev->stats.rx_dropped++;
677 if (error == ES58X_ERR_OK && event == ES58X_EVENT_OK) {
678 netdev_err(netdev, "%s: Both error and event are zero\n",
683 skb = alloc_can_err_skb(netdev, &cf);
686 case ES58X_ERR_OK: /* 0: No error */
689 case ES58X_ERR_PROT_STUFF:
691 netdev_dbg(netdev, "Error BITSTUFF\n");
693 cf->data[2] |= CAN_ERR_PROT_STUFF;
696 case ES58X_ERR_PROT_FORM:
698 netdev_dbg(netdev, "Error FORMAT\n");
700 cf->data[2] |= CAN_ERR_PROT_FORM;
705 netdev_dbg(netdev, "Error ACK\n");
707 cf->can_id |= CAN_ERR_ACK;
710 case ES58X_ERR_PROT_BIT:
712 netdev_dbg(netdev, "Error BIT\n");
714 cf->data[2] |= CAN_ERR_PROT_BIT;
717 case ES58X_ERR_PROT_CRC:
719 netdev_dbg(netdev, "Error CRC\n");
721 cf->data[3] |= CAN_ERR_PROT_LOC_CRC_SEQ;
724 case ES58X_ERR_PROT_BIT1:
727 "Error: expected a recessive bit but monitored a dominant one\n");
729 cf->data[2] |= CAN_ERR_PROT_BIT1;
732 case ES58X_ERR_PROT_BIT0:
735 "Error expected a dominant bit but monitored a recessive one\n");
737 cf->data[2] |= CAN_ERR_PROT_BIT0;
740 case ES58X_ERR_PROT_OVERLOAD:
742 netdev_dbg(netdev, "Error OVERLOAD\n");
744 cf->data[2] |= CAN_ERR_PROT_OVERLOAD;
747 case ES58X_ERR_PROT_UNSPEC:
749 netdev_dbg(netdev, "Unspecified error\n");
751 cf->can_id |= CAN_ERR_PROT;
757 "%s: Unspecified error code 0x%04X\n",
758 __func__, (int)error);
760 cf->can_id |= CAN_ERR_PROT;
765 case ES58X_EVENT_OK: /* 0: No event */
768 case ES58X_EVENT_CRTL_ACTIVE:
769 if (can->state == CAN_STATE_BUS_OFF) {
771 "%s: state transition: BUS OFF -> ACTIVE\n",
775 netdev_dbg(netdev, "Event CAN BUS ACTIVE\n");
777 cf->data[1] |= CAN_ERR_CRTL_ACTIVE;
778 can->state = CAN_STATE_ERROR_ACTIVE;
781 case ES58X_EVENT_CRTL_PASSIVE:
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
789 cf->data[1] |= CAN_ERR_CRTL_RX_PASSIVE;
790 cf->data[1] |= CAN_ERR_CRTL_TX_PASSIVE;
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++;
799 case ES58X_EVENT_CRTL_WARNING:
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
807 cf->data[1] |= CAN_ERR_CRTL_RX_WARNING;
808 cf->data[1] |= CAN_ERR_CRTL_TX_WARNING;
810 if (can->state < CAN_STATE_BUS_OFF)
811 can->state = CAN_STATE_ERROR_WARNING;
812 can_stats->error_warning++;
815 case ES58X_EVENT_BUSOFF:
817 netdev_dbg(netdev, "Event CAN BUS OFF\n");
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;
825 ret = can->do_set_mode(netdev, CAN_MODE_STOP);
831 case ES58X_EVENT_SINGLE_WIRE:
834 "Lost connection on either CAN high or CAN low\n");
835 /* Lost connection on either CAN high or CAN
836 * low. Setting both flags by default.
839 cf->data[4] |= CAN_ERR_TRX_CANH_NO_WIRE;
840 cf->data[4] |= CAN_ERR_TRX_CANL_NO_WIRE;
847 "%s: Unspecified event code 0x%04X\n",
848 __func__, (int)event);
850 cf->can_id |= CAN_ERR_CRTL;
854 /* driver/net/can/dev.c:can_restart() takes in account error
855 * messages in the RX stats. Doing the same here for
858 netdev->stats.rx_packets++;
859 netdev->stats.rx_bytes += CAN_ERR_DLC;
863 cf->can_id |= CAN_ERR_CRTL;
864 if (cf->data[2] || cf->data[3]) {
865 cf->can_id |= CAN_ERR_PROT;
866 can_stats->bus_error++;
869 cf->can_id |= CAN_ERR_TRX;
871 es58x_set_skb_timestamp(netdev, skb, timestamp);
875 if ((event & ES58X_EVENT_CRTL_PASSIVE) &&
876 priv->err_passive_before_rtx_success == ES58X_CONSECUTIVE_ERR_PASSIVE_MAX) {
878 "Got %d consecutive warning events with no successful RX or TX. Forcing bus-off\n",
879 priv->err_passive_before_rtx_success);
880 return es58x_rx_err_msg(netdev, ES58X_ERR_OK,
881 ES58X_EVENT_BUSOFF, timestamp);
888 * es58x_cmd_ret_desc() - Convert a command type to a string.
889 * @cmd_ret_type: Type of the command which triggered the return code.
891 * The final line (return "<unknown>") should not be reached. If this
892 * is the case, there is an implementation bug.
894 * Return: a readable description of the @cmd_ret_type.
896 static const char *es58x_cmd_ret_desc(enum es58x_ret_type cmd_ret_type)
898 switch (cmd_ret_type) {
899 case ES58X_RET_TYPE_SET_BITTIMING:
900 return "Set bittiming";
901 case ES58X_RET_TYPE_ENABLE_CHANNEL:
902 return "Enable channel";
903 case ES58X_RET_TYPE_DISABLE_CHANNEL:
904 return "Disable channel";
905 case ES58X_RET_TYPE_TX_MSG:
906 return "Transmit message";
907 case ES58X_RET_TYPE_RESET_RX:
909 case ES58X_RET_TYPE_RESET_TX:
911 case ES58X_RET_TYPE_DEVICE_ERR:
912 return "Device error";
919 * es58x_rx_cmd_ret_u8() - Handle the command's return code received
920 * from the ES58X device.
921 * @dev: Device, only used for the dev_XXX() print functions.
922 * @cmd_ret_type: Type of the command which triggered the return code.
923 * @rx_cmd_ret_u8: Command error code as returned by the ES58X device.
925 * Handles the 8 bits command return code. Those are specific to the
926 * ES581.4 device. The return value will eventually be used by
927 * es58x_handle_urb_cmd() function which will take proper actions in
928 * case of critical issues such and memory errors or bad CRC values.
930 * In contrast with es58x_rx_cmd_ret_u32(), the network device is
933 * Return: zero on success, return errno when any error occurs.
935 int es58x_rx_cmd_ret_u8(struct device *dev,
936 enum es58x_ret_type cmd_ret_type,
937 enum es58x_ret_u8 rx_cmd_ret_u8)
939 const char *ret_desc = es58x_cmd_ret_desc(cmd_ret_type);
941 switch (rx_cmd_ret_u8) {
942 case ES58X_RET_U8_OK:
943 dev_dbg_ratelimited(dev, "%s: OK\n", ret_desc);
946 case ES58X_RET_U8_ERR_UNSPECIFIED_FAILURE:
947 dev_err(dev, "%s: unspecified failure\n", ret_desc);
950 case ES58X_RET_U8_ERR_NO_MEM:
951 dev_err(dev, "%s: device ran out of memory\n", ret_desc);
954 case ES58X_RET_U8_ERR_BAD_CRC:
955 dev_err(dev, "%s: CRC of previous command is incorrect\n",
960 dev_err(dev, "%s: returned unknown value: 0x%02X\n",
961 ret_desc, rx_cmd_ret_u8);
967 * es58x_rx_cmd_ret_u32() - Handle the command return code received
968 * from the ES58X device.
969 * @netdev: CAN network device.
970 * @cmd_ret_type: Type of the command which triggered the return code.
971 * @rx_cmd_ret_u32: error code as returned by the ES58X device.
973 * Handles the 32 bits command return code. The return value will
974 * eventually be used by es58x_handle_urb_cmd() function which will
975 * take proper actions in case of critical issues such and memory
976 * errors or bad CRC values.
978 * Return: zero on success, errno when any error occurs.
980 int es58x_rx_cmd_ret_u32(struct net_device *netdev,
981 enum es58x_ret_type cmd_ret_type,
982 enum es58x_ret_u32 rx_cmd_ret_u32)
984 struct es58x_priv *priv = es58x_priv(netdev);
985 const struct es58x_operators *ops = priv->es58x_dev->ops;
986 const char *ret_desc = es58x_cmd_ret_desc(cmd_ret_type);
988 switch (rx_cmd_ret_u32) {
989 case ES58X_RET_U32_OK:
990 switch (cmd_ret_type) {
991 case ES58X_RET_TYPE_ENABLE_CHANNEL:
992 es58x_can_reset_echo_fifo(netdev);
993 priv->can.state = CAN_STATE_ERROR_ACTIVE;
994 netif_wake_queue(netdev);
996 "%s: %s (Serial Number %s): CAN%d channel becomes ready\n",
997 ret_desc, priv->es58x_dev->udev->product,
998 priv->es58x_dev->udev->serial,
999 priv->channel_idx + 1);
1002 case ES58X_RET_TYPE_TX_MSG:
1003 if (IS_ENABLED(CONFIG_VERBOSE_DEBUG) && net_ratelimit())
1004 netdev_vdbg(netdev, "%s: OK\n", ret_desc);
1008 netdev_dbg(netdev, "%s: OK\n", ret_desc);
1013 case ES58X_RET_U32_ERR_UNSPECIFIED_FAILURE:
1014 if (cmd_ret_type == ES58X_RET_TYPE_ENABLE_CHANNEL) {
1018 "%s: channel is already opened, closing and re-opening it to reflect new configuration\n",
1020 ret = ops->disable_channel(es58x_priv(netdev));
1023 return ops->enable_channel(es58x_priv(netdev));
1025 if (cmd_ret_type == ES58X_RET_TYPE_DISABLE_CHANNEL) {
1027 "%s: channel is already closed\n", ret_desc);
1031 "%s: unspecified failure\n", ret_desc);
1034 case ES58X_RET_U32_ERR_NO_MEM:
1035 netdev_err(netdev, "%s: device ran out of memory\n", ret_desc);
1038 case ES58X_RET_U32_WARN_PARAM_ADJUSTED:
1040 "%s: some incompatible parameters have been adjusted\n",
1044 case ES58X_RET_U32_WARN_TX_MAYBE_REORDER:
1046 "%s: TX messages might have been reordered\n",
1050 case ES58X_RET_U32_ERR_TIMEDOUT:
1051 netdev_err(netdev, "%s: command timed out\n", ret_desc);
1054 case ES58X_RET_U32_ERR_FIFO_FULL:
1055 netdev_warn(netdev, "%s: fifo is full\n", ret_desc);
1058 case ES58X_RET_U32_ERR_BAD_CONFIG:
1059 netdev_err(netdev, "%s: bad configuration\n", ret_desc);
1062 case ES58X_RET_U32_ERR_NO_RESOURCE:
1063 netdev_err(netdev, "%s: no resource available\n", ret_desc);
1067 netdev_err(netdev, "%s returned unknown value: 0x%08X\n",
1068 ret_desc, rx_cmd_ret_u32);
1074 * es58x_increment_rx_errors() - Increment the network devices' error
1076 * @es58x_dev: ES58X device.
1078 * If an error occurs on the early stages on receiving an URB command,
1079 * we might not be able to figure out on which network device the
1080 * error occurred. In such case, we arbitrarily increment the error
1081 * count of all the network devices attached to our ES58X device.
1083 static void es58x_increment_rx_errors(struct es58x_device *es58x_dev)
1087 for (i = 0; i < es58x_dev->num_can_ch; i++)
1088 if (es58x_dev->netdev[i])
1089 es58x_dev->netdev[i]->stats.rx_errors++;
1093 * es58x_handle_urb_cmd() - Handle the URB command
1094 * @es58x_dev: ES58X device.
1095 * @urb_cmd: The URB command received from the ES58X device, might not
1098 * Sends the URB command to the device specific function. Manages the
1099 * errors thrown back by those functions.
1101 static void es58x_handle_urb_cmd(struct es58x_device *es58x_dev,
1102 const union es58x_urb_cmd *urb_cmd)
1104 const struct es58x_operators *ops = es58x_dev->ops;
1108 ret = ops->handle_urb_cmd(es58x_dev, urb_cmd);
1114 dev_err_ratelimited(es58x_dev->dev, "Device is not ready\n");
1123 cmd_len = es58x_get_urb_cmd_len(es58x_dev,
1124 ops->get_msg_len(urb_cmd));
1125 dev_err(es58x_dev->dev,
1126 "ops->handle_urb_cmd() returned error %pe",
1128 es58x_print_hex_dump(urb_cmd, cmd_len);
1135 dev_crit(es58x_dev->dev,
1136 "ops->handle_urb_cmd() returned error %pe, detaching all network devices\n",
1138 for (i = 0; i < es58x_dev->num_can_ch; i++)
1139 if (es58x_dev->netdev[i])
1140 netif_device_detach(es58x_dev->netdev[i]);
1141 if (es58x_dev->ops->reset_device)
1142 es58x_dev->ops->reset_device(es58x_dev);
1146 /* Because the urb command could not fully be parsed,
1147 * channel_id is not confirmed. Incrementing rx_errors count
1150 es58x_increment_rx_errors(es58x_dev);
1154 * es58x_check_rx_urb() - Check the length and format of the URB command.
1155 * @es58x_dev: ES58X device.
1156 * @urb_cmd: The URB command received from the ES58X device, might not
1158 * @urb_actual_len: The actual length of the URB command.
1160 * Check if the first message of the received urb is valid, that is to
1161 * say that both the header and the length are coherent.
1164 * the length of the first message of the URB on success.
1166 * -ENODATA if the URB command is incomplete (in which case, the URB
1167 * command should be buffered and combined with the next URB to try to
1168 * reconstitute the URB command).
1170 * -EOVERFLOW if the length is bigger than the maximum expected one.
1172 * -EBADRQC if the start of frame does not match the expected value.
1174 static signed int es58x_check_rx_urb(struct es58x_device *es58x_dev,
1175 const union es58x_urb_cmd *urb_cmd,
1178 const struct device *dev = es58x_dev->dev;
1179 const struct es58x_parameters *param = es58x_dev->param;
1181 signed int urb_cmd_len, ret;
1183 if (urb_actual_len < param->urb_cmd_header_len) {
1185 "%s: Received %d bytes [%*ph]: header incomplete\n",
1186 __func__, urb_actual_len, urb_actual_len,
1191 sof = get_unaligned_le16(&urb_cmd->sof);
1192 if (sof != param->rx_start_of_frame) {
1193 dev_err_ratelimited(es58x_dev->dev,
1194 "%s: Expected sequence 0x%04X for start of frame but got 0x%04X.\n",
1195 __func__, param->rx_start_of_frame, sof);
1199 msg_len = es58x_dev->ops->get_msg_len(urb_cmd);
1200 urb_cmd_len = es58x_get_urb_cmd_len(es58x_dev, msg_len);
1201 if (urb_cmd_len > param->rx_urb_cmd_max_len) {
1202 dev_err_ratelimited(es58x_dev->dev,
1203 "%s: Biggest expected size for rx urb_cmd is %u but receive a command of size %d\n",
1205 param->rx_urb_cmd_max_len, urb_cmd_len);
1207 } else if (urb_actual_len < urb_cmd_len) {
1208 dev_vdbg(dev, "%s: Received %02d/%02d bytes\n",
1209 __func__, urb_actual_len, urb_cmd_len);
1213 ret = es58x_check_crc(es58x_dev, urb_cmd, urb_cmd_len);
1221 * es58x_copy_to_cmd_buf() - Copy an array to the URB command buffer.
1222 * @es58x_dev: ES58X device.
1223 * @raw_cmd: the buffer we want to copy.
1224 * @raw_cmd_len: length of @raw_cmd.
1226 * Concatenates @raw_cmd_len bytes of @raw_cmd to the end of the URB
1229 * Return: zero on success, -EMSGSIZE if not enough space is available
1232 static int es58x_copy_to_cmd_buf(struct es58x_device *es58x_dev,
1233 u8 *raw_cmd, int raw_cmd_len)
1235 if (es58x_dev->rx_cmd_buf_len + raw_cmd_len >
1236 es58x_dev->param->rx_urb_cmd_max_len)
1239 memcpy(&es58x_dev->rx_cmd_buf.raw_cmd[es58x_dev->rx_cmd_buf_len],
1240 raw_cmd, raw_cmd_len);
1241 es58x_dev->rx_cmd_buf_len += raw_cmd_len;
1247 * es58x_split_urb_try_recovery() - Try to recover bad URB sequences.
1248 * @es58x_dev: ES58X device.
1249 * @raw_cmd: pointer to the buffer we want to copy.
1250 * @raw_cmd_len: length of @raw_cmd.
1252 * Under some rare conditions, we might get incorrect URBs from the
1253 * device. From our observations, one of the valid URB gets replaced
1254 * by one from the past. The full root cause is not identified.
1256 * This function looks for the next start of frame in the urb buffer
1257 * in order to try to recover.
1259 * Such behavior was not observed on the devices of the ES58X FD
1260 * family and only seems to impact the ES581.4.
1262 * Return: the number of bytes dropped on success, -EBADMSG if recovery failed.
1264 static int es58x_split_urb_try_recovery(struct es58x_device *es58x_dev,
1265 u8 *raw_cmd, size_t raw_cmd_len)
1267 union es58x_urb_cmd *urb_cmd;
1268 signed int urb_cmd_len;
1270 int dropped_bytes = 0;
1272 es58x_increment_rx_errors(es58x_dev);
1274 while (raw_cmd_len > sizeof(sof)) {
1275 urb_cmd = (union es58x_urb_cmd *)raw_cmd;
1276 sof = get_unaligned_le16(&urb_cmd->sof);
1278 if (sof == es58x_dev->param->rx_start_of_frame) {
1279 urb_cmd_len = es58x_check_rx_urb(es58x_dev,
1280 urb_cmd, raw_cmd_len);
1281 if ((urb_cmd_len == -ENODATA) || urb_cmd_len > 0) {
1282 dev_info_ratelimited(es58x_dev->dev,
1283 "Recovery successful! Dropped %d bytes (urb_cmd_len: %d)\n",
1286 return dropped_bytes;
1294 dev_warn_ratelimited(es58x_dev->dev, "%s: Recovery failed\n", __func__);
1299 * es58x_handle_incomplete_cmd() - Reconstitute an URB command from
1300 * different URB pieces.
1301 * @es58x_dev: ES58X device.
1302 * @urb: last urb buffer received.
1304 * The device might split the URB commands in an arbitrary amount of
1305 * pieces. This function concatenates those in an URB buffer until a
1306 * full URB command is reconstituted and consume it.
1309 * number of bytes consumed from @urb if successful.
1311 * -ENODATA if the URB command is still incomplete.
1313 * -EBADMSG if the URB command is incorrect.
1315 static signed int es58x_handle_incomplete_cmd(struct es58x_device *es58x_dev,
1319 signed int urb_cmd_len, tmp_cmd_buf_len, ret;
1321 tmp_cmd_buf_len = es58x_dev->rx_cmd_buf_len;
1322 cpy_len = min_t(int, es58x_dev->param->rx_urb_cmd_max_len -
1323 es58x_dev->rx_cmd_buf_len, urb->actual_length);
1324 ret = es58x_copy_to_cmd_buf(es58x_dev, urb->transfer_buffer, cpy_len);
1328 urb_cmd_len = es58x_check_rx_urb(es58x_dev, &es58x_dev->rx_cmd_buf,
1329 es58x_dev->rx_cmd_buf_len);
1330 if (urb_cmd_len == -ENODATA) {
1332 } else if (urb_cmd_len < 0) {
1333 dev_err_ratelimited(es58x_dev->dev,
1334 "Could not reconstitute incomplete command from previous URB, dropping %d bytes\n",
1335 tmp_cmd_buf_len + urb->actual_length);
1336 dev_err_ratelimited(es58x_dev->dev,
1337 "Error code: %pe, es58x_dev->rx_cmd_buf_len: %d, urb->actual_length: %u\n",
1338 ERR_PTR(urb_cmd_len),
1339 tmp_cmd_buf_len, urb->actual_length);
1340 es58x_print_hex_dump(&es58x_dev->rx_cmd_buf, tmp_cmd_buf_len);
1341 es58x_print_hex_dump(urb->transfer_buffer, urb->actual_length);
1342 return urb->actual_length;
1345 es58x_handle_urb_cmd(es58x_dev, &es58x_dev->rx_cmd_buf);
1346 return urb_cmd_len - tmp_cmd_buf_len; /* consumed length */
1350 * es58x_split_urb() - Cut the received URB in individual URB commands.
1351 * @es58x_dev: ES58X device.
1352 * @urb: last urb buffer received.
1354 * The device might send urb in bulk format (i.e. several URB commands
1355 * concatenated together). This function will split all the commands
1356 * contained in the urb.
1359 * number of bytes consumed from @urb if successful.
1361 * -ENODATA if the URB command is incomplete.
1363 * -EBADMSG if the URB command is incorrect.
1365 static signed int es58x_split_urb(struct es58x_device *es58x_dev,
1368 union es58x_urb_cmd *urb_cmd;
1369 u8 *raw_cmd = urb->transfer_buffer;
1370 s32 raw_cmd_len = urb->actual_length;
1373 if (es58x_dev->rx_cmd_buf_len != 0) {
1374 ret = es58x_handle_incomplete_cmd(es58x_dev, urb);
1375 if (ret != -ENODATA)
1376 es58x_dev->rx_cmd_buf_len = 0;
1384 while (raw_cmd_len > 0) {
1385 if (raw_cmd[0] == ES58X_HEARTBEAT) {
1390 urb_cmd = (union es58x_urb_cmd *)raw_cmd;
1391 ret = es58x_check_rx_urb(es58x_dev, urb_cmd, raw_cmd_len);
1393 es58x_handle_urb_cmd(es58x_dev, urb_cmd);
1394 } else if (ret == -ENODATA) {
1395 es58x_copy_to_cmd_buf(es58x_dev, raw_cmd, raw_cmd_len);
1397 } else if (ret < 0) {
1398 ret = es58x_split_urb_try_recovery(es58x_dev, raw_cmd,
1411 * es58x_read_bulk_callback() - Callback for reading data from device.
1412 * @urb: last urb buffer received.
1414 * This function gets eventually called each time an URB is received
1415 * from the ES58X device.
1417 * Checks urb status, calls read function and resubmits urb read
1420 static void es58x_read_bulk_callback(struct urb *urb)
1422 struct es58x_device *es58x_dev = urb->context;
1423 const struct device *dev = es58x_dev->dev;
1426 switch (urb->status) {
1427 case 0: /* success */
1431 dev_err_ratelimited(dev, "%s: error %pe\n",
1432 __func__, ERR_PTR(urb->status));
1433 es58x_print_hex_dump_debug(urb->transfer_buffer,
1434 urb->transfer_buffer_length);
1438 dev_warn_ratelimited(dev, "%s: error %pe. Device unplugged?\n",
1439 __func__, ERR_PTR(urb->status));
1444 dev_err_ratelimited(dev, "%s: error %pe\n",
1445 __func__, ERR_PTR(urb->status));
1449 dev_dbg_ratelimited(dev, "%s: error %pe\n",
1450 __func__, ERR_PTR(urb->status));
1454 dev_err_ratelimited(dev, "%s: error %pe\n",
1455 __func__, ERR_PTR(urb->status));
1459 ret = es58x_split_urb(es58x_dev, urb);
1460 if ((ret != -ENODATA) && ret < 0) {
1461 dev_err(es58x_dev->dev, "es58x_split_urb() returned error %pe",
1463 es58x_print_hex_dump_debug(urb->transfer_buffer,
1464 urb->actual_length);
1466 /* Because the urb command could not be parsed,
1467 * channel_id is not confirmed. Incrementing rx_errors
1468 * count of all channels.
1470 es58x_increment_rx_errors(es58x_dev);
1474 usb_fill_bulk_urb(urb, es58x_dev->udev, es58x_dev->rx_pipe,
1475 urb->transfer_buffer, urb->transfer_buffer_length,
1476 es58x_read_bulk_callback, es58x_dev);
1478 ret = usb_submit_urb(urb, GFP_ATOMIC);
1479 if (ret == -ENODEV) {
1480 for (i = 0; i < es58x_dev->num_can_ch; i++)
1481 if (es58x_dev->netdev[i])
1482 netif_device_detach(es58x_dev->netdev[i]);
1484 dev_err_ratelimited(dev,
1485 "Failed resubmitting read bulk urb: %pe\n",
1490 usb_free_coherent(urb->dev, urb->transfer_buffer_length,
1491 urb->transfer_buffer, urb->transfer_dma);
1495 * es58x_write_bulk_callback() - Callback after writing data to the device.
1496 * @urb: urb buffer which was previously submitted.
1498 * This function gets eventually called each time an URB was sent to
1501 * Puts the @urb back to the urbs idle anchor and tries to restart the
1504 static void es58x_write_bulk_callback(struct urb *urb)
1506 struct net_device *netdev = urb->context;
1507 struct es58x_device *es58x_dev = es58x_priv(netdev)->es58x_dev;
1509 switch (urb->status) {
1510 case 0: /* success */
1514 if (net_ratelimit())
1515 netdev_err(netdev, "%s: error %pe\n",
1516 __func__, ERR_PTR(urb->status));
1517 es58x_print_hex_dump(urb->transfer_buffer,
1518 urb->transfer_buffer_length);
1522 if (net_ratelimit())
1523 netdev_dbg(netdev, "%s: error %pe\n",
1524 __func__, ERR_PTR(urb->status));
1525 usb_free_coherent(urb->dev,
1526 es58x_dev->param->tx_urb_cmd_max_len,
1527 urb->transfer_buffer, urb->transfer_dma);
1531 if (net_ratelimit())
1532 netdev_info(netdev, "%s: error %pe\n",
1533 __func__, ERR_PTR(urb->status));
1537 usb_anchor_urb(urb, &es58x_dev->tx_urbs_idle);
1538 atomic_inc(&es58x_dev->tx_urbs_idle_cnt);
1542 * es58x_alloc_urb() - Allocate memory for an URB and its transfer
1544 * @es58x_dev: ES58X device.
1545 * @urb: URB to be allocated.
1546 * @buf: used to return DMA address of buffer.
1547 * @buf_len: requested buffer size.
1548 * @mem_flags: affect whether allocation may block.
1550 * Allocates an URB and its @transfer_buffer and set its @transfer_dma
1553 * This function is used at start-up to allocate all RX URBs at once
1554 * and during run time for TX URBs.
1556 * Return: zero on success, -ENOMEM if no memory is available.
1558 static int es58x_alloc_urb(struct es58x_device *es58x_dev, struct urb **urb,
1559 u8 **buf, size_t buf_len, gfp_t mem_flags)
1561 *urb = usb_alloc_urb(0, mem_flags);
1563 dev_err(es58x_dev->dev, "No memory left for URBs\n");
1567 *buf = usb_alloc_coherent(es58x_dev->udev, buf_len,
1568 mem_flags, &(*urb)->transfer_dma);
1570 dev_err(es58x_dev->dev, "No memory left for USB buffer\n");
1575 (*urb)->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
1581 * es58x_get_tx_urb() - Get an URB for transmission.
1582 * @es58x_dev: ES58X device.
1584 * Gets an URB from the idle urbs anchor or allocate a new one if the
1587 * If there are more than ES58X_TX_URBS_MAX in the idle anchor, do
1588 * some garbage collection. The garbage collection is done here
1589 * instead of within es58x_write_bulk_callback() because
1590 * usb_free_coherent() should not be used in IRQ context:
1591 * c.f. WARN_ON(irqs_disabled()) in dma_free_attrs().
1593 * Return: a pointer to an URB on success, NULL if no memory is
1596 static struct urb *es58x_get_tx_urb(struct es58x_device *es58x_dev)
1598 atomic_t *idle_cnt = &es58x_dev->tx_urbs_idle_cnt;
1599 struct urb *urb = usb_get_from_anchor(&es58x_dev->tx_urbs_idle);
1605 tx_buf_len = es58x_dev->param->tx_urb_cmd_max_len;
1606 if (es58x_alloc_urb(es58x_dev, &urb, &buf, tx_buf_len,
1610 usb_fill_bulk_urb(urb, es58x_dev->udev, es58x_dev->tx_pipe,
1611 buf, tx_buf_len, NULL, NULL);
1615 while (atomic_dec_return(idle_cnt) > ES58X_TX_URBS_MAX) {
1616 /* Garbage collector */
1617 struct urb *tmp = usb_get_from_anchor(&es58x_dev->tx_urbs_idle);
1621 usb_free_coherent(tmp->dev,
1622 es58x_dev->param->tx_urb_cmd_max_len,
1623 tmp->transfer_buffer, tmp->transfer_dma);
1631 * es58x_submit_urb() - Send data to the device.
1632 * @es58x_dev: ES58X device.
1633 * @urb: URB to be sent.
1634 * @netdev: CAN network device.
1636 * Return: zero on success, errno when any error occurs.
1638 static int es58x_submit_urb(struct es58x_device *es58x_dev, struct urb *urb,
1639 struct net_device *netdev)
1643 es58x_set_crc(urb->transfer_buffer, urb->transfer_buffer_length);
1644 usb_fill_bulk_urb(urb, es58x_dev->udev, es58x_dev->tx_pipe,
1645 urb->transfer_buffer, urb->transfer_buffer_length,
1646 es58x_write_bulk_callback, netdev);
1647 usb_anchor_urb(urb, &es58x_dev->tx_urbs_busy);
1648 ret = usb_submit_urb(urb, GFP_ATOMIC);
1650 netdev_err(netdev, "%s: USB send urb failure: %pe\n",
1651 __func__, ERR_PTR(ret));
1652 usb_unanchor_urb(urb);
1653 usb_free_coherent(urb->dev,
1654 es58x_dev->param->tx_urb_cmd_max_len,
1655 urb->transfer_buffer, urb->transfer_dma);
1663 * es58x_send_msg() - Prepare an URB and submit it.
1664 * @es58x_dev: ES58X device.
1665 * @cmd_type: Command type.
1666 * @cmd_id: Command ID.
1667 * @msg: ES58X message to be sent.
1668 * @msg_len: Length of @msg.
1669 * @channel_idx: Index of the network device.
1671 * Creates an URB command from a given message, sets the header and the
1672 * CRC and then submits it.
1674 * Return: zero on success, errno when any error occurs.
1676 int es58x_send_msg(struct es58x_device *es58x_dev, u8 cmd_type, u8 cmd_id,
1677 const void *msg, u16 msg_len, int channel_idx)
1679 struct net_device *netdev;
1680 union es58x_urb_cmd *urb_cmd;
1684 if (channel_idx == ES58X_CHANNEL_IDX_NA)
1685 netdev = es58x_dev->netdev[0]; /* Default to first channel */
1687 netdev = es58x_dev->netdev[channel_idx];
1689 urb_cmd_len = es58x_get_urb_cmd_len(es58x_dev, msg_len);
1690 if (urb_cmd_len > es58x_dev->param->tx_urb_cmd_max_len)
1693 urb = es58x_get_tx_urb(es58x_dev);
1697 urb_cmd = urb->transfer_buffer;
1698 es58x_dev->ops->fill_urb_header(urb_cmd, cmd_type, cmd_id,
1699 channel_idx, msg_len);
1700 memcpy(&urb_cmd->raw_cmd[es58x_dev->param->urb_cmd_header_len],
1702 urb->transfer_buffer_length = urb_cmd_len;
1704 return es58x_submit_urb(es58x_dev, urb, netdev);
1708 * es58x_alloc_rx_urbs() - Allocate RX URBs.
1709 * @es58x_dev: ES58X device.
1711 * Allocate URBs for reception and anchor them.
1713 * Return: zero on success, errno when any error occurs.
1715 static int es58x_alloc_rx_urbs(struct es58x_device *es58x_dev)
1717 const struct device *dev = es58x_dev->dev;
1718 const struct es58x_parameters *param = es58x_dev->param;
1719 size_t rx_buf_len = es58x_dev->rx_max_packet_size;
1725 for (i = 0; i < param->rx_urb_max; i++) {
1726 ret = es58x_alloc_urb(es58x_dev, &urb, &buf, rx_buf_len,
1731 usb_fill_bulk_urb(urb, es58x_dev->udev, es58x_dev->rx_pipe,
1732 buf, rx_buf_len, es58x_read_bulk_callback,
1734 usb_anchor_urb(urb, &es58x_dev->rx_urbs);
1736 ret = usb_submit_urb(urb, GFP_KERNEL);
1738 usb_unanchor_urb(urb);
1739 usb_free_coherent(es58x_dev->udev, rx_buf_len,
1740 buf, urb->transfer_dma);
1748 dev_err(dev, "%s: Could not setup any rx URBs\n", __func__);
1751 dev_dbg(dev, "%s: Allocated %d rx URBs each of size %zu\n",
1752 __func__, i, rx_buf_len);
1758 * es58x_free_urbs() - Free all the TX and RX URBs.
1759 * @es58x_dev: ES58X device.
1761 static void es58x_free_urbs(struct es58x_device *es58x_dev)
1765 if (!usb_wait_anchor_empty_timeout(&es58x_dev->tx_urbs_busy, 1000)) {
1766 dev_err(es58x_dev->dev, "%s: Timeout, some TX urbs still remain\n",
1768 usb_kill_anchored_urbs(&es58x_dev->tx_urbs_busy);
1771 while ((urb = usb_get_from_anchor(&es58x_dev->tx_urbs_idle)) != NULL) {
1772 usb_free_coherent(urb->dev, es58x_dev->param->tx_urb_cmd_max_len,
1773 urb->transfer_buffer, urb->transfer_dma);
1775 atomic_dec(&es58x_dev->tx_urbs_idle_cnt);
1777 if (atomic_read(&es58x_dev->tx_urbs_idle_cnt))
1778 dev_err(es58x_dev->dev,
1779 "All idle urbs were freed but tx_urb_idle_cnt is %d\n",
1780 atomic_read(&es58x_dev->tx_urbs_idle_cnt));
1782 usb_kill_anchored_urbs(&es58x_dev->rx_urbs);
1786 * es58x_open() - Enable the network device.
1787 * @netdev: CAN network device.
1789 * Called when the network transitions to the up state. Allocate the
1790 * URB resources if needed and open the channel.
1792 * Return: zero on success, errno when any error occurs.
1794 static int es58x_open(struct net_device *netdev)
1796 struct es58x_device *es58x_dev = es58x_priv(netdev)->es58x_dev;
1799 if (atomic_inc_return(&es58x_dev->opened_channel_cnt) == 1) {
1800 ret = es58x_alloc_rx_urbs(es58x_dev);
1804 ret = es58x_set_realtime_diff_ns(es58x_dev);
1809 ret = open_candev(netdev);
1813 ret = es58x_dev->ops->enable_channel(es58x_priv(netdev));
1817 netif_start_queue(netdev);
1822 if (atomic_dec_and_test(&es58x_dev->opened_channel_cnt))
1823 es58x_free_urbs(es58x_dev);
1824 netdev_err(netdev, "%s: Could not open the network device: %pe\n",
1825 __func__, ERR_PTR(ret));
1831 * es58x_stop() - Disable the network device.
1832 * @netdev: CAN network device.
1834 * Called when the network transitions to the down state. If all the
1835 * channels of the device are closed, free the URB resources which are
1836 * not needed anymore.
1838 * Return: zero on success, errno when any error occurs.
1840 static int es58x_stop(struct net_device *netdev)
1842 struct es58x_priv *priv = es58x_priv(netdev);
1843 struct es58x_device *es58x_dev = priv->es58x_dev;
1846 netif_stop_queue(netdev);
1847 ret = es58x_dev->ops->disable_channel(priv);
1851 priv->can.state = CAN_STATE_STOPPED;
1852 es58x_can_reset_echo_fifo(netdev);
1853 close_candev(netdev);
1855 es58x_flush_pending_tx_msg(netdev);
1857 if (atomic_dec_and_test(&es58x_dev->opened_channel_cnt))
1858 es58x_free_urbs(es58x_dev);
1864 * es58x_xmit_commit() - Send the bulk urb.
1865 * @netdev: CAN network device.
1867 * Do the bulk send. This function should be called only once by bulk
1870 * Return: zero on success, errno when any error occurs.
1872 static int es58x_xmit_commit(struct net_device *netdev)
1874 struct es58x_priv *priv = es58x_priv(netdev);
1877 if (!es58x_is_can_state_active(netdev))
1880 if (es58x_is_echo_skb_threshold_reached(priv))
1881 netif_stop_queue(netdev);
1883 ret = es58x_submit_urb(priv->es58x_dev, priv->tx_urb, netdev);
1885 priv->tx_urb = NULL;
1891 * es58x_xmit_more() - Can we put more packets?
1892 * @priv: ES58X private parameters related to the network device.
1894 * Return: true if we can put more, false if it is time to send.
1896 static bool es58x_xmit_more(struct es58x_priv *priv)
1898 unsigned int free_slots =
1899 priv->can.echo_skb_max - (priv->tx_head - priv->tx_tail);
1901 return netdev_xmit_more() && free_slots > 0 &&
1902 priv->tx_can_msg_cnt < priv->es58x_dev->param->tx_bulk_max;
1906 * es58x_start_xmit() - Transmit an skb.
1907 * @skb: socket buffer of a CAN message.
1908 * @netdev: CAN network device.
1910 * Called when a packet needs to be transmitted.
1912 * This function relies on Byte Queue Limits (BQL). The main benefit
1913 * is to increase the throughput by allowing bulk transfers
1914 * (c.f. xmit_more flag).
1916 * Queues up to tx_bulk_max messages in &tx_urb buffer and does
1917 * a bulk send of all messages in one single URB.
1919 * Return: NETDEV_TX_OK regardless of if we could transmit the @skb or
1922 static netdev_tx_t es58x_start_xmit(struct sk_buff *skb,
1923 struct net_device *netdev)
1925 struct es58x_priv *priv = es58x_priv(netdev);
1926 struct es58x_device *es58x_dev = priv->es58x_dev;
1927 unsigned int frame_len;
1930 if (can_dropped_invalid_skb(netdev, skb)) {
1933 return NETDEV_TX_OK;
1936 if (priv->tx_urb && priv->tx_can_msg_is_fd != can_is_canfd_skb(skb)) {
1937 /* Can not do bulk send with mixed CAN and CAN FD frames. */
1938 ret = es58x_xmit_commit(netdev);
1943 if (!priv->tx_urb) {
1944 priv->tx_urb = es58x_get_tx_urb(es58x_dev);
1945 if (!priv->tx_urb) {
1949 priv->tx_can_msg_cnt = 0;
1950 priv->tx_can_msg_is_fd = can_is_canfd_skb(skb);
1953 ret = es58x_dev->ops->tx_can_msg(priv, skb);
1957 frame_len = can_skb_get_frame_len(skb);
1958 ret = can_put_echo_skb(skb, netdev,
1959 priv->tx_head & es58x_dev->param->fifo_mask,
1963 netdev_sent_queue(netdev, frame_len);
1966 priv->tx_can_msg_cnt++;
1969 if (!es58x_xmit_more(priv)) {
1970 ret = es58x_xmit_commit(netdev);
1975 return NETDEV_TX_OK;
1979 netdev->stats.tx_dropped++;
1981 netdev_warn(netdev, "%s: send message failure: %pe\n",
1982 __func__, ERR_PTR(ret));
1983 netdev->stats.tx_errors++;
1984 es58x_flush_pending_tx_msg(netdev);
1985 return NETDEV_TX_OK;
1988 static const struct net_device_ops es58x_netdev_ops = {
1989 .ndo_open = es58x_open,
1990 .ndo_stop = es58x_stop,
1991 .ndo_start_xmit = es58x_start_xmit
1995 * es58x_set_mode() - Change network device mode.
1996 * @netdev: CAN network device.
1997 * @mode: either %CAN_MODE_START, %CAN_MODE_STOP or %CAN_MODE_SLEEP
1999 * Currently, this function is only used to stop and restart the
2000 * channel during a bus off event (c.f. es58x_rx_err_msg() and
2001 * drivers/net/can/dev.c:can_restart() which are the two only
2004 * Return: zero on success, errno when any error occurs.
2006 static int es58x_set_mode(struct net_device *netdev, enum can_mode mode)
2008 struct es58x_priv *priv = es58x_priv(netdev);
2011 case CAN_MODE_START:
2012 switch (priv->can.state) {
2013 case CAN_STATE_BUS_OFF:
2014 return priv->es58x_dev->ops->enable_channel(priv);
2016 case CAN_STATE_STOPPED:
2017 return es58x_open(netdev);
2019 case CAN_STATE_ERROR_ACTIVE:
2020 case CAN_STATE_ERROR_WARNING:
2021 case CAN_STATE_ERROR_PASSIVE:
2027 switch (priv->can.state) {
2028 case CAN_STATE_STOPPED:
2031 case CAN_STATE_ERROR_ACTIVE:
2032 case CAN_STATE_ERROR_WARNING:
2033 case CAN_STATE_ERROR_PASSIVE:
2034 case CAN_STATE_BUS_OFF:
2036 return priv->es58x_dev->ops->disable_channel(priv);
2039 case CAN_MODE_SLEEP:
2046 * es58x_init_priv() - Initialize private parameters.
2047 * @es58x_dev: ES58X device.
2048 * @priv: ES58X private parameters related to the network device.
2049 * @channel_idx: Index of the network device.
2051 static void es58x_init_priv(struct es58x_device *es58x_dev,
2052 struct es58x_priv *priv, int channel_idx)
2054 const struct es58x_parameters *param = es58x_dev->param;
2055 struct can_priv *can = &priv->can;
2057 priv->es58x_dev = es58x_dev;
2058 priv->channel_idx = channel_idx;
2059 priv->tx_urb = NULL;
2060 priv->tx_can_msg_cnt = 0;
2062 can->bittiming_const = param->bittiming_const;
2063 if (param->ctrlmode_supported & CAN_CTRLMODE_FD) {
2064 can->data_bittiming_const = param->data_bittiming_const;
2065 can->tdc_const = param->tdc_const;
2067 can->bitrate_max = param->bitrate_max;
2068 can->clock = param->clock;
2069 can->state = CAN_STATE_STOPPED;
2070 can->ctrlmode_supported = param->ctrlmode_supported;
2071 can->do_set_mode = es58x_set_mode;
2075 * es58x_init_netdev() - Initialize the network device.
2076 * @es58x_dev: ES58X device.
2077 * @channel_idx: Index of the network device.
2079 * Return: zero on success, errno when any error occurs.
2081 static int es58x_init_netdev(struct es58x_device *es58x_dev, int channel_idx)
2083 struct net_device *netdev;
2084 struct device *dev = es58x_dev->dev;
2087 netdev = alloc_candev(sizeof(struct es58x_priv),
2088 es58x_dev->param->fifo_mask + 1);
2090 dev_err(dev, "Could not allocate candev\n");
2093 SET_NETDEV_DEV(netdev, dev);
2094 es58x_dev->netdev[channel_idx] = netdev;
2095 es58x_init_priv(es58x_dev, es58x_priv(netdev), channel_idx);
2097 netdev->netdev_ops = &es58x_netdev_ops;
2098 netdev->flags |= IFF_ECHO; /* We support local echo */
2100 ret = register_candev(netdev);
2104 netdev_queue_set_dql_min_limit(netdev_get_tx_queue(netdev, 0),
2105 es58x_dev->param->dql_min_limit);
2111 * es58x_get_product_info() - Get the product information and print them.
2112 * @es58x_dev: ES58X device.
2114 * Do a synchronous call to get the product information.
2116 * Return: zero on success, errno when any error occurs.
2118 static int es58x_get_product_info(struct es58x_device *es58x_dev)
2120 struct usb_device *udev = es58x_dev->udev;
2121 const int es58x_prod_info_idx = 6;
2122 /* Empirical tests show a prod_info length of maximum 83,
2123 * below should be more than enough.
2125 const size_t prod_info_len = 127;
2129 prod_info = kmalloc(prod_info_len, GFP_KERNEL);
2133 ret = usb_string(udev, es58x_prod_info_idx, prod_info, prod_info_len);
2135 dev_err(es58x_dev->dev,
2136 "%s: Could not read the product info: %pe\n",
2137 __func__, ERR_PTR(ret));
2140 if (ret >= prod_info_len - 1) {
2141 dev_warn(es58x_dev->dev,
2142 "%s: Buffer is too small, result might be truncated\n",
2145 dev_info(es58x_dev->dev, "Product info: %s\n", prod_info);
2149 return ret < 0 ? ret : 0;
2153 * es58x_init_es58x_dev() - Initialize the ES58X device.
2154 * @intf: USB interface.
2155 * @p_es58x_dev: pointer to the address of the ES58X device.
2156 * @driver_info: Quirks of the device.
2158 * Return: zero on success, errno when any error occurs.
2160 static int es58x_init_es58x_dev(struct usb_interface *intf,
2161 struct es58x_device **p_es58x_dev,
2162 kernel_ulong_t driver_info)
2164 struct device *dev = &intf->dev;
2165 struct es58x_device *es58x_dev;
2166 const struct es58x_parameters *param;
2167 const struct es58x_operators *ops;
2168 struct usb_device *udev = interface_to_usbdev(intf);
2169 struct usb_endpoint_descriptor *ep_in, *ep_out;
2173 "Starting %s %s (Serial Number %s) driver version %s\n",
2174 udev->manufacturer, udev->product, udev->serial, DRV_VERSION);
2176 ret = usb_find_common_endpoints(intf->cur_altsetting, &ep_in, &ep_out,
2181 if (driver_info & ES58X_FD_FAMILY) {
2182 param = &es58x_fd_param;
2183 ops = &es58x_fd_ops;
2185 param = &es581_4_param;
2189 es58x_dev = kzalloc(es58x_sizeof_es58x_device(param), GFP_KERNEL);
2193 es58x_dev->param = param;
2194 es58x_dev->ops = ops;
2195 es58x_dev->dev = dev;
2196 es58x_dev->udev = udev;
2198 if (driver_info & ES58X_DUAL_CHANNEL)
2199 es58x_dev->num_can_ch = 2;
2201 es58x_dev->num_can_ch = 1;
2203 init_usb_anchor(&es58x_dev->rx_urbs);
2204 init_usb_anchor(&es58x_dev->tx_urbs_idle);
2205 init_usb_anchor(&es58x_dev->tx_urbs_busy);
2206 atomic_set(&es58x_dev->tx_urbs_idle_cnt, 0);
2207 atomic_set(&es58x_dev->opened_channel_cnt, 0);
2208 usb_set_intfdata(intf, es58x_dev);
2210 es58x_dev->rx_pipe = usb_rcvbulkpipe(es58x_dev->udev,
2211 ep_in->bEndpointAddress);
2212 es58x_dev->tx_pipe = usb_sndbulkpipe(es58x_dev->udev,
2213 ep_out->bEndpointAddress);
2214 es58x_dev->rx_max_packet_size = le16_to_cpu(ep_in->wMaxPacketSize);
2216 *p_es58x_dev = es58x_dev;
2222 * es58x_probe() - Initialize the USB device.
2223 * @intf: USB interface.
2224 * @id: USB device ID.
2226 * Return: zero on success, -ENODEV if the interface is not supported
2227 * or errno when any other error occurs.
2229 static int es58x_probe(struct usb_interface *intf,
2230 const struct usb_device_id *id)
2232 struct es58x_device *es58x_dev;
2235 ret = es58x_init_es58x_dev(intf, &es58x_dev, id->driver_info);
2239 ret = es58x_get_product_info(es58x_dev);
2241 goto cleanup_es58x_dev;
2243 for (ch_idx = 0; ch_idx < es58x_dev->num_can_ch; ch_idx++) {
2244 ret = es58x_init_netdev(es58x_dev, ch_idx);
2246 goto cleanup_candev;
2252 for (ch_idx = 0; ch_idx < es58x_dev->num_can_ch; ch_idx++)
2253 if (es58x_dev->netdev[ch_idx]) {
2254 unregister_candev(es58x_dev->netdev[ch_idx]);
2255 free_candev(es58x_dev->netdev[ch_idx]);
2264 * es58x_disconnect() - Disconnect the USB device.
2265 * @intf: USB interface
2267 * Called by the usb core when driver is unloaded or device is
2270 static void es58x_disconnect(struct usb_interface *intf)
2272 struct es58x_device *es58x_dev = usb_get_intfdata(intf);
2273 struct net_device *netdev;
2276 dev_info(&intf->dev, "Disconnecting %s %s\n",
2277 es58x_dev->udev->manufacturer, es58x_dev->udev->product);
2279 for (i = 0; i < es58x_dev->num_can_ch; i++) {
2280 netdev = es58x_dev->netdev[i];
2283 unregister_candev(netdev);
2284 es58x_dev->netdev[i] = NULL;
2285 free_candev(netdev);
2288 es58x_free_urbs(es58x_dev);
2291 usb_set_intfdata(intf, NULL);
2294 static struct usb_driver es58x_driver = {
2295 .name = ES58X_MODULE_NAME,
2296 .probe = es58x_probe,
2297 .disconnect = es58x_disconnect,
2298 .id_table = es58x_id_table
2301 module_usb_driver(es58x_driver);