Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0
0002 
0003 /* Driver for ETAS GmbH ES58X USB CAN(-FD) Bus Interfaces.
0004  *
0005  * File es58x_core.c: Core logic to manage the network devices and the
0006  * USB interface.
0007  *
0008  * Copyright (c) 2019 Robert Bosch Engineering and Business Solutions. All rights reserved.
0009  * Copyright (c) 2020 ETAS K.K.. All rights reserved.
0010  * Copyright (c) 2020, 2021 Vincent Mailhol <mailhol.vincent@wanadoo.fr>
0011  */
0012 
0013 #include <linux/ethtool.h>
0014 #include <linux/kernel.h>
0015 #include <linux/module.h>
0016 #include <linux/usb.h>
0017 #include <linux/crc16.h>
0018 #include <asm/unaligned.h>
0019 
0020 #include "es58x_core.h"
0021 
0022 MODULE_AUTHOR("Vincent Mailhol <mailhol.vincent@wanadoo.fr>");
0023 MODULE_AUTHOR("Arunachalam Santhanam <arunachalam.santhanam@in.bosch.com>");
0024 MODULE_DESCRIPTION("Socket CAN driver for ETAS ES58X USB adapters");
0025 MODULE_LICENSE("GPL v2");
0026 
0027 #define ES58X_VENDOR_ID 0x108C
0028 #define ES581_4_PRODUCT_ID 0x0159
0029 #define ES582_1_PRODUCT_ID 0x0168
0030 #define ES584_1_PRODUCT_ID 0x0169
0031 
0032 /* ES58X FD has some interface protocols unsupported by this driver. */
0033 #define ES58X_FD_INTERFACE_PROTOCOL 0
0034 
0035 /* Table of devices which work with this driver. */
0036 static const struct usb_device_id es58x_id_table[] = {
0037     {
0038         /* ETAS GmbH ES581.4 USB dual-channel CAN Bus Interface module. */
0039         USB_DEVICE(ES58X_VENDOR_ID, ES581_4_PRODUCT_ID),
0040         .driver_info = ES58X_DUAL_CHANNEL
0041     }, {
0042         /* ETAS GmbH ES582.1 USB dual-channel CAN FD Bus Interface module. */
0043         USB_DEVICE_INTERFACE_PROTOCOL(ES58X_VENDOR_ID, ES582_1_PRODUCT_ID,
0044                           ES58X_FD_INTERFACE_PROTOCOL),
0045         .driver_info = ES58X_DUAL_CHANNEL | ES58X_FD_FAMILY
0046     }, {
0047         /* ETAS GmbH ES584.1 USB single-channel CAN FD Bus Interface module. */
0048         USB_DEVICE_INTERFACE_PROTOCOL(ES58X_VENDOR_ID, ES584_1_PRODUCT_ID,
0049                           ES58X_FD_INTERFACE_PROTOCOL),
0050         .driver_info = ES58X_FD_FAMILY
0051     }, {
0052         /* Terminating entry */
0053     }
0054 };
0055 
0056 MODULE_DEVICE_TABLE(usb, es58x_id_table);
0057 
0058 #define es58x_print_hex_dump(buf, len)                  \
0059     print_hex_dump(KERN_DEBUG,                  \
0060                KBUILD_MODNAME " " __stringify(buf) ": ",    \
0061                DUMP_PREFIX_NONE, 16, 1, buf, len, false)
0062 
0063 #define es58x_print_hex_dump_debug(buf, len)                 \
0064     print_hex_dump_debug(KBUILD_MODNAME " " __stringify(buf) ": ",\
0065                  DUMP_PREFIX_NONE, 16, 1, buf, len, false)
0066 
0067 /* The last two bytes of an ES58X command is a CRC16. The first two
0068  * bytes (the start of frame) are skipped and the CRC calculation
0069  * starts on the third byte.
0070  */
0071 #define ES58X_CRC_CALC_OFFSET sizeof_field(union es58x_urb_cmd, sof)
0072 
0073 /**
0074  * es58x_calculate_crc() - Compute the crc16 of a given URB.
0075  * @urb_cmd: The URB command for which we want to calculate the CRC.
0076  * @urb_len: Length of @urb_cmd. Must be at least bigger than 4
0077  *  (ES58X_CRC_CALC_OFFSET + sizeof(crc))
0078  *
0079  * Return: crc16 value.
0080  */
0081 static u16 es58x_calculate_crc(const union es58x_urb_cmd *urb_cmd, u16 urb_len)
0082 {
0083     u16 crc;
0084     ssize_t len = urb_len - ES58X_CRC_CALC_OFFSET - sizeof(crc);
0085 
0086     crc = crc16(0, &urb_cmd->raw_cmd[ES58X_CRC_CALC_OFFSET], len);
0087     return crc;
0088 }
0089 
0090 /**
0091  * es58x_get_crc() - Get the CRC value of a given URB.
0092  * @urb_cmd: The URB command for which we want to get the CRC.
0093  * @urb_len: Length of @urb_cmd. Must be at least bigger than 4
0094  *  (ES58X_CRC_CALC_OFFSET + sizeof(crc))
0095  *
0096  * Return: crc16 value.
0097  */
0098 static u16 es58x_get_crc(const union es58x_urb_cmd *urb_cmd, u16 urb_len)
0099 {
0100     u16 crc;
0101     const __le16 *crc_addr;
0102 
0103     crc_addr = (__le16 *)&urb_cmd->raw_cmd[urb_len - sizeof(crc)];
0104     crc = get_unaligned_le16(crc_addr);
0105     return crc;
0106 }
0107 
0108 /**
0109  * es58x_set_crc() - Set the CRC value of a given URB.
0110  * @urb_cmd: The URB command for which we want to get the CRC.
0111  * @urb_len: Length of @urb_cmd. Must be at least bigger than 4
0112  *  (ES58X_CRC_CALC_OFFSET + sizeof(crc))
0113  */
0114 static void es58x_set_crc(union es58x_urb_cmd *urb_cmd, u16 urb_len)
0115 {
0116     u16 crc;
0117     __le16 *crc_addr;
0118 
0119     crc = es58x_calculate_crc(urb_cmd, urb_len);
0120     crc_addr = (__le16 *)&urb_cmd->raw_cmd[urb_len - sizeof(crc)];
0121     put_unaligned_le16(crc, crc_addr);
0122 }
0123 
0124 /**
0125  * es58x_check_crc() - Validate the CRC value of a given URB.
0126  * @es58x_dev: ES58X device.
0127  * @urb_cmd: The URB command for which we want to check the CRC.
0128  * @urb_len: Length of @urb_cmd. Must be at least bigger than 4
0129  *  (ES58X_CRC_CALC_OFFSET + sizeof(crc))
0130  *
0131  * Return: zero on success, -EBADMSG if the CRC check fails.
0132  */
0133 static int es58x_check_crc(struct es58x_device *es58x_dev,
0134                const union es58x_urb_cmd *urb_cmd, u16 urb_len)
0135 {
0136     u16 calculated_crc = es58x_calculate_crc(urb_cmd, urb_len);
0137     u16 expected_crc = es58x_get_crc(urb_cmd, urb_len);
0138 
0139     if (expected_crc != calculated_crc) {
0140         dev_err_ratelimited(es58x_dev->dev,
0141                     "%s: Bad CRC, urb_len: %d\n",
0142                     __func__, urb_len);
0143         return -EBADMSG;
0144     }
0145 
0146     return 0;
0147 }
0148 
0149 /**
0150  * es58x_timestamp_to_ns() - Convert a timestamp value received from a
0151  *  ES58X device to nanoseconds.
0152  * @timestamp: Timestamp received from a ES58X device.
0153  *
0154  * The timestamp received from ES58X is expressed in multiples of 0.5
0155  * micro seconds. This function converts it in to nanoseconds.
0156  *
0157  * Return: Timestamp value in nanoseconds.
0158  */
0159 static u64 es58x_timestamp_to_ns(u64 timestamp)
0160 {
0161     const u64 es58x_timestamp_ns_mult_coef = 500ULL;
0162 
0163     return es58x_timestamp_ns_mult_coef * timestamp;
0164 }
0165 
0166 /**
0167  * es58x_set_skb_timestamp() - Set the hardware timestamp of an skb.
0168  * @netdev: CAN network device.
0169  * @skb: socket buffer of a CAN message.
0170  * @timestamp: Timestamp received from an ES58X device.
0171  *
0172  * Used for both received and echo messages.
0173  */
0174 static void es58x_set_skb_timestamp(struct net_device *netdev,
0175                     struct sk_buff *skb, u64 timestamp)
0176 {
0177     struct es58x_device *es58x_dev = es58x_priv(netdev)->es58x_dev;
0178     struct skb_shared_hwtstamps *hwts;
0179 
0180     hwts = skb_hwtstamps(skb);
0181     /* Ignoring overflow (overflow on 64 bits timestamp with nano
0182      * second precision would occur after more than 500 years).
0183      */
0184     hwts->hwtstamp = ns_to_ktime(es58x_timestamp_to_ns(timestamp) +
0185                      es58x_dev->realtime_diff_ns);
0186 }
0187 
0188 /**
0189  * es58x_rx_timestamp() - Handle a received timestamp.
0190  * @es58x_dev: ES58X device.
0191  * @timestamp: Timestamp received from a ES58X device.
0192  *
0193  * Calculate the difference between the ES58X device and the kernel
0194  * internal clocks. This difference will be later used as an offset to
0195  * convert the timestamps of RX and echo messages to match the kernel
0196  * system time (e.g. convert to UNIX time).
0197  */
0198 void es58x_rx_timestamp(struct es58x_device *es58x_dev, u64 timestamp)
0199 {
0200     u64 ktime_real_ns = ktime_get_real_ns();
0201     u64 device_timestamp = es58x_timestamp_to_ns(timestamp);
0202 
0203     dev_dbg(es58x_dev->dev, "%s: request round-trip time: %llu ns\n",
0204         __func__, ktime_real_ns - es58x_dev->ktime_req_ns);
0205 
0206     es58x_dev->realtime_diff_ns =
0207         (es58x_dev->ktime_req_ns + ktime_real_ns) / 2 - device_timestamp;
0208     es58x_dev->ktime_req_ns = 0;
0209 
0210     dev_dbg(es58x_dev->dev,
0211         "%s: Device timestamp: %llu, diff with kernel: %llu\n",
0212         __func__, device_timestamp, es58x_dev->realtime_diff_ns);
0213 }
0214 
0215 /**
0216  * es58x_set_realtime_diff_ns() - Calculate difference between the
0217  *  clocks of the ES58X device and the kernel
0218  * @es58x_dev: ES58X device.
0219  *
0220  * Request a timestamp from the ES58X device. Once the answer is
0221  * received, the timestamp difference will be set by the callback
0222  * function es58x_rx_timestamp().
0223  *
0224  * Return: zero on success, errno when any error occurs.
0225  */
0226 static int es58x_set_realtime_diff_ns(struct es58x_device *es58x_dev)
0227 {
0228     if (es58x_dev->ktime_req_ns) {
0229         dev_warn(es58x_dev->dev,
0230              "%s: Previous request to set timestamp has not completed yet\n",
0231              __func__);
0232         return -EBUSY;
0233     }
0234 
0235     es58x_dev->ktime_req_ns = ktime_get_real_ns();
0236     return es58x_dev->ops->get_timestamp(es58x_dev);
0237 }
0238 
0239 /**
0240  * es58x_is_can_state_active() - Is the network device in an active
0241  *  CAN state?
0242  * @netdev: CAN network device.
0243  *
0244  * The device is considered active if it is able to send or receive
0245  * CAN frames, that is to say if it is in any of
0246  * CAN_STATE_ERROR_ACTIVE, CAN_STATE_ERROR_WARNING or
0247  * CAN_STATE_ERROR_PASSIVE states.
0248  *
0249  * Caution: when recovering from a bus-off,
0250  * net/core/dev.c#can_restart() will call
0251  * net/core/dev.c#can_flush_echo_skb() without using any kind of
0252  * locks. For this reason, it is critical to guarantee that no TX or
0253  * echo operations (i.e. any access to priv->echo_skb[]) can be done
0254  * while this function is returning false.
0255  *
0256  * Return: true if the device is active, else returns false.
0257  */
0258 static bool es58x_is_can_state_active(struct net_device *netdev)
0259 {
0260     return es58x_priv(netdev)->can.state < CAN_STATE_BUS_OFF;
0261 }
0262 
0263 /**
0264  * es58x_is_echo_skb_threshold_reached() - Determine the limit of how
0265  *  many skb slots can be taken before we should stop the network
0266  *  queue.
0267  * @priv: ES58X private parameters related to the network device.
0268  *
0269  * We need to save enough free skb slots in order to be able to do
0270  * bulk send. This function can be used to determine when to wake or
0271  * stop the network queue in regard to the number of skb slots already
0272  * taken if the echo FIFO.
0273  *
0274  * Return: boolean.
0275  */
0276 static bool es58x_is_echo_skb_threshold_reached(struct es58x_priv *priv)
0277 {
0278     u32 num_echo_skb =  priv->tx_head - priv->tx_tail;
0279     u32 threshold = priv->can.echo_skb_max -
0280         priv->es58x_dev->param->tx_bulk_max + 1;
0281 
0282     return num_echo_skb >= threshold;
0283 }
0284 
0285 /**
0286  * es58x_can_free_echo_skb_tail() - Remove the oldest echo skb of the
0287  *  echo FIFO.
0288  * @netdev: CAN network device.
0289  *
0290  * Naming convention: the tail is the beginning of the FIFO, i.e. the
0291  * first skb to have entered the FIFO.
0292  */
0293 static void es58x_can_free_echo_skb_tail(struct net_device *netdev)
0294 {
0295     struct es58x_priv *priv = es58x_priv(netdev);
0296     u16 fifo_mask = priv->es58x_dev->param->fifo_mask;
0297     unsigned int frame_len = 0;
0298 
0299     can_free_echo_skb(netdev, priv->tx_tail & fifo_mask, &frame_len);
0300     netdev_completed_queue(netdev, 1, frame_len);
0301 
0302     priv->tx_tail++;
0303 
0304     netdev->stats.tx_dropped++;
0305 }
0306 
0307 /**
0308  * es58x_can_get_echo_skb_recovery() - Try to re-sync the echo FIFO.
0309  * @netdev: CAN network device.
0310  * @rcv_packet_idx: Index
0311  *
0312  * This function should not be called under normal circumstances. In
0313  * the unlikely case that one or several URB packages get dropped by
0314  * the device, the index will get out of sync. Try to recover by
0315  * dropping the echo skb packets with older indexes.
0316  *
0317  * Return: zero if recovery was successful, -EINVAL otherwise.
0318  */
0319 static int es58x_can_get_echo_skb_recovery(struct net_device *netdev,
0320                        u32 rcv_packet_idx)
0321 {
0322     struct es58x_priv *priv = es58x_priv(netdev);
0323     int ret = 0;
0324 
0325     netdev->stats.tx_errors++;
0326 
0327     if (net_ratelimit())
0328         netdev_warn(netdev,
0329                 "Bad echo packet index: %u. First index: %u, end index %u, num_echo_skb: %02u/%02u\n",
0330                 rcv_packet_idx, priv->tx_tail, priv->tx_head,
0331                 priv->tx_head - priv->tx_tail,
0332                 priv->can.echo_skb_max);
0333 
0334     if ((s32)(rcv_packet_idx - priv->tx_tail) < 0) {
0335         if (net_ratelimit())
0336             netdev_warn(netdev,
0337                     "Received echo index is from the past. Ignoring it\n");
0338         ret = -EINVAL;
0339     } else if ((s32)(rcv_packet_idx - priv->tx_head) >= 0) {
0340         if (net_ratelimit())
0341             netdev_err(netdev,
0342                    "Received echo index is from the future. Ignoring it\n");
0343         ret = -EINVAL;
0344     } else {
0345         if (net_ratelimit())
0346             netdev_warn(netdev,
0347                     "Recovery: dropping %u echo skb from index %u to %u\n",
0348                     rcv_packet_idx - priv->tx_tail,
0349                     priv->tx_tail, rcv_packet_idx - 1);
0350         while (priv->tx_tail != rcv_packet_idx) {
0351             if (priv->tx_tail == priv->tx_head)
0352                 return -EINVAL;
0353             es58x_can_free_echo_skb_tail(netdev);
0354         }
0355     }
0356     return ret;
0357 }
0358 
0359 /**
0360  * es58x_can_get_echo_skb() - Get the skb from the echo FIFO and loop
0361  *  it back locally.
0362  * @netdev: CAN network device.
0363  * @rcv_packet_idx: Index of the first packet received from the device.
0364  * @tstamps: Array of hardware timestamps received from a ES58X device.
0365  * @pkts: Number of packets (and so, length of @tstamps).
0366  *
0367  * Callback function for when we receive a self reception
0368  * acknowledgment.  Retrieves the skb from the echo FIFO, sets its
0369  * hardware timestamp (the actual time it was sent) and loops it back
0370  * locally.
0371  *
0372  * The device has to be active (i.e. network interface UP and not in
0373  * bus off state or restarting).
0374  *
0375  * Packet indexes must be consecutive (i.e. index of first packet is
0376  * @rcv_packet_idx, index of second packet is @rcv_packet_idx + 1 and
0377  * index of last packet is @rcv_packet_idx + @pkts - 1).
0378  *
0379  * Return: zero on success.
0380  */
0381 int es58x_can_get_echo_skb(struct net_device *netdev, u32 rcv_packet_idx,
0382                u64 *tstamps, unsigned int pkts)
0383 {
0384     struct es58x_priv *priv = es58x_priv(netdev);
0385     unsigned int rx_total_frame_len = 0;
0386     unsigned int num_echo_skb = priv->tx_head - priv->tx_tail;
0387     int i;
0388     u16 fifo_mask = priv->es58x_dev->param->fifo_mask;
0389 
0390     if (!netif_running(netdev)) {
0391         if (net_ratelimit())
0392             netdev_info(netdev,
0393                     "%s: %s is down, dropping %d echo packets\n",
0394                     __func__, netdev->name, pkts);
0395         netdev->stats.tx_dropped += pkts;
0396         return 0;
0397     } else if (!es58x_is_can_state_active(netdev)) {
0398         if (net_ratelimit())
0399             netdev_dbg(netdev,
0400                    "Bus is off or device is restarting. Ignoring %u echo packets from index %u\n",
0401                    pkts, rcv_packet_idx);
0402         /* stats.tx_dropped will be (or was already)
0403          * incremented by
0404          * drivers/net/can/net/dev.c:can_flush_echo_skb().
0405          */
0406         return 0;
0407     } else if (num_echo_skb == 0) {
0408         if (net_ratelimit())
0409             netdev_warn(netdev,
0410                     "Received %u echo packets from index: %u but echo skb queue is empty.\n",
0411                     pkts, rcv_packet_idx);
0412         netdev->stats.tx_dropped += pkts;
0413         return 0;
0414     }
0415 
0416     if (priv->tx_tail != rcv_packet_idx) {
0417         if (es58x_can_get_echo_skb_recovery(netdev, rcv_packet_idx) < 0) {
0418             if (net_ratelimit())
0419                 netdev_warn(netdev,
0420                         "Could not find echo skb for echo packet index: %u\n",
0421                         rcv_packet_idx);
0422             return 0;
0423         }
0424     }
0425     if (num_echo_skb < pkts) {
0426         int pkts_drop = pkts - num_echo_skb;
0427 
0428         if (net_ratelimit())
0429             netdev_err(netdev,
0430                    "Received %u echo packets but have only %d echo skb. Dropping %d echo skb\n",
0431                    pkts, num_echo_skb, pkts_drop);
0432         netdev->stats.tx_dropped += pkts_drop;
0433         pkts -= pkts_drop;
0434     }
0435 
0436     for (i = 0; i < pkts; i++) {
0437         unsigned int skb_idx = priv->tx_tail & fifo_mask;
0438         struct sk_buff *skb = priv->can.echo_skb[skb_idx];
0439         unsigned int frame_len = 0;
0440 
0441         if (skb)
0442             es58x_set_skb_timestamp(netdev, skb, tstamps[i]);
0443 
0444         netdev->stats.tx_bytes += can_get_echo_skb(netdev, skb_idx,
0445                                &frame_len);
0446         rx_total_frame_len += frame_len;
0447 
0448         priv->tx_tail++;
0449     }
0450 
0451     netdev_completed_queue(netdev, pkts, rx_total_frame_len);
0452     netdev->stats.tx_packets += pkts;
0453 
0454     priv->err_passive_before_rtx_success = 0;
0455     if (!es58x_is_echo_skb_threshold_reached(priv))
0456         netif_wake_queue(netdev);
0457 
0458     return 0;
0459 }
0460 
0461 /**
0462  * es58x_can_reset_echo_fifo() - Reset the echo FIFO.
0463  * @netdev: CAN network device.
0464  *
0465  * The echo_skb array of struct can_priv will be flushed by
0466  * drivers/net/can/dev.c:can_flush_echo_skb(). This function resets
0467  * the parameters of the struct es58x_priv of our device and reset the
0468  * queue (c.f. BQL).
0469  */
0470 static void es58x_can_reset_echo_fifo(struct net_device *netdev)
0471 {
0472     struct es58x_priv *priv = es58x_priv(netdev);
0473 
0474     priv->tx_tail = 0;
0475     priv->tx_head = 0;
0476     priv->tx_urb = NULL;
0477     priv->err_passive_before_rtx_success = 0;
0478     netdev_reset_queue(netdev);
0479 }
0480 
0481 /**
0482  * es58x_flush_pending_tx_msg() - Reset the buffer for transmission messages.
0483  * @netdev: CAN network device.
0484  *
0485  * es58x_start_xmit() will queue up to tx_bulk_max messages in
0486  * &tx_urb buffer and do a bulk send of all messages in one single URB
0487  * (c.f. xmit_more flag). When the device recovers from a bus off
0488  * state or when the device stops, the tx_urb buffer might still have
0489  * pending messages in it and thus need to be flushed.
0490  */
0491 static void es58x_flush_pending_tx_msg(struct net_device *netdev)
0492 {
0493     struct es58x_priv *priv = es58x_priv(netdev);
0494     struct es58x_device *es58x_dev = priv->es58x_dev;
0495 
0496     if (priv->tx_urb) {
0497         netdev_warn(netdev, "%s: dropping %d TX messages\n",
0498                 __func__, priv->tx_can_msg_cnt);
0499         netdev->stats.tx_dropped += priv->tx_can_msg_cnt;
0500         while (priv->tx_can_msg_cnt > 0) {
0501             unsigned int frame_len = 0;
0502             u16 fifo_mask = priv->es58x_dev->param->fifo_mask;
0503 
0504             priv->tx_head--;
0505             priv->tx_can_msg_cnt--;
0506             can_free_echo_skb(netdev, priv->tx_head & fifo_mask,
0507                       &frame_len);
0508             netdev_completed_queue(netdev, 1, frame_len);
0509         }
0510         usb_anchor_urb(priv->tx_urb, &priv->es58x_dev->tx_urbs_idle);
0511         atomic_inc(&es58x_dev->tx_urbs_idle_cnt);
0512         usb_free_urb(priv->tx_urb);
0513     }
0514     priv->tx_urb = NULL;
0515 }
0516 
0517 /**
0518  * es58x_tx_ack_msg() - Handle acknowledgment messages.
0519  * @netdev: CAN network device.
0520  * @tx_free_entries: Number of free entries in the device transmit FIFO.
0521  * @rx_cmd_ret_u32: error code as returned by the ES58X device.
0522  *
0523  * ES58X sends an acknowledgment message after a transmission request
0524  * is done. This is mandatory for the ES581.4 but is optional (and
0525  * deactivated in this driver) for the ES58X_FD family.
0526  *
0527  * Under normal circumstances, this function should never throw an
0528  * error message.
0529  *
0530  * Return: zero on success, errno when any error occurs.
0531  */
0532 int es58x_tx_ack_msg(struct net_device *netdev, u16 tx_free_entries,
0533              enum es58x_ret_u32 rx_cmd_ret_u32)
0534 {
0535     struct es58x_priv *priv = es58x_priv(netdev);
0536 
0537     if (tx_free_entries <= priv->es58x_dev->param->tx_bulk_max) {
0538         if (net_ratelimit())
0539             netdev_err(netdev,
0540                    "Only %d entries left in device queue, num_echo_skb: %d/%d\n",
0541                    tx_free_entries,
0542                    priv->tx_head - priv->tx_tail,
0543                    priv->can.echo_skb_max);
0544         netif_stop_queue(netdev);
0545     }
0546 
0547     return es58x_rx_cmd_ret_u32(netdev, ES58X_RET_TYPE_TX_MSG,
0548                     rx_cmd_ret_u32);
0549 }
0550 
0551 /**
0552  * es58x_rx_can_msg() - Handle a received a CAN message.
0553  * @netdev: CAN network device.
0554  * @timestamp: Hardware time stamp (only relevant in rx branches).
0555  * @data: CAN payload.
0556  * @can_id: CAN ID.
0557  * @es58x_flags: Please refer to enum es58x_flag.
0558  * @dlc: Data Length Code (raw value).
0559  *
0560  * Fill up a CAN skb and post it.
0561  *
0562  * This function handles the case where the DLC of a classical CAN
0563  * frame is greater than CAN_MAX_DLEN (c.f. the len8_dlc field of
0564  * struct can_frame).
0565  *
0566  * Return: zero on success.
0567  */
0568 int es58x_rx_can_msg(struct net_device *netdev, u64 timestamp, const u8 *data,
0569              canid_t can_id, enum es58x_flag es58x_flags, u8 dlc)
0570 {
0571     struct canfd_frame *cfd;
0572     struct can_frame *ccf;
0573     struct sk_buff *skb;
0574     u8 len;
0575     bool is_can_fd = !!(es58x_flags & ES58X_FLAG_FD_DATA);
0576 
0577     if (dlc > CAN_MAX_RAW_DLC) {
0578         netdev_err(netdev,
0579                "%s: DLC is %d but maximum should be %d\n",
0580                __func__, dlc, CAN_MAX_RAW_DLC);
0581         return -EMSGSIZE;
0582     }
0583 
0584     if (is_can_fd) {
0585         len = can_fd_dlc2len(dlc);
0586         skb = alloc_canfd_skb(netdev, &cfd);
0587     } else {
0588         len = can_cc_dlc2len(dlc);
0589         skb = alloc_can_skb(netdev, &ccf);
0590         cfd = (struct canfd_frame *)ccf;
0591     }
0592     if (!skb) {
0593         netdev->stats.rx_dropped++;
0594         return 0;
0595     }
0596 
0597     cfd->can_id = can_id;
0598     if (es58x_flags & ES58X_FLAG_EFF)
0599         cfd->can_id |= CAN_EFF_FLAG;
0600     if (is_can_fd) {
0601         cfd->len = len;
0602         if (es58x_flags & ES58X_FLAG_FD_BRS)
0603             cfd->flags |= CANFD_BRS;
0604         if (es58x_flags & ES58X_FLAG_FD_ESI)
0605             cfd->flags |= CANFD_ESI;
0606     } else {
0607         can_frame_set_cc_len(ccf, dlc, es58x_priv(netdev)->can.ctrlmode);
0608         if (es58x_flags & ES58X_FLAG_RTR) {
0609             ccf->can_id |= CAN_RTR_FLAG;
0610             len = 0;
0611         }
0612     }
0613     memcpy(cfd->data, data, len);
0614     netdev->stats.rx_packets++;
0615     netdev->stats.rx_bytes += len;
0616 
0617     es58x_set_skb_timestamp(netdev, skb, timestamp);
0618     netif_rx(skb);
0619 
0620     es58x_priv(netdev)->err_passive_before_rtx_success = 0;
0621 
0622     return 0;
0623 }
0624 
0625 /**
0626  * es58x_rx_err_msg() - Handle a received CAN event or error message.
0627  * @netdev: CAN network device.
0628  * @error: Error code.
0629  * @event: Event code.
0630  * @timestamp: Timestamp received from a ES58X device.
0631  *
0632  * Handle the errors and events received by the ES58X device, create
0633  * a CAN error skb and post it.
0634  *
0635  * In some rare cases the devices might get stuck alternating between
0636  * CAN_STATE_ERROR_PASSIVE and CAN_STATE_ERROR_WARNING. To prevent
0637  * this behavior, we force a bus off state if the device goes in
0638  * CAN_STATE_ERROR_WARNING for ES58X_MAX_CONSECUTIVE_WARN consecutive
0639  * times with no successful transmission or reception in between.
0640  *
0641  * Once the device is in bus off state, the only way to restart it is
0642  * through the drivers/net/can/dev.c:can_restart() function. The
0643  * device is technically capable to recover by itself under certain
0644  * circumstances, however, allowing self recovery would create
0645  * complex race conditions with drivers/net/can/dev.c:can_restart()
0646  * and thus was not implemented. To activate automatic restart, please
0647  * set the restart-ms parameter (e.g. ip link set can0 type can
0648  * restart-ms 100).
0649  *
0650  * If the bus is really instable, this function would try to send a
0651  * lot of log messages. Those are rate limited (i.e. you will see
0652  * messages such as "net_ratelimit: XXX callbacks suppressed" in
0653  * dmesg).
0654  *
0655  * Return: zero on success, errno when any error occurs.
0656  */
0657 int es58x_rx_err_msg(struct net_device *netdev, enum es58x_err error,
0658              enum es58x_event event, u64 timestamp)
0659 {
0660     struct es58x_priv *priv = es58x_priv(netdev);
0661     struct can_priv *can = netdev_priv(netdev);
0662     struct can_device_stats *can_stats = &can->can_stats;
0663     struct can_frame *cf = NULL;
0664     struct sk_buff *skb;
0665     int ret = 0;
0666 
0667     if (!netif_running(netdev)) {
0668         if (net_ratelimit())
0669             netdev_info(netdev, "%s: %s is down, dropping packet\n",
0670                     __func__, netdev->name);
0671         netdev->stats.rx_dropped++;
0672         return 0;
0673     }
0674 
0675     if (error == ES58X_ERR_OK && event == ES58X_EVENT_OK) {
0676         netdev_err(netdev, "%s: Both error and event are zero\n",
0677                __func__);
0678         return -EINVAL;
0679     }
0680 
0681     skb = alloc_can_err_skb(netdev, &cf);
0682 
0683     switch (error) {
0684     case ES58X_ERR_OK:  /* 0: No error */
0685         break;
0686 
0687     case ES58X_ERR_PROT_STUFF:
0688         if (net_ratelimit())
0689             netdev_dbg(netdev, "Error BITSTUFF\n");
0690         if (cf)
0691             cf->data[2] |= CAN_ERR_PROT_STUFF;
0692         break;
0693 
0694     case ES58X_ERR_PROT_FORM:
0695         if (net_ratelimit())
0696             netdev_dbg(netdev, "Error FORMAT\n");
0697         if (cf)
0698             cf->data[2] |= CAN_ERR_PROT_FORM;
0699         break;
0700 
0701     case ES58X_ERR_ACK:
0702         if (net_ratelimit())
0703             netdev_dbg(netdev, "Error ACK\n");
0704         if (cf)
0705             cf->can_id |= CAN_ERR_ACK;
0706         break;
0707 
0708     case ES58X_ERR_PROT_BIT:
0709         if (net_ratelimit())
0710             netdev_dbg(netdev, "Error BIT\n");
0711         if (cf)
0712             cf->data[2] |= CAN_ERR_PROT_BIT;
0713         break;
0714 
0715     case ES58X_ERR_PROT_CRC:
0716         if (net_ratelimit())
0717             netdev_dbg(netdev, "Error CRC\n");
0718         if (cf)
0719             cf->data[3] |= CAN_ERR_PROT_LOC_CRC_SEQ;
0720         break;
0721 
0722     case ES58X_ERR_PROT_BIT1:
0723         if (net_ratelimit())
0724             netdev_dbg(netdev,
0725                    "Error: expected a recessive bit but monitored a dominant one\n");
0726         if (cf)
0727             cf->data[2] |= CAN_ERR_PROT_BIT1;
0728         break;
0729 
0730     case ES58X_ERR_PROT_BIT0:
0731         if (net_ratelimit())
0732             netdev_dbg(netdev,
0733                    "Error expected a dominant bit but monitored a recessive one\n");
0734         if (cf)
0735             cf->data[2] |= CAN_ERR_PROT_BIT0;
0736         break;
0737 
0738     case ES58X_ERR_PROT_OVERLOAD:
0739         if (net_ratelimit())
0740             netdev_dbg(netdev, "Error OVERLOAD\n");
0741         if (cf)
0742             cf->data[2] |= CAN_ERR_PROT_OVERLOAD;
0743         break;
0744 
0745     case ES58X_ERR_PROT_UNSPEC:
0746         if (net_ratelimit())
0747             netdev_dbg(netdev, "Unspecified error\n");
0748         if (cf)
0749             cf->can_id |= CAN_ERR_PROT;
0750         break;
0751 
0752     default:
0753         if (net_ratelimit())
0754             netdev_err(netdev,
0755                    "%s: Unspecified error code 0x%04X\n",
0756                    __func__, (int)error);
0757         if (cf)
0758             cf->can_id |= CAN_ERR_PROT;
0759         break;
0760     }
0761 
0762     switch (event) {
0763     case ES58X_EVENT_OK:    /* 0: No event */
0764         break;
0765 
0766     case ES58X_EVENT_CRTL_ACTIVE:
0767         if (can->state == CAN_STATE_BUS_OFF) {
0768             netdev_err(netdev,
0769                    "%s: state transition: BUS OFF -> ACTIVE\n",
0770                    __func__);
0771         }
0772         if (net_ratelimit())
0773             netdev_dbg(netdev, "Event CAN BUS ACTIVE\n");
0774         if (cf)
0775             cf->data[1] |= CAN_ERR_CRTL_ACTIVE;
0776         can->state = CAN_STATE_ERROR_ACTIVE;
0777         break;
0778 
0779     case ES58X_EVENT_CRTL_PASSIVE:
0780         if (net_ratelimit())
0781             netdev_dbg(netdev, "Event CAN BUS PASSIVE\n");
0782         /* Either TX or RX error count reached passive state
0783          * but we do not know which. Setting both flags by
0784          * default.
0785          */
0786         if (cf) {
0787             cf->data[1] |= CAN_ERR_CRTL_RX_PASSIVE;
0788             cf->data[1] |= CAN_ERR_CRTL_TX_PASSIVE;
0789         }
0790         if (can->state < CAN_STATE_BUS_OFF)
0791             can->state = CAN_STATE_ERROR_PASSIVE;
0792         can_stats->error_passive++;
0793         if (priv->err_passive_before_rtx_success < U8_MAX)
0794             priv->err_passive_before_rtx_success++;
0795         break;
0796 
0797     case ES58X_EVENT_CRTL_WARNING:
0798         if (net_ratelimit())
0799             netdev_dbg(netdev, "Event CAN BUS WARNING\n");
0800         /* Either TX or RX error count reached warning state
0801          * but we do not know which. Setting both flags by
0802          * default.
0803          */
0804         if (cf) {
0805             cf->data[1] |= CAN_ERR_CRTL_RX_WARNING;
0806             cf->data[1] |= CAN_ERR_CRTL_TX_WARNING;
0807         }
0808         if (can->state < CAN_STATE_BUS_OFF)
0809             can->state = CAN_STATE_ERROR_WARNING;
0810         can_stats->error_warning++;
0811         break;
0812 
0813     case ES58X_EVENT_BUSOFF:
0814         if (net_ratelimit())
0815             netdev_dbg(netdev, "Event CAN BUS OFF\n");
0816         if (cf)
0817             cf->can_id |= CAN_ERR_BUSOFF;
0818         can_stats->bus_off++;
0819         netif_stop_queue(netdev);
0820         if (can->state != CAN_STATE_BUS_OFF) {
0821             can->state = CAN_STATE_BUS_OFF;
0822             can_bus_off(netdev);
0823             ret = can->do_set_mode(netdev, CAN_MODE_STOP);
0824         }
0825         break;
0826 
0827     case ES58X_EVENT_SINGLE_WIRE:
0828         if (net_ratelimit())
0829             netdev_warn(netdev,
0830                     "Lost connection on either CAN high or CAN low\n");
0831         /* Lost connection on either CAN high or CAN
0832          * low. Setting both flags by default.
0833          */
0834         if (cf) {
0835             cf->data[4] |= CAN_ERR_TRX_CANH_NO_WIRE;
0836             cf->data[4] |= CAN_ERR_TRX_CANL_NO_WIRE;
0837         }
0838         break;
0839 
0840     default:
0841         if (net_ratelimit())
0842             netdev_err(netdev,
0843                    "%s: Unspecified event code 0x%04X\n",
0844                    __func__, (int)event);
0845         if (cf)
0846             cf->can_id |= CAN_ERR_CRTL;
0847         break;
0848     }
0849 
0850     if (cf) {
0851         if (cf->data[1])
0852             cf->can_id |= CAN_ERR_CRTL;
0853         if (cf->data[2] || cf->data[3]) {
0854             cf->can_id |= CAN_ERR_PROT;
0855             can_stats->bus_error++;
0856         }
0857         if (cf->data[4])
0858             cf->can_id |= CAN_ERR_TRX;
0859 
0860         es58x_set_skb_timestamp(netdev, skb, timestamp);
0861         netif_rx(skb);
0862     }
0863 
0864     if ((event & ES58X_EVENT_CRTL_PASSIVE) &&
0865         priv->err_passive_before_rtx_success == ES58X_CONSECUTIVE_ERR_PASSIVE_MAX) {
0866         netdev_info(netdev,
0867                 "Got %d consecutive warning events with no successful RX or TX. Forcing bus-off\n",
0868                 priv->err_passive_before_rtx_success);
0869         return es58x_rx_err_msg(netdev, ES58X_ERR_OK,
0870                     ES58X_EVENT_BUSOFF, timestamp);
0871     }
0872 
0873     return ret;
0874 }
0875 
0876 /**
0877  * es58x_cmd_ret_desc() - Convert a command type to a string.
0878  * @cmd_ret_type: Type of the command which triggered the return code.
0879  *
0880  * The final line (return "<unknown>") should not be reached. If this
0881  * is the case, there is an implementation bug.
0882  *
0883  * Return: a readable description of the @cmd_ret_type.
0884  */
0885 static const char *es58x_cmd_ret_desc(enum es58x_ret_type cmd_ret_type)
0886 {
0887     switch (cmd_ret_type) {
0888     case ES58X_RET_TYPE_SET_BITTIMING:
0889         return "Set bittiming";
0890     case ES58X_RET_TYPE_ENABLE_CHANNEL:
0891         return "Enable channel";
0892     case ES58X_RET_TYPE_DISABLE_CHANNEL:
0893         return "Disable channel";
0894     case ES58X_RET_TYPE_TX_MSG:
0895         return "Transmit message";
0896     case ES58X_RET_TYPE_RESET_RX:
0897         return "Reset RX";
0898     case ES58X_RET_TYPE_RESET_TX:
0899         return "Reset TX";
0900     case ES58X_RET_TYPE_DEVICE_ERR:
0901         return "Device error";
0902     }
0903 
0904     return "<unknown>";
0905 };
0906 
0907 /**
0908  * es58x_rx_cmd_ret_u8() - Handle the command's return code received
0909  *  from the ES58X device.
0910  * @dev: Device, only used for the dev_XXX() print functions.
0911  * @cmd_ret_type: Type of the command which triggered the return code.
0912  * @rx_cmd_ret_u8: Command error code as returned by the ES58X device.
0913  *
0914  * Handles the 8 bits command return code. Those are specific to the
0915  * ES581.4 device. The return value will eventually be used by
0916  * es58x_handle_urb_cmd() function which will take proper actions in
0917  * case of critical issues such and memory errors or bad CRC values.
0918  *
0919  * In contrast with es58x_rx_cmd_ret_u32(), the network device is
0920  * unknown.
0921  *
0922  * Return: zero on success, return errno when any error occurs.
0923  */
0924 int es58x_rx_cmd_ret_u8(struct device *dev,
0925             enum es58x_ret_type cmd_ret_type,
0926             enum es58x_ret_u8 rx_cmd_ret_u8)
0927 {
0928     const char *ret_desc = es58x_cmd_ret_desc(cmd_ret_type);
0929 
0930     switch (rx_cmd_ret_u8) {
0931     case ES58X_RET_U8_OK:
0932         dev_dbg_ratelimited(dev, "%s: OK\n", ret_desc);
0933         return 0;
0934 
0935     case ES58X_RET_U8_ERR_UNSPECIFIED_FAILURE:
0936         dev_err(dev, "%s: unspecified failure\n", ret_desc);
0937         return -EBADMSG;
0938 
0939     case ES58X_RET_U8_ERR_NO_MEM:
0940         dev_err(dev, "%s: device ran out of memory\n", ret_desc);
0941         return -ENOMEM;
0942 
0943     case ES58X_RET_U8_ERR_BAD_CRC:
0944         dev_err(dev, "%s: CRC of previous command is incorrect\n",
0945             ret_desc);
0946         return -EIO;
0947 
0948     default:
0949         dev_err(dev, "%s: returned unknown value: 0x%02X\n",
0950             ret_desc, rx_cmd_ret_u8);
0951         return -EBADMSG;
0952     }
0953 }
0954 
0955 /**
0956  * es58x_rx_cmd_ret_u32() - Handle the command return code received
0957  *  from the ES58X device.
0958  * @netdev: CAN network device.
0959  * @cmd_ret_type: Type of the command which triggered the return code.
0960  * @rx_cmd_ret_u32: error code as returned by the ES58X device.
0961  *
0962  * Handles the 32 bits command return code. The return value will
0963  * eventually be used by es58x_handle_urb_cmd() function which will
0964  * take proper actions in case of critical issues such and memory
0965  * errors or bad CRC values.
0966  *
0967  * Return: zero on success, errno when any error occurs.
0968  */
0969 int es58x_rx_cmd_ret_u32(struct net_device *netdev,
0970              enum es58x_ret_type cmd_ret_type,
0971              enum es58x_ret_u32 rx_cmd_ret_u32)
0972 {
0973     struct es58x_priv *priv = es58x_priv(netdev);
0974     const struct es58x_operators *ops = priv->es58x_dev->ops;
0975     const char *ret_desc = es58x_cmd_ret_desc(cmd_ret_type);
0976 
0977     switch (rx_cmd_ret_u32) {
0978     case ES58X_RET_U32_OK:
0979         switch (cmd_ret_type) {
0980         case ES58X_RET_TYPE_ENABLE_CHANNEL:
0981             es58x_can_reset_echo_fifo(netdev);
0982             priv->can.state = CAN_STATE_ERROR_ACTIVE;
0983             netif_wake_queue(netdev);
0984             netdev_info(netdev,
0985                     "%s: %s (Serial Number %s): CAN%d channel becomes ready\n",
0986                     ret_desc, priv->es58x_dev->udev->product,
0987                     priv->es58x_dev->udev->serial,
0988                     priv->channel_idx + 1);
0989             break;
0990 
0991         case ES58X_RET_TYPE_TX_MSG:
0992             if (IS_ENABLED(CONFIG_VERBOSE_DEBUG) && net_ratelimit())
0993                 netdev_vdbg(netdev, "%s: OK\n", ret_desc);
0994             break;
0995 
0996         default:
0997             netdev_dbg(netdev, "%s: OK\n", ret_desc);
0998             break;
0999         }
1000         return 0;
1001 
1002     case ES58X_RET_U32_ERR_UNSPECIFIED_FAILURE:
1003         if (cmd_ret_type == ES58X_RET_TYPE_ENABLE_CHANNEL) {
1004             int ret;
1005 
1006             netdev_warn(netdev,
1007                     "%s: channel is already opened, closing and re-opening it to reflect new configuration\n",
1008                     ret_desc);
1009             ret = ops->disable_channel(es58x_priv(netdev));
1010             if (ret)
1011                 return ret;
1012             return ops->enable_channel(es58x_priv(netdev));
1013         }
1014         if (cmd_ret_type == ES58X_RET_TYPE_DISABLE_CHANNEL) {
1015             netdev_info(netdev,
1016                     "%s: channel is already closed\n", ret_desc);
1017             return 0;
1018         }
1019         netdev_err(netdev,
1020                "%s: unspecified failure\n", ret_desc);
1021         return -EBADMSG;
1022 
1023     case ES58X_RET_U32_ERR_NO_MEM:
1024         netdev_err(netdev, "%s: device ran out of memory\n", ret_desc);
1025         return -ENOMEM;
1026 
1027     case ES58X_RET_U32_WARN_PARAM_ADJUSTED:
1028         netdev_warn(netdev,
1029                 "%s: some incompatible parameters have been adjusted\n",
1030                 ret_desc);
1031         return 0;
1032 
1033     case ES58X_RET_U32_WARN_TX_MAYBE_REORDER:
1034         netdev_warn(netdev,
1035                 "%s: TX messages might have been reordered\n",
1036                 ret_desc);
1037         return 0;
1038 
1039     case ES58X_RET_U32_ERR_TIMEDOUT:
1040         netdev_err(netdev, "%s: command timed out\n", ret_desc);
1041         return -ETIMEDOUT;
1042 
1043     case ES58X_RET_U32_ERR_FIFO_FULL:
1044         netdev_warn(netdev, "%s: fifo is full\n", ret_desc);
1045         return 0;
1046 
1047     case ES58X_RET_U32_ERR_BAD_CONFIG:
1048         netdev_err(netdev, "%s: bad configuration\n", ret_desc);
1049         return -EINVAL;
1050 
1051     case ES58X_RET_U32_ERR_NO_RESOURCE:
1052         netdev_err(netdev, "%s: no resource available\n", ret_desc);
1053         return -EBUSY;
1054 
1055     default:
1056         netdev_err(netdev, "%s returned unknown value: 0x%08X\n",
1057                ret_desc, rx_cmd_ret_u32);
1058         return -EBADMSG;
1059     }
1060 }
1061 
1062 /**
1063  * es58x_increment_rx_errors() - Increment the network devices' error
1064  *  count.
1065  * @es58x_dev: ES58X device.
1066  *
1067  * If an error occurs on the early stages on receiving an URB command,
1068  * we might not be able to figure out on which network device the
1069  * error occurred. In such case, we arbitrarily increment the error
1070  * count of all the network devices attached to our ES58X device.
1071  */
1072 static void es58x_increment_rx_errors(struct es58x_device *es58x_dev)
1073 {
1074     int i;
1075 
1076     for (i = 0; i < es58x_dev->num_can_ch; i++)
1077         if (es58x_dev->netdev[i])
1078             es58x_dev->netdev[i]->stats.rx_errors++;
1079 }
1080 
1081 /**
1082  * es58x_handle_urb_cmd() - Handle the URB command
1083  * @es58x_dev: ES58X device.
1084  * @urb_cmd: The URB command received from the ES58X device, might not
1085  *  be aligned.
1086  *
1087  * Sends the URB command to the device specific function. Manages the
1088  * errors thrown back by those functions.
1089  */
1090 static void es58x_handle_urb_cmd(struct es58x_device *es58x_dev,
1091                  const union es58x_urb_cmd *urb_cmd)
1092 {
1093     const struct es58x_operators *ops = es58x_dev->ops;
1094     size_t cmd_len;
1095     int i, ret;
1096 
1097     ret = ops->handle_urb_cmd(es58x_dev, urb_cmd);
1098     switch (ret) {
1099     case 0:     /* OK */
1100         return;
1101 
1102     case -ENODEV:
1103         dev_err_ratelimited(es58x_dev->dev, "Device is not ready\n");
1104         break;
1105 
1106     case -EINVAL:
1107     case -EMSGSIZE:
1108     case -EBADRQC:
1109     case -EBADMSG:
1110     case -ECHRNG:
1111     case -ETIMEDOUT:
1112         cmd_len = es58x_get_urb_cmd_len(es58x_dev,
1113                         ops->get_msg_len(urb_cmd));
1114         dev_err(es58x_dev->dev,
1115             "ops->handle_urb_cmd() returned error %pe",
1116             ERR_PTR(ret));
1117         es58x_print_hex_dump(urb_cmd, cmd_len);
1118         break;
1119 
1120     case -EFAULT:
1121     case -ENOMEM:
1122     case -EIO:
1123     default:
1124         dev_crit(es58x_dev->dev,
1125              "ops->handle_urb_cmd() returned error %pe, detaching all network devices\n",
1126              ERR_PTR(ret));
1127         for (i = 0; i < es58x_dev->num_can_ch; i++)
1128             if (es58x_dev->netdev[i])
1129                 netif_device_detach(es58x_dev->netdev[i]);
1130         if (es58x_dev->ops->reset_device)
1131             es58x_dev->ops->reset_device(es58x_dev);
1132         break;
1133     }
1134 
1135     /* Because the urb command could not fully be parsed,
1136      * channel_id is not confirmed. Incrementing rx_errors count
1137      * of all channels.
1138      */
1139     es58x_increment_rx_errors(es58x_dev);
1140 }
1141 
1142 /**
1143  * es58x_check_rx_urb() - Check the length and format of the URB command.
1144  * @es58x_dev: ES58X device.
1145  * @urb_cmd: The URB command received from the ES58X device, might not
1146  *  be aligned.
1147  * @urb_actual_len: The actual length of the URB command.
1148  *
1149  * Check if the first message of the received urb is valid, that is to
1150  * say that both the header and the length are coherent.
1151  *
1152  * Return:
1153  * the length of the first message of the URB on success.
1154  *
1155  * -ENODATA if the URB command is incomplete (in which case, the URB
1156  * command should be buffered and combined with the next URB to try to
1157  * reconstitute the URB command).
1158  *
1159  * -EOVERFLOW if the length is bigger than the maximum expected one.
1160  *
1161  * -EBADRQC if the start of frame does not match the expected value.
1162  */
1163 static signed int es58x_check_rx_urb(struct es58x_device *es58x_dev,
1164                      const union es58x_urb_cmd *urb_cmd,
1165                      u32 urb_actual_len)
1166 {
1167     const struct device *dev = es58x_dev->dev;
1168     const struct es58x_parameters *param = es58x_dev->param;
1169     u16 sof, msg_len;
1170     signed int urb_cmd_len, ret;
1171 
1172     if (urb_actual_len < param->urb_cmd_header_len) {
1173         dev_vdbg(dev,
1174              "%s: Received %d bytes [%*ph]: header incomplete\n",
1175              __func__, urb_actual_len, urb_actual_len,
1176              urb_cmd->raw_cmd);
1177         return -ENODATA;
1178     }
1179 
1180     sof = get_unaligned_le16(&urb_cmd->sof);
1181     if (sof != param->rx_start_of_frame) {
1182         dev_err_ratelimited(es58x_dev->dev,
1183                     "%s: Expected sequence 0x%04X for start of frame but got 0x%04X.\n",
1184                     __func__, param->rx_start_of_frame, sof);
1185         return -EBADRQC;
1186     }
1187 
1188     msg_len = es58x_dev->ops->get_msg_len(urb_cmd);
1189     urb_cmd_len = es58x_get_urb_cmd_len(es58x_dev, msg_len);
1190     if (urb_cmd_len > param->rx_urb_cmd_max_len) {
1191         dev_err_ratelimited(es58x_dev->dev,
1192                     "%s: Biggest expected size for rx urb_cmd is %u but receive a command of size %d\n",
1193                     __func__,
1194                     param->rx_urb_cmd_max_len, urb_cmd_len);
1195         return -EOVERFLOW;
1196     } else if (urb_actual_len < urb_cmd_len) {
1197         dev_vdbg(dev, "%s: Received %02d/%02d bytes\n",
1198              __func__, urb_actual_len, urb_cmd_len);
1199         return -ENODATA;
1200     }
1201 
1202     ret = es58x_check_crc(es58x_dev, urb_cmd, urb_cmd_len);
1203     if (ret)
1204         return ret;
1205 
1206     return urb_cmd_len;
1207 }
1208 
1209 /**
1210  * es58x_copy_to_cmd_buf() - Copy an array to the URB command buffer.
1211  * @es58x_dev: ES58X device.
1212  * @raw_cmd: the buffer we want to copy.
1213  * @raw_cmd_len: length of @raw_cmd.
1214  *
1215  * Concatenates @raw_cmd_len bytes of @raw_cmd to the end of the URB
1216  * command buffer.
1217  *
1218  * Return: zero on success, -EMSGSIZE if not enough space is available
1219  * to do the copy.
1220  */
1221 static int es58x_copy_to_cmd_buf(struct es58x_device *es58x_dev,
1222                  u8 *raw_cmd, int raw_cmd_len)
1223 {
1224     if (es58x_dev->rx_cmd_buf_len + raw_cmd_len >
1225         es58x_dev->param->rx_urb_cmd_max_len)
1226         return -EMSGSIZE;
1227 
1228     memcpy(&es58x_dev->rx_cmd_buf.raw_cmd[es58x_dev->rx_cmd_buf_len],
1229            raw_cmd, raw_cmd_len);
1230     es58x_dev->rx_cmd_buf_len += raw_cmd_len;
1231 
1232     return 0;
1233 }
1234 
1235 /**
1236  * es58x_split_urb_try_recovery() - Try to recover bad URB sequences.
1237  * @es58x_dev: ES58X device.
1238  * @raw_cmd: pointer to the buffer we want to copy.
1239  * @raw_cmd_len: length of @raw_cmd.
1240  *
1241  * Under some rare conditions, we might get incorrect URBs from the
1242  * device. From our observations, one of the valid URB gets replaced
1243  * by one from the past. The full root cause is not identified.
1244  *
1245  * This function looks for the next start of frame in the urb buffer
1246  * in order to try to recover.
1247  *
1248  * Such behavior was not observed on the devices of the ES58X FD
1249  * family and only seems to impact the ES581.4.
1250  *
1251  * Return: the number of bytes dropped on success, -EBADMSG if recovery failed.
1252  */
1253 static int es58x_split_urb_try_recovery(struct es58x_device *es58x_dev,
1254                     u8 *raw_cmd, size_t raw_cmd_len)
1255 {
1256     union es58x_urb_cmd *urb_cmd;
1257     signed int urb_cmd_len;
1258     u16 sof;
1259     int dropped_bytes = 0;
1260 
1261     es58x_increment_rx_errors(es58x_dev);
1262 
1263     while (raw_cmd_len > sizeof(sof)) {
1264         urb_cmd = (union es58x_urb_cmd *)raw_cmd;
1265         sof = get_unaligned_le16(&urb_cmd->sof);
1266 
1267         if (sof == es58x_dev->param->rx_start_of_frame) {
1268             urb_cmd_len = es58x_check_rx_urb(es58x_dev,
1269                              urb_cmd, raw_cmd_len);
1270             if ((urb_cmd_len == -ENODATA) || urb_cmd_len > 0) {
1271                 dev_info_ratelimited(es58x_dev->dev,
1272                              "Recovery successful! Dropped %d bytes (urb_cmd_len: %d)\n",
1273                              dropped_bytes,
1274                              urb_cmd_len);
1275                 return dropped_bytes;
1276             }
1277         }
1278         raw_cmd++;
1279         raw_cmd_len--;
1280         dropped_bytes++;
1281     }
1282 
1283     dev_warn_ratelimited(es58x_dev->dev, "%s: Recovery failed\n", __func__);
1284     return -EBADMSG;
1285 }
1286 
1287 /**
1288  * es58x_handle_incomplete_cmd() - Reconstitute an URB command from
1289  *  different URB pieces.
1290  * @es58x_dev: ES58X device.
1291  * @urb: last urb buffer received.
1292  *
1293  * The device might split the URB commands in an arbitrary amount of
1294  * pieces. This function concatenates those in an URB buffer until a
1295  * full URB command is reconstituted and consume it.
1296  *
1297  * Return:
1298  * number of bytes consumed from @urb if successful.
1299  *
1300  * -ENODATA if the URB command is still incomplete.
1301  *
1302  * -EBADMSG if the URB command is incorrect.
1303  */
1304 static signed int es58x_handle_incomplete_cmd(struct es58x_device *es58x_dev,
1305                           struct urb *urb)
1306 {
1307     size_t cpy_len;
1308     signed int urb_cmd_len, tmp_cmd_buf_len, ret;
1309 
1310     tmp_cmd_buf_len = es58x_dev->rx_cmd_buf_len;
1311     cpy_len = min_t(int, es58x_dev->param->rx_urb_cmd_max_len -
1312             es58x_dev->rx_cmd_buf_len, urb->actual_length);
1313     ret = es58x_copy_to_cmd_buf(es58x_dev, urb->transfer_buffer, cpy_len);
1314     if (ret < 0)
1315         return ret;
1316 
1317     urb_cmd_len = es58x_check_rx_urb(es58x_dev, &es58x_dev->rx_cmd_buf,
1318                      es58x_dev->rx_cmd_buf_len);
1319     if (urb_cmd_len == -ENODATA) {
1320         return -ENODATA;
1321     } else if (urb_cmd_len < 0) {
1322         dev_err_ratelimited(es58x_dev->dev,
1323                     "Could not reconstitute incomplete command from previous URB, dropping %d bytes\n",
1324                     tmp_cmd_buf_len + urb->actual_length);
1325         dev_err_ratelimited(es58x_dev->dev,
1326                     "Error code: %pe, es58x_dev->rx_cmd_buf_len: %d, urb->actual_length: %u\n",
1327                     ERR_PTR(urb_cmd_len),
1328                     tmp_cmd_buf_len, urb->actual_length);
1329         es58x_print_hex_dump(&es58x_dev->rx_cmd_buf, tmp_cmd_buf_len);
1330         es58x_print_hex_dump(urb->transfer_buffer, urb->actual_length);
1331         return urb->actual_length;
1332     }
1333 
1334     es58x_handle_urb_cmd(es58x_dev, &es58x_dev->rx_cmd_buf);
1335     return urb_cmd_len - tmp_cmd_buf_len;   /* consumed length */
1336 }
1337 
1338 /**
1339  * es58x_split_urb() - Cut the received URB in individual URB commands.
1340  * @es58x_dev: ES58X device.
1341  * @urb: last urb buffer received.
1342  *
1343  * The device might send urb in bulk format (i.e. several URB commands
1344  * concatenated together). This function will split all the commands
1345  * contained in the urb.
1346  *
1347  * Return:
1348  * number of bytes consumed from @urb if successful.
1349  *
1350  * -ENODATA if the URB command is incomplete.
1351  *
1352  * -EBADMSG if the URB command is incorrect.
1353  */
1354 static signed int es58x_split_urb(struct es58x_device *es58x_dev,
1355                   struct urb *urb)
1356 {
1357     union es58x_urb_cmd *urb_cmd;
1358     u8 *raw_cmd = urb->transfer_buffer;
1359     s32 raw_cmd_len = urb->actual_length;
1360     int ret;
1361 
1362     if (es58x_dev->rx_cmd_buf_len != 0) {
1363         ret = es58x_handle_incomplete_cmd(es58x_dev, urb);
1364         if (ret != -ENODATA)
1365             es58x_dev->rx_cmd_buf_len = 0;
1366         if (ret < 0)
1367             return ret;
1368 
1369         raw_cmd += ret;
1370         raw_cmd_len -= ret;
1371     }
1372 
1373     while (raw_cmd_len > 0) {
1374         if (raw_cmd[0] == ES58X_HEARTBEAT) {
1375             raw_cmd++;
1376             raw_cmd_len--;
1377             continue;
1378         }
1379         urb_cmd = (union es58x_urb_cmd *)raw_cmd;
1380         ret = es58x_check_rx_urb(es58x_dev, urb_cmd, raw_cmd_len);
1381         if (ret > 0) {
1382             es58x_handle_urb_cmd(es58x_dev, urb_cmd);
1383         } else if (ret == -ENODATA) {
1384             es58x_copy_to_cmd_buf(es58x_dev, raw_cmd, raw_cmd_len);
1385             return -ENODATA;
1386         } else if (ret < 0) {
1387             ret = es58x_split_urb_try_recovery(es58x_dev, raw_cmd,
1388                                raw_cmd_len);
1389             if (ret < 0)
1390                 return ret;
1391         }
1392         raw_cmd += ret;
1393         raw_cmd_len -= ret;
1394     }
1395 
1396     return 0;
1397 }
1398 
1399 /**
1400  * es58x_read_bulk_callback() - Callback for reading data from device.
1401  * @urb: last urb buffer received.
1402  *
1403  * This function gets eventually called each time an URB is received
1404  * from the ES58X device.
1405  *
1406  * Checks urb status, calls read function and resubmits urb read
1407  * operation.
1408  */
1409 static void es58x_read_bulk_callback(struct urb *urb)
1410 {
1411     struct es58x_device *es58x_dev = urb->context;
1412     const struct device *dev = es58x_dev->dev;
1413     int i, ret;
1414 
1415     switch (urb->status) {
1416     case 0:     /* success */
1417         break;
1418 
1419     case -EOVERFLOW:
1420         dev_err_ratelimited(dev, "%s: error %pe\n",
1421                     __func__, ERR_PTR(urb->status));
1422         es58x_print_hex_dump_debug(urb->transfer_buffer,
1423                        urb->transfer_buffer_length);
1424         goto resubmit_urb;
1425 
1426     case -EPROTO:
1427         dev_warn_ratelimited(dev, "%s: error %pe. Device unplugged?\n",
1428                      __func__, ERR_PTR(urb->status));
1429         goto free_urb;
1430 
1431     case -ENOENT:
1432     case -EPIPE:
1433         dev_err_ratelimited(dev, "%s: error %pe\n",
1434                     __func__, ERR_PTR(urb->status));
1435         goto free_urb;
1436 
1437     case -ESHUTDOWN:
1438         dev_dbg_ratelimited(dev, "%s: error %pe\n",
1439                     __func__, ERR_PTR(urb->status));
1440         goto free_urb;
1441 
1442     default:
1443         dev_err_ratelimited(dev, "%s: error %pe\n",
1444                     __func__, ERR_PTR(urb->status));
1445         goto resubmit_urb;
1446     }
1447 
1448     ret = es58x_split_urb(es58x_dev, urb);
1449     if ((ret != -ENODATA) && ret < 0) {
1450         dev_err(es58x_dev->dev, "es58x_split_urb() returned error %pe",
1451             ERR_PTR(ret));
1452         es58x_print_hex_dump_debug(urb->transfer_buffer,
1453                        urb->actual_length);
1454 
1455         /* Because the urb command could not be parsed,
1456          * channel_id is not confirmed. Incrementing rx_errors
1457          * count of all channels.
1458          */
1459         es58x_increment_rx_errors(es58x_dev);
1460     }
1461 
1462  resubmit_urb:
1463     ret = usb_submit_urb(urb, GFP_ATOMIC);
1464     if (ret == -ENODEV) {
1465         for (i = 0; i < es58x_dev->num_can_ch; i++)
1466             if (es58x_dev->netdev[i])
1467                 netif_device_detach(es58x_dev->netdev[i]);
1468     } else if (ret)
1469         dev_err_ratelimited(dev,
1470                     "Failed resubmitting read bulk urb: %pe\n",
1471                     ERR_PTR(ret));
1472     return;
1473 
1474  free_urb:
1475     usb_free_coherent(urb->dev, urb->transfer_buffer_length,
1476               urb->transfer_buffer, urb->transfer_dma);
1477 }
1478 
1479 /**
1480  * es58x_write_bulk_callback() - Callback after writing data to the device.
1481  * @urb: urb buffer which was previously submitted.
1482  *
1483  * This function gets eventually called each time an URB was sent to
1484  * the ES58X device.
1485  *
1486  * Puts the @urb back to the urbs idle anchor and tries to restart the
1487  * network queue.
1488  */
1489 static void es58x_write_bulk_callback(struct urb *urb)
1490 {
1491     struct net_device *netdev = urb->context;
1492     struct es58x_device *es58x_dev = es58x_priv(netdev)->es58x_dev;
1493 
1494     switch (urb->status) {
1495     case 0:     /* success */
1496         break;
1497 
1498     case -EOVERFLOW:
1499         if (net_ratelimit())
1500             netdev_err(netdev, "%s: error %pe\n",
1501                    __func__, ERR_PTR(urb->status));
1502         es58x_print_hex_dump(urb->transfer_buffer,
1503                      urb->transfer_buffer_length);
1504         break;
1505 
1506     case -ENOENT:
1507         if (net_ratelimit())
1508             netdev_dbg(netdev, "%s: error %pe\n",
1509                    __func__, ERR_PTR(urb->status));
1510         usb_free_coherent(urb->dev,
1511                   es58x_dev->param->tx_urb_cmd_max_len,
1512                   urb->transfer_buffer, urb->transfer_dma);
1513         return;
1514 
1515     default:
1516         if (net_ratelimit())
1517             netdev_info(netdev, "%s: error %pe\n",
1518                     __func__, ERR_PTR(urb->status));
1519         break;
1520     }
1521 
1522     usb_anchor_urb(urb, &es58x_dev->tx_urbs_idle);
1523     atomic_inc(&es58x_dev->tx_urbs_idle_cnt);
1524 }
1525 
1526 /**
1527  * es58x_alloc_urb() - Allocate memory for an URB and its transfer
1528  *  buffer.
1529  * @es58x_dev: ES58X device.
1530  * @urb: URB to be allocated.
1531  * @buf: used to return DMA address of buffer.
1532  * @buf_len: requested buffer size.
1533  * @mem_flags: affect whether allocation may block.
1534  *
1535  * Allocates an URB and its @transfer_buffer and set its @transfer_dma
1536  * address.
1537  *
1538  * This function is used at start-up to allocate all RX URBs at once
1539  * and during run time for TX URBs.
1540  *
1541  * Return: zero on success, -ENOMEM if no memory is available.
1542  */
1543 static int es58x_alloc_urb(struct es58x_device *es58x_dev, struct urb **urb,
1544                u8 **buf, size_t buf_len, gfp_t mem_flags)
1545 {
1546     *urb = usb_alloc_urb(0, mem_flags);
1547     if (!*urb) {
1548         dev_err(es58x_dev->dev, "No memory left for URBs\n");
1549         return -ENOMEM;
1550     }
1551 
1552     *buf = usb_alloc_coherent(es58x_dev->udev, buf_len,
1553                   mem_flags, &(*urb)->transfer_dma);
1554     if (!*buf) {
1555         dev_err(es58x_dev->dev, "No memory left for USB buffer\n");
1556         usb_free_urb(*urb);
1557         return -ENOMEM;
1558     }
1559 
1560     (*urb)->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
1561 
1562     return 0;
1563 }
1564 
1565 /**
1566  * es58x_get_tx_urb() - Get an URB for transmission.
1567  * @es58x_dev: ES58X device.
1568  *
1569  * Gets an URB from the idle urbs anchor or allocate a new one if the
1570  * anchor is empty.
1571  *
1572  * If there are more than ES58X_TX_URBS_MAX in the idle anchor, do
1573  * some garbage collection. The garbage collection is done here
1574  * instead of within es58x_write_bulk_callback() because
1575  * usb_free_coherent() should not be used in IRQ context:
1576  * c.f. WARN_ON(irqs_disabled()) in dma_free_attrs().
1577  *
1578  * Return: a pointer to an URB on success, NULL if no memory is
1579  * available.
1580  */
1581 static struct urb *es58x_get_tx_urb(struct es58x_device *es58x_dev)
1582 {
1583     atomic_t *idle_cnt = &es58x_dev->tx_urbs_idle_cnt;
1584     struct urb *urb = usb_get_from_anchor(&es58x_dev->tx_urbs_idle);
1585 
1586     if (!urb) {
1587         size_t tx_buf_len;
1588         u8 *buf;
1589 
1590         tx_buf_len = es58x_dev->param->tx_urb_cmd_max_len;
1591         if (es58x_alloc_urb(es58x_dev, &urb, &buf, tx_buf_len,
1592                     GFP_ATOMIC))
1593             return NULL;
1594 
1595         usb_fill_bulk_urb(urb, es58x_dev->udev, es58x_dev->tx_pipe,
1596                   buf, tx_buf_len, es58x_write_bulk_callback,
1597                   NULL);
1598         return urb;
1599     }
1600 
1601     while (atomic_dec_return(idle_cnt) > ES58X_TX_URBS_MAX) {
1602         /* Garbage collector */
1603         struct urb *tmp = usb_get_from_anchor(&es58x_dev->tx_urbs_idle);
1604 
1605         if (!tmp)
1606             break;
1607         usb_free_coherent(tmp->dev,
1608                   es58x_dev->param->tx_urb_cmd_max_len,
1609                   tmp->transfer_buffer, tmp->transfer_dma);
1610         usb_free_urb(tmp);
1611     }
1612 
1613     return urb;
1614 }
1615 
1616 /**
1617  * es58x_submit_urb() - Send data to the device.
1618  * @es58x_dev: ES58X device.
1619  * @urb: URB to be sent.
1620  * @netdev: CAN network device.
1621  *
1622  * Return: zero on success, errno when any error occurs.
1623  */
1624 static int es58x_submit_urb(struct es58x_device *es58x_dev, struct urb *urb,
1625                 struct net_device *netdev)
1626 {
1627     int ret;
1628 
1629     es58x_set_crc(urb->transfer_buffer, urb->transfer_buffer_length);
1630     urb->context = netdev;
1631     usb_anchor_urb(urb, &es58x_dev->tx_urbs_busy);
1632     ret = usb_submit_urb(urb, GFP_ATOMIC);
1633     if (ret) {
1634         netdev_err(netdev, "%s: USB send urb failure: %pe\n",
1635                __func__, ERR_PTR(ret));
1636         usb_unanchor_urb(urb);
1637         usb_free_coherent(urb->dev,
1638                   es58x_dev->param->tx_urb_cmd_max_len,
1639                   urb->transfer_buffer, urb->transfer_dma);
1640     }
1641     usb_free_urb(urb);
1642 
1643     return ret;
1644 }
1645 
1646 /**
1647  * es58x_send_msg() - Prepare an URB and submit it.
1648  * @es58x_dev: ES58X device.
1649  * @cmd_type: Command type.
1650  * @cmd_id: Command ID.
1651  * @msg: ES58X message to be sent.
1652  * @msg_len: Length of @msg.
1653  * @channel_idx: Index of the network device.
1654  *
1655  * Creates an URB command from a given message, sets the header and the
1656  * CRC and then submits it.
1657  *
1658  * Return: zero on success, errno when any error occurs.
1659  */
1660 int es58x_send_msg(struct es58x_device *es58x_dev, u8 cmd_type, u8 cmd_id,
1661            const void *msg, u16 msg_len, int channel_idx)
1662 {
1663     struct net_device *netdev;
1664     union es58x_urb_cmd *urb_cmd;
1665     struct urb *urb;
1666     int urb_cmd_len;
1667 
1668     if (channel_idx == ES58X_CHANNEL_IDX_NA)
1669         netdev = es58x_dev->netdev[0];  /* Default to first channel */
1670     else
1671         netdev = es58x_dev->netdev[channel_idx];
1672 
1673     urb_cmd_len = es58x_get_urb_cmd_len(es58x_dev, msg_len);
1674     if (urb_cmd_len > es58x_dev->param->tx_urb_cmd_max_len)
1675         return -EOVERFLOW;
1676 
1677     urb = es58x_get_tx_urb(es58x_dev);
1678     if (!urb)
1679         return -ENOMEM;
1680 
1681     urb_cmd = urb->transfer_buffer;
1682     es58x_dev->ops->fill_urb_header(urb_cmd, cmd_type, cmd_id,
1683                     channel_idx, msg_len);
1684     memcpy(&urb_cmd->raw_cmd[es58x_dev->param->urb_cmd_header_len],
1685            msg, msg_len);
1686     urb->transfer_buffer_length = urb_cmd_len;
1687 
1688     return es58x_submit_urb(es58x_dev, urb, netdev);
1689 }
1690 
1691 /**
1692  * es58x_alloc_rx_urbs() - Allocate RX URBs.
1693  * @es58x_dev: ES58X device.
1694  *
1695  * Allocate URBs for reception and anchor them.
1696  *
1697  * Return: zero on success, errno when any error occurs.
1698  */
1699 static int es58x_alloc_rx_urbs(struct es58x_device *es58x_dev)
1700 {
1701     const struct device *dev = es58x_dev->dev;
1702     const struct es58x_parameters *param = es58x_dev->param;
1703     u16 rx_buf_len = usb_maxpacket(es58x_dev->udev, es58x_dev->rx_pipe);
1704     struct urb *urb;
1705     u8 *buf;
1706     int i;
1707     int ret = -EINVAL;
1708 
1709     for (i = 0; i < param->rx_urb_max; i++) {
1710         ret = es58x_alloc_urb(es58x_dev, &urb, &buf, rx_buf_len,
1711                       GFP_KERNEL);
1712         if (ret)
1713             break;
1714 
1715         usb_fill_bulk_urb(urb, es58x_dev->udev, es58x_dev->rx_pipe,
1716                   buf, rx_buf_len, es58x_read_bulk_callback,
1717                   es58x_dev);
1718         usb_anchor_urb(urb, &es58x_dev->rx_urbs);
1719 
1720         ret = usb_submit_urb(urb, GFP_KERNEL);
1721         if (ret) {
1722             usb_unanchor_urb(urb);
1723             usb_free_coherent(es58x_dev->udev, rx_buf_len,
1724                       buf, urb->transfer_dma);
1725             usb_free_urb(urb);
1726             break;
1727         }
1728         usb_free_urb(urb);
1729     }
1730 
1731     if (i == 0) {
1732         dev_err(dev, "%s: Could not setup any rx URBs\n", __func__);
1733         return ret;
1734     }
1735     dev_dbg(dev, "%s: Allocated %d rx URBs each of size %u\n",
1736         __func__, i, rx_buf_len);
1737 
1738     return ret;
1739 }
1740 
1741 /**
1742  * es58x_free_urbs() - Free all the TX and RX URBs.
1743  * @es58x_dev: ES58X device.
1744  */
1745 static void es58x_free_urbs(struct es58x_device *es58x_dev)
1746 {
1747     struct urb *urb;
1748 
1749     if (!usb_wait_anchor_empty_timeout(&es58x_dev->tx_urbs_busy, 1000)) {
1750         dev_err(es58x_dev->dev, "%s: Timeout, some TX urbs still remain\n",
1751             __func__);
1752         usb_kill_anchored_urbs(&es58x_dev->tx_urbs_busy);
1753     }
1754 
1755     while ((urb = usb_get_from_anchor(&es58x_dev->tx_urbs_idle)) != NULL) {
1756         usb_free_coherent(urb->dev, es58x_dev->param->tx_urb_cmd_max_len,
1757                   urb->transfer_buffer, urb->transfer_dma);
1758         usb_free_urb(urb);
1759         atomic_dec(&es58x_dev->tx_urbs_idle_cnt);
1760     }
1761     if (atomic_read(&es58x_dev->tx_urbs_idle_cnt))
1762         dev_err(es58x_dev->dev,
1763             "All idle urbs were freed but tx_urb_idle_cnt is %d\n",
1764             atomic_read(&es58x_dev->tx_urbs_idle_cnt));
1765 
1766     usb_kill_anchored_urbs(&es58x_dev->rx_urbs);
1767 }
1768 
1769 /**
1770  * es58x_open() - Enable the network device.
1771  * @netdev: CAN network device.
1772  *
1773  * Called when the network transitions to the up state. Allocate the
1774  * URB resources if needed and open the channel.
1775  *
1776  * Return: zero on success, errno when any error occurs.
1777  */
1778 static int es58x_open(struct net_device *netdev)
1779 {
1780     struct es58x_device *es58x_dev = es58x_priv(netdev)->es58x_dev;
1781     int ret;
1782 
1783     if (!es58x_dev->opened_channel_cnt) {
1784         ret = es58x_alloc_rx_urbs(es58x_dev);
1785         if (ret)
1786             return ret;
1787 
1788         ret = es58x_set_realtime_diff_ns(es58x_dev);
1789         if (ret)
1790             goto free_urbs;
1791     }
1792 
1793     ret = open_candev(netdev);
1794     if (ret)
1795         goto free_urbs;
1796 
1797     ret = es58x_dev->ops->enable_channel(es58x_priv(netdev));
1798     if (ret)
1799         goto free_urbs;
1800 
1801     es58x_dev->opened_channel_cnt++;
1802     netif_start_queue(netdev);
1803 
1804     return ret;
1805 
1806  free_urbs:
1807     if (!es58x_dev->opened_channel_cnt)
1808         es58x_free_urbs(es58x_dev);
1809     netdev_err(netdev, "%s: Could not open the network device: %pe\n",
1810            __func__, ERR_PTR(ret));
1811 
1812     return ret;
1813 }
1814 
1815 /**
1816  * es58x_stop() - Disable the network device.
1817  * @netdev: CAN network device.
1818  *
1819  * Called when the network transitions to the down state. If all the
1820  * channels of the device are closed, free the URB resources which are
1821  * not needed anymore.
1822  *
1823  * Return: zero on success, errno when any error occurs.
1824  */
1825 static int es58x_stop(struct net_device *netdev)
1826 {
1827     struct es58x_priv *priv = es58x_priv(netdev);
1828     struct es58x_device *es58x_dev = priv->es58x_dev;
1829     int ret;
1830 
1831     netif_stop_queue(netdev);
1832     ret = es58x_dev->ops->disable_channel(priv);
1833     if (ret)
1834         return ret;
1835 
1836     priv->can.state = CAN_STATE_STOPPED;
1837     es58x_can_reset_echo_fifo(netdev);
1838     close_candev(netdev);
1839 
1840     es58x_flush_pending_tx_msg(netdev);
1841 
1842     es58x_dev->opened_channel_cnt--;
1843     if (!es58x_dev->opened_channel_cnt)
1844         es58x_free_urbs(es58x_dev);
1845 
1846     return 0;
1847 }
1848 
1849 /**
1850  * es58x_xmit_commit() - Send the bulk urb.
1851  * @netdev: CAN network device.
1852  *
1853  * Do the bulk send. This function should be called only once by bulk
1854  * transmission.
1855  *
1856  * Return: zero on success, errno when any error occurs.
1857  */
1858 static int es58x_xmit_commit(struct net_device *netdev)
1859 {
1860     struct es58x_priv *priv = es58x_priv(netdev);
1861     int ret;
1862 
1863     if (!es58x_is_can_state_active(netdev))
1864         return -ENETDOWN;
1865 
1866     if (es58x_is_echo_skb_threshold_reached(priv))
1867         netif_stop_queue(netdev);
1868 
1869     ret = es58x_submit_urb(priv->es58x_dev, priv->tx_urb, netdev);
1870     if (ret == 0)
1871         priv->tx_urb = NULL;
1872 
1873     return ret;
1874 }
1875 
1876 /**
1877  * es58x_xmit_more() - Can we put more packets?
1878  * @priv: ES58X private parameters related to the network device.
1879  *
1880  * Return: true if we can put more, false if it is time to send.
1881  */
1882 static bool es58x_xmit_more(struct es58x_priv *priv)
1883 {
1884     unsigned int free_slots =
1885         priv->can.echo_skb_max - (priv->tx_head - priv->tx_tail);
1886 
1887     return netdev_xmit_more() && free_slots > 0 &&
1888         priv->tx_can_msg_cnt < priv->es58x_dev->param->tx_bulk_max;
1889 }
1890 
1891 /**
1892  * es58x_start_xmit() - Transmit an skb.
1893  * @skb: socket buffer of a CAN message.
1894  * @netdev: CAN network device.
1895  *
1896  * Called when a packet needs to be transmitted.
1897  *
1898  * This function relies on Byte Queue Limits (BQL). The main benefit
1899  * is to increase the throughput by allowing bulk transfers
1900  * (c.f. xmit_more flag).
1901  *
1902  * Queues up to tx_bulk_max messages in &tx_urb buffer and does
1903  * a bulk send of all messages in one single URB.
1904  *
1905  * Return: NETDEV_TX_OK regardless of if we could transmit the @skb or
1906  *  had to drop it.
1907  */
1908 static netdev_tx_t es58x_start_xmit(struct sk_buff *skb,
1909                     struct net_device *netdev)
1910 {
1911     struct es58x_priv *priv = es58x_priv(netdev);
1912     struct es58x_device *es58x_dev = priv->es58x_dev;
1913     unsigned int frame_len;
1914     int ret;
1915 
1916     if (can_dropped_invalid_skb(netdev, skb)) {
1917         if (priv->tx_urb)
1918             goto xmit_commit;
1919         return NETDEV_TX_OK;
1920     }
1921 
1922     if (priv->tx_urb && priv->tx_can_msg_is_fd != can_is_canfd_skb(skb)) {
1923         /* Can not do bulk send with mixed CAN and CAN FD frames. */
1924         ret = es58x_xmit_commit(netdev);
1925         if (ret)
1926             goto drop_skb;
1927     }
1928 
1929     if (!priv->tx_urb) {
1930         priv->tx_urb = es58x_get_tx_urb(es58x_dev);
1931         if (!priv->tx_urb) {
1932             ret = -ENOMEM;
1933             goto drop_skb;
1934         }
1935         priv->tx_can_msg_cnt = 0;
1936         priv->tx_can_msg_is_fd = can_is_canfd_skb(skb);
1937     }
1938 
1939     ret = es58x_dev->ops->tx_can_msg(priv, skb);
1940     if (ret)
1941         goto drop_skb;
1942 
1943     frame_len = can_skb_get_frame_len(skb);
1944     ret = can_put_echo_skb(skb, netdev,
1945                    priv->tx_head & es58x_dev->param->fifo_mask,
1946                    frame_len);
1947     if (ret)
1948         goto xmit_failure;
1949     netdev_sent_queue(netdev, frame_len);
1950 
1951     priv->tx_head++;
1952     priv->tx_can_msg_cnt++;
1953 
1954  xmit_commit:
1955     if (!es58x_xmit_more(priv)) {
1956         ret = es58x_xmit_commit(netdev);
1957         if (ret)
1958             goto xmit_failure;
1959     }
1960 
1961     return NETDEV_TX_OK;
1962 
1963  drop_skb:
1964     dev_kfree_skb(skb);
1965     netdev->stats.tx_dropped++;
1966  xmit_failure:
1967     netdev_warn(netdev, "%s: send message failure: %pe\n",
1968             __func__, ERR_PTR(ret));
1969     netdev->stats.tx_errors++;
1970     es58x_flush_pending_tx_msg(netdev);
1971     return NETDEV_TX_OK;
1972 }
1973 
1974 static const struct net_device_ops es58x_netdev_ops = {
1975     .ndo_open = es58x_open,
1976     .ndo_stop = es58x_stop,
1977     .ndo_start_xmit = es58x_start_xmit,
1978     .ndo_eth_ioctl = can_eth_ioctl_hwts,
1979 };
1980 
1981 static const struct ethtool_ops es58x_ethtool_ops = {
1982     .get_ts_info = can_ethtool_op_get_ts_info_hwts,
1983 };
1984 
1985 /**
1986  * es58x_set_mode() - Change network device mode.
1987  * @netdev: CAN network device.
1988  * @mode: either %CAN_MODE_START, %CAN_MODE_STOP or %CAN_MODE_SLEEP
1989  *
1990  * Currently, this function is only used to stop and restart the
1991  * channel during a bus off event (c.f. es58x_rx_err_msg() and
1992  * drivers/net/can/dev.c:can_restart() which are the two only
1993  * callers).
1994  *
1995  * Return: zero on success, errno when any error occurs.
1996  */
1997 static int es58x_set_mode(struct net_device *netdev, enum can_mode mode)
1998 {
1999     struct es58x_priv *priv = es58x_priv(netdev);
2000 
2001     switch (mode) {
2002     case CAN_MODE_START:
2003         switch (priv->can.state) {
2004         case CAN_STATE_BUS_OFF:
2005             return priv->es58x_dev->ops->enable_channel(priv);
2006 
2007         case CAN_STATE_STOPPED:
2008             return es58x_open(netdev);
2009 
2010         case CAN_STATE_ERROR_ACTIVE:
2011         case CAN_STATE_ERROR_WARNING:
2012         case CAN_STATE_ERROR_PASSIVE:
2013         default:
2014             return 0;
2015         }
2016 
2017     case CAN_MODE_STOP:
2018         switch (priv->can.state) {
2019         case CAN_STATE_STOPPED:
2020             return 0;
2021 
2022         case CAN_STATE_ERROR_ACTIVE:
2023         case CAN_STATE_ERROR_WARNING:
2024         case CAN_STATE_ERROR_PASSIVE:
2025         case CAN_STATE_BUS_OFF:
2026         default:
2027             return priv->es58x_dev->ops->disable_channel(priv);
2028         }
2029 
2030     case CAN_MODE_SLEEP:
2031     default:
2032         return -EOPNOTSUPP;
2033     }
2034 }
2035 
2036 /**
2037  * es58x_init_priv() - Initialize private parameters.
2038  * @es58x_dev: ES58X device.
2039  * @priv: ES58X private parameters related to the network device.
2040  * @channel_idx: Index of the network device.
2041  */
2042 static void es58x_init_priv(struct es58x_device *es58x_dev,
2043                 struct es58x_priv *priv, int channel_idx)
2044 {
2045     const struct es58x_parameters *param = es58x_dev->param;
2046     struct can_priv *can = &priv->can;
2047 
2048     priv->es58x_dev = es58x_dev;
2049     priv->channel_idx = channel_idx;
2050     priv->tx_urb = NULL;
2051     priv->tx_can_msg_cnt = 0;
2052 
2053     can->bittiming_const = param->bittiming_const;
2054     if (param->ctrlmode_supported & CAN_CTRLMODE_FD) {
2055         can->data_bittiming_const = param->data_bittiming_const;
2056         can->tdc_const = param->tdc_const;
2057     }
2058     can->bitrate_max = param->bitrate_max;
2059     can->clock = param->clock;
2060     can->state = CAN_STATE_STOPPED;
2061     can->ctrlmode_supported = param->ctrlmode_supported;
2062     can->do_set_mode = es58x_set_mode;
2063 }
2064 
2065 /**
2066  * es58x_init_netdev() - Initialize the network device.
2067  * @es58x_dev: ES58X device.
2068  * @channel_idx: Index of the network device.
2069  *
2070  * Return: zero on success, errno when any error occurs.
2071  */
2072 static int es58x_init_netdev(struct es58x_device *es58x_dev, int channel_idx)
2073 {
2074     struct net_device *netdev;
2075     struct device *dev = es58x_dev->dev;
2076     int ret;
2077 
2078     netdev = alloc_candev(sizeof(struct es58x_priv),
2079                   es58x_dev->param->fifo_mask + 1);
2080     if (!netdev) {
2081         dev_err(dev, "Could not allocate candev\n");
2082         return -ENOMEM;
2083     }
2084     SET_NETDEV_DEV(netdev, dev);
2085     es58x_dev->netdev[channel_idx] = netdev;
2086     es58x_init_priv(es58x_dev, es58x_priv(netdev), channel_idx);
2087 
2088     netdev->netdev_ops = &es58x_netdev_ops;
2089     netdev->ethtool_ops = &es58x_ethtool_ops;
2090     netdev->flags |= IFF_ECHO;  /* We support local echo */
2091     netdev->dev_port = channel_idx;
2092 
2093     ret = register_candev(netdev);
2094     if (ret)
2095         return ret;
2096 
2097     netdev_queue_set_dql_min_limit(netdev_get_tx_queue(netdev, 0),
2098                        es58x_dev->param->dql_min_limit);
2099 
2100     return ret;
2101 }
2102 
2103 /**
2104  * es58x_free_netdevs() - Release all network resources of the device.
2105  * @es58x_dev: ES58X device.
2106  */
2107 static void es58x_free_netdevs(struct es58x_device *es58x_dev)
2108 {
2109     int i;
2110 
2111     for (i = 0; i < es58x_dev->num_can_ch; i++) {
2112         struct net_device *netdev = es58x_dev->netdev[i];
2113 
2114         if (!netdev)
2115             continue;
2116         unregister_candev(netdev);
2117         es58x_dev->netdev[i] = NULL;
2118         free_candev(netdev);
2119     }
2120 }
2121 
2122 /**
2123  * es58x_get_product_info() - Get the product information and print them.
2124  * @es58x_dev: ES58X device.
2125  *
2126  * Do a synchronous call to get the product information.
2127  *
2128  * Return: zero on success, errno when any error occurs.
2129  */
2130 static int es58x_get_product_info(struct es58x_device *es58x_dev)
2131 {
2132     struct usb_device *udev = es58x_dev->udev;
2133     const int es58x_prod_info_idx = 6;
2134     /* Empirical tests show a prod_info length of maximum 83,
2135      * below should be more than enough.
2136      */
2137     const size_t prod_info_len = 127;
2138     char *prod_info;
2139     int ret;
2140 
2141     prod_info = kmalloc(prod_info_len, GFP_KERNEL);
2142     if (!prod_info)
2143         return -ENOMEM;
2144 
2145     ret = usb_string(udev, es58x_prod_info_idx, prod_info, prod_info_len);
2146     if (ret < 0) {
2147         dev_err(es58x_dev->dev,
2148             "%s: Could not read the product info: %pe\n",
2149             __func__, ERR_PTR(ret));
2150         goto out_free;
2151     }
2152     if (ret >= prod_info_len - 1) {
2153         dev_warn(es58x_dev->dev,
2154              "%s: Buffer is too small, result might be truncated\n",
2155              __func__);
2156     }
2157     dev_info(es58x_dev->dev, "Product info: %s\n", prod_info);
2158 
2159  out_free:
2160     kfree(prod_info);
2161     return ret < 0 ? ret : 0;
2162 }
2163 
2164 /**
2165  * es58x_init_es58x_dev() - Initialize the ES58X device.
2166  * @intf: USB interface.
2167  * @driver_info: Quirks of the device.
2168  *
2169  * Return: pointer to an ES58X device on success, error pointer when
2170  *  any error occurs.
2171  */
2172 static struct es58x_device *es58x_init_es58x_dev(struct usb_interface *intf,
2173                          kernel_ulong_t driver_info)
2174 {
2175     struct device *dev = &intf->dev;
2176     struct es58x_device *es58x_dev;
2177     const struct es58x_parameters *param;
2178     const struct es58x_operators *ops;
2179     struct usb_device *udev = interface_to_usbdev(intf);
2180     struct usb_endpoint_descriptor *ep_in, *ep_out;
2181     int ret;
2182 
2183     dev_info(dev, "Starting %s %s (Serial Number %s)\n",
2184          udev->manufacturer, udev->product, udev->serial);
2185 
2186     ret = usb_find_common_endpoints(intf->cur_altsetting, &ep_in, &ep_out,
2187                     NULL, NULL);
2188     if (ret)
2189         return ERR_PTR(ret);
2190 
2191     if (driver_info & ES58X_FD_FAMILY) {
2192         param = &es58x_fd_param;
2193         ops = &es58x_fd_ops;
2194     } else {
2195         param = &es581_4_param;
2196         ops = &es581_4_ops;
2197     }
2198 
2199     es58x_dev = devm_kzalloc(dev, es58x_sizeof_es58x_device(param),
2200                  GFP_KERNEL);
2201     if (!es58x_dev)
2202         return ERR_PTR(-ENOMEM);
2203 
2204     es58x_dev->param = param;
2205     es58x_dev->ops = ops;
2206     es58x_dev->dev = dev;
2207     es58x_dev->udev = udev;
2208 
2209     if (driver_info & ES58X_DUAL_CHANNEL)
2210         es58x_dev->num_can_ch = 2;
2211     else
2212         es58x_dev->num_can_ch = 1;
2213 
2214     init_usb_anchor(&es58x_dev->rx_urbs);
2215     init_usb_anchor(&es58x_dev->tx_urbs_idle);
2216     init_usb_anchor(&es58x_dev->tx_urbs_busy);
2217     atomic_set(&es58x_dev->tx_urbs_idle_cnt, 0);
2218     usb_set_intfdata(intf, es58x_dev);
2219 
2220     es58x_dev->rx_pipe = usb_rcvbulkpipe(es58x_dev->udev,
2221                          ep_in->bEndpointAddress);
2222     es58x_dev->tx_pipe = usb_sndbulkpipe(es58x_dev->udev,
2223                          ep_out->bEndpointAddress);
2224 
2225     return es58x_dev;
2226 }
2227 
2228 /**
2229  * es58x_probe() - Initialize the USB device.
2230  * @intf: USB interface.
2231  * @id: USB device ID.
2232  *
2233  * Return: zero on success, -ENODEV if the interface is not supported
2234  * or errno when any other error occurs.
2235  */
2236 static int es58x_probe(struct usb_interface *intf,
2237                const struct usb_device_id *id)
2238 {
2239     struct es58x_device *es58x_dev;
2240     int ch_idx, ret;
2241 
2242     es58x_dev = es58x_init_es58x_dev(intf, id->driver_info);
2243     if (IS_ERR(es58x_dev))
2244         return PTR_ERR(es58x_dev);
2245 
2246     ret = es58x_get_product_info(es58x_dev);
2247     if (ret)
2248         return ret;
2249 
2250     for (ch_idx = 0; ch_idx < es58x_dev->num_can_ch; ch_idx++) {
2251         ret = es58x_init_netdev(es58x_dev, ch_idx);
2252         if (ret) {
2253             es58x_free_netdevs(es58x_dev);
2254             return ret;
2255         }
2256     }
2257 
2258     return ret;
2259 }
2260 
2261 /**
2262  * es58x_disconnect() - Disconnect the USB device.
2263  * @intf: USB interface
2264  *
2265  * Called by the usb core when driver is unloaded or device is
2266  * removed.
2267  */
2268 static void es58x_disconnect(struct usb_interface *intf)
2269 {
2270     struct es58x_device *es58x_dev = usb_get_intfdata(intf);
2271 
2272     dev_info(&intf->dev, "Disconnecting %s %s\n",
2273          es58x_dev->udev->manufacturer, es58x_dev->udev->product);
2274 
2275     es58x_free_netdevs(es58x_dev);
2276     es58x_free_urbs(es58x_dev);
2277     usb_set_intfdata(intf, NULL);
2278 }
2279 
2280 static struct usb_driver es58x_driver = {
2281     .name = KBUILD_MODNAME,
2282     .probe = es58x_probe,
2283     .disconnect = es58x_disconnect,
2284     .id_table = es58x_id_table
2285 };
2286 
2287 module_usb_driver(es58x_driver);